Repository: VickScarlet/lifeRestart Branch: main Commit: 59a10587a719 Files: 159 Total size: 7.1 MB Directory structure: gitextract_s0gy15dj/ ├── .dockerignore ├── .github/ │ ├── dependabot.yml │ └── workflows/ │ └── deploy.yml ├── .gitignore ├── .vscode/ │ └── launch.json ├── Dockerfile ├── LICENSE ├── README-zh_CN.md ├── README.md ├── data/ │ ├── en-us/ │ │ ├── achievement.xlsx │ │ ├── age.xlsx │ │ ├── character.xlsx │ │ ├── events.xlsx │ │ └── talents.xlsx │ ├── specialthanks-afd.xlsx │ ├── specialthanks-dun.xlsx │ └── zh-cn/ │ ├── achievement.xlsx │ ├── age.xlsx │ ├── character.xlsx │ ├── events.xlsx │ └── talents.xlsx ├── design/ │ └── cyber/ │ ├── lifeRestart.sketch │ └── lifeRestart.xd ├── index.html ├── jsconfig.json ├── laya/ │ ├── .laya │ ├── pages/ │ │ ├── particle/ │ │ │ └── fly.part │ │ └── view/ │ │ ├── CyberTheme/ │ │ │ ├── Celebrity.ui │ │ │ ├── CyberAchievement.ui │ │ │ ├── CyberAchievementPopup.ui │ │ │ ├── CyberMain.ui │ │ │ ├── CyberProperty.ui │ │ │ ├── CyberSummary.ui │ │ │ ├── CyberTalent.ui │ │ │ ├── CyberTrajectory.ui │ │ │ ├── Mode.ui │ │ │ └── animation/ │ │ │ ├── bottomBreath.ani │ │ │ ├── circleFlash.ani │ │ │ ├── jumpBackground.ani │ │ │ └── lightRotation.ani │ │ ├── DefaultTheme/ │ │ │ ├── Achievement.ui │ │ │ ├── AchievementPopup.ui │ │ │ ├── Celebrity.ui │ │ │ ├── Main.ui │ │ │ ├── Mode.ui │ │ │ ├── Property.ui │ │ │ ├── Summary.ui │ │ │ ├── Talent.ui │ │ │ ├── Thanks.ui │ │ │ └── Trajectory.ui │ │ ├── Loading.ui │ │ ├── MessagePopup.ui │ │ ├── SaveLoad.ui │ │ └── Themes.ui │ └── styles.xml ├── lifeRestart.laya ├── package.json ├── public/ │ ├── condition_test.html │ ├── images/ │ │ └── atlas/ │ │ ├── .rec │ │ └── images/ │ │ ├── accessories.atlas │ │ ├── border.atlas │ │ ├── button.atlas │ │ ├── icons.atlas │ │ ├── progress.atlas │ │ ├── radio.atlas │ │ ├── resource.atlas │ │ ├── slider.atlas │ │ └── texture.atlas │ ├── libs/ │ │ └── laya/ │ │ ├── LayaRender.js │ │ ├── bytebuffer.js │ │ ├── domparserinone.js │ │ ├── laya.Alipaymini.js │ │ ├── laya.ani.js │ │ ├── laya.bdmini.js │ │ ├── laya.bilimini.js │ │ ├── laya.core.js │ │ ├── laya.d3.js │ │ ├── laya.d3Plugin.js │ │ ├── laya.debugtool.js │ │ ├── laya.device.js │ │ ├── laya.filter.js │ │ ├── laya.html.js │ │ ├── laya.hwmini.js │ │ ├── laya.particle.js │ │ ├── laya.pathfinding.js │ │ ├── laya.qqmini.js │ │ ├── laya.quickgamemini.js │ │ ├── laya.tbmini.js │ │ ├── laya.tbplugin.js │ │ ├── laya.tiledmap.js │ │ ├── laya.ttmini.js │ │ ├── laya.ui.js │ │ ├── laya.vvmini.js │ │ ├── laya.webgl.js │ │ ├── laya.wxmini.js │ │ ├── laya.xmmini.js │ │ ├── matter-RenderLaya.js │ │ ├── matter.js │ │ ├── protobuf.js │ │ └── worker.js │ ├── particle/ │ │ └── fly.part │ ├── unpack.json │ └── view/ │ └── CyberTheme/ │ └── animation/ │ ├── bottomBreath.ani │ ├── circleFlash.ani │ ├── jumpBackground.ani │ └── lightRotation.ani ├── repl/ │ ├── app.js │ └── index.js ├── src/ │ ├── @types/ │ │ ├── LayaAir.d.ts │ │ ├── layaAir.minigame.d.ts │ │ └── union.d.ts │ ├── app.js │ ├── functions/ │ │ ├── condition.js │ │ ├── condition.spec.js │ │ └── util.js │ ├── i18n/ │ │ ├── en-us.js │ │ └── zh-cn.js │ ├── index.js │ ├── modules/ │ │ ├── achievement.js │ │ ├── character.js │ │ ├── event.js │ │ ├── life.js │ │ ├── property.js │ │ └── talent.js │ └── ui/ │ ├── laya.patch.js │ ├── layaUI.max.all.js │ ├── pluginFunction.js │ ├── promisesLaya.js │ ├── runtime.js │ ├── themes/ │ │ ├── cyber/ │ │ │ ├── achievement.js │ │ │ ├── celebrity.js │ │ │ ├── main.js │ │ │ ├── mode.js │ │ │ ├── popup/ │ │ │ │ └── achievementPopup.js │ │ │ ├── property.js │ │ │ ├── summary.js │ │ │ ├── talent.js │ │ │ └── trajectory.js │ │ ├── default/ │ │ │ ├── achievement.js │ │ │ ├── celebrity.js │ │ │ ├── main.js │ │ │ ├── mode.js │ │ │ ├── popup/ │ │ │ │ └── achievementPopup.js │ │ │ ├── property.js │ │ │ ├── summary.js │ │ │ ├── talent.js │ │ │ ├── thanks.js │ │ │ └── trajectory.js │ │ ├── loading.js │ │ ├── message.js │ │ ├── saveload.js │ │ └── themes.js │ ├── uiManager.js │ └── views.js ├── template/ │ ├── _config.yml │ ├── _layouts/ │ │ └── default.html │ ├── index.md │ └── view/ │ └── index.html └── vite.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ node_modules npm-debug.log ================================================ FILE: .github/dependabot.yml ================================================ # To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file version: 2 updates: - package-ecosystem: "" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "weekly" ================================================ FILE: .github/workflows/deploy.yml ================================================ name: Build and Deploy on: push: branches: [main] permissions: contents: write jobs: build-and-deploy: concurrency: ci-${{ github.ref }} # Recommended if you intend to make multiple deployments in quick succession. runs-on: ubuntu-latest steps: - name: Checkout 🛎️ uses: actions/checkout@v4 - name: Install pnpm uses: pnpm/action-setup@v4 with: version: 10 - name: Install and Build 🔧 # This example project is built using npm and outputs the result to the 'build' folder. Replace with the commands required to build your project, or remove this step entirely if your site is pre-built. run: | pnpm install pnpm xlsx2json pnpm build - name: Deploy 🚀 uses: JamesIves/github-pages-deploy-action@v4 with: folder: template # The folder the action should deploy. ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env .env.test # parcel-bundler cache (https://parceljs.org/) .cache # Next.js build output .next # Nuxt.js build / generate output .nuxt dist # Gatsby files .cache/ # Comment in the public line in if your project uses Gatsby and *not* Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port utils/xlsxTransform-* /.idea __localStorage.json template/public public/data ================================================ FILE: .vscode/launch.json ================================================ { // 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。 // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "test", "program": "${workspaceFolder}/test", "skipFiles": [ "/**", "**/node_modumes/**" ] }, ] } ================================================ FILE: Dockerfile ================================================ FROM node:alpine ENV NPM_CONFIG_LOGLEVEL info WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . EXPOSE 8080 CMD ["yarn", "dev"] ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2021 神戸小鳥 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. ================================================ FILE: README-zh_CN.md ================================================ # Life Restart [English](./README.md) | 简体中文 ## 简介 - Game Life Restart ## 使用
网页版
```bash # 1. 下载项目代码 git clone https://github.com/VickScarlet/lifeRestart.git my-project # 2. 进入目录安装依赖 cd my-project pnpm install # 3. 转换XLSX表 pnpm xlsx2json # 4. 启动本地开发服务器 pnpm dev ``` 启动完成后打开浏览器访问 [http://localhost:5173](http://localhost:5173)。
控制台版本
```bash node repl ```
## 其他版本
版本列表
- Cocos版:[gameall3d/LifeRestart_Cocos](https://github.com/gameall3d/LifeRestart_Cocos)
> 更多信息请参考 [官网文档](https://liferestart.syaro.io/)。 ================================================ FILE: README.md ================================================ # Life Restart English | [简体中文](./README-zh_CN.md) ## Introduction - Game Life Restart ## Usage
Web Version
```bash # 1. Clone project code. git clone git@github.com:VickScarlet/lifeRestart.git my-project cd my-project # 2. Installation dependence. pnpm install # 3. Transform XLSX pnpm xlsx2json # 4. Start local dev server. pnpm dev ``` After the startup is complete, open a browser and visit [http://localhost:5173](http://localhost:5173).
Command Line Version
```bash node repl ```
## Other Version
Versions
- Cocos Ver: [gameall3d/LifeRestart_Cocos](https://github.com/gameall3d/LifeRestart_Cocos)
> More instructions at [documentation](https://liferestart.syaro.io/). ================================================ FILE: index.html ================================================ Life Restart ================================================ FILE: jsconfig.json ================================================ { // See http://go.microsoft.com/fwlink/?LinkId=759670 // for the documentation about the jsconfig.json format "compilerOptions": { "module": "esnext", "target": "es6", }, "include":["src", "repl", "vite.config.js"], "exclude": ["node_modules", "public", "view"] } ================================================ FILE: laya/.laya ================================================ img,temp,sound embed png,jpg public/images/atlas public src/ui 0 public/ui.json Box,List,Tab,RadioGroup,ViewStack,Panel,HBox,VBox,Tree,Sprite View,Dialog 2 80 2048 2048 512 512 false false src/view 0 1 true true 0.9.9 beta ================================================ FILE: laya/pages/particle/fly.part ================================================ {"textureName":"images/texture/texture_1.png","positionVariance":{"0":0,"1":0,"2":0},"minVerticalVelocity":-100,"minVerticalEndRadian":0,"minStartSize":0,"minStartRadius":0,"minRotateSpeed":0,"minHorizontalVelocity":100,"minHorizontalEndRadian":0,"minEndSize":18.55,"minEndRadius":218.75,"minColor":{"0":0.15,"1":0.92,"2":0.91,"3":0.6000000238418579},"maxVerticalVelocity":100,"maxVerticalEndRadian":0,"maxStartSize":2.04,"maxStartRadius":0,"maxRotateSpeed":0,"maxPartices":400,"maxHorizontalVelocity":100,"maxHorizontalEndRadian":0,"maxEndSize":24.35,"maxEndRadius":84.82,"maxColor":{"0":0.57,"1":1,"2":0,"3":1},"gravity":{"0":0,"1":0,"2":0},"endVelocity":2,"emitterVelocitySensitivity":56.89,"duration":9.52,"colorComponentInter":true,"blendState":0,"ageAddScale":10,"backColor":"#ffffff","textureFileName":"comp\\clip_num.png","textureCount":1,"minHorizontalStartRadian":0,"maxHorizontalStartRadian":0,"minVerticalStartRadian":0,"maxVerticalStartRadian":0,"emitterType":"null","emissionRate":0,"sphereEmitterRadius":1,"sphereEmitterVelocity":0,"sphereEmitterVelocityAddVariance":0,"ringEmitterRadius":30,"ringEmitterVelocity":0,"ringEmitterVelocityAddVariance":0,"ringEmitterUp":2,"minStartColor":{"0":0.5,"1":0.5,"2":0.5,"3":0.2},"maxStartColor":{"0":1,"1":1,"2":1,"3":1},"minEndColor":{"0":0,"1":0,"2":0,"3":0.08},"maxEndColor":{"0":1,"1":1,"2":1,"3":1},"pointEmitterPosition":{"0":0,"1":0,"2":0},"pointEmitterPositionVariance":{"0":0,"1":0,"2":0},"pointEmitterVelocity":{"0":0,"1":0,"2":0},"pointEmitterVelocityAddVariance":{"0":0,"1":0,"2":0},"boxEmitterCenterPosition":{"0":0,"1":0,"2":0},"boxEmitterSize":{"0":0,"1":0,"2":0},"boxEmitterVelocity":{"0":0,"1":0,"2":0},"boxEmitterVelocityAddVariance":{"0":0,"1":0,"2":0},"sphereEmitterCenterPosition":{"0":0,"1":0,"2":0},"ringEmitterCenterPosition":{"0":0,"1":0,"2":0},"useEndRadian":true,"disableColor":false} ================================================ FILE: laya/pages/view/CyberTheme/Celebrity.ui ================================================ { "x":0, "type":"View", "selectedBox":83, "selecteID":84, "props":{"width":1125,"sceneColor":"#000000","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"top":40,"right":0,"name":"title","left":0}, "nodeParent":1, "label":"Box(title)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":73, "child":[ { "x":30, "type":"Image", "props":{"skin":"images/accessories/titlebar@3x.png","right":0,"left":0}, "nodeParent":73, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":74, "child":[ ] }, { "x":30, "type":"HBox", "props":{"y":160,"x":563,"space":30,"height":70,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":73, "label":"HBox", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":75, "child":[ { "type":"Image", "props":{"y":10,"x":1,"skin":"images/accessories/title_left@3x.png","name":"left"}, "nodeParent":75, "label":"Image(left)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":76, "child":[ ] }, { "type":"Label", "props":{"y":0,"x":2,"text":"UI_Title_Celebrity","fontSize":60,"font":"方正像素12","color":"#ffffff"}, "nodeParent":75, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":77, "child":[ ] }, { "type":"Image", "props":{"y":10,"x":3,"skin":"images/accessories/title_right@3x.png","name":"right"}, "nodeParent":75, "label":"Image(right)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":78, "child":[ ] }] }], "$LOCKED":true }, { "x":15, "type":"Panel", "props":{"var":"panelCharacter","vScrollBarSkin":" ","top":300,"right":0,"name":"panelCharacter","left":0,"bottom":700}, "nodeParent":1, "label":"Panel(panelCharacter)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":2, "child":[ { "x":30, "type":"VBox", "props":{"y":10,"width":1000,"var":"vboxCharacter","space":20,"name":"vboxCharacter","centerX":0}, "nodeParent":2, "label":"VBox(vboxCharacter)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":8, "child":[ { "x":45, "type":"Box", "props":{"right":0,"name":"boxCharacter","left":0}, "nodeParent":8, "label":"Box(boxCharacter)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":10, "child":[ { "type":"Box", "props":{"y":0,"right":0,"name":"boxName","left":0,"height":100}, "nodeParent":10, "label":"Box(boxName)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":12, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/border/border_1@3x.png","sizeGrid":"15,130,15,130","right":0,"left":0,"bottom":0}, "nodeParent":12, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":64, "child":[ ] }, { "type":"Label", "props":{"valign":"middle","text":"颜值10 智力10 体质10 家境Π","name":"label","fontSize":55,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"align":"center"}, "nodeParent":12, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":18, "child":[ ] }] }, { "type":"VBox", "props":{"top":100,"space":20,"right":25,"name":"vboxStates","left":25}, "nodeParent":10, "label":"VBox(vboxStates)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":11, "child":[ { "type":"Label", "props":{"valign":"middle","text":"颜值10 智力10 体质10 家境Π","name":"label","height":100,"fontSize":55,"font":"方正像素12","color":"#ffffff","centerX":0,"align":"center"}, "nodeParent":11, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":14, "child":[ ] }] }] }, { "x":45, "type":"Box", "props":{"right":25,"name":"boxTalent","left":25,"height":100}, "nodeParent":8, "label":"Box(boxTalent)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":15, "child":[ { "type":"Image", "props":{"y":-220,"x":-25,"top":0,"skin":"images/border/up@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":15, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":66, "child":[ ] }, { "type":"Label", "props":{"valign":"middle","text":"颜值10 智力10 体质10 家境Π","name":"label","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"align":"center"}, "nodeParent":15, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":17, "child":[ ] }, { "type":"Box", "props":{"y":0,"x":0,"width":15,"visible":false,"name":"grade1","height":100}, "nodeParent":15, "label":"Box(grade1)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":67, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":100,"fillColor":"#55fffe"}, "nodeParent":67, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":70, "child":[ ] }] }, { "type":"Box", "props":{"y":0,"x":0,"width":15,"visible":false,"name":"grade2","height":100}, "nodeParent":15, "label":"Box(grade2)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":68, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":100,"fillColor":"#b17cff"}, "nodeParent":68, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":71, "child":[ ] }] }, { "type":"Box", "props":{"y":0,"x":0,"width":15,"visible":false,"name":"grade3","height":100}, "nodeParent":15, "label":"Box(grade3)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":69, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":100,"fillColor":"#ffce45"}, "nodeParent":69, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":72, "child":[ ] }] }] }, { "x":45, "type":"Box", "props":{"y":10,"x":10,"right":0,"name":"boxUniqueUnGenerate","left":0}, "nodeParent":8, "label":"Box(boxUniqueUnGenerate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":79, "child":[ { "x":60, "type":"Box", "props":{"y":0,"right":0,"name":"boxName","left":0,"height":100}, "nodeParent":79, "label":"Box(boxName)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":80, "child":[ { "x":75, "type":"Image", "props":{"top":0,"skin":"images/border/border_1@3x.png","sizeGrid":"15,130,15,130","right":0,"left":0,"bottom":0}, "nodeParent":80, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":81, "child":[ ] }, { "x":75, "type":"Label", "props":{"valign":"middle","text":"UI_UniqueWaTaShi","name":"label","fontSize":55,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"align":"center"}, "nodeParent":80, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":82, "child":[ ] }] }, { "x":60, "type":"VBox", "props":{"top":100,"space":20,"right":25,"name":"vboxStates","left":25}, "nodeParent":79, "label":"VBox(vboxStates)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":83, "child":[ { "x":75, "type":"Label", "props":{"valign":"middle","text":"UI_UniqueWaTaShiContent","right":0,"name":"label","left":0,"leading":30,"fontSize":55,"font":"方正像素12","color":"#ffffff","align":"center"}, "nodeParent":83, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":84, "child":[ ] }, { "x":75, "type":"Box", "props":{"y":12,"x":10,"right":0,"name":"boxBtn","left":0,"height":200}, "nodeParent":83, "label":"Box(boxBtn)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":85, "child":[ { "x":90, "type":"Button", "props":{"width":500,"skin":"images/button/button_main@3x.png","name":"btn","label":"UI_GenerateNow","centerY":0,"centerX":0}, "nodeParent":85, "label":"Button(btn)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":88, "child":[ { "type":"Box", "props":{}, "nodeParent":88, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":89, "child":[ { "type":"Animation", "props":{"y":96,"x":250,"width":0,"source":"view/CyberTheme/animation/circleFlash.ani","scaleX":4,"height":0,"blendMode":"lighter","autoPlay":true}, "nodeParent":89, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":90, "child":[ ] }, { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":89, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":91, "child":[ { "type":"Rect", "props":{"y":37,"x":25,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":92, "child":[ ] }, { "type":"Rect", "props":{"y":37,"x":470,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":93, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":44,"width":414,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":94, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":171,"width":160,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":95, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":44,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":96, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":337,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":97, "child":[ ] }, { "type":"Rect", "props":{"y":148,"x":29,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":98, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":331,"width":19,"rotation":55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":99, "child":[ ] }, { "type":"Rect", "props":{"y":166,"x":160,"width":19,"rotation":-55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":100, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":458,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":101, "child":[ ] }, { "type":"Rect", "props":{"y":26,"x":48,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":102, "child":[ ] }, { "type":"Rect", "props":{"y":153,"x":477,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":103, "child":[ ] }] }] }, { "type":"Box", "props":{}, "nodeParent":88, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":104, "child":[ { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":104, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":105, "child":[ { "type":"Poly", "props":{"y":41,"x":35,"points":"0,0,8,-6,8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":105, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":106, "child":[ ] }, { "type":"Poly", "props":{"y":41,"x":464,"points":"0,0,-8,-6,-8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":105, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":107, "child":[ ] }, { "type":"Poly", "props":{"y":160,"x":177,"points":"0,0,147,0,153,10,-6,10","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":105, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":108, "child":[ ] }] }, { "type":"Animation", "props":{"y":172,"x":520,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleX":6,"blendMode":"lighter","autoPlay":true}, "nodeParent":104, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":109, "child":[ ] }] }] }] }] }] }] }] }, { "x":15, "type":"Box", "props":{"right":0,"left":0,"height":0,"bottom":0}, "nodeParent":1, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":63, "child":[ { "x":30, "type":"Button", "props":{"y":-450,"width":500,"var":"btnRetry","skin":"images/button/button_main@3x.png","name":"btnRetry","label":"UI_AllNot","centerX":0}, "nodeParent":63, "label":"Button(btnRetry)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":19, "child":[ { "type":"Box", "props":{}, "nodeParent":19, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":20, "child":[ { "type":"Animation", "props":{"y":96,"x":250,"width":0,"source":"view/CyberTheme/animation/circleFlash.ani","scaleX":4,"height":0,"blendMode":"lighter","autoPlay":true}, "nodeParent":20, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":21, "child":[ ] }, { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":20, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":22, "child":[ { "type":"Rect", "props":{"y":37,"x":25,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":23, "child":[ ] }, { "type":"Rect", "props":{"y":37,"x":470,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":24, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":44,"width":414,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":25, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":171,"width":160,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":26, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":44,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":27, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":337,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":28, "child":[ ] }, { "type":"Rect", "props":{"y":148,"x":29,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":29, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":331,"width":19,"rotation":55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":30, "child":[ ] }, { "type":"Rect", "props":{"y":166,"x":160,"width":19,"rotation":-55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":31, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":458,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":32, "child":[ ] }, { "type":"Rect", "props":{"y":26,"x":48,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":33, "child":[ ] }, { "type":"Rect", "props":{"y":153,"x":477,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":34, "child":[ ] }] }] }, { "type":"Box", "props":{}, "nodeParent":19, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":35, "child":[ { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":35, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":36, "child":[ { "type":"Poly", "props":{"y":41,"x":35,"points":"0,0,8,-6,8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":36, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":37, "child":[ ] }, { "type":"Poly", "props":{"y":41,"x":464,"points":"0,0,-8,-6,-8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":36, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":38, "child":[ ] }, { "type":"Poly", "props":{"y":160,"x":177,"points":"0,0,147,0,153,10,-6,10","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":36, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":39, "child":[ ] }] }, { "type":"Animation", "props":{"y":172,"x":520,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleX":6,"blendMode":"lighter","autoPlay":true}, "nodeParent":35, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":40, "child":[ ] }] }] }, { "x":30, "type":"Button", "props":{"y":-200,"width":500,"var":"btnNext","skin":"images/button/button_main@3x.png","name":"btnNext","label":"UI_Make_New_Life","centerX":0}, "nodeParent":63, "label":"Button(btnNext)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":41, "child":[ { "type":"Box", "props":{}, "nodeParent":41, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":42, "child":[ { "type":"Animation", "props":{"y":96,"x":250,"width":0,"source":"view/CyberTheme/animation/circleFlash.ani","scaleX":4,"height":0,"blendMode":"lighter","autoPlay":true}, "nodeParent":42, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":43, "child":[ ] }, { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":42, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":44, "child":[ { "type":"Rect", "props":{"y":37,"x":25,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":45, "child":[ ] }, { "type":"Rect", "props":{"y":37,"x":470,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":46, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":44,"width":414,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":47, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":171,"width":160,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":48, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":44,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":49, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":337,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":50, "child":[ ] }, { "type":"Rect", "props":{"y":148,"x":29,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":51, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":331,"width":19,"rotation":55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":52, "child":[ ] }, { "type":"Rect", "props":{"y":166,"x":160,"width":19,"rotation":-55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":53, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":458,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":54, "child":[ ] }, { "type":"Rect", "props":{"y":26,"x":48,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":55, "child":[ ] }, { "type":"Rect", "props":{"y":153,"x":477,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":56, "child":[ ] }] }] }, { "type":"Box", "props":{}, "nodeParent":41, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":57, "child":[ { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":57, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":58, "child":[ { "type":"Poly", "props":{"y":41,"x":35,"points":"0,0,8,-6,8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":58, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":59, "child":[ ] }, { "type":"Poly", "props":{"y":41,"x":464,"points":"0,0,-8,-6,-8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":58, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":60, "child":[ ] }, { "type":"Poly", "props":{"y":160,"x":177,"points":"0,0,147,0,153,10,-6,10","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":58, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":61, "child":[ ] }] }, { "type":"Animation", "props":{"y":172,"x":520,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleX":6,"blendMode":"lighter","autoPlay":true}, "nodeParent":57, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":62, "child":[ ] }] }] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/CyberTheme/CyberAchievement.ui ================================================ { "x":0, "type":"View", "selectedBox":3, "selecteID":7, "props":{"width":1125,"sceneColor":"#000000","sceneBg":"laya/views/view/CyberTheme/CyberAchievement.png","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Button", "props":{"y":200,"var":"btnBack","skin":"images/button/button_back@3x.png","name":"btnBack","left":30}, "nodeParent":1, "label":"Button(btnBack)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":2, "child":[ ] }, { "x":15, "type":"Box", "props":{"width":1,"top":0,"right":0,"height":1}, "nodeParent":1, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":68, "child":[ { "x":30, "type":"Box", "props":{"y":200,"x":-170,"width":260,"var":"btnRank","runtime":"Laya.runtime.ScaleButton","height":90,"anchorY":0.5,"anchorX":0.5}, "nodeParent":68, "label":"Box(btnRank)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":3, "child":[ { "x":45, "type":"Image", "props":{"top":0,"skin":"images/button/button_small@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":3, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":4, "child":[ ], "$HIDDEN":false }, { "x":45, "type":"Box", "props":{"width":90,"left":8,"height":90}, "nodeParent":3, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":5, "child":[ { "x":60, "type":"Image", "props":{"skin":"images/icons/icon_rank@3x.png","centerY":0,"centerX":0}, "nodeParent":5, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":6, "child":[ ] }] }, { "x":45, "type":"Label", "props":{"text":"UI_Rank","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":40,"anchorY":0.5,"anchorX":0.5}, "nodeParent":3, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":7, "child":[ ] }] }] }, { "x":15, "type":"Box", "props":{"y":310,"x":0,"top":310,"right":0,"left":0,"height":120}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":16, "child":[ { "type":"Label", "props":{"y":110,"x":140,"var":"btnStatistics","text":"UI_Statistics","name":"btnStatistics","fontSize":100,"font":"方正像素12","color":"#ffffff","anchorY":1,"anchorX":0.5}, "nodeParent":16, "label":"Label(btnStatistics)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":18, "child":[ ] }, { "type":"Label", "props":{"y":110,"x":360,"var":"btnAchievement","text":"UI_Achievement","name":"btnAchievement","fontSize":60,"font":"方正像素12","color":"#ffffff","anchorY":1,"anchorX":0.5}, "nodeParent":16, "label":"Label(btnAchievement)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":21, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"x":0,"width":2250,"var":"boxPage","top":450,"name":"boxPage","bottom":80}, "nodeParent":1, "label":"Box(boxPage)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":8, "child":[ { "type":"Box", "props":{"width":1125,"var":"boxA","top":0,"name":"boxA","left":0,"bottom":0}, "nodeParent":8, "label":"Box(boxA)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":66, "child":[ { "type":"Box", "props":{"width":1125,"top":0,"height":1125,"centerX":0}, "nodeParent":66, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":25, "child":[ { "type":"Image", "props":{"top":40,"skin":"images/border/border_2@3x.png","right":30,"left":30,"bottom":30}, "nodeParent":25, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":26, "child":[ ], "$HIDDEN":false }, { "type":"Sprite", "props":{"y":150,"x":100,"width":920,"height":380}, "nodeParent":25, "label":"Sprite", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":52, "child":[ { "type":"Rect", "props":{"y":-1,"x":460,"width":4,"lineWidth":1,"lineColor":"#1a5459","height":320,"fillColor":"#1a5459"}, "nodeParent":52, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":50, "child":[ ] }, { "type":"Rect", "props":{"y":370,"x":0,"width":920,"lineWidth":1,"lineColor":"#1a5459","height":5,"fillColor":"#1a5459"}, "nodeParent":52, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":51, "child":[ ] }], "$HIDDEN":false }, { "type":"Box", "props":{"width":400,"top":150,"left":100,"height":320}, "nodeParent":25, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":28, "child":[ { "type":"HBox", "props":{"y":130,"x":0}, "nodeParent":28, "label":"HBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":54, "child":[ { "type":"Label", "props":{"var":"labRemakeTimes","text":"1","name":"labRemakeTimes","fontSize":70,"font":"方正像素12","color":"#55fffe","bold":true,"anchorY":1,"anchorX":0}, "nodeParent":54, "label":"Label(labRemakeTimes)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":31, "child":[ ] }, { "type":"Label", "props":{"text":"UI_Times","fontSize":70,"font":"方正像素12","color":"#55fffe","bold":true,"anchorY":1,"anchorX":0}, "nodeParent":54, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":53, "child":[ ] }] }, { "type":"Label", "props":{"y":210,"x":0,"text":"UI_Remake_Times","fontSize":62,"font":"方正像素12","color":"#ffffff","bold":false,"anchorY":1,"anchorX":0}, "nodeParent":28, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":32, "child":[ ] }, { "type":"Label", "props":{"y":240,"var":"labRemakeTimesJudge","text":"抽到紫色几率不变","name":"labRemakeTimesJudge","fontSize":42,"font":"方正像素12","color":"#93aaae","bold":false,"anchorY":0,"anchorX":0}, "nodeParent":28, "label":"Label(labRemakeTimesJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":33, "child":[ ] }] }, { "type":"Box", "props":{"width":400,"top":150,"right":100,"height":320}, "nodeParent":25, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":29, "child":[ { "type":"HBox", "props":{"y":130}, "nodeParent":29, "label":"HBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":55, "child":[ { "type":"Label", "props":{"var":"labAchievementCount","text":"1","name":"labAchievementCount","fontSize":70,"font":"方正像素12","color":"#55fffe","bold":true,"anchorY":1,"anchorX":0}, "nodeParent":55, "label":"Label(labAchievementCount)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":56, "child":[ ] }, { "type":"Label", "props":{"text":"UI_Count","fontSize":70,"font":"方正像素12","color":"#55fffe","bold":true,"anchorY":1,"anchorX":0}, "nodeParent":55, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":57, "child":[ ] }] }, { "type":"Label", "props":{"y":210,"x":0,"text":"UI_Achievement_Count","fontSize":62,"font":"方正像素12","color":"#ffffff","bold":false,"anchorY":1,"anchorX":0}, "nodeParent":29, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":38, "child":[ ] }, { "type":"Label", "props":{"y":240,"x":0,"var":"labAchievementCountJudge","text":"抽到橙色几率不变","name":"labAchievementCountJudge","fontSize":42,"font":"方正像素12","color":"#93aaae","bold":false,"anchorY":0,"anchorX":0}, "nodeParent":29, "label":"Label(labAchievementCountJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":39, "child":[ ] }] }, { "type":"Box", "props":{"right":100,"left":100,"height":450,"bottom":100}, "nodeParent":25, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":30, "child":[ { "type":"Box", "props":{"top":25,"right":0,"left":0,"height":180}, "nodeParent":30, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":41, "child":[ { "type":"Label", "props":{"y":85,"x":0,"text":"UI_Event_Collection_Rate","fontSize":62,"font":"方正像素12","color":"#ffffff","bold":false,"anchorY":1,"anchorX":0}, "nodeParent":41, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":42, "child":[ ], "$HIDDEN":false }, { "type":"ProgressBar", "props":{"y":135,"var":"prgEventRate","value":1,"skin":"images/progress/progress_1@3x.png","right":240,"name":"prgEventRate","left":0,"anchorY":0.5,"anchorX":0}, "nodeParent":41, "label":"ProgressBar(prgEventRate)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":43, "child":[ ] }, { "type":"Label", "props":{"var":"labEventRate","text":"100%","right":0,"name":"labEventRate","fontSize":110,"font":"方正像素12","color":"#55fffe","centerY":0,"bold":false,"anchorY":0.5,"anchorX":1}, "nodeParent":41, "label":"Label(labEventRate)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":44, "child":[ ] }] }, { "type":"Box", "props":{"right":0,"left":0,"height":180,"bottom":30}, "nodeParent":30, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":45, "child":[ { "type":"Label", "props":{"y":85,"x":0,"text":"UI_Talent_Collection_Rate","fontSize":62,"font":"方正像素12","color":"#ffffff","bold":false,"anchorY":1,"anchorX":0}, "nodeParent":45, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":46, "child":[ ] }, { "type":"ProgressBar", "props":{"y":135,"var":"prgTalentRate","value":0.73,"skin":"images/progress/progress_1@3x.png","right":240,"name":"prgTalentRate","left":0,"anchorY":0.5,"anchorX":0}, "nodeParent":45, "label":"ProgressBar(prgTalentRate)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":47, "child":[ ] }, { "type":"Label", "props":{"var":"labTalentRate","text":"73%","right":0,"name":"labTalentRate","fontSize":110,"font":"方正像素12","color":"#55fffe","centerY":0,"bold":false,"anchorY":0.5,"anchorX":1}, "nodeParent":45, "label":"Label(labTalentRate)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":48, "child":[ ] }], "$HIDDEN":false }] }] }] }, { "type":"Box", "props":{"width":1125,"var":"boxB","top":0,"right":0,"name":"boxB","bottom":0}, "nodeParent":8, "label":"Box(boxB)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":67, "child":[ { "type":"List", "props":{"y":35,"width":1080,"var":"listAchievements","vScrollBarSkin":"images/slider/vslider_1@3x.png","top":35,"name":"listAchievements","centerX":0,"bottom":35}, "nodeParent":67, "label":"List(listAchievements)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":9, "child":[ { "type":"Box", "props":{"y":0,"x":0,"width":530,"runtime":"Laya.runtime.ColorFilterItem","renderType":"render","height":460}, "nodeParent":9, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":10, "child":[ { "type":"Image", "props":{"top":20,"skin":"images/border/achievement@3x.png","right":20,"name":"uncomplete","left":20,"bottom":20}, "nodeParent":10, "label":"Image(uncomplete)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":11, "child":[ ], "$HIDDEN":false }, { "type":"Image", "props":{"top":0,"skin":"images/border/achievement_complete@3x.png","right":0,"name":"completed","left":0,"bottom":0}, "nodeParent":10, "label":"Image(completed)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":12, "child":[ ], "$HIDDEN":false }, { "type":"Label", "props":{"text":"霹雳霹雳","name":"name","fontSize":80,"font":"方正像素12","color":"#ffffff","centerY":-30,"centerX":0}, "nodeParent":10, "label":"Label(name)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":13, "child":[ ] }, { "type":"Label", "props":{"wordWrap":true,"text":"被第九重雷劫劈死","right":40,"name":"description","left":40,"height":95,"fontSize":42,"font":"方正像素12","color":"#9ca5a9","bottom":25,"align":"center"}, "nodeParent":10, "label":"Label(description)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":14, "child":[ ] }] }] }] }], "$HIDDEN":false }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }], "$HIDDEN":false } ================================================ FILE: laya/pages/view/CyberTheme/CyberAchievementPopup.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":10, "props":{"y":50,"width":570,"sceneColor":"#000000","mouseThrough":true,"mouseEnabled":false,"height":150,"alpha":0.75}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":2, "child":[ { "type":"Rect", "props":{"width":570,"lineWidth":1,"height":150,"fillColor":"#55fffe"}, "nodeParent":2, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":4, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"x":0,"var":"boxBg","name":"boxBg"}, "nodeParent":1, "label":"Box(boxBg)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":5, "child":[ { "type":"Rect", "props":{"width":560,"lineWidth":1,"height":150,"fillColor":"#272727"}, "nodeParent":5, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":6, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":560,"height":150}, "nodeParent":1, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":8, "child":[ { "x":30, "type":"Image", "props":{"x":70,"skin":"images/icons/icon_achievement@3x.png","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":8, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":7, "child":[ ] }, { "x":30, "type":"Label", "props":{"x":150,"var":"labName","text":"所有人都是我","name":"labName","fontSize":60,"font":"方正像素12","color":"#cccccc","centerY":0}, "nodeParent":8, "label":"Label(labName)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":9, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/CyberTheme/CyberMain.ui ================================================ { "x":0, "type":"View", "selectedBox":93, "selecteID":94, "props":{"y":1218,"x":562,"width":1125,"sceneColor":"#000000","sceneBg":"laya/views/view/CyberTheme/CyberMain.png","runtime":"Laya.runtime.ViewBase","height":2436,"anchorY":0.5,"anchorX":0.5}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Image", "props":{"var":"imgBg","skin":"images/background/background_1@3x.png","name":"imgBg","centerY":0,"centerX":0}, "nodeParent":1, "label":"Image(imgBg)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":67, "child":[ { "type":"Animation", "props":{"y":0,"x":0,"width":1125,"source":"view/CyberTheme/animation/jumpBackground.ani","interval":80,"height":2436,"blendMode":"lighter","autoPlay":true,"alpha":0.3}, "nodeParent":67, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":70, "child":[ ] }], "$HIDDEN":false }, { "x":15, "type":"Image", "props":{"var":"imgTitle","skin":"images/accessories/title@3x.png","runtime":"Laya.runtime.ColorFilterItem","name":"imgTitle","centerY":-350,"centerX":0}, "nodeParent":1, "label":"Image(imgTitle)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":68, "child":[ { "type":"Box", "props":{"y":0,"x":0}, "nodeParent":68, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":75, "child":[ { "type":"Image", "props":{"y":8,"x":8,"skin":"images/accessories/title_neon@3x.png","renderType":"mask"}, "nodeParent":75, "label":"Image", "isOpen":true, "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":71, "child":[ ] }, { "type":"Animation", "props":{"y":286,"x":436,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleY":1.5,"scaleX":5,"blendMode":"lighter","autoPlay":true}, "nodeParent":75, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":77, "child":[ ] }] }] }, { "x":15, "type":"Image", "props":{"skin":"images/accessories/insert_coin@3x.png","centerY":540,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":7, "child":[ ] }, { "x":15, "type":"Label", "props":{"text":"UI_Title_Remake","fontSize":80,"font":"方正像素12","color":"#ffffff","centerY":-135,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":8, "child":[ ] }, { "x":15, "type":"Label", "props":{"wordWrap":true,"text":"UI_Title_Subsequent","right":0,"left":0,"fontSize":48,"font":"方正像素12","color":"#828c95","centerY":-20,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":1, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":11, "child":[ ] }, { "x":15, "type":"Label", "props":{"text":"UI_Cyber_Theme_Art_Design","right":50,"fontSize":48,"font":"方正像素12","color":"#00fffd","bottom":30,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":12, "child":[ ] }, { "x":15, "type":"Button", "props":{"var":"btnRemake","skin":"images/button/button_main@3x.png","pivotY":96,"pivotX":329,"name":"btnRemake","labelSize":60,"label":"UI_Remake","centerY":720,"centerX":0}, "nodeParent":1, "label":"Button(btnRemake)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":13, "child":[ { "type":"Box", "props":{}, "nodeParent":13, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":29, "child":[ { "type":"Animation", "props":{"y":93,"x":330,"width":0,"source":"view/CyberTheme/animation/circleFlash.ani","scaleX":5,"height":0,"blendMode":"lighter","autoPlay":true}, "nodeParent":29, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":26, "child":[ ] }, { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":29, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":44, "child":[ { "type":"Rect", "props":{"y":37,"x":25,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":45, "child":[ ] }, { "type":"Rect", "props":{"y":37,"x":625,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":46, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":44,"width":569,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":47, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":171,"width":316,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":48, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":44,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":49, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":493,"width":120,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":50, "child":[ ] }, { "type":"Rect", "props":{"y":148,"x":29,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":51, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":487,"width":19,"rotation":55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":52, "child":[ ] }, { "type":"Rect", "props":{"y":166,"x":160,"width":19,"rotation":-55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":53, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":613,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":54, "child":[ ] }, { "type":"Rect", "props":{"y":26,"x":48,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":55, "child":[ ] }, { "type":"Rect", "props":{"y":153,"x":632,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":44, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":56, "child":[ ] }] }] }, { "type":"Box", "props":{}, "nodeParent":13, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":57, "child":[ { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":57, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":58, "child":[ { "type":"Poly", "props":{"y":41,"x":35,"points":"0,0,8,-6,8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":58, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":62, "child":[ ] }, { "type":"Poly", "props":{"y":41,"x":621,"points":"0,0,-8,-6,-8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":58, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":63, "child":[ ] }, { "type":"Poly", "props":{"y":160,"x":177,"points":"0,0,305,0,311,10,-6,10","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":58, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":65, "child":[ ] }] }, { "type":"Animation", "props":{"y":172,"x":330,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleX":4,"blendMode":"lighter","autoPlay":true}, "nodeParent":57, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":66, "child":[ ] }] }] }, { "x":15, "type":"Box", "props":{"y":200,"x":200,"width":225,"var":"btnThanks","runtime":"Laya.runtime.ScaleButton","name":"btnThanks","height":90,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnThanks)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":15, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/button/button_small@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":15, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":16, "child":[ ], "$HIDDEN":false }, { "type":"Box", "props":{"width":90,"left":8,"height":90}, "nodeParent":15, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":19, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_thanks@3x.png","centerY":0,"centerX":0}, "nodeParent":19, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":18, "child":[ ] }] }, { "type":"Label", "props":{"text":"UI_Thanks","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":40,"anchorY":0.5,"anchorX":0.5}, "nodeParent":15, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":20, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"y":0,"x":1100,"width":1,"top":0,"right":0,"height":1}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":84, "child":[ { "type":"Box", "props":{"y":200,"x":-200,"width":225,"var":"btnAchievement","runtime":"Laya.runtime.ScaleButton","name":"btnAchievement","height":90,"anchorY":0.5,"anchorX":0.5}, "nodeParent":84, "label":"Box(btnAchievement)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":21, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/button/button_small@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":21, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":22, "child":[ ], "$HIDDEN":false }, { "type":"Box", "props":{"width":90,"left":8,"height":90}, "nodeParent":21, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":23, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_achievement@3x.png","centerY":0,"centerX":0}, "nodeParent":23, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":24, "child":[ ] }] }, { "type":"Label", "props":{"text":"UI_Achievement","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":40,"anchorY":0.5,"anchorX":0.5}, "nodeParent":21, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":25, "child":[ ] }], "$HIDDEN":false }] }, { "x":15, "type":"Box", "props":{"width":1,"left":0,"height":1,"bottom":0}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":85, "child":[ { "type":"Box", "props":{"y":-175,"x":100,"width":160,"var":"btnGithub","runtime":"Laya.runtime.ScaleButton","name":"btnGithub","height":160,"anchorY":0.5,"anchorX":0.5}, "nodeParent":85, "label":"Box(btnGithub)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":82, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/icons/icon_github.png","right":0,"left":0,"bottom":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":82, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":78, "child":[ ] }] }, { "type":"Box", "props":{"y":-355,"x":100,"width":160,"var":"btnDiscord","runtime":"Laya.runtime.ScaleButton","name":"btnDiscord","height":160,"anchorY":0.5,"anchorX":0.5}, "nodeParent":85, "label":"Box(btnDiscord)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":83, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/icons/icon_discord.png","right":0,"left":0,"bottom":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":83, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":79, "child":[ ] }] }] }, { "x":15, "type":"Box", "props":{"right":0,"bottom":0}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":88, "child":[ { "type":"Box", "props":{"y":-300,"x":-100,"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"anchorY":0.5,"anchorX":0.5}, "nodeParent":88, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":90, "child":[ { "type":"Box", "props":{"width":110,"var":"btnSaveLoad","runtime":"Laya.runtime.ColorfulBox","name":"btnSmall","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":90, "label":"Box(btnSaveLoad)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":91, "child":[ { "type":"Image", "props":{"width":80,"skin":"images/icons/icon_save.png","height":80,"centerY":0,"centerX":0}, "nodeParent":91, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":92, "child":[ ] }] }] }, { "type":"Box", "props":{"y":-175,"x":-100,"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"anchorY":0.5,"anchorX":0.5}, "nodeParent":88, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":89, "child":[ { "type":"Box", "props":{"width":110,"var":"btnThemes","runtime":"Laya.runtime.ColorfulBox","name":"btnThemes","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":89, "label":"Box(btnThemes)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":86, "child":[ { "type":"Image", "props":{"width":90,"skin":"images/icons/icon_themes.png","height":90,"centerY":0,"centerX":0}, "nodeParent":86, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":87, "child":[ ] }] }] }] }, { "x":15, "type":"Box", "props":{"x":572,"var":"banner","centerX":0,"bottom":100,"anchorY":1,"anchorX":0.5}, "nodeParent":1, "label":"Box(banner)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":93, "child":[ { "x":30, "type":"Label", "props":{"text":"UI_Banner","fontSize":40,"font":"方正像素12","color":"#00fffd"}, "nodeParent":93, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":94, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/CyberTheme/CyberProperty.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":97, "referenceLines":null, "props":{"width":1125,"sceneColor":"#000000","sceneBg":"laya/views/view/CyberTheme/CyberProperty.png","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"top":40,"right":0,"name":"title","left":0}, "nodeParent":1, "label":"Box(title)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":2, "child":[ { "type":"Image", "props":{"skin":"images/accessories/titlebar@3x.png","right":0,"left":0}, "nodeParent":2, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":3, "child":[ ] }, { "type":"HBox", "props":{"y":160,"x":563,"space":30,"height":70,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":2, "label":"HBox", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":4, "child":[ { "type":"Image", "props":{"y":10,"x":1,"skin":"images/accessories/title_left@3x.png","name":"left"}, "nodeParent":4, "label":"Image(left)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":5, "child":[ ] }, { "type":"Label", "props":{"y":0,"x":2,"text":"UI_Title_Property","fontSize":60,"font":"方正像素12","color":"#ffffff"}, "nodeParent":4, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":6, "child":[ ] }, { "type":"Image", "props":{"y":10,"x":3,"skin":"images/accessories/title_right@3x.png","name":"right"}, "nodeParent":4, "label":"Image(right)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":7, "child":[ ] }] }], "$LOCKED":true }, { "x":15, "type":"Box", "props":{"top":340,"right":40,"name":"propertyAllocate","left":40,"height":840}, "nodeParent":1, "label":"Box(propertyAllocate)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":8, "child":[ { "type":"Image", "props":{"top":-15,"skin":"images/border/border_2@3x.png","right":-15,"left":-15,"bottom":-15}, "nodeParent":8, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":55, "child":[ ] }, { "type":"HBox", "props":{"top":680,"right":80,"height":100}, "nodeParent":8, "label":"HBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":50, "child":[ { "type":"Label", "props":{"x":0,"text":"UI_Left_Property_Point","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0}, "nodeParent":50, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":52, "child":[ ] }, { "type":"Label", "props":{"x":1,"text":"UI_Colon","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0}, "nodeParent":50, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":54, "child":[ ] }, { "type":"Label", "props":{"x":2,"var":"labLeftPropertyPoint","text":"0","name":"labLeftPropertyPoint","fontSize":80,"font":"方正像素12","color":"#ffffff","centerY":0}, "nodeParent":50, "label":"Label(labLeftPropertyPoint)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":53, "child":[ ] }] }, { "type":"VBox", "props":{"top":90,"space":22,"right":50,"left":50,"height":600}, "nodeParent":8, "label":"VBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":120, "child":[ { "type":"Box", "props":{"y":0,"var":"boxCharm","right":0,"name":"boxCharm","left":0,"height":130}, "nodeParent":120, "label":"Box(boxCharm)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":10, "child":[ { "type":"Box", "props":{"width":120,"left":0,"height":120,"centerY":0}, "nodeParent":10, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":17, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_chr@3x.png","scaleY":1.4,"scaleX":1.4,"centerY":0,"centerX":0}, "nodeParent":17, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":18, "child":[ ] }] }, { "type":"Label", "props":{"x":183,"text":"UI_Property_Charm","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":10, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":19, "child":[ ] }, { "type":"Box", "props":{"width":590,"var":"boxCharmAllocate","right":30,"name":"boxCharmAllocate","height":110,"centerY":0}, "nodeParent":10, "label":"Box(boxCharmAllocate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":20, "child":[ { "type":"Box", "props":{"width":110,"var":"btnCharmReduce","name":"btnCharmReduce","left":0,"height":110,"centerY":0}, "nodeParent":20, "label":"Box(btnCharmReduce)", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":21, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":21, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":24, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":24, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":26, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":24, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":27, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":24, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":28, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":24, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":30, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":21, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":39, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":39, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":25, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":25, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":23, "child":[ ] }] }] }] }, { "type":"Box", "props":{"y":0,"x":110,"top":0,"right":110,"left":110,"bottom":0}, "nodeParent":20, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":42, "child":[ { "type":"TextInput", "props":{"var":"inputCharm","type":"number","top":0,"text":"0","skin":"images/border/up@3x.png","right":0,"promptColor":"#828282","prompt":0,"name":"inputCharm","maxChars":1,"left":0,"fontSize":80,"font":"方正像素12","color":"#ffffff","bottom":0,"align":"center"}, "nodeParent":42, "label":"TextInput(inputCharm)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":48, "child":[ ] }, { "type":"Box", "props":{"y":0,"x":0,"top":0,"right":0,"mouseThrough":true,"mouseEnabled":false,"left":0,"bottom":0,"alpha":0.2}, "nodeParent":42, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":43, "child":[ { "type":"Rect", "props":{"width":370,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":43, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":44, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":43, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":45, "child":[ ] }] }] }, { "type":"Box", "props":{"width":110,"var":"btnCharmIncrease","right":0,"name":"btnCharmIncrease","height":110,"centerY":0}, "nodeParent":20, "label":"Box(btnCharmIncrease)", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":22, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":22, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":31, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":31, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":32, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":31, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":33, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":31, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":34, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":31, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":35, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":22, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":38, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":38, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":36, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":36, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":37, "child":[ ] }] }, { "type":"Box", "props":{"width":48,"rotation":90,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":38, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":40, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":40, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":41, "child":[ ] }] }] }] }] }] }, { "type":"Box", "props":{"y":1,"var":"boxIntelligence","right":0,"name":"boxIntelligence","left":0,"height":130}, "nodeParent":120, "label":"Box(boxIntelligence)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":121, "child":[ { "type":"Box", "props":{"width":120,"left":0,"height":120,"centerY":0}, "nodeParent":121, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":122, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_int@3x.png","scaleY":1.4,"scaleX":1.4,"centerY":0,"centerX":0}, "nodeParent":122, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":123, "child":[ ] }] }, { "type":"Label", "props":{"x":183,"text":"UI_Property_Intelligence","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":121, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":124, "child":[ ] }, { "type":"Box", "props":{"width":590,"var":"boxIntelligenceAllocate","right":30,"name":"boxIntelligenceAllocate","height":110,"centerY":0}, "nodeParent":121, "label":"Box(boxIntelligenceAllocate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":125, "child":[ { "type":"Box", "props":{"width":110,"var":"btnIntelligenceReduce","name":"btnIntelligenceReduce","left":0,"height":110,"centerY":0}, "nodeParent":125, "label":"Box(btnIntelligenceReduce)", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":126, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":126, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":127, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":127, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":128, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":127, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":129, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":127, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":130, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":127, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":131, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":126, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":132, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":132, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":133, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":134, "child":[ ] }] }] }] }, { "type":"Box", "props":{"y":0,"x":110,"top":0,"right":110,"left":110,"bottom":0}, "nodeParent":125, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":135, "child":[ { "type":"TextInput", "props":{"var":"inputIntelligence","type":"number","top":0,"text":"0","skin":"images/border/up@3x.png","right":0,"promptColor":"#828282","prompt":0,"name":"inputIntelligence","maxChars":1,"left":0,"fontSize":80,"font":"方正像素12","color":"#ffffff","bottom":0,"align":"center"}, "nodeParent":135, "label":"TextInput(inputIntelligence)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":136, "child":[ ] }, { "type":"Box", "props":{"y":0,"x":0,"top":0,"right":0,"mouseThrough":true,"mouseEnabled":false,"left":0,"bottom":0,"alpha":0.2}, "nodeParent":135, "label":"Box", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":137, "child":[ { "type":"Rect", "props":{"width":370,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":137, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":138, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":137, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":139, "child":[ ] }] }] }, { "type":"Box", "props":{"width":110,"var":"btnIntelligenceIncrease","right":0,"name":"btnIntelligenceIncrease","height":110,"centerY":0}, "nodeParent":125, "label":"Box(btnIntelligenceIncrease)", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":140, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":140, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":141, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":141, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":142, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":141, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":143, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":141, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":144, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":141, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":145, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":140, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":146, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":146, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":147, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":147, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":148, "child":[ ] }] }, { "type":"Box", "props":{"width":48,"rotation":90,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":146, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":149, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":149, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":150, "child":[ ] }] }] }] }] }] }, { "type":"Box", "props":{"y":2,"var":"boxStrength","right":0,"name":"boxStrength","left":0,"height":130}, "nodeParent":120, "label":"Box(boxStrength)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":151, "child":[ { "type":"Box", "props":{"width":120,"left":0,"height":120,"centerY":0}, "nodeParent":151, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":152, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_str@3x.png","scaleY":1.4,"scaleX":1.4,"centerY":0,"centerX":0}, "nodeParent":152, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":153, "child":[ ] }] }, { "type":"Label", "props":{"x":183,"text":"UI_Property_Strength","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":151, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":154, "child":[ ] }, { "type":"Box", "props":{"width":590,"var":"boxStrengthAllocate","right":30,"name":"boxStrengthAllocate","height":110,"centerY":0}, "nodeParent":151, "label":"Box(boxStrengthAllocate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":155, "child":[ { "type":"Box", "props":{"width":110,"var":"btnStrengthReduce","name":"btnStrengthReduce","left":0,"height":110,"centerY":0}, "nodeParent":155, "label":"Box(btnStrengthReduce)", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":156, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":156, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":157, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":157, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":158, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":157, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":159, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":157, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":160, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":157, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":161, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":156, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":162, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":162, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":163, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":163, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":164, "child":[ ] }] }] }] }, { "type":"Box", "props":{"y":0,"x":110,"top":0,"right":110,"left":110,"bottom":0}, "nodeParent":155, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":165, "child":[ { "type":"TextInput", "props":{"var":"inputStrength","type":"number","top":0,"text":"0","skin":"images/border/up@3x.png","right":0,"promptColor":"#828282","prompt":0,"name":"inputStrength","maxChars":1,"left":0,"fontSize":80,"font":"方正像素12","color":"#ffffff","bottom":0,"align":"center"}, "nodeParent":165, "label":"TextInput(inputStrength)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":166, "child":[ ] }, { "type":"Box", "props":{"y":0,"x":0,"top":0,"right":0,"mouseThrough":true,"mouseEnabled":false,"left":0,"bottom":0,"alpha":0.2}, "nodeParent":165, "label":"Box", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":167, "child":[ { "type":"Rect", "props":{"width":370,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":167, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":168, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":167, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":169, "child":[ ] }] }] }, { "type":"Box", "props":{"width":110,"var":"btnStrengthIncrease","right":0,"name":"btnStrengthIncrease","height":110,"centerY":0}, "nodeParent":155, "label":"Box(btnStrengthIncrease)", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":170, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":170, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":171, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":171, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":172, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":171, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":173, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":171, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":174, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":171, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":175, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":170, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":176, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":176, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":177, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":177, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":178, "child":[ ] }] }, { "type":"Box", "props":{"width":48,"rotation":90,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":176, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":179, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":179, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":180, "child":[ ] }] }] }] }] }] }, { "type":"Box", "props":{"y":3,"var":"boxMoney","right":0,"name":"boxMoney","left":0,"height":130}, "nodeParent":120, "label":"Box(boxMoney)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":181, "child":[ { "type":"Box", "props":{"width":120,"left":0,"height":120,"centerY":0}, "nodeParent":181, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":182, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_mny@3x.png","scaleY":1.4,"scaleX":1.4,"centerY":0,"centerX":0}, "nodeParent":182, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":183, "child":[ ] }] }, { "type":"Label", "props":{"x":183,"text":"UI_Property_Money","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":181, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":184, "child":[ ] }, { "type":"Box", "props":{"width":590,"var":"boxMoneyAllocate","right":30,"name":"boxMoneyAllocate","height":110,"centerY":0}, "nodeParent":181, "label":"Box(boxMoneyAllocate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":185, "child":[ { "type":"Box", "props":{"width":110,"var":"btnMoneyReduce","name":"btnMoneyReduce","left":0,"height":110,"centerY":0}, "nodeParent":185, "label":"Box(btnMoneyReduce)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":186, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":186, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":187, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":187, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":188, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":187, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":189, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":187, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":190, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":187, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":191, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":186, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":192, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":192, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":193, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":193, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":194, "child":[ ] }] }] }] }, { "type":"Box", "props":{"y":0,"x":110,"top":0,"right":110,"left":110,"bottom":0}, "nodeParent":185, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":195, "child":[ { "type":"TextInput", "props":{"var":"inputMoney","type":"number","top":0,"text":"0","skin":"images/border/up@3x.png","right":0,"promptColor":"#828282","prompt":0,"name":"inputMoney","maxChars":1,"left":0,"fontSize":80,"font":"方正像素12","color":"#ffffff","bottom":0,"align":"center"}, "nodeParent":195, "label":"TextInput(inputMoney)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":196, "child":[ ] }, { "type":"Box", "props":{"y":0,"x":0,"top":0,"right":0,"mouseThrough":true,"mouseEnabled":false,"left":0,"bottom":0,"alpha":0.2}, "nodeParent":195, "label":"Box", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":197, "child":[ { "type":"Rect", "props":{"width":370,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":197, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":198, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":197, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":199, "child":[ ] }] }] }, { "type":"Box", "props":{"width":110,"var":"btnMoneyIncrease","right":0,"name":"btnMoneyIncrease","height":110,"centerY":0}, "nodeParent":185, "label":"Box(btnMoneyIncrease)", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":200, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":200, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":201, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":201, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":202, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#55fffe"}, "nodeParent":201, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":203, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":201, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":204, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#55fffe"}, "nodeParent":201, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":205, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":200, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":206, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":206, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":207, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":207, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":208, "child":[ ] }] }, { "type":"Box", "props":{"width":48,"rotation":90,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":206, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":209, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#55fffe"}, "nodeParent":209, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":210, "child":[ ] }] }] }] }] }] }] }], "$LOCKED":true }, { "x":15, "type":"Box", "props":{"right":40,"name":"selectedTalents","left":40,"height":700,"bottom":500}, "nodeParent":1, "label":"Box(selectedTalents)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":56, "child":[ { "type":"Label", "props":{"top":20,"text":"UI_Selected_Talent","left":20,"fontSize":50,"font":"方正像素12","color":"#ffffff"}, "nodeParent":56, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":57, "child":[ ] }, { "type":"List", "props":{"var":"listSelectedTalents","vScrollBarSkin":" ","top":110,"spaceY":30,"right":10,"repeatY":3,"name":"listSelectedTalents","left":10,"bottom":10}, "nodeParent":56, "label":"List(listSelectedTalents)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":58, "child":[ { "type":"Box", "props":{"y":20,"right":10,"renderType":"render","left":10,"height":160}, "nodeParent":58, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":59, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/border/up@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":59, "label":"Image", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":63, "child":[ ] }, { "type":"Box", "props":{"width":15,"name":"grade1","height":160}, "nodeParent":59, "label":"Box(grade1)", "isOpen":null, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":61, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":160,"fillColor":"#55fffe"}, "nodeParent":61, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":62, "child":[ ] }] }, { "type":"Box", "props":{"width":15,"name":"grade2","height":160}, "nodeParent":59, "label":"Box(grade2)", "isOpen":null, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":64, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":160,"fillColor":"#b17cff"}, "nodeParent":64, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":65, "child":[ ] }] }, { "type":"Box", "props":{"width":15,"name":"grade3","height":160}, "nodeParent":59, "label":"Box(grade3)", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":66, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":160,"fillColor":"#ffce45"}, "nodeParent":66, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":67, "child":[ ] }] }, { "type":"Label", "props":{"text":"Title","name":"labTitle","left":52,"fontSize":55,"font":"方正像素12","color":"#ffffff","centerY":0}, "nodeParent":59, "label":"Label(labTitle)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":68, "child":[ ] }, { "type":"Label", "props":{"y":10,"text":"descriptipn","right":33,"name":"labDescription","fontSize":44,"font":"方正像素12","color":"#76979d","centerY":0}, "nodeParent":59, "label":"Label(labDescription)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":69, "child":[ ] }] }] }], "$LOCKED":true }, { "x":15, "type":"Box", "props":{"width":1000,"name":"buttonGroup","height":200,"centerX":0,"bottom":90}, "nodeParent":1, "label":"Box(buttonGroup)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":71, "child":[ { "type":"Box", "props":{"width":500,"top":0,"left":0,"bottom":0}, "nodeParent":71, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":72, "child":[ { "type":"Button", "props":{"width":500,"var":"btnRandomAllocate","skin":"images/button/button_main@3x.png","name":"btnRandomAllocate","label":"UI_Random_Allocate","centerY":0,"centerX":0}, "nodeParent":72, "label":"Button(btnRandomAllocate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":74, "child":[ { "type":"Box", "props":{}, "nodeParent":74, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":76, "child":[ { "type":"Animation", "props":{"y":96,"x":250,"width":0,"source":"view/CyberTheme/animation/circleFlash.ani","scaleX":4,"height":0,"blendMode":"lighter","autoPlay":true}, "nodeParent":76, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":78, "child":[ ] }, { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":76, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":79, "child":[ { "type":"Rect", "props":{"y":37,"x":25,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":80, "child":[ ] }, { "type":"Rect", "props":{"y":37,"x":470,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":81, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":44,"width":414,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":82, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":171,"width":160,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":83, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":44,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":84, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":337,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":85, "child":[ ] }, { "type":"Rect", "props":{"y":148,"x":29,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":86, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":331,"width":19,"rotation":55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":87, "child":[ ] }, { "type":"Rect", "props":{"y":166,"x":160,"width":19,"rotation":-55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":88, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":458,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":89, "child":[ ] }, { "type":"Rect", "props":{"y":26,"x":48,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":90, "child":[ ] }, { "type":"Rect", "props":{"y":153,"x":477,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":79, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":91, "child":[ ] }] }] }, { "type":"Box", "props":{}, "nodeParent":74, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":77, "child":[ { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":77, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":92, "child":[ { "type":"Poly", "props":{"y":41,"x":35,"points":"0,0,8,-6,8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":92, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":93, "child":[ ] }, { "type":"Poly", "props":{"y":41,"x":464,"points":"0,0,-8,-6,-8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":92, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":94, "child":[ ] }, { "type":"Poly", "props":{"y":160,"x":177,"points":"0,0,147,0,153,10,-6,10","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":92, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":95, "child":[ ] }] }, { "type":"Animation", "props":{"y":172,"x":520,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleX":6,"blendMode":"lighter","autoPlay":true}, "nodeParent":77, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":96, "child":[ ] }] }] }] }, { "type":"Box", "props":{"width":500,"top":0,"right":0,"bottom":0}, "nodeParent":71, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":73, "child":[ { "type":"Button", "props":{"width":500,"var":"btnNext","skin":"images/button/button_main@3x.png","name":"btnNext","label":"UI_Make_New_Life","centerY":0,"centerX":0}, "nodeParent":73, "label":"Button(btnNext)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":75, "child":[ { "type":"Box", "props":{"runtime":"Laya.runtime.ColorFilterItem","colorFilter":"#ffce45ff","blendMode":"lighter"}, "nodeParent":75, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":99, "child":[ { "type":"Animation", "props":{"y":96,"x":250,"width":0,"source":"view/CyberTheme/animation/circleFlash.ani","scaleX":4,"height":0,"blendMode":"lighter","autoPlay":true}, "nodeParent":99, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":101, "child":[ ] }, { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":99, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":102, "child":[ { "type":"Rect", "props":{"y":37,"x":25,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":103, "child":[ ] }, { "type":"Rect", "props":{"y":37,"x":470,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":104, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":44,"width":414,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":105, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":171,"width":160,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":106, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":44,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":107, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":337,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":108, "child":[ ] }, { "type":"Rect", "props":{"y":148,"x":29,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":109, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":331,"width":19,"rotation":55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":110, "child":[ ] }, { "type":"Rect", "props":{"y":166,"x":160,"width":19,"rotation":-55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":111, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":458,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":112, "child":[ ] }, { "type":"Rect", "props":{"y":26,"x":48,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":113, "child":[ ] }, { "type":"Rect", "props":{"y":153,"x":477,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":102, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":114, "child":[ ] }] }] }, { "type":"Box", "props":{"runtime":"Laya.runtime.ColorFilterItem","colorFilter":"#ffce45ff","blendMode":"lighter"}, "nodeParent":75, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":100, "child":[ { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":100, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":115, "child":[ { "type":"Poly", "props":{"y":41,"x":35,"points":"0,0,8,-6,8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":115, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":116, "child":[ ] }, { "type":"Poly", "props":{"y":41,"x":464,"points":"0,0,-8,-6,-8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":115, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":117, "child":[ ] }, { "type":"Poly", "props":{"y":160,"x":177,"points":"0,0,147,0,153,10,-6,10","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":115, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":118, "child":[ ] }] }, { "type":"Animation", "props":{"y":172,"x":250,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleX":4,"blendMode":"lighter","autoPlay":true}, "nodeParent":100, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":119, "child":[ ] }] }] }] }], "$LOCKED":true }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/CyberTheme/CyberSummary.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":8, "props":{"width":1125,"sceneColor":"#000000","sceneBg":"laya/views/view/CyberTheme/CyberSummary.png","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"top":40,"right":0,"name":"title","left":0}, "nodeParent":1, "label":"Box(title)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":2, "child":[ { "x":30, "type":"Image", "props":{"skin":"images/accessories/titlebar@3x.png","right":0,"left":0}, "nodeParent":2, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":3, "child":[ ] }, { "x":30, "type":"HBox", "props":{"y":160,"x":563,"space":30,"height":70,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":2, "label":"HBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":4, "child":[ { "x":45, "type":"Image", "props":{"y":10,"x":1,"skin":"images/accessories/title_left@3x.png","name":"left"}, "nodeParent":4, "label":"Image(left)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":5, "child":[ ] }, { "x":45, "type":"Label", "props":{"y":0,"x":2,"text":"UI_Title_Summary","fontSize":60,"font":"方正像素12","color":"#ffffff"}, "nodeParent":4, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":6, "child":[ ] }, { "x":45, "type":"Image", "props":{"y":10,"x":3,"skin":"images/accessories/title_right@3x.png","name":"right"}, "nodeParent":4, "label":"Image(right)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":7, "child":[ ] }] }], "$LOCKED":true }, { "x":15, "type":"Box", "props":{"y":340,"x":40,"top":340,"right":40,"name":"summary","left":40,"height":870}, "nodeParent":1, "label":"Box(summary)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":8, "child":[ { "type":"Image", "props":{"top":-15,"skin":"images/border/border_2@3x.png","right":-15,"left":-15,"bottom":-15}, "nodeParent":8, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":11, "child":[ ] }, { "type":"Box", "props":{"top":60,"right":50,"left":50,"height":220}, "nodeParent":8, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":227, "child":[ { "type":"Box", "props":{"width":220,"left":20,"height":220,"centerY":0}, "nodeParent":227, "label":"Box", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":228, "child":[ ] }, { "type":"Box", "props":{"top":0,"right":0,"left":250,"height":100}, "nodeParent":227, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":229, "child":[ { "type":"Box", "props":{"width":320,"top":5,"left":5,"bottom":5}, "nodeParent":229, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":231, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/border/property@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":231, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":234, "child":[ ], "$HIDDEN":false }, { "type":"HBox", "props":{"left":20,"centerY":0}, "nodeParent":231, "label":"HBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":239, "child":[ { "type":"Label", "props":{"x":0,"text":"UI_Final_Age","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"align":"center"}, "nodeParent":239, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":237, "child":[ ] }, { "type":"Label", "props":{"x":1,"text":"UI_Colon","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"align":"center"}, "nodeParent":239, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":238, "child":[ ] }] }, { "type":"Label", "props":{"var":"labAge","text":"0","right":40,"name":"labAge","fontSize":50,"font":"方正像素12","color":"#5cc8dc","centerY":0,"align":"center"}, "nodeParent":231, "label":"Label(labAge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":236, "child":[ ] }] }, { "type":"Label", "props":{"width":220,"var":"labAgeJudge","text":"Judge","right":0,"name":"labAgeJudge","fontSize":50,"font":"方正像素12","color":"#5cc8dc","centerY":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":229, "label":"Label(labAgeJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":226, "child":[ ] }] }, { "type":"Box", "props":{"right":0,"left":250,"height":100,"bottom":0}, "nodeParent":227, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":230, "child":[ { "type":"Box", "props":{"width":320,"top":5,"left":5,"bottom":5}, "nodeParent":230, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":240, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/border/property@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":240, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":241, "child":[ ], "$HIDDEN":false }, { "type":"HBox", "props":{"left":20,"centerY":0}, "nodeParent":240, "label":"HBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":242, "child":[ { "type":"Label", "props":{"x":0,"text":"UI_Total_Judge","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"align":"center"}, "nodeParent":242, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":243, "child":[ ] }, { "type":"Label", "props":{"x":1,"text":"UI_Colon","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"align":"center"}, "nodeParent":242, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":244, "child":[ ] }] }, { "type":"Label", "props":{"var":"labTotal","text":"0","right":40,"name":"labTotal","fontSize":50,"font":"方正像素12","color":"#5cc8dc","centerY":0,"align":"center"}, "nodeParent":240, "label":"Label(labTotal)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":245, "child":[ ] }] }, { "type":"Label", "props":{"width":220,"var":"labTotalJudge","text":"Judge","right":0,"name":"labTotalJudge","fontSize":50,"font":"方正像素12","color":"#5cc8dc","centerY":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":230, "label":"Label(labTotalJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":225, "child":[ ] }] }] }, { "type":"VBox", "props":{"top":340,"space":5,"right":50,"left":50}, "nodeParent":8, "label":"VBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":16, "child":[ { "type":"Box", "props":{"y":0,"right":0,"name":"boxCharm","left":0,"height":90}, "nodeParent":16, "label":"Box(boxCharm)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":17, "child":[ { "type":"Box", "props":{"width":120,"left":0,"height":120,"centerY":0}, "nodeParent":17, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":18, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_chr@3x.png","scaleY":1.1,"scaleX":1.1,"centerY":0,"centerX":0}, "nodeParent":18, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":19, "child":[ ] }] }, { "type":"Label", "props":{"x":170,"text":"UI_Property_Charm","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":17, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":20, "child":[ ] }, { "type":"Box", "props":{"var":"boxCharmGrade","top":20,"runtime":"Laya.runtime.ColorFilterItem","right":240,"name":"boxCharmGrade","left":255,"bottom":20}, "nodeParent":17, "label":"Box(boxCharmGrade)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":200, "child":[ { "type":"ProgressBar", "props":{"var":"prgCharm","value":0.91,"top":0,"skin":"images/progress/progress_2.png","right":0,"name":"prgCharm","left":0,"bottom":0}, "nodeParent":200, "label":"ProgressBar(prgCharm)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":199, "child":[ ] }, { "type":"Label", "props":{"var":"labCharm","text":"100","strokeColor":"#323232","stroke":8,"name":"labCharm","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":200, "label":"Label(labCharm)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":251, "child":[ ] }] }, { "type":"Label", "props":{"width":220,"var":"labCharmJudge","text":"Judge","right":0,"name":"labCharmJudge","fontSize":50,"font":"方正像素12","color":"#5cc8dc","centerY":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":17, "label":"Label(labCharmJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":219, "child":[ ] }] }, { "type":"Box", "props":{"y":1,"right":0,"name":"boxIntelligence","left":0,"height":90}, "nodeParent":16, "label":"Box(boxIntelligence)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":47, "child":[ { "type":"Box", "props":{"width":120,"left":0,"height":120,"centerY":0}, "nodeParent":47, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":48, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_int@3x.png","scaleY":1.1,"scaleX":1.1,"centerY":0,"centerX":0}, "nodeParent":48, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":49, "child":[ ] }] }, { "type":"Label", "props":{"x":170,"text":"UI_Property_Intelligence","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":47, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":50, "child":[ ] }, { "type":"Box", "props":{"var":"boxIntelligenceGrade","top":20,"runtime":"Laya.runtime.ColorFilterItem","right":240,"name":"boxIntelligenceGrade","left":255,"bottom":20}, "nodeParent":47, "label":"Box(boxIntelligenceGrade)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":211, "child":[ { "type":"ProgressBar", "props":{"var":"prgIntelligence","value":0.57,"top":0,"skin":"images/progress/progress_2.png","right":0,"name":"prgIntelligence","left":0,"bottom":0}, "nodeParent":211, "label":"ProgressBar(prgIntelligence)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":212, "child":[ ] }, { "type":"Label", "props":{"var":"labIntelligence","text":"100","strokeColor":"#323232","stroke":8,"name":"labIntelligence","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":211, "label":"Label(labIntelligence)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":249, "child":[ ] }] }, { "type":"Label", "props":{"width":220,"var":"labIntelligenceJudge","text":"Judge","right":0,"name":"labIntelligenceJudge","fontSize":50,"font":"方正像素12","color":"#5cc8dc","centerY":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":47, "label":"Label(labIntelligenceJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":220, "child":[ ] }] }, { "type":"Box", "props":{"y":2,"right":0,"name":"boxStrength","left":0,"height":90}, "nodeParent":16, "label":"Box(boxStrength)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":77, "child":[ { "type":"Box", "props":{"width":120,"left":0,"height":120,"centerY":0}, "nodeParent":77, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":78, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_str@3x.png","scaleY":1.1,"scaleX":1.1,"centerY":0,"centerX":0}, "nodeParent":78, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":79, "child":[ ] }] }, { "type":"Label", "props":{"x":170,"text":"UI_Property_Strength","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":77, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":80, "child":[ ] }, { "type":"Box", "props":{"var":"boxStrengthGrade","top":20,"runtime":"Laya.runtime.ColorFilterItem","right":240,"name":"boxStrengthGrade","left":255,"bottom":20}, "nodeParent":77, "label":"Box(boxStrengthGrade)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":213, "child":[ { "type":"ProgressBar", "props":{"var":"prgStrength","value":0.235,"top":0,"skin":"images/progress/progress_2.png","right":0,"name":"prgStrength","left":0,"bottom":0}, "nodeParent":213, "label":"ProgressBar(prgStrength)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":214, "child":[ ] }, { "type":"Label", "props":{"var":"labStrength","text":"100","strokeColor":"#323232","stroke":8,"name":"labStrength","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":213, "label":"Label(labStrength)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":246, "child":[ ] }] }, { "type":"Label", "props":{"width":220,"var":"labStrengthJudge","text":"Judge","right":0,"name":"labStrengthJudge","fontSize":50,"font":"方正像素12","color":"#5cc8dc","centerY":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":77, "label":"Label(labStrengthJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":224, "child":[ ] }] }, { "type":"Box", "props":{"y":3,"right":0,"name":"boxMoney","left":0,"height":90}, "nodeParent":16, "label":"Box(boxMoney)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":107, "child":[ { "type":"Box", "props":{"width":120,"left":0,"height":120,"centerY":0}, "nodeParent":107, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":108, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_mny@3x.png","scaleY":1.1,"scaleX":1.1,"centerY":0,"centerX":0}, "nodeParent":108, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":109, "child":[ ] }] }, { "type":"Label", "props":{"x":170,"text":"UI_Property_Money","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":107, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":110, "child":[ ] }, { "type":"Box", "props":{"var":"boxMoneyGrade","top":20,"runtime":"Laya.runtime.ColorFilterItem","right":240,"name":"boxMoneyGrade","left":255,"bottom":20}, "nodeParent":107, "label":"Box(boxMoneyGrade)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":215, "child":[ { "type":"ProgressBar", "props":{"var":"prgMoney","value":0.8,"top":0,"skin":"images/progress/progress_2.png","right":0,"name":"prgMoney","left":0,"bottom":0}, "nodeParent":215, "label":"ProgressBar(prgMoney)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":216, "child":[ ] }, { "type":"Label", "props":{"var":"labMoney","text":"100","strokeColor":"#323232","stroke":8,"name":"labMoney","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":215, "label":"Label(labMoney)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":250, "child":[ ] }] }, { "type":"Label", "props":{"width":220,"var":"labMoneyJudge","text":"Judge","right":0,"name":"labMoneyJudge","fontSize":50,"font":"方正像素12","color":"#5cc8dc","centerY":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":107, "label":"Label(labMoneyJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":222, "child":[ ] }] }, { "type":"Box", "props":{"y":4,"right":0,"name":"boxSpirit","left":0,"height":90}, "nodeParent":16, "label":"Box(boxSpirit)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":195, "child":[ { "type":"Box", "props":{"width":120,"left":0,"height":120,"centerY":0}, "nodeParent":195, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":196, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_spr@3x.png","scaleY":1.1,"scaleX":1.1,"centerY":0,"centerX":0}, "nodeParent":196, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":197, "child":[ ] }] }, { "type":"Label", "props":{"x":170,"text":"UI_Property_Spirit","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":195, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":198, "child":[ ] }, { "type":"Box", "props":{"var":"boxSpiritGrade","top":20,"runtime":"Laya.runtime.ColorFilterItem","right":240,"name":"boxSpiritGrade","left":255,"bottom":20}, "nodeParent":195, "label":"Box(boxSpiritGrade)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":217, "child":[ { "type":"ProgressBar", "props":{"var":"prgSpirit","value":0.37,"top":0,"skin":"images/progress/progress_2.png","right":0,"name":"prgSpirit","left":0,"bottom":0}, "nodeParent":217, "label":"ProgressBar(prgSpirit)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":218, "child":[ ] }, { "type":"Label", "props":{"var":"labSpirit","text":"100","strokeColor":"#323232","stroke":8,"name":"labSpirit","fontSize":50,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":217, "label":"Label(labSpirit)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":252, "child":[ ] }] }, { "type":"Label", "props":{"width":220,"var":"labSpiritJudge","text":"Judge","right":0,"name":"labSpiritJudge","fontSize":50,"font":"方正像素12","color":"#5cc8dc","centerY":0,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":195, "label":"Label(labSpiritJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":223, "child":[ ] }] }] }], "$LOCKED":true, "$HIDDEN":false }, { "x":15, "type":"Box", "props":{"right":40,"name":"selectedTalents","left":40,"height":700,"bottom":410}, "nodeParent":1, "label":"Box(selectedTalents)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":9, "child":[ { "x":30, "type":"Label", "props":{"top":20,"text":"UI_Talent_Extend","left":20,"fontSize":50,"font":"方正像素12","color":"#ffffff"}, "nodeParent":9, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":137, "child":[ ], "$HIDDEN":false }, { "x":30, "type":"List", "props":{"var":"listSelectedTalents","vScrollBarSkin":" ","top":110,"spaceY":30,"right":10,"repeatY":3,"name":"listSelectedTalents","left":10,"bottom":10}, "nodeParent":9, "label":"List(listSelectedTalents)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":138, "child":[ { "x":45, "type":"Box", "props":{"y":20,"right":10,"renderType":"render","left":10,"height":160}, "nodeParent":138, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":139, "child":[ { "x":60, "type":"Image", "props":{"top":0,"skin":"images/border/up@3x.png","right":0,"name":"unselected","left":0,"bottom":0}, "nodeParent":139, "label":"Image(unselected)", "isOpen":true, "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":140, "child":[ ], "$HIDDEN":true }, { "x":60, "type":"Box", "props":{"top":0,"right":0,"name":"selected","left":0,"bottom":0}, "nodeParent":139, "label":"Box(selected)", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":259, "child":[ { "x":75, "type":"Box", "props":{"y":-22,"x":0,"renderType":"mask"}, "nodeParent":259, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":260, "child":[ { "x":90, "type":"Rect", "props":{"width":1800,"lineWidth":1,"height":204,"fillColor":"#ff0000"}, "nodeParent":260, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":261, "child":[ ] }], "$HIDDEN":true }, { "x":75, "type":"Image", "props":{"top":-19,"skin":"images/border/achievement_complete@3x.png","right":-19,"left":-80,"bottom":-19}, "nodeParent":259, "label":"Image", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":257, "child":[ ], "$HIDDEN":false }, { "x":75, "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":160,"fillColor":"#55fffe"}, "nodeParent":259, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":262, "child":[ ] }] }, { "x":60, "type":"Box", "props":{"width":15,"name":"grade1","height":160}, "nodeParent":139, "label":"Box(grade1)", "isOpen":false, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":141, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":160,"fillColor":"#55fffe"}, "nodeParent":141, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":142, "child":[ ] }] }, { "x":60, "type":"Box", "props":{"width":15,"name":"grade2","height":160}, "nodeParent":139, "label":"Box(grade2)", "isOpen":false, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":143, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":160,"fillColor":"#b17cff"}, "nodeParent":143, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":144, "child":[ ] }] }, { "x":60, "type":"Box", "props":{"width":15,"name":"grade3","height":160}, "nodeParent":139, "label":"Box(grade3)", "isOpen":false, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":145, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":160,"fillColor":"#ffce45"}, "nodeParent":145, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":146, "child":[ ] }] }, { "x":60, "type":"Label", "props":{"text":"Title","name":"labTitle","left":52,"fontSize":55,"font":"方正像素12","color":"#ffffff","centerY":0}, "nodeParent":139, "label":"Label(labTitle)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":147, "child":[ ] }, { "x":60, "type":"Label", "props":{"y":10,"text":"descriptipn","right":33,"name":"labDescription","fontSize":44,"font":"方正像素12","color":"#76979d","centerY":0}, "nodeParent":139, "label":"Label(labDescription)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":148, "child":[ ] }] }] }], "$LOCKED":true }, { "x":15, "type":"Box", "props":{"x":10,"width":1000,"name":"buttonGroup","height":200,"centerX":0,"bottom":70}, "nodeParent":1, "label":"Box(buttonGroup)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":10, "child":[ { "x":30, "type":"Button", "props":{"y":100,"x":250,"width":500,"var":"btnAgain","skin":"images/button/button_main@3x.png","name":"btnAgain","label":"UI_Remake_Again","centerY":0,"centerX":0}, "nodeParent":10, "label":"Button(btnAgain)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":150, "child":[ { "x":45, "type":"Box", "props":{}, "nodeParent":150, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":151, "child":[ { "type":"Animation", "props":{"y":96,"x":250,"width":0,"source":"view/CyberTheme/animation/circleFlash.ani","scaleX":4,"height":0,"blendMode":"lighter","autoPlay":true}, "nodeParent":151, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":152, "child":[ ] }, { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":151, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":153, "child":[ { "type":"Rect", "props":{"y":37,"x":25,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":154, "child":[ ] }, { "type":"Rect", "props":{"y":37,"x":470,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":155, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":44,"width":414,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":156, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":171,"width":160,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":157, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":44,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":158, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":337,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":159, "child":[ ] }, { "type":"Rect", "props":{"y":148,"x":29,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":160, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":331,"width":19,"rotation":55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":161, "child":[ ] }, { "type":"Rect", "props":{"y":166,"x":160,"width":19,"rotation":-55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":162, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":458,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":163, "child":[ ] }, { "type":"Rect", "props":{"y":26,"x":48,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":164, "child":[ ] }, { "type":"Rect", "props":{"y":153,"x":477,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":153, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":165, "child":[ ] }] }] }, { "x":45, "type":"Box", "props":{}, "nodeParent":150, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":166, "child":[ { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":166, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":167, "child":[ { "type":"Poly", "props":{"y":41,"x":35,"points":"0,0,8,-6,8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":167, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":168, "child":[ ] }, { "type":"Poly", "props":{"y":41,"x":464,"points":"0,0,-8,-6,-8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":167, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":169, "child":[ ] }, { "type":"Poly", "props":{"y":160,"x":177,"points":"0,0,147,0,153,10,-6,10","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":167, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":170, "child":[ ] }] }, { "type":"Animation", "props":{"y":172,"x":520,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleX":6,"blendMode":"lighter","autoPlay":true}, "nodeParent":166, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":171, "child":[ ] }] }] }], "$LOCKED":true }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }], "$HIDDEN":true } ================================================ FILE: laya/pages/view/CyberTheme/CyberTalent.ui ================================================ { "x":0, "type":"View", "selectedBox":21, "selecteID":22, "props":{"width":1125,"sceneColor":"#000000","sceneBg":"laya/views/view/CyberTheme/CyberTalent.png","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"var":"pageDrawCard","top":0,"right":0,"name":"pageDrawCard","left":0,"bottom":0}, "nodeParent":1, "label":"Box(pageDrawCard)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":19, "child":[ { "type":"Box", "props":{"y":1117,"x":562,"width":2,"height":2,"centerY":-100,"centerX":0}, "nodeParent":19, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":4, "child":[ { "type":"Animation", "props":{"y":1,"x":1,"width":100,"source":"view/CyberTheme/animation/lightRotation.ani","height":100,"autoPlay":true}, "nodeParent":4, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":3, "child":[ ] }, { "type":"Image", "props":{"y":585,"skin":"images/border/card@3x.png","scaleY":0.9,"scaleX":0.9,"rotation":15,"centerY":-50,"centerX":0,"anchorY":1.2,"anchorX":0.5,"alpha":0.8}, "nodeParent":4, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":10, "child":[ ], "$HIDDEN":false }, { "type":"Image", "props":{"y":634,"skin":"images/border/card@3x.png","scaleY":0.9,"scaleX":0.9,"rotation":-15,"centerY":-50,"centerX":0,"anchorY":1.2,"anchorX":0.5,"alpha":0.8}, "nodeParent":4, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":9, "child":[ ], "$HIDDEN":false }, { "type":"Image", "props":{"y":634,"skin":"images/border/card@3x.png","centerY":-50,"centerX":0,"anchorY":1.2,"anchorX":0.5,"alpha":0.8}, "nodeParent":4, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":8, "child":[ ], "$HIDDEN":false }, { "type":"Image", "props":{"skin":"images/accessories/cardicon@3x.png","centerY":-30,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":4, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":11, "child":[ ] }] }, { "type":"Button", "props":{"y":1930,"x":563,"width":657,"var":"btnDrawCard","skin":"images/button/button_main@3x.png","name":"btnDrawCard","labelSize":60,"label":"UI_Talent_Draw","height":192,"centerX":0}, "nodeParent":19, "label":"Button(btnDrawCard)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":5, "child":[ { "type":"Box", "props":{}, "nodeParent":5, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":56, "child":[ { "type":"Animation", "props":{"y":93,"x":330,"width":0,"source":"view/CyberTheme/animation/circleFlash.ani","scaleX":5,"height":0,"blendMode":"lighter","autoPlay":true}, "nodeParent":56, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":58, "child":[ ] }, { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":56, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":59, "child":[ { "type":"Rect", "props":{"y":37,"x":25,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":60, "child":[ ] }, { "type":"Rect", "props":{"y":37,"x":625,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":61, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":44,"width":569,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":62, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":171,"width":316,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":63, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":44,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":64, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":493,"width":120,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":65, "child":[ ] }, { "type":"Rect", "props":{"y":148,"x":29,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":66, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":487,"width":19,"rotation":55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":67, "child":[ ] }, { "type":"Rect", "props":{"y":166,"x":160,"width":19,"rotation":-55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":68, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":613,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":69, "child":[ ] }, { "type":"Rect", "props":{"y":26,"x":48,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":70, "child":[ ] }, { "type":"Rect", "props":{"y":153,"x":632,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":59, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":71, "child":[ ] }] }] }, { "type":"Box", "props":{}, "nodeParent":5, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":57, "child":[ { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":57, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":72, "child":[ { "type":"Poly", "props":{"y":41,"x":35,"points":"0,0,8,-6,8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":72, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":73, "child":[ ] }, { "type":"Poly", "props":{"y":41,"x":621,"points":"0,0,-8,-6,-8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":72, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":74, "child":[ ] }, { "type":"Poly", "props":{"y":160,"x":177,"points":"0,0,305,0,311,10,-6,10","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":72, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":75, "child":[ ] }] }, { "type":"Animation", "props":{"y":172,"x":330,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleX":4,"blendMode":"lighter","autoPlay":true}, "nodeParent":57, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":76, "child":[ ] }] }], "$HIDDEN":false }], "$LOCKED":true, "$HIDDEN":true }, { "x":15, "type":"Box", "props":{"y":0,"x":0,"var":"pageResult","top":0,"right":0,"name":"pageResult","left":0,"bottom":0}, "nodeParent":1, "label":"Box(pageResult)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":21, "child":[ { "x":30, "type":"List", "props":{"width":1085,"var":"listTalents","vScrollBarSkin":" ","top":310,"name":"listTalents","centerX":0,"bottom":370}, "nodeParent":21, "label":"List(listTalents)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":22, "child":[ { "type":"Box", "props":{"width":537,"renderType":"render","height":352}, "nodeParent":22, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":23, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/border/talent_item@3x.png","right":0,"name":"unselected","left":0,"bottom":0}, "nodeParent":23, "label":"Image(unselected)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":24, "child":[ ], "$HIDDEN":false }, { "type":"Image", "props":{"top":0,"skin":"images/border/talent_item_selected@3x.png","right":0,"name":"selected","left":0,"bottom":3}, "nodeParent":23, "label":"Image(selected)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":25, "child":[ ], "$HIDDEN":false }, { "type":"HBox", "props":{"top":104,"space":15,"name":"hboxTitle","left":66,"height":58}, "nodeParent":23, "label":"HBox(hboxTitle)", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":26, "child":[ { "type":"Box", "props":{"y":0,"x":0,"width":15,"name":"grades","height":58}, "nodeParent":26, "label":"Box(grades)", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":108, "child":[ { "type":"Box", "props":{"width":15,"name":"grade1","height":58}, "nodeParent":108, "label":"Box(grade1)", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":27, "child":[ { "type":"Sprite", "props":{}, "nodeParent":27, "label":"Sprite", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":28, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":58,"fillColor":"#55fffe"}, "nodeParent":28, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":29, "child":[ ] }], "$HIDDEN":false }] }, { "type":"Box", "props":{"width":15,"name":"grade2","height":58}, "nodeParent":108, "label":"Box(grade2)", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":105, "child":[ { "type":"Sprite", "props":{}, "nodeParent":105, "label":"Sprite", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":106, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":58,"fillColor":"#b17cff"}, "nodeParent":106, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":107, "child":[ ] }], "$HIDDEN":false }] }, { "type":"Box", "props":{"width":15,"name":"grade3","height":58}, "nodeParent":108, "label":"Box(grade3)", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":102, "child":[ { "type":"Sprite", "props":{}, "nodeParent":102, "label":"Sprite", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":103, "child":[ { "type":"Rect", "props":{"width":15,"lineWidth":1,"height":58,"fillColor":"#ffce45"}, "nodeParent":103, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":104, "child":[ ] }], "$HIDDEN":false }] }] }, { "type":"Label", "props":{"x":1,"text":"Title","name":"labTitle","fontSize":58,"font":"方正像素12","color":"#ffffff"}, "nodeParent":26, "label":"Label(labTitle)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":30, "child":[ ] }] }, { "type":"Label", "props":{"y":205,"wordWrap":true,"text":"description","right":66,"name":"labDescription","left":66,"leading":8,"fontSize":44,"font":"方正像素12","color":"#9dacaf"}, "nodeParent":23, "label":"Label(labDescription)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":32, "child":[ ] }] }], "$LOCKED":true, "$HIDDEN":false }, { "x":30, "type":"Box", "props":{"right":0,"left":0,"height":1,"bottom":0}, "nodeParent":21, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":109, "child":[ { "x":45, "type":"Button", "props":{"width":1040,"var":"btnNext","skin":"images/button/button_main@3x.png","name":"btnNext","labelSize":60,"label":"UI_Next","height":192,"centerY":-180,"centerX":0}, "nodeParent":109, "label":"Button(btnNext)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":33, "child":[ { "type":"Box", "props":{}, "nodeParent":33, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":78, "child":[ { "type":"Animation", "props":{"y":96,"x":520,"width":0,"source":"view/CyberTheme/animation/circleFlash.ani","scaleX":7,"height":0,"blendMode":"lighter","autoPlay":true}, "nodeParent":78, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":80, "child":[ ] }, { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":78, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":81, "child":[ { "type":"Rect", "props":{"y":37,"x":25,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":82, "child":[ ] }, { "type":"Rect", "props":{"y":37,"x":1010,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":83, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":44,"width":954,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":84, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":171,"width":700,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":85, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":44,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":86, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":877,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":87, "child":[ ] }, { "type":"Rect", "props":{"y":148,"x":29,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":88, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":871,"width":19,"rotation":55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":89, "child":[ ] }, { "type":"Rect", "props":{"y":166,"x":160,"width":19,"rotation":-55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":90, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":998,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":91, "child":[ ] }, { "type":"Rect", "props":{"y":26,"x":48,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":92, "child":[ ] }, { "type":"Rect", "props":{"y":153,"x":1017,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":81, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":93, "child":[ ] }] }] }, { "type":"Box", "props":{}, "nodeParent":33, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":79, "child":[ { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":79, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":94, "child":[ { "type":"Poly", "props":{"y":41,"x":35,"points":"0,0,8,-6,8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":94, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":95, "child":[ ] }, { "type":"Poly", "props":{"y":41,"x":1004,"points":"0,0,-8,-6,-8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":94, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":96, "child":[ ] }, { "type":"Poly", "props":{"y":160,"x":177,"points":"0,0,687,0,693,10,-6,10","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":94, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":97, "child":[ ], "$HIDDEN":false }] }, { "type":"Animation", "props":{"y":172,"x":520,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleX":6,"blendMode":"lighter","autoPlay":true}, "nodeParent":79, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":98, "child":[ ] }] }] }] }], "$LOCKED":true, "$HIDDEN":true }, { "x":15, "type":"Box", "props":{"top":40,"right":0,"name":"title","left":0}, "nodeParent":1, "label":"Box(title)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":20, "child":[ { "x":30, "type":"Image", "props":{"skin":"images/accessories/titlebar@3x.png","right":0,"left":0}, "nodeParent":20, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":12, "child":[ ], "$HIDDEN":false }, { "x":30, "type":"HBox", "props":{"y":160,"x":563,"space":30,"height":70,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":20, "label":"HBox", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":13, "child":[ { "type":"Image", "props":{"y":10,"x":1,"skin":"images/accessories/title_left@3x.png","name":"left"}, "nodeParent":13, "label":"Image(left)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":14, "child":[ ] }, { "type":"Label", "props":{"y":0,"x":2,"text":"UI_Title_Talent","fontSize":60,"font":"方正像素12","color":"#ffffff"}, "nodeParent":13, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":17, "child":[ ] }, { "type":"Image", "props":{"y":10,"x":3,"skin":"images/accessories/title_right@3x.png","name":"right"}, "nodeParent":13, "label":"Image(right)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":15, "child":[ ] }] }], "$LOCKED":true, "$HIDDEN":false }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }], "$HIDDEN":false } ================================================ FILE: laya/pages/view/CyberTheme/CyberTrajectory.ui ================================================ { "x":0, "type":"View", "selectedBox":88, "selecteID":153, "props":{"width":1125,"sceneColor":"#000000","sceneBg":"laya/views/view/CyberTheme/CyberTrajectory.png","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Sprite", "props":{"y":0,"x":0}, "nodeParent":1, "label":"Sprite", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":29, "child":[ { "type":"Rect", "props":{"width":1125,"lineWidth":1,"height":2436,"fillColor":"#04131f"}, "nodeParent":29, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":30, "child":[ ], "$HIDDEN":false }], "$HIDDEN":false }, { "x":15, "type":"Box", "props":{"top":126,"right":20,"left":20,"height":275}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":31, "child":[ { "type":"Image", "props":{"top":-13,"skin":"images/border/border_2@3x.png","right":-13,"left":-13,"bottom":-13}, "nodeParent":31, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":35, "child":[ ], "$HIDDEN":false }, { "type":"Box", "props":{"width":192,"left":36,"height":192,"centerY":0}, "nodeParent":31, "label":"Box", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":32, "child":[ ] }, { "type":"VBox", "props":{"space":13,"right":45,"left":242,"centerY":0,"align":"left"}, "nodeParent":31, "label":"VBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":72, "child":[ { "type":"HBox", "props":{"y":1,"space":13,"align":"middle"}, "nodeParent":72, "label":"HBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":71, "child":[ { "type":"Box", "props":{"x":1,"width":260,"name":"boxCharm","height":82}, "nodeParent":71, "label":"Box(boxCharm)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":34, "child":[ { "type":"Image", "props":{"y":-10,"x":-5,"top":0,"skin":"images/border/property@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":34, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":36, "child":[ ], "$HIDDEN":false }, { "type":"Box", "props":{"width":82,"left":5,"height":82}, "nodeParent":34, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":37, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_chr@3x.png","centerY":0,"centerX":0}, "nodeParent":37, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":38, "child":[ ] }] }, { "type":"Label", "props":{"text":"UI_Property_Charm","fontSize":40,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"anchorY":5,"anchorX":0.5}, "nodeParent":34, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":39, "child":[ ] }, { "type":"Box", "props":{"y":0,"width":82,"right":5,"height":82}, "nodeParent":34, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":41, "child":[ { "type":"Label", "props":{"var":"labCharm","text":"10","name":"labCharm","fontSize":55,"font":"方正像素12","color":"#55fffe","centerY":0,"centerX":0,"anchorY":5,"anchorX":0.5}, "nodeParent":41, "label":"Label(labCharm)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":40, "child":[ ] }] }], "$HIDDEN":false }, { "type":"Box", "props":{"y":0,"x":2,"width":260,"name":"boxMoney","height":82}, "nodeParent":71, "label":"Box(boxMoney)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":43, "child":[ { "type":"Image", "props":{"y":-10,"x":-5,"top":0,"skin":"images/border/property@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":43, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":44, "child":[ ], "$HIDDEN":false }, { "type":"Box", "props":{"width":82,"left":5,"height":82}, "nodeParent":43, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":45, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_mny@3x.png","centerY":0,"centerX":0}, "nodeParent":45, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":46, "child":[ ] }] }, { "type":"Label", "props":{"text":"UI_Property_Money","fontSize":40,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"anchorY":5,"anchorX":0.5}, "nodeParent":43, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":47, "child":[ ] }, { "type":"Box", "props":{"y":0,"width":82,"right":5,"height":82}, "nodeParent":43, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":48, "child":[ { "type":"Label", "props":{"var":"labMoney","text":"10","name":"labMoney","fontSize":55,"font":"方正像素12","color":"#55fffe","centerY":0,"centerX":0,"anchorY":5,"anchorX":0.5}, "nodeParent":48, "label":"Label(labMoney)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":49, "child":[ ] }] }] }, { "type":"Box", "props":{"x":3,"width":260,"name":"boxIntelligence","height":82}, "nodeParent":71, "label":"Box(boxIntelligence)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":50, "child":[ { "type":"Image", "props":{"y":-10,"x":-5,"top":0,"skin":"images/border/property@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":50, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":51, "child":[ ], "$HIDDEN":false }, { "type":"Box", "props":{"width":82,"left":5,"height":82}, "nodeParent":50, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":52, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_int@3x.png","centerY":0,"centerX":0}, "nodeParent":52, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":53, "child":[ ] }] }, { "type":"Label", "props":{"text":"UI_Property_Intelligence","fontSize":40,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"anchorY":5,"anchorX":0.5}, "nodeParent":50, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":54, "child":[ ] }, { "type":"Box", "props":{"y":0,"width":82,"right":5,"height":82}, "nodeParent":50, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":55, "child":[ { "type":"Label", "props":{"var":"labIntelligence","text":"10","name":"labIntelligence","fontSize":55,"font":"方正像素12","color":"#55fffe","centerY":0,"centerX":0,"anchorY":5,"anchorX":0.5}, "nodeParent":55, "label":"Label(labIntelligence)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":56, "child":[ ] }] }], "$HIDDEN":false }] }, { "type":"HBox", "props":{"y":2,"space":13,"align":"middle"}, "nodeParent":72, "label":"HBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":73, "child":[ { "type":"Box", "props":{"y":0,"x":0,"width":260,"name":"boxStrength","height":82}, "nodeParent":73, "label":"Box(boxStrength)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":74, "child":[ { "type":"Image", "props":{"y":-10,"x":-5,"top":0,"skin":"images/border/property@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":74, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":75, "child":[ ], "$HIDDEN":false }, { "type":"Box", "props":{"width":82,"left":5,"height":82}, "nodeParent":74, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":76, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_str@3x.png","centerY":0,"centerX":0}, "nodeParent":76, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":77, "child":[ ] }] }, { "type":"Label", "props":{"text":"UI_Property_Strength","fontSize":40,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"anchorY":5,"anchorX":0.5}, "nodeParent":74, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":78, "child":[ ] }, { "type":"Box", "props":{"y":0,"width":82,"right":5,"height":82}, "nodeParent":74, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":79, "child":[ { "type":"Label", "props":{"var":"labStrength","text":"10","name":"labStrength","fontSize":55,"font":"方正像素12","color":"#55fffe","centerY":0,"centerX":0,"anchorY":5,"anchorX":0.5}, "nodeParent":79, "label":"Label(labStrength)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":80, "child":[ ] }] }] }, { "type":"Box", "props":{"width":260,"name":"boxSpirit","height":82}, "nodeParent":73, "label":"Box(boxSpirit)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":81, "child":[ { "type":"Image", "props":{"y":-10,"x":-5,"top":0,"skin":"images/border/property@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":81, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":82, "child":[ ], "$HIDDEN":false }, { "type":"Box", "props":{"width":82,"left":5,"height":82}, "nodeParent":81, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":83, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_spr@3x.png","centerY":0,"centerX":0}, "nodeParent":83, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":84, "child":[ ] }] }, { "type":"Label", "props":{"text":"UI_Property_Spirit","fontSize":40,"font":"方正像素12","color":"#ffffff","centerY":0,"centerX":0,"anchorY":5,"anchorX":0.5}, "nodeParent":81, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":85, "child":[ ] }, { "type":"Box", "props":{"y":0,"width":82,"right":5,"height":82}, "nodeParent":81, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":86, "child":[ { "type":"Label", "props":{"var":"labSpirit","text":"10","name":"labSpirit","fontSize":55,"font":"方正像素12","color":"#55fffe","centerY":0,"centerX":0,"anchorY":5,"anchorX":0.5}, "nodeParent":86, "label":"Label(labSpirit)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":87, "child":[ ] }] }] }], "$HIDDEN":false }], "$HIDDEN":false }], "$LOCKED":true, "$HIDDEN":false }, { "x":15, "type":"Box", "props":{"right":0,"left":0,"height":1,"bottom":-1}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":14, "child":[ { "type":"Button", "props":{"y":-155,"width":500,"var":"btnSummary","skin":"images/button/button_main@3x.png","name":"btnSummary","label":"UI_Goto_Summary","centerX":0}, "nodeParent":14, "label":"Button(btnSummary)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":13, "child":[ { "type":"Box", "props":{}, "nodeParent":13, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":130, "child":[ { "type":"Animation", "props":{"y":96,"x":250,"width":0,"source":"view/CyberTheme/animation/circleFlash.ani","scaleX":4,"height":0,"blendMode":"lighter","autoPlay":true}, "nodeParent":130, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":132, "child":[ ] }, { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":130, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":133, "child":[ { "type":"Rect", "props":{"y":37,"x":25,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":134, "child":[ ] }, { "type":"Rect", "props":{"y":37,"x":470,"width":7,"lineWidth":1,"height":116,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":135, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":44,"width":414,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":136, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":171,"width":160,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":137, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":44,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":138, "child":[ ] }, { "type":"Rect", "props":{"y":163,"x":337,"width":121,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":139, "child":[ ] }, { "type":"Rect", "props":{"y":148,"x":29,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":140, "child":[ ] }, { "type":"Rect", "props":{"y":150,"x":331,"width":19,"rotation":55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":141, "child":[ ] }, { "type":"Rect", "props":{"y":166,"x":160,"width":19,"rotation":-55,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":142, "child":[ ] }, { "type":"Rect", "props":{"y":21,"x":458,"width":25,"rotation":40,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":143, "child":[ ] }, { "type":"Rect", "props":{"y":26,"x":48,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":144, "child":[ ] }, { "type":"Rect", "props":{"y":153,"x":477,"width":25,"rotation":140,"lineWidth":1,"height":6,"fillColor":"#ff0000"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":145, "child":[ ] }] }] }, { "type":"Box", "props":{}, "nodeParent":13, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":131, "child":[ { "type":"Box", "props":{"renderType":"mask"}, "nodeParent":131, "label":"Box", "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":146, "child":[ { "type":"Poly", "props":{"y":41,"x":35,"points":"0,0,8,-6,8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":146, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":147, "child":[ ] }, { "type":"Poly", "props":{"y":41,"x":464,"points":"0,0,-8,-6,-8,113,0,107","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":146, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":148, "child":[ ] }, { "type":"Poly", "props":{"y":160,"x":177,"points":"0,0,147,0,153,10,-6,10","lineWidth":1,"lineColor":"#ff0000","fillColor":"#00ffff"}, "nodeParent":146, "label":"Poly", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":149, "child":[ ] }] }, { "type":"Animation", "props":{"y":172,"x":520,"source":"view/CyberTheme/animation/bottomBreath.ani","scaleX":6,"blendMode":"lighter","autoPlay":true}, "nodeParent":131, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":150, "child":[ ] }] }], "$HIDDEN":false }, { "type":"Box", "props":{"y":-155,"var":"boxSpeed","right":100,"name":"boxSpeed","left":100,"height":150,"anchorY":0.5,"anchorX":0.5}, "nodeParent":14, "label":"Box(boxSpeed)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":104, "child":[ { "type":"ProgressBar", "props":{"var":"prgSpeed","skin":"images/progress/progress_s.png","right":0,"name":"prgSpeed","left":0,"bottom":0}, "nodeParent":104, "label":"ProgressBar(prgSpeed)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":105, "child":[ ] }, { "type":"HScrollBar", "props":{"var":"scbSpeed","skin":"images/slider/hslider_s.png","right":0,"name":"scbSpeed","min":0,"max":1000,"left":0,"height":60,"bottom":0}, "nodeParent":104, "label":"HScrollBar(scbSpeed)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":106, "child":[ ] }, { "type":"Label", "props":{"text":"UI_Manual","fontSize":50,"font":"方正像素12","color":"#55fffe","bottom":70}, "nodeParent":104, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":107, "child":[ ] }, { "type":"Label", "props":{"text":"UI_Auto","right":0,"fontSize":50,"font":"方正像素12","color":"#55fffe","bottom":70}, "nodeParent":104, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":108, "child":[ ] }] }], "$LOCKED":true, "$HIDDEN":false }, { "x":15, "type":"Box", "props":{"top":440,"right":20,"left":20,"bottom":250}, "nodeParent":1, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":102, "child":[ { "x":30, "type":"Image", "props":{"top":0,"skin":"images/border/border_1@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":102, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":6, "child":[ ] }, { "x":30, "type":"Panel", "props":{"var":"panelTrajectory","vScrollBarSkin":"images/slider/vslider_1@3x.png","top":80,"right":20,"name":"panelTrajectory","left":0,"bottom":80}, "nodeParent":102, "label":"Panel(panelTrajectory)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":18, "child":[ { "x":45, "type":"VBox", "props":{"var":"vboxTrajectory","top":0,"right":40,"name":"vboxTrajectory","left":20}, "nodeParent":18, "label":"VBox(vboxTrajectory)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":17, "child":[ { "x":60, "type":"Box", "props":{"right":0,"name":"boxTrajectoryItem","left":0}, "nodeParent":17, "label":"Box(boxTrajectoryItem)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":88, "child":[ { "x":75, "type":"Box", "props":{"y":0,"width":10,"top":0,"runtime":"Laya.runtime.ColorfulBox","name":"boxGrade","left":0,"height":50}, "nodeParent":88, "label":"Box(boxGrade)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":153, "child":[ ] }, { "x":75, "type":"HBox", "props":{"y":0,"x":220,"name":"hboxAge","anchorX":1,"align":"middle"}, "nodeParent":88, "label":"HBox(hboxAge)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":91, "child":[ { "type":"Label", "props":{"x":0,"text":"3000","name":"labAge","fontSize":50,"font":"方正像素12","color":"#cfea5c","anchorX":0}, "nodeParent":91, "label":"Label(labAge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":90, "child":[ ] }, { "type":"Label", "props":{"x":1,"text":"岁","fontSize":50,"font":"方正像素12","color":"#cfea5c","anchorX":0}, "nodeParent":91, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":94, "child":[ ] }, { "type":"Label", "props":{"x":2,"text":":","fontSize":50,"font":"方正像素12","color":"#cfea5c","anchorX":0}, "nodeParent":91, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":92, "child":[ ] }] }, { "x":75, "type":"Label", "props":{"wordWrap":true,"text":"你的父母开始辅导你数学和英语,智力+1","right":0,"name":"labContent","left":240,"leading":44,"fontSize":50,"font":"方正像素12","color":"#ffffff"}, "nodeParent":88, "label":"Label(labContent)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":95, "child":[ ] }] }] }], "$HIDDEN":false }, { "x":30, "type":"Box", "props":{"y":20,"x":20,"var":"btnUp","top":20,"right":20,"name":"btnUp","left":20,"height":50}, "nodeParent":102, "label":"Box(btnUp)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":19, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/border/up@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":19, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":20, "child":[ ] }, { "type":"Box", "props":{"width":60,"height":60,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":19, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":22, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_up@3x.png","centerY":0,"centerX":0}, "nodeParent":22, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":24, "child":[ ] }] }] }, { "x":30, "type":"Box", "props":{"y":1676,"x":20,"var":"btnDown","right":20,"name":"btnDown","left":20,"height":50,"bottom":20}, "nodeParent":102, "label":"Box(btnDown)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":25, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/border/up@3x.png","right":0,"left":0,"bottom":0}, "nodeParent":25, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":26, "child":[ ] }, { "type":"Box", "props":{"width":60,"rotation":180,"height":60,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":25, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":27, "child":[ { "type":"Image", "props":{"skin":"images/icons/icon_up@3x.png","centerY":0,"centerX":0}, "nodeParent":27, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":28, "child":[ ] }] }] }] }, { "x":15, "type":"Box", "props":{"width":10,"var":"boxParticle","name":"boxParticle","height":10,"centerY":0,"centerX":0}, "nodeParent":1, "label":"Box(boxParticle)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":152, "child":[ { "type":"Particle2D", "source":"particle/fly.part", "props":{"y":5,"x":5,"url":"particle/fly.part","autoPlay":true}, "nodeParent":152, "label":"Particle2D", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":151, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/CyberTheme/Mode.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":8, "props":{"width":1125,"sceneColor":"#000000","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"y":10,"x":10,"width":600,"var":"btnCustom","runtime":"Laya.runtime.ScaleButton","name":"btn","height":400,"centerY":-400,"centerX":0}, "nodeParent":1, "label":"Box(btnCustom)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":2, "child":[ { "x":30, "type":"Image", "props":{"top":-15,"skin":"images/border/achievement_complete@3x.png","right":-15,"left":-15,"bottom":-15}, "nodeParent":2, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":10, "child":[ ] }, { "x":30, "type":"Label", "props":{"top":50,"text":"UI_CustomMode","fontSize":80,"font":"方正像素12","color":"#ffffff","centerX":0,"bold":true}, "nodeParent":2, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":4, "child":[ ] }, { "x":30, "type":"Label", "props":{"top":200,"text":"UI_CustomModeDescription","right":0,"left":0,"leading":20,"fontSize":40,"font":"方正像素12","color":"#bcbcbc","bottom":0,"align":"center"}, "nodeParent":2, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":5, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"y":10,"x":20,"width":600,"var":"btnCelebrity","runtime":"Laya.runtime.ScaleButton","name":"btn","height":400,"centerY":400,"centerX":0}, "nodeParent":1, "label":"Box(btnCelebrity)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":3, "child":[ { "x":30, "type":"Image", "props":{"y":-15,"x":-15,"top":-15,"skin":"images/border/achievement_complete@3x.png","right":-15,"left":-15,"bottom":-15}, "nodeParent":3, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":11, "child":[ ] }, { "x":30, "type":"Label", "props":{"top":50,"text":"UI_CelebrityMode","fontSize":80,"font":"方正像素12","color":"#ffffff","centerX":0,"bold":true}, "nodeParent":3, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":7, "child":[ ] }, { "x":30, "type":"Label", "props":{"top":200,"text":"UI_CelebrityModeDescription","right":0,"left":0,"leading":20,"fontSize":40,"font":"方正像素12","color":"#bcbcbc","bottom":0,"align":"center"}, "nodeParent":3, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":8, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/CyberTheme/animation/bottomBreath.ani ================================================ { "x":0, "type":"View", "selectedBox":1, "props":{"sceneWidth":200,"sceneHeight":200,"sceneColor":"#000000"}, "nodeParent":-1, "label":"View", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":1, "child":[ { "type":"GraphicNode", "props":{}, "nodeParent":1, "label":"GraphicNode", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":2, "child":[ ] }], "animations":[ { "nodes":[ { "target":2, "keyframes":{ "y":[ { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"y", "index":0 }], "x":[ { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"x", "index":0 }], "skin":[ { "value":"images/resource/bottombreath.png", "tweenMethod":"linearNone", "tween":false, "target":2, "key":"skin", "index":0 }], "anchorY":[ { "value":1, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"anchorY", "index":0 }], "anchorX":[ { "value":0.5, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"anchorX", "index":0 }], "alpha":[ { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"alpha", "index":0 }, { "value":0.5, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"alpha", "index":36 }, { "value":1, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"alpha", "index":48 }, { "value":0.8, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"alpha", "index":96 }, { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"alpha", "index":120 }] } }], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/CyberTheme/animation/circleFlash.ani ================================================ { "x":0, "type":"View", "selectedBox":1, "props":{"sceneWidth":200,"sceneHeight":200,"sceneColor":"#000000"}, "nodeParent":-1, "label":"View", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":1, "child":[ { "type":"GraphicNode", "props":{}, "nodeParent":1, "label":"GraphicNode", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":2, "child":[ ] }], "animations":[ { "nodes":[ { "target":2, "keyframes":{ "y":[ { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"y", "index":0 }], "x":[ { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"x", "index":0 }], "skin":[ { "value":"images/resource/circleflash.png", "tweenMethod":"linearNone", "tween":false, "target":2, "key":"skin", "index":0 }], "skewX":[ { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"skewX", "index":0 }], "scaleX":[ { "value":-1, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"scaleX", "index":0 }], "rotation":[ { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":0 }, { "value":-90, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":10 }, { "value":-135, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":15 }, { "value":-270, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":20 }, { "value":-360, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":25 }, { "value":-650, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":35 }, { "value":-680, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":37 }, { "value":-710, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":39 }, { "value":-720, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":41 }], "anchorY":[ { "value":0.5, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"anchorY", "index":0 }], "anchorX":[ { "value":0.5, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"anchorX", "index":0 }] } }], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/CyberTheme/animation/jumpBackground.ani ================================================ { "type":"View", "selectedBox":1, "props":{"sceneWidth":200,"sceneHeight":200,"sceneColor":"#000000"}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "type":"GraphicNode", "props":{}, "nodeParent":1, "label":"GraphicNode", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":3, "child":[ ] }], "animations":[ { "nodes":[ { "target":3, "keyframes":{ "y":[ { "value":-13, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":0 }, { "value":-13, "tweenMethod":"strongOut", "tween":true, "target":3, "key":"y", "index":2 }, { "value":-5, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":3 }, { "value":-3, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":5 }, { "value":-15, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":6 }, { "value":-15, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":9 }, { "value":3, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":10 }, { "value":-14, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":11 }, { "value":-14, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":15 }, { "value":-22, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":16 }, { "value":-22, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":19 }, { "value":-13, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"y", "index":20 }], "x":[ { "value":-18, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":0 }, { "value":-18, "tweenMethod":"strongOut", "tween":true, "target":3, "key":"x", "index":2 }, { "value":-3, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":3 }, { "value":-5, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":5 }, { "value":-16, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":6 }, { "value":-12, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":9 }, { "value":0, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":10 }, { "value":-8, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":11 }, { "value":-8, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":15 }, { "value":-11, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":16 }, { "value":-11, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":19 }, { "value":-18, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"x", "index":20 }], "skin":[ { "value":"images/background/background_1@3x.png", "tweenMethod":"linearNone", "tween":false, "target":3, "key":"skin", "index":0 }], "scaleY":[ { "value":1.01, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"scaleY", "index":0 }], "scaleX":[ { "value":1.01, "tweenMethod":"linearNone", "tween":true, "target":3, "key":"scaleX", "index":0 }] } }], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/CyberTheme/animation/lightRotation.ani ================================================ { "x":0, "type":"View", "selectedBox":1, "props":{"sceneWidth":600,"sceneHeight":400,"sceneColor":"#000000"}, "nodeParent":-1, "label":"View", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":1, "child":[ { "type":"GraphicNode", "props":{}, "nodeParent":1, "label":"GraphicNode", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":2, "child":[ ] }], "animations":[ { "nodes":[ { "target":2, "keyframes":{ "y":[ { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"y", "index":0 }], "x":[ { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"x", "index":0 }], "width":[ { "value":1715, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"width", "index":0 }], "skin":[ { "value":"images/background/background_2@3x.png", "tweenMethod":"linearNone", "tween":false, "target":2, "key":"skin", "index":0 }], "rotation":[ { "value":0, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":0 }, { "value":360, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"rotation", "index":279 }], "pivotY":[ { "value":862, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"pivotY", "index":0 }], "pivotX":[ { "value":868, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"pivotX", "index":0 }], "height":[ { "value":1716, "tweenMethod":"linearNone", "tween":true, "target":2, "key":"height", "index":0 }] } }], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/DefaultTheme/Achievement.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":9, "props":{"width":1125,"sceneColor":"#000000","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Label", "props":{"y":80,"text":"UI_Statistics","name":"title","fontSize":80,"font":"SimHei","color":"#ffffff","centerX":0}, "nodeParent":1, "label":"Label(title)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":86, "child":[ ] }, { "x":15, "type":"Box", "props":{"width":260,"var":"btnBack","top":50,"runtime":"Laya.runtime.ColorfulBox","right":50,"name":"btnBack","height":90,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnBack)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":69, "child":[ { "type":"Label", "props":{"y":1028,"x":332,"text":"UI_Back","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":69, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":70, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"x":33,"width":1060,"top":230,"height":540,"centerX":0}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":25, "child":[ { "type":"Box", "props":{"width":500,"var":"boxRemakeTimes","top":0,"runtime":"Laya.runtime.ColorfulBox","name":"boxRemakeTimes","left":0,"height":240}, "nodeParent":25, "label":"Box(boxRemakeTimes)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":28, "child":[ { "type":"Label", "props":{"var":"labRemakeTimes","text":"label","right":0,"name":"font_default","left":0,"fontSize":60,"font":"SimHei","color":"#ffffff","centerY":-60,"bold":true,"align":"center"}, "nodeParent":28, "label":"Label(labRemakeTimes)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":32, "child":[ ] }, { "type":"Label", "props":{"var":"labRemakeTimesJudge","text":"label","right":0,"name":"font_default","left":0,"fontSize":45,"font":"SimHei","color":"#ffffff","centerY":60,"bold":false,"align":"center"}, "nodeParent":28, "label":"Label(labRemakeTimesJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":33, "child":[ ] }] }, { "type":"Box", "props":{"width":500,"var":"boxAchievementCount","top":0,"runtime":"Laya.runtime.ColorfulBox","right":0,"name":"boxAchievementCount","height":240}, "nodeParent":25, "label":"Box(boxAchievementCount)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":29, "child":[ { "type":"Label", "props":{"var":"labAchievementCount","text":"label","right":0,"name":"font_default","left":0,"fontSize":60,"font":"SimHei","color":"#ffffff","centerY":-60,"bold":true,"align":"center"}, "nodeParent":29, "label":"Label(labAchievementCount)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":38, "child":[ ] }, { "type":"Label", "props":{"var":"labAchievementCountJudge","text":"label","right":0,"name":"font_default","left":0,"fontSize":45,"font":"SimHei","color":"#ffffff","centerY":60,"bold":false,"align":"center"}, "nodeParent":29, "label":"Label(labAchievementCountJudge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":39, "child":[ ] }] }, { "type":"Box", "props":{"width":500,"var":"boxEventRate","runtime":"Laya.runtime.ColorfulBox","name":"boxEventRate","left":0,"height":240,"bottom":0}, "nodeParent":25, "label":"Box(boxEventRate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":71, "child":[ { "type":"Box", "props":{"y":0,"x":0,"width":500,"var":"prgEventRate","height":240,"blendMode":"lighter","alpha":0.1}, "nodeParent":71, "label":"Box(prgEventRate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":82, "child":[ { "type":"Rect", "props":{"width":500,"lineWidth":1,"height":240,"fillColor":"#ffffff"}, "nodeParent":82, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":83, "child":[ ] }] }, { "type":"Label", "props":{"text":"UI_Event_Collection_Rate","right":0,"name":"font_default","left":0,"fontSize":60,"font":"SimHei","color":"#ffffff","centerY":-60,"bold":true,"align":"center"}, "nodeParent":71, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":72, "child":[ ] }, { "type":"Label", "props":{"var":"labEventRate","text":"label","right":0,"name":"font_default","left":0,"fontSize":45,"font":"SimHei","color":"#ffffff","centerY":60,"bold":false,"align":"center"}, "nodeParent":71, "label":"Label(labEventRate)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":73, "child":[ ] }] }, { "type":"Box", "props":{"width":500,"var":"boxTalentRate","runtime":"Laya.runtime.ColorfulBox","right":0,"name":"boxTalentRate","height":240,"bottom":0}, "nodeParent":25, "label":"Box(boxTalentRate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":74, "child":[ { "type":"Box", "props":{"y":0,"x":0,"width":500,"var":"prgTalentRate","height":240,"blendMode":"lighter","alpha":0.1}, "nodeParent":74, "label":"Box(prgTalentRate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":84, "child":[ { "type":"Rect", "props":{"width":500,"lineWidth":1,"height":240,"fillColor":"#ffffff"}, "nodeParent":84, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":85, "child":[ ] }] }, { "type":"Label", "props":{"text":"UI_Talent_Collection_Rate","right":0,"name":"font_default","left":0,"fontSize":60,"font":"SimHei","color":"#ffffff","centerY":-60,"bold":true,"align":"center"}, "nodeParent":74, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":75, "child":[ ] }, { "type":"Label", "props":{"var":"labTalentRate","text":"label","right":0,"name":"font_default","left":0,"fontSize":45,"font":"SimHei","color":"#ffffff","centerY":60,"bold":false,"align":"center"}, "nodeParent":74, "label":"Label(labTalentRate)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":76, "child":[ ] }] }] }, { "x":15, "type":"Box", "props":{"width":1060,"top":800,"runtime":"Laya.runtime.ColorfulBox","name":"hr","height":10,"centerX":0}, "nodeParent":1, "label":"Box(hr)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":91, "child":[ ] }, { "x":15, "type":"Label", "props":{"top":870,"text":"UI_Achievement","name":"title","fontSize":80,"font":"SimHei","color":"#ffffff","centerX":0}, "nodeParent":1, "label":"Label(title)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":92, "child":[ ] }, { "x":15, "type":"Box", "props":{"x":945,"width":260,"var":"btnRank","top":870,"runtime":"Laya.runtime.ColorfulBox","right":50,"name":"btnRank","height":90,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnRank)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":3, "child":[ { "x":30, "type":"Label", "props":{"text":"UI_Rank","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":3, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":7, "child":[ ] }] }, { "x":15, "type":"List", "props":{"width":1080,"var":"listAchievements","vScrollBarSkin":" ","top":1000,"spaceY":60,"spaceX":60,"repeatX":2,"name":"listAchievements","centerX":0,"bottom":35}, "nodeParent":1, "label":"List(listAchievements)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":9, "child":[ { "x":30, "type":"Box", "props":{"y":10,"x":10,"width":500,"runtime":"Laya.runtime.ColorfulBox","renderType":"render","height":320}, "nodeParent":9, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":77, "child":[ { "x":45, "type":"Label", "props":{"text":"label","right":0,"name":"name","left":0,"fontSize":60,"font":"SimHei","color":"#ffffff","centerY":-80,"bold":true,"align":"center"}, "nodeParent":77, "label":"Label(name)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":78, "child":[ ] }, { "x":45, "type":"Label", "props":{"text":"label","right":0,"name":"description","left":0,"fontSize":45,"font":"SimHei","color":"#ffffff","centerY":80,"bold":false,"anchorY":0,"anchorX":0,"align":"center"}, "nodeParent":77, "label":"Label(description)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":79, "child":[ ] }, { "x":45, "type":"Box", "props":{"width":500,"name":"boxMask","height":320,"alpha":0.5}, "nodeParent":77, "label":"Box(boxMask)", "isOpen":false, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":80, "child":[ { "type":"Rect", "props":{"width":500,"lineWidth":1,"height":320,"fillColor":"#000000"}, "nodeParent":80, "label":"Rect", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":81, "child":[ ] }] }] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }], "$HIDDEN":false } ================================================ FILE: laya/pages/view/DefaultTheme/AchievementPopup.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":13, "props":{"y":50,"width":570,"sceneColor":"#000000","mouseThrough":true,"mouseEnabled":false,"height":150,"alpha":0.75}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"var":"boxBg","top":0,"right":0,"name":"boxBg","left":0,"bottom":0}, "nodeParent":1, "label":"Box(boxBg)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":5, "child":[ { "x":30, "type":"Rect", "props":{"y":0,"x":560,"width":10,"lineWidth":1,"height":150,"fillColor":"#84ff55"}, "nodeParent":5, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":14, "child":[ ] }, { "x":30, "type":"Box", "props":{"var":"bg1","top":0,"runtime":"Laya.runtime.ColorfulBox","right":10,"left":0,"bottom":0}, "nodeParent":5, "label":"Box(bg1)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":15, "child":[ ] }] }, { "x":15, "type":"Label", "props":{"y":10,"text":"UI_Achievement_Achieve","left":40,"fontSize":40,"font":"SimHei","color":"#84ff55","bold":true}, "nodeParent":1, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":12, "child":[ ] }, { "x":15, "type":"Label", "props":{"var":"labName","text":"Achievement","name":"labName","left":40,"fontSize":60,"font":"SimHei","color":"#cccccc","centerY":30}, "nodeParent":1, "label":"Label(labName)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":13, "child":[ ] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/DefaultTheme/Celebrity.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":28, "props":{"width":1125,"sceneColor":"#000000","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Label", "props":{"y":80,"text":"UI_Title_Celebrity","name":"title","fontSize":80,"font":"SimHei","color":"#ffffff","centerX":0}, "nodeParent":1, "label":"Label(title)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":19, "child":[ ] }, { "x":15, "type":"Panel", "props":{"var":"panelCharacter","vScrollBarSkin":" ","top":200,"right":0,"name":"panelCharacter","left":0,"bottom":700}, "nodeParent":1, "label":"Panel(panelCharacter)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":2, "child":[ { "x":30, "type":"VBox", "props":{"y":10,"width":1000,"var":"vboxCharacter","space":20,"name":"vboxCharacter","centerX":0}, "nodeParent":2, "label":"VBox(vboxCharacter)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":8, "child":[ { "x":45, "type":"Box", "props":{"right":0,"name":"boxCharacter","left":0}, "nodeParent":8, "label":"Box(boxCharacter)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":10, "child":[ { "type":"Box", "props":{"y":0,"runtime":"Laya.runtime.ColorfulBox","right":0,"name":"boxName","left":0,"height":100}, "nodeParent":10, "label":"Box(boxName)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":12, "child":[ { "type":"Label", "props":{"valign":"middle","text":"颜值10 智力10 体质10 家境Π","name":"label","fontSize":55,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"align":"center"}, "nodeParent":12, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":18, "child":[ ] }] }, { "type":"VBox", "props":{"top":100,"space":20,"runtime":"Laya.runtime.ColorfulBox","right":25,"name":"vboxStates","left":25}, "nodeParent":10, "label":"VBox(vboxStates)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":11, "child":[ { "type":"Label", "props":{"valign":"middle","text":"颜值10 智力10 体质10 家境Π","name":"label","height":100,"fontSize":55,"font":"SimHei","color":"#ffffff","centerX":0,"align":"center"}, "nodeParent":11, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":14, "child":[ ] }] }] }, { "x":45, "type":"Box", "props":{"runtime":"Laya.runtime.ColorfulBox","right":25,"name":"boxTalent","left":25,"height":100}, "nodeParent":8, "label":"Box(boxTalent)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":15, "child":[ { "type":"Label", "props":{"valign":"middle","text":"颜值10 智力10 体质10 家境Π","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"align":"center"}, "nodeParent":15, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":17, "child":[ ] }] }, { "x":45, "type":"Box", "props":{"y":10,"x":10,"right":0,"name":"boxUniqueUnGenerate","left":0}, "nodeParent":8, "label":"Box(boxUniqueUnGenerate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":20, "child":[ { "x":60, "type":"Box", "props":{"y":0,"runtime":"Laya.runtime.ColorfulBox","right":0,"name":"boxName","left":0,"height":100}, "nodeParent":20, "label":"Box(boxName)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":21, "child":[ { "x":75, "type":"Label", "props":{"valign":"middle","text":"UI_UniqueWaTaShi","name":"label","fontSize":55,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"align":"center"}, "nodeParent":21, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":22, "child":[ ] }] }, { "x":60, "type":"VBox", "props":{"top":100,"space":20,"runtime":"Laya.runtime.ColorfulBox","right":25,"name":"vboxStates","left":25}, "nodeParent":20, "label":"VBox(vboxStates)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":23, "child":[ { "x":75, "type":"Label", "props":{"y":1,"valign":"middle","text":"UI_UniqueWaTaShiContent","right":0,"name":"label","left":0,"leading":30,"fontSize":55,"font":"SimHei","color":"#ffffff","align":"center"}, "nodeParent":23, "label":"Label(label)", "isOpen":true, "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":24, "child":[ ] }, { "x":75, "type":"Box", "props":{"y":2,"right":0,"name":"boxBtn","left":0,"height":150}, "nodeParent":23, "label":"Box(boxBtn)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":25, "child":[ { "x":90, "type":"Box", "props":{"runtime":"Laya.runtime.ColorfulBox","right":50,"name":"btn","left":50,"height":120,"centerY":0}, "nodeParent":25, "label":"Box(btn)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":26, "child":[ { "x":105, "type":"Label", "props":{"y":30,"x":290,"text":"UI_GenerateNow","name":"label","fontSize":60,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":26, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":27, "child":[ ] }] }] }] }] }] }] }, { "x":15, "type":"Box", "props":{"width":480,"var":"btnRetry","runtime":"Laya.runtime.ColorfulBox","name":"btnRetry","height":150,"centerX":0,"bottom":400}, "nodeParent":1, "label":"Box(btnRetry)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":4, "child":[ { "x":30, "type":"Label", "props":{"text":"UI_AllNot","name":"label","fontSize":60,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":4, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":5, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":480,"var":"btnNext","runtime":"Laya.runtime.ColorfulBox","name":"btnNext","height":150,"centerX":0,"bottom":150}, "nodeParent":1, "label":"Box(btnNext)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":6, "child":[ { "x":30, "type":"Label", "props":{"text":"UI_Make_New_Life","name":"label","fontSize":60,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":6, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":7, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/DefaultTheme/Main.ui ================================================ { "x":0, "type":"View", "selectedBox":101, "selecteID":102, "props":{"y":1218,"x":562,"width":1125,"sceneColor":"#000000","runtime":"Laya.runtime.ViewBase","height":2436,"anchorY":0.5,"anchorX":0.5}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Label", "props":{"text":"UI_Title_Remake","name":"title","fontSize":130,"font":"SimHei","color":"#ffffff","centerY":-260,"centerX":0,"bold":true,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Label(title)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":8, "child":[ ] }, { "x":15, "type":"Label", "props":{"wordWrap":true,"var":"labSubTitle","text":"UI_Title_Subsequent","right":0,"name":"title","left":0,"fontSize":70,"font":"SimHei","color":"#999999","centerY":-120,"anchorY":0.5,"anchorX":0.5,"align":"center"}, "nodeParent":1, "label":"Label(labSubTitle)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":11, "child":[ ] }, { "x":15, "type":"Box", "props":{"width":600,"var":"btnRemake","runtime":"Laya.runtime.ColorfulBox","name":"btnRemake","height":150,"centerY":600,"centerX":0}, "nodeParent":1, "label":"Box(btnRemake)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":85, "child":[ { "x":30, "type":"Label", "props":{"text":"UI_Remake","name":"label","fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":85, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":86, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":260,"var":"btnThanks","top":50,"runtime":"Laya.runtime.ColorfulBox","right":50,"name":"btnSmall","height":90,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnThanks)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":15, "child":[ { "type":"Label", "props":{"text":"UI_Thanks","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":15, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":20, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":260,"var":"btnAchievement","top":180,"runtime":"Laya.runtime.ColorfulBox","right":50,"name":"btnSmall","height":90,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnAchievement)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":21, "child":[ { "x":30, "type":"Label", "props":{"text":"UI_Achievement","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":21, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":25, "child":[ ] }], "$HIDDEN":false }, { "x":15, "type":"Box", "props":{"y":0,"x":0,"width":160,"var":"btnGithub","runtime":"Laya.runtime.ScaleButton","rotation":-45,"name":"btnGithub","height":160,"anchorY":0,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnGithub)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":82, "child":[ { "type":"Rect", "props":{"y":0,"x":-70,"width":300,"lineWidth":1,"height":140,"fillColor":"#000000"}, "nodeParent":82, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":88, "child":[ ] }, { "type":"Image", "props":{"top":0,"skin":"images/icons/icon_github.png","rotation":0,"right":0,"left":0,"bottom":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":82, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":78, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":-70,"width":300,"renderType":"hit","lineWidth":1,"height":140,"fillColor":"#000000"}, "nodeParent":82, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":89, "child":[ ] }, { "type":"Box", "props":{"y":0,"x":-70,"renderType":"mask"}, "nodeParent":82, "label":"Box", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":91, "child":[ { "type":"Rect", "props":{"width":300,"lineWidth":1,"height":140,"fillColor":"#000000"}, "nodeParent":91, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":90, "child":[ ] }] }] }, { "x":15, "type":"Box", "props":{"width":160,"left":50,"height":160,"bottom":50}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":92, "child":[ { "type":"Box", "props":{"width":160,"var":"btnDiscord","runtime":"Laya.runtime.ScaleButton","name":"btnDiscord","height":160,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":92, "label":"Box(btnDiscord)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":83, "child":[ { "type":"Image", "props":{"top":0,"skin":"images/icons/icon_discord.png","right":0,"left":0,"bottom":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":83, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":79, "child":[ ] }] }] }, { "x":15, "type":"Box", "props":{"y":2201,"x":1020,"width":110,"var":"btnSaveLoad","runtime":"Laya.runtime.ColorfulBox","right":50,"name":"btnSmall","height":110,"bottom":180,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnSaveLoad)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":99, "child":[ { "x":30, "type":"Image", "props":{"width":80,"skin":"images/icons/icon_save.png","height":80,"centerY":0,"centerX":0}, "nodeParent":99, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":100, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":110,"var":"btnThemes","runtime":"Laya.runtime.ColorfulBox","right":50,"name":"btnThemes","height":110,"bottom":50,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnThemes)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":96, "child":[ { "type":"Image", "props":{"width":90,"skin":"images/icons/icon_themes.png","height":90,"centerY":0,"centerX":0}, "nodeParent":96, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":98, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"x":562,"var":"banner","centerX":0,"bottom":100,"anchorY":1,"anchorX":0.5}, "nodeParent":1, "label":"Box(banner)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":101, "child":[ { "x":30, "type":"Label", "props":{"text":"UI_Banner","name":"title","fontSize":40,"font":"SimHei","color":"#ffffff"}, "nodeParent":101, "label":"Label(title)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":102, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/DefaultTheme/Mode.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":11, "props":{"width":1125,"sceneColor":"#000000","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"width":600,"var":"btnCustom","runtime":"Laya.runtime.ColorfulBox","name":"btn","height":400,"centerY":-400,"centerX":0}, "nodeParent":1, "label":"Box(btnCustom)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":2, "child":[ { "x":30, "type":"Label", "props":{"top":50,"text":"UI_CustomMode","name":"font_default","fontSize":80,"font":"SimHei","color":"#ffffff","centerX":0,"bold":true}, "nodeParent":2, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":4, "child":[ ] }, { "x":30, "type":"Label", "props":{"top":200,"text":"UI_CustomModeDescription","right":0,"name":"font_default","left":0,"leading":20,"fontSize":40,"font":"SimHei","color":"#ffffff","bottom":0,"align":"center"}, "nodeParent":2, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":5, "child":[ ] }, { "x":30, "type":"Label", "props":{"runtime":"Laya.runtime.ColorAgentLabel","name":"label"}, "nodeParent":2, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":10, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"x":10,"width":600,"var":"btnCelebrity","runtime":"Laya.runtime.ColorfulBox","name":"btn","height":400,"centerY":400,"centerX":0}, "nodeParent":1, "label":"Box(btnCelebrity)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":3, "child":[ { "x":30, "type":"Label", "props":{"top":50,"text":"UI_CelebrityMode","name":"font_default","fontSize":80,"font":"SimHei","color":"#ffffff","centerX":0,"bold":true}, "nodeParent":3, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":8, "child":[ ] }, { "x":30, "type":"Label", "props":{"top":200,"text":"UI_CelebrityModeDescription","right":0,"name":"font_default","left":0,"leading":20,"fontSize":40,"font":"SimHei","color":"#ffffff","bottom":0,"align":"center"}, "nodeParent":3, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":9, "child":[ ] }, { "x":30, "type":"Label", "props":{"y":10,"x":10,"runtime":"Laya.runtime.ColorAgentLabel","name":"label"}, "nodeParent":3, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":11, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/DefaultTheme/Property.ui ================================================ { "x":0, "type":"View", "selectedBox":181, "selecteID":184, "referenceLines":null, "props":{"width":1125,"sceneColor":"#000000","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Label", "props":{"y":80,"var":"title","text":"UI_Title_Property","name":"title","fontSize":80,"font":"SimHei","color":"#ffffff","centerX":0}, "nodeParent":1, "label":"Label(title)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":6, "child":[ ] }, { "x":15, "type":"Box", "props":{"top":230,"right":40,"name":"propertyAllocate","left":40,"height":1100}, "nodeParent":1, "label":"Box(propertyAllocate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":8, "child":[ { "x":30, "type":"HBox", "props":{"top":0,"height":100,"centerX":0}, "nodeParent":8, "label":"HBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":50, "child":[ { "x":45, "type":"Label", "props":{"x":0,"text":"UI_Left_Property_Point","name":"font_default","fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0}, "nodeParent":50, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":52, "child":[ ] }, { "x":45, "type":"Label", "props":{"x":1,"text":"UI_Colon","name":"font_default","fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0}, "nodeParent":50, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":54, "child":[ ] }, { "x":45, "type":"Label", "props":{"x":2,"var":"labLeftPropertyPoint","text":"0","name":"font_default","fontSize":70,"color":"#ffffff","centerY":0}, "nodeParent":50, "label":"Label(labLeftPropertyPoint)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":53, "child":[ ] }] }, { "x":30, "type":"VBox", "props":{"top":200,"space":100,"right":50,"left":50}, "nodeParent":8, "label":"VBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":120, "child":[ { "x":45, "type":"Box", "props":{"y":0,"var":"boxCharm","right":0,"left":0,"height":130}, "nodeParent":120, "label":"Box(boxCharm)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":10, "child":[ { "x":60, "type":"Label", "props":{"x":183,"text":"UI_Property_Charm","name":"font_default","fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":10, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":19, "child":[ ] }, { "x":60, "type":"Box", "props":{"width":590,"var":"boxCharmAllocate","runtime":"Laya.runtime.ColorFilterItem","right":30,"name":"property","height":110,"centerY":0}, "nodeParent":10, "label":"Box(boxCharmAllocate)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":20, "child":[ { "type":"Box", "props":{"width":110,"var":"btnCharmReduce","name":"btnCharmReduce","left":0,"height":110,"centerY":0}, "nodeParent":20, "label":"Box(btnCharmReduce)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":21, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":21, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":24, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":24, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":26, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":24, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":27, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":24, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":28, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":24, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":30, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":21, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":39, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":39, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":25, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":25, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":23, "child":[ ] }] }] }] }, { "type":"Box", "props":{"y":0,"x":110,"top":0,"right":110,"left":110,"bottom":0}, "nodeParent":20, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":42, "child":[ { "type":"TextInput", "props":{"var":"inputCharm","type":"number","top":0,"text":"0","right":0,"promptColor":"#828282","prompt":0,"name":"inputCharm","maxChars":1,"left":0,"fontSize":80,"font":"SimHei","color":"#ffffff","bottom":0,"align":"center"}, "nodeParent":42, "label":"TextInput(inputCharm)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":48, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":42, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":223, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":42, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":224, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"var":"btnCharmIncrease","right":0,"name":"btnCharmIncrease","height":110,"centerY":0}, "nodeParent":20, "label":"Box(btnCharmIncrease)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":22, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":22, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":31, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":31, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":32, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":31, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":33, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":31, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":34, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":31, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":35, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":22, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":38, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":38, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":36, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":36, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":37, "child":[ ] }] }, { "type":"Box", "props":{"width":48,"rotation":90,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":38, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":40, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":40, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":41, "child":[ ] }] }] }] }] }] }, { "x":45, "type":"Box", "props":{"y":1,"var":"boxIntelligence","right":0,"left":0,"height":130}, "nodeParent":120, "label":"Box(boxIntelligence)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":121, "child":[ { "x":60, "type":"Label", "props":{"x":183,"text":"UI_Property_Intelligence","name":"font_default","fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":121, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":124, "child":[ ] }, { "x":60, "type":"Box", "props":{"width":590,"var":"boxIntelligenceAllocate","runtime":"Laya.runtime.ColorFilterItem","right":30,"name":"property","height":110,"centerY":0}, "nodeParent":121, "label":"Box(boxIntelligenceAllocate)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":125, "child":[ { "type":"Box", "props":{"width":110,"var":"btnIntelligenceReduce","name":"btnIntelligenceReduce","left":0,"height":110,"centerY":0}, "nodeParent":125, "label":"Box(btnIntelligenceReduce)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":126, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":126, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":127, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":127, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":128, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":127, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":129, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":127, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":130, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":127, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":131, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":126, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":132, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":132, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":133, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":133, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":134, "child":[ ] }] }] }] }, { "type":"Box", "props":{"y":0,"x":110,"top":0,"right":110,"left":110,"bottom":0}, "nodeParent":125, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":135, "child":[ { "type":"TextInput", "props":{"var":"inputIntelligence","type":"number","top":0,"text":"0","right":0,"promptColor":"#828282","prompt":0,"name":"inputIntelligence","maxChars":1,"left":0,"fontSize":80,"font":"SimHei","color":"#ffffff","bottom":0,"align":"center"}, "nodeParent":135, "label":"TextInput(inputIntelligence)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":136, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":135, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":221, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":135, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":222, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"var":"btnIntelligenceIncrease","right":0,"name":"btnIntelligenceIncrease","height":110,"centerY":0}, "nodeParent":125, "label":"Box(btnIntelligenceIncrease)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":140, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":140, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":141, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":141, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":142, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":141, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":143, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":141, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":144, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":141, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":145, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":140, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":146, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":146, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":147, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":147, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":148, "child":[ ] }] }, { "type":"Box", "props":{"width":48,"rotation":90,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":146, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":149, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":149, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":150, "child":[ ] }] }] }] }] }] }, { "x":45, "type":"Box", "props":{"y":2,"var":"boxStrength","right":0,"left":0,"height":130}, "nodeParent":120, "label":"Box(boxStrength)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":151, "child":[ { "x":60, "type":"Label", "props":{"x":183,"text":"UI_Property_Strength","name":"font_default","fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":151, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":154, "child":[ ] }, { "x":60, "type":"Box", "props":{"width":590,"var":"boxStrengthAllocate","runtime":"Laya.runtime.ColorFilterItem","right":30,"name":"property","height":110,"centerY":0}, "nodeParent":151, "label":"Box(boxStrengthAllocate)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":155, "child":[ { "type":"Box", "props":{"width":110,"var":"btnStrengthReduce","name":"btnStrengthReduce","left":0,"height":110,"centerY":0}, "nodeParent":155, "label":"Box(btnStrengthReduce)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":156, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":156, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":157, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":157, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":158, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":157, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":159, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":157, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":160, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":157, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":161, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":156, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":162, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":162, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":163, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":163, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":164, "child":[ ] }] }] }] }, { "type":"Box", "props":{"y":0,"x":110,"top":0,"right":110,"left":110,"bottom":0}, "nodeParent":155, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":165, "child":[ { "type":"TextInput", "props":{"var":"inputStrength","type":"number","top":0,"text":"0","right":0,"promptColor":"#828282","prompt":0,"name":"inputStrength","maxChars":1,"left":0,"fontSize":80,"font":"SimHei","color":"#ffffff","bottom":0,"align":"center"}, "nodeParent":165, "label":"TextInput(inputStrength)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":166, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":165, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":219, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":165, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":220, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"var":"btnStrengthIncrease","right":0,"name":"btnStrengthIncrease","height":110,"centerY":0}, "nodeParent":155, "label":"Box(btnStrengthIncrease)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":170, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":170, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":171, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":171, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":172, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":171, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":173, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":171, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":174, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":171, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":175, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":170, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":176, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":176, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":177, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":177, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":178, "child":[ ] }] }, { "type":"Box", "props":{"width":48,"rotation":90,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":176, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":179, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":179, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":180, "child":[ ] }] }] }] }] }] }, { "x":45, "type":"Box", "props":{"y":3,"var":"boxMoney","right":0,"left":0,"height":130}, "nodeParent":120, "label":"Box(boxMoney)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":181, "child":[ { "x":60, "type":"Label", "props":{"x":183,"text":"UI_Property_Money","name":"font_default","fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":181, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":184, "child":[ ] }, { "x":60, "type":"Box", "props":{"width":590,"var":"boxMoneyAllocate","runtime":"Laya.runtime.ColorFilterItem","right":30,"name":"property","height":110,"centerY":0}, "nodeParent":181, "label":"Box(boxMoneyAllocate)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":185, "child":[ { "type":"Box", "props":{"width":110,"var":"btnMoneyReduce","name":"btnMoneyReduce","left":0,"height":110,"centerY":0}, "nodeParent":185, "label":"Box(btnMoneyReduce)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":186, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":186, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":187, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":187, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":188, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":187, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":189, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":187, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":190, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":187, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":191, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":186, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":192, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":192, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":193, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":193, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":194, "child":[ ] }] }] }] }, { "type":"Box", "props":{"y":0,"x":110,"top":0,"right":110,"left":110,"bottom":0}, "nodeParent":185, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":195, "child":[ { "type":"TextInput", "props":{"var":"inputMoney","type":"number","top":0,"text":"0","right":0,"promptColor":"#828282","prompt":0,"name":"inputMoney","maxChars":1,"left":0,"fontSize":80,"font":"SimHei","color":"#ffffff","bottom":0,"align":"center"}, "nodeParent":195, "label":"TextInput(inputMoney)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":196, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":195, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":217, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":370,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":195, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":218, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"var":"btnMoneyIncrease","right":0,"name":"btnMoneyIncrease","height":110,"centerY":0}, "nodeParent":185, "label":"Box(btnMoneyIncrease)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":200, "child":[ { "type":"Box", "props":{"width":110,"height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":200, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":201, "child":[ { "type":"Rect", "props":{"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":201, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":202, "child":[ ] }, { "type":"Rect", "props":{"y":106,"x":0,"width":110,"lineWidth":1,"height":4,"fillColor":"#ffffff"}, "nodeParent":201, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":203, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":0,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":201, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":204, "child":[ ] }, { "type":"Rect", "props":{"y":0,"x":106,"width":4,"lineWidth":1,"height":110,"fillColor":"#ffffff"}, "nodeParent":201, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":205, "child":[ ] }] }, { "type":"Box", "props":{"width":110,"runtime":"Laya.runtime.ScaleButton","height":110,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":200, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":206, "child":[ { "type":"Box", "props":{"width":48,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":206, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":207, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":207, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":208, "child":[ ] }] }, { "type":"Box", "props":{"width":48,"rotation":90,"height":12,"centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":206, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":209, "child":[ { "type":"Rect", "props":{"y":0,"x":0,"width":48,"lineWidth":1,"height":12,"fillColor":"#ffffff"}, "nodeParent":209, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":210, "child":[ ] }] }] }] }] }] }] }], "$LOCKED":true }, { "x":15, "type":"Box", "props":{"right":40,"name":"selectedTalents","left":40,"height":450,"bottom":300}, "nodeParent":1, "label":"Box(selectedTalents)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":56, "child":[ { "x":30, "type":"Label", "props":{"top":20,"text":"UI_Selected_Talent","name":"font_default","left":20,"fontSize":50,"font":"SimHei","color":"#ffffff"}, "nodeParent":56, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":57, "child":[ ] }, { "x":30, "type":"List", "props":{"var":"listSelectedTalents","vScrollBarSkin":" ","top":110,"spaceY":20,"right":10,"repeatY":3,"repeatX":1,"name":"listSelectedTalents","left":10,"bottom":10}, "nodeParent":56, "label":"List(listSelectedTalents)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":58, "child":[ { "x":45, "type":"Box", "props":{"y":15,"runtime":"Laya.runtime.ColorfulBox","right":15,"renderType":"render","left":15,"height":80}, "nodeParent":58, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":215, "child":[ { "x":60, "type":"Label", "props":{"y":20,"text":"Title","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":215, "label":"Label(label)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":216, "child":[ ] }] }] }], "$LOCKED":true }, { "x":15, "type":"HBox", "props":{"space":40,"name":"buttonGroup","height":150,"centerX":0,"bottom":90}, "nodeParent":1, "label":"HBox(buttonGroup)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":212, "child":[ { "x":30, "type":"Box", "props":{"y":0,"x":0,"width":480,"var":"btnRandomAllocate","top":0,"runtime":"Laya.runtime.ColorfulBox","name":"btnRandomAllocate","bottom":0}, "nodeParent":212, "label":"Box(btnRandomAllocate)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":72, "child":[ { "x":45, "type":"Label", "props":{"text":"UI_Random_Allocate","name":"label","fontSize":60,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":72, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":213, "child":[ ] }] }, { "x":30, "type":"Box", "props":{"x":1,"width":480,"var":"btnNext","top":0,"runtime":"Laya.runtime.ColorfulBox","name":"btnNext","bottom":0}, "nodeParent":212, "label":"Box(btnNext)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":73, "child":[ { "x":45, "type":"Label", "props":{"text":"UI_Make_New_Life","name":"label","fontSize":60,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":73, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":214, "child":[ ] }] }], "$LOCKED":true }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/DefaultTheme/Summary.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":8, "props":{"width":1125,"sceneColor":"#000000","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Label", "props":{"y":80,"var":"title","text":"UI_Title_Summary","name":"title","fontSize":80,"font":"SimHei","color":"#ffffff","centerX":0}, "nodeParent":1, "label":"Label(title)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":6, "child":[ ] }, { "x":15, "type":"Box", "props":{"top":230,"right":40,"name":"summary","left":40,"bottom":800}, "nodeParent":1, "label":"Box(summary)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":8, "child":[ { "x":30, "type":"List", "props":{"var":"listSummary","top":0,"spaceY":20,"right":0,"repeatY":7,"repeatX":1,"name":"listSummary","left":0,"bottom":0}, "nodeParent":8, "label":"List(listSummary)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":265, "child":[ { "x":45, "type":"Box", "props":{"y":15,"runtime":"Laya.runtime.ColorfulBox","right":15,"renderType":"render","left":15,"height":160}, "nodeParent":265, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":266, "child":[ { "x":60, "type":"Label", "props":{"y":20,"text":"Title","name":"label","left":100,"fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0}, "nodeParent":266, "label":"Label(label)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":267, "child":[ ] }] }] }], "$LOCKED":true, "$HIDDEN":false }, { "x":15, "type":"Box", "props":{"right":40,"name":"selectedTalents","left":40,"height":450,"bottom":300}, "nodeParent":1, "label":"Box(selectedTalents)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":9, "child":[ { "x":30, "type":"Label", "props":{"top":20,"text":"UI_Talent_Extend","name":"font_default","left":20,"fontSize":50,"color":"#ffffff"}, "nodeParent":9, "label":"Label(font_default)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":137, "child":[ ], "$HIDDEN":false }, { "x":30, "type":"List", "props":{"var":"listSelectedTalents","vScrollBarSkin":" ","top":110,"spaceY":20,"right":0,"repeatY":3,"repeatX":1,"name":"listSelectedTalents","left":0,"bottom":10}, "nodeParent":9, "label":"List(listSelectedTalents)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":138, "child":[ { "x":45, "type":"Box", "props":{"y":15,"runtime":"Laya.runtime.ColorfulBox","right":15,"renderType":"render","left":15,"height":80}, "nodeParent":138, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":263, "child":[ { "x":60, "type":"Label", "props":{"y":20,"text":"Title","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":263, "label":"Label(label)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":264, "child":[ ] }, { "x":60, "type":"Box", "props":{"top":0,"runtime":"Laya.runtime.BlankBox","right":0,"name":"blank","left":0,"bottom":0,"alpha":0.3}, "nodeParent":263, "label":"Box(blank)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":270, "child":[ ] }] }] }], "$LOCKED":true }, { "x":15, "type":"Box", "props":{"right":1,"name":"buttonGroup","left":1,"bottom":0}, "nodeParent":1, "label":"Box(buttonGroup)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":10, "child":[ { "x":30, "type":"Box", "props":{"width":600,"var":"btnAgain","runtime":"Laya.runtime.ColorfulBox","name":"btnAgain","height":150,"centerX":0,"bottom":100}, "nodeParent":10, "label":"Box(btnAgain)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":268, "child":[ { "x":45, "type":"Label", "props":{"text":"UI_Remake_Again","name":"label","fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":268, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":269, "child":[ ] }] }], "$LOCKED":true }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }], "$HIDDEN":false } ================================================ FILE: laya/pages/view/DefaultTheme/Talent.ui ================================================ { "x":0, "type":"View", "selectedBox":21, "selecteID":114, "props":{"width":1125,"sceneColor":"#000000","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Label", "props":{"y":80,"var":"title","text":"UI_Title_Talent","name":"title","fontSize":80,"font":"SimHei","color":"#ffffff","centerX":0}, "nodeParent":1, "label":"Label(title)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":17, "child":[ ] }, { "x":15, "type":"Box", "props":{"var":"pageDrawCard","top":0,"right":0,"name":"pageDrawCard","left":0,"bottom":0}, "nodeParent":1, "label":"Box(pageDrawCard)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":19, "child":[ { "type":"Box", "props":{"width":600,"var":"btnDrawCard","runtime":"Laya.runtime.ColorfulBox","name":"btnDrawCard","height":150,"centerY":0,"centerX":0}, "nodeParent":19, "label":"Box(btnDrawCard)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":110, "child":[ { "type":"Label", "props":{"text":"UI_Talent_Draw","name":"label","fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":110, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":111, "child":[ ] }] }], "$LOCKED":true, "$HIDDEN":false }, { "x":15, "type":"Box", "props":{"y":0,"x":0,"var":"pageResult","top":0,"right":0,"name":"pageResult","left":0,"bottom":0}, "nodeParent":1, "label":"Box(pageResult)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":21, "child":[ { "x":30, "type":"List", "props":{"width":1085,"var":"listTalents","vScrollBarSkin":" ","top":230,"spaceY":20,"repeatX":1,"name":"listTalents","centerX":0,"bottom":250}, "nodeParent":21, "label":"List(listTalents)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":22, "child":[ { "x":45, "type":"Box", "props":{"y":15,"runtime":"Laya.runtime.ColorfulBox","right":15,"renderType":"render","left":15,"height":80}, "nodeParent":22, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":false, "hasChild":true, "compId":23, "child":[ { "x":60, "type":"Label", "props":{"y":20,"text":"Title","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":23, "label":"Label(label)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":30, "child":[ ] }, { "x":60, "type":"Box", "props":{"top":0,"runtime":"Laya.runtime.BlankBox","right":0,"name":"blank","left":0,"bottom":0,"alpha":0.3}, "nodeParent":23, "label":"Box(blank)", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":116, "child":[ ] }] }], "$LOCKED":true, "$HIDDEN":false }, { "x":30, "type":"Box", "props":{"x":263,"width":1085,"var":"btnNext","runtime":"Laya.runtime.ColorfulBox","name":"btnNext","height":150,"centerX":0,"bottom":30}, "nodeParent":21, "label":"Box(btnNext)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":114, "child":[ { "x":45, "type":"Label", "props":{"text":"UI_Next","name":"label","fontSize":70,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":114, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":115, "child":[ ] }] }], "$LOCKED":true, "$HIDDEN":false }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }], "$HIDDEN":false } ================================================ FILE: laya/pages/view/DefaultTheme/Thanks.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":161, "props":{"width":1125,"sceneColor":"#666666","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"y":95,"x":945,"width":260,"var":"btnBack","top":50,"runtime":"Laya.runtime.ColorfulBox","right":50,"name":"btnBack","height":90,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnBack)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":153, "child":[ { "type":"Label", "props":{"y":1028,"x":332,"text":"UI_Back","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":153, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":154, "child":[ ] }] }, { "x":15, "type":"Panel", "props":{"width":1100,"var":"panelTopSupports","vScrollBarSkin":" ","top":170,"name":"panelTopSupports","height":400,"centerX":0}, "nodeParent":1, "label":"Panel(panelTopSupports)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":18, "child":[ { "type":"VBox", "props":{"y":15,"var":"vboxTopSupports","space":30,"right":-6,"name":"vboxTopSupports","left":-6}, "nodeParent":18, "label":"VBox(vboxTopSupports)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":17, "child":[ { "type":"Box", "props":{"runtime":"Laya.runtime.ColorfulBox","right":0,"name":"boxTopSupport","left":0}, "nodeParent":17, "label":"Box(boxTopSupport)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":88, "child":[ { "type":"Label", "props":{"y":25,"wordWrap":true,"width":250,"text":"Sombody","name":"name","left":50,"leading":25,"fontSize":50,"font":"SimHei","color":"#000000","align":"center"}, "nodeParent":88, "label":"Label(name)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":155, "child":[ ] }, { "type":"Label", "props":{"y":25,"wordWrap":true,"text":"This is he say","right":20,"name":"comment","left":350,"leading":25,"fontSize":50,"font":"SimHei","color":"#000000","align":"center"}, "nodeParent":88, "label":"Label(comment)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":95, "child":[ ] }] }] }], "$HIDDEN":false }, { "x":15, "type":"List", "props":{"width":1100,"var":"listSupports","vScrollBarSkin":" ","top":600,"spaceY":50,"spaceX":50,"name":"listSupports","centerX":0,"bottom":200}, "nodeParent":1, "label":"List(listSupports)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":161, "child":[ { "x":30, "type":"Label", "props":{"y":30,"x":25,"width":500,"text":"label","renderType":"render","fontSize":50,"font":"SimHei","color":"#ffffff","align":"center"}, "nodeParent":161, "label":"Label", "isDirectory":false, "isAniNode":false, "hasChild":false, "compId":162, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":400,"var":"btnDDF","runtime":"Laya.runtime.ColorfulBox","name":"btnDDF","height":100,"centerX":300,"bottom":50,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnDDF)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":163, "child":[ { "x":30, "type":"Label", "props":{"y":1028,"x":332,"text":"UI_Support_Programmer","name":"label","fontSize":45,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":163, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":164, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":400,"var":"btnAFD","runtime":"Laya.runtime.ColorfulBox","name":"btnAFD","height":100,"centerX":-300,"bottom":50,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnAFD)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":165, "child":[ { "x":30, "type":"Label", "props":{"y":1028,"x":332,"text":"UI_Support_Designer","name":"label","fontSize":45,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":165, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":166, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/DefaultTheme/Trajectory.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":95, "props":{"width":1125,"sceneColor":"#000000","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"top":80,"right":20,"left":20,"height":120}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":31, "child":[ { "type":"HBox", "props":{"space":15,"centerY":0,"centerX":0,"align":"middle"}, "nodeParent":31, "label":"HBox", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":71, "child":[ { "type":"Box", "props":{"x":0,"width":200,"runtime":"Laya.runtime.ColorfulBox","name":"propertyBox","height":120,"centerY":0}, "nodeParent":71, "label":"Box(propertyBox)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":34, "child":[ { "type":"Label", "props":{"y":30,"text":"UI_Property_Charm","name":"label","fontSize":45,"font":"SimHei","color":"#ffffff","centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":34, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":39, "child":[ ] }, { "type":"Box", "props":{"runtime":"Laya.runtime.ColorfulBox","right":0,"name":"propertyValue","left":0,"height":60,"bottom":0}, "nodeParent":34, "label":"Box(propertyValue)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":41, "child":[ { "type":"Label", "props":{"var":"labCharm","text":"10","name":"label","fontSize":55,"font":"SimHei","color":"#55fffe","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":41, "label":"Label(labCharm)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":40, "child":[ ] }] }], "$HIDDEN":false }, { "type":"Box", "props":{"x":1,"width":200,"runtime":"Laya.runtime.ColorfulBox","name":"propertyBox","height":120,"centerY":0}, "nodeParent":71, "label":"Box(propertyBox)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":50, "child":[ { "type":"Label", "props":{"y":30,"text":"UI_Property_Intelligence","name":"label","fontSize":45,"font":"SimHei","color":"#ffffff","centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":50, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":54, "child":[ ] }, { "type":"Box", "props":{"runtime":"Laya.runtime.ColorfulBox","right":0,"name":"propertyValue","left":0,"height":60,"bottom":0}, "nodeParent":50, "label":"Box(propertyValue)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":55, "child":[ { "type":"Label", "props":{"var":"labIntelligence","text":"10","name":"label","fontSize":55,"font":"SimHei","color":"#55fffe","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":55, "label":"Label(labIntelligence)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":56, "child":[ ] }] }], "$HIDDEN":false }, { "type":"Box", "props":{"x":2,"width":200,"runtime":"Laya.runtime.ColorfulBox","name":"propertyBox","height":120,"centerY":0}, "nodeParent":71, "label":"Box(propertyBox)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":74, "child":[ { "type":"Label", "props":{"y":30,"text":"UI_Property_Strength","name":"label","fontSize":45,"font":"SimHei","color":"#ffffff","centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":74, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":78, "child":[ ] }, { "type":"Box", "props":{"runtime":"Laya.runtime.ColorfulBox","right":0,"name":"propertyValue","left":0,"height":60,"bottom":0}, "nodeParent":74, "label":"Box(propertyValue)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":79, "child":[ { "type":"Label", "props":{"var":"labStrength","text":"10","name":"label","fontSize":55,"font":"SimHei","color":"#55fffe","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":79, "label":"Label(labStrength)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":80, "child":[ ] }] }] }, { "type":"Box", "props":{"x":3,"width":200,"runtime":"Laya.runtime.ColorfulBox","name":"propertyBox","height":120,"centerY":0}, "nodeParent":71, "label":"Box(propertyBox)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":43, "child":[ { "type":"Label", "props":{"y":30,"text":"UI_Property_Money","name":"label","fontSize":45,"font":"SimHei","color":"#ffffff","centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":43, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":47, "child":[ ] }, { "type":"Box", "props":{"runtime":"Laya.runtime.ColorfulBox","right":0,"name":"propertyValue","left":0,"height":60,"bottom":0}, "nodeParent":43, "label":"Box(propertyValue)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":48, "child":[ { "type":"Label", "props":{"var":"labMoney","text":"10","name":"label","fontSize":55,"font":"SimHei","color":"#55fffe","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":48, "label":"Label(labMoney)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":49, "child":[ ] }] }] }, { "type":"Box", "props":{"x":4,"width":200,"runtime":"Laya.runtime.ColorfulBox","name":"propertyBox","height":120,"centerY":0}, "nodeParent":71, "label":"Box(propertyBox)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":81, "child":[ { "type":"Label", "props":{"y":30,"text":"UI_Property_Spirit","name":"label","fontSize":45,"font":"SimHei","color":"#ffffff","centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":81, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":85, "child":[ ] }, { "type":"Box", "props":{"runtime":"Laya.runtime.ColorfulBox","right":0,"name":"propertyValue","left":0,"height":60,"bottom":0}, "nodeParent":81, "label":"Box(propertyValue)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":86, "child":[ { "type":"Label", "props":{"var":"labSpirit","text":"10","name":"label","fontSize":55,"font":"SimHei","color":"#55fffe","centerY":0,"centerX":0,"anchorY":0.5,"anchorX":0.5}, "nodeParent":86, "label":"Label(labSpirit)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":87, "child":[ ] }] }] }] }], "$LOCKED":true, "$HIDDEN":false }, { "x":15, "type":"Box", "props":{"x":20,"var":"boxTrajectory","top":240,"runtime":"Laya.runtime.ColorfulBox","right":20,"name":"boxTrajectory","left":20,"bottom":250}, "nodeParent":1, "label":"Box(boxTrajectory)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":102, "child":[ { "x":30, "type":"Panel", "props":{"var":"panelTrajectory","vScrollBarSkin":" ","top":0,"right":0,"name":"panelTrajectory","left":0,"bottom":0}, "nodeParent":102, "label":"Panel(panelTrajectory)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":18, "child":[ { "x":45, "type":"VBox", "props":{"y":15,"var":"vboxTrajectory","space":20,"right":-6,"name":"vboxTrajectory","left":-6}, "nodeParent":18, "label":"VBox(vboxTrajectory)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":17, "child":[ { "x":60, "type":"Box", "props":{"runtime":"Laya.runtime.ColorfulBox","right":0,"name":"boxTrajectoryItem","left":0}, "nodeParent":17, "label":"Box(boxTrajectoryItem)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":88, "child":[ { "x":75, "type":"HBox", "props":{"y":25,"x":200,"name":"hboxAge","anchorX":1,"align":"middle"}, "nodeParent":88, "label":"HBox(hboxAge)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":91, "child":[ { "type":"Label", "props":{"x":0,"text":"3000","name":"labAge","fontSize":50,"font":"SimHei","color":"#cfea5c","anchorX":0}, "nodeParent":91, "label":"Label(labAge)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":90, "child":[ ] }, { "type":"Label", "props":{"x":1,"text":"岁","fontSize":50,"font":"SimHei","color":"#cfea5c","anchorX":0}, "nodeParent":91, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":94, "child":[ ] }, { "type":"Label", "props":{"x":2,"text":":","fontSize":50,"font":"SimHei","color":"#cfea5c","anchorX":0}, "nodeParent":91, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":92, "child":[ ] }] }, { "x":75, "type":"Label", "props":{"y":25,"wordWrap":true,"text":"你的父母开始辅导你数学和英语,智力+1","right":0,"name":"labContent","left":220,"leading":25,"fontSize":50,"font":"SimHei","color":"#ffffff"}, "nodeParent":88, "label":"Label(labContent)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":95, "child":[ ] }] }] }], "$HIDDEN":false }] }, { "x":15, "type":"Box", "props":{"right":0,"left":0,"height":1,"bottom":-1}, "nodeParent":1, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":14, "child":[ { "x":30, "type":"Box", "props":{"width":600,"var":"btnSummary","runtime":"Laya.runtime.ColorfulBox","name":"btnSummary","height":150,"centerX":0,"bottom":80}, "nodeParent":14, "label":"Box(btnSummary)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":151, "child":[ { "x":45, "type":"Label", "props":{"text":"UI_Goto_Summary","name":"label","fontSize":60,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0}, "nodeParent":151, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":152, "child":[ ] }] }, { "x":30, "type":"Box", "props":{"y":-155,"var":"boxSpeed","runtime":"Laya.runtime.ColorFilterItem","right":100,"name":"boxSpeed","left":100,"height":150,"anchorY":0.5,"anchorX":0.5}, "nodeParent":14, "label":"Box(boxSpeed)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":104, "child":[ { "x":45, "type":"ProgressBar", "props":{"var":"prgSpeed","skin":"images/progress/progress_s.png","right":0,"name":"prgSpeed","left":0,"bottom":0}, "nodeParent":104, "label":"ProgressBar(prgSpeed)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":105, "child":[ ] }, { "x":45, "type":"HScrollBar", "props":{"var":"scbSpeed","skin":"images/slider/hslider_s.png","right":0,"name":"scbSpeed","min":0,"max":1000,"left":0,"height":60,"bottom":0}, "nodeParent":104, "label":"HScrollBar(scbSpeed)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":106, "child":[ ] }, { "x":45, "type":"Label", "props":{"text":"UI_Manual","fontSize":50,"color":"#ffffff","bottom":70}, "nodeParent":104, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":107, "child":[ ] }, { "x":45, "type":"Label", "props":{"text":"UI_Auto","right":0,"fontSize":50,"font":"SimHei","color":"#ffffff","bottom":70}, "nodeParent":104, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":108, "child":[ ] }] }], "$LOCKED":true, "$HIDDEN":false }, { "x":15, "type":"Box", "props":{"width":10,"var":"boxParticle","name":"boxParticle","height":10,"centerY":0,"centerX":0}, "nodeParent":1, "label":"Box(boxParticle)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":153, "child":[ { "type":"Particle2D", "source":"particle/fly.part", "props":{"y":5,"x":5,"url":"particle/fly.part","autoPlay":true}, "nodeParent":153, "label":"Particle2D", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":154, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/Loading.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":12, "props":{"width":1125,"sceneColor":"#000000","runtime":"Laya.runtime.ViewBase","height":2436}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Sprite", "props":{"y":0,"x":0,"alpha":0.3}, "nodeParent":1, "label":"Sprite", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":11, "child":[ { "x":30, "type":"Rect", "props":{"width":2000,"lineWidth":1,"height":3000,"fillColor":"#000000"}, "nodeParent":11, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":12, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":200,"scaleY":2,"scaleX":2,"height":200,"centerY":0,"centerX":0}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":2, "child":[ { "type":"Animation", "props":{"y":100,"x":100,"source":"view/CyberTheme/animation/circleFlash.ani","autoPlay":true}, "nodeParent":2, "label":"Animation", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":3, "child":[ ] }, { "type":"Image", "props":{"skin":"images/resource/circle.png","renderType":"mask"}, "nodeParent":2, "label":"Image", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":9, "child":[ ] }] }, { "x":15, "type":"Label", "props":{"text":"UI_Loading","fontSize":80,"font":"Impact","color":"#ffffff","centerY":400,"centerX":0}, "nodeParent":1, "label":"Label", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":10, "child":[ ] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/MessagePopup.ui ================================================ { "x":0, "type":"View", "selectedBox":1, "selecteID":2, "props":{"width":1100,"sceneColor":"#000000","mouseThrough":true,"mouseEnabled":false,"height":230}, "nodeParent":-1, "label":"View", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"var":"boxBg","top":10,"runtime":"Laya.runtime.ColorfulBox","right":10,"name":"boxBg","left":10,"bottom":10,"alpha":0.75}, "nodeParent":1, "label":"Box(boxBg)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":3, "child":[ ] }, { "x":15, "type":"Label", "props":{"wordWrap":true,"var":"message","text":"消息","right":50,"name":"message","left":50,"fontSize":60,"font":"SimHei","color":"#ffffff","centerY":0,"align":"center"}, "nodeParent":1, "label":"Label(message)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":2, "child":[ ] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/SaveLoad.ui ================================================ { "x":0, "type":"Dialog", "selectedBox":1, "selecteID":25, "props":{"width":645,"sceneColor":"#000000","height":400}, "nodeParent":-1, "label":"Dialog", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"top":0,"right":0,"left":0,"bottom":300}, "nodeParent":1, "label":"Box", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":15, "child":[ { "type":"Box", "props":{"y":0,"x":0,"width":645,"height":2}, "nodeParent":15, "label":"Box", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":19, "child":[ { "type":"Rect", "props":{"width":645,"lineWidth":1,"height":2,"fillColor":"#97ffe6"}, "nodeParent":19, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":17, "child":[ ] }] }, { "type":"Box", "props":{"width":645,"height":2,"centerX":0,"bottom":0}, "nodeParent":15, "label":"Box", "isOpen":null, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":20, "child":[ { "type":"Rect", "props":{"width":645,"lineWidth":1,"height":2,"fillColor":"#97ffe6"}, "nodeParent":20, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":21, "child":[ ] }] }, { "type":"Box", "props":{"width":645,"height":100,"centerY":0,"centerX":0,"alpha":0.2}, "nodeParent":15, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":22, "child":[ { "type":"Rect", "props":{"width":645,"lineWidth":1,"height":100,"fillColor":"#000000"}, "nodeParent":22, "label":"Rect", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":23, "child":[ ] }] }] }, { "x":15, "type":"TextInput", "props":{"wordWrap":false,"var":"input","valign":"middle","top":0,"text":"content","right":0,"overflow":"scroll","left":0,"fontSize":35,"font":"SimHei","color":"#ffffff","bottom":300}, "nodeParent":1, "label":"TextInput(input)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":4, "child":[ ] }, { "x":15, "type":"Box", "props":{"width":120,"var":"btnSave","runtime":"Laya.runtime.ColorfulBox","name":"btnSmall","left":5,"height":120,"bottom":155,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnSave)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":5, "child":[ { "type":"Label", "props":{"text":"UI_Save","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"bold":true,"anchorY":0.5,"anchorX":0.5}, "nodeParent":5, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":7, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":120,"var":"btnLoad","runtime":"Laya.runtime.ColorfulBox","name":"btnSmall","left":130,"height":120,"bottom":155,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnLoad)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":6, "child":[ { "type":"Label", "props":{"text":"UI_Load","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"bold":true,"anchorY":0.5,"anchorX":0.5}, "nodeParent":6, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":8, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":120,"var":"btnRead","runtime":"Laya.runtime.ColorfulBox","name":"btnSmall","left":260,"height":120,"bottom":155,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnRead)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":13, "child":[ { "type":"Label", "props":{"text":"UI_Read","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"bold":true,"anchorY":0.5,"anchorX":0.5}, "nodeParent":13, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":14, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":120,"var":"btnWrite","runtime":"Laya.runtime.ColorfulBox","name":"btnSmall","left":390,"height":120,"bottom":155,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnWrite)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":11, "child":[ { "type":"Label", "props":{"text":"UI_Write","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"bold":true,"anchorY":0.5,"anchorX":0.5}, "nodeParent":11, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":12, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"x":10,"width":120,"var":"btnClose","runtime":"Laya.runtime.ColorfulBox","right":5,"name":"btnSmall","height":120,"bottom":155,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnClose)", "isOpen":false, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":9, "child":[ { "type":"Label", "props":{"text":"×","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"bold":true,"anchorY":0.5,"anchorX":0.5}, "nodeParent":9, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":10, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"y":20,"var":"btnBackup","runtime":"Laya.runtime.ColorfulBox","right":5,"name":"btnBackup","left":5,"height":120,"bottom":5,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnBackup)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":25, "child":[ { "x":30, "type":"Label", "props":{"text":"UI_BackupBtn","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"bold":true,"anchorY":0.5,"anchorX":0.5}, "nodeParent":25, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":26, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/pages/view/Themes.ui ================================================ { "x":0, "type":"Dialog", "selectedBox":1, "selecteID":13, "props":{"width":350,"sceneColor":"#000000","height":550}, "nodeParent":-1, "label":"Dialog", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":1, "child":[ { "x":15, "type":"Box", "props":{"top":20,"right":20,"left":20,"bottom":130}, "nodeParent":1, "label":"Box", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":6, "child":[ { "x":30, "type":"RadioGroup", "props":{"var":"radioTheme","name":"radioTheme","height":380,"centerY":0,"centerX":0}, "nodeParent":6, "label":"RadioGroup(radioTheme)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":13, "child":[ { "x":45, "type":"Radio", "props":{"width":300,"top":0,"skin":"images/radio/radio_cyber.png","name":"item0","height":100}, "nodeParent":13, "label":"Radio(item0)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":10, "child":[ ] }, { "x":45, "type":"Radio", "props":{"width":300,"skin":"images/radio/radio_dark.png","name":"item1","height":100,"centerY":0}, "nodeParent":13, "label":"Radio(item1)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":11, "child":[ ] }, { "x":45, "type":"Radio", "props":{"width":300,"skin":"images/radio/radio_light.png","name":"item2","height":100,"bottom":0}, "nodeParent":13, "label":"Radio(item2)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":12, "child":[ ] }] }] }, { "x":15, "type":"Box", "props":{"width":90,"var":"btnOK","runtime":"Laya.runtime.ColorfulBox","name":"btnSmall","left":20,"height":90,"bottom":20,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnOK)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":2, "child":[ { "x":30, "type":"Label", "props":{"text":"√","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"bold":true,"anchorY":0.5,"anchorX":0.5}, "nodeParent":2, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":3, "child":[ ] }] }, { "x":15, "type":"Box", "props":{"width":90,"var":"btnClose","runtime":"Laya.runtime.ColorfulBox","right":20,"name":"btnSmall","height":90,"bottom":20,"anchorY":0.5,"anchorX":0.5}, "nodeParent":1, "label":"Box(btnClose)", "isOpen":true, "isDirectory":true, "isAniNode":true, "hasChild":true, "compId":14, "child":[ { "x":30, "type":"Label", "props":{"text":"×","name":"label","fontSize":50,"font":"SimHei","color":"#ffffff","centerY":0,"centerX":0,"bold":true,"anchorY":0.5,"anchorX":0.5}, "nodeParent":14, "label":"Label(label)", "isDirectory":false, "isAniNode":true, "hasChild":false, "compId":15, "child":[ ] }] }], "animations":[ { "nodes":[ ], "name":"ani1", "id":1, "frameRate":24, "action":0 }] } ================================================ FILE: laya/styles.xml ================================================ ================================================ FILE: lifeRestart.laya ================================================ {"proName":"lifeRestart","engineType":0,"proType":2,"layaProType":0} ================================================ FILE: package.json ================================================ { "name": "life_restart", "type": "module", "main": "repl/index.js", "version": "2.1.0", "author": "Vick Scarlet ", "scripts": { "xlsx2json": "vt transform -d public \"data/**/*.xlsx\"", "dev": "vite", "build": "vite build", "start": "vite preview", "test": "vitest" }, "devDependencies": { "v-transform": "^2.2.0", "vite": "^7.3.1", "vitest": "^4.0.18" } } ================================================ FILE: public/condition_test.html ================================================ 颜值: (CHR)
智力: (INT)
体质: (STR)
家境: (MNY)
快乐: (SPR)
生命: (LIF)
天赋: (TLT)
事件: (EVT)


表达式:

结果:


================================================ FILE: public/images/atlas/.rec ================================================ D . D fonts R 39B4F491 方正像素12.ttf D images D images/accessories P ADDDCB66 cardicon@3x.png R 0E2F6E7F insert_coin@3x.png R B45325FC title@3x.png P 074FEF52 title_left@3x.png R 97E72B92 title_neon@3x.png P 2BA0101A title_right@3x.png R E1602E15 titlebar@3x.png D images/background R 9343F3BB background_1@3x.png R 0B49B27D background_2@3x.png D images/border P A2B33396 achievement@3x.png R 45A1A604 achievement_complete@3x.png R 6CF3EE8E border_1@3x.png R AAEA6308 border_2@3x.png R A57A026E card@3x.png P C1EDDBED property@3x.png R A8C7A5A5 talent_item@3x.png R DCE4E73A talent_item_selected@3x.png R 373CDF45 up@3x.png D images/button P 69FF5572 button_back@3x.png R 441BFE78 button_main@3x.png P F2B85B54 button_small@3x.png D images/icons P C677F3AE icon_achievement@3x.png P 3D072134 icon_chr@3x.png P C663FAF5 icon_discord.png P 3FA91C13 icon_github.png P AB934AEA icon_int@3x.png P F1A0724B icon_mny@3x.png P D5AADAC9 icon_rank@3x.png P 0806E5F3 icon_save.png P 2DB0325D icon_spr@3x.png P 2EFA541B icon_str@3x.png P 804842C9 icon_thanks@3x.png P 96DD5D94 icon_themes.png P 6ECB5FEC icon_up@3x.png D images/progress P E2BF0C93 progress_1@3x$bar.png P B86E1D0F progress_1@3x.png P E7F15BA7 progress_2$bar.png P 641A22BF progress_2.png P AF80A9AF progress_s$bar.png P 41417E8D progress_s.png D images/radio P CCF63014 radio_cyber.png P 040DE73C radio_dark.png P BA975F5A radio_light.png D images/resource P F3659301 bottombreath.png P 496D6FB9 circle.png P B5087365 circleflash.png D images/slider P 9682C590 hslider_s$bar.png P F6238BD4 hslider_s$down.png P F4198287 hslider_s$up.png P 2A785866 hslider_s.png R 8B95E6D3 vslider_1@3x$bar.png P 6581FBA8 vslider_1@3x$down.png P 6581FBA8 vslider_1@3x$up.png R C9587878 vslider_1@3x.png D images/texture P FD231754 texture_1.png ================================================ FILE: public/images/atlas/images/accessories.atlas ================================================ {"frames":{"cardicon@3x.png":{"frame":{"h":466,"idx":0,"w":455,"x":0,"y":0},"sourceSize":{"h":466,"w":455},"spriteSourceSize":{"x":0,"y":0}},"title_left@3x.png":{"frame":{"h":27,"idx":0,"w":48,"x":456,"y":0},"sourceSize":{"h":27,"w":48},"spriteSourceSize":{"x":0,"y":0}},"title_right@3x.png":{"frame":{"h":27,"idx":0,"w":48,"x":456,"y":28},"sourceSize":{"h":27,"w":48},"spriteSourceSize":{"x":0,"y":0}}},"meta":{"image":"accessories.png","prefix":"images/accessories/"}} ================================================ FILE: public/images/atlas/images/border.atlas ================================================ {"frames":{"achievement@3x.png":{"frame":{"h":412,"idx":0,"w":486,"x":0,"y":0},"sourceSize":{"h":412,"w":486},"spriteSourceSize":{"x":0,"y":0}},"property@3x.png":{"frame":{"h":84,"idx":0,"w":257,"x":0,"y":413},"sourceSize":{"h":84,"w":257},"spriteSourceSize":{"x":0,"y":0}}},"meta":{"image":"border.png","prefix":"images/border/"}} ================================================ FILE: public/images/atlas/images/button.atlas ================================================ {"frames":{"button_back@3x.png":{"frame":{"h":114,"idx":0,"w":147,"x":0,"y":91},"sourceSize":{"h":114,"w":147},"spriteSourceSize":{"x":0,"y":0}},"button_small@3x.png":{"frame":{"h":90,"idx":0,"w":225,"x":0,"y":0},"sourceSize":{"h":90,"w":225},"spriteSourceSize":{"x":0,"y":0}}},"meta":{"image":"button.png","prefix":"images/button/"}} ================================================ FILE: public/images/atlas/images/icons.atlas ================================================ {"frames":{"icon_achievement@3x.png":{"frame":{"h":69,"idx":0,"w":65,"x":188,"y":385},"sourceSize":{"h":69,"w":65},"spriteSourceSize":{"x":0,"y":0}},"icon_chr@3x.png":{"frame":{"h":61,"idx":0,"w":57,"x":320,"y":448},"sourceSize":{"h":61,"w":57},"spriteSourceSize":{"x":0,"y":0}},"icon_discord.png":{"frame":{"h":384,"idx":0,"w":384,"x":0,"y":0},"sourceSize":{"h":384,"w":384},"spriteSourceSize":{"x":0,"y":0}},"icon_github.png":{"frame":{"h":384,"idx":0,"w":384,"x":385,"y":0},"sourceSize":{"h":384,"w":384},"spriteSourceSize":{"x":0,"y":0}},"icon_int@3x.png":{"frame":{"h":57,"idx":0,"w":54,"x":188,"y":455},"sourceSize":{"h":57,"w":54},"spriteSourceSize":{"x":0,"y":0}},"icon_mny@3x.png":{"frame":{"h":57,"idx":0,"w":54,"x":243,"y":455},"sourceSize":{"h":57,"w":54},"spriteSourceSize":{"x":0,"y":0}},"icon_rank@3x.png":{"frame":{"h":62,"idx":0,"w":72,"x":320,"y":385},"sourceSize":{"h":62,"w":72},"spriteSourceSize":{"x":0,"y":0}},"icon_save.png":{"frame":{"h":90,"idx":0,"w":90,"x":97,"y":385},"sourceSize":{"h":90,"w":90},"spriteSourceSize":{"x":0,"y":0}},"icon_spr@3x.png":{"frame":{"h":60,"idx":0,"w":57,"x":378,"y":448},"sourceSize":{"h":60,"w":57},"spriteSourceSize":{"x":0,"y":0}},"icon_str@3x.png":{"frame":{"h":57,"idx":0,"w":54,"x":393,"y":385},"sourceSize":{"h":57,"w":54},"spriteSourceSize":{"x":0,"y":0}},"icon_thanks@3x.png":{"frame":{"h":69,"idx":0,"w":65,"x":254,"y":385},"sourceSize":{"h":69,"w":65},"spriteSourceSize":{"x":0,"y":0}},"icon_themes.png":{"frame":{"h":96,"idx":0,"w":96,"x":0,"y":385},"sourceSize":{"h":96,"w":96},"spriteSourceSize":{"x":0,"y":0}},"icon_up@3x.png":{"frame":{"h":18,"idx":0,"w":33,"x":97,"y":476},"sourceSize":{"h":18,"w":33},"spriteSourceSize":{"x":0,"y":0}}},"meta":{"image":"icons.png","prefix":"images/icons/"}} ================================================ FILE: public/images/atlas/images/progress.atlas ================================================ {"frames":{"progress_1@3x$bar.png":{"frame":{"h":36,"idx":0,"w":203,"x":0,"y":262},"sourceSize":{"h":36,"w":203},"spriteSourceSize":{"x":0,"y":0}},"progress_1@3x.png":{"frame":{"h":36,"idx":0,"w":203,"x":204,"y":262},"sourceSize":{"h":36,"w":203},"spriteSourceSize":{"x":0,"y":0}},"progress_2$bar.png":{"frame":{"h":200,"idx":0,"w":200,"x":0,"y":0},"sourceSize":{"h":200,"w":200},"spriteSourceSize":{"x":0,"y":0}},"progress_2.png":{"frame":{"h":200,"idx":0,"w":200,"x":201,"y":0},"sourceSize":{"h":200,"w":200},"spriteSourceSize":{"x":0,"y":0}},"progress_s$bar.png":{"frame":{"h":60,"idx":0,"w":226,"x":0,"y":201},"sourceSize":{"h":60,"w":226},"spriteSourceSize":{"x":0,"y":0}},"progress_s.png":{"frame":{"h":60,"idx":0,"w":226,"x":227,"y":201},"sourceSize":{"h":60,"w":226},"spriteSourceSize":{"x":0,"y":0}}},"meta":{"image":"progress.png","prefix":"images/progress/"}} ================================================ FILE: public/images/atlas/images/radio.atlas ================================================ {"frames":{"radio_cyber.png":{"frame":{"h":300,"idx":0,"w":300,"x":0,"y":0},"sourceSize":{"h":300,"w":300},"spriteSourceSize":{"x":0,"y":0}},"radio_dark.png":{"frame":{"h":300,"idx":0,"w":300,"x":0,"y":301},"sourceSize":{"h":300,"w":300},"spriteSourceSize":{"x":0,"y":0}},"radio_light.png":{"frame":{"h":300,"idx":0,"w":300,"x":301,"y":0},"sourceSize":{"h":300,"w":300},"spriteSourceSize":{"x":0,"y":0}}},"meta":{"image":"radio.png","prefix":"images/radio/"}} ================================================ FILE: public/images/atlas/images/resource.atlas ================================================ {"frames":{"bottombreath.png":{"frame":{"h":200,"idx":0,"w":200,"x":0,"y":0},"sourceSize":{"h":200,"w":200},"spriteSourceSize":{"x":0,"y":0}},"circle.png":{"frame":{"h":200,"idx":0,"w":200,"x":0,"y":201},"sourceSize":{"h":200,"w":200},"spriteSourceSize":{"x":0,"y":0}},"circleflash.png":{"frame":{"h":200,"idx":0,"w":200,"x":201,"y":0},"sourceSize":{"h":200,"w":200},"spriteSourceSize":{"x":0,"y":0}}},"meta":{"image":"resource.png","prefix":"images/resource/"}} ================================================ FILE: public/images/atlas/images/slider.atlas ================================================ {"frames":{"hslider_s$bar.png":{"frame":{"h":180,"idx":0,"w":47,"x":0,"y":61},"sourceSize":{"h":180,"w":47},"spriteSourceSize":{"x":0,"y":0}},"hslider_s$down.png":{"frame":{"h":1,"idx":0,"w":1,"x":0,"y":242},"sourceSize":{"h":1,"w":1},"spriteSourceSize":{"x":0,"y":0}},"hslider_s$up.png":{"frame":{"h":1,"idx":0,"w":1,"x":0,"y":244},"sourceSize":{"h":1,"w":1},"spriteSourceSize":{"x":0,"y":0}},"hslider_s.png":{"frame":{"h":60,"idx":0,"w":226,"x":0,"y":0},"sourceSize":{"h":60,"w":226},"spriteSourceSize":{"x":0,"y":0}},"vslider_1@3x$down.png":{"frame":{"h":1,"idx":0,"w":1,"x":0,"y":246},"sourceSize":{"h":1,"w":1},"spriteSourceSize":{"x":0,"y":0}},"vslider_1@3x$up.png":{"frame":{"h":1,"idx":0,"w":1,"x":0,"y":248},"sourceSize":{"h":1,"w":1},"spriteSourceSize":{"x":0,"y":0}}},"meta":{"image":"slider.png","prefix":"images/slider/"}} ================================================ FILE: public/images/atlas/images/texture.atlas ================================================ {"frames":{"texture_1.png":{"frame":{"h":400,"idx":0,"w":400,"x":0,"y":0},"sourceSize":{"h":400,"w":400},"spriteSourceSize":{"x":0,"y":0}}},"meta":{"image":"texture.png","prefix":"images/texture/"}} ================================================ FILE: public/libs/laya/LayaRender.js ================================================ /** * Matter.js 渲染器在 LayaAir 的实现。 */ (function() { var LayaRender = {}; var Common = Matter.Common; var Composite = Matter.Composite; var Bounds = Matter.Bounds; var Events = Matter.Events; var Grid = Matter.Grid; var Vector = Matter.Vector; /** * 创建新的渲染器。 * @param {object} options 所有属性都有默认值,options中的属性会覆盖默认属性。 * @return {render} 返回创建的旋绕器 */ LayaRender.create = function(options) { var defaults = { controller: LayaRender, engine: null, element: null, canvas: null, mouse: null, frameRequestId: null, options: { width: 800, height: 600, pixelRatio: 1, background: '#fafafa', wireframeBackground: '#222222', hasBounds: !!options.bounds, enabled: true, wireframes: true, showSleeping: true, showDebug: false, showBroadphase: false, showBounds: false, showVelocity: false, showCollisions: false, showSeparations: false, showAxes: false, showPositions: false, showAngleIndicator: false, showIds: false, showShadows: false, showVertexNumbers: false, showConvexHulls: false, showInternalEdges: false, showMousePosition: false } }; var render = Common.extend(defaults, options); render.mouse = options.mouse; render.engine = options.engine; // 如果用户没有指定contaienr,默认使用stage render.container = render.container || Laya.stage; render.bounds = render.bounds || { min: { x: 0, y: 0 }, max: { x: render.width, y: render.height } }; return render; } /** * 运行渲染器。 * @param {render} render 渲染的目标是LayaRender.create()返回的对象 * @return {void} */ LayaRender.run = function(render) { Laya.timer.frameLoop(1, this, LayaRender.world, [render]); Events.on(render.engine.world, 'afterRemove', LayaRender.onRemoveSprite); }; /** * 停止渲染器。 * @param {render} LayaRender.create()返回的对象 * @return {void} */ LayaRender.stop = function(render) { Laya.timer.clear(this, LayaRender.world); Events.off(render.engine.world, 'afterRemove', LayaRender.onRemoveSprite); } LayaRender.onRemoveSprite = function(args) { var sprite = args.object.layaSprite; if (sprite && sprite.parent) sprite.parent.removeChild(sprite); } /** * 渲染给定的 engine 的 Matter.World 对象。 * 这是渲染的入口,每次场景改变时都应该被调用。 * @param {render} render * @return {void} */ LayaRender.world = function(render) { var engine = render.engine, world = engine.world, renderer = render.renderer, container = render.container, options = render.options, bodies = Composite.allBodies(world), allConstraints = Composite.allConstraints(world), constraints = [], i; if (options.wireframes) { LayaRender.setBackground(render, options.wireframeBackground); } else { LayaRender.setBackground(render, options.background); } // 处理 bounds var boundsWidth = render.bounds.max.x - render.bounds.min.x, boundsHeight = render.bounds.max.y - render.bounds.min.y, boundsScaleX = boundsWidth / render.options.width, boundsScaleY = boundsHeight / render.options.height; if (options.hasBounds) { // 隐藏不在视口内的bodies for (i = 0; i < bodies.length; i++) { var body = bodies[i]; body.render.sprite.visible = Bounds.overlaps(body.bounds, render.bounds); } // 过滤掉不在视口内的 constraints for (i = 0; i < allConstraints.length; i++) { var constraint = allConstraints[i], bodyA = constraint.bodyA, bodyB = constraint.bodyB, pointAWorld = constraint.pointA, pointBWorld = constraint.pointB; if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA); if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB); if (!pointAWorld || !pointBWorld) continue; if (Bounds.contains(render.bounds, pointAWorld) || Bounds.contains(render.bounds, pointBWorld)) constraints.push(constraint); } // 改变视口 container.scale(1 / boundsScaleX, 1 / boundsScaleY); container.pos(-render.bounds.min.x * (1 / boundsScaleX), -render.bounds.min.y * (1 / boundsScaleY)); } else { constraints = allConstraints; } for (i = 0; i < bodies.length; i++) LayaRender.body(render, bodies[i]); for (i = 0; i < constraints.length; i++) LayaRender.constraint(render, constraints[i]); }; /** * 设置背景色或者背景图片。 * @param {render} render * @param {string} background 16进制颜色字符串或者图片路径 */ LayaRender.setBackground = function(render, background) { if (render.currentBackground !== background) { var isColor = background.indexOf && background.indexOf('#') !== -1; render.container.graphics.clear(); if (isColor) { // 使用纯色背景 render.container.bgColor = background; } else { render.container.loadImage(background); // 使用背景图片时把背景色设置为白色 render.container.bgColor = "#FFFFFF"; } render.currentBackground = background; } } /** * 渲染 body * @param {render} render * @param {body} body * @return {void} */ LayaRender.body = function(render, body) { var engine = render.engine, bodyRender = body.render; if (!bodyRender.visible) return; // 有纹理的body if (bodyRender.sprite && bodyRender.sprite.texture) { var spriteId = 'b-' + body.id, sprite = body.layaSprite, container = render.container; // 如果sprite不存在,则初始化一个 if (!sprite) sprite = body.layaSprite = _createBodySprite(render, body); // 如果sprite未在显示列表,则添加至显示列表 if (!container.contains(sprite)) container.addChild(sprite); // 更新sprite位置 sprite.x = body.position.x; sprite.y = body.position.y; sprite.rotation = body.angle * 180 / Math.PI; sprite.scaleX = bodyRender.sprite.xScale || 1; sprite.scaleY = bodyRender.sprite.yScale || 1; } else // 没有纹理的body { var primitiveId = 'b-' + body.id, sprite = body.layaSprite, container = render.container; // 如果sprite不存在,则初始化一个 if (!sprite) { sprite = body.layaSprite = _createBodyPrimitive(render, body); sprite.initialAngle = body.angle; } // 如果sprite未在显示列表,则添加至显示列表 if (!container.contains(sprite)) container.addChild(sprite); // 更新sprite位置 sprite.x = body.position.x; sprite.y = body.position.y; sprite.rotation = (body.angle - sprite.initialAngle) * 180 / Math.PI; } }; /** * 创建使用纹理的Sprite对象。 * @param {render} render * @param {body} body * @return {void} */ var _createBodySprite = function(render, body) { var bodyRender = body.render, texturePath = bodyRender.sprite.texture, sprite = new Laya.Sprite(); sprite.loadImage(texturePath); sprite.pivotX = body.render.sprite.xOffset; sprite.pivotY = body.render.sprite.yOffset; return sprite; }; /** * 创建使用矢量绘图的Sprite对象。 * @param {render} render * @param {body} body * @return {void} */ var _createBodyPrimitive = function(render, body) { var bodyRender = body.render, options = render.options, sprite = new Laya.Sprite(), fillStyle, strokeStyle, lineWidth, part, points = []; var primitive = sprite.graphics; primitive.clear(); // 处理 compound parts for (var k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) { part = body.parts[k]; if (!options.wireframes) { fillStyle = bodyRender.fillStyle; strokeStyle = bodyRender.strokeStyle; lineWidth = bodyRender.lineWidth; } else { fillStyle = null; strokeStyle = '#bbbbbb'; lineWidth = 1; } points.push(part.vertices[0].x - body.position.x, part.vertices[0].y - body.position.y); for (var j = 1; j < part.vertices.length; j++) { points.push(part.vertices[j].x - body.position.x, part.vertices[j].y - body.position.y); } points.push(part.vertices[0].x - body.position.x, part.vertices[0].y - body.position.y); primitive.drawPoly(0, 0, points, fillStyle, strokeStyle, lineWidth); // 角度指示器 if (options.showAngleIndicator || options.showAxes) { lineWidth = 1; if (options.wireframes) { strokeStyle = '#CD5C5C'; } else { strokeStyle = bodyRender.strokeStyle; } primitive.drawLine(part.position.x - body.position.x, part.position.y - body.position.y, ((part.vertices[0].x + part.vertices[part.vertices.length - 1].x) / 2 - body.position.x), ((part.vertices[0].y + part.vertices[part.vertices.length - 1].y) / 2 - body.position.y)); } } return sprite; }; /** * 绘制 constraint。 * @param {render} render * @param {constraint} constraint * @return {void} */ LayaRender.constraint = function(render, constraint) { var engine = render.engine, bodyA = constraint.bodyA, bodyB = constraint.bodyB, pointA = constraint.pointA, pointB = constraint.pointB, container = render.container, constraintRender = constraint.render, primitiveId = 'c-' + constraint.id, sprite = constraint.layaSprite; // 如果sprite不存在,则初始化一个 if (!sprite) sprite = constraint.layaSprite = new Laya.Sprite(); var primitive = sprite.graphics; // constraint 没有两个终点时不渲染 if (!constraintRender.visible || !constraint.pointA || !constraint.pointB) { primitive.clear(); return; } // 如果sprite未在显示列表,则添加至显示列表 if (!container.contains(sprite)) container.addChild(sprite); // 渲染 constraint primitive.clear(); var fromX, fromY, toX, toY; if (bodyA) { fromX = bodyA.position.x + pointA.x; fromY = bodyA.position.y + pointA.y; } else { fromX = pointA.x; fromY = pointA.y; } if (bodyB) { toX = bodyB.position.x + pointB.x; toY = bodyB.position.y + pointB.y; } else { toX = pointB.x; toY = pointB.y; } primitive.drawLine(fromX, fromY, toX, toY, constraintRender.strokeStyle, constraintRender.lineWidth); }; window.LayaRender = LayaRender; })(); ================================================ FILE: public/libs/laya/bytebuffer.js ================================================ /* Copyright 2013-2014 Daniel Wirtz Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @license bytebuffer.js (c) 2015 Daniel Wirtz * Backing buffer: ArrayBuffer, Accessor: Uint8Array * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/bytebuffer.js for details */ (function(global, factory) { /* AMD */ if (typeof define === 'function' && define["amd"]) define(["long"], factory); /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"]) module['exports'] = (function() { var Long; try { Long = require("long"); } catch (e) {} return factory(Long); })(); /* Global */ else (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]); })(this, function(Long) { "use strict"; /** * Constructs a new ByteBuffer. * @class The swiss army knife for binary data in JavaScript. * @exports ByteBuffer * @constructor * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}. * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to * {@link ByteBuffer.DEFAULT_ENDIAN}. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to * {@link ByteBuffer.DEFAULT_NOASSERT}. * @expose */ var ByteBuffer = function(capacity, littleEndian, noAssert) { if (typeof capacity === 'undefined') capacity = ByteBuffer.DEFAULT_CAPACITY; if (typeof littleEndian === 'undefined') littleEndian = ByteBuffer.DEFAULT_ENDIAN; if (typeof noAssert === 'undefined') noAssert = ByteBuffer.DEFAULT_NOASSERT; if (!noAssert) { capacity = capacity | 0; if (capacity < 0) throw RangeError("Illegal capacity"); littleEndian = !!littleEndian; noAssert = !!noAssert; } /** * Backing ArrayBuffer. * @type {!ArrayBuffer} * @expose */ this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity); /** * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`. * @type {?Uint8Array} * @expose */ this.view = capacity === 0 ? null : new Uint8Array(this.buffer); /** * Absolute read/write offset. * @type {number} * @expose * @see ByteBuffer#flip * @see ByteBuffer#clear */ this.offset = 0; /** * Marked offset. * @type {number} * @expose * @see ByteBuffer#mark * @see ByteBuffer#reset */ this.markedOffset = -1; /** * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation. * @type {number} * @expose * @see ByteBuffer#flip * @see ByteBuffer#clear */ this.limit = capacity; /** * Whether to use little endian byte order, defaults to `false` for big endian. * @type {boolean} * @expose */ this.littleEndian = littleEndian; /** * Whether to skip assertions of offsets and values, defaults to `false`. * @type {boolean} * @expose */ this.noAssert = noAssert; }; /** * ByteBuffer version. * @type {string} * @const * @expose */ ByteBuffer.VERSION = "5.0.1"; /** * Little endian constant that can be used instead of its boolean value. Evaluates to `true`. * @type {boolean} * @const * @expose */ ByteBuffer.LITTLE_ENDIAN = true; /** * Big endian constant that can be used instead of its boolean value. Evaluates to `false`. * @type {boolean} * @const * @expose */ ByteBuffer.BIG_ENDIAN = false; /** * Default initial capacity of `16`. * @type {number} * @expose */ ByteBuffer.DEFAULT_CAPACITY = 16; /** * Default endianess of `false` for big endian. * @type {boolean} * @expose */ ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN; /** * Default no assertions flag of `false`. * @type {boolean} * @expose */ ByteBuffer.DEFAULT_NOASSERT = false; /** * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded * and int64 support is not available. * @type {?Long} * @const * @see https://github.com/dcodeIO/long.js * @expose */ ByteBuffer.Long = Long || null; /** * @alias ByteBuffer.prototype * @inner */ var ByteBufferPrototype = ByteBuffer.prototype; /** * An indicator used to reliably determine if an object is a ByteBuffer or not. * @type {boolean} * @const * @expose * @private */ ByteBufferPrototype.__isByteBuffer__; Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", { value: true, enumerable: false, configurable: false }); // helpers /** * @type {!ArrayBuffer} * @inner */ var EMPTY_BUFFER = new ArrayBuffer(0); /** * String.fromCharCode reference for compile-time renaming. * @type {function(...number):string} * @inner */ var stringFromCharCode = String.fromCharCode; /** * Creates a source function for a string. * @param {string} s String to read from * @returns {function():number|null} Source function returning the next char code respectively `null` if there are * no more characters left. * @throws {TypeError} If the argument is invalid * @inner */ function stringSource(s) { var i=0; return function() { return i < s.length ? s.charCodeAt(i++) : null; }; } /** * Creates a destination function for a string. * @returns {function(number=):undefined|string} Destination function successively called with the next char code. * Returns the final string when called without arguments. * @inner */ function stringDestination() { var cs = [], ps = []; return function() { if (arguments.length === 0) return ps.join('')+stringFromCharCode.apply(String, cs); if (cs.length + arguments.length > 1024) ps.push(stringFromCharCode.apply(String, cs)), cs.length = 0; Array.prototype.push.apply(cs, arguments); }; } /** * Gets the accessor type. * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes) * @expose */ ByteBuffer.accessor = function() { return Uint8Array; }; /** * Allocates a new ByteBuffer backed by a buffer of the specified capacity. * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}. * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to * {@link ByteBuffer.DEFAULT_ENDIAN}. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to * {@link ByteBuffer.DEFAULT_NOASSERT}. * @returns {!ByteBuffer} * @expose */ ByteBuffer.allocate = function(capacity, littleEndian, noAssert) { return new ByteBuffer(capacity, littleEndian, noAssert); }; /** * Concatenates multiple ByteBuffers into one. * @param {!Array.} buffers Buffers to concatenate * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary", * defaults to "utf8") * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults * to {@link ByteBuffer.DEFAULT_ENDIAN}. * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to * {@link ByteBuffer.DEFAULT_NOASSERT}. * @returns {!ByteBuffer} Concatenated ByteBuffer * @expose */ ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) { if (typeof encoding === 'boolean' || typeof encoding !== 'string') { noAssert = littleEndian; littleEndian = encoding; encoding = undefined; } var capacity = 0; for (var i=0, k=buffers.length, length; i 0) capacity += length; } if (capacity === 0) return new ByteBuffer(0, littleEndian, noAssert); var bb = new ByteBuffer(capacity, littleEndian, noAssert), bi; i=0; while (i} buffer Anything that can be wrapped * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to * "utf8") * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to * {@link ByteBuffer.DEFAULT_ENDIAN}. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to * {@link ByteBuffer.DEFAULT_NOASSERT}. * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer` * @expose */ ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) { if (typeof encoding !== 'string') { noAssert = littleEndian; littleEndian = encoding; encoding = undefined; } if (typeof buffer === 'string') { if (typeof encoding === 'undefined') encoding = "utf8"; switch (encoding) { case "base64": return ByteBuffer.fromBase64(buffer, littleEndian); case "hex": return ByteBuffer.fromHex(buffer, littleEndian); case "binary": return ByteBuffer.fromBinary(buffer, littleEndian); case "utf8": return ByteBuffer.fromUTF8(buffer, littleEndian); case "debug": return ByteBuffer.fromDebug(buffer, littleEndian); default: throw Error("Unsupported encoding: "+encoding); } } if (buffer === null || typeof buffer !== 'object') throw TypeError("Illegal buffer"); var bb; if (ByteBuffer.isByteBuffer(buffer)) { bb = ByteBufferPrototype.clone.call(buffer); bb.markedOffset = -1; return bb; } if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array bb = new ByteBuffer(0, littleEndian, noAssert); if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER bb.buffer = buffer.buffer; bb.offset = buffer.byteOffset; bb.limit = buffer.byteOffset + buffer.byteLength; bb.view = new Uint8Array(buffer.buffer); } } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer bb = new ByteBuffer(0, littleEndian, noAssert); if (buffer.byteLength > 0) { bb.buffer = buffer; bb.offset = 0; bb.limit = buffer.byteLength; bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null; } } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets bb = new ByteBuffer(buffer.length, littleEndian, noAssert); bb.limit = buffer.length; for (var i=0; i} value Array of booleans to write * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted. * @returns {!ByteBuffer} * @expose */ ByteBufferPrototype.writeBitSet = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (!(value instanceof Array)) throw TypeError("Illegal BitSet: Not an array"); if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } var start = offset, bits = value.length, bytes = (bits >> 3), bit = 0, k; offset += this.writeVarint32(bits,offset); while(bytes--) { k = (!!value[bit++] & 1) | ((!!value[bit++] & 1) << 1) | ((!!value[bit++] & 1) << 2) | ((!!value[bit++] & 1) << 3) | ((!!value[bit++] & 1) << 4) | ((!!value[bit++] & 1) << 5) | ((!!value[bit++] & 1) << 6) | ((!!value[bit++] & 1) << 7); this.writeByte(k,offset++); } if(bit < bits) { var m = 0; k = 0; while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++)); this.writeByte(k,offset++); } if (relative) { this.offset = offset; return this; } return offset - start; } /** * Reads a BitSet as an array of booleans. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted. * @returns {Array * @expose */ ByteBufferPrototype.readBitSet = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; var ret = this.readVarint32(offset), bits = ret.value, bytes = (bits >> 3), bit = 0, value = [], k; offset += ret.length; while(bytes--) { k = this.readByte(offset++); value[bit++] = !!(k & 0x01); value[bit++] = !!(k & 0x02); value[bit++] = !!(k & 0x04); value[bit++] = !!(k & 0x08); value[bit++] = !!(k & 0x10); value[bit++] = !!(k & 0x20); value[bit++] = !!(k & 0x40); value[bit++] = !!(k & 0x80); } if(bit < bits) { var m = 0; k = this.readByte(offset++); while(bit < bits) value[bit++] = !!((k >> (m++)) & 1); } if (relative) { this.offset = offset; } return value; } /** * Reads the specified number of bytes. * @param {number} length Number of bytes to read * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted. * @returns {!ByteBuffer} * @expose */ ByteBufferPrototype.readBytes = function(length, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + length > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength); } var slice = this.slice(offset, offset + length); if (relative) this.offset += length; return slice; }; /** * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}. * @function * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets * will be modified according to the performed read operation. * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8") * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeBytes = ByteBufferPrototype.append; // types/ints/int8 /** * Writes an 8bit signed integer. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeInt8 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value !== 'number' || value % 1 !== 0) throw TypeError("Illegal value: "+value+" (not an integer)"); value |= 0; if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } offset += 1; var capacity0 = this.buffer.byteLength; if (offset > capacity0) this.resize((capacity0 *= 2) > offset ? capacity0 : offset); offset -= 1; this.view[offset] = value; if (relative) this.offset += 1; return this; }; /** * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}. * @function * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8; /** * Reads an 8bit signed integer. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. * @returns {number} Value read * @expose */ ByteBufferPrototype.readInt8 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 1 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); } var value = this.view[offset]; if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed if (relative) this.offset += 1; return value; }; /** * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}. * @function * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. * @returns {number} Value read * @expose */ ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8; /** * Writes an 8bit unsigned integer. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeUint8 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value !== 'number' || value % 1 !== 0) throw TypeError("Illegal value: "+value+" (not an integer)"); value >>>= 0; if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } offset += 1; var capacity1 = this.buffer.byteLength; if (offset > capacity1) this.resize((capacity1 *= 2) > offset ? capacity1 : offset); offset -= 1; this.view[offset] = value; if (relative) this.offset += 1; return this; }; /** * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}. * @function * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8; /** * Reads an 8bit unsigned integer. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. * @returns {number} Value read * @expose */ ByteBufferPrototype.readUint8 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 1 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); } var value = this.view[offset]; if (relative) this.offset += 1; return value; }; /** * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}. * @function * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. * @returns {number} Value read * @expose */ ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8; // types/ints/int16 /** * Writes a 16bit signed integer. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. * @throws {TypeError} If `offset` or `value` is not a valid number * @throws {RangeError} If `offset` is out of bounds * @expose */ ByteBufferPrototype.writeInt16 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value !== 'number' || value % 1 !== 0) throw TypeError("Illegal value: "+value+" (not an integer)"); value |= 0; if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } offset += 2; var capacity2 = this.buffer.byteLength; if (offset > capacity2) this.resize((capacity2 *= 2) > offset ? capacity2 : offset); offset -= 2; if (this.littleEndian) { this.view[offset+1] = (value & 0xFF00) >>> 8; this.view[offset ] = value & 0x00FF; } else { this.view[offset] = (value & 0xFF00) >>> 8; this.view[offset+1] = value & 0x00FF; } if (relative) this.offset += 2; return this; }; /** * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}. * @function * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. * @throws {TypeError} If `offset` or `value` is not a valid number * @throws {RangeError} If `offset` is out of bounds * @expose */ ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16; /** * Reads a 16bit signed integer. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. * @returns {number} Value read * @throws {TypeError} If `offset` is not a valid number * @throws {RangeError} If `offset` is out of bounds * @expose */ ByteBufferPrototype.readInt16 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 2 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength); } var value = 0; if (this.littleEndian) { value = this.view[offset ]; value |= this.view[offset+1] << 8; } else { value = this.view[offset ] << 8; value |= this.view[offset+1]; } if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed if (relative) this.offset += 2; return value; }; /** * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}. * @function * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. * @returns {number} Value read * @throws {TypeError} If `offset` is not a valid number * @throws {RangeError} If `offset` is out of bounds * @expose */ ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16; /** * Writes a 16bit unsigned integer. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. * @throws {TypeError} If `offset` or `value` is not a valid number * @throws {RangeError} If `offset` is out of bounds * @expose */ ByteBufferPrototype.writeUint16 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value !== 'number' || value % 1 !== 0) throw TypeError("Illegal value: "+value+" (not an integer)"); value >>>= 0; if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } offset += 2; var capacity3 = this.buffer.byteLength; if (offset > capacity3) this.resize((capacity3 *= 2) > offset ? capacity3 : offset); offset -= 2; if (this.littleEndian) { this.view[offset+1] = (value & 0xFF00) >>> 8; this.view[offset ] = value & 0x00FF; } else { this.view[offset] = (value & 0xFF00) >>> 8; this.view[offset+1] = value & 0x00FF; } if (relative) this.offset += 2; return this; }; /** * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}. * @function * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. * @throws {TypeError} If `offset` or `value` is not a valid number * @throws {RangeError} If `offset` is out of bounds * @expose */ ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16; /** * Reads a 16bit unsigned integer. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. * @returns {number} Value read * @throws {TypeError} If `offset` is not a valid number * @throws {RangeError} If `offset` is out of bounds * @expose */ ByteBufferPrototype.readUint16 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 2 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength); } var value = 0; if (this.littleEndian) { value = this.view[offset ]; value |= this.view[offset+1] << 8; } else { value = this.view[offset ] << 8; value |= this.view[offset+1]; } if (relative) this.offset += 2; return value; }; /** * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}. * @function * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. * @returns {number} Value read * @throws {TypeError} If `offset` is not a valid number * @throws {RangeError} If `offset` is out of bounds * @expose */ ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16; // types/ints/int32 /** * Writes a 32bit signed integer. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @expose */ ByteBufferPrototype.writeInt32 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value !== 'number' || value % 1 !== 0) throw TypeError("Illegal value: "+value+" (not an integer)"); value |= 0; if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } offset += 4; var capacity4 = this.buffer.byteLength; if (offset > capacity4) this.resize((capacity4 *= 2) > offset ? capacity4 : offset); offset -= 4; if (this.littleEndian) { this.view[offset+3] = (value >>> 24) & 0xFF; this.view[offset+2] = (value >>> 16) & 0xFF; this.view[offset+1] = (value >>> 8) & 0xFF; this.view[offset ] = value & 0xFF; } else { this.view[offset ] = (value >>> 24) & 0xFF; this.view[offset+1] = (value >>> 16) & 0xFF; this.view[offset+2] = (value >>> 8) & 0xFF; this.view[offset+3] = value & 0xFF; } if (relative) this.offset += 4; return this; }; /** * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @expose */ ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32; /** * Reads a 32bit signed integer. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @returns {number} Value read * @expose */ ByteBufferPrototype.readInt32 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 4 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength); } var value = 0; if (this.littleEndian) { value = this.view[offset+2] << 16; value |= this.view[offset+1] << 8; value |= this.view[offset ]; value += this.view[offset+3] << 24 >>> 0; } else { value = this.view[offset+1] << 16; value |= this.view[offset+2] << 8; value |= this.view[offset+3]; value += this.view[offset ] << 24 >>> 0; } value |= 0; // Cast to signed if (relative) this.offset += 4; return value; }; /** * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted. * @returns {number} Value read * @expose */ ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32; /** * Writes a 32bit unsigned integer. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @expose */ ByteBufferPrototype.writeUint32 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value !== 'number' || value % 1 !== 0) throw TypeError("Illegal value: "+value+" (not an integer)"); value >>>= 0; if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } offset += 4; var capacity5 = this.buffer.byteLength; if (offset > capacity5) this.resize((capacity5 *= 2) > offset ? capacity5 : offset); offset -= 4; if (this.littleEndian) { this.view[offset+3] = (value >>> 24) & 0xFF; this.view[offset+2] = (value >>> 16) & 0xFF; this.view[offset+1] = (value >>> 8) & 0xFF; this.view[offset ] = value & 0xFF; } else { this.view[offset ] = (value >>> 24) & 0xFF; this.view[offset+1] = (value >>> 16) & 0xFF; this.view[offset+2] = (value >>> 8) & 0xFF; this.view[offset+3] = value & 0xFF; } if (relative) this.offset += 4; return this; }; /** * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}. * @function * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @expose */ ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32; /** * Reads a 32bit unsigned integer. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @returns {number} Value read * @expose */ ByteBufferPrototype.readUint32 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 4 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength); } var value = 0; if (this.littleEndian) { value = this.view[offset+2] << 16; value |= this.view[offset+1] << 8; value |= this.view[offset ]; value += this.view[offset+3] << 24 >>> 0; } else { value = this.view[offset+1] << 16; value |= this.view[offset+2] << 8; value |= this.view[offset+3]; value += this.view[offset ] << 24 >>> 0; } if (relative) this.offset += 4; return value; }; /** * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}. * @function * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @returns {number} Value read * @expose */ ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32; // types/ints/int64 if (Long) { /** * Writes a 64bit signed integer. * @param {number|!Long} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeInt64 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value === 'number') value = Long.fromNumber(value); else if (typeof value === 'string') value = Long.fromString(value); else if (!(value && value instanceof Long)) throw TypeError("Illegal value: "+value+" (not an integer or Long)"); if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } if (typeof value === 'number') value = Long.fromNumber(value); else if (typeof value === 'string') value = Long.fromString(value); offset += 8; var capacity6 = this.buffer.byteLength; if (offset > capacity6) this.resize((capacity6 *= 2) > offset ? capacity6 : offset); offset -= 8; var lo = value.low, hi = value.high; if (this.littleEndian) { this.view[offset+3] = (lo >>> 24) & 0xFF; this.view[offset+2] = (lo >>> 16) & 0xFF; this.view[offset+1] = (lo >>> 8) & 0xFF; this.view[offset ] = lo & 0xFF; offset += 4; this.view[offset+3] = (hi >>> 24) & 0xFF; this.view[offset+2] = (hi >>> 16) & 0xFF; this.view[offset+1] = (hi >>> 8) & 0xFF; this.view[offset ] = hi & 0xFF; } else { this.view[offset ] = (hi >>> 24) & 0xFF; this.view[offset+1] = (hi >>> 16) & 0xFF; this.view[offset+2] = (hi >>> 8) & 0xFF; this.view[offset+3] = hi & 0xFF; offset += 4; this.view[offset ] = (lo >>> 24) & 0xFF; this.view[offset+1] = (lo >>> 16) & 0xFF; this.view[offset+2] = (lo >>> 8) & 0xFF; this.view[offset+3] = lo & 0xFF; } if (relative) this.offset += 8; return this; }; /** * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}. * @param {number|!Long} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64; /** * Reads a 64bit signed integer. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {!Long} * @expose */ ByteBufferPrototype.readInt64 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 8 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength); } var lo = 0, hi = 0; if (this.littleEndian) { lo = this.view[offset+2] << 16; lo |= this.view[offset+1] << 8; lo |= this.view[offset ]; lo += this.view[offset+3] << 24 >>> 0; offset += 4; hi = this.view[offset+2] << 16; hi |= this.view[offset+1] << 8; hi |= this.view[offset ]; hi += this.view[offset+3] << 24 >>> 0; } else { hi = this.view[offset+1] << 16; hi |= this.view[offset+2] << 8; hi |= this.view[offset+3]; hi += this.view[offset ] << 24 >>> 0; offset += 4; lo = this.view[offset+1] << 16; lo |= this.view[offset+2] << 8; lo |= this.view[offset+3]; lo += this.view[offset ] << 24 >>> 0; } var value = new Long(lo, hi, false); if (relative) this.offset += 8; return value; }; /** * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {!Long} * @expose */ ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64; /** * Writes a 64bit unsigned integer. * @param {number|!Long} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeUint64 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value === 'number') value = Long.fromNumber(value); else if (typeof value === 'string') value = Long.fromString(value); else if (!(value && value instanceof Long)) throw TypeError("Illegal value: "+value+" (not an integer or Long)"); if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } if (typeof value === 'number') value = Long.fromNumber(value); else if (typeof value === 'string') value = Long.fromString(value); offset += 8; var capacity7 = this.buffer.byteLength; if (offset > capacity7) this.resize((capacity7 *= 2) > offset ? capacity7 : offset); offset -= 8; var lo = value.low, hi = value.high; if (this.littleEndian) { this.view[offset+3] = (lo >>> 24) & 0xFF; this.view[offset+2] = (lo >>> 16) & 0xFF; this.view[offset+1] = (lo >>> 8) & 0xFF; this.view[offset ] = lo & 0xFF; offset += 4; this.view[offset+3] = (hi >>> 24) & 0xFF; this.view[offset+2] = (hi >>> 16) & 0xFF; this.view[offset+1] = (hi >>> 8) & 0xFF; this.view[offset ] = hi & 0xFF; } else { this.view[offset ] = (hi >>> 24) & 0xFF; this.view[offset+1] = (hi >>> 16) & 0xFF; this.view[offset+2] = (hi >>> 8) & 0xFF; this.view[offset+3] = hi & 0xFF; offset += 4; this.view[offset ] = (lo >>> 24) & 0xFF; this.view[offset+1] = (lo >>> 16) & 0xFF; this.view[offset+2] = (lo >>> 8) & 0xFF; this.view[offset+3] = lo & 0xFF; } if (relative) this.offset += 8; return this; }; /** * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}. * @function * @param {number|!Long} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64; /** * Reads a 64bit unsigned integer. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {!Long} * @expose */ ByteBufferPrototype.readUint64 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 8 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength); } var lo = 0, hi = 0; if (this.littleEndian) { lo = this.view[offset+2] << 16; lo |= this.view[offset+1] << 8; lo |= this.view[offset ]; lo += this.view[offset+3] << 24 >>> 0; offset += 4; hi = this.view[offset+2] << 16; hi |= this.view[offset+1] << 8; hi |= this.view[offset ]; hi += this.view[offset+3] << 24 >>> 0; } else { hi = this.view[offset+1] << 16; hi |= this.view[offset+2] << 8; hi |= this.view[offset+3]; hi += this.view[offset ] << 24 >>> 0; offset += 4; lo = this.view[offset+1] << 16; lo |= this.view[offset+2] << 8; lo |= this.view[offset+3]; lo += this.view[offset ] << 24 >>> 0; } var value = new Long(lo, hi, true); if (relative) this.offset += 8; return value; }; /** * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}. * @function * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {!Long} * @expose */ ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64; } // Long // types/floats/float32 /* ieee754 - https://github.com/feross/ieee754 The MIT License (MIT) Copyright (c) Feross Aboukhadijeh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. */ /** * Reads an IEEE754 float from a byte array. * @param {!Array} buffer * @param {number} offset * @param {boolean} isLE * @param {number} mLen * @param {number} nBytes * @returns {number} * @inner */ function ieee754_read(buffer, offset, isLE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? (nBytes - 1) : 0, d = isLE ? -1 : 1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); } /** * Writes an IEEE754 float to a byte array. * @param {!Array} buffer * @param {number} value * @param {number} offset * @param {boolean} isLE * @param {number} mLen * @param {number} nBytes * @inner */ function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isLE ? 0 : (nBytes - 1), d = isLE ? 1 : -1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128; } /** * Writes a 32bit float. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeFloat32 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value !== 'number') throw TypeError("Illegal value: "+value+" (not a number)"); if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } offset += 4; var capacity8 = this.buffer.byteLength; if (offset > capacity8) this.resize((capacity8 *= 2) > offset ? capacity8 : offset); offset -= 4; ieee754_write(this.view, value, offset, this.littleEndian, 23, 4); if (relative) this.offset += 4; return this; }; /** * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}. * @function * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32; /** * Reads a 32bit float. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @returns {number} * @expose */ ByteBufferPrototype.readFloat32 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 4 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength); } var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4); if (relative) this.offset += 4; return value; }; /** * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}. * @function * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. * @returns {number} * @expose */ ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32; // types/floats/float64 /** * Writes a 64bit float. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeFloat64 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value !== 'number') throw TypeError("Illegal value: "+value+" (not a number)"); if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } offset += 8; var capacity9 = this.buffer.byteLength; if (offset > capacity9) this.resize((capacity9 *= 2) > offset ? capacity9 : offset); offset -= 8; ieee754_write(this.view, value, offset, this.littleEndian, 52, 8); if (relative) this.offset += 8; return this; }; /** * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}. * @function * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64; /** * Reads a 64bit float. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {number} * @expose */ ByteBufferPrototype.readFloat64 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 8 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength); } var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8); if (relative) this.offset += 8; return value; }; /** * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}. * @function * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. * @returns {number} * @expose */ ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64; // types/varints/varint32 /** * Maximum number of bytes required to store a 32bit base 128 variable-length integer. * @type {number} * @const * @expose */ ByteBuffer.MAX_VARINT32_BYTES = 5; /** * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer. * @param {number} value Value to encode * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES} * @expose */ ByteBuffer.calculateVarint32 = function(value) { // ref: src/google/protobuf/io/coded_stream.cc value = value >>> 0; if (value < 1 << 7 ) return 1; else if (value < 1 << 14) return 2; else if (value < 1 << 21) return 3; else if (value < 1 << 28) return 4; else return 5; }; /** * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding. * @param {number} n Signed 32bit integer * @returns {number} Unsigned zigzag encoded 32bit integer * @expose */ ByteBuffer.zigZagEncode32 = function(n) { return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h }; /** * Decodes a zigzag encoded signed 32bit integer. * @param {number} n Unsigned zigzag encoded 32bit integer * @returns {number} Signed 32bit integer * @expose */ ByteBuffer.zigZagDecode32 = function(n) { return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h }; /** * Writes a 32bit base 128 variable-length integer. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written * @expose */ ByteBufferPrototype.writeVarint32 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value !== 'number' || value % 1 !== 0) throw TypeError("Illegal value: "+value+" (not an integer)"); value |= 0; if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } var size = ByteBuffer.calculateVarint32(value), b; offset += size; var capacity10 = this.buffer.byteLength; if (offset > capacity10) this.resize((capacity10 *= 2) > offset ? capacity10 : offset); offset -= size; value >>>= 0; while (value >= 0x80) { b = (value & 0x7f) | 0x80; this.view[offset++] = b; value >>>= 7; } this.view[offset++] = value; if (relative) { this.offset = offset; return this; } return size; }; /** * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer. * @param {number} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written * @expose */ ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) { return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset); }; /** * Reads a 32bit base 128 variable-length integer. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read * and the actual number of bytes read. * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available * to fully decode the varint. * @expose */ ByteBufferPrototype.readVarint32 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 1 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); } var c = 0, value = 0 >>> 0, b; do { if (!this.noAssert && offset > this.limit) { var err = Error("Truncated"); err['truncated'] = true; throw err; } b = this.view[offset++]; if (c < 5) value |= (b & 0x7f) << (7*c); ++c; } while ((b & 0x80) !== 0); value |= 0; if (relative) { this.offset = offset; return value; } return { "value": value, "length": c }; }; /** * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read * and the actual number of bytes read. * @throws {Error} If it's not a valid varint * @expose */ ByteBufferPrototype.readVarint32ZigZag = function(offset) { var val = this.readVarint32(offset); if (typeof val === 'object') val["value"] = ByteBuffer.zigZagDecode32(val["value"]); else val = ByteBuffer.zigZagDecode32(val); return val; }; // types/varints/varint64 if (Long) { /** * Maximum number of bytes required to store a 64bit base 128 variable-length integer. * @type {number} * @const * @expose */ ByteBuffer.MAX_VARINT64_BYTES = 10; /** * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer. * @param {number|!Long} value Value to encode * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES} * @expose */ ByteBuffer.calculateVarint64 = function(value) { if (typeof value === 'number') value = Long.fromNumber(value); else if (typeof value === 'string') value = Long.fromString(value); // ref: src/google/protobuf/io/coded_stream.cc var part0 = value.toInt() >>> 0, part1 = value.shiftRightUnsigned(28).toInt() >>> 0, part2 = value.shiftRightUnsigned(56).toInt() >>> 0; if (part2 == 0) { if (part1 == 0) { if (part0 < 1 << 14) return part0 < 1 << 7 ? 1 : 2; else return part0 < 1 << 21 ? 3 : 4; } else { if (part1 < 1 << 14) return part1 < 1 << 7 ? 5 : 6; else return part1 < 1 << 21 ? 7 : 8; } } else return part2 < 1 << 7 ? 9 : 10; }; /** * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding. * @param {number|!Long} value Signed long * @returns {!Long} Unsigned zigzag encoded long * @expose */ ByteBuffer.zigZagEncode64 = function(value) { if (typeof value === 'number') value = Long.fromNumber(value, false); else if (typeof value === 'string') value = Long.fromString(value, false); else if (value.unsigned !== false) value = value.toSigned(); // ref: src/google/protobuf/wire_format_lite.h return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned(); }; /** * Decodes a zigzag encoded signed 64bit integer. * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number * @returns {!Long} Signed long * @expose */ ByteBuffer.zigZagDecode64 = function(value) { if (typeof value === 'number') value = Long.fromNumber(value, false); else if (typeof value === 'string') value = Long.fromString(value, false); else if (value.unsigned !== false) value = value.toSigned(); // ref: src/google/protobuf/wire_format_lite.h return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned(); }; /** * Writes a 64bit base 128 variable-length integer. * @param {number|Long} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written. * @expose */ ByteBufferPrototype.writeVarint64 = function(value, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof value === 'number') value = Long.fromNumber(value); else if (typeof value === 'string') value = Long.fromString(value); else if (!(value && value instanceof Long)) throw TypeError("Illegal value: "+value+" (not an integer or Long)"); if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } if (typeof value === 'number') value = Long.fromNumber(value, false); else if (typeof value === 'string') value = Long.fromString(value, false); else if (value.unsigned !== false) value = value.toSigned(); var size = ByteBuffer.calculateVarint64(value), part0 = value.toInt() >>> 0, part1 = value.shiftRightUnsigned(28).toInt() >>> 0, part2 = value.shiftRightUnsigned(56).toInt() >>> 0; offset += size; var capacity11 = this.buffer.byteLength; if (offset > capacity11) this.resize((capacity11 *= 2) > offset ? capacity11 : offset); offset -= size; switch (size) { case 10: this.view[offset+9] = (part2 >>> 7) & 0x01; case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F; case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F; case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F; case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F; case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F; case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F; case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F; case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F; case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F; } if (relative) { this.offset += size; return this; } else { return size; } }; /** * Writes a zig-zag encoded 64bit base 128 variable-length integer. * @param {number|Long} value Value to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written. * @expose */ ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) { return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset); }; /** * Reads a 64bit base 128 variable-length integer. Requires Long.js. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes * read if omitted. * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and * the actual number of bytes read. * @throws {Error} If it's not a valid varint * @expose */ ByteBufferPrototype.readVarint64 = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 1 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); } // ref: src/google/protobuf/io/coded_stream.cc var start = offset, part0 = 0, part1 = 0, part2 = 0, b = 0; b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) { b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { throw Error("Buffer overrun"); }}}}}}}}}} var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false); if (relative) { this.offset = offset; return value; } else { return { 'value': value, 'length': offset-start }; } }; /** * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes * read if omitted. * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and * the actual number of bytes read. * @throws {Error} If it's not a valid varint * @expose */ ByteBufferPrototype.readVarint64ZigZag = function(offset) { var val = this.readVarint64(offset); if (val && val['value'] instanceof Long) val["value"] = ByteBuffer.zigZagDecode64(val["value"]); else val = ByteBuffer.zigZagDecode64(val); return val; }; } // Long // types/strings/cstring /** * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL * characters itself. * @param {string} str String to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes * contained in `str` + 1 if omitted. * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written * @expose */ ByteBufferPrototype.writeCString = function(str, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; var i, k = str.length; if (!this.noAssert) { if (typeof str !== 'string') throw TypeError("Illegal str: Not a string"); for (i=0; i>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } // UTF8 strings do not contain zero bytes in between except for the zero character, so: k = utfx.calculateUTF16asUTF8(stringSource(str))[1]; offset += k+1; var capacity12 = this.buffer.byteLength; if (offset > capacity12) this.resize((capacity12 *= 2) > offset ? capacity12 : offset); offset -= k+1; utfx.encodeUTF16toUTF8(stringSource(str), function(b) { this.view[offset++] = b; }.bind(this)); this.view[offset++] = 0; if (relative) { this.offset = offset; return this; } return k; }; /** * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters * itself. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes * read if omitted. * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string * read and the actual number of bytes read. * @expose */ ByteBufferPrototype.readCString = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 1 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); } var start = offset, temp; // UTF8 strings do not contain zero bytes in between except for the zero character itself, so: var sd, b = -1; utfx.decodeUTF8toUTF16(function() { if (b === 0) return null; if (offset >= this.limit) throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit); b = this.view[offset++]; return b === 0 ? null : b; }.bind(this), sd = stringDestination(), true); if (relative) { this.offset = offset; return sd(); } else { return { "string": sd(), "length": offset - start }; } }; // types/strings/istring /** * Writes a length as uint32 prefixed UTF8 encoded string. * @param {string} str String to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written * @expose * @see ByteBuffer#writeVarint32 */ ByteBufferPrototype.writeIString = function(str, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof str !== 'string') throw TypeError("Illegal str: Not a string"); if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } var start = offset, k; k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1]; offset += 4+k; var capacity13 = this.buffer.byteLength; if (offset > capacity13) this.resize((capacity13 *= 2) > offset ? capacity13 : offset); offset -= 4+k; if (this.littleEndian) { this.view[offset+3] = (k >>> 24) & 0xFF; this.view[offset+2] = (k >>> 16) & 0xFF; this.view[offset+1] = (k >>> 8) & 0xFF; this.view[offset ] = k & 0xFF; } else { this.view[offset ] = (k >>> 24) & 0xFF; this.view[offset+1] = (k >>> 16) & 0xFF; this.view[offset+2] = (k >>> 8) & 0xFF; this.view[offset+3] = k & 0xFF; } offset += 4; utfx.encodeUTF16toUTF8(stringSource(str), function(b) { this.view[offset++] = b; }.bind(this)); if (offset !== start + 4 + k) throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k)); if (relative) { this.offset = offset; return this; } return offset - start; }; /** * Reads a length as uint32 prefixed UTF8 encoded string. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes * read if omitted. * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string * read and the actual number of bytes read. * @expose * @see ByteBuffer#readVarint32 */ ByteBufferPrototype.readIString = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 4 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength); } var start = offset; var len = this.readUint32(offset); var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4); offset += str['length']; if (relative) { this.offset = offset; return str['string']; } else { return { 'string': str['string'], 'length': offset - start }; } }; // types/strings/utf8string /** * Metrics representing number of UTF8 characters. Evaluates to `c`. * @type {string} * @const * @expose */ ByteBuffer.METRICS_CHARS = 'c'; /** * Metrics representing number of bytes. Evaluates to `b`. * @type {string} * @const * @expose */ ByteBuffer.METRICS_BYTES = 'b'; /** * Writes an UTF8 encoded string. * @param {string} str String to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted. * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written. * @expose */ ByteBufferPrototype.writeUTF8String = function(str, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } var k; var start = offset; k = utfx.calculateUTF16asUTF8(stringSource(str))[1]; offset += k; var capacity14 = this.buffer.byteLength; if (offset > capacity14) this.resize((capacity14 *= 2) > offset ? capacity14 : offset); offset -= k; utfx.encodeUTF16toUTF8(stringSource(str), function(b) { this.view[offset++] = b; }.bind(this)); if (relative) { this.offset = offset; return this; } return offset - start; }; /** * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}. * @function * @param {string} str String to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted. * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written. * @expose */ ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String; /** * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF. * @param {string} str String to calculate * @returns {number} Number of UTF8 characters * @expose */ ByteBuffer.calculateUTF8Chars = function(str) { return utfx.calculateUTF16asUTF8(stringSource(str))[0]; }; /** * Calculates the number of UTF8 bytes of a string. * @param {string} str String to calculate * @returns {number} Number of UTF8 bytes * @expose */ ByteBuffer.calculateUTF8Bytes = function(str) { return utfx.calculateUTF16asUTF8(stringSource(str))[1]; }; /** * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}. * @function * @param {string} str String to calculate * @returns {number} Number of UTF8 bytes * @expose */ ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes; /** * Reads an UTF8 encoded string. * @param {number} length Number of characters or bytes to read. * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to * {@link ByteBuffer.METRICS_CHARS}. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes * read if omitted. * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string * read and the actual number of bytes read. * @expose */ ByteBufferPrototype.readUTF8String = function(length, metrics, offset) { if (typeof metrics === 'number') { offset = metrics; metrics = undefined; } var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS; if (!this.noAssert) { if (typeof length !== 'number' || length % 1 !== 0) throw TypeError("Illegal length: "+length+" (not an integer)"); length |= 0; if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } var i = 0, start = offset, sd; if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser sd = stringDestination(); utfx.decodeUTF8(function() { return i < length && offset < this.limit ? this.view[offset++] : null; }.bind(this), function(cp) { ++i; utfx.UTF8toUTF16(cp, sd); }); if (i !== length) throw RangeError("Illegal range: Truncated data, "+i+" == "+length); if (relative) { this.offset = offset; return sd(); } else { return { "string": sd(), "length": offset - start }; } } else if (metrics === ByteBuffer.METRICS_BYTES) { if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + length > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength); } var k = offset + length; utfx.decodeUTF8toUTF16(function() { return offset < k ? this.view[offset++] : null; }.bind(this), sd = stringDestination(), this.noAssert); if (offset !== k) throw RangeError("Illegal range: Truncated data, "+offset+" == "+k); if (relative) { this.offset = offset; return sd(); } else { return { 'string': sd(), 'length': offset - start }; } } else throw TypeError("Unsupported metrics: "+metrics); }; /** * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}. * @function * @param {number} length Number of characters or bytes to read * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to * {@link ByteBuffer.METRICS_CHARS}. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes * read if omitted. * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string * read and the actual number of bytes read. * @expose */ ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String; // types/strings/vstring /** * Writes a length as varint32 prefixed UTF8 encoded string. * @param {string} str String to write * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written * @expose * @see ByteBuffer#writeVarint32 */ ByteBufferPrototype.writeVString = function(str, offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof str !== 'string') throw TypeError("Illegal str: Not a string"); if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } var start = offset, k, l; k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1]; l = ByteBuffer.calculateVarint32(k); offset += l+k; var capacity15 = this.buffer.byteLength; if (offset > capacity15) this.resize((capacity15 *= 2) > offset ? capacity15 : offset); offset -= l+k; offset += this.writeVarint32(k, offset); utfx.encodeUTF16toUTF8(stringSource(str), function(b) { this.view[offset++] = b; }.bind(this)); if (offset !== start+k+l) throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l)); if (relative) { this.offset = offset; return this; } return offset - start; }; /** * Reads a length as varint32 prefixed UTF8 encoded string. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes * read if omitted. * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string * read and the actual number of bytes read. * @expose * @see ByteBuffer#readVarint32 */ ByteBufferPrototype.readVString = function(offset) { var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 1 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); } var start = offset; var len = this.readVarint32(offset); var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']); offset += str['length']; if (relative) { this.offset = offset; return str['string']; } else { return { 'string': str['string'], 'length': offset - start }; } }; /** * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended * data's length. * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets * will be modified according to the performed read operation. * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8") * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. * @returns {!ByteBuffer} this * @expose * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|` * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|` */ ByteBufferPrototype.append = function(source, encoding, offset) { if (typeof encoding === 'number' || typeof encoding !== 'string') { offset = encoding; encoding = undefined; } var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } if (!(source instanceof ByteBuffer)) source = ByteBuffer.wrap(source, encoding); var length = source.limit - source.offset; if (length <= 0) return this; // Nothing to append offset += length; var capacity16 = this.buffer.byteLength; if (offset > capacity16) this.resize((capacity16 *= 2) > offset ? capacity16 : offset); offset -= length; this.view.set(source.view.subarray(source.offset, source.limit), offset); source.offset += length; if (relative) this.offset += length; return this; }; /** * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the specified offset up to the length of this ByteBuffer's data. * @param {!ByteBuffer} target Target ByteBuffer * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes * read if omitted. * @returns {!ByteBuffer} this * @expose * @see ByteBuffer#append */ ByteBufferPrototype.appendTo = function(target, offset) { target.append(this, offset); return this; }; /** * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to * disable them if your code already makes sure that everything is valid. * @param {boolean} assert `true` to enable assertions, otherwise `false` * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.assert = function(assert) { this.noAssert = !assert; return this; }; /** * Gets the capacity of this ByteBuffer's backing buffer. * @returns {number} Capacity of the backing buffer * @expose */ ByteBufferPrototype.capacity = function() { return this.buffer.byteLength; }; /** * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.clear = function() { this.offset = 0; this.limit = this.buffer.byteLength; this.markedOffset = -1; return this; }; /** * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset}, * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}. * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false` * @returns {!ByteBuffer} Cloned instance * @expose */ ByteBufferPrototype.clone = function(copy) { var bb = new ByteBuffer(0, this.littleEndian, this.noAssert); if (copy) { bb.buffer = new ArrayBuffer(this.buffer.byteLength); bb.view = new Uint8Array(bb.buffer); } else { bb.buffer = this.buffer; bb.view = this.view; } bb.offset = this.offset; bb.markedOffset = this.markedOffset; bb.limit = this.limit; return bb; }; /** * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and * adapt {@link ByteBuffer#markedOffset} to the same relative position if set. * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset} * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit} * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.compact = function(begin, end) { if (typeof begin === 'undefined') begin = this.offset; if (typeof end === 'undefined') end = this.limit; if (!this.noAssert) { if (typeof begin !== 'number' || begin % 1 !== 0) throw TypeError("Illegal begin: Not an integer"); begin >>>= 0; if (typeof end !== 'number' || end % 1 !== 0) throw TypeError("Illegal end: Not an integer"); end >>>= 0; if (begin < 0 || begin > end || end > this.buffer.byteLength) throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); } if (begin === 0 && end === this.buffer.byteLength) return this; // Already compacted var len = end - begin; if (len === 0) { this.buffer = EMPTY_BUFFER; this.view = null; if (this.markedOffset >= 0) this.markedOffset -= begin; this.offset = 0; this.limit = 0; return this; } var buffer = new ArrayBuffer(len); var view = new Uint8Array(buffer); view.set(this.view.subarray(begin, end)); this.buffer = buffer; this.view = view; if (this.markedOffset >= 0) this.markedOffset -= begin; this.offset = 0; this.limit = len; return this; }; /** * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and * {@link ByteBuffer#limit}. * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}. * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}. * @returns {!ByteBuffer} Copy * @expose */ ByteBufferPrototype.copy = function(begin, end) { if (typeof begin === 'undefined') begin = this.offset; if (typeof end === 'undefined') end = this.limit; if (!this.noAssert) { if (typeof begin !== 'number' || begin % 1 !== 0) throw TypeError("Illegal begin: Not an integer"); begin >>>= 0; if (typeof end !== 'number' || end % 1 !== 0) throw TypeError("Illegal end: Not an integer"); end >>>= 0; if (begin < 0 || begin > end || end > this.buffer.byteLength) throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); } if (begin === end) return new ByteBuffer(0, this.littleEndian, this.noAssert); var capacity = end - begin, bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert); bb.offset = 0; bb.limit = capacity; if (bb.markedOffset >= 0) bb.markedOffset -= begin; this.copyTo(bb, 0, begin, end); return bb; }; /** * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and * {@link ByteBuffer#limit}. * @param {!ByteBuffer} target Target ByteBuffer * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset} * by the number of bytes copied if omitted. * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the * number of bytes copied if omitted. * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit} * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) { var relative, targetRelative; if (!this.noAssert) { if (!ByteBuffer.isByteBuffer(target)) throw TypeError("Illegal target: Not a ByteBuffer"); } targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0; sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0; sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0; if (targetOffset < 0 || targetOffset > target.buffer.byteLength) throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength); if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength) throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength); var len = sourceLimit - sourceOffset; if (len === 0) return target; // Nothing to copy target.ensureCapacity(targetOffset + len); target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset); if (relative) this.offset += len; if (targetRelative) target.offset += len; return this; }; /** * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity, * the required capacity will be used instead. * @param {number} capacity Required capacity * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.ensureCapacity = function(capacity) { var current = this.buffer.byteLength; if (current < capacity) return this.resize((current *= 2) > capacity ? current : capacity); return this; }; /** * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. * @param {number|string} value Byte value to fill with. If given as a string, the first character is used. * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes * written if omitted. defaults to {@link ByteBuffer#offset}. * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}. * @returns {!ByteBuffer} this * @expose * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes */ ByteBufferPrototype.fill = function(value, begin, end) { var relative = typeof begin === 'undefined'; if (relative) begin = this.offset; if (typeof value === 'string' && value.length > 0) value = value.charCodeAt(0); if (typeof begin === 'undefined') begin = this.offset; if (typeof end === 'undefined') end = this.limit; if (!this.noAssert) { if (typeof value !== 'number' || value % 1 !== 0) throw TypeError("Illegal value: "+value+" (not an integer)"); value |= 0; if (typeof begin !== 'number' || begin % 1 !== 0) throw TypeError("Illegal begin: Not an integer"); begin >>>= 0; if (typeof end !== 'number' || end % 1 !== 0) throw TypeError("Illegal end: Not an integer"); end >>>= 0; if (begin < 0 || begin > end || end > this.buffer.byteLength) throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); } if (begin >= end) return this; // Nothing to fill while (begin < end) this.view[begin++] = value; if (relative) this.offset = begin; return this; }; /** * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.flip = function() { this.limit = this.offset; this.offset = 0; return this; }; /** * Marks an offset on this ByteBuffer to be used later. * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}. * @returns {!ByteBuffer} this * @throws {TypeError} If `offset` is not a valid number * @throws {RangeError} If `offset` is out of bounds * @see ByteBuffer#reset * @expose */ ByteBufferPrototype.mark = function(offset) { offset = typeof offset === 'undefined' ? this.offset : offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } this.markedOffset = offset; return this; }; /** * Sets the byte order. * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.order = function(littleEndian) { if (!this.noAssert) { if (typeof littleEndian !== 'boolean') throw TypeError("Illegal littleEndian: Not a boolean"); } this.littleEndian = !!littleEndian; return this; }; /** * Switches (to) little endian byte order. * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.LE = function(littleEndian) { this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true; return this; }; /** * Switches (to) big endian byte order. * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.BE = function(bigEndian) { this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false; return this; }; /** * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer * will be resized and its contents moved accordingly. * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be * modified according to the performed read operation. * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8") * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes * prepended if omitted. * @returns {!ByteBuffer} this * @expose * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|` * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|` */ ByteBufferPrototype.prepend = function(source, encoding, offset) { if (typeof encoding === 'number' || typeof encoding !== 'string') { offset = encoding; encoding = undefined; } var relative = typeof offset === 'undefined'; if (relative) offset = this.offset; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset >>>= 0; if (offset < 0 || offset + 0 > this.buffer.byteLength) throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); } if (!(source instanceof ByteBuffer)) source = ByteBuffer.wrap(source, encoding); var len = source.limit - source.offset; if (len <= 0) return this; // Nothing to prepend var diff = len - offset; if (diff > 0) { // Not enough space before offset, so resize + move var buffer = new ArrayBuffer(this.buffer.byteLength + diff); var view = new Uint8Array(buffer); view.set(this.view.subarray(offset, this.buffer.byteLength), len); this.buffer = buffer; this.view = view; this.offset += diff; if (this.markedOffset >= 0) this.markedOffset += diff; this.limit += diff; offset += diff; } else { var arrayView = new Uint8Array(this.buffer); } this.view.set(source.view.subarray(source.offset, source.limit), offset - len); source.offset = source.limit; if (relative) this.offset -= len; return this; }; /** * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer * will be resized and its contents moved accordingly. * @param {!ByteBuffer} target Target ByteBuffer * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes * prepended if omitted. * @returns {!ByteBuffer} this * @expose * @see ByteBuffer#prepend */ ByteBufferPrototype.prependTo = function(target, offset) { target.prepend(this, offset); return this; }; /** * Prints debug information about this ByteBuffer's contents. * @param {function(string)=} out Output function to call, defaults to console.log * @expose */ ByteBufferPrototype.printDebug = function(out) { if (typeof out !== 'function') out = console.log.bind(console); out( this.toString()+"\n"+ "-------------------------------------------------------------------\n"+ this.toDebug(/* columns */ true) ); }; /** * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and * {@link ByteBuffer#limit}, so this returns `limit - offset`. * @returns {number} Remaining readable bytes. May be negative if `offset > limit`. * @expose */ ByteBufferPrototype.remaining = function() { return this.limit - this.offset; }; /** * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark} * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been * marked, sets `offset = 0`. * @returns {!ByteBuffer} this * @see ByteBuffer#mark * @expose */ ByteBufferPrototype.reset = function() { if (this.markedOffset >= 0) { this.offset = this.markedOffset; this.markedOffset = -1; } else { this.offset = 0; } return this; }; /** * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that * large or larger. * @param {number} capacity Capacity required * @returns {!ByteBuffer} this * @throws {TypeError} If `capacity` is not a number * @throws {RangeError} If `capacity < 0` * @expose */ ByteBufferPrototype.resize = function(capacity) { if (!this.noAssert) { if (typeof capacity !== 'number' || capacity % 1 !== 0) throw TypeError("Illegal capacity: "+capacity+" (not an integer)"); capacity |= 0; if (capacity < 0) throw RangeError("Illegal capacity: 0 <= "+capacity); } if (this.buffer.byteLength < capacity) { var buffer = new ArrayBuffer(capacity); var view = new Uint8Array(buffer); view.set(this.view); this.buffer = buffer; this.view = view; } return this; }; /** * Reverses this ByteBuffer's contents. * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset} * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit} * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.reverse = function(begin, end) { if (typeof begin === 'undefined') begin = this.offset; if (typeof end === 'undefined') end = this.limit; if (!this.noAssert) { if (typeof begin !== 'number' || begin % 1 !== 0) throw TypeError("Illegal begin: Not an integer"); begin >>>= 0; if (typeof end !== 'number' || end % 1 !== 0) throw TypeError("Illegal end: Not an integer"); end >>>= 0; if (begin < 0 || begin > end || end > this.buffer.byteLength) throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); } if (begin === end) return this; // Nothing to reverse Array.prototype.reverse.call(this.view.subarray(begin, end)); return this; }; /** * Skips the next `length` bytes. This will just advance * @param {number} length Number of bytes to skip. May also be negative to move the offset back. * @returns {!ByteBuffer} this * @expose */ ByteBufferPrototype.skip = function(length) { if (!this.noAssert) { if (typeof length !== 'number' || length % 1 !== 0) throw TypeError("Illegal length: "+length+" (not an integer)"); length |= 0; } var offset = this.offset + length; if (!this.noAssert) { if (offset < 0 || offset > this.buffer.byteLength) throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength); } this.offset = offset; return this; }; /** * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`. * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}. * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}. * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer} * @expose */ ByteBufferPrototype.slice = function(begin, end) { if (typeof begin === 'undefined') begin = this.offset; if (typeof end === 'undefined') end = this.limit; if (!this.noAssert) { if (typeof begin !== 'number' || begin % 1 !== 0) throw TypeError("Illegal begin: Not an integer"); begin >>>= 0; if (typeof end !== 'number' || end % 1 !== 0) throw TypeError("Illegal end: Not an integer"); end >>>= 0; if (begin < 0 || begin > end || end > this.buffer.byteLength) throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); } var bb = this.clone(); bb.offset = begin; bb.limit = end; return bb; }; /** * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if * possible. Defaults to `false` * @returns {!ArrayBuffer} Contents as an ArrayBuffer * @expose */ ByteBufferPrototype.toBuffer = function(forceCopy) { var offset = this.offset, limit = this.limit; if (!this.noAssert) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: Not an integer"); offset >>>= 0; if (typeof limit !== 'number' || limit % 1 !== 0) throw TypeError("Illegal limit: Not an integer"); limit >>>= 0; if (offset < 0 || offset > limit || limit > this.buffer.byteLength) throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength); } // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So: if (!forceCopy && offset === 0 && limit === this.buffer.byteLength) return this.buffer; if (offset === limit) return EMPTY_BUFFER; var buffer = new ArrayBuffer(limit - offset); new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0); return buffer; }; /** * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}. * @function * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory. * Defaults to `false` * @returns {!ArrayBuffer} Contents as an ArrayBuffer * @expose */ ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer; /** * Converts the ByteBuffer's contents to a string. * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with * highlighted offsets. * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset} * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit} * @returns {string} String representation * @throws {Error} If `encoding` is invalid * @expose */ ByteBufferPrototype.toString = function(encoding, begin, end) { if (typeof encoding === 'undefined') return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")"; if (typeof encoding === 'number') encoding = "utf8", begin = encoding, end = begin; switch (encoding) { case "utf8": return this.toUTF8(begin, end); case "base64": return this.toBase64(begin, end); case "hex": return this.toHex(begin, end); case "binary": return this.toBinary(begin, end); case "debug": return this.toDebug(); case "columns": return this.toColumns(); default: throw Error("Unsupported encoding: "+encoding); } }; // lxiv-embeddable /** * lxiv-embeddable (c) 2014 Daniel Wirtz * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/lxiv for details */ var lxiv = function() { "use strict"; /** * lxiv namespace. * @type {!Object.} * @exports lxiv */ var lxiv = {}; /** * Character codes for output. * @type {!Array.} * @inner */ var aout = [ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47 ]; /** * Character codes for input. * @type {!Array.} * @inner */ var ain = []; for (var i=0, k=aout.length; i>2)&0x3f]); t = (b&0x3)<<4; if ((b = src()) !== null) { t |= (b>>4)&0xf; dst(aout[(t|((b>>4)&0xf))&0x3f]); t = (b&0xf)<<2; if ((b = src()) !== null) dst(aout[(t|((b>>6)&0x3))&0x3f]), dst(aout[b&0x3f]); else dst(aout[t&0x3f]), dst(61); } else dst(aout[t&0x3f]), dst(61), dst(61); } }; /** * Decodes base64 char codes to bytes. * @param {!function():number|null} src Characters source as a function returning the next char code respectively * `null` if there are no more characters left. * @param {!function(number)} dst Bytes destination as a function successively called with the next byte. * @throws {Error} If a character code is invalid */ lxiv.decode = function(src, dst) { var c, t1, t2; function fail(c) { throw Error("Illegal character code: "+c); } while ((c = src()) !== null) { t1 = ain[c]; if (typeof t1 === 'undefined') fail(c); if ((c = src()) !== null) { t2 = ain[c]; if (typeof t2 === 'undefined') fail(c); dst((t1<<2)>>>0|(t2&0x30)>>4); if ((c = src()) !== null) { t1 = ain[c]; if (typeof t1 === 'undefined') if (c === 61) break; else fail(c); dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2); if ((c = src()) !== null) { t2 = ain[c]; if (typeof t2 === 'undefined') if (c === 61) break; else fail(c); dst(((t1&0x3)<<6)>>>0|t2); } } } } }; /** * Tests if a string is valid base64. * @param {string} str String to test * @returns {boolean} `true` if valid, otherwise `false` */ lxiv.test = function(str) { return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str); }; return lxiv; }(); // encodings/base64 /** * Encodes this ByteBuffer's contents to a base64 encoded string. * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}. * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}. * @returns {string} Base64 encoded string * @throws {RangeError} If `begin` or `end` is out of bounds * @expose */ ByteBufferPrototype.toBase64 = function(begin, end) { if (typeof begin === 'undefined') begin = this.offset; if (typeof end === 'undefined') end = this.limit; begin = begin | 0; end = end | 0; if (begin < 0 || end > this.capacity || begin > end) throw RangeError("begin, end"); var sd; lxiv.encode(function() { return begin < end ? this.view[begin++] : null; }.bind(this), sd = stringDestination()); return sd(); }; /** * Decodes a base64 encoded string to a ByteBuffer. * @param {string} str String to decode * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to * {@link ByteBuffer.DEFAULT_ENDIAN}. * @returns {!ByteBuffer} ByteBuffer * @expose */ ByteBuffer.fromBase64 = function(str, littleEndian) { if (typeof str !== 'string') throw TypeError("str"); var bb = new ByteBuffer(str.length/4*3, littleEndian), i = 0; lxiv.decode(stringSource(str), function(b) { bb.view[i++] = b; }); bb.limit = i; return bb; }; /** * Encodes a binary string to base64 like `window.btoa` does. * @param {string} str Binary string * @returns {string} Base64 encoded string * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa * @expose */ ByteBuffer.btoa = function(str) { return ByteBuffer.fromBinary(str).toBase64(); }; /** * Decodes a base64 encoded string to binary like `window.atob` does. * @param {string} b64 Base64 encoded string * @returns {string} Binary string * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob * @expose */ ByteBuffer.atob = function(b64) { return ByteBuffer.fromBase64(b64).toBinary(); }; // encodings/binary /** * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes. * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}. * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}. * @returns {string} Binary encoded string * @throws {RangeError} If `offset > limit` * @expose */ ByteBufferPrototype.toBinary = function(begin, end) { if (typeof begin === 'undefined') begin = this.offset; if (typeof end === 'undefined') end = this.limit; begin |= 0; end |= 0; if (begin < 0 || end > this.capacity() || begin > end) throw RangeError("begin, end"); if (begin === end) return ""; var chars = [], parts = []; while (begin < end) { chars.push(this.view[begin++]); if (chars.length >= 1024) parts.push(String.fromCharCode.apply(String, chars)), chars = []; } return parts.join('') + String.fromCharCode.apply(String, chars); }; /** * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer. * @param {string} str String to decode * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to * {@link ByteBuffer.DEFAULT_ENDIAN}. * @returns {!ByteBuffer} ByteBuffer * @expose */ ByteBuffer.fromBinary = function(str, littleEndian) { if (typeof str !== 'string') throw TypeError("str"); var i = 0, k = str.length, charCode, bb = new ByteBuffer(k, littleEndian); while (i 0xff) throw RangeError("illegal char code: "+charCode); bb.view[i++] = charCode; } bb.limit = k; return bb; }; // encodings/debug /** * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are: * * `<` : offset, * * `'` : markedOffset, * * `>` : limit, * * `|` : offset and limit, * * `[` : offset and markedOffset, * * `]` : markedOffset and limit, * * `!` : offset, markedOffset and limit * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false` * @returns {string|!Array.} Debug string or array of lines if `asArray = true` * @expose * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3` * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4` * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1` * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1` */ ByteBufferPrototype.toDebug = function(columns) { var i = -1, k = this.buffer.byteLength, b, hex = "", asc = "", out = ""; while (i 32 && b < 127 ? String.fromCharCode(b) : '.'; } ++i; if (columns) { if (i > 0 && i % 16 === 0 && i !== k) { while (hex.length < 3*16+3) hex += " "; out += hex+asc+"\n"; hex = asc = ""; } } if (i === this.offset && i === this.limit) hex += i === this.markedOffset ? "!" : "|"; else if (i === this.offset) hex += i === this.markedOffset ? "[" : "<"; else if (i === this.limit) hex += i === this.markedOffset ? "]" : ">"; else hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : ""); } if (columns && hex !== " ") { while (hex.length < 3*16+3) hex += " "; out += hex + asc + "\n"; } return columns ? out : hex; }; /** * Decodes a hex encoded string with marked offsets to a ByteBuffer. * @param {string} str Debug string to decode (not be generated with `columns = true`) * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to * {@link ByteBuffer.DEFAULT_ENDIAN}. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to * {@link ByteBuffer.DEFAULT_NOASSERT}. * @returns {!ByteBuffer} ByteBuffer * @expose * @see ByteBuffer#toDebug */ ByteBuffer.fromDebug = function(str, littleEndian, noAssert) { var k = str.length, bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert); var i = 0, j = 0, ch, b, rs = false, // Require symbol next ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)? fail = false; while (i': if (!noAssert) { if (hl) { fail = true; break; } hl = true; } bb.limit = j; rs = false; break; case "'": if (!noAssert) { if (hm) { fail = true; break; } hm = true; } bb.markedOffset = j; rs = false; break; case ' ': rs = false; break; default: if (!noAssert) { if (rs) { fail = true; break; } } b = parseInt(ch+str.charAt(i++), 16); if (!noAssert) { if (isNaN(b) || b < 0 || b > 255) throw TypeError("Illegal str: Not a debug encoded string"); } bb.view[j++] = b; rs = true; } if (fail) throw TypeError("Illegal str: Invalid symbol at "+i); } if (!noAssert) { if (!ho || !hl) throw TypeError("Illegal str: Missing offset or limit"); if (j>>= 0; if (typeof end !== 'number' || end % 1 !== 0) throw TypeError("Illegal end: Not an integer"); end >>>= 0; if (begin < 0 || begin > end || end > this.buffer.byteLength) throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); } var out = new Array(end - begin), b; while (begin < end) { b = this.view[begin++]; if (b < 0x10) out.push("0", b.toString(16)); else out.push(b.toString(16)); } return out.join(''); }; /** * Decodes a hex encoded string to a ByteBuffer. * @param {string} str String to decode * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to * {@link ByteBuffer.DEFAULT_ENDIAN}. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to * {@link ByteBuffer.DEFAULT_NOASSERT}. * @returns {!ByteBuffer} ByteBuffer * @expose */ ByteBuffer.fromHex = function(str, littleEndian, noAssert) { if (!noAssert) { if (typeof str !== 'string') throw TypeError("Illegal str: Not a string"); if (str.length % 2 !== 0) throw TypeError("Illegal str: Length not a multiple of 2"); } var k = str.length, bb = new ByteBuffer((k / 2) | 0, littleEndian), b; for (var i=0, j=0; i 255) throw TypeError("Illegal str: Contains non-hex characters"); bb.view[j++] = b; } bb.limit = j; return bb; }; // utfx-embeddable /** * utfx-embeddable (c) 2014 Daniel Wirtz * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/utfx for details */ var utfx = function() { "use strict"; /** * utfx namespace. * @inner * @type {!Object.} */ var utfx = {}; /** * Maximum valid code point. * @type {number} * @const */ utfx.MAX_CODEPOINT = 0x10FFFF; /** * Encodes UTF8 code points to UTF8 bytes. * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point * respectively `null` if there are no more code points left or a single numeric code point. * @param {!function(number)} dst Bytes destination as a function successively called with the next byte */ utfx.encodeUTF8 = function(src, dst) { var cp = null; if (typeof src === 'number') cp = src, src = function() { return null; }; while (cp !== null || (cp = src()) !== null) { if (cp < 0x80) dst(cp&0x7F); else if (cp < 0x800) dst(((cp>>6)&0x1F)|0xC0), dst((cp&0x3F)|0x80); else if (cp < 0x10000) dst(((cp>>12)&0x0F)|0xE0), dst(((cp>>6)&0x3F)|0x80), dst((cp&0x3F)|0x80); else dst(((cp>>18)&0x07)|0xF0), dst(((cp>>12)&0x3F)|0x80), dst(((cp>>6)&0x3F)|0x80), dst((cp&0x3F)|0x80); cp = null; } }; /** * Decodes UTF8 bytes to UTF8 code points. * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there * are no more bytes left. * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point. * @throws {RangeError} If a starting byte is invalid in UTF8 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the * remaining bytes. */ utfx.decodeUTF8 = function(src, dst) { var a, b, c, d, fail = function(b) { b = b.slice(0, b.indexOf(null)); var err = Error(b.toString()); err.name = "TruncatedError"; err['bytes'] = b; throw err; }; while ((a = src()) !== null) { if ((a&0x80) === 0) dst(a); else if ((a&0xE0) === 0xC0) ((b = src()) === null) && fail([a, b]), dst(((a&0x1F)<<6) | (b&0x3F)); else if ((a&0xF0) === 0xE0) ((b=src()) === null || (c=src()) === null) && fail([a, b, c]), dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F)); else if ((a&0xF8) === 0xF0) ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]), dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F)); else throw RangeError("Illegal starting byte: "+a); } }; /** * Converts UTF16 characters to UTF8 code points. * @param {!function():number|null} src Characters source as a function returning the next char code respectively * `null` if there are no more characters left. * @param {!function(number)} dst Code points destination as a function successively called with each converted code * point. */ utfx.UTF16toUTF8 = function(src, dst) { var c1, c2 = null; while (true) { if ((c1 = c2 !== null ? c2 : src()) === null) break; if (c1 >= 0xD800 && c1 <= 0xDFFF) { if ((c2 = src()) !== null) { if (c2 >= 0xDC00 && c2 <= 0xDFFF) { dst((c1-0xD800)*0x400+c2-0xDC00+0x10000); c2 = null; continue; } } } dst(c1); } if (c2 !== null) dst(c2); }; /** * Converts UTF8 code points to UTF16 characters. * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point * respectively `null` if there are no more code points left or a single numeric code point. * @param {!function(number)} dst Characters destination as a function successively called with each converted char code. * @throws {RangeError} If a code point is out of range */ utfx.UTF8toUTF16 = function(src, dst) { var cp = null; if (typeof src === 'number') cp = src, src = function() { return null; }; while (cp !== null || (cp = src()) !== null) { if (cp <= 0xFFFF) dst(cp); else cp -= 0x10000, dst((cp>>10)+0xD800), dst((cp%0x400)+0xDC00); cp = null; } }; /** * Converts and encodes UTF16 characters to UTF8 bytes. * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null` * if there are no more characters left. * @param {!function(number)} dst Bytes destination as a function successively called with the next byte. */ utfx.encodeUTF16toUTF8 = function(src, dst) { utfx.UTF16toUTF8(src, function(cp) { utfx.encodeUTF8(cp, dst); }); }; /** * Decodes and converts UTF8 bytes to UTF16 characters. * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there * are no more bytes left. * @param {!function(number)} dst Characters destination as a function successively called with each converted char code. * @throws {RangeError} If a starting byte is invalid in UTF8 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes. */ utfx.decodeUTF8toUTF16 = function(src, dst) { utfx.decodeUTF8(src, function(cp) { utfx.UTF8toUTF16(cp, dst); }); }; /** * Calculates the byte length of an UTF8 code point. * @param {number} cp UTF8 code point * @returns {number} Byte length */ utfx.calculateCodePoint = function(cp) { return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4; }; /** * Calculates the number of UTF8 bytes required to store UTF8 code points. * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively * `null` if there are no more code points left. * @returns {number} The number of UTF8 bytes required */ utfx.calculateUTF8 = function(src) { var cp, l=0; while ((cp = src()) !== null) l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4; return l; }; /** * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes. * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively * `null` if there are no more characters left. * @returns {!Array.} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1. */ utfx.calculateUTF16asUTF8 = function(src) { var n=0, l=0; utfx.UTF16toUTF8(src, function(cp) { ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4; }); return [n,l]; }; return utfx; }(); // encodings/utf8 /** * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded * string. * @returns {string} Hex encoded string * @throws {RangeError} If `offset > limit` * @expose */ ByteBufferPrototype.toUTF8 = function(begin, end) { if (typeof begin === 'undefined') begin = this.offset; if (typeof end === 'undefined') end = this.limit; if (!this.noAssert) { if (typeof begin !== 'number' || begin % 1 !== 0) throw TypeError("Illegal begin: Not an integer"); begin >>>= 0; if (typeof end !== 'number' || end % 1 !== 0) throw TypeError("Illegal end: Not an integer"); end >>>= 0; if (begin < 0 || begin > end || end > this.buffer.byteLength) throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); } var sd; try { utfx.decodeUTF8toUTF16(function() { return begin < end ? this.view[begin++] : null; }.bind(this), sd = stringDestination()); } catch (e) { if (begin !== end) throw RangeError("Illegal range: Truncated data, "+begin+" != "+end); } return sd(); }; /** * Decodes an UTF8 encoded string to a ByteBuffer. * @param {string} str String to decode * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to * {@link ByteBuffer.DEFAULT_ENDIAN}. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to * {@link ByteBuffer.DEFAULT_NOASSERT}. * @returns {!ByteBuffer} ByteBuffer * @expose */ ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) { if (!noAssert) if (typeof str !== 'string') throw TypeError("Illegal str: Not a string"); var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert), i = 0; utfx.encodeUTF16toUTF8(stringSource(str), function(b) { bb.view[i++] = b; }); bb.limit = i; return bb; }; return ByteBuffer; }); ================================================ FILE: public/libs/laya/domparserinone.js ================================================ var entityMap = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'", Agrave: "À", Aacute: "Á", Acirc: "Â", Atilde: "Ã", Auml: "Ä", Aring: "Å", AElig: "Æ", Ccedil: "Ç", Egrave: "È", Eacute: "É", Ecirc: "Ê", Euml: "Ë", Igrave: "Ì", Iacute: "Í", Icirc: "Î", Iuml: "Ï", ETH: "Ð", Ntilde: "Ñ", Ograve: "Ò", Oacute: "Ó", Ocirc: "Ô", Otilde: "Õ", Ouml: "Ö", Oslash: "Ø", Ugrave: "Ù", Uacute: "Ú", Ucirc: "Û", Uuml: "Ü", Yacute: "Ý", THORN: "Þ", szlig: "ß", agrave: "à", aacute: "á", acirc: "â", atilde: "ã", auml: "ä", aring: "å", aelig: "æ", ccedil: "ç", egrave: "è", eacute: "é", ecirc: "ê", euml: "ë", igrave: "ì", iacute: "í", icirc: "î", iuml: "ï", eth: "ð", ntilde: "ñ", ograve: "ò", oacute: "ó", ocirc: "ô", otilde: "õ", ouml: "ö", oslash: "ø", ugrave: "ù", uacute: "ú", ucirc: "û", uuml: "ü", yacute: "ý", thorn: "þ", yuml: "ÿ", nbsp: " ", iexcl: "¡", cent: "¢", pound: "£", curren: "¤", yen: "¥", brvbar: "¦", sect: "§", uml: "¨", copy: "©", ordf: "ª", laquo: "«", not: "¬", shy: "­­", reg: "®", macr: "¯", deg: "°", plusmn: "±", sup2: "²", sup3: "³", acute: "´", micro: "µ", para: "¶", middot: "·", cedil: "¸", sup1: "¹", ordm: "º", raquo: "»", frac14: "¼", frac12: "½", frac34: "¾", iquest: "¿", times: "×", divide: "÷", forall: "∀", part: "∂", exist: "∃", empty: "∅", nabla: "∇", isin: "∈", notin: "∉", ni: "∋", prod: "∏", sum: "∑", minus: "−", lowast: "∗", radic: "√", prop: "∝", infin: "∞", ang: "∠", and: "∧", or: "∨", cap: "∩", cup: "∪", 'int': "∫", there4: "∴", sim: "∼", cong: "≅", asymp: "≈", ne: "≠", equiv: "≡", le: "≤", ge: "≥", sub: "⊂", sup: "⊃", nsub: "⊄", sube: "⊆", supe: "⊇", oplus: "⊕", otimes: "⊗", perp: "⊥", sdot: "⋅", Alpha: "Α", Beta: "Β", Gamma: "Γ", Delta: "Δ", Epsilon: "Ε", Zeta: "Ζ", Eta: "Η", Theta: "Θ", Iota: "Ι", Kappa: "Κ", Lambda: "Λ", Mu: "Μ", Nu: "Ν", Xi: "Ξ", Omicron: "Ο", Pi: "Π", Rho: "Ρ", Sigma: "Σ", Tau: "Τ", Upsilon: "Υ", Phi: "Φ", Chi: "Χ", Psi: "Ψ", Omega: "Ω", alpha: "α", beta: "β", gamma: "γ", delta: "δ", epsilon: "ε", zeta: "ζ", eta: "η", theta: "θ", iota: "ι", kappa: "κ", lambda: "λ", mu: "μ", nu: "ν", xi: "ξ", omicron: "ο", pi: "π", rho: "ρ", sigmaf: "ς", sigma: "σ", tau: "τ", upsilon: "υ", phi: "φ", chi: "χ", psi: "ψ", omega: "ω", thetasym: "ϑ", upsih: "ϒ", piv: "ϖ", OElig: "Œ", oelig: "œ", Scaron: "Š", scaron: "š", Yuml: "Ÿ", fnof: "ƒ", circ: "ˆ", tilde: "˜", ensp: " ", emsp: " ", thinsp: " ", zwnj: "‌", zwj: "‍", lrm: "‎", rlm: "‏", ndash: "–", mdash: "—", lsquo: "‘", rsquo: "’", sbquo: "‚", ldquo: "“", rdquo: "”", bdquo: "„", dagger: "†", Dagger: "‡", bull: "•", hellip: "…", permil: "‰", prime: "′", Prime: "″", lsaquo: "‹", rsaquo: "›", oline: "‾", euro: "€", trade: "™", larr: "←", uarr: "↑", rarr: "→", darr: "↓", harr: "↔", crarr: "↵", lceil: "⌈", rceil: "⌉", lfloor: "⌊", rfloor: "⌋", loz: "◊", spades: "♠", clubs: "♣", hearts: "♥", diams: "♦" }; //for(var n in exports.entityMap){console.log(exports.entityMap[n].charCodeAt())} //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] //[5] Name ::= NameStartChar (NameChar)* var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"); var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/ //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE var S_TAG = 0;//tag name offerring var S_ATTR = 1;//attr name offerring var S_ATTR_SPACE=2;//attr name end and space offer var S_EQ = 3;//=space? var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only) var S_ATTR_END = 5;//attr value end and no space(quot end) var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) var S_TAG_CLOSE = 7;//closed el SaxO={}; function XMLReader(){ } XMLReader.prototype = { parse:function(source,defaultNSMap,entityMap){ var domBuilder = this.domBuilder; domBuilder.startDocument(); _copy(defaultNSMap ,defaultNSMap = {}) parse(source,defaultNSMap,entityMap, domBuilder,this.errorHandler); domBuilder.endDocument(); } } function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ function fixedFromCharCode(code) { // String.prototype.fromCharCode does not supports // > 2 bytes unicode chars directly if (code > 0xffff) { code -= 0x10000; var surrogate1 = 0xd800 + (code >> 10) , surrogate2 = 0xdc00 + (code & 0x3ff); return String.fromCharCode(surrogate1, surrogate2); } else { return String.fromCharCode(code); } } function entityReplacer(a){ var k = a.slice(1,-1); if(k in entityMap){ return entityMap[k]; }else if(k.charAt(0) === '#'){ return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) }else{ errorHandler.error('entity not found:'+a); return a; } } function appendText(end){//has some bugs if(end>start){ var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); locator&&position(start); domBuilder.characters(xt,0,end-start); start = end } } function position(p,m){ while(p>=lineEnd && (m = linePattern.exec(source))){ lineStart = m.index; lineEnd = lineStart + m[0].length; locator.lineNumber++; //console.log('line++:',locator,startPos,endPos) } locator.columnNumber = p-lineStart+1; } var lineStart = 0; var lineEnd = 0; var linePattern = /.*(?:\r\n?|\n)|.*$/g var locator = domBuilder.locator; var parseStack = [{currentNSMap:defaultNSMapCopy}] var closeMap = {}; var start = 0; while(true){ try{ var tagStart = source.indexOf('<',start); if(tagStart<0){ if(!source.substr(start).match(/^\s*$/)){ var doc = domBuilder.doc; var text = doc.createTextNode(source.substr(start)); doc.appendChild(text); domBuilder.currentElement = text; } return; } if(tagStart>start){ appendText(tagStart); } switch(source.charAt(tagStart+1)){ case '/': var end = source.indexOf('>',tagStart+3); var tagName = source.substring(tagStart+2,end); var config = parseStack.pop(); if(end<0){ tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); //console.error('#@@@@@@'+tagName) errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); end = tagStart+1+tagName.length; }else if(tagName.match(/\s locator&&position(tagStart); end = parseInstruction(source,tagStart,domBuilder); break; case '!':// start){ start = end; }else{ //TODO: 这里有可能sax回退,有位置错误风险 appendText(Math.max(tagStart,start)+1); } } } function copyLocator(f,t){ t.lineNumber = f.lineNumber; t.columnNumber = f.columnNumber; return t; } /** * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack); * @return end of the elementStartPart(end of elementEndPart for selfClosed el) */ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ var attrName; var value; var p = ++start; var s = S_TAG;//status while(true){ var c = source.charAt(p); switch(c){ case '=': if(s === S_ATTR){//attrName attrName = source.slice(start,p); s = S_EQ; }else if(s === S_ATTR_SPACE){ s = S_EQ; }else{ //fatalError: equal must after attrName or space after attrName throw new Error('attribute equal must after attrName'); } break; case '\'': case '"': if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE ){//equal if(s === S_ATTR){ errorHandler.warning('attribute value must after "="') attrName = source.slice(start,p) } start = p+1; p = source.indexOf(c,start) if(p>0){ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); el.add(attrName,value,start-1); s = S_ATTR_END; }else{ //fatalError: no end quot match throw new Error('attribute value no end \''+c+'\' match'); } }else if(s == S_ATTR_NOQUOT_VALUE){ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); //console.log(attrName,value,start,p) el.add(attrName,value,start); //console.dir(el) errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); start = p+1; s = S_ATTR_END }else{ //fatalError: no equal before throw new Error('attribute value must after "="'); } break; case '/': switch(s){ case S_TAG: el.setTagName(source.slice(start,p)); case S_ATTR_END: case S_TAG_SPACE: case S_TAG_CLOSE: s =S_TAG_CLOSE; el.closed = true; case S_ATTR_NOQUOT_VALUE: case S_ATTR: case S_ATTR_SPACE: break; //case S_EQ: default: throw new Error("attribute invalid close char('/')") } break; case ''://end document //throw new Error('unexpected end of input') errorHandler.error('unexpected end of input'); if(s == S_TAG){ el.setTagName(source.slice(start,p)); } return p; case '>': switch(s){ case S_TAG: el.setTagName(source.slice(start,p)); case S_ATTR_END: case S_TAG_SPACE: case S_TAG_CLOSE: break;//normal case S_ATTR_NOQUOT_VALUE://Compatible state case S_ATTR: value = source.slice(start,p); if(value.slice(-1) === '/'){ el.closed = true; value = value.slice(0,-1) } case S_ATTR_SPACE: if(s === S_ATTR_SPACE){ value = attrName; } if(s == S_ATTR_NOQUOT_VALUE){ errorHandler.warning('attribute "'+value+'" missed quot(")!!'); el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start) }else{ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') } el.add(value,value,start) } break; case S_EQ: throw new Error('attribute value missed!!'); } // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName)) return p; /*xml space '\x20' | #x9 | #xD | #xA; */ case '\u0080': c = ' '; default: if(c<= ' '){//space switch(s){ case S_TAG: el.setTagName(source.slice(start,p));//tagName s = S_TAG_SPACE; break; case S_ATTR: attrName = source.slice(start,p) s = S_ATTR_SPACE; break; case S_ATTR_NOQUOT_VALUE: var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); errorHandler.warning('attribute "'+value+'" missed quot(")!!'); el.add(attrName,value,start) case S_ATTR_END: s = S_TAG_SPACE; break; //case S_TAG_SPACE: //case S_EQ: //case S_ATTR_SPACE: // void();break; //case S_TAG_CLOSE: //ignore warning } }else{//not space //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE switch(s){ //case S_TAG:void();break; //case S_ATTR:void();break; //case S_ATTR_NOQUOT_VALUE:void();break; case S_ATTR_SPACE: var tagName = el.tagName; if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){ errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') } el.add(attrName,attrName,start); start = p; s = S_ATTR; break; case S_ATTR_END: errorHandler.warning('attribute space is required"'+attrName+'"!!') case S_TAG_SPACE: s = S_ATTR; start = p; break; case S_EQ: s = S_ATTR_NOQUOT_VALUE; start = p; break; case S_TAG_CLOSE: throw new Error("elements closed character '/' and '>' must be connected to"); } } }//end outer switch //console.log('p++',p) p++; } } /** * @return true if has new namespace define */ SaxO.appendElement=function appendElement(el,domBuilder,currentNSMap){ var tagName = el.tagName; var localNSMap = null; //var currentNSMap = parseStack[parseStack.length-1].currentNSMap; var i = el.length; while(i--){ var a = el[i]; var qName = a.qName; var value = a.value; var nsp = qName.indexOf(':'); if(nsp>0){ var prefix = a.prefix = qName.slice(0,nsp); var localName = qName.slice(nsp+1); var nsPrefix = prefix === 'xmlns' && localName }else{ localName = qName; prefix = null nsPrefix = qName === 'xmlns' && '' } //can not set prefix,because prefix !== '' a.localName = localName ; //prefix == null for no ns prefix attribute if(nsPrefix !== false){//hack!! if(localNSMap == null){ localNSMap = {} //console.log(currentNSMap,0) _copy(currentNSMap,currentNSMap={}) //console.log(currentNSMap,1) } currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; a.uri = 'http://www.w3.org/2000/xmlns/' domBuilder.startPrefixMapping(nsPrefix, value) } } var i = el.length; while(i--){ a = el[i]; var prefix = a.prefix; if(prefix){//no prefix attribute has no namespace if(prefix === 'xml'){ a.uri = 'http://www.w3.org/XML/1998/namespace'; }if(prefix !== 'xmlns'){ a.uri = currentNSMap[prefix || ''] //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)} } } } var nsp = tagName.indexOf(':'); if(nsp>0){ prefix = el.prefix = tagName.slice(0,nsp); localName = el.localName = tagName.slice(nsp+1); }else{ prefix = null;//important!! localName = el.localName = tagName; } //no prefix element has default namespace var ns = el.uri = currentNSMap[prefix || '']; domBuilder.startElement(ns,localName,tagName,el); //endPrefixMapping and startPrefixMapping have not any help for dom builder //localNSMap = null if(el.closed){ domBuilder.endElement(ns,localName,tagName); if(localNSMap){ for(prefix in localNSMap){ domBuilder.endPrefixMapping(prefix) } } }else{ el.currentNSMap = currentNSMap; el.localNSMap = localNSMap; //parseStack.push(el); return true; } } function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ if(/^(?:script|textarea)$/i.test(tagName)){ var elEndStart = source.indexOf('',elStartEnd); var text = source.substring(elStartEnd+1,elEndStart); if(/[&<]/.test(text)){ if(/^script$/i.test(tagName)){ //if(!/\]\]>/.test(text)){ //lexHandler.startCDATA(); domBuilder.characters(text,0,text.length); //lexHandler.endCDATA(); return elEndStart; //} }//}else{//text area text = text.replace(/&#?\w+;/g,entityReplacer); domBuilder.characters(text,0,text.length); return elEndStart; //} } } return elStartEnd+1; } function fixSelfClosed(source,elStartEnd,tagName,closeMap){ //if(tagName in closeMap){ var pos = closeMap[tagName]; if(pos == null){ //console.log(tagName) pos = source.lastIndexOf('') if(pos',start+4); //append comment source.substring(4,end)//"); case DOCUMENT_TYPE_NODE: var pubid = node.publicId; var sysid = node.systemId; buf.push(''); }else if(sysid && sysid!='.'){ buf.push(' SYSTEM "',sysid,'">'); }else{ var sub = node.internalSubset; if(sub){ buf.push(" [",sub,"]"); } buf.push(">"); } return; case PROCESSING_INSTRUCTION_NODE: return buf.push( ""); case ENTITY_REFERENCE_NODE: return buf.push( '&',node.nodeName,';'); //case ENTITY_NODE: //case NOTATION_NODE: default: buf.push('??',node.nodeName); } } function importNode(doc,node,deep){ var node2; switch (node.nodeType) { case ELEMENT_NODE: node2 = node.cloneNode(false); node2.ownerDocument = doc; //var attrs = node2.attributes; //var len = attrs.length; //for(var i=0;i -1; var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}; if(locator){ domBuilder.setDocumentLocator(locator) } sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator); sax.domBuilder = options.domBuilder || domBuilder; if(isHTML){ defaultNSMap['']= 'http://www.w3.org/1999/xhtml'; } defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace'; if(source){ sax.parse(source,defaultNSMap,entityMap); }else{ sax.errorHandler.error("invalid doc source"); } return domBuilder.doc; } function buildErrorHandler(errorImpl,domBuilder,locator){ if(!errorImpl){ if(domBuilder instanceof DOMHandler){ return domBuilder; } errorImpl = domBuilder ; } var errorHandler = {} var isCallback = errorImpl instanceof Function; locator = locator||{} function build(key){ var fn = errorImpl[key]; if(!fn && isCallback){ fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl; } errorHandler[key] = fn && function(msg){ fn('[xmldom '+key+']\t'+msg+_locator(locator)); }||function(){}; } build('warning'); build('error'); build('fatalError'); return errorHandler; } //console.log('#\n\n\n\n\n\n\n####') /** * +ContentHandler+ErrorHandler * +LexicalHandler+EntityResolver2 * -DeclHandler-DTDHandler * * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2 * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html */ function DOMHandler() { this.cdata = false; } function position(locator,node){ node.lineNumber = locator.lineNumber; node.columnNumber = locator.columnNumber; } /** * @see org.xml.sax.ContentHandler#startDocument * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html */ DOMHandler.prototype = { startDocument : function() { this.doc = new DOMImplementation().createDocument(null, null, null); if (this.locator) { this.doc.documentURI = this.locator.systemId; } }, startElement:function(namespaceURI, localName, qName, attrs) { var doc = this.doc; var el = doc.createElementNS(namespaceURI, qName||localName); var len = attrs.length; appendElement(this, el); this.currentElement = el; this.locator && position(this.locator,el) for (var i = 0 ; i < len; i++) { var namespaceURI = attrs.getURI(i); var value = attrs.getValue(i); var qName = attrs.getQName(i); var attr = doc.createAttributeNS(namespaceURI, qName); this.locator &&position(attrs.getLocator(i),attr); attr.value = attr.nodeValue = value; el.setAttributeNode(attr) } }, endElement:function(namespaceURI, localName, qName) { var current = this.currentElement var tagName = current.tagName; this.currentElement = current.parentNode; }, startPrefixMapping:function(prefix, uri) { }, endPrefixMapping:function(prefix) { }, processingInstruction:function(target, data) { var ins = this.doc.createProcessingInstruction(target, data); this.locator && position(this.locator,ins) appendElement(this, ins); }, ignorableWhitespace:function(ch, start, length) { }, characters:function(chars, start, length) { chars = _toString.apply(this,arguments) //console.log(chars) if(chars){ if (this.cdata) { var charNode = this.doc.createCDATASection(chars); } else { var charNode = this.doc.createTextNode(chars); } if(this.currentElement){ this.currentElement.appendChild(charNode); }else if(/^\s*$/.test(chars)){ this.doc.appendChild(charNode); //process xml } this.locator && position(this.locator,charNode) } }, skippedEntity:function(name) { }, endDocument:function() { this.doc.normalize(); }, setDocumentLocator:function (locator) { if(this.locator = locator){// && !('lineNumber' in locator)){ locator.lineNumber = 0; } }, //LexicalHandler comment:function(chars, start, length) { chars = _toString.apply(this,arguments) var comm = this.doc.createComment(chars); this.locator && position(this.locator,comm) appendElement(this, comm); }, startCDATA:function() { //used in characters() methods this.cdata = true; }, endCDATA:function() { this.cdata = false; }, startDTD:function(name, publicId, systemId) { var impl = this.doc.implementation; if (impl && impl.createDocumentType) { var dt = impl.createDocumentType(name, publicId, systemId); this.locator && position(this.locator,dt) appendElement(this, dt); } }, /** * @see org.xml.sax.ErrorHandler * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html */ warning:function(error) { console.warn('[xmldom warning]\t'+error,_locator(this.locator)); }, error:function(error) { console.error('[xmldom error]\t'+error,_locator(this.locator)); }, fatalError:function(error) { console.error('[xmldom fatalError]\t'+error,_locator(this.locator)); throw error; } } function _locator(l){ if(l){ return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']' } } function _toString(chars,start,length){ if(typeof chars == 'string'){ return chars.substr(start,length) }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)") if(chars.length >= start+length || start){ return new java.lang.String(chars,start,length)+''; } return chars; } } /* * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html * used method of org.xml.sax.ext.LexicalHandler: * #comment(chars, start, length) * #startCDATA() * #endCDATA() * #startDTD(name, publicId, systemId) * * * IGNORED method of org.xml.sax.ext.LexicalHandler: * #endDTD() * #startEntity(name) * #endEntity(name) * * * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html * IGNORED method of org.xml.sax.ext.DeclHandler * #attributeDecl(eName, aName, type, mode, value) * #elementDecl(name, model) * #externalEntityDecl(name, publicId, systemId) * #internalEntityDecl(name, value) * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html * IGNORED method of org.xml.sax.EntityResolver2 * #resolveEntity(String name,String publicId,String baseURI,String systemId) * #resolveEntity(publicId, systemId) * #getExternalSubset(name, baseURI) * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html * IGNORED method of org.xml.sax.DTDHandler * #notationDecl(name, publicId, systemId) {}; * #unparsedEntityDecl(name, publicId, systemId, notationName) {}; */ "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){ DOMHandler.prototype[key] = function(){return null} }) /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */ function appendElement (hander,node) { if (!hander.currentElement) { hander.doc.appendChild(node); } else { hander.currentElement.appendChild(node); } }//appendChild and setAttributeNS are preformance key htmlEntity={}; htmlEntity.entityMap=entityMap; window.Parser = { DOMParser :DOMParser}; ================================================ FILE: public/libs/laya/laya.Alipaymini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Config=Laya.Config,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,RunDriver=laya.utils.RunDriver; var SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager,URL=laya.net.URL,Utils=laya.utils.Utils; //class laya.ali.mini.ALIMiniAdapter var ALIMiniAdapter=(function(){ function ALIMiniAdapter(){} __class(ALIMiniAdapter,'laya.ali.mini.ALIMiniAdapter'); ALIMiniAdapter.getJson=function(data){ return JSON.parse(data); } ALIMiniAdapter.init=function(isPosMsg,isSon){ (isPosMsg===void 0)&& (isPosMsg=false); (isSon===void 0)&& (isSon=false); if (ALIMiniAdapter._inited)return; ALIMiniAdapter._inited=true; ALIMiniAdapter.window=/*__JS__ */window; if(!ALIMiniAdapter.window.hasOwnProperty("my")) return; if(ALIMiniAdapter.window.navigator.userAgent.indexOf('AlipayMiniGame')<0)return; ALIMiniAdapter.isZiYu=isSon; ALIMiniAdapter.isPosMsgYu=isPosMsg; ALIMiniAdapter.EnvConfig={}; if(!ALIMiniAdapter.isZiYu){ MiniFileMgr$6.setNativeFileDir("/layaairGame"); MiniFileMgr$6.existDir(MiniFileMgr$6.fileNativeDir,Handler.create(ALIMiniAdapter,ALIMiniAdapter.onMkdirCallBack)); } ALIMiniAdapter.systemInfo=ALIMiniAdapter.window.my.getSystemInfoSync(); ALIMiniAdapter.window.focus=function (){ }; Laya['_getUrlPath']=function (){ }; Laya['getUrlPath']=function (){ }; ALIMiniAdapter.window.logtime=function (str){ }; ALIMiniAdapter.window.alertTimeLog=function (str){ }; ALIMiniAdapter.window.resetShareInfo=function (){ }; ALIMiniAdapter.window.CanvasRenderingContext2D=function (){}; ALIMiniAdapter.window.CanvasRenderingContext2D.prototype=ALIMiniAdapter.window.my.createCanvas().getContext('2d').__proto__; ALIMiniAdapter.window.document.body.appendChild=function (){ }; ALIMiniAdapter.EnvConfig.pixelRatioInt=0; RunDriver.getPixelRatio=ALIMiniAdapter.pixelRatio; ALIMiniAdapter._preCreateElement=Browser.createElement; Browser["createElement"]=ALIMiniAdapter.createElement; RunDriver.createShaderCondition=ALIMiniAdapter.createShaderCondition; Utils['parseXMLFromString']=ALIMiniAdapter.parseXMLFromString; Input['_createInputElement']=MiniInput$6['_createInputElement']; ALIMiniAdapter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader$6.prototype.load; Loader.prototype._loadImage=MiniImage$6.prototype._loadImage; LocalStorage._baseClass=MiniLocalStorage$6; MiniLocalStorage$6.__init__(); ALIMiniAdapter.onReciveData(); Config.useRetinalCanvas=true; } ALIMiniAdapter.onReciveData=function(){ if(laya.ali.mini.ALIMiniAdapter.isZiYu){ ALIMiniAdapter.window.my.onMessage(function(message){ if(message['isLoad']=="opendatacontext"){ if(message.url){ MiniFileMgr$6.ziyuFileData[message.url]=message.atlasdata; MiniFileMgr$6.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }else if(message['isLoad']=="openJsondatacontext"){ if(message.url){ MiniFileMgr$6.ziyuFileData[message.url]=message.atlasdata; } }else if(message['isLoad']=="openJsondatacontextPic"){ MiniFileMgr$6.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }); } } ALIMiniAdapter.measureText=function(str){ var tempObj=ALIMiniAdapter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } ALIMiniAdapter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return ""; return "utf8"; } ALIMiniAdapter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr$6.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr$6.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } ALIMiniAdapter.remove=function(fileUrl,callBack){ MiniFileMgr$6.deleteFile("",fileUrl,callBack,"",0); } ALIMiniAdapter.removeAll=function(){ MiniFileMgr$6.deleteAll(); } ALIMiniAdapter.hasNativeFile=function(fileUrl){ return MiniFileMgr$6.isLocalNativeFile(fileUrl); } ALIMiniAdapter.getFileInfo=function(fileUrl){ return MiniFileMgr$6.getFileInfo(fileUrl); } ALIMiniAdapter.getFileList=function(){ return MiniFileMgr$6.filesListObj; } ALIMiniAdapter.exitMiniProgram=function(){ ALIMiniAdapter.window.my.exitMiniProgram(); } ALIMiniAdapter.onMkdirCallBack=function(errorCode,data){ if (!errorCode){ MiniFileMgr$6.filesListObj=JSON.parse(data.data); MiniFileMgr$6.fakeObj=JSON.parse(data.data); } } ALIMiniAdapter.pixelRatio=function(){ if (!ALIMiniAdapter.EnvConfig.pixelRatioInt){ try { ALIMiniAdapter.EnvConfig.pixelRatioInt=ALIMiniAdapter.systemInfo.pixelRatio; return ALIMiniAdapter.systemInfo.pixelRatio; }catch (error){} } return ALIMiniAdapter.EnvConfig.pixelRatioInt; } ALIMiniAdapter.createElement=function(type){ if (type=="canvas"){ var _source; if (ALIMiniAdapter.idx==1){ if(ALIMiniAdapter.isZiYu){ _source=ALIMiniAdapter.window.sharedCanvas; _source.style={}; }else{ _source=ALIMiniAdapter.window.canvas; _source.style={}; } }else { _source=ALIMiniAdapter.window.my.createCanvas(); _source.style={}; } ALIMiniAdapter.idx++; return _source; }else if (type=="textarea" || type=="input"){ return ALIMiniAdapter.onCreateInput(type); }else if (type=="div"){ var node=ALIMiniAdapter._preCreateElement(type); node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } else { return ALIMiniAdapter._preCreateElement(type); } } ALIMiniAdapter.onCreateInput=function(type){ var node=ALIMiniAdapter._preCreateElement(type); node.focus=MiniInput$6.wxinputFocus; node.blur=MiniInput$6.wxinputblur; node.style={}; node.value=0; node.parentElement={}; node.placeholder={}; node.type={}; node.setColor=function (value){ }; node.setType=function (value){ }; node.setFontFace=function (value){ }; node.addEventListener=function (value){ }; node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } ALIMiniAdapter.createShaderCondition=function(conditionScript){ var _$this=this; var func=function (){ var abc=conditionScript; return _$this[conditionScript.replace("this.","")]; } return func; } ALIMiniAdapter.sendAtlasToOpenDataContext=function(url){ if(!laya.ali.mini.ALIMiniAdapter.isZiYu){ var atlasJson=Loader.getRes(URL.formatURL(url)); if(atlasJson){ var textureArr=(atlasJson.meta.image).split(","); if (atlasJson.meta && atlasJson.meta.image){ var toloadPics=atlasJson.meta.image.split(","); var split=url.indexOf("/")>=0 ? "/" :"\\"; var idx=url.lastIndexOf(split); var folderPath=idx >=0 ? url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[url.replace(".json",".png")]; } for(i=0;i\s+<'); try { /*__JS__ */rst=(new window.Parser.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } ALIMiniAdapter.idx=1; __static(ALIMiniAdapter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir"];} ]); return ALIMiniAdapter; })() /**@private **/ //class laya.ali.mini.MiniFileMgr var MiniFileMgr$6=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.ali.mini.MiniFileMgr',null,'MiniFileMgr$6'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=ALIMiniAdapter.nativefiles.length;i=totalSize)){ if(data.size > ALIMiniAdapter.minClearSize) ALIMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > ALIMiniAdapter.minClearSize) ALIMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=ALIMiniAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.ali.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i *
  • 1.0 正常速度
  • *
  • 0.5 半速(更慢)
  • *
  • 2.0 倍速(更快)
  • *
  • -1.0 向后,正常速度
  • *
  • -0.5 向后,半速
  • * *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ if(!this.videoElement) return 0; return this.videoElement.playbackRate; },function(value){ if(!this.videoElement) return; this.videoElement.playbackRate=value; }); __getset(0,__proto,'x',function(){ if(!this.videoElement) return 0; return this.videoElement.x; },function(value){ if(!this.videoElement) return; this.videoElement.x=value; }); __getset(0,__proto,'y',function(){ if(!this.videoElement) return 0; return this.videoElement.y; },function(value){ if(!this.videoElement) return; this.videoElement.y=value; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.src; }); MiniVideo.__init__=function(){ /*__JS__ */laya.device.media.Video=MiniVideo; } return MiniVideo; })() /**@private **/ //class laya.ali.mini.MiniAccelerator extends laya.events.EventDispatcher var MiniAccelerator$6=(function(_super){ function MiniAccelerator(){ MiniAccelerator.__super.call(this); } __class(MiniAccelerator,'laya.ali.mini.MiniAccelerator',_super,'MiniAccelerator$6'); var __proto=MiniAccelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); MiniAccelerator.startListen(this["onDeviceOrientationChange"]); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) MiniAccelerator.stopListen(); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } MiniAccelerator.__init__=function(){ try{ var Acc; Acc=/*__JS__ */laya.device.motion.Accelerator; if (!Acc)return; Acc["prototype"]["on"]=MiniAccelerator["prototype"]["on"]; Acc["prototype"]["off"]=MiniAccelerator["prototype"]["off"]; }catch (e){ } } MiniAccelerator.startListen=function(callBack){ MiniAccelerator._callBack=callBack; if (MiniAccelerator._isListening)return; MiniAccelerator._isListening=true; try{ ALIMiniAdapter.window.my.onAccelerometerChange(laya.ali.mini.MiniAccelerator.onAccelerometerChange); }catch(e){} } MiniAccelerator.stopListen=function(){ MiniAccelerator._isListening=false; try{ ALIMiniAdapter.window.my.stopAccelerometer({}); }catch(e){} } MiniAccelerator.onAccelerometerChange=function(res){ var e; e={}; e.acceleration=res; e.accelerationIncludingGravity=res; e.rotationRate={}; if (MiniAccelerator._callBack !=null){ MiniAccelerator._callBack(e); } } MiniAccelerator._isListening=false; MiniAccelerator._callBack=null; return MiniAccelerator; })(EventDispatcher) /**@private **/ //class laya.ali.mini.MiniLoader extends laya.events.EventDispatcher var MiniLoader$6=(function(_super){ function MiniLoader(){ MiniLoader.__super.call(this); } __class(MiniLoader,'laya.ali.mini.MiniLoader',_super,'MiniLoader$6'); var __proto=MiniLoader.prototype; /** *@private *@param url *@param type *@param cache *@param group *@param ignoreCache */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); var thisLoader=this; thisLoader._url=url; if (url.indexOf("data:image")===0)thisLoader._type=type=/*laya.net.Loader.IMAGE*/"image"; else { thisLoader._type=type || (type=thisLoader.getTypeFromUrl(url)); } thisLoader._cache=cache; thisLoader._data=null; if (!ignoreCache && Loader.loadedMap[URL.formatURL(url)]){ thisLoader._data=Loader.loadedMap[URL.formatURL(url)]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",thisLoader._data); return; } if (Loader.parserMap[type] !=null){ thisLoader._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; }; var encoding=ALIMiniAdapter.getUrlEncode(url,type); var urlType=Utils.getFileExtension(url); if ((MiniLoader._fileTypeArr.indexOf(urlType)!=-1)|| type==/*laya.net.Loader.IMAGE*/"image"){ ALIMiniAdapter.EnvConfig.load.call(this,url,type,cache,group,ignoreCache); }else { if(ALIMiniAdapter.isZiYu && !MiniFileMgr$6.ziyuFileData[url]){ url=URL.formatURL(url); } if(ALIMiniAdapter.isZiYu && MiniFileMgr$6.ziyuFileData[url]){ var tempData=MiniFileMgr$6.ziyuFileData[url]; thisLoader.onLoaded(tempData); return; } if (!MiniFileMgr$6.getFileInfo(url)){ if (MiniFileMgr$6.isLocalNativeFile(url)){ if (ALIMiniAdapter.subNativeFiles && ALIMiniAdapter.subNativeheads.length==0){ for (var key in ALIMiniAdapter.subNativeFiles){ var tempArr=ALIMiniAdapter.subNativeFiles[key]; ALIMiniAdapter.subNativeheads=ALIMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ ALIMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(ALIMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && ALIMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=ALIMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } MiniFileMgr$6.read(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); return; }; var tempUrl=url; var tempurl=URL.formatURL(url); if (tempurl.indexOf(ALIMiniAdapter.window.my.env.USER_DATA_PATH)==-1 &&(url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)&& !ALIMiniAdapter.AutoCacheDownFile){ ALIMiniAdapter.EnvConfig.load.call(thisLoader,tempUrl,type,cache,group,ignoreCache); }else { fileObj=MiniFileMgr$6.getFileInfo(url); if(fileObj){ fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; MiniFileMgr$6.readFile(fileObj.url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else if (thisLoader.type=="image" || thisLoader.type=="htmlimage"){ ALIMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } else{ url=URL.formatURL(url); if(type !=/*laya.net.Loader.IMAGE*/"image" && ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1)|| MiniFileMgr$6.isLocalNativeFile(url))){ MiniFileMgr$6.readFile(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else{ MiniFileMgr$6.downFiles(encodeURI(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url,true); } } } }else { var fileObj=MiniFileMgr$6.getFileInfo(URL.formatURL(url)); fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; var nativepath=MiniFileMgr$6.getFileNativePath(fileObj.md5); MiniFileMgr$6.readFile(nativepath,fileObj.encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); } } } MiniLoader.onReadNativeCallBack=function(encoding,url,type,cache,group,ignoreCache,thisLoader,errorCode,data){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); (errorCode===void 0)&& (errorCode=0); if (!errorCode){ var tempData; if (type==/*laya.net.Loader.JSON*/"json" || type==/*laya.net.Loader.ATLAS*/"atlas"){ tempData=ALIMiniAdapter.getJson(data.data); }else if (type==/*laya.net.Loader.XML*/"xml"){ tempData=Utils.parseXMLFromString(data.data); }else { tempData=data.data; } if(!ALIMiniAdapter.isZiYu &&ALIMiniAdapter.isPosMsgYu && type !=/*laya.net.Loader.BUFFER*/"arraybuffer" && ALIMiniAdapter.window.wx){ ALIMiniAdapter.window.my.postMessage({url:url,data:tempData,isLoad:"filedata"}); } thisLoader.onLoaded(tempData); }else if (errorCode==1){ console.log("-----------本地加载失败,尝试外网加载----"); ALIMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } } __static(MiniLoader, ['_fileTypeArr',function(){return this._fileTypeArr=['png','jpg','bmp','jpeg','gif'];} ]); return MiniLoader; })(EventDispatcher) /**@private **/ //class laya.ali.mini.MiniSound extends laya.events.EventDispatcher var MiniSound$6=(function(_super){ function MiniSound(){ /**@private **/ this._sound=null; /** *@private *声音URL */ this.url=null; /** *@private *是否已加载完成 */ this.loaded=false; /**@private **/ this.readyUrl=null; MiniSound.__super.call(this); } __class(MiniSound,'laya.ali.mini.MiniSound',_super,'MiniSound$6'); var __proto=MiniSound.prototype; /** *@private *加载声音。 *@param url 地址。 * */ __proto.load=function(url){ if (!MiniFileMgr$6.isLocalNativeFile(url)){ url=URL.formatURL(url); }else{ if (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1){ if(MiniFileMgr$6.loadPath !=""){ url=url.split(MiniFileMgr$6.loadPath)[1]; }else{ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; if(tempStr !="") url=url.split(tempStr)[1]; } } } this.url=url; this.readyUrl=url; if (MiniSound._audioCache[this.readyUrl]){ this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if(ALIMiniAdapter.autoCacheFile&&MiniFileMgr$6.getFileInfo(url)){ this.onDownLoadCallBack(url,0); }else{ if(!ALIMiniAdapter.autoCacheFile){ this.onDownLoadCallBack(url,0); }else{ if (MiniFileMgr$6.isLocalNativeFile(url)){ tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="") url=url.split(tempStr)[1]; if (!url){ url=tempUrl; } if (ALIMiniAdapter.subNativeFiles && ALIMiniAdapter.subNativeheads.length==0){ for (var key in ALIMiniAdapter.subNativeFiles){ var tempArr=ALIMiniAdapter.subNativeFiles[key]; ALIMiniAdapter.subNativeheads=ALIMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ ALIMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(ALIMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && ALIMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=ALIMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } this.onDownLoadCallBack(url,0); }else{ MiniFileMgr$6.downOtherFiles(url,Handler.create(this,this.onDownLoadCallBack,[url]),url); } } } } /**@private **/ __proto.onDownLoadCallBack=function(sourceUrl,errorCode,tempFilePath){ (tempFilePath===void 0)&& (tempFilePath=""); if (!errorCode){ var fileNativeUrl; if(ALIMiniAdapter.autoCacheFile){ if(tempFilePath !=""){ fileNativeUrl=tempFilePath; }else{ var fileObj=MiniFileMgr$6.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$6.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=sourceUrl; } } this._sound=MiniSound._createSound(); this._sound.src=this.url=fileNativeUrl; }else{ this._sound=MiniSound._createSound(); this._sound.src=sourceUrl; } this._sound.onCanPlay(MiniSound.bindToThis(this.onCanPlay,this)); this._sound.onError(MiniSound.bindToThis(this.onError,this)); }else{ this.event(/*laya.events.Event.ERROR*/"error"); } } /**@private **/ __proto.onError=function(error){ try{ console.log("sound error:"+error); } catch(error){ } this.event(/*laya.events.Event.ERROR*/"error"); this._sound.offError(null); } /**@private **/ __proto.onCanPlay=function(){ this.loaded=true; this.event(/*laya.events.Event.COMPLETE*/"complete"); this._sound.offCanPlay(null); } /** *@private *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); var tSound; if (this.url==SoundManager._tMusic){ if (!MiniSound._musicAudio)MiniSound._musicAudio=MiniSound._createSound(); tSound=MiniSound._musicAudio; }else { if(MiniSound._audioCache[this.readyUrl]){ tSound=MiniSound._audioCache[this.readyUrl]._sound; }else{ tSound=MiniSound._createSound(); } } if(ALIMiniAdapter.autoCacheFile&&MiniFileMgr$6.getFileInfo(this.url)){ var fileNativeUrl; var fileObj=MiniFileMgr$6.getFileInfo(this.url); var fileMd5Name=fileObj.md5; tSound.src=this.url=MiniFileMgr$6.getFileNativePath(fileMd5Name); }else{ tSound.src=this.url; }; var channel=new MiniSoundChannel$6(tSound,this); channel.url=this.url; channel.loops=loops; channel.loop=(loops===0 ? true :false); channel.startTime=startTime; channel.play(); SoundManager.addChannel(channel); return channel; } /** *@private *释放声音资源。 * */ __proto.dispose=function(){ var ad=MiniSound._audioCache[this.readyUrl]; if (ad){ ad.src=""; if(ad._sound){ ad._sound.destroy(); ad._sound=null; ad=null; } delete MiniSound._audioCache[this.readyUrl]; } } /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ return this._sound.duration; }); MiniSound._createSound=function(){ MiniSound._id++; return ALIMiniAdapter.window.my.createInnerAudioContext(); } MiniSound.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } MiniSound._musicAudio=null; MiniSound._id=0; MiniSound._audioCache={}; return MiniSound; })(EventDispatcher) /**@private **/ //class laya.ali.mini.MiniSoundChannel extends laya.media.SoundChannel var MiniSoundChannel$6=(function(_super){ function MiniSoundChannel(audio,miniSound){ /**@private **/ this._audio=null; /**@private **/ this._onEnd=null; /**@private **/ this._miniSound=null; MiniSoundChannel.__super.call(this); this._audio=audio; this._miniSound=miniSound; this._onEnd=MiniSoundChannel.bindToThis(this.__onEnd,this); audio.onEnded(this._onEnd); } __class(MiniSoundChannel,'laya.ali.mini.MiniSoundChannel',_super,'MiniSoundChannel$6'); var __proto=MiniSoundChannel.prototype; /**@private **/ __proto.__onEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.stop(); this._audio.offEnded(null); this._miniSound.dispose(); this._audio=null; this._miniSound=null; this._onEnd=null; } /**@private **/ __proto.pause=function(){ this.isStopped=true; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',null,function(time){ if(this._audio){ this._audio.startTime=time; } }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ return this._audio.autoplay; },function(value){ this._audio.autoplay=value; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ return this._audio.loop; },function(value){ this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.ani.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Bezier=laya.maths.Bezier,Browser=laya.utils.Browser,Byte=laya.utils.Byte,Event=laya.events.Event; var EventDispatcher=laya.events.EventDispatcher,Graphics=laya.display.Graphics,HTMLCanvas=laya.resource.HTMLCanvas; var Handler=laya.utils.Handler,Loader=laya.net.Loader,MathUtil=laya.maths.MathUtil,Matrix=laya.maths.Matrix; var Node=laya.display.Node,Point=laya.maths.Point,Rectangle=laya.maths.Rectangle,Render=laya.renders.Render; var RenderContext=laya.renders.RenderContext,Resource=laya.resource.Resource,RunDriver=laya.utils.RunDriver; var SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager,Sprite=laya.display.Sprite; var Stat=laya.utils.Stat,Texture=laya.resource.Texture,URL=laya.net.URL,Utils=laya.utils.Utils; /** *@private *@author ... */ //class laya.ani.AnimationContent var AnimationContent=(function(){ function AnimationContent(){ this.nodes=null; this.name=null; this.playTime=NaN; this.bone3DMap=null; this.totalKeyframeDatasLength=0; } __class(AnimationContent,'laya.ani.AnimationContent'); return AnimationContent; })() /** *@private *@author ... */ //class laya.ani.AnimationNodeContent var AnimationNodeContent=(function(){ function AnimationNodeContent(){ this.name=null; this.parentIndex=0; this.parent=null; this.keyframeWidth=0; this.lerpType=0; this.interpolationMethod=null; this.childs=null; this.keyFrame=null; //=new Vector.; this.playTime=NaN; this.extenData=null; this.dataOffset=0; } __class(AnimationNodeContent,'laya.ani.AnimationNodeContent'); return AnimationNodeContent; })() /** *@private */ //class laya.ani.AnimationParser01 var AnimationParser01=(function(){ function AnimationParser01(){} __class(AnimationParser01,'laya.ani.AnimationParser01'); AnimationParser01.parse=function(templet,reader){ var data=reader.__getBuffer(); var i=0,j=0,k=0,n=0,l=0,m=0,o=0; var aniClassName=reader.readUTFString(); templet._aniClassName=aniClassName; var strList=reader.readUTFString().split("\n"); var aniCount=reader.getUint8(); var publicDataPos=reader.getUint32(); var publicExtDataPos=reader.getUint32(); var publicData; if (publicDataPos > 0) publicData=data.slice(publicDataPos,publicExtDataPos); var publicRead=new Byte(publicData); if (publicExtDataPos > 0) templet._publicExtData=data.slice(publicExtDataPos,data.byteLength); templet._useParent=!!reader.getUint8(); templet._anis.length=aniCount; for (i=0;i < aniCount;i++){ var ani=templet._anis[i]=new AnimationContent(); {}; ani.nodes=new Array; var name=ani.name=strList[reader.getUint16()]; templet._aniMap[name]=i; ani.bone3DMap={}; ani.playTime=reader.getFloat32(); var boneCount=ani.nodes.length=reader.getUint8(); ani.totalKeyframeDatasLength=0; for (j=0;j < boneCount;j++){ var node=ani.nodes[j]=new AnimationNodeContent(); {}; node.childs=[]; var nameIndex=reader.getInt16(); if (nameIndex >=0){ node.name=strList[nameIndex]; ani.bone3DMap[node.name]=j; } node.keyFrame=new Array; node.parentIndex=reader.getInt16(); node.parentIndex==-1 ? node.parent=null :node.parent=ani.nodes[node.parentIndex] node.lerpType=reader.getUint8(); var keyframeParamsOffset=reader.getUint32(); publicRead.pos=keyframeParamsOffset; var keyframeDataCount=node.keyframeWidth=publicRead.getUint16(); ani.totalKeyframeDatasLength+=keyframeDataCount; if (node.lerpType===0 || node.lerpType===1){ node.interpolationMethod=[]; node.interpolationMethod.length=keyframeDataCount; for (k=0;k < keyframeDataCount;k++) node.interpolationMethod[k]=AnimationTemplet.interpolation[publicRead.getUint8()]; } if (node.parent !=null) node.parent.childs.push(node); var privateDataLen=reader.getUint16(); if (privateDataLen > 0){ node.extenData=data.slice(reader.pos,reader.pos+privateDataLen); reader.pos+=privateDataLen; }; var keyframeCount=reader.getUint16(); node.keyFrame.length=keyframeCount; var startTime=0; var keyFrame; for (k=0,n=keyframeCount;k < n;k++){ keyFrame=node.keyFrame[k]=new KeyFramesContent(); {}; keyFrame.duration=reader.getFloat32(); keyFrame.startTime=startTime; if (node.lerpType===2){ keyFrame.interpolationData=[]; var interDataLength=reader.getUint8(); var lerpType=0; lerpType=reader.getFloat32(); switch (lerpType){ case 254: keyFrame.interpolationData.length=keyframeDataCount; for (o=0;o < keyframeDataCount;o++) keyFrame.interpolationData[o]=0; break ; case 255: keyFrame.interpolationData.length=keyframeDataCount; for (o=0;o < keyframeDataCount;o++) keyFrame.interpolationData[o]=5; break ; default : keyFrame.interpolationData.push(lerpType); for (m=1;m < interDataLength;m++){ keyFrame.interpolationData.push(reader.getFloat32()); } } } keyFrame.data=new Float32Array(keyframeDataCount); for (l=0;l < keyframeDataCount;l++){ keyFrame.data[l]=reader.getFloat32(); if (keyFrame.data[l] >-0.00000001 && keyFrame.data[l] < 0.00000001)keyFrame.data[l]=0; } startTime+=keyFrame.duration; } keyFrame.startTime=ani.playTime; node.playTime=ani.playTime; templet._calculateKeyFrame(node,keyframeCount,keyframeDataCount); } } } return AnimationParser01; })() /** *@private */ //class laya.ani.AnimationParser02 var AnimationParser02=(function(){ function AnimationParser02(){} __class(AnimationParser02,'laya.ani.AnimationParser02'); AnimationParser02.READ_DATA=function(){ AnimationParser02._DATA.offset=AnimationParser02._reader.getUint32(); AnimationParser02._DATA.size=AnimationParser02._reader.getUint32(); } AnimationParser02.READ_BLOCK=function(){ var count=AnimationParser02._BLOCK.count=AnimationParser02._reader.getUint16(); var blockStarts=AnimationParser02._BLOCK.blockStarts=[]; var blockLengths=AnimationParser02._BLOCK.blockLengths=[]; for (var i=0;i < count;i++){ blockStarts.push(AnimationParser02._reader.getUint32()); blockLengths.push(AnimationParser02._reader.getUint32()); } } AnimationParser02.READ_STRINGS=function(){ var offset=AnimationParser02._reader.getUint32(); var count=AnimationParser02._reader.getUint16(); var prePos=AnimationParser02._reader.pos; AnimationParser02._reader.pos=offset+AnimationParser02._DATA.offset; for (var i=0;i < count;i++) AnimationParser02._strings[i]=AnimationParser02._reader.readUTFString(); AnimationParser02._reader.pos=prePos; } AnimationParser02.parse=function(templet,reader){ AnimationParser02._templet=templet; AnimationParser02._reader=reader; var arrayBuffer=reader.__getBuffer(); AnimationParser02.READ_DATA(); AnimationParser02.READ_BLOCK(); AnimationParser02.READ_STRINGS(); for (var i=0,n=AnimationParser02._BLOCK.count;i < n;i++){ var index=reader.getUint16(); var blockName=AnimationParser02._strings[index]; var fn=AnimationParser02["READ_"+blockName]; if (fn==null) throw new Error("model file err,no this function:"+index+" "+blockName); else fn.call(); } } AnimationParser02.READ_ANIMATIONS=function(){ var reader=AnimationParser02._reader; var arrayBuffer=reader.__getBuffer(); var i=0,j=0,k=0,n=0,l=0; var keyframeWidth=reader.getUint16(); var interpolationMethod=[]; interpolationMethod.length=keyframeWidth; for (i=0;i < keyframeWidth;i++) interpolationMethod[i]=AnimationTemplet.interpolation[reader.getByte()]; var aniCount=reader.getUint8(); AnimationParser02._templet._anis.length=aniCount; for (i=0;i < aniCount;i++){ var ani=AnimationParser02._templet._anis[i]= {}; ani.nodes=new Array; var aniName=ani.name=AnimationParser02._strings[reader.getUint16()]; AnimationParser02._templet._aniMap[aniName]=i; ani.bone3DMap={}; ani.playTime=reader.getFloat32(); var boneCount=ani.nodes.length=reader.getInt16(); ani.totalKeyframeDatasLength=0; for (j=0;j < boneCount;j++){ var node=ani.nodes[j]= {}; node.keyframeWidth=keyframeWidth; node.childs=[]; var nameIndex=reader.getUint16(); if (nameIndex >=0){ node.name=AnimationParser02._strings[nameIndex]; ani.bone3DMap[node.name]=j; } node.keyFrame=new Array; node.parentIndex=reader.getInt16(); node.parentIndex==-1 ? node.parent=null :node.parent=ani.nodes[node.parentIndex] ani.totalKeyframeDatasLength+=keyframeWidth; node.interpolationMethod=interpolationMethod; if (node.parent !=null) node.parent.childs.push(node); var keyframeCount=reader.getUint16(); node.keyFrame.length=keyframeCount; var keyFrame=null,lastKeyFrame=null; for (k=0,n=keyframeCount;k < n;k++){ keyFrame=node.keyFrame[k]= {}; keyFrame.startTime=reader.getFloat32(); (lastKeyFrame)&& (lastKeyFrame.duration=keyFrame.startTime-lastKeyFrame.startTime); var offset=AnimationParser02._DATA.offset; var keyframeDataOffset=reader.getUint32(); var keyframeDataLength=keyframeWidth *4; var keyframeArrayBuffer=arrayBuffer.slice(offset+keyframeDataOffset,offset+keyframeDataOffset+keyframeDataLength); keyFrame.data=new Float32Array(keyframeArrayBuffer); lastKeyFrame=keyFrame; } keyFrame.duration=0; node.playTime=ani.playTime; AnimationParser02._templet._calculateKeyFrame(node,keyframeCount,keyframeWidth); } } } AnimationParser02._templet=null; AnimationParser02._reader=null; AnimationParser02._strings=[]; __static(AnimationParser02, ['_BLOCK',function(){return this._BLOCK={count:0};},'_DATA',function(){return this._DATA={offset:0,size:0};} ]); return AnimationParser02; })() /** *@private */ //class laya.ani.AnimationState var AnimationState=(function(){ function AnimationState(){} __class(AnimationState,'laya.ani.AnimationState'); AnimationState.stopped=0; AnimationState.paused=1; AnimationState.playing=2; return AnimationState; })() /** *@private */ //class laya.ani.bone.Bone var Bone=(function(){ function Bone(){ this.name=null; this.root=null; this.parentBone=null; this.length=10; this.transform=null; this.inheritScale=true; this.inheritRotation=true; this.rotation=NaN; this.resultRotation=NaN; this.d=-1; this._tempMatrix=null; this._sprite=null; this.resultTransform=new Transform(); this.resultMatrix=new Matrix(); this._children=[]; } __class(Bone,'laya.ani.bone.Bone'); var __proto=Bone.prototype; __proto.setTempMatrix=function(matrix){ this._tempMatrix=matrix; var i=0,n=0; var tBone; for (i=0,n=this._children.length;i < n;i++){ tBone=this._children[i]; tBone.setTempMatrix(this._tempMatrix); } } __proto.update=function(pMatrix){ this.rotation=this.transform.skX; var tResultMatrix; if (pMatrix){ tResultMatrix=this.resultTransform.getMatrix(); Matrix.mul(tResultMatrix,pMatrix,this.resultMatrix); this.resultRotation=this.rotation; } else { this.resultRotation=this.rotation+this.parentBone.resultRotation; if (this.parentBone){ if (this.inheritRotation && this.inheritScale){ tResultMatrix=this.resultTransform.getMatrix(); Matrix.mul(tResultMatrix,this.parentBone.resultMatrix,this.resultMatrix); } else { var temp=0; var parent=this.parentBone; var tAngle=NaN; var cos=NaN; var sin=NaN; var tParentMatrix=this.parentBone.resultMatrix; tResultMatrix=this.resultTransform.getMatrix(); var worldX=tParentMatrix.a *tResultMatrix.tx+tParentMatrix.c *tResultMatrix.ty+tParentMatrix.tx; var worldY=tParentMatrix.b *tResultMatrix.tx+tParentMatrix.d *tResultMatrix.ty+tParentMatrix.ty; var tTestMatrix=new Matrix(); if (this.inheritRotation){ tAngle=Math.atan2(parent.resultMatrix.b,parent.resultMatrix.a); cos=Math.cos(tAngle),sin=Math.sin(tAngle); tTestMatrix.setTo(cos,sin,-sin,cos,0,0); Matrix.mul(this._tempMatrix,tTestMatrix,Matrix.TEMP); Matrix.TEMP.copyTo(tTestMatrix); tResultMatrix=this.resultTransform.getMatrix(); Matrix.mul(tResultMatrix,tTestMatrix,this.resultMatrix); if (this.resultTransform.scX *this.resultTransform.scY < 0){ this.resultMatrix.rotate(Math.PI*0.5); } this.resultMatrix.tx=worldX; this.resultMatrix.ty=worldY; } else if (this.inheritScale){ tResultMatrix=this.resultTransform.getMatrix(); Matrix.TEMP.identity(); Matrix.TEMP.d=this.d; Matrix.mul(tResultMatrix,Matrix.TEMP,this.resultMatrix); this.resultMatrix.tx=worldX; this.resultMatrix.ty=worldY; } else { tResultMatrix=this.resultTransform.getMatrix(); Matrix.TEMP.identity(); Matrix.TEMP.d=this.d; Matrix.mul(tResultMatrix,Matrix.TEMP,this.resultMatrix); this.resultMatrix.tx=worldX; this.resultMatrix.ty=worldY; } } } else { tResultMatrix=this.resultTransform.getMatrix(); tResultMatrix.copyTo(this.resultMatrix); } }; var i=0,n=0; var tBone; for (i=0,n=this._children.length;i < n;i++){ tBone=this._children[i]; tBone.update(); } } __proto.updateChild=function(){ var i=0,n=0; var tBone; for (i=0,n=this._children.length;i < n;i++){ tBone=this._children[i]; tBone.update(); } } __proto.setRotation=function(rd){ if (this._sprite){ this._sprite.rotation=rd *180 / Math.PI; } } __proto.updateDraw=function(x,y){ if (!Bone.ShowBones || Bone.ShowBones[this.name]){ if (this._sprite){ this._sprite.x=x+this.resultMatrix.tx; this._sprite.y=y+this.resultMatrix.ty; } else { this._sprite=new Sprite(); this._sprite.graphics.drawCircle(0,0,5,"#ff0000"); this._sprite.graphics.drawLine(0,0,this.length,0,"#00ff00"); this._sprite.graphics.fillText(this.name,0,0,"20px Arial","#00ff00","center"); Laya.stage.addChild(this._sprite); this._sprite.x=x+this.resultMatrix.tx; this._sprite.y=y+this.resultMatrix.ty; } }; var i=0,n=0; var tBone; for (i=0,n=this._children.length;i < n;i++){ tBone=this._children[i]; tBone.updateDraw(x,y); } } __proto.addChild=function(bone){ this._children.push(bone); bone.parentBone=this; } __proto.findBone=function(boneName){ if (this.name==boneName){ return this; } else { var i=0,n=0; var tBone; var tResult; for (i=0,n=this._children.length;i < n;i++){ tBone=this._children[i]; tResult=tBone.findBone(boneName); if (tResult){ return tResult; } } } return null; } __proto.localToWorld=function(local){ var localX=local[0]; var localY=local[1]; local[0]=localX *this.resultMatrix.a+localY *this.resultMatrix.c+this.resultMatrix.tx; local[1]=localX *this.resultMatrix.b+localY *this.resultMatrix.d+this.resultMatrix.ty; } Bone.ShowBones={}; return Bone; })() /** *@private */ //class laya.ani.bone.BoneSlot var BoneSlot=(function(){ function BoneSlot(){ /**插槽名称 */ this.name=null; /**插槽绑定的骨骼名称 */ this.parent=null; /**插糟显示数据数据的名称 */ this.attachmentName=null; /**原始数据的索引 */ this.srcDisplayIndex=-1; /**判断对象是否是原对象 */ this.type="src"; /**模板的指针 */ this.templet=null; /**当前插槽对应的数据 */ this.currSlotData=null; /**当前插槽显示的纹理 */ this.currTexture=null; /**显示对象对应的数据 */ this.currDisplayData=null; /**显示皮肤的索引 */ this.displayIndex=-1; /**@private */ this.originalIndex=-1; /**用户自定义的皮肤 */ this._diyTexture=null; this._parentMatrix=null; this._resultMatrix=null; /**索引替换表 */ this._replaceDic={}; /**当前diyTexture的动画纹理 */ this._curDiyUV=null; this._curDiyVS=null; /**实时模式下,复用使用 */ this._skinSprite=null; /**@private 变形动画数据 */ this.deformData=null; this._mVerticleArr=null; } __class(BoneSlot,'laya.ani.bone.BoneSlot'); var __proto=BoneSlot.prototype; /** *设置要显示的插槽数据 *@param slotData *@param disIndex *@param freshIndex 是否重置纹理 */ __proto.showSlotData=function(slotData,freshIndex){ (freshIndex===void 0)&& (freshIndex=true); this.currSlotData=slotData; if(freshIndex) this.displayIndex=this.srcDisplayIndex; this.currDisplayData=null; this.currTexture=null; } /** *通过名字显示指定对象 *@param name */ __proto.showDisplayByName=function(name){ if (this.currSlotData){ this.showDisplayByIndex(this.currSlotData.getDisplayByName(name)); } } /** *替换贴图名 *@param tarName 要替换的贴图名 *@param newName 替换后的贴图名 */ __proto.replaceDisplayByName=function(tarName,newName){ if (!this.currSlotData)return; var preIndex=0; preIndex=this.currSlotData.getDisplayByName(tarName); var newIndex=0; newIndex=this.currSlotData.getDisplayByName(newName); this.replaceDisplayByIndex(preIndex,newIndex); } /** *替换贴图索引 *@param tarIndex 要替换的索引 *@param newIndex 替换后的索引 */ __proto.replaceDisplayByIndex=function(tarIndex,newIndex){ if (!this.currSlotData)return; this._replaceDic[tarIndex]=newIndex; if (this.originalIndex==tarIndex){ this.showDisplayByIndex(tarIndex); } } /** *指定显示对象 *@param index */ __proto.showDisplayByIndex=function(index){ this.originalIndex=index; if (this._replaceDic[index]!=null)index=this._replaceDic[index]; if (this.currSlotData && index >-1 && index < this.currSlotData.displayArr.length){ this.displayIndex=index; this.currDisplayData=this.currSlotData.displayArr[index]; if (this.currDisplayData){ var tName=this.currDisplayData.name; this.currTexture=this.templet.getTexture(tName); if (this.currTexture && this.currDisplayData.type==0 && this.currDisplayData.uvs && (!Render.isConchApp || (Render.isConchApp && Sprite.RUNTIMEVERION > "0.9.15"))){ this.currTexture=this.currDisplayData.createTexture(this.currTexture); } } }else { this.displayIndex=-1; this.currDisplayData=null; this.currTexture=null; } } /** *替换皮肤 *@param _texture */ __proto.replaceSkin=function(_texture){ this._diyTexture=_texture; if (this._curDiyUV)this._curDiyUV.length=0; if (this.currDisplayData&&this._diyTexture==this.currDisplayData.texture){ this._diyTexture=null; } } /** *保存父矩阵的索引 *@param parentMatrix */ __proto.setParentMatrix=function(parentMatrix){ this._parentMatrix=parentMatrix; } /** *把纹理画到Graphics上 *@param graphics *@param noUseSave */ __proto.draw=function(graphics,boneMatrixArray,noUseSave,alpha){ (noUseSave===void 0)&& (noUseSave=false); (alpha===void 0)&& (alpha=1); if ((this._diyTexture==null && this.currTexture==null)|| this.currDisplayData==null){ if (!(this.currDisplayData && this.currDisplayData.type==3)){ return; } }; var tTexture=this.currTexture; if (this._diyTexture)tTexture=this._diyTexture; var tSkinSprite; switch (this.currDisplayData.type){ case 0: if (graphics){ var tCurrentMatrix=this.getDisplayMatrix(); if (this._parentMatrix){ var tRotateKey=false; if (tCurrentMatrix){ Matrix.mul(tCurrentMatrix,this._parentMatrix,Matrix.TEMP); var tResultMatrix; if (noUseSave){ if (this._resultMatrix==null)this._resultMatrix=new Matrix(); tResultMatrix=this._resultMatrix; }else { tResultMatrix=new Matrix(); } if ((!Render.isWebGL && this.currDisplayData.uvs)|| (Render.isWebGL && this._diyTexture && this.currDisplayData.uvs)){ var tTestMatrix=BoneSlot._tempMatrix; tTestMatrix.identity(); if (this.currDisplayData.uvs[1] > this.currDisplayData.uvs[5]){ tTestMatrix.d=-1; } if (this.currDisplayData.uvs[0] > this.currDisplayData.uvs[4] && this.currDisplayData.uvs[1] > this.currDisplayData.uvs[5]){ tRotateKey=true; tTestMatrix.rotate(-Math.PI/2); } Matrix.mul(tTestMatrix,Matrix.TEMP,tResultMatrix); }else { Matrix.TEMP.copyTo(tResultMatrix); } if (tRotateKey){ graphics.drawTexture(tTexture,-this.currDisplayData.height / 2,-this.currDisplayData.width / 2,this.currDisplayData.height,this.currDisplayData.width,tResultMatrix); }else { graphics.drawTexture(tTexture,-this.currDisplayData.width / 2,-this.currDisplayData.height / 2,this.currDisplayData.width,this.currDisplayData.height,tResultMatrix); } } } } break ; case 1: if (noUseSave){ if (this._skinSprite==null){ this._skinSprite=BoneSlot.createSkinMesh(); } tSkinSprite=this._skinSprite; }else { tSkinSprite=BoneSlot.createSkinMesh(); } if (tSkinSprite==null){ return; }; var tIBArray; var tRed=1; var tGreed=1; var tBlue=1; var tAlpha=1; if (this.currDisplayData.bones==null){ var tVertices=this.currDisplayData.weights; if (this.deformData){ tVertices=this.deformData; }; var tUVs; if (this._diyTexture){ if (!this._curDiyUV){ this._curDiyUV=[]; } if (this._curDiyUV.length==0){ this._curDiyUV=UVTools.getRelativeUV(this.currTexture.uv,this.currDisplayData.uvs,this._curDiyUV); this._curDiyUV=UVTools.getAbsoluteUV(this._diyTexture.uv,this._curDiyUV,this._curDiyUV); } tUVs=this._curDiyUV; }else{ tUVs=this.currDisplayData.uvs; } this._mVerticleArr=tVertices; var tTriangleNum=this.currDisplayData.triangles.length / 3; tIBArray=this.currDisplayData.triangles; tSkinSprite.init2(tTexture,null ,tIBArray,this._mVerticleArr,tUVs); var tCurrentMatrix2=this.getDisplayMatrix(); if (this._parentMatrix){ if (tCurrentMatrix2){ Matrix.mul(tCurrentMatrix2,this._parentMatrix,Matrix.TEMP); var tResultMatrix2; if (noUseSave){ if (this._resultMatrix==null)this._resultMatrix=new Matrix(); tResultMatrix2=this._resultMatrix; }else { tResultMatrix2=new Matrix(); } Matrix.TEMP.copyTo(tResultMatrix2); tSkinSprite.transform=tResultMatrix2; } } }else { this.skinMesh(boneMatrixArray,tSkinSprite,alpha); } graphics.drawSkin(tSkinSprite); break ; case 2: if (noUseSave){ if (this._skinSprite==null){ this._skinSprite=BoneSlot.createSkinMesh(); } tSkinSprite=this._skinSprite; }else { tSkinSprite=BoneSlot.createSkinMesh(); } if (tSkinSprite==null){ return; } this.skinMesh(boneMatrixArray,tSkinSprite,alpha); graphics.drawSkin(tSkinSprite); break ; case 3: break ; } } /** *显示蒙皮动画 *@param boneMatrixArray 当前帧的骨骼矩阵 */ __proto.skinMesh=function(boneMatrixArray,skinSprite,alpha){ var tTexture=this.currTexture; var tBones=this.currDisplayData.bones; var tUvs; if (this._diyTexture){ tTexture=this._diyTexture; if (!this._curDiyUV){ this._curDiyUV=[]; } if (this._curDiyUV.length==0){ this._curDiyUV=UVTools.getRelativeUV(this.currTexture.uv,this.currDisplayData.uvs,this._curDiyUV); this._curDiyUV=UVTools.getAbsoluteUV(this._diyTexture.uv,this._curDiyUV,this._curDiyUV); } tUvs=this._curDiyUV; }else{ tUvs=this.currDisplayData.uvs; }; var tWeights=this.currDisplayData.weights; var tTriangles=this.currDisplayData.triangles; var tIBArray; var tRx=0; var tRy=0; var nn=0; var tMatrix; var tX=NaN; var tY=NaN; var tB=0; var tWeight=0; var tVertices=[]; var i=0,j=0,n=0; var tRed=1; var tGreed=1; var tBlue=1; var tAlpha=alpha; if (this.deformData && this.deformData.length > 0){ var f=0; for (i=0,n=tBones.length;i < n;){ nn=tBones[i++]+i; tRx=0,tRy=0; for (;i < nn;i++){ tMatrix=boneMatrixArray[tBones[i]] tX=tWeights[tB]+this.deformData[f++]; tY=tWeights[tB+1]+this.deformData[f++]; tWeight=tWeights[tB+2]; tRx+=(tX *tMatrix.a+tY *tMatrix.c+tMatrix.tx)*tWeight; tRy+=(tX *tMatrix.b+tY *tMatrix.d+tMatrix.ty)*tWeight; tB+=3; } tVertices.push(tRx,tRy); } }else { for (i=0,n=tBones.length;i < n;){ nn=tBones[i++]+i; tRx=0,tRy=0; for (;i < nn;i++){ tMatrix=boneMatrixArray[tBones[i]] tX=tWeights[tB]; tY=tWeights[tB+1]; tWeight=tWeights[tB+2]; tRx+=(tX *tMatrix.a+tY *tMatrix.c+tMatrix.tx)*tWeight; tRy+=(tX *tMatrix.b+tY *tMatrix.d+tMatrix.ty)*tWeight; tB+=3; } tVertices.push(tRx,tRy); } } this._mVerticleArr=tVertices; tIBArray=tTriangles; skinSprite.init2(tTexture,null,tIBArray,this._mVerticleArr,tUvs); } /** *画骨骼的起始点,方便调试 *@param graphics */ __proto.drawBonePoint=function(graphics){ if (graphics && this._parentMatrix){ graphics.drawCircle(this._parentMatrix.tx,this._parentMatrix.ty,5,"#ff0000"); } } /** *得到显示对象的矩阵 *@return */ __proto.getDisplayMatrix=function(){ if (this.currDisplayData){ return this.currDisplayData.transform.getMatrix(); } return null; } /** *得到插糟的矩阵 *@return */ __proto.getMatrix=function(){ return this._resultMatrix; } /** *用原始数据拷贝出一个 *@return */ __proto.copy=function(){ var tBoneSlot=new BoneSlot(); tBoneSlot.type="copy"; tBoneSlot.name=this.name; tBoneSlot.attachmentName=this.attachmentName; tBoneSlot.srcDisplayIndex=this.srcDisplayIndex; tBoneSlot.parent=this.parent; tBoneSlot.displayIndex=this.displayIndex; tBoneSlot.templet=this.templet; tBoneSlot.currSlotData=this.currSlotData; tBoneSlot.currTexture=this.currTexture; tBoneSlot.currDisplayData=this.currDisplayData; return tBoneSlot; } BoneSlot.createSkinMesh=function(){ if (Render.isWebGL || Render.isConchApp){ return RunDriver.skinAniSprite(); }else{ if (!Render.isWebGL){ if (Skeleton.useSimpleMeshInCanvas){ return new SimpleSkinMeshCanvas(); }else{ return new SkinMeshCanvas(); } } } return null; } __static(BoneSlot, ['_tempMatrix',function(){return this._tempMatrix=new Matrix();} ]); return BoneSlot; })() /** *@private *canvas mesh渲染器 */ //class laya.ani.bone.canvasmesh.CanvasMeshRender var CanvasMeshRender=(function(){ function CanvasMeshRender(){ /** *mesh数据 */ this.mesh=null; /** *矩阵 */ this.transform=null; /** *绘图环境 */ this.context=null; /** *绘制mesh的模式 0:顶点索引模式 1:无顶点索引模式 */ this.mode=0; } __class(CanvasMeshRender,'laya.ani.bone.canvasmesh.CanvasMeshRender'); var __proto=CanvasMeshRender.prototype; /** *将mesh数据渲染到context上面 *@param context * */ __proto.renderToContext=function(context){ this.context=context.ctx||context; if (this.mesh){ if (this.mode==0){ this._renderWithIndexes(this.mesh); }else{ this._renderNoIndexes(this.mesh); } } } /** *无顶点索引的模式 *@param mesh * */ __proto._renderNoIndexes=function(mesh){ var i=0,len=mesh.vertices.length / 2; var index=0; for (i=0;i < len-2;i++){ index=i *2; this._renderDrawTriangle(mesh,index,(index+2),(index+4)); } } /** *使用顶点索引模式绘制 *@param mesh * */ __proto._renderWithIndexes=function(mesh){ var indexes=mesh.indexes; var i=0,len=indexes.length; for (i=0;i < len;i+=3){ var index0=indexes[i] *2; var index1=indexes[i+1] *2; var index2=indexes[i+2] *2; this._renderDrawTriangle(mesh,index0,index1,index2); } } /** *绘制三角形 *@param mesh mesh *@param index0 顶点0 *@param index1 顶点1 *@param index2 顶点2 * */ __proto._renderDrawTriangle=function(mesh,index0,index1,index2){ var context=this.context; var uvs=mesh.uvs; var vertices=mesh.vertices; var texture=mesh.texture; var source=texture.bitmap; var textureSource=source.source; var textureWidth=texture.width; var textureHeight=texture.height; var sourceWidth=source.width; var sourceHeight=source.height; var u0=NaN; var u1=NaN; var u2=NaN; var v0=NaN; var v1=NaN; var v2=NaN; if (mesh.useUvTransform){ var ut=mesh.uvTransform; u0=((uvs[index0] *ut.a)+(uvs[index0+1] *ut.c)+ut.tx)*sourceWidth; u1=((uvs[index1] *ut.a)+(uvs[index1+1] *ut.c)+ut.tx)*sourceWidth; u2=((uvs[index2] *ut.a)+(uvs[index2+1] *ut.c)+ut.tx)*sourceWidth; v0=((uvs[index0] *ut.b)+(uvs[index0+1] *ut.d)+ut.ty)*sourceHeight; v1=((uvs[index1] *ut.b)+(uvs[index1+1] *ut.d)+ut.ty)*sourceHeight; v2=((uvs[index2] *ut.b)+(uvs[index2+1] *ut.d)+ut.ty)*sourceHeight; } else { u0=uvs[index0] *sourceWidth; u1=uvs[index1] *sourceWidth; u2=uvs[index2] *sourceWidth; v0=uvs[index0+1] *sourceHeight; v1=uvs[index1+1] *sourceHeight; v2=uvs[index2+1] *sourceHeight; }; var x0=vertices[index0]; var x1=vertices[index1]; var x2=vertices[index2]; var y0=vertices[index0+1]; var y1=vertices[index1+1]; var y2=vertices[index2+1]; if (mesh.canvasPadding > 0){ var paddingX=mesh.canvasPadding; var paddingY=mesh.canvasPadding; var centerX=(x0+x1+x2)/ 3; var centerY=(y0+y1+y2)/ 3; var normX=x0-centerX; var normY=y0-centerY; var dist=Math.sqrt((normX *normX)+(normY *normY)); x0=centerX+((normX / dist)*(dist+paddingX)); y0=centerY+((normY / dist)*(dist+paddingY)); normX=x1-centerX; normY=y1-centerY; dist=Math.sqrt((normX *normX)+(normY *normY)); x1=centerX+((normX / dist)*(dist+paddingX)); y1=centerY+((normY / dist)*(dist+paddingY)); normX=x2-centerX; normY=y2-centerY; dist=Math.sqrt((normX *normX)+(normY *normY)); x2=centerX+((normX / dist)*(dist+paddingX)); y2=centerY+((normY / dist)*(dist+paddingY)); } context.save(); if (this.transform){ var mt=this.transform; context.transform(mt.a,mt.b,mt.c,mt.d,mt.tx,mt.ty); } context.beginPath(); context.moveTo(x0,y0); context.lineTo(x1,y1); context.lineTo(x2,y2); context.closePath(); context.clip(); var delta=(u0 *v1)+(v0 *u2)+(u1 *v2)-(v1 *u2)-(v0 *u1)-(u0 *v2); var dDelta=1 / delta; var deltaA=(x0 *v1)+(v0 *x2)+(x1 *v2)-(v1 *x2)-(v0 *x1)-(x0 *v2); var deltaB=(u0 *x1)+(x0 *u2)+(u1 *x2)-(x1 *u2)-(x0 *u1)-(u0 *x2); var deltaC=(u0 *v1 *x2)+(v0 *x1 *u2)+(x0 *u1 *v2)-(x0 *v1 *u2)-(v0 *u1 *x2)-(u0 *x1 *v2); var deltaD=(y0 *v1)+(v0 *y2)+(y1 *v2)-(v1 *y2)-(v0 *y1)-(y0 *v2); var deltaE=(u0 *y1)+(y0 *u2)+(u1 *y2)-(y1 *u2)-(y0 *u1)-(u0 *y2); var deltaF=(u0 *v1 *y2)+(v0 *y1 *u2)+(y0 *u1 *v2)-(y0 *v1 *u2)-(v0 *u1 *y2)-(u0 *y1 *v2); context.transform(deltaA *dDelta,deltaD *dDelta,deltaB *dDelta,deltaE*dDelta,deltaC *dDelta,deltaF *dDelta); context.drawImage(textureSource,texture.uv[0]*sourceWidth,texture.uv[1]*sourceHeight,textureWidth,textureHeight,texture.uv[0]*sourceWidth,texture.uv[1]*sourceHeight,textureWidth,textureHeight); context.restore(); } return CanvasMeshRender; })() /** *@private */ //class laya.ani.bone.canvasmesh.MeshData var MeshData=(function(){ function MeshData(){ /** *纹理 */ this.texture=null; /** *uv数据 */ this.uvs=[0,0,1,0,1,1,0,1]; /** *顶点数据 */ this.vertices=[0,0,100,0,100,100,0,100]; /** *顶点索引 */ this.indexes=[0,1,3,3,1,2]; /** *uv变换矩阵 */ this.uvTransform=null; /** *是否有uv变化矩阵 */ this.useUvTransform=false; /** *扩展像素,用来去除黑边 */ this.canvasPadding=1; } __class(MeshData,'laya.ani.bone.canvasmesh.MeshData'); var __proto=MeshData.prototype; /** *计算mesh的Bounds *@return * */ __proto.getBounds=function(){ return Rectangle._getWrapRec(this.vertices); } return MeshData; })() /** *@private */ //class laya.ani.bone.DeformAniData var DeformAniData=(function(){ function DeformAniData(){ this.skinName=null; this.deformSlotDataList=[]; } __class(DeformAniData,'laya.ani.bone.DeformAniData'); return DeformAniData; })() /** *@private */ //class laya.ani.bone.DeformSlotData var DeformSlotData=(function(){ function DeformSlotData(){ this.deformSlotDisplayList=[]; } __class(DeformSlotData,'laya.ani.bone.DeformSlotData'); return DeformSlotData; })() /** *@private */ //class laya.ani.bone.DeformSlotDisplayData var DeformSlotDisplayData=(function(){ function DeformSlotDisplayData(){ this.boneSlot=null; this.slotIndex=-1; this.attachment=null; this.deformData=null; this.frameIndex=0; this.timeList=[]; this.vectices=[]; this.tweenKeyList=[]; } __class(DeformSlotDisplayData,'laya.ani.bone.DeformSlotDisplayData'); var __proto=DeformSlotDisplayData.prototype; __proto.binarySearch1=function(values,target){ var low=0; var high=values.length-2; if (high==0) return 1; var current=high >>> 1; while (true){ if (values[Math.floor(current+1)] <=target) low=current+1; else high=current; if (low==high) return low+1; current=(low+high)>>> 1; } return 0; } // Can't happen. __proto.apply=function(time,boneSlot,alpha){ (alpha===void 0)&& (alpha=1); time+=0.05; if (this.timeList.length <=0){ return; }; var i=0; var n=0; var tTime=this.timeList[0]; if (time < tTime){ return; }; var tVertexCount=this.vectices[0].length; var tVertices=[]; var tFrameIndex=this.binarySearch1(this.timeList,time); this.frameIndex=tFrameIndex; if (time >=this.timeList[this.timeList.length-1]){ var lastVertices=this.vectices[this.vectices.length-1]; if (alpha < 1){ for (i=0;i < tVertexCount;i++){ tVertices[i]+=(lastVertices[i]-tVertices[i])*alpha; } }else { for (i=0;i < tVertexCount;i++){ tVertices[i]=lastVertices[i]; } } this.deformData=tVertices; return; }; var tTweenKey=this.tweenKeyList[this.frameIndex]; var tPrevVertices=this.vectices[this.frameIndex-1]; var tNextVertices=this.vectices[this.frameIndex]; var tPreFrameTime=this.timeList[this.frameIndex-1]; var tFrameTime=this.timeList[this.frameIndex]; if (this.tweenKeyList[tFrameIndex-1]){ alpha=(time-tPreFrameTime)/ (tFrameTime-tPreFrameTime); }else { alpha=0; }; var tPrev=NaN; for (i=0;i < tVertexCount;i++){ tPrev=tPrevVertices[i]; tVertices[i]=tPrev+(tNextVertices[i]-tPrev)*alpha; } this.deformData=tVertices; } return DeformSlotDisplayData; })() /** *@private */ //class laya.ani.bone.DrawOrderData var DrawOrderData=(function(){ function DrawOrderData(){ this.time=NaN; this.drawOrder=[]; } __class(DrawOrderData,'laya.ani.bone.DrawOrderData'); return DrawOrderData; })() /** *@private */ //class laya.ani.bone.EventData var EventData=(function(){ function EventData(){ this.name=null; this.intValue=0; this.floatValue=NaN; this.stringValue=null; this.audioValue=null; this.time=NaN; } __class(EventData,'laya.ani.bone.EventData'); return EventData; })() /** *@private */ //class laya.ani.bone.IkConstraint var IkConstraint=(function(){ function IkConstraint(data,bones){ this._targetBone=null; this._bones=null; this._data=null; this.name=null; this.mix=NaN; this.bendDirection=NaN; this.isSpine=true; //debug相关代码 this._sp=null; this.isDebug=false; this._data=data; this._targetBone=bones[data.targetBoneIndex]; this.isSpine=data.isSpine; if (this._bones==null)this._bones=[]; this._bones.length=0; for (var i=0,n=data.boneIndexs.length;i < n;i++){ this._bones.push(bones[data.boneIndexs[i]]); } this.name=data.name; this.mix=data.mix; this.bendDirection=data.bendDirection; } __class(IkConstraint,'laya.ani.bone.IkConstraint'); var __proto=IkConstraint.prototype; __proto.apply=function(){ switch (this._bones.length){ case 1: this._applyIk1(this._bones[0],this._targetBone.resultMatrix.tx,this._targetBone.resultMatrix.ty,this.mix); break ; case 2: if (this.isSpine){ this._applyIk2(this._bones[0],this._bones[1],this._targetBone.resultMatrix.tx,this._targetBone.resultMatrix.ty,this.bendDirection,this.mix); }else{ this._applyIk3(this._bones[0],this._bones[1],this._targetBone.resultMatrix.tx,this._targetBone.resultMatrix.ty,this.bendDirection,this.mix); } break ; } } __proto._applyIk1=function(bone,targetX,targetY,alpha){ var pp=bone.parentBone; var id=1 / (pp.resultMatrix.a *pp.resultMatrix.d-pp.resultMatrix.b *pp.resultMatrix.c); var x=targetX-pp.resultMatrix.tx; var y=targetY-pp.resultMatrix.ty; var tx=(x *pp.resultMatrix.d-y *pp.resultMatrix.c)*id-bone.transform.x; var ty=(y *pp.resultMatrix.a-x *pp.resultMatrix.b)*id-bone.transform.y; var rotationIK=Math.atan2(ty,tx)*IkConstraint.radDeg-0-bone.transform.skX; if (bone.transform.scX < 0)rotationIK+=180; if (rotationIK > 180) rotationIK-=360; else if (rotationIK <-180)rotationIK+=360; bone.transform.skX=bone.transform.skY=bone.transform.skX+rotationIK *alpha; bone.update(); } __proto.updatePos=function(x,y){ if (this._sp){ this._sp.pos(x,y); } } __proto._applyIk2=function(parent,child,targetX,targetY,bendDir,alpha){ if (alpha==0){ return; }; var px=parent.resultTransform.x,py=parent.resultTransform.y; var psx=parent.transform.scX,psy=parent.transform.scY; var csx=child.transform.scX; var os1=0,os2=0,s2=0; if (psx < 0){ psx=-psx; os1=180; s2=-1; }else { os1=0; s2=1; } if (psy < 0){ psy=-psy; s2=-s2; } if (csx < 0){ csx=-csx; os2=180; }else { os2=0 }; var cx=child.resultTransform.x,cy=NaN,cwx=NaN,cwy=NaN; var a=parent.resultMatrix.a,b=parent.resultMatrix.c; var c=parent.resultMatrix.b,d=parent.resultMatrix.d; var u=Math.abs(psx-psy)<=0.0001; if (!u){ cy=0; cwx=a *cx+parent.resultMatrix.tx; cwy=c *cx+parent.resultMatrix.ty; }else { cy=child.resultTransform.y; cwx=a *cx+b *cy+parent.resultMatrix.tx; cwy=c *cx+d *cy+parent.resultMatrix.ty; } if (this.isDebug){ if (!this._sp){ this._sp=new Sprite(); Laya.stage.addChild(this._sp); } this._sp.graphics.clear(); this._sp.graphics.drawCircle(targetX,targetY,15,"#ffff00"); this._sp.graphics.drawCircle(cwx,cwy,15,"#ff00ff"); } parent.setRotation(Math.atan2(cwy-parent.resultMatrix.ty,cwx-parent.resultMatrix.tx)); var pp=parent.parentBone; a=pp.resultMatrix.a; b=pp.resultMatrix.c; c=pp.resultMatrix.b; d=pp.resultMatrix.d; var id=1 / (a *d-b *c); var x=targetX-pp.resultMatrix.tx,y=targetY-pp.resultMatrix.ty; var tx=(x *d-y *b)*id-px; var ty=(y *a-x *c)*id-py; x=cwx-pp.resultMatrix.tx; y=cwy-pp.resultMatrix.ty; var dx=(x *d-y *b)*id-px; var dy=(y *a-x *c)*id-py; var l1=Math.sqrt(dx *dx+dy *dy); var l2=child.length *csx; var a1=NaN,a2=NaN; if (u){ l2 *=psx; var cos=(tx *tx+ty *ty-l1 *l1-l2 *l2)/ (2 *l1 *l2); if (cos <-1) cos=-1; else if (cos > 1)cos=1; a2=Math.acos(cos)*bendDir; a=l1+l2 *cos; b=l2 *Math.sin(a2); a1=Math.atan2(ty *a-tx *b,tx *a+ty *b); }else { a=psx *l2; b=psy *l2; var aa=a *a,bb=b *b,dd=tx *tx+ty *ty,ta=Math.atan2(ty,tx); c=bb *l1 *l1+aa *dd-aa *bb; var c1=-2 *bb *l1,c2=bb-aa; d=c1 *c1-4 *c2 *c; if (d > 0){ var q=Math.sqrt(d); if (c1 < 0)q=-q; q=-(c1+q)/ 2; var r0=q / c2,r1=c / q; var r=Math.abs(r0)< Math.abs(r1)? r0 :r1; if (r *r <=dd){ y=Math.sqrt(dd-r *r)*bendDir; a1=ta-Math.atan2(y,r); a2=Math.atan2(y / psy,(r-l1)/ psx); } }; var minAngle=0,minDist=Number.MAX_VALUE,minX=0,minY=0; var maxAngle=0,maxDist=0,maxX=0,maxY=0; x=l1+a; d=x *x; if (d > maxDist){ maxAngle=0; maxDist=d; maxX=x; } x=l1-a; d=x *x; if (d < minDist){ minAngle=Math.PI; minDist=d; minX=x; }; var angle=Math.acos(-a *l1 / (aa-bb)); x=a *Math.cos(angle)+l1; y=b *Math.sin(angle); d=x *x+y *y; if (d < minDist){ minAngle=angle; minDist=d; minX=x; minY=y; } if (d > maxDist){ maxAngle=angle; maxDist=d; maxX=x; maxY=y; } if (dd <=(minDist+maxDist)/ 2){ a1=ta-Math.atan2(minY *bendDir,minX); a2=minAngle *bendDir; }else { a1=ta-Math.atan2(maxY *bendDir,maxX); a2=maxAngle *bendDir; } }; var os=Math.atan2(cy,cx)*s2; var rotation=parent.resultTransform.skX; a1=(a1-os)*IkConstraint.radDeg+os1-rotation; if (a1 > 180) a1-=360; else if (a1 <-180)a1+=360; parent.resultTransform.x=px; parent.resultTransform.y=py; parent.resultTransform.skX=parent.resultTransform.skY=rotation+a1 *alpha; rotation=child.resultTransform.skX; rotation=rotation % 360; a2=((a2+os)*IkConstraint.radDeg-0)*s2+os2-rotation; if (a2 > 180) a2-=360; else if (a2 <-180)a2+=360; child.resultTransform.x=cx; child.resultTransform.y=cy; child.resultTransform.skX=child.resultTransform.skY=child.resultTransform.skY+a2 *alpha; parent.update(); } __proto._applyIk3=function(parent,child,targetX,targetY,bendDir,alpha){ if (alpha==0){ return; }; var cwx=NaN,cwy=NaN; var x=child.resultMatrix.a *child.length; var y=child.resultMatrix.b *child.length; var lLL=x *x+y *y; var lL=Math.sqrt(lLL); var parentX=parent.resultMatrix.tx; var parentY=parent.resultMatrix.ty; var childX=child.resultMatrix.tx; var childY=child.resultMatrix.ty; var dX=childX-parentX; var dY=childY-parentY; var lPP=dX *dX+dY *dY; var lP=Math.sqrt(lPP); dX=targetX-parent.resultMatrix.tx; dY=targetY-parent.resultMatrix.ty; var lTT=dX *dX+dY *dY; var lT=Math.sqrt(lTT); var ikRadianA=0; if (lL+lP <=lT || lT+lL <=lP || lT+lP <=lL){ var rate=NaN; if (lL+lP <=lT){ rate=1; }else{ rate=-1; } childX=parentX+rate*(targetX-parentX)*lP / lT; childY=parentY+rate*(targetY-parentY)*lP / lT; } else{ var h=(lPP-lLL+lTT)/ (2 *lTT); var r=Math.sqrt(lPP-h *h *lTT)/ lT; var hX=parentX+(dX *h); var hY=parentY+(dY *h); var rX=-dY *r; var rY=dX *r; if (bendDir>0){ childX=hX-rX; childY=hY-rY; } else{ childX=hX+rX; childY=hY+rY; } } cwx=childX; cwy=childY; if (this.isDebug){ if (!this._sp){ this._sp=new Sprite(); Laya.stage.addChild(this._sp); } this._sp.graphics.clear(); this._sp.graphics.drawCircle(parentX,parentY,15,"#ff00ff"); this._sp.graphics.drawCircle(targetX,targetY,15,"#ffff00"); this._sp.graphics.drawCircle(cwx,cwy,15,"#ff00ff"); }; var pRotation=NaN; pRotation=Math.atan2(cwy-parent.resultMatrix.ty,cwx-parent.resultMatrix.tx); parent.setRotation(pRotation); var pTarMatrix; pTarMatrix=IkConstraint._tempMatrix; pTarMatrix.identity(); pTarMatrix.rotate(pRotation); pTarMatrix.scale(parent.resultMatrix.getScaleX(),parent.resultMatrix.getScaleY()); pTarMatrix.translate(parent.resultMatrix.tx,parent.resultMatrix.ty); pTarMatrix.copyTo(parent.resultMatrix); parent.updateChild(); var childRotation=NaN; childRotation=Math.atan2(targetY-cwy,targetX-cwx); child.setRotation(childRotation); var childTarMatrix; childTarMatrix=IkConstraint._tempMatrix; childTarMatrix.identity(); childTarMatrix.rotate(childRotation); childTarMatrix.scale(child.resultMatrix.getScaleX(),child.resultMatrix.getScaleY()); childTarMatrix.translate(cwx,cwy); pTarMatrix.copyTo(child.resultMatrix); child.updateChild(); } __static(IkConstraint, ['radDeg',function(){return this.radDeg=180 / Math.PI;},'degRad',function(){return this.degRad=Math.PI / 180;},'_tempMatrix',function(){return this._tempMatrix=new Matrix();} ]); return IkConstraint; })() /** *@private */ //class laya.ani.bone.IkConstraintData var IkConstraintData=(function(){ function IkConstraintData(){ this.name=null; this.targetBoneName=null; this.bendDirection=1; this.mix=1; this.isSpine=true; this.targetBoneIndex=-1; this.boneNames=[]; this.boneIndexs=[]; } __class(IkConstraintData,'laya.ani.bone.IkConstraintData'); return IkConstraintData; })() /** *@private *Mesh数据处理工具 *@version 1.0 * *@created 2017-4-28 下午2:46:23 */ //class laya.ani.bone.MeshTools var MeshTools=(function(){ function MeshTools(){} __class(MeshTools,'laya.ani.bone.MeshTools'); MeshTools.findEdge=function(verticles,offI,min){ (offI===void 0)&& (offI=0); (min===void 0)&& (min=true); var i=0,len=0; var tIndex=0; len=verticles.length; tIndex=-1; for (i=0;i < len;i+=2){ if (tIndex < 0 || (min==(verticles[tIndex+offI] < verticles[i+offI]))){ tIndex=i; } } return tIndex; } MeshTools.findBestTriangle=function(verticles){ var topI=0; topI=MeshTools.findEdge(verticles,1,true); var bottomI=0; bottomI=MeshTools.findEdge(verticles,1,false); var leftI=0; leftI=MeshTools.findEdge(verticles,0,true); var rightI=0; rightI=MeshTools.findEdge(verticles,0,false); var rst; rst=MeshTools._bestTriangle; rst.length=0; rst.push(leftI,rightI); if (rst.indexOf(topI)< 0)rst.push(topI); if (rst.indexOf(bottomI)< 0)rst.push(bottomI); return rst; } MeshTools.solveMesh=function(mesh,rst){ rst=rst||[]; rst.length=0; var mUv; mUv=mesh.uvs; var mVer; mVer=mesh.vertices; var uvAbs; var indexs; indexs=MeshTools.findBestTriangle(mUv); var index0=0; var index1=0; var index2=0; index0=indexs[0]; index1=indexs[1]; index2=indexs[2]; MeshTools._absArr.length=0; var newVerticles; if (MeshTools.isNormalUV(mesh.texture.uv)){ MeshTools.adptTexture(mesh); } uvAbs=MeshTools.solvePoints(mesh.texture.uv,mUv[index0],mUv[index0+1],mUv[index1]-mUv[index0],mUv[index1+1]-mUv[index0+1],mUv[index2]-mUv[index0],mUv[index2+1]-mUv[index0+1],MeshTools._absArr); newVerticles=MeshTools.transPoints(uvAbs,mVer[index0],mVer[index0+1],mVer[index1]-mVer[index0],mVer[index1+1]-mVer[index0+1],mVer[index2]-mVer[index0],mVer[index2+1]-mVer[index0+1],rst); return newVerticles; } MeshTools.findWrapRect=function(verticles){ var topI=0; topI=MeshTools.findEdge(verticles,1,true); var bottomI=0; bottomI=MeshTools.findEdge(verticles,1,false); var leftI=0; leftI=MeshTools.findEdge(verticles,0,true); var rightI=0; rightI=MeshTools.findEdge(verticles,0,false); var left=NaN; left=verticles[leftI]; var right=NaN; right=verticles[rightI]; var top=NaN; top=verticles[topI+1]; var bottom=NaN; bottom=verticles[bottomI+1]; var rst; return [right,bottom,left-right,top-bottom]; } MeshTools.adptTexture=function(mesh){ var rec; rec=MeshTools.findWrapRect(mesh.uvs); var oTex; var nTex; oTex=mesh.texture; var oWidth=oTex.width; var oHeight=oTex.height; nTex=Texture.create(oTex,rec[0] *oWidth,rec[1] *oHeight,rec[2] *oWidth,rec[3] *oHeight); mesh.texture=nTex; } MeshTools.isNormalUV=function(uv){ return uv[0]==0 && uv[1]==0 && uv[4]==1 && uv[5]==1; } MeshTools.solvePoints=function(pointList,oX,oY,v1x,v1y,v2x,v2y,rst){ rst=rst||[]; var i=0,len=0; len=pointList.length; var tRst; for (i=0;i < len;i+=2){ tRst=MeshTools.solve2(pointList[i],pointList[i+1],oX,oY,v1x,v1y,v2x,v2y); rst.push(tRst[0],tRst[1]); } return rst; } MeshTools.transPoints=function(abs,oX,oY,v1x,v1y,v2x,v2y,rst){ rst=rst|| []; var i=0,len=0; len=abs.length; var tRst; for (i=0;i < len;i+=2){ tRst=MeshTools.transPoint(abs[i],abs[i+1],oX,oY,v1x,v1y,v2x,v2y,rst); } return rst; } MeshTools.transPoint=function(a,b,oX,oY,v1x,v1y,v2x,v2y,rst){ rst=rst|| []; var nX=NaN; var nY=NaN; nX=oX+v1x *a+v2x *b; nY=oY+v1y *a+v2y *b; rst.push(nX,nY) return rst; } MeshTools.solve2=function(rx,ry,oX,oY,v1x,v1y,v2x,v2y,rv,rst){ (rv===void 0)&& (rv=false); rst=rst||[]; var a=NaN,b=NaN; if (v1x==0){ return MeshTools.solve2(rx,ry,oX,oY,v2x,v2y,v1x,v1y,true,rst); }; var dX=NaN; var dY=NaN; dX=rx-oX; dY=ry-oY; b=(dY-dX *v1y / v1x)/ (v2y-v2x *v1y / v1x); a=(dX-b *v2x)/ v1x; if(rv){ rst.push(b,a); }else{ rst.push(a,b); } return rst; } MeshTools.solve=function(pointC,point0,v1,v2){ return MeshTools.solve2(pointC.x,pointC.y,point0.x,point0.y,v1.x,v1.y,v2.x,v2.y); } MeshTools._bestTriangle=[]; MeshTools._absArr=[]; return MeshTools; })() /** *@private *路径作用器 *1,生成根据骨骼计算控制点 *2,根据控制点生成路径,并计算路径上的节点 *3,根据节点,重新调整骨骼位置 */ //class laya.ani.bone.PathConstraint var PathConstraint=(function(){ function PathConstraint(data,bones){ this.target=null; this.data=null; this.bones=null; this.position=NaN; this.spacing=NaN; this.rotateMix=NaN; this.translateMix=NaN; this._debugKey=false; this._spaces=null; this._segments=[]; this._curves=[]; this.data=data; this.position=data.position; this.spacing=data.spacing; this.rotateMix=data.rotateMix; this.translateMix=data.translateMix; this.bones=[]; var tBoneIds=this.data.bones; for (var i=0,n=tBoneIds.length;i < n;i++){ this.bones.push(bones[tBoneIds[i]]); } } __class(PathConstraint,'laya.ani.bone.PathConstraint'); var __proto=PathConstraint.prototype; /** *计算骨骼在路径上的节点 *@param boneSlot *@param boneMatrixArray *@param graphics */ __proto.apply=function(boneList,graphics){ if (!this.target) return; var tTranslateMix=this.translateMix; var tRotateMix=this.translateMix; var tTranslate=tTranslateMix > 0; var tRotate=tRotateMix > 0; var tSpacingMode=this.data.spacingMode; var tLengthSpacing=tSpacingMode=="length"; var tRotateMode=this.data.rotateMode; var tTangents=tRotateMode=="tangent"; var tScale=tRotateMode=="chainScale"; var lengths=[]; var boneCount=this.bones.length; var spacesCount=tTangents ? boneCount :boneCount+1; var spaces=[]; this._spaces=spaces; spaces[0]=this.position; var spacing=this.spacing; if (tScale || tLengthSpacing){ for (var i=0,n=spacesCount-1;i < n;){ var bone=this.bones[i]; var length=bone.length; var x=length *bone.resultMatrix.a; var y=length *bone.resultMatrix.b; length=Math.sqrt(x *x+y *y); if (tScale) lengths[i]=length; spaces[++i]=tLengthSpacing ? Math.max(0,length+spacing):spacing; } } else { for (i=1;i < spacesCount;i++){ spaces[i]=spacing; } }; var positions=this.computeWorldPositions(this.target,boneList,graphics,spacesCount,tTangents,this.data.positionMode=="percent",tSpacingMode=="percent"); if (this._debugKey){ for (i=0;i < positions.length;i++){ graphics.drawCircle(positions[i++],positions[i++],5,"#00ff00"); }; var tLinePos=[]; for (i=0;i < positions.length;i++){ tLinePos.push(positions[i++],positions[i++]); } graphics.drawLines(0,0,tLinePos,"#ff0000"); }; var skeletonX=NaN; var skeletonY=NaN; var boneX=positions[0]; var boneY=positions[1]; var offsetRotation=this.data.offsetRotation; var tip=tRotateMode=="chain" && offsetRotation==0; var p=NaN; for (i=0,p=3;i < boneCount;i++,p+=3){ bone=this.bones[i]; bone.resultMatrix.tx+=(boneX-bone.resultMatrix.tx)*tTranslateMix; bone.resultMatrix.ty+=(boneY-bone.resultMatrix.ty)*tTranslateMix; x=positions[p]; y=positions[p+1]; var dx=x-boneX,dy=y-boneY; if (tScale){ length=lengths[i]; if (length !=0){ var s=(Math.sqrt(dx *dx+dy *dy)/ length-1)*tRotateMix+1; bone.resultMatrix.a *=s; bone.resultMatrix.c *=s; } } boneX=x; boneY=y; if (tRotate){ var a=bone.resultMatrix.a; var b=bone.resultMatrix.c; var c=bone.resultMatrix.b; var d=bone.resultMatrix.d; var r=NaN; var cos=NaN; var sin=NaN; if (tTangents){ r=positions[p-1]; } else if (spaces[i+1]==0){ r=positions[p+2]; } else { r=Math.atan2(dy,dx); } r-=Math.atan2(c,a)-offsetRotation / 180 *Math.PI; if (tip){ cos=Math.cos(r); sin=Math.sin(r); length=bone.length; boneX+=(length *(cos *a-sin *c)-dx)*tRotateMix; boneY+=(length *(sin *a+cos *c)-dy)*tRotateMix; } if (r > Math.PI){ r-=(Math.PI *2); } else if (r <-Math.PI){ r+=(Math.PI *2); } r *=tRotateMix; cos=Math.cos(r); sin=Math.sin(r); bone.resultMatrix.a=cos *a-sin *c; bone.resultMatrix.c=cos *b-sin *d; bone.resultMatrix.b=sin *a+cos *c; bone.resultMatrix.d=sin *b+cos *d; } } } /** *计算顶点的世界坐标 *@param boneSlot *@param boneList *@param start *@param count *@param worldVertices *@param offset */ __proto.computeWorldVertices2=function(boneSlot,boneList,start,count,worldVertices,offset){ var tBones=boneSlot.currDisplayData.bones; var tWeights=boneSlot.currDisplayData.weights; var tTriangles=boneSlot.currDisplayData.triangles; var tMatrix; var i=0; var v=0; var skip=0; var n=0; var w=0; var b=0; var wx=0; var wy=0; var vx=0; var vy=0; var bone; var len=0; if (tBones==null){ if (!tTriangles)tTriangles=tWeights; if (boneSlot.deformData) tTriangles=boneSlot.deformData; var parentName; parentName=boneSlot.parent; if (boneList){ len=boneList.length; for (i=0;i < len;i++){ if (boneList[i].name==parentName){ bone=boneList[i]; break ; } } }; var tBoneMt; if (bone){ tBoneMt=bone.resultMatrix; } if (!tBoneMt)tBoneMt=PathConstraint._tempMt; var x=tBoneMt.tx; var y=tBoneMt.ty; var a=tBoneMt.a,bb=tBoneMt.b,c=tBoneMt.c,d=tBoneMt.d; if(bone)d*=bone.d; for (v=start,w=offset;w < count;v+=2,w+=2){ vx=tTriangles[v],vy=tTriangles[v+1]; worldVertices[w]=vx *a+vy *bb+x; worldVertices[w+1]=-(vx *c+vy *d+y); } return; } for (i=0;i < start;i+=2){ n=tBones[v]; v+=n+1; skip+=n; }; var skeletonBones=boneList; for (w=offset,b=skip *3;w < count;w+=2){ wx=0,wy=0; n=tBones[v++]; n+=v; for (;v < n;v++,b+=3){ tMatrix=skeletonBones[tBones[v]].resultMatrix; vx=tWeights[b]; vy=tWeights[b+1]; var weight=tWeights[b+2]; wx+=(vx *tMatrix.a+vy *tMatrix.c+tMatrix.tx)*weight; wy+=(vx *tMatrix.b+vy *tMatrix.d+tMatrix.ty)*weight; } worldVertices[w]=wx; worldVertices[w+1]=wy; } } /** *计算路径上的节点 *@param boneSlot *@param boneList *@param graphics *@param spacesCount *@param tangents *@param percentPosition *@param percentSpacing *@return */ __proto.computeWorldPositions=function(boneSlot,boneList,graphics,spacesCount,tangents,percentPosition,percentSpacing){ var tBones=boneSlot.currDisplayData.bones; var tWeights=boneSlot.currDisplayData.weights; var tTriangles=boneSlot.currDisplayData.triangles; var tRx=0; var tRy=0; var nn=0; var tMatrix; var tX=NaN; var tY=NaN; var tB=0; var tWeight=0; var tVertices=[]; var i=0,j=0,n=0; var verticesLength=boneSlot.currDisplayData.verLen; var target=boneSlot; var position=this.position; var spaces=this._spaces; var world=[]; var out=[]; var closed=false; var curveCount=verticesLength / 6; var prevCurve=-1; var pathLength=NaN; var o=0,curve=0; var p=NaN; var space=NaN; var prev=NaN; var length=NaN; if (!true){ var lengths=boneSlot.currDisplayData.lengths; curveCount-=closed ? 1 :2; pathLength=lengths[curveCount]; if (percentPosition) position *=pathLength; if (percentSpacing){ for (i=0;i < spacesCount;i++) spaces[i] *=pathLength; } world.length=8; for (i=0,o=0,curve=0;i < spacesCount;i++,o+=3){ space=spaces[i]; position+=space; p=position; if (closed){ p %=pathLength; if (p < 0) p+=pathLength; curve=0; } else if (p < 0){ if (prevCurve !=PathConstraint.BEFORE){ prevCurve=PathConstraint.BEFORE; this.computeWorldVertices2(target,boneList,2,4,world,0); } this.addBeforePosition(p,world,0,out,o); continue ; } else if (p > pathLength){ if (prevCurve !=PathConstraint.AFTER){ prevCurve=PathConstraint.AFTER; this.computeWorldVertices2(target,boneList,verticesLength-6,4,world,0); } this.addAfterPosition(p-pathLength,world,0,out,o); continue ; } for (;;curve++){ length=lengths[curve]; if (p > length) continue ; if (curve==0) p /=length; else { prev=lengths[curve-1]; p=(p-prev)/ (length-prev); } break ; } if (curve !=prevCurve){ prevCurve=curve; if (closed && curve==curveCount){ this.computeWorldVertices2(target,boneList,verticesLength-4,4,world,0); this.computeWorldVertices2(target,boneList,0,4,world,4); } else this.computeWorldVertices2(target,boneList,curve *6+2,8,world,0); } this.addCurvePosition(p,world[0],world[1],world[2],world[3],world[4],world[5],world[6],world[7],out,o,tangents || (i > 0 && space==0)); } return out; } if (closed){ verticesLength+=2; world[verticesLength-2]=world[0]; world[verticesLength-1]=world[1]; } else { curveCount--; verticesLength-=4; this.computeWorldVertices2(boneSlot,boneList,2,verticesLength,tVertices,0); if (this._debugKey){ for (i=0;i < tVertices.length;){ graphics.drawCircle(tVertices[i++],tVertices[i++],10,"#ff0000"); } } world=tVertices; } this._curves.length=curveCount; var curves=this._curves; pathLength=0; var x1=world[0],y1=world[1],cx1=0,cy1=0,cx2=0,cy2=0,x2=0,y2=0; var tmpx=NaN,tmpy=NaN,dddfx=NaN,dddfy=NaN,ddfx=NaN,ddfy=NaN,dfx=NaN,dfy=NaN; var w=0; for (i=0,w=2;i < curveCount;i++,w+=6){ cx1=world[w]; cy1=world[w+1]; cx2=world[w+2]; cy2=world[w+3]; x2=world[w+4]; y2=world[w+5]; tmpx=(x1-cx1 *2+cx2)*0.1875; tmpy=(y1-cy1 *2+cy2)*0.1875; dddfx=((cx1-cx2)*3-x1+x2)*0.09375; dddfy=((cy1-cy2)*3-y1+y2)*0.09375; ddfx=tmpx *2+dddfx; ddfy=tmpy *2+dddfy; dfx=(cx1-x1)*0.75+tmpx+dddfx *0.16666667; dfy=(cy1-y1)*0.75+tmpy+dddfy *0.16666667; pathLength+=Math.sqrt(dfx *dfx+dfy *dfy); dfx+=ddfx; dfy+=ddfy; ddfx+=dddfx; ddfy+=dddfy; pathLength+=Math.sqrt(dfx *dfx+dfy *dfy); dfx+=ddfx; dfy+=ddfy; pathLength+=Math.sqrt(dfx *dfx+dfy *dfy); dfx+=ddfx+dddfx; dfy+=ddfy+dddfy; pathLength+=Math.sqrt(dfx *dfx+dfy *dfy); curves[i]=pathLength; x1=x2; y1=y2; } if (percentPosition) position *=pathLength; if (percentSpacing){ for (i=0;i < spacesCount;i++) spaces[i] *=pathLength; }; var segments=this._segments; var curveLength=0; var segment=0; for (i=0,o=0,curve=0,segment=0;i < spacesCount;i++,o+=3){ space=spaces[i]; position+=space; p=position; if (closed){ p %=pathLength; if (p < 0) p+=pathLength; curve=0; } else if (p < 0){ this.addBeforePosition(p,world,0,out,o); continue ; } else if (p > pathLength){ this.addAfterPosition(p-pathLength,world,verticesLength-4,out,o); continue ; } for (;;curve++){ length=curves[curve]; if (p > length) continue ; if (curve==0) p /=length; else { prev=curves[curve-1]; p=(p-prev)/ (length-prev); } break ; } if (curve !=prevCurve){ prevCurve=curve; var ii=curve *6; x1=world[ii]; y1=world[ii+1]; cx1=world[ii+2]; cy1=world[ii+3]; cx2=world[ii+4]; cy2=world[ii+5]; x2=world[ii+6]; y2=world[ii+7]; tmpx=(x1-cx1 *2+cx2)*0.03; tmpy=(y1-cy1 *2+cy2)*0.03; dddfx=((cx1-cx2)*3-x1+x2)*0.006; dddfy=((cy1-cy2)*3-y1+y2)*0.006; ddfx=tmpx *2+dddfx; ddfy=tmpy *2+dddfy; dfx=(cx1-x1)*0.3+tmpx+dddfx *0.16666667; dfy=(cy1-y1)*0.3+tmpy+dddfy *0.16666667; curveLength=Math.sqrt(dfx *dfx+dfy *dfy); segments[0]=curveLength; for (ii=1;ii < 8;ii++){ dfx+=ddfx; dfy+=ddfy; ddfx+=dddfx; ddfy+=dddfy; curveLength+=Math.sqrt(dfx *dfx+dfy *dfy); segments[ii]=curveLength; } dfx+=ddfx; dfy+=ddfy; curveLength+=Math.sqrt(dfx *dfx+dfy *dfy); segments[8]=curveLength; dfx+=ddfx+dddfx; dfy+=ddfy+dddfy; curveLength+=Math.sqrt(dfx *dfx+dfy *dfy); segments[9]=curveLength; segment=0; } p *=curveLength; for (;;segment++){ length=segments[segment]; if (p > length) continue ; if (segment==0) p /=length; else { prev=segments[segment-1]; p=segment+(p-prev)/ (length-prev); } break ; } this.addCurvePosition(p *0.1,x1,y1,cx1,cy1,cx2,cy2,x2,y2,out,o,tangents || (i > 0 && space==0)); } return out; } __proto.addBeforePosition=function(p,temp,i,out,o){ var x1=temp[i],y1=temp[i+1],dx=temp[i+2]-x1,dy=temp[i+3]-y1,r=Math.atan2(dy,dx); out[o]=x1+p *Math.cos(r); out[o+1]=y1+p *Math.sin(r); out[o+2]=r; } __proto.addAfterPosition=function(p,temp,i,out,o){ var x1=temp[i+2],y1=temp[i+3],dx=x1-temp[i],dy=y1-temp[i+1],r=Math.atan2(dy,dx); out[o]=x1+p *Math.cos(r); out[o+1]=y1+p *Math.sin(r); out[o+2]=r; } __proto.addCurvePosition=function(p,x1,y1,cx1,cy1,cx2,cy2,x2,y2,out,o,tangents){ if (p==0) p=0.0001; var tt=p *p,ttt=tt *p,u=1-p,uu=u *u,uuu=uu *u; var ut=u *p,ut3=ut *3,uut3=u *ut3,utt3=ut3 *p; var x=x1 *uuu+cx1 *uut3+cx2 *utt3+x2 *ttt,y=y1 *uuu+cy1 *uut3+cy2 *utt3+y2 *ttt; out[o]=x; out[o+1]=y; if (tangents){ out[o+2]=Math.atan2(y-(y1 *uu+cy1 *ut *2+cy2 *tt),x-(x1 *uu+cx1 *ut *2+cx2 *tt)); } else { out[o+2]=0; } } PathConstraint.NONE=-1; PathConstraint.BEFORE=-2; PathConstraint.AFTER=-3; __static(PathConstraint, ['_tempMt',function(){return this._tempMt=new Matrix();} ]); return PathConstraint; })() /** *@private */ //class laya.ani.bone.PathConstraintData var PathConstraintData=(function(){ function PathConstraintData(){ this.name=null; this.target=null; this.positionMode=null; this.spacingMode=null; this.rotateMode=null; this.offsetRotation=NaN; this.position=NaN; this.spacing=NaN; this.rotateMix=NaN; this.translateMix=NaN; this.bones=[]; } __class(PathConstraintData,'laya.ani.bone.PathConstraintData'); return PathConstraintData; })() /** *@private */ //class laya.ani.bone.SkinData var SkinData=(function(){ function SkinData(){ this.name=null; this.slotArr=[]; } __class(SkinData,'laya.ani.bone.SkinData'); return SkinData; })() /** *@private */ //class laya.ani.bone.SkinSlotDisplayData var SkinSlotDisplayData=(function(){ function SkinSlotDisplayData(){ this.name=null; this.attachmentName=null; this.type=0; this.transform=null; this.width=NaN; this.height=NaN; this.texture=null; this.bones=null; this.uvs=null; this.weights=null; this.triangles=null; this.vertices=null; this.lengths=null; this.verLen=0; } __class(SkinSlotDisplayData,'laya.ani.bone.SkinSlotDisplayData'); var __proto=SkinSlotDisplayData.prototype; __proto.createTexture=function(currTexture){ if (this.texture)return this.texture; this.texture=new Texture(currTexture.bitmap,this.uvs); if (this.uvs[0] > this.uvs[4] && this.uvs[1] > this.uvs[5]){ this.texture.width=currTexture.height; this.texture.height=currTexture.width; this.texture.offsetX=-currTexture.offsetX; this.texture.offsetY=-currTexture.offsetY; this.texture.sourceWidth=currTexture.sourceHeight; this.texture.sourceHeight=currTexture.sourceWidth; }else { this.texture.width=currTexture.width; this.texture.height=currTexture.height; this.texture.offsetX=-currTexture.offsetX; this.texture.offsetY=-currTexture.offsetY; this.texture.sourceWidth=currTexture.sourceWidth; this.texture.sourceHeight=currTexture.sourceHeight; } if (!Render.isWebGL){ if (this.uvs[1] > this.uvs[5]){ this.texture.offsetY=this.texture.sourceHeight-this.texture.height-this.texture.offsetY; } } return this.texture; } __proto.destory=function(){ if (this.texture)this.texture.destroy(); } return SkinSlotDisplayData; })() /** *@private */ //class laya.ani.bone.SlotData var SlotData=(function(){ function SlotData(){ this.name=null; this.displayArr=[]; } __class(SlotData,'laya.ani.bone.SlotData'); var __proto=SlotData.prototype; __proto.getDisplayByName=function(name){ var tDisplay; for (var i=0,n=this.displayArr.length;i < n;i++){ tDisplay=this.displayArr[i]; if (tDisplay.attachmentName==name){ return i; } } return-1; } return SlotData; })() /** *@private */ //class laya.ani.bone.TfConstraint var TfConstraint=(function(){ function TfConstraint(data,bones){ this._data=null; this._bones=null; this.target=null; this.rotateMix=NaN; this.translateMix=NaN; this.scaleMix=NaN; this.shearMix=NaN; this._temp=__newvec(2,0); this._data=data; if (this._bones==null){ this._bones=[]; } this.target=bones[data.targetIndex]; var j=0,n=0; for (j=0,n=data.boneIndexs.length;j < n;j++){ this._bones.push(bones[data.boneIndexs[j]]); } this.rotateMix=data.rotateMix; this.translateMix=data.translateMix; this.scaleMix=data.scaleMix; this.shearMix=data.shearMix; } __class(TfConstraint,'laya.ani.bone.TfConstraint'); var __proto=TfConstraint.prototype; __proto.apply=function(){ var tTfBone; var ta=this.target.resultMatrix.a,tb=this.target.resultMatrix.b,tc=this.target.resultMatrix.c,td=this.target.resultMatrix.d; for (var j=0,n=this._bones.length;j < n;j++){ tTfBone=this._bones[j]; if (this.rotateMix > 0){ var a=tTfBone.resultMatrix.a,b=tTfBone.resultMatrix.b,c=tTfBone.resultMatrix.c,d=tTfBone.resultMatrix.d; var r=Math.atan2(tc,ta)-Math.atan2(c,a)+this._data.offsetRotation *Math.PI / 180; if (r > Math.PI) r-=Math.PI *2; else if (r <-Math.PI)r+=Math.PI *2; r *=this.rotateMix; var cos=Math.cos(r),sin=Math.sin(r); tTfBone.resultMatrix.a=cos *a-sin *c; tTfBone.resultMatrix.b=cos *b-sin *d; tTfBone.resultMatrix.c=sin *a+cos *c; tTfBone.resultMatrix.d=sin *b+cos *d; } if (this.translateMix){ this._temp[0]=this._data.offsetX; this._temp[1]=this._data.offsetY; this.target.localToWorld(this._temp); tTfBone.resultMatrix.tx+=(this._temp[0]-tTfBone.resultMatrix.tx)*this.translateMix; tTfBone.resultMatrix.ty+=(this._temp[1]-tTfBone.resultMatrix.ty)*this.translateMix; tTfBone.updateChild(); } if (this.scaleMix > 0){ var bs=Math.sqrt(tTfBone.resultMatrix.a *tTfBone.resultMatrix.a+tTfBone.resultMatrix.c *tTfBone.resultMatrix.c); var ts=Math.sqrt(ta *ta+tc *tc); var s=bs > 0.00001 ? (bs+(ts-bs+this._data.offsetScaleX)*this.scaleMix)/ bs :0; tTfBone.resultMatrix.a *=s; tTfBone.resultMatrix.c *=s; bs=Math.sqrt(tTfBone.resultMatrix.b *tTfBone.resultMatrix.b+tTfBone.resultMatrix.d *tTfBone.resultMatrix.d); ts=Math.sqrt(tb *tb+td *td); s=bs > 0.00001 ? (bs+(ts-bs+this._data.offsetScaleY)*this.scaleMix)/ bs :0; tTfBone.resultMatrix.b *=s; tTfBone.resultMatrix.d *=s; } if (this.shearMix > 0){ b=tTfBone.resultMatrix.b,d=tTfBone.resultMatrix.d; var by=Math.atan2(d,b); r=Math.atan2(td,tb)-Math.atan2(tc,ta)-(by-Math.atan2(tTfBone.resultMatrix.c,tTfBone.resultMatrix.a)); if (r > Math.PI) r-=Math.PI *2; else if (r <-Math.PI)r+=Math.PI *2; r=by+(r+this._data.offsetShearY *Math.PI / 180)*this.shearMix; s=Math.sqrt(b *b+d *d); tTfBone.resultMatrix.b=Math.cos(r)*s; tTfBone.resultMatrix.d=Math.sin(r)*s; } } } return TfConstraint; })() /** *@private */ //class laya.ani.bone.TfConstraintData var TfConstraintData=(function(){ function TfConstraintData(){ this.name=null; this.targetIndex=0; this.rotateMix=NaN; this.translateMix=NaN; this.scaleMix=NaN; this.shearMix=NaN; this.offsetRotation=NaN; this.offsetX=NaN; this.offsetY=NaN; this.offsetScaleX=NaN; this.offsetScaleY=NaN; this.offsetShearY=NaN; this.boneIndexs=[]; } __class(TfConstraintData,'laya.ani.bone.TfConstraintData'); return TfConstraintData; })() /** *@private */ //class laya.ani.bone.Transform var Transform=(function(){ function Transform(){ this.skX=0; this.skY=0; this.scX=1; this.scY=1; this.x=0; this.y=0; this.skewX=0; this.skewY=0; this.mMatrix=null; } __class(Transform,'laya.ani.bone.Transform'); var __proto=Transform.prototype; __proto.initData=function(data){ if (data.x !=undefined){ this.x=data.x; } if (data.y !=undefined){ this.y=data.y; } if (data.skX !=undefined){ this.skX=data.skX; } if (data.skY !=undefined){ this.skY=data.skY; } if (data.scX !=undefined){ this.scX=data.scX; } if (data.scY !=undefined){ this.scY=data.scY; } } __proto.getMatrix=function(){ var tMatrix; if (this.mMatrix){ tMatrix=this.mMatrix; }else { tMatrix=this.mMatrix=new Matrix(); } tMatrix.identity(); tMatrix.scale(this.scX,this.scY); if (this.skewX || this.skewY){ this.skew(tMatrix,this.skewX *Math.PI / 180,this.skewY *Math.PI / 180); } tMatrix.rotate(this.skX *Math.PI / 180); tMatrix.translate(this.x,this.y); return tMatrix; } __proto.skew=function(m,x,y){ var sinX=Math.sin(y); var cosX=Math.cos(y); var sinY=Math.sin(x); var cosY=Math.cos(x); m.setTo(m.a *cosY-m.b *sinX, m.a *sinY+m.b *cosX, m.c *cosY-m.d *sinX, m.c *sinY+m.d *cosX, m.tx *cosY-m.ty *sinX, m.tx *sinY+m.ty *cosX); return m; } return Transform; })() /** *用于UV转换的工具类 *@private */ //class laya.ani.bone.UVTools var UVTools=(function(){ function UVTools(){} __class(UVTools,'laya.ani.bone.UVTools'); UVTools.getRelativeUV=function(bigUV,smallUV,rst){ var startX=bigUV[0]; var width=bigUV[2]-bigUV[0]; var startY=bigUV[1]; var height=bigUV[5]-bigUV[1]; if(!rst)rst=[]; rst.length=smallUV.length; var i=0,len=0; len=rst.length; var dWidth=1 / width; var dHeight=1 / height; for (i=0;i < len;i+=2){ rst[i]=(smallUV[i]-startX)*dWidth; rst[i+1]=(smallUV[i+1]-startY)*dHeight; } return rst; } UVTools.getAbsoluteUV=function(bigUV,smallUV,rst){ if (bigUV[0]==0 && bigUV[1]==0 && bigUV[4]==1 && bigUV[5]==1){ if (rst){ Utils.copyArray(rst,smallUV); return rst; }else{ return smallUV; } }; var startX=bigUV[0]; var width=bigUV[2]-bigUV[0]; var startY=bigUV[1]; var height=bigUV[5]-bigUV[1]; if(!rst)rst=[]; rst.length=smallUV.length; var i=0,len=0; len=rst.length; for (i=0;i < len;i+=2){ rst[i]=smallUV[i]*width+startX; rst[i+1]=smallUV[i+1]*height+startY; } return rst; } return UVTools; })() /** *@private *@author ... */ //class laya.ani.KeyFramesContent var KeyFramesContent=(function(){ function KeyFramesContent(){ this.startTime=NaN; this.duration=NaN; this.interpolationData=null; //私有插值方式 [type0(插值类型),Data0(插值数据,可为空),type1(插值类型),Data1(插值数据,可为空)] 注意:254全线性插值,255全不插值 this.data=null; //=new Float32Array(); this.nextData=null; } __class(KeyFramesContent,'laya.ani.KeyFramesContent'); return KeyFramesContent; })() /** *@private *... *@author ww */ //class laya.ani.math.BezierLerp var BezierLerp=(function(){ function BezierLerp(){} __class(BezierLerp,'laya.ani.math.BezierLerp'); BezierLerp.getBezierRate=function(t,px0,py0,px1,py1){ var key=BezierLerp._getBezierParamKey(px0,py0,px1,py1); var vKey=key *100+t; if (BezierLerp._bezierResultCache[vKey])return BezierLerp._bezierResultCache[vKey]; var points=BezierLerp._getBezierPoints(px0,py0,px1,py1,key); var i=0,len=0; len=points.length; for (i=0;i < len;i+=2){ if (t <=points[i]){ BezierLerp._bezierResultCache[vKey]=points[i+1]; return points[i+1]; } } BezierLerp._bezierResultCache[vKey]=1; return 1; } BezierLerp._getBezierParamKey=function(px0,py0,px1,py1){ return (((px0 *100+py0)*100+px1)*100+py1)*100; } BezierLerp._getBezierPoints=function(px0,py0,px1,py1,key){ if (BezierLerp._bezierPointsCache[key])return BezierLerp._bezierPointsCache[key]; var controlPoints; controlPoints=[0,0,px0,py0,px1,py1,1,1]; var bz; bz=new Bezier(); var points; points=bz.getBezierPoints(controlPoints,100,3); BezierLerp._bezierPointsCache[key]=points; return points; } BezierLerp._bezierResultCache={}; BezierLerp._bezierPointsCache={}; return BezierLerp; })() /** *AnimationPlayer 类用于动画播放器。 */ //class laya.ani.AnimationPlayer extends laya.events.EventDispatcher var AnimationPlayer=(function(_super){ function AnimationPlayer(){ /**@private */ this._destroyed=false; /**数据模板*/ this._templet=null; /**当前精确时间,不包括重播时间*/ this._currentTime=NaN; /**当前帧时间,不包括重播时间*/ this._currentFrameTime=NaN; /**动画播放的起始时间位置*/ this._playStart=NaN; /**动画播放的结束时间位置*/ this._playEnd=NaN; /**动画播放一次的总时间*/ this._playDuration=NaN; /**动画播放总时间*/ this._overallDuration=NaN; /**是否在一帧结束时停止*/ this._stopWhenCircleFinish=false; /**已播放时间,包括重播时间*/ this._elapsedPlaybackTime=NaN; /**播放时帧数*/ this._startUpdateLoopCount=NaN; /**当前动画索引*/ this._currentAnimationClipIndex=0; /**当前帧数*/ this._currentKeyframeIndex=0; /**是否暂停*/ this._paused=false; /**默认帧率,必须大于0*/ this._cacheFrameRate=0; /**帧率间隔时间*/ this._cacheFrameRateInterval=NaN; /**缓存播放速率*/ this._cachePlayRate=NaN; this._fullFrames=null; /**是否缓存*/ this.isCache=true; /**播放速率*/ this.playbackRate=1.0; /**停止时是否归零*/ this.returnToZeroStopped=false; AnimationPlayer.__super.call(this); this._destroyed=false; this._currentAnimationClipIndex=-1; this._currentKeyframeIndex=-1; this._currentTime=0.0; this._overallDuration=Number.MAX_VALUE; this._stopWhenCircleFinish=false; this._elapsedPlaybackTime=0; this._startUpdateLoopCount=-1; this._cachePlayRate=1.0; this.cacheFrameRate=60; this.returnToZeroStopped=false; } __class(AnimationPlayer,'laya.ani.AnimationPlayer',_super); var __proto=AnimationPlayer.prototype; Laya.imps(__proto,{"laya.resource.IDestroy":true}) /** *@private */ __proto._onTempletLoadedComputeFullKeyframeIndices=function(cachePlayRate,cacheFrameRate,templet){ if (this._templet===templet && this._cachePlayRate===cachePlayRate && this._cacheFrameRate===cacheFrameRate) this._computeFullKeyframeIndices(); } /** *@private */ __proto._computeFullKeyframeIndices=function(){ var anifullFrames=this._fullFrames=[]; var templet=this._templet; var cacheFrameInterval=this._cacheFrameRateInterval *this._cachePlayRate; for (var i=0,iNum=templet.getAnimationCount();i < iNum;i++){ var aniFullFrame=[]; for (var j=0,jNum=templet.getAnimation(i).nodes.length;j < jNum;j++){ var node=templet.getAnimation(i).nodes[j]; var frameCount=Math.floor(node.playTime / cacheFrameInterval+0.01); var nodeFullFrames=new Uint16Array(frameCount+1); var lastFrameIndex=-1; for (var n=0,nNum=node.keyFrame.length;n < nNum;n++){ var keyFrame=node.keyFrame[n]; var tm=keyFrame.startTime; var endTm=tm+keyFrame.duration+cacheFrameInterval; do { var frameIndex=Math.floor(tm / cacheFrameInterval+0.5); for (var k=lastFrameIndex+1;k < frameIndex;k++) nodeFullFrames[k]=n; lastFrameIndex=frameIndex; nodeFullFrames[frameIndex]=n; tm+=cacheFrameInterval; }while (tm <=endTm); } aniFullFrame.push(nodeFullFrames); } anifullFrames.push(aniFullFrame); } } /** *@private */ __proto._onAnimationTempletLoaded=function(){ (this.destroyed)|| (this._calculatePlayDuration()); } /** *@private */ __proto._calculatePlayDuration=function(){ if (this.state!==/*laya.ani.AnimationState.stopped*/0){ var oriDuration=this._templet.getAniDuration(this._currentAnimationClipIndex); (this._playEnd===0)&& (this._playEnd=oriDuration); if (this._playEnd > oriDuration) this._playEnd=oriDuration; this._playDuration=this._playEnd-this._playStart; } } /** *@private */ __proto._setPlayParams=function(time,cacheFrameInterval){ this._currentTime=time; this._currentKeyframeIndex=Math.max(Math.floor((this.currentPlayTime)/ cacheFrameInterval+0.01),0); this._currentFrameTime=this._currentKeyframeIndex *cacheFrameInterval; } /** *@private */ __proto._setPlayParamsWhenStop=function(currentAniClipPlayDuration,cacheFrameInterval,playEnd){ (playEnd===void 0)&& (playEnd=-1); this._currentTime=currentAniClipPlayDuration; var endTime=playEnd > 0 ? playEnd :currentAniClipPlayDuration; this._currentKeyframeIndex=Math.max(Math.floor(endTime / cacheFrameInterval+0.01),0); this._currentFrameTime=this._currentKeyframeIndex *cacheFrameInterval; this._currentAnimationClipIndex=-1; } /** *@private */ __proto._update=function(elapsedTime){ if (this._currentAnimationClipIndex===-1 || this._paused || !this._templet || !this._templet.loaded) return; var cacheFrameInterval=this._cacheFrameRateInterval *this._cachePlayRate; var time=0; (this._startUpdateLoopCount!==Stat.loopCount)&& (time=elapsedTime *this.playbackRate,this._elapsedPlaybackTime+=time); var currentAniClipPlayDuration=this.playDuration; time+=this._currentTime; if ((this._overallDuration!==0 && this._elapsedPlaybackTime >=this._overallDuration)|| (this._overallDuration===0 && this._elapsedPlaybackTime >=currentAniClipPlayDuration) || (this._overallDuration===0 && time >=this.playEnd)){ this._setPlayParamsWhenStop(currentAniClipPlayDuration,cacheFrameInterval,this.playEnd); this.event(/*laya.events.Event.STOPPED*/"stopped"); return; } if (currentAniClipPlayDuration > 0){ if (time >=currentAniClipPlayDuration){ do { time-=currentAniClipPlayDuration; if (this._stopWhenCircleFinish){ this._setPlayParamsWhenStop(currentAniClipPlayDuration,cacheFrameInterval); this._stopWhenCircleFinish=false; this.event(/*laya.events.Event.STOPPED*/"stopped"); return; } if (time < currentAniClipPlayDuration){ this._setPlayParams(time,cacheFrameInterval); this.event(/*laya.events.Event.COMPLETE*/"complete"); } }while (time >=currentAniClipPlayDuration) }else { this._setPlayParams(time,cacheFrameInterval); } }else { if (this._stopWhenCircleFinish){ this._setPlayParamsWhenStop(currentAniClipPlayDuration,cacheFrameInterval); this._stopWhenCircleFinish=false; this.event(/*laya.events.Event.STOPPED*/"stopped"); return; } this._currentTime=this._currentFrameTime=this._currentKeyframeIndex=0; this.event(/*laya.events.Event.COMPLETE*/"complete"); } } /** *@private */ __proto._destroy=function(){ this.offAll(); this._templet=null; this._fullFrames=null; this._destroyed=true; } /** *播放动画。 *@param index 动画索引。 *@param playbackRate 播放速率。 *@param duration 播放时长(0为1次,Number.MAX_VALUE为循环播放)。 *@param playStart 播放的起始时间位置。 *@param playEnd 播放的结束时间位置。(0为动画一次循环的最长结束时间位置)。 */ __proto.play=function(index,playbackRate,overallDuration,playStart,playEnd){ (index===void 0)&& (index=0); (playbackRate===void 0)&& (playbackRate=1.0); (overallDuration===void 0)&& (overallDuration=2147483647); (playStart===void 0)&& (playStart=0); (playEnd===void 0)&& (playEnd=0); if (!this._templet) throw new Error("AnimationPlayer:templet must not be null,maybe you need to set url."); if (overallDuration < 0 || playStart < 0 || playEnd < 0) throw new Error("AnimationPlayer:overallDuration,playStart and playEnd must large than zero."); if ((playEnd!==0)&& (playStart > playEnd)) throw new Error("AnimationPlayer:start must less than end."); this._currentTime=0; this._currentFrameTime=0; this._elapsedPlaybackTime=0; this.playbackRate=playbackRate; this._overallDuration=overallDuration; this._playStart=playStart; this._playEnd=playEnd; this._paused=false; this._currentAnimationClipIndex=index; this._currentKeyframeIndex=0; this._startUpdateLoopCount=Stat.loopCount; this.event(/*laya.events.Event.PLAYED*/"played"); if (this._templet.loaded) this._calculatePlayDuration(); else this._templet.once(/*laya.events.Event.LOADED*/"loaded",this,this._onAnimationTempletLoaded); this._update(0); } /** *播放动画。 *@param index 动画索引。 *@param playbackRate 播放速率。 *@param duration 播放时长(0为1次,Number.MAX_VALUE为循环播放)。 *@param playStartFrame 播放的原始起始帧率位置。 *@param playEndFrame 播放的原始结束帧率位置。(0为动画一次循环的最长结束时间位置)。 */ __proto.playByFrame=function(index,playbackRate,overallDuration,playStartFrame,playEndFrame,fpsIn3DBuilder){ (index===void 0)&& (index=0); (playbackRate===void 0)&& (playbackRate=1.0); (overallDuration===void 0)&& (overallDuration=2147483647); (playStartFrame===void 0)&& (playStartFrame=0); (playEndFrame===void 0)&& (playEndFrame=0); (fpsIn3DBuilder===void 0)&& (fpsIn3DBuilder=30); var interval=1000.0 / fpsIn3DBuilder; this.play(index,playbackRate,overallDuration,playStartFrame *interval,playEndFrame *interval); } /** *停止播放当前动画 *@param immediate 是否立即停止 */ __proto.stop=function(immediate){ (immediate===void 0)&& (immediate=true); if (immediate){ this._currentTime=this._currentFrameTime=this._currentKeyframeIndex=0; this._currentAnimationClipIndex=-1; this.event(/*laya.events.Event.STOPPED*/"stopped"); }else { this._stopWhenCircleFinish=true; } } /** *动画播放的结束时间位置。 *@return 结束时间位置。 */ __getset(0,__proto,'playEnd',function(){ return this._playEnd; }); /** *设置动画数据模板,注意:修改此值会有计算开销。 *@param value 动画数据模板 */ /** *获取动画数据模板 *@param value 动画数据模板 */ __getset(0,__proto,'templet',function(){ return this._templet; },function(value){ if (!this.state===/*laya.ani.AnimationState.stopped*/0) this.stop(true); if (this._templet!==value){ this._templet=value; if (value.loaded) this._computeFullKeyframeIndices(); else value.once(/*laya.events.Event.LOADED*/"loaded",this,this._onTempletLoadedComputeFullKeyframeIndices,[this._cachePlayRate,this._cacheFrameRate]); } }); /** *动画播放的起始时间位置。 *@return 起始时间位置。 */ __getset(0,__proto,'playStart',function(){ return this._playStart; }); /** *获取动画播放一次的总时间 *@return 动画播放一次的总时间 */ __getset(0,__proto,'playDuration',function(){ return this._playDuration; }); /** *获取当前播放状态 *@return 当前播放状态 */ __getset(0,__proto,'state',function(){ if (this._currentAnimationClipIndex===-1) return /*laya.ani.AnimationState.stopped*/0; if (this._paused) return /*laya.ani.AnimationState.paused*/1; return /*laya.ani.AnimationState.playing*/2; }); /** *获取当前帧数 *@return 当前帧数 */ __getset(0,__proto,'currentKeyframeIndex',function(){ return this._currentKeyframeIndex; }); /** *获取动画播放的总总时间 *@return 动画播放的总时间 */ __getset(0,__proto,'overallDuration',function(){ return this._overallDuration; }); /** *获取当前帧时间,不包括重播时间 *@return value 当前时间 */ __getset(0,__proto,'currentFrameTime',function(){ return this._currentFrameTime; }); /** *获取当前动画索引 *@return value 当前动画索引 */ __getset(0,__proto,'currentAnimationClipIndex',function(){ return this._currentAnimationClipIndex; }); /** *获取当前精确时间,不包括重播时间 *@return value 当前时间 */ __getset(0,__proto,'currentPlayTime',function(){ return this._currentTime+this._playStart; }); /** *设置缓存播放速率,默认值为1.0,注意:修改此值会有计算开销。* *@return value 缓存播放速率。 */ /** *获取缓存播放速率。* *@return 缓存播放速率。 */ __getset(0,__proto,'cachePlayRate',function(){ return this._cachePlayRate; },function(value){ if (this._cachePlayRate!==value){ this._cachePlayRate=value; if (this._templet) if (this._templet.loaded) this._computeFullKeyframeIndices(); else this._templet.once(/*laya.events.Event.LOADED*/"loaded",this,this._onTempletLoadedComputeFullKeyframeIndices,[value,this._cacheFrameRate]); } }); /** *设置默认帧率,每秒60帧,注意:修改此值会有计算开销。* *@return value 缓存帧率 */ /** *获取默认帧率* *@return value 默认帧率 */ __getset(0,__proto,'cacheFrameRate',function(){ return this._cacheFrameRate; },function(value){ if (this._cacheFrameRate!==value){ this._cacheFrameRate=value; this._cacheFrameRateInterval=1000.0 / this._cacheFrameRate; if (this._templet) if (this._templet.loaded) this._computeFullKeyframeIndices(); else this._templet.once(/*laya.events.Event.LOADED*/"loaded",this,this._onTempletLoadedComputeFullKeyframeIndices,[this._cachePlayRate,value]); } }); /** *设置当前播放位置 *@param value 当前时间 */ __getset(0,__proto,'currentTime',null,function(value){ if (this._currentAnimationClipIndex===-1 || !this._templet || !this._templet.loaded) return; if (value < this._playStart || value > this._playEnd) throw new Error("AnimationPlayer:value must large than playStartTime,small than playEndTime."); this._startUpdateLoopCount=Stat.loopCount; var cacheFrameInterval=this._cacheFrameRateInterval *this._cachePlayRate; this._currentTime=value; this._currentKeyframeIndex=Math.max(Math.floor(this.currentPlayTime / cacheFrameInterval),0); this._currentFrameTime=this._currentKeyframeIndex *cacheFrameInterval; }); /** *设置是否暂停 *@param value 是否暂停 */ /** *获取当前是否暂停 *@return 是否暂停 */ __getset(0,__proto,'paused',function(){ return this._paused; },function(value){ this._paused=value; value && this.event(/*laya.events.Event.PAUSED*/"paused"); }); /** *获取缓存帧率间隔时间 *@return 缓存帧率间隔时间 */ __getset(0,__proto,'cacheFrameRateInterval',function(){ return this._cacheFrameRateInterval; }); /** *获取是否已销毁。 *@return 是否已销毁。 */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); return AnimationPlayer; })(EventDispatcher) /** *@private */ //class laya.ani.GraphicsAni extends laya.display.Graphics var GraphicsAni=(function(_super){ function GraphicsAni(){ GraphicsAni.__super.call(this); if (Render.isConchNode){ this["drawSkin"]=function (skin){ skin.transform || (skin.transform=Matrix.EMPTY); /*__JS__ */this._addCmd([skin]); this.setSkinMesh&&this.setSkinMesh(skin._ps,skin.mVBData,skin.mEleNum,0,skin.mTexture,skin.transform); }; } } __class(GraphicsAni,'laya.ani.GraphicsAni',_super); var __proto=GraphicsAni.prototype; /** *@private *画自定义蒙皮动画 *@param skin */ __proto.drawSkin=function(skin){ var arr=[skin]; this._saveToCmd(Render._context._drawSkin,arr); } GraphicsAni.create=function(){ var rs=GraphicsAni._caches.pop(); return rs||new GraphicsAni(); } GraphicsAni.recycle=function(graphics){ graphics.clear(); GraphicsAni._caches.push(graphics); } GraphicsAni._caches=[]; return GraphicsAni; })(Graphics) /** *@private *Canvas版本的SkinMesh */ //class laya.ani.bone.canvasmesh.SkinMeshCanvas extends laya.ani.bone.canvasmesh.CanvasMeshRender var SkinMeshCanvas=(function(_super){ function SkinMeshCanvas(){ SkinMeshCanvas.__super.call(this); this.mesh=new MeshData(); } __class(SkinMeshCanvas,'laya.ani.bone.canvasmesh.SkinMeshCanvas',_super); var __proto=SkinMeshCanvas.prototype; __proto.init2=function(texture,vs,ps,verticles,uvs){ if (this.transform){ this.transform=null; }; var _ps; if (ps){ _ps=ps; }else { _ps=[]; _ps.push(0,1,3,3,1,2); } this.mesh.texture=texture; this.mesh.indexes=_ps; this.mesh.vertices=verticles; this.mesh.uvs=uvs; } __proto.render=function(context,x,y){ if(!this.mesh.texture)return; if(!this.transform){ this.transform=SkinMeshCanvas._tempMatrix; this.transform.identity(); this.transform.translate(x,y); this.renderToContext(context); this.transform.translate(-x,-y); this.transform=null; }else{ this.transform.translate(x,y); this.renderToContext(context); this.transform.translate(-x,-y); } } __static(SkinMeshCanvas, ['_tempMatrix',function(){return this._tempMatrix=new Matrix();} ]); return SkinMeshCanvas; })(CanvasMeshRender) /** *AnimationTemplet 类用于动画模板资源。 */ //class laya.ani.AnimationTemplet extends laya.resource.Resource var AnimationTemplet=(function(_super){ function AnimationTemplet(){ /**@private */ //this._aniVersion=null; /**@private */ this._aniMap={}; /**@private */ //this._publicExtData=null; /**@private */ //this._useParent=false; /**@private */ //this.unfixedCurrentFrameIndexes=null; /**@private */ //this.unfixedCurrentTimes=null; /**@private */ //this.unfixedKeyframes=null; /**@private */ this.unfixedLastAniIndex=-1; /**@private */ //this._aniClassName=null; /**@private */ //this._animationDatasCache=null; AnimationTemplet.__super.call(this); this._anis=new Array; } __class(AnimationTemplet,'laya.ani.AnimationTemplet',_super); var __proto=AnimationTemplet.prototype; /** *@private */ __proto.parse=function(data){ var reader=new Byte(data); this._aniVersion=reader.readUTFString(); AnimationParser01.parse(this,reader); } /** *@private */ __proto._calculateKeyFrame=function(node,keyframeCount,keyframeDataCount){ var keyFrames=node.keyFrame; keyFrames[keyframeCount]=keyFrames[0]; for (var i=0;i < keyframeCount;i++){ var keyFrame=keyFrames[i]; keyFrame.nextData=(keyFrame.duration===0)? keyFrame.data :keyFrames[i+1].data; } keyFrames.length--; } /** *@inheritDoc */ __proto.onAsynLoaded=function(url,data,params){ var reader=new Byte(data); this._aniVersion=reader.readUTFString(); switch (this._aniVersion){ case "LAYAANIMATION:02": AnimationParser02.parse(this,reader); break ; default : AnimationParser01.parse(this,reader); } this._endLoaded(); } /** *@inheritDoc */ __proto.disposeResource=function(){ this._aniVersion=null; this._anis=null; this._aniMap=null; this._publicExtData=null; this.unfixedCurrentFrameIndexes=null; this.unfixedCurrentTimes=null; this.unfixedKeyframes=null; this._aniClassName=null; this._animationDatasCache=null; } __proto.getAnimationCount=function(){ return this._anis.length; } __proto.getAnimation=function(aniIndex){ return this._anis[aniIndex]; } __proto.getAniDuration=function(aniIndex){ return this._anis[aniIndex].playTime; } __proto.getNodes=function(aniIndex){ return this._anis[aniIndex].nodes; } __proto.getNodeIndexWithName=function(aniIndex,name){ return this._anis[aniIndex].bone3DMap[name]; } __proto.getNodeCount=function(aniIndex){ return this._anis[aniIndex].nodes.length; } __proto.getTotalkeyframesLength=function(aniIndex){ return this._anis[aniIndex].totalKeyframeDatasLength; } __proto.getPublicExtData=function(){ return this._publicExtData; } __proto.getAnimationDataWithCache=function(key,cacheDatas,aniIndex,frameIndex){ var aniDatas=cacheDatas[aniIndex]; if (!aniDatas){ return null; }else { var keyDatas=aniDatas[key]; if (!keyDatas) return null; else { return keyDatas[frameIndex]; } } } __proto.setAnimationDataWithCache=function(key,cacheDatas,aniIndex,frameIndex,data){ var aniDatas=(cacheDatas[aniIndex])|| (cacheDatas[aniIndex]={}); var aniDatasCache=(aniDatas[key])|| (aniDatas[key]=[]); aniDatasCache[frameIndex]=data; } __proto.getOriginalData=function(aniIndex,originalData,nodesFrameIndices,frameIndex,playCurTime){ var oneAni=this._anis[aniIndex]; var nodes=oneAni.nodes; var j=0; for (var i=0,n=nodes.length,outOfs=0;i < n;i++){ var node=nodes[i]; var key; key=node.keyFrame[nodesFrameIndices[i][frameIndex]]; node.dataOffset=outOfs; var dt=playCurTime-key.startTime; var lerpType=node.lerpType; if (lerpType){ switch (lerpType){ case 0: case 1: for (j=0;j < node.keyframeWidth;) j+=node.interpolationMethod[j](node,j,originalData,outOfs+j,key.data,dt,null,key.duration,key.nextData); break ; case 2:; var interpolationData=key.interpolationData; var interDataLen=interpolationData.length; var dataIndex=0; for (j=0;j < interDataLen;){ var type=interpolationData[j]; switch (type){ case 6: j+=AnimationTemplet.interpolation[type](node,dataIndex,originalData,outOfs+dataIndex,key.data,dt,null,key.duration,key.nextData,interpolationData,j+1); break ; case 7: j+=AnimationTemplet.interpolation[type](node,dataIndex,originalData,outOfs+dataIndex,key.data,dt,null,key.duration,key.nextData,interpolationData,j+1); break ; default : j+=AnimationTemplet.interpolation[type](node,dataIndex,originalData,outOfs+dataIndex,key.data,dt,null,key.duration,key.nextData); } dataIndex++; } break ; } }else { for (j=0;j < node.keyframeWidth;) j+=node.interpolationMethod[j](node,j,originalData,outOfs+j,key.data,dt,null,key.duration,key.nextData); } outOfs+=node.keyframeWidth; } } __proto.getNodesCurrentFrameIndex=function(aniIndex,playCurTime){ var ani=this._anis[aniIndex]; var nodes=ani.nodes; if (aniIndex!==this.unfixedLastAniIndex){ this.unfixedCurrentFrameIndexes=new Uint32Array(nodes.length); this.unfixedCurrentTimes=new Float32Array(nodes.length); this.unfixedLastAniIndex=aniIndex; } for (var i=0,n=nodes.length,outOfs=0;i < n;i++){ var node=nodes[i]; if (playCurTime < this.unfixedCurrentTimes[i]) this.unfixedCurrentFrameIndexes[i]=0; this.unfixedCurrentTimes[i]=playCurTime; while ((this.unfixedCurrentFrameIndexes[i] < node.keyFrame.length)){ if (node.keyFrame[this.unfixedCurrentFrameIndexes[i]].startTime > this.unfixedCurrentTimes[i]) break ; this.unfixedCurrentFrameIndexes[i]++; } this.unfixedCurrentFrameIndexes[i]--; } return this.unfixedCurrentFrameIndexes; } __proto.getOriginalDataUnfixedRate=function(aniIndex,originalData,playCurTime){ var oneAni=this._anis[aniIndex]; var nodes=oneAni.nodes; if (aniIndex!==this.unfixedLastAniIndex){ this.unfixedCurrentFrameIndexes=new Uint32Array(nodes.length); this.unfixedCurrentTimes=new Float32Array(nodes.length); this.unfixedKeyframes=__newvec(nodes.length); this.unfixedLastAniIndex=aniIndex; }; var j=0; for (var i=0,n=nodes.length,outOfs=0;i < n;i++){ var node=nodes[i]; if (playCurTime < this.unfixedCurrentTimes[i]) this.unfixedCurrentFrameIndexes[i]=0; this.unfixedCurrentTimes[i]=playCurTime; while (this.unfixedCurrentFrameIndexes[i] < node.keyFrame.length){ if (node.keyFrame[this.unfixedCurrentFrameIndexes[i]].startTime > this.unfixedCurrentTimes[i]) break ; this.unfixedKeyframes[i]=node.keyFrame[this.unfixedCurrentFrameIndexes[i]]; this.unfixedCurrentFrameIndexes[i]++; }; var key=this.unfixedKeyframes[i]; node.dataOffset=outOfs; var dt=playCurTime-key.startTime; var lerpType=node.lerpType; if (lerpType){ switch (node.lerpType){ case 0: case 1: for (j=0;j < node.keyframeWidth;) j+=node.interpolationMethod[j](node,j,originalData,outOfs+j,key.data,dt,null,key.duration,key.nextData); break ; case 2:; var interpolationData=key.interpolationData; var interDataLen=interpolationData.length; var dataIndex=0; for (j=0;j < interDataLen;){ var type=interpolationData[j]; switch (type){ case 6: j+=AnimationTemplet.interpolation[type](node,dataIndex,originalData,outOfs+dataIndex,key.data,dt,null,key.duration,key.nextData,interpolationData,j+1); break ; case 7: j+=AnimationTemplet.interpolation[type](node,dataIndex,originalData,outOfs+dataIndex,key.data,dt,null,key.duration,key.nextData,interpolationData,j+1); break ; default : j+=AnimationTemplet.interpolation[type](node,dataIndex,originalData,outOfs+dataIndex,key.data,dt,null,key.duration,key.nextData); } dataIndex++; } break ; } }else { for (j=0;j < node.keyframeWidth;) j+=node.interpolationMethod[j](node,j,originalData,outOfs+j,key.data,dt,null,key.duration,key.nextData); } outOfs+=node.keyframeWidth; } } AnimationTemplet._LinearInterpolation_0=function(bone,index,out,outOfs,data,dt,dData,duration,nextData,interData){ var amount=duration===0 ? 0 :dt / duration; out[outOfs]=(1.0-amount)*data[index]+amount *nextData[index]; return 1; } AnimationTemplet._QuaternionInterpolation_1=function(bone,index,out,outOfs,data,dt,dData,duration,nextData,interData){ var amount=duration===0 ? 0 :dt / duration; MathUtil.slerpQuaternionArray(data,index,nextData,index,amount,out,outOfs); return 4; } AnimationTemplet._AngleInterpolation_2=function(bone,index,out,outOfs,data,dt,dData,duration,nextData,interData){ return 0; } AnimationTemplet._RadiansInterpolation_3=function(bone,index,out,outOfs,data,dt,dData,duration,nextData,interData){ return 0; } AnimationTemplet._Matrix4x4Interpolation_4=function(bone,index,out,outOfs,data,dt,dData,duration,nextData,interData){ for (var i=0;i < 16;i++,index++) out[outOfs+i]=data[index]+dt *dData[index]; return 16; } AnimationTemplet._NoInterpolation_5=function(bone,index,out,outOfs,data,dt,dData,duration,nextData,interData){ out[outOfs]=data[index]; return 1; } AnimationTemplet._BezierInterpolation_6=function(bone,index,out,outOfs,data,dt,dData,duration,nextData,interData,offset){ (offset===void 0)&& (offset=0); out[outOfs]=data[index]+(nextData[index]-data[index])*BezierLerp.getBezierRate(dt / duration,interData[offset],interData[offset+1],interData[offset+2],interData[offset+3]); return 5; } AnimationTemplet._BezierInterpolation_7=function(bone,index,out,outOfs,data,dt,dData,duration,nextData,interData,offset){ (offset===void 0)&& (offset=0); out[outOfs]=interData[offset+4]+interData[offset+5] *BezierLerp.getBezierRate((dt *0.001+interData[offset+6])/ interData[offset+7],interData[offset],interData[offset+1],interData[offset+2],interData[offset+3]); return 9; } AnimationTemplet.load=function(url){ return Laya.loader.create(url,null,null,AnimationTemplet); } AnimationTemplet.interpolation=[AnimationTemplet._LinearInterpolation_0,AnimationTemplet._QuaternionInterpolation_1,AnimationTemplet._AngleInterpolation_2,AnimationTemplet._RadiansInterpolation_3,AnimationTemplet._Matrix4x4Interpolation_4,AnimationTemplet._NoInterpolation_5,AnimationTemplet._BezierInterpolation_6,AnimationTemplet._BezierInterpolation_7]; return AnimationTemplet; })(Resource) /** *@private *将mesh元素缓存到canvas中并进行绘制 */ //class laya.ani.bone.canvasmesh.CacheAbleSkinMesh extends laya.ani.bone.canvasmesh.SkinMeshCanvas var CacheAbleSkinMesh=(function(_super){ function CacheAbleSkinMesh(){ this.isCached=false; this.canvas=null; this.tex=null; this.rec=null; CacheAbleSkinMesh.__super.call(this); } __class(CacheAbleSkinMesh,'laya.ani.bone.canvasmesh.CacheAbleSkinMesh',_super); var __proto=CacheAbleSkinMesh.prototype; __proto.getCanvasPic=function(){ var canvas=new HTMLCanvas("2D"); var ctx=canvas.getContext('2d'); this.rec=this.mesh.getBounds(); debugger; canvas.size(this.rec.width,this.rec.height); var preTransform; preTransform=this.transform; this.transform=CacheAbleSkinMesh.tempMt; this.transform.identity(); this.transform.translate(-this.rec.x,-this.rec.y); this.renderToContext(ctx); this.transform.translate(+this.rec.x,+this.rec.y); this.transform=preTransform; return new Texture(canvas); } __proto.render=function(context,x,y){ if (!this.mesh.texture)return; if (!this.isCached){ this.isCached=true; this.tex=this.getCanvasPic(); } if(!this.transform){ this.transform=SkinMeshCanvas._tempMatrix; this.transform.identity(); this.transform.translate(x,y); this._renderTextureToContext(context); this.transform.translate(-x,-y); this.transform=null; }else{ this.transform.translate(x,y); this._renderTextureToContext(context); this.transform.translate(-x,-y); } } __proto._renderTextureToContext=function(context){ this.context=context.ctx || context; context.save(); var texture; texture=this.tex; if (this.transform){ var mt=this.transform; context.transform(mt.a,mt.b,mt.c,mt.d,mt.tx,mt.ty); } this.rec=this.mesh.getBounds(); context.translate(this.rec.x,this.rec.y); context.drawTexture(texture,0,0,texture.width,texture.height,0,0); context.restore(); } __static(CacheAbleSkinMesh, ['tempMt',function(){return this.tempMt=new Matrix();} ]); return CacheAbleSkinMesh; })(SkinMeshCanvas) /** *@private *简化mesh绘制,多顶点mesh改为四顶点mesh,只绘制矩形不绘制三角形 */ //class laya.ani.bone.canvasmesh.SimpleSkinMeshCanvas extends laya.ani.bone.canvasmesh.SkinMeshCanvas var SimpleSkinMeshCanvas=(function(_super){ function SimpleSkinMeshCanvas(){ /** *当前mesh数据是否可用 */ this.cacheOK=false; /** *当前渲染数据是否可用 */ this.cacheCmdOK=false; /** *transform参数缓存 */ this.transformCmds=[]; /** *drawImage参数缓存 */ this.drawCmds=[] SimpleSkinMeshCanvas.__super.call(this); this.tempMesh=new MeshData(); } __class(SimpleSkinMeshCanvas,'laya.ani.bone.canvasmesh.SimpleSkinMeshCanvas',_super); var __proto=SimpleSkinMeshCanvas.prototype; __proto.init2=function(texture,vs,ps,verticles,uvs){ _super.prototype.init2.call(this,texture,vs,ps,verticles,uvs); this.cacheOK=false; this.cacheCmdOK=false; this.transformCmds.length=6; this.drawCmds.length=9; } __proto.renderToContext=function(context){ this.context=context.ctx || context; if (this.mesh){ if (this.mesh.uvs.length <=8){ if (this.mode==0){ this._renderWithIndexes(this.mesh); } else { this._renderNoIndexes(this.mesh); } return; } if (!this.cacheOK){ this.tempMesh.texture=this.mesh.texture; this.tempMesh.uvs=this.mesh.texture.uv; this.tempMesh.vertices=MeshTools.solveMesh(this.mesh,this.tempMesh.vertices); this.cacheOK=true; } if (this.mode==0){ this._renderWithIndexes(this.tempMesh); } else { this._renderNoIndexes(this.tempMesh); } } } __proto._renderWithIndexes=function(mesh){ if(this.cacheCmdOK){ this.renderByCache(mesh); return; }; var indexes=mesh.indexes; var i=0,len=indexes.length; if (len > 1) len=1; for (i=0;i < len;i+=3){ var index0=indexes[i] *2; var index1=indexes[i+1] *2; var index2=indexes[i+2] *2; this._renderDrawTriangle(mesh,index0,index1,index2); } this.cacheCmdOK=true; } __proto._renderDrawTriangle=function(mesh,index0,index1,index2){ var context=this.context; var uvs=mesh.uvs; var vertices=mesh.vertices; var texture=mesh.texture; var source=texture.bitmap; var textureSource=source.source; var textureWidth=texture.width; var textureHeight=texture.height; var sourceWidth=source.width; var sourceHeight=source.height; var u0=NaN; var u1=NaN; var u2=NaN; var v0=NaN; var v1=NaN; var v2=NaN; if (mesh.useUvTransform){ var ut=mesh.uvTransform; u0=((uvs[index0] *ut.a)+(uvs[index0+1] *ut.c)+ut.tx)*sourceWidth; u1=((uvs[index1] *ut.a)+(uvs[index1+1] *ut.c)+ut.tx)*sourceWidth; u2=((uvs[index2] *ut.a)+(uvs[index2+1] *ut.c)+ut.tx)*sourceWidth; v0=((uvs[index0] *ut.b)+(uvs[index0+1] *ut.d)+ut.ty)*sourceHeight; v1=((uvs[index1] *ut.b)+(uvs[index1+1] *ut.d)+ut.ty)*sourceHeight; v2=((uvs[index2] *ut.b)+(uvs[index2+1] *ut.d)+ut.ty)*sourceHeight; } else { u0=uvs[index0] *sourceWidth; u1=uvs[index1] *sourceWidth; u2=uvs[index2] *sourceWidth; v0=uvs[index0+1] *sourceHeight; v1=uvs[index1+1] *sourceHeight; v2=uvs[index2+1] *sourceHeight; }; var x0=vertices[index0]; var x1=vertices[index1]; var x2=vertices[index2]; var y0=vertices[index0+1]; var y1=vertices[index1+1]; var y2=vertices[index2+1]; var delta=(u0 *v1)+(v0 *u2)+(u1 *v2)-(v1 *u2)-(v0 *u1)-(u0 *v2); var dDelta=1 / delta; var deltaA=(x0 *v1)+(v0 *x2)+(x1 *v2)-(v1 *x2)-(v0 *x1)-(x0 *v2); var deltaB=(u0 *x1)+(x0 *u2)+(u1 *x2)-(x1 *u2)-(x0 *u1)-(u0 *x2); var deltaC=(u0 *v1 *x2)+(v0 *x1 *u2)+(x0 *u1 *v2)-(x0 *v1 *u2)-(v0 *u1 *x2)-(u0 *x1 *v2); var deltaD=(y0 *v1)+(v0 *y2)+(y1 *v2)-(v1 *y2)-(v0 *y1)-(y0 *v2); var deltaE=(u0 *y1)+(y0 *u2)+(u1 *y2)-(y1 *u2)-(y0 *u1)-(u0 *y2); var deltaF=(u0 *v1 *y2)+(v0 *y1 *u2)+(y0 *u1 *v2)-(y0 *v1 *u2)-(v0 *u1 *y2)-(u0 *y1 *v2); this.transformCmds[0]=deltaA *dDelta; this.transformCmds[1]=deltaD *dDelta; this.transformCmds[2]=deltaB *dDelta; this.transformCmds[3]=deltaE *dDelta; this.transformCmds[4]=deltaC *dDelta; this.transformCmds[5]=deltaF *dDelta; this.drawCmds[0]=textureSource; this.drawCmds[1]=texture.uv[0] *sourceWidth; this.drawCmds[2]=texture.uv[1] *sourceHeight; this.drawCmds[3]=textureWidth; this.drawCmds[4]=textureHeight; this.drawCmds[5]=texture.uv[0] *sourceWidth; this.drawCmds[6]=texture.uv[1] *sourceHeight; this.drawCmds[7]=textureWidth; this.drawCmds[8]=textureHeight; context.save(); if (this.transform){ var mt=this.transform; context.transform(mt.a,mt.b,mt.c,mt.d,mt.tx,mt.ty); } context.transform.apply(context,this.transformCmds); context.drawImage.apply(context,this.drawCmds); context.restore(); } /** *绘制缓存的命令 *@param mesh * */ __proto.renderByCache=function(mesh){ var context=this.context; context.save(); if (this.transform){ var mt=this.transform; context.transform(mt.a,mt.b,mt.c,mt.d,mt.tx,mt.ty); } context.transform.apply(context,this.transformCmds); context.drawImage.apply(context,this.drawCmds); context.restore(); } return SimpleSkinMeshCanvas; })(SkinMeshCanvas) /** *骨骼动画由TempletAnimationPlayerSkeleton三部分组成。 */ //class laya.ani.bone.Skeleton extends laya.display.Sprite var Skeleton=(function(_super){ function Skeleton(templet,aniMode){ this._templet=null; /**@private */ this._player=null; /**@private */ this._curOriginalData=null; //当前骨骼的偏移数据 this._boneMatrixArray=[]; //当前骨骼动画的最终结果数据 this._lastTime=0; //上次的帧时间 this._currAniName=null; this._currAniIndex=-1; this._pause=true; /**@private */ this._aniClipIndex=-1; /**@private */ this._clipIndex=-1; this._skinIndex=0; this._skinName="default"; this._aniMode=0; //当前动画自己的缓冲区 this._graphicsCache=null; this._boneSlotDic=null; this._bindBoneBoneSlotDic=null; this._boneSlotArray=null; this._index=-1; this._total=-1; this._indexControl=false; //加载路径 this._aniPath=null; this._texturePath=null; this._complete=null; this._loadAniMode=0; this._yReverseMatrix=null; this._ikArr=null; this._tfArr=null; this._pathDic=null; this._rootBone=null; /**@private */ this._boneList=null; /**@private */ this._aniSectionDic=null; this._eventIndex=0; this._drawOrderIndex=0; this._drawOrder=null; this._lastAniClipIndex=-1; this._lastUpdateAniClipIndex=-1; this._playAudio=true; this._soundChannelArr=[]; Skeleton.__super.call(this); (aniMode===void 0)&& (aniMode=0); if (templet)this.init(templet,aniMode); } __class(Skeleton,'laya.ani.bone.Skeleton',_super); var __proto=Skeleton.prototype; /** *初始化动画 *@param templet 模板 *@param aniMode 动画模式 * * * * * * * * * * * *
    模式描述
    0 使用模板缓冲的数据,模板缓冲的数据,不允许修改(内存开销小,计算开销小,不支持换装)
    1 使用动画自己的缓冲区,每个动画都会有自己的缓冲区,相当耗费内存 (内存开销大,计算开销小,支持换装)
    2 使用动态方式,去实时去画(内存开销小,计算开销大,支持换装,不建议使用)
    */ __proto.init=function(templet,aniMode){ (aniMode===void 0)&& (aniMode=0); var i=0,n=0; if (aniMode==1){ this._graphicsCache=[]; for (i=0,n=templet.getAnimationCount();i < n;i++){ this._graphicsCache.push([]); } } this._yReverseMatrix=templet.yReverseMatrix; this._aniMode=aniMode; this._templet=templet; this._player=new AnimationPlayer(); this._player.cacheFrameRate=templet.rate; this._player.templet=templet; this._player.play(); this._parseSrcBoneMatrix(); this._boneList=templet.mBoneArr; this._rootBone=templet.mRootBone; this._aniSectionDic=templet.aniSectionDic; if (templet.ikArr.length > 0){ this._ikArr=[]; for (i=0,n=templet.ikArr.length;i < n;i++){ this._ikArr.push(new IkConstraint(templet.ikArr[i],this._boneList)); } } if (templet.pathArr.length > 0){ var tPathData; var tPathConstraint; if (this._pathDic==null)this._pathDic={}; var tBoneSlot; for (i=0,n=templet.pathArr.length;i < n;i++){ tPathData=templet.pathArr[i]; tPathConstraint=new PathConstraint(tPathData,this._boneList); tBoneSlot=this._boneSlotDic[tPathData.name]; if (tBoneSlot){ tPathConstraint=new PathConstraint(tPathData,this._boneList); tPathConstraint.target=tBoneSlot; } this._pathDic[tPathData.name]=tPathConstraint; } } if (templet.tfArr.length > 0){ this._tfArr=[]; for (i=0,n=templet.tfArr.length;i < n;i++){ this._tfArr.push(new TfConstraint(templet.tfArr[i],this._boneList)); } } if (templet.skinDataArray.length > 0){ var tSkinData=this._templet.skinDataArray[this._skinIndex]; this._skinName=tSkinData.name; } this._player.on(/*laya.events.Event.PLAYED*/"played",this,this._onPlay); this._player.on(/*laya.events.Event.STOPPED*/"stopped",this,this._onStop); this._player.on(/*laya.events.Event.PAUSED*/"paused",this,this._onPause); } /** *通过加载直接创建动画 *@param path 要加载的动画文件路径 *@param complete 加载完成的回调函数 *@param aniMode 与Skeleton.initaniMode作用一致 */ __proto.load=function(path,complete,aniMode){ (aniMode===void 0)&& (aniMode=0); this._aniPath=path; this._complete=complete; this._loadAniMode=aniMode; Laya.loader.load([{url:path,type:/*laya.net.Loader.BUFFER*/"arraybuffer"}],Handler.create(this,this._onLoaded)); } /** *加载完成 */ __proto._onLoaded=function(){ var arraybuffer=Loader.getRes(this._aniPath); if (arraybuffer==null)return; if (Templet.TEMPLET_DICTIONARY==null){ Templet.TEMPLET_DICTIONARY={}; }; var tFactory; tFactory=Templet.TEMPLET_DICTIONARY[this._aniPath]; if (tFactory){ if (tFactory.isParseFail){ this._parseFail(); }else { if (tFactory.isParserComplete){ this._parseComplete(); }else { tFactory.on(/*laya.events.Event.COMPLETE*/"complete",this,this._parseComplete); tFactory.on(/*laya.events.Event.ERROR*/"error",this,this._parseFail); } } }else { tFactory=new Templet(); tFactory._setUrl(this._aniPath); Templet.TEMPLET_DICTIONARY[this._aniPath]=tFactory; tFactory.on(/*laya.events.Event.COMPLETE*/"complete",this,this._parseComplete); tFactory.on(/*laya.events.Event.ERROR*/"error",this,this._parseFail); tFactory.isParserComplete=false; tFactory.parseData(null,arraybuffer); } } /** *解析完成 */ __proto._parseComplete=function(){ var tTemple=Templet.TEMPLET_DICTIONARY[this._aniPath]; if (tTemple){ this.init(tTemple,this._loadAniMode); this.play(0,true); } this._complete && this._complete.runWith(this); } /** *解析失败 */ __proto._parseFail=function(){ console.log("[Error]:"+this._aniPath+"解析失败"); } /** *传递PLAY事件 */ __proto._onPlay=function(){ this.event(/*laya.events.Event.PLAYED*/"played"); } /** *传递STOP事件 */ __proto._onStop=function(){ var tEventData; var tEventAniArr=this._templet.eventAniArr; var tEventArr=tEventAniArr[this._aniClipIndex]; if (tEventArr && this._eventIndex < tEventArr.length){ for (;this._eventIndex < tEventArr.length;this._eventIndex++){ tEventData=tEventArr[this._eventIndex]; if (tEventData.time >=this._player.playStart && tEventData.time <=this._player.playEnd){ this.event(/*laya.events.Event.LABEL*/"label",tEventData); } } } this._drawOrder=null; this.event(/*laya.events.Event.STOPPED*/"stopped"); } /** *传递PAUSE事件 */ __proto._onPause=function(){ this.event(/*laya.events.Event.PAUSED*/"paused"); } /** *创建骨骼的矩阵,保存每次计算的最终结果 */ __proto._parseSrcBoneMatrix=function(){ var i=0,n=0; n=this._templet.srcBoneMatrixArr.length; for (i=0;i < n;i++){ this._boneMatrixArray.push(new Matrix()); } if (this._aniMode==0){ this._boneSlotDic=this._templet.boneSlotDic; this._bindBoneBoneSlotDic=this._templet.bindBoneBoneSlotDic; this._boneSlotArray=this._templet.boneSlotArray; }else { if (this._boneSlotDic==null)this._boneSlotDic={}; if (this._bindBoneBoneSlotDic==null)this._bindBoneBoneSlotDic={}; if (this._boneSlotArray==null)this._boneSlotArray=[]; var tArr=this._templet.boneSlotArray; var tBS; var tBSArr; for (i=0,n=tArr.length;i < n;i++){ tBS=tArr[i]; tBSArr=this._bindBoneBoneSlotDic[tBS.parent]; if (tBSArr==null){ this._bindBoneBoneSlotDic[tBS.parent]=tBSArr=[]; } this._boneSlotDic[tBS.name]=tBS=tBS.copy(); tBSArr.push(tBS); this._boneSlotArray.push(tBS); } } } __proto._emitMissedEvents=function(startTime,endTime,startIndex){ (startIndex===void 0)&& (startIndex=0); var tEventAniArr=this._templet.eventAniArr; var tEventArr=tEventAniArr[this._player.currentAnimationClipIndex]; if (tEventArr){ var i=0,len=0; var tEventData; len=tEventArr.length; for (i=startIndex;i < len;i++){ tEventData=tEventArr[i]; if (tEventData.time >=this._player.playStart && tEventData.time <=this._player.playEnd){ this.event(/*laya.events.Event.LABEL*/"label",tEventData); } } } } /** *更新动画 *@param autoKey true为正常更新,false为index手动更新 */ __proto._update=function(autoKey){ (autoKey===void 0)&& (autoKey=true); if (this._pause)return; if (autoKey && this._indexControl){ return; }; var tCurrTime=this.timer.currTimer; var preIndex=this._player.currentKeyframeIndex; var dTime=tCurrTime-this._lastTime; if (autoKey){ this._player._update(dTime); }else { preIndex=-1; } this._lastTime=tCurrTime; if (!this._player)return; this._index=this._clipIndex=this._player.currentKeyframeIndex; if (this._index < 0)return; if (dTime > 0 && this._clipIndex==preIndex && this._lastUpdateAniClipIndex==this._aniClipIndex){ return; } this._lastUpdateAniClipIndex=this._aniClipIndex; if (preIndex > this._clipIndex && this._eventIndex !=0){ this._emitMissedEvents(this._player.playStart,this._player.playEnd,this._eventIndex); this._eventIndex=0; }; var tEventData; var tEventAniArr=this._templet.eventAniArr; var tEventArr=tEventAniArr[this._aniClipIndex]; var _soundChannel; if (tEventArr && this._eventIndex < tEventArr.length){ tEventData=tEventArr[this._eventIndex]; if (tEventData.time >=this._player.playStart && tEventData.time <=this._player.playEnd){ if (this._player.currentPlayTime >=tEventData.time){ this.event(/*laya.events.Event.LABEL*/"label",tEventData); this._eventIndex++; if (this._playAudio && tEventData.audioValue && tEventData.audioValue!=="null"){ _soundChannel=SoundManager.playSound(this._player.templet._path+tEventData.audioValue,1,Handler.create(this,this._onAniSoundStoped)); SoundManager.playbackRate=this._player.playbackRate; _soundChannel && this._soundChannelArr.push(_soundChannel); } } }else if (tEventData.time < this._player.playStart && this._playAudio && tEventData.audioValue && tEventData.audioValue!=="null"){ this._eventIndex++; _soundChannel=SoundManager.playSound(this._player.templet._path+tEventData.audioValue,1,Handler.create(this,this._onAniSoundStoped),null,(this._player.currentPlayTime-tEventData.time)/ 1000); SoundManager.playbackRate=this._player.playbackRate; _soundChannel && this._soundChannelArr.push(_soundChannel); }else { this._eventIndex++; } }; var tGraphics; if (this._aniMode==0){ tGraphics=this._templet.getGrahicsDataWithCache(this._aniClipIndex,this._clipIndex); if (tGraphics){ if (this.graphics !=tGraphics){ this.graphics=tGraphics; } return; }else { var i=0,minIndex=0; minIndex=this._clipIndex; while ((!this._templet.getGrahicsDataWithCache(this._aniClipIndex,minIndex-1))&& (minIndex > 0)){ minIndex--; } if (minIndex < this._clipIndex){ for (i=minIndex;i < this._clipIndex;i++){ this._createGraphics(i); } } } }else if (this._aniMode==1){ tGraphics=this._getGrahicsDataWithCache(this._aniClipIndex,this._clipIndex); if (tGraphics){ if (this.graphics !=tGraphics){ this.graphics=tGraphics; } return; }else { minIndex=this._clipIndex; while ((!this._getGrahicsDataWithCache(this._aniClipIndex,minIndex-1))&& (minIndex > 0)){ minIndex--; } if (minIndex < this._clipIndex){ for (i=minIndex;i < this._clipIndex;i++){ this._createGraphics(i); } } } } this._createGraphics(); } /** *@private *清掉播放完成的音频 *@param force 是否强制删掉所有的声音channel */ __proto._onAniSoundStoped=function(force){ var _channel; for (var len=this._soundChannelArr.length,i=0;i < len;i++){ _channel=this._soundChannelArr[i]; if (_channel.isStopped || force){ !_channel.isStopped && _channel.stop(); this._soundChannelArr.splice(i,1); len--;i--; } } } /** *@private *创建grahics图像 */ __proto._createGraphics=function(_clipIndex){ (_clipIndex===void 0)&& (_clipIndex=-1); if (_clipIndex==-1)_clipIndex=this._clipIndex; var curTime=_clipIndex *this._player.cacheFrameRateInterval; var tDrawOrderData; var tDrawOrderAniArr=this._templet.drawOrderAniArr; var tDrawOrderArr=tDrawOrderAniArr[this._aniClipIndex]; if (tDrawOrderArr && tDrawOrderArr.length > 0){ this._drawOrderIndex=0; tDrawOrderData=tDrawOrderArr[this._drawOrderIndex]; while (curTime >=tDrawOrderData.time){ this._drawOrder=tDrawOrderData.drawOrder; this._drawOrderIndex++; if (this._drawOrderIndex >=tDrawOrderArr.length){ break ; } tDrawOrderData=tDrawOrderArr[this._drawOrderIndex]; } }; var tGraphics; if (this._aniMode==0 || this._aniMode==1){ this.graphics=GraphicsAni.create(); }else { if ((this.graphics instanceof laya.ani.GraphicsAni )){ this.graphics.clear(); }else { this.graphics=GraphicsAni.create(); } } tGraphics=this.graphics; var bones=this._templet.getNodes(this._aniClipIndex); this._templet.getOriginalData(this._aniClipIndex,this._curOriginalData,this._player._fullFrames[this._aniClipIndex],_clipIndex,curTime); var tSectionArr=this._aniSectionDic[this._aniClipIndex]; var tParentMatrix; var tStartIndex=0; var i=0,j=0,k=0,n=0; var tDBBoneSlot; var tDBBoneSlotArr; var tParentTransform; var tSrcBone; var boneCount=this._templet.srcBoneMatrixArr.length; for (i=0,n=tSectionArr[0];i < boneCount;i++){ tSrcBone=this._boneList[i]; tParentTransform=this._templet.srcBoneMatrixArr[i]; tSrcBone.resultTransform.scX=tParentTransform.scX *this._curOriginalData[tStartIndex++]; tSrcBone.resultTransform.skX=tParentTransform.skX+this._curOriginalData[tStartIndex++]; tSrcBone.resultTransform.skY=tParentTransform.skY+this._curOriginalData[tStartIndex++]; tSrcBone.resultTransform.scY=tParentTransform.scY *this._curOriginalData[tStartIndex++]; tSrcBone.resultTransform.x=tParentTransform.x+this._curOriginalData[tStartIndex++]; tSrcBone.resultTransform.y=tParentTransform.y+this._curOriginalData[tStartIndex++]; if (this._templet.tMatrixDataLen===8){ tSrcBone.resultTransform.skewX=tParentTransform.skewX+this._curOriginalData[tStartIndex++]; tSrcBone.resultTransform.skewY=tParentTransform.skewY+this._curOriginalData[tStartIndex++]; } }; var tSlotDic={}; var tSlotAlphaDic={}; var tBoneData; for (n+=tSectionArr[1];i < n;i++){ tBoneData=bones[i]; tSlotDic[tBoneData.name]=this._curOriginalData[tStartIndex++]; tSlotAlphaDic[tBoneData.name]=this._curOriginalData[tStartIndex++]; this._curOriginalData[tStartIndex++]; this._curOriginalData[tStartIndex++]; this._curOriginalData[tStartIndex++]; this._curOriginalData[tStartIndex++]; }; var tBendDirectionDic={}; var tMixDic={}; for (n+=tSectionArr[2];i < n;i++){ tBoneData=bones[i]; tBendDirectionDic[tBoneData.name]=this._curOriginalData[tStartIndex++]; tMixDic[tBoneData.name]=this._curOriginalData[tStartIndex++]; this._curOriginalData[tStartIndex++]; this._curOriginalData[tStartIndex++]; this._curOriginalData[tStartIndex++]; this._curOriginalData[tStartIndex++]; } if (this._pathDic){ var tPathConstraint; for (n+=tSectionArr[3];i < n;i++){ tBoneData=bones[i]; tPathConstraint=this._pathDic[tBoneData.name]; if (tPathConstraint){ var tByte=new Byte(tBoneData.extenData); switch (tByte.getByte()){ case 1: tPathConstraint.position=this._curOriginalData[tStartIndex++]; break ; case 2: tPathConstraint.spacing=this._curOriginalData[tStartIndex++]; break ; case 3: tPathConstraint.rotateMix=this._curOriginalData[tStartIndex++]; tPathConstraint.translateMix=this._curOriginalData[tStartIndex++]; break ; } } } } if (this._yReverseMatrix){ this._rootBone.update(this._yReverseMatrix); }else { this._rootBone.update(Matrix.TEMP.identity()); } if (this._ikArr){ var tIkConstraint; for (i=0,n=this._ikArr.length;i < n;i++){ tIkConstraint=this._ikArr[i]; if (tBendDirectionDic.hasOwnProperty(tIkConstraint.name)){ tIkConstraint.bendDirection=tBendDirectionDic[tIkConstraint.name]; } if (tMixDic.hasOwnProperty(tIkConstraint.name)){ tIkConstraint.mix=tMixDic[tIkConstraint.name] } tIkConstraint.apply(); } } if (this._pathDic){ for (var tPathStr in this._pathDic){ tPathConstraint=this._pathDic[tPathStr]; tPathConstraint.apply(this._boneList,tGraphics); } } if (this._tfArr){ var tTfConstraint; for (i=0,k=this._tfArr.length;i < k;i++){ tTfConstraint=this._tfArr[i]; tTfConstraint.apply(); } } for (i=0,k=this._boneList.length;i < k;i++){ tSrcBone=this._boneList[i]; tDBBoneSlotArr=this._bindBoneBoneSlotDic[tSrcBone.name]; tSrcBone.resultMatrix.copyTo(this._boneMatrixArray[i]); if (tDBBoneSlotArr){ for (j=0,n=tDBBoneSlotArr.length;j < n;j++){ tDBBoneSlot=tDBBoneSlotArr[j]; if (tDBBoneSlot){ tDBBoneSlot.setParentMatrix(tSrcBone.resultMatrix); } } } }; var tDeformDic={}; var tDeformAniArr=this._templet.deformAniArr; var tDeformAniData; var tDeformSlotData; var tDeformSlotDisplayData; if (tDeformAniArr && tDeformAniArr.length > 0){ if (this._lastAniClipIndex !=this._aniClipIndex){ this._lastAniClipIndex=this._aniClipIndex; for (i=0,n=this._boneSlotArray.length;i < n;i++){ tDBBoneSlot=this._boneSlotArray[i]; tDBBoneSlot.deformData=null; } }; var tSkinDeformAni=tDeformAniArr[this._aniClipIndex]; tDeformAniData=(tSkinDeformAni["default"]); this._setDeform(tDeformAniData,tDeformDic,this._boneSlotArray,curTime); var tSkin; for (tSkin in tSkinDeformAni){ if (tSkin !="default" && tSkin !=this._skinName){ tDeformAniData=tSkinDeformAni [tSkin]; this._setDeform(tDeformAniData,tDeformDic,this._boneSlotArray,curTime); } } tDeformAniData=(tSkinDeformAni[this._skinName]); this._setDeform(tDeformAniData,tDeformDic,this._boneSlotArray,curTime); }; var tSlotData2; var tSlotData3; var tObject; if (this._drawOrder){ for (i=0,n=this._drawOrder.length;i < n;i++){ tDBBoneSlot=this._boneSlotArray[this._drawOrder[i]]; tSlotData2=tSlotDic[tDBBoneSlot.name]; tSlotData3=tSlotAlphaDic[tDBBoneSlot.name]; if (!isNaN(tSlotData3)){ tGraphics.save(); tGraphics.alpha(tSlotData3); } if (!isNaN(tSlotData2)&& tSlotData2 !=-2){ if (this._templet.attachmentNames){ tDBBoneSlot.showDisplayByName(this._templet.attachmentNames[tSlotData2]); }else { tDBBoneSlot.showDisplayByIndex(tSlotData2); } } if (tDeformDic[this._drawOrder[i]]){ tObject=tDeformDic[this._drawOrder[i]]; if (tDBBoneSlot.currDisplayData && tObject[tDBBoneSlot.currDisplayData.attachmentName]){ tDBBoneSlot.deformData=tObject[tDBBoneSlot.currDisplayData.attachmentName]; }else { tDBBoneSlot.deformData=null; } }else { tDBBoneSlot.deformData=null; } if (!isNaN(tSlotData3)){ tDBBoneSlot.draw(tGraphics,this._boneMatrixArray,this._aniMode==2,tSlotData3); }else { tDBBoneSlot.draw(tGraphics,this._boneMatrixArray,this._aniMode==2); } if (!isNaN(tSlotData3)){ tGraphics.restore(); } } }else { for (i=0,n=this._boneSlotArray.length;i < n;i++){ tDBBoneSlot=this._boneSlotArray[i]; tSlotData2=tSlotDic[tDBBoneSlot.name]; tSlotData3=tSlotAlphaDic[tDBBoneSlot.name]; if (!isNaN(tSlotData3)){ tGraphics.save(); tGraphics.alpha(tSlotData3); } if (!isNaN(tSlotData2)&& tSlotData2 !=-2){ if (this._templet.attachmentNames){ tDBBoneSlot.showDisplayByName(this._templet.attachmentNames[tSlotData2]); }else { tDBBoneSlot.showDisplayByIndex(tSlotData2); } } if (tDeformDic[i]){ tObject=tDeformDic[i]; if (tDBBoneSlot.currDisplayData && tObject[tDBBoneSlot.currDisplayData.attachmentName]){ tDBBoneSlot.deformData=tObject[tDBBoneSlot.currDisplayData.attachmentName]; }else { tDBBoneSlot.deformData=null; } }else { tDBBoneSlot.deformData=null; } if (!isNaN(tSlotData3)){ tDBBoneSlot.draw(tGraphics,this._boneMatrixArray,this._aniMode==2,tSlotData3); }else { tDBBoneSlot.draw(tGraphics,this._boneMatrixArray,this._aniMode==2); } if (!isNaN(tSlotData3)){ tGraphics.restore(); } } } if (this._aniMode==0){ this._templet.setGrahicsDataWithCache(this._aniClipIndex,_clipIndex,tGraphics); }else if (this._aniMode==1){ this._setGrahicsDataWithCache(this._aniClipIndex,_clipIndex,tGraphics); } } /** *设置deform数据 *@param tDeformAniData *@param tDeformDic *@param _boneSlotArray *@param curTime */ __proto._setDeform=function(tDeformAniData,tDeformDic,_boneSlotArray,curTime){ if (!tDeformAniData)return; var tDeformSlotData; var tDeformSlotDisplayData; var tDBBoneSlot; var i=0,n=0,j=0; if (tDeformAniData){ for (i=0,n=tDeformAniData.deformSlotDataList.length;i < n;i++){ tDeformSlotData=tDeformAniData.deformSlotDataList[i]; for (j=0;j < tDeformSlotData.deformSlotDisplayList.length;j++){ tDeformSlotDisplayData=tDeformSlotData.deformSlotDisplayList[j]; tDBBoneSlot=_boneSlotArray[tDeformSlotDisplayData.slotIndex]; tDeformSlotDisplayData.apply(curTime,tDBBoneSlot); if (!tDeformDic[tDeformSlotDisplayData.slotIndex]){ tDeformDic[tDeformSlotDisplayData.slotIndex]={}; } tDeformDic[tDeformSlotDisplayData.slotIndex][tDeformSlotDisplayData.attachment]=tDeformSlotDisplayData.deformData; } } } } /** *得到当前动画的数量 *@return 当前动画的数量 */ __proto.getAnimNum=function(){ return this._templet.getAnimationCount(); } /** *得到指定动画的名字 *@param index 动画的索引 */ __proto.getAniNameByIndex=function(index){ return this._templet.getAniNameByIndex(index); } /** *通过名字得到插槽的引用 *@param name 动画的名字 *@return 插槽的引用 */ __proto.getSlotByName=function(name){ return this._boneSlotDic[name]; } /** *通过名字显示一套皮肤 *@param name 皮肤的名字 *@param freshSlotIndex 是否将插槽纹理重置到初始化状态 */ __proto.showSkinByName=function(name,freshSlotIndex){ (freshSlotIndex===void 0)&& (freshSlotIndex=true); this.showSkinByIndex(this._templet.getSkinIndexByName(name),freshSlotIndex); } /** *通过索引显示一套皮肤 *@param skinIndex 皮肤索引 *@param freshSlotIndex 是否将插槽纹理重置到初始化状态 */ __proto.showSkinByIndex=function(skinIndex,freshSlotIndex){ (freshSlotIndex===void 0)&& (freshSlotIndex=true); for (var i=0;i < this._boneSlotArray.length;i++){ (this._boneSlotArray [i]).showSlotData(null,freshSlotIndex); } if (this._templet.showSkinByIndex(this._boneSlotDic,skinIndex,freshSlotIndex)){ var tSkinData=this._templet.skinDataArray[skinIndex]; this._skinIndex=skinIndex; this._skinName=tSkinData.name; } this._clearCache(); } /** *设置某插槽的皮肤 *@param slotName 插槽名称 *@param index 插糟皮肤的索引 */ __proto.showSlotSkinByIndex=function(slotName,index){ if (this._aniMode==0)return; var tBoneSlot=this.getSlotByName(slotName); if (tBoneSlot){ tBoneSlot.showDisplayByIndex(index); } this._clearCache(); } /** *设置某插槽的皮肤 *@param slotName 插槽名称 *@param name 皮肤名称 */ __proto.showSlotSkinByName=function(slotName,name){ if (this._aniMode==0)return; var tBoneSlot=this.getSlotByName(slotName); if (tBoneSlot){ tBoneSlot.showDisplayByName(name); } this._clearCache(); } /** *替换插槽贴图名 *@param slotName 插槽名称 *@param oldName 要替换的贴图名 *@param newName 替换后的贴图名 */ __proto.replaceSlotSkinName=function(slotName,oldName,newName){ if (this._aniMode==0)return; var tBoneSlot=this.getSlotByName(slotName); if (tBoneSlot){ tBoneSlot.replaceDisplayByName(oldName,newName); } this._clearCache(); } /** *替换插槽的贴图索引 *@param slotName 插槽名称 *@param oldIndex 要替换的索引 *@param newIndex 替换后的索引 */ __proto.replaceSlotSkinByIndex=function(slotName,oldIndex,newIndex){ if (this._aniMode==0)return; var tBoneSlot=this.getSlotByName(slotName); if (tBoneSlot){ tBoneSlot.replaceDisplayByIndex(oldIndex,newIndex); } this._clearCache(); } /** *设置自定义皮肤 *@param name 插糟的名字 *@param texture 自定义的纹理 */ __proto.setSlotSkin=function(slotName,texture){ if (this._aniMode==0)return; var tBoneSlot=this.getSlotByName(slotName); if (tBoneSlot){ tBoneSlot.replaceSkin(texture); } this._clearCache(); } /** *换装的时候,需要清一下缓冲区 */ __proto._clearCache=function(){ if (this._aniMode==1){ for (var i=0,n=this._graphicsCache.length;i < n;i++){ for (var j=0,len=this._graphicsCache[i].length;j < len;j++){ var gp=this._graphicsCache[i][j]; if (gp !=this.graphics){ GraphicsAni.recycle(gp); } } this._graphicsCache[i].length=0; } } } /** *播放动画 * *@param nameOrIndex 动画名字或者索引 *@param loop 是否循环播放 *@param force false,如果要播的动画跟上一个相同就不生效,true,强制生效 *@param start 起始时间 *@param end 结束时间 *@param freshSkin 是否刷新皮肤数据 *@param playAudio 是否播放音频 */ __proto.play=function(nameOrIndex,loop,force,start,end,freshSkin,playAudio){ (force===void 0)&& (force=true); (start===void 0)&& (start=0); (end===void 0)&& (end=0); (freshSkin===void 0)&& (freshSkin=true); (playAudio===void 0)&& (playAudio=true); this._playAudio=playAudio; this._indexControl=false; var index=-1; var duration=NaN; if (loop){ duration=2147483647; }else { duration=0; } if ((typeof nameOrIndex=='string')){ for (var i=0,n=this._templet.getAnimationCount();i < n;i++){ var animation=this._templet.getAnimation(i); if (animation && nameOrIndex==animation.name){ index=i; break ; } } }else { index=nameOrIndex; } if (index >-1 && index < this.getAnimNum()){ this._aniClipIndex=index; if (force || this._pause || this._currAniIndex !=index){ this._currAniIndex=index; this._curOriginalData=new Float32Array(this._templet.getTotalkeyframesLength(index)); this._drawOrder=null; this._eventIndex=0; this._player.play(index,this._player.playbackRate,duration,start,end); if (freshSkin) this._templet.showSkinByIndex(this._boneSlotDic,this._skinIndex); if (this._pause){ this._pause=false; this._lastTime=Browser.now(); this.timer.frameLoop(1,this,this._update,null,true); } this._update(); } } } /** *停止动画 */ __proto.stop=function(){ if (!this._pause){ this._pause=true; if (this._player){ this._player.stop(true); } if (this._soundChannelArr.length > 0){ this._onAniSoundStoped(true); } this.timer.clear(this,this._update); } } /** *设置动画播放速率 *@param value 1为标准速率 */ __proto.playbackRate=function(value){ if (this._player){ this._player.playbackRate=value; } } /** *暂停动画的播放 */ __proto.paused=function(){ if (!this._pause){ this._pause=true; if (this._player){ this._player.paused=true; } if (this._soundChannelArr.length > 0){ var _soundChannel; for (var len=this._soundChannelArr.length,i=0;i < len;i++){ _soundChannel=this._soundChannelArr[i]; if (!_soundChannel.isStopped){ _soundChannel.pause(); } } } this.timer.clear(this,this._update); } } /** *恢复动画的播放 */ __proto.resume=function(){ this._indexControl=false; if (this._pause){ this._pause=false; if (this._player){ this._player.paused=false; } if (this._soundChannelArr.length > 0){ var _soundChannel; for (var len=this._soundChannelArr.length,i=0;i < len;i++){ _soundChannel=this._soundChannelArr[i]; if (_soundChannel.audioBuffer){ _soundChannel.resume(); } } } this._lastTime=Browser.now(); this.timer.frameLoop(1,this,this._update,null,true); } } /** *@private *得到缓冲数据 *@param aniIndex *@param frameIndex *@return */ __proto._getGrahicsDataWithCache=function(aniIndex,frameIndex){ return this._graphicsCache[aniIndex][frameIndex]; } /** *@private *保存缓冲grahpics *@param aniIndex *@param frameIndex *@param graphics */ __proto._setGrahicsDataWithCache=function(aniIndex,frameIndex,graphics){ this._graphicsCache[aniIndex][frameIndex]=graphics; } /** *销毁当前动画 */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._templet=null; if (this._player)this._player.offAll(); this._player=null; this._curOriginalData=null; this._boneMatrixArray.length=0; this._lastTime=0; this.timer.clear(this,this._update); if (this._soundChannelArr.length > 0){ this._onAniSoundStoped(true); } } /** *设置动画路径 */ /** *得到资源的URL */ __getset(0,__proto,'url',function(){ return this._aniPath; },function(path){ this.load(path); }); /** *@private *设置帧索引 */ /** *@private *得到帧索引 */ __getset(0,__proto,'index',function(){ return this._index; },function(value){ if (this.player){ this._index=value; this._player.currentTime=this._index *1000 / this._player.cacheFrameRate; this._indexControl=true; this._update(false); } }); /** *得到总帧数据 */ __getset(0,__proto,'total',function(){ if (this._templet && this._player){ this._total=Math.floor(this._templet.getAniDuration(this._player.currentAnimationClipIndex)/ 1000 *this._player.cacheFrameRate); }else { this._total=-1; } return this._total; }); /** *得到动画模板的引用 */ __getset(0,__proto,'templet',function(){ return this._templet; }); /** *得到播放器的引用 */ __getset(0,__proto,'player',function(){ return this._player; }); Skeleton.useSimpleMeshInCanvas=false; return Skeleton; })(Sprite) /** *

    MovieClip 用于播放经过工具处理后的 swf 动画。

    */ //class laya.ani.swf.MovieClip extends laya.display.Sprite var MovieClip=(function(_super){ function MovieClip(parentMovieClip){ /**@private 数据起始位置。*/ this._start=0; /**@private 当前位置。*/ this._Pos=0; /**@private 数据。*/ this._data=null; /**@private */ this._curIndex=0; /**@private */ this._preIndex=0; /**@private */ this._playIndex=0; /**@private */ this._playing=false; /**@private */ this._ended=true; /**@private 总帧数。*/ this._count=0; /**@private id_data起始位置表*/ this._ids=null; /**@private */ this._loadedImage={}; /**@private id_实例表*/ this._idOfSprite=null; /**@private 父mc*/ this._parentMovieClip=null; /**@private 需要更新的movieClip表*/ this._movieClipList=null; /**@private */ this._labels=null; /**资源根目录。*/ this.basePath=null; /**@private */ this._atlasPath=null; /**@private */ this._url=null; /**@private */ this._isRoot=false; /**@private */ this._completeHandler=null; /**@private */ this._endFrame=-1; /**播放间隔(单位:毫秒)。*/ this.interval=30; /**是否循环播放 */ this.loop=false; MovieClip.__super.call(this); this._ids={}; this._idOfSprite=[]; this._reset(); this._playing=false; this._parentMovieClip=parentMovieClip; if (!parentMovieClip){ this._movieClipList=[this]; this._isRoot=true; this._setUpNoticeType(/*laya.display.Node.NOTICE_DISPLAY*/0x1); }else { this._isRoot=false; this._movieClipList=parentMovieClip._movieClipList; this._movieClipList.push(this); } } __class(MovieClip,'laya.ani.swf.MovieClip',_super); var __proto=MovieClip.prototype; /** *

    销毁此对象。以及销毁引用的Texture

    *@param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); this._clear(); _super.prototype.destroy.call(this,destroyChild); } /**@private */ __proto._setDisplay=function(value){ _super.prototype._setDisplay.call(this,value); if (this._isRoot){ this._$3__onDisplay(value); } } /**@private */ __proto._$3__onDisplay=function(value){ if (value)this.timer.loop(this.interval,this,this.updates,null,true); else this.timer.clear(this,this.updates); } /**@private 更新时间轴*/ __proto.updates=function(){ if (this._parentMovieClip)return; var i=0,len=0; len=this._movieClipList.length; for (i=0;i < len;i++){ this._movieClipList[i]&&this._movieClipList[i]._update(); } } /** *增加一个标签到index帧上,播放到此index后会派发label事件 *@param label 标签名称 *@param index 索引位置 */ __proto.addLabel=function(label,index){ if (!this._labels)this._labels={}; this._labels[index]=label; } /** *删除某个标签 *@param label 标签名字,如果label为空,则删除所有Label */ __proto.removeLabel=function(label){ if (!label)this._labels=null; else if (!this._labels){ for (var name in this._labels){ if (this._labels[name]===label){ delete this._labels[name]; break ; } } } } /** *@private *动画的帧更新处理函数。 */ __proto._update=function(){ if (!this._data)return; if (!this._playing)return; this._playIndex++; if (this._playIndex >=this._count){ if (!this.loop){ this._playIndex--; this.stop(); return; } this._playIndex=0; } this._parse(this._playIndex); if (this._labels && this._labels[this._playIndex])this.event(/*laya.events.Event.LABEL*/"label",this._labels[this._playIndex]); if (this._endFrame!=-1&&this._endFrame==this._playIndex){ this._endFrame=-1; if (this._completeHandler !=null){ var handler=this._completeHandler; this._completeHandler=null; handler.run(); } this.stop(); } } /** *停止播放动画。 */ __proto.stop=function(){ this._playing=false; } /** *跳到某帧并停止播放动画。 *@param frame 要跳到的帧 */ __proto.gotoAndStop=function(index){ this.index=index; this.stop(); } /** *@private *清理。 */ __proto._clear=function(){ this.stop(); this._idOfSprite.length=0; if (!this._parentMovieClip){ this.timer.clear(this,this.updates); var i=0,len=0; len=this._movieClipList.length; for (i=0;i < len;i++){ if (this._movieClipList[i] !=this) this._movieClipList[i]._clear(); } this._movieClipList.length=0; } if (this._atlasPath){ Loader.clearRes(this._atlasPath); }; var key; for (key in this._loadedImage){ if (this._loadedImage[key]){ Loader.clearRes(key); this._loadedImage[key]=false; } } this.removeChildren(); this.graphics=null; this._parentMovieClip=null; } /** *播放动画。 *@param index 帧索引。 */ __proto.play=function(index,loop){ (index===void 0)&& (index=0); (loop===void 0)&& (loop=true); this.loop=loop; this._playing=true; if (this._data) this._displayFrame(index); } /**@private */ __proto._displayFrame=function(frameIndex){ (frameIndex===void 0)&& (frameIndex=-1); if (frameIndex !=-1){ if (this._curIndex > frameIndex)this._reset(); this._parse(frameIndex); } } /**@private */ __proto._reset=function(rm){ (rm===void 0)&& (rm=true); if (rm && this._curIndex !=1)this.removeChildren(); this._preIndex=this._curIndex=-1; this._Pos=this._start; } /**@private */ __proto._parse=function(frameIndex){ var curChild=this; var mc,sp,key=0,type=0,tPos=0,ttype=0,ifAdd=false; var _idOfSprite=this._idOfSprite,_data=this._data,eStr; if (this._ended)this._reset(); _data.pos=this._Pos; this._ended=false; this._playIndex=frameIndex; if (this._curIndex > frameIndex&&frameIndex 0); break ; case 7: sp=_idOfSprite[ _data.getUint16()]; var mt=sp.transform || Matrix.create(); mt.setTo(_data.getFloat32(),_data.getFloat32(),_data.getFloat32(),_data.getFloat32(),_data.getFloat32(),_data.getFloat32()); sp.transform=mt; break ; case 8: _idOfSprite[_data.getUint16()].setPos(_data.getFloat32(),_data.getFloat32()); break ; case 9: _idOfSprite[_data.getUint16()].setSize(_data.getFloat32(),_data.getFloat32()); break ; case 10: _idOfSprite[ _data.getUint16()].alpha=_data.getFloat32(); break ; case 11: _idOfSprite[_data.getUint16()].setScale(_data.getFloat32(),_data.getFloat32()); break ; case 98: eStr=_data.getString(); this.event(eStr); if (eStr=="stop")this.stop(); break ; case 99: this._curIndex=_data.getUint16(); ifAdd && this.updateZOrder(); break ; case 100: this._count=this._curIndex+1; this._ended=true; if (this._playing){ this.event(/*laya.events.Event.FRAME*/"enterframe"); this.event(/*laya.events.Event.END*/"end"); this.event(/*laya.events.Event.COMPLETE*/"complete"); } this._reset(false); break ; } } if (this._playing&&!this._ended)this.event(/*laya.events.Event.FRAME*/"enterframe"); this._Pos=_data.pos; } /**@private */ __proto._setData=function(data,start){ this._data=data; this._start=start+3; } /** *加载资源。 *@param url swf 资源地址。 *@param atlas 是否使用图集资源 *@param atlasPath 图集路径,默认使用与swf同名的图集 */ __proto.load=function(url,atlas,atlasPath){ (atlas===void 0)&& (atlas=false); this._url=url; if(atlas)this._atlasPath=atlasPath?atlasPath:url.split(".swf")[0]+".json"; this.stop(); this._clear(); this._movieClipList=[this]; var urls; urls=[ {url:url,type:/*laya.net.Loader.BUFFER*/"arraybuffer" }]; if (this._atlasPath){ urls.push({url:this._atlasPath,type:/*laya.net.Loader.ATLAS*/"atlas" }); } Laya.loader.load(urls,Handler.create(this,this._onLoaded)); } /**@private */ __proto._onLoaded=function(){ var data; data=Loader.getRes(this._url); if (!data){ this.event(/*laya.events.Event.ERROR*/"error","file not find"); return; } if (this._atlasPath && !Loader.getAtlas(this._atlasPath)){ this.event(/*laya.events.Event.ERROR*/"error","Atlas not find"); return; } this.basePath=this._atlasPath?Loader.getAtlas(this._atlasPath).dir:this._url.split(".swf")[0]+"/image/"; this._initData(data); } /**@private */ __proto._initState=function(){ this._reset(); this._ended=false; var preState=this._playing; this._playing=false; this._curIndex=0; while (!this._ended)this._parse(++this._curIndex); this._playing=preState; } /**@private */ __proto._initData=function(data){ this._data=new Byte(data); var i=0,len=this._data.getUint16(); for (i=0;i < len;i++)this._ids[this._data.getInt16()]=this._data.getInt32(); this.interval=1000 / this._data.getUint16(); this._setData(this._data,this._ids[32767]); this._initState(); this.play(0); this.event(/*laya.events.Event.LOADED*/"loaded"); if (!this._parentMovieClip)this.timer.loop(this.interval,this,this.updates,null,true); } /** *从开始索引播放到结束索引,结束之后出发complete回调 *@param start 开始索引 *@param end 结束索引 *@param complete 结束回调 */ __proto.playTo=function(start,end,complete){ this._completeHandler=complete; this._endFrame=end; this.play(start,false); } /**当前播放索引。*/ __getset(0,__proto,'index',function(){ return this._playIndex; },function(value){ this._playIndex=value; if (this._data) this._displayFrame(this._playIndex); if (this._labels && this._labels[value])this.event(/*laya.events.Event.LABEL*/"label",this._labels[value]); }); /** *帧总数。 */ __getset(0,__proto,'count',function(){ return this._count; }); /** *是否在播放中 */ __getset(0,__proto,'playing',function(){ return this._playing; }); /** *资源地址。 */ __getset(0,__proto,'url',null,function(path){ this.load(path); }); MovieClip._ValueList=["x","y","width","height","scaleX","scaleY","rotation","alpha"]; return MovieClip; })(Sprite) /** *动画模板类 */ //class laya.ani.bone.Templet extends laya.ani.AnimationTemplet var Templet=(function(_super){ function Templet(){ this._mainTexture=null; this._textureJson=null; this._graphicsCache=[]; /**存放原始骨骼信息 */ this.srcBoneMatrixArr=[]; /**IK数据 */ this.ikArr=[]; /**transform数据 */ this.tfArr=[]; /**path数据 */ this.pathArr=[]; /**存放插槽数据的字典 */ this.boneSlotDic={}; /**绑定插槽数据的字典 */ this.bindBoneBoneSlotDic={}; /**存放插糟数据的数组 */ this.boneSlotArray=[]; /**皮肤数据 */ this.skinDataArray=[]; /**皮肤的字典数据 */ this.skinDic={}; /**存放纹理数据 */ this.subTextureDic={}; /**是否解析失败 */ this.isParseFail=false; /**反转矩阵,有些骨骼动画要反转才能显示 */ this.yReverseMatrix=null; /**渲染顺序动画数据 */ this.drawOrderAniArr=[]; /**事件动画数据 */ this.eventAniArr=[]; /**@private 索引对应的名称 */ this.attachmentNames=null; /**顶点动画数据 */ this.deformAniArr=[]; /**是否需要解析audio数据 */ this._isParseAudio=false; this._isDestroyed=false; this._rate=30; this.isParserComplete=false; this.aniSectionDic={}; this._skBufferUrl=null; this._textureDic={}; this._loadList=null; this._path=null; /**@private */ this.tMatrixDataLen=0; this.mRootBone=null; Templet.__super.call(this); this.skinSlotDisplayDataArr=[]; this.mBoneArr=[]; } __class(Templet,'laya.ani.bone.Templet',_super); var __proto=Templet.prototype; __proto.loadAni=function(url){ this._skBufferUrl=url; Laya.loader.load(url,Handler.create(this,this.onComplete),null,/*laya.net.Loader.BUFFER*/"arraybuffer"); } __proto.onComplete=function(content){ if (this._isDestroyed){ this.destroy(); return; }; var tSkBuffer=Loader.getRes(this._skBufferUrl); if (!tSkBuffer){ this.event(/*laya.events.Event.ERROR*/"error","load failed:"+this._skBufferUrl); return; } this._path=this._skBufferUrl.slice(0,this._skBufferUrl.lastIndexOf("/"))+"/"; this.parseData(null,tSkBuffer); } /** *解析骨骼动画数据 *@param texture 骨骼动画用到的纹理 *@param skeletonData 骨骼动画信息及纹理分块信息 *@param playbackRate 缓冲的帧率数据(会根据帧率去分帧) */ __proto.parseData=function(texture,skeletonData,playbackRate){ (playbackRate===void 0)&& (playbackRate=30); if(!this._path&&this.url)this._path=this.url.slice(0,this.url.lastIndexOf("/"))+"/"; this._mainTexture=texture; if (this._mainTexture){ if (Render.isWebGL && texture.bitmap){ texture.bitmap.enableMerageInAtlas=false; } } this._rate=playbackRate; this.parse(skeletonData); } /** *创建动画 *0,使用模板缓冲的数据,模板缓冲的数据,不允许修改 (内存开销小,计算开销小,不支持换装) *1,使用动画自己的缓冲区,每个动画都会有自己的缓冲区,相当耗费内存 (内存开销大,计算开销小,支持换装) *2,使用动态方式,去实时去画 (内存开销小,计算开销大,支持换装,不建议使用) *@param aniMode 0 动画模式,0:不支持换装,1,2支持换装 *@return */ __proto.buildArmature=function(aniMode){ (aniMode===void 0)&& (aniMode=0); return new Skeleton(this,aniMode); } /** *@private *解析动画 *@param data 解析的二进制数据 *@param playbackRate 帧率 */ __proto.parse=function(data){ _super.prototype.parse.call(this,data); this._endLoaded(); if (this._aniVersion===Templet.LAYA_ANIMATION_VISION){ this._isParseAudio=true; }else if (this._aniVersion !=Templet.LAYA_ANIMATION_160_VISION){ console.log("[Error] 版本不一致,请使用IDE版本配套的重新导出"+this._aniVersion+"->"+Templet.LAYA_ANIMATION_VISION); this._loaded=false; } if (this.loaded){ if (this._mainTexture){ this._parsePublicExtData(); }else { this._parseTexturePath(); } }else { this.event(/*laya.events.Event.ERROR*/"error",this); this.isParseFail=true; } } __proto._parseTexturePath=function(){ if (this._isDestroyed){ this.destroy(); return; }; var i=0; this._loadList=[]; var tByte=new Byte(this.getPublicExtData()); var tX=0,tY=0,tWidth=0,tHeight=0; var tFrameX=0,tFrameY=0,tFrameWidth=0,tFrameHeight=0; var tTempleData=0; var tTextureLen=tByte.getInt32(); var tTextureName=tByte.readUTFString(); var tTextureNameArr=tTextureName.split("\n"); var tTexture; var tSrcTexturePath; for (i=0;i < tTextureLen;i++){ tSrcTexturePath=this._path+tTextureNameArr[i *2]; tTextureName=tTextureNameArr[i *2+1]; tX=tByte.getFloat32(); tY=tByte.getFloat32(); tWidth=tByte.getFloat32(); tHeight=tByte.getFloat32(); tTempleData=tByte.getFloat32(); tFrameX=isNaN(tTempleData)? 0 :tTempleData; tTempleData=tByte.getFloat32(); tFrameY=isNaN(tTempleData)? 0 :tTempleData; tTempleData=tByte.getFloat32(); tFrameWidth=isNaN(tTempleData)? tWidth :tTempleData; tTempleData=tByte.getFloat32(); tFrameHeight=isNaN(tTempleData)? tHeight :tTempleData; if (this._loadList.indexOf(tSrcTexturePath)==-1){ this._loadList.push(tSrcTexturePath); } } Laya.loader.load(this._loadList,Handler.create(this,this._textureComplete)); } /** *纹理加载完成 */ __proto._textureComplete=function(){ var tTexture; var tTextureName; for (var i=0,n=this._loadList.length;i < n;i++){ tTextureName=this._loadList[i]; tTexture=this._textureDic[tTextureName]=Loader.getRes(tTextureName); if (Render.isWebGL && tTexture && tTexture.bitmap){ tTexture.bitmap.enableMerageInAtlas=false; } } this._parsePublicExtData(); } /** *解析自定义数据 */ __proto._parsePublicExtData=function(){ var i=0,j=0,k=0,l=0,n=0; for (i=0,n=this.getAnimationCount();i < n;i++){ this._graphicsCache.push([]); }; var isSpine=false; isSpine=this._aniClassName !="Dragon"; var tByte=new Byte(this.getPublicExtData()); var tX=0,tY=0,tWidth=0,tHeight=0; var tFrameX=0,tFrameY=0,tFrameWidth=0,tFrameHeight=0; var tTempleData=0; var tTextureLen=tByte.getInt32(); var tTextureName=tByte.readUTFString(); var tTextureNameArr=tTextureName.split("\n"); var tTexture; var tSrcTexturePath; for (i=0;i < tTextureLen;i++){ tTexture=this._mainTexture; tSrcTexturePath=this._path+tTextureNameArr[i *2]; tTextureName=tTextureNameArr[i *2+1]; if (this._mainTexture==null){ tTexture=this._textureDic[tSrcTexturePath]; } if (!tTexture){ this.event(/*laya.events.Event.ERROR*/"error",this); this.isParseFail=true; return; } tX=tByte.getFloat32(); tY=tByte.getFloat32(); tWidth=tByte.getFloat32(); tHeight=tByte.getFloat32(); tTempleData=tByte.getFloat32(); tFrameX=isNaN(tTempleData)? 0 :tTempleData; tTempleData=tByte.getFloat32(); tFrameY=isNaN(tTempleData)? 0 :tTempleData; tTempleData=tByte.getFloat32(); tFrameWidth=isNaN(tTempleData)? tWidth :tTempleData; tTempleData=tByte.getFloat32(); tFrameHeight=isNaN(tTempleData)? tHeight :tTempleData; this.subTextureDic[tTextureName]=Texture.create(tTexture,tX,tY,tWidth,tHeight,-tFrameX,-tFrameY,tFrameWidth,tFrameHeight); } this._mainTexture=tTexture; var tAniCount=tByte.getUint16(); var tSectionArr; for (i=0;i < tAniCount;i++){ tSectionArr=[]; tSectionArr.push(tByte.getUint16()); tSectionArr.push(tByte.getUint16()); tSectionArr.push(tByte.getUint16()); tSectionArr.push(tByte.getUint16()); this.aniSectionDic[i]=tSectionArr; }; var tBone; var tParentBone; var tName; var tParentName; var tBoneLen=tByte.getInt16(); var tBoneDic={}; var tRootBone; for (i=0;i < tBoneLen;i++){ tBone=new Bone(); if (i==0){ tRootBone=tBone; }else { tBone.root=tRootBone; } tBone.d=isSpine?-1:1; tName=tByte.readUTFString(); tParentName=tByte.readUTFString(); tBone.length=tByte.getFloat32(); if (tByte.getByte()==1){ tBone.inheritRotation=false; } if (tByte.getByte()==1){ tBone.inheritScale=false; } tBone.name=tName; if (tParentName){ tParentBone=tBoneDic[tParentName]; if (tParentBone){ tParentBone.addChild(tBone); }else { this.mRootBone=tBone; } } tBoneDic[tName]=tBone; this.mBoneArr.push(tBone); } this.tMatrixDataLen=tByte.getUint16(); var tLen=tByte.getUint16(); var parentIndex=0; var boneLength=Math.floor(tLen / this.tMatrixDataLen); var tResultTransform; var tMatrixArray=this.srcBoneMatrixArr; for (i=0;i < boneLength;i++){ tResultTransform=new Transform(); tResultTransform.scX=tByte.getFloat32(); tResultTransform.skX=tByte.getFloat32(); tResultTransform.skY=tByte.getFloat32(); tResultTransform.scY=tByte.getFloat32(); tResultTransform.x=tByte.getFloat32(); tResultTransform.y=tByte.getFloat32(); if (this.tMatrixDataLen===8){ tResultTransform.skewX=tByte.getFloat32(); tResultTransform.skewY=tByte.getFloat32(); } tMatrixArray.push(tResultTransform); tBone=this.mBoneArr[i]; tBone.transform=tResultTransform; }; var tIkConstraintData; var tIkLen=tByte.getUint16(); var tIkBoneLen=0; for (i=0;i < tIkLen;i++){ tIkConstraintData=new IkConstraintData(); tIkBoneLen=tByte.getUint16(); for (j=0;j < tIkBoneLen;j++){ tIkConstraintData.boneNames.push(tByte.readUTFString()); tIkConstraintData.boneIndexs.push(tByte.getInt16()); } tIkConstraintData.name=tByte.readUTFString(); tIkConstraintData.targetBoneName=tByte.readUTFString(); tIkConstraintData.targetBoneIndex=tByte.getInt16(); tIkConstraintData.bendDirection=tByte.getFloat32(); tIkConstraintData.mix=tByte.getFloat32(); tIkConstraintData.isSpine=isSpine; this.ikArr.push(tIkConstraintData); }; var tTfConstraintData; var tTfLen=tByte.getUint16(); var tTfBoneLen=0; for (i=0;i < tTfLen;i++){ tTfConstraintData=new TfConstraintData(); tTfBoneLen=tByte.getUint16(); for (j=0;j < tTfBoneLen;j++){ tTfConstraintData.boneIndexs.push(tByte.getInt16()); } tTfConstraintData.name=tByte.getUTFString(); tTfConstraintData.targetIndex=tByte.getInt16(); tTfConstraintData.rotateMix=tByte.getFloat32(); tTfConstraintData.translateMix=tByte.getFloat32(); tTfConstraintData.scaleMix=tByte.getFloat32(); tTfConstraintData.shearMix=tByte.getFloat32(); tTfConstraintData.offsetRotation=tByte.getFloat32(); tTfConstraintData.offsetX=tByte.getFloat32(); tTfConstraintData.offsetY=tByte.getFloat32(); tTfConstraintData.offsetScaleX=tByte.getFloat32(); tTfConstraintData.offsetScaleY=tByte.getFloat32(); tTfConstraintData.offsetShearY=tByte.getFloat32(); this.tfArr.push(tTfConstraintData); }; var tPathConstraintData; var tPathLen=tByte.getUint16(); var tPathBoneLen=0; for (i=0;i < tPathLen;i++){ tPathConstraintData=new PathConstraintData(); tPathConstraintData.name=tByte.readUTFString(); tPathBoneLen=tByte.getUint16(); for (j=0;j < tPathBoneLen;j++){ tPathConstraintData.bones.push(tByte.getInt16()); } tPathConstraintData.target=tByte.readUTFString(); tPathConstraintData.positionMode=tByte.readUTFString(); tPathConstraintData.spacingMode=tByte.readUTFString(); tPathConstraintData.rotateMode=tByte.readUTFString(); tPathConstraintData.offsetRotation=tByte.getFloat32(); tPathConstraintData.position=tByte.getFloat32(); tPathConstraintData.spacing=tByte.getFloat32(); tPathConstraintData.rotateMix=tByte.getFloat32(); tPathConstraintData.translateMix=tByte.getFloat32(); this.pathArr.push(tPathConstraintData); }; var tDeformSlotLen=0; var tDeformSlotDisplayLen=0; var tDSlotIndex=0; var tDAttachment; var tDeformTimeLen=0; var tDTime=NaN; var tDeformVecticesLen=0; var tDeformAniData; var tDeformSlotData; var tDeformSlotDisplayData; var tDeformVectices; var tDeformAniLen=tByte.getInt16(); for (i=0;i < tDeformAniLen;i++){ var tDeformSkinLen=tByte.getUint8(); var tSkinDic={}; this.deformAniArr.push(tSkinDic); for (var f=0;f < tDeformSkinLen;f++){ tDeformAniData=new DeformAniData(); tDeformAniData.skinName=tByte.getUTFString(); tSkinDic[tDeformAniData.skinName]=tDeformAniData; tDeformSlotLen=tByte.getInt16(); for (j=0;j < tDeformSlotLen;j++){ tDeformSlotData=new DeformSlotData(); tDeformAniData.deformSlotDataList.push(tDeformSlotData); tDeformSlotDisplayLen=tByte.getInt16(); for (k=0;k < tDeformSlotDisplayLen;k++){ tDeformSlotDisplayData=new DeformSlotDisplayData(); tDeformSlotData.deformSlotDisplayList.push(tDeformSlotDisplayData); tDeformSlotDisplayData.slotIndex=tDSlotIndex=tByte.getInt16(); tDeformSlotDisplayData.attachment=tDAttachment=tByte.getUTFString(); tDeformTimeLen=tByte.getInt16(); for (l=0;l < tDeformTimeLen;l++){ if (tByte.getByte()==1){ tDeformSlotDisplayData.tweenKeyList.push(true); }else { tDeformSlotDisplayData.tweenKeyList.push(false); } tDTime=tByte.getFloat32(); tDeformSlotDisplayData.timeList.push(tDTime); tDeformVectices=[]; tDeformSlotDisplayData.vectices.push(tDeformVectices); tDeformVecticesLen=tByte.getInt16(); for (n=0;n < tDeformVecticesLen;n++){ tDeformVectices.push(tByte.getFloat32()); } } } } } }; var tDrawOrderArr; var tDrawOrderAniLen=tByte.getInt16(); var tDrawOrderLen=0; var tDrawOrderData; var tDoLen=0; for (i=0;i < tDrawOrderAniLen;i++){ tDrawOrderLen=tByte.getInt16(); tDrawOrderArr=[]; for (j=0;j < tDrawOrderLen;j++){ tDrawOrderData=new DrawOrderData(); tDrawOrderData.time=tByte.getFloat32(); tDoLen=tByte.getInt16(); for (k=0;k < tDoLen;k++){ tDrawOrderData.drawOrder.push(tByte.getInt16()); } tDrawOrderArr.push(tDrawOrderData); } this.drawOrderAniArr.push(tDrawOrderArr); }; var tEventArr; var tEventAniLen=tByte.getInt16(); var tEventLen=0; var tEventData; for (i=0;i < tEventAniLen;i++){ tEventLen=tByte.getInt16(); tEventArr=[]; for (j=0;j < tEventLen;j++){ tEventData=new EventData(); tEventData.name=tByte.getUTFString(); if (this._isParseAudio)tEventData.audioValue=tByte.getUTFString(); tEventData.intValue=tByte.getInt32(); tEventData.floatValue=tByte.getFloat32(); tEventData.stringValue=tByte.getUTFString(); tEventData.time=tByte.getFloat32(); tEventArr.push(tEventData); } this.eventAniArr.push(tEventArr); }; var tAttachmentLen=tByte.getInt16(); if (tAttachmentLen > 0){ this.attachmentNames=[]; for (i=0;i < tAttachmentLen;i++){ this.attachmentNames.push(tByte.getUTFString()); } }; var tBoneSlotLen=tByte.getInt16(); var tDBBoneSlot; var tDBBoneSlotArr; for (i=0;i < tBoneSlotLen;i++){ tDBBoneSlot=new BoneSlot(); tDBBoneSlot.name=tByte.readUTFString(); tDBBoneSlot.parent=tByte.readUTFString(); tDBBoneSlot.attachmentName=tByte.readUTFString(); tDBBoneSlot.srcDisplayIndex=tDBBoneSlot.displayIndex=tByte.getInt16(); tDBBoneSlot.templet=this; this.boneSlotDic[tDBBoneSlot.name]=tDBBoneSlot; tDBBoneSlotArr=this.bindBoneBoneSlotDic[tDBBoneSlot.parent]; if (tDBBoneSlotArr==null){ this.bindBoneBoneSlotDic[tDBBoneSlot.parent]=tDBBoneSlotArr=[]; } tDBBoneSlotArr.push(tDBBoneSlot); this.boneSlotArray.push(tDBBoneSlot); }; var tNameString=tByte.readUTFString(); var tNameArray=tNameString.split("\n"); var tNameStartIndex=0; var tSkinDataLen=tByte.getUint8(); var tSkinData,tSlotData,tDisplayData; var tSlotDataLen=0,tDisplayDataLen=0; var tUvLen=0,tWeightLen=0,tTriangleLen=0,tVerticeLen=0,tLengthLen=0; for (i=0;i < tSkinDataLen;i++){ tSkinData=new SkinData(); tSkinData.name=tNameArray[tNameStartIndex++]; tSlotDataLen=tByte.getUint8(); for (j=0;j < tSlotDataLen;j++){ tSlotData=new SlotData(); tSlotData.name=tNameArray[tNameStartIndex++]; tDBBoneSlot=this.boneSlotDic[tSlotData.name]; tDisplayDataLen=tByte.getUint8(); for (k=0;k < tDisplayDataLen;k++){ tDisplayData=new SkinSlotDisplayData(); this.skinSlotDisplayDataArr.push(tDisplayData); tDisplayData.name=tNameArray[tNameStartIndex++]; tDisplayData.attachmentName=tNameArray[tNameStartIndex++]; tDisplayData.transform=new Transform(); tDisplayData.transform.scX=tByte.getFloat32(); tDisplayData.transform.skX=tByte.getFloat32(); tDisplayData.transform.skY=tByte.getFloat32(); tDisplayData.transform.scY=tByte.getFloat32(); tDisplayData.transform.x=tByte.getFloat32(); tDisplayData.transform.y=tByte.getFloat32(); tSlotData.displayArr.push(tDisplayData); tDisplayData.width=tByte.getFloat32(); tDisplayData.height=tByte.getFloat32(); tDisplayData.type=tByte.getUint8(); tDisplayData.verLen=tByte.getUint16(); tBoneLen=tByte.getUint16(); if (tBoneLen > 0){ tDisplayData.bones=[]; for (l=0;l < tBoneLen;l++){ var tBoneId=tByte.getUint16(); tDisplayData.bones.push(tBoneId); } } tUvLen=tByte.getUint16(); if (tUvLen > 0){ tDisplayData.uvs=[]; for (l=0;l < tUvLen;l++){ tDisplayData.uvs.push(tByte.getFloat32()); } } tWeightLen=tByte.getUint16(); if (tWeightLen > 0){ tDisplayData.weights=[]; for (l=0;l < tWeightLen;l++){ tDisplayData.weights.push(tByte.getFloat32()); } } tTriangleLen=tByte.getUint16(); if (tTriangleLen > 0){ tDisplayData.triangles=[]; for (l=0;l < tTriangleLen;l++){ tDisplayData.triangles.push(tByte.getUint16()); } } tVerticeLen=tByte.getUint16(); if (tVerticeLen > 0){ tDisplayData.vertices=[]; for (l=0;l < tVerticeLen;l++){ tDisplayData.vertices.push(tByte.getFloat32()); } } tLengthLen=tByte.getUint16(); if (tLengthLen > 0){ tDisplayData.lengths=[]; for (l=0;l < tLengthLen;l++){ tDisplayData.lengths.push(tByte.getFloat32()); } } } tSkinData.slotArr.push(tSlotData); } this.skinDic[tSkinData.name]=tSkinData; this.skinDataArray.push(tSkinData); }; var tReverse=tByte.getUint8(); if (tReverse==1){ this.yReverseMatrix=new Matrix(1,0,0,-1,0,0); if (tRootBone){ tRootBone.setTempMatrix(this.yReverseMatrix); } }else { if (tRootBone){ tRootBone.setTempMatrix(new Matrix()); } } this.showSkinByIndex(this.boneSlotDic,0); this.isParserComplete=true; this.event(/*laya.events.Event.COMPLETE*/"complete",this); } /** *得到指定的纹理 *@param name 纹理的名字 *@return */ __proto.getTexture=function(name){ var tTexture=this.subTextureDic[name]; if (!tTexture){ tTexture=this.subTextureDic[name.substr(0,name.length-1)]; } if (tTexture==null){ return this._mainTexture; } return tTexture; } /** *@private *显示指定的皮肤 *@param boneSlotDic 插糟字典的引用 *@param skinIndex 皮肤的索引 *@param freshDisplayIndex 是否重置插槽纹理 */ __proto.showSkinByIndex=function(boneSlotDic,skinIndex,freshDisplayIndex){ (freshDisplayIndex===void 0)&& (freshDisplayIndex=true); if (skinIndex < 0 && skinIndex >=this.skinDataArray.length)return false; var i=0,n=0; var tBoneSlot; var tSlotData; var tSkinData=this.skinDataArray[skinIndex]; if (tSkinData){ for (i=0,n=tSkinData.slotArr.length;i < n;i++){ tSlotData=tSkinData.slotArr[i]; if (tSlotData){ tBoneSlot=boneSlotDic[tSlotData.name]; if (tBoneSlot){ tBoneSlot.showSlotData(tSlotData,freshDisplayIndex); if (freshDisplayIndex&&tBoneSlot.attachmentName !="undefined" && tBoneSlot.attachmentName !="null"){ tBoneSlot.showDisplayByName(tBoneSlot.attachmentName); }else { tBoneSlot.showDisplayByIndex(tBoneSlot.displayIndex); } } } } return true; } return false; } /** *通过皮肤名字得到皮肤索引 *@param skinName 皮肤名称 *@return */ __proto.getSkinIndexByName=function(skinName){ var tSkinData; for (var i=0,n=this.skinDataArray.length;i < n;i++){ tSkinData=this.skinDataArray[i]; if (tSkinData.name==skinName){ return i; } } return-1; } /** *@private *得到缓冲数据 *@param aniIndex 动画索引 *@param frameIndex 帧索引 *@return */ __proto.getGrahicsDataWithCache=function(aniIndex,frameIndex){ if (this._graphicsCache[aniIndex] && this._graphicsCache[aniIndex][frameIndex]){ return this._graphicsCache[aniIndex][frameIndex]; } return null; } /** *@private *保存缓冲grahpics *@param aniIndex 动画索引 *@param frameIndex 帧索引 *@param graphics 要保存的数据 */ __proto.setGrahicsDataWithCache=function(aniIndex,frameIndex,graphics){ this._graphicsCache[aniIndex][frameIndex]=graphics; } /** *释放纹理 */ __proto.destroy=function(){ this._isDestroyed=true; var tTexture; /*for each*/for(var $each_tTexture in this.subTextureDic){ tTexture=this.subTextureDic[$each_tTexture]; if(tTexture) tTexture.destroy(); } var $each_tTexture; /*for each*/for($each_tTexture in this._textureDic){ tTexture=this._textureDic[$each_tTexture]; if(tTexture) tTexture.destroy(); }; var tSkinSlotDisplayData; for (var i=0,n=this.skinSlotDisplayDataArr.length;i < n;i++){ tSkinSlotDisplayData=this.skinSlotDisplayDataArr[i]; tSkinSlotDisplayData.destory(); } this.skinSlotDisplayDataArr.length=0; if (this.url){ delete Templet.TEMPLET_DICTIONARY[this.url]; } laya.resource.Resource.prototype.destroy.call(this); } /** *通过索引得动画名称 *@param index *@return */ __proto.getAniNameByIndex=function(index){ var tAni=this.getAnimation(index); if (tAni)return tAni.name; return null; } __getset(0,__proto,'rate',function(){ return this._rate; },function(v){ this._rate=v; }); Templet.LAYA_ANIMATION_160_VISION="LAYAANIMATION:1.6.0"; Templet.LAYA_ANIMATION_VISION="LAYAANIMATION:1.7.0"; Templet.TEMPLET_DICTIONARY=null; return Templet; })(AnimationTemplet) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.bdmini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,RunDriver=laya.utils.RunDriver; var SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager,URL=laya.net.URL,Utils=laya.utils.Utils; //class laya.bd.mini.BMiniAdapter var BMiniAdapter=(function(){ function BMiniAdapter(){} __class(BMiniAdapter,'laya.bd.mini.BMiniAdapter'); BMiniAdapter.getJson=function(data){ return JSON.parse(data); } BMiniAdapter.init=function(isPosMsg,isSon){ (isPosMsg===void 0)&& (isPosMsg=false); (isSon===void 0)&& (isSon=false); if (BMiniAdapter._inited)return; BMiniAdapter._inited=true; BMiniAdapter.window=/*__JS__ */window; if(BMiniAdapter.window.navigator.userAgent.indexOf('SwanGame')<0)return; BMiniAdapter.isZiYu=isSon; BMiniAdapter.isPosMsgYu=isPosMsg; BMiniAdapter.EnvConfig={}; try{ /*__JS__ */laya.webgl.resource.WebGLCanvas.premulAlpha=true; }catch(e){ } if(!BMiniAdapter.isZiYu){ MiniFileMgr$1.setNativeFileDir("/layaairGame"); MiniFileMgr$1.existDir(MiniFileMgr$1.fileNativeDir,Handler.create(BMiniAdapter,BMiniAdapter.onMkdirCallBack)); } if(!BMiniAdapter.isZiYu){ BMiniAdapter.systemInfo=BMiniAdapter.window.swan.getSystemInfoSync(); } BMiniAdapter.window.focus=function (){ }; Laya['getUrlPath']=function (){ }; Laya['_getUrlPath']=function (){ }; BMiniAdapter.window.logtime=function (str){ }; BMiniAdapter.window.alertTimeLog=function (str){ }; BMiniAdapter.window.resetShareInfo=function (){ }; BMiniAdapter.window.CanvasRenderingContext2D=function (){ }; BMiniAdapter.window.CanvasRenderingContext2D.prototype=BMiniAdapter.window.swan.createCanvas().getContext('2d').__proto__; BMiniAdapter.window.document.body.appendChild=function (){ }; BMiniAdapter.EnvConfig.pixelRatioInt=0; RunDriver.getPixelRatio=BMiniAdapter.pixelRatio; BMiniAdapter._preCreateElement=Browser.createElement; Browser["createElement"]=BMiniAdapter.createElement; RunDriver.createShaderCondition=BMiniAdapter.createShaderCondition; Utils['parseXMLFromString']=BMiniAdapter.parseXMLFromString; Input['_createInputElement']=MiniInput$1['_createInputElement']; BMiniAdapter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader$1.prototype.load; Loader.prototype._loadImage=MiniImage$1.prototype._loadImage; LocalStorage._baseClass=MiniLocalStorage$1; MiniLocalStorage$1.__init__(); BMiniAdapter.onReciveData(); } BMiniAdapter.onReciveData=function(){ if(laya.bd.mini.BMiniAdapter.isZiYu){ BMiniAdapter.window.swan.onMessage(function(message){ if(message['isLoad']=="opendatacontext"){ if(message.url){ MiniFileMgr$1.ziyuFileData[message.url]=message.atlasdata; MiniFileMgr$1.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }else if(message['isLoad']=="openJsondatacontext"){ if(message.url){ MiniFileMgr$1.ziyuFileData[message.url]=message.atlasdata; } }else if(message['isLoad']=="openJsondatacontextPic"){ MiniFileMgr$1.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }); } } BMiniAdapter.measureText=function(str){ var tempObj=BMiniAdapter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } BMiniAdapter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return ""; return "utf8"; } BMiniAdapter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr$1.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr$1.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } BMiniAdapter.remove=function(fileUrl,callBack){ MiniFileMgr$1.deleteFile("",fileUrl,callBack,"",0); } BMiniAdapter.removeAll=function(){ MiniFileMgr$1.deleteAll(); } BMiniAdapter.hasNativeFile=function(fileUrl){ return MiniFileMgr$1.isLocalNativeFile(fileUrl); } BMiniAdapter.getFileInfo=function(fileUrl){ return MiniFileMgr$1.getFileInfo(fileUrl); } BMiniAdapter.getFileList=function(){ return MiniFileMgr$1.filesListObj; } BMiniAdapter.exitMiniProgram=function(){ BMiniAdapter.window.swan.exitMiniProgram(); } BMiniAdapter.onMkdirCallBack=function(errorCode,data){ if (!errorCode){ MiniFileMgr$1.filesListObj=JSON.parse(data.data); MiniFileMgr$1.fakeObj=JSON.parse(data.data); } BMiniAdapter.onChuLiYuJiaZai(); } BMiniAdapter.onChuLiYuJiaZai=function(){ if(BMiniAdapter.window.preloadResources){ var preloadResources=BMiniAdapter.window.preloadResources; for(var i=0,sz=preloadResources.length;i=0 ? "/" :"\\"; var idx=url.lastIndexOf(split); var folderPath=idx >=0 ? url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[url.replace(".json",".png")]; } for(i=0;i\s+<'); try { /*__JS__ */rst=(new window.Parser.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } BMiniAdapter.idx=1; __static(BMiniAdapter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir","wxlocal"];} ]); return BMiniAdapter; })() /**@private **/ //class laya.bd.mini.MiniFileMgr var MiniFileMgr$1=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.bd.mini.MiniFileMgr',null,'MiniFileMgr$1'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=BMiniAdapter.nativefiles.length;i=totalSize){ if(data.size > BMiniAdapter.minClearSize) BMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((fileUseSize+chaSize+data.size)>=totalSize){ if(data.size > BMiniAdapter.minClearSize) BMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=BMiniAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.bd.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); if(!fileObj) return; var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); var isAdd=tempFileName !="" ? true :false; laya.bd.mini.MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.pause(); this._audio.offEnded(null); this._audio=null; this._miniSound=null; this._onEnd=null; } /**@private **/ __proto.pause=function(){ this.isStopped=true; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ return this._audio.autoplay; },function(value){ this._audio.autoplay=value; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ return this._audio.loop; },function(value){ this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.bilimini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Config=Laya.Config,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,HttpRequest=laya.net.HttpRequest,Input=laya.display.Input; var Loader=laya.net.Loader,LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render; var RunDriver=laya.utils.RunDriver,SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager; var URL=laya.net.URL,Utils=laya.utils.Utils; //class laya.bili.mini.BLMiniAdapter var BLMiniAdapter=(function(){ function BLMiniAdapter(){} __class(BLMiniAdapter,'laya.bili.mini.BLMiniAdapter'); BLMiniAdapter.getJson=function(data){ return JSON.parse(data); } BLMiniAdapter.init=function(isPosMsg,isSon){ (isPosMsg===void 0)&& (isPosMsg=false); (isSon===void 0)&& (isSon=false); if (BLMiniAdapter._inited)return; BLMiniAdapter._inited=true; BLMiniAdapter.window=/*__JS__ */window; if(!BLMiniAdapter.window.hasOwnProperty("bl")) return; if(BLMiniAdapter.window.navigator.userAgent.indexOf('MiniGame')<0)return; BLMiniAdapter.isZiYu=isSon; BLMiniAdapter.isPosMsgYu=isPosMsg; BLMiniAdapter.EnvConfig={}; try{ /*__JS__ */laya.webgl.resource.WebGLCanvas.premulAlpha=true; }catch(e){ } if(!BLMiniAdapter.isZiYu){ MiniFileMgr$5.setNativeFileDir("/layaairGame"); MiniFileMgr$5.existDir(MiniFileMgr$5.fileNativeDir,Handler.create(BLMiniAdapter,BLMiniAdapter.onMkdirCallBack)); } BLMiniAdapter.systemInfo=BLMiniAdapter.window.bl.getSystemInfoSync(); if (BLMiniAdapter.systemInfo.system.toLowerCase()==='ios 10.1.1'){ try{ /*__JS__ */laya.webgl.resource.WebGLCharImage.canUseCanvas=false; }catch(e){ } } BLMiniAdapter.window.focus=function (){ }; Laya['_getUrlPath']=function (){ }; Laya['getUrlPath']=function (){ }; BLMiniAdapter.window.logtime=function (str){ }; BLMiniAdapter.window.alertTimeLog=function (str){ }; BLMiniAdapter.window.resetShareInfo=function (){ }; BLMiniAdapter.window.CanvasRenderingContext2D=function (){ }; HttpRequest._urlEncode=function (str){ var strTemp=""; var length=str.length; for (var i=0;i < length;i++){ var word=str[i]; if (BLMiniAdapter.IGNORE.test(word)){ strTemp+=word; } else{ try { strTemp+=encodeURI(word); } catch (e){ console.log("errorInfo",">>>"+word,null); } } } return strTemp; } BLMiniAdapter.window.CanvasRenderingContext2D.prototype=BLMiniAdapter.window.bl.createCanvas().getContext('2d').__proto__; BLMiniAdapter.window.document.body.appendChild=function (){ }; BLMiniAdapter.EnvConfig.pixelRatioInt=0; RunDriver.getPixelRatio=BLMiniAdapter.pixelRatio; BLMiniAdapter._preCreateElement=Browser.createElement; Browser["createElement"]=BLMiniAdapter.createElement; RunDriver.createShaderCondition=BLMiniAdapter.createShaderCondition; Utils['parseXMLFromString']=BLMiniAdapter.parseXMLFromString; Input['_createInputElement']=MiniInput$5['_createInputElement']; BLMiniAdapter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader$5.prototype.load; Loader.prototype._loadImage=MiniImage$5.prototype._loadImage; LocalStorage._baseClass=MiniLocalStorage$5; MiniLocalStorage$5.__init__(); Config.useRetinalCanvas=true; BLMiniAdapter.onReciveData(); } BLMiniAdapter.onReciveData=function(){ if(laya.bili.mini.BLMiniAdapter.isZiYu){ BLMiniAdapter.window.bl.onMessage(function(message){ if(message['isLoad']=="opendatacontext"){ if(message.url){ MiniFileMgr$5.ziyuFileData[message.url]=message.atlasdata; MiniFileMgr$5.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }else if(message['isLoad']=="openJsondatacontext"){ if(message.url){ MiniFileMgr$5.ziyuFileData[message.url]=message.atlasdata; } }else if(message['isLoad']=="openJsondatacontextPic"){ MiniFileMgr$5.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }); } } BLMiniAdapter.measureText=function(str){ var tempObj=BLMiniAdapter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } BLMiniAdapter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return ""; return "utf8"; } BLMiniAdapter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr$5.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr$5.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } BLMiniAdapter.remove=function(fileUrl,callBack){ MiniFileMgr$5.deleteFile("",fileUrl,callBack,"",0); } BLMiniAdapter.removeAll=function(){ MiniFileMgr$5.deleteAll(); } BLMiniAdapter.hasNativeFile=function(fileUrl){ return MiniFileMgr$5.isLocalNativeFile(fileUrl); } BLMiniAdapter.getFileInfo=function(fileUrl){ return MiniFileMgr$5.getFileInfo(fileUrl); } BLMiniAdapter.getFileList=function(){ return MiniFileMgr$5.filesListObj; } BLMiniAdapter.exitMiniProgram=function(){ BLMiniAdapter.window.bl.exitMiniProgram(); } BLMiniAdapter.onMkdirCallBack=function(errorCode,data){ if (!errorCode){ MiniFileMgr$5.filesListObj=JSON.parse(data.data); MiniFileMgr$5.fakeObj=JSON.parse(data.data); } } BLMiniAdapter.pixelRatio=function(){ if (!BLMiniAdapter.EnvConfig.pixelRatioInt){ try { BLMiniAdapter.EnvConfig.pixelRatioInt=BLMiniAdapter.systemInfo.pixelRatio; return BLMiniAdapter.systemInfo.pixelRatio; }catch (error){} } return BLMiniAdapter.EnvConfig.pixelRatioInt; } BLMiniAdapter.createElement=function(type){ if (type=="canvas"){ var _source; if (BLMiniAdapter.idx==1){ if(BLMiniAdapter.isZiYu){ _source=BLMiniAdapter.window.sharedCanvas; _source.style={}; }else{ _source=BLMiniAdapter.window.canvas; } }else { _source=BLMiniAdapter.window.document.createElement("canvas"); } BLMiniAdapter.idx++; return _source; }else if (type=="textarea" || type=="input"){ return BLMiniAdapter.onCreateInput(type); }else if (type=="div"){ var node=BLMiniAdapter._preCreateElement(type); node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } else { return BLMiniAdapter._preCreateElement(type); } } BLMiniAdapter.onCreateInput=function(type){ var node=BLMiniAdapter._preCreateElement(type); node.focus=MiniInput$5.wxinputFocus; node.blur=MiniInput$5.wxinputblur; node.style={}; node.value=0; node.parentElement={}; node.placeholder={}; node.type={}; node.setColor=function (value){ }; node.setType=function (value){ }; node.setFontFace=function (value){ }; node.addEventListener=function (value){ }; node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } BLMiniAdapter.createShaderCondition=function(conditionScript){ var _$this=this; var func=function (){ var abc=conditionScript; return _$this[conditionScript.replace("this.","")]; } return func; } BLMiniAdapter.sendAtlasToOpenDataContext=function(url){ if(!laya.bili.mini.BLMiniAdapter.isZiYu){ var atlasJson=Loader.getRes(URL.formatURL(url)); if(atlasJson){ var textureArr=(atlasJson.meta.image).split(","); if (atlasJson.meta && atlasJson.meta.image){ var toloadPics=atlasJson.meta.image.split(","); var split=url.indexOf("/")>=0 ? "/" :"\\"; var idx=url.lastIndexOf(split); var folderPath=idx >=0 ? url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[url.replace(".json",".png")]; } for(i=0;i\s+<'); try { /*__JS__ */rst=(new window.Parser.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } BLMiniAdapter.idx=1; __static(BLMiniAdapter, ['IGNORE',function(){return this.IGNORE=new RegExp("[-_.!~*'();/?:@&=+$,#%]|[0-9|A-Z|a-z]");},'nativefiles',function(){return this.nativefiles=["layaNativeDir","wxlocal"];} ]); return BLMiniAdapter; })() /**@private **/ //class laya.bili.mini.MiniFileMgr var MiniFileMgr$5=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.bili.mini.MiniFileMgr',null,'MiniFileMgr$5'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=BLMiniAdapter.nativefiles.length;i=totalSize)){ if(data.size > BLMiniAdapter.minClearSize) BLMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > BLMiniAdapter.minClearSize) BLMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=BLMiniAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.bili.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i *
  • 1.0 正常速度
  • *
  • 0.5 半速(更慢)
  • *
  • 2.0 倍速(更快)
  • *
  • -1.0 向后,正常速度
  • *
  • -0.5 向后,半速
  • * *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ if(!this.videoElement) return 0; return this.videoElement.playbackRate; },function(value){ if(!this.videoElement) return; this.videoElement.playbackRate=value; }); __getset(0,__proto,'x',function(){ if(!this.videoElement) return 0; return this.videoElement.x; },function(value){ if(!this.videoElement) return; this.videoElement.x=value; }); __getset(0,__proto,'y',function(){ if(!this.videoElement) return 0; return this.videoElement.y; },function(value){ if(!this.videoElement) return; this.videoElement.y=value; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.src; }); MiniVideo.__init__=function(){ /*__JS__ */laya.device.media.Video=MiniVideo; } return MiniVideo; })() /**@private **/ //class laya.bili.mini.MiniAccelerator extends laya.events.EventDispatcher var MiniAccelerator$5=(function(_super){ function MiniAccelerator(){ MiniAccelerator.__super.call(this); } __class(MiniAccelerator,'laya.bili.mini.MiniAccelerator',_super,'MiniAccelerator$5'); var __proto=MiniAccelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); MiniAccelerator.startListen(this["onDeviceOrientationChange"]); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) MiniAccelerator.stopListen(); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } MiniAccelerator.__init__=function(){ try{ var Acc; Acc=/*__JS__ */laya.device.motion.Accelerator; if (!Acc)return; Acc["prototype"]["on"]=MiniAccelerator["prototype"]["on"]; Acc["prototype"]["off"]=MiniAccelerator["prototype"]["off"]; }catch (e){ } } MiniAccelerator.startListen=function(callBack){ MiniAccelerator._callBack=callBack; if (MiniAccelerator._isListening)return; MiniAccelerator._isListening=true; try{ BLMiniAdapter.window.bl.onAccelerometerChange(laya.bili.mini.MiniAccelerator.onAccelerometerChange); }catch(e){} } MiniAccelerator.stopListen=function(){ MiniAccelerator._isListening=false; try{ BLMiniAdapter.window.bl.stopAccelerometer({}); }catch(e){} } MiniAccelerator.onAccelerometerChange=function(res){ var e; e={}; e.acceleration=res; e.accelerationIncludingGravity=res; e.rotationRate={}; if (MiniAccelerator._callBack !=null){ MiniAccelerator._callBack(e); } } MiniAccelerator._isListening=false; MiniAccelerator._callBack=null; return MiniAccelerator; })(EventDispatcher) /**@private **/ //class laya.bili.mini.MiniLoader extends laya.events.EventDispatcher var MiniLoader$5=(function(_super){ function MiniLoader(){ MiniLoader.__super.call(this); } __class(MiniLoader,'laya.bili.mini.MiniLoader',_super,'MiniLoader$5'); var __proto=MiniLoader.prototype; /** *@private *@param url *@param type *@param cache *@param group *@param ignoreCache */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); var thisLoader=this; thisLoader._url=url; if (url.indexOf("data:image")===0)thisLoader._type=type=/*laya.net.Loader.IMAGE*/"image"; else { thisLoader._type=type || (type=thisLoader.getTypeFromUrl(url)); } thisLoader._cache=cache; thisLoader._data=null; if (!ignoreCache && Loader.loadedMap[URL.formatURL(url)]){ thisLoader._data=Loader.loadedMap[URL.formatURL(url)]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",thisLoader._data); return; } if (Loader.parserMap[type] !=null){ thisLoader._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; }; var encoding=BLMiniAdapter.getUrlEncode(url,type); var urlType=Utils.getFileExtension(url); if ((MiniLoader._fileTypeArr.indexOf(urlType)!=-1)|| type==/*laya.net.Loader.IMAGE*/"image"){ BLMiniAdapter.EnvConfig.load.call(this,url,type,cache,group,ignoreCache); }else { if(BLMiniAdapter.isZiYu && !MiniFileMgr$5.ziyuFileData[url]){ url=URL.formatURL(url); } if(BLMiniAdapter.isZiYu && MiniFileMgr$5.ziyuFileData[url]){ var tempData=MiniFileMgr$5.ziyuFileData[url]; thisLoader.onLoaded(tempData); return; } if (!MiniFileMgr$5.getFileInfo(URL.formatURL(url))){ if (MiniFileMgr$5.isLocalNativeFile(url)){ if (BLMiniAdapter.subNativeFiles && BLMiniAdapter.subNativeheads.length==0){ for (var key in BLMiniAdapter.subNativeFiles){ var tempArr=BLMiniAdapter.subNativeFiles[key]; BLMiniAdapter.subNativeheads=BLMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ BLMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(BLMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && BLMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=BLMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } MiniFileMgr$5.read(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); return; }; var tempUrl=url; var tempurl=URL.formatURL(url); if (tempurl.indexOf(BLMiniAdapter.window.bl.env.USER_DATA_PATH)==-1 &&(url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)&& !BLMiniAdapter.AutoCacheDownFile){ BLMiniAdapter.EnvConfig.load.call(thisLoader,tempUrl,type,cache,group,ignoreCache); }else { fileObj=MiniFileMgr$5.getFileInfo(url); if(fileObj){ fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; MiniFileMgr$5.readFile(fileObj.url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else if (thisLoader.type=="image" || thisLoader.type=="htmlimage"){ BLMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } else{ url=URL.formatURL(url); if(type !=/*laya.net.Loader.IMAGE*/"image" && ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1)|| MiniFileMgr$5.isLocalNativeFile(url))){ MiniFileMgr$5.readFile(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else{ MiniFileMgr$5.downFiles(encodeURI(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url,cache); } } } }else { var fileObj=MiniFileMgr$5.getFileInfo(URL.formatURL(url)); fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; var nativepath=MiniFileMgr$5.getFileNativePath(fileObj.md5); MiniFileMgr$5.readFile(nativepath,fileObj.encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),URL.formatURL(url)); } } } MiniLoader.onReadNativeCallBack=function(encoding,url,type,cache,group,ignoreCache,thisLoader,errorCode,data){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); (errorCode===void 0)&& (errorCode=0); if (!errorCode){ var tempData; if (type==/*laya.net.Loader.JSON*/"json" || type==/*laya.net.Loader.ATLAS*/"atlas"){ tempData=BLMiniAdapter.getJson(data.data); }else if (type==/*laya.net.Loader.XML*/"xml"){ tempData=Utils.parseXMLFromString(data.data); }else { tempData=data.data; } if(!BLMiniAdapter.isZiYu &&BLMiniAdapter.isPosMsgYu && type !=/*laya.net.Loader.BUFFER*/"arraybuffer" && BLMiniAdapter.window.bl){ BLMiniAdapter.window.bl.postMessage({url:url,data:tempData,isLoad:"filedata"}); } thisLoader.onLoaded(tempData); }else if (errorCode==1){ console.log("-----------本地加载失败,尝试外网加载----"); BLMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } } __static(MiniLoader, ['_fileTypeArr',function(){return this._fileTypeArr=['png','jpg','bmp','jpeg','gif'];} ]); return MiniLoader; })(EventDispatcher) /**@private **/ //class laya.bili.mini.MiniSound extends laya.events.EventDispatcher var MiniSound$5=(function(_super){ function MiniSound(){ /**@private **/ this._sound=null; /** *@private *声音URL */ this.url=null; /** *@private *是否已加载完成 */ this.loaded=false; /**@private **/ this.readyUrl=null; MiniSound.__super.call(this); } __class(MiniSound,'laya.bili.mini.MiniSound',_super,'MiniSound$5'); var __proto=MiniSound.prototype; /** *@private *加载声音。 *@param url 地址。 * */ __proto.load=function(url){ if (!MiniFileMgr$5.isLocalNativeFile(url)){ url=URL.formatURL(url); }else{ if (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1){ if(MiniFileMgr$5.loadPath !=""){ url=url.split(MiniFileMgr$5.loadPath)[1]; }else{ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; if(tempStr !="") url=url.split(tempStr)[1]; } } } this.url=url; this.readyUrl=url; if (MiniSound._audioCache[this.readyUrl]){ this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if(BLMiniAdapter.autoCacheFile&&MiniFileMgr$5.getFileInfo(url)){ this.onDownLoadCallBack(url,0); }else{ if(!BLMiniAdapter.autoCacheFile){ this.onDownLoadCallBack(url,0); }else{ if (MiniFileMgr$5.isLocalNativeFile(url)){ tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="") url=url.split(tempStr)[1]; if (!url){ url=tempUrl; } if (BLMiniAdapter.subNativeFiles && BLMiniAdapter.subNativeheads.length==0){ for (var key in BLMiniAdapter.subNativeFiles){ var tempArr=BLMiniAdapter.subNativeFiles[key]; BLMiniAdapter.subNativeheads=BLMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ BLMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(BLMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && BLMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=BLMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } this.onDownLoadCallBack(url,0); }else{ MiniFileMgr$5.downOtherFiles(url,Handler.create(this,this.onDownLoadCallBack,[url]),url); } } } } /**@private **/ __proto.onDownLoadCallBack=function(sourceUrl,errorCode){ if (!errorCode){ var fileNativeUrl; if(BLMiniAdapter.autoCacheFile){ var fileObj=MiniFileMgr$5.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$5.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=sourceUrl; } this._sound=MiniSound._createSound(); this._sound.src=this.url=fileNativeUrl; }else{ this._sound=MiniSound._createSound(); this._sound.src=sourceUrl; } this._sound.onCanplay(MiniSound.bindToThis(this.onCanPlay,this)); this._sound.onError(MiniSound.bindToThis(this.onError,this)); }else{ this.event(/*laya.events.Event.ERROR*/"error"); } } /**@private **/ __proto.onError=function(error){ try{ console.log("-----1---------------minisound-----id:"+MiniSound._id); console.log(error); } catch(error){ console.log("-----2---------------minisound-----id:"+MiniSound._id); console.log(error); } this.event(/*laya.events.Event.ERROR*/"error"); this._sound.offError(MiniSound.bindToThis(this.onError,this)); } /**@private **/ __proto.onCanPlay=function(){ this.loaded=true; this.event(/*laya.events.Event.COMPLETE*/"complete"); this._sound.offCanplay(MiniSound.bindToThis(this.onCanPlay,this)); } /** *@private *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); var tSound; if (this.url==SoundManager._tMusic){ if (!MiniSound._musicAudio)MiniSound._musicAudio=MiniSound._createSound(); tSound=MiniSound._musicAudio; }else { if(MiniSound._audioCache[this.readyUrl]){ tSound=MiniSound._audioCache[this.readyUrl]._sound; }else{ tSound=MiniSound._createSound(); } } if(BLMiniAdapter.autoCacheFile&&MiniFileMgr$5.getFileInfo(this.url)){ var fileNativeUrl; var fileObj=MiniFileMgr$5.getFileInfo(this.url); var fileMd5Name=fileObj.md5; tSound.src=this.url=MiniFileMgr$5.getFileNativePath(fileMd5Name); }else{ tSound.src=this.url; }; var channel=new MiniSoundChannel$5(tSound,this); channel.url=this.url; channel.loops=loops; channel.loop=(loops===0 ? true :false); channel.startTime=startTime; channel.play(); SoundManager.addChannel(channel); return channel; } /** *@private *释放声音资源。 * */ __proto.dispose=function(){ var ad=MiniSound._audioCache[this.readyUrl]; if (ad){ ad.src=""; if(ad._sound){ ad._sound.destroy(); ad._sound=null; ad=null; } delete MiniSound._audioCache[this.readyUrl]; } } /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ return this._sound.duration; }); MiniSound._createSound=function(){ MiniSound._id++; return BLMiniAdapter.window.bl.createInnerAudioContext(); } MiniSound.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } MiniSound._musicAudio=null; MiniSound._id=0; MiniSound._audioCache={}; return MiniSound; })(EventDispatcher) /**@private **/ //class laya.bili.mini.MiniSoundChannel extends laya.media.SoundChannel var MiniSoundChannel$5=(function(_super){ function MiniSoundChannel(audio,miniSound){ /**@private **/ this._audio=null; /**@private **/ this._onEnd=null; /**@private **/ this._miniSound=null; MiniSoundChannel.__super.call(this); this._audio=audio; this._miniSound=miniSound; this._onEnd=MiniSoundChannel.bindToThis(this.__onEnd,this); audio.onEnded(this._onEnd); } __class(MiniSoundChannel,'laya.bili.mini.MiniSoundChannel',_super,'MiniSoundChannel$5'); var __proto=MiniSoundChannel.prototype; /**@private **/ __proto.__onEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.pause(); this._audio.offEnded(null); this._audio=null; this._miniSound=null; this._onEnd=null; } /**@private **/ __proto.pause=function(){ this.isStopped=true; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',null,function(time){ if(this._audio){ this._audio.startTime=time; } }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ return this._audio.autoplay; },function(value){ this._audio.autoplay=value; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ return this._audio.loop; },function(value){ this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.core.js ================================================ /***********************************/ /*http://www.layabox.com 2017/12/12*/ /***********************************/ var Laya=window.Laya=(function(window,document){ var Laya={ __internals:[], __packages:{}, __classmap:{'Object':Object,'Function':Function,'Array':Array,'String':String}, __sysClass:{'object':'Object','array':'Array','string':'String','dictionary':'Dictionary'}, __propun:{writable: true,enumerable: false,configurable: true}, __presubstr:String.prototype.substr, __substr:function(ofs,sz){return arguments.length==1?Laya.__presubstr.call(this,ofs):Laya.__presubstr.call(this,ofs,sz>0?sz:(this.length+sz));}, __init:function(_classs){_classs.forEach(function(o){o.__init$ && o.__init$();});}, __isClass:function(o){return o && (o.__isclass || o==Object || o==String || o==Array);}, __newvec:function(sz,value){ var d=[]; d.length=sz; for(var i=0;i1){ for(var i=0,sz=strs.length-1;i0){ if(fullName.indexOf('laya.')==0){ var paths=fullName.split('.'); miniName=miniName || paths[paths.length-1]; if(Laya[miniName]) console.log("Warning!,this class["+miniName+"] already exist:",Laya[miniName]); Laya[miniName]=o; } } else { if(fullName=="Main") window.Main=o; else{ if(Laya[fullName]){ console.log("Error!,this class["+fullName+"] already exist:",Laya[fullName]); } Laya[fullName]=o; } } } var un=Laya.un,p=o.prototype; un(p,'hasOwnProperty',Laya.__hasOwnProperty); un(p,'__class',o); un(p,'__super',_super); un(p,'__className',fullName); un(o,'__super',_super); un(o,'__className',fullName); un(o,'__isclass',true); un(o,'super',function(o){this.__super.call(o);}); }, imps:function(dec,src){ if(!src) return null; var d=dec.__imps|| Laya.un(dec,'__imps',{}); function __(name){ var c,exs; if(! (c=Laya.__internals[name]) ) return; d[name]=true; if(!(exs=c.extend)) return; for(var i=0;iLaya 是全局对象的引用入口集。 *Laya类引用了一些常用的全局对象,比如Laya.stage:舞台,Laya.timer:时间管理器,Laya.loader:加载管理器,使用时注意大小写。 */ //class Laya var ___Laya=(function(){ //function Laya(){} /** *表示是否捕获全局错误并弹出提示。默认为false。 *适用于移动设备等不方便调试的时候,设置为true后,如有未知错误,可以弹窗抛出详细错误堆栈。 */ __getset(1,Laya,'alertGlobalError',null,function(value){ var erralert=0; if (value){ Browser.window.onerror=function (msg,url,line,column,detail){ if (erralert++< 5 && detail) alert("出错啦,请把此信息截图给研发商\n"+msg+"\n"+detail.stack || detail); } }else { Browser.window.onerror=null; } }); Laya.init=function(width,height,__plugins){ var plugins=[];for(var i=2,sz=arguments.length;i-1)console.error("请先引用小游戏适配库laya.wxmini.js,详细教程:https://ldc.layabox.com/doc/?nav=zh-ts-5-0-0")}}; __static(Laya, ['conchMarket',function(){return this.conchMarket=/*__JS__ */window.conch?conchMarket:null;},'PlatformClass',function(){return this.PlatformClass=/*__JS__ */window.PlatformClass;},'_evcode',function(){return this._evcode="e"+String.fromCharCode(100+10+8)+"a"+"l";} ]); return Laya; })() /** *Config 用于配置一些全局参数。如需更改,请在初始化引擎之前设置。 */ //class Config var Config=(function(){ function Config(){} __class(Config,'Config'); Config.WebGLTextCacheCount=500; Config.atlasEnable=false; Config.showCanvasMark=false; Config.animationInterval=50; Config.isAntialias=false; Config.isAlpha=false; Config.premultipliedAlpha=true; Config.isStencil=true; Config.preserveDrawingBuffer=false; Config.useRetinalCanvas=false; Config.CborderSize=12; return Config; })() /** *EventDispatcher 类是可调度事件的所有类的基类。 */ //class laya.events.EventDispatcher var EventDispatcher=(function(){ var EventHandler; function EventDispatcher(){ /**@private */ this._events=null; } __class(EventDispatcher,'laya.events.EventDispatcher'); var __proto=EventDispatcher.prototype; /** *检查 EventDispatcher 对象是否为特定事件类型注册了任何侦听器。 *@param type 事件的类型。 *@return 如果指定类型的侦听器已注册,则值为 true;否则,值为 false。 */ __proto.hasListener=function(type){ var listener=this._events && this._events[type]; return !!listener; } /** *派发事件。 *@param type 事件类型。 *@param data (可选)回调数据。注意:如果是需要传递多个参数 p1,p2,p3,...可以使用数组结构如:[p1,p2,p3,...] ;如果需要回调单个参数 p ,且 p 是一个数组,则需要使用结构如:[p],其他的单个参数 p ,可以直接传入参数 p。 *@return 此事件类型是否有侦听者,如果有侦听者则值为 true,否则值为 false。 */ __proto.event=function(type,data){ if (!this._events || !this._events[type])return false; var listeners=this._events[type]; if (listeners.run){ if (listeners.once)delete this._events[type]; data !=null ? listeners.runWith(data):listeners.run(); }else { for (var i=0,n=listeners.length;i < n;i++){ var listener=listeners[i]; if (listener){ (data !=null)? listener.runWith(data):listener.run(); } if (!listener || listener.once){ listeners.splice(i,1); i--; n--; } } if (listeners.length===0 && this._events)delete this._events[type]; } return true; } /** *使用 EventDispatcher 对象注册指定类型的事件侦听器对象,以使侦听器能够接收事件通知。 *@param type 事件的类型。 *@param caller 事件侦听函数的执行域。 *@param listener 事件侦听函数。 *@param args (可选)事件侦听函数的回调参数。 *@return 此 EventDispatcher 对象。 */ __proto.on=function(type,caller,listener,args){ return this._createListener(type,caller,listener,args,false); } /** *使用 EventDispatcher 对象注册指定类型的事件侦听器对象,以使侦听器能够接收事件通知,此侦听事件响应一次后自动移除。 *@param type 事件的类型。 *@param caller 事件侦听函数的执行域。 *@param listener 事件侦听函数。 *@param args (可选)事件侦听函数的回调参数。 *@return 此 EventDispatcher 对象。 */ __proto.once=function(type,caller,listener,args){ return this._createListener(type,caller,listener,args,true); } /**@private */ __proto._createListener=function(type,caller,listener,args,once,offBefore){ (offBefore===void 0)&& (offBefore=true); offBefore && this.off(type,caller,listener,once); var handler=EventHandler.create(caller || this,listener,args,once); this._events || (this._events={}); var events=this._events; if (!events[type])events[type]=handler; else { if (!events[type].run)events[type].push(handler); else events[type]=[events[type],handler]; } return this; } /** *从 EventDispatcher 对象中删除侦听器。 *@param type 事件的类型。 *@param caller 事件侦听函数的执行域。 *@param listener 事件侦听函数。 *@param onceOnly (可选)如果值为 true ,则只移除通过 once 方法添加的侦听器。 *@return 此 EventDispatcher 对象。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this._events || !this._events[type])return this; var listeners=this._events[type]; if (listeners !=null){ if (listeners.run){ if ((!caller || listeners.caller===caller)&& listeners.method===listener && (!onceOnly || listeners.once)){ delete this._events[type]; listeners.recover(); } }else { var count=0; for (var i=0,n=listeners.length;i < n;i++){ var item=listeners[i]; if (!item){ count++; continue ; } if (item && (!caller || item.caller===caller)&& item.method===listener && (!onceOnly || item.once)){ count++; listeners[i]=null; item.recover(); } } if (count===n)delete this._events[type]; } } return this; } /** *从 EventDispatcher 对象中删除指定事件类型的所有侦听器。 *@param type (可选)事件类型,如果值为 null,则移除本对象所有类型的侦听器。 *@return 此 EventDispatcher 对象。 */ __proto.offAll=function(type){ var events=this._events; if (!events)return this; if (type){ this._recoverHandlers(events[type]); delete events[type]; }else { for (var name in events){ this._recoverHandlers(events[name]); } this._events=null; } return this; } __proto._recoverHandlers=function(arr){ if (!arr)return; if (arr.run){ arr.recover(); }else { for (var i=arr.length-1;i >-1;i--){ if (arr[i]){ arr[i].recover(); arr[i]=null; } } } } /** *检测指定事件类型是否是鼠标事件。 *@param type 事件的类型。 *@return 如果是鼠标事件,则值为 true;否则,值为 false。 */ __proto.isMouseEvent=function(type){ return EventDispatcher.MOUSE_EVENTS[type]; } EventDispatcher.MOUSE_EVENTS={"rightmousedown":true,"rightmouseup":true,"rightclick":true,"mousedown":true,"mouseup":true,"mousemove":true,"mouseover":true,"mouseout":true,"click":true,"doubleclick":true}; EventDispatcher.__init$=function(){ Object.defineProperty(laya.events.EventDispatcher.prototype,"_events",{enumerable:false,writable:true}); /**@private */ //class EventHandler extends laya.utils.Handler EventHandler=(function(_super){ function EventHandler(caller,method,args,once){ EventHandler.__super.call(this,caller,method,args,once); } __class(EventHandler,'',_super); var __proto=EventHandler.prototype; __proto.recover=function(){ if (this._id > 0){ this._id=0; EventHandler._pool.push(this.clear()); } } EventHandler.create=function(caller,method,args,once){ (once===void 0)&& (once=true); if (EventHandler._pool.length)return EventHandler._pool.pop().setTo(caller,method,args,once); return new EventHandler(caller,method,args,once); } EventHandler._pool=[]; return EventHandler; })(Handler) } return EventDispatcher; })() /** *

    Handler 是事件处理器类。

    *

    推荐使用 Handler.create()方法从对象池创建,减少对象创建消耗。创建的 Handler 对象不再使用后,可以使用 Handler.recover()将其回收到对象池,回收后不要再使用此对象,否则会导致不可预料的错误。

    *

    注意:由于鼠标事件也用本对象池,不正确的回收及调用,可能会影响鼠标事件的执行。

    */ //class laya.utils.Handler var Handler=(function(){ function Handler(caller,method,args,once){ /**执行域(this)。*/ //this.caller=null; /**处理方法。*/ //this.method=null; /**参数。*/ //this.args=null; /**表示是否只执行一次。如果为true,回调后执行recover()进行回收,回收后会被再利用,默认为false 。*/ this.once=false; /**@private */ this._id=0; (once===void 0)&& (once=false); this.setTo(caller,method,args,once); } __class(Handler,'laya.utils.Handler'); var __proto=Handler.prototype; /** *设置此对象的指定属性值。 *@param caller 执行域(this)。 *@param method 回调方法。 *@param args 携带的参数。 *@param once 是否只执行一次,如果为true,执行后执行recover()进行回收。 *@return 返回 handler 本身。 */ __proto.setTo=function(caller,method,args,once){ this._id=Handler._gid++; this.caller=caller; this.method=method; this.args=args; this.once=once; return this; } /** *执行处理器。 */ __proto.run=function(){ if (this.method==null)return null; var id=this._id; var result=this.method.apply(this.caller,this.args); this._id===id && this.once && this.recover(); return result; } /** *执行处理器,携带额外数据。 *@param data 附加的回调数据,可以是单数据或者Array(作为多参)。 */ __proto.runWith=function(data){ if (this.method==null)return null; var id=this._id; if (data==null) var result=this.method.apply(this.caller,this.args); else if (!this.args && !data.unshift)result=this.method.call(this.caller,data); else if (this.args)result=this.method.apply(this.caller,this.args.concat(data)); else result=this.method.apply(this.caller,data); this._id===id && this.once && this.recover(); return result; } /** *清理对象引用。 */ __proto.clear=function(){ this.caller=null; this.method=null; this.args=null; return this; } /** *清理并回收到 Handler 对象池内。 */ __proto.recover=function(){ if (this._id > 0){ this._id=0; Handler._pool.push(this.clear()); } } Handler.create=function(caller,method,args,once){ (once===void 0)&& (once=true); if (Handler._pool.length)return Handler._pool.pop().setTo(caller,method,args,once); return new Handler(caller,method,args,once); } Handler._pool=[]; Handler._gid=1; return Handler; })() /** *BitmapFont 是位图字体类,用于定义位图字体信息。 */ //class laya.display.BitmapFont var BitmapFont=(function(){ function BitmapFont(){ this._texture=null; this._fontCharDic={}; this._fontWidthMap={}; this._complete=null; this._path=null; this._maxWidth=0; this._spaceWidth=10; this._padding=null; /**当前位图字体字号。*/ this.fontSize=12; /**表示是否根据实际使用的字体大小缩放位图字体大小。*/ this.autoScaleSize=false; /**字符间距(以像素为单位)。*/ this.letterSpacing=0; } __class(BitmapFont,'laya.display.BitmapFont'); var __proto=BitmapFont.prototype; /** *通过指定位图字体文件路径,加载位图字体文件,加载完成后会自动解析。 *@param path 位图字体文件的路径。 *@param complete 加载并解析完成的回调。如果成功返回this,如果失败返回null */ __proto.loadFont=function(path,complete){ this._path=path; this._complete=complete; Laya.loader.load([{url:this._path,type:/*laya.net.Loader.XML*/"xml"},{url:this._path.replace(".fnt",".png"),type:/*laya.net.Loader.IMAGE*/"image"}],Handler.create(this,this.onLoaded)); } /** *@private */ __proto.onLoaded=function(){ this.parseFont(Loader.getRes(this._path),Loader.getRes(this._path.replace(".fnt",".png"))); this._complete && this._complete.runWith(this._texture?this:null); } /** *解析字体文件。 *@param xml 字体文件XML。 *@param texture 字体的纹理。 */ __proto.parseFont=function(xml,texture){ if (xml==null || texture==null)return; this._texture=texture; var tX=0; var tScale=1; var tInfo=xml.getElementsByTagName("info"); if (!tInfo[0].getAttributeNode){ return this.parseFont2(xml,texture); } this.fontSize=parseInt(tInfo[0].getAttributeNode("size").nodeValue); var tPadding=tInfo[0].getAttributeNode("padding").nodeValue; var tPaddingArray=tPadding.split(","); this._padding=[parseInt(tPaddingArray[0]),parseInt(tPaddingArray[1]),parseInt(tPaddingArray[2]),parseInt(tPaddingArray[3])]; var chars; chars=xml.getElementsByTagName("char"); var i=0; for (i=0;i < chars.length;i++){ var tAttribute=chars[i]; var tId=parseInt(tAttribute.getAttributeNode("id").nodeValue); var xOffset=parseInt(tAttribute.getAttributeNode("xoffset").nodeValue)/ tScale; var yOffset=parseInt(tAttribute.getAttributeNode("yoffset").nodeValue)/ tScale; var xAdvance=parseInt(tAttribute.getAttributeNode("xadvance").nodeValue)/ tScale; var region=new Rectangle(); region.x=parseInt(tAttribute.getAttributeNode("x").nodeValue); region.y=parseInt(tAttribute.getAttributeNode("y").nodeValue); region.width=parseInt(tAttribute.getAttributeNode("width").nodeValue); region.height=parseInt(tAttribute.getAttributeNode("height").nodeValue); var tTexture=Texture.create(texture,region.x,region.y,region.width,region.height,xOffset,yOffset); this._maxWidth=Math.max(this._maxWidth,xAdvance+this.letterSpacing); this._fontCharDic[tId]=tTexture; this._fontWidthMap[tId]=xAdvance; } } /** *@private *解析字体文件。 *@param xml 字体文件XML。 *@param texture 字体的纹理。 */ __proto.parseFont2=function(xml,texture){ if (xml==null || texture==null)return; this._texture=texture; var tX=0; var tScale=1; var tInfo=xml.getElementsByTagName("info"); this.fontSize=parseInt(tInfo[0].attributes["size"].nodeValue); var tPadding=tInfo[0].attributes["padding"].nodeValue; var tPaddingArray=tPadding.split(","); this._padding=[parseInt(tPaddingArray[0]),parseInt(tPaddingArray[1]),parseInt(tPaddingArray[2]),parseInt(tPaddingArray[3])]; var chars=xml.getElementsByTagName("char"); var i=0; for (i=0;i < chars.length;i++){ var tAttribute=chars[i].attributes; var tId=parseInt(tAttribute["id"].nodeValue); var xOffset=parseInt(tAttribute["xoffset"].nodeValue)/ tScale; var yOffset=parseInt(tAttribute["yoffset"].nodeValue)/ tScale; var xAdvance=parseInt(tAttribute["xadvance"].nodeValue)/ tScale; var region=new Rectangle(); region.x=parseInt(tAttribute["x"].nodeValue); region.y=parseInt(tAttribute["y"].nodeValue); region.width=parseInt(tAttribute["width"].nodeValue); region.height=parseInt(tAttribute["height"].nodeValue); var tTexture=Texture.create(texture,region.x,region.y,region.width,region.height,xOffset,yOffset); this._maxWidth=Math.max(this._maxWidth,xAdvance+this.letterSpacing); this._fontCharDic[tId]=tTexture; this._fontWidthMap[tId]=xAdvance; } } /** *获取指定字符的字体纹理对象。 *@param char 字符。 *@return 指定的字体纹理对象。 */ __proto.getCharTexture=function(char){ return this._fontCharDic[char.charCodeAt(0)]; } /** *销毁位图字体,调用Text.unregisterBitmapFont 时,默认会销毁。 */ __proto.destroy=function(){ if (this._texture){ for (var p in this._fontCharDic){ var tTexture=this._fontCharDic[p]; if (tTexture)tTexture.destroy(); } this._texture.destroy(); this._fontCharDic=null; this._fontWidthMap=null; this._texture=null; } } /** *设置空格的宽(如果字体库有空格,这里就可以不用设置了)。 *@param spaceWidth 宽度,单位为像素。 */ __proto.setSpaceWidth=function(spaceWidth){ this._spaceWidth=spaceWidth; } /** *获取指定字符的宽度。 *@param char 字符。 *@return 宽度。 */ __proto.getCharWidth=function(char){ var code=char.charCodeAt(0); if (this._fontWidthMap[code])return this._fontWidthMap[code]+this.letterSpacing; if (char==" ")return this._spaceWidth+this.letterSpacing; return 0; } /** *获取指定文本内容的宽度。 *@param text 文本内容。 *@return 宽度。 */ __proto.getTextWidth=function(text){ var tWidth=0; for (var i=0,n=text.length;i < n;i++){ tWidth+=this.getCharWidth(text.charAt(i)); } return tWidth; } /** *获取最大字符宽度。 */ __proto.getMaxWidth=function(){ return this._maxWidth; } /** *获取最大字符高度。 */ __proto.getMaxHeight=function(){ return this.fontSize; } /** *@private *将指定的文本绘制到指定的显示对象上。 */ __proto.drawText=function(text,sprite,drawX,drawY,align,width){ var tWidth=this.getTextWidth(text); var tTexture; var dx=0; align==="center" && (dx=(width-tWidth)/ 2); align==="right" && (dx=(width-tWidth)); var tX=0; for (var i=0,n=text.length;i < n;i++){ tTexture=this.getCharTexture(text.charAt(i)); if (tTexture){ sprite.graphics.drawTexture(tTexture,drawX+tX+dx,drawY); tX+=this.getCharWidth(text.charAt(i)); } } } return BitmapFont; })() /** *@private *Style 类是元素样式定义类。 */ //class laya.display.css.Style var Style=(function(){ function Style(){ /**透明度。*/ this.alpha=1; /**表示是否显示。*/ this.visible=true; /**表示滚动区域。*/ this.scrollRect=null; /**混合模式。*/ this.blendMode=null; /**@private */ this._type=0; this.direction="ltr"; this._tf=Style._TF_EMPTY; } __class(Style,'laya.display.css.Style'); var __proto=Style.prototype; __proto.getTransform=function(){ return this._tf; } __proto.setTransform=function(value){ this._tf=value==='none' || !value ? Style._TF_EMPTY :value; } __proto.setTranslateX=function(value){ this._tf===Style._TF_EMPTY && (this._tf=new TransformInfo()); this._tf.translateX=value; } __proto.setTranslateY=function(value){ this._tf===Style._TF_EMPTY && (this._tf=new TransformInfo()); this._tf.translateY=value; } __proto.setScaleX=function(value){ this._tf===Style._TF_EMPTY && (this._tf=new TransformInfo()); this._tf.scaleX=value; } __proto.setScale=function(x,y){ this._tf===Style._TF_EMPTY && (this._tf=new TransformInfo()); this._tf.scaleX=x; this._tf.scaleY=y; } __proto.setScaleY=function(value){ this._tf===Style._TF_EMPTY && (this._tf=new TransformInfo()); this._tf.scaleY=value; } __proto.setRotate=function(value){ this._tf===Style._TF_EMPTY && (this._tf=new TransformInfo()); this._tf.rotate=value; } __proto.setSkewX=function(value){ this._tf===Style._TF_EMPTY && (this._tf=new TransformInfo()); this._tf.skewX=value; } __proto.setSkewY=function(value){ this._tf===Style._TF_EMPTY && (this._tf=new TransformInfo()); this._tf.skewY=value; } /**销毁此对象。*/ __proto.destroy=function(){ this.scrollRect=null; } /**@private */ __proto.render=function(sprite,context,x,y){} /**@private */ __proto.getCSSStyle=function(){ return CSSStyle.EMPTY; } /**@private */ __proto._enableLayout=function(){ return false; } /**X 轴缩放值。*/ __getset(0,__proto,'scaleX',function(){ return this._tf.scaleX; },function(value){ this.setScaleX(value); }); /**元素应用的 2D 或 3D 转换的值。该属性允许我们对元素进行旋转、缩放、移动或倾斜。*/ __getset(0,__proto,'transform',function(){ return this.getTransform(); },function(value){ this.setTransform(value); }); /**定义转换,只是用 X 轴的值。*/ __getset(0,__proto,'translateX',function(){ return this._tf.translateX; },function(value){ this.setTranslateX(value); }); /**定义转换,只是用 Y 轴的值。*/ __getset(0,__proto,'translateY',function(){ return this._tf.translateY; },function(value){ this.setTranslateY(value); }); /**Y 轴缩放值。*/ __getset(0,__proto,'scaleY',function(){ return this._tf.scaleY; },function(value){ this.setScaleY(value); }); /**表示元素是否显示为块级元素。*/ __getset(0,__proto,'block',function(){ return (this._type & 0x1)!=0; }); /**定义沿着 Y 轴的 2D 倾斜转换。*/ __getset(0,__proto,'skewY',function(){ return this._tf.skewY; },function(value){ this.setSkewY(value); }); /**定义旋转角度。*/ __getset(0,__proto,'rotate',function(){ return this._tf.rotate; },function(value){ this.setRotate(value); }); /**定义沿着 X 轴的 2D 倾斜转换。*/ __getset(0,__proto,'skewX',function(){ return this._tf.skewX; },function(value){ this.setSkewX(value); }); /**表示元素的左内边距。*/ __getset(0,__proto,'paddingLeft',function(){ return 0; }); /**表示元素的上内边距。*/ __getset(0,__proto,'paddingTop',function(){ return 0; }); /**是否为绝对定位。*/ __getset(0,__proto,'absolute',function(){ return true; }); Style.__init__=function(){ Style._TF_EMPTY=new TransformInfo(); Style.EMPTY=new Style(); } Style.EMPTY=null; Style._TF_EMPTY=null; return Style; })() /** *@private *Font 类是字体显示定义类。 */ //class laya.display.css.Font var Font=(function(){ function Font(src){ this._type=0; this._weight=0; this._decoration=null; this._text=null; /** *首行缩进 (以像素为单位)。 */ this.indent=0; this._color=Color.create(Font.defaultColor); this.family=Font.defaultFamily; this.stroke=Font._STROKE; this.size=Font.defaultSize; src && src!==Font.EMPTY && src.copyTo(this); } __class(Font,'laya.display.css.Font'); var __proto=Font.prototype; /** *字体样式字符串。 */ __proto.set=function(value){ this._text=null; var strs=value.split(' '); for (var i=0,n=strs.length;i < n;i++){ var str=strs[i]; switch (str){ case 'italic': this.italic=true; continue ; case 'bold': this.bold=true; continue ; } if (str.indexOf('px')> 0){ this.size=parseInt(str); this.family=strs[i+1]; i++; continue ; } } } /** *返回字体样式字符串。 *@return 字体样式字符串。 */ __proto.toString=function(){ this._text="" this.italic && (this._text+="italic "); this.bold && (this._text+="bold "); return this._text+=this.size+"px "+this.family; } /** *将当前的属性值复制到传入的 Font 对象。 *@param dec 一个 Font 对象。 */ __proto.copyTo=function(dec){ dec._type=this._type; dec._text=this._text; dec._weight=this._weight; dec._color=this._color; dec.family=this.family; dec.stroke=this.stroke !=Font._STROKE ? this.stroke.slice():Font._STROKE; dec.indent=this.indent; dec.size=this.size; } /** *表示是否为密码格式。 */ __getset(0,__proto,'password',function(){ return (this._type & 0x400)!==0; },function(value){ value ? (this._type |=0x400):(this._type &=~0x400); }); /** *表示颜色字符串。 */ __getset(0,__proto,'color',function(){ return this._color.strColor; },function(value){ this._color=Color.create(value); }); /** *表示是否为斜体。 */ __getset(0,__proto,'italic',function(){ return (this._type & 0x200)!==0; },function(value){ value ? (this._type |=0x200):(this._type &=~0x200); }); /** *表示是否为粗体。 */ __getset(0,__proto,'bold',function(){ return (this._type & 0x800)!==0; },function(value){ value ? (this._type |=0x800):(this._type &=~0x800); }); /** *文本的粗细。 */ __getset(0,__proto,'weight',function(){ return ""+this._weight; },function(value){ var weight=0; switch (value){ case 'normal': break ; case 'bold': this.bold=true; weight=700; break ; case 'bolder': weight=800; break ; case 'lighter': weight=100; break ; default : weight=parseInt(value); } this._weight=weight; this._text=null; }); /** *规定添加到文本的修饰。 */ __getset(0,__proto,'decoration',function(){ return this._decoration ? this._decoration.value :null; },function(value){ var strs=value.split(' '); this._decoration || (this._decoration={}); switch (strs[0]){ case '_': this._decoration.type='underline' break ; case '-': this._decoration.type='line-through' break ; case 'overline': this._decoration.type='overline' break ; default : this._decoration.type=strs[0]; } strs[1] && (this._decoration.color=Color.create(strs)); this._decoration.value=value; }); Font.__init__=function(){ Font.EMPTY=new Font(null); } Font.EMPTY=null; Font.defaultColor="#000000"; Font.defaultSize=12; Font.defaultFamily="Arial"; Font.defaultFont="12px Arial"; Font._STROKE=[0,"#000000"]; Font._ITALIC=0x200; Font._PASSWORD=0x400; Font._BOLD=0x800; return Font; })() /** *@private */ //class laya.display.css.TransformInfo var TransformInfo=(function(){ function TransformInfo(){ this.translateX=0; this.translateY=0; this.scaleX=1; this.scaleY=1; this.rotate=0; this.skewX=0; this.skewY=0; } __class(TransformInfo,'laya.display.css.TransformInfo'); return TransformInfo; })() /** *Graphics 类用于创建绘图显示对象。Graphics可以同时绘制多个位图或者矢量图,还可以结合save,restore,transform,scale,rotate,translate,alpha等指令对绘图效果进行变化。 *Graphics以命令流方式存储,可以通过cmds属性访问所有命令流。Graphics是比Sprite更轻量级的对象,合理使用能提高应用性能(比如把大量的节点绘图改为一个节点的Graphics命令集合,能减少大量节点创建消耗)。 *@see laya.display.Sprite#graphics */ //class laya.display.Graphics var Graphics=(function(){ function Graphics(){ /**@private */ //this._sp=null; /**@private */ this._one=null; /**@private */ this._cmds=null; /**@private */ //this._vectorgraphArray=null; /**@private */ //this._graphicBounds=null; this._render=this._renderEmpty; if (Render.isConchNode){ var _this_=this; _this_._nativeObj=new (window)._conchGraphics(); _this_.id=_this_._nativeObj.conchID; } } __class(Graphics,'laya.display.Graphics'); var __proto=Graphics.prototype; /** *

    销毁此对象。

    */ __proto.destroy=function(){ this.clear(); if (this._graphicBounds)this._graphicBounds.destroy(); this._graphicBounds=null; this._vectorgraphArray=null; this._sp && (this._sp._renderType=0); this._sp=null; } /** *

    清空绘制命令。

    *@param recoverCmds 是否回收绘图指令 */ __proto.clear=function(recoverCmds){ (recoverCmds===void 0)&& (recoverCmds=false); var i=0,len=0; if (recoverCmds){ var tCmd=this._one; if (this._cmds){ len=this._cmds.length; for (i=0;i < len;i++){ tCmd=this._cmds[i]; if (tCmd && (tCmd.callee===Render._context._drawTexture || tCmd.callee===Render._context._drawTextureWithTransform)){ tCmd[0]=null; Graphics._cache.push(tCmd); } } this._cmds.length=0; }else if (tCmd){ if (tCmd && (tCmd.callee===Render._context._drawTexture || tCmd.callee===Render._context._drawTextureWithTransform)){ tCmd[0]=null; Graphics._cache.push(tCmd); } } }else { this._cmds=null; } this._one=null; this._render=this._renderEmpty; this._sp && (this._sp._renderType &=~ /*laya.renders.RenderSprite.IMAGE*/0x01 & ~ /*laya.renders.RenderSprite.GRAPHICS*/0x200); this._repaint(); if (this._vectorgraphArray){ for (i=0,len=this._vectorgraphArray.length;i < len;i++){ VectorGraphManager.getInstance().deleteShape(this._vectorgraphArray[i]); } this._vectorgraphArray.length=0; } } /**@private */ __proto._clearBoundsCache=function(){ if (this._graphicBounds)this._graphicBounds.reset(); } /**@private */ __proto._initGraphicBounds=function(){ if (!this._graphicBounds){ this._graphicBounds=new GraphicsBounds(); this._graphicBounds._graphics=this; } } /** *@private *重绘此对象。 */ __proto._repaint=function(){ this._clearBoundsCache(); this._sp && this._sp.repaint(); } /**@private */ __proto._isOnlyOne=function(){ return !this._cmds || this._cmds.length===0; } /** *获取位置及宽高信息矩阵(比较耗CPU,频繁使用会造成卡顿,尽量少用)。 *@param realSize (可选)使用图片的真实大小,默认为false *@return 位置与宽高组成的 一个 Rectangle 对象。 */ __proto.getBounds=function(realSize){ (realSize===void 0)&& (realSize=false); this._initGraphicBounds(); return this._graphicBounds.getBounds(realSize); } /** *@private *@param realSize (可选)使用图片的真实大小,默认为false *获取端点列表。 */ __proto.getBoundPoints=function(realSize){ (realSize===void 0)&& (realSize=false); this._initGraphicBounds(); return this._graphicBounds.getBoundPoints(realSize); } __proto._addCmd=function(a){ this._cmds=this._cmds || []; a.callee=a.shift(); this._cmds.push(a); } __proto.setFilters=function(fs){ this._saveToCmd(Render._context._setFilters,fs); } /** *绘制纹理。 *@param tex 纹理。 *@param x (可选)X轴偏移量。 *@param y (可选)Y轴偏移量。 *@param width (可选)宽度。 *@param height (可选)高度。 *@param m (可选)矩阵信息。 *@param alpha (可选)透明度。 */ __proto.drawTexture=function(tex,x,y,width,height,m,alpha){ (x===void 0)&& (x=0); (y===void 0)&& (y=0); (width===void 0)&& (width=0); (height===void 0)&& (height=0); (alpha===void 0)&& (alpha=1); if (!tex || alpha < 0.01)return null; if (!width)width=tex.sourceWidth; if (!height)height=tex.sourceHeight; alpha=alpha < 0 ? 0 :(alpha > 1 ? 1 :alpha); var offset=(!Render.isWebGL && (Browser.onFirefox || Browser.onEdge||Browser.onIE||Browser.onSafari))? 0.5 :0; var wRate=width / tex.sourceWidth; var hRate=height / tex.sourceHeight; width=tex.width *wRate; height=tex.height *hRate; if (tex.loaded && (width <=0 || height <=0))return null; x+=tex.offsetX *wRate; y+=tex.offsetY *hRate; this._sp && (this._sp._renderType |=/*laya.renders.RenderSprite.GRAPHICS*/0x200); var args; x-=offset; y-=offset; width+=2 *offset; height+=2 *offset; if (Graphics._cache.length){ args=Graphics._cache.pop(); args[0]=tex; args[1]=x; args[2]=y; args[3]=width; args[4]=height; args[5]=m; args[6]=alpha; }else { args=[tex,x,y,width,height,m,alpha]; } args.callee=(m || alpha !=1)? Render._context._drawTextureWithTransform :Render._context._drawTexture; if (this._one==null && !m && alpha==1){ this._one=args; this._render=this._renderOneImg; }else { this._saveToCmd(args.callee,args); } if (!tex.loaded){ tex.once(/*laya.events.Event.LOADED*/"loaded",this,this._textureLoaded,[tex,args]); } this._repaint(); return args; } /** *@private 清理贴图并替换为最新的 *@param tex */ __proto.cleanByTexture=function(tex,x,y,width,height){ (width===void 0)&& (width=0); (height===void 0)&& (height=0); if (!tex)return this.clear(); if (this._one && this._render===this._renderOneImg){ if (!width)width=tex.sourceWidth; if (!height)height=tex.sourceHeight; var wRate=width / tex.sourceWidth; var hRate=height / tex.sourceHeight; width=tex.width *wRate; height=tex.height *hRate; x+=tex.offsetX *wRate; y+=tex.offsetY *hRate; this._one[0]=tex; this._one[1]=x; this._one[2]=y; this._one[3]=width; this._one[4]=height; this._repaint(); }else { this.clear(); tex && this.drawTexture(tex,x,y,width,height); } } /** *批量绘制同样纹理。 *@param tex 纹理。 *@param pos 绘制坐标。 */ __proto.drawTextures=function(tex,pos){ if (!tex)return; this._saveToCmd(Render._context._drawTextures,[tex,pos]); } /** *用texture填充。 *@param tex 纹理。 *@param x X轴偏移量。 *@param y Y轴偏移量。 *@param width (可选)宽度。 *@param height (可选)高度。 *@param type (可选)填充类型 repeat|repeat-x|repeat-y|no-repeat *@param offset (可选)贴图纹理偏移 */ __proto.fillTexture=function(tex,x,y,width,height,type,offset){ (width===void 0)&& (width=0); (height===void 0)&& (height=0); (type===void 0)&& (type="repeat"); if (!tex)return; var args=[tex,x,y,width,height,type,offset || Point.EMPTY,{}]; if (!tex.loaded){ tex.once(/*laya.events.Event.LOADED*/"loaded",this,this._textureLoaded,[tex,args]); } this._saveToCmd(Render._context._fillTexture,args); } __proto._textureLoaded=function(tex,param){ param[3]=param[3] || tex.width; param[4]=param[4] || tex.height; this._repaint(); } /** *填充一个圆形。这是一个临时函数,以后会删除,建议用户自己实现。 *@param x *@param y *@param tex *@param cx 圆心位置。 *@param cy *@param radius *@param segNum 分段数,越大越平滑。 */ __proto.fillCircle=function(x,y,tex,cx,cy,radius,segNum){ tex.bitmap.enableMerageInAtlas=false; var verts=new Float32Array((segNum+1)*2); var uvs=new Float32Array((segNum+1)*2); var indices=new Uint16Array(segNum*3); var dang=2 *Math.PI / segNum; var cang=0; verts[0]=cx; verts[1]=cy; uvs[0]=cx / tex.width; uvs[1]=cy / tex.height; var idx=2; for (var i=0;i < segNum;i++){ var px=radius *Math.cos(cang)+cx; var py=radius *Math.sin(cang)+cy; verts[idx]=px; verts[idx+1]=py; uvs[idx]=px / tex.width; uvs[idx+1]=py / tex.height; cang+=dang; idx+=2; } idx=0; for (i=0;i < segNum;i++){ indices[idx++]=0; indices[idx++]=i+1; indices[idx++]=(i+2 >=segNum+1)?1:(i+2); } this.drawTriangles(tex,x,y,verts,uvs,indices); } /** *绘制一组三角形 *@param texture 纹理。 *@param x X轴偏移量。 *@param y Y轴偏移量。 *@param vertices 顶点数组。 *@param indices 顶点索引。 *@param uvData UV数据。 *@param matrix 缩放矩阵。 *@param alpha alpha *@param color 颜色变换 *@param blendMode blend模式 */ __proto.drawTriangles=function(texture,x,y,vertices,uvs,indices,matrix,alpha,color,blendMode){ (alpha===void 0)&& (alpha=1); this._saveToCmd(Render._context.drawTriangles,[texture,x,y,vertices,uvs,indices,matrix,alpha,color,blendMode]); } /** *@private *保存到命令流。 */ __proto._saveToCmd=function(fun,args){ this._sp && (this._sp._renderType |=/*laya.renders.RenderSprite.GRAPHICS*/0x200); if (this._one==null){ this._one=args; this._render=this._renderOne; }else { this._sp && (this._sp._renderType &=~ /*laya.renders.RenderSprite.IMAGE*/0x01); this._render=this._renderAll; (this._cmds || (this._cmds=[])).length===0 && this._cmds.push(this._one); this._cmds.push(args); } args.callee=fun; this._repaint(); return args; } /** *设置剪裁区域,超出剪裁区域的坐标不显示。 *@param x X 轴偏移量。 *@param y Y 轴偏移量。 *@param width 宽度。 *@param height 高度。 */ __proto.clipRect=function(x,y,width,height){ this._saveToCmd(Render._context._clipRect,[x,y,width,height]); } /** *在画布上绘制文本。 *@param text 在画布上输出的文本。 *@param x 开始绘制文本的 x 坐标位置(相对于画布)。 *@param y 开始绘制文本的 y 坐标位置(相对于画布)。 *@param font 定义字号和字体,比如"20px Arial"。 *@param color 定义文本颜色,比如"#ff0000"。 *@param textAlign 文本对齐方式,可选值:"left","center","right"。 */ __proto.fillText=function(text,x,y,font,color,textAlign,underLine){ (underLine===void 0)&& (underLine=0); this._saveToCmd(Render._context._fillText,[text,x,y,font || Font.defaultFont,color,textAlign]); } /** *在画布上绘制“被填充且镶边的”文本。 *@param text 在画布上输出的文本。 *@param x 开始绘制文本的 x 坐标位置(相对于画布)。 *@param y 开始绘制文本的 y 坐标位置(相对于画布)。 *@param font 定义字体和字号,比如"20px Arial"。 *@param fillColor 定义文本颜色,比如"#ff0000"。 *@param borderColor 定义镶边文本颜色。 *@param lineWidth 镶边线条宽度。 *@param textAlign 文本对齐方式,可选值:"left","center","right"。 */ __proto.fillBorderText=function(text,x,y,font,fillColor,borderColor,lineWidth,textAlign){ this._saveToCmd(Render._context._fillBorderText,[text,x,y,font || Font.defaultFont,fillColor,borderColor,lineWidth,textAlign]); } /** *在画布上绘制文本(没有填色)。文本的默认颜色是黑色。 *@param text 在画布上输出的文本。 *@param x 开始绘制文本的 x 坐标位置(相对于画布)。 *@param y 开始绘制文本的 y 坐标位置(相对于画布)。 *@param font 定义字体和字号,比如"20px Arial"。 *@param color 定义文本颜色,比如"#ff0000"。 *@param lineWidth 线条宽度。 *@param textAlign 文本对齐方式,可选值:"left","center","right"。 */ __proto.strokeText=function(text,x,y,font,color,lineWidth,textAlign){ this._saveToCmd(Render._context._strokeText,[text,x,y,font || Font.defaultFont,color,lineWidth,textAlign]); } /** *设置透明度。 *@param value 透明度。 */ __proto.alpha=function(value){ value=value < 0 ? 0 :(value > 1 ? 1 :value); this._saveToCmd(Render._context._alpha,[value]); } /** *设置当前透明度。 *@param value 透明度。 */ __proto.setAlpha=function(value){ value=value < 0 ? 0 :(value > 1 ? 1 :value); this._saveToCmd(Render._context._setAlpha,[value]); } /** *替换绘图的当前转换矩阵。 *@param mat 矩阵。 *@param pivotX (可选)水平方向轴心点坐标。 *@param pivotY (可选)垂直方向轴心点坐标。 */ __proto.transform=function(matrix,pivotX,pivotY){ (pivotX===void 0)&& (pivotX=0); (pivotY===void 0)&& (pivotY=0); this._saveToCmd(Render._context._transform,[matrix,pivotX,pivotY]); } /** *旋转当前绘图。(推荐使用transform,性能更高) *@param angle 旋转角度,以弧度计。 *@param pivotX (可选)水平方向轴心点坐标。 *@param pivotY (可选)垂直方向轴心点坐标。 */ __proto.rotate=function(angle,pivotX,pivotY){ (pivotX===void 0)&& (pivotX=0); (pivotY===void 0)&& (pivotY=0); this._saveToCmd(Render._context._rotate,[angle,pivotX,pivotY]); } /** *缩放当前绘图至更大或更小。(推荐使用transform,性能更高) *@param scaleX 水平方向缩放值。 *@param scaleY 垂直方向缩放值。 *@param pivotX (可选)水平方向轴心点坐标。 *@param pivotY (可选)垂直方向轴心点坐标。 */ __proto.scale=function(scaleX,scaleY,pivotX,pivotY){ (pivotX===void 0)&& (pivotX=0); (pivotY===void 0)&& (pivotY=0); this._saveToCmd(Render._context._scale,[scaleX,scaleY,pivotX,pivotY]); } /** *重新映射画布上的 (0,0)位置。 *@param x 添加到水平坐标(x)上的值。 *@param y 添加到垂直坐标(y)上的值。 */ __proto.translate=function(x,y){ this._saveToCmd(Render._context._translate,[x,y]); } /** *保存当前环境的状态。 */ __proto.save=function(){ this._saveToCmd(Render._context._save,[]); } /** *返回之前保存过的路径状态和属性。 */ __proto.restore=function(){ this._saveToCmd(Render._context._restore,[]); } /** *@private *替换文本内容。 *@param text 文本内容。 *@return 替换成功则值为true,否则值为flase。 */ __proto.replaceText=function(text){ this._repaint(); var cmds=this._cmds; if (!cmds){ if (this._one && this._isTextCmd(this._one.callee)){ if (this._one[0].toUpperCase)this._one[0]=text; else this._one[0].setText(text); return true; } }else { for (var i=cmds.length-1;i >-1;i--){ if (this._isTextCmd(cmds[i].callee)){ if (cmds[i][0].toUpperCase)cmds[i][0]=text; else cmds[i][0].setText(text); return true; } } } return false; } /**@private */ __proto._isTextCmd=function(fun){ return fun===Render._context._fillText || fun===Render._context._fillBorderText || fun===Render._context._strokeText; } /** *@private *替换文本颜色。 *@param color 颜色。 */ __proto.replaceTextColor=function(color){ this._repaint(); var cmds=this._cmds; if (!cmds){ if (this._one && this._isTextCmd(this._one.callee)){ this._one[4]=color; if (!this._one[0].toUpperCase)this._one[0].changed=true; } }else { for (var i=cmds.length-1;i >-1;i--){ if (this._isTextCmd(cmds[i].callee)){ cmds[i][4]=color; if (!cmds[i][0].toUpperCase)cmds[i][0].changed=true; } } } } /** *加载并显示一个图片。 *@param url 图片地址。 *@param x (可选)显示图片的x位置。 *@param y (可选)显示图片的y位置。 *@param width (可选)显示图片的宽度,设置为0表示使用图片默认宽度。 *@param height (可选)显示图片的高度,设置为0表示使用图片默认高度。 *@param complete (可选)加载完成回调。 */ __proto.loadImage=function(url,x,y,width,height,complete){ var _$this=this; (x===void 0)&& (x=0); (y===void 0)&& (y=0); (width===void 0)&& (width=0); (height===void 0)&& (height=0); var tex=Loader.getRes(url); if (tex)onloaded(tex); else Laya.loader.load(url,Handler.create(null,onloaded),null,/*laya.net.Loader.IMAGE*/"image"); function onloaded (tex){ if (tex){ _$this.drawTexture(tex,x,y,width,height); if (complete !=null)complete.call(_$this._sp,tex); } } } /** *@private */ __proto._renderEmpty=function(sprite,context,x,y){} /** *@private */ __proto._renderAll=function(sprite,context,x,y){ var cmds=this._cmds,cmd; for (var i=0,n=cmds.length;i < n;i++){ (cmd=cmds[i]).callee.call(context,x,y,cmd); } } /** *@private */ __proto._renderOne=function(sprite,context,x,y){ this._one.callee.call(context,x,y,this._one); } /** *@private */ __proto._renderOneImg=function(sprite,context,x,y){ this._one.callee.call(context,x,y,this._one); if (sprite._renderType!==2305){ sprite._renderType |=/*laya.renders.RenderSprite.IMAGE*/0x01; } } /** *绘制一条线。 *@param fromX X轴开始位置。 *@param fromY Y轴开始位置。 *@param toX X轴结束位置。 *@param toY Y轴结束位置。 *@param lineColor 颜色。 *@param lineWidth (可选)线条宽度。 */ __proto.drawLine=function(fromX,fromY,toX,toY,lineColor,lineWidth){ (lineWidth===void 0)&& (lineWidth=1); var tId=0; if (Render.isWebGL){ tId=VectorGraphManager.getInstance().getId(); if (this._vectorgraphArray==null)this._vectorgraphArray=[]; this._vectorgraphArray.push(tId); }; var offset=lineWidth % 2===0 ? 0 :0.5; var arr=[fromX+offset,fromY+offset,toX+offset,toY+offset,lineColor,lineWidth,tId]; this._saveToCmd(Render._context._drawLine,arr); } /** *绘制一系列线段。 *@param x 开始绘制的X轴位置。 *@param y 开始绘制的Y轴位置。 *@param points 线段的点集合。格式:[x1,y1,x2,y2,x3,y3...]。 *@param lineColor 线段颜色,或者填充绘图的渐变对象。 *@param lineWidth (可选)线段宽度。 */ __proto.drawLines=function(x,y,points,lineColor,lineWidth){ (lineWidth===void 0)&& (lineWidth=1); var tId=0; if (!points || points.length < 4)return; if (Render.isWebGL){ tId=VectorGraphManager.getInstance().getId(); if (this._vectorgraphArray==null)this._vectorgraphArray=[]; this._vectorgraphArray.push(tId); }; var offset=lineWidth % 2===0 ? 0 :0.5; var arr=[x+offset,y+offset,points,lineColor,lineWidth,tId]; this._saveToCmd(Render._context._drawLines,arr); } /** *绘制一系列曲线。 *@param x 开始绘制的 X 轴位置。 *@param y 开始绘制的 Y 轴位置。 *@param points 线段的点集合,格式[startx,starty,ctrx,ctry,startx,starty...]。 *@param lineColor 线段颜色,或者填充绘图的渐变对象。 *@param lineWidth (可选)线段宽度。 */ __proto.drawCurves=function(x,y,points,lineColor,lineWidth){ (lineWidth===void 0)&& (lineWidth=1); var arr=[x,y,points,lineColor,lineWidth]; this._saveToCmd(Render._context._drawCurves,arr); } /** *绘制矩形。 *@param x 开始绘制的 X 轴位置。 *@param y 开始绘制的 Y 轴位置。 *@param width 矩形宽度。 *@param height 矩形高度。 *@param fillColor 填充颜色,或者填充绘图的渐变对象。 *@param lineColor (可选)边框颜色,或者填充绘图的渐变对象。 *@param lineWidth (可选)边框宽度。 */ __proto.drawRect=function(x,y,width,height,fillColor,lineColor,lineWidth){ (lineWidth===void 0)&& (lineWidth=1); var offset=lineColor ? lineWidth / 2 :0; var lineOffset=lineColor ? lineWidth :0; var arr=[x+offset,y+offset,width-lineOffset,height-lineOffset,fillColor,lineColor,lineWidth]; this._saveToCmd(Render._context._drawRect,arr); } /** *绘制圆形。 *@param x 圆点X 轴位置。 *@param y 圆点Y 轴位置。 *@param radius 半径。 *@param fillColor 填充颜色,或者填充绘图的渐变对象。 *@param lineColor (可选)边框颜色,或者填充绘图的渐变对象。 *@param lineWidth (可选)边框宽度。 */ __proto.drawCircle=function(x,y,radius,fillColor,lineColor,lineWidth){ (lineWidth===void 0)&& (lineWidth=1); var offset=lineColor ? lineWidth / 2 :0; var tId=0; if (Render.isWebGL){ tId=VectorGraphManager.getInstance().getId(); if (this._vectorgraphArray==null)this._vectorgraphArray=[]; this._vectorgraphArray.push(tId); }; var arr=[x,y,radius-offset,fillColor,lineColor,lineWidth,tId]; this._saveToCmd(Render._context._drawCircle,arr); } /** *绘制扇形。 *@param x 开始绘制的 X 轴位置。 *@param y 开始绘制的 Y 轴位置。 *@param radius 扇形半径。 *@param startAngle 开始角度。 *@param endAngle 结束角度。 *@param fillColor 填充颜色,或者填充绘图的渐变对象。 *@param lineColor (可选)边框颜色,或者填充绘图的渐变对象。 *@param lineWidth (可选)边框宽度。 */ __proto.drawPie=function(x,y,radius,startAngle,endAngle,fillColor,lineColor,lineWidth){ (lineWidth===void 0)&& (lineWidth=1); var offset=lineColor ? lineWidth / 2 :0; var lineOffset=lineColor ? lineWidth :0; var tId=0; if (Render.isWebGL){ tId=VectorGraphManager.getInstance().getId(); if (this._vectorgraphArray==null)this._vectorgraphArray=[]; this._vectorgraphArray.push(tId); }; var arr=[x+offset,y+offset,radius-lineOffset,startAngle,endAngle,fillColor,lineColor,lineWidth,tId]; arr[3]=Utils.toRadian(startAngle); arr[4]=Utils.toRadian(endAngle); this._saveToCmd(Render._context._drawPie,arr); } /** *绘制多边形。 *@param x 开始绘制的 X 轴位置。 *@param y 开始绘制的 Y 轴位置。 *@param points 多边形的点集合。 *@param fillColor 填充颜色,或者填充绘图的渐变对象。 *@param lineColor (可选)边框颜色,或者填充绘图的渐变对象。 *@param lineWidth (可选)边框宽度。 */ __proto.drawPoly=function(x,y,points,fillColor,lineColor,lineWidth){ (lineWidth===void 0)&& (lineWidth=1); var tId=0; var tIsConvexPolygon=false; if (Render.isWebGL){ tId=VectorGraphManager.getInstance().getId(); if (this._vectorgraphArray==null)this._vectorgraphArray=[]; this._vectorgraphArray.push(tId); if (points.length > 6){ tIsConvexPolygon=false; }else { tIsConvexPolygon=true; } }; var offset=lineColor ? (lineWidth % 2===0 ? 0 :0.5):0; var arr=[x+offset,y+offset,points,fillColor,lineColor,lineWidth,tId,tIsConvexPolygon]; this._saveToCmd(Render._context._drawPoly,arr); } /** *绘制路径。 *@param x 开始绘制的 X 轴位置。 *@param y 开始绘制的 Y 轴位置。 *@param paths 路径集合,路径支持以下格式:[["moveTo",x,y],["lineTo",x,y,x,y,x,y],["arcTo",x1,y1,x2,y2,r],["closePath"]]。 *@param brush (可选)刷子定义,支持以下设置{fillStyle}。 *@param pen (可选)画笔定义,支持以下设置{strokeStyle,lineWidth,lineJoin,lineCap,miterLimit}。 */ __proto.drawPath=function(x,y,paths,brush,pen){ var arr=[x,y,paths,brush,pen]; this._saveToCmd(Render._context._drawPath,arr); } __proto.setDirection=function(dir){} /** *@private *命令流。存储了所有绘制命令。 */ __getset(0,__proto,'cmds',function(){ return this._cmds; },function(value){ this._sp && (this._sp._renderType |=/*laya.renders.RenderSprite.GRAPHICS*/0x200); this._cmds=value; this._render=this._renderAll; this._repaint(); }); Graphics.__init__=function(){ if (Render.isConchNode){ var from=laya.display.Graphics.prototype; var to=Browser.window.ConchGraphics.prototype; var list=["setDirection","clear","destroy","alpha","rotate","transform","scale","translate","save","restore","clipRect","blendMode","fillText","fillBorderText","_fands","drawRect","drawCircle","drawPie","drawPoly","drawPath","drawImageM","drawLine","drawLines","_drawPs","drawCurves","replaceText","replaceTextColor","_fillImage","fillTexture","setSkinMesh","drawParticle","drawImageS"]; for (var i=0,len=list.length;i <=len;i++){ var temp=list[i]; from[temp]=to[temp]; } from._saveToCmd=null; if (to.drawImageS){ from.drawTextures=function (tex,pos){ if (!tex)return; if (!(tex.loaded && tex.bitmap && tex.source)){ return; }; var uv=tex.uv,w=tex.bitmap.width,h=tex.bitmap.height; this.drawImageS(tex.bitmap.source,uv[0] *w,uv[1] *h,(uv[2]-uv[0])*w,(uv[5]-uv[3])*h,tex.offsetX,tex.offsetY,tex.width,tex.height,pos); } } from.drawTexture=function (tex,x,y,width,height,m,alpha){ (x===void 0)&& (x=0); (y===void 0)&& (y=0); (width===void 0)&& (width=0); (height===void 0)&& (height=0); (alpha===void 0)&& (alpha=1); if (!tex)return; if (!tex.loaded){ tex.once(/*laya.events.Event.LOADED*/"loaded",this,function(){ this.drawTexture(tex,x,y,width,height,m); }); return; } if (!(tex.loaded && tex.bitmap && tex.source)){ return; } if (!width)width=tex.sourceWidth; if (!height)height=tex.sourceHeight; alpha=alpha < 0 ? 0 :(alpha > 1 ? 1 :alpha); width=width-tex.sourceWidth+tex.width; height=height-tex.sourceHeight+tex.height; if (width <=0 || height <=0)return; x+=tex.offsetX; y+=tex.offsetY; var uv=tex.uv,w=tex.bitmap.width,h=tex.bitmap.height; if (uv[4] < uv[0] && uv[5] < uv[1]){ this.drawImageM(tex.bitmap.source,uv[4] *w,uv[5] *h,(uv[0]-uv[4])*w,(uv[1]-uv[5])*h,x,y,width,height,m,alpha); } else { this.drawImageM(tex.bitmap.source,uv[0] *w,uv[1] *h,(uv[2]-uv[0])*w,(uv[5]-uv[3])*h,x,y,width,height,m,alpha); } this._repaint(); } from.fillTexture=function (tex,x,y,width,height,type,offset){ (width===void 0)&& (width=0); (height===void 0)&& (height=0); (type===void 0)&& (type="repeat"); if (!tex)return; if (tex.loaded){ var ctxi=Render._context.ctx; var w=tex.bitmap.width,h=tex.bitmap.height,uv=tex.uv; var pat; if (tex.uv !=Texture.DEF_UV){ pat=ctxi.createPattern(tex.bitmap.source,type,uv[0] *w,uv[1] *h,(uv[2]-uv[0])*w,(uv[5]-uv[3])*h); }else { pat=ctxi.createPattern(tex.bitmap.source,type); }; var sX=0,sY=0; if (offset){ x+=offset.x % tex.width; y+=offset.y % tex.height; sX-=offset.x % tex.width; sY-=offset.y % tex.height; } this._fillImage(pat,x,y,sX,sY,width,height); } } } } Graphics._cache=[]; return Graphics; })() /** *@private *Graphic bounds数据类 */ //class laya.display.GraphicsBounds var GraphicsBounds=(function(){ function GraphicsBounds(){ /**@private */ //this._temp=null; /**@private */ //this._bounds=null; /**@private */ //this._rstBoundPoints=null; /**@private */ this._cacheBoundsType=false; /**@private */ //this._graphics=null; } __class(GraphicsBounds,'laya.display.GraphicsBounds'); var __proto=GraphicsBounds.prototype; /** *销毁 */ __proto.destroy=function(){ this._graphics=null; this._temp=null; this._rstBoundPoints=null; this._bounds=null; } /** *重置数据 */ __proto.reset=function(){ this._temp && (this._temp.length=0); } /** *获取位置及宽高信息矩阵(比较耗CPU,频繁使用会造成卡顿,尽量少用)。 *@param realSize (可选)使用图片的真实大小,默认为false *@return 位置与宽高组成的 一个 Rectangle 对象。 */ __proto.getBounds=function(realSize){ (realSize===void 0)&& (realSize=false); if (!this._bounds || !this._temp || this._temp.length < 1 || realSize !=this._cacheBoundsType){ this._bounds=Rectangle._getWrapRec(this.getBoundPoints(realSize),this._bounds) } this._cacheBoundsType=realSize; return this._bounds; } /** *@private *@param realSize (可选)使用图片的真实大小,默认为false *获取端点列表。 */ __proto.getBoundPoints=function(realSize){ (realSize===void 0)&& (realSize=false); if (!this._temp || this._temp.length < 1 || realSize !=this._cacheBoundsType) this._temp=this._getCmdPoints(realSize); this._cacheBoundsType=realSize; return this._rstBoundPoints=Utils.copyArray(this._rstBoundPoints,this._temp); } __proto._getCmdPoints=function(realSize){ (realSize===void 0)&& (realSize=false); var context=Render._context; var cmds=this._graphics.cmds; var rst; rst=this._temp || (this._temp=[]); rst.length=0; if (!cmds && this._graphics._one !=null){ GraphicsBounds._tempCmds.length=0; GraphicsBounds._tempCmds.push(this._graphics._one); cmds=GraphicsBounds._tempCmds; } if (!cmds) return rst; var matrixs; matrixs=GraphicsBounds._tempMatrixArrays; matrixs.length=0; var tMatrix=GraphicsBounds._initMatrix; tMatrix.identity(); var tempMatrix=GraphicsBounds._tempMatrix; var cmd; var tex; var wRate=NaN; var hRate=NaN; var oWidth=NaN; var oHeight=NaN; var offX=NaN; var offY=NaN; for (var i=0,n=cmds.length;i < n;i++){ cmd=cmds[i]; if (!cmd.callee)continue ; switch (cmd.callee){ case context._save: case 7: matrixs.push(tMatrix); tMatrix=tMatrix.clone(); break ; case context._restore: case 8: tMatrix=matrixs.pop(); break ; case context._scale: case 5: tempMatrix.identity(); tempMatrix.translate(-cmd[2],-cmd[3]); tempMatrix.scale(cmd[0],cmd[1]); tempMatrix.translate(cmd[2],cmd[3]); this._switchMatrix(tMatrix,tempMatrix); break ; case context._rotate: case 3: tempMatrix.identity(); tempMatrix.translate(-cmd[1],-cmd[2]); tempMatrix.rotate(cmd[0]); tempMatrix.translate(cmd[1],cmd[2]); this._switchMatrix(tMatrix,tempMatrix); break ; case context._translate: case 6: tempMatrix.identity(); tempMatrix.translate(cmd[0],cmd[1]); this._switchMatrix(tMatrix,tempMatrix); break ; case context._transform: case 4: tempMatrix.identity(); tempMatrix.translate(-cmd[1],-cmd[2]); tempMatrix.concat(cmd[0]); tempMatrix.translate(cmd[1],cmd[2]); this._switchMatrix(tMatrix,tempMatrix); break ; case 16: case 24: GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[0],cmd[1],cmd[2],cmd[3]),tMatrix); break ; case 17: tMatrix.copyTo(tempMatrix); tempMatrix.concat(cmd[4]); GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[0],cmd[1],cmd[2],cmd[3]),tempMatrix); break ; case context._drawTexture: tex=cmd[0]; if (realSize){ if (cmd[3] && cmd[4]){ GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[1],cmd[2],cmd[3],cmd[4]),tMatrix); }else { tex=cmd[0]; GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[1],cmd[2],tex.width,tex.height),tMatrix); } }else { wRate=(cmd[3] || tex.sourceWidth)/ tex.width; hRate=(cmd[4] || tex.sourceHeight)/ tex.height; oWidth=wRate *tex.sourceWidth; oHeight=hRate *tex.sourceHeight; offX=tex.offsetX > 0 ? tex.offsetX :0; offY=tex.offsetY > 0 ? tex.offsetY :0; offX *=wRate; offY *=hRate; GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[1]-offX,cmd[2]-offY,oWidth,oHeight),tMatrix); } break ; case context._fillTexture: if (cmd[3] && cmd[4]){ GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[1],cmd[2],cmd[3],cmd[4]),tMatrix); }else { tex=cmd[0]; GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[1],cmd[2],tex.width,tex.height),tMatrix); } break ; case context._drawTextureWithTransform:; var drawMatrix; if (cmd[5]){ tMatrix.copyTo(tempMatrix); tempMatrix.concat(cmd[5]); drawMatrix=tempMatrix; }else { drawMatrix=tMatrix; } if (realSize){ if (cmd[3] && cmd[4]){ GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[1],cmd[2],cmd[3],cmd[4]),drawMatrix); }else { tex=cmd[0]; GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[1],cmd[2],tex.width,tex.height),drawMatrix); } }else { tex=cmd[0]; wRate=(cmd[3] || tex.sourceWidth)/ tex.width; hRate=(cmd[4] || tex.sourceHeight)/ tex.height; oWidth=wRate *tex.sourceWidth; oHeight=hRate *tex.sourceHeight; offX=tex.offsetX > 0 ? tex.offsetX :0; offY=tex.offsetY > 0 ? tex.offsetY :0; offX *=wRate; offY *=hRate; GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[1]-offX,cmd[2]-offY,oWidth,oHeight),drawMatrix); } break ; case context._drawRect: case 13: GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[0],cmd[1],cmd[2],cmd[3]),tMatrix); break ; case context._drawCircle: case context._fillCircle: case 14: GraphicsBounds._addPointArrToRst(rst,Rectangle._getBoundPointS(cmd[0]-cmd[2],cmd[1]-cmd[2],cmd[2]+cmd[2],cmd[2]+cmd[2]),tMatrix); break ; case context._drawLine: case 20: GraphicsBounds._tempPoints.length=0; var lineWidth=NaN; lineWidth=cmd[5] *0.5; if (cmd[0]==cmd[2]){ GraphicsBounds._tempPoints.push(cmd[0]+lineWidth,cmd[1],cmd[2]+lineWidth,cmd[3],cmd[0]-lineWidth,cmd[1],cmd[2]-lineWidth,cmd[3]); }else if (cmd[1]==cmd[3]){ GraphicsBounds._tempPoints.push(cmd[0],cmd[1]+lineWidth,cmd[2],cmd[3]+lineWidth,cmd[0],cmd[1]-lineWidth,cmd[2],cmd[3]-lineWidth); }else { GraphicsBounds._tempPoints.push(cmd[0],cmd[1],cmd[2],cmd[3]); } GraphicsBounds._addPointArrToRst(rst,GraphicsBounds._tempPoints,tMatrix); break ; case context._drawCurves: case 22: GraphicsBounds._addPointArrToRst(rst,Bezier.I.getBezierPoints(cmd[2]),tMatrix,cmd[0],cmd[1]); break ; case context._drawPoly: case context._drawLines: case 18: GraphicsBounds._addPointArrToRst(rst,cmd[2],tMatrix,cmd[0],cmd[1]); break ; case context._drawPath: case 19: GraphicsBounds._addPointArrToRst(rst,this._getPathPoints(cmd[2]),tMatrix,cmd[0],cmd[1]); break ; case context._drawPie: case 15: GraphicsBounds._addPointArrToRst(rst,this._getPiePoints(cmd[0],cmd[1],cmd[2],cmd[3],cmd[4]),tMatrix); break ; } } if (rst.length > 200){ rst=Utils.copyArray(rst,Rectangle._getWrapRec(rst)._getBoundPoints()); }else if (rst.length > 8) rst=GrahamScan.scanPList(rst); return rst; } __proto._switchMatrix=function(tMatix,tempMatrix){ tempMatrix.concat(tMatix); tempMatrix.copyTo(tMatix); } __proto._getPiePoints=function(x,y,radius,startAngle,endAngle){ var rst=GraphicsBounds._tempPoints; GraphicsBounds._tempPoints.length=0; rst.push(x,y); var delta=(endAngle-startAngle)% (2 *Math.PI); var segnum=10; var step=delta / segnum; var i=NaN; var angle=startAngle; for (i=0;i <=segnum;i++){ rst.push(x+radius *Math.cos(angle),y+radius *Math.sin(angle)); angle+=step; } return rst; } __proto._getPathPoints=function(paths){ var i=0,len=0; var rst=GraphicsBounds._tempPoints; rst.length=0; len=paths.length; var tCMD; for (i=0;i < len;i++){ tCMD=paths[i]; if (tCMD.length > 1){ rst.push(tCMD[1],tCMD[2]); if (tCMD.length > 3){ rst.push(tCMD[3],tCMD[4]); } } } return rst; } GraphicsBounds._addPointArrToRst=function(rst,points,matrix,dx,dy){ (dx===void 0)&& (dx=0); (dy===void 0)&& (dy=0); var i=0,len=0; len=points.length; for (i=0;i < len;i+=2){ GraphicsBounds._addPointToRst(rst,points[i]+dx,points[i+1]+dy,matrix); } } GraphicsBounds._addPointToRst=function(rst,x,y,matrix){ var _tempPoint=Point.TEMP; _tempPoint.setTo(x ? x :0,y ? y :0); matrix.transformPoint(_tempPoint); rst.push(_tempPoint.x,_tempPoint.y); } GraphicsBounds._tempPoints=[]; GraphicsBounds._tempMatrixArrays=[]; GraphicsBounds._tempCmds=[]; __static(GraphicsBounds, ['_tempMatrix',function(){return this._tempMatrix=new Matrix();},'_initMatrix',function(){return this._initMatrix=new Matrix();} ]); return GraphicsBounds; })() /** *Event 是事件类型的集合。一般当发生事件时,Event 对象将作为参数传递给事件侦听器。 */ //class laya.events.Event var Event=(function(){ function Event(){ /**事件类型。*/ //this.type=null; /**原生浏览器事件。*/ //this.nativeEvent=null; /**事件目标触发对象。*/ //this.target=null; /**事件当前冒泡对象。*/ //this.currentTarget=null; /**@private */ //this._stoped=false; /**分配给触摸点的唯一标识号(作为 int)。*/ //this.touchId=0; /**键盘值*/ //this.keyCode=0; /**滚轮滑动增量*/ //this.delta=0; } __class(Event,'laya.events.Event'); var __proto=Event.prototype; /** *设置事件数据。 *@param type 事件类型。 *@param currentTarget 事件目标触发对象。 *@param target 事件当前冒泡对象。 *@return 返回当前 Event 对象。 */ __proto.setTo=function(type,currentTarget,target){ this.type=type; this.currentTarget=currentTarget; this.target=target; return this; } /** *阻止对事件流中当前节点的后续节点中的所有事件侦听器进行处理。此方法不会影响当前节点 (currentTarget)中的任何事件侦听器。 */ __proto.stopPropagation=function(){ this._stoped=true; } /**鼠标在 Stage 上的 Y 轴坐标*/ __getset(0,__proto,'stageY',function(){ return Laya.stage.mouseY; }); /** *包含按下或释放的键的字符代码值。字符代码值为英文键盘值。 */ __getset(0,__proto,'charCode',function(){ return this.nativeEvent.charCode; }); /** *触摸点列表。 */ __getset(0,__proto,'touches',function(){ var arr=this.nativeEvent.touches; if (arr){ var stage=Laya.stage; for (var i=0,n=arr.length;i < n;i++){ var e=arr[i]; var point=Point.TEMP; point.setTo(e.clientX,e.clientY); stage._canvasTransform.invertTransformPoint(point); stage.transform.invertTransformPoint(point); e.stageX=point.x; e.stageY=point.y; } } return arr; }); /** *表示键在键盘上的位置。这对于区分在键盘上多次出现的键非常有用。
    *例如,您可以根据此属性的值来区分左 Shift 键和右 Shift 键:左 Shift 键的值为 KeyLocation.LEFT,右 Shift 键的值为 KeyLocation.RIGHT。另一个示例是区分标准键盘 (KeyLocation.STANDARD)与数字键盘 (KeyLocation.NUM_PAD)上按下的数字键。 */ __getset(0,__proto,'keyLocation',function(){ return this.nativeEvent.keyLocation; }); /** *表示 Ctrl 键是处于活动状态 (true)还是非活动状态 (false)。 */ __getset(0,__proto,'ctrlKey',function(){ return this.nativeEvent.ctrlKey; }); /** *表示 Alt 键是处于活动状态 (true)还是非活动状态 (false)。 */ __getset(0,__proto,'altKey',function(){ return this.nativeEvent.altKey; }); /** *表示 Shift 键是处于活动状态 (true)还是非活动状态 (false)。 */ __getset(0,__proto,'shiftKey',function(){ return this.nativeEvent.shiftKey; }); /**鼠标在 Stage 上的 X 轴坐标*/ __getset(0,__proto,'stageX',function(){ return Laya.stage.mouseX; }); Event.EMPTY=new Event(); Event.MOUSE_DOWN="mousedown"; Event.MOUSE_UP="mouseup"; Event.CLICK="click"; Event.RIGHT_MOUSE_DOWN="rightmousedown"; Event.RIGHT_MOUSE_UP="rightmouseup"; Event.RIGHT_CLICK="rightclick"; Event.MOUSE_MOVE="mousemove"; Event.MOUSE_OVER="mouseover"; Event.MOUSE_OUT="mouseout"; Event.MOUSE_WHEEL="mousewheel"; Event.ROLL_OVER="mouseover"; Event.ROLL_OUT="mouseout"; Event.DOUBLE_CLICK="doubleclick"; Event.CHANGE="change"; Event.CHANGED="changed"; Event.RESIZE="resize"; Event.ADDED="added"; Event.REMOVED="removed"; Event.DISPLAY="display"; Event.UNDISPLAY="undisplay"; Event.ERROR="error"; Event.COMPLETE="complete"; Event.LOADED="loaded"; Event.PROGRESS="progress"; Event.INPUT="input"; Event.RENDER="render"; Event.OPEN="open"; Event.MESSAGE="message"; Event.CLOSE="close"; Event.KEY_DOWN="keydown"; Event.KEY_PRESS="keypress"; Event.KEY_UP="keyup"; Event.FRAME="enterframe"; Event.DRAG_START="dragstart"; Event.DRAG_MOVE="dragmove"; Event.DRAG_END="dragend"; Event.ENTER="enter"; Event.SELECT="select"; Event.BLUR="blur"; Event.FOCUS="focus"; Event.VISIBILITY_CHANGE="visibilitychange"; Event.FOCUS_CHANGE="focuschange"; Event.PLAYED="played"; Event.PAUSED="paused"; Event.STOPPED="stopped"; Event.START="start"; Event.END="end"; Event.ENABLE_CHANGED="enablechanged"; Event.ACTIVE_IN_HIERARCHY_CHANGED="activeinhierarchychanged"; Event.COMPONENT_ADDED="componentadded"; Event.COMPONENT_REMOVED="componentremoved"; Event.LAYER_CHANGED="layerchanged"; Event.HIERARCHY_LOADED="hierarchyloaded"; Event.RECOVERED="recovered"; Event.RELEASED="released"; Event.LINK="link"; Event.LABEL="label"; Event.FULL_SCREEN_CHANGE="fullscreenchange"; Event.DEVICE_LOST="devicelost"; Event.MESH_CHANGED="meshchanged"; Event.MATERIAL_CHANGED="materialchanged"; Event.WORLDMATRIX_NEEDCHANGE="worldmatrixneedchanged"; Event.ANIMATION_CHANGED="animationchanged"; Event.TRIGGER_ENTER="triggerenter"; Event.TRIGGER_STAY="triggerstay"; Event.TRIGGER_EXIT="triggerexit"; Event.TRAIL_FILTER_CHANGE="trailfilterchange"; Event.DOMINO_FILTER_CHANGE="dominofilterchange"; return Event; })() /** *Keyboard 类的属性是一些常数,这些常数表示控制游戏时最常用的键。 */ //class laya.events.Keyboard var Keyboard=(function(){ function Keyboard(){} __class(Keyboard,'laya.events.Keyboard'); Keyboard.NUMBER_0=48; Keyboard.NUMBER_1=49; Keyboard.NUMBER_2=50; Keyboard.NUMBER_3=51; Keyboard.NUMBER_4=52; Keyboard.NUMBER_5=53; Keyboard.NUMBER_6=54; Keyboard.NUMBER_7=55; Keyboard.NUMBER_8=56; Keyboard.NUMBER_9=57; Keyboard.A=65; Keyboard.B=66; Keyboard.C=67; Keyboard.D=68; Keyboard.E=69; Keyboard.F=70; Keyboard.G=71; Keyboard.H=72; Keyboard.I=73; Keyboard.J=74; Keyboard.K=75; Keyboard.L=76; Keyboard.M=77; Keyboard.N=78; Keyboard.O=79; Keyboard.P=80; Keyboard.Q=81; Keyboard.R=82; Keyboard.S=83; Keyboard.T=84; Keyboard.U=85; Keyboard.V=86; Keyboard.W=87; Keyboard.X=88; Keyboard.Y=89; Keyboard.Z=90; Keyboard.F1=112; Keyboard.F2=113; Keyboard.F3=114; Keyboard.F4=115; Keyboard.F5=116; Keyboard.F6=117; Keyboard.F7=118; Keyboard.F8=119; Keyboard.F9=120; Keyboard.F10=121; Keyboard.F11=122; Keyboard.F12=123; Keyboard.F13=124; Keyboard.F14=125; Keyboard.F15=126; Keyboard.NUMPAD=21; Keyboard.NUMPAD_0=96; Keyboard.NUMPAD_1=97; Keyboard.NUMPAD_2=98; Keyboard.NUMPAD_3=99; Keyboard.NUMPAD_4=100; Keyboard.NUMPAD_5=101; Keyboard.NUMPAD_6=102; Keyboard.NUMPAD_7=103; Keyboard.NUMPAD_8=104; Keyboard.NUMPAD_9=105; Keyboard.NUMPAD_ADD=107; Keyboard.NUMPAD_DECIMAL=110; Keyboard.NUMPAD_DIVIDE=111; Keyboard.NUMPAD_ENTER=108; Keyboard.NUMPAD_MULTIPLY=106; Keyboard.NUMPAD_SUBTRACT=109; Keyboard.SEMICOLON=186; Keyboard.EQUAL=187; Keyboard.COMMA=188; Keyboard.MINUS=189; Keyboard.PERIOD=190; Keyboard.SLASH=191; Keyboard.BACKQUOTE=192; Keyboard.LEFTBRACKET=219; Keyboard.BACKSLASH=220; Keyboard.RIGHTBRACKET=221; Keyboard.QUOTE=222; Keyboard.ALTERNATE=18; Keyboard.BACKSPACE=8; Keyboard.CAPS_LOCK=20; Keyboard.COMMAND=15; Keyboard.CONTROL=17; Keyboard.DELETE=46; Keyboard.ENTER=13; Keyboard.ESCAPE=27; Keyboard.PAGE_UP=33; Keyboard.PAGE_DOWN=34; Keyboard.END=35; Keyboard.HOME=36; Keyboard.LEFT=37; Keyboard.UP=38; Keyboard.RIGHT=39; Keyboard.DOWN=40; Keyboard.SHIFT=16; Keyboard.SPACE=32; Keyboard.TAB=9; Keyboard.INSERT=45; return Keyboard; })() /** *

    KeyBoardManager 是键盘事件管理类。该类从浏览器中接收键盘事件,并派发该事件。

    *

    派发事件时若 Stage.focus 为空则只从 Stage 上派发该事件,否则将从 Stage.focus 对象开始一直冒泡派发该事件。所以在 Laya.stage 上监听键盘事件一定能够收到,如果在其他地方监听,则必须处在Stage.focus的冒泡链上才能收到该事件。

    *

    用户可以通过代码 Laya.stage.focus=someNode 的方式来设置focus对象。

    *

    用户可统一的根据事件对象中 e.keyCode 来判断按键类型,该属性兼容了不同浏览器的实现。

    */ //class laya.events.KeyBoardManager var KeyBoardManager=(function(){ function KeyBoardManager(){} __class(KeyBoardManager,'laya.events.KeyBoardManager'); KeyBoardManager.__init__=function(){ KeyBoardManager._addEvent("keydown"); KeyBoardManager._addEvent("keypress"); KeyBoardManager._addEvent("keyup"); } KeyBoardManager._addEvent=function(type){ Browser.document.addEventListener(type,function(e){ laya.events.KeyBoardManager._dispatch(e,type); },true); } KeyBoardManager._dispatch=function(e,type){ if (!KeyBoardManager.enabled)return; KeyBoardManager._event._stoped=false; KeyBoardManager._event.nativeEvent=e; KeyBoardManager._event.keyCode=e.keyCode || e.which || e.charCode; if (type==="keydown")KeyBoardManager._pressKeys[KeyBoardManager._event.keyCode]=true; else if (type==="keyup")KeyBoardManager._pressKeys[KeyBoardManager._event.keyCode]=null; var target=(Laya.stage.focus && (Laya.stage.focus.event !=null)&& Laya.stage.focus.displayedInStage)? Laya.stage.focus :Laya.stage; var ct=target; while (ct){ ct.event(type,KeyBoardManager._event.setTo(type,ct,target)); ct=ct.parent; } } KeyBoardManager.hasKeyDown=function(key){ return KeyBoardManager._pressKeys[key]; } KeyBoardManager._pressKeys={}; KeyBoardManager.enabled=true; __static(KeyBoardManager, ['_event',function(){return this._event=new Event();} ]); return KeyBoardManager; })() /** *

    KeyLocation 类包含表示在键盘或类似键盘的输入设备上按键位置的常量。

    *

    KeyLocation 常数用在键盘事件对象的 keyLocation 属性中。

    */ //class laya.events.KeyLocation var KeyLocation=(function(){ function KeyLocation(){} __class(KeyLocation,'laya.events.KeyLocation'); KeyLocation.STANDARD=0; KeyLocation.LEFT=1; KeyLocation.RIGHT=2; KeyLocation.NUM_PAD=3; return KeyLocation; })() /** *

    MouseManager 是鼠标、触摸交互管理器。

    *

    鼠标事件流包括捕获阶段、目标阶段、冒泡阶段。
    *捕获阶段:此阶段引擎会从stage开始递归检测stage及其子对象,直到找到命中的目标对象或者未命中任何对象;
    *目标阶段:找到命中的目标对象;
    *冒泡阶段:事件离开目标对象,按节点层级向上逐层通知,直到到达舞台的过程。

    */ //class laya.events.MouseManager var MouseManager=(function(){ function MouseManager(){ /**canvas 上的鼠标X坐标。*/ this.mouseX=0; /**canvas 上的鼠标Y坐标。*/ this.mouseY=0; /**是否禁用除 stage 以外的鼠标事件检测。*/ this.disableMouseEvent=false; /**鼠标按下的时间。单位为毫秒。*/ this.mouseDownTime=0; /**鼠标移动精度。*/ this.mouseMoveAccuracy=2; this._stage=null; this._target=null; this._lastMoveTimer=0; this._isLeftMouse=false; this._eventList=[]; this._touchIDs={}; this._id=1; this._tTouchID=0; this._event=new Event(); this._matrix=new Matrix(); this._point=new Point(); this._rect=new Rectangle(); this._prePoint=new Point(); this._curTouchID=NaN; } __class(MouseManager,'laya.events.MouseManager'); var __proto=MouseManager.prototype; /** *@private *初始化。 */ __proto.__init__=function(stage,canvas){ var _$this=this; this._stage=stage; var _this=this; var list=this._eventList; canvas.oncontextmenu=function (e){ if (MouseManager.enabled)return false; } canvas.addEventListener('mousedown',function(e){ if (MouseManager.enabled){ if(!Browser.onIE)e.preventDefault(); list.push(e); _this.mouseDownTime=Browser.now(); } }); canvas.addEventListener('mouseup',function(e){ if (MouseManager.enabled){ e.preventDefault(); list.push(e); _this.mouseDownTime=-Browser.now(); } },true); canvas.addEventListener('mousemove',function(e){ if (MouseManager.enabled){ e.preventDefault(); var now=Browser.now(); if (now-_this._lastMoveTimer < 10)return; _this._lastMoveTimer=now; list.push(e); } },true); canvas.addEventListener("mouseout",function(e){ if (MouseManager.enabled)list.push(e); }) canvas.addEventListener("mouseover",function(e){ if (MouseManager.enabled)list.push(e); }) canvas.addEventListener("touchstart",function(e){ if (MouseManager.enabled){ list.push(e); if (!MouseManager._isFirstTouch&&!Input.isInputting)e.preventDefault(); _this.mouseDownTime=Browser.now(); } }); canvas.addEventListener("touchend",function(e){ if (MouseManager.enabled){ if (!MouseManager._isFirstTouch&&!Input.isInputting)e.preventDefault(); MouseManager._isFirstTouch=false; list.push(e); _this.mouseDownTime=-Browser.now(); }else { _$this._curTouchID=NaN; } },true); canvas.addEventListener("touchmove",function(e){ if (MouseManager.enabled){ e.preventDefault(); list.push(e); } },true); canvas.addEventListener("touchcancel",function(e){ if (MouseManager.enabled){ e.preventDefault(); list.push(e); }else { _$this._curTouchID=NaN; } },true); canvas.addEventListener('mousewheel',function(e){ if (MouseManager.enabled)list.push(e); }); canvas.addEventListener('DOMMouseScroll',function(e){ if (MouseManager.enabled)list.push(e); }); } __proto.initEvent=function(e,nativeEvent){ var _this=this; _this._event._stoped=false; _this._event.nativeEvent=nativeEvent || e; _this._target=null; this._point.setTo(e.pageX || e.clientX,e.pageY || e.clientY); this._stage._canvasTransform.invertTransformPoint(this._point); _this.mouseX=this._point.x; _this.mouseY=this._point.y; _this._event.touchId=e.identifier || 0; this._tTouchID=_this._event.touchId; var evt; evt=TouchManager.I._event; evt._stoped=false; evt.nativeEvent=_this._event.nativeEvent; evt.touchId=_this._event.touchId; } __proto.checkMouseWheel=function(e){ this._event.delta=e.wheelDelta ? e.wheelDelta *0.025 :-e.detail; var _lastOvers=TouchManager.I.getLastOvers(); for (var i=0,n=_lastOvers.length;i < n;i++){ var ele=_lastOvers[i]; ele.event(/*laya.events.Event.MOUSE_WHEEL*/"mousewheel",this._event.setTo(/*laya.events.Event.MOUSE_WHEEL*/"mousewheel",ele,this._target)); } } // _stage.event(Event.MOUSE_WHEEL,_event.setTo(Event.MOUSE_WHEEL,_stage,_target)); __proto.onMouseMove=function(ele){ TouchManager.I.onMouseMove(ele,this._tTouchID); } __proto.onMouseDown=function(ele){ if (Input.isInputting && Laya.stage.focus && Laya.stage.focus["focus"] && !Laya.stage.focus.contains(this._target)){ var pre_input=Laya.stage.focus['_tf'] || Laya.stage.focus; var new_input=ele['_tf'] || ele; if ((new_input instanceof laya.display.Input )&& new_input.multiline==pre_input.multiline) pre_input['_focusOut'](); else pre_input.focus=false; } TouchManager.I.onMouseDown(ele,this._tTouchID,this._isLeftMouse); } __proto.onMouseUp=function(ele){ TouchManager.I.onMouseUp(ele,this._tTouchID,this._isLeftMouse); } __proto.check=function(sp,mouseX,mouseY,callBack){ this._point.setTo(mouseX,mouseY); sp.fromParentPoint(this._point); mouseX=this._point.x; mouseY=this._point.y; var scrollRect=sp.scrollRect; if (scrollRect){ this._rect.setTo(scrollRect.x,scrollRect.y,scrollRect.width,scrollRect.height); if (!this._rect.contains(mouseX,mouseY))return false; } if (!this.disableMouseEvent){ if (sp.hitTestPrior && !sp.mouseThrough && !this.hitTest(sp,mouseX,mouseY)){ return false; } for (var i=sp._childs.length-1;i >-1;i--){ var child=sp._childs[i]; if (!child.destroyed && child.mouseEnabled && child.visible){ if (this.check(child,mouseX,mouseY,callBack))return true; } } }; var isHit=(sp.hitTestPrior && !sp.mouseThrough && !this.disableMouseEvent)? true :this.hitTest(sp,mouseX,mouseY); if (isHit){ this._target=sp; callBack.call(this,sp); }else if (callBack===this.onMouseUp && sp===this._stage){ this._target=this._stage; callBack.call(this,this._target); } return isHit; } __proto.hitTest=function(sp,mouseX,mouseY){ var isHit=false; if (sp.scrollRect){ mouseX-=sp.scrollRect.x; mouseY-=sp.scrollRect.y; } if ((sp.hitArea instanceof laya.utils.HitArea )){ return sp.hitArea.isHit(mouseX,mouseY); } if (sp.width > 0 && sp.height > 0 || sp.mouseThrough || sp.hitArea){ if (!sp.mouseThrough){ var hitRect=this._rect; if (sp.hitArea)hitRect=sp.hitArea; else hitRect.setTo(0,0,sp.width,sp.height); isHit=hitRect.contains(mouseX,mouseY); }else { isHit=sp.getGraphicBounds().contains(mouseX,mouseY); } } return isHit; } /** *执行事件处理。 */ __proto.runEvent=function(){ var len=this._eventList.length; if (!len)return; var _this=this; var i=0,j=0,n=0,touch; while (i < len){ var evt=this._eventList[i]; if (evt.type!=='mousemove')this._prePoint.x=this._prePoint.y=-1000000; switch (evt.type){ case 'mousedown': this._touchIDs[0]=this._id++; if (!MouseManager._isTouchRespond){ _this._isLeftMouse=evt.button===0; _this.initEvent(evt); _this.check(_this._stage,_this.mouseX,_this.mouseY,_this.onMouseDown); }else MouseManager._isTouchRespond=false; break ; case 'mouseup': _this._isLeftMouse=evt.button===0; _this.initEvent(evt); _this.check(_this._stage,_this.mouseX,_this.mouseY,_this.onMouseUp); break ; case 'mousemove': if ((Math.abs(this._prePoint.x-evt.clientX)+Math.abs(this._prePoint.y-evt.clientY))>=this.mouseMoveAccuracy){ this._prePoint.x=evt.clientX; this._prePoint.y=evt.clientY; _this.initEvent(evt); _this.check(_this._stage,_this.mouseX,_this.mouseY,_this.onMouseMove); } break ; case "touchstart": MouseManager._isTouchRespond=true; _this._isLeftMouse=true; var touches=evt.changedTouches; for (j=0,n=touches.length;j < n;j++){ touch=touches[j]; if (MouseManager.multiTouchEnabled || isNaN(this._curTouchID)){ this._curTouchID=touch.identifier; if (this._id % 200===0)this._touchIDs={}; this._touchIDs[touch.identifier]=this._id++; _this.initEvent(touch,evt); _this.check(_this._stage,_this.mouseX,_this.mouseY,_this.onMouseDown); } } break ; case "touchend": case "touchcancel": MouseManager._isTouchRespond=true; _this._isLeftMouse=true; var touchends=evt.changedTouches; for (j=0,n=touchends.length;j < n;j++){ touch=touchends[j]; if (MouseManager.multiTouchEnabled || touch.identifier==this._curTouchID){ this._curTouchID=NaN; _this.initEvent(touch,evt); var isChecked=false; isChecked=_this.check(_this._stage,_this.mouseX,_this.mouseY,_this.onMouseUp); if (!isChecked){ _this.onMouseUp(null); } } } break ; case "touchmove":; var touchemoves=evt.changedTouches; for (j=0,n=touchemoves.length;j < n;j++){ touch=touchemoves[j]; if (MouseManager.multiTouchEnabled || touch.identifier==this._curTouchID){ _this.initEvent(touch,evt); _this.check(_this._stage,_this.mouseX,_this.mouseY,_this.onMouseMove); } } break ; case "wheel": case "mousewheel": case "DOMMouseScroll": _this.checkMouseWheel(evt); break ; case "mouseout": TouchManager.I.stageMouseOut(); break ; case "mouseover": _this._stage.event(/*laya.events.Event.MOUSE_OVER*/"mouseover",_this._event.setTo(/*laya.events.Event.MOUSE_OVER*/"mouseover",_this._stage,_this._stage)); break ; } i++; } this._eventList.length=0; } MouseManager.enabled=true; MouseManager.multiTouchEnabled=true; MouseManager._isTouchRespond=false; MouseManager._isFirstTouch=true; __static(MouseManager, ['instance',function(){return this.instance=new MouseManager();} ]); return MouseManager; })() /** *@private *Touch事件管理类,处理多点触控下的鼠标事件 */ //class laya.events.TouchManager var TouchManager=(function(){ function TouchManager(){ /** *当前over的touch表 */ this.preOvers=[]; /** *当前down的touch表 */ this.preDowns=[]; this.preRightDowns=[]; /** *是否启用 */ this.enable=true; this._lastClickTime=0; this._event=new Event(); } __class(TouchManager,'laya.events.TouchManager'); var __proto=TouchManager.prototype; __proto._clearTempArrs=function(){ TouchManager._oldArr.length=0; TouchManager._newArr.length=0; TouchManager._tEleArr.length=0; } /** *从touch表里查找对应touchID的数据 *@param touchID touch ID *@param arr touch表 *@return * */ __proto.getTouchFromArr=function(touchID,arr){ var i=0,len=0; len=arr.length; var tTouchO; for (i=0;i < len;i++){ tTouchO=arr[i]; if (tTouchO.id==touchID){ return tTouchO; } } return null; } /** *从touch表里移除一个元素 *@param touchID touch ID *@param arr touch表 * */ __proto.removeTouchFromArr=function(touchID,arr){ var i=0; for (i=arr.length-1;i >=0;i--){ if (arr[i].id==touchID){ arr.splice(i,1); } } } /** *创建一个touch数据 *@param ele 当前的根节点 *@param touchID touchID *@return * */ __proto.createTouchO=function(ele,touchID){ var rst; rst=Pool.getItem("TouchData")|| {}; rst.id=touchID; rst.tar=ele; return rst; } /** *处理touchStart *@param ele 根节点 *@param touchID touchID *@param isLeft (可选)是否为左键 */ __proto.onMouseDown=function(ele,touchID,isLeft){ (isLeft===void 0)&& (isLeft=false); if (!this.enable) return; var preO; var tO; var arrs; preO=this.getTouchFromArr(touchID,this.preOvers); arrs=this.getEles(ele,null,TouchManager._tEleArr); if (!preO){ tO=this.createTouchO(ele,touchID); this.preOvers.push(tO); }else { preO.tar=ele; } if (Browser.onMobile) this.sendEvents(arrs,/*laya.events.Event.MOUSE_OVER*/"mouseover"); var preDowns; preDowns=isLeft ? this.preDowns :this.preRightDowns; preO=this.getTouchFromArr(touchID,preDowns); if (!preO){ tO=this.createTouchO(ele,touchID); preDowns.push(tO); }else { preO.tar=ele; } this.sendEvents(arrs,isLeft ? /*laya.events.Event.MOUSE_DOWN*/"mousedown" :/*laya.events.Event.RIGHT_MOUSE_DOWN*/"rightmousedown"); this._clearTempArrs(); } /** *派发事件。 *@param eles 对象列表。 *@param type 事件类型。 */ __proto.sendEvents=function(eles,type){ var i=0,len=0; len=eles.length; this._event._stoped=false; var _target; _target=eles[0]; var tE; for (i=0;i < len;i++){ tE=eles[i]; if (tE.destroyed)return; tE.event(type,this._event.setTo(type,tE,_target)); if (this._event._stoped) break ; } } /** *获取对象列表。 *@param start 起始节点。 *@param end 结束节点。 *@param rst 返回值。如果此值不为空,则将其赋值为计算结果,从而避免创建新数组;如果此值为空,则创建新数组返回。 *@return Array 返回节点列表。 */ __proto.getEles=function(start,end,rst){ if (!rst){ rst=[]; }else { rst.length=0; } while (start && start !=end){ rst.push(start); start=start.parent; } return rst; } /** *touchMove时处理out事件和over时间。 *@param eleNew 新的根节点。 *@param elePre 旧的根节点。 *@param touchID (可选)touchID,默认为0。 */ __proto.checkMouseOutAndOverOfMove=function(eleNew,elePre,touchID){ (touchID===void 0)&& (touchID=0); if (elePre==eleNew) return; var tar; var arrs; var i=0,len=0; if (elePre.contains(eleNew)){ arrs=this.getEles(eleNew,elePre,TouchManager._tEleArr); this.sendEvents(arrs,/*laya.events.Event.MOUSE_OVER*/"mouseover"); }else if (eleNew.contains(elePre)){ arrs=this.getEles(elePre,eleNew,TouchManager._tEleArr); this.sendEvents(arrs,/*laya.events.Event.MOUSE_OUT*/"mouseout"); }else { arrs=TouchManager._tEleArr; arrs.length=0; var oldArr; oldArr=this.getEles(elePre,null,TouchManager._oldArr); var newArr; newArr=this.getEles(eleNew,null,TouchManager._newArr); len=oldArr.length; var tIndex=0; for (i=0;i < len;i++){ tar=oldArr[i]; tIndex=newArr.indexOf(tar); if (tIndex >=0){ newArr.splice(tIndex,newArr.length-tIndex); break ; }else { arrs.push(tar); } } if (arrs.length > 0){ this.sendEvents(arrs,/*laya.events.Event.MOUSE_OUT*/"mouseout"); } if (newArr.length > 0){ this.sendEvents(newArr,/*laya.events.Event.MOUSE_OVER*/"mouseover"); } } } /** *处理TouchMove事件 *@param ele 根节点 *@param touchID touchID * */ __proto.onMouseMove=function(ele,touchID){ if (!this.enable) return; var preO; preO=this.getTouchFromArr(touchID,this.preOvers); var arrs; var tO; if (!preO){ arrs=this.getEles(ele,null,TouchManager._tEleArr); this.sendEvents(arrs,/*laya.events.Event.MOUSE_OVER*/"mouseover"); this.preOvers.push(this.createTouchO(ele,touchID)); }else { this.checkMouseOutAndOverOfMove(ele,preO.tar); preO.tar=ele; arrs=this.getEles(ele,null,TouchManager._tEleArr); } this.sendEvents(arrs,/*laya.events.Event.MOUSE_MOVE*/"mousemove"); this._clearTempArrs(); } __proto.getLastOvers=function(){ TouchManager._tEleArr.length=0; if (this.preOvers.length > 0 && this.preOvers[0].tar){ return this.getEles(this.preOvers[0].tar,null,TouchManager._tEleArr); } TouchManager._tEleArr.push(Laya.stage); return TouchManager._tEleArr; } __proto.stageMouseOut=function(){ var lastOvers; lastOvers=this.getLastOvers(); this.preOvers.length=0; this.sendEvents(lastOvers,/*laya.events.Event.MOUSE_OUT*/"mouseout"); } /** *处理TouchEnd事件 *@param ele 根节点 *@param touchID touchID *@param isLeft 是否为左键 */ __proto.onMouseUp=function(ele,touchID,isLeft){ (isLeft===void 0)&& (isLeft=false); if (!this.enable) return; var preO; var tO; var arrs; var oldArr; var i=0,len=0; var tar; var sendArr; var onMobile=Browser.onMobile; arrs=this.getEles(ele,null,TouchManager._tEleArr); this.sendEvents(arrs,isLeft ? /*laya.events.Event.MOUSE_UP*/"mouseup" :/*laya.events.Event.RIGHT_MOUSE_UP*/"rightmouseup"); var preDowns; preDowns=isLeft ? this.preDowns :this.preRightDowns; preO=this.getTouchFromArr(touchID,preDowns); if (!preO){ }else { var isDouble=false; var now=Browser.now(); isDouble=now-this._lastClickTime < 300; this._lastClickTime=now; if (ele==preO.tar){ sendArr=arrs; }else { oldArr=this.getEles(preO.tar,null,TouchManager._oldArr); sendArr=TouchManager._newArr; sendArr.length=0; len=oldArr.length; for (i=0;i < len;i++){ tar=oldArr[i]; if (arrs.indexOf(tar)>=0){ sendArr.push(tar); } } } if (sendArr.length > 0){ this.sendEvents(sendArr,isLeft ? /*laya.events.Event.CLICK*/"click" :/*laya.events.Event.RIGHT_CLICK*/"rightclick"); } if (isLeft && isDouble){ this.sendEvents(sendArr,/*laya.events.Event.DOUBLE_CLICK*/"doubleclick"); } this.removeTouchFromArr(touchID,preDowns); preO.tar=null; Pool.recover("TouchData",preO); } preO=this.getTouchFromArr(touchID,this.preOvers); if (!preO){ }else { if (onMobile){ sendArr=this.getEles(preO.tar,null,sendArr); if (sendArr && sendArr.length > 0){ this.sendEvents(sendArr,/*laya.events.Event.MOUSE_OUT*/"mouseout"); } this.removeTouchFromArr(touchID,this.preOvers); preO.tar=null; Pool.recover("TouchData",preO); } } this._clearTempArrs(); } TouchManager._oldArr=[]; TouchManager._newArr=[]; TouchManager._tEleArr=[]; __static(TouchManager, ['I',function(){return this.I=new TouchManager();} ]); return TouchManager; })() /** *Filter 是滤镜基类。 */ //class laya.filters.Filter var Filter=(function(){ function Filter(){ /**@private */ this._action=null; } __class(Filter,'laya.filters.Filter'); var __proto=Filter.prototype; Laya.imps(__proto,{"laya.filters.IFilter":true}) /**@private */ __proto.callNative=function(sp){} /**@private 滤镜类型。*/ __getset(0,__proto,'type',function(){return-1}); /**@private 滤镜动作。*/ __getset(0,__proto,'action',function(){return this._action }); Filter.BLUR=0x10; Filter.COLOR=0x20; Filter.GLOW=0x08; Filter._filterStart=null; Filter._filterEnd=null; Filter._EndTarget=null; Filter._recycleScope=null; Filter._filter=null; Filter._useSrc=null; Filter._endSrc=null; Filter._useOut=null; Filter._endOut=null; return Filter; })() /** *@private *ColorFilterAction 是一个颜色滤镜应用类。 */ //class laya.filters.ColorFilterAction var ColorFilterAction=(function(){ function ColorFilterAction(){ this.data=null; } __class(ColorFilterAction,'laya.filters.ColorFilterAction'); var __proto=ColorFilterAction.prototype; Laya.imps(__proto,{"laya.filters.IFilterAction":true}) /** *给指定的对象应用颜色滤镜。 *@param srcCanvas 需要应用画布对象。 *@return 应用了滤镜后的画布对象。 */ __proto.apply=function(srcCanvas){ var ctx=srcCanvas.ctx.ctx; var canvas=srcCanvas.ctx.ctx.canvas; if (canvas.width==0 || canvas.height==0)return canvas; var imgdata=ctx.getImageData(0,0,canvas.width,canvas.height); var data=imgdata.data; var nData; for (var i=0,n=data.length;i < n;i+=4){ nData=this.getColor(data[i],data[i+1],data[i+2],data[i+3]); if (data[i+3]==0)continue ; data[i]=nData[0]; data[i+1]=nData[1]; data[i+2]=nData[2]; data[i+3]=nData[3]; } ctx.putImageData(imgdata,0,0); return srcCanvas; } __proto.getColor=function(red,green,blue,alpha){ var rst=[]; if (this.data._mat && this.data._alpha){ var mat=this.data._mat; var tempAlpha=this.data._alpha; rst[0]=mat[0] *red+mat[1] *green+mat[2] *blue+mat[3] *alpha+tempAlpha[0]; rst[1]=mat[4] *red+mat[5] *green+mat[6] *blue+mat[7] *alpha+tempAlpha[1]; rst[2]=mat[8] *red+mat[9] *green+mat[10] *blue+mat[11] *alpha+tempAlpha[2]; rst[3]=mat[12] *red+mat[13] *green+mat[14] *blue+mat[15] *alpha+tempAlpha[3]; } return rst; } return ColorFilterAction; })() /** *@private */ //class laya.maths.Arith var Arith=(function(){ function Arith(){} __class(Arith,'laya.maths.Arith'); Arith.formatR=function(r){ if (r > Math.PI)r-=Math.PI *2; if (r <-Math.PI)r+=Math.PI *2; return r; } Arith.isPOT=function(w,h){ return (w > 0 && (w & (w-1))===0 && h > 0 && (h & (h-1))===0); } Arith.setMatToArray=function(mat,array){ mat.a,mat.b,0,0,mat.c,mat.d,0,0,0,0,1,0,mat.tx+20,mat.ty+20,0,1 array[0]=mat.a; array[1]=mat.b; array[4]=mat.c; array[5]=mat.d; array[12]=mat.tx; array[13]=mat.ty; } return Arith; })() /** *@private *计算贝塞尔曲线的工具类。 */ //class laya.maths.Bezier var Bezier=(function(){ function Bezier(){ /**@private */ this._controlPoints=[new Point(),new Point(),new Point()]; this._calFun=this.getPoint2; } __class(Bezier,'laya.maths.Bezier'); var __proto=Bezier.prototype; /**@private */ __proto._switchPoint=function(x,y){ var tPoint=this._controlPoints.shift(); tPoint.setTo(x,y); this._controlPoints.push(tPoint); } /** *计算二次贝塞尔点。 *@param t *@param rst * */ __proto.getPoint2=function(t,rst){ var p1=this._controlPoints[0]; var p2=this._controlPoints[1]; var p3=this._controlPoints[2]; var lineX=Math.pow((1-t),2)*p1.x+2 *t *(1-t)*p2.x+Math.pow(t,2)*p3.x; var lineY=Math.pow((1-t),2)*p1.y+2 *t *(1-t)*p2.y+Math.pow(t,2)*p3.y; rst.push(lineX,lineY); } /** *计算三次贝塞尔点 *@param t *@param rst * */ __proto.getPoint3=function(t,rst){ var p1=this._controlPoints[0]; var p2=this._controlPoints[1]; var p3=this._controlPoints[2]; var p4=this._controlPoints[3]; var lineX=Math.pow((1-t),3)*p1.x+3 *p2.x *t *(1-t)*(1-t)+3 *p3.x *t *t *(1-t)+p4.x *Math.pow(t,3); var lineY=Math.pow((1-t),3)*p1.y+3 *p2.y *t *(1-t)*(1-t)+3 *p3.y *t *t *(1-t)+p4.y *Math.pow(t,3); rst.push(lineX,lineY); } /** *计算贝塞尔点序列 *@param count *@param rst * */ __proto.insertPoints=function(count,rst){ var i=NaN; count=count > 0 ? count :5; var dLen=NaN; dLen=1 / count; for (i=0;i <=1;i+=dLen){ this._calFun(i,rst); } } /** *获取贝塞尔曲线上的点。 *@param pList 控制点[x0,y0,x1,y1...] *@param inSertCount 每次曲线的插值数量 *@return * */ __proto.getBezierPoints=function(pList,inSertCount,count){ (inSertCount===void 0)&& (inSertCount=5); (count===void 0)&& (count=2); var i=0,len=0; len=pList.length; if (len < (count+1)*2)return []; var rst; rst=[]; switch (count){ case 2: this._calFun=this.getPoint2; break ; case 3: this._calFun=this.getPoint3; break ; default : return []; } while (this._controlPoints.length <=count){ this._controlPoints.push(new Point()); } for (i=0;i < count *2;i+=2){ this._switchPoint(pList[i],pList[i+1]); } for (i=count *2;i < len;i+=2){ this._switchPoint(pList[i],pList[i+1]); if ((i / 2)% count==0) this.insertPoints(inSertCount,rst); } return rst; } __static(Bezier, ['I',function(){return this.I=new Bezier();} ]); return Bezier; })() /** *@private *凸包算法。 */ //class laya.maths.GrahamScan var GrahamScan=(function(){ function GrahamScan(){} __class(GrahamScan,'laya.maths.GrahamScan'); GrahamScan.multiply=function(p1,p2,p0){ return ((p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y)); } GrahamScan.dis=function(p1,p2){ return (p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y); } GrahamScan._getPoints=function(count,tempUse,rst){ (tempUse===void 0)&& (tempUse=false); if (!GrahamScan._mPointList)GrahamScan._mPointList=[]; while (GrahamScan._mPointList.length < count)GrahamScan._mPointList.push(new Point()); if (!rst)rst=[]; rst.length=0; if (tempUse){ GrahamScan.getFrom(rst,GrahamScan._mPointList,count); }else { GrahamScan.getFromR(rst,GrahamScan._mPointList,count); } return rst; } GrahamScan.getFrom=function(rst,src,count){ var i=0; for (i=0;i < count;i++){ rst.push(src[i]); } return rst; } GrahamScan.getFromR=function(rst,src,count){ var i=0; for (i=0;i < count;i++){ rst.push(src.pop()); } return rst; } GrahamScan.pListToPointList=function(pList,tempUse){ (tempUse===void 0)&& (tempUse=false); var i=0,len=pList.length / 2,rst=GrahamScan._getPoints(len,tempUse,GrahamScan._tempPointList); for (i=0;i < len;i++){ rst[i].setTo(pList[i+i],pList[i+i+1]); } return rst; } GrahamScan.pointListToPlist=function(pointList){ var i=0,len=pointList.length,rst=GrahamScan._temPList,tPoint; rst.length=0; for (i=0;i < len;i++){ tPoint=pointList[i]; rst.push(tPoint.x,tPoint.y); } return rst; } GrahamScan.scanPList=function(pList){ return Utils.copyArray(pList,GrahamScan.pointListToPlist(GrahamScan.scan(GrahamScan.pListToPointList(pList,true)))); } GrahamScan.scan=function(PointSet){ var i=0,j=0,k=0,top=2,tmp,n=PointSet.length,ch; var _tmpDic={}; var key; ch=GrahamScan._temArr; ch.length=0; n=PointSet.length; for (i=n-1;i >=0;i--){ tmp=PointSet[i]; key=tmp.x+"_"+tmp.y; if (!_tmpDic.hasOwnProperty(key)){ _tmpDic[key]=true; ch.push(tmp); } } n=ch.length; Utils.copyArray(PointSet,ch); for (i=1;i < n;i++) if ((PointSet[i].y < PointSet[k].y)|| ((PointSet[i].y==PointSet[k].y)&& (PointSet[i].x < PointSet[k].x))) k=i; tmp=PointSet[0]; PointSet[0]=PointSet[k]; PointSet[k]=tmp; for (i=1;i < n-1;i++){ k=i; for (j=i+1;j < n;j++) if ((GrahamScan.multiply(PointSet[j],PointSet[k],PointSet[0])> 0)|| ((GrahamScan.multiply(PointSet[j],PointSet[k],PointSet[0])==0)&& (GrahamScan.dis(PointSet[0],PointSet[j])< GrahamScan.dis(PointSet[0],PointSet[k])))) k=j; tmp=PointSet[i]; PointSet[i]=PointSet[k]; PointSet[k]=tmp; } ch=GrahamScan._temArr; ch.length=0; if (PointSet.length < 3){ return Utils.copyArray(ch,PointSet); } ch.push(PointSet[0],PointSet[1],PointSet[2]); for (i=3;i < n;i++){ while (ch.length >=2 && GrahamScan.multiply(PointSet[i],ch[ch.length-1],ch[ch.length-2])>=0)ch.pop(); PointSet[i] && ch.push(PointSet[i]); } return ch; } GrahamScan._mPointList=null; GrahamScan._tempPointList=[]; GrahamScan._temPList=[]; GrahamScan._temArr=[]; return GrahamScan; })() /** *@private *MathUtil 是一个数据处理工具类。 */ //class laya.maths.MathUtil var MathUtil=(function(){ function MathUtil(){} __class(MathUtil,'laya.maths.MathUtil'); MathUtil.subtractVector3=function(l,r,o){ o[0]=l[0]-r[0]; o[1]=l[1]-r[1]; o[2]=l[2]-r[2]; } MathUtil.lerp=function(left,right,amount){ return left *(1-amount)+right *amount; } MathUtil.scaleVector3=function(f,b,e){ e[0]=f[0] *b; e[1]=f[1] *b; e[2]=f[2] *b; } MathUtil.lerpVector3=function(l,r,t,o){ var ax=l[0],ay=l[1],az=l[2]; o[0]=ax+t *(r[0]-ax); o[1]=ay+t *(r[1]-ay); o[2]=az+t *(r[2]-az); } MathUtil.lerpVector4=function(l,r,t,o){ var ax=l[0],ay=l[1],az=l[2],aw=l[3]; o[0]=ax+t *(r[0]-ax); o[1]=ay+t *(r[1]-ay); o[2]=az+t *(r[2]-az); o[3]=aw+t *(r[3]-aw); } MathUtil.slerpQuaternionArray=function(a,Offset1,b,Offset2,t,out,Offset3){ var ax=a[Offset1+0],ay=a[Offset1+1],az=a[Offset1+2],aw=a[Offset1+3],bx=b[Offset2+0],by=b[Offset2+1],bz=b[Offset2+2],bw=b[Offset2+3]; var omega,cosom,sinom,scale0,scale1; cosom=ax *bx+ay *by+az *bz+aw *bw; if (cosom < 0.0){ cosom=-cosom; bx=-bx; by=-by; bz=-bz; bw=-bw; } if ((1.0-cosom)> 0.000001){ omega=Math.acos(cosom); sinom=Math.sin(omega); scale0=Math.sin((1.0-t)*omega)/ sinom; scale1=Math.sin(t *omega)/ sinom; }else { scale0=1.0-t; scale1=t; } out[Offset3+0]=scale0 *ax+scale1 *bx; out[Offset3+1]=scale0 *ay+scale1 *by; out[Offset3+2]=scale0 *az+scale1 *bz; out[Offset3+3]=scale0 *aw+scale1 *bw; return out; } MathUtil.getRotation=function(x0,y0,x1,y1){ return Math.atan2(y1-y0,x1-x0)/ Math.PI *180; } MathUtil.sortBigFirst=function(a,b){ if (a==b) return 0; return b > a ? 1 :-1; } MathUtil.sortSmallFirst=function(a,b){ if (a==b) return 0; return b > a ?-1 :1; } MathUtil.sortNumBigFirst=function(a,b){ return parseFloat(b)-parseFloat(a); } MathUtil.sortNumSmallFirst=function(a,b){ return parseFloat(a)-parseFloat(b); } MathUtil.sortByKey=function(key,bigFirst,forceNum){ (bigFirst===void 0)&& (bigFirst=false); (forceNum===void 0)&& (forceNum=true); var _sortFun; if (bigFirst){ _sortFun=forceNum ? MathUtil.sortNumBigFirst :MathUtil.sortBigFirst; }else { _sortFun=forceNum ? MathUtil.sortNumSmallFirst :MathUtil.sortSmallFirst; } return function (a,b){ return _sortFun(a[key],b[key]); } } return MathUtil; })() /** *

    Matrix 类表示一个转换矩阵,它确定如何将点从一个坐标空间映射到另一个坐标空间。

    *

    您可以对一个显示对象执行不同的图形转换,方法是设置 Matrix 对象的属性,将该 Matrix 对象应用于 Transform 对象的 matrix 属性,然后应用该 Transform 对象作为显示对象的 transform 属性。这些转换函数包括平移(x 和 y 重新定位)、旋转、缩放和倾斜。

    */ //class laya.maths.Matrix var Matrix=(function(){ function Matrix(a,b,c,d,tx,ty){ /**缩放或旋转图像时影响像素沿 x 轴定位的值。*/ //this.a=NaN; /**旋转或倾斜图像时影响像素沿 y 轴定位的值。*/ //this.b=NaN; /**旋转或倾斜图像时影响像素沿 x 轴定位的值。*/ //this.c=NaN; /**缩放或旋转图像时影响像素沿 y 轴定位的值。*/ //this.d=NaN; /**沿 x 轴平移每个点的距离。*/ //this.tx=NaN; /**沿 y 轴平移每个点的距离。*/ //this.ty=NaN; /**@private 表示此对象是否在对象池中。*/ this.inPool=false; /**@private 是否有改变矩阵的值。*/ this.bTransform=false; (a===void 0)&& (a=1); (b===void 0)&& (b=0); (c===void 0)&& (c=0); (d===void 0)&& (d=1); (tx===void 0)&& (tx=0); (ty===void 0)&& (ty=0); this.a=a; this.b=b; this.c=c; this.d=d; this.tx=tx; this.ty=ty; this._checkTransform(); } __class(Matrix,'laya.maths.Matrix'); var __proto=Matrix.prototype; /** *将本矩阵设置为单位矩阵。 *@return 返回当前矩形。 */ __proto.identity=function(){ this.a=this.d=1; this.b=this.tx=this.ty=this.c=0; this.bTransform=false; return this; } /**@private */ __proto._checkTransform=function(){ return this.bTransform=(this.a!==1 || this.b!==0 || this.c!==0 || this.d!==1); } /** *设置沿 x 、y 轴平移每个点的距离。 *@param x 沿 x 轴平移每个点的距离。 *@param y 沿 y 轴平移每个点的距离。 *@return 返回对象本身 */ __proto.setTranslate=function(x,y){ this.tx=x; this.ty=y; return this; } /** *沿 x 和 y 轴平移矩阵,平移的变化量由 x 和 y 参数指定。 *@param x 沿 x 轴向右移动的量(以像素为单位)。 *@param y 沿 y 轴向下移动的量(以像素为单位)。 *@return 返回此矩形对象。 */ __proto.translate=function(x,y){ this.tx+=x; this.ty+=y; return this; } /** *对矩阵应用缩放转换。 *@param x 用于沿 x 轴缩放对象的乘数。 *@param y 用于沿 y 轴缩放对象的乘数。 */ __proto.scale=function(x,y){ this.a *=x; this.d *=y; this.c *=x; this.b *=y; this.tx *=x; this.ty *=y; this.bTransform=true; } /** *对 Matrix 对象应用旋转转换。 *@param angle 以弧度为单位的旋转角度。 */ __proto.rotate=function(angle){ var cos=Math.cos(angle); var sin=Math.sin(angle); var a1=this.a; var c1=this.c; var tx1=this.tx; this.a=a1 *cos-this.b *sin; this.b=a1 *sin+this.b *cos; this.c=c1 *cos-this.d *sin; this.d=c1 *sin+this.d *cos; this.tx=tx1 *cos-this.ty *sin; this.ty=tx1 *sin+this.ty *cos; this.bTransform=true; } /** *对 Matrix 对象应用倾斜转换。 *@param x 沿着 X 轴的 2D 倾斜弧度。 *@param y 沿着 Y 轴的 2D 倾斜弧度。 *@return 当前 Matrix 对象。 */ __proto.skew=function(x,y){ var tanX=Math.tan(x); var tanY=Math.tan(y); var a1=this.a; var b1=this.b; this.a+=tanY *this.c; this.b+=tanY *this.d; this.c+=tanX *a1; this.d+=tanX *b1; return this; } /** *对指定的点应用当前矩阵的逆转化并返回此点。 *@param out 待转化的点 Point 对象。 *@return 返回out */ __proto.invertTransformPoint=function(out){ var a1=this.a; var b1=this.b; var c1=this.c; var d1=this.d; var tx1=this.tx; var n=a1 *d1-b1 *c1; var a2=d1 / n; var b2=-b1 / n; var c2=-c1 / n; var d2=a1 / n; var tx2=(c1 *this.ty-d1 *tx1)/ n; var ty2=-(a1 *this.ty-b1 *tx1)/ n; return out.setTo(a2 *out.x+c2 *out.y+tx2,b2 *out.x+d2 *out.y+ty2); } /** *将 Matrix 对象表示的几何转换应用于指定点。 *@param out 用来设定输出结果的点。 *@return 返回out */ __proto.transformPoint=function(out){ return out.setTo(this.a *out.x+this.c *out.y+this.tx,this.b *out.x+this.d *out.y+this.ty); } /** *将 Matrix 对象表示的几何转换应用于指定点,忽略tx、ty。 *@param out 用来设定输出结果的点。 *@return 返回out */ __proto.transformPointN=function(out){ return out.setTo(this.a *out.x+this.c *out.y ,this.b *out.x+this.d *out.y); } /** *@private *将 Matrix 对象表示的几何转换应用于指定点。 *@param data 点集合。 *@param out 存储应用转化的点的列表。 *@return 返回out数组 */ __proto.transformPointArray=function(data,out){ var len=data.length; for (var i=0;i < len;i+=2){ var x=data[i],y=data[i+1]; out[i]=this.a *x+this.c *y+this.tx; out[i+1]=this.b *x+this.d *y+this.ty; } return out; } /** *@private *将 Matrix 对象表示的几何缩放转换应用于指定点。 *@param data 点集合。 *@param out 存储应用转化的点的列表。 *@return 返回out数组 */ __proto.transformPointArrayScale=function(data,out){ var len=data.length; for (var i=0;i < len;i+=2){ var x=data[i],y=data[i+1]; out[i]=this.a *x+this.c *y; out[i+1]=this.b *x+this.d *y; } return out; } /** *获取 X 轴缩放值。 *@return X 轴缩放值。 */ __proto.getScaleX=function(){ return this.b===0 ? this.a :Math.sqrt(this.a *this.a+this.b *this.b); } /** *获取 Y 轴缩放值。 *@return Y 轴缩放值。 */ __proto.getScaleY=function(){ return this.c===0 ? this.d :Math.sqrt(this.c *this.c+this.d *this.d); } /** *执行原始矩阵的逆转换。 *@return 当前矩阵对象。 */ __proto.invert=function(){ var a1=this.a; var b1=this.b; var c1=this.c; var d1=this.d; var tx1=this.tx; var n=a1 *d1-b1 *c1; this.a=d1 / n; this.b=-b1 / n; this.c=-c1 / n; this.d=a1 / n; this.tx=(c1 *this.ty-d1 *tx1)/ n; this.ty=-(a1 *this.ty-b1 *tx1)/ n; return this; } /** *将 Matrix 的成员设置为指定值。 *@param a 缩放或旋转图像时影响像素沿 x 轴定位的值。 *@param b 旋转或倾斜图像时影响像素沿 y 轴定位的值。 *@param c 旋转或倾斜图像时影响像素沿 x 轴定位的值。 *@param d 缩放或旋转图像时影响像素沿 y 轴定位的值。 *@param tx 沿 x 轴平移每个点的距离。 *@param ty 沿 y 轴平移每个点的距离。 *@return 当前矩阵对象。 */ __proto.setTo=function(a,b,c,d,tx,ty){ this.a=a,this.b=b,this.c=c,this.d=d,this.tx=tx,this.ty=ty; return this; } /** *将指定矩阵与当前矩阵连接,从而将这两个矩阵的几何效果有效地结合在一起。 *@param matrix 要连接到源矩阵的矩阵。 *@return 当前矩阵。 */ __proto.concat=function(matrix){ var a=this.a; var c=this.c; var tx=this.tx; this.a=a *matrix.a+this.b *matrix.c; this.b=a *matrix.b+this.b *matrix.d; this.c=c *matrix.a+this.d *matrix.c; this.d=c *matrix.b+this.d *matrix.d; this.tx=tx *matrix.a+this.ty *matrix.c+matrix.tx; this.ty=tx *matrix.b+this.ty *matrix.d+matrix.ty; return this; } /** *@private *对矩阵应用缩放转换。反向相乘 *@param x 用于沿 x 轴缩放对象的乘数。 *@param y 用于沿 y 轴缩放对象的乘数。 */ __proto.scaleEx=function(x,y){ var ba=this.a,bb=this.b,bc=this.c,bd=this.d; if (bb!==0 || bc!==0){ this.a=x *ba; this.b=x *bb; this.c=y *bc; this.d=y *bd; }else { this.a=x *ba; this.b=0 *bd; this.c=0 *ba; this.d=y *bd; } this.bTransform=true; } /** *@private *对 Matrix 对象应用旋转转换。反向相乘 *@param angle 以弧度为单位的旋转角度。 */ __proto.rotateEx=function(angle){ var cos=Math.cos(angle); var sin=Math.sin(angle); var ba=this.a,bb=this.b,bc=this.c,bd=this.d; if (bb!==0 || bc!==0){ this.a=cos *ba+sin *bc; this.b=cos *bb+sin *bd; this.c=-sin *ba+cos *bc; this.d=-sin *bb+cos *bd; }else { this.a=cos *ba; this.b=sin *bd; this.c=-sin *ba; this.d=cos *bd; } this.bTransform=true; } /** *返回此 Matrix 对象的副本。 *@return 与原始实例具有完全相同的属性的新 Matrix 实例。 */ __proto.clone=function(){ var dec=Matrix.create(); dec.a=this.a; dec.b=this.b; dec.c=this.c; dec.d=this.d; dec.tx=this.tx; dec.ty=this.ty; dec.bTransform=this.bTransform; return dec; } /** *将当前 Matrix 对象中的所有矩阵数据复制到指定的 Matrix 对象中。 *@param dec 要复制当前矩阵数据的 Matrix 对象。 *@return 已复制当前矩阵数据的 Matrix 对象。 */ __proto.copyTo=function(dec){ dec.a=this.a; dec.b=this.b; dec.c=this.c; dec.d=this.d; dec.tx=this.tx; dec.ty=this.ty; dec.bTransform=this.bTransform; return dec; } /** *返回列出该 Matrix 对象属性的文本值。 *@return 一个字符串,它包含 Matrix 对象的属性值:a、b、c、d、tx 和 ty。 */ __proto.toString=function(){ return this.a+","+this.b+","+this.c+","+this.d+","+this.tx+","+this.ty; } /** *销毁此对象。 */ __proto.destroy=function(){ if (this.inPool)return; var cache=Matrix._cache; this.inPool=true; cache._length || (cache._length=0); cache[cache._length++]=this; this.a=this.d=1; this.b=this.c=this.tx=this.ty=0; this.bTransform=false; } Matrix.mul=function(m1,m2,out){ var aa=m1.a,ab=m1.b,ac=m1.c,ad=m1.d,atx=m1.tx,aty=m1.ty; var ba=m2.a,bb=m2.b,bc=m2.c,bd=m2.d,btx=m2.tx,bty=m2.ty; if (bb!==0 || bc!==0){ out.a=aa *ba+ab *bc; out.b=aa *bb+ab *bd; out.c=ac *ba+ad *bc; out.d=ac *bb+ad *bd; out.tx=ba *atx+bc *aty+btx; out.ty=bb *atx+bd *aty+bty; }else { out.a=aa *ba; out.b=ab *bd; out.c=ac *ba; out.d=ad *bd; out.tx=ba *atx+btx; out.ty=bd *aty+bty; } return out; } Matrix.mul16=function(m1,m2,out){ var aa=m1.a,ab=m1.b,ac=m1.c,ad=m1.d,atx=m1.tx,aty=m1.ty; var ba=m2.a,bb=m2.b,bc=m2.c,bd=m2.d,btx=m2.tx,bty=m2.ty; if (bb!==0 || bc!==0){ out[0]=aa *ba+ab *bc; out[1]=aa *bb+ab *bd; out[4]=ac *ba+ad *bc; out[5]=ac *bb+ad *bd; out[12]=ba *atx+bc *aty+btx; out[13]=bb *atx+bd *aty+bty; }else { out[0]=aa *ba; out[1]=ab *bd; out[4]=ac *ba; out[5]=ad *bd; out[12]=ba *atx+btx; out[13]=bd *aty+bty; } return out; } Matrix.mulPre=function(m1,ba,bb,bc,bd,btx,bty,out){ var aa=m1.a,ab=m1.b,ac=m1.c,ad=m1.d,atx=m1.tx,aty=m1.ty; if (bb!==0 || bc!==0){ out.a=aa *ba+ab *bc; out.b=aa *bb+ab *bd; out.c=ac *ba+ad *bc; out.d=ac *bb+ad *bd; out.tx=ba *atx+bc *aty+btx; out.ty=bb *atx+bd *aty+bty; }else { out.a=aa *ba; out.b=ab *bd; out.c=ac *ba; out.d=ad *bd; out.tx=ba *atx+btx; out.ty=bd *aty+bty; } return out; } Matrix.mulPos=function(m1,aa,ab,ac,ad,atx,aty,out){ var ba=m1.a,bb=m1.b,bc=m1.c,bd=m1.d,btx=m1.tx,bty=m1.ty; if (bb!==0 || bc!==0){ out.a=aa *ba+ab *bc; out.b=aa *bb+ab *bd; out.c=ac *ba+ad *bc; out.d=ac *bb+ad *bd; out.tx=ba *atx+bc *aty+btx; out.ty=bb *atx+bd *aty+bty; }else { out.a=aa *ba; out.b=ab *bd; out.c=ac *ba; out.d=ad *bd; out.tx=ba *atx+btx; out.ty=bd *aty+bty; } return out; } Matrix.preMul=function(parent,self,out){ var pa=parent.a,pb=parent.b,pc=parent.c,pd=parent.d; var na=self.a,nb=self.b,nc=self.c,nd=self.d,ntx=self.tx,nty=self.ty; out.a=na *pa; out.b=out.c=0; out.d=nd *pd; out.tx=ntx *pa+parent.tx; out.ty=nty *pd+parent.ty; if (nb!==0 || nc!==0 || pb!==0 || pc!==0){ out.a+=nb *pc; out.d+=nc *pb; out.b+=na *pb+nb *pd; out.c+=nc *pa+nd *pc; out.tx+=nty *pc; out.ty+=ntx *pb; } return out; } Matrix.preMulXY=function(parent,x,y,out){ var pa=parent.a,pb=parent.b,pc=parent.c,pd=parent.d; out.a=pa; out.b=pb; out.c=pc; out.d=pd; out.tx=x *pa+parent.tx+y *pc; out.ty=y *pd+parent.ty+x *pb; return out; } Matrix.create=function(){ var cache=Matrix._cache; var mat=!cache._length ? (new Matrix()):cache[--cache._length]; mat.inPool=false; return mat; } Matrix.EMPTY=new Matrix(); Matrix.TEMP=new Matrix(); Matrix._cache=[]; return Matrix; })() /** *Point 对象表示二维坐标系统中的某个位置,其中 x 表示水平轴,y 表示垂直轴。 */ //class laya.maths.Point var Point=(function(){ function Point(x,y){ /**该点的水平坐标。*/ //this.x=NaN; /**该点的垂直坐标。*/ //this.y=NaN; (x===void 0)&& (x=0); (y===void 0)&& (y=0); this.x=x; this.y=y; } __class(Point,'laya.maths.Point'); var __proto=Point.prototype; /** *将 Point 的成员设置为指定值。 *@param x 水平坐标。 *@param y 垂直坐标。 *@return 当前 Point 对象。 */ __proto.setTo=function(x,y){ this.x=x; this.y=y; return this; } /** *计算当前点和目标点(x,y)的距离。 *@param x 水平坐标。 *@param y 垂直坐标。 *@return 返回当前点和目标点之间的距离。 */ __proto.distance=function(x,y){ return Math.sqrt((this.x-x)*(this.x-x)+(this.y-y)*(this.y-y)); } /**返回包含 x 和 y 坐标的值的字符串。*/ __proto.toString=function(){ return this.x+","+this.y; } /** *标准化向量。 */ __proto.normalize=function(){ var d=Math.sqrt(this.x *this.x+this.y *this.y); if (d > 0){ var id=1.0 / d; this.x *=id; this.y *=id; } } Point.TEMP=new Point(); Point.EMPTY=new Point(); return Point; })() /** *

    Rectangle 对象是按其位置(由它左上角的点 (x,y)确定)以及宽度和高度定义的区域。

    *

    Rectangle 类的 x、y、width 和 height 属性相互独立;更改一个属性的值不会影响其他属性。

    */ //class laya.maths.Rectangle var Rectangle=(function(){ function Rectangle(x,y,width,height){ /**矩形左上角的 X 轴坐标。*/ //this.x=NaN; /**矩形左上角的 Y 轴坐标。*/ //this.y=NaN; /**矩形的宽度。*/ //this.width=NaN; /**矩形的高度。*/ //this.height=NaN; (x===void 0)&& (x=0); (y===void 0)&& (y=0); (width===void 0)&& (width=0); (height===void 0)&& (height=0); this.x=x; this.y=y; this.width=width; this.height=height; } __class(Rectangle,'laya.maths.Rectangle'); var __proto=Rectangle.prototype; /** *将 Rectangle 的属性设置为指定值。 *@param x x 矩形左上角的 X 轴坐标。 *@param y x 矩形左上角的 Y 轴坐标。 *@param width 矩形的宽度。 *@param height 矩形的高。 *@return 返回属性值修改后的矩形对象本身。 */ __proto.setTo=function(x,y,width,height){ this.x=x; this.y=y; this.width=width; this.height=height; return this; } /** *复制 source 对象的属性值到此矩形对象中。 *@param sourceRect 源 Rectangle 对象。 *@return 返回属性值修改后的矩形对象本身。 */ __proto.copyFrom=function(source){ this.x=source.x; this.y=source.y; this.width=source.width; this.height=source.height; return this; } /** *确定由此 Rectangle 对象定义的矩形区域内是否包含指定的点。 *@param x 点的 X 轴坐标值(水平位置)。 *@param y 点的 Y 轴坐标值(垂直位置)。 *@return 如果 Rectangle 对象包含指定的点,则值为 true;否则为 false。 */ __proto.contains=function(x,y){ if (this.width <=0 || this.height <=0)return false; if (x >=this.x && x < this.right){ if (y >=this.y && y < this.bottom){ return true; } } return false; } /** *确定在 rect 参数中指定的对象是否与此 Rectangle 对象相交。此方法检查指定的 Rectangle 对象的 x、y、width 和 height 属性,以查看它是否与此 Rectangle 对象相交。 *@param rect Rectangle 对象。 *@return 如果传入的矩形对象与此对象相交,则返回 true 值,否则返回 false。 */ __proto.intersects=function(rect){ return !(rect.x > (this.x+this.width)|| (rect.x+rect.width)< this.x || rect.y > (this.y+this.height)|| (rect.y+rect.height)< this.y); } /** *如果在 rect 参数中指定的 Rectangle 对象与此 Rectangle 对象相交,则返回交集区域作为 Rectangle 对象。如果矩形不相交,则此方法返回null。 *@param rect 待比较的矩形区域。 *@param out (可选)待输出的矩形区域。如果为空则创建一个新的。建议:尽量复用对象,减少对象创建消耗。 *@return 返回相交的矩形区域对象。 */ __proto.intersection=function(rect,out){ if (!this.intersects(rect))return null; out || (out=new Rectangle()); out.x=Math.max(this.x,rect.x); out.y=Math.max(this.y,rect.y); out.width=Math.min(this.right,rect.right)-out.x; out.height=Math.min(this.bottom,rect.bottom)-out.y; return out; } /** *

    矩形联合,通过填充两个矩形之间的水平和垂直空间,将这两个矩形组合在一起以创建一个新的 Rectangle 对象。

    *

    注意:union()方法忽略高度或宽度值为 0 的矩形,如:var rect2:Rectangle=new Rectangle(300,300,50,0);

    *@param 要添加到此 Rectangle 对象的 Rectangle 对象。 *@param out 用于存储输出结果的矩形对象。如果为空,则创建一个新的。建议:尽量复用对象,减少对象创建消耗。Rectangle.TEMP对象用于对象复用。 *@return 充当两个矩形的联合的新 Rectangle 对象。 */ __proto.union=function(source,out){ out || (out=new Rectangle()); this.clone(out); if (source.width <=0 || source.height <=0)return out; out.addPoint(source.x,source.y); out.addPoint(source.right,source.bottom); return this; } /** *返回一个 Rectangle 对象,其 x、y、width 和 height 属性的值与当前 Rectangle 对象的对应值相同。 *@param out (可选)用于存储结果的矩形对象。如果为空,则创建一个新的。建议:尽量复用对象,减少对象创建消耗。。Rectangle.TEMP对象用于对象复用。 *@return Rectangle 对象,其 x、y、width 和 height 属性的值与当前 Rectangle 对象的对应值相同。 */ __proto.clone=function(out){ out || (out=new Rectangle()); out.x=this.x; out.y=this.y; out.width=this.width; out.height=this.height; return out; } /** *当前 Rectangle 对象的水平位置 x 和垂直位置 y 以及高度 width 和宽度 height 以逗号连接成的字符串。 */ __proto.toString=function(){ return this.x+","+this.y+","+this.width+","+this.height; } /** *检测传入的 Rectangle 对象的属性是否与当前 Rectangle 对象的属性 x、y、width、height 属性值都相等。 *@param rect 待比较的 Rectangle 对象。 *@return 如果判断的属性都相等,则返回 true ,否则返回 false。 */ __proto.equals=function(rect){ if (!rect || rect.x!==this.x || rect.y!==this.y || rect.width!==this.width || rect.height!==this.height)return false; return true; } /** *

    为当前矩形对象加一个点,以使当前矩形扩展为包含当前矩形和此点的最小矩形。

    *

    此方法会修改本对象。

    *@param x 点的 X 坐标。 *@param y 点的 Y 坐标。 *@return 返回此 Rectangle 对象。 */ __proto.addPoint=function(x,y){ this.x > x && (this.width+=this.x-x,this.x=x); this.y > y && (this.height+=this.y-y,this.y=y); if (this.width < x-this.x)this.width=x-this.x; if (this.height < y-this.y)this.height=y-this.y; return this; } /** *@private *返回代表当前矩形的顶点数据。 *@return 顶点数据。 */ __proto._getBoundPoints=function(){ var rst=Rectangle._temB; rst.length=0; if (this.width==0 || this.height==0)return rst; rst.push(this.x,this.y,this.x+this.width,this.y,this.x,this.y+this.height,this.x+this.width,this.y+this.height); return rst; } /** *确定此 Rectangle 对象是否为空。 *@return 如果 Rectangle 对象的宽度或高度小于等于 0,则返回 true 值,否则返回 false。 */ __proto.isEmpty=function(){ if (this.width <=0 || this.height <=0)return true; return false; } /**此矩形右侧的 X 轴坐标。 x 和 width 属性的和。*/ __getset(0,__proto,'right',function(){ return this.x+this.width; }); /**此矩形底端的 Y 轴坐标。y 和 height 属性的和。*/ __getset(0,__proto,'bottom',function(){ return this.y+this.height; }); Rectangle._getBoundPointS=function(x,y,width,height){ var rst=Rectangle._temA; rst.length=0; if (width==0 || height==0)return rst; rst.push(x,y,x+width,y,x,y+height,x+width,y+height); return rst; } Rectangle._getWrapRec=function(pointList,rst){ if (!pointList || pointList.length < 1)return rst ? rst.setTo(0,0,0,0):Rectangle.TEMP.setTo(0,0,0,0); rst=rst ? rst :new Rectangle(); var i,len=pointList.length,minX,maxX,minY,maxY,tPoint=Point.TEMP; minX=minY=99999; maxX=maxY=-minX; for (i=0;i < len;i+=2){ tPoint.x=pointList[i]; tPoint.y=pointList[i+1]; minX=minX < tPoint.x ? minX :tPoint.x; minY=minY < tPoint.y ? minY :tPoint.y; maxX=maxX > tPoint.x ? maxX :tPoint.x; maxY=maxY > tPoint.y ? maxY :tPoint.y; } return rst.setTo(minX,minY,maxX-minX,maxY-minY); } Rectangle.EMPTY=new Rectangle(); Rectangle.TEMP=new Rectangle(); Rectangle._temB=[]; Rectangle._temA=[]; return Rectangle; })() /** *SoundManager 是一个声音管理类。提供了对背景音乐、音效的播放控制方法。 *引擎默认有两套声音方案:WebAudio和H5Audio *播放音效,优先使用WebAudio播放声音,如果WebAudio不可用,则用H5Audio播放,H5Audio在部分机器上有兼容问题(比如不能混音,播放有延迟等)。 *播放背景音乐,则使用H5Audio播放(使用WebAudio会增加特别大的内存,并且要等加载完毕后才能播放,有延迟) *建议背景音乐用mp3类型,音效用wav或者mp3类型(如果打包为app,音效只能用wav格式)。 *详细教程及声音格式请参考:http://ldc.layabox.com/doc/?nav=ch-as-1-7-0 */ //class laya.media.SoundManager var SoundManager=(function(){ function SoundManager(){} __class(SoundManager,'laya.media.SoundManager'); __getset(1,SoundManager,'useAudioMusic',function(){ return SoundManager._useAudioMusic; },function(value){ SoundManager._useAudioMusic=value; if (value){ SoundManager._musicClass=AudioSound; }else{ SoundManager._musicClass=null; } }); /** *失去焦点后是否自动停止背景音乐。 *@param v Boolean 失去焦点后是否自动停止背景音乐。 * */ /** *失去焦点后是否自动停止背景音乐。 */ __getset(1,SoundManager,'autoStopMusic',function(){ return SoundManager._autoStopMusic; },function(v){ Laya.stage.off(/*laya.events.Event.BLUR*/"blur",null,SoundManager._stageOnBlur); Laya.stage.off(/*laya.events.Event.FOCUS*/"focus",null,SoundManager._stageOnFocus); Laya.stage.off(/*laya.events.Event.VISIBILITY_CHANGE*/"visibilitychange",null,SoundManager._visibilityChange); SoundManager._autoStopMusic=v; if (v){ Laya.stage.on(/*laya.events.Event.BLUR*/"blur",null,SoundManager._stageOnBlur); Laya.stage.on(/*laya.events.Event.FOCUS*/"focus",null,SoundManager._stageOnFocus); Laya.stage.on(/*laya.events.Event.VISIBILITY_CHANGE*/"visibilitychange",null,SoundManager._visibilityChange); } }); /** *背景音乐和所有音效是否静音。 */ __getset(1,SoundManager,'muted',function(){ return SoundManager._muted; },function(value){ if (value==SoundManager._muted)return; if (value){ SoundManager.stopAllSound(); } SoundManager.musicMuted=value; SoundManager._muted=value; }); /** *背景音乐(不包括音效)是否静音。 */ __getset(1,SoundManager,'musicMuted',function(){ return SoundManager._musicMuted; },function(value){ if (value==SoundManager._musicMuted)return; if (value){ if (SoundManager._tMusic){ if (SoundManager._musicChannel&&!SoundManager._musicChannel.isStopped){ if (Render.isConchApp){ /*__JS__ */if (SoundManager._musicChannel._audio)SoundManager._musicChannel._audio.muted=true;; } else { SoundManager._musicChannel.pause(); } }else{ SoundManager._musicChannel=null; } }else{ SoundManager._musicChannel=null; } SoundManager._musicMuted=value; }else { SoundManager._musicMuted=value; if (SoundManager._tMusic){ if (SoundManager._musicChannel){ if (Render.isConchApp){ /*__JS__ */if (SoundManager._musicChannel._audio)SoundManager._musicChannel._audio.muted=false;; } else { SoundManager._musicChannel.resume(); } } } } }); /** *所有音效(不包括背景音乐)是否静音。 */ __getset(1,SoundManager,'soundMuted',function(){ return SoundManager._soundMuted; },function(value){ SoundManager._soundMuted=value; }); SoundManager.addChannel=function(channel){ if (SoundManager._channels.indexOf(channel)>=0)return; SoundManager._channels.push(channel); } SoundManager.removeChannel=function(channel){ var i=0; for (i=SoundManager._channels.length-1;i >=0;i--){ if (SoundManager._channels[i]==channel){ SoundManager._channels.splice(i,1); } } } SoundManager.disposeSoundIfNotUsed=function(url){ var i=0; for (i=SoundManager._channels.length-1;i >=0;i--){ if (SoundManager._channels[i].url==url){ return; } } SoundManager.destroySound(url); } SoundManager._visibilityChange=function(){ if (Laya.stage.isVisibility){ SoundManager._stageOnFocus(); }else { SoundManager._stageOnBlur(); } } SoundManager._stageOnBlur=function(){ SoundManager._isActive=false; if (SoundManager._musicChannel){ if (!SoundManager._musicChannel.isStopped){ SoundManager._blurPaused=true; SoundManager._musicChannel.pause(); } } SoundManager.stopAllSound(); Laya.stage.once(/*laya.events.Event.MOUSE_DOWN*/"mousedown",null,SoundManager._stageOnFocus); } SoundManager._recoverWebAudio=function(){ if(WebAudioSound.ctx&&WebAudioSound.ctx.state!="running"&&WebAudioSound.ctx.resume) WebAudioSound.ctx.resume(); } SoundManager._stageOnFocus=function(){ SoundManager._isActive=true; SoundManager._recoverWebAudio(); Laya.stage.off(/*laya.events.Event.MOUSE_DOWN*/"mousedown",null,SoundManager._stageOnFocus); if (SoundManager._blurPaused){ if (SoundManager._musicChannel && SoundManager._musicChannel.isStopped){ SoundManager._blurPaused=false; SoundManager._musicChannel.resume(); } } } SoundManager.playSound=function(url,loops,complete,soundClass,startTime){ (loops===void 0)&& (loops=1); (startTime===void 0)&& (startTime=0); if (!SoundManager._isActive || !url)return null; if (SoundManager._muted)return null; SoundManager._recoverWebAudio(); url=URL.formatURL(url); if (url==SoundManager._tMusic){ if (SoundManager._musicMuted)return null; }else { if (Render.isConchApp){ var ext=Utils.getFileExtension(url); if (ext !="wav" && ext !="ogg"){ alert("The sound only supports wav or ogg format,for optimal performance reason,please refer to the official website document."); return null; } } if (SoundManager._soundMuted)return null; }; var tSound; if (!Browser.onMiniGame && !Browser.onAlipayMiniGame && !Browser.onBDMiniGame && !Browser.onVVMiniGame && !Browser.onKGMiniGame && !Browser.onQGMiniGame && !Browser.onTTMiniGame && !Browser.onHWMiniGame && !Browser.onTBMiniGame){ tSound=Laya.loader.getRes(url); } if (!soundClass)soundClass=SoundManager._soundClass; if (!tSound){ tSound=new soundClass(); tSound.load(url); if (!Browser.onMiniGame && !Browser.onAlipayMiniGame && !Browser.onBDMiniGame && !Browser.onVVMiniGame && !Browser.onKGMiniGame && !Browser.onQGMiniGame && !Browser.onTTMiniGame && !Browser.onHWMiniGame && !Browser.onTBMiniGame){ Loader.cacheRes(url,tSound); } }; var channel; channel=tSound.play(startTime,loops); if (!channel)return null; channel.url=url; channel.volume=(url==SoundManager._tMusic)? SoundManager.musicVolume :SoundManager.soundVolume; channel.completeHandler=complete; return channel; } SoundManager.destroySound=function(url){ var tSound=Laya.loader.getRes(url); if (tSound){ Loader.clearRes(url); tSound.dispose(); } } SoundManager.playMusic=function(url,loops,complete,startTime){ (loops===void 0)&& (loops=0); (startTime===void 0)&& (startTime=0); url=URL.formatURL(url); SoundManager._tMusic=url; if (SoundManager._musicChannel)SoundManager._musicChannel.stop(); return SoundManager._musicChannel=SoundManager.playSound(url,loops,complete,SoundManager._musicClass,startTime); } SoundManager.stopSound=function(url){ url=URL.formatURL(url); var i=0; var channel; for (i=SoundManager._channels.length-1;i >=0;i--){ channel=SoundManager._channels[i]; if (channel.url==url){ channel.stop(); } } } SoundManager.stopAll=function(){ SoundManager._tMusic=null; var i=0; var channel; for (i=SoundManager._channels.length-1;i >=0;i--){ channel=SoundManager._channels[i]; channel.stop(); } } SoundManager.stopAllSound=function(){ var i=0; var channel; for (i=SoundManager._channels.length-1;i >=0;i--){ channel=SoundManager._channels[i]; if (channel.url !=SoundManager._tMusic){ channel.stop(); } } } SoundManager.stopMusic=function(){ if (SoundManager._musicChannel)SoundManager._musicChannel.stop(); SoundManager._tMusic=null; } SoundManager.setSoundVolume=function(volume,url){ if (url){ url=URL.formatURL(url); SoundManager._setVolume(url,volume); }else { SoundManager.soundVolume=volume; var i=0; var channel; for (i=SoundManager._channels.length-1;i >=0;i--){ channel=SoundManager._channels[i]; if (channel.url !=SoundManager._tMusic){ channel.volume=volume; } } } } SoundManager.setMusicVolume=function(volume){ SoundManager.musicVolume=volume; SoundManager._setVolume(SoundManager._tMusic,volume); } SoundManager._setVolume=function(url,volume){ url=URL.formatURL(url); var i=0; var channel; for (i=SoundManager._channels.length-1;i >=0;i--){ channel=SoundManager._channels[i]; if (channel.url==url){ channel.volume=volume; } } } SoundManager.musicVolume=1; SoundManager.soundVolume=1; SoundManager.playbackRate=1; SoundManager._useAudioMusic=true; SoundManager._muted=false; SoundManager._soundMuted=false; SoundManager._musicMuted=false; SoundManager._tMusic=null; SoundManager._musicChannel=null; SoundManager._channels=[]; SoundManager._autoStopMusic=false; SoundManager._blurPaused=false; SoundManager._isActive=true; SoundManager._soundClass=null; SoundManager._musicClass=null; SoundManager.autoReleaseSound=true; return SoundManager; })() /** *

    LocalStorage 类用于没有时间限制的数据存储。

    */ //class laya.net.LocalStorage var LocalStorage=(function(){ var Storage; function LocalStorage(){} __class(LocalStorage,'laya.net.LocalStorage'); LocalStorage.__init__=function(){ if (!LocalStorage._baseClass){ LocalStorage._baseClass=Storage; Storage.init(); } LocalStorage.items=LocalStorage._baseClass.items; LocalStorage.support=LocalStorage._baseClass.support; } LocalStorage.setItem=function(key,value){ LocalStorage._baseClass.setItem(key,value); } LocalStorage.getItem=function(key){ return LocalStorage._baseClass.getItem(key); } LocalStorage.setJSON=function(key,value){ LocalStorage._baseClass.setJSON(key,value); } LocalStorage.getJSON=function(key){ return LocalStorage._baseClass.getJSON(key); } LocalStorage.removeItem=function(key){ LocalStorage._baseClass.removeItem(key); } LocalStorage.clear=function(){ LocalStorage._baseClass.clear(); } LocalStorage._baseClass=null; LocalStorage.items=null; LocalStorage.support=false; LocalStorage.__init$=function(){ //class Storage Storage=(function(){ function Storage(){} __class(Storage,''); Storage.init=function(){ /*__JS__ */try{Storage.support=true;Storage.items=window.localStorage;Storage.setItem('laya','1');Storage.removeItem('laya');}catch(e){Storage.support=false;}if(!Storage.support)console.log('LocalStorage is not supprot or browser is private mode.'); } Storage.setItem=function(key,value){ try { Storage.support && Storage.items.setItem(key,value); }catch (e){ console.warn("set localStorage failed",e); } } Storage.getItem=function(key){ return Storage.support ? Storage.items.getItem(key):null; } Storage.setJSON=function(key,value){ try { Storage.support && Storage.items.setItem(key,JSON.stringify(value)); }catch (e){ console.warn("set localStorage failed",e); } } Storage.getJSON=function(key){ return JSON.parse(Storage.support ? Storage.items.getItem(key):null); } Storage.removeItem=function(key){ Storage.support && Storage.items.removeItem(key); } Storage.clear=function(){ Storage.support && Storage.items.clear(); } Storage.items=null; Storage.support=false; return Storage; })() } return LocalStorage; })() /** *

    资源版本的生成由layacmd或IDE完成,使用 ResourceVersion 简化使用过程。

    *

    调用 enable 启用资源版本管理。

    */ //class laya.net.ResourceVersion var ResourceVersion=(function(){ function ResourceVersion(){} __class(ResourceVersion,'laya.net.ResourceVersion'); ResourceVersion.enable=function(manifestFile,callback,type){ (type===void 0)&& (type=2); laya.net.ResourceVersion.type=type; Laya.loader.load(manifestFile,Handler.create(null,ResourceVersion.onManifestLoaded,[callback]),null,/*laya.net.Loader.JSON*/"json"); } ResourceVersion.onManifestLoaded=function(callback,data){ URL.customFormat=ResourceVersion.addVersionPrefix; ResourceVersion.manifest=data; callback.run(); if (!data){ console.warn("资源版本清单文件不存在,不使用资源版本管理。忽略ERR_FILE_NOT_FOUND错误。"); } } ResourceVersion.addVersionPrefix=function(originURL){ if (ResourceVersion.manifest && ResourceVersion.manifest[originURL]){ if (ResourceVersion.type==2)return ResourceVersion.manifest[originURL]; return ResourceVersion.manifest[originURL]+"/"+originURL; } return originURL; } ResourceVersion.FOLDER_VERSION=1; ResourceVersion.FILENAME_VERSION=2; ResourceVersion.manifest=null; ResourceVersion.type=1; return ResourceVersion; })() /** *@private */ //class laya.net.TTFLoader var TTFLoader=(function(){ function TTFLoader(){ this.fontName=null; this.complete=null; this.err=null; this._fontTxt=null; this._url=null; this._div=null; this._txtWidth=NaN; this._http=null; } __class(TTFLoader,'laya.net.TTFLoader'); var __proto=TTFLoader.prototype; __proto.load=function(fontPath){ this._url=fontPath; var tArr=fontPath.split(".ttf")[0].split("/"); this.fontName=tArr[tArr.length-1]; if (Browser.window.conch){ this._loadConch(); }else if (Browser.window.FontFace){ this._loadWithFontFace() } else { this._loadWithCSS(); } } __proto._loadConch=function(){ this._http=new HttpRequest(); this._http.on(/*laya.events.Event.ERROR*/"error",this,this._onErr); this._http.on(/*laya.events.Event.COMPLETE*/"complete",this,this._onHttpLoaded); this._http.send(this._url,null,"get",/*laya.net.Loader.BUFFER*/"arraybuffer"); } __proto._onHttpLoaded=function(data){ Browser.window.conch.setFontFaceFromBuffer(this.fontName,data); this._clearHttp(); this._complete(); } __proto._clearHttp=function(){ if (this._http){ this._http.off(/*laya.events.Event.ERROR*/"error",this,this._onErr); this._http.off(/*laya.events.Event.COMPLETE*/"complete",this,this._onHttpLoaded); this._http=null; } } __proto._onErr=function(){ this._clearHttp(); if (this.err){ this.err.runWith("fail:"+this._url); this.err=null; } } __proto._complete=function(){ Laya.timer.clear(this,this._complete); Laya.timer.clear(this,this._checkComplete); if (this._div && this._div.parentNode){ this._div.parentNode.removeChild(this._div); this._div=null; } if (this.complete){ this.complete.runWith(this); this.complete=null; } } __proto._checkComplete=function(){ if (RunDriver.measureText("LayaTTFFont",this._fontTxt).width !=this._txtWidth){ this._complete(); } } __proto._loadWithFontFace=function(){ var fontFace=new Browser.window.FontFace(this.fontName,"url('"+this._url+"')"); Browser.window.document.fonts.add(fontFace); var self=this; fontFace.loaded.then((function(){ self._complete() })); fontFace.load(); } __proto._createDiv=function(){ this._div=Browser.createElement("div"); this._div.innerHTML="laya"; var _style=this._div.style; _style.fontFamily=this.fontName; _style.position="absolute"; _style.left="-100px"; _style.top="-100px"; Browser.document.body.appendChild(this._div); } __proto._loadWithCSS=function(){ var _$this=this; var fontStyle=Browser.createElement("style"); fontStyle.type="text/css"; Browser.document.body.appendChild(fontStyle); fontStyle.textContent="@font-face { font-family:'"+this.fontName+"'; src:url('"+this._url+"');}"; this._fontTxt="40px "+this.fontName; this._txtWidth=RunDriver.measureText("LayaTTFFont",this._fontTxt).width; var self=this; fontStyle.onload=function (){ Laya.timer.once(10000,self,_$this._complete); }; Laya.timer.loop(20,this,this._checkComplete); this._createDiv(); } TTFLoader._testString="LayaTTFFont"; return TTFLoader; })() /** *

    URL 类用于定义地址信息。

    */ //class laya.net.URL var URL=(function(){ function URL(url){ /**@private */ this._url=null; /**@private */ this._path=null; this._url=URL.formatURL(url); this._path=URL.getPath(url); } __class(URL,'laya.net.URL'); var __proto=URL.prototype; /**地址的路径。*/ __getset(0,__proto,'path',function(){ return this._path; }); /**格式化后的地址。*/ __getset(0,__proto,'url',function(){ return this._url; }); URL.formatURL=function(url,base){ if (!url)return "null path"; if (url.indexOf(":")> 0)return url; if (URL.customFormat !=null)url=URL.customFormat(url,base); var char1=url.charAt(0); if (char1==="."){ return URL.formatRelativePath((base || URL.basePath)+url); }else if (char1==='~'){ return URL.rootPath+url.substring(1); }else if (char1==="d"){ if (url.indexOf("data:image")===0)return url; }else if (char1==="/"){ return url; } return (base || URL.basePath)+url; } URL.formatRelativePath=function(value){ var parts=value.split("/"); for (var i=0,len=parts.length;i < len;i++){ if (parts[i]=='..'){ parts.splice(i-1,2); i-=2; } } return parts.join('/'); } URL.isAbsolute=function(url){ return url.indexOf(":")> 0 || url.charAt(0)=='/'; } URL.getPath=function(url){ var ofs=url.lastIndexOf('/'); return ofs > 0 ? url.substr(0,ofs+1):""; } URL.getFileName=function(url){ var ofs=url.lastIndexOf('/'); return ofs > 0 ? url.substr(ofs+1):url; } URL.version={}; URL.basePath=""; URL.rootPath=""; URL.customFormat=function(url){ var newUrl=URL.version[url]; if (!Render.isConchApp && newUrl)url+="?v="+newUrl; return url; } return URL; })() /** *@private *Render 是渲染管理类。它是一个单例,可以使用 Laya.render 访问。 */ //class laya.renders.Render var Render=(function(){ function Render(width,height){ /**@private */ this._timeId=0; var style=Render._mainCanvas.source.style; style.position='absolute'; style.top=style.left="0px"; style.background="#000000"; Render._mainCanvas.source.id="layaCanvas"; var isWebGl=laya.renders.Render.isWebGL; Render._mainCanvas.source.width=width; Render._mainCanvas.source.height=height; isWebGl && Render.WebGL.init(Render._mainCanvas,width,height); if(!Browser.onKGMiniGame) Browser.container.appendChild(Render._mainCanvas.source); Render._context=new RenderContext(width,height,isWebGl ? null :Render._mainCanvas); Render._context.ctx.setIsMainContext(); Browser.window.requestAnimationFrame(loop); function loop (stamp){ Laya.stage._loop(); Browser.window.requestAnimationFrame(loop); } Laya.stage.on("visibilitychange",this,this._onVisibilitychange); } __class(Render,'laya.renders.Render'); var __proto=Render.prototype; /**@private */ __proto._onVisibilitychange=function(){ if (!Laya.stage.isVisibility){ this._timeId=Browser.window.setInterval(this._enterFrame,1000); }else if (this._timeId !=0){ Browser.window.clearInterval(this._timeId); } } /**@private */ __proto._enterFrame=function(e){ Laya.stage._loop(); } /**目前使用的渲染器。*/ __getset(1,Render,'context',function(){ return Render._context; }); /**渲染使用的原生画布引用。 */ __getset(1,Render,'canvas',function(){ return Render._mainCanvas.source; }); Render._context=null; Render._mainCanvas=null; Render.WebGL=null; Render.isConchNode=false; Render.isConchApp=false; Render.isConchWebGL=false; Render.isWebGL=false; Render.is3DMode=false; Render.optimizeTextureMemory=function(url,texture){ return true; } Render.__init$=function(){ /*__JS__ */window.ConchRenderType=window.ConchRenderType||1; /*__JS__ */window.ConchRenderType|=(!window.conch?0:0x04);;{ Render.isConchNode=/*__JS__ */(window.ConchRenderType & 5)==5; Render.isConchApp=/*__JS__ */(window.ConchRenderType & 0x04)==0x04; Render.isConchWebGL=/*__JS__ */window.ConchRenderType==6; };; } return Render; })() /** *@private *渲染环境 */ //class laya.renders.RenderContext var RenderContext=(function(){ function RenderContext(width,height,canvas){ /**全局x坐标 */ this.x=0; /**全局y坐标 */ this.y=0; /**当前使用的画布 */ //this.canvas=null; /**当前使用的画布上下文 */ //this.ctx=null; this._drawTexture=function(x,y,args){ if (args[0].loaded)this.ctx.drawTexture(args[0],args[1],args[2],args[3],args[4],x,y); } this._fillTexture=function(x,y,args){ if (args[0].loaded)this.ctx.fillTexture(args[0],args[1]+x,args[2]+y,args[3],args[4],args[5],args[6],args[7]); } this._drawTextureWithTransform=function(x,y,args){ if (args[0].loaded)this.ctx.drawTextureWithTransform(args[0],args[1],args[2],args[3],args[4],args[5],x,y,args[6]); } this._fillQuadrangle=function(x,y,args){ this.ctx.fillQuadrangle(args[0],args[1],args[2],args[3],args[4]); } this._drawRect=function(x,y,args){ var ctx=this.ctx; if (args[4] !=null){ ctx.fillStyle=args[4]; ctx.fillRect(x+args[0],y+args[1],args[2],args[3],null); } if (args[5] !=null){ ctx.strokeStyle=args[5]; ctx.lineWidth=args[6]; ctx.strokeRect(x+args[0],y+args[1],args[2],args[3],args[6]); } } //矢量方法 this._drawPie=function(x,y,args){ var ctx=this.ctx; Render.isWebGL && ctx.setPathId(args[8]); ctx.beginPath(); if (Render.isWebGL){ ctx.movePath(args[0]+x,args[1]+y); ctx.moveTo(0,0); }else { ctx.moveTo(x+args[0],y+args[1]); } ctx.arc(x+args[0],y+args[1],args[2],args[3],args[4]); ctx.closePath(); this._fillAndStroke(args[5],args[6],args[7],true); } this._clipRect=function(x,y,args){ this.ctx.clipRect(x+args[0],y+args[1],args[2],args[3]); } this._fillRect=function(x,y,args){ this.ctx.fillRect(x+args[0],y+args[1],args[2],args[3],args[4]); } this._drawCircle=function(x,y,args){ var ctx=this.ctx; Render.isWebGL && ctx.setPathId(args[6]); Stat.drawCall++; ctx.beginPath(); Render.isWebGL && ctx.movePath(args[0]+x,args[1]+y); ctx.arc(args[0]+x,args[1]+y,args[2],0,RenderContext.PI2); ctx.closePath(); this._fillAndStroke(args[3],args[4],args[5],true); } this._fillCircle=function(x,y,args){ Stat.drawCall++; var ctx=this.ctx; ctx.beginPath(); ctx.fillStyle=args[3]; ctx.arc(args[0]+x,args[1]+y,args[2],0,RenderContext.PI2); ctx.fill(); } this._setShader=function(x,y,args){ this.ctx.setShader(args[0]); } this._drawLine=function(x,y,args){ var ctx=this.ctx; Render.isWebGL && ctx.setPathId(args[6]); ctx.beginPath(); ctx.strokeStyle=args[4]; ctx.lineWidth=args[5]; if (Render.isWebGL){ ctx.movePath(x,y); ctx.moveTo(args[0],args[1]); ctx.lineTo(args[2],args[3]); }else { ctx.moveTo(x+args[0],y+args[1]); ctx.lineTo(x+args[2],y+args[3]); } ctx.stroke(); } this._drawLines=function(x,y,args){ var ctx=this.ctx; Render.isWebGL && ctx.setPathId(args[5]); ctx.beginPath(); x+=args[0],y+=args[1]; Render.isWebGL && ctx.movePath(x,y); ctx.strokeStyle=args[3]; ctx.lineWidth=args[4]; var points=args[2]; var i=2,n=points.length; if (Render.isWebGL){ ctx.moveTo(points[0],points[1]); while (i < n){ ctx.lineTo(points[i++],points[i++]); } }else { ctx.moveTo(x+points[0],y+points[1]); while (i < n){ ctx.lineTo(x+points[i++],y+points[i++]); } } ctx.stroke(); } this._drawLinesWebGL=function(x,y,args){ this.ctx.drawLines(x+this.x+args[0],y+this.y+args[1],args[2],args[3],args[4]); } //x:Number,y:Number,points:Array,lineColor:String,lineWidth:Number=1 this._drawCurves=function(x,y,args){ this.ctx.drawCurves(x,y,args); } this._draw=function(x,y,args){ args[0].call(null,this,x,y); } this._transformByMatrix=function(x,y,args){ this.ctx.transformByMatrix(args[0]); } this._setTransform=function(x,y,args){ this.ctx.setTransform(args[0],args[1],args[2],args[3],args[4],args[5]); } this._setTransformByMatrix=function(x,y,args){ this.ctx.setTransformByMatrix(args[0]); } this._save=function(x,y,args){ this.ctx.save(); } this._restore=function(x,y,args){ this.ctx.restore(); } this._translate=function(x,y,args){ this.ctx.translate(args[0],args[1]); } this._transform=function(x,y,args){ this.ctx.translate(args[1]+x,args[2]+y); var mat=args[0]; this.ctx.transform(mat.a,mat.b,mat.c,mat.d,mat.tx,mat.ty); this.ctx.translate(-x-args[1],-y-args[2]); } this._rotate=function(x,y,args){ this.ctx.translate(args[1]+x,args[2]+y); this.ctx.rotate(args[0]); this.ctx.translate(-x-args[1],-y-args[2]); } this._scale=function(x,y,args){ this.ctx.translate(args[2]+x,args[3]+y); this.ctx.scale(args[0],args[1]); this.ctx.translate(-x-args[2],-y-args[3]); } this._alpha=function(x,y,args){ this.ctx.globalAlpha *=args[0]; } this._setAlpha=function(x,y,args){ this.ctx.globalAlpha=args[0]; } this._fillText=function(x,y,args){ this.ctx.fillText(args[0],args[1]+x,args[2]+y,args[3],args[4],args[5]); } this._strokeText=function(x,y,args){ this.ctx.strokeText(args[0],args[1]+x,args[2]+y,args[3],args[4],args[5],args[6]); } this._fillBorderText=function(x,y,args){ this.ctx.fillBorderText(args[0],args[1]+x,args[2]+y,args[3],args[4],args[5],args[6],args[7]); } this._blendMode=function(x,y,args){ this.ctx.globalCompositeOperation=args[0]; } this._beginClip=function(x,y,args){ this.ctx.beginClip && this.ctx.beginClip(x+args[0],y+args[1],args[2],args[3]); } this._setIBVB=function(x,y,args){ this.ctx.setIBVB(args[0]+x,args[1]+y,args[2],args[3],args[4],args[5],args[6],args[7]); } this._fillTrangles=function(x,y,args){ this.ctx.fillTrangles(args[0],args[1]+x,args[2]+y,args[3],args[4]); } //x:Number,y:Number,paths:Array,brush:Object=null,pen:Object=null this._drawPath=function(x,y,args){ var ctx=this.ctx; Render.isWebGL && ctx.setPathId(-1); ctx.beginPath(); x+=args[0],y+=args[1]; Render.isWebGL && ctx.movePath(x,y); var paths=args[2]; for (var i=0,n=paths.length;i < n;i++){ var path=paths[i]; switch (path[0]){ case "moveTo": Render.isWebGL ? ctx.moveTo(path[1],path[2]):ctx.moveTo(x+path[1],y+path[2]); break ; case "lineTo": Render.isWebGL ? ctx.lineTo(path[1],path[2]):ctx.lineTo(x+path[1],y+path[2]); break ; case "arcTo": Render.isWebGL ? ctx.arcTo(path[1],path[2],path[3],path[4],path[5]):ctx.arcTo(x+path[1],y+path[2],x+path[3],y+path[4],path[5]); break ; case "closePath": ctx.closePath(); break ; } }; var brush=args[3]; if (brush !=null){ ctx.fillStyle=brush.fillStyle; ctx.fill(); }; var pen=args[4]; if (pen !=null){ ctx.strokeStyle=pen.strokeStyle; ctx.lineWidth=pen.lineWidth || 1; ctx.lineJoin=pen.lineJoin; ctx.lineCap=pen.lineCap; ctx.miterLimit=pen.miterLimit; ctx.stroke(); } } // polygon(x:Number,y:Number,r:Number,edges:Number,color:uint,borderWidth:int=2,borderColor:uint=0) this.drawPoly=function(x,y,args){ this.ctx.drawPoly(x+this.x+args[0],y+this.y+args[1],args[2],args[3],args[4],args[5],args[6]); } //x:Number,y:Number,points:Array,fillColor:String,lineColor:String=null,lineWidth:Number=1 this._drawPoly=function(x,y,args){ var ctx=this.ctx; var points=args[2]; var i=2,n=points.length; if (Render.isWebGL){ ctx.setPathId(args[6]); ctx.beginPath(); x+=args[0],y+=args[1]; ctx.movePath(x,y); ctx.moveTo(points[0],points[1]); while (i < n){ ctx.lineTo(points[i++],points[i++]); } }else { ctx.beginPath(); x+=args[0],y+=args[1]; ctx.moveTo(x+points[0],y+points[1]); while (i < n){ ctx.lineTo(x+points[i++],y+points[i++]); } } ctx.closePath(); this._fillAndStroke(args[3],args[4],args[5],args[7]); } this._drawSkin=function(x,y,args){ var tSprite=args[0]; if (tSprite){ var ctx=this.ctx; tSprite.render(ctx,x,y); } } this._drawParticle=function(x,y,args){ this.ctx.drawParticle(x+this.x,y+this.y,args[0]); } this._setFilters=function(x,y,args){ this.ctx.setFilters(args); } if (canvas){ this.ctx=canvas.getContext('2d'); }else { canvas=HTMLCanvas.create("3D"); this.ctx=RunDriver.createWebGLContext2D(canvas); canvas._setContext(this.ctx); } canvas.size(width,height); this.canvas=canvas; } __class(RenderContext,'laya.renders.RenderContext'); var __proto=RenderContext.prototype; /**销毁当前渲染环境*/ __proto.destroy=function(){ if (this.canvas){ this.canvas.destroy(); this.canvas=null; this.ctx=null; } if (this.ctx){ this.ctx.destroy(); this.ctx=null; } } __proto.drawTexture=function(tex,x,y,width,height){ if (tex.loaded)this.ctx.drawTexture(tex,x,y,width,height,this.x,this.y); } __proto._drawTextures=function(x,y,args){ if (args[0].loaded)this.ctx.drawTextures(args[0],args[1],x+this.x,y+this.y); } __proto.drawTextureWithTransform=function(tex,x,y,width,height,m,alpha){ if (tex.loaded)this.ctx.drawTextureWithTransform(tex,x,y,width,height,m,this.x,this.y,alpha); } __proto.fillQuadrangle=function(tex,x,y,point4,m){ this.ctx.fillQuadrangle(tex,x,y,point4,m); } __proto.drawCanvas=function(canvas,x,y,width,height){ this.ctx.drawCanvas(canvas,x+this.x,y+this.y,width,height); } __proto.drawRect=function(x,y,width,height,color,lineWidth){ (lineWidth===void 0)&& (lineWidth=1); var ctx=this.ctx; ctx.strokeStyle=color; ctx.lineWidth=lineWidth; ctx.strokeRect(x+this.x,y+this.y,width,height,lineWidth); } __proto._fillAndStroke=function(fillColor,strokeColor,lineWidth,isConvexPolygon){ (isConvexPolygon===void 0)&& (isConvexPolygon=false); var ctx=this.ctx; if (fillColor !=null){ ctx.fillStyle=fillColor; if (Render.isWebGL){ ctx.fill(isConvexPolygon); }else { ctx.fill(); } } if (strokeColor !=null && lineWidth > 0){ ctx.strokeStyle=strokeColor; ctx.lineWidth=lineWidth; ctx.stroke(); } } //ctx.translate(-x-args[0],-y-args[1]); __proto.clipRect=function(x,y,width,height){ this.ctx.clipRect(x+this.x,y+this.y,width,height); } __proto.fillRect=function(x,y,width,height,fillStyle){ this.ctx.fillRect(x+this.x,y+this.y,width,height,fillStyle); } __proto.drawCircle=function(x,y,radius,color,lineWidth){ (lineWidth===void 0)&& (lineWidth=1); Stat.drawCall++; var ctx=this.ctx; ctx.beginPath(); ctx.strokeStyle=color; ctx.lineWidth=lineWidth; ctx.arc(x+this.x,y+this.y,radius,0,RenderContext.PI2); ctx.stroke(); } /** *绘制三角形 *@param x *@param y *@param tex *@param args [x,y,texture,vertices,indices,uvs,matrix] */ __proto.drawTriangles=function(x,y,args){ if (Render.isWebGL){ this.ctx.drawTriangles(args[0],x+args[1],y+args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9]); }else { var indices=args[5]; var i=0,len=indices.length; var ctx=this.ctx; for (i=0;i < len;i+=3){ var index0=indices[i] *2; var index1=indices[i+1] *2; var index2=indices[i+2] *2; ctx.drawTriangle(args[0],args[3],args[4],index0,index1,index2,args[6],true); } } } __proto.fillCircle=function(x,y,radius,color){ Stat.drawCall++; var ctx=this.ctx; ctx.beginPath(); ctx.fillStyle=color; ctx.arc(x+this.x,y+this.y,radius,0,RenderContext.PI2); ctx.fill(); } __proto.setShader=function(shader){ this.ctx.setShader(shader); } __proto.drawLine=function(fromX,fromY,toX,toY,color,lineWidth){ (lineWidth===void 0)&& (lineWidth=1); var ctx=this.ctx; ctx.beginPath(); ctx.strokeStyle=color; ctx.lineWidth=lineWidth; ctx.moveTo(this.x+fromX,this.y+fromY); ctx.lineTo(this.x+toX,this.y+toY); ctx.stroke(); } __proto.clear=function(){ this.ctx.clear(); } __proto.transformByMatrix=function(value){ this.ctx.transformByMatrix(value); } __proto.setTransform=function(a,b,c,d,tx,ty){ this.ctx.setTransform(a,b,c,d,tx,ty); } __proto.setTransformByMatrix=function(value){ this.ctx.setTransformByMatrix(value); } __proto.save=function(){ this.ctx.save(); } __proto.restore=function(){ this.ctx.restore(); } __proto.translate=function(x,y){ this.ctx.translate(x,y); } __proto.transform=function(a,b,c,d,tx,ty){ this.ctx.transform(a,b,c,d,tx,ty); } __proto.rotate=function(angle){ this.ctx.rotate(angle); } __proto.scale=function(scaleX,scaleY){ this.ctx.scale(scaleX,scaleY); } __proto.alpha=function(value){ this.ctx.globalAlpha *=value; } __proto.setAlpha=function(value){ this.ctx.globalAlpha=value; } __proto.fillWords=function(words,x,y,font,color,underLine){ (underLine===void 0)&& (underLine=0); this.ctx.fillWords(words,x,y,font,color,underLine); } /***@private */ __proto.fillBorderWords=function(words,x,y,font,fillColor,borderColor,lineWidth){ this.ctx.fillBorderWords(words,x,y,font,fillColor,borderColor,lineWidth); } __proto.fillText=function(text,x,y,font,color,textAlign){ this.ctx.fillText(text,x+this.x,y+this.y,font,color,textAlign); } __proto.strokeText=function(text,x,y,font,color,lineWidth,textAlign){ this.ctx.strokeText(text,x+this.x,y+this.y,font,color,lineWidth,textAlign); } __proto.blendMode=function(type){ this.ctx.globalCompositeOperation=type; } __proto.flush=function(){ this.ctx.flush && this.ctx.flush(); } __proto.addRenderObject=function(o){ this.ctx.addRenderObject(o); } __proto.beginClip=function(x,y,w,h){ this.ctx.beginClip && this.ctx.beginClip(x,y,w,h); } __proto.endClip=function(){ this.ctx.endClip && this.ctx.endClip(); } __proto.fillTrangles=function(x,y,args){ this.ctx.fillTrangles(args[0],args[1],args[2],args[3],args.length > 4 ? args[4] :null); } RenderContext.PI2=2 *Math.PI; return RenderContext; })() /** *@private *精灵渲染器 */ //class laya.renders.RenderSprite var RenderSprite=(function(){ function RenderSprite(type,next){ /**@private */ //this._next=null; /**@private */ //this._fun=null; this._next=next || RenderSprite.NORENDER; switch (type){ case 0: this._fun=this._no; return; case 0x01: this._fun=this._image; return; case 0x02: this._fun=this._alpha; return; case 0x04: this._fun=this._transform; return; case 0x08: this._fun=this._blend; return; case 0x10: this._fun=this._canvas; return; case 0x40: this._fun=this._mask; return; case 0x80: this._fun=this._clip; return; case 0x100: this._fun=this._style; return; case 0x200: this._fun=this._graphics; return; case 0x800: this._fun=this._childs; return; case 0x400: this._fun=this._custom; return; case 0x01 | 0x200: this._fun=this._image2; return; case 0x01 | 0x04 | 0x200: this._fun=this._image2; return; case 0x20: this._fun=Filter._filter; return; case 0x11111: this._fun=RenderSprite._initRenderFun; return; } this.onCreate(type); } __class(RenderSprite,'laya.renders.RenderSprite'); var __proto=RenderSprite.prototype; __proto.onCreate=function(type){} __proto._style=function(sprite,context,x,y){ sprite._style.render(sprite,context,x,y); var next=this._next; next._fun.call(next,sprite,context,x,y); } __proto._no=function(sprite,context,x,y){} __proto._custom=function(sprite,context,x,y){ sprite.customRender(context,x,y); var tf=sprite._style._tf; this._next._fun.call(this._next,sprite,context,x-tf.translateX,y-tf.translateY); } __proto._clip=function(sprite,context,x,y){ var next=this._next; if (next==RenderSprite.NORENDER)return; var r=sprite._style.scrollRect; context.ctx.save(); context.ctx.clipRect(x,y,r.width,r.height); next._fun.call(next,sprite,context,x-r.x,y-r.y); context.ctx.restore(); } __proto._blend=function(sprite,context,x,y){ var style=sprite._style; if (style.blendMode){ context.ctx.globalCompositeOperation=style.blendMode; }; var next=this._next; next._fun.call(next,sprite,context,x,y); context.ctx.globalCompositeOperation="source-over"; } __proto._mask=function(sprite,context,x,y){ var next=this._next; next._fun.call(next,sprite,context,x,y); var mask=sprite.mask; if (mask){ context.ctx.globalCompositeOperation="destination-in"; if (mask.numChildren > 0 || !mask.graphics._isOnlyOne()){ mask.cacheAsBitmap=true; } mask.render(context,x-sprite.pivotX,y-sprite.pivotY); } context.ctx.globalCompositeOperation="source-over"; } __proto._graphics=function(sprite,context,x,y){ var tf=sprite._style._tf; sprite._graphics && sprite._graphics._render(sprite,context,x-tf.translateX,y-tf.translateY); var next=this._next; next._fun.call(next,sprite,context,x,y); } __proto._image=function(sprite,context,x,y){ var style=sprite._style; context.ctx.drawTexture2(x,y,style._tf.translateX,style._tf.translateY,sprite.transform,style.alpha,style.blendMode,sprite._graphics._one); } __proto._image2=function(sprite,context,x,y){ var tf=sprite._style._tf; context.ctx.drawTexture2(x,y,tf.translateX,tf.translateY,sprite.transform,1,null,sprite._graphics._one); } __proto._alpha=function(sprite,context,x,y){ var style=sprite._style; var alpha; if ((alpha=style.alpha)> 0.01 || sprite._needRepaint()){ var temp=context.ctx.globalAlpha; context.ctx.globalAlpha *=alpha; var next=this._next; next._fun.call(next,sprite,context,x,y); context.ctx.globalAlpha=temp; } } __proto._transform=function(sprite,context,x,y){ var transform=sprite.transform,_next=this._next; if (transform && _next !=RenderSprite.NORENDER){ context.save(); context.transform(transform.a,transform.b,transform.c,transform.d,transform.tx+x,transform.ty+y); _next._fun.call(_next,sprite,context,0,0); context.restore(); }else _next._fun.call(_next,sprite,context,x,y); } __proto._childs=function(sprite,context,x,y){ var style=sprite._style; var tf=style._tf; x=x-tf.translateX+style.paddingLeft; y=y-tf.translateY+style.paddingTop; if (style._calculation){ var words=sprite._getWords(); if (words){ var tStyle=style; if (tStyle){ if (tStyle.stroke){ context.fillBorderWords(words,x,y,tStyle.font,tStyle.color,tStyle.strokeColor,tStyle.stroke); }else{ context.fillWords(words,x,y,tStyle.font,tStyle.color,(tStyle.textDecoration!="none"&&tStyle.underLine)?1:0); } } } }; var childs=sprite._childs,n=childs.length,ele; if (sprite.viewport || (sprite.optimizeScrollRect && sprite._style.scrollRect)){ var rect=sprite.viewport || sprite._style.scrollRect; var left=rect.x; var top=rect.y; var right=rect.right; var bottom=rect.bottom; var _x=NaN,_y=NaN; for (i=0;i < n;++i){ if ((ele=childs [i]).visible && ((_x=ele._x)< right && (_x+ele.width)> left && (_y=ele._y)< bottom && (_y+ele.height)> top)){ ele.render(context,x,y); } } }else { for (var i=0;i < n;++i) (ele=(childs [i]))._style.visible && ele.render(context,x,y); } } //} __proto._canvas=function(sprite,context,x,y){ var _cacheCanvas=sprite._$P.cacheCanvas; if (!_cacheCanvas){ this._next._fun.call(this._next,sprite,context,x,y); return; } _cacheCanvas.type==='bitmap' ? (Stat.canvasBitmap++):(Stat.canvasNormal++); var tx=_cacheCanvas.ctx; if (sprite._needRepaint()|| !tx){ this._canvas_repaint(sprite,context,x,y); } else{ var tRec=_cacheCanvas._cacheRec; context.drawCanvas(tx.canvas,x+tRec.x,y+tRec.y,tRec.width,tRec.height); } } __proto._canvas_repaint=function(sprite,context,x,y){ var _cacheCanvas=sprite._$P.cacheCanvas; var _next=this._next; if (!_cacheCanvas){ _next._fun.call(_next,sprite,tx,x,y); return; }; var tx=_cacheCanvas.ctx; var _repaint=sprite._needRepaint()|| (!tx); var canvas; var left; var top; var tRec; var tCacheType=_cacheCanvas.type; tCacheType==='bitmap' ? (Stat.canvasBitmap++):(Stat.canvasNormal++); if (_repaint){ if (!_cacheCanvas._cacheRec) _cacheCanvas._cacheRec=new Rectangle(); var w,h; if (!Render.isWebGL || tCacheType==="bitmap"){ tRec=sprite.getSelfBounds(); tRec.x=tRec.x-sprite.pivotX; tRec.y=tRec.y-sprite.pivotY; tRec.x=tRec.x-16; tRec.y=tRec.y-16; tRec.width=tRec.width+32; tRec.height=tRec.height+32; tRec.x=Math.floor(tRec.x+x)-x; tRec.y=Math.floor(tRec.y+y)-y; tRec.width=Math.floor(tRec.width); tRec.height=Math.floor(tRec.height); _cacheCanvas._cacheRec.copyFrom(tRec); }else{ _cacheCanvas._cacheRec.setTo(-sprite.pivotX,-sprite.pivotY,1,1); } tRec=_cacheCanvas._cacheRec; var scaleX=Render.isWebGL ? 1 :Browser.pixelRatio *Laya.stage.clientScaleX; var scaleY=Render.isWebGL ? 1 :Browser.pixelRatio *Laya.stage.clientScaleY; if (!Render.isWebGL){ var chainScaleX=1; var chainScaleY=1; var tar; tar=sprite; while (tar && tar !=Laya.stage){ chainScaleX *=tar.scaleX; chainScaleY *=tar.scaleY; tar=tar.parent; } if (Render.isWebGL){ if (chainScaleX < 1)scaleX *=chainScaleX; if (chainScaleY < 1)scaleY *=chainScaleY; }else { if (chainScaleX > 1)scaleX *=chainScaleX; if (chainScaleY > 1)scaleY *=chainScaleY; } } if (sprite.scrollRect){ var scrollRect=sprite.scrollRect; tRec.x-=scrollRect.x; tRec.y-=scrollRect.y; } w=tRec.width *scaleX; h=tRec.height *scaleY; left=tRec.x; top=tRec.y; if (Render.isWebGL && tCacheType==='bitmap' && (w > 2048 || h > 2048)){ console.warn("cache bitmap size larger than 2048,cache ignored"); if (_cacheCanvas.ctx){ Pool.recover("RenderContext",_cacheCanvas.ctx); _cacheCanvas.ctx.canvas.size(0,0); _cacheCanvas.ctx=null; } _next._fun.call(_next,sprite,context,x,y); return; } if (!tx){ tx=_cacheCanvas.ctx=Pool.getItem("RenderContext")|| new RenderContext(w,h,HTMLCanvas.create(/*laya.resource.HTMLCanvas.TYPEAUTO*/"AUTO")); } tx.ctx.sprite=sprite; canvas=tx.canvas; canvas.clear(); (canvas.width !=w || canvas.height !=h)&& canvas.size(w,h); if (tCacheType==='bitmap')canvas.context.asBitmap=true; else if(tCacheType==='normal')canvas.context.asBitmap=false; var t; if (scaleX !=1 || scaleY !=1){ var ctx=(tx).ctx; ctx.save(); ctx.scale(scaleX,scaleY); if (!Render.isConchWebGL && Render.isConchApp){ t=sprite._$P.cf; t && ctx.setFilterMatrix && ctx.setFilterMatrix(t._mat,t._alpha); } _next._fun.call(_next,sprite,tx,-left,-top); ctx.restore(); if (!Render.isConchApp || Render.isConchWebGL)sprite._applyFilters(); }else { ctx=(tx).ctx; if (!Render.isConchWebGL && Render.isConchApp){ t=sprite._$P.cf; t && ctx.setFilterMatrix && ctx.setFilterMatrix(t._mat,t._alpha); } _next._fun.call(_next,sprite,tx,-left,-top); if (!Render.isConchApp || Render.isConchWebGL)sprite._applyFilters(); } if (sprite._$P.staticCache)_cacheCanvas.reCache=false; Stat.canvasReCache++; }else { tRec=_cacheCanvas._cacheRec; left=tRec.x; top=tRec.y; canvas=tx.canvas; } context.drawCanvas(canvas,x+left,y+top,tRec.width,tRec.height); } RenderSprite.__init__=function(){ var i=0,len=0; var initRender; initRender=RunDriver.createRenderSprite(0x11111,null); len=RenderSprite.renders.length=0x800 *2; for (i=0;i < len;i++) RenderSprite.renders[i]=initRender; RenderSprite.renders[0]=RunDriver.createRenderSprite(0,null); function _initSame (value,o){ var n=0; for (var i=0;i < value.length;i++){ n |=value[i]; RenderSprite.renders[n]=o; } } _initSame([0x01,0x200,0x04,0x02],new RenderSprite(0x01,null)); RenderSprite.renders[0x01 | 0x200]=RunDriver.createRenderSprite(0x01 | 0x200,null); RenderSprite.renders[0x01 | 0x04 | 0x200]=new RenderSprite(0x01 | 0x04 | 0x200,null); } RenderSprite._initRenderFun=function(sprite,context,x,y){ var type=sprite._renderType; var r=RenderSprite.renders[type]=RenderSprite._getTypeRender(type); r._fun(sprite,context,x,y); } RenderSprite._getTypeRender=function(type){ var rst=null; var tType=0x800; while (tType > 1){ if (tType & type) rst=RunDriver.createRenderSprite(tType,rst); tType=tType >> 1; } return rst; } RenderSprite.IMAGE=0x01; RenderSprite.ALPHA=0x02; RenderSprite.TRANSFORM=0x04; RenderSprite.BLEND=0x08; RenderSprite.CANVAS=0x10; RenderSprite.FILTERS=0x20; RenderSprite.MASK=0x40; RenderSprite.CLIP=0x80; RenderSprite.STYLE=0x100; RenderSprite.GRAPHICS=0x200; RenderSprite.CUSTOM=0x400; RenderSprite.CHILDS=0x800; RenderSprite.INIT=0x11111; RenderSprite.renders=[]; RenderSprite.NORENDER=new RenderSprite(0,null); return RenderSprite; })() /** *@private *Context扩展类 */ //class laya.resource.Context var Context=(function(){ function Context(){ /***@private */ //this._canvas=null; this._repaint=false; } __class(Context,'laya.resource.Context'); var __proto=Context.prototype; __proto.replaceReset=function(){ var i=0,len=0; len=Context.replaceKeys.length; var key; for (i=0;i < len;i++){ key=Context.replaceKeys[i]; this[Context.newKeys[i]]=this[key]; } } __proto.replaceResotre=function(){ /*__JS__ */this.__restore(); /*__JS__ */this.__reset(); } __proto.setIsMainContext=function(){} __proto.drawTextures=function(tex,pos,tx,ty){ Stat.drawCall+=pos.length / 2; var w=tex.width; var h=tex.height; for (var i=0,sz=pos.length;i < sz;i+=2){ this.drawTexture(tex,pos[i],pos[i+1],w,h,tx,ty); } } /***@private */ __proto.drawCanvas=function(canvas,x,y,width,height){ Stat.drawCall++; this.drawImage(canvas.source,x,y,width,height); } /***@private */ __proto.fillRect=function(x,y,width,height,style){ Stat.drawCall++; style && (this.fillStyle=style); /*__JS__ */this.__fillRect(x,y,width,height); } /***@private */ __proto.fillText=function(text,x,y,font,color,textAlign){ Stat.drawCall++; if (arguments.length > 3 && (typeof font=='string')){ this.font=font; this.fillStyle=color; /*__JS__ */this.textAlign=textAlign; this.textBaseline="top"; } if ((typeof font=='number')){ /*__JS__ */this.__fillText(text,x,y,font); }else{ /*__JS__ */this.__fillText(text,x,y); } } /***@private */ __proto.fillBorderText=function(text,x,y,font,fillColor,borderColor,lineWidth,textAlign){ Stat.drawCall++; this.font=font; this.fillStyle=fillColor; this.textBaseline="top"; /*__JS__ */this.strokeStyle=borderColor; /*__JS__ */this.lineWidth=lineWidth; /*__JS__ */this.textAlign=textAlign; /*__JS__ */this.__strokeText(text,x,y); /*__JS__ */this.__fillText(text,x,y); } /***@private */ __proto.strokeText=function(text,x,y,font,color,lineWidth,textAlign){ Stat.drawCall++; if (arguments.length > 3 && (typeof font=='string')){ this.font=font; /*__JS__ */this.strokeStyle=color; /*__JS__ */this.lineWidth=lineWidth; /*__JS__ */this.textAlign=textAlign; this.textBaseline="top"; } if ((typeof font=='number')){ /*__JS__ */this.__strokeText(text,x,y,font); }else /*__JS__ */this.__strokeText(text,x,y); } /***@private */ __proto.transformByMatrix=function(value){ this.transform(value.a,value.b,value.c,value.d,value.tx,value.ty); } /***@private */ __proto.setTransformByMatrix=function(value){ this.setTransform(value.a,value.b,value.c,value.d,value.tx,value.ty); } /***@private */ __proto.clipRect=function(x,y,width,height){ Stat.drawCall++; this.beginPath(); this.rect(x,y,width,height); this.clip(); } /***@private */ __proto.drawTexture=function(tex,x,y,width,height,tx,ty){ Stat.drawCall++; var uv=tex.uv,w=tex.bitmap.width,h=tex.bitmap.height; this.drawImage(tex.source,uv[0] *w,uv[1] *h,(uv[2]-uv[0])*w,(uv[5]-uv[3])*h,x+tx,y+ty,width,height); } /***@private */ __proto.drawTextureWithTransform=function(tex,x,y,width,height,m,tx,ty,alpha){ Stat.drawCall++; var uv=tex.uv,w=tex.bitmap.width,h=tex.bitmap.height; this.save(); alpha !=1 && (this.globalAlpha *=alpha); if (m){ this.transform(m.a,m.b,m.c,m.d,m.tx+tx,m.ty+ty); this.drawImage(tex.source,uv[0] *w,uv[1] *h,(uv[2]-uv[0])*w,(uv[5]-uv[3])*h,x ,y,width,height); }else { this.drawImage(tex.source,uv[0] *w,uv[1] *h,(uv[2]-uv[0])*w,(uv[5]-uv[3])*h,x+tx ,y+ty,width,height); } this.restore(); } /***@private */ __proto.drawTexture2=function(x,y,pivotX,pivotY,m,alpha,blendMode,args2){ var tex=args2[0]; if (!(tex.loaded && tex.bitmap && tex.source)){ return; } Stat.drawCall++; var alphaChanged=alpha!==1; if (alphaChanged){ var temp=this.globalAlpha; this.globalAlpha *=alpha; }; var uv=tex.uv,w=tex.bitmap.width,h=tex.bitmap.height; if (m){ this.save(); this.transform(m.a,m.b,m.c,m.d,m.tx+x,m.ty+y); this.drawImage(tex.source,uv[0] *w,uv[1] *h,(uv[2]-uv[0])*w,(uv[5]-uv[3])*h,args2[1]-pivotX ,args2[2]-pivotY,args2[3],args2[4]); this.restore(); }else { this.drawImage(tex.source,uv[0] *w,uv[1] *h,(uv[2]-uv[0])*w,(uv[5]-uv[3])*h,args2[1]-pivotX+x ,args2[2]-pivotY+y,args2[3],args2[4]); } if (alphaChanged)this.globalAlpha=temp; } __proto.fillTexture=function(texture,x,y,width,height,type,offset,other){ if (!other.pat){ if (texture.uv !=Texture.DEF_UV){ var canvas=new HTMLCanvas("2D"); canvas.getContext('2d'); canvas.size(texture.width,texture.height); canvas.context.drawTexture(texture,0,0,texture.width,texture.height,0,0); texture=new Texture(canvas); } other.pat=this.createPattern(texture.bitmap.source,type); }; var oX=x,oY=y; var sX=0,sY=0; if (offset){ oX+=offset.x % texture.width; oY+=offset.y % texture.height; sX-=offset.x % texture.width; sY-=offset.y % texture.height; } this.translate(oX,oY); this.fillRect(sX,sY,width,height,other.pat); this.translate(-oX,-oY); } __proto.drawTriangle=function(texture,vertices,uvs,index0,index1,index2,matrix,canvasPadding){ var source=texture.bitmap; var textureSource=source.source; var textureWidth=texture.width; var textureHeight=texture.height; var sourceWidth=source.width; var sourceHeight=source.height; var u0=uvs[index0] *sourceWidth; var u1=uvs[index1] *sourceWidth; var u2=uvs[index2] *sourceWidth; var v0=uvs[index0+1] *sourceHeight; var v1=uvs[index1+1] *sourceHeight; var v2=uvs[index2+1] *sourceHeight; var x0=vertices[index0]; var x1=vertices[index1]; var x2=vertices[index2]; var y0=vertices[index0+1]; var y1=vertices[index1+1]; var y2=vertices[index2+1]; if (canvasPadding){ var paddingX=1; var paddingY=1; var centerX=(x0+x1+x2)/ 3; var centerY=(y0+y1+y2)/ 3; var normX=x0-centerX; var normY=y0-centerY; var dist=Math.sqrt((normX *normX)+(normY *normY)); x0=centerX+((normX / dist)*(dist+paddingX)); y0=centerY+((normY / dist)*(dist+paddingY)); normX=x1-centerX; normY=y1-centerY; dist=Math.sqrt((normX *normX)+(normY *normY)); x1=centerX+((normX / dist)*(dist+paddingX)); y1=centerY+((normY / dist)*(dist+paddingY)); normX=x2-centerX; normY=y2-centerY; dist=Math.sqrt((normX *normX)+(normY *normY)); x2=centerX+((normX / dist)*(dist+paddingX)); y2=centerY+((normY / dist)*(dist+paddingY)); } this.save(); if (matrix) this.transform(matrix.a,matrix.b,matrix.c,matrix.d,matrix.tx,matrix.ty); this.beginPath(); this.moveTo(x0,y0); this.lineTo(x1,y1); this.lineTo(x2,y2); this.closePath(); this.clip(); var delta=(u0 *v1)+(v0 *u2)+(u1 *v2)-(v1 *u2)-(v0 *u1)-(u0 *v2); var dDelta=1 / delta; var deltaA=(x0 *v1)+(v0 *x2)+(x1 *v2)-(v1 *x2)-(v0 *x1)-(x0 *v2); var deltaB=(u0 *x1)+(x0 *u2)+(u1 *x2)-(x1 *u2)-(x0 *u1)-(u0 *x2); var deltaC=(u0 *v1 *x2)+(v0 *x1 *u2)+(x0 *u1 *v2)-(x0 *v1 *u2)-(v0 *u1 *x2)-(u0 *x1 *v2); var deltaD=(y0 *v1)+(v0 *y2)+(y1 *v2)-(v1 *y2)-(v0 *y1)-(y0 *v2); var deltaE=(u0 *y1)+(y0 *u2)+(u1 *y2)-(y1 *u2)-(y0 *u1)-(u0 *y2); var deltaF=(u0 *v1 *y2)+(v0 *y1 *u2)+(y0 *u1 *v2)-(y0 *v1 *u2)-(v0 *u1 *y2)-(u0 *y1 *v2); this.transform(deltaA *dDelta,deltaD *dDelta,deltaB *dDelta,deltaE *dDelta,deltaC *dDelta,deltaF *dDelta); this.drawImage(textureSource,texture.uv[0] *sourceWidth,texture.uv[1] *sourceHeight,textureWidth,textureHeight,texture.uv[0] *sourceWidth,texture.uv[1] *sourceHeight,textureWidth,textureHeight); this.restore(); } /***@private */ __proto.flush=function(){ return 0; } /***@private */ __proto.fillWords=function(words,x,y,font,color,underLine){ font && (this.font=font); color && (this.fillStyle=color); var _this=this; this.textBaseline="top"; /*__JS__ */this.textAlign='left'; for (var i=0,n=words.length;i < n;i++){ var a=words[i]; /*__JS__ */this.__fillText(a.char,a.x+x,a.y+y); if (underLine===1){ var tHeight=a.height; var dX=a.style.letterSpacing*0.5; if (!dX)dX=0; this.beginPath(); this.strokeStyle=color; this.lineWidth=1; this.moveTo(x+a.x-dX+0.5,y+a.y+tHeight+0.5); this.lineTo(x+a.x+a.width+dX+0.5,y+a.y+tHeight+0.5); this.stroke(); } } } /***@private */ __proto.fillBorderWords=function(words,x,y,font,color,borderColor,lineWidth){ font && (this.font=font); color && (this.fillStyle=color); this.textBaseline="top"; /*__JS__ */this.lineWidth=lineWidth; /*__JS__ */this.textAlign='left'; /*__JS__ */this.strokeStyle=borderColor; for (var i=0,n=words.length;i < n;i++){ var a=words[i]; /*__JS__ */this.__strokeText(a.char,a.x+x,a.y+y); /*__JS__ */this.__fillText(a.char,a.x+x,a.y+y); } } /***@private */ __proto.destroy=function(){ /*__JS__ */this.canvas.width=this.canvas.height=0; } /***@private */ __proto.clear=function(){ this.clearRect(0,0,this._canvas.width,this._canvas.height); this._repaint=false; } __proto.drawCurves=function(x,y,args){ this.beginPath(); this.strokeStyle=args[3]; this.lineWidth=args[4]; var points=args[2]; x+=args[0],y+=args[1]; this.moveTo(x+points[0],y+points[1]); var i=2,n=points.length; while (i < n){ this.quadraticCurveTo(x+points[i++],y+points[i++],x+points[i++],y+points[i++]); } this.stroke(); } Context.__init__=function(to){ var from=laya.resource.Context.prototype; to=to || /*__JS__ */window.CanvasRenderingContext2D.prototype; if (to.inited)return; to.inited=true; to.__fillText=to.fillText; to.__fillRect=to.fillRect; to.__strokeText=to.strokeText; var funs=['drawTextures',"drawTriangle",'fillWords','fillBorderWords','setIsMainContext','fillRect','strokeText','fillTexture','fillText','transformByMatrix','setTransformByMatrix','clipRect','drawTexture','drawTexture2','drawTextureWithTransform','flush','clear','destroy','drawCanvas','fillBorderText','drawCurves']; funs.forEach(function(i){ to[i]=from[i]; }); } Context.replaceCanvasGetSet=function(tar,key){ var oldO=/*__JS__ */Object.getOwnPropertyDescriptor(tar,key); if (!oldO||!oldO.configurable)return false; var newO={}; var tkey; for (tkey in oldO){ if (tkey !="set"){ newO[tkey]=oldO[tkey]; } }; var preFun=oldO["set"]; newO["set"]=function (v){ var _self=/*__JS__ */this; preFun.call(_self,v); var _ct=_self.getContext("2d"); if (_ct && "__reset" in _ct){ _ct.__reset(); } } /*__JS__ */Object.defineProperty(tar,key,newO); return true; } Context.replaceGetSet=function(tar,key){ var oldO=/*__JS__ */Object.getOwnPropertyDescriptor(tar,key); if (!oldO||!oldO.configurable)return false; var newO={}; var tkey; for (tkey in oldO){ if (tkey !="set"){ newO[tkey]=oldO[tkey]; } }; var preFun=oldO["set"]; var dataKey="___"+key+"__"; Context.newKeys.push(dataKey); newO["set"]=function (v){ var _self=/*__JS__ */this; if (v !=_self[dataKey]){ _self[dataKey]=v; preFun.call(_self,v); } } /*__JS__ */Object.defineProperty(tar,key,newO); return true; } Context._default=new Context(); Context.newKeys=[]; __static(Context, ['replaceKeys',function(){return this.replaceKeys=["font","fillStyle","textBaseline"];} ]); return Context; })() /** *@private *ResourceManager 是资源管理类。它用于资源的载入、获取、销毁。 */ //class laya.resource.ResourceManager var ResourceManager=(function(){ function ResourceManager(name){ /**唯一标识ID。*/ this._id=0; /**名字。*/ this._name=null; /**所管理资源。*/ this._resources=null; /**所管理资源的累计内存,以字节为单位。*/ this._memorySize=0; /**垃圾回收比例,范围是0到1。*/ this._garbageCollectionRate=NaN; /**自动释放机制中内存是否溢出。*/ this._isOverflow=false; /**是否启用自动释放机制。*/ this.autoRelease=false; /**自动释放机制的内存触发上限,以字节为单位。*/ this.autoReleaseMaxSize=0; this._id=++ResourceManager._uniqueIDCounter; this._name=name ? name :"Content Manager"; ResourceManager._isResourceManagersSorted=false; this._memorySize=0; this._isOverflow=false; this.autoRelease=false; this.autoReleaseMaxSize=1024 *1024 *512; this._garbageCollectionRate=0.2; ResourceManager._resourceManagers.push(this); this._resources=[]; } __class(ResourceManager,'laya.resource.ResourceManager'); var __proto=ResourceManager.prototype; Laya.imps(__proto,{"laya.resource.IDispose":true}) /** *获取指定索引的资源 Resource 对象。 *@param 索引。 *@return 资源 Resource 对象。 */ __proto.getResourceByIndex=function(index){ return this._resources[index]; } /** *获取此管理器所管理的资源个数。 *@return 资源个数。 */ __proto.getResourcesLength=function(){ return this._resources.length; } /** *添加指定资源。 *@param resource 需要添加的资源 Resource 对象。 *@return 是否添加成功。 */ __proto.addResource=function(resource){ if (resource.resourceManager) resource.resourceManager.removeResource(resource); var index=this._resources.indexOf(resource); if (index===-1){ resource._resourceManager=this; this._resources.push(resource); this.addSize(resource.memorySize); return true; } return false; } /** *移除指定资源。 *@param resource 需要移除的资源 Resource 对象 *@return 是否移除成功。 */ __proto.removeResource=function(resource){ var index=this._resources.indexOf(resource); if (index!==-1){ this._resources.splice(index,1); resource._resourceManager=null; this._memorySize-=resource.memorySize; return true; } return false; } /** *卸载此资源管理器载入的资源。 */ __proto.unload=function(){ var tempResources=this._resources.slice(0,this._resources.length); for (var i=0;i < tempResources.length;i++){ var resource=tempResources[i]; resource.destroy(); } tempResources.length=0; } /**释放资源。*/ __proto.dispose=function(){ if (this===ResourceManager._systemResourceManager) throw new Error("systemResourceManager不能被释放!"); ResourceManager._resourceManagers.splice(ResourceManager._resourceManagers.indexOf(this),1); ResourceManager._isResourceManagersSorted=false; var tempResources=this._resources.slice(0,this._resources.length); for (var i=0;i < tempResources.length;i++){ var resource=tempResources[i]; resource.resourceManager.removeResource(resource); resource.destroy(); } tempResources.length=0; } /** *增加内存。 *@param add 需要增加的内存大小。 */ __proto.addSize=function(add){ if (add){ if (this.autoRelease && add > 0) ((this._memorySize+add)> this.autoReleaseMaxSize)&& (this.garbageCollection((1-this._garbageCollectionRate)*this.autoReleaseMaxSize)); this._memorySize+=add; } } /** *垃圾回收。 *@param reserveSize 保留尺寸。 */ __proto.garbageCollection=function(reserveSize){ var all=this._resources; all=all.slice(); all.sort(function(a,b){ if (!a || !b) throw new Error("a或b不能为空!"); if (a.released && b.released) return 0; else if (a.released) return 1; else if (b.released) return-1; return a._lastUseFrameCount-b._lastUseFrameCount; }); var currentFrameCount=Stat.loopCount; for (var i=0,n=all.length;i < n;i++){ var resou=all[i]; if (currentFrameCount-resou._lastUseFrameCount > 1){ resou.releaseResource(); }else { if (this._memorySize >=reserveSize) this._isOverflow=true; return; } if (this._memorySize < reserveSize){ this._isOverflow=false; return; } } } /** *唯一标识 ID 。 */ __getset(0,__proto,'id',function(){ return this._id; }); /** *名字。 */ __getset(0,__proto,'name',function(){ return this._name; },function(value){ if ((value || value!=="")&& this._name!==value){ this._name=value; ResourceManager._isResourceManagersSorted=false; } }); /** *此管理器所管理资源的累计内存,以字节为单位。 */ __getset(0,__proto,'memorySize',function(){ return this._memorySize; }); /** *系统资源管理器。 */ __getset(1,ResourceManager,'systemResourceManager',function(){ return ResourceManager._systemResourceManager; }); ResourceManager.__init__=function(){ ResourceManager.currentResourceManager=ResourceManager.systemResourceManager; } ResourceManager.getLoadedResourceManagerByIndex=function(index){ return ResourceManager._resourceManagers[index]; } ResourceManager.getLoadedResourceManagersCount=function(){ return ResourceManager._resourceManagers.length; } ResourceManager.recreateContentManagers=function(force){ (force===void 0)&& (force=false); var temp=ResourceManager.currentResourceManager; for (var i=0;i < ResourceManager._resourceManagers.length;i++){ ResourceManager.currentResourceManager=ResourceManager._resourceManagers[i]; for (var j=0;j < ResourceManager.currentResourceManager._resources.length;j++){ ResourceManager.currentResourceManager._resources[j].releaseResource(force); ResourceManager.currentResourceManager._resources[j].activeResource(force); } } ResourceManager.currentResourceManager=temp; } ResourceManager.releaseContentManagers=function(force){ (force===void 0)&& (force=false); var temp=ResourceManager.currentResourceManager; for (var i=0;i < ResourceManager._resourceManagers.length;i++){ ResourceManager.currentResourceManager=ResourceManager._resourceManagers[i]; for (var j=0;j < ResourceManager.currentResourceManager._resources.length;j++){ var resource=ResourceManager.currentResourceManager._resources[j]; (!resource.released)&& (resource.releaseResource(force)); } } ResourceManager.currentResourceManager=temp; } ResourceManager._uniqueIDCounter=0; ResourceManager._isResourceManagersSorted=false; ResourceManager._resourceManagers=[]; __static(ResourceManager, ['_systemResourceManager',function(){return this._systemResourceManager=new ResourceManager("System Resource Manager");},'currentResourceManager',function(){return this.currentResourceManager=ResourceManager._systemResourceManager;} ]); return ResourceManager; })() /** *@private */ //class laya.system.System var System=(function(){ function System(){} __class(System,'laya.system.System'); System.changeDefinition=function(name,classObj){ Laya[name]=classObj; var str=name+"=classObj"; Laya._runScript(str); } System.__init__=function(){ if (Render.isConchApp){ /*__JS__ */conch.disableConchResManager(); /*__JS__ */conch.disableConchAutoRestoreLostedDevice(); } } return System; })() SoundManager; /** *Browser 是浏览器代理类。封装浏览器及原生 js 提供的一些功能。 */ //class laya.utils.Browser var Browser=(function(){ function Browser(){} __class(Browser,'laya.utils.Browser'); /**设备像素比。*/ __getset(1,Browser,'pixelRatio',function(){ Browser.__init__(); if (Browser.userAgent.indexOf("Mozilla/6.0(Linux; Android 6.0; HUAWEI NXT-AL10 Build/HUAWEINXT-AL10)")>-1)return 2; return RunDriver.getPixelRatio(); }); /**浏览器窗口物理高度,其值等于clientHeight *pixelRatio,并且浏览器发生反转之后,宽高会互换。*/ __getset(1,Browser,'height',function(){ Browser.__init__(); return ((Laya.stage && Laya.stage.canvasRotation)? Browser.clientWidth :Browser.clientHeight)*Browser.pixelRatio; }); /** *浏览器窗口可视宽度。 *通过分析浏览器信息获得。浏览器多个属性值优先级为:window.innerWidth(包含滚动条宽度)> document.body.clientWidth(不包含滚动条宽度),如果前者为0或为空,则选择后者。 */ __getset(1,Browser,'clientWidth',function(){ Browser.__init__(); return Browser.window.innerWidth || Browser.document.body.clientWidth; }); /**浏览器原生 window 对象的引用。*/ __getset(1,Browser,'window',function(){ Browser.__init__(); return Browser._window; }); /** *浏览器窗口可视高度。 *通过分析浏览器信息获得。浏览器多个属性值优先级为:window.innerHeight(包含滚动条高度)> document.body.clientHeight(不包含滚动条高度)> document.documentElement.clientHeight(不包含滚动条高度),如果前者为0或为空,则选择后者。 */ __getset(1,Browser,'clientHeight',function(){ Browser.__init__(); return Browser.window.innerHeight || Browser.document.body.clientHeight || Browser.document.documentElement.clientHeight; }); /**浏览器窗口物理宽度,其值等于clientWidth *pixelRatio,并且浏览器发生反转之后,宽高会互换。*/ __getset(1,Browser,'width',function(){ Browser.__init__(); return ((Laya.stage && Laya.stage.canvasRotation)? Browser.clientHeight :Browser.clientWidth)*Browser.pixelRatio; }); /**画布容器,用来盛放画布的容器。方便对画布进行控制*/ __getset(1,Browser,'container',function(){ Browser.__init__(); if (!Browser._container){ Browser._container=Browser.createElement("div"); Browser._container.id="layaContainer"; Browser.document.body.appendChild(Browser._container); } return Browser._container; },function(value){ Browser._container=value; }); /**浏览器原生 document 对象的引用。*/ __getset(1,Browser,'document',function(){ Browser.__init__(); return Browser._document; }); Browser.__init__=function(){ SoundManager; if (Browser._window)return; Browser._window=RunDriver.getWindow(); Browser._document=Browser.window.document; Browser._window.addEventListener('message',function(e){ laya.utils.Browser._onMessage(e); },false); /*__JS__ */Browser.document.__createElement=Browser.document.createElement; /*__JS__ */window.requestAnimationFrame=window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (c){return window.setTimeout(c,1000 / 60);};; /*__JS__ */var $BS=window.document.body.style;$BS['-webkit-user-select']='none';$BS['-webkit-tap-highlight-color']='rgba(200,200,200,0)';; Browser.userAgent=/*[SAFE]*/ Browser.window.navigator.userAgent; Browser.u=/*[SAFE]*/ Browser.userAgent; Browser.onIOS=/*[SAFE]*/ !!Browser.u.match(/\(i[^;]+;(U;)? CPU.+Mac OS X/); Browser.onMobile=/*[SAFE]*/ Browser.u.indexOf("Mobile")>-1; Browser.onIPhone=/*[SAFE]*/ Browser.u.indexOf("iPhone")>-1; Browser.onMac=/*[SAFE]*/ Browser.u.indexOf("Mac OS X")>-1; Browser.onIPad=/*[SAFE]*/ Browser.u.indexOf("iPad")>-1; Browser.onAndroid=/*[SAFE]*/ Browser.u.indexOf('Android')>-1 || Browser.u.indexOf('Adr')>-1; Browser.onWP=/*[SAFE]*/ Browser.u.indexOf("Windows Phone")>-1; Browser.onQQBrowser=/*[SAFE]*/ Browser.u.indexOf("QQBrowser")>-1; Browser.onMQQBrowser=/*[SAFE]*/ Browser.u.indexOf("MQQBrowser")>-1 || (Browser.u.indexOf("Mobile")>-1 && Browser.u.indexOf("QQ")>-1); Browser.onIE=/*[SAFE]*/ !!Browser.window.ActiveXObject || "ActiveXObject" in Browser.window; Browser.onWeiXin=/*[SAFE]*/ Browser.u.indexOf('MicroMessenger')>-1; Browser.onPC=/*[SAFE]*/ !Browser.onMobile; Browser.onSafari=/*[SAFE]*/ Browser.u.indexOf("Safari")>-1; Browser.onFirefox=/*[SAFE]*/ Browser.u.indexOf('Firefox')>-1; Browser.onEdge=/*[SAFE]*/ Browser.u.indexOf('Edge')>-1; Browser.onMiniGame=/*[SAFE]*/ Browser.u.indexOf('MiniGame')>-1; Browser.onBDMiniGame=/*[SAFE]*/ Browser.u.indexOf('SwanGame')>-1; Browser.onHWMiniGame=/*[SAFE]*/ laya.utils.Browser.window.hasOwnProperty("hbs"); if(Browser.u.indexOf('OPPO')>-1 && Browser.u.indexOf('MiniGame')>-1){ Browser.onQGMiniGame=true; Browser.onMiniGame=false; } if (laya.utils.Browser.window.hasOwnProperty("bl")&& Browser.u.indexOf('MiniGame')>-1){ Browser.onBLMiniGame=true; Browser.onMiniGame=false; } if (laya.utils.Browser.window.hasOwnProperty("qq")&& Browser.u.indexOf('MiniGame')>-1){ Browser.onQQMiniGame=true; Browser.onMiniGame=false; } if (laya.utils.Browser.window.hasOwnProperty("tt")&& Browser.u.indexOf('MiniGame')>-1){ Browser.onTTMiniGame=true; Browser.onMiniGame=false; } if(Browser.u.indexOf("VVGame")>-1) Browser.onVVMiniGame=true; Browser.onKGMiniGame=/*[SAFE]*/ Browser.u.indexOf('QuickGame')>-1; Browser.onLimixiu=/*[SAFE]*/ Browser.u.indexOf('limixiu')>-1; Browser.onIPhoneX=/iPhone/gi.test(Browser.window.navigator.userAgent)&& (Math.min(Browser.clientHeight,Browser.clientWidth)==375 && Math.max(Browser.clientHeight,Browser.clientWidth)==812); Browser.httpProtocol=/*[SAFE]*/ Browser.window.location.protocol=="http:"; if(Browser.u.indexOf('AlipayMiniGame')>-1){ Browser.onAlipayMiniGame=true; Browser.onMiniGame=false; } if ((Browser.u.indexOf('TB')>-1 || Browser.u.indexOf('Taobao')>-1 || Browser.u.indexOf('TM/')>-1)&& laya.utils.Browser.window.hasOwnProperty('my')){ Browser.onTBMiniGame=true; } if (Browser.onMiniGame && Browser.window.focus==null){ console.error("请先初始化小游戏适配库,详细教程https://ldc.layabox.com/doc/?nav=zh-ts-5-0-0"); } Browser.webAudioEnabled=/*[SAFE]*/ Browser.window["AudioContext"] || Browser.window["webkitAudioContext"] || Browser.window["mozAudioContext"] ? true :false; Browser.soundType=/*[SAFE]*/ Browser.webAudioEnabled ? "WEBAUDIOSOUND" :"AUDIOSOUND"; /*__JS__ */Sound=Browser.webAudioEnabled?WebAudioSound:AudioSound;; /*__JS__ */if (Browser.webAudioEnabled)WebAudioSound.initWebAudio();; if (!Browser.onTBMiniGame){ AudioSound._initMusicAudio(); } /*__JS__ */Browser.enableTouch=(('ontouchstart' in window)|| window.DocumentTouch && document instanceof DocumentTouch); /*__JS__ */window.focus(); /*__JS__ */SoundManager._soundClass=Sound;; SoundManager._musicClass=AudioSound; Render._mainCanvas=Render._mainCanvas || HTMLCanvas.create('2D'); if (Browser.canvas)return; Browser.canvas=HTMLCanvas.create('2D'); Browser.context=Browser.canvas.getContext('2d'); } Browser._onMessage=function(e){ if (!e.data)return; if (e.data.name=="size"){ Browser.window.innerWidth=e.data.width; Browser.window.innerHeight=e.data.height; Browser.window.__innerHeight=e.data.clientHeight; if (!Browser.document.createEvent){ console.warn("no document.createEvent"); return; }; var evt=Browser.document.createEvent("HTMLEvents"); evt.initEvent("resize",false,false); Browser.window.dispatchEvent(evt); return; } } Browser.createElement=function(type){ Browser.__init__(); return Browser.document.__createElement(type); } Browser.getElementById=function(type){ Browser.__init__(); return Browser.document.getElementById(type); } Browser.removeElement=function(ele){ if (ele && ele.parentNode)ele.parentNode.removeChild(ele); } Browser.now=function(){ return RunDriver.now(); } Browser._window=null; Browser._document=null; Browser._container=null; Browser.userAgent=null; Browser.u=null; Browser.onIOS=false; Browser.onMac=false; Browser.onMobile=false; Browser.onIPhone=false; Browser.onIPad=false; Browser.onAndroid=false; Browser.onWP=false; Browser.onQQBrowser=false; Browser.onMQQBrowser=false; Browser.onSafari=false; Browser.onFirefox=false; Browser.onEdge=false; Browser.onIE=false; Browser.onWeiXin=false; Browser.onMiniGame=false; Browser.onTTMiniGame=false; Browser.onBDMiniGame=false; Browser.onKGMiniGame=false; Browser.onQGMiniGame=false; Browser.onVVMiniGame=false; Browser.onQQMiniGame=false; Browser.onLimixiu=false; Browser.onBLMiniGame=false; Browser.onAlipayMiniGame=false; Browser.onTTMiniGame=false; Browser.onHWMiniGame=false; Browser.onTBMiniGame=false; Browser.onPC=false; Browser.httpProtocol=false; Browser.webAudioEnabled=false; Browser.soundType=null; Browser.enableTouch=false; Browser.canvas=null; Browser.context=null; Browser.onIPhoneX=false; Browser.__init$=function(){ AudioSound; WebAudioSound; } return Browser; })() /** *

    Byte 类提供用于优化读取、写入以及处理二进制数据的方法和属性。

    *

    注意: Byte 类适用于需要在字节层访问数据的高级开发人员。

    */ //class laya.utils.Byte var Byte=(function(){ function Byte(data){ /** *@private *是否为小端数据。 */ this._xd_=true; this._allocated_=8; /** *@private *原始数据。 */ //this._d_=null; /** *@private *DataView */ //this._u8d_=null; /**@private */ this._pos_=0; /**@private */ this._length=0; if (data){ this._u8d_=new Uint8Array(data); this._d_=new DataView(this._u8d_.buffer); this._length=this._d_.byteLength; }else { this.___resizeBuffer(this._allocated_); } } __class(Byte,'laya.utils.Byte'); var __proto=Byte.prototype; /**@private */ __proto.___resizeBuffer=function(len){ try { var newByteView=new Uint8Array(len); if (this._u8d_ !=null){ if (this._u8d_.length <=len)newByteView.set(this._u8d_); else newByteView.set(this._u8d_.subarray(0,len)); } this._u8d_=newByteView; this._d_=new DataView(newByteView.buffer); }catch (err){ throw "___resizeBuffer err:"+len; } } /** *

    常用于解析固定格式的字节流。

    *

    先从字节流的当前字节偏移位置处读取一个 Uint16 值,然后以此值为长度,读取此长度的字符串。

    *@return 读取的字符串。 */ __proto.getString=function(){ return this.rUTF(this.getUint16()); } /** *从字节流中 start 参数指定的位置开始,读取 len 参数指定的字节数的数据,用于创建一个 Float32Array 对象并返回此对象。 *@param start 开始位置。 *@param len 需要读取的字节长度。如果要读取的长度超过可读取范围,则只返回可读范围内的值。 *@return 读取的 Float32Array 对象。 */ __proto.getFloat32Array=function(start,len){ var end=start+len; end=(end > this._length)? this._length :end; var v=new Float32Array(this._d_.buffer.slice(start,end)); this._pos_=end; return v; } /** *从字节流中 start 参数指定的位置开始,读取 len 参数指定的字节数的数据,用于创建一个 Uint8Array 对象并返回此对象。 *@param start 开始位置。 *@param len 需要读取的字节长度。如果要读取的长度超过可读取范围,则只返回可读范围内的值。 *@return 读取的 Uint8Array 对象。 */ __proto.getUint8Array=function(start,len){ var end=start+len; end=(end > this._length)? this._length :end; var v=new Uint8Array(this._d_.buffer.slice(start,end)); this._pos_=end; return v; } /** *从字节流中 start 参数指定的位置开始,读取 len 参数指定的字节数的数据,用于创建一个 Int16Array 对象并返回此对象。 *@param start 开始读取的字节偏移量位置。 *@param len 需要读取的字节长度。如果要读取的长度超过可读取范围,则只返回可读范围内的值。 *@return 读取的 Uint8Array 对象。 */ __proto.getInt16Array=function(start,len){ var end=start+len; end=(end > this._length)? this._length :end; var v=new Int16Array(this._d_.buffer.slice(start,end)); this._pos_=end; return v; } /** *从字节流的当前字节偏移位置处读取一个 IEEE 754 单精度(32 位)浮点数。 *@return 单精度(32 位)浮点数。 */ __proto.getFloat32=function(){ if (this._pos_+4 > this._length)throw "getFloat32 error - Out of bounds"; var v=this._d_.getFloat32(this._pos_,this._xd_); this._pos_+=4; return v; } /** *从字节流的当前字节偏移量位置处读取一个 IEEE 754 双精度(64 位)浮点数。 *@return 双精度(64 位)浮点数。 */ __proto.getFloat64=function(){ if (this._pos_+8 > this._length)throw "getFloat64 error - Out of bounds"; var v=this._d_.getFloat64(this._pos_,this._xd_); this._pos_+=8; return v; } /** *在字节流的当前字节偏移量位置处写入一个 IEEE 754 单精度(32 位)浮点数。 *@param value 单精度(32 位)浮点数。 */ __proto.writeFloat32=function(value){ this.ensureWrite(this._pos_+4); this._d_.setFloat32(this._pos_,value,this._xd_); this._pos_+=4; } /** *在字节流的当前字节偏移量位置处写入一个 IEEE 754 双精度(64 位)浮点数。 *@param value 双精度(64 位)浮点数。 */ __proto.writeFloat64=function(value){ this.ensureWrite(this._pos_+8); this._d_.setFloat64(this._pos_,value,this._xd_); this._pos_+=8; } /** *从字节流的当前字节偏移量位置处读取一个 Int32 值。 *@return Int32 值。 */ __proto.getInt32=function(){ if (this._pos_+4 > this._length)throw "getInt32 error - Out of bounds"; var float=this._d_.getInt32(this._pos_,this._xd_); this._pos_+=4; return float; } /** *从字节流的当前字节偏移量位置处读取一个 Uint32 值。 *@return Uint32 值。 */ __proto.getUint32=function(){ if (this._pos_+4 > this._length)throw "getUint32 error - Out of bounds"; var v=this._d_.getUint32(this._pos_,this._xd_); this._pos_+=4; return v; } /** *在字节流的当前字节偏移量位置处写入指定的 Int32 值。 *@param value 需要写入的 Int32 值。 */ __proto.writeInt32=function(value){ this.ensureWrite(this._pos_+4); this._d_.setInt32(this._pos_,value,this._xd_); this._pos_+=4; } /** *在字节流的当前字节偏移量位置处写入 Uint32 值。 *@param value 需要写入的 Uint32 值。 */ __proto.writeUint32=function(value){ this.ensureWrite(this._pos_+4); this._d_.setUint32(this._pos_,value,this._xd_); this._pos_+=4; } /** *从字节流的当前字节偏移量位置处读取一个 Int16 值。 *@return Int16 值。 */ __proto.getInt16=function(){ if (this._pos_+2 > this._length)throw "getInt16 error - Out of bounds"; var us=this._d_.getInt16(this._pos_,this._xd_); this._pos_+=2; return us; } /** *从字节流的当前字节偏移量位置处读取一个 Uint16 值。 *@return Uint16 值。 */ __proto.getUint16=function(){ if (this._pos_+2 > this._length)throw "getUint16 error - Out of bounds"; var us=this._d_.getUint16(this._pos_,this._xd_); this._pos_+=2; return us; } /** *在字节流的当前字节偏移量位置处写入指定的 Uint16 值。 *@param value 需要写入的Uint16 值。 */ __proto.writeUint16=function(value){ this.ensureWrite(this._pos_+2); this._d_.setUint16(this._pos_,value,this._xd_); this._pos_+=2; } /** *在字节流的当前字节偏移量位置处写入指定的 Int16 值。 *@param value 需要写入的 Int16 值。 */ __proto.writeInt16=function(value){ this.ensureWrite(this._pos_+2); this._d_.setInt16(this._pos_,value,this._xd_); this._pos_+=2; } /** *从字节流的当前字节偏移量位置处读取一个 Uint8 值。 *@return Uint8 值。 */ __proto.getUint8=function(){ if (this._pos_+1 > this._length)throw "getUint8 error - Out of bounds"; return this._d_.getUint8(this._pos_++); } /** *在字节流的当前字节偏移量位置处写入指定的 Uint8 值。 *@param value 需要写入的 Uint8 值。 */ __proto.writeUint8=function(value){ this.ensureWrite(this._pos_+1); this._d_.setUint8(this._pos_,value); this._pos_++; } /** *@private *从字节流的指定字节偏移量位置处读取一个 Uint8 值。 *@param pos 字节读取位置。 *@return Uint8 值。 */ __proto._getUInt8=function(pos){ return this._d_.getUint8(pos); } /** *@private *从字节流的指定字节偏移量位置处读取一个 Uint16 值。 *@param pos 字节读取位置。 *@return Uint16 值。 */ __proto._getUint16=function(pos){ return this._d_.getUint16(pos,this._xd_); } /** *@private *使用 getFloat32()读取6个值,用于创建并返回一个 Matrix 对象。 *@return Matrix 对象。 */ __proto._getMatrix=function(){ var rst=new Matrix(this.getFloat32(),this.getFloat32(),this.getFloat32(),this.getFloat32(),this.getFloat32(),this.getFloat32()); return rst; } /** *@private *读取指定长度的 UTF 型字符串。 *@param len 需要读取的长度。 *@return 读取的字符串。 */ __proto.rUTF=function(len){ var v="",max=this._pos_+len,c=0,c2=0,c3=0,f=String.fromCharCode; var u=this._u8d_,i=0; while (this._pos_ < max){ c=u[this._pos_++]; if (c < 0x80){ if (c !=0){ v+=f(c); } }else if (c < 0xE0){ v+=f(((c & 0x3F)<< 6)| (u[this._pos_++] & 0x7F)); }else if (c < 0xF0){ c2=u[this._pos_++]; v+=f(((c & 0x1F)<< 12)| ((c2 & 0x7F)<< 6)| (u[this._pos_++] & 0x7F)); }else { c2=u[this._pos_++]; c3=u[this._pos_++]; v+=f(((c & 0x0F)<< 18)| ((c2 & 0x7F)<< 12)| ((c3 << 6)& 0x7F)| (u[this._pos_++] & 0x7F)); } i++; } return v; } /** *@private *读取 len 参数指定的长度的字符串。 *@param len 要读取的字符串的长度。 *@return 指定长度的字符串。 */ __proto.getCustomString=function(len){ var v="",ulen=0,c=0,c2=0,f=String.fromCharCode; var u=this._u8d_,i=0; while (len > 0){ c=u[this._pos_]; if (c < 0x80){ v+=f(c); this._pos_++; len--; }else { ulen=c-0x80; this._pos_++; len-=ulen; while (ulen > 0){ c=u[this._pos_++]; c2=u[this._pos_++]; v+=f((c2 << 8)| c); ulen--; } } } return v; } /** *清除字节数组的内容,并将 length 和 pos 属性重置为 0。调用此方法将释放 Byte 实例占用的内存。 */ __proto.clear=function(){ this._pos_=0; this.length=0; } /** *@private *获取此对象的 ArrayBuffer 引用。 *@return */ __proto.__getBuffer=function(){ return this._d_.buffer; } /** *

    将 UTF-8 字符串写入字节流。类似于 writeUTF()方法,但 writeUTFBytes()不使用 16 位长度的字为字符串添加前缀。

    *

    对应的读取方法为: getUTFBytes 。

    *@param value 要写入的字符串。 */ __proto.writeUTFBytes=function(value){ value=value+""; for (var i=0,sz=value.length;i < sz;i++){ var c=value.charCodeAt(i); if (c <=0x7F){ this.writeByte(c); }else if (c <=0x7FF){ this.ensureWrite(this._pos_+2); this._u8d_.set([0xC0 | (c >> 6),0x80 | (c & 0x3F)],this._pos_); this._pos_+=2; }else if (c <=0xFFFF){ this.ensureWrite(this._pos_+3); this._u8d_.set([0xE0 | (c >> 12),0x80 | ((c >> 6)& 0x3F),0x80 | (c & 0x3F)],this._pos_); this._pos_+=3; }else { this.ensureWrite(this._pos_+4); this._u8d_.set([0xF0 | (c >> 18),0x80 | ((c >> 12)& 0x3F),0x80 | ((c >> 6)& 0x3F),0x80 | (c & 0x3F)],this._pos_); this._pos_+=4; } } } /** *

    将 UTF-8 字符串写入字节流。先写入以字节表示的 UTF-8 字符串长度(作为 16 位整数),然后写入表示字符串字符的字节。

    *

    对应的读取方法为: getUTFString 。

    *@param value 要写入的字符串值。 */ __proto.writeUTFString=function(value){ var tPos=this.pos; this.writeUint16(1); this.writeUTFBytes(value); var dPos=this.pos-tPos-2; if (dPos >=65536){ throw "writeUTFString byte len more than 65536"; } this._d_.setUint16(tPos,dPos,this._xd_); } /** *@private *读取 UTF-8 字符串。 *@return 读取的字符串。 */ __proto.readUTFString=function(){ return this.readUTFBytes(this.getUint16()); } /** *

    从字节流中读取一个 UTF-8 字符串。假定字符串的前缀是一个无符号的短整型(以此字节表示要读取的长度)。

    *

    对应的写入方法为: writeUTFString 。

    *@return 读取的字符串。 */ __proto.getUTFString=function(){ return this.readUTFString(); } /** *@private *读字符串,必须是 writeUTFBytes 方法写入的字符串。 *@param len 要读的buffer长度,默认将读取缓冲区全部数据。 *@return 读取的字符串。 */ __proto.readUTFBytes=function(len){ (len===void 0)&& (len=-1); if (len==0)return ""; var lastBytes=this.bytesAvailable; if (len > lastBytes)throw "readUTFBytes error - Out of bounds"; len=len > 0 ? len :lastBytes; return this.rUTF(len); } /** *

    从字节流中读取一个由 length 参数指定的长度的 UTF-8 字节序列,并返回一个字符串。

    *

    一般读取的是由 writeUTFBytes 方法写入的字符串。

    *@param len 要读的buffer长度,默认将读取缓冲区全部数据。 *@return 读取的字符串。 */ __proto.getUTFBytes=function(len){ (len===void 0)&& (len=-1); return this.readUTFBytes(len); } /** *

    在字节流中写入一个字节。

    *

    使用参数的低 8 位。忽略高 24 位。

    *@param value */ __proto.writeByte=function(value){ this.ensureWrite(this._pos_+1); this._d_.setInt8(this._pos_,value); this._pos_+=1; } /** *@private *从字节流中读取带符号的字节。 */ __proto.readByte=function(){ if (this._pos_+1 > this._length)throw "readByte error - Out of bounds"; return this._d_.getInt8(this._pos_++); } /** *

    从字节流中读取带符号的字节。

    *

    返回值的范围是从-128 到 127。

    *@return 介于-128 和 127 之间的整数。 */ __proto.getByte=function(){ return this.readByte(); } /** *

    保证该字节流的可用长度不小于 lengthToEnsure 参数指定的值。

    *@param lengthToEnsure 指定的长度。 */ __proto.ensureWrite=function(lengthToEnsure){ if (this._length < lengthToEnsure)this._length=lengthToEnsure; if (this._allocated_ < lengthToEnsure)this.length=lengthToEnsure; } /** *

    将指定 arraybuffer 对象中的以 offset 为起始偏移量, length 为长度的字节序列写入字节流。

    *

    如果省略 length 参数,则使用默认长度 0,该方法将从 offset 开始写入整个缓冲区;如果还省略了 offset 参数,则写入整个缓冲区。

    *

    如果 offset 或 length 小于0,本函数将抛出异常。

    *$NEXTBIG 由于没有判断length和arraybuffer的合法性,当开发者填写了错误的length值时,会导致写入多余的空白数据甚至内存溢出,为了避免影响开发者正在使用此方法的功能,下个重大版本会修复这些问题。 *@param arraybuffer 需要写入的 Arraybuffer 对象。 *@param offset Arraybuffer 对象的索引的偏移量(以字节为单位) *@param length 从 Arraybuffer 对象写入到 Byte 对象的长度(以字节为单位) */ __proto.writeArrayBuffer=function(arraybuffer,offset,length){ (offset===void 0)&& (offset=0); (length===void 0)&& (length=0); if (offset < 0 || length < 0)throw "writeArrayBuffer error - Out of bounds"; if (length==0)length=arraybuffer.byteLength-offset; this.ensureWrite(this._pos_+length); var uint8array=new Uint8Array(arraybuffer); this._u8d_.set(uint8array.subarray(offset,offset+length),this._pos_); this._pos_+=length; } /** *读取ArrayBuffer数据 *@param length *@return */ __proto.readArrayBuffer=function(length){ var rst; rst=this._u8d_.buffer.slice(this._pos_,this._pos_+length); this._pos_=this._pos_+length return rst; } /** *获取此对象的 ArrayBuffer 数据,数据只包含有效数据部分。 */ __getset(0,__proto,'buffer',function(){ var rstBuffer=this._d_.buffer; if (rstBuffer.byteLength==this.length)return rstBuffer; return rstBuffer.slice(0,this.length); }); /** *

    Byte 实例的字节序。取值为:BIG_ENDIANBIG_ENDIAN

    *

    主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。通过 getSystemEndian 可以获取当前系统的字节序。

    *

    BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。
    *LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。

    */ __getset(0,__proto,'endian',function(){ return this._xd_ ? "littleEndian" :"bigEndian"; },function(endianStr){ this._xd_=(endianStr=="littleEndian"); }); /** *

    Byte 对象的长度(以字节为单位)。

    *

    如果将长度设置为大于当前长度的值,则用零填充字节数组的右侧;如果将长度设置为小于当前长度的值,将会截断该字节数组。

    *

    如果要设置的长度大于当前已分配的内存空间的字节长度,则重新分配内存空间,大小为以下两者较大者:要设置的长度、当前已分配的长度的2倍,并将原有数据拷贝到新的内存空间中;如果要设置的长度小于当前已分配的内存空间的字节长度,也会重新分配内存空间,大小为要设置的长度,并将原有数据从头截断为要设置的长度存入新的内存空间中。

    */ __getset(0,__proto,'length',function(){ return this._length; },function(value){ if (this._allocated_ < value) this.___resizeBuffer(this._allocated_=Math.floor(Math.max(value,this._allocated_ *2))); else if (this._allocated_ > value) this.___resizeBuffer(this._allocated_=value); this._length=value; }); /** *移动或返回 Byte 对象的读写指针的当前位置(以字节为单位)。下一次调用读取方法时将在此位置开始读取,或者下一次调用写入方法时将在此位置开始写入。 */ __getset(0,__proto,'pos',function(){ return this._pos_; },function(value){ this._pos_=value; }); /** *可从字节流的当前位置到末尾读取的数据的字节数。 */ __getset(0,__proto,'bytesAvailable',function(){ return this._length-this._pos_; }); Byte.getSystemEndian=function(){ if (!Byte._sysEndian){ var buffer=new ArrayBuffer(2); new DataView(buffer).setInt16(0,256,true); Byte._sysEndian=(new Int16Array(buffer))[0]===256 ? /*CLASS CONST:laya.utils.Byte.LITTLE_ENDIAN*/"littleEndian" :/*CLASS CONST:laya.utils.Byte.BIG_ENDIAN*/"bigEndian"; } return Byte._sysEndian; } Byte.BIG_ENDIAN="bigEndian"; Byte.LITTLE_ENDIAN="littleEndian"; Byte._sysEndian=null; return Byte; })() /** *@private *对象缓存统一管理类 */ //class laya.utils.CacheManager var CacheManager=(function(){ function CacheManager(){} __class(CacheManager,'laya.utils.CacheManager'); CacheManager.regCacheByFunction=function(disposeFunction,getCacheListFunction){ CacheManager.unRegCacheByFunction(disposeFunction,getCacheListFunction); var cache; cache={tryDispose:disposeFunction,getCacheList:getCacheListFunction}; CacheManager._cacheList.push(cache); } CacheManager.unRegCacheByFunction=function(disposeFunction,getCacheListFunction){ var i=0,len=0; len=CacheManager._cacheList.length; for (i=0;i < len;i++){ if (CacheManager._cacheList[i].tryDispose==disposeFunction && CacheManager._cacheList[i].getCacheList==getCacheListFunction){ CacheManager._cacheList.splice(i,1); return; } } } CacheManager.forceDispose=function(){ var i=0,len=CacheManager._cacheList.length; for (i=0;i < len;i++){ CacheManager._cacheList[i].tryDispose(true); } } CacheManager.beginCheck=function(waitTime){ (waitTime===void 0)&& (waitTime=15000); Laya.timer.loop(waitTime,null,CacheManager._checkLoop); } CacheManager.stopCheck=function(){ Laya.timer.clear(null,CacheManager._checkLoop); } CacheManager._checkLoop=function(){ var cacheList=CacheManager._cacheList; if (cacheList.length < 1)return; var tTime=Browser.now(); var count=0; var len=0; len=count=cacheList.length; while (count > 0){ CacheManager._index++; CacheManager._index=CacheManager._index % len; cacheList[CacheManager._index].tryDispose(false); if (Browser.now()-tTime > CacheManager.loopTimeLimit)break ; count--; } } CacheManager.loopTimeLimit=2; CacheManager._cacheList=[]; CacheManager._index=0; return CacheManager; })() /** *ClassUtils 是一个类工具类。 */ //class laya.utils.ClassUtils var ClassUtils=(function(){ function ClassUtils(){} __class(ClassUtils,'laya.utils.ClassUtils'); ClassUtils.regClass=function(className,classDef){ ClassUtils._classMap[className]=classDef; } ClassUtils.getRegClass=function(className){ return ClassUtils._classMap[className]; } ClassUtils.getInstance=function(className){ var compClass=ClassUtils.getClass(className); if (compClass) return new compClass(); else console.warn("[error] Undefined class:",className); return null; } ClassUtils.createByJson=function(json,node,root,customHandler,instanceHandler){ if ((typeof json=='string')) json=JSON.parse(json); var props=json.props; if (!node){ node=instanceHandler ? instanceHandler.runWith(json):ClassUtils.getInstance(props.runtime || json.type); if (!node) return null; }; var child=json.child; if (child){ for (var i=0,n=child.length;i < n;i++){ var data=child[i]; if ((data.props.name==="render" || data.props.renderType==="render")&& node["_$set_itemRender"]) node.itemRender=data; else { if (data.type=="Graphic"){ ClassUtils.addGraphicsToSprite(data,node); }else if (ClassUtils.isDrawType(data.type)){ ClassUtils.addGraphicToSprite(data,node,true); }else { var tChild=ClassUtils.createByJson(data,null,root,customHandler,instanceHandler) if (data.type=="Script"){ if (tChild.hasOwnProperty("owner")){ tChild["owner"]=node; }else if (tChild.hasOwnProperty("target")){ tChild["target"]=node; } }else if (data.props.renderType=="mask"){ node.mask=tChild; }else { node.addChild(tChild); } } } } } if (props){ for (var prop in props){ var value=props[prop]; if (prop==="var" && root){ root[value]=node; }else if ((value instanceof Array)&& (typeof (node[prop])=='function')){ node[prop].apply(node,value); }else { node[prop]=value; } } } if (customHandler && json.customProps){ customHandler.runWith([node,json]); } if (node["created"]) node.created(); return node; } ClassUtils.addGraphicsToSprite=function(graphicO,sprite){ var graphics; graphics=graphicO.child; if (!graphics || graphics.length < 1) return; var g; g=ClassUtils._getGraphicsFromSprite(graphicO,sprite); var ox=0; var oy=0; if (graphicO.props){ ox=ClassUtils._getObjVar(graphicO.props,"x",0); oy=ClassUtils._getObjVar(graphicO.props,"y",0); } if (ox !=0 && oy !=0){ g.translate(ox,oy); }; var i=0,len=0; len=graphics.length; for (i=0;i < len;i++){ ClassUtils._addGraphicToGraphics(graphics[i],g); } if (ox !=0 && oy !=0){ g.translate(-ox,-oy); } } ClassUtils.addGraphicToSprite=function(graphicO,sprite,isChild){ (isChild===void 0)&& (isChild=false); var g; g=isChild ? ClassUtils._getGraphicsFromSprite(graphicO,sprite):sprite.graphics; ClassUtils._addGraphicToGraphics(graphicO,g); } ClassUtils._getGraphicsFromSprite=function(dataO,sprite){ var g; if (!dataO || !dataO.props) return sprite.graphics; var propsName; propsName=dataO.props.renderType; switch (propsName){ case "hit": case "unHit":; var hitArea; if (!sprite.hitArea){ sprite.hitArea=new HitArea(); } hitArea=sprite.hitArea; if (!hitArea[propsName]){ hitArea[propsName]=new Graphics(); } g=hitArea[propsName]; break ; default : } if (!g) g=sprite.graphics; return g; } ClassUtils._getTransformData=function(propsO){ var m; if (propsO.hasOwnProperty("pivotX")|| propsO.hasOwnProperty("pivotY")){ m=m || new Matrix(); m.translate(-ClassUtils._getObjVar(propsO,"pivotX",0),-ClassUtils._getObjVar(propsO,"pivotY",0)); }; var sx=ClassUtils._getObjVar(propsO,"scaleX",1),sy=ClassUtils._getObjVar(propsO,"scaleY",1); var rotate=ClassUtils._getObjVar(propsO,"rotation",0); var skewX=ClassUtils._getObjVar(propsO,"skewX",0); var skewY=ClassUtils._getObjVar(propsO,"skewY",0); if (sx !=1 || sy !=1 || rotate !=0){ m=m || new Matrix(); m.scale(sx,sy); m.rotate(rotate *0.0174532922222222); } return m; } ClassUtils._addGraphicToGraphics=function(graphicO,graphic){ var propsO; propsO=graphicO.props; if (!propsO) return; var drawConfig; drawConfig=ClassUtils.DrawTypeDic[graphicO.type]; if (!drawConfig) return; var g; g=graphic; var m; var params=ClassUtils._getParams(propsO,drawConfig[1],drawConfig[2],drawConfig[3]); m=ClassUtils._tM; if (m || ClassUtils._alpha !=1){ g.save(); if (m) g.transform(m); if (ClassUtils._alpha !=1) g.alpha(ClassUtils._alpha); } g[drawConfig[0]].apply(g,params); if (m || ClassUtils._alpha !=1){ g.restore(); } } ClassUtils._adptLineData=function(params){ params[2]=parseFloat(params[0])+parseFloat(params[2]); params[3]=parseFloat(params[1])+parseFloat(params[3]); return params; } ClassUtils._adptTextureData=function(params){ params[0]=Loader.getRes(params[0]); return params; } ClassUtils._adptLinesData=function(params){ params[2]=ClassUtils._getPointListByStr(params[2]); return params; } ClassUtils.isDrawType=function(type){ if (type=="Image") return false; return ClassUtils.DrawTypeDic.hasOwnProperty(type); } ClassUtils._getParams=function(obj,params,xPos,adptFun){ (xPos===void 0)&& (xPos=0); var rst; rst=ClassUtils._temParam; rst.length=params.length; var i=0,len=0; len=params.length; for (i=0;i < len;i++){ rst[i]=ClassUtils._getObjVar(obj,params[i][0],params[i][1]); } ClassUtils._alpha=ClassUtils._getObjVar(obj,"alpha",1); var m; m=ClassUtils._getTransformData(obj); if (m){ if (!xPos)xPos=0; m.translate(rst[xPos],rst[xPos+1]); rst[xPos]=rst[xPos+1]=0; ClassUtils._tM=m; }else { ClassUtils._tM=null; } if (adptFun && ClassUtils[adptFun]){ rst=ClassUtils[adptFun](rst); } return rst; } ClassUtils._getPointListByStr=function(str){ var pointArr; pointArr=str.split(","); var i=0,len=0; len=pointArr.length; for (i=0;i < len;i++){ pointArr[i]=parseFloat(pointArr[i]); } return pointArr; } ClassUtils._getObjVar=function(obj,key,noValue){ if (obj.hasOwnProperty(key)){ return obj[key]; } return noValue; } ClassUtils._temParam=[]; ClassUtils._classMap={'Sprite':'laya.display.Sprite','Text':'laya.display.Text','Animation':'laya.display.Animation','Skeleton':'laya.ani.bone.Skeleton','Particle2D':'laya.particle.Particle2D','div':'laya.html.dom.HTMLDivElement','p':'laya.html.dom.HTMLElement','img':'laya.html.dom.HTMLImageElement','span':'laya.html.dom.HTMLElement','br':'laya.html.dom.HTMLBrElement','style':'laya.html.dom.HTMLStyleElement','font':'laya.html.dom.HTMLElement','a':'laya.html.dom.HTMLElement','#text':'laya.html.dom.HTMLElement'}; ClassUtils.getClass=function(className){ var classObject=ClassUtils._classMap[className] || className; if ((typeof classObject=='string')) return Laya["__classmap"][classObject]; return classObject; } ClassUtils._tM=null; ClassUtils._alpha=NaN; __static(ClassUtils, ['DrawTypeDic',function(){return this.DrawTypeDic={"Rect":["drawRect",[["x",0],["y",0],["width",0],["height",0],["fillColor",null],["lineColor",null],["lineWidth",1]]],"Circle":["drawCircle",[["x",0],["y",0],["radius",0],["fillColor",null],["lineColor",null],["lineWidth",1]]],"Pie":["drawPie",[["x",0],["y",0],["radius",0],["startAngle",0],["endAngle",0],["fillColor",null],["lineColor",null],["lineWidth",1]]],"Image":["drawTexture",[["x",0],["y",0],["width",0],["height",0]]],"Texture":["drawTexture",[["skin",null],["x",0],["y",0],["width",0],["height",0]],1,"_adptTextureData"],"FillTexture":["fillTexture",[["skin",null],["x",0],["y",0],["width",0],["height",0],["repeat",null]],1,"_adptTextureData"],"FillText":["fillText",[["text",""],["x",0],["y",0],["font",null],["color",null],["textAlign",null]],1],"Line":["drawLine",[["x",0],["y",0],["toX",0],["toY",0],["lineColor",null],["lineWidth",0]],0,"_adptLineData"],"Lines":["drawLines",[["x",0],["y",0],["points",""],["lineColor",null],["lineWidth",0]],0,"_adptLinesData"],"Curves":["drawCurves",[["x",0],["y",0],["points",""],["lineColor",null],["lineWidth",0]],0,"_adptLinesData"],"Poly":["drawPoly",[["x",0],["y",0],["points",""],["fillColor",null],["lineColor",null],["lineWidth",1]],0,"_adptLinesData"]};} ]); return ClassUtils; })() /** *@private *Color 是一个颜色值处理类。 */ //class laya.utils.Color var Color=(function(){ function Color(str){ /**@private */ this._color=[]; /**字符串型颜色值。*/ //this.strColor=null; /**uint 型颜色值。*/ //this.numColor=0; //this._drawStyle=null; if ((typeof str=='string')){ this.strColor=str; if (str===null)str="#000000"; str.charAt(0)=='#' && (str=str.substr(1)); var len=str.length; if (len==3 || len==4){ var temp=""; for (var i=0;i < len;i++){ temp+=(str[i]+str[i]); } str=temp; }; var color=this.numColor=parseInt(str,16); var flag=(str.length==8); if (flag){ this._color=[parseInt(str.substr(0,2),16)/ 255,((0x00FF0000 & color)>> 16)/ 255,((0x0000FF00 & color)>> 8)/ 255,(0x000000FF & color)/ 255]; return; } }else { color=this.numColor=str; this.strColor=Utils.toHexColor(color); } this._color=[((0xFF0000 & color)>> 16)/ 255,((0xFF00 & color)>> 8)/ 255,(0xFF & color)/ 255,1]; (this._color).__id=++Color._COLODID; } __class(Color,'laya.utils.Color'); Color._initDefault=function(){ Color._DEFAULT={}; for (var i in Color._COLOR_MAP)Color._SAVE[i]=Color._DEFAULT[i]=new Color(Color._COLOR_MAP[i]); return Color._DEFAULT; } Color._initSaveMap=function(){ Color._SAVE_SIZE=0; Color._SAVE={}; for (var i in Color._DEFAULT)Color._SAVE[i]=Color._DEFAULT[i]; } Color.create=function(str){ var color=Color._SAVE[str+""]; if (color !=null)return color; (Color._SAVE_SIZE < 1000)|| Color._initSaveMap(); return Color._SAVE[str+""]=new Color(str); } Color._SAVE={}; Color._SAVE_SIZE=0; Color._COLOR_MAP={"white":'#FFFFFF',"red":'#FF0000',"green":'#00FF00',"blue":'#0000FF',"black":'#000000',"yellow":'#FFFF00','gray':'#AAAAAA'}; Color._DEFAULT=Color._initDefault(); Color._COLODID=1; return Color; })() /** *Dictionary 是一个字典型的数据存取类。 */ //class laya.utils.Dictionary var Dictionary=(function(){ function Dictionary(){ this._values=[]; this._keys=[]; } __class(Dictionary,'laya.utils.Dictionary'); var __proto=Dictionary.prototype; /** *给指定的键名设置值。 *@param key 键名。 *@param value 值。 */ __proto.set=function(key,value){ var index=this.indexOf(key); if (index >=0){ this._values[index]=value; return; } this._keys.push(key); this._values.push(value); } /** *获取指定对象的键名索引。 *@param key 键名对象。 *@return 键名索引。 */ __proto.indexOf=function(key){ var index=this._keys.indexOf(key); if (index >=0)return index; key=((typeof key=='string'))? Number(key):(((typeof key=='number'))? key.toString():key); return this._keys.indexOf(key); } /** *返回指定键名的值。 *@param key 键名对象。 *@return 指定键名的值。 */ __proto.get=function(key){ var index=this.indexOf(key); return index < 0 ? null :this._values[index]; } /** *移除指定键名的值。 *@param key 键名对象。 *@return 是否成功移除。 */ __proto.remove=function(key){ var index=this.indexOf(key); if (index >=0){ this._keys.splice(index,1); this._values.splice(index,1); return true; } return false; } /** *清除此对象的键名列表和键值列表。 */ __proto.clear=function(){ this._values.length=0; this._keys.length=0; } /** *获取所有的子元素列表。 */ __getset(0,__proto,'values',function(){ return this._values; }); /** *获取所有的子元素键名列表。 */ __getset(0,__proto,'keys',function(){ return this._keys; }); return Dictionary; })() /** *@private *Dragging 类是触摸滑动控件。 */ //class laya.utils.Dragging var Dragging=(function(){ function Dragging(){ /**被拖动的对象。*/ //this.target=null; /**缓动衰减系数。*/ this.ratio=0.92; /**单帧最大偏移量。*/ this.maxOffset=60; /**滑动范围。*/ //this.area=null; /**表示拖动是否有惯性。*/ //this.hasInertia=false; /**橡皮筋最大值。*/ //this.elasticDistance=NaN; /**橡皮筋回弹时间,单位为毫秒。*/ //this.elasticBackTime=NaN; /**事件携带数据。*/ //this.data=null; this._dragging=false; this._clickOnly=true; //this._elasticRateX=NaN; //this._elasticRateY=NaN; //this._lastX=NaN; //this._lastY=NaN; //this._offsetX=NaN; //this._offsetY=NaN; //this._offsets=null; //this._disableMouseEvent=false; //this._tween=null; //this._parent=null; } __class(Dragging,'laya.utils.Dragging'); var __proto=Dragging.prototype; /** *开始拖拽。 *@param target 待拖拽的 Sprite 对象。 *@param area 滑动范围。 *@param hasInertia 拖动是否有惯性。 *@param elasticDistance 橡皮筋最大值。 *@param elasticBackTime 橡皮筋回弹时间,单位为毫秒。 *@param data 事件携带数据。 *@param disableMouseEvent 鼠标事件是否有效。 *@param ratio 惯性阻尼系数 */ __proto.start=function(target,area,hasInertia,elasticDistance,elasticBackTime,data,disableMouseEvent,ratio){ (ratio===void 0)&& (ratio=0.92); this.clearTimer(); this.target=target; this.area=area; this.hasInertia=hasInertia; this.elasticDistance=area ? elasticDistance :0; this.elasticBackTime=elasticBackTime; this.data=data; this._disableMouseEvent=disableMouseEvent; this.ratio=ratio; this._parent=target.parent; this._clickOnly=true; this._dragging=true; this._elasticRateX=this._elasticRateY=1; this._lastX=this._parent.mouseX; this._lastY=this._parent.mouseY; Laya.stage.on(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.onStageMouseUp); Laya.stage.on(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.onStageMouseUp); Laya.timer.frameLoop(1,this,this.loop); } /** *清除计时器。 */ __proto.clearTimer=function(){ Laya.timer.clear(this,this.loop); Laya.timer.clear(this,this.tweenMove); if (this._tween){ this._tween.recover(); this._tween=null; } } /** *停止拖拽。 */ __proto.stop=function(){ if (this._dragging){ MouseManager.instance.disableMouseEvent=false; Laya.stage.off(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.onStageMouseUp); Laya.stage.off(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.onStageMouseUp); this._dragging=false; this.target && this.area && this.backToArea(); this.clear(); } } /** *拖拽的循环处理函数。 */ __proto.loop=function(){ var point=this._parent.getMousePoint(); var mouseX=point.x; var mouseY=point.y; var offsetX=mouseX-this._lastX; var offsetY=mouseY-this._lastY; if (this._clickOnly){ if (Math.abs(offsetX *Laya.stage._canvasTransform.getScaleX())> 1 || Math.abs(offsetY *Laya.stage._canvasTransform.getScaleY())> 1){ this._clickOnly=false; this._offsets || (this._offsets=[]); this._offsets.length=0; this.target.event(/*laya.events.Event.DRAG_START*/"dragstart",this.data); MouseManager.instance.disableMouseEvent=this._disableMouseEvent; this.target._set$P("$_MOUSEDOWN",false); }else return; }else { this._offsets.push(offsetX,offsetY); } if (offsetX===0 && offsetY===0)return; this._lastX=mouseX; this._lastY=mouseY; this.target.x+=offsetX *this._elasticRateX; this.target.y+=offsetY *this._elasticRateY; this.area && this.checkArea(); this.target.event(/*laya.events.Event.DRAG_MOVE*/"dragmove",this.data); } /** *拖拽区域检测。 */ __proto.checkArea=function(){ if (this.elasticDistance <=0){ this.backToArea(); }else { if (this.target.x < this.area.x){ var offsetX=this.area.x-this.target.x; }else if (this.target.x > this.area.x+this.area.width){ offsetX=this.target.x-this.area.x-this.area.width; }else { offsetX=0; } this._elasticRateX=Math.max(0,1-(offsetX / this.elasticDistance)); if (this.target.y < this.area.y){ var offsetY=this.area.y-this.target.y; }else if (this.target.y > this.area.y+this.area.height){ offsetY=this.target.y-this.area.y-this.area.height; }else { offsetY=0; } this._elasticRateY=Math.max(0,1-(offsetY / this.elasticDistance)); } } /** *移动至设定的拖拽区域。 */ __proto.backToArea=function(){ this.target.x=Math.min(Math.max(this.target.x,this.area.x),this.area.x+this.area.width); this.target.y=Math.min(Math.max(this.target.y,this.area.y),this.area.y+this.area.height); } /** *舞台的抬起事件侦听函数。 *@param e Event 对象。 */ __proto.onStageMouseUp=function(e){ MouseManager.instance.disableMouseEvent=false; Laya.stage.off(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.onStageMouseUp); Laya.stage.off(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.onStageMouseUp); Laya.timer.clear(this,this.loop); if (this._clickOnly || !this.target)return; if (this.hasInertia){ if (this._offsets.length < 1){ this._offsets.push(this._parent.mouseX-this._lastX,this._parent.mouseY-this._lastY); } this._offsetX=this._offsetY=0; var len=this._offsets.length; var n=Math.min(len,6); var m=this._offsets.length-n; for (var i=len-1;i > m;i--){ this._offsetY+=this._offsets[i--]; this._offsetX+=this._offsets[i]; } this._offsetX=this._offsetX / n *2; this._offsetY=this._offsetY / n *2; if (Math.abs(this._offsetX)> this.maxOffset)this._offsetX=this._offsetX > 0 ? this.maxOffset :-this.maxOffset; if (Math.abs(this._offsetY)> this.maxOffset)this._offsetY=this._offsetY > 0 ? this.maxOffset :-this.maxOffset; Laya.timer.frameLoop(1,this,this.tweenMove); }else if (this.elasticDistance > 0){ this.checkElastic(); }else { this.clear(); } } /** *橡皮筋效果检测。 */ __proto.checkElastic=function(){ var tx=NaN; var ty=NaN; if (this.target.x < this.area.x)tx=this.area.x; else if (this.target.x > this.area.x+this.area.width)tx=this.area.x+this.area.width; if (this.target.y < this.area.y)ty=this.area.y; else if (this.target.y > this.area.y+this.area.height)ty=this.area.y+this.area.height; if (!isNaN(tx)|| !isNaN(ty)){ var obj={}; if (!isNaN(tx))obj.x=tx; if (!isNaN(ty))obj.y=ty; this._tween=Tween.to(this.target,obj,this.elasticBackTime,Ease.sineOut,Handler.create(this,this.clear),0,false,false); }else { this.clear(); } } /** *移动。 */ __proto.tweenMove=function(){ this._offsetX *=this.ratio *this._elasticRateX; this._offsetY *=this.ratio *this._elasticRateY; this.target.x+=this._offsetX; this.target.y+=this._offsetY; this.area && this.checkArea(); this.target.event(/*laya.events.Event.DRAG_MOVE*/"dragmove",this.data); if ((Math.abs(this._offsetX)< 1 && Math.abs(this._offsetY)< 1)|| this._elasticRateX < 0.5 || this._elasticRateY < 0.5){ Laya.timer.clear(this,this.tweenMove); if (this.elasticDistance > 0)this.checkElastic(); else this.clear(); } } /** *结束拖拽。 */ __proto.clear=function(){ if (this.target){ this.clearTimer(); var sp=this.target; this.target=null; this._parent=null; sp.event(/*laya.events.Event.DRAG_END*/"dragend",this.data); } } return Dragging; })() /** *Ease 类定义了缓动函数,以便实现 Tween 动画的缓动效果。 */ //class laya.utils.Ease var Ease=(function(){ function Ease(){} __class(Ease,'laya.utils.Ease'); Ease.linearNone=function(t,b,c,d){ return c *t / d+b; } Ease.linearIn=function(t,b,c,d){ return c *t / d+b; } Ease.linearInOut=function(t,b,c,d){ return c *t / d+b; } Ease.linearOut=function(t,b,c,d){ return c *t / d+b; } Ease.bounceIn=function(t,b,c,d){ return c-Ease.bounceOut(d-t,0,c,d)+b; } Ease.bounceInOut=function(t,b,c,d){ if (t < d *0.5)return Ease.bounceIn(t *2,0,c,d)*.5+b; else return Ease.bounceOut(t *2-d,0,c,d)*.5+c *.5+b; } Ease.bounceOut=function(t,b,c,d){ if ((t /=d)< (1 / 2.75))return c *(7.5625 *t *t)+b; else if (t < (2 / 2.75))return c *(7.5625 *(t-=(1.5 / 2.75))*t+.75)+b; else if (t < (2.5 / 2.75))return c *(7.5625 *(t-=(2.25 / 2.75))*t+.9375)+b; else return c *(7.5625 *(t-=(2.625 / 2.75))*t+.984375)+b; } Ease.backIn=function(t,b,c,d,s){ (s===void 0)&& (s=1.70158); return c *(t /=d)*t *((s+1)*t-s)+b; } Ease.backInOut=function(t,b,c,d,s){ (s===void 0)&& (s=1.70158); if ((t /=d *0.5)< 1)return c *0.5 *(t *t *(((s *=(1.525))+1)*t-s))+b; return c / 2 *((t-=2)*t *(((s *=(1.525))+1)*t+s)+2)+b; } Ease.backOut=function(t,b,c,d,s){ (s===void 0)&& (s=1.70158); return c *((t=t / d-1)*t *((s+1)*t+s)+1)+b; } Ease.elasticIn=function(t,b,c,d,a,p){ (a===void 0)&& (a=0); (p===void 0)&& (p=0); var s; if (t==0)return b; if ((t /=d)==1)return b+c; if (!p)p=d *.3; if (!a || (c > 0 && a < c)|| (c < 0 && a <-c)){ a=c; s=p / 4; }else s=p / Ease.PI2 *Math.asin(c / a); return-(a *Math.pow(2,10 *(t-=1))*Math.sin((t *d-s)*Ease.PI2 / p))+b; } Ease.elasticInOut=function(t,b,c,d,a,p){ (a===void 0)&& (a=0); (p===void 0)&& (p=0); var s; if (t==0)return b; if ((t /=d *0.5)==2)return b+c; if (!p)p=d *(.3 *1.5); if (!a || (c > 0 && a < c)|| (c < 0 && a <-c)){ a=c; s=p / 4; }else s=p / Ease.PI2 *Math.asin(c / a); if (t < 1)return-.5 *(a *Math.pow(2,10 *(t-=1))*Math.sin((t *d-s)*Ease.PI2 / p))+b; return a *Math.pow(2,-10 *(t-=1))*Math.sin((t *d-s)*Ease.PI2 / p)*.5+c+b; } Ease.elasticOut=function(t,b,c,d,a,p){ (a===void 0)&& (a=0); (p===void 0)&& (p=0); var s; if (t==0)return b; if ((t /=d)==1)return b+c; if (!p)p=d *.3; if (!a || (c > 0 && a < c)|| (c < 0 && a <-c)){ a=c; s=p / 4; }else s=p / Ease.PI2 *Math.asin(c / a); return (a *Math.pow(2,-10 *t)*Math.sin((t *d-s)*Ease.PI2 / p)+c+b); } Ease.strongIn=function(t,b,c,d){ return c *(t /=d)*t *t *t *t+b; } Ease.strongInOut=function(t,b,c,d){ if ((t /=d *0.5)< 1)return c *0.5 *t *t *t *t *t+b; return c *0.5 *((t-=2)*t *t *t *t+2)+b; } Ease.strongOut=function(t,b,c,d){ return c *((t=t / d-1)*t *t *t *t+1)+b; } Ease.sineInOut=function(t,b,c,d){ return-c *0.5 *(Math.cos(Math.PI *t / d)-1)+b; } Ease.sineIn=function(t,b,c,d){ return-c *Math.cos(t / d *Ease.HALF_PI)+c+b; } Ease.sineOut=function(t,b,c,d){ return c *Math.sin(t / d *Ease.HALF_PI)+b; } Ease.quintIn=function(t,b,c,d){ return c *(t /=d)*t *t *t *t+b; } Ease.quintInOut=function(t,b,c,d){ if ((t /=d *0.5)< 1)return c *0.5 *t *t *t *t *t+b; return c *0.5 *((t-=2)*t *t *t *t+2)+b; } Ease.quintOut=function(t,b,c,d){ return c *((t=t / d-1)*t *t *t *t+1)+b; } Ease.quartIn=function(t,b,c,d){ return c *(t /=d)*t *t *t+b; } Ease.quartInOut=function(t,b,c,d){ if ((t /=d *0.5)< 1)return c *0.5 *t *t *t *t+b; return-c *0.5 *((t-=2)*t *t *t-2)+b; } Ease.quartOut=function(t,b,c,d){ return-c *((t=t / d-1)*t *t *t-1)+b; } Ease.cubicIn=function(t,b,c,d){ return c *(t /=d)*t *t+b; } Ease.cubicInOut=function(t,b,c,d){ if ((t /=d *0.5)< 1)return c *0.5 *t *t *t+b; return c *0.5 *((t-=2)*t *t+2)+b; } Ease.cubicOut=function(t,b,c,d){ return c *((t=t / d-1)*t *t+1)+b; } Ease.quadIn=function(t,b,c,d){ return c *(t /=d)*t+b; } Ease.quadInOut=function(t,b,c,d){ if ((t /=d *0.5)< 1)return c *0.5 *t *t+b; return-c *0.5 *((--t)*(t-2)-1)+b; } Ease.quadOut=function(t,b,c,d){ return-c *(t /=d)*(t-2)+b; } Ease.expoIn=function(t,b,c,d){ return (t==0)? b :c *Math.pow(2,10 *(t / d-1))+b-c *0.001; } Ease.expoInOut=function(t,b,c,d){ if (t==0)return b; if (t==d)return b+c; if ((t /=d *0.5)< 1)return c *0.5 *Math.pow(2,10 *(t-1))+b; return c *0.5 *(-Math.pow(2,-10 *--t)+2)+b; } Ease.expoOut=function(t,b,c,d){ return (t==d)? b+c :c *(-Math.pow(2,-10 *t / d)+1)+b; } Ease.circIn=function(t,b,c,d){ return-c *(Math.sqrt(1-(t /=d)*t)-1)+b; } Ease.circInOut=function(t,b,c,d){ if ((t /=d *0.5)< 1)return-c *0.5 *(Math.sqrt(1-t *t)-1)+b; return c *0.5 *(Math.sqrt(1-(t-=2)*t)+1)+b; } Ease.circOut=function(t,b,c,d){ return c *Math.sqrt(1-(t=t / d-1)*t)+b; } Ease.HALF_PI=Math.PI *0.5; Ease.PI2=Math.PI *2; return Ease; })() /** *鼠标点击区域,可以设置绘制一系列矢量图作为点击区域和非点击区域(目前只支持圆形,矩形,多边形) */ //class laya.utils.HitArea var HitArea=(function(){ function HitArea(){ /**@private */ this._hit=null; /**@private */ this._unHit=null; } __class(HitArea,'laya.utils.HitArea'); var __proto=HitArea.prototype; /** *是否包含某个点 *@param x x坐标 *@param y y坐标 *@return 是否点击到 */ __proto.isHit=function(x,y){ if (!HitArea.isHitGraphic(x,y,this.hit))return false; return !HitArea.isHitGraphic(x,y,this.unHit); } /** *检测对象是否包含指定的点。 *@param x 点的 X 轴坐标值(水平位置)。 *@param y 点的 Y 轴坐标值(垂直位置)。 *@return 如果包含指定的点,则值为 true;否则为 false。 */ __proto.contains=function(x,y){ return this.isHit(x,y); } /** *可点击区域,可以设置绘制一系列矢量图作为点击区域(目前只支持圆形,矩形,多边形) */ __getset(0,__proto,'hit',function(){ if (!this._hit)this._hit=new Graphics(); return this._hit; },function(value){ this._hit=value; }); /** *不可点击区域,可以设置绘制一系列矢量图作为非点击区域(目前只支持圆形,矩形,多边形) */ __getset(0,__proto,'unHit',function(){ if (!this._unHit)this._unHit=new Graphics(); return this._unHit; },function(value){ this._unHit=value; }); HitArea.isHitGraphic=function(x,y,graphic){ if (!graphic)return false; var cmds; cmds=graphic.cmds; if (!cmds && graphic._one){ cmds=HitArea._cmds; cmds.length=1; cmds[0]=graphic._one; } if (!cmds)return false; var i=0,len=0; len=cmds.length; var cmd; for (i=0;i < len;i++){ cmd=cmds[i]; if (!cmd)continue ; var context=Render._context; switch (cmd.callee){ case context._translate: case 6: x-=cmd[0]; y-=cmd[1]; default : } if (HitArea.isHitCmd(x,y,cmd))return true; } return false; } HitArea.isHitCmd=function(x,y,cmd){ if (!cmd)return false; var context=Render._context; var rst=false; switch (cmd["callee"]){ case context._drawRect: case 13: HitArea._rec.setTo(cmd[0],cmd[1],cmd[2],cmd[3]); rst=HitArea._rec.contains(x,y); break ; case context._drawCircle: case context._fillCircle: case 14:; var d=NaN; x-=cmd[0]; y-=cmd[1]; d=x *x+y *y; rst=d < cmd[2] *cmd[2]; break ; case context._drawPoly: case 18: x-=cmd[0]; y-=cmd[1]; rst=HitArea.ptInPolygon(x,y,cmd[2]); break ; default : break ; } return rst; } HitArea.ptInPolygon=function(x,y,areaPoints){ var p; p=HitArea._ptPoint; p.setTo(x,y); var nCross=0; var p1x=NaN,p1y=NaN,p2x=NaN,p2y=NaN; var len=0; len=areaPoints.length; for (var i=0;i < len;i+=2){ p1x=areaPoints[i]; p1y=areaPoints[i+1]; p2x=areaPoints[(i+2)% len]; p2y=areaPoints[(i+3)% len]; if (p1y==p2y) continue ; if (p.y < Math.min(p1y,p2y)) continue ; if (p.y >=Math.max(p1y,p2y)) continue ; var tx=(p.y-p1y)*(p2x-p1x)/ (p2y-p1y)+p1x; if (tx > p.x){ nCross++; } } return (nCross % 2==1); } HitArea._cmds=[]; __static(HitArea, ['_rec',function(){return this._rec=new Rectangle();},'_ptPoint',function(){return this._ptPoint=new Point();} ]); return HitArea; })() /** *@private *HTMLChar 是一个 HTML 字符类。 */ //class laya.utils.HTMLChar var HTMLChar=(function(){ function HTMLChar(char,w,h,style){ //this._sprite=null; //this._x=NaN; //this._y=NaN; //this._w=NaN; //this._h=NaN; /**表示是否是正常单词(英文|.|数字)。*/ //this.isWord=false; /**字符。*/ //this.char=null; /**字符数量。*/ //this.charNum=NaN; /**CSS 样式。*/ //this.style=null; this.char=char; this.charNum=char.charCodeAt(0); this._x=this._y=0; this.width=w; this.height=h; this.style=style; this.isWord=!HTMLChar._isWordRegExp.test(char); } __class(HTMLChar,'laya.utils.HTMLChar'); var __proto=HTMLChar.prototype; Laya.imps(__proto,{"laya.display.ILayout":true}) /** *设置与此对象绑定的显示对象 Sprite 。 *@param sprite 显示对象 Sprite 。 */ __proto.setSprite=function(sprite){ this._sprite=sprite; } /** *获取与此对象绑定的显示对象 Sprite。 *@return */ __proto.getSprite=function(){ return this._sprite; } /**@private */ __proto._isChar=function(){ return true; } /**@private */ __proto._getCSSStyle=function(){ return this.style; } /** *宽度。 */ __getset(0,__proto,'width',function(){ return this._w; },function(value){ this._w=value; }); /** *此对象存储的 X 轴坐标值。 *当设置此值时,如果此对象有绑定的 Sprite 对象,则改变 Sprite 对象的属性 x 的值。 */ __getset(0,__proto,'x',function(){ return this._x; },function(value){ if (this._sprite){ this._sprite.x=value; } this._x=value; }); /** *此对象存储的 Y 轴坐标值。 *当设置此值时,如果此对象有绑定的 Sprite 对象,则改变 Sprite 对象的属性 y 的值。 */ __getset(0,__proto,'y',function(){ return this._y; },function(value){ if (this._sprite){ this._sprite.y=value; } this._y=value; }); /** *高度。 */ __getset(0,__proto,'height',function(){ return this._h; },function(value){ this._h=value; }); HTMLChar._isWordRegExp=new RegExp("[\\w\.]",""); return HTMLChar; })() /** *Log 类用于在界面内显示日志记录信息。 */ //class laya.utils.Log var Log=(function(){ function Log(){} __class(Log,'laya.utils.Log'); Log.enable=function(){ if (!Log._logdiv){ Log._logdiv=Browser.window.document.createElement('div'); Browser.window.document.body.appendChild(Log._logdiv); Log._logdiv.style.cssText="pointer-events:none;border:white;overflow:hidden;z-index:1000000;background:rgba(100,100,100,0.6);color:white;position: absolute;left:0px;top:0px;width:50%;height:50%;"; } } Log.toggle=function(){ var style=Log._logdiv.style; if (style.width=="1px"){ style.width=style.height="50%"; }else { style.width=style.height="1px"; } } Log.print=function(value){ if (Log._logdiv){ if (Log._count >=Log.maxCount)Log.clear(); Log._count++; Log._logdiv.innerText+=value+"\n"; Log._logdiv.scrollTop=Log._logdiv.scrollHeight; } } Log.clear=function(){ Log._logdiv.innerText=""; Log._count=0; } Log._logdiv=null; Log._count=0; Log.maxCount=20; return Log; })() /** *Mouse 类用于控制鼠标光标。 */ //class laya.utils.Mouse var Mouse=(function(){ function Mouse(){} __class(Mouse,'laya.utils.Mouse'); /** *设置鼠标样式 *@param cursorStr *例如auto move no-drop col-resize *all-scroll pointer not-allowed row-resize *crosshair progress e-resize ne-resize *default text n-resize nw-resize *help vertical-text s-resize se-resize *inherit wait w-resize sw-resize * */ __getset(1,Mouse,'cursor',function(){ return Mouse._style.cursor; },function(cursorStr){ Mouse._style.cursor=cursorStr; }); Mouse.hide=function(){ if (Mouse.cursor !="none"){ Mouse._preCursor=Mouse.cursor; Mouse.cursor="none"; } } Mouse.show=function(){ if (Mouse.cursor=="none"){ if (Mouse._preCursor){ Mouse.cursor=Mouse._preCursor; }else { Mouse.cursor="auto"; } } } Mouse._preCursor=null; __static(Mouse, ['_style',function(){return this._style=Browser.document.body.style;} ]); return Mouse; })() /** *

    Pool 是对象池类,用于对象的存贮、重复使用。

    *

    合理使用对象池,可以有效减少对象创建的开销,避免频繁的垃圾回收,从而优化游戏流畅度。

    */ //class laya.utils.Pool var Pool=(function(){ function Pool(){} __class(Pool,'laya.utils.Pool'); Pool.getPoolBySign=function(sign){ return Pool._poolDic[sign] || (Pool._poolDic[sign]=[]); } Pool.clearBySign=function(sign){ if (Pool._poolDic[sign])Pool._poolDic[sign].length=0; } Pool.recover=function(sign,item){ if (item["__InPool"])return; item["__InPool"]=true; Pool.getPoolBySign(sign).push(item); } Pool.getItemByClass=function(sign,cls){ var pool=Pool.getPoolBySign(sign); var rst=pool.length ? pool.pop():new cls(); rst["__InPool"]=false; return rst; } Pool.getItemByCreateFun=function(sign,createFun,caller){ var pool=Pool.getPoolBySign(sign); var rst=pool.length ? pool.pop():createFun.call(caller); rst["__InPool"]=false; return rst; } Pool.getItem=function(sign){ var pool=Pool.getPoolBySign(sign); var rst=pool.length ? pool.pop():null; if (rst){ rst["__InPool"]=false; } return rst; } Pool._poolDic={}; Pool.InPoolSign="__InPool"; return Pool; })() /** *@private *基于个数的对象缓存管理器 */ //class laya.utils.PoolCache var PoolCache=(function(){ function PoolCache(){ /** *对象在Pool中的标识 */ this.sign=null; /** *允许缓存的最大数量 */ this.maxCount=1000; } __class(PoolCache,'laya.utils.PoolCache'); var __proto=PoolCache.prototype; /** *获取缓存的对象列表 *@return * */ __proto.getCacheList=function(){ return Pool.getPoolBySign(this.sign); } /** *尝试清理缓存 *@param force 是否强制清理 * */ __proto.tryDispose=function(force){ var list; list=Pool.getPoolBySign(this.sign); if (list.length > this.maxCount){ list.splice(this.maxCount,list.length-this.maxCount); } } PoolCache.addPoolCacheManager=function(sign,maxCount){ (maxCount===void 0)&& (maxCount=100); var cache; cache=new PoolCache(); cache.sign=sign; cache.maxCount=maxCount; CacheManager.regCacheByFunction(Utils.bind(cache.tryDispose,cache),Utils.bind(cache.getCacheList,cache)); } return PoolCache; })() /** *

    Stat 是一个性能统计面板,可以实时更新相关的性能参数。

    *

    参与统计的性能参数如下(所有参数都是每大约1秒进行更新):
    *FPS(Canvas)/FPS(WebGL):Canvas 模式或者 WebGL 模式下的帧频,也就是每秒显示的帧数,值越高、越稳定,感觉越流畅;
    *Sprite:统计所有渲染节点(包括容器)数量,它的大小会影响引擎进行节点遍历、数据组织和渲染的效率。其值越小,游戏运行效率越高;
    *DrawCall:此值是决定性能的重要指标,其值越小,游戏运行效率越高。Canvas模式下表示每大约1秒的图像绘制次数;WebGL模式下表示每大约1秒的渲染提交批次,每次准备数据并通知GPU渲染绘制的过程称为1次DrawCall,在每次DrawCall中除了在通知GPU的渲染上比较耗时之外,切换材质与shader也是非常耗时的操作;
    *CurMem:Canvas模式下,表示内存占用大小,值越小越好,过高会导致游戏闪退;WebGL模式下,表示内存与显存的占用,值越小越好;
    *Shader:是 WebGL 模式独有的性能指标,表示每大约1秒 Shader 提交次数,值越小越好;
    *Canvas:由三个数值组成,只有设置 CacheAs 后才会有值,默认为0/0/0。从左到右数值的意义分别为:每帧重绘的画布数量 / 缓存类型为"normal"类型的画布数量 / 缓存类型为"bitmap"类型的画布数量。

    */ //class laya.utils.Stat var Stat=(function(){ function Stat(){} __class(Stat,'laya.utils.Stat'); /** *点击性能统计显示区域的处理函数。 */ __getset(1,Stat,'onclick',null,function(fn){ if (Stat._sp){ Stat._sp.on("click",Stat._sp,fn); } if (Stat._canvas){ Stat._canvas.source.onclick=fn; Stat._canvas.source.style.pointerEvents=''; } }); Stat.show=function(x,y){ (x===void 0)&& (x=0); (y===void 0)&& (y=0); if (Render.isConchApp && !Render.isConchWebGL){ Browser.window.conch.showFPS && Browser.window.conch.showFPS(x,y); return; } if (!Render.isConchWebGL && !Browser.onMiniGame &&! Browser.onLimixiu && !Browser.onKGMiniGame && !Browser.onBDMiniGame&& !Browser.onTTMiniGame && !Browser.onQGMiniGame && !Browser.onVVMiniGame && !Browser.onBLMiniGame && !Browser.onAlipayMiniGame && !Browser.onQQMiniGame && !Browser.onTTMiniGame && !Browser.onHWMiniGame && !Browser.onTBMiniGame)Stat._useCanvas=true; Stat._show=true; Stat._fpsData.length=60; Stat._view[0]={title:"FPS(Canvas)",value:"_fpsStr",color:"yellow",units:"int"}; Stat._view[1]={title:"Sprite",value:"_spriteStr",color:"white",units:"int"}; Stat._view[2]={title:"DrawCall",value:"drawCall",color:"white",units:"int"}; Stat._view[3]={title:"CurMem",value:"currentMemorySize",color:"yellow",units:"M"}; if (Render.isWebGL){ Stat._view[4]={title:"Shader",value:"shaderCall",color:"white",units:"int"}; if (!Render.is3DMode){ Stat._view[0].title="FPS(WebGL)"; Stat._view[5]={title:"Canvas",value:"_canvasStr",color:"white",units:"int"}; }else { Stat._view[0].title="FPS(3D)"; Stat._view[5]={title:"TriFaces",value:"trianglesFaces",color:"white",units:"int"}; Stat._view[6]={title:"treeNodeColl",value:"treeNodeCollision",color:"white",units:"int"}; Stat._view[7]={title:"treeSpriteColl",value:"treeSpriteCollision",color:"white",units:"int"}; } }else { Stat._view[4]={title:"Canvas",value:"_canvasStr",color:"white",units:"int"}; } if (Stat._useCanvas){ Stat.createUIPre(x,y); }else Stat.createUI(x,y); Stat.enable(); } Stat.createUIPre=function(x,y){ var pixel=Browser.pixelRatio; if(Laya.stage.useRetinalCanvas){ pixel=3; } Stat._width=pixel *130; Stat._vx=pixel *75; Stat._height=pixel *(Stat._view.length *12+3 *pixel)+4; Stat._fontSize=12 *pixel; for (var i=0;i < Stat._view.length;i++){ Stat._view[i].x=4; Stat._view[i].y=i *Stat._fontSize+2 *pixel; } if (!Stat._canvas){ Stat._canvas=new HTMLCanvas('2D'); Stat._canvas.size(Stat._width,Stat._height); Stat._ctx=Stat._canvas.getContext('2d'); Stat._ctx.textBaseline="top"; Stat._ctx.font=Stat._fontSize+"px Sans-serif"; Stat._canvas.source.style.cssText="pointer-events:none;background:rgba(150,150,150,0.8);z-index:100000;position: absolute;direction:ltr;left:"+x+"px;top:"+y+"px;width:"+(Stat._width / pixel)+"px;height:"+(Stat._height / pixel)+"px;"; } Stat._first=true; Stat.loop(); Stat._first=false; if(!Browser.onKGMiniGame){ Browser.container.appendChild(Stat._canvas.source); } } Stat.createUI=function(x,y){ var stat=Stat._sp; var pixel=Browser.pixelRatio; if(Laya.stage.useRetinalCanvas){ pixel=3; } if (!stat){ stat=new Sprite(); Stat._leftText=new Text(); Stat._leftText.pos(5,5); Stat._leftText.color="#ffffff"; stat.addChild(Stat._leftText); Stat._txt=new Text(); Stat._txt.pos(80*pixel,5); Stat._txt.color="#ffffff"; stat.addChild(Stat._txt); Stat._sp=stat; } stat.pos(x,y); var text=""; for (var i=0;i < Stat._view.length;i++){ var one=Stat._view[i]; text+=one.title+"\n"; } Stat._leftText.text=text; var width=pixel *138; var height=pixel *(Stat._view.length *12+3 *pixel)+4; Stat._txt.fontSize=Stat._fontSize *pixel; Stat._leftText.fontSize=Stat._fontSize *pixel; stat.size(width,height); stat.graphics.clear(); stat.graphics.setAlpha(0.5); stat.graphics.drawRect(0,0,width,height,"#999999"); stat.graphics.setAlpha(1); Stat.loop(); } Stat.enable=function(){ Laya.timer.frameLoop(1,Stat,Stat.loop); } Stat.hide=function(){ Stat._show=false; Laya.timer.clear(Stat,Stat.loop); if (Stat._canvas){ Browser.removeElement(Stat._canvas.source); } } Stat.clear=function(){ Stat.trianglesFaces=Stat.drawCall=Stat.shaderCall=Stat.spriteCount=Stat.spriteRenderUseCacheCount=Stat.treeNodeCollision=Stat.treeSpriteCollision=Stat.canvasNormal=Stat.canvasBitmap=Stat.canvasReCache=0; } Stat.loop=function(){ Stat._count++; var timer=Browser.now(); if (timer-Stat._timer < 1000)return; var count=Stat._count; Stat.FPS=Math.round((count *1000)/ (timer-Stat._timer)); if (Stat._show){ Stat.trianglesFaces=Math.round(Stat.trianglesFaces / count); if (!Stat._useCanvas){ Stat.drawCall=Math.round(Stat.drawCall / count)-2; Stat.shaderCall=Math.round(Stat.shaderCall / count)-4; Stat.spriteCount=Math.round(Stat.spriteCount / count)-4; }else{ Stat.drawCall=Math.round(Stat.drawCall / count)-2; Stat.shaderCall=Math.round(Stat.shaderCall / count); Stat.spriteCount=Math.round(Stat.spriteCount / count)-1; } Stat.spriteRenderUseCacheCount=Math.round(Stat.spriteRenderUseCacheCount / count); Stat.canvasNormal=Math.round(Stat.canvasNormal / count); Stat.canvasBitmap=Math.round(Stat.canvasBitmap / count); Stat.canvasReCache=Math.ceil(Stat.canvasReCache / count); Stat.treeNodeCollision=Math.round(Stat.treeNodeCollision / count); Stat.treeSpriteCollision=Math.round(Stat.treeSpriteCollision / count); var delay=Stat.FPS > 0 ? Math.floor(1000 / Stat.FPS).toString():" "; Stat._fpsStr=Stat.FPS+(Stat.renderSlow ? " slow" :"")+" "+delay; Stat._spriteStr=Stat.spriteCount+(Stat.spriteRenderUseCacheCount ? ("/"+Stat.spriteRenderUseCacheCount):''); Stat._canvasStr=Stat.canvasReCache+"/"+Stat.canvasNormal+"/"+Stat.canvasBitmap; Stat.currentMemorySize=ResourceManager.systemResourceManager.memorySize; if (Stat._useCanvas){ Stat.renderInfoPre(); }else Stat.renderInfo(); Stat.clear(); } Stat._count=0; Stat._timer=timer; } Stat.renderInfoPre=function(){ if (Stat._canvas){ var ctx=Stat._ctx; ctx.clearRect(Stat._first ? 0 :Stat._vx,0,Stat._width,Stat._height); for (var i=0;i < Stat._view.length;i++){ var one=Stat._view[i]; if (Stat._first){ ctx.fillStyle="white"; ctx.fillText(one.title,one.x,one.y,null,null,null); } ctx.fillStyle=one.color; var value=Stat[one.value]; (one.units=="M")&& (value=Math.floor(value / (1024 *1024)*100)/ 100+" M"); ctx.fillText(value+"",one.x+Stat._vx,one.y,null,null,null); } } } Stat.renderInfo=function(){ var text=""; for (var i=0;i < Stat._view.length;i++){ var one=Stat._view[i]; var value=Stat[one.value]; (one.units=="M")&& (value=Math.floor(value / (1024 *1024)*100)/ 100+" M"); (one.units=="K")&& (value=Math.floor(value / (1024)*100)/ 100+" K"); text+=value+"\n"; } Stat._txt.text=text; } Stat.FPS=0; Stat.loopCount=0; Stat.shaderCall=0; Stat.drawCall=0; Stat.trianglesFaces=0; Stat.spriteCount=0; Stat.spriteRenderUseCacheCount=0; Stat.treeNodeCollision=0; Stat.treeSpriteCollision=0; Stat.canvasNormal=0; Stat.canvasBitmap=0; Stat.canvasReCache=0; Stat.renderSlow=false; Stat.currentMemorySize=0; Stat._fpsStr=null; Stat._canvasStr=null; Stat._spriteStr=null; Stat._fpsData=[]; Stat._timer=0; Stat._count=0; Stat._view=[]; Stat._fontSize=12; Stat._txt=null; Stat._leftText=null; Stat._sp=null; Stat._show=false; Stat._useCanvas=false; Stat._canvas=null; Stat._ctx=null; Stat._first=false; Stat._vx=NaN; Stat._width=0; Stat._height=100; return Stat; })() /** *@private *StringKey 类用于存取字符串对应的数字。 */ //class laya.utils.StringKey var StringKey=(function(){ function StringKey(){ this._strsToID={}; this._idToStrs=[]; this._length=0; } __class(StringKey,'laya.utils.StringKey'); var __proto=StringKey.prototype; /** *添加一个字符。 *@param str 字符,将作为key 存储相应生成的数字。 *@return 此字符对应的数字。 */ __proto.add=function(str){ var index=this._strsToID[str]; if (index !=null)return index; this._idToStrs[this._length]=str; return this._strsToID[str]=this._length++; } /** *获取指定字符对应的ID。 *@param str 字符。 *@return 此字符对应的ID。 */ __proto.getID=function(str){ var index=this._strsToID[str]; return index==null ?-1 :index; } /** *根据指定ID获取对应字符。 *@param id ID。 *@return 此id对应的字符。 */ __proto.getName=function(id){ var str=this._idToStrs[id]; return str==null ? undefined :str; } return StringKey; })() /** *Timer 是时钟管理类。它是一个单例,不要手动实例化此类,应该通过 Laya.timer 访问。 */ //class laya.utils.Timer var Timer=(function(){ var TimerHandler; function Timer(){ /**两帧之间的时间间隔,单位毫秒。*/ this._delta=0; /**时针缩放。*/ this.scale=1; /**当前的帧数。*/ this.currFrame=0; /**@private */ this._mid=1; /**@private */ this._map=[]; /**@private */ this._laters=[]; /**@private */ this._handlers=[]; /**@private */ this._temp=[]; /**@private */ this._count=0; this.currTimer=this._now(); this._lastTimer=this._now(); this._init(); } __class(Timer,'laya.utils.Timer'); var __proto=Timer.prototype; /**@private */ __proto._init=function(){ Laya.timer && Laya.timer.frameLoop(1,this,this._update); } /**@private */ __proto._now=function(){ return /*__JS__ */Date.now(); } /** *@private *帧循环处理函数。 */ __proto._update=function(){ if (this.scale <=0){ this._lastTimer=this._now(); return; }; var frame=this.currFrame=this.currFrame+this.scale; var now=this._now(); this._delta=(now-this._lastTimer)*this.scale; var timer=this.currTimer=this.currTimer+this._delta; this._lastTimer=now; var handlers=this._handlers; this._count=0; for (i=0,n=handlers.length;i < n;i++){ handler=handlers[i]; if (handler.method!==null){ var t=handler.userFrame ? frame :timer; if (t >=handler.exeTime){ if (handler.repeat){ if (!handler.jumpFrame){ handler.exeTime+=handler.delay; handler.run(false); if (t > handler.exeTime){ handler.exeTime+=Math.ceil((t-handler.exeTime)/ handler.delay)*handler.delay; } }else { while (t >=handler.exeTime){ handler.exeTime+=handler.delay; handler.run(false); } } }else { handler.run(true); } } }else { this._count++; } } if (this._count > 30 || frame % 200===0)this._clearHandlers(); var laters=this._laters; for (var i=0,n=laters.length-1;i <=n;i++){ var handler=laters[i]; if (handler.method!==null){ this._map[handler.key]=null; handler.run(false); } this._recoverHandler(handler); i===n && (n=laters.length-1); } laters.length=0; } /**@private */ __proto._clearHandlers=function(){ var handlers=this._handlers; for (var i=0,n=handlers.length;i < n;i++){ var handler=handlers[i]; if (handler.method!==null)this._temp.push(handler); else this._recoverHandler(handler); } this._handlers=this._temp; this._temp=handlers; this._temp.length=0; } /**@private */ __proto._recoverHandler=function(handler){ if(this._map[handler.key]==handler)this._map[handler.key]=null; handler.clear(); Timer._pool.push(handler); } /**@private */ __proto._create=function(useFrame,repeat,delay,caller,method,args,coverBefore){ if (!delay){ method.apply(caller,args); return null; } if (coverBefore){ var handler=this._getHandler(caller,method); if (handler){ handler.repeat=repeat; handler.userFrame=useFrame; handler.delay=delay; handler.caller=caller; handler.method=method; handler.args=args; handler.exeTime=delay+(useFrame ? this.currFrame :this.currTimer+this._now()-this._lastTimer); return handler; } } handler=Timer._pool.length > 0 ? Timer._pool.pop():new TimerHandler(); handler.repeat=repeat; handler.userFrame=useFrame; handler.delay=delay; handler.caller=caller; handler.method=method; handler.args=args; handler.exeTime=delay+(useFrame ? this.currFrame :this.currTimer+this._now()-this._lastTimer)+1; this._indexHandler(handler); this._handlers.push(handler); return handler; } /**@private */ __proto._indexHandler=function(handler){ var caller=handler.caller; var method=handler.method; var cid=caller ? caller.$_GID || (caller.$_GID=Utils.getGID()):0; var mid=method.$_TID || (method.$_TID=(this._mid++)*100000); handler.key=cid+mid; this._map[handler.key]=handler; } /** *定时执行一次。 *@param delay 延迟时间(单位为毫秒)。 *@param caller 执行域(this)。 *@param method 定时器回调函数。 *@param args 回调参数。 *@param coverBefore 是否覆盖之前的延迟执行,默认为 true 。 */ __proto.once=function(delay,caller,method,args,coverBefore){ (coverBefore===void 0)&& (coverBefore=true); this._create(false,false,delay,caller,method,args,coverBefore); } /** *定时重复执行。 *@param delay 间隔时间(单位毫秒)。 *@param caller 执行域(this)。 *@param method 定时器回调函数。 *@param args 回调参数。 *@param coverBefore 是否覆盖之前的延迟执行,默认为 true 。 *@param jumpFrame 时钟是否跳帧。基于时间的循环回调,单位时间间隔内,如能执行多次回调,出于性能考虑,引擎默认只执行一次,设置jumpFrame=true后,则回调会连续执行多次 */ __proto.loop=function(delay,caller,method,args,coverBefore,jumpFrame){ (coverBefore===void 0)&& (coverBefore=true); (jumpFrame===void 0)&& (jumpFrame=false); var handler=this._create(false,true,delay,caller,method,args,coverBefore); if (handler)handler.jumpFrame=jumpFrame; } /** *定时执行一次(基于帧率)。 *@param delay 延迟几帧(单位为帧)。 *@param caller 执行域(this)。 *@param method 定时器回调函数。 *@param args 回调参数。 *@param coverBefore 是否覆盖之前的延迟执行,默认为 true 。 */ __proto.frameOnce=function(delay,caller,method,args,coverBefore){ (coverBefore===void 0)&& (coverBefore=true); this._create(true,false,delay,caller,method,args,coverBefore); } /** *定时重复执行(基于帧率)。 *@param delay 间隔几帧(单位为帧)。 *@param caller 执行域(this)。 *@param method 定时器回调函数。 *@param args 回调参数。 *@param coverBefore 是否覆盖之前的延迟执行,默认为 true 。 */ __proto.frameLoop=function(delay,caller,method,args,coverBefore){ (coverBefore===void 0)&& (coverBefore=true); this._create(true,true,delay,caller,method,args,coverBefore); } /**返回统计信息。*/ __proto.toString=function(){ return "callLater:"+this._laters.length+" handlers:"+this._handlers.length+" pool:"+Timer._pool.length; } /** *清理定时器。 *@param caller 执行域(this)。 *@param method 定时器回调函数。 */ __proto.clear=function(caller,method){ var handler=this._getHandler(caller,method); if (handler){ this._map[handler.key]=null;handler.key=0; handler.clear(); } } /** *清理对象身上的所有定时器。 *@param caller 执行域(this)。 */ __proto.clearAll=function(caller){ if (!caller)return; for (var i=0,n=this._handlers.length;i < n;i++){ var handler=this._handlers[i]; if (handler.caller===caller){ this._map[handler.key]=null;handler.key=0; handler.clear(); } } } /**@private */ __proto._getHandler=function(caller,method){ var cid=caller ? caller.$_GID || (caller.$_GID=Utils.getGID()):0; var mid=method.$_TID || (method.$_TID=(this._mid++)*100000); return this._map[cid+mid]; } /** *延迟执行。 *@param caller 执行域(this)。 *@param method 定时器回调函数。 *@param args 回调参数。 */ __proto.callLater=function(caller,method,args){ if (this._getHandler(caller,method)==null){ if (Timer._pool.length) var handler=Timer._pool.pop(); else handler=new TimerHandler(); handler.caller=caller; handler.method=method; handler.args=args; this._indexHandler(handler); this._laters.push(handler); } } /** *立即执行 callLater 。 *@param caller 执行域(this)。 *@param method 定时器回调函数。 */ __proto.runCallLater=function(caller,method){ var handler=this._getHandler(caller,method); if (handler && handler.method !=null){ this._map[handler.key]=null; handler.run(true); } } /** *立即提前执行定时器,执行之后从队列中删除 *@param caller 执行域(this)。 *@param method 定时器回调函数。 */ __proto.runTimer=function(caller,method){ this.runCallLater(caller,method); } /** *两帧之间的时间间隔,单位毫秒。 */ __getset(0,__proto,'delta',function(){ return this._delta; }); Timer._pool=[]; Timer.__init$=function(){ /**@private */ //class TimerHandler TimerHandler=(function(){ function TimerHandler(){ this.key=0; this.repeat=false; this.delay=0; this.userFrame=false; this.exeTime=0; this.caller=null; this.method=null; this.args=null; this.jumpFrame=false; } __class(TimerHandler,''); var __proto=TimerHandler.prototype; __proto.clear=function(){ this.caller=null; this.method=null; this.args=null; } __proto.run=function(withClear){ var caller=this.caller; if (caller && caller.destroyed)return this.clear(); var method=this.method; var args=this.args; withClear && this.clear(); if (method==null)return; args ? method.apply(caller,args):method.call(caller); } return TimerHandler; })() } return Timer; })() /** *Tween 是一个缓动类。使用此类能够实现对目标对象属性的渐变。 */ //class laya.utils.Tween var Tween=(function(){ function Tween(){ /**@private */ //this._complete=null; /**@private */ //this._target=null; /**@private */ //this._ease=null; /**@private */ //this._props=null; /**@private */ //this._duration=0; /**@private */ //this._delay=0; /**@private */ //this._startTimer=0; /**@private */ //this._usedTimer=0; /**@private */ //this._usedPool=false; /**@private */ //this._delayParam=null; /**@private 唯一标识,TimeLintLite用到*/ this.gid=0; /**更新回调,缓动数值发生变化时,回调变化的值*/ //this.update=null; } __class(Tween,'laya.utils.Tween'); var __proto=Tween.prototype; /** *缓动对象的props属性到目标值。 *@param target 目标对象(即将更改属性值的对象)。 *@param props 变化的属性列表,比如{x:100,y:20,ease:Ease.backOut,complete:Handler.create(this,onComplete),update:new Handler(this,onComplete)}。 *@param duration 花费的时间,单位毫秒。 *@param ease 缓动类型,默认为匀速运动。 *@param complete 结束回调函数。 *@param delay 延迟执行时间。 *@param coverBefore 是否覆盖之前的缓动。 *@return 返回Tween对象。 */ __proto.to=function(target,props,duration,ease,complete,delay,coverBefore){ (delay===void 0)&& (delay=0); (coverBefore===void 0)&& (coverBefore=false); return this._create(target,props,duration,ease,complete,delay,coverBefore,true,false,true); } /** *从props属性,缓动到当前状态。 *@param target 目标对象(即将更改属性值的对象)。 *@param props 变化的属性列表,比如{x:100,y:20,ease:Ease.backOut,complete:Handler.create(this,onComplete),update:new Handler(this,onComplete)}。 *@param duration 花费的时间,单位毫秒。 *@param ease 缓动类型,默认为匀速运动。 *@param complete 结束回调函数。 *@param delay 延迟执行时间。 *@param coverBefore 是否覆盖之前的缓动。 *@return 返回Tween对象。 */ __proto.from=function(target,props,duration,ease,complete,delay,coverBefore){ (delay===void 0)&& (delay=0); (coverBefore===void 0)&& (coverBefore=false); return this._create(target,props,duration,ease,complete,delay,coverBefore,false,false,true); } /**@private */ __proto._create=function(target,props,duration,ease,complete,delay,coverBefore,isTo,usePool,runNow){ if (!target)throw new Error("Tween:target is null"); this._target=target; this._duration=duration; this._ease=ease || props.ease || Tween.easeNone; this._complete=complete || props.complete; this._delay=delay; this._props=[]; this._usedTimer=0; this._startTimer=Browser.now(); this._usedPool=usePool; this._delayParam=null; this.update=props.update; var gid=(target.$_GID || (target.$_GID=Utils.getGID())); if (!Tween.tweenMap[gid]){ Tween.tweenMap[gid]=[this]; }else { if (coverBefore)Tween.clearTween(target); Tween.tweenMap[gid].push(this); } if (runNow){ if (delay <=0)this.firstStart(target,props,isTo); else{ this._delayParam=[target,props,isTo]; Laya.scaleTimer.once(delay,this,this.firstStart,this._delayParam); } }else { this._initProps(target,props,isTo); } return this; } __proto.firstStart=function(target,props,isTo){ this._delayParam=null; if (target.destroyed){ this.clear(); return; } this._initProps(target,props,isTo); this._beginLoop(); } __proto._initProps=function(target,props,isTo){ for (var p in props){ if ((typeof (target[p])=='number')){ var start=isTo ? target[p] :props[p]; var end=isTo ? props[p] :target[p]; this._props.push([p,start,end-start]); if (!isTo)target[p]=start; } } } __proto._beginLoop=function(){ Laya.scaleTimer.frameLoop(1,this,this._doEase); } /**执行缓动**/ __proto._doEase=function(){ this._updateEase(Browser.now()); } /**@private */ __proto._updateEase=function(time){ var target=this._target; if (!target)return; if (target.destroyed)return Tween.clearTween(target); var usedTimer=this._usedTimer=time-this._startTimer-this._delay; if (usedTimer < 0)return; if (usedTimer >=this._duration)return this.complete(); var ratio=usedTimer > 0 ? this._ease(usedTimer,0,1,this._duration):0; var props=this._props; for (var i=0,n=props.length;i < n;i++){ var prop=props[i]; target[prop[0]]=prop[1]+(ratio *prop[2]); } if (this.update)this.update.run(); } /** *立即结束缓动并到终点。 */ __proto.complete=function(){ if (!this._target)return; Laya.scaleTimer.runTimer(this,this.firstStart); var target=this._target; var props=this._props; var handler=this._complete; for (var i=0,n=props.length;i < n;i++){ var prop=props[i]; target[prop[0]]=prop[1]+prop[2]; } if (this.update)this.update.run(); this.clear(); handler && handler.run(); } /** *暂停缓动,可以通过resume或restart重新开始。 */ __proto.pause=function(){ Laya.scaleTimer.clear(this,this._beginLoop); Laya.scaleTimer.clear(this,this._doEase); Laya.scaleTimer.clear(this,this.firstStart); var time=Browser.now(); var dTime=NaN; dTime=time-this._startTimer-this._delay; if (dTime < 0){ this._usedTimer=dTime; } } /** *设置开始时间。 *@param startTime 开始时间。 */ __proto.setStartTime=function(startTime){ this._startTimer=startTime; } /** *停止并清理当前缓动。 */ __proto.clear=function(){ if (this._target){ this._remove(); this._clear(); } } /** *@private */ __proto._clear=function(){ this.pause(); Laya.scaleTimer.clear(this,this.firstStart); this._complete=null; this._target=null; this._ease=null; this._props=null; this._delayParam=null; if (this._usedPool){ this.update=null; Pool.recover("tween",this); } } /**回收到对象池。*/ __proto.recover=function(){ this._usedPool=true; this._clear(); } __proto._remove=function(){ var tweens=Tween.tweenMap[this._target.$_GID]; if (tweens){ for (var i=0,n=tweens.length;i < n;i++){ if (tweens[i]===this){ tweens.splice(i,1); break ; } } } } /** *重新开始暂停的缓动。 */ __proto.restart=function(){ this.pause(); this._usedTimer=0; this._startTimer=Browser.now(); if (this._delayParam){ Laya.scaleTimer.once(this._delay,this,this.firstStart,this._delayParam); return; }; var props=this._props; for (var i=0,n=props.length;i < n;i++){ var prop=props[i]; this._target[prop[0]]=prop[1]; } Laya.scaleTimer.once(this._delay,this,this._beginLoop); } /** *恢复暂停的缓动。 */ __proto.resume=function(){ if (this._usedTimer >=this._duration)return; this._startTimer=Browser.now()-this._usedTimer-this._delay; if (this._delayParam){ if (this._usedTimer < 0){ Laya.scaleTimer.once(-this._usedTimer,this,this.firstStart,this._delayParam); }else{ this.firstStart.apply(this,this._delayParam); } }else{ this._beginLoop(); } } /**设置当前执行比例**/ __getset(0,__proto,'progress',null,function(v){ var uTime=v *this._duration; this._startTimer=Browser.now()-this._delay-uTime; }); Tween.to=function(target,props,duration,ease,complete,delay,coverBefore,autoRecover){ (delay===void 0)&& (delay=0); (coverBefore===void 0)&& (coverBefore=false); (autoRecover===void 0)&& (autoRecover=true); return Pool.getItemByClass("tween",Tween)._create(target,props,duration,ease,complete,delay,coverBefore,true,autoRecover,true); } Tween.from=function(target,props,duration,ease,complete,delay,coverBefore,autoRecover){ (delay===void 0)&& (delay=0); (coverBefore===void 0)&& (coverBefore=false); (autoRecover===void 0)&& (autoRecover=true); return Pool.getItemByClass("tween",Tween)._create(target,props,duration,ease,complete,delay,coverBefore,false,autoRecover,true); } Tween.clearAll=function(target){ if (!target || !target.$_GID)return; var tweens=Tween.tweenMap[target.$_GID]; if (tweens){ for (var i=0,n=tweens.length;i < n;i++){ tweens[i]._clear(); } tweens.length=0; } } Tween.clear=function(tween){ tween.clear(); } Tween.clearTween=function(target){ Tween.clearAll(target); } Tween.easeNone=function(t,b,c,d){ return c *t / d+b; } Tween.tweenMap={}; return Tween; })() /** *Utils 是工具类。 */ //class laya.utils.Utils var Utils=(function(){ function Utils(){} __class(Utils,'laya.utils.Utils'); Utils.toRadian=function(angle){ return angle *Utils._pi2; } Utils.toAngle=function(radian){ return radian *Utils._pi; } Utils.toHexColor=function(color){ if (color < 0 || isNaN(color))return null; var str=color.toString(16); while (str.length < 6)str="0"+str; return "#"+str; } Utils.getGID=function(){ return Utils._gid++; } Utils.concatArray=function(source,array){ if (!array)return source; if (!source)return array; var i=0,len=array.length; for (i=0;i < len;i++){ source.push(array[i]); } return source; } Utils.clearArray=function(array){ if (!array)return array; array.length=0; return array; } Utils.copyArray=function(source,array){ source || (source=[]); if (!array)return source; source.length=array.length; var i=0,len=array.length; for (i=0;i < len;i++){ source[i]=array[i]; } return source; } Utils.getGlobalRecByPoints=function(sprite,x0,y0,x1,y1){ var newLTPoint; newLTPoint=new Point(x0,y0); newLTPoint=sprite.localToGlobal(newLTPoint); var newRBPoint; newRBPoint=new Point(x1,y1); newRBPoint=sprite.localToGlobal(newRBPoint); return Rectangle._getWrapRec([newLTPoint.x,newLTPoint.y,newRBPoint.x,newRBPoint.y]); } Utils.getGlobalPosAndScale=function(sprite){ return Utils.getGlobalRecByPoints(sprite,0,0,1,1); } Utils.bind=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } Utils.measureText=function(txt,font){ return RunDriver.measureText(txt,font); } Utils.updateOrder=function(array){ if (!array || array.length < 2)return false; var i=1,j=0,len=array.length,key=NaN,c; while (i < len){ j=i; c=array[j]; key=array[j]._zOrder; while (--j >-1){ if (array[j]._zOrder > key)array[j+1]=array[j]; else break ; } array[j+1]=c; i++; }; var model=c.parent.conchModel; if (model){ if (model.updateZOrder !=null){ model.updateZOrder(); }else { for (i=0;i < len;i++){ model.removeChild(array[i].conchModel); } for (i=0;i < len;i++){ model.addChildAt(array[i].conchModel,i); } } } return true; } Utils.transPointList=function(points,x,y){ var i=0,len=points.length; for (i=0;i < len;i+=2){ points[i]+=x; points[i+1]+=y; } } Utils.parseInt=function(str,radix){ (radix===void 0)&& (radix=0); var result=Browser.window.parseInt(str,radix); if (isNaN(result))return 0; return result; } Utils.getFileExtension=function(path){ Utils._extReg.lastIndex=path.lastIndexOf("."); var result=Utils._extReg.exec(path); if (result && result.length > 1){ return result[1].toLowerCase(); } return null; } Utils.getTransformRelativeToWindow=function(coordinateSpace,x,y){ var stage=Laya.stage; var globalTransform=laya.utils.Utils.getGlobalPosAndScale(coordinateSpace); var canvasMatrix=stage._canvasTransform.clone(); var canvasLeft=canvasMatrix.tx; var canvasTop=canvasMatrix.ty; canvasMatrix.rotate(-Math.PI / 180 *Laya.stage.canvasDegree); canvasMatrix.scale(Laya.stage.clientScaleX,Laya.stage.clientScaleY); var perpendicular=(Laya.stage.canvasDegree % 180 !=0); var tx=NaN,ty=NaN; if (perpendicular){ tx=y+globalTransform.y; ty=x+globalTransform.x; tx *=canvasMatrix.d; ty *=canvasMatrix.a; if (Laya.stage.canvasDegree==90){ tx=canvasLeft-tx; ty+=canvasTop; } else { tx+=canvasLeft; ty=canvasTop-ty; } } else { tx=x+globalTransform.x; ty=y+globalTransform.y; tx *=canvasMatrix.a; ty *=canvasMatrix.d; tx+=canvasLeft; ty+=canvasTop; }; var domScaleX=NaN,domScaleY=NaN; if (perpendicular){ domScaleX=canvasMatrix.d *globalTransform.height; domScaleY=canvasMatrix.a *globalTransform.width; }else { domScaleX=canvasMatrix.a *globalTransform.width; domScaleY=canvasMatrix.d *globalTransform.height; } return {x:tx,y:ty,scaleX:domScaleX,scaleY:domScaleY}; } Utils.fitDOMElementInArea=function(dom,coordinateSpace,x,y,width,height){ if (!dom._fitLayaAirInitialized){ dom._fitLayaAirInitialized=true; dom.style.transformOrigin=dom.style.webKittransformOrigin="left top"; dom.style.position="absolute" }; var transform=Utils.getTransformRelativeToWindow(coordinateSpace,x,y); dom.style.transform=dom.style.webkitTransform="scale("+transform.scaleX+","+transform.scaleY+") rotate("+(Laya.stage.canvasDegree)+"deg)"; dom.style.width=width+'px'; dom.style.height=height+'px'; dom.style.left=transform.x+'px'; dom.style.top=transform.y+'px'; } Utils.isOkTextureList=function(textureList){ if (!textureList)return false; var i=0,len=textureList.length; var tTexture; for (i=0;i < len;i++){ tTexture=textureList[i]; if (!tTexture||!tTexture.source)return false; } return true; } Utils.isOKCmdList=function(cmds){ if (!cmds)return false; var i=0,len=cmds.length; var context=Render._context; var cmd; var tex; for (i=0;i < len;i++){ cmd=cmds[i]; switch(cmd.callee){ case context._drawTexture: case context._fillTexture: case context._drawTextureWithTransform: tex=cmd[0]; if (!tex || !tex.source)return false; } } return true; } Utils._gid=1; Utils._pi=180 / Math.PI; Utils._pi2=Math.PI / 180; Utils._extReg=/\.(\w+)\??/g; Utils.parseXMLFromString=function(value){ var rst; value=value.replace(/>\s+<'); /*__JS__ */rst=(new DOMParser()).parseFromString(value,'text/xml'); if (rst.firstChild.textContent.indexOf("This page contains the following errors")>-1){ throw new Error(rst.firstChild.firstChild.textContent); } return rst; } return Utils; })() /** *@private */ //class laya.utils.VectorGraphManager var VectorGraphManager=(function(){ function VectorGraphManager(){ this.useDic={}; this.shapeDic={}; this.shapeLineDic={}; this._id=0; this._checkKey=false; this._freeIdArray=[]; if (Render.isWebGL){ CacheManager.regCacheByFunction(Utils.bind(this.startDispose,this),Utils.bind(this.getCacheList,this)); } } __class(VectorGraphManager,'laya.utils.VectorGraphManager'); var __proto=VectorGraphManager.prototype; /** *得到个空闲的ID *@return */ __proto.getId=function(){ return this._id++; } /** *添加一个图形到列表中 *@param id *@param shape */ __proto.addShape=function(id,shape){ this.shapeDic[id]=shape; if (!this.useDic[id]){ this.useDic[id]=true; } } /** *添加一个线图形到列表中 *@param id *@param Line */ __proto.addLine=function(id,Line){ this.shapeLineDic[id]=Line; if (!this.shapeLineDic[id]){ this.shapeLineDic[id]=true; } } /** *检测一个对象是否在使用中 *@param id */ __proto.getShape=function(id){ if (this._checkKey){ if (this.useDic[id] !=null){ this.useDic[id]=true; } } } /** *删除一个图形对象 *@param id */ __proto.deleteShape=function(id){ if (this.shapeDic[id]){ this.shapeDic[id]=null; delete this.shapeDic[id]; } if (this.shapeLineDic[id]){ this.shapeLineDic[id]=null; delete this.shapeLineDic[id]; } if (this.useDic[id] !=null){ delete this.useDic[id]; } } /** *得到缓存列表 *@return */ __proto.getCacheList=function(){ var str; var list=[]; for (str in this.shapeDic){ list.push(this.shapeDic[str]); } for (str in this.shapeLineDic){ list.push(this.shapeLineDic[str]); } return list; } /** *开始清理状态,准备销毁 */ __proto.startDispose=function(key){ var str; for (str in this.useDic){ this.useDic[str]=false; } this._checkKey=true; } /** *确认销毁 */ __proto.endDispose=function(){ if (this._checkKey){ var str; for (str in this.useDic){ if (!this.useDic[str]){ this.deleteShape(str); } } this._checkKey=false; } } VectorGraphManager.getInstance=function(){ return VectorGraphManager.instance=VectorGraphManager.instance|| new VectorGraphManager(); } VectorGraphManager.instance=null; return VectorGraphManager; })() /** *封装弱引用WeakMap *如果支持WeakMap,则使用WeakMap,如果不支持,则用Object代替 *注意:如果采用Object,为了防止内存泄漏,则采用定时清理缓存策略 */ //class laya.utils.WeakObject var WeakObject=(function(){ function WeakObject(){ /**@private */ this._obj=null; this._obj=WeakObject.supportWeakMap ? new Browser.window.WeakMap():{}; if (!WeakObject.supportWeakMap)WeakObject._maps.push(this); } __class(WeakObject,'laya.utils.WeakObject'); var __proto=WeakObject.prototype; /** *设置缓存 *@param key kye对象,可被回收 *@param value object对象,可被回收 */ __proto.set=function(key,value){ if (key==null)return; if (WeakObject.supportWeakMap){ var objKey=key; if ((typeof key=='string')|| (typeof key=='number')){ objKey=WeakObject._keys[key]; if (!objKey)objKey=WeakObject._keys[key]={k:key}; } this._obj.set(objKey,value); }else { if ((typeof key=='string')|| (typeof key=='number')){ this._obj[key]=value; }else { key.$_GID || (key.$_GID=Utils.getGID()); this._obj[key.$_GID]=value; } } } /** *获取缓存 *@param key kye对象,可被回收 */ __proto.get=function(key){ if (key==null)return null; if (WeakObject.supportWeakMap){ var objKey=((typeof key=='string')|| (typeof key=='number'))? WeakObject._keys[key] :key; if (!objKey)return null; return this._obj.get(objKey); }else { if ((typeof key=='string')|| (typeof key=='number'))return this._obj[key]; return this._obj[key.$_GID]; } } /** *删除缓存 */ __proto.del=function(key){ if (key==null)return; if (WeakObject.supportWeakMap){ var objKey=((typeof key=='string')|| (typeof key=='number'))? WeakObject._keys[key] :key; if (!objKey)return; /*__JS__ */this._obj.delete(objKey); }else { if ((typeof key=='string')|| (typeof key=='number'))delete this._obj[key]; else delete this._obj[this._obj.$_GID]; } } /** *是否有缓存 */ __proto.has=function(key){ if (key==null)return false; if (WeakObject.supportWeakMap){ var objKey=((typeof key=='string')|| (typeof key=='number'))? WeakObject._keys[key] :key; return this._obj.has(objKey); }else { if ((typeof key=='string')|| (typeof key=='number'))return this._obj[key] !=null; return this._obj[this._obj.$_GID] !=null; } } WeakObject.__init__=function(){ WeakObject.supportWeakMap=Browser.window.WeakMap !=null; if (!WeakObject.supportWeakMap)Laya.timer.loop(WeakObject.delInterval,null,WeakObject.clearCache); } WeakObject.clearCache=function(){ for (var i=0,n=WeakObject._maps.length;i < n;i++){ var obj=WeakObject._maps[i]; obj._obj={}; } } WeakObject.supportWeakMap=false; WeakObject.delInterval=5 *60 *1000; WeakObject._keys={}; WeakObject._maps=[]; __static(WeakObject, ['I',function(){return this.I=new WeakObject();} ]); return WeakObject; })() /** *@private */ //class laya.utils.WordText var WordText=(function(){ function WordText(){ this.id=NaN; this.save=[]; this.toUpperCase=null; this.changed=false; this._text=null; } __class(WordText,'laya.utils.WordText'); var __proto=WordText.prototype; __proto.setText=function(txt){ this.changed=true; this._text=txt; } __proto.toString=function(){ return this._text; } __proto.charCodeAt=function(i){ return this._text ? this._text.charCodeAt(i):NaN; } __proto.charAt=function(i){ return this._text ? this._text.charAt(i):null; } __getset(0,__proto,'length',function(){ return this._text ? this._text.length :0; }); return WordText; })() /** *Node 类是可放在显示列表中的所有对象的基类。该显示列表管理 Laya 运行时中显示的所有对象。使用 Node 类排列显示列表中的显示对象。Node 对象可以有子显示对象。 */ //class laya.display.Node extends laya.events.EventDispatcher var Node=(function(_super){ function Node(){ /**@private */ this._bits=0; /**@private 是否在显示列表中显示*/ this._displayedInStage=false; /**@private 父节点对象*/ this._parent=null; /**@private */ this.conchModel=null; /**节点名称。*/ this.name=""; /**[只读]是否已经销毁。对象销毁后不能再使用。*/ this._destroyed=false; Node.__super.call(this); this._childs=Node.ARRAY_EMPTY; this._$P=Node.PROP_EMPTY; this.timer=Laya.scaleTimer; this.conchModel=Render.isConchNode ? this.createConchModel():null; } __class(Node,'laya.display.Node',_super); var __proto=Node.prototype; /**@private */ __proto._setBit=function(type,value){ if (type==0x1){ var preValue=this._getBit(type); if (preValue !=value){ this._updateDisplayedInstage(); } } if (value){ this._bits |=type; }else { this._bits &=~type; } } /**@private */ __proto._getBit=function(type){ return (this._bits & type)!=0; } /**@private */ __proto._setUpNoticeChain=function(){ if (this._getBit(0x1)){ this._setUpNoticeType(0x1); } } /**@private */ __proto._setUpNoticeType=function(type){ var ele=this; ele._setBit(type,true); ele=ele.parent; while (ele){ if (ele._getBit(type))return; ele._setBit(type,true); ele=ele.parent; } } /** *

    增加事件侦听器,以使侦听器能够接收事件通知。

    *

    如果侦听鼠标事件,则会自动设置自己和父亲节点的属性 mouseEnabled 的值为 true(如果父节点mouseEnabled=false,则停止设置父节点mouseEnabled属性)。

    *@param type 事件的类型。 *@param caller 事件侦听函数的执行域。 *@param listener 事件侦听函数。 *@param args (可选)事件侦听函数的回调参数。 *@return 此 EventDispatcher 对象。 */ __proto.on=function(type,caller,listener,args){ if (type===/*laya.events.Event.DISPLAY*/"display" || type===/*laya.events.Event.UNDISPLAY*/"undisplay"){ if (!this._getBit(0x1)){ this._setUpNoticeType(0x1); } } return this._createListener(type,caller,listener,args,false); } /** *

    增加事件侦听器,以使侦听器能够接收事件通知,此侦听事件响应一次后则自动移除侦听。

    *

    如果侦听鼠标事件,则会自动设置自己和父亲节点的属性 mouseEnabled 的值为 true(如果父节点mouseEnabled=false,则停止设置父节点mouseEnabled属性)。

    *@param type 事件的类型。 *@param caller 事件侦听函数的执行域。 *@param listener 事件侦听函数。 *@param args (可选)事件侦听函数的回调参数。 *@return 此 EventDispatcher 对象。 */ __proto.once=function(type,caller,listener,args){ if (type===/*laya.events.Event.DISPLAY*/"display" || type===/*laya.events.Event.UNDISPLAY*/"undisplay"){ if (!this._getBit(0x1)){ this._setUpNoticeType(0x1); } } return this._createListener(type,caller,listener,args,true); } /**@private */ __proto.createConchModel=function(){ return null; } /** *

    销毁此对象。destroy对象默认会把自己从父节点移除,并且清理自身引用关系,等待js自动垃圾回收机制回收。destroy后不能再使用。

    *

    destroy时会移除自身的事情监听,自身的timer监听,移除子对象及从父节点移除自己。

    *@param destroyChild (可选)是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); this._destroyed=true; this._parent && this._parent.removeChild(this); if (this._childs){ if (destroyChild)this.destroyChildren(); else this.removeChildren(); } this._childs=null; this._$P=null; this.offAll(); this.timer.clearAll(this); } /** *销毁所有子对象,不销毁自己本身。 */ __proto.destroyChildren=function(){ if (this._childs){ for (var i=this._childs.length-1;i >-1;i--){ this._childs[i].destroy(true); } } } /** *添加子节点。 *@param node 节点对象 *@return 返回添加的节点 */ __proto.addChild=function(node){ if (!node || this.destroyed || node===this)return node; if ((node).zOrder)this._set$P("hasZorder",true); if (node._parent===this){ var index=this.getChildIndex(node); if (index!==this._childs.length-1){ this._childs.splice(index,1); this._childs.push(node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,this._childs.length-1); } this._childChanged(); } }else { node.parent && node.parent.removeChild(node); this._childs===Node.ARRAY_EMPTY && (this._childs=[]); this._childs.push(node); this.conchModel && this.conchModel.addChildAt(node.conchModel,this._childs.length-1); node.parent=this; this._childChanged(); } return node; } /** *批量增加子节点 *@param ...args 无数子节点。 */ __proto.addChildren=function(__args){ var args=arguments; var i=0,n=args.length; while (i < n){ this.addChild(args[i++]); } } /** *添加子节点到指定的索引位置。 *@param node 节点对象。 *@param index 索引位置。 *@return 返回添加的节点。 */ __proto.addChildAt=function(node,index){ if (!node || this.destroyed || node===this)return node; if ((node).zOrder)this._set$P("hasZorder",true); if (index >=0 && index <=this._childs.length){ if (node._parent===this){ var oldIndex=this.getChildIndex(node); this._childs.splice(oldIndex,1); this._childs.splice(index,0,node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,index); } this._childChanged(); }else { node.parent && node.parent.removeChild(node); this._childs===Node.ARRAY_EMPTY && (this._childs=[]); this._childs.splice(index,0,node); this.conchModel && this.conchModel.addChildAt(node.conchModel,index); node.parent=this; } return node; }else { throw new Error("appendChildAt:The index is out of bounds"); } } /** *根据子节点对象,获取子节点的索引位置。 *@param node 子节点。 *@return 子节点所在的索引位置。 */ __proto.getChildIndex=function(node){ return this._childs.indexOf(node); } /** *根据子节点的名字,获取子节点对象。 *@param name 子节点的名字。 *@return 节点对象。 */ __proto.getChildByName=function(name){ var nodes=this._childs; if (nodes){ for (var i=0,n=nodes.length;i < n;i++){ var node=nodes[i]; if (node.name===name)return node; } } return null; } /**@private */ __proto._get$P=function(key){ return this._$P[key]; } /**@private */ __proto._set$P=function(key,value){ if (!this.destroyed){ this._$P===Node.PROP_EMPTY && (this._$P={}); this._$P[key]=value; } return value; } /** *根据子节点的索引位置,获取子节点对象。 *@param index 索引位置 *@return 子节点 */ __proto.getChildAt=function(index){ return this._childs[index]; } /** *设置子节点的索引位置。 *@param node 子节点。 *@param index 新的索引。 *@return 返回子节点本身。 */ __proto.setChildIndex=function(node,index){ var childs=this._childs; if (index < 0 || index >=childs.length){ throw new Error("setChildIndex:The index is out of bounds."); }; var oldIndex=this.getChildIndex(node); if (oldIndex < 0)throw new Error("setChildIndex:node is must child of this object."); childs.splice(oldIndex,1); childs.splice(index,0,node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,index); } this._childChanged(); return node; } /** *@private *子节点发生改变。 *@param child 子节点。 */ __proto._childChanged=function(child){} /** *删除子节点。 *@param node 子节点 *@return 被删除的节点 */ __proto.removeChild=function(node){ if (!this._childs)return node; var index=this._childs.indexOf(node); return this.removeChildAt(index); } /** *从父容器删除自己,如已经被删除不会抛出异常。 *@return 当前节点( Node )对象。 */ __proto.removeSelf=function(){ this._parent && this._parent.removeChild(this); return this; } /** *根据子节点名字删除对应的子节点对象,如果找不到不会抛出异常。 *@param name 对象名字。 *@return 查找到的节点( Node )对象。 */ __proto.removeChildByName=function(name){ var node=this.getChildByName(name); node && this.removeChild(node); return node; } /** *根据子节点索引位置,删除对应的子节点对象。 *@param index 节点索引位置。 *@return 被删除的节点。 */ __proto.removeChildAt=function(index){ var node=this.getChildAt(index); if (node){ this._childs.splice(index,1); this.conchModel && this.conchModel.removeChild(node.conchModel); node.parent=null; } return node; } /** *删除指定索引区间的所有子对象。 *@param beginIndex 开始索引。 *@param endIndex 结束索引。 *@return 当前节点对象。 */ __proto.removeChildren=function(beginIndex,endIndex){ (beginIndex===void 0)&& (beginIndex=0); (endIndex===void 0)&& (endIndex=0x7fffffff); if (this._childs && this._childs.length > 0){ var childs=this._childs; if (beginIndex===0 && endIndex >=n){ var arr=childs; this._childs=Node.ARRAY_EMPTY; }else { arr=childs.splice(beginIndex,endIndex-beginIndex); } for (var i=0,n=arr.length;i < n;i++){ arr[i].parent=null; this.conchModel && this.conchModel.removeChild(arr[i].conchModel); } } return this; } /** *替换子节点。 *@internal 将传入的新节点对象替换到已有子节点索引位置处。 *@param newNode 新节点。 *@param oldNode 老节点。 *@return 返回新节点。 */ __proto.replaceChild=function(newNode,oldNode){ var index=this._childs.indexOf(oldNode); if (index >-1){ this._childs.splice(index,1,newNode); if (this.conchModel){ this.conchModel.removeChild(oldNode.conchModel); this.conchModel.addChildAt(newNode.conchModel,index); } oldNode.parent=null; newNode.parent=this; return newNode; } return null; } /**@private */ __proto._updateDisplayedInstage=function(){ var ele; ele=this; var stage=Laya.stage; this._displayedInStage=false; while (ele){ if (ele._getBit(0x1)){ this._displayedInStage=ele._displayedInStage; break ; } if (ele==stage || ele._displayedInStage){ this._displayedInStage=true; break ; } ele=ele.parent; } } /**@private */ __proto._setDisplay=function(value){ if (this._displayedInStage!==value){ this._displayedInStage=value; if (value)this.event(/*laya.events.Event.DISPLAY*/"display"); else this.event(/*laya.events.Event.UNDISPLAY*/"undisplay"); } } /** *@private *设置指定节点对象是否可见(是否在渲染列表中)。 *@param node 节点。 *@param display 是否可见。 */ __proto._displayChild=function(node,display){ var childs=node._childs; if (childs){ for (var i=0,n=childs.length;i < n;i++){ var child=childs[i]; if (!child._getBit(0x1))continue ; if (child._childs.length > 0){ this._displayChild(child,display); }else { child._setDisplay(display); } } } node._setDisplay(display); } /** *当前容器是否包含指定的 Node 节点对象 。 *@param node 指定的 Node 节点对象 。 *@return 一个布尔值表示是否包含指定的 Node 节点对象 。 */ __proto.contains=function(node){ if (node===this)return true; while (node){ if (node.parent===this)return true; node=node.parent; } return false; } /** *定时重复执行某函数。功能同Laya.timer.timerLoop()。 *@param delay 间隔时间(单位毫秒)。 *@param caller 执行域(this)。 *@param method 结束时的回调方法。 *@param args (可选)回调参数。 *@param coverBefore (可选)是否覆盖之前的延迟执行,默认为true。 *@param jumpFrame 时钟是否跳帧。基于时间的循环回调,单位时间间隔内,如能执行多次回调,出于性能考虑,引擎默认只执行一次,设置jumpFrame=true后,则回调会连续执行多次 */ __proto.timerLoop=function(delay,caller,method,args,coverBefore,jumpFrame){ (coverBefore===void 0)&& (coverBefore=true); (jumpFrame===void 0)&& (jumpFrame=false); this.timer.loop(delay,caller,method,args,coverBefore,jumpFrame); } /** *定时执行某函数一次。功能同Laya.timer.timerOnce()。 *@param delay 延迟时间(单位毫秒)。 *@param caller 执行域(this)。 *@param method 结束时的回调方法。 *@param args (可选)回调参数。 *@param coverBefore (可选)是否覆盖之前的延迟执行,默认为true。 */ __proto.timerOnce=function(delay,caller,method,args,coverBefore){ (coverBefore===void 0)&& (coverBefore=true); this.timer._create(false,false,delay,caller,method,args,coverBefore); } /** *定时重复执行某函数(基于帧率)。功能同Laya.timer.frameLoop()。 *@param delay 间隔几帧(单位为帧)。 *@param caller 执行域(this)。 *@param method 结束时的回调方法。 *@param args (可选)回调参数。 *@param coverBefore (可选)是否覆盖之前的延迟执行,默认为true。 */ __proto.frameLoop=function(delay,caller,method,args,coverBefore){ (coverBefore===void 0)&& (coverBefore=true); this.timer._create(true,true,delay,caller,method,args,coverBefore); } /** *定时执行一次某函数(基于帧率)。功能同Laya.timer.frameOnce()。 *@param delay 延迟几帧(单位为帧)。 *@param caller 执行域(this) *@param method 结束时的回调方法 *@param args (可选)回调参数 *@param coverBefore (可选)是否覆盖之前的延迟执行,默认为true */ __proto.frameOnce=function(delay,caller,method,args,coverBefore){ (coverBefore===void 0)&& (coverBefore=true); this.timer._create(true,false,delay,caller,method,args,coverBefore); } /** *清理定时器。功能同Laya.timer.clearTimer()。 *@param caller 执行域(this)。 *@param method 结束时的回调方法。 */ __proto.clearTimer=function(caller,method){ this.timer.clear(caller,method); } /** *子对象数量。 */ __getset(0,__proto,'numChildren',function(){ return this._childs.length; }); /** *[只读]是否已经销毁。对象销毁后不能再使用。 *@return */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); /**父节点。*/ __getset(0,__proto,'parent',function(){ return this._parent; },function(value){ if (this._parent!==value){ if (value){ this._parent=value; this.event(/*laya.events.Event.ADDED*/"added"); if (this._getBit(0x1)){ this._setUpNoticeChain(); value.displayedInStage && this._displayChild(this,true); } value._childChanged(this); }else { this.event(/*laya.events.Event.REMOVED*/"removed"); this._parent._childChanged(); if (this._getBit(0x1))this._displayChild(this,false); this._parent=value; } } }); /**表示是否在显示列表中显示。*/ __getset(0,__proto,'displayedInStage',function(){ if (this._getBit(0x1))return this._displayedInStage; this._setUpNoticeType(0x1); return this._displayedInStage; }); Node.ARRAY_EMPTY=[]; Node.PROP_EMPTY={}; Node.NOTICE_DISPLAY=0x1; Node.MOUSEENABLE=0x2; return Node; })(EventDispatcher) /** *@private *CSSStyle 类是元素CSS样式定义类。 */ //class laya.display.css.CSSStyle extends laya.display.css.Style var CSSStyle=(function(_super){ function CSSStyle(ower){ this._bgground=null; this._border=null; //this._ower=null; this._rect=null; /**@private */ this.underLine=0; /**行高。 */ this.lineHeight=0; CSSStyle.__super.call(this); this._padding=CSSStyle._PADDING; this._spacing=CSSStyle._SPACING; this._aligns=CSSStyle._ALIGNS; this._font=Font.EMPTY; this._ower=ower; } __class(CSSStyle,'laya.display.css.CSSStyle',_super); var __proto=CSSStyle.prototype; /**@inheritDoc */ __proto.destroy=function(){ this._ower=null; this._font=null; this._rect=null; } /** *复制传入的 CSSStyle 属性值。 *@param src 待复制的 CSSStyle 对象。 */ __proto.inherit=function(src){ this._font=src._font; this._spacing=src._spacing===CSSStyle._SPACING ? CSSStyle._SPACING :src._spacing.slice(); this.lineHeight=src.lineHeight; } /**@private */ __proto._widthAuto=function(){ return (this._type & 0x40000)!==0; } /**@inheritDoc */ __proto.widthed=function(sprite){ return (this._type & 0x8)!=0; } /** *@private */ __proto._calculation=function(type,value){ if (value.indexOf('%')< 0)return false; var ower=this._ower; var parent=ower.parent; var rect=this._rect; function getValue (pw,w,nums){ return (pw *nums[0]+w *nums[1]+nums[2]); } function onParentResize (type){ var pw=parent.width,w=ower.width; rect.width && (ower.width=getValue(pw,w,rect.width)); rect.height && (ower.height=getValue(pw,w,rect.height)); rect.left && (ower.x=getValue(pw,w,rect.left)); rect.top && (ower.y=getValue(pw,w,rect.top)); } if (rect===null){ parent._getCSSStyle()._type |=0x80000; parent.on(/*laya.events.Event.RESIZE*/"resize",this,onParentResize); this._rect=rect={input:{}}; }; var nums=value.split(' '); nums[0]=parseFloat(nums[0])/ 100; if (nums.length==1) nums[1]=nums[2]=0; else { nums[1]=parseFloat(nums[1])/ 100; nums[2]=parseFloat(nums[2]); } rect[type]=nums; rect.input[type]=value; onParentResize(type); return true; } /** *是否已设置高度。 *@param sprite 显示对象 Sprite。 *@return 一个Boolean 表示是否已设置高度。 */ __proto.heighted=function(sprite){ return (this._type & 0x2000)!=0; } /** *设置宽高。 *@param w 宽度。 *@param h 高度。 */ __proto.size=function(w,h){ var ower=this._ower; var resize=false; if (w!==-1 && w !=this._ower.width){ this._type |=0x8; this._ower.width=w; resize=true; } if (h!==-1 && h !=this._ower.height){ this._type |=0x2000; this._ower.height=h; resize=true; } if (resize){ ower._layoutLater(); (this._type & 0x80000)&& ower.event(/*laya.events.Event.RESIZE*/"resize",this); } } /**@private */ __proto._getAlign=function(){ return this._aligns[0]; } /**@private */ __proto._getValign=function(){ return this._aligns[1]; } /**@private */ __proto._getCssFloat=function(){ return (this._type & 0x8000)!=0 ? 0x8000 :0; } __proto._createFont=function(){ return (this._type & 0x1000)? this._font :(this._type |=0x1000,this._font=new Font(this._font)); } /**@inheritDoc */ __proto.render=function(sprite,context,x,y){ var w=sprite.width; var h=sprite.height; x-=sprite.pivotX; y-=sprite.pivotY; this._bgground && this._bgground.color !=null && context.ctx.fillRect(x,y,w,h,this._bgground.color); this._border && this._border.color && context.drawRect(x,y,w,h,this._border.color.strColor,this._border.size); } /**@inheritDoc */ __proto.getCSSStyle=function(){ return this; } /** *设置 CSS 样式字符串。 *@param text CSS样式字符串。 */ __proto.cssText=function(text){ this.attrs(CSSStyle.parseOneCSS(text,';')); } /** *根据传入的属性名、属性值列表,设置此对象的属性值。 *@param attrs 属性名与属性值列表。 */ __proto.attrs=function(attrs){ if (attrs){ for (var i=0,n=attrs.length;i < n;i++){ var attr=attrs[i]; this[attr[0]]=attr[1]; } } } /**@inheritDoc */ __proto.setTransform=function(value){ (value==='none')? (this._tf=Style._TF_EMPTY):this.attrs(CSSStyle.parseOneCSS(value,',')); } /** *定义 X 轴、Y 轴移动转换。 *@param x X 轴平移量。 *@param y Y 轴平移量。 */ __proto.translate=function(x,y){ this._tf===Style._TF_EMPTY && (this._tf=new TransformInfo()); this._tf.translateX=x; this._tf.translateY=y; } /** *定义 缩放转换。 *@param x X 轴缩放值。 *@param y Y 轴缩放值。 */ __proto.scale=function(x,y){ this._tf===Style._TF_EMPTY && (this._tf=new TransformInfo()); this._tf.scaleX=x; this._tf.scaleY=y; } /**@private */ __proto._enableLayout=function(){ return (this._type & 0x2)===0 && (this._type & 0x4)===0; } /** *是否显示为块级元素。 */ __getset(0,__proto,'block',_super.prototype._$get_block,function(value){ value ? (this._type |=0x1):(this._type &=(~0x1)); }); /** *垂直对齐方式。 */ __getset(0,__proto,'valign',function(){ return CSSStyle._valigndef[this._aligns[1]]; },function(value){ this._aligns===CSSStyle._ALIGNS && (this._aligns=[0,0,0]); this._aligns[1]=CSSStyle._valigndef[value]; }); /** *高度。 */ __getset(0,__proto,'height',null,function(h){ this._type |=0x2000; if ((typeof h=='string')){ if (this._calculation("height",h))return; h=parseInt(h); } this.size(-1,h); }); /** *宽度。 */ __getset(0,__proto,'width',null,function(w){ this._type |=0x8; if ((typeof w=='string')){ var offset=w.indexOf('auto'); if (offset >=0){ this._type |=0x40000; w=w.substr(0,offset); } if (this._calculation("width",w))return; w=parseInt(w); } this.size(w,-1); }); /** *字体粗细。 */ __getset(0,__proto,'fontWeight',function(){ return this._font.weight; },function(value){ this._createFont().weight=value; }); /** *表示左边距。 */ __getset(0,__proto,'left',null,function(value){ var ower=this._ower; if (((typeof value=='string'))){ if (value==="center") value="50% -50% 0"; else if (value==="right") value="100% -100% 0"; if (this._calculation("left",value))return; value=parseInt(value); } ower.x=value; }); __getset(0,__proto,'_translate',null,function(value){ this.translate(value[0],value[1]); }); /**@inheritDoc */ __getset(0,__proto,'absolute',function(){ return (this._type & 0x4)!==0; }); /** *表示上边距。 */ __getset(0,__proto,'top',null,function(value){ var ower=this._ower; if (((typeof value=='string'))){ if (value==="middle") value="50% -50% 0"; else if (value==="bottom") value="100% -100% 0"; if (this._calculation("top",value))return; value=parseInt(value); } ower.y=value; }); /** *水平对齐方式。 */ __getset(0,__proto,'align',function(){ return CSSStyle._aligndef[this._aligns[0]]; },function(value){ this._aligns===CSSStyle._ALIGNS && (this._aligns=[0,0,0]); this._aligns[0]=CSSStyle._aligndef[value]; }); /** *表示是否加粗。 */ __getset(0,__proto,'bold',function(){ return this._font.bold; },function(value){ this._createFont().bold=value; }); /** *边距信息。 */ __getset(0,__proto,'padding',function(){ return this._padding; },function(value){ this._padding=value; }); /** *行间距。 */ __getset(0,__proto,'leading',function(){ return this._spacing[1]; },function(d){ ((typeof d=='string'))&& (d=parseInt(d+"")); this._spacing===CSSStyle._SPACING && (this._spacing=[0,0]); this._spacing[1]=d; }); /** *是否是行元素。 */ __getset(0,__proto,'lineElement',function(){ return (this._type & 0x10000)!=0; },function(value){ value ? (this._type |=0x10000):(this._type &=(~0x10000)); }); /** *浮动方向。 */ __getset(0,__proto,'cssFloat',function(){ return (this._type & 0x8000)!=0 ? "right" :"left"; },function(value){ this.lineElement=false; value==="right" ? (this._type |=0x8000):(this._type &=(~0x8000)); }); /** *添加到文本的修饰。 */ __getset(0,__proto,'textDecoration',function(){ return this._font.decoration; },function(value){ this._createFont().decoration=value; }); /** *设置如何处理元素内的空白。 */ __getset(0,__proto,'whiteSpace',function(){ return (this._type & 0x20000)? "nowrap" :""; },function(type){ type==="nowrap" && (this._type |=0x20000); type==="none" && (this._type &=~0x20000); }); __getset(0,__proto,'background',null,function(value){ if (!value){ this._bgground=null; return; } this._bgground || (this._bgground={}); this._bgground.color=value; this._ower.conchModel && this._ower.conchModel.bgColor(value); this._type |=0x4000; this._ower._renderType |=/*laya.renders.RenderSprite.STYLE*/0x100; }); /** *表示是否换行。 */ __getset(0,__proto,'wordWrap',function(){ return (this._type & 0x20000)===0; },function(value){ value ? (this._type &=~0x20000):(this._type |=0x20000); }); /** *字体颜色。 */ __getset(0,__proto,'color',function(){ return this._font.color; },function(value){ this._createFont().color=value; }); /** *

    指定文本字段是否是密码文本字段。

    *如果此属性的值为 true,则文本字段被视为密码文本字段,并使用星号而不是实际字符来隐藏输入的字符。如果为 false,则不会将文本字段视为密码文本字段。 */ __getset(0,__proto,'password',function(){ return this._font.password; },function(value){ this._createFont().password=value; }); /** *背景颜色。 */ __getset(0,__proto,'backgroundColor',function(){ return this._bgground ? this._bgground.color :null; },function(value){ if (value==='none')this._bgground=null; else (this._bgground || (this._bgground={}),this._bgground.color=value); this._ower.conchModel && this._ower.conchModel.bgColor(value); this._ower._renderType |=/*laya.renders.RenderSprite.STYLE*/0x100; }); /** *字体信息。 */ __getset(0,__proto,'font',function(){ return this._font.toString(); },function(value){ this._createFont().set(value); }); /** *文本的粗细。 */ __getset(0,__proto,'weight',null,function(value){ this._createFont().weight=value; }); /** *间距。 */ __getset(0,__proto,'letterSpacing',function(){ return this._spacing[0]; },function(d){ ((typeof d=='string'))&& (d=parseInt(d+"")); this._spacing===CSSStyle._SPACING && (this._spacing=[0,0]); this._spacing[0]=d; }); /** *字体大小。 */ __getset(0,__proto,'fontSize',function(){ return this._font.size; },function(value){ this._createFont().size=value; }); /** *表示是否为斜体。 */ __getset(0,__proto,'italic',function(){ return this._font.italic; },function(value){ this._createFont().italic=value; }); /** *字体系列。 */ __getset(0,__proto,'fontFamily',function(){ return this._font.family; },function(value){ this._createFont().family=value; }); /** *

    描边宽度(以像素为单位)。

    *默认值0,表示不描边。 *@default 0 */ __getset(0,__proto,'stroke',function(){ return this._font.stroke[0]; },function(value){ if (this._createFont().stroke===Font._STROKE)this._font.stroke=[0,"#000000"]; this._font.stroke[0]=value; }); /** *

    描边颜色,以字符串表示。

    *@default "#000000"; */ __getset(0,__proto,'strokeColor',function(){ return this._font.stroke[1]; },function(value){ if (this._createFont().stroke===Font._STROKE)this._font.stroke=[0,"#000000"]; this._font.stroke[1]=value; }); /** *边框属性,比如border="5px solid red" */ __getset(0,__proto,'border',function(){ return this._border ? this._border.value :""; },function(value){ if (value=='none'){ this._border=null; return; } this._border || (this._border={}); this._border.value=value; var values=value.split(' '); this._border.color=Color.create(values[values.length-1]); if (values.length==1){ this._border.size=1; this._border.type='solid'; return; }; var i=0; if (values[0].indexOf('px')> 0){ this._border.size=parseInt(values[0]); i++; }else this._border.size=1; this._border.type=values[i]; this._ower._renderType |=/*laya.renders.RenderSprite.STYLE*/0x100; }); /** *边框的颜色。 */ __getset(0,__proto,'borderColor',function(){ return (this._border && this._border.color)? this._border.color.strColor :null; },function(value){ if (!value){ this._border=null; return; } this._border || (this._border={size:1,type:'solid'}); this._border.color=(value==null)? null :Color.create(value); this._ower.conchModel && this._ower.conchModel.border(this._border.color.strColor); this._ower._renderType |=/*laya.renders.RenderSprite.STYLE*/0x100; }); /** *元素的定位类型。 */ __getset(0,__proto,'position',function(){ return (this._type & 0x4)? "absolute" :""; },function(value){ value=="absolute" ? (this._type |=0x4):(this._type &=~0x4); }); /** *规定元素应该生成的框的类型。 */ __getset(0,__proto,'display',null,function(value){ switch (value){ case '': this._type &=~0x2; this.visible=true; break ; case 'none': this._type |=0x2; this.visible=false; this._ower._layoutLater(); break ; } }); /**@inheritDoc */ __getset(0,__proto,'paddingLeft',function(){ return this.padding[3]; }); /**@inheritDoc */ __getset(0,__proto,'paddingTop',function(){ return this.padding[0]; }); __getset(0,__proto,'_scale',null,function(value){ this._ower.scale(value[0],value[1]); }); __getset(0,__proto,'_rotate',null,function(value){ this._ower.rotation=value; }); CSSStyle.parseOneCSS=function(text,clipWord){ var out=[]; var attrs=text.split(clipWord); var valueArray; for (var i=0,n=attrs.length;i < n;i++){ var attr=attrs[i]; var ofs=attr.indexOf(':'); var name=attr.substr(0,ofs).replace(/^\s+|\s+$/g,''); if (name.length==0) continue ; var value=attr.substr(ofs+1).replace(/^\s+|\s+$/g,''); var one=[name,value]; switch (name){ case 'italic': case 'bold': one[1]=value=="true"; break ; case 'line-height': one[0]='lineHeight'; one[1]=parseInt(value); break ; case 'font-size': one[0]='fontSize'; one[1]=parseInt(value); break ; case 'padding': valueArray=value.split(' '); valueArray.length > 1 || (valueArray[1]=valueArray[2]=valueArray[3]=valueArray[0]); one[1]=[parseInt(valueArray[0]),parseInt(valueArray[1]),parseInt(valueArray[2]),parseInt(valueArray[3])]; break ; case 'rotate': one[0]="_rotate"; one[1]=parseFloat(value); break ; case 'scale': valueArray=value.split(' '); one[0]="_scale"; one[1]=[parseFloat(valueArray[0]),parseFloat(valueArray[1])]; break ; case 'translate': valueArray=value.split(' '); one[0]="_translate"; one[1]=[parseInt(valueArray[0]),parseInt(valueArray[1])]; break ; default : (one[0]=CSSStyle._CSSTOVALUE[name])|| (one[0]=name); } out.push(one); } return out; } CSSStyle.parseCSS=function(text,uri){ var one; while ((one=CSSStyle._parseCSSRegExp.exec(text))!=null){ CSSStyle.styleSheets[one[1]]=CSSStyle.parseOneCSS(one[2],';'); } } CSSStyle.EMPTY=new CSSStyle(null); CSSStyle._CSSTOVALUE={'letter-spacing':'letterSpacing','line-spacing':'lineSpacing','white-space':'whiteSpace','line-height':'lineHeight','scale-x':'scaleX','scale-y':'scaleY','translate-x':'translateX','translate-y':'translateY','font-family':'fontFamily','font-weight':'fontWeight','vertical-align':'valign','text-decoration':'textDecoration','background-color':'backgroundColor','border-color':'borderColor','float':'cssFloat'}; CSSStyle._parseCSSRegExp=new RegExp("([\.\#]\\w+)\\s*{([\\s\\S]*?)}","g"); CSSStyle._aligndef={'left':0,'center':1,'right':2,0:'left',1:'center',2:'right'}; CSSStyle._valigndef={'top':0,'middle':1,'bottom':2,0:'top',1:'middle',2:'bottom'}; CSSStyle.styleSheets={}; CSSStyle.ALIGN_CENTER=1; CSSStyle.ALIGN_RIGHT=2; CSSStyle.VALIGN_MIDDLE=1; CSSStyle.VALIGN_BOTTOM=2; CSSStyle._CSS_BLOCK=0x1; CSSStyle._DISPLAY_NONE=0x2; CSSStyle._ABSOLUTE=0x4; CSSStyle._WIDTH_SET=0x8; CSSStyle._PADDING=[0,0,0,0]; CSSStyle._RECT=[-1,-1,-1,-1]; CSSStyle._SPACING=[0,0]; CSSStyle._ALIGNS=[0,0,0]; CSSStyle.ADDLAYOUTED=0x200; CSSStyle._NEWFONT=0x1000; CSSStyle._HEIGHT_SET=0x2000; CSSStyle._BACKGROUND_SET=0x4000; CSSStyle._FLOAT_RIGHT=0x8000; CSSStyle._LINE_ELEMENT=0x10000; CSSStyle._NOWARP=0x20000; CSSStyle._WIDTHAUTO=0x40000; CSSStyle._LISTERRESZIE=0x80000; return CSSStyle; })(Style) /** *@private *使用Audio标签播放声音 */ //class laya.media.h5audio.AudioSound extends laya.events.EventDispatcher var AudioSound=(function(_super){ function AudioSound(){ /** *声音URL */ this.url=null; /** *播放用的audio标签 */ this.audio=null; /** *是否已加载完成 */ this.loaded=false; AudioSound.__super.call(this); } __class(AudioSound,'laya.media.h5audio.AudioSound',_super); var __proto=AudioSound.prototype; /** *释放声音 * */ __proto.dispose=function(){ var ad=AudioSound._audioCache[this.url]; Pool.clearBySign("audio:"+this.url); if (ad){ if (!Render.isConchApp){ ad.src=""; } delete AudioSound._audioCache[this.url]; } } /** *加载声音 *@param url * */ __proto.load=function(url){ url=URL.formatURL(url); this.url=url; var ad; if (url==SoundManager._tMusic){ AudioSound._initMusicAudio(); ad=AudioSound._musicAudio; if (ad.src !=url){ delete AudioSound._audioCache[ad.src]; ad=null; } }else{ ad=AudioSound._audioCache[url]; } if (ad && ad.readyState >=2){ this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (!ad){ if (url==SoundManager._tMusic){ AudioSound._initMusicAudio(); ad=AudioSound._musicAudio; }else{ ad=Browser.createElement("audio"); } AudioSound._audioCache[url]=ad; ad.src=url; } ad.addEventListener("canplaythrough",onLoaded); ad.addEventListener("error",onErr); var me=this; function onLoaded (){ offs(); me.loaded=true; me.event(/*laya.events.Event.COMPLETE*/"complete"); } function onErr (){ ad.load=null; offs(); me.event(/*laya.events.Event.ERROR*/"error"); } function offs (){ ad.removeEventListener("canplaythrough",onLoaded); ad.removeEventListener("error",onErr); } this.audio=ad; if (ad.load){ ad.load(); }else { onErr(); } } /** *播放声音 *@param startTime 起始时间 *@param loops 循环次数 *@return * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); if (!this.url)return null; var ad; if (this.url==SoundManager._tMusic){ ad=AudioSound._musicAudio; if (ad.src !="" && ad.src !=this.url){ delete AudioSound._audioCache[ad.src]; AudioSound._audioCache[this.url]=ad; } }else{ ad=AudioSound._audioCache[this.url]; } if (!ad)return null; var tAd; tAd=Pool.getItem("audio:"+this.url); if (Render.isConchApp){ if (!tAd){ tAd=Browser.createElement("audio"); tAd.src=this.url; } } else { if (this.url==SoundManager._tMusic){ AudioSound._initMusicAudio(); tAd=AudioSound._musicAudio; tAd.src=this.url; }else{ tAd=tAd ? tAd :ad.cloneNode(true); } }; var channel=new AudioSoundChannel(tAd); channel.url=this.url; channel.loops=loops; channel.startTime=startTime; channel.play(); SoundManager.addChannel(channel); return channel; } /** *获取总时间。 */ __getset(0,__proto,'duration',function(){ var ad; ad=AudioSound._audioCache[this.url]; if (!ad) return 0; return ad.duration; }); AudioSound._initMusicAudio=function(){ if (AudioSound._musicAudio)return; if (!AudioSound._musicAudio)AudioSound._musicAudio=Browser.createElement("audio"); if (!Render.isConchApp){ Browser.document.addEventListener("mousedown",AudioSound._makeMusicOK); } } AudioSound._makeMusicOK=function(){ Browser.document.removeEventListener("mousedown",AudioSound._makeMusicOK); if (!AudioSound._musicAudio.src){ AudioSound._musicAudio.src=""; AudioSound._musicAudio.load(); }else{ AudioSound._musicAudio.play(); } } AudioSound._audioCache={}; AudioSound._musicAudio=null; return AudioSound; })(EventDispatcher) /** *

    SoundChannel 用来控制程序中的声音。每个声音均分配给一个声道,而且应用程序可以具有混合在一起的多个声道。

    *

    SoundChannel 类包含控制声音的播放、暂停、停止、音量的方法,以及获取声音的播放状态、总时间、当前播放时间、总循环次数、播放地址等信息的方法。

    */ //class laya.media.SoundChannel extends laya.events.EventDispatcher var SoundChannel=(function(_super){ function SoundChannel(){ /** *声音地址。 */ this.url=null; /** *循环次数。 */ this.loops=0; /** *开始时间。 */ this.startTime=NaN; /** *表示声音是否已暂停。 */ this.isStopped=false; /** *播放完成处理器。 */ this.completeHandler=null; SoundChannel.__super.call(this); } __class(SoundChannel,'laya.media.SoundChannel',_super); var __proto=SoundChannel.prototype; /** *播放。 */ __proto.play=function(){} /** *停止。 */ __proto.stop=function(){ if (this.completeHandler)this.completeHandler.run(); } /** *暂停。 */ __proto.pause=function(){} /** *继续播放。 */ __proto.resume=function(){} /** *private */ __proto.__runComplete=function(handler){ if (handler){ handler.run(); } } /** *音量范围从 0(静音)至 1(最大音量)。 */ __getset(0,__proto,'volume',function(){ return 1; },function(v){ }); /** *获取当前播放时间。 */ __getset(0,__proto,'position',function(){ return 0; }); /** *获取总时间。 */ __getset(0,__proto,'duration',function(){ return 0; }); return SoundChannel; })(EventDispatcher) /** *Sound 类是用来播放控制声音的类。 */ //class laya.media.Sound extends laya.events.EventDispatcher var Sound=(function(_super){ function Sound(){ Sound.__super.call(this);; } __class(Sound,'laya.media.Sound',_super); var __proto=Sound.prototype; /** *加载声音。 *@param url 地址。 * */ __proto.load=function(url){} /** *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); return null; } /** *释放声音资源。 * */ __proto.dispose=function(){} /** *获取总时间。 */ __getset(0,__proto,'duration',function(){ return 0; }); return Sound; })(EventDispatcher) /** *@private *web audio api方式播放声音 */ //class laya.media.webaudio.WebAudioSound extends laya.events.EventDispatcher var WebAudioSound=(function(_super){ function WebAudioSound(){ /** *声音URL */ this.url=null; /** *是否已加载完成 */ this.loaded=false; /** *声音文件数据 */ this.data=null; /** *声音原始文件数据 */ this.audioBuffer=null; /** *待播放的声音列表 */ this.__toPlays=null; /** *@private */ this._disposed=false; WebAudioSound.__super.call(this); } __class(WebAudioSound,'laya.media.webaudio.WebAudioSound',_super); var __proto=WebAudioSound.prototype; /** *加载声音 *@param url * */ __proto.load=function(url){ var me=this; url=URL.formatURL(url); this.url=url; this.audioBuffer=WebAudioSound._dataCache[url]; if (this.audioBuffer){ this._loaded(this.audioBuffer); return; } WebAudioSound.e.on("loaded:"+url,this,this._loaded); WebAudioSound.e.on("err:"+url,this,this._err); if (WebAudioSound.__loadingSound[url]){ return; } WebAudioSound.__loadingSound[url]=true; var request=new Browser.window.XMLHttpRequest(); request.open("GET",url,true); request.responseType="arraybuffer"; request.onload=function (){ if (me._disposed){ me._removeLoadEvents(); return; } me.data=request.response; WebAudioSound.buffs.push({"buffer":me.data,"url":me.url}); WebAudioSound.decode(); }; request.onerror=function (e){ me._err(); } request.send(); } __proto._err=function(){ this._removeLoadEvents(); WebAudioSound.__loadingSound[this.url]=false; this.event(/*laya.events.Event.ERROR*/"error"); if (!this.__toPlays)return; var i=0,len=0; var toPlays; toPlays=this.__toPlays; len=toPlays.length; var tParams; for (i=0;i < len;i++){ tParams=toPlays[i]; if (tParams[2] && !(tParams [2]).isStopped){ (tParams [2]).event(/*laya.events.Event.ERROR*/"error"); } } this.__toPlays.length=0; } __proto._loaded=function(audioBuffer){ this._removeLoadEvents(); if (this._disposed){ return; } this.audioBuffer=audioBuffer; WebAudioSound._dataCache[this.url]=this.audioBuffer; this.loaded=true; this.event(/*laya.events.Event.COMPLETE*/"complete"); } __proto._removeLoadEvents=function(){ WebAudioSound.e.off("loaded:"+this.url,this,this._loaded); WebAudioSound.e.off("err:"+this.url,this,this._err); } __proto.__playAfterLoaded=function(){ if (!this.__toPlays)return; var i=0,len=0; var toPlays; toPlays=this.__toPlays; len=toPlays.length; var tParams; for (i=0;i < len;i++){ tParams=toPlays[i]; if (tParams[2] && !(tParams [2]).isStopped){ this.play(tParams[0],tParams[1],tParams[2]); } } this.__toPlays.length=0; } /** *播放声音 *@param startTime 起始时间 *@param loops 循环次数 *@return * */ __proto.play=function(startTime,loops,channel){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); channel=channel ? channel :new WebAudioSoundChannel(); if (!this.audioBuffer){ if (this.url){ if (!this.__toPlays)this.__toPlays=[]; this.__toPlays.push([startTime,loops,channel]); this.once(/*laya.events.Event.COMPLETE*/"complete",this,this.__playAfterLoaded); this.load(this.url); } } channel.url=this.url; channel.loops=loops; channel["audioBuffer"]=this.audioBuffer; channel.startTime=startTime; channel.play(); SoundManager.addChannel(channel); return channel; } __proto.dispose=function(){ this._disposed=true; delete WebAudioSound._dataCache[this.url]; delete WebAudioSound.__loadingSound[this.url]; this.audioBuffer=null; this.data=null; this.__toPlays=[]; } __getset(0,__proto,'duration',function(){ if (this.audioBuffer){ return this.audioBuffer.duration; } return 0; }); WebAudioSound.decode=function(){ if (WebAudioSound.buffs.length <=0 || WebAudioSound.isDecoding){ return; } WebAudioSound.isDecoding=true; WebAudioSound.tInfo=WebAudioSound.buffs.shift(); WebAudioSound.ctx.decodeAudioData(WebAudioSound.tInfo["buffer"],WebAudioSound._done,WebAudioSound._fail); } WebAudioSound._done=function(audioBuffer){ WebAudioSound.e.event("loaded:"+WebAudioSound.tInfo.url,audioBuffer); WebAudioSound.isDecoding=false; WebAudioSound.decode(); } WebAudioSound._fail=function(){ WebAudioSound.e.event("err:"+WebAudioSound.tInfo.url,null); WebAudioSound.isDecoding=false; WebAudioSound.decode(); } WebAudioSound._playEmptySound=function(){ if (WebAudioSound.ctx==null){ return; }; var source=WebAudioSound.ctx.createBufferSource(); source.buffer=WebAudioSound._miniBuffer; source.connect(WebAudioSound.ctx.destination); source.start(0,0,0); } WebAudioSound._unlock=function(){ if (WebAudioSound._unlocked){ return; } WebAudioSound._playEmptySound(); if (WebAudioSound.ctx.state=="running"){ Browser.document.removeEventListener("mousedown",WebAudioSound._unlock,true); Browser.document.removeEventListener("touchend",WebAudioSound._unlock,true); Browser.document.removeEventListener("touchstart",WebAudioSound._unlock,true); WebAudioSound._unlocked=true; } } WebAudioSound.initWebAudio=function(){ if (WebAudioSound.ctx.state !="running"){ WebAudioSound._unlock(); Browser.document.addEventListener("mousedown",WebAudioSound._unlock,true); Browser.document.addEventListener("touchend",WebAudioSound._unlock,true); Browser.document.addEventListener("touchstart",WebAudioSound._unlock,true); } } WebAudioSound._dataCache={}; WebAudioSound.buffs=[]; WebAudioSound.isDecoding=false; WebAudioSound._unlocked=false; WebAudioSound.tInfo=null; WebAudioSound.__loadingSound={}; __static(WebAudioSound, ['window',function(){return this.window=Browser.window;},'webAudioEnabled',function(){return this.webAudioEnabled=WebAudioSound.window["AudioContext"] || WebAudioSound.window["webkitAudioContext"] || WebAudioSound.window["mozAudioContext"];},'ctx',function(){return this.ctx=WebAudioSound.webAudioEnabled ? new (WebAudioSound.window["AudioContext"] || WebAudioSound.window["webkitAudioContext"] || WebAudioSound.window["mozAudioContext"])():undefined;},'_miniBuffer',function(){return this._miniBuffer=WebAudioSound.ctx.createBuffer(1,1,22050);},'e',function(){return this.e=new EventDispatcher();} ]); return WebAudioSound; })(EventDispatcher) /** *

    HttpRequest 通过封装 HTML XMLHttpRequest 对象提供了对 HTTP 协议的完全的访问,包括做出 POST 和 HEAD 请求以及普通的 GET 请求的能力。 HttpRequest 只提供以异步的形式返回 Web 服务器的响应,并且能够以文本或者二进制的形式返回内容。

    *

    注意:建议每次请求都使用新的 HttpRequest 对象,因为每次调用该对象的send方法时,都会清空之前设置的数据,并重置 HTTP 请求的状态,这会导致之前还未返回响应的请求被重置,从而得不到之前请求的响应结果。

    */ //class laya.net.HttpRequest extends laya.events.EventDispatcher var HttpRequest=(function(_super){ function HttpRequest(){ /**@private */ this._responseType=null; /**@private */ this._data=null; HttpRequest.__super.call(this); this._http=new Browser.window.XMLHttpRequest(); } __class(HttpRequest,'laya.net.HttpRequest',_super); var __proto=HttpRequest.prototype; /** *发送 HTTP 请求。 *@param url 请求的地址。大多数浏览器实施了一个同源安全策略,并且要求这个 URL 与包含脚本的文本具有相同的主机名和端口。 *@param data (default=null)发送的数据。 *@param method (default="get")用于请求的 HTTP 方法。值包括 "get"、"post"、"head"。 *@param responseType (default="text")Web 服务器的响应类型,可设置为 "text"、"json"、"xml"、"arraybuffer"。 *@param headers (default=null)HTTP 请求的头部信息。参数形如key-value数组:key是头部的名称,不应该包括空白、冒号或换行;value是头部的值,不应该包括换行。比如["Content-Type","application/json"]。 */ __proto.send=function(url,data,method,responseType,headers){ (method===void 0)&& (method="get"); (responseType===void 0)&& (responseType="text"); this._responseType=responseType; this._data=null; if (Browser.onQGMiniGame || Browser.onVVMiniGame || Browser.onQQMiniGame || Browser.onBDMiniGame || Browser.onBLMiniGame || Browser.onAlipayMiniGame || Browser.onHWMiniGame || Browser.onTTMiniGame || Browser.onTBMiniGame){ url=HttpRequest._urlEncode(url); }; var _this=this; var http=this._http; http.open(method,url,true); if (headers){ for (var i=0;i < headers.length;i++){ http.setRequestHeader(headers[i++],headers[i]); } }else if (!Render.isConchApp){ if (!data || (typeof data=='string'))http.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); else http.setRequestHeader("Content-Type","application/json"); }; var retType=responseType!=="arraybuffer" ? "text" :"arraybuffer"; http.responseType=retType; if (http.dataType){ http.dataType=retType; } http.onerror=function (e){ _this._onError(e); } http.onabort=function (e){ _this._onAbort(e); } http.onprogress=function (e){ _this._onProgress(e); } http.onload=function (e){ _this._onLoad(e); } if (Browser.onBLMiniGame && Browser.onAndroid && !data){ data={}; } http.send(data); } /** *@private *请求进度的侦听处理函数。 *@param e 事件对象。 */ __proto._onProgress=function(e){ if (e && e.lengthComputable)this.event(/*laya.events.Event.PROGRESS*/"progress",e.loaded / e.total); } /** *@private *请求中断的侦听处理函数。 *@param e 事件对象。 */ __proto._onAbort=function(e){ this.error("Request was aborted by user"); } /** *@private *请求出错侦的听处理函数。 *@param e 事件对象。 */ __proto._onError=function(e){ this.error("Request failed Status:"+this._http.status+" text:"+this._http.statusText); } /** *@private *请求消息返回的侦听处理函数。 *@param e 事件对象。 */ __proto._onLoad=function(e){ var http=this._http; var status=http.status!==undefined ? http.status :200; if (status===200 || status===204 || status===0){ this.complete(); }else { this.error("["+http.status+"]"+http.statusText+":"+http.responseURL); } } /** *@private *请求错误的处理函数。 *@param message 错误信息。 */ __proto.error=function(message){ this.clear(); this.event(/*laya.events.Event.ERROR*/"error",message); } /** *@private *请求成功完成的处理函数。 */ __proto.complete=function(){ this.clear(); var flag=true; try { if (this._responseType==="json"){ this._data=JSON.parse(this._http.responseText); }else if (this._responseType==="xml"){ this._data=Utils.parseXMLFromString(this._http.responseText); }else { this._data=this._http.response || this._http.responseText; } }catch (e){ flag=false; this.error(e.message); } flag && this.event(/*laya.events.Event.COMPLETE*/"complete",(this._data instanceof Array)? [this._data] :this._data); } /** *@private *清除当前请求。 */ __proto.clear=function(){ var http=this._http; http.onerror=http.onabort=http.onprogress=http.onload=null; } /**请求的地址。*/ __getset(0,__proto,'url',function(){ return this._http.responseURL; }); /** *本对象所封装的原生 XMLHttpRequest 引用。 */ __getset(0,__proto,'http',function(){ return this._http; }); /**返回的数据。*/ __getset(0,__proto,'data',function(){ return this._data; }); __static(HttpRequest, ['_urlEncode',function(){return this._urlEncode=encodeURI;} ]); return HttpRequest; })(EventDispatcher) /** *Loader 类可用来加载文本、JSON、XML、二进制、图像等资源。 */ //class laya.net.Loader extends laya.events.EventDispatcher var Loader=(function(_super){ function Loader(){ /**@private 加载后的数据对象,只读*/ this._data=null; /**@private */ this._class=null; /**@private */ this._url=null; /**@private */ this._type=null; /**@private */ this._cache=false; /**@private */ this._http=null; /**@private 自定义解析不派发complete事件,但会派发loaded事件,手动调用endLoad方法再派发complete事件*/ this._customParse=false; Loader.__super.call(this); } __class(Loader,'laya.net.Loader',_super); var __proto=Loader.prototype; /** *加载资源。加载错误会派发 Event.ERROR 事件,参数为错误信息。 *@param url 资源地址。 *@param type (default=null)资源类型。可选值为:Loader.TEXT、Loader.JSON、Loader.XML、Loader.BUFFER、Loader.IMAGE、Loader.SOUND、Loader.ATLAS、Loader.FONT。如果为null,则根据文件后缀分析类型。 *@param cache (default=true)是否缓存数据。 *@param group (default=null)分组名称。 *@param ignoreCache (default=false)是否忽略缓存,强制重新加载。 */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); this._url=url; if (url.indexOf("data:image")===0)this._type=type="image"; else { this._type=type || (type=this.getTypeFromUrl(url)); url=URL.formatURL(url); } this._cache=cache; this._data=null; if (!ignoreCache && Loader.loadedMap[url]){ this._data=Loader.loadedMap[url]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",this._data); return; } if (group)Loader.setGroup(url,group); if (Loader.parserMap[type] !=null){ this._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; } if (type==="image" || type==="htmlimage" || type==="nativeimage")return this._loadImage(url); if (type==="sound")return this._loadSound(url); if (type==="ttf")return this._loadTTF(url); var contentType; switch (type){ case "atlas": case "plf": contentType="json"; break ; case "font": contentType="xml"; break ; case "pkm": contentType="arraybuffer"; break default : contentType=type; } if (Loader.preLoadedMap[url]){ this.onLoaded(Loader.preLoadedMap[url]); }else{ if(Browser.onVVMiniGame || Browser.onHWMiniGame){ this._http=new HttpRequest(); }else{ if (!this._http){ this._http=new HttpRequest(); } } this._http.on(/*laya.events.Event.PROGRESS*/"progress",this,this.onProgress); this._http.on(/*laya.events.Event.ERROR*/"error",this,this.onError); this._http.on(/*laya.events.Event.COMPLETE*/"complete",this,this.onLoaded); this._http.send(url,null,"get",contentType); } } /** *获取指定资源地址的数据类型。 *@param url 资源地址。 *@return 数据类型。 */ __proto.getTypeFromUrl=function(url){ var type=Utils.getFileExtension(url); if (type)return Loader.typeMap[type]; console.warn("Not recognize the resources suffix",url); return "text"; } /** *@private *加载TTF资源。 *@param url 资源地址。 */ __proto._loadTTF=function(url){ url=URL.formatURL(url); var ttfLoader=new TTFLoader(); ttfLoader.complete=Handler.create(this,this.onLoaded); ttfLoader.load(url); } /** *@private *加载图片资源。 *@param url 资源地址。 */ __proto._loadImage=function(url){ url=URL.formatURL(url); var _this=this; var image; function clear (){ image.onload=null; image.onerror=null; delete Loader.imgCache[url] }; var onload=function (){ clear(); _this.onLoaded(image); }; var onerror=function (){ clear(); _this.event(/*laya.events.Event.ERROR*/"error","Load image failed"); } if (this._type==="nativeimage"){ image=new Browser.window.Image(); image.crossOrigin=""; image.onload=onload; image.onerror=onerror; image.src=url; Loader.imgCache[url]=image; }else { new HTMLImage.create(url,{onload:onload,onerror:onerror,onCreate:function (img){ image=img; Loader.imgCache[url]=img; }}); } } /** *@private *加载声音资源。 *@param url 资源地址。 */ __proto._loadSound=function(url){ var sound=(new SoundManager._soundClass()); var _this=this; sound.on(/*laya.events.Event.COMPLETE*/"complete",this,soundOnload); sound.on(/*laya.events.Event.ERROR*/"error",this,soundOnErr); sound.load(url); function soundOnload (){ clear(); _this.onLoaded(sound); } function soundOnErr (){ clear(); sound.dispose(); _this.event(/*laya.events.Event.ERROR*/"error","Load sound failed"); } function clear (){ sound.offAll(); } } /**@private */ __proto.onProgress=function(value){ if (this._type==="atlas")this.event(/*laya.events.Event.PROGRESS*/"progress",value *0.3); else this.event(/*laya.events.Event.PROGRESS*/"progress",value); } /**@private */ __proto.onError=function(message){ this.event(/*laya.events.Event.ERROR*/"error",message); } /** *资源加载完成的处理函数。 *@param data 数据。 */ __proto.onLoaded=function(data){ var type=this._type; if (type=="plf"){ this.parsePLFData(data); this.complete(data); }else if (type==="image"){ var tex=new Texture(data); tex.url=this._url; this.complete(tex); }else if (type==="sound" || type==="htmlimage" || type==="nativeimage"){ this.complete(data); }else if (type==="atlas"){ if (!data.src && !data._setContext){ if (!this._data){ this._data=data; if (data.meta && data.meta.image){ var toloadPics=data.meta.image.split(","); var split=this._url.indexOf("/")>=0 ? "/" :"\\"; var idx=this._url.lastIndexOf(split); var folderPath=idx >=0 ? this._url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[this._url.replace(".json",".png")]; } toloadPics.reverse(); data.toLoads=toloadPics; data.pics=[]; } this.event(/*laya.events.Event.PROGRESS*/"progress",0.3+1 / toloadPics.length *0.6); return this._loadImage(URL.formatURL(toloadPics.pop())); }else { this._data.pics.push(data); if (this._data.toLoads.length > 0){ this.event(/*laya.events.Event.PROGRESS*/"progress",0.3+1 / this._data.toLoads.length *0.6); return this._loadImage(this._data.toLoads.pop()); }; var frames=this._data.frames; var cleanUrl=this._url.split("?")[0]; var directory=(this._data.meta && this._data.meta.prefix)? this._data.meta.prefix :cleanUrl.substring(0,cleanUrl.lastIndexOf("."))+"/"; var pics=this._data.pics; var atlasURL=URL.formatURL(this._url); var map=Loader.atlasMap[atlasURL] || (Loader.atlasMap[atlasURL]=[]); map.dir=directory; var scaleRate=1; if (this._data.meta && this._data.meta.scale && this._data.meta.scale !=1){ scaleRate=parseFloat(this._data.meta.scale); for (var name in frames){ var obj=frames[name]; var tPic=pics[obj.frame.idx ? obj.frame.idx :0]; var url=URL.formatURL(directory+name); tPic.scaleRate=scaleRate; var tTexture; tTexture=Texture.create(tPic,obj.frame.x,obj.frame.y,obj.frame.w,obj.frame.h,obj.spriteSourceSize.x,obj.spriteSourceSize.y,obj.sourceSize.w,obj.sourceSize.h); Loader.cacheRes(url,tTexture); tTexture.url=url; map.push(url); } }else{ for (name in frames){ obj=frames[name]; tPic=pics[obj.frame.idx ? obj.frame.idx :0]; url=URL.formatURL(directory+name); Loader.cacheRes(url,Texture.create(tPic,obj.frame.x,obj.frame.y,obj.frame.w,obj.frame.h,obj.spriteSourceSize.x,obj.spriteSourceSize.y,obj.sourceSize.w,obj.sourceSize.h)); Loader.loadedMap[url].url=url; map.push(url); } } delete this._data.pics; this.complete(this._data); } }else if (type=="font"){ if (!data.src){ this._data=data; this.event(/*laya.events.Event.PROGRESS*/"progress",0.5); return this._loadImage(this._url.replace(".fnt",".png")); }else { var bFont=new BitmapFont(); bFont.parseFont(this._data,data); var tArr=this._url.split(".fnt")[0].split("/"); var fontName=tArr[tArr.length-1]; Text.registerBitmapFont(fontName,bFont); this._data=bFont; this.complete(this._data); } }else if (type=="pkm"){ var image=HTMLImage.create(data,this._url); var tex1=new Texture(image); tex1.url=this._url; this.complete(tex1); }else { this.complete(data); } } __proto.parsePLFData=function(plfData){ var type; var filePath; var fileDic; for (type in plfData){ fileDic=plfData[type]; switch(type){ case "json": case "text": for (filePath in fileDic){ Loader.preLoadedMap[URL.formatURL(filePath)]=fileDic[filePath] } break ; default : for (filePath in fileDic){ Loader.preLoadedMap[URL.formatURL(filePath)]=fileDic[filePath] } } } } /** *加载完成。 *@param data 加载的数据。 */ __proto.complete=function(data){ this._data=data; if (this._customParse){ this.event(/*laya.events.Event.LOADED*/"loaded",(data instanceof Array)? [data] :data); }else { Loader._loaders.push(this); if (!Loader._isWorking)Loader.checkNext(); } } /** *结束加载,处理是否缓存及派发完成事件 Event.COMPLETE 。 *@param content 加载后的数据 */ __proto.endLoad=function(content){ content && (this._data=content); if (this._cache)Loader.cacheRes(this._url,this._data); this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",(this.data instanceof Array)? [this.data] :this.data); } /**加载地址。*/ __getset(0,__proto,'url',function(){ return this._url; }); /**返回的数据。*/ __getset(0,__proto,'data',function(){ return this._data; }); /**是否缓存。*/ __getset(0,__proto,'cache',function(){ return this._cache; }); /**加载类型。*/ __getset(0,__proto,'type',function(){ return this._type; }); Loader.checkNext=function(){ Loader._isWorking=true; var startTimer=Browser.now(); var thisTimer=startTimer; while (Loader._startIndex < Loader._loaders.length){ thisTimer=Browser.now(); Loader._loaders[Loader._startIndex].endLoad(); Loader._startIndex++; if (Browser.now()-startTimer > Loader.maxTimeOut){ console.warn("loader callback cost a long time:"+(Browser.now()-startTimer)+" url="+Loader._loaders[Loader._startIndex-1].url); Laya.timer.frameOnce(1,null,Loader.checkNext); return; } } Loader._loaders.length=0; Loader._startIndex=0; Loader._isWorking=false; } Loader.clearRes=function(url,forceDispose){ (forceDispose===void 0)&& (forceDispose=false); url=URL.formatURL(url); var arr=Loader.getAtlas(url); if (arr){ for (var i=0,n=arr.length;i < n;i++){ var resUrl=arr[i]; var tex=Loader.getRes(resUrl); delete Loader.loadedMap[resUrl]; if (tex)tex.destroy(forceDispose); } arr.length=0; delete Loader.atlasMap[url]; delete Loader.loadedMap[url]; }else { var res=Loader.loadedMap[url]; if (res){ delete Loader.loadedMap[url]; if ((res instanceof laya.resource.Texture )&& res.bitmap)(res).destroy(forceDispose); } } } Loader.clearTextureRes=function(url){ url=URL.formatURL(url); var arr=laya.net.Loader.getAtlas(url); var res=(arr && arr.length>0)? laya.net.Loader.getRes(arr[0]):laya.net.Loader.getRes(url); if (res && res.bitmap){ if (Render.isConchApp && !Render.isConchWebGL){ if (res.bitmap.source.releaseTexture){ res.bitmap.source.releaseTexture(); } }else if (res.bitmap._atlaser==null){ res.bitmap.releaseResource(true); } } } Loader.getRes=function(url){ return Loader.loadedMap[URL.formatURL(url)]; } Loader.getAtlas=function(url){ return Loader.atlasMap[URL.formatURL(url)]; } Loader.cacheRes=function(url,data){ url=URL.formatURL(url); if (Loader.loadedMap[url] !=null){ console.warn("Resources already exist,is repeated loading:",url); }else { Loader.loadedMap[url]=data; } } Loader.setGroup=function(url,group){ if (!Loader.groupMap[group])Loader.groupMap[group]=[]; Loader.groupMap[group].push(url); } Loader.clearResByGroup=function(group){ if (!Loader.groupMap[group])return; var arr=Loader.groupMap[group],i=0,len=arr.length; for (i=0;i < len;i++){ Loader.clearRes(arr[i]); } arr.length=0; } Loader.TEXT="text"; Loader.JSON="json"; Loader.XML="xml"; Loader.BUFFER="arraybuffer"; Loader.IMAGE="image"; Loader.SOUND="sound"; Loader.ATLAS="atlas"; Loader.FONT="font"; Loader.TTF="ttf"; Loader.PLF="plf"; Loader.PKM="pkm"; Loader.typeMap={"png":"image","jpg":"image","jpeg":"image","txt":"text","json":"json","xml":"xml","als":"atlas","atlas":"atlas","mp3":"sound","ogg":"sound","wav":"sound","part":"json","fnt":"font","pkm":"pkm","ttf":"ttf","plf":"plf","ani":"json","sk":"arraybuffer"}; Loader.parserMap={}; Loader.groupMap={}; Loader.maxTimeOut=100; Loader.loadedMap={}; Loader.preLoadedMap={}; Loader.atlasMap={}; Loader._loaders=[]; Loader._isWorking=false; Loader._startIndex=0; Loader.imgCache={}; return Loader; })(EventDispatcher) /** *

    LoaderManager 类用于用于批量加载资源。此类是单例,不要手动实例化此类,请通过Laya.loader访问。

    *

    全部队列加载完成,会派发 Event.COMPLETE 事件;如果队列中任意一个加载失败,会派发 Event.ERROR 事件,事件回调参数值为加载出错的资源地址。

    *

    LoaderManager 类提供了以下几种功能:
    *多线程:默认5个加载线程,可以通过maxLoader属性修改线程数量;
    *多优先级:有0-4共5个优先级,优先级高的优先加载。0最高,4最低;
    *重复过滤:自动过滤重复加载(不会有多个相同地址的资源同时加载)以及复用缓存资源,防止重复加载;
    *错误重试:资源加载失败后,会重试加载(以最低优先级插入加载队列),retryNum设定加载失败后重试次数,retryDelay设定加载重试的时间间隔。

    *@see laya.net.Loader */ //class laya.net.LoaderManager extends laya.events.EventDispatcher var LoaderManager=(function(_super){ var ResInfo; function LoaderManager(){ /**加载出错后的重试次数,默认重试一次*/ this.retryNum=1; /**延迟时间多久再进行错误重试,默认立即重试*/ this.retryDelay=0; /**最大下载线程,默认为5个*/ this.maxLoader=5; /**@private */ this._loaders=[]; /**@private */ this._loaderCount=0; /**@private */ this._resInfos=[]; /**@private */ this._infoPool=[]; /**@private */ this._maxPriority=5; /**@private */ this._failRes={}; LoaderManager.__super.call(this); for (var i=0;i < this._maxPriority;i++)this._resInfos[i]=[]; } __class(LoaderManager,'laya.net.LoaderManager',_super); var __proto=LoaderManager.prototype; /** *

    根据clas类型创建一个未初始化资源的对象,随后进行异步加载,资源加载完成后,初始化对象的资源,并通过此对象派发 Event.LOADED 事件,事件回调参数值为此对象本身。套嵌资源的子资源会保留资源路径"?"后的部分。

    *

    如果url为数组,返回true;否则返回指定的资源类对象,可以通过侦听此对象的 Event.LOADED 事件来判断资源是否已经加载完毕。

    *

    注意:cache参数只能对文件后缀为atlas的资源进行缓存控制,其他资源会忽略缓存,强制重新加载。

    *@param url 资源地址或者数组。如果url和clas同时指定了资源类型,优先使用url指定的资源类型。参数形如:[{url:xx,clas:xx,priority:xx,params:xx},{url:xx,clas:xx,priority:xx,params:xx}]。 *@param complete 加载结束回调。根据url类型不同分为2种情况:1. url为String类型,也就是单个资源地址,如果加载成功,则回调参数值为加载完成的资源,否则为null;2. url为数组类型,指定了一组要加载的资源,如果全部加载成功,则回调参数值为true,否则为false。 *@param progress 资源加载进度回调,回调参数值为当前资源加载的进度信息(0-1)。 *@param clas 资源类名。如果url和clas同时指定了资源类型,优先使用url指定的资源类型。参数形如:Texture。 *@param params 资源构造参数。 *@param priority (default=1)加载的优先级,优先级高的优先加载。有0-4共5个优先级,0最高,4最低。 *@param cache 是否缓存加载的资源。 *@return 如果url为数组,返回true;否则返回指定的资源类对象。 */ __proto.create=function(url,complete,progress,clas,params,priority,cache,group){ (priority===void 0)&& (priority=1); (cache===void 0)&& (cache=true); if ((url instanceof Array)){ var items=url; var itemCount=items.length; var loadedCount=0; if (progress){ var progress2=Handler.create(progress.caller,progress.method,progress.args,false); } for (var i=0;i < itemCount;i++){ var item=items[i]; if ((typeof item=='string')) item=items[i]={url:item}; item.progress=0; } for (i=0;i < itemCount;i++){ item=items[i]; var progressHandler=progress ? Handler.create(null,onProgress,[item],false):null; var completeHandler=(progress || complete)? Handler.create(null,onComplete,[item]):null; this._create(item.url,completeHandler,progressHandler,item.clas || clas,item.params || params,item.priority || priority,cache,item.group || group); } function onComplete (item,content){ loadedCount++; item.progress=1; if (loadedCount===itemCount && complete){ complete.run(); } } function onProgress (item,value){ item.progress=value; var num=0; for (var j=0;j < itemCount;j++){ var item1=items[j]; num+=item1.progress; }; var v=num / itemCount; progress2.runWith(v); } return true; }else return this._create(url,complete,progress,clas,params,priority,cache,group); } __proto._create=function(url,complete,progress,clas,params,priority,cache,group){ (priority===void 0)&& (priority=1); (cache===void 0)&& (cache=true); var formarUrl=URL.formatURL(url); var item=this.getRes(formarUrl); if (!item){ var extension=Utils.getFileExtension(url); var creatItem=LoaderManager.createMap[extension]; if (!creatItem) throw new Error("LoaderManager:unknown file("+url+") extension with: "+extension+"."); if (!clas)clas=creatItem[0]; var type=creatItem[1]; if (extension=="atlas"){ this.load(url,complete,progress,type,priority,cache); }else { if (clas===Texture)type="htmlimage"; item=clas ? new clas():null; if (item.hasOwnProperty("_loaded")) item._loaded=false; item._setUrl(url); (group)&& (item._setGroup(group)); this._createLoad(item,url,Handler.create(null,onLoaded),progress,type,priority,false,group,true); function onLoaded (data){ (item && !item.destroyed && data)&& (item.onAsynLoaded.call(item,url,data,params)); if (complete)complete.run(); Laya.loader.event(url); } (cache)&& (this.cacheRes(formarUrl,item)); } }else { if (!item.hasOwnProperty("loaded")|| item.loaded){ progress && progress.runWith(1); complete && complete.run(); }else if (complete){ Laya.loader._createListener(url,complete.caller,complete.method,complete.args,true,false); } } return item; } /** *

    加载资源。资源加载错误时,本对象会派发 Event.ERROR 事件,事件回调参数值为加载出错的资源地址。

    *

    因为返回值为 LoaderManager 对象本身,所以可以使用如下语法:Laya.loader.load(...).load(...);

    *@param url 要加载的单个资源地址或资源信息数组。比如:简单数组:["a.png","b.png"];复杂数组[{url:"a.png",type:Loader.IMAGE,size:100,priority:1},{url:"b.json",type:Loader.JSON,size:50,priority:1}]。 *@param complete 加载结束回调。根据url类型不同分为2种情况:1. url为String类型,也就是单个资源地址,如果加载成功,则回调参数值为加载完成的资源,否则为null;2. url为数组类型,指定了一组要加载的资源,如果全部加载成功,则回调参数值为true,否则为false。 *@param progress 加载进度回调。回调参数值为当前资源的加载进度信息(0-1)。 *@param type 资源类型。比如:Loader.IMAGE。 *@param priority (default=1)加载的优先级,优先级高的优先加载。有0-4共5个优先级,0最高,4最低。 *@param cache 是否缓存加载结果。 *@param group 分组,方便对资源进行管理。 *@param ignoreCache 是否忽略缓存,强制重新加载。 *@return 此 LoaderManager 对象本身。 */ __proto.load=function(url,complete,progress,type,priority,cache,group,ignoreCache){ var _$this=this; (priority===void 0)&& (priority=1); (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); if ((url instanceof Array))return this._loadAssets(url,complete,progress,type,priority,cache,group); var content=Loader.getRes(url); if (content !=null){ Laya.timer.frameOnce(1,null,function(){ progress && progress.runWith(1); complete && complete.runWith(content); _$this._loaderCount || _$this.event(/*laya.events.Event.COMPLETE*/"complete"); }); }else { var info=LoaderManager._resMap[url]; if (!info){ info=this._infoPool.length ? this._infoPool.pop():new ResInfo(); info.url=url; info.type=type; info.cache=cache; info.group=group; info.ignoreCache=ignoreCache; complete && info.on(/*laya.events.Event.COMPLETE*/"complete",complete.caller,complete.method,complete.args); progress && info.on(/*laya.events.Event.PROGRESS*/"progress",progress.caller,progress.method,progress.args); LoaderManager._resMap[url]=info; priority=priority < this._maxPriority ? priority :this._maxPriority-1; this._resInfos[priority].push(info); this._next(); }else { complete && info._createListener(/*laya.events.Event.COMPLETE*/"complete",complete.caller,complete.method,complete.args,false,false); progress && info._createListener(/*laya.events.Event.PROGRESS*/"progress",progress.caller,progress.method,progress.args,false,false); } } return this; } /** *@private */ __proto._createLoad=function(item,url,complete,progress,type,priority,cache,group,ignoreCache){ var _$this=this; (priority===void 0)&& (priority=1); (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); if ((url instanceof Array))return this._loadAssets(url,complete,progress,type,priority,cache,group); var content=Loader.getRes(url); if (content !=null){ Laya.timer.frameOnce(1,null,function(){ progress && progress.runWith(1); complete && complete.runWith(content); _$this._loaderCount || _$this.event(/*laya.events.Event.COMPLETE*/"complete"); }); }else { var info=LoaderManager._resMap[url]; if (!info){ info=this._infoPool.length ? this._infoPool.pop():new ResInfo(); info.url=url; info.clas=item; info.type=type; info.cache=cache; info.group=group; info.ignoreCache=ignoreCache; complete && info.on(/*laya.events.Event.COMPLETE*/"complete",complete.caller,complete.method,complete.args); progress && info.on(/*laya.events.Event.PROGRESS*/"progress",progress.caller,progress.method,progress.args); LoaderManager._resMap[url]=info; priority=priority < this._maxPriority ? priority :this._maxPriority-1; this._resInfos[priority].push(info); this._next(); }else { complete && info._createListener(/*laya.events.Event.COMPLETE*/"complete",complete.caller,complete.method,complete.args,false,false); progress && info._createListener(/*laya.events.Event.PROGRESS*/"progress",progress.caller,progress.method,progress.args,false,false); } } return this; } __proto._next=function(){ if (this._loaderCount >=this.maxLoader)return; for (var i=0;i < this._maxPriority;i++){ var infos=this._resInfos[i]; while (infos.length > 0){ var info=infos.shift(); if (info)return this._doLoad(info); } } this._loaderCount || this.event(/*laya.events.Event.COMPLETE*/"complete"); } __proto._doLoad=function(resInfo){ this._loaderCount++; var loader=this._loaders.length ? this._loaders.pop():new Loader(); loader.on(/*laya.events.Event.COMPLETE*/"complete",null,onLoaded); loader.on(/*laya.events.Event.PROGRESS*/"progress",null,function(num){ resInfo.event(/*laya.events.Event.PROGRESS*/"progress",num); }); loader.on(/*laya.events.Event.ERROR*/"error",null,function(msg){ onLoaded(null); }); var _this=this; function onLoaded (data){ loader.offAll(); loader._data=null; loader._customParse=false; _this._loaders.push(loader); _this._endLoad(resInfo,(data instanceof Array)? [data] :data); _this._loaderCount--; _this._next(); } loader._class=resInfo.clas; loader.load(resInfo.url,resInfo.type,resInfo.cache,resInfo.group,resInfo.ignoreCache); } __proto._endLoad=function(resInfo,content){ var url=resInfo.url; if (content==null){ var errorCount=this._failRes[url] || 0; if (errorCount < this.retryNum){ console.warn("[warn]Retry to load:",url); this._failRes[url]=errorCount+1; Laya.timer.once(this.retryDelay,this,this._addReTry,[resInfo],false); return; }else { console.warn("[error]Failed to load:",url); this.event(/*laya.events.Event.ERROR*/"error",url); } } if (this._failRes[url])this._failRes[url]=0; delete LoaderManager._resMap[url]; resInfo.event(/*laya.events.Event.COMPLETE*/"complete",content); resInfo.offAll(); this._infoPool.push(resInfo); } __proto._addReTry=function(resInfo){ this._resInfos[this._maxPriority-1].push(resInfo); this._next(); } /** *清理指定资源地址缓存。 *@param url 资源地址。 *@param forceDispose 是否强制销毁,有些资源是采用引用计数方式销毁,如果forceDispose=true,则忽略引用计数,直接销毁,比如Texture,默认为false */ __proto.clearRes=function(url,forceDispose){ (forceDispose===void 0)&& (forceDispose=false); Loader.clearRes(url,forceDispose); } /** *获取指定资源地址的资源。 *@param url 资源地址。 *@return 返回资源。 */ __proto.getRes=function(url){ return Loader.getRes(url); } /** *缓存资源。 *@param url 资源地址。 *@param data 要缓存的内容。 */ __proto.cacheRes=function(url,data){ Loader.cacheRes(url,data); } /** *销毁Texture使用的图片资源,保留texture壳,如果下次渲染的时候,发现texture使用的图片资源不存在,则会自动恢复 *相比clearRes,clearTextureRes只是清理texture里面使用的图片资源,并不销毁texture,再次使用到的时候会自动恢复图片资源 *而clearRes会彻底销毁texture,导致不能再使用;clearTextureRes能确保立即销毁图片资源,并且不用担心销毁错误,clearRes则采用引用计数方式销毁 *【注意】如果图片本身在自动合集里面(默认图片小于512*512),内存是不能被销毁的,此图片被大图合集管理器管理 *@param url 图集地址或者texture地址,比如 Loader.clearTextureRes("res/atlas/comp.atlas");Loader.clearTextureRes("hall/bg.jpg"); */ __proto.clearTextureRes=function(url){ Loader.clearTextureRes(url); } /** *设置资源分组。 *@param url 资源地址。 *@param group 分组名 */ __proto.setGroup=function(url,group){ Loader.setGroup(url,group); } /** *根据分组清理资源。 *@param group 分组名 */ __proto.clearResByGroup=function(group){ Loader.clearResByGroup(group); } /**清理当前未完成的加载,所有未加载的内容全部停止加载。*/ __proto.clearUnLoaded=function(){ for (var i=0;i < this._maxPriority;i++){ var infos=this._resInfos[i]; for (var j=infos.length-1;j >-1;j--){ var info=infos[j]; if (info){ info.offAll(); this._infoPool.push(info); } } infos.length=0; } this._loaderCount=0; LoaderManager._resMap={}; } /** *根据地址集合清理掉未加载的内容 *@param urls 资源地址集合 */ __proto.cancelLoadByUrls=function(urls){ if (!urls)return; for (var i=0,n=urls.length;i < n;i++){ this.cancelLoadByUrl(urls[i]); } } /** *根据地址清理掉未加载的内容 *@param url 资源地址 */ __proto.cancelLoadByUrl=function(url){ for (var i=0;i < this._maxPriority;i++){ var infos=this._resInfos[i]; for (var j=infos.length-1;j >-1;j--){ var info=infos[j]; if (info && info.url===url){ infos[j]=null; info.offAll(); this._infoPool.push(info); } } } if (LoaderManager._resMap[url])delete LoaderManager._resMap[url]; } /** *@private *加载数组里面的资源。 *@param arr 简单:["a.png","b.png"],复杂[{url:"a.png",type:Loader.IMAGE,size:100,priority:1},{url:"b.json",type:Loader.JSON,size:50,priority:1}]*/ __proto._loadAssets=function(arr,complete,progress,type,priority,cache,group){ (priority===void 0)&& (priority=1); (cache===void 0)&& (cache=true); var itemCount=arr.length; var loadedCount=0; var totalSize=0; var items=[]; var success=true; for (var i=0;i < itemCount;i++){ var item=arr[i]; if ((typeof item=='string'))item={url:item,type:type,size:1,priority:priority}; if (!item.size)item.size=1; item.progress=0; totalSize+=item.size; items.push(item); var progressHandler=progress ? Handler.create(null,loadProgress,[item],false):null; var completeHandler=(complete || progress)? Handler.create(null,loadComplete,[item]):null; this.load(item.url,completeHandler,progressHandler,item.type,item.priority || 1,cache,item.group || group); } function loadComplete (item,content){ loadedCount++; item.progress=1; if (!content)success=false; if (loadedCount===itemCount && complete){ complete.runWith(success); } } function loadProgress (item,value){ if (progress !=null){ item.progress=value; var num=0; for (var j=0;j < items.length;j++){ var item1=items[j]; num+=item1.size *item1.progress; }; var v=num / totalSize; progress.runWith(v); } } return this; } LoaderManager.cacheRes=function(url,data){ Loader.cacheRes(url,data); } LoaderManager._resMap={}; __static(LoaderManager, ['createMap',function(){return this.createMap={atlas:[null,/*laya.net.Loader.ATLAS*/"atlas"]};} ]); LoaderManager.__init$=function(){ //class ResInfo extends laya.events.EventDispatcher ResInfo=(function(_super){ function ResInfo(){ this.url=null; this.type=null; this.cache=false; this.group=null; this.ignoreCache=false; this.clas=null; ResInfo.__super.call(this); } __class(ResInfo,'',_super); return ResInfo; })(EventDispatcher) } return LoaderManager; })(EventDispatcher) /** *

    ColorFilter 是颜色滤镜。使用 ColorFilter 类可以将 4 x 5 矩阵转换应用于输入图像上的每个像素的 RGBA 颜色和 Alpha 值,以生成具有一组新的 RGBA 颜色和 Alpha 值的结果。该类允许饱和度更改、色相旋转、亮度转 Alpha 以及各种其他效果。您可以将滤镜应用于任何显示对象(即,从 Sprite 类继承的对象)。

    *

    注意:对于 RGBA 值,最高有效字节代表红色通道值,其后的有效字节分别代表绿色、蓝色和 Alpha 通道值。

    */ //class laya.filters.ColorFilter extends laya.filters.Filter var ColorFilter=(function(_super){ function ColorFilter(mat){ /**@private */ //this._mat=null; /**@private */ //this._alpha=null; ColorFilter.__super.call(this); if (!mat){ mat=[0.3,0.59,0.11,0,0,0.3,0.59,0.11,0,0,0.3,0.59,0.11,0,0,0,0,0,1,0]; } this._mat=new Float32Array(16); this._alpha=new Float32Array(4); var j=0; var z=0; for (var i=0;i < 20;i++){ if (i % 5 !=4){ this._mat[j++]=mat[i]; }else { this._alpha[z++]=mat[i]; } } this._action=RunDriver.createFilterAction(0x20); this._action.data=this; } __class(ColorFilter,'laya.filters.ColorFilter',_super); var __proto=ColorFilter.prototype; Laya.imps(__proto,{"laya.filters.IFilter":true}) /** *@private 通知微端 */ __proto.callNative=function(sp){ var t=sp._$P.cf=this; sp.conchModel && sp.conchModel.setFilterMatrix && sp.conchModel.setFilterMatrix(this._mat,this._alpha); } /**@private */ __getset(0,__proto,'type',function(){ return 0x20; }); /**@private */ __getset(0,__proto,'action',function(){ return this._action; }); return ColorFilter; })(Filter) /** *

    Socket 封装了 HTML5 WebSocket ,允许服务器端与客户端进行全双工(full-duplex)的实时通信,并且允许跨域通信。在建立连接后,服务器和 Browser/Client Agent 都能主动的向对方发送或接收文本和二进制数据。

    *

    要使用 Socket 类的方法,请先使用构造函数 new Socket 创建一个 Socket 对象。 Socket 以异步方式传输和接收数据。

    */ //class laya.net.Socket extends laya.events.EventDispatcher var Socket=(function(_super){ function Socket(host,port,byteClass){ /**@private */ this._endian=null; /**@private */ this._stamp=NaN; /**@private */ this._socket=null; /**@private */ this._connected=false; /**@private */ this._addInputPosition=0; /**@private */ this._input=null; /**@private */ this._output=null; /** *@private *表示建立连接时需等待的毫秒数。 */ this.timeout=0; /** *@private *在写入或读取对象时,控制所使用的 AMF 的版本。 */ this.objectEncoding=0; /** *不再缓存服务端发来的数据。 */ this.disableInput=false; /** *用来发送和接收数据的 Byte 类。 */ this._byteClass=null; /** *

    子协议名称。子协议名称字符串,或由多个子协议名称字符串构成的数组。必须在调用 connect 或者 connectByUrl 之前进行赋值,否则无效。

    *

    指定后,只有当服务器选择了其中的某个子协议,连接才能建立成功,否则建立失败,派发 Event.ERROR 事件。

    *@see https://html.spec.whatwg.org/multipage/comms.html#dom-websocket */ this.protocols=[]; (port===void 0)&& (port=0); Socket.__super.call(this); this._byteClass=byteClass ? byteClass :Byte; this.endian="bigEndian"; this.timeout=20000; this._addInputPosition=0; if (host && port > 0 && port < 65535) this.connect(host,port); } __class(Socket,'laya.net.Socket',_super); var __proto=Socket.prototype; /** *

    连接到指定的主机和端口。

    *

    连接成功派发 Event.OPEN 事件;连接失败派发 Event.ERROR 事件;连接被关闭派发 Event.CLOSE 事件;接收到数据派发 Event.MESSAGE 事件; 除了 Event.MESSAGE 事件参数为数据内容,其他事件参数都是原生的 HTML DOM Event 对象。

    *@param host 服务器地址。 *@param port 服务器端口。 */ __proto.connect=function(host,port){ var url="ws://"+host+":"+port; if (Browser.window.location.protocol=="https:"){ url="wss://"+host+":"+port; }else { url="ws://"+host+":"+port; } this.connectByUrl(url); } /** *

    连接到指定的服务端 WebSocket URL。 URL 类似 ws://yourdomain:port。

    *

    连接成功派发 Event.OPEN 事件;连接失败派发 Event.ERROR 事件;连接被关闭派发 Event.CLOSE 事件;接收到数据派发 Event.MESSAGE 事件; 除了 Event.MESSAGE 事件参数为数据内容,其他事件参数都是原生的 HTML DOM Event 对象。

    *@param url 要连接的服务端 WebSocket URL。 URL 类似 ws://yourdomain:port。 */ __proto.connectByUrl=function(url){ var _$this=this; if (this._socket !=null) this.close(); this._socket && this.cleanSocket(); if (!this.protocols || this.protocols.length==0){ this._socket=new Browser.window.WebSocket(url); }else { this._socket=new Browser.window.WebSocket(url,this.protocols); } this._socket.binaryType="arraybuffer"; this._output=new this._byteClass(); this._output.endian=this.endian; this._input=new this._byteClass(); this._input.endian=this.endian; this._addInputPosition=0; this._socket.onopen=function (e){ _$this._onOpen(e); }; this._socket.onmessage=function (msg){ _$this._onMessage(msg); }; this._socket.onclose=function (e){ _$this._onClose(e); }; this._socket.onerror=function (e){ _$this._onError(e); }; } /** *清理socket。 */ __proto.cleanSocket=function(){ try { this._socket.close(); }catch (e){} this._connected=false; this._socket.onopen=null; this._socket.onmessage=null; this._socket.onclose=null; this._socket.onerror=null; this._socket=null; } /** *关闭连接。 */ __proto.close=function(){ if (this._socket !=null){ try { this._socket.close(); }catch (e){} } } /** *@private *连接建立成功 。 */ __proto._onOpen=function(e){ this._connected=true; this.event(/*laya.events.Event.OPEN*/"open",e); } /** *@private *接收到数据处理方法。 *@param msg 数据。 */ __proto._onMessage=function(msg){ if (!msg || !msg.data)return; var data=msg.data; if (this.disableInput && data){ this.event(/*laya.events.Event.MESSAGE*/"message",data); return; } if (this._input.length > 0 && this._input.bytesAvailable < 1){ this._input.clear(); this._addInputPosition=0; }; var pre=this._input.pos; !this._addInputPosition && (this._addInputPosition=0); this._input.pos=this._addInputPosition; if (data){ if ((typeof data=='string')){ this._input.writeUTFBytes(data); }else { this._input.writeArrayBuffer(data); } this._addInputPosition=this._input.pos; this._input.pos=pre; } this.event(/*laya.events.Event.MESSAGE*/"message",data); } /** *@private *连接被关闭处理方法。 */ __proto._onClose=function(e){ this._connected=false; this.event(/*laya.events.Event.CLOSE*/"close",e) } /** *@private *出现异常处理方法。 */ __proto._onError=function(e){ this.event(/*laya.events.Event.ERROR*/"error",e) } /** *发送数据到服务器。 *@param data 需要发送的数据,可以是String或者ArrayBuffer。 */ __proto.send=function(data){ this._socket.send(data); } /** *发送缓冲区中的数据到服务器。 */ __proto.flush=function(){ if (this._output && this._output.length > 0){ var evt; try { this._socket && this._socket.send(this._output.__getBuffer().slice(0,this._output.length)); }catch (e){ evt=e; } this._output.endian=this.endian; this._output.clear(); if (evt)this.event(/*laya.events.Event.ERROR*/"error",evt); } } /** *缓存的服务端发来的数据。 */ __getset(0,__proto,'input',function(){ return this._input; }); /** *表示需要发送至服务端的缓冲区中的数据。 */ __getset(0,__proto,'output',function(){ return this._output; }); /** *表示此 Socket 对象目前是否已连接。 */ __getset(0,__proto,'connected',function(){ return this._connected; }); /** *

    主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。

    *

    LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。

    *

    BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。

    */ __getset(0,__proto,'endian',function(){ return this._endian; },function(value){ this._endian=value; if (this._input !=null)this._input.endian=value; if (this._output !=null)this._output.endian=value; }); Socket.LITTLE_ENDIAN="littleEndian"; Socket.BIG_ENDIAN="bigEndian"; return Socket; })(EventDispatcher) /** *@private *Worker Image加载器 */ //class laya.net.WorkerLoader extends laya.events.EventDispatcher var WorkerLoader=(function(_super){ function WorkerLoader(){ /** *使用的Worker对象。 */ this.worker=null; WorkerLoader.__super.call(this); var _$this=this; this.worker=new Browser.window.Worker(WorkerLoader.workerPath); this.worker.onmessage=function (evt){ _$this.workerMessage(evt.data); } } __class(WorkerLoader,'laya.net.WorkerLoader',_super); var __proto=WorkerLoader.prototype; /** *@private */ __proto.workerMessage=function(data){ if (data){ switch(data.type){ case "Image": this.imageLoaded(data); break ; case "Msg": this.event("image_msg",data.msg); break ; } } } /** *@private */ __proto.imageLoaded=function(data){ if (data && data.buffer && data.buffer.length < 10){ WorkerLoader._enable=false; this._myTrace("buffer lost when postmessage ,disable workerloader"); this.event(data.url,null); this.event("image_err",data.url+"\n"+data.msg); return; } if (!data.dataType){ this.event(data.url,null); this.event("image_err",data.url+"\n"+data.msg); return; }; var canvas,ctx; var imageData; switch(data.dataType){ case "buffer": canvas=new HTMLCanvas("2D"); ctx=canvas.source.getContext("2d"); imageData=ctx.createImageData(data.width,data.height); imageData.data.set(data.buffer); canvas.size(imageData.width,imageData.height); ctx.putImageData(imageData,0,0); canvas.memorySize=0; break ; case "imagedata": canvas=new HTMLCanvas("2D"); ctx=canvas.source.getContext("2d"); imageData=data.imagedata; canvas.size(imageData.width,imageData.height); ctx.putImageData(imageData,0,0); imageData=data.imagedata; canvas.memorySize=0; break ; case "imageBitmap": imageData=data.imageBitmap; if (!Render.isWebGL){ canvas=new HTMLCanvas("2D"); ctx=canvas.source.getContext("2d"); canvas.size(imageData.width,imageData.height); ctx.drawImage(imageData,0,0); canvas.src=data.url; }else canvas=imageData; break ; } if (Render.isWebGL) /*__JS__ */canvas=new laya.webgl.resource.WebGLImage(canvas,data.url);; this.event(data.url,canvas); } /** *@private */ __proto._myTrace=function(__arg){ var arg=arguments; var rst=[]; var i=0,len=arg.length; for(i=0;iResource 资源存取类。 */ //class laya.resource.Resource extends laya.events.EventDispatcher var Resource=(function(_super){ function Resource(){ /**@private */ //this.__loaded=false; /**@private */ //this._id=0; /**@private */ //this._memorySize=0; /**@private */ //this._released=false; /**@private */ //this._destroyed=false; /**@private */ //this._referenceCount=0; /**@private */ //this._group=null; /**@private */ //this._url=null; /**@private */ //this._resourceManager=null; /**@private */ //this._lastUseFrameCount=0; /**是否加锁,如果true为不能使用自动释放机制。*/ //this.lock=false; /**名称。 */ //this.name=null; Resource.__super.call(this); this._$1__id=++Resource._uniqueIDCounter; this.__loaded=true; this._destroyed=false; this._referenceCount=0; Resource._idResourcesMap[this.id]=this; this._released=true; this.lock=false; this._memorySize=0; this._lastUseFrameCount=-1; (ResourceManager.currentResourceManager)&& (ResourceManager.currentResourceManager.addResource(this)); } __class(Resource,'laya.resource.Resource',_super); var __proto=Resource.prototype; Laya.imps(__proto,{"laya.resource.ICreateResource":true,"laya.resource.IDispose":true}) /** *@private */ __proto._setUrl=function(url){ if (this._url!==url){ var resList; if (this._url){ resList=Resource._urlResourcesMap[this._url]; resList.splice(resList.indexOf(this),1); (resList.length===0)&& (delete Resource._urlResourcesMap[this._url]); } if (url){ resList=Resource._urlResourcesMap[url]; (resList)|| (Resource._urlResourcesMap[url]=resList=[]); resList.push(this); } this._url=url; } } /** *@private */ __proto._getGroup=function(){ return this._group; } /** *@private */ __proto._setGroup=function(value){ if (this._group!==value){ var groupList; if (this._group){ groupList=Resource._groupResourcesMap[this._group]; groupList.splice(groupList.indexOf(this),1); (groupList.length===0)&& (delete Resource._groupResourcesMap[this._group]); } if (value){ groupList=Resource._groupResourcesMap[value]; (groupList)|| (Resource._groupResourcesMap[value]=groupList=[]); groupList.push(this); } this._group=value; } } /** *@private */ __proto._addReference=function(){ this._referenceCount++; } /** *@private */ __proto._removeReference=function(){ this._referenceCount--; } /** *@private */ __proto._clearReference=function(){ this._referenceCount=0; } /** *@private */ __proto._endLoaded=function(){ this.__loaded=true; this.event(/*laya.events.Event.LOADED*/"loaded",this); } /** *@private */ __proto.recreateResource=function(){ this.completeCreate(); } /** *@private */ __proto.disposeResource=function(){} /** *激活资源,使用资源前应先调用此函数激活。 *@param force 是否强制创建。 */ __proto.activeResource=function(force){ (force===void 0)&& (force=false); this._lastUseFrameCount=Stat.loopCount; if (!this._destroyed && this.__loaded && (this._released || force)) this.recreateResource(); } /** *释放资源。 *@param force 是否强制释放。 *@return 是否成功释放。 */ __proto.releaseResource=function(force){ (force===void 0)&& (force=false); if (!force && this.lock) return false; if (!this._released || force){ this.disposeResource(); this._released=true; this._lastUseFrameCount=-1; this.event(/*laya.events.Event.RELEASED*/"released",this); return true; }else { return false; } } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ throw new Error("Resource: must override this function!"); } /** *

    彻底处理资源,处理后不能恢复。

    *

    注意:会强制解锁清理。

    */ __proto.destroy=function(){ if (this._destroyed) return; if (this._resourceManager!==null) this._resourceManager.removeResource(this); this._destroyed=true; this.lock=false; this.releaseResource(); delete Resource._idResourcesMap[this.id]; var resList; if (this._url){ resList=Resource._urlResourcesMap[this._url]; if (resList){ resList.splice(resList.indexOf(this),1); (resList.length===0)&& (delete Resource._urlResourcesMap[this.url]); } Loader.clearRes(this._url); (this.__loaded)||(RunDriver.cancelLoadByUrl(this._url)); } if (this._group){ resList=Resource._groupResourcesMap[this._group]; resList.splice(resList.indexOf(this),1); (resList.length===0)&& (delete Resource._groupResourcesMap[this.url]); } } /**完成资源激活。*/ __proto.completeCreate=function(){ this._released=false; this.event(/*laya.events.Event.RECOVERED*/"recovered",this); } /** *@private */ __proto.dispose=function(){ this.destroy(); } /** *@private */ /** *占用内存尺寸。 */ __getset(0,__proto,'memorySize',function(){ return this._memorySize; },function(value){ var offsetValue=value-this._memorySize; this._memorySize=value; this.resourceManager && this.resourceManager.addSize(offsetValue); }); /** *@private */ __getset(0,__proto,'_loaded',null,function(value){ this.__loaded=value; }); /** *获取是否已加载完成。 */ __getset(0,__proto,'loaded',function(){ return this.__loaded; }); /** *获取唯一标识ID,通常用于识别。 */ __getset(0,__proto,'id',function(){ return this._$1__id; }); /** *是否已处理。 */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); /** *设置资源组名。 */ /** *获取资源组名。 */ __getset(0,__proto,'group',function(){ return this._getGroup(); },function(value){ this._setGroup(value); }); /** *资源管理员。 */ __getset(0,__proto,'resourceManager',function(){ return this._resourceManager; }); /** *获取资源的URL地址。 *@return URL地址。 */ __getset(0,__proto,'url',function(){ return this._url; }); /** *是否已释放。 */ __getset(0,__proto,'released',function(){ return this._released; }); /** *获取资源的引用计数。 */ __getset(0,__proto,'referenceCount',function(){ return this._referenceCount; }); Resource.getResourceByID=function(id){ return Resource._idResourcesMap[id]; } Resource.getResourceByURL=function(url,index){ (index===void 0)&& (index=0); return Resource._urlResourcesMap[url][index]; } Resource.getResourceCountByURL=function(url){ return Resource._urlResourcesMap[url].length; } Resource.destroyUnusedResources=function(group){ var res; if (group){ var resouList=Resource._groupResourcesMap[group]; if (resouList){ var tempResouList=resouList.slice(); for (var i=0,n=tempResouList.length;i < n;i++){ res=tempResouList[i]; if (!res.lock && res._referenceCount===0) res.destroy(); } } }else { for (var k in Resource._idResourcesMap){ res=Resource._idResourcesMap[k]; if (!res.lock && res._referenceCount===0) res.destroy(); } } } Resource._uniqueIDCounter=0; Resource._idResourcesMap={}; Resource._urlResourcesMap={}; Resource._groupResourcesMap={}; return Resource; })(EventDispatcher) /** *Texture 是一个纹理处理类。 */ //class laya.resource.Texture extends laya.events.EventDispatcher var Texture=(function(_super){ function Texture(bitmap,uv){ /**图片或者canvas 。*/ //this.bitmap=null; /**UV信息。*/ //this.uv=null; /**沿 X 轴偏移量。*/ this.offsetX=0; /**沿 Y 轴偏移量。*/ this.offsetY=0; /**原始宽度(包括被裁剪的透明区域)。*/ this.sourceWidth=0; /**原始高度(包括被裁剪的透明区域)。*/ this.sourceHeight=0; /**@private */ //this._loaded=false; /**@private */ this._w=0; /**@private */ this._h=0; /**@private 唯一ID*/ //this.$_GID=NaN; /**图片地址*/ //this.url=null; /**@private */ this._uvID=0; this._atlasID=-1; /**@private */ this.scaleRate=1; Texture.__super.call(this); if (bitmap && bitmap._addReference!=null){ bitmap._addReference(); } this.setTo(bitmap,uv); } __class(Texture,'laya.resource.Texture',_super); var __proto=Texture.prototype; /** *@private */ __proto._setUrl=function(url){ this.url=url; } /** *设置此对象的位图资源、UV数据信息。 *@param bitmap 位图资源 *@param uv UV数据信息 */ __proto.setTo=function(bitmap,uv){ if (/*__JS__ */bitmap instanceof window.HTMLElement){ var canvas=HTMLCanvas.create("2D",bitmap); this.bitmap=canvas; }else{ this.bitmap=bitmap; } this.uv=uv || Texture.DEF_UV; if (bitmap){ this._w=bitmap.width; this._h=bitmap.height; this.sourceWidth=this.sourceWidth || this._w; this.sourceHeight=this.sourceHeight || this._h this._loaded=this._w > 0; var _this=this; if (this._loaded){ RunDriver.addToAtlas && RunDriver.addToAtlas(_this); }else { var bm=bitmap; if ((bm instanceof laya.resource.HTMLImage )&& bm.image) bm.image.addEventListener('load',function(e){ RunDriver.addToAtlas && RunDriver.addToAtlas(_this); },false); } } } /**@private 激活资源。*/ __proto.active=function(){ if (this.bitmap)this.bitmap.activeResource(); } /** *销毁纹理(分直接销毁,跟计数销毁两种)。 *@param forceDispose (default=false)true为强制销毁主纹理,false是通过计数销毁纹理。 */ __proto.destroy=function(forceDispose){ (forceDispose===void 0)&& (forceDispose=false); if (this.bitmap && (this.bitmap).referenceCount > 0){ var temp=this.bitmap; if (forceDispose){ if (Render.isConchApp && temp.source && temp.source.conchDestroy){ this.bitmap.source.conchDestroy(); } this.bitmap=null; temp.dispose(); (temp)._clearReference(); }else { (temp)._removeReference(); if ((temp).referenceCount==0){ if (Render.isConchApp && temp.source && temp.source.conchDestroy){ this.bitmap.source.conchDestroy(); } this.bitmap=null; temp.dispose(); } } if (this.url && this===Laya.loader.getRes(this.url))Laya.loader.clearRes(this.url,forceDispose); this._loaded=false; } } /** *加载指定地址的图片。 *@param url 图片地址。 */ __proto.load=function(url){ var _$this=this; this._loaded=false; url=URL.customFormat(url); var fileBitmap=(this.bitmap || (this.bitmap=HTMLImage.create(url))); if (fileBitmap)fileBitmap._addReference(); var _this=this; fileBitmap.onload=function (){ fileBitmap.onload=null; _this._loaded=true; _$this.sourceWidth=_$this._w=fileBitmap.width; _$this.sourceHeight=_$this._h=fileBitmap.height; _this.event(/*laya.events.Event.LOADED*/"loaded",this); (RunDriver.addToAtlas)&& (RunDriver.addToAtlas(_this)); }; } /**@private */ __proto.addTextureToAtlas=function(e){ RunDriver.addTextureToAtlas(this); } /** *获取Texture上的某个区域的像素点 *@param x *@param y *@param width *@param height *@return 返回像素点集合 */ __proto.getPixels=function(x,y,width,height){ if (Render.isConchApp){ var temp=this.bitmap; if (temp.source && temp.source.getImageData){ var arraybuffer=temp.source.getImageData(x,y,width,height); var tUint8Array=new Uint8Array(arraybuffer); return /*__JS__ */Array.from(tUint8Array); } return null; }else if (Render.isWebGL){ return RunDriver.getTexturePixels(this,x,y,width,height); }else { Browser.canvas.size(width,height); Browser.canvas.clear(); Browser.context.drawTexture(this,-x,-y,this.width,this.height,0,0); var info=Browser.context.getImageData(0,0,width,height); } return info.data; } /**@private */ __proto.onAsynLoaded=function(url,bitmap){ if (bitmap)bitmap._addReference(); this.setTo(bitmap,this.uv); } /**激活并获取资源。*/ __getset(0,__proto,'source',function(){ if (!this.bitmap)return null; this.bitmap.activeResource(); return this.bitmap.source; }); /** *表示是否加载成功,只能表示初次载入成功(通常包含下载和载入),并不能完全表示资源是否可立即使用(资源管理机制释放影响等)。 */ __getset(0,__proto,'loaded',function(){ return this._loaded; }); /** *表示资源是否已释放。 */ __getset(0,__proto,'released',function(){ if (!this.bitmap)return true; return this.bitmap.released; }); /**实际宽度。*/ __getset(0,__proto,'width',function(){ if (this._w)return this._w; return (this.uv && this.uv!==Texture.DEF_UV)? (this.uv[2]-this.uv[0])*this.bitmap.width :this.bitmap.width; },function(value){ this._w=value; this.sourceWidth || (this.sourceWidth=value); }); /** *通过外部设置是否启用纹理平铺(后面要改成在着色器里计算) */ /** *获取当前纹理是否启用了纹理平铺 */ __getset(0,__proto,'repeat',function(){ if (Render.isWebGL && this.bitmap){ return this.bitmap.repeat; } return true; },function(value){ if (value){ if (Render.isWebGL && this.bitmap){ this.bitmap.repeat=value; if (value){ this.bitmap.enableMerageInAtlas=false; } } } }); /**实际高度。*/ __getset(0,__proto,'height',function(){ if (this._h)return this._h; return (this.uv && this.uv!==Texture.DEF_UV)? (this.uv[5]-this.uv[1])*this.bitmap.height :this.bitmap.height; },function(value){ this._h=value; this.sourceHeight || (this.sourceHeight=value); }); /** *设置线性采样的状态(目前只能第一次绘制前设置false生效,来关闭线性采样)。 */ /** *获取当前纹理是否启用了线性采样。 */ __getset(0,__proto,'isLinearSampling',function(){ return Render.isWebGL ? (this.bitmap.minFifter !=0x2600):true; },function(value){ if (!value && Render.isWebGL){ if (!value && (this.bitmap.minFifter==-1)&& (this.bitmap.magFifter==-1)){ this.bitmap.minFifter=0x2600; this.bitmap.magFifter=0x2600; this.bitmap.enableMerageInAtlas=false; } } }); Texture.moveUV=function(offsetX,offsetY,uv){ for (var i=0;i < 8;i+=2){ uv[i]+=offsetX; uv[i+1]+=offsetY; } return uv; } Texture.create=function(source,x,y,width,height,offsetX,offsetY,sourceWidth,sourceHeight){ (offsetX===void 0)&& (offsetX=0); (offsetY===void 0)&& (offsetY=0); (sourceWidth===void 0)&& (sourceWidth=0); (sourceHeight===void 0)&& (sourceHeight=0); var btex=(source instanceof laya.resource.Texture ); var uv=btex ? source.uv :Texture.DEF_UV; var bitmap=btex ? source.bitmap :source; var bIsAtlas=RunDriver.isAtlas(bitmap); if (bIsAtlas){ var atlaser=bitmap._atlaser; var nAtlasID=(source)._atlasID; if (nAtlasID==-1){ throw new Error("create texture error"); } bitmap=atlaser._inAtlasTextureBitmapValue[nAtlasID]; uv=atlaser._inAtlasTextureOriUVValue[nAtlasID]; }; var tex=new Texture(bitmap,null); if (bitmap.width && (x+width)> bitmap.width)width=bitmap.width-x; if (bitmap.height && (y+height)> bitmap.height)height=bitmap.height-y; tex.width=width; tex.height=height; tex.offsetX=offsetX; tex.offsetY=offsetY; tex.sourceWidth=sourceWidth || width; tex.sourceHeight=sourceHeight || height; var dwidth=1 / bitmap.width; var dheight=1 / bitmap.height; x *=dwidth; y *=dheight; width *=dwidth; height *=dheight; var u1=tex.uv[0],v1=tex.uv[1],u2=tex.uv[4],v2=tex.uv[5]; var inAltasUVWidth=(u2-u1),inAltasUVHeight=(v2-v1); var oriUV=Texture.moveUV(uv[0],uv[1],[x,y,x+width,y,x+width,y+height,x,y+height]); tex.uv=[u1+oriUV[0] *inAltasUVWidth,v1+oriUV[1] *inAltasUVHeight,u2-(1-oriUV[2])*inAltasUVWidth,v1+oriUV[3] *inAltasUVHeight,u2-(1-oriUV[4])*inAltasUVWidth,v2-(1-oriUV[5])*inAltasUVHeight,u1+oriUV[6] *inAltasUVWidth,v2-(1-oriUV[7])*inAltasUVHeight]; if (bIsAtlas){ tex.addTextureToAtlas(); }; var bitmapScale=bitmap.scaleRate; if (bitmapScale && bitmapScale !=1){ tex.sourceWidth /=bitmapScale; tex.sourceHeight /=bitmapScale; tex.width /=bitmapScale; tex.height /=bitmapScale; tex.scaleRate=bitmapScale; tex.offsetX /=bitmapScale; tex.offsetY /=bitmapScale; }else{ tex.scaleRate=1; } return tex; } Texture.createFromTexture=function(texture,x,y,width,height){ var texScaleRate=texture.scaleRate; if (texScaleRate !=1){ x *=texScaleRate; y *=texScaleRate; width *=texScaleRate; height *=texScaleRate; }; var rect=Rectangle.TEMP.setTo(x-texture.offsetX,y-texture.offsetY,width,height); var result=rect.intersection(Texture._rect1.setTo(0,0,texture.width,texture.height),Texture._rect2); if (result) var tex=Texture.create(texture,result.x,result.y,result.width,result.height,result.x-rect.x,result.y-rect.y,width,height); else return null; tex.bitmap._removeReference(); return tex; } Texture.DEF_UV=[0,0,1.0,0,1.0,1.0,0,1.0]; Texture.INV_UV=[0,1,1.0,1,1.0,0.0,0,0.0]; Texture._rect1=new Rectangle(); Texture._rect2=new Rectangle(); return Texture; })(EventDispatcher) /** *TimeLine 是一个用来创建时间轴动画的类。 */ //class laya.utils.TimeLine extends laya.events.EventDispatcher var TimeLine=(function(_super){ var tweenData; function TimeLine(){ this._labelDic=null; this._tweenDic={}; this._tweenDataList=[]; this._endTweenDataList=null; //以结束时间进行排序 this._currTime=0; this._lastTime=0; this._startTime=0; /**当前动画数据播放到第几个了*/ this._index=0; /**为TWEEN创建属于自己的唯一标识,方便管理*/ this._gidIndex=0; /**保留所有对象第一次注册动画时的状态(根据时间跳转时,需要把对象的回复,再计算接下来的状态)*/ this._firstTweenDic={}; /**是否需要排序*/ this._startTimeSort=false; this._endTimeSort=false; /**是否循环*/ this._loopKey=false; /**缩放动画播放的速度。*/ this.scale=1; this._frameRate=60; this._frameIndex=0; this._total=0; TimeLine.__super.call(this); } __class(TimeLine,'laya.utils.TimeLine',_super); var __proto=TimeLine.prototype; /** *控制一个对象,从当前点移动到目标点。 *@param target 要控制的对象。 *@param props 要控制对象的属性。 *@param duration 对象TWEEN的时间。 *@param ease 缓动类型 *@param offset 相对于上一个对象,偏移多长时间(单位:毫秒)。 */ __proto.to=function(target,props,duration,ease,offset){ (offset===void 0)&& (offset=0); return this._create(target,props,duration,ease,offset,true); } /** *从 props 属性,缓动到当前状态。 *@param target target 目标对象(即将更改属性值的对象) *@param props 要控制对象的属性 *@param duration 对象TWEEN的时间 *@param ease 缓动类型 *@param offset 相对于上一个对象,偏移多长时间(单位:毫秒) */ __proto.from=function(target,props,duration,ease,offset){ (offset===void 0)&& (offset=0); return this._create(target,props,duration,ease,offset,false); } /**@private */ __proto._create=function(target,props,duration,ease,offset,isTo){ var tTweenData=Pool.getItemByClass("tweenData",tweenData); tTweenData.isTo=isTo; tTweenData.type=0; tTweenData.target=target; tTweenData.duration=duration; tTweenData.data=props; tTweenData.startTime=this._startTime+offset; tTweenData.endTime=tTweenData.startTime+tTweenData.duration; tTweenData.ease=ease; this._startTime=Math.max(tTweenData.endTime,this._startTime); this._tweenDataList.push(tTweenData); this._startTimeSort=true; this._endTimeSort=true; return this; } /** *在时间队列中加入一个标签。 *@param label 标签名称。 *@param offset 标签相对于上个动画的偏移时间(单位:毫秒)。 */ __proto.addLabel=function(label,offset){ var tTweenData=Pool.getItemByClass("tweenData",tweenData); tTweenData.type=1; tTweenData.data=label; tTweenData.endTime=tTweenData.startTime=this._startTime+offset; this._labelDic || (this._labelDic={}); this._labelDic[label]=tTweenData; this._tweenDataList.push(tTweenData); return this; } /** *移除指定的标签 *@param label */ __proto.removeLabel=function(label){ if (this._labelDic && this._labelDic[label]){ var tTweenData=this._labelDic[label]; if (tTweenData){ var tIndex=this._tweenDataList.indexOf(tTweenData); if (tIndex >-1){ this._tweenDataList.splice(tIndex,1); } } delete this._labelDic[label]; } } /** *动画从整个动画的某一时间开始。 *@param time(单位:毫秒)。 */ __proto.gotoTime=function(time){ if (this._tweenDataList==null || this._tweenDataList.length==0)return; var tTween; var tObject; for (var p in this._firstTweenDic){ tObject=this._firstTweenDic[p]; if (tObject){ for (var tDataP in tObject){ if (tObject.diyTarget.hasOwnProperty(tDataP)){ tObject.diyTarget[tDataP]=tObject[tDataP]; } } } } for (p in this._tweenDic){ tTween=this._tweenDic[p]; tTween.clear(); delete this._tweenDic[p]; } this._index=0; this._gidIndex=0; this._currTime=time; this._lastTime=Browser.now(); var tTweenDataCopyList; if (this._endTweenDataList==null || this._endTimeSort){ this._endTimeSort=false; this._endTweenDataList=tTweenDataCopyList=this._tweenDataList.concat(); function Compare (paraA,paraB){ if (paraA.endTime > paraB.endTime){ return 1; }else if (paraA.endTime < paraB.endTime){ return-1; }else { return 0; } } tTweenDataCopyList.sort(Compare); }else { tTweenDataCopyList=this._endTweenDataList }; var tTweenData; for (var i=0,n=tTweenDataCopyList.length;i < n;i++){ tTweenData=tTweenDataCopyList[i]; if (tTweenData.type==0){ if (time >=tTweenData.endTime){ this._index=Math.max(this._index,i+1); var props=tTweenData.data; if (tTweenData.isTo){ for (var tP in props){ tTweenData.target[tP]=props[tP]; } } }else { break ; } } } for (i=0,n=this._tweenDataList.length;i < n;i++){ tTweenData=this._tweenDataList[i]; if (tTweenData.type==0){ if (time >=tTweenData.startTime && time < tTweenData.endTime){ this._index=Math.max(this._index,i+1); this._gidIndex++; tTween=Pool.getItemByClass("tween",Tween); tTween._create(tTweenData.target,tTweenData.data,tTweenData.duration,tTweenData.ease,Handler.create(this,this._animComplete,[this._gidIndex]),0,false,tTweenData.isTo,true,false); tTween.setStartTime(this._currTime-(time-tTweenData.startTime)); tTween._updateEase(this._currTime); tTween.gid=this._gidIndex; this._tweenDic[this._gidIndex]=tTween; } } } } /** *从指定的标签开始播。 *@param Label 标签名。 */ __proto.gotoLabel=function(Label){ if (this._labelDic==null)return; var tLabelData=this._labelDic[Label]; if (tLabelData)this.gotoTime(tLabelData.startTime); } /** *暂停整个动画。 */ __proto.pause=function(){ Laya.timer.clear(this,this._update); } /** *恢复暂停动画的播放。 */ __proto.resume=function(){ this.play(this._currTime,this._loopKey); } /** *播放动画。 *@param timeOrLabel 开启播放的时间点或标签名。 *@param loop 是否循环播放。 */ __proto.play=function(timeOrLabel,loop){ (timeOrLabel===void 0)&& (timeOrLabel=0); (loop===void 0)&& (loop=false); if (!this._tweenDataList)return; if (this._startTimeSort){ this._startTimeSort=false; function Compare (paraA,paraB){ if (paraA.startTime > paraB.startTime){ return 1; }else if (paraA.startTime < paraB.startTime){ return-1; }else { return 0; } } this._tweenDataList.sort(Compare); for (var i=0,n=this._tweenDataList.length;i < n;i++){ var tTweenData=this._tweenDataList[i]; if (tTweenData !=null && tTweenData.type==0){ var tTarget=tTweenData.target; var gid=(tTarget.$_GID || (tTarget.$_GID=Utils.getGID())); var tSrcData=null; if (this._firstTweenDic[gid]==null){ tSrcData={}; tSrcData.diyTarget=tTarget; this._firstTweenDic[gid]=tSrcData; }else { tSrcData=this._firstTweenDic[gid]; } for (var p in tTweenData.data){ if (tSrcData[p]==null){ tSrcData[p]=tTarget[p]; } } } } } if ((typeof timeOrLabel=='string')){ this.gotoLabel(timeOrLabel); }else { this.gotoTime(timeOrLabel); } this._loopKey=loop; this._lastTime=Browser.now(); Laya.timer.frameLoop(1,this,this._update); } /** *更新当前动画。 */ __proto._update=function(){ if (this._currTime >=this._startTime){ if (this._loopKey){ this._complete(); if (!this._tweenDataList)return; this.gotoTime(0); }else { for (var p in this._tweenDic){ tTween=this._tweenDic[p]; tTween.complete(); } this._complete(); this.pause(); return; } }; var tNow=Browser.now(); var tFrameTime=tNow-this._lastTime; var tCurrTime=this._currTime+=tFrameTime *this.scale; this._lastTime=tNow; for (p in this._tweenDic){ tTween=this._tweenDic[p]; tTween._updateEase(tCurrTime); }; var tTween; if (this._tweenDataList.length !=0 && this._index < this._tweenDataList.length){ var tTweenData=this._tweenDataList[this._index]; if (tCurrTime >=tTweenData.startTime){ this._index++; if (tTweenData.type==0){ this._gidIndex++; tTween=Pool.getItemByClass("tween",Tween); tTween._create(tTweenData.target,tTweenData.data,tTweenData.duration,tTweenData.ease,Handler.create(this,this._animComplete,[this._gidIndex]),0,false,tTweenData.isTo,true,false); tTween.setStartTime(tCurrTime); tTween.gid=this._gidIndex; this._tweenDic[this._gidIndex]=tTween; tTween._updateEase(tCurrTime); }else { this.event(/*laya.events.Event.LABEL*/"label",tTweenData.data); } } } } /** *指定的动画索引处的动画播放完成后,把此动画从列表中删除。 *@param index */ __proto._animComplete=function(index){ var tTween=this._tweenDic[index]; if (tTween)delete this._tweenDic[index]; } /**@private */ __proto._complete=function(){ this.event(/*laya.events.Event.COMPLETE*/"complete"); } /** *重置所有对象,复用对象的时候使用。 */ __proto.reset=function(){ var p; if (this._labelDic){ for (p in this._labelDic){ delete this._labelDic[p]; } }; var tTween; for (p in this._tweenDic){ tTween=this._tweenDic[p]; tTween.clear(); delete this._tweenDic[p]; } for (p in this._firstTweenDic){ delete this._firstTweenDic[p]; } this._endTweenDataList=null; if (this._tweenDataList && this._tweenDataList.length){ var i=0,len=0; len=this._tweenDataList.length; for (i=0;i < len;i++){ if(this._tweenDataList[i]) this._tweenDataList[i].destroy(); } } this._tweenDataList.length=0; this._currTime=0; this._lastTime=0; this._startTime=0; this._index=0; this._gidIndex=0; this.scale=1; Laya.timer.clear(this,this._update); } /** *彻底销毁此对象。 */ __proto.destroy=function(){ this.reset(); this._labelDic=null; this._tweenDic=null; this._tweenDataList=null; this._firstTweenDic=null; } /** *@private *设置帧索引 */ /** *@private *得到帧索引 */ __getset(0,__proto,'index',function(){ return this._frameIndex; },function(value){ this._frameIndex=value; this.gotoTime(this._frameIndex / this._frameRate *1000); }); /** *得到总帧数。 */ __getset(0,__proto,'total',function(){ this._total=Math.floor(this._startTime / 1000 *this._frameRate); return this._total; }); TimeLine.to=function(target,props,duration,ease,offset){ (offset===void 0)&& (offset=0); return (new TimeLine()).to(target,props,duration,ease,offset); } TimeLine.from=function(target,props,duration,ease,offset){ (offset===void 0)&& (offset=0); return (new TimeLine()).from(target,props,duration,ease,offset); } TimeLine.__init$=function(){ //class tweenData tweenData=(function(){ function tweenData(){ this.type=0; //0代表TWEEN,1代表标签 this.isTo=true; this.startTime=NaN; this.endTime=NaN; this.target=null; this.duration=NaN; this.ease=null; this.data=null; } __class(tweenData,''); var __proto=tweenData.prototype; __proto.destroy=function(){ this.target=null; this.ease=null; this.data=null; this.isTo=true; this.type=0; Pool.recover("tweenData",this); } return tweenData; })() } return TimeLine; })(EventDispatcher) /** *

    Sprite 是基本的显示图形的显示列表节点。 Sprite 默认没有宽高,默认不接受鼠标事件。通过 graphics 可以绘制图片或者矢量图,支持旋转,缩放,位移等操作。Sprite同时也是容器类,可用来添加多个子节点。

    *

    注意: Sprite 默认没有宽高,可以通过getBounds函数获取;也可手动设置宽高;还可以设置autoSize=true,然后再获取宽高。Sprite的宽高一般用于进行碰撞检测和排版,并不影响显示图像大小,如果需要更改显示图像大小,请使用 scaleXscaleYscale

    *

    Sprite 默认不接受鼠标事件,即mouseEnabled=false,但是只要对其监听任意鼠标事件,会自动打开自己以及所有父对象的mouseEnabled=true。所以一般也无需手动设置mouseEnabled

    *

    LayaAir引擎API设计精简巧妙。核心显示类只有一个SpriteSprite针对不同的情况做了渲染优化,所以保证一个类实现丰富功能的同时,又达到高性能。

    * *@example 创建了一个 Sprite 实例。 *package *{ *import laya.display.Sprite; *import laya.events.Event; * *public class Sprite_Example *{ *private var sprite:Sprite; *private var shape:Sprite *public function Sprite_Example() *{ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *onInit(); *} *private function onInit():void *{ *sprite=new Sprite();//创建一个 Sprite 类的实例对象 sprite 。 *sprite.loadImage("resource/ui/bg.png");//加载并显示图片。 *sprite.x=200;//设置 sprite 对象相对于父容器的水平方向坐标值。 *sprite.y=200;//设置 sprite 对象相对于父容器的垂直方向坐标值。 *sprite.pivotX=0;//设置 sprite 对象的水平方法轴心点坐标。 *sprite.pivotY=0;//设置 sprite 对象的垂直方法轴心点坐标。 *Laya.stage.addChild(sprite);//将此 sprite 对象添加到显示列表。 *sprite.on(Event.CLICK,this,onClickSprite);//给 sprite 对象添加点击事件侦听。 *shape=new Sprite();//创建一个 Sprite 类的实例对象 sprite 。 *shape.graphics.drawRect(0,0,100,100,"#ccff00","#ff0000",2);//绘制一个有边框的填充矩形。 *shape.x=400;//设置 shape 对象相对于父容器的水平方向坐标值。 *shape.y=200;//设置 shape 对象相对于父容器的垂直方向坐标值。 *shape.width=100;//设置 shape 对象的宽度。 *shape.height=100;//设置 shape 对象的高度。 *shape.pivotX=50;//设置 shape 对象的水平方法轴心点坐标。 *shape.pivotY=50;//设置 shape 对象的垂直方法轴心点坐标。 *Laya.stage.addChild(shape);//将此 shape 对象添加到显示列表。 *shape.on(Event.CLICK,this,onClickShape);//给 shape 对象添加点击事件侦听。 *} *private function onClickSprite():void *{ *trace("点击 sprite 对象。"); *sprite.rotation+=5;//旋转 sprite 对象。 *} *private function onClickShape():void *{ *trace("点击 shape 对象。"); *shape.rotation+=5;//旋转 shape 对象。 *} *} *} * *@example *var sprite; *var shape; *Sprite_Example(); *function Sprite_Example() *{ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *onInit(); *} *function onInit() *{ *sprite=new laya.display.Sprite();//创建一个 Sprite 类的实例对象 sprite 。 *sprite.loadImage("resource/ui/bg.png");//加载并显示图片。 *sprite.x=200;//设置 sprite 对象相对于父容器的水平方向坐标值。 *sprite.y=200;//设置 sprite 对象相对于父容器的垂直方向坐标值。 *sprite.pivotX=0;//设置 sprite 对象的水平方法轴心点坐标。 *sprite.pivotY=0;//设置 sprite 对象的垂直方法轴心点坐标。 *Laya.stage.addChild(sprite);//将此 sprite 对象添加到显示列表。 *sprite.on(Event.CLICK,this,onClickSprite);//给 sprite 对象添加点击事件侦听。 *shape=new laya.display.Sprite();//创建一个 Sprite 类的实例对象 sprite 。 *shape.graphics.drawRect(0,0,100,100,"#ccff00","#ff0000",2);//绘制一个有边框的填充矩形。 *shape.x=400;//设置 shape 对象相对于父容器的水平方向坐标值。 *shape.y=200;//设置 shape 对象相对于父容器的垂直方向坐标值。 *shape.width=100;//设置 shape 对象的宽度。 *shape.height=100;//设置 shape 对象的高度。 *shape.pivotX=50;//设置 shape 对象的水平方法轴心点坐标。 *shape.pivotY=50;//设置 shape 对象的垂直方法轴心点坐标。 *Laya.stage.addChild(shape);//将此 shape 对象添加到显示列表。 *shape.on(laya.events.Event.CLICK,this,onClickShape);//给 shape 对象添加点击事件侦听。 *} *function onClickSprite() *{ *console.log("点击 sprite 对象。"); *sprite.rotation+=5;//旋转 sprite 对象。 *} *function onClickShape() *{ *console.log("点击 shape 对象。"); *shape.rotation+=5;//旋转 shape 对象。 *} * *@example *import Sprite=laya.display.Sprite; *class Sprite_Example { *private sprite:Sprite; *private shape:Sprite *public Sprite_Example(){ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *this.onInit(); *} *private onInit():void { *this.sprite=new Sprite();//创建一个 Sprite 类的实例对象 sprite 。 *this.sprite.loadImage("resource/ui/bg.png");//加载并显示图片。 *this.sprite.x=200;//设置 sprite 对象相对于父容器的水平方向坐标值。 *this.sprite.y=200;//设置 sprite 对象相对于父容器的垂直方向坐标值。 *this.sprite.pivotX=0;//设置 sprite 对象的水平方法轴心点坐标。 *this.sprite.pivotY=0;//设置 sprite 对象的垂直方法轴心点坐标。 *Laya.stage.addChild(this.sprite);//将此 sprite 对象添加到显示列表。 *this.sprite.on(laya.events.Event.CLICK,this,this.onClickSprite);//给 sprite 对象添加点击事件侦听。 *this.shape=new Sprite();//创建一个 Sprite 类的实例对象 sprite 。 *this.shape.graphics.drawRect(0,0,100,100,"#ccff00","#ff0000",2);//绘制一个有边框的填充矩形。 *this.shape.x=400;//设置 shape 对象相对于父容器的水平方向坐标值。 *this.shape.y=200;//设置 shape 对象相对于父容器的垂直方向坐标值。 *this.shape.width=100;//设置 shape 对象的宽度。 *this.shape.height=100;//设置 shape 对象的高度。 *this.shape.pivotX=50;//设置 shape 对象的水平方法轴心点坐标。 *this.shape.pivotY=50;//设置 shape 对象的垂直方法轴心点坐标。 *Laya.stage.addChild(this.shape);//将此 shape 对象添加到显示列表。 *this.shape.on(laya.events.Event.CLICK,this,this.onClickShape);//给 shape 对象添加点击事件侦听。 *} *private onClickSprite():void { *console.log("点击 sprite 对象。"); *this.sprite.rotation+=5;//旋转 sprite 对象。 *} *private onClickShape():void { *console.log("点击 shape 对象。"); *this.shape.rotation+=5;//旋转 shape 对象。 *} *} */ //class laya.display.Sprite extends laya.display.Node var Sprite=(function(_super){ function Sprite(){ /**@private 矩阵变换信息。*/ this._transform=null; /**@private */ this._tfChanged=false; /**@private */ this._x=0; /**@private */ this._y=0; /**@private */ this._width=0; /**@private */ this._height=0; /**@private */ this._repaint=1; /**@private 鼠标状态,0:auto,1:mouseEnabled=false,2:mouseEnabled=true。*/ this._mouseEnableState=0; /**@private Z排序,数值越大越靠前。*/ this._zOrder=0; /**@private */ this._graphics=null; /**@private */ this._renderType=0; /**@private */ this._optimizeScrollRect=false; /**@private */ this._texture=null; /** *

    鼠标事件与此对象的碰撞检测是否可穿透。碰撞检测发生在鼠标事件的捕获阶段,此阶段引擎会从stage开始递归检测stage及其子对象,直到找到命中的目标对象或者未命中任何对象。

    *

    穿透表示鼠标事件发生的位置处于本对象绘图区域内时,才算命中,而与对象宽高和值为Rectangle对象的hitArea属性无关。如果sprite.hitArea值是HitArea对象,表示显式声明了此对象的鼠标事件响应区域,而忽略对象的宽高、mouseThrough属性。

    *

    影响对象鼠标事件响应区域的属性为:width、height、hitArea,优先级顺序为:hitArea(type:HitArea)>hitArea(type:Rectangle)>width/height。

    *@default false 不可穿透,此对象的鼠标响应区域由width、height、hitArea属性决定。

    */ this.mouseThrough=false; /** *

    指定是否自动计算宽高数据。默认值为 false 。

    *

    Sprite宽高默认为0,并且不会随着绘制内容的变化而变化,如果想根据绘制内容获取宽高,可以设置本属性为true,或者通过getBounds方法获取。设置为true,对性能有一定影响。

    */ this.autoSize=false; /** *

    指定鼠标事件检测是优先检测自身,还是优先检测其子对象。鼠标事件检测发生在鼠标事件的捕获阶段,此阶段引擎会从stage开始递归检测stage及其子对象,直到找到命中的目标对象或者未命中任何对象。

    *

    如果为false,优先检测子对象,当有子对象被命中时,中断检测,获得命中目标。如果未命中任何子对象,最后再检测此对象;如果为true,则优先检测本对象,如果本对象没有被命中,直接中断检测,表示没有命中目标;如果本对象被命中,则进一步递归检测其子对象,以确认最终的命中目标。

    *

    合理使用本属性,能减少鼠标事件检测的节点,提高性能。可以设置为true的情况:开发者并不关心此节点的子节点的鼠标事件检测结果,也就是以此节点作为其子节点的鼠标事件检测依据。

    *

    Stage对象和UI的View组件默认为true。

    *@default false 优先检测此对象的子对象,当递归检测完所有子对象后,仍然没有找到目标对象,最后再检测此对象。 */ this.hitTestPrior=false; /** *

    视口大小,视口外的子对象,将不被渲染(如果想实现裁剪效果,请使用srollRect),合理使用能提高渲染性能。比如由一个个小图片拼成的地图块,viewport外面的小图片将不渲染

    *

    srollRect和viewport的区别:
    *1. srollRect自带裁剪效果,viewport只影响子对象渲染是否渲染,不具有裁剪效果(性能更高)。
    *2. 设置rect的x,y属性均能实现区域滚动效果,但scrollRect会保持0,0点位置不变。

    *@default null */ this.viewport=null; Sprite.__super.call(this); this._style=Style.EMPTY; } __class(Sprite,'laya.display.Sprite',_super); var __proto=Sprite.prototype; Laya.imps(__proto,{"laya.display.ILayout":true}) /**@private */ __proto.createConchModel=function(){ return /*__JS__ */new ConchNode(); } /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); this._releaseMem(); _super.prototype.destroy.call(this,destroyChild); this._style && this._style.destroy(); this._transform && this._transform.destroy(); this._transform=null; this._style=null; this._graphics=null; } /**根据zOrder进行重新排序。*/ __proto.updateZOrder=function(){ Utils.updateOrder(this._childs)&& this.repaint(); } /**在设置cacheAs的情况下,调用此方法会重新刷新缓存。*/ __proto.reCache=function(){ if (this._$P.cacheCanvas)this._$P.cacheCanvas.reCache=true; this._repaint=1; } /** *

    设置对象在自身坐标系下的边界范围。与 getSelfBounds 对应。当 autoSize==true 时,会影响对象宽高。设置后,当需要获取自身边界范围时,就不再需要计算,合理使用能提高性能。比如 getBounds 会优先使用 setBounds 指定的值,如果没有指定则进行计算,此计算会对性能消耗比较大。

    *

    注意: setBoundsgetBounds 并非对应相等关系, getBounds 获取的是本对象在父容器坐标系下的边界范围,通过设置 setBounds 会影响 getBounds 的结果。

    *@param bound bounds矩形区域 */ __proto.setBounds=function(bound){ this._set$P("uBounds",bound); } /** *

    获取本对象在父容器坐标系的矩形显示区域。

    *

    注意: 1.计算量较大,尽量少用,如果需要频繁使用,可以通过手动设置 setBounds 来缓存自身边界信息,从而避免比较消耗性能的计算。2. setBoundsgetBounds 并非对应相等关系, getBounds 获取的是本对象在父容器坐标系下的边界范围,通过设置 setBounds 会影响 getBounds 的结果。

    *@return 矩形区域。 */ __proto.getBounds=function(){ if (!this._$P.mBounds)this._set$P("mBounds",new Rectangle()); return Rectangle._getWrapRec(this._boundPointsToParent(),this._$P.mBounds); } /** *获取对象在自身坐标系的边界范围。与 setBounds 对应。 *

    注意:计算量较大,尽量少用,如果需要频繁使用,可以提前手动设置 setBounds 来缓存自身边界信息,从而避免比较消耗性能的计算。

    *@return 矩形区域。 */ __proto.getSelfBounds=function(){ if (this._$P.uBounds)return this._$P.uBounds; if (!this._$P.mBounds)this._set$P("mBounds",new Rectangle()); return Rectangle._getWrapRec(this._getBoundPointsM(false),this._$P.mBounds); } /** *@private *获取本对象在父容器坐标系的显示区域多边形顶点列表。 *当显示对象链中有旋转时,返回多边形顶点列表,无旋转时返回矩形的四个顶点。 *@param ifRotate (可选)之前的对象链中是否有旋转。 *@return 顶点列表。结构:[x1,y1,x2,y2,x3,y3,...]。 */ __proto._boundPointsToParent=function(ifRotate){ (ifRotate===void 0)&& (ifRotate=false); var pX=0,pY=0; if (this._style){ pX=this._style._tf.translateX; pY=this._style._tf.translateY; ifRotate=ifRotate || (this._style._tf.rotate!==0); if (this._style.scrollRect){ pX+=this._style.scrollRect.x; pY+=this._style.scrollRect.y; } }; var pList=this._getBoundPointsM(ifRotate); if (!pList || pList.length < 1)return pList; if (pList.length !=8){ pList=ifRotate ? GrahamScan.scanPList(pList):Rectangle._getWrapRec(pList,Rectangle.TEMP)._getBoundPoints(); } if (!this.transform){ Utils.transPointList(pList,this._x-pX,this._y-pY); return pList; }; var tPoint=Point.TEMP; var i=0,len=pList.length; for (i=0;i < len;i+=2){ tPoint.x=pList[i]; tPoint.y=pList[i+1]; this.toParentPoint(tPoint); pList[i]=tPoint.x; pList[i+1]=tPoint.y; } return pList; } /** *返回此实例中的绘图对象( Graphics )的显示区域,不包括子对象。 *@param realSize (可选)使用图片的真实大小,默认为false *@return 一个 Rectangle 对象,表示获取到的显示区域。 */ __proto.getGraphicBounds=function(realSize){ (realSize===void 0)&& (realSize=false); if (!this._graphics)return Rectangle.TEMP.setTo(0,0,0,0); return this._graphics.getBounds(realSize); } /** *@private *获取自己坐标系的显示区域多边形顶点列表 *@param ifRotate (可选)当前的显示对象链是否由旋转 *@return 顶点列表。结构:[x1,y1,x2,y2,x3,y3,...]。 */ __proto._getBoundPointsM=function(ifRotate){ (ifRotate===void 0)&& (ifRotate=false); if (this._$P.uBounds)return this._$P.uBounds._getBoundPoints(); if (!this._$P.temBM)this._set$P("temBM",[]); if (this.scrollRect){ var rst=Utils.clearArray(this._$P.temBM); var rec=Rectangle.TEMP; rec.copyFrom(this.scrollRect); Utils.concatArray(rst,rec._getBoundPoints()); return rst; }; var pList=this._graphics ? this._graphics.getBoundPoints():Utils.clearArray(this._$P.temBM); var child; var cList; var __childs; __childs=this._childs; for (var i=0,n=__childs.length;i < n;i++){ child=__childs [i]; if ((child instanceof laya.display.Sprite )&& child.visible==true){ cList=child._boundPointsToParent(ifRotate); if (cList) pList=pList ? Utils.concatArray(pList,cList):cList; } } return pList; } /** *@private *获取样式。 *@return 样式 Style 。 */ __proto.getStyle=function(){ this._style===Style.EMPTY && (this._style=new Style()); return this._style; } /** *@private *设置样式。 *@param value 样式。 */ __proto.setStyle=function(value){ this._style=value; } /**@private */ __proto._adjustTransform=function(){ this._tfChanged=false; var style=this._style; var tf=style._tf; var sx=tf.scaleX,sy=tf.scaleY; var m; if (tf.rotate || sx!==1 || sy!==1 || tf.skewX || tf.skewY){ m=this._transform || (this._transform=Matrix.create()); m.bTransform=true; var skx=(tf.rotate-tf.skewX)*0.0174532922222222; var sky=(tf.rotate+tf.skewY)*0.0174532922222222; var cx=Math.cos(sky); var ssx=Math.sin(sky); var cy=Math.sin(skx); var ssy=Math.cos(skx); m.a=sx *cx; m.b=sx *ssx; m.c=-sy *cy; m.d=sy *ssy; m.tx=m.ty=0; return m; }else { this._transform && this._transform.destroy(); this._transform=null; this._renderType &=~ /*laya.renders.RenderSprite.TRANSFORM*/0x04; } return m; } /** *

    设置坐标位置。相当于分别设置x和y属性。

    *

    因为返回值为Sprite对象本身,所以可以使用如下语法:spr.pos(...).scale(...);

    *@param x X轴坐标。 *@param y Y轴坐标。 *@param speedMode (可选)是否极速模式,正常是调用this.x=value进行赋值,极速模式直接调用内部函数处理,如果未重写x,y属性,建议设置为急速模式性能更高。 *@return 返回对象本身。 */ __proto.pos=function(x,y,speedMode){ (speedMode===void 0)&& (speedMode=false); if (this._x!==x || this._y!==y){ if (this.destroyed)return this; if (speedMode){ this._x=x; this._y=y; this.conchModel && this.conchModel.pos(this._x,this._y); var p=this._parent; if (p && p._repaint===0){ p._repaint=1; p.parentRepaint(); } if (this._$P.maskParent && this._$P.maskParent._repaint===0){ this._$P.maskParent._repaint=1; this._$P.maskParent.parentRepaint(); } }else { this.x=x; this.y=y; } } return this; } /** *

    设置轴心点。相当于分别设置pivotX和pivotY属性。

    *

    因为返回值为Sprite对象本身,所以可以使用如下语法:spr.pivot(...).pos(...);

    *@param x X轴心点。 *@param y Y轴心点。 *@return 返回对象本身。 */ __proto.pivot=function(x,y){ this.pivotX=x; this.pivotY=y; return this; } /** *

    设置宽高。相当于分别设置width和height属性。

    *

    因为返回值为Sprite对象本身,所以可以使用如下语法:spr.size(...).pos(...);

    *@param width 宽度值。 *@param hegiht 高度值。 *@return 返回对象本身。 */ __proto.size=function(width,height){ this.width=width; this.height=height; return this; } /** *

    设置缩放。相当于分别设置scaleX和scaleY属性。

    *

    因为返回值为Sprite对象本身,所以可以使用如下语法:spr.scale(...).pos(...);

    *@param scaleX X轴缩放比例。 *@param scaleY Y轴缩放比例。 *@param speedMode (可选)是否极速模式,正常是调用this.scaleX=value进行赋值,极速模式直接调用内部函数处理,如果未重写scaleX,scaleY属性,建议设置为急速模式性能更高。 *@return 返回对象本身。 */ __proto.scale=function(scaleX,scaleY,speedMode){ (speedMode===void 0)&& (speedMode=false); var style=this.getStyle(); var _tf=style._tf; if (_tf.scaleX !=scaleX || _tf.scaleY !=scaleY){ if (this.destroyed)return this; if (speedMode){ style.setScale(scaleX,scaleY); this._tfChanged=true; this.conchModel && this.conchModel.scale(scaleX,scaleY); this._renderType |=/*laya.renders.RenderSprite.TRANSFORM*/0x04; var p=this._parent; if (p && p._repaint===0){ p._repaint=1; p.parentRepaint(); } }else { this.scaleX=scaleX; this.scaleY=scaleY; } } return this; } /** *

    设置倾斜角度。相当于分别设置skewX和skewY属性。

    *

    因为返回值为Sprite对象本身,所以可以使用如下语法:spr.skew(...).pos(...);

    *@param skewX 水平倾斜角度。 *@param skewY 垂直倾斜角度。 *@return 返回对象本身 */ __proto.skew=function(skewX,skewY){ this.skewX=skewX; this.skewY=skewY; return this; } /** *更新、呈现显示对象。由系统调用。 *@param context 渲染的上下文引用。 *@param x X轴坐标。 *@param y Y轴坐标。 */ __proto.render=function(context,x,y){ Stat.spriteCount++; RenderSprite.renders[this._renderType]._fun(this,context,x+this._x,y+this._y); this._repaint=0; } /** *

    绘制 当前SpriteCanvas 上,并返回一个HtmlCanvas。

    *

    绘制的结果可以当作图片源,再次绘制到其他Sprite里面,示例:

    * *var htmlCanvas:HTMLCanvas=sprite.drawToCanvas(100,100,0,0);//把精灵绘制到canvas上面 *var texture:Texture=new Texture(htmlCanvas);//使用htmlCanvas创建Texture *var sp:Sprite=new Sprite().pos(0,200);//创建精灵并把它放倒200位置 *sp.graphics.drawTexture(texture);//把截图绘制到精灵上 *Laya.stage.addChild(sp);//把精灵显示到舞台 * *

    也可以获取原始图片数据,分享到网上,从而实现截图效果,示例:

    * *var htmlCanvas:HTMLCanvas=sprite.drawToCanvas(100,100,0,0);//把精灵绘制到canvas上面 * *htmlCanvas.toBase64("image/png",0.92,function(base64){//webgl和canvas模式下为同步方法,加速器下是异步方法 *trace(base64);//打印图片base64信息,可以发给服务器或者保存为图片 *}); * *@param canvasWidth 画布宽度。 *@param canvasHeight 画布高度。 *@param x 绘制的 X 轴偏移量。 *@param y 绘制的 Y 轴偏移量。 *@return HTMLCanvas 对象。 */ __proto.drawToCanvas=function(canvasWidth,canvasHeight,offsetX,offsetY){ if (Render.isConchNode){ var canvas=HTMLCanvas.create("2D"); var context=new RenderContext(canvasWidth,canvasHeight,canvas); context.ctx.setCanvasType(1); this.conchModel.drawToCanvas(canvas.source,offsetX,offsetY); return canvas; }else { return RunDriver.drawToCanvas(this,this._renderType,canvasWidth,canvasHeight,offsetX,offsetY); } } /** *

    自定义更新、呈现显示对象。一般用来扩展渲染模式,请合理使用,可能会导致在加速器上无法渲染。

    *

    注意不要在此函数内增加或删除树节点,否则会对树节点遍历造成影响。

    *@param context 渲染的上下文引用。 *@param x X轴坐标。 *@param y Y轴坐标。 */ __proto.customRender=function(context,x,y){ this._renderType |=/*laya.renders.RenderSprite.CUSTOM*/0x400; } /** *@private *应用滤镜。 */ __proto._applyFilters=function(){ if (Render.isWebGL)return; var _filters; _filters=this._$P.filters; if (!_filters || _filters.length < 1)return; for (var i=0,n=_filters.length;i < n;i++){ _filters[i].action.apply(this._$P.cacheCanvas); } } /** *@private *查看当前原件中是否包含发光滤镜。 *@return 一个 Boolean 值,表示当前原件中是否包含发光滤镜。 */ __proto._isHaveGlowFilter=function(){ var i=0,len=0; if (this.filters){ for (i=0;i < this.filters.length;i++){ if (this.filters[i].type==/*laya.filters.Filter.GLOW*/0x08){ return true; } } } for (i=0,len=this._childs.length;i < len;i++){ if (this._childs[i]._isHaveGlowFilter()){ return true; } } return false; } /** *把本地坐标转换为相对stage的全局坐标。 *@param point 本地坐标点。 *@param createNewPoint (可选)是否创建一个新的Point对象作为返回值,默认为false,使用输入的point对象返回,减少对象创建开销。 *@return 转换后的坐标的点。 */ __proto.localToGlobal=function(point,createNewPoint){ (createNewPoint===void 0)&& (createNewPoint=false); if (createNewPoint===true){ point=new Point(point.x,point.y); }; var ele=this; while (ele){ if (ele==Laya.stage)break ; point=ele.toParentPoint(point); ele=ele.parent; } return point; } /** *把stage的全局坐标转换为本地坐标。 *@param point 全局坐标点。 *@param createNewPoint (可选)是否创建一个新的Point对象作为返回值,默认为false,使用输入的point对象返回,减少对象创建开销。 *@return 转换后的坐标的点。 */ __proto.globalToLocal=function(point,createNewPoint){ (createNewPoint===void 0)&& (createNewPoint=false); if (createNewPoint){ point=new Point(point.x,point.y); }; var ele=this; var list=[]; while (ele){ if (ele==Laya.stage)break ; list.push(ele); ele=ele.parent; }; var i=list.length-1; while (i >=0){ ele=list[i]; point=ele.fromParentPoint(point); i--; } return point; } /** *将本地坐标系坐标转转换到父容器坐标系。 *@param point 本地坐标点。 *@return 转换后的点。 */ __proto.toParentPoint=function(point){ if (!point)return point; point.x-=this.pivotX; point.y-=this.pivotY; if (this.transform){ this._transform.transformPoint(point); } point.x+=this._x; point.y+=this._y; var scroll=this._style.scrollRect; if (scroll){ point.x-=scroll.x; point.y-=scroll.y; } return point; } /** *将父容器坐标系坐标转换到本地坐标系。 *@param point 父容器坐标点。 *@return 转换后的点。 */ __proto.fromParentPoint=function(point){ if (!point)return point; point.x-=this._x; point.y-=this._y; var scroll=this._style.scrollRect; if (scroll){ point.x+=scroll.x; point.y+=scroll.y; } if (this.transform){ this._transform.invertTransformPoint(point); } point.x+=this.pivotX; point.y+=this.pivotY; return point; } /** *

    增加事件侦听器,以使侦听器能够接收事件通知。

    *

    如果侦听鼠标事件,则会自动设置自己和父亲节点的属性 mouseEnabled 的值为 true(如果父节点mouseEnabled=false,则停止设置父节点mouseEnabled属性)。

    *@param type 事件的类型。 *@param caller 事件侦听函数的执行域。 *@param listener 事件侦听函数。 *@param args (可选)事件侦听函数的回调参数。 *@return 此 EventDispatcher 对象。 */ __proto.on=function(type,caller,listener,args){ if (this._mouseEnableState!==1 && this.isMouseEvent(type)){ this.mouseEnabled=true; this._setBit(/*laya.display.Node.MOUSEENABLE*/0x2,true); if (this._parent){ this._$2__onDisplay(); } return this._createListener(type,caller,listener,args,false); } return _super.prototype.on.call(this,type,caller,listener,args); } /** *

    增加事件侦听器,以使侦听器能够接收事件通知,此侦听事件响应一次后则自动移除侦听。

    *

    如果侦听鼠标事件,则会自动设置自己和父亲节点的属性 mouseEnabled 的值为 true(如果父节点mouseEnabled=false,则停止设置父节点mouseEnabled属性)。

    *@param type 事件的类型。 *@param caller 事件侦听函数的执行域。 *@param listener 事件侦听函数。 *@param args (可选)事件侦听函数的回调参数。 *@return 此 EventDispatcher 对象。 */ __proto.once=function(type,caller,listener,args){ if (this._mouseEnableState!==1 && this.isMouseEvent(type)){ this.mouseEnabled=true; this._setBit(/*laya.display.Node.MOUSEENABLE*/0x2,true); if (this._parent){ this._$2__onDisplay(); } return this._createListener(type,caller,listener,args,true); } return _super.prototype.once.call(this,type,caller,listener,args); } /**@private */ __proto._$2__onDisplay=function(){ if (this._mouseEnableState!==1){ var ele=this; ele=ele.parent; while (ele && ele._mouseEnableState!==1){ if (ele._getBit(/*laya.display.Node.MOUSEENABLE*/0x2))break ; ele.mouseEnabled=true; ele._setBit(/*laya.display.Node.MOUSEENABLE*/0x2,true); ele=ele.parent; } } } /** *

    加载并显示一个图片。功能等同于graphics.loadImage方法。支持异步加载。

    *

    注意:多次调用loadImage绘制不同的图片,会同时显示。

    *@param url 图片地址。 *@param x (可选)显示图片的x位置。 *@param y (可选)显示图片的y位置。 *@param width (可选)显示图片的宽度,设置为0表示使用图片默认宽度。 *@param height (可选)显示图片的高度,设置为0表示使用图片默认高度。 *@param complete (可选)加载完成回调。 *@return 返回精灵对象本身。 */ __proto.loadImage=function(url,x,y,width,height,complete){ var _$this=this; (x===void 0)&& (x=0); (y===void 0)&& (y=0); (width===void 0)&& (width=0); (height===void 0)&& (height=0); function loaded (tex){ if (!_$this.destroyed){ _$this.size(x+(width || tex.width),y+(height || tex.height)); _$this.repaint(); complete && complete.runWith(tex); } } this.graphics.loadImage(url,x,y,width,height,loaded); return this; } /**cacheAs后,设置自己和父对象缓存失效。*/ __proto.repaint=function(){ this.conchModel && this.conchModel.repaint && this.conchModel.repaint(); if (this._repaint===0){ this._repaint=1; this.parentRepaint(); } if (this._$P && this._$P.maskParent){ this._$P.maskParent.repaint(); } } /** *@private *获取是否重新缓存。 *@return 如果重新缓存值为 true,否则值为 false。 */ __proto._needRepaint=function(){ return (this._repaint!==0)&& this._$P.cacheCanvas && this._$P.cacheCanvas.reCache; } /**@private */ __proto._childChanged=function(child){ if (this._childs.length)this._renderType |=/*laya.renders.RenderSprite.CHILDS*/0x800; else this._renderType &=~ /*laya.renders.RenderSprite.CHILDS*/0x800; if (child && this._get$P("hasZorder"))Laya.timer.callLater(this,this.updateZOrder); this.repaint(); } /**cacheAs时,设置所有父对象缓存失效。 */ __proto.parentRepaint=function(){ var p=this._parent; if (p && p._repaint===0){ p._repaint=1; p.parentRepaint(); } } /** *开始拖动此对象。 *@param area (可选)拖动区域,此区域为当前对象注册点活动区域(不包括对象宽高),可选。 *@param hasInertia (可选)鼠标松开后,是否还惯性滑动,默认为false,可选。 *@param elasticDistance (可选)橡皮筋效果的距离值,0为无橡皮筋效果,默认为0,可选。 *@param elasticBackTime (可选)橡皮筋回弹时间,单位为毫秒,默认为300毫秒,可选。 *@param data (可选)拖动事件携带的数据,可选。 *@param disableMouseEvent (可选)禁用其他对象的鼠标检测,默认为false,设置为true能提高性能。 *@param ratio (可选)惯性阻尼系数,影响惯性力度和时长。 */ __proto.startDrag=function(area,hasInertia,elasticDistance,elasticBackTime,data,disableMouseEvent,ratio){ (hasInertia===void 0)&& (hasInertia=false); (elasticDistance===void 0)&& (elasticDistance=0); (elasticBackTime===void 0)&& (elasticBackTime=300); (disableMouseEvent===void 0)&& (disableMouseEvent=false); (ratio===void 0)&& (ratio=0.92); this._$P.dragging || (this._set$P("dragging",new Dragging())); this._$P.dragging.start(this,area,hasInertia,elasticDistance,elasticBackTime,data,disableMouseEvent,ratio); } /**停止拖动此对象。*/ __proto.stopDrag=function(){ this._$P.dragging && this._$P.dragging.stop(); } __proto._releaseMem=function(){ if (!this._$P)return; var cc=this._$P.cacheCanvas; if (cc && cc.ctx){ Pool.recover("RenderContext",cc.ctx); cc.ctx.canvas.size(0,0); cc.ctx=null; }; var fc=this._$P._filterCache; if (fc){ fc.destroy(); fc.recycle(); this._set$P('_filterCache',null); } this._$P._isHaveGlowFilter && this._set$P('_isHaveGlowFilter',false); this._$P._isHaveGlowFilter=null; } /**@private */ __proto._setDisplay=function(value){ if (!value)this._releaseMem(); _super.prototype._setDisplay.call(this,value); } /** *检测某个点是否在此对象内。 *@param x 全局x坐标。 *@param y 全局y坐标。 *@return 表示是否在对象内。 */ __proto.hitTestPoint=function(x,y){ var point=this.globalToLocal(Point.TEMP.setTo(x,y)); x=point.x; y=point.y; var rect=this._$P.hitArea ? this._$P.hitArea :(this._width > 0 && this._height > 0)? Rectangle.TEMP.setTo(0,0,this._width,this._height):this.getSelfBounds(); return rect.contains(x,y); } /**获得相对于本对象上的鼠标坐标信息。*/ __proto.getMousePoint=function(){ return this.globalToLocal(Point.TEMP.setTo(Laya.stage.mouseX,Laya.stage.mouseY)); } /**@private */ __proto._getWords=function(){ return null; } /**@private */ __proto._addChildsToLayout=function(out){ var words=this._getWords(); if (words==null && this._childs.length==0)return false; if (words){ for (var i=0,n=words.length;i < n;i++){ out.push(words[i]); } } this._childs.forEach(function(o,index,array){ o._style._enableLayout()&& o._addToLayout(out); }); return true; } /**@private */ __proto._addToLayout=function(out){ if (this._style.absolute)return; this._style.block ? out.push(this):(this._addChildsToLayout(out)&& (this.x=this.y=0)); } /**@private */ __proto._isChar=function(){ return false; } /**@private */ __proto._getCSSStyle=function(){ return this._style.getCSSStyle(); } /** *@private *设置指定属性名的属性值。 *@param name 属性名。 *@param value 属性值。 */ __proto._setAttributes=function(name,value){ switch (name){ case 'x': this.x=parseFloat(value); break ; case 'y': this.y=parseFloat(value); break ; case 'width': this.width=parseFloat(value); break ; case 'height': this.height=parseFloat(value); break ; default : this[name]=value; } } /** *@private */ __proto._layoutLater=function(){ this.parent && (this.parent)._layoutLater(); } /** *

    指定是否对使用了 scrollRect 的显示对象进行优化处理。默认为false(不优化)。

    *

    当值为ture时:将对此对象使用了scrollRect 设定的显示区域以外的显示内容不进行渲染,以提高性能(如果子对象有旋转缩放或者中心点偏移,则显示筛选会不精确)。

    */ __getset(0,__proto,'optimizeScrollRect',function(){ return this._optimizeScrollRect; },function(b){ if (this._optimizeScrollRect !=b){ this._optimizeScrollRect=b; this.conchModel && this.conchModel.optimizeScrollRect(b); } }); /** *设置是否开启自定义渲染,只有开启自定义渲染,才能使用customRender函数渲染。 */ __getset(0,__proto,'customRenderEnable',null,function(b){ if (b){ this._renderType |=/*laya.renders.RenderSprite.CUSTOM*/0x400; if (Render.isConchNode){ Sprite.CustomList.push(this); var canvas=new HTMLCanvas("2d"); canvas._setContext(/*__JS__ */new CanvasRenderingContext2D()); /*__JS__ */this.customContext=new RenderContext(0,0,canvas); canvas.context.setCanvasType && canvas.context.setCanvasType(2); this.conchModel.custom(canvas.context); } } }); /** *指定显示对象是否缓存为静态图像。功能同cacheAs的normal模式。建议优先使用cacheAs代替。 */ __getset(0,__proto,'cacheAsBitmap',function(){ return this.cacheAs!=="none"; },function(value){ this.cacheAs=value ? (this._$P["hasFilter"] ? "none" :"normal"):"none"; }); /** *

    指定显示对象是否缓存为静态图像,cacheAs时,子对象发生变化,会自动重新缓存,同时也可以手动调用reCache方法更新缓存。

    *

    建议把不经常变化的“复杂内容”缓存为静态图像,能极大提高渲染性能。cacheAs有"none","normal"和"bitmap"三个值可选。 *

  • 默认为"none",不做任何缓存。
  • *
  • 当值为"normal"时,canvas模式下进行画布缓存,webgl模式下进行命令缓存。
  • *
  • 当值为"bitmap"时,canvas模式下进行依然是画布缓存,webgl模式下使用renderTarget缓存。
  • *

    webgl下renderTarget缓存模式缺点:会额外创建renderTarget对象,增加内存开销,缓存面积有最大2048限制,不断重绘时会增加CPU开销。优点:大幅减少drawcall,渲染性能最高。 *webgl下命令缓存模式缺点:只会减少节点遍历及命令组织,不会减少drawcall数,性能中等。优点:没有额外内存开销,无需renderTarget支持。

    */ __getset(0,__proto,'cacheAs',function(){ return this._$P.cacheCanvas==null ? "none" :this._$P.cacheCanvas.type; },function(value){ var cacheCanvas=this._$P.cacheCanvas; if (value===(cacheCanvas ? cacheCanvas.type :"none"))return; if (value!=="none"){ if (!this._getBit(/*laya.display.Node.NOTICE_DISPLAY*/0x1))this._setUpNoticeType(/*laya.display.Node.NOTICE_DISPLAY*/0x1); cacheCanvas || (cacheCanvas=this._set$P("cacheCanvas",Pool.getItemByClass("cacheCanvas",Object))); cacheCanvas.type=value; cacheCanvas.reCache=true; this._renderType |=/*laya.renders.RenderSprite.CANVAS*/0x10; if (value=="bitmap")this.conchModel && this.conchModel.cacheAs(1); this._set$P("cacheForFilters",false); }else { if (this._$P["_mask"]){ }else if (this._$P["hasFilter"]){ this._set$P("cacheForFilters",true); }else { if (cacheCanvas){ var cc=cacheCanvas; if (cc && cc.ctx){ Pool.recover("RenderContext",cc.ctx); cc.ctx.canvas.size(0,0); cc.ctx=null; } Pool.recover("cacheCanvas",cacheCanvas); } this._$P.cacheCanvas=null; this._renderType &=~ /*laya.renders.RenderSprite.CANVAS*/0x10; this.conchModel && this.conchModel.cacheAs(0); } } this.repaint(); }); /**z排序,更改此值,则会按照值的大小对同一容器的所有对象重新排序。值越大,越靠上。默认为0,则根据添加顺序排序。*/ __getset(0,__proto,'zOrder',function(){ return this._zOrder; },function(value){ if (this._zOrder !=value){ this._zOrder=value; this.conchModel && this.conchModel.setZOrder && this.conchModel.setZOrder(value); if (this._parent){ value && this._parent._set$P("hasZorder",true); Laya.timer.callLater(this._parent,this.updateZOrder); } } }); /**旋转角度,默认值为0。以角度为单位。*/ __getset(0,__proto,'rotation',function(){ return this._style._tf.rotate; },function(value){ var style=this.getStyle(); if (style._tf.rotate!==value){ style.setRotate(value); this._tfChanged=true; this.conchModel && this.conchModel.rotate(value); this._renderType |=/*laya.renders.RenderSprite.TRANSFORM*/0x04; var p=this._parent; if (p && p._repaint===0){ p._repaint=1; p.parentRepaint(); } } }); /** *

    显示对象的宽度,单位为像素,默认为0。

    *

    此宽度用于鼠标碰撞检测,并不影响显示对象图像大小。需要对显示对象的图像进行缩放,请使用scale、scaleX、scaleY。

    *

    可以通过getbounds获取显示对象图像的实际宽度。

    */ __getset(0,__proto,'width',function(){ if (!this.autoSize)return this._width; return this.getSelfBounds().width; },function(value){ if (this._width!==value){ this._width=value; this.conchModel && this.conchModel.size(value,this._height) this.repaint(); } }); /**表示显示对象相对于父容器的水平方向坐标值。*/ __getset(0,__proto,'x',function(){ return this._x; },function(value){ if (this._x!==value){ if (this.destroyed)return; this._x=value; this.conchModel && this.conchModel.pos(value,this._y); var p=this._parent; if (p && p._repaint===0){ p._repaint=1; p.parentRepaint(); } if (this._$P.maskParent && this._$P.maskParent._repaint===0){ this._$P.maskParent._repaint=1; this._$P.maskParent.parentRepaint(); } } }); /** *获得相对于stage的全局Y轴缩放值(会叠加父亲节点的缩放值)。 */ __getset(0,__proto,'globalScaleY',function(){ var scale=1; var ele=this; while (ele){ if (ele===Laya.stage)break ; scale *=ele.scaleY; ele=ele.parent; } return scale; }); /** *

    可以设置一个Rectangle区域作为点击区域,或者设置一个HitArea实例作为点击区域,HitArea内可以设置可点击和不可点击区域。

    *

    如果不设置hitArea,则根据宽高形成的区域进行碰撞。

    */ __getset(0,__proto,'hitArea',function(){ return this._$P.hitArea; },function(value){ this._set$P("hitArea",value); }); /** *是否静态缓存此对象的当前帧的最终属性。为 true 时,子对象变化时不会自动更新缓存,但是可以通过调用 reCache 方法手动刷新。 *注意: 1. 设置 cacheAs 为非空和非"none"时才有效。 2. 由于渲染的时机在脚本执行之后,也就是说当前帧渲染的是对象的最终属性,所以如果在当前帧渲染之前、设置静态缓存之后改变对象属性,则最终渲染结果表现的是对象的最终属性。 */ __getset(0,__proto,'staticCache',function(){ return this._$P.staticCache; },function(value){ this._set$P("staticCache",value); if (!value)this.reCache(); }); /**设置一个Texture实例,并显示此图片(如果之前有其他绘制,则会被清除掉)。等同于graphics.clear();graphics.drawTexture()*/ __getset(0,__proto,'texture',function(){ return this._texture; },function(value){ if (this._texture !=value){ this._texture=value; this.graphics.cleanByTexture(value,0,0); } }); /**表示显示对象相对于父容器的垂直方向坐标值。*/ __getset(0,__proto,'y',function(){ return this._y; },function(value){ if (this._y!==value){ if (this.destroyed)return; this._y=value; this.conchModel && this.conchModel.pos(this._x,value); var p=this._parent; if (p && p._repaint===0){ p._repaint=1; p.parentRepaint(); } if (this._$P.maskParent && this._$P.maskParent._repaint===0){ this._$P.maskParent._repaint=1; this._$P.maskParent.parentRepaint(); } } }); /** *

    显示对象的高度,单位为像素,默认为0。

    *

    此高度用于鼠标碰撞检测,并不影响显示对象图像大小。需要对显示对象的图像进行缩放,请使用scale、scaleX、scaleY。

    *

    可以通过getbounds获取显示对象图像的实际高度。

    */ __getset(0,__proto,'height',function(){ if (!this.autoSize)return this._height; return this.getSelfBounds().height; },function(value){ if (this._height!==value){ this._height=value; this.conchModel && this.conchModel.size(this._width,value); this.repaint(); } }); /**指定要使用的混合模式。目前只支持"lighter"。*/ __getset(0,__proto,'blendMode',function(){ return this._style.blendMode; },function(value){ this.getStyle().blendMode=value; this.conchModel && this.conchModel.blendMode(value); if (value && value !="source-over")this._renderType |=/*laya.renders.RenderSprite.BLEND*/0x08; else this._renderType &=~ /*laya.renders.RenderSprite.BLEND*/0x08; this.parentRepaint(); }); /**X轴缩放值,默认值为1。设置为负数,可以实现水平反转效果,比如scaleX=-1。*/ __getset(0,__proto,'scaleX',function(){ return this._style._tf.scaleX; },function(value){ var style=this.getStyle(); if (style._tf.scaleX!==value){ style.setScaleX(value); this._tfChanged=true; this.conchModel && this.conchModel.scale(value,style._tf.scaleY); this._renderType |=/*laya.renders.RenderSprite.TRANSFORM*/0x04; var p=this._parent; if (p && p._repaint===0){ p._repaint=1; p.parentRepaint(); } } }); /**Y轴缩放值,默认值为1。设置为负数,可以实现垂直反转效果,比如scaleX=-1。*/ __getset(0,__proto,'scaleY',function(){ return this._style._tf.scaleY; },function(value){ var style=this.getStyle(); if (style._tf.scaleY!==value){ style.setScaleY(value); this._tfChanged=true; this.conchModel && this.conchModel.scale(style._tf.scaleX,value); this._renderType |=/*laya.renders.RenderSprite.TRANSFORM*/0x04; var p=this._parent; if (p && p._repaint===0){ p._repaint=1; p.parentRepaint(); } } }); /**对舞台 stage 的引用。*/ __getset(0,__proto,'stage',function(){ return Laya.stage; }); /**水平倾斜角度,默认值为0。以角度为单位。*/ __getset(0,__proto,'skewX',function(){ return this._style._tf.skewX; },function(value){ var style=this.getStyle(); if (style._tf.skewX!==value){ style.setSkewX(value); this._tfChanged=true; this.conchModel && this.conchModel.skew(value,style._tf.skewY); this._renderType |=/*laya.renders.RenderSprite.TRANSFORM*/0x04; var p=this._parent; if (p && p._repaint===0){ p._repaint=1; p.parentRepaint(); } } }); /** *

    显示对象的滚动矩形范围,具有裁剪效果(如果只想限制子对象渲染区域,请使用viewport),设置optimizeScrollRect=true,可以优化裁剪区域外的内容不进行渲染。

    *

    srollRect和viewport的区别:
    *1.srollRect自带裁剪效果,viewport只影响子对象渲染是否渲染,不具有裁剪效果(性能更高)。
    *2.设置rect的x,y属性均能实现区域滚动效果,但scrollRect会保持0,0点位置不变。

    */ __getset(0,__proto,'scrollRect',function(){ return this._style.scrollRect; },function(value){ this.getStyle().scrollRect=value; this.repaint(); if (value){ this._renderType |=/*laya.renders.RenderSprite.CLIP*/0x80; this.conchModel && this.conchModel.scrollRect(value.x,value.y,value.width,value.height); }else { this._renderType &=~ /*laya.renders.RenderSprite.CLIP*/0x80; if (this.conchModel){ if (Sprite.RUNTIMEVERION < "0.9.1") this.conchModel.removeType(0x40); else this.conchModel.removeType(/*laya.renders.RenderSprite.CLIP*/0x80); } } }); /**垂直倾斜角度,默认值为0。以角度为单位。*/ __getset(0,__proto,'skewY',function(){ return this._style._tf.skewY; },function(value){ var style=this.getStyle(); if (style._tf.skewY!==value){ style.setSkewY(value); this._tfChanged=true; this.conchModel && this.conchModel.skew(style._tf.skewX,value); this._renderType |=/*laya.renders.RenderSprite.TRANSFORM*/0x04; var p=this._parent; if (p && p._repaint===0){ p._repaint=1; p.parentRepaint(); } } }); /** *

    对象的矩阵信息。通过设置矩阵可以实现节点旋转,缩放,位移效果。

    *

    矩阵更多信息请参考 Matrix

    */ __getset(0,__proto,'transform',function(){ return this._tfChanged ? this._adjustTransform():this._transform; },function(value){ this._tfChanged=false; this._transform=value; if (value){ this._x=value.tx; this._y=value.ty; value.tx=value.ty=0; this.conchModel && this.conchModel.transform(value.a,value.b,value.c,value.d,this._x,this._y); } if (value)this._renderType |=/*laya.renders.RenderSprite.TRANSFORM*/0x04; else { this._renderType &=~ /*laya.renders.RenderSprite.TRANSFORM*/0x04; this.conchModel && this.conchModel.removeType(/*laya.renders.RenderSprite.TRANSFORM*/0x04); } this.parentRepaint(); }); /**X轴 轴心点的位置,单位为像素,默认为0。轴心点会影响对象位置,缩放中心,旋转中心。*/ __getset(0,__proto,'pivotX',function(){ return this._style._tf.translateX; },function(value){ this.getStyle().setTranslateX(value); this.conchModel && this.conchModel.pivot(value,this._style._tf.translateY); this.repaint(); }); /**Y轴 轴心点的位置,单位为像素,默认为0。轴心点会影响对象位置,缩放中心,旋转中心。*/ __getset(0,__proto,'pivotY',function(){ return this._style._tf.translateY; },function(value){ this.getStyle().setTranslateY(value); this.conchModel && this.conchModel.pivot(this._style._tf.translateX,value); this.repaint(); }); /**透明度,值为0-1,默认值为1,表示不透明。更改alpha值会影响drawcall。*/ __getset(0,__proto,'alpha',function(){ return this._style.alpha; },function(value){ if (this._style && this._style.alpha!==value){ value=value < 0 ? 0 :(value > 1 ? 1 :value); this.getStyle().alpha=value; this.conchModel && this.conchModel.alpha(value); if (value!==1)this._renderType |=/*laya.renders.RenderSprite.ALPHA*/0x02; else this._renderType &=~ /*laya.renders.RenderSprite.ALPHA*/0x02; this.parentRepaint(); } }); /**表示是否可见,默认为true。如果设置不可见,节点将不被渲染。*/ __getset(0,__proto,'visible',function(){ return this._style.visible; },function(value){ if (this._style && this._style.visible!==value){ this.getStyle().visible=value; this.conchModel && this.conchModel.visible(value); this.parentRepaint(); } }); /**绘图对象。封装了绘制位图和矢量图的接口,Sprite所有的绘图操作都通过Graphics来实现的。*/ __getset(0,__proto,'graphics',function(){ return this._graphics || (this.graphics=RunDriver.createGraphics()); },function(value){ if (this._graphics)this._graphics._sp=null; this._graphics=value; if (value){ this._renderType &=~ /*laya.renders.RenderSprite.IMAGE*/0x01; this._renderType |=/*laya.renders.RenderSprite.GRAPHICS*/0x200; value._sp=this; this.conchModel && this.conchModel.graphics(this._graphics); }else { this._renderType &=~ /*laya.renders.RenderSprite.GRAPHICS*/0x200; this._renderType &=~ /*laya.renders.RenderSprite.IMAGE*/0x01; if (this.conchModel){ if (Sprite.RUNTIMEVERION < "0.9.1") this.conchModel.removeType(0x100); else this.conchModel.removeType(/*laya.renders.RenderSprite.GRAPHICS*/0x200); } } this.repaint(); }); /**滤镜集合。可以设置多个滤镜组合。*/ __getset(0,__proto,'filters',function(){ return this._$P.filters; },function(value){ value && value.length===0 && (value=null); if (this._$P.filters==value)return; this._set$P("filters",value ? value.slice():null); if (Render.isConchApp){ if (this.conchModel){ if (Sprite.RUNTIMEVERION < "0.9.1") this.conchModel.removeType(0x10); else this.conchModel.removeType(/*laya.renders.RenderSprite.FILTERS*/0x20); } if (this._$P.filters && this._$P.filters.length==1){ this._$P.filters[0].callNative(this); } } if (Render.isWebGL){ if (value && value.length){ this._renderType |=/*laya.renders.RenderSprite.FILTERS*/0x20; }else { this._renderType &=~ /*laya.renders.RenderSprite.FILTERS*/0x20; } } if (value && value.length > 0){ if (!this._getBit(/*laya.display.Node.NOTICE_DISPLAY*/0x1))this._setUpNoticeType(/*laya.display.Node.NOTICE_DISPLAY*/0x1); if (!(Render.isWebGL && value.length==1 && (((value[0])instanceof laya.filters.ColorFilter )))){ if (this.cacheAs !="bitmap"){ if (!Render.isConchNode)this.cacheAs="bitmap"; this._set$P("cacheForFilters",true); } this._set$P("hasFilter",true); } }else { this._set$P("hasFilter",false); if (this._$P["cacheForFilters"] && this.cacheAs=="bitmap"){ this.cacheAs="none"; } } this.repaint(); }); __getset(0,__proto,'parent',_super.prototype._$get_parent,function(value){ Laya.superSet(Node,this,'parent',value); if (value && this._getBit(/*laya.display.Node.MOUSEENABLE*/0x2)){ this._$2__onDisplay(); } }); /** *

    遮罩,可以设置一个对象(支持位图和矢量图),根据对象形状进行遮罩显示。

    *

    【注意】遮罩对象坐标系是相对遮罩对象本身的,和Flash机制不同

    */ __getset(0,__proto,'mask',function(){ return this._$P._mask; },function(value){ if (value && this.mask && this.mask._$P.maskParent)return; if (value){ this.cacheAs="bitmap"; this._set$P("_mask",value); value._set$P("maskParent",this); }else { this.mask && this.mask._set$P("maskParent",null); this._set$P("_mask",value); this.cacheAs="none"; } this.conchModel && this.conchModel.mask(value ? value.conchModel :null); this._renderType |=/*laya.renders.RenderSprite.MASK*/0x40; this.parentRepaint(); }); /** *是否接受鼠标事件。 *默认为false,如果监听鼠标事件,则会自动设置本对象及父节点的属性 mouseEnable 的值都为 true(如果父节点手动设置为false,则不会更改)。 **/ __getset(0,__proto,'mouseEnabled',function(){ return this._mouseEnableState > 1; },function(value){ this._mouseEnableState=value ? 2 :1; }); /** *获得相对于stage的全局X轴缩放值(会叠加父亲节点的缩放值)。 */ __getset(0,__proto,'globalScaleX',function(){ var scale=1; var ele=this; while (ele){ if (ele===Laya.stage)break ; scale *=ele.scaleX; ele=ele.parent; } return scale; }); /** *返回鼠标在此对象坐标系上的 X 轴坐标信息。 */ __getset(0,__proto,'mouseX',function(){ return this.getMousePoint().x; }); /** *返回鼠标在此对象坐标系上的 Y 轴坐标信息。 */ __getset(0,__proto,'mouseY',function(){ return this.getMousePoint().y; }); Sprite.fromImage=function(url){ return new Sprite().loadImage(url); } Sprite.CustomList=[]; __static(Sprite, ['RUNTIMEVERION',function(){return this.RUNTIMEVERION=/*__JS__ */window.conch?conchConfig.getRuntimeVersion().substr(conchConfig.getRuntimeVersion().lastIndexOf('-')+1):'';} ]); return Sprite; })(Node) /** *@private *audio标签播放声音的音轨控制 */ //class laya.media.h5audio.AudioSoundChannel extends laya.media.SoundChannel var AudioSoundChannel=(function(_super){ function AudioSoundChannel(audio){ /** *播放用的audio标签 */ this._audio=null; this._onEnd=null; this._resumePlay=null; AudioSoundChannel.__super.call(this); this._onEnd=Utils.bind(this.__onEnd,this); this._resumePlay=Utils.bind(this.__resumePlay,this); audio.addEventListener("ended",this._onEnd); this._audio=audio; } __class(AudioSoundChannel,'laya.media.h5audio.AudioSoundChannel',_super); var __proto=AudioSoundChannel.prototype; __proto.__onEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } __proto.__resumePlay=function(){ if (this._audio)this._audio.removeEventListener("canplay",this._resumePlay); if (this.isStopped)return; try { this._audio.currentTime=this.startTime; Browser.container.appendChild(this._audio); this._audio.play(); }catch (e){ this.event(/*laya.events.Event.ERROR*/"error"); } } /** *播放 */ __proto.play=function(){ this.isStopped=false; if (!this._audio)return; try { this._audio.playbackRate=SoundManager.playbackRate; this._audio.currentTime=this.startTime; }catch (e){ this._audio.addEventListener("canplay",this._resumePlay); return; } SoundManager.addChannel(this); Browser.container.appendChild(this._audio); if("play" in this._audio) this._audio.play(); } /** *停止播放 * */ __proto.stop=function(){ this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; if ("pause" in this._audio) if (Render.isConchApp){ this._audio.stop(); } this._audio.pause(); this._audio.removeEventListener("ended",this._onEnd); this._audio.removeEventListener("canplay",this._resumePlay); if (!Browser.onIE){ if (this._audio!=AudioSound._musicAudio){ Pool.recover("audio:"+this.url,this._audio); } } Browser.removeElement(this._audio); this._audio=null; } __proto.pause=function(){ this.isStopped=true; SoundManager.removeChannel(this); if("pause" in this._audio) this._audio.pause(); } __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); if("play" in this._audio) this._audio.play(); } /** *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /** *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /** *设置音量 *@param v * */ /** *获取音量 *@return * */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); return AudioSoundChannel; })(SoundChannel) /** *@private *web audio api方式播放声音的音轨控制 */ //class laya.media.webaudio.WebAudioSoundChannel extends laya.media.SoundChannel var WebAudioSoundChannel=(function(_super){ function WebAudioSoundChannel(){ /** *声音原始文件数据 */ this.audioBuffer=null; /** *gain节点 */ this.gain=null; /** *播放用的数据 */ this.bufferSource=null; /** *当前时间 */ this._currentTime=0; /** *当前音量 */ this._volume=1; /** *播放开始时的时间戳 */ this._startTime=0; this._pauseTime=0; this._onPlayEnd=null; this.context=WebAudioSound.ctx; WebAudioSoundChannel.__super.call(this); this._onPlayEnd=Utils.bind(this.__onPlayEnd,this); if (this.context["createGain"]){ this.gain=this.context["createGain"](); }else { this.gain=this.context["createGainNode"](); } } __class(WebAudioSoundChannel,'laya.media.webaudio.WebAudioSoundChannel',_super); var __proto=WebAudioSoundChannel.prototype; /** *播放声音 */ __proto.play=function(){ SoundManager.addChannel(this); this.isStopped=false; this._clearBufferSource(); if (!this.audioBuffer)return; if (this.startTime >=this.duration)return this.stop(); var context=this.context; var gain=this.gain; var bufferSource=context.createBufferSource(); this.bufferSource=bufferSource; bufferSource.buffer=this.audioBuffer; bufferSource.connect(gain); if (gain) gain.disconnect(); gain.connect(context.destination); bufferSource.onended=this._onPlayEnd; this._startTime=Browser.now(); if (this.gain.gain.setTargetAtTime){ this.gain.gain.setTargetAtTime(this._volume,this.context.currentTime,0.001); }else this.gain.gain.value=this._volume; if (this.loops==0){ bufferSource.loop=true; } if (bufferSource.playbackRate.setTargetAtTime){ bufferSource.playbackRate.setTargetAtTime(SoundManager.playbackRate,this.context.currentTime,0.001) }else bufferSource.playbackRate.value=SoundManager.playbackRate; bufferSource.start(0,this.startTime); this._currentTime=0; } __proto.__onPlayEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } __proto._clearBufferSource=function(){ if (this.bufferSource){ var sourceNode=this.bufferSource; if (sourceNode.stop){ sourceNode.stop(0); }else { sourceNode.noteOff(0); } sourceNode.disconnect(0); sourceNode.onended=null; if (!WebAudioSoundChannel._tryCleanFailed)this._tryClearBuffer(sourceNode); this.bufferSource=null; } } __proto._tryClearBuffer=function(sourceNode){ if (!Browser.onMac){ try{ sourceNode.buffer=null; }catch (e){ WebAudioSoundChannel._tryCleanFailed=true; } return; } try {sourceNode.buffer=WebAudioSound._miniBuffer;}catch (e){WebAudioSoundChannel._tryCleanFailed=true;} } /** *停止播放 */ __proto.stop=function(){ _super.prototype.stop.call(this); this._clearBufferSource(); this.audioBuffer=null; if (this.gain) this.gain.disconnect(); this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if(SoundManager.autoReleaseSound) Laya.timer.once(5000,null,SoundManager.disposeSoundIfNotUsed,[this.url],false); } __proto.pause=function(){ if (!this.isStopped){ this._pauseTime=this.position; } this._clearBufferSource(); if (this.gain) this.gain.disconnect(); this.isStopped=true; SoundManager.removeChannel(this); if(SoundManager.autoReleaseSound) Laya.timer.once(5000,null,SoundManager.disposeSoundIfNotUsed,[this.url],false); } __proto.resume=function(){ this.startTime=this._pauseTime; this.play(); } /** *获取当前播放位置 */ __getset(0,__proto,'position',function(){ if (this.bufferSource){ return (Browser.now()-this._startTime)/ 1000+this.startTime; } return 0; }); __getset(0,__proto,'duration',function(){ if (this.audioBuffer){ return this.audioBuffer.duration; } return 0; }); /** *设置音量 */ /** *获取音量 */ __getset(0,__proto,'volume',function(){ return this._volume; },function(v){ if (this.isStopped){ return; } this._volume=v; if (this.gain.gain.setTargetAtTime){ this.gain.gain.setTargetAtTime(v,this.context.currentTime,0.001); }else this.gain.gain.value=v; }); WebAudioSoundChannel._tryCleanFailed=false; WebAudioSoundChannel.SetTargetDelay=0.001; return WebAudioSoundChannel; })(SoundChannel) /** *@private *Bitmap 是图片资源类。 */ //class laya.resource.Bitmap extends laya.resource.Resource var Bitmap=(function(_super){ function Bitmap(){ /**@private *HTML Image或HTML Canvas或WebGL Texture。 **/ //this._source=null; /**@private 宽度*/ //this._w=NaN; /**@private 高度*/ //this._h=NaN; Bitmap.__super.call(this); this._w=0; this._h=0; } __class(Bitmap,'laya.resource.Bitmap',_super); var __proto=Bitmap.prototype; /*** *宽度。 */ __getset(0,__proto,'width',function(){ return this._w; }); /*** *高度。 */ __getset(0,__proto,'height',function(){ return this._h; }); /*** *HTML Image 或 HTML Canvas 或 WebGL Texture 。 */ __getset(0,__proto,'source',function(){ return this._source; }); return Bitmap; })(Resource) /** *

    动画播放基类,提供了基础的动画播放控制方法和帧标签事件相关功能。

    *

    可以继承此类,但不要直接实例化此类,因为有些方法需要由子类实现。

    */ //class laya.display.AnimationPlayerBase extends laya.display.Sprite var AnimationPlayerBase=(function(_super){ function AnimationPlayerBase(){ /** *是否循环播放,调用play(...)方法时,会将此值设置为指定的参数值。 */ this.loop=false; /** *

    播放顺序类型:AnimationPlayerBase.WRAP_POSITIVE为正序播放,AnimationPlayerBase.WRAP_REVERSE为倒序播放,AnimationPlayerBase.WRAP_PINGPONG为pingpong播放(当按指定顺序播放完结尾后,如果继续播发,则会改变播放顺序)。

    *

    默认为正序播放。

    */ this.wrapMode=0; /**@private */ this._index=0; /**@private */ this._count=0; /**@private */ this._isPlaying=false; /**@private */ this._labels=null; /**是否是逆序播放*/ this._isReverse=false; /**@private */ this._frameRateChanged=false; /**@private */ this._controlNode=null; /**@private */ this._actionName=null; AnimationPlayerBase.__super.call(this); this._interval=Config.animationInterval; this._setUpNoticeType(/*laya.display.Node.NOTICE_DISPLAY*/0x1); } __class(AnimationPlayerBase,'laya.display.AnimationPlayerBase',_super); var __proto=AnimationPlayerBase.prototype; /** *

    开始播放动画。play(...)方法被设计为在创建实例后的任何时候都可以被调用,当相应的资源加载完毕、调用动画帧填充方法(set frames)或者将实例显示在舞台上时,会判断是否正在播放中,如果是,则进行播放。

    *

    配合wrapMode属性,可设置动画播放顺序类型。

    *@param start (可选)指定动画播放开始的索引(int)或帧标签(String)。帧标签可以通过addLabel(...)和removeLabel(...)进行添加和删除。 *@param loop (可选)是否循环播放。 *@param name (可选)动画名称。 *@param showWarn(可选)是否动画不存在时打印警告 */ __proto.play=function(start,loop,name,showWarn){ (start===void 0)&& (start=0); (loop===void 0)&& (loop=true); (name===void 0)&& (name=""); (showWarn===void 0)&& (showWarn=true); this._isPlaying=true; this.index=((typeof start=='string'))? this._getFrameByLabel(start):start; this.loop=loop; this._actionName=name; this._isReverse=this.wrapMode==1; if (this.interval > 0){ this.timerLoop(this.interval,this,this._frameLoop,null,true,true); } } /**@private */ __proto._getFrameByLabel=function(label){ var i=0; for (i=0;i < this._count;i++){ if (this._labels[i] && (this._labels [i]).indexOf(label)>=0)return i; } return 0; } /**@private */ __proto._frameLoop=function(){ if (this._isReverse){ this._index--; if (this._index < 0){ if (this.loop){ if (this.wrapMode==2){ this._index=this._count > 0 ? 1 :0; this._isReverse=false; }else { this._index=this._count-1; } this.event(/*laya.events.Event.COMPLETE*/"complete"); }else { this._index=0; this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } } }else { this._index++; if (this._index >=this._count){ if (this.loop){ if (this.wrapMode==2){ this._index=this._count-2 >=0 ? this._count-2 :0; this._isReverse=true; }else { this._index=0; } this.event(/*laya.events.Event.COMPLETE*/"complete"); }else { this._index--; this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } } } this.index=this._index; } /**@private */ __proto._setControlNode=function(node){ if (this._controlNode){ this._controlNode.off(/*laya.events.Event.DISPLAY*/"display",this,this._checkResumePlaying); this._controlNode.off(/*laya.events.Event.UNDISPLAY*/"undisplay",this,this._checkResumePlaying); } this._controlNode=node; if (node && node !=this){ node.on(/*laya.events.Event.DISPLAY*/"display",this,this._checkResumePlaying); node.on(/*laya.events.Event.UNDISPLAY*/"undisplay",this,this._checkResumePlaying); } } /**@private */ __proto._setDisplay=function(value){ _super.prototype._setDisplay.call(this,value); this._checkResumePlaying(); } /**@private */ __proto._checkResumePlaying=function(){ if (this._isPlaying){ if (this._controlNode.displayedInStage)this.play(this._index,this.loop,this._actionName); else this.clearTimer(this,this._frameLoop); } } /** *停止动画播放。 */ __proto.stop=function(){ this._isPlaying=false; this.clearTimer(this,this._frameLoop); } /** *增加一个帧标签到指定索引的帧上。当动画播放到此索引的帧时会派发Event.LABEL事件,派发事件是在完成当前帧画面更新之后。 *@param label 帧标签名称 *@param index 帧索引 */ __proto.addLabel=function(label,index){ if (!this._labels)this._labels={}; if (!this._labels[index])this._labels[index]=[]; this._labels[index].push(label); } /** *删除指定的帧标签。 *@param label 帧标签名称。注意:如果为空,则删除所有帧标签! */ __proto.removeLabel=function(label){ if (!label)this._labels=null; else if (this._labels){ for (var name in this._labels){ this._removeLabelFromLabelList(this._labels[name],label); } } } /**@private */ __proto._removeLabelFromLabelList=function(list,label){ if (!list)return; for (var i=list.length-1;i >=0;i--){ if (list[i]==label){ list.splice(i,1); } } } /** *将动画切换到指定帧并停在那里。 *@param position 帧索引或帧标签 */ __proto.gotoAndStop=function(position){ this.index=((typeof position=='string'))? this._getFrameByLabel(position):position; this.stop(); } /** *@private *显示到某帧 *@param value 帧索引 */ __proto._displayToIndex=function(value){} /** *停止动画播放,并清理对象属性。之后可存入对象池,方便对象复用。 */ __proto.clear=function(){ this.stop(); this._labels=null; } /** *

    动画播放的帧间隔时间(单位:毫秒)。默认值依赖于Config.animationInterval=50,通过Config.animationInterval可以修改默认帧间隔时间。

    *

    要想为某动画设置独立的帧间隔时间,可以使用set interval,注意:如果动画正在播放,设置后会重置帧循环定时器的起始时间为当前时间,也就是说,如果频繁设置interval,会导致动画帧更新的时间间隔会比预想的要慢,甚至不更新。

    */ __getset(0,__proto,'interval',function(){ return this._interval; },function(value){ if (this._interval !=value){ this._frameRateChanged=true; this._interval=value; if (this._isPlaying && value > 0){ this.timerLoop(value,this,this._frameLoop,null,true,true); } } }); /** *是否正在播放中。 */ __getset(0,__proto,'isPlaying',function(){ return this._isPlaying; }); /** *动画当前帧的索引。 */ __getset(0,__proto,'index',function(){ return this._index; },function(value){ this._index=value; this._displayToIndex(value); if (this._labels && this._labels[value]){ var tArr=this._labels[value]; for (var i=0,len=tArr.length;i < len;i++){ this.event(/*laya.events.Event.LABEL*/"label",tArr[i]); } } }); /** *当前动画中帧的总数。 */ __getset(0,__proto,'count',function(){ return this._count; }); AnimationPlayerBase.WRAP_POSITIVE=0; AnimationPlayerBase.WRAP_REVERSE=1; AnimationPlayerBase.WRAP_PINGPONG=2; return AnimationPlayerBase; })(Sprite) /** *

    Text 类用于创建显示对象以显示文本。

    *

    *注意:如果运行时系统找不到设定的字体,则用系统默认的字体渲染文字,从而导致显示异常。(通常电脑上显示正常,在一些移动端因缺少设置的字体而显示异常)。 *

    *@example *package *{ *import laya.display.Text; *public class Text_Example *{ *public function Text_Example() *{ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *onInit(); *} *private function onInit():void *{ *var text:Text=new Text();//创建一个 Text 类的实例对象 text 。 *text.text="这个是一个 Text 文本示例。"; *text.color="#008fff";//设置 text 的文本颜色。 *text.font="Arial";//设置 text 的文本字体。 *text.bold=true;//设置 text 的文本显示为粗体。 *text.fontSize=30;//设置 text 的字体大小。 *text.wordWrap=true;//设置 text 的文本自动换行。 *text.x=100;//设置 text 对象的属性 x 的值,用于控制 text 对象的显示位置。 *text.y=100;//设置 text 对象的属性 y 的值,用于控制 text 对象的显示位置。 *text.width=300;//设置 text 的宽度。 *text.height=200;//设置 text 的高度。 *text.italic=true;//设置 text 的文本显示为斜体。 *text.borderColor="#fff000";//设置 text 的文本边框颜色。 *Laya.stage.addChild(text);//将 text 添加到显示列表。 *} *} *} *@example *Text_Example(); *function Text_Example() *{ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *onInit(); *} *function onInit() *{ *var text=new laya.display.Text();//创建一个 Text 类的实例对象 text 。 *text.text="这个是一个 Text 文本示例。"; *text.color="#008fff";//设置 text 的文本颜色。 *text.font="Arial";//设置 text 的文本字体。 *text.bold=true;//设置 text 的文本显示为粗体。 *text.fontSize=30;//设置 text 的字体大小。 *text.wordWrap=true;//设置 text 的文本自动换行。 *text.x=100;//设置 text 对象的属性 x 的值,用于控制 text 对象的显示位置。 *text.y=100;//设置 text 对象的属性 y 的值,用于控制 text 对象的显示位置。 *text.width=300;//设置 text 的宽度。 *text.height=200;//设置 text 的高度。 *text.italic=true;//设置 text 的文本显示为斜体。 *text.borderColor="#fff000";//设置 text 的文本边框颜色。 *Laya.stage.addChild(text);//将 text 添加到显示列表。 *} *@example *class Text_Example { *constructor(){ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *this.onInit(); *} *private onInit():void { *var text:laya.display.Text=new laya.display.Text();//创建一个 Text 类的实例对象 text 。 *text.text="这个是一个 Text 文本示例。"; *text.color="#008fff";//设置 text 的文本颜色。 *text.font="Arial";//设置 text 的文本字体。 *text.bold=true;//设置 text 的文本显示为粗体。 *text.fontSize=30;//设置 text 的字体大小。 *text.wordWrap=true;//设置 text 的文本自动换行。 *text.x=100;//设置 text 对象的属性 x 的值,用于控制 text 对象的显示位置。 *text.y=100;//设置 text 对象的属性 y 的值,用于控制 text 对象的显示位置。 *text.width=300;//设置 text 的宽度。 *text.height=200;//设置 text 的高度。 *text.italic=true;//设置 text 的文本显示为斜体。 *text.borderColor="#fff000";//设置 text 的文本边框颜色。 *Laya.stage.addChild(text);//将 text 添加到显示列表。 *} *} */ //class laya.display.Text extends laya.display.Sprite var Text=(function(_super){ function Text(){ /**@private */ this._clipPoint=null; /**当前使用的位置字体。*/ this._currBitmapFont=null; /**@private 表示文本内容字符串。*/ this._text=null; /**@private 表示文本内容是否发生改变。*/ this._isChanged=false; /**@private 表示文本的宽度,以像素为单位。*/ this._textWidth=0; /**@private 表示文本的高度,以像素为单位。*/ this._textHeight=0; /**@private 存储文字行数信息。*/ this._lines=[]; /**@private 保存每行宽度*/ this._lineWidths=[]; /**@private 文本的内容位置 X 轴信息。*/ this._startX=NaN; /**@private 文本的内容位置X轴信息。 */ this._startY=NaN; /**@private 当前可视行索引。*/ this._lastVisibleLineIndex=-1; /**@private 当前可视行索引。*/ this._words=null; /**@private */ this._charSize={}; /** *是否显示下划线。 */ this.underline=false; /** *下划线的颜色,为null则使用字体颜色。 */ this._underlineColor=null; Text.__super.call(this); this.overflow=Text.VISIBLE; this._style=new CSSStyle(this); (this._style).wordWrap=false; } __class(Text,'laya.display.Text',_super); var __proto=Text.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._lines=null; if (this._words){ this._words.length=0; this._words=null; } } /** *@private *@inheritDoc */ __proto._getBoundPointsM=function(ifRotate){ (ifRotate===void 0)&& (ifRotate=false); var rec=Rectangle.TEMP; rec.setTo(0,0,this.width,this.height); return rec._getBoundPoints(); } /** *@inheritDoc */ __proto.getGraphicBounds=function(realSize){ (realSize===void 0)&& (realSize=false); var rec=Rectangle.TEMP; rec.setTo(0,0,this.width,this.height); return rec; } /** *@private *@inheritDoc */ __proto._getCSSStyle=function(){ return this._style; } /** *

    根据指定的文本,从语言包中取当前语言的文本内容。并对此文本中的{i}文本进行替换。

    *

    设置Text.langPacks语言包后,即可使用lang获取里面的语言

    *

    例如: *

  • (1)text 的值为“我的名字”,先取到这个文本对应的当前语言版本里的值“My name”,将“My name”设置为当前文本的内容。
  • *
  • (2)text 的值为“恭喜你赢得{0}个钻石,{1}经验。”,arg1 的值为100,arg2 的值为200。 *则先取到这个文本对应的当前语言版本里的值“Congratulations on your winning {0}diamonds,{1}experience.”, *然后将文本里的{0}、{1},依据括号里的数字从0开始替换为 arg1、arg2 的值。 *将替换处理后的文本“Congratulations on your winning 100 diamonds,200 experience.”设置为当前文本的内容。 *
  • *

    *@param text 文本内容。 *@param ...args 文本替换参数。 */ __proto.lang=function(text,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10){ text=Text.langPacks && Text.langPacks[text] ? Text.langPacks[text] :text; if (arguments.length < 2){ this._text=text; }else { for (var i=0,n=arguments.length;i < n;i++){ text=text.replace("{"+i+"}",arguments[i+1]); } this._text=text; } } /** *@private */ __proto._isPassWordMode=function(){ var style=this._style; var password=style.password; if (("prompt" in this)&& this['prompt']==this._text) password=false; return password; } /** *@private */ __proto._getPassWordTxt=function(txt){ var len=txt.length; var word; word=""; for (var j=len;j > 0;j--){ word+="●"; } return word; } /** *渲染文字。 *@param begin 开始渲染的行索引。 *@param visibleLineCount 渲染的行数。 */ __proto.renderText=function(begin,visibleLineCount){ var graphics=this.graphics; graphics.clear(true); var ctxFont=(this.italic ? "italic " :"")+(this.bold ? "bold " :"")+this.fontSize+"px "+(Browser.onIPhone ? (laya.display.Text._fontFamilyMap[this.font] || this.font):this.font); Browser.context.font=ctxFont; if (Render.isConchNode){ Browser.context.direction=this.direction; graphics.setDirection && graphics.setDirection(this.direction); }; var padding=this.padding; var startX=padding[3]; var textAlgin="left"; var lines=this._lines; var lineHeight=this.leading+this._charSize.height; var tCurrBitmapFont=this._currBitmapFont; if (tCurrBitmapFont){ lineHeight=this.leading+tCurrBitmapFont.getMaxHeight(); }; var startY=padding[0]; if ((!tCurrBitmapFont)&& this._width > 0 && this._textWidth <=this._width){ if (this.align=="right"){ textAlgin="right"; startX=this._width-padding[1]; }else if (this.align=="center"){ textAlgin="center"; startX=this._width *0.5+padding[3]-padding[1]; } } if (this._height > 0){ var tempVAlign=(this._textHeight > this._height)? "top" :this.valign; if (tempVAlign==="middle") startY=(this._height-visibleLineCount *lineHeight)*0.5+padding[0]-padding[2]; else if (tempVAlign==="bottom") startY=this._height-visibleLineCount *lineHeight-padding[2]; }; var style=this._style; if (tCurrBitmapFont && tCurrBitmapFont.autoScaleSize){ var bitmapScale=tCurrBitmapFont.fontSize / this.fontSize; } if (this._clipPoint){ graphics.save(); if (tCurrBitmapFont && tCurrBitmapFont.autoScaleSize){ var tClipWidth=0; var tClipHeight=0; this._width ? tClipWidth=(this._width-padding[3]-padding[1]):tClipWidth=this._textWidth; this._height ? tClipHeight=(this._height-padding[0]-padding[2]):tClipHeight=this._textHeight; tClipWidth *=bitmapScale; tClipHeight *=bitmapScale; graphics.clipRect(padding[3],padding[0],tClipWidth,tClipHeight); }else { graphics.clipRect(padding[3],padding[0],this._width ? (this._width-padding[3]-padding[1]):this._textWidth,this._height ? (this._height-padding[0]-padding[2]):this._textHeight); } }; var password=style.password; if (("prompt" in this)&& this['prompt']==this._text) password=false; var x=0,y=0; var end=Math.min(this._lines.length,visibleLineCount+begin)|| 1; for (var i=begin;i < end;i++){ var word=lines[i]; var _word; if (password){ var len=word.length; word=""; for (var j=len;j > 0;j--){ word+="●"; } } if (word===undefined)word=""; x=startX-(this._clipPoint ? this._clipPoint.x :0); y=startY+lineHeight *i-(this._clipPoint ? this._clipPoint.y :0); this.underline && this.drawUnderline(textAlgin,x,y,i); if (tCurrBitmapFont){ var tWidth=this.width; if (tCurrBitmapFont.autoScaleSize){ tWidth=this.width *bitmapScale; } tCurrBitmapFont.drawText(word,this,x,y,this.align,tWidth); }else { if (Render.isWebGL){ this._words || (this._words=[]); _word=this._words.length > (i-begin)? this._words[i-begin] :new WordText(); _word.setText(word); }else { _word=word; } style.stroke ? graphics.fillBorderText(_word,x,y,ctxFont,this.color,style.strokeColor,style.stroke,textAlgin):graphics.fillText(_word,x,y,ctxFont,this.color,textAlgin); } } if (tCurrBitmapFont && tCurrBitmapFont.autoScaleSize){ var tScale=1 / bitmapScale; this.scale(tScale,tScale); } if (this._clipPoint) graphics.restore(); this._startX=startX; this._startY=startY; } /** *绘制下划线 *@param x 本行坐标 *@param y 本行坐标 *@param lineIndex 本行索引 */ __proto.drawUnderline=function(align,x,y,lineIndex){ var lineWidth=this._lineWidths[lineIndex]; switch (align){ case 'center': x-=lineWidth / 2; break ; case 'right': x-=lineWidth; break ; case 'left': default : break ; } y+=this._charSize.height; this._graphics.drawLine(x,y,x+lineWidth,y,this.underlineColor || this.color,1); } /** *

    排版文本。

    *

    进行宽高计算,渲染、重绘文本。

    */ __proto.typeset=function(){ this._isChanged=false; if (!this._text){ this._clipPoint=null; this._textWidth=this._textHeight=0; this.graphics.clear(true); return; } if (Render.isConchApp){ var ctxFont=""+this._getCSSStyle().font; var style=this._getCSSStyle(); if (style.stroke){ if (this._getCSSStyle().strokeColor){ ctxFont+=" "+1+" "+this._getCSSStyle().strokeColor; } } Browser.context.font=ctxFont; if (Render.isConchNode){ Browser.context.direction=this.direction; this.graphics.setDirection && this.graphics.setDirection(this.direction); } } else { Browser.context.font=this._getCSSStyle().font; } this._lines.length=0; this._lineWidths.length=0; if (this._isPassWordMode()){ this.parseLines(this._getPassWordTxt(this._text)); }else this.parseLines(this._text); this.evalTextSize(); if (this.checkEnabledViewportOrNot()) this._clipPoint || (this._clipPoint=new Point(0,0)); else this._clipPoint=null; var lineCount=this._lines.length; if (this.overflow !=Text.VISIBLE){ var func=this.overflow==Text.HIDDEN ? Math.floor :Math.ceil; lineCount=Math.min(lineCount,func((this.height-this.padding[0]-this.padding[2])/ (this.leading+this._charSize.height))); }; var startLine=this.scrollY / (this._charSize.height+this.leading)| 0; this.renderText(startLine,lineCount); this.repaint(); } __proto.evalTextSize=function(){ var nw=NaN,nh=NaN; nw=Math.max.apply(this,this._lineWidths); if (this._currBitmapFont) nh=this._lines.length *(this._currBitmapFont.getMaxHeight()+this.leading)+this.padding[0]+this.padding[2]; else nh=this._lines.length *(this._charSize.height+this.leading)+this.padding[0]+this.padding[2]; if (nw !=this._textWidth || nh !=this._textHeight){ this._textWidth=nw; this._textHeight=nh; if (!this._width || !this._height) this.conchModel && this.conchModel.size(this._width || this._textWidth,this._height || this._textHeight); } } __proto.checkEnabledViewportOrNot=function(){ return this.overflow==Text.SCROLL && ((this._width > 0 && this._textWidth > this._width)|| (this._height > 0 && this._textHeight > this._height)); } /** *

    快速更改显示文本。不进行排版计算,效率较高。

    *

    如果只更改文字内容,不更改文字样式,建议使用此接口,能提高效率。

    *@param text 文本内容。 */ __proto.changeText=function(text){ if (this._text!==text){ this.lang(text+""); if (this._graphics && this._graphics.replaceText(this._text)){ }else { this.typeset(); } } } /** *@private *分析文本换行。 */ __proto.parseLines=function(text){ var needWordWrapOrTruncate=this.wordWrap || this.overflow==Text.HIDDEN; if (needWordWrapOrTruncate){ var wordWrapWidth=this.getWordWrapWidth(); } if (this._currBitmapFont){ this._charSize.width=this._currBitmapFont.getMaxWidth(); this._charSize.height=this._currBitmapFont.getMaxHeight(); }else { var measureResult=Browser.context.measureText(Text._testWord); if (Render.isConchApp && measureResult.width===0 && measureResult.height===0){ measureResult=Browser.context.measureText('W'); } this._charSize.width=measureResult.width; this._charSize.height=(measureResult.height || this.fontSize); }; var lines=text.replace(/\r\n/g,"\n").split("\n"); for (var i=0,n=lines.length;i < n;i++){ var line=lines[i]; if (needWordWrapOrTruncate) this.parseLine(line,wordWrapWidth); else { this._lineWidths.push(this.getTextWidth(line)); this._lines.push(line); } } } /** *@private *解析行文本。 *@param line 某行的文本。 *@param wordWrapWidth 文本的显示宽度。 */ __proto.parseLine=function(line,wordWrapWidth){ var ctx=Browser.context; var lines=this._lines; var maybeIndex=0; var execResult; var charsWidth=NaN; var wordWidth=NaN; var startIndex=0; charsWidth=this.getTextWidth(line); if (charsWidth <=wordWrapWidth){ lines.push(line); this._lineWidths.push(charsWidth); return; } charsWidth=this._charSize.width; maybeIndex=Math.floor(wordWrapWidth / charsWidth); (maybeIndex==0)&& (maybeIndex=1); charsWidth=this.getTextWidth(line.substring(0,maybeIndex)); wordWidth=charsWidth; for (var j=maybeIndex,m=line.length;j < m;j++){ charsWidth=this.getTextWidth(line.charAt(j)); wordWidth+=charsWidth; if (wordWidth > wordWrapWidth){ if (this.wordWrap){ var newLine=line.substring(startIndex,j); if (newLine.charCodeAt(newLine.length-1)< 255){ execResult=/(?:\w|-)+$/.exec(newLine); if (execResult){ j=execResult.index+startIndex; if (execResult.index==0) j+=newLine.length; else newLine=line.substring(startIndex,j); } }else if (Text.RightToLeft){ execResult=/([\u0600-\u06FF])+$/.exec(newLine); if(execResult){ j=execResult.index+startIndex; if (execResult.index==0) j+=newLine.length; else newLine=line.substring(startIndex,j); } } lines.push(newLine); this._lineWidths.push(wordWidth-charsWidth); startIndex=j; if (j+maybeIndex < m){ j+=maybeIndex; charsWidth=this.getTextWidth(line.substring(startIndex,j)); wordWidth=charsWidth; j--; }else { lines.push(line.substring(startIndex,m)); this._lineWidths.push(this.getTextWidth(lines[lines.length-1])); startIndex=-1; break ; } }else if (this.overflow==Text.HIDDEN){ lines.push(line.substring(0,j)); this._lineWidths.push(this.getTextWidth(lines[lines.length-1])); return; } } } if (this.wordWrap && startIndex !=-1){ lines.push(line.substring(startIndex,m)); this._lineWidths.push(this.getTextWidth(lines[lines.length-1])); } } __proto.getTextWidth=function(text){ if (this._currBitmapFont) return this._currBitmapFont.getTextWidth(text); else return Browser.context.measureText(text).width; } /** *获取换行所需的宽度。 */ __proto.getWordWrapWidth=function(){ var p=this.padding; var w=NaN; if (this._currBitmapFont && this._currBitmapFont.autoScaleSize) w=this._width *(this._currBitmapFont.fontSize / this.fontSize); else w=this._width; if (w <=0){ w=this.wordWrap ? 100 :Browser.width; } w <=0 && (w=100); return w-p[3]-p[1]; } /** *返回字符在本类实例的父坐标系下的坐标。 *@param charIndex 索引位置。 *@param out (可选)输出的Point引用。 *@return Point 字符在本类实例的父坐标系下的坐标。如果out参数不为空,则将结果赋值给指定的Point对象,否则创建一个新的Point对象返回。建议使用Point.TEMP作为out参数,可以省去Point对象创建和垃圾回收的开销,尤其是在需要频繁执行的逻辑中,比如帧循环和MOUSE_MOVE事件回调函数里面。 */ __proto.getCharPoint=function(charIndex,out){ this._isChanged && Laya.timer.runCallLater(this,this.typeset); var len=0,lines=this._lines,startIndex=0; for (var i=0,n=lines.length;i < n;i++){ len+=lines[i].length; if (charIndex < len){ var line=i; break ; } startIndex=len; }; var ctxFont=(this.italic ? "italic " :"")+(this.bold ? "bold " :"")+this.fontSize+"px "+this.font; Browser.context.font=ctxFont; if (Render.isConchNode){ Browser.context.direction=this.direction; this.graphics.setDirection && this.graphics.setDirection(this.direction); }; var width=this.getTextWidth(this._text.substring(startIndex,charIndex)); var point=out || new Point(); return point.setTo(this._startX+width-(this._clipPoint ? this._clipPoint.x :0),this._startY+line *(this._charSize.height+this.leading)-(this._clipPoint ? this._clipPoint.y :0)); } /** *@inheritDoc */ __getset(0,__proto,'width',function(){ if (this._width) return this._width; return this.textWidth+this.padding[1]+this.padding[3]; },function(value){ if (value !=this._width){ Laya.superSet(Sprite,this,'width',value); this.isChanged=true; } }); /** *表示文本的宽度,以像素为单位。 */ __getset(0,__proto,'textWidth',function(){ this._isChanged && Laya.timer.runCallLater(this,this.typeset); return this._textWidth; }); /** *@inheritDoc */ __getset(0,__proto,'height',function(){ if (this._height)return this._height; return this.textHeight; },function(value){ if (value !=this._height){ Laya.superSet(Sprite,this,'height',value); this.isChanged=true; } }); /** *表示文本的高度,以像素为单位。 */ __getset(0,__proto,'textHeight',function(){ this._isChanged && Laya.timer.runCallLater(this,this.typeset); return this._textHeight; }); /** *

    边距信息。

    *

    数据格式:[上边距,右边距,下边距,左边距](边距以像素为单位)。

    */ __getset(0,__proto,'padding',function(){ return this._getCSSStyle().padding; },function(value){ this._getCSSStyle().padding=value; this.isChanged=true; }); /** *

    指定文本是否为粗体字。

    *

    默认值为 false,这意味着不使用粗体字。如果值为 true,则文本为粗体字。

    */ __getset(0,__proto,'bold',function(){ return this._getCSSStyle().bold; },function(value){ this._getCSSStyle().bold=value; this.isChanged=true; }); /**当前文本的内容字符串。*/ __getset(0,__proto,'text',function(){ return this._text || ""; },function(value){ if (this._text!==value){ this.lang(value+""); this.isChanged=true; this.event(/*laya.events.Event.CHANGE*/"change"); } }); /** *

    表示文本的颜色值。可以通过 Text.defaultColor 设置默认颜色。

    *

    默认值为黑色。

    */ __getset(0,__proto,'color',function(){ return this._getCSSStyle().color; },function(value){ if (this._getCSSStyle().color !=value){ this._getCSSStyle().color=value; if (!this._isChanged && this._graphics){ this._graphics.replaceTextColor(this.color) }else { this.isChanged=true; } } }); /** *

    文本的字体名称,以字符串形式表示。

    *

    默认值为:"Arial",可以通过Font.defaultFont设置默认字体。

    *

    如果运行时系统找不到设定的字体,则用系统默认的字体渲染文字,从而导致显示异常。(通常电脑上显示正常,在一些移动端因缺少设置的字体而显示异常)。

    *@see laya.display.css.Font#defaultFamily */ __getset(0,__proto,'font',function(){ return this._getCSSStyle().fontFamily; },function(value){ if (this._currBitmapFont){ this._currBitmapFont=null; this.scale(1,1); } if (Text._bitmapFonts && Text._bitmapFonts[value]){ this._currBitmapFont=Text._bitmapFonts[value]; } this._getCSSStyle().fontFamily=value; this.isChanged=true; }); /** *

    指定文本的字体大小(以像素为单位)。

    *

    默认为20像素,可以通过 Text.defaultSize 设置默认大小。

    */ __getset(0,__proto,'fontSize',function(){ return this._getCSSStyle().fontSize; },function(value){ this._getCSSStyle().fontSize=value; this.isChanged=true; }); /** *

    表示使用此文本格式的文本是否为斜体。

    *

    默认值为 false,这意味着不使用斜体。如果值为 true,则文本为斜体。

    */ __getset(0,__proto,'italic',function(){ return this._getCSSStyle().italic; },function(value){ this._getCSSStyle().italic=value; this.isChanged=true; }); /** *

    表示文本的水平显示方式。

    *

    取值: *

  • "left": 居左对齐显示。
  • *
  • "center": 居中对齐显示。
  • *
  • "right": 居右对齐显示。
  • *

    */ __getset(0,__proto,'align',function(){ return this._getCSSStyle().align; },function(value){ this._getCSSStyle().align=value; this.isChanged=true; }); /** *

    表示文本的垂直显示方式。

    *

    取值: *

  • "top": 居顶部对齐显示。
  • *
  • "middle": 居中对齐显示。
  • *
  • "bottom": 居底部对齐显示。
  • *

    */ __getset(0,__proto,'valign',function(){ return this._getCSSStyle().valign; },function(value){ this._getCSSStyle().valign=value; this.isChanged=true; }); /** *

    表示文本是否自动换行,默认为false。

    *

    若值为true,则自动换行;否则不自动换行。

    */ __getset(0,__proto,'wordWrap',function(){ return this._getCSSStyle().wordWrap; },function(value){ this._getCSSStyle().wordWrap=value; this.isChanged=true; }); /** *垂直行间距(以像素为单位)。 */ __getset(0,__proto,'leading',function(){ return this._getCSSStyle().leading; },function(value){ this._getCSSStyle().leading=value; this.isChanged=true; }); /** *文本背景颜色,以字符串表示。 */ __getset(0,__proto,'bgColor',function(){ return this._getCSSStyle().backgroundColor; },function(value){ this._getCSSStyle().backgroundColor=value; this.isChanged=true; }); /** *文本边框背景颜色,以字符串表示。 */ __getset(0,__proto,'borderColor',function(){ return this._getCSSStyle().borderColor; },function(value){ this._getCSSStyle().borderColor=value; this.isChanged=true; }); /** *

    描边宽度(以像素为单位)。

    *

    默认值0,表示不描边。

    */ __getset(0,__proto,'stroke',function(){ return this._getCSSStyle().stroke; },function(value){ this._getCSSStyle().stroke=value; this.isChanged=true; }); /** *

    描边颜色,以字符串表示。

    *

    默认值为 "#000000"(黑色);

    */ __getset(0,__proto,'strokeColor',function(){ return this._getCSSStyle().strokeColor; },function(value){ this._getCSSStyle().strokeColor=value; this.isChanged=true; }); /** * * */ /** * * */ __getset(0,__proto,'direction',function(){ return this._getCSSStyle().direction; },function(value){ this._getCSSStyle().direction=value; this.isChanged=true; }); /** *一个布尔值,表示文本的属性是否有改变。若为true表示有改变。 */ __getset(0,__proto,'isChanged',null,function(value){ if (this._isChanged!==value){ this._isChanged=value; value && Laya.timer.callLater(this,this.typeset); } }); /** *

    设置横向滚动量。

    *

    即使设置超出滚动范围的值,也会被自动限制在可能的最大值处。

    */ /** *获取横向滚动量。 */ __getset(0,__proto,'scrollX',function(){ if (!this._clipPoint) return 0; return this._clipPoint.x; },function(value){ if (this.overflow !=Text.SCROLL || (this.textWidth < this._width || !this._clipPoint)) return; value=value < this.padding[3] ? this.padding[3] :value; var maxScrollX=this._textWidth-this._width; value=value > maxScrollX ? maxScrollX :value; var visibleLineCount=this._height / (this._charSize.height+this.leading)| 0+1; this._clipPoint.x=value; this.renderText(this._lastVisibleLineIndex,visibleLineCount); }); /** *设置纵向滚动量(px)。即使设置超出滚动范围的值,也会被自动限制在可能的最大值处。 */ /** *获取纵向滚动量。 */ __getset(0,__proto,'scrollY',function(){ if (!this._clipPoint) return 0; return this._clipPoint.y; },function(value){ if (this.overflow !=Text.SCROLL || (this.textHeight < this._height || !this._clipPoint)) return; value=value < this.padding[0] ? this.padding[0] :value; var maxScrollY=this._textHeight-this._height; value=value > maxScrollY ? maxScrollY :value; var startLine=value / (this._charSize.height+this.leading)| 0; this._lastVisibleLineIndex=startLine; var visibleLineCount=(this._height / (this._charSize.height+this.leading)| 0)+1; this._clipPoint.y=value; this.renderText(startLine,visibleLineCount); }); /** *获取横向可滚动最大值。 */ __getset(0,__proto,'maxScrollX',function(){ return (this.textWidth < this._width)? 0 :this._textWidth-this._width; }); /** *获取纵向可滚动最大值。 */ __getset(0,__proto,'maxScrollY',function(){ return (this.textHeight < this._height)? 0 :this._textHeight-this._height; }); __getset(0,__proto,'lines',function(){ if (this._isChanged) this.typeset(); return this._lines; }); __getset(0,__proto,'underlineColor',function(){ return this._underlineColor; },function(value){ this._underlineColor=value; this._isChanged=true; this.typeset(); }); Text.registerBitmapFont=function(name,bitmapFont){ Text._bitmapFonts || (Text._bitmapFonts={}); Text._bitmapFonts[name]=bitmapFont; } Text.unregisterBitmapFont=function(name,destroy){ (destroy===void 0)&& (destroy=true); if (Text._bitmapFonts && Text._bitmapFonts[name]){ var tBitmapFont=Text._bitmapFonts[name]; if (destroy){ tBitmapFont.destroy(); } delete Text._bitmapFonts[name]; } } Text.setTextRightToLeft=function(){ var style; style=Browser.canvas.source.style; style.display="none"; style.position="absolute"; style.direction="rtl"; Render._mainCanvas.source.style.direction="rtl"; laya.display.Text.RightToLeft=true; Browser.document.body.appendChild(Browser.canvas.source); } Text.supportFont=function(font){ Browser.context.font="10px sans-serif"; var defaultFontWidth=Browser.context.measureText("abcji").width; Browser.context.font="10px "+font; var customFontWidth=Browser.context.measureText("abcji").width; console.log(defaultFontWidth,customFontWidth); if (defaultFontWidth===customFontWidth)return false; else return true; } Text._testWord="游"; Text.langPacks=null; Text.VISIBLE="visible"; Text.SCROLL="scroll"; Text.HIDDEN="hidden"; Text.CharacterCache=true; Text.RightToLeft=false; Text._bitmapFonts=null; __static(Text, ['_fontFamilyMap',function(){return this._fontFamilyMap={"报隶" :"报隶-简","黑体" :"黑体-简","楷体" :"楷体-简","兰亭黑" :"兰亭黑-简","隶变" :"隶变-简","凌慧体" :"凌慧体-简","翩翩体" :"翩翩体-简","苹方" :"苹方-简","手札体" :"手札体-简","宋体" :"宋体-简","娃娃体" :"娃娃体-简","魏碑" :"魏碑-简","行楷" :"行楷-简","雅痞" :"雅痞-简","圆体" :"圆体-简"};} ]); return Text; })(Sprite) /** *

    Stage 是舞台类,显示列表的根节点,所有显示对象都在舞台上显示。通过 Laya.stage 单例访问。

    *

    Stage提供几种适配模式,不同的适配模式会产生不同的画布大小,画布越大,渲染压力越大,所以要选择合适的适配方案。

    *

    Stage提供不同的帧率模式,帧率越高,渲染压力越大,越费电,合理使用帧率甚至动态更改帧率有利于改进手机耗电。

    */ //class laya.display.Stage extends laya.display.Sprite var Stage=(function(_super){ function Stage(){ /**当前焦点对象,此对象会影响当前键盘事件的派发主体。*/ this.focus=null; /**设计宽度(初始化时设置的宽度Laya.init(width,height))*/ this.designWidth=0; /**设计高度(初始化时设置的高度Laya.init(width,height))*/ this.designHeight=0; /**画布是否发生翻转。*/ this.canvasRotation=false; /**画布的旋转角度。*/ this.canvasDegree=0; /** *

    设置是否渲染,设置为false,可以停止渲染,画面会停留到最后一次渲染上,减少cpu消耗,此设置不影响时钟。

    *

    比如非激活状态,可以设置renderingEnabled=false以节省消耗。

    **/ this.renderingEnabled=true; /**是否启用屏幕适配,可以适配后,在某个时候关闭屏幕适配,防止某些操作导致的屏幕以外改变*/ this.screenAdaptationEnabled=true; /**@private */ this._screenMode="none"; /**@private */ this._scaleMode="noscale"; /**@private */ this._alignV="top"; /**@private */ this._alignH="left"; /**@private */ this._bgColor="black"; /**@private */ this._mouseMoveTime=0; /**@private */ this._renderCount=0; /**@private */ this._frameStartTime=NaN; /**@private */ this._isFocused=false; /**@private */ this._isVisibility=false; /**@private 3D场景*/ this._scenes=null; /**@private */ this._frameRate="fast"; /**使用物理分辨率作为canvas大小,会改进渲染效果,但是会降低性能*/ this.useRetinalCanvas=false; Stage.__super.call(this); this.offset=new Point(); this._canvasTransform=new Matrix(); this._previousOrientation=Browser.window.orientation; var _$this=this; this.transform=Matrix.create(); this._scenes=[]; this.mouseEnabled=true; this.hitTestPrior=true; this.autoSize=false; this._displayedInStage=true; this._isFocused=true; this._isVisibility=true; this.useRetinalCanvas=Config.useRetinalCanvas; var window=Browser.window; var _this=this; window.addEventListener("focus",function(){ _$this._isFocused=true; _this.event(/*laya.events.Event.FOCUS*/"focus"); _this.event(/*laya.events.Event.FOCUS_CHANGE*/"focuschange"); }); window.addEventListener("blur",function(){ _$this._isFocused=false; _this.event(/*laya.events.Event.BLUR*/"blur"); _this.event(/*laya.events.Event.FOCUS_CHANGE*/"focuschange"); if (_this._isInputting())Input["inputElement"].target.focus=false; }); var hidden="hidden",state="visibilityState",visibilityChange="visibilitychange"; var document=window.document; if (typeof document.hidden!=="undefined"){ visibilityChange="visibilitychange"; state="visibilityState"; }else if (typeof document.mozHidden!=="undefined"){ visibilityChange="mozvisibilitychange"; state="mozVisibilityState"; }else if (typeof document.msHidden!=="undefined"){ visibilityChange="msvisibilitychange"; state="msVisibilityState"; }else if (typeof document.webkitHidden!=="undefined"){ visibilityChange="webkitvisibilitychange"; state="webkitVisibilityState"; } window.document.addEventListener(visibilityChange,visibleChangeFun); function visibleChangeFun (){ if (Browser.document[state]=="hidden"){ _this._setStageVisible(false); }else { _this._setStageVisible(true); } } window.document.addEventListener("qbrowserVisibilityChange",qbroserVisibleChangeFun); function qbroserVisibleChangeFun (e){ _this._setStageVisible(!e.hidden); } window.addEventListener("resize",function(){ var orientation=Browser.window.orientation; if (orientation !=null && orientation !=_$this._previousOrientation && _this._isInputting()){ Input["inputElement"].target.focus=false; } _$this._previousOrientation=orientation; if (_this._isInputting())return; _this._resetCanvas(); }); window.addEventListener("orientationchange",function(e){ _this._resetCanvas(); }); this.on(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this._onmouseMove); if (Browser.onMobile)this.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this._onmouseMove); } __class(Stage,'laya.display.Stage',_super); var __proto=Stage.prototype; __proto._setStageVisible=function(value){ if (this._isVisibility==value)return; this._isVisibility=value; if (!this._isVisibility)if (this._isInputting())Input["inputElement"].target.focus=false; this.event(/*laya.events.Event.VISIBILITY_CHANGE*/"visibilitychange"); } /** *@private *在移动端输入时,输入法弹出期间不进行画布尺寸重置。 */ __proto._isInputting=function(){ return (Browser.onMobile && Input.isInputting); } /**@private */ __proto._changeCanvasSize=function(){ this.setScreenSize(Browser.clientWidth *Browser.pixelRatio,Browser.clientHeight *Browser.pixelRatio); } /**@private */ __proto._resetCanvas=function(){ if (!this.screenAdaptationEnabled)return; var canvas=Render._mainCanvas; var canvasStyle=canvas.source.style; canvas.size(1,1); Laya.timer.once(100,this,this._changeCanvasSize); } /** *设置屏幕大小,场景会根据屏幕大小进行适配。可以动态调用此方法,来更改游戏显示的大小。 *@param screenWidth 屏幕宽度。 *@param screenHeight 屏幕高度。 */ __proto.setScreenSize=function(screenWidth,screenHeight){ var rotation=false; if (this._screenMode!=="none"){ var screenType=screenWidth / screenHeight < 1 ? "vertical" :"horizontal"; rotation=screenType!==this._screenMode; if (rotation){ var temp=screenHeight; screenHeight=screenWidth; screenWidth=temp; } } this.canvasRotation=rotation; var canvas=Render._mainCanvas; var canvasStyle=canvas.source.style; var mat=this._canvasTransform.identity(); var scaleMode=this._scaleMode; var scaleX=screenWidth / this.designWidth; var scaleY=screenHeight / this.designHeight; var canvasWidth=Config.useRetinalCanvas?screenWidth:this.designWidth; var canvasHeight=Config.useRetinalCanvas?screenHeight:this.designHeight; var realWidth=screenWidth; var realHeight=screenHeight; var pixelRatio=Browser.pixelRatio; this._width=this.designWidth; this._height=this.designHeight; switch (scaleMode){ case "noscale": scaleX=scaleY=1; realWidth=this.designWidth; realHeight=this.designHeight; break ; case "showall": scaleX=scaleY=Math.min(scaleX,scaleY); canvasWidth=realWidth=Math.round(this.designWidth *scaleX); canvasHeight=realHeight=Math.round(this.designHeight *scaleY); break ; case "noborder": scaleX=scaleY=Math.max(scaleX,scaleY); realWidth=Math.round(this.designWidth *scaleX); realHeight=Math.round(this.designHeight *scaleY); break ; case "full": scaleX=scaleY=1; this._width=canvasWidth=screenWidth; this._height=canvasHeight=screenHeight; break ; case "fixedwidth": scaleY=scaleX; this._height=canvasHeight=Math.round(screenHeight / scaleX); break ; case "fixedheight": scaleX=scaleY; this._width=canvasWidth=Math.round(screenWidth / scaleY); break ; case "fixedauto": if ((screenWidth / screenHeight)< (this.designWidth / this.designHeight)){ scaleY=scaleX; this._height=canvasHeight=Math.round(screenHeight / scaleX); }else { scaleX=scaleY; this._width=canvasWidth=Math.round(screenWidth / scaleY); } break ; } if (this.conchModel)this.conchModel.size(this._width,this._height); if (Config.useRetinalCanvas){ realWidth=canvasWidth=screenWidth; realHeight=canvasHeight=screenHeight; } scaleX *=this.scaleX; scaleY *=this.scaleY; if (scaleX===1 && scaleY===1){ this.transform.identity(); }else { this.transform.a=this._formatData(scaleX / (realWidth / canvasWidth)); this.transform.d=this._formatData(scaleY / (realHeight / canvasHeight)); this.conchModel && this.conchModel.scale(this.transform.a,this.transform.d); } canvas.size(canvasWidth,canvasHeight); RunDriver.changeWebGLSize(canvasWidth,canvasHeight); mat.scale(realWidth / canvasWidth / pixelRatio,realHeight / canvasHeight / pixelRatio); if (this._alignH==="left")this.offset.x=0; else if (this._alignH==="right")this.offset.x=(screenWidth-realWidth)/pixelRatio; else this.offset.x=(screenWidth-realWidth)*0.5 / pixelRatio; if (this._alignV==="top")this.offset.y=0; else if (this._alignV==="bottom")this.offset.y=(screenHeight-realHeight)/pixelRatio; else this.offset.y=(screenHeight-realHeight)*0.5 / pixelRatio; this.offset.x=Math.round(this.offset.x); this.offset.y=Math.round(this.offset.y); mat.translate(this.offset.x,this.offset.y); this.canvasDegree=0; if (rotation){ if (this._screenMode==="horizontal"){ mat.rotate(Math.PI / 2); mat.translate(screenHeight / pixelRatio,0); this.canvasDegree=90; }else { mat.rotate(-Math.PI / 2); mat.translate(0,screenWidth / pixelRatio); this.canvasDegree=-90; } } mat.a=this._formatData(mat.a); mat.d=this._formatData(mat.d); mat.tx=this._formatData(mat.tx); mat.ty=this._formatData(mat.ty); canvasStyle.transformOrigin=canvasStyle.webkitTransformOrigin=canvasStyle.msTransformOrigin=canvasStyle.mozTransformOrigin=canvasStyle.oTransformOrigin="0px 0px 0px"; canvasStyle.transform=canvasStyle.webkitTransform=canvasStyle.msTransform=canvasStyle.mozTransform=canvasStyle.oTransform="matrix("+mat.toString()+")"; canvasStyle.width=canvasWidth; canvasStyle.height=canvasHeight; mat.translate(parseInt(canvasStyle.left)|| 0,parseInt(canvasStyle.top)|| 0); this.visible=true; this._repaint=1; this.event(/*laya.events.Event.RESIZE*/"resize"); } /**@private */ __proto._formatData=function(value){ if (Math.abs(value)< 0.000001)return 0; if (Math.abs(1-value)< 0.001)return value > 0 ? 1 :-1; return value; } /**@inheritDoc */ __proto.getMousePoint=function(){ return Point.TEMP.setTo(this.mouseX,this.mouseY); } /**@inheritDoc */ __proto.repaint=function(){ this._repaint=1; } /**@inheritDoc */ __proto.parentRepaint=function(){} /**@private */ __proto._loop=function(){ this.render(Render.context,0,0); return true; } /**@private */ __proto._onmouseMove=function(e){ this._mouseMoveTime=Browser.now(); } /** *

    获得距当前帧开始后,过了多少时间,单位为毫秒。

    *

    可以用来判断函数内时间消耗,通过合理控制每帧函数处理消耗时长,避免一帧做事情太多,对复杂计算分帧处理,能有效降低帧率波动。

    */ __proto.getTimeFromFrameStart=function(){ return Browser.now()-this._frameStartTime; } /**@inheritDoc */ __proto.render=function(context,x,y){ if (this._frameRate==="sleep" && !Render.isConchApp){ var now=Browser.now(); if (now-this._frameStartTime >=1000)this._frameStartTime=now; else return; } this._renderCount++; Render.isFlash && this.repaint(); if (!this._style.visible){ if (this._renderCount % 5===0){ Stat.loopCount++; MouseManager.instance.runEvent(); Laya.timer._update(); } return; } this._frameStartTime=Browser.now(); var frameMode=this._frameRate==="mouse" ? (((this._frameStartTime-this._mouseMoveTime)< 2000)? "fast" :"slow"):this._frameRate; var isFastMode=(frameMode!=="slow"); var isDoubleLoop=(this._renderCount % 2===0); Stat.renderSlow=!isFastMode; if (isFastMode || isDoubleLoop || Render.isConchApp){ Stat.loopCount++; MouseManager.instance.runEvent(); Laya.timer._update(); RunDriver.update3DLoop(); var scene; var i=0,n=0; if (Render.isConchNode){ for (i=0,n=this._scenes.length;i < n;i++){ scene=this._scenes[i]; (scene)&& (scene._updateSceneConch()); } }else { for (i=0,n=this._scenes.length;i < n;i++){ scene=this._scenes[i]; (scene)&& (scene._updateScene()); } } if (Render.isConchNode){ var customList=Sprite["CustomList"]; for (i=0,n=customList.length;i < n;i++){ var customItem=customList[i]; customItem.customRender(customItem.customContext,0,0); } return; } } if (Render.isConchNode)return; if (this.renderingEnabled && (isFastMode || !isDoubleLoop || Render.isConchWebGL)){ if (Render.isWebGL){ context.clear(); _super.prototype.render.call(this,context,x,y); Stat._show&& Stat._sp && Stat._sp.render(context,x,y); RunDriver.clear(this._bgColor); RunDriver.beginFlush(); context.flush(); RunDriver.endFinish(); VectorGraphManager.instance && VectorGraphManager.getInstance().endDispose(); }else { RunDriver.clear(this._bgColor); _super.prototype.render.call(this,context,x,y); Stat._show&& Stat._sp && Stat._sp.render(context,x,y); } } } /**@private */ __proto._requestFullscreen=function(){ var element=Browser.document.documentElement; if (element.requestFullscreen){ element.requestFullscreen(); }else if (element.mozRequestFullScreen){ element.mozRequestFullScreen(); }else if (element.webkitRequestFullscreen){ element.webkitRequestFullscreen(); }else if (element.msRequestFullscreen){ element.msRequestFullscreen(); } } /**@private */ __proto._fullScreenChanged=function(){ Laya.stage.event(/*laya.events.Event.FULL_SCREEN_CHANGE*/"fullscreenchange"); } /**退出全屏模式*/ __proto.exitFullscreen=function(){ var document=Browser.document; if (document.exitFullscreen){ document.exitFullscreen(); }else if (document.mozCancelFullScreen){ document.mozCancelFullScreen(); }else if (document.webkitExitFullscreen){ document.webkitExitFullscreen(); } } /**当前视窗由缩放模式导致的 X 轴缩放系数。*/ __getset(0,__proto,'clientScaleX',function(){ return this._transform ? this._transform.getScaleX():1; }); //[Deprecated] __getset(0,__proto,'desginHeight',function(){ console.debug("desginHeight已经弃用,请使用designHeight代替"); return this.designHeight; }); /**帧率类型,支持三种模式:fast-60帧(默认),slow-30帧,mouse-30帧(鼠标活动后会自动加速到60,鼠标不动2秒后降低为30帧,以节省消耗),sleep-1帧。*/ __getset(0,__proto,'frameRate',function(){ return this._frameRate; },function(value){ this._frameRate=value; if (Render.isConchApp){ switch (this._frameRate){ case "slow": Browser.window.conch && Browser.window.conchConfig.setSlowFrame && Browser.window.conchConfig.setSlowFrame(true); break ; case "fast": Browser.window.conch && Browser.window.conchConfig.setSlowFrame && Browser.window.conchConfig.setSlowFrame(false); break ; case "mouse": Browser.window.conch && Browser.window.conchConfig.setMouseFrame && Browser.window.conchConfig.setMouseFrame(2000); break ; case "sleep": Browser.window.conch && Browser.window.conchConfig.setLimitFPS && Browser.window.conchConfig.setLimitFPS(1); break ; default : throw new Error("Stage:frameRate invalid."); break ; } } }); /**当前视窗由缩放模式导致的 Y 轴缩放系数。*/ __getset(0,__proto,'clientScaleY',function(){ return this._transform ? this._transform.getScaleY():1; }); __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ this.designWidth=value; Laya.superSet(Sprite,this,'width',value); Laya.timer.callLater(this,this._changeCanvasSize); }); /** *

    水平对齐方式。默认值为"left"。

    *

      取值范围: *
    • "left" :居左对齐;
    • *
    • "center" :居中对齐;
    • *
    • "right" :居右对齐;
    • *

    */ __getset(0,__proto,'alignH',function(){ return this._alignH; },function(value){ this._alignH=value; Laya.timer.callLater(this,this._changeCanvasSize); }); /** *舞台是否获得焦点。 */ __getset(0,__proto,'isFocused',function(){ return this._isFocused; }); __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ this.designHeight=value; Laya.superSet(Sprite,this,'height',value); Laya.timer.callLater(this,this._changeCanvasSize); }); __getset(0,__proto,'transform',function(){ if (this._tfChanged)this._adjustTransform(); return this._transform=this._transform|| Matrix.create(); },_super.prototype._$set_transform); /** *舞台是否处于可见状态(是否进入后台)。 */ __getset(0,__proto,'isVisibility',function(){ return this._isVisibility; }); //[Deprecated] __getset(0,__proto,'desginWidth',function(){ console.debug("desginWidth已经弃用,请使用designWidth代替"); return this.designWidth; }); /** *

    缩放模式。默认值为 "noscale"。

    *

      取值范围: *
    • "noscale" :不缩放;
    • *
    • "exactfit" :全屏不等比缩放;
    • *
    • "showall" :最小比例缩放;
    • *
    • "noborder" :最大比例缩放;
    • *
    • "full" :不缩放,stage的宽高等于屏幕宽高;
    • *
    • "fixedwidth" :宽度不变,高度根据屏幕比缩放;
    • *
    • "fixedheight" :高度不变,宽度根据屏幕比缩放;
    • *
    • "fixedauto" :根据宽高比,自动选择使用fixedwidth或fixedheight;
    • *

    */ __getset(0,__proto,'scaleMode',function(){ return this._scaleMode; },function(value){ this._scaleMode=value; Laya.timer.callLater(this,this._changeCanvasSize); }); /** *

    垂直对齐方式。默认值为"top"。

    *

      取值范围: *
    • "top" :居顶部对齐;
    • *
    • "middle" :居中对齐;
    • *
    • "bottom" :居底部对齐;
    • *

    */ __getset(0,__proto,'alignV',function(){ return this._alignV; },function(value){ this._alignV=value; Laya.timer.callLater(this,this._changeCanvasSize); }); /**舞台的背景颜色,默认为黑色,null为透明。*/ __getset(0,__proto,'bgColor',function(){ return this._bgColor; },function(value){ this._bgColor=value; this.conchModel && this.conchModel.bgColor(value); if (Render.isWebGL){ if (value){ Stage._wgColor=Color.create(value)._color; }else { Stage._wgColor=null; } } if (Browser.onLimixiu){ Stage._wgColor=Color.create(value)._color; }else if (value){ Render.canvas.style.background=value; }else { Render.canvas.style.background="none"; } }); /**鼠标在 Stage 上的 X 轴坐标。*/ __getset(0,__proto,'mouseX',function(){ return Math.round(MouseManager.instance.mouseX / this.clientScaleX); }); /**鼠标在 Stage 上的 Y 轴坐标。*/ __getset(0,__proto,'mouseY',function(){ return Math.round(MouseManager.instance.mouseY / this.clientScaleY); }); /** *

    场景布局类型。

    *

      取值范围: *
    • "none" :不更改屏幕
    • *
    • "horizontal" :自动横屏
    • *
    • "vertical" :自动竖屏
    • *

    */ __getset(0,__proto,'screenMode',function(){ return this._screenMode; },function(value){ this._screenMode=value; }); __getset(0,__proto,'visible',_super.prototype._$get_visible,function(value){ if (this.visible!==value){ Laya.superSet(Sprite,this,'visible',value); var style=Render._mainCanvas.source.style; style.visibility=value ? "visible" :"hidden"; } }); /** *

    是否开启全屏,用户点击后进入全屏。

    *

    兼容性提示:部分浏览器不允许点击进入全屏,比如Iphone等。

    */ __getset(0,__proto,'fullScreenEnabled',null,function(value){ var document=Browser.document; var canvas=Render.canvas; if (value){ canvas.addEventListener('mousedown',this._requestFullscreen); canvas.addEventListener('touchstart',this._requestFullscreen); document.addEventListener("fullscreenchange",this._fullScreenChanged); document.addEventListener("mozfullscreenchange",this._fullScreenChanged); document.addEventListener("webkitfullscreenchange",this._fullScreenChanged); document.addEventListener("msfullscreenchange",this._fullScreenChanged); }else { canvas.removeEventListener('mousedown',this._requestFullscreen); canvas.removeEventListener('touchstart',this._requestFullscreen); document.removeEventListener("fullscreenchange",this._fullScreenChanged); document.removeEventListener("mozfullscreenchange",this._fullScreenChanged); document.removeEventListener("webkitfullscreenchange",this._fullScreenChanged); document.removeEventListener("msfullscreenchange",this._fullScreenChanged); } }); Stage.SCALE_NOSCALE="noscale"; Stage.SCALE_EXACTFIT="exactfit"; Stage.SCALE_SHOWALL="showall"; Stage.SCALE_NOBORDER="noborder"; Stage.SCALE_FULL="full"; Stage.SCALE_FIXED_WIDTH="fixedwidth"; Stage.SCALE_FIXED_HEIGHT="fixedheight"; Stage.SCALE_FIXED_AUTO="fixedauto"; Stage.ALIGN_LEFT="left"; Stage.ALIGN_RIGHT="right"; Stage.ALIGN_CENTER="center"; Stage.ALIGN_TOP="top"; Stage.ALIGN_MIDDLE="middle"; Stage.ALIGN_BOTTOM="bottom"; Stage.SCREEN_NONE="none"; Stage.SCREEN_HORIZONTAL="horizontal"; Stage.SCREEN_VERTICAL="vertical"; Stage.FRAME_FAST="fast"; Stage.FRAME_SLOW="slow"; Stage.FRAME_MOUSE="mouse"; Stage.FRAME_SLEEP="sleep"; Stage.FRAME_MOUSE_THREDHOLD=2000; __static(Stage, ['_wgColor',function(){return this._wgColor=[0,0,0,1];} ]); return Stage; })(Sprite) /** *@private */ //class laya.media.SoundNode extends laya.display.Sprite var SoundNode=(function(_super){ function SoundNode(){ this.url=null; this._channel=null; this._tar=null; this._playEvents=null; this._stopEvents=null; SoundNode.__super.call(this); this.visible=false; this.on(/*laya.events.Event.ADDED*/"added",this,this._onParentChange); this.on(/*laya.events.Event.REMOVED*/"removed",this,this._onParentChange); } __class(SoundNode,'laya.media.SoundNode',_super); var __proto=SoundNode.prototype; /**@private */ __proto._onParentChange=function(){ this.target=this.parent; } /** *播放 *@param loops 循环次数 *@param complete 完成回调 * */ __proto.play=function(loops,complete){ (loops===void 0)&& (loops=1); if (isNaN(loops)){ loops=1; } if (!this.url)return; this.stop(); this._channel=SoundManager.playSound(this.url,loops,complete); } /** *停止播放 * */ __proto.stop=function(){ if (this._channel && !this._channel.isStopped){ this._channel.stop(); } this._channel=null; } /**@private */ __proto._setPlayAction=function(tar,event,action,add){ (add===void 0)&& (add=true); if (!this[action])return; if (!tar)return; if (add){ tar.on(event,this,this[action]); }else { tar.off(event,this,this[action]); } } /**@private */ __proto._setPlayActions=function(tar,events,action,add){ (add===void 0)&& (add=true); if (!tar)return; if (!events)return; var eventArr=events.split(","); var i=0,len=0; len=eventArr.length; for (i=0;i < len;i++){ this._setPlayAction(tar,eventArr[i],action,add); } } /** *设置触发播放的事件 *@param events * */ __getset(0,__proto,'playEvent',null,function(events){ this._playEvents=events; if (!events)return; if (this._tar){ this._setPlayActions(this._tar,events,"play"); } }); /** *设置控制播放的对象 *@param tar * */ __getset(0,__proto,'target',null,function(tar){ if (this._tar){ this._setPlayActions(this._tar,this._playEvents,"play",false); this._setPlayActions(this._tar,this._stopEvents,"stop",false); } this._tar=tar; if (this._tar){ this._setPlayActions(this._tar,this._playEvents,"play",true); this._setPlayActions(this._tar,this._stopEvents,"stop",true); } }); /** *设置触发停止的事件 *@param events * */ __getset(0,__proto,'stopEvent',null,function(events){ this._stopEvents=events; if (!events)return; if (this._tar){ this._setPlayActions(this._tar,events,"stop"); } }); return SoundNode; })(Sprite) /** *@private *FileBitmap 是图片文件资源类。 */ //class laya.resource.FileBitmap extends laya.resource.Bitmap var FileBitmap=(function(_super){ function FileBitmap(){ /**@private 文件路径全名。*/ this._src=null; /**@private onload触发函数*/ this._onload=null; /**@private onerror触发函数*/ this._onerror=null; FileBitmap.__super.call(this); } __class(FileBitmap,'laya.resource.FileBitmap',_super); var __proto=FileBitmap.prototype; /** *文件路径全名。 */ __getset(0,__proto,'src',function(){ return this._src; },function(value){ this._src=value; }); /** *载入完成处理函数。 */ __getset(0,__proto,'onload',null,function(value){ }); /** *错误处理函数。 */ __getset(0,__proto,'onerror',null,function(value){ }); return FileBitmap; })(Bitmap) /** *HTMLCanvas 是 Html Canvas 的代理类,封装了 Canvas 的属性和方法。。请不要直接使用 new HTMLCanvas! */ //class laya.resource.HTMLCanvas extends laya.resource.Bitmap var HTMLCanvas=(function(_super){ function HTMLCanvas(type,canvas){ //this._ctx=null; this._is2D=false; HTMLCanvas.__super.call(this); var _$this=this; this._source=this; if (type==="2D" || (type==="AUTO" && !Render.isWebGL)){ this._is2D=true; this._source=canvas || Browser.createElement("canvas"); this._w=this._source.width; this._h=this._source.height; var o=this; o.getContext=function (contextID,other){ if (_$this._ctx)return _$this._ctx; var ctx=_$this._ctx=_$this._source.getContext(contextID,other); if (ctx){ ctx._canvas=o; if(!Render.isFlash&&!Browser.onLimixiu)ctx.size=function (w,h){ }; } return ctx; } } this.lock=true; } __class(HTMLCanvas,'laya.resource.HTMLCanvas',_super); var __proto=HTMLCanvas.prototype; /** *清空画布内容。 */ __proto.clear=function(){ this._ctx && this._ctx.clear(); } /** *销毁。 */ __proto.destroy=function(){ this._ctx && this._ctx.destroy(); this._ctx=null; laya.resource.Resource.prototype.destroy.call(this); } /** *释放。 */ __proto.release=function(){} /** *@private *设置 Canvas 渲染上下文。 *@param context Canvas 渲染上下文。 */ __proto._setContext=function(context){ this._ctx=context; } /** *获取 Canvas 渲染上下文。 *@param contextID 上下文ID. *@param other *@return Canvas 渲染上下文 Context 对象。 */ __proto.getContext=function(contextID,other){ return this._ctx ? this._ctx :(this._ctx=HTMLCanvas._createContext(this)); } /** *获取内存大小。 *@return 内存大小。 */ __proto.getMemSize=function(){ return 0; } /** *设置宽高。 *@param w 宽度。 *@param h 高度。 */ __proto.size=function(w,h){ if (this._w !=w || this._h !=h ||(this._source && (this._source.width!=w || this._source.height!=h))){ this._w=w; this._h=h; this.memorySize=this._w *this._h *4; this._ctx && this._ctx.size(w,h); this._source && (this._source.height=h,this._source.width=w); } } __proto.getCanvas=function(){ return this._source; } __proto.toBase64=function(type,encoderOptions,callBack){ if (this._source){ if (Render.isConchApp && this._source.toBase64){ this._source.toBase64(type,encoderOptions,callBack); } else { var base64Data=this._source.toDataURL(type,encoderOptions); callBack.call(this,base64Data); } } } /** *Canvas 渲染上下文。 */ __getset(0,__proto,'context',function(){ return this._ctx; }); /** *是否当作 Bitmap 对象。 */ __getset(0,__proto,'asBitmap',null,function(value){ }); HTMLCanvas.create=function(type,canvas){ return new HTMLCanvas(type,canvas); } HTMLCanvas.TYPE2D="2D"; HTMLCanvas.TYPE3D="3D"; HTMLCanvas.TYPEAUTO="AUTO"; HTMLCanvas._createContext=null; return HTMLCanvas; })(Bitmap) /** *@private */ //class laya.resource.HTMLSubImage extends laya.resource.Bitmap var HTMLSubImage=(function(_super){ //请不要直接使用new HTMLSubImage function HTMLSubImage(canvas,offsetX,offsetY,width,height,atlasImage,src,allowMerageInAtlas){ HTMLSubImage.__super.call(this); throw new Error("不允许new!"); } __class(HTMLSubImage,'laya.resource.HTMLSubImage',_super); HTMLSubImage.create=function(canvas,offsetX,offsetY,width,height,atlasImage,src,allowMerageInAtlas){ (allowMerageInAtlas===void 0)&& (allowMerageInAtlas=false); return new HTMLSubImage(canvas,offsetX,offsetY,width,height,atlasImage,src,allowMerageInAtlas); } return HTMLSubImage; })(Bitmap) /** *

    Animation 是Graphics动画类。实现了基于Graphics的动画创建、播放、控制接口。

    *

    本类使用了动画模版缓存池,它以一定的内存开销来节省CPU开销,当相同的动画模版被多次使用时,相比于每次都创建新的动画模版,使用动画模版缓存池,只需创建一次,缓存之后多次复用,从而节省了动画模版创建的开销。

    *

    动画模版缓存池,以key-value键值对存储,key可以自定义,也可以从指定的配置文件中读取,value为对应的动画模版,是一个Graphics对象数组,每个Graphics对象对应一个帧图像,动画的播放实质就是定时切换Graphics对象。

    *

    使用set source、loadImages(...)、loadAtlas(...)、loadAnimation(...)方法可以创建动画模版。使用play(...)可以播放指定动画。

    *@example 以下示例代码,创建了一个 Text 实例。 *package *{ *import laya.display.Animation; *import laya.net.Loader; *import laya.utils.Handler; *public class Animation_Example *{ *public function Animation_Example() *{ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *init();//初始化 *} *private function init():void *{ *var animation:Animation=new Animation();//创建一个 Animation 类的实例对象 animation 。 *animation.loadAtlas("resource/ani/fighter.json");//加载图集并播放 *animation.x=200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 *animation.y=200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 *animation.interval=50;//设置 animation 对象的动画播放间隔时间,单位:毫秒。 *animation.play();//播放动画。 *Laya.stage.addChild(animation);//将 animation 对象添加到显示列表。 *} *} *} * *@example *Animation_Example(); *function Animation_Example(){ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *init();//初始化 *} *function init() *{ *var animation=new Laya.Animation();//创建一个 Animation 类的实例对象 animation 。 *animation.loadAtlas("resource/ani/fighter.json");//加载图集并播放 *animation.x=200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 *animation.y=200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 *animation.interval=50;//设置 animation 对象的动画播放间隔时间,单位:毫秒。 *animation.play();//播放动画。 *Laya.stage.addChild(animation);//将 animation 对象添加到显示列表。 *} * *@example *import Animation=laya.display.Animation; *class Animation_Example { *constructor(){ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *this.init(); *} *private init():void { *var animation:Animation=new Laya.Animation();//创建一个 Animation 类的实例对象 animation 。 *animation.loadAtlas("resource/ani/fighter.json");//加载图集并播放 *animation.x=200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 *animation.y=200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 *animation.interval=50;//设置 animation 对象的动画播放间隔时间,单位:毫秒。 *animation.play();//播放动画。 *Laya.stage.addChild(animation);//将 animation 对象添加到显示列表。 *} *} *new Animation_Example(); */ //class laya.display.Animation extends laya.display.AnimationPlayerBase var Animation=(function(_super){ function Animation(){ /**@private */ this._frames=null; /**@private */ this._url=null; Animation.__super.call(this); this._setControlNode(this); } __class(Animation,'laya.display.Animation',_super); var __proto=Animation.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); this.stop(); laya.display.Sprite.prototype.destroy.call(this,destroyChild); this._frames=null; this._labels=null; } /** *

    开始播放动画。会在动画模版缓存池中查找key值为name的动画模版,存在则用此动画模版初始化当前序列帧, 如果不存在,则使用当前序列帧。

    *

    play(...)方法被设计为在创建实例后的任何时候都可以被调用,调用后就处于播放状态,当相应的资源加载完毕、调用动画帧填充方法(set frames)或者将实例显示在舞台上时,会判断是否处于播放状态,如果是,则开始播放。

    *

    配合wrapMode属性,可设置动画播放顺序类型。

    *@param start (可选)指定动画播放开始的索引(int)或帧标签(String)。帧标签可以通过addLabel(...)和removeLabel(...)进行添加和删除。 *@param loop (可选)是否循环播放。 *@param name (可选)动画模板在动画模版缓存池中的key,也可认为是动画名称。如果name为空,则播放当前动画序列帧;如果不为空,则在动画模版缓存池中寻找key值为name的动画模版,如果存在则用此动画模版初始化当前序列帧并播放,如果不存在,则仍然播放当前动画序列帧;如果没有当前动画的帧数据,则不播放,但该实例仍然处于播放状态。 *@param showWarn(可选)是否动画不存在时打印警告 */ __proto.play=function(start,loop,name,showWarn){ (start===void 0)&& (start=0); (loop===void 0)&& (loop=true); (name===void 0)&& (name=""); (showWarn===void 0)&& (showWarn=true); if (name)this._setFramesFromCache(name,showWarn); this._isPlaying=true; this.index=((typeof start=='string'))? this._getFrameByLabel(start):start; this.loop=loop; this._actionName=name; this._isReverse=this.wrapMode==1; if (this._frames && this.interval > 0){ this.timerLoop(this.interval,this,this._frameLoop,null,true,true); } } /**@private */ __proto._setFramesFromCache=function(name,showWarn){ (showWarn===void 0)&& (showWarn=false); if (this._url)name=this._url+"#"+name; if (name && Animation.framesMap[name]){ var tAniO; tAniO=Animation.framesMap[name]; if ((tAniO instanceof Array)){ this._frames=Animation.framesMap[name]; this._count=this._frames.length; }else { if (tAniO.nodeRoot){ Animation.framesMap[name]=this._parseGraphicAnimationByData(tAniO); tAniO=Animation.framesMap[name]; } this._frames=tAniO.frames; this._count=this._frames.length; if (!this._frameRateChanged)this._interval=tAniO.interval; this._labels=this._copyLabels(tAniO.labels); } return true; }else { if (showWarn)console.log("ani not found:",name); } return false; } /**@private */ __proto._copyLabels=function(labels){ if (!labels)return null; var rst; rst={}; var key; for (key in labels){ rst[key]=Utils.copyArray([],labels[key]); } return rst; } /**@private */ __proto._frameLoop=function(){ if (this._style.visible && this._style.alpha > 0.01){ _super.prototype._frameLoop.call(this); } } /**@private */ __proto._displayToIndex=function(value){ if (this._frames)this.graphics=this._frames[value]; } /** *停止动画播放,并清理对象属性。之后可存入对象池,方便对象复用。 */ __proto.clear=function(){ this.stop(); this.graphics=null; this._frames=null; this._labels=null; } /** *

    根据指定的动画模版初始化当前动画序列帧。选择动画模版的过程如下:1. 动画模版缓存池中key为cacheName的动画模版;2. 如果不存在,则加载指定的图片集合并创建动画模版。注意:只有指定不为空的cacheName,才能将创建好的动画模版以此为key缓存到动画模版缓存池,否则不进行缓存。

    *

    动画模版缓存池是以一定的内存开销来节省CPU开销,当相同的动画模版被多次使用时,相比于每次都创建新的动画模版,使用动画模版缓存池,只需创建一次,缓存之后多次复用,从而节省了动画模版创建的开销。

    *

    因为返回值为Animation对象本身,所以可以使用如下语法:ani.loadImages(...).loadImages(...).play(...);。

    *@param urls 图片路径集合。需要创建动画模版时,会以此为数据源。参数形如:[url1,url2,url3,...]。 *@param cacheName (可选)动画模板在动画模版缓存池中的key。如果此参数不为空,表示使用动画模版缓存池。如果动画模版缓存池中存在key为cacheName的动画模版,则使用此模版。否则,创建新的动画模版,如果cacheName不为空,则以cacheName为key缓存到动画模版缓存池中,如果cacheName为空,不进行缓存。 *@return 返回Animation对象本身。 */ __proto.loadImages=function(urls,cacheName){ (cacheName===void 0)&& (cacheName=""); this._url=""; if (!this._setFramesFromCache(cacheName)){ this.frames=Animation.framesMap[cacheName] ? Animation.framesMap[cacheName] :Animation.createFrames(urls,cacheName); } return this; } /** *

    根据指定的动画模版初始化当前动画序列帧。选择动画模版的过程如下:1. 动画模版缓存池中key为cacheName的动画模版;2. 如果不存在,则加载指定的图集并创建动画模版。

    *

    注意:只有指定不为空的cacheName,才能将创建好的动画模版以此为key缓存到动画模版缓存池,否则不进行缓存。

    *

    动画模版缓存池是以一定的内存开销来节省CPU开销,当相同的动画模版被多次使用时,相比于每次都创建新的动画模版,使用动画模版缓存池,只需创建一次,缓存之后多次复用,从而节省了动画模版创建的开销。

    *

    因为返回值为Animation对象本身,所以可以使用如下语法:ani.loadAtlas(...).loadAtlas(...).play(...);。

    *@param url 图集路径。需要创建动画模版时,会以此为数据源。 *@param loaded (可选)使用指定图集初始化动画完毕的回调。 *@param cacheName (可选)动画模板在动画模版缓存池中的key。如果此参数不为空,表示使用动画模版缓存池。如果动画模版缓存池中存在key为cacheName的动画模版,则使用此模版。否则,创建新的动画模版,如果cacheName不为空,则以cacheName为key缓存到动画模版缓存池中,如果cacheName为空,不进行缓存。 *@return 返回动画本身。 */ __proto.loadAtlas=function(url,loaded,cacheName){ (cacheName===void 0)&& (cacheName=""); this._url=""; var _this_=this; function onLoaded (loadUrl){ if (url===loadUrl){ _this_.frames=Animation.framesMap[cacheName] ? Animation.framesMap[cacheName] :Animation.createFrames(url,cacheName); if (loaded)loaded.run(); } } if (!_this_._setFramesFromCache(cacheName)){ if (Loader.getAtlas(url))onLoaded(url); else Laya.loader.load(url,Handler.create(null,onLoaded,[url]),null,/*laya.net.Loader.ATLAS*/"atlas"); } return this; } /** *

    加载并解析由LayaAir IDE制作的动画文件,此文件中可能包含多个动画。默认帧率为在IDE中设计的帧率,如果调用过set interval,则使用此帧间隔对应的帧率。加载后创建动画模版,并缓存到动画模版缓存池,key "url#动画名称" 对应相应动画名称的动画模板,key "url#" 对应动画模版集合的默认动画模版。

    *

    注意:如果调用本方法前,还没有预加载动画使用的图集,请将atlas参数指定为对应的图集路径,否则会导致动画创建失败。

    *

    动画模版缓存池是以一定的内存开销来节省CPU开销,当相同的动画模版被多次使用时,相比于每次都创建新的动画模版,使用动画模版缓存池,只需创建一次,缓存之后多次复用,从而节省了动画模版创建的开销。

    *

    因为返回值为Animation对象本身,所以可以使用如下语法:ani.loadAnimation(...).loadAnimation(...).play(...);。

    *@param url 动画文件路径。可由LayaAir IDE创建并发布。 *@param loaded (可选)使用指定动画资源初始化动画完毕的回调。 *@param atlas (可选)动画用到的图集地址(可选)。 *@return 返回动画本身。 */ __proto.loadAnimation=function(url,loaded,atlas){ this._url=url; var _this_=this; if (!this._actionName)this._actionName=""; if (!_this_._setFramesFromCache(this._actionName)){ if (!atlas || Loader.getAtlas(atlas)){ this._loadAnimationData(url,loaded,atlas); }else { Laya.loader.load(atlas,Handler.create(this,this._loadAnimationData,[url,loaded,atlas]),null,/*laya.net.Loader.ATLAS*/"atlas") } }else { _this_._setFramesFromCache(this._actionName,true); this.index=0; if (loaded)loaded.run(); } return this; } /**@private */ __proto._loadAnimationData=function(url,loaded,atlas){ var _$this=this; if (atlas && !Loader.getAtlas(atlas)){ console.warn("atlas load fail:"+atlas); return; }; var _this_=this; function onLoaded (loadUrl){ if (!Loader.getRes(loadUrl))return; if (url===loadUrl){ var tAniO; if (!Animation.framesMap[url+"#"]){ var aniData=_this_._parseGraphicAnimation(Loader.getRes(url)); if (!aniData)return; var aniList=aniData.animationList; var i=0,len=aniList.length; var defaultO; for (i=0;i < len;i++){ tAniO=aniList[i]; Animation.framesMap[url+"#"+tAniO.name]=tAniO; if (!defaultO)defaultO=tAniO; } if (defaultO){ Animation.framesMap[url+"#"]=defaultO; _this_._setFramesFromCache(_$this._actionName,true); _$this.index=0; } _$this._checkResumePlaying(); }else { _this_._setFramesFromCache(_$this._actionName,true); _$this.index=0; _$this._checkResumePlaying(); } if (loaded)loaded.run(); } } if (Loader.getRes(url))onLoaded(url); else Laya.loader.load(url,Handler.create(null,onLoaded,[url]),null,/*laya.net.Loader.JSON*/"json"); Loader.clearRes(url); } /**@private */ __proto._parseGraphicAnimation=function(animationData){ return GraphicAnimation.parseAnimationData(animationData); } /**@private */ __proto._parseGraphicAnimationByData=function(animationObject){ return GraphicAnimation.parseAnimationByData(animationObject); } /** *当前动画的帧图像数组。本类中,每个帧图像是一个Graphics对象,而动画播放就是定时切换Graphics对象的过程。 */ __getset(0,__proto,'frames',function(){ return this._frames; },function(value){ this._frames=value; if (value){ this._count=value.length; if (this._isPlaying)this.play(this._index,this.loop,this._actionName); else this.index=this._index; } }); /** *是否自动播放,默认为false。如果设置为true,则动画被创建并添加到舞台后自动播放。 */ __getset(0,__proto,'autoPlay',null,function(value){ if (value)this.play(); else this.stop(); }); /** *

    动画数据源。

    *

    类型如下:
    *1. LayaAir IDE动画文件路径:使用此类型需要预加载所需的图集资源,否则会创建失败,如果不想预加载或者需要创建完毕的回调,请使用loadAnimation(...)方法;
    *2. 图集路径:使用此类型创建的动画模版不会被缓存到动画模版缓存池中,如果需要缓存或者创建完毕的回调,请使用loadAtlas(...)方法;
    *3. 图片路径集合:使用此类型创建的动画模版不会被缓存到动画模版缓存池中,如果需要缓存,请使用loadImages(...)方法。

    *@param value 数据源。比如:图集:"xx/a1.atlas";图片集合:"a1.png,a2.png,a3.png";LayaAir IDE动画"xx/a1.ani"。 */ __getset(0,__proto,'source',null,function(value){ if (value.indexOf(".ani")>-1)this.loadAnimation(value); else if (value.indexOf(".json")>-1 || value.indexOf("als")>-1 || value.indexOf("atlas")>-1)this.loadAtlas(value); else this.loadImages(value.split(",")); }); /** *设置自动播放的动画名称,在LayaAir IDE中可以创建的多个动画组成的动画集合,选择其中一个动画名称进行播放。 */ __getset(0,__proto,'autoAnimation',null,function(value){ this.play(0,true,value,false); }); Animation.createFrames=function(url,name){ var arr,i=0,n=0,g; if ((typeof url=='string')){ var atlas=Loader.getAtlas(url); if (atlas && atlas.length){ arr=[]; for (i=0,n=atlas.length;i < n;i++){ g=new RunDriver.createGraphics(); g.drawTexture(Loader.getRes(atlas[i]),0,0); arr.push(g); } } }else if ((url instanceof Array)){ arr=[]; for (i=0,n=url.length;i < n;i++){ g=new RunDriver.createGraphics(); g.loadImage(url[i],0,0); arr.push(g); } } if (name)Animation.framesMap[name]=arr; return arr; } Animation.clearCache=function(key){ var cache=Animation.framesMap; var val; var key2=key+"#"; for (val in cache){ if (val===key || val.indexOf(key2)==0){ delete Animation.framesMap[val]; } } } Animation.framesMap={}; return Animation; })(AnimationPlayerBase) /** *关键帧动画播放类。 */ //class laya.display.FrameAnimation extends laya.display.AnimationPlayerBase var FrameAnimation=(function(_super){ function FrameAnimation(){ /** *@private *id对象表 */ this._targetDic=null; /** *@private *动画数据 */ this._animationData=null; /**@private */ this._animationNewFrames=null; FrameAnimation.__super.call(this); if (FrameAnimation._sortIndexFun==null){ FrameAnimation._sortIndexFun=MathUtil.sortByKey("index",false,true); } } __class(FrameAnimation,'laya.display.FrameAnimation',_super); var __proto=FrameAnimation.prototype; /** *@private *初始化动画数据 *@param targetDic 对象表 *@param animationData 动画数据 * */ __proto._setUp=function(targetDic,animationData){ this._labels=null; this._animationNewFrames=null; this._targetDic=targetDic; this._animationData=animationData; this.interval=1000 / animationData.frameRate; if (animationData.parsed){ this._count=animationData.count; this._labels=animationData.labels; this._animationNewFrames=animationData.animationNewFrames; }else { this._animationNewFrames=[]; this._calculateDatas(); } animationData.parsed=true; animationData.labels=this._labels; animationData.count=this._count; animationData.animationNewFrames=this._animationNewFrames; } /**@inheritDoc */ __proto.clear=function(){ _super.prototype.clear.call(this); this._targetDic=null; this._animationData=null; } /**@inheritDoc */ __proto._displayToIndex=function(value){ if (!this._animationData)return; if (value < 0)value=0; if (value > this._count)value=this._count; var nodes=this._animationData.nodes,i=0,len=nodes.length; for (i=0;i < len;i++){ this._displayNodeToFrame(nodes[i],value); } } /** *@private *将节点设置到某一帧的状态 *@param node 节点ID *@param frame *@param targetDic 节点表 * */ __proto._displayNodeToFrame=function(node,frame,targetDic){ if (!targetDic)targetDic=this._targetDic; var target=targetDic[node.target]; if (!target){ return; }; var frames=node.frames,key,propFrames,value; var keys=node.keys,i=0,len=keys.length; for (i=0;i < len;i++){ key=keys[i]; propFrames=frames[key]; if (propFrames.length > frame){ value=propFrames[frame]; }else { value=propFrames[propFrames.length-1]; } target[key]=value; } } /** *@private *计算帧数据 * */ __proto._calculateDatas=function(){ if (!this._animationData)return; var nodes=this._animationData.nodes,i=0,len=nodes.length,tNode; this._count=0; for (i=0;i < len;i++){ tNode=nodes[i]; this._calculateNodeKeyFrames(tNode); } this._count+=1; } /** *@private *计算某个节点的帧数据 *@param node * */ __proto._calculateNodeKeyFrames=function(node){ var keyFrames=node.keyframes,key,tKeyFrames,target=node.target; if (!node.frames){ node.frames={}; } if (!node.keys){ node.keys=[]; }else { node.keys.length=0; } if (!node.initValues){ node.initValues={}; } for (key in keyFrames){ tKeyFrames=keyFrames[key]; if (!node.frames[key]){ node.frames[key]=[]; } if (this._targetDic && this._targetDic[target]){ node.initValues[key]=this._targetDic[target][key]; } tKeyFrames.sort(FrameAnimation._sortIndexFun); node.keys.push(key); this._calculateNodePropFrames(tKeyFrames,node.frames[key],key,target); } } /** *将动画控制对象还原到动画控制之前的状态 */ __proto.resetToInitState=function(){ if (!this._targetDic)return; if (!this._animationData)return; var nodes=this._animationData.nodes,i=0,len=nodes.length; var tNode; var initValues; for (i=0;i < len;i++){ tNode=nodes[i]; initValues=tNode.initValues; if (!initValues)continue ; var target=this._targetDic[tNode.target]; if (!target)continue ; var key; for (key in initValues){ target[key]=initValues[key]; } } } /** *@private *计算节点某个属性的帧数据 *@param keyframes *@param frames *@param key *@param target * */ __proto._calculateNodePropFrames=function(keyframes,frames,key,target){ var i=0,len=keyframes.length-1; frames.length=keyframes[len].index+1; for (i=0;i < len;i++){ this._dealKeyFrame(keyframes[i]); this._calculateFrameValues(keyframes[i],keyframes[i+1],frames); } if (len==0){ frames[keyframes[0].index]=keyframes[0].value; if (this._animationNewFrames) this._animationNewFrames[keyframes[0].index]=true; } this._dealKeyFrame(keyframes[i]); } /** *@private * */ __proto._dealKeyFrame=function(keyFrame){ if (keyFrame.label && keyFrame.label !="")this.addLabel(keyFrame.label,keyFrame.index); } /** *@private *计算两个关键帧直接的帧数据 *@param startFrame *@param endFrame *@param result * */ __proto._calculateFrameValues=function(startFrame,endFrame,result){ var i=0,easeFun; var start=startFrame.index,end=endFrame.index; var startValue=startFrame.value; var dValue=endFrame.value-startFrame.value; var dLen=end-start; if (end > this._count)this._count=end; if (startFrame.tween){ easeFun=Ease[startFrame.tweenMethod]; if (easeFun==null){ easeFun=Ease.linearNone; } for (i=start;i < end;i++){ result[i]=easeFun(i-start,startValue,dValue,dLen); if (this._animationNewFrames){ this._animationNewFrames[i]=true; } } }else { for (i=start;i < end;i++){ result[i]=startValue; } } if (this._animationNewFrames){ this._animationNewFrames[startFrame.index]=true; this._animationNewFrames[endFrame.index]=true; } result[endFrame.index]=endFrame.value; } FrameAnimation._sortIndexFun=null; return FrameAnimation; })(AnimationPlayerBase) /** *

    Input 类用于创建显示对象以显示和输入文本。

    *

    Input 类封装了原生的文本输入框,由于不同浏览器的差异,会导致此对象的默认文本的位置与用户点击输入时的文本的位置有少许的偏差。

    */ //class laya.display.Input extends laya.display.Text var Input=(function(_super){ function Input(){ /**@private */ this._focus=false; /**@private */ this._multiline=false; /**@private */ this._editable=true; /**@private */ this._restrictPattern=null; this._type="text"; /**输入提示符。*/ this._prompt=''; /**输入提示符颜色。*/ this._promptColor="#A9A9A9"; this._originColor="#000000"; this._content=''; Input.__super.call(this); this._maxChars=1E5; this._width=100; this._height=20; this.multiline=false; this.overflow=Text.SCROLL; this.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this._onMouseDown); this.on(/*laya.events.Event.UNDISPLAY*/"undisplay",this,this._onUnDisplay); } __class(Input,'laya.display.Input',_super); var __proto=Input.prototype; /** *设置光标位置和选取字符。 *@param startIndex 光标起始位置。 *@param endIndex 光标结束位置。 */ __proto.setSelection=function(startIndex,endIndex){ this.focus=true; laya.display.Input.inputElement.selectionStart=startIndex; laya.display.Input.inputElement.selectionEnd=endIndex; } __proto._onUnDisplay=function(e){ this.focus=false; } __proto._onMouseDown=function(e){ this.focus=true; } /** *在输入期间,如果 Input 实例的位置改变,调用_syncInputTransform同步输入框的位置。 */ __proto._syncInputTransform=function(){ var inputElement=this.nativeInput; var transform=Utils.getTransformRelativeToWindow(this,this.padding[3],this.padding[0]); var inputWid=this._width-this.padding[1]-this.padding[3]; var inputHei=this._height-this.padding[0]-this.padding[2]; if (Render.isConchApp){ inputElement.setScale(transform.scaleX,transform.scaleY); inputElement.setSize(inputWid,inputHei); inputElement.setPos(transform.x,transform.y); }else { Input.inputContainer.style.transform=Input.inputContainer.style.webkitTransform="scale("+transform.scaleX+","+transform.scaleY+") rotate("+(Laya.stage.canvasDegree)+"deg)"; inputElement.style.width=inputWid+'px'; inputElement.style.height=inputHei+'px'; Input.inputContainer.style.left=transform.x+'px'; Input.inputContainer.style.top=transform.y+'px'; } } /**选中当前实例的所有文本。*/ __proto.select=function(){ this.nativeInput.select(); } __proto._setInputMethod=function(){ Input.input.parentElement && (Input.inputContainer.removeChild(Input.input)); Input.area.parentElement && (Input.inputContainer.removeChild(Input.area)); Input.inputElement=(this._multiline ? Input.area :Input.input); Input.inputContainer.appendChild(Input.inputElement); if (Text.RightToLeft){ Input.inputElement.style.direction="rtl"; } } __proto._focusIn=function(){ laya.display.Input.isInputting=true; var input=this.nativeInput; this._focus=true; var cssStyle=input.style; cssStyle.whiteSpace=(this.wordWrap ? "pre-wrap" :"nowrap"); this._setPromptColor(); input.readOnly=!this._editable; if (Render.isConchApp){ input.setType(this._type); input.setForbidEdit(!this._editable); } input.maxLength=this._maxChars; var padding=this.padding; input.type=this._type; input.value=this._content; input.placeholder=this._prompt; Laya.stage.off(/*laya.events.Event.KEY_DOWN*/"keydown",this,this._onKeyDown); Laya.stage.on(/*laya.events.Event.KEY_DOWN*/"keydown",this,this._onKeyDown); Laya.stage.focus=this; this.event(/*laya.events.Event.FOCUS*/"focus"); if (Browser.onPC)input.focus(); if(!Browser.onMiniGame && !Browser.onBDMiniGame && !Browser.onQGMiniGame && !Browser.onVVMiniGame && !Browser.onBLMiniGame && !Browser.onAlipayMiniGame && !Browser.onTTMiniGame && !Browser.onHWMiniGame && !Browser.onTBMiniGame){ var temp=this._text; this._text=null; } this.typeset(); input.setColor(this._originColor); if(input.setBgColor) input.setBgColor(this.bgColor); input.setFontSize(this.fontSize); input.setFontFace(Browser.onIPhone ? (Text._fontFamilyMap[this.font] || this.font):this.font); if (Render.isConchApp){ input.setMultiAble && input.setMultiAble(this._multiline); } cssStyle.lineHeight=(this.leading+this.fontSize)+"px"; cssStyle.fontStyle=(this.italic ? "italic" :"normal"); cssStyle.fontWeight=(this.bold ? "bold" :"normal"); cssStyle.textAlign=this.align; cssStyle.padding="0 0"; this._syncInputTransform(); if (!Render.isConchApp && Browser.onPC) Laya.timer.frameLoop(1,this,this._syncInputTransform); } // 设置DOM输入框提示符颜色。 __proto._setPromptColor=function(){ Input.promptStyleDOM=Browser.getElementById("promptStyle"); if (!Input.promptStyleDOM){ Input.promptStyleDOM=Browser.createElement("style"); Input.promptStyleDOM.setAttribute("id","promptStyle"); Browser.document.head.appendChild(Input.promptStyleDOM); } Input.promptStyleDOM.innerText="input::-webkit-input-placeholder, textarea::-webkit-input-placeholder {"+"color:"+this._promptColor+"}"+"input:-moz-placeholder, textarea:-moz-placeholder {"+"color:"+this._promptColor+"}"+"input::-moz-placeholder, textarea::-moz-placeholder {"+"color:"+this._promptColor+"}"+"input:-ms-input-placeholder, textarea:-ms-input-placeholder {"+"color:"+this._promptColor+"}"; } /**@private */ __proto._focusOut=function(){ laya.display.Input.isInputting=false; this._focus=false; this._text=null; this._content=this.nativeInput.value; if (!this._content){ Laya.superSet(Text,this,'text',this._prompt); Laya.superSet(Text,this,'color',this._promptColor); }else { Laya.superSet(Text,this,'text',this._content); Laya.superSet(Text,this,'color',this._originColor); } Laya.stage.off(/*laya.events.Event.KEY_DOWN*/"keydown",this,this._onKeyDown); Laya.stage.focus=null; this.event(/*laya.events.Event.BLUR*/"blur"); if (Render.isConchApp)this.nativeInput.blur(); Browser.onPC && Laya.timer.clear(this,this._syncInputTransform); } /**@private */ __proto._onKeyDown=function(e){ if (e.keyCode===13){ if (Browser.onMobile && !this._multiline) this.focus=false; this.event(/*laya.events.Event.ENTER*/"enter"); } } __proto.changeText=function(text){ this._content=text; if (this._focus){ this.nativeInput.value=text || ''; this.event(/*laya.events.Event.CHANGE*/"change"); }else _super.prototype.changeText.call(this,text); } /**@inheritDoc */ __getset(0,__proto,'color',_super.prototype._$get_color,function(value){ if (this._focus) this.nativeInput.setColor(value); Laya.superSet(Text,this,'color',this._content?value:this._promptColor); this._originColor=value; }); //[Deprecated] __getset(0,__proto,'inputElementYAdjuster',function(){ console.warn("deprecated: 由于即使设置了该值,在各平台和浏览器之间也不一定一致,inputElementYAdjuster已弃用。"); return 0; },function(value){ console.warn("deprecated: 由于即使设置了该值,在各平台和浏览器之间也不一定一致,inputElementYAdjuster已弃用。"); }); /**表示是否是多行输入框。*/ __getset(0,__proto,'multiline',function(){ return this._multiline; },function(value){ this._multiline=value; this.valign=value ? "top" :"middle"; }); /** *

    字符数量限制,默认为10000。

    *

    设置字符数量限制时,小于等于0的值将会限制字符数量为10000。

    */ __getset(0,__proto,'maxChars',function(){ return this._maxChars; },function(value){ if (value <=0) value=1E5; this._maxChars=value; }); /**@inheritDoc */ __getset(0,__proto,'text',function(){ if (this._focus) return this.nativeInput.value; else return this._content || ""; },function(value){ Laya.superSet(Text,this,'color',this._originColor); value+=''; if (this._focus){ this.nativeInput.value=value || ''; this.event(/*laya.events.Event.CHANGE*/"change"); }else { if (!this._multiline) value=value.replace(/\r?\n/g,''); this._content=value; if (value) Laya.superSet(Text,this,'text',value); else { Laya.superSet(Text,this,'text',this._prompt); Laya.superSet(Text,this,'color',this.promptColor); } } }); /** *获取对输入框的引用实例。 */ __getset(0,__proto,'nativeInput',function(){ return this._multiline ? Input.area :Input.input; }); /** *设置输入提示符。 */ __getset(0,__proto,'prompt',function(){ return this._prompt; },function(value){ if (!this._text && value) Laya.superSet(Text,this,'color',this._promptColor); this.promptColor=this._promptColor; if (this._text) Laya.superSet(Text,this,'text',(this._text==this._prompt)?value:this._text); else Laya.superSet(Text,this,'text',value); this._prompt=Text.langPacks && Text.langPacks[value] ? Text.langPacks[value] :value; }); // 因此 调用focus接口是无法都在移动平台立刻弹出键盘的 /** *表示焦点是否在此实例上。 */ __getset(0,__proto,'focus',function(){ return this._focus; },function(value){ var input=this.nativeInput; if (this._focus!==value){ if (value){ if (input.target){ input.target._focusOut(); }else { this._setInputMethod(); } input.target=this; this._focusIn(); }else { input.target=null; this._focusOut(); Browser.document.body.scrollTop=0; input.blur(); if (Render.isConchApp){ input.setPos(-10000,-10000); }else if (Input.inputContainer.contains(input)) Input.inputContainer.removeChild(input); } } }); /**限制输入的字符。*/ __getset(0,__proto,'restrict',function(){ if (this._restrictPattern){ return this._restrictPattern.source; } return ""; },function(pattern){ if (pattern){ pattern="[^"+pattern+"]"; if (pattern.indexOf("^^")>-1) pattern=pattern.replace("^^",""); this._restrictPattern=new RegExp(pattern,"g"); }else this._restrictPattern=null; }); /** *是否可编辑。 */ __getset(0,__proto,'editable',function(){ return this._editable; },function(value){ this._editable=value; if (Render.isConchApp){ Input.input.setForbidEdit(!value); } }); /** *设置输入提示符颜色。 */ __getset(0,__proto,'promptColor',function(){ return this._promptColor; },function(value){ this._promptColor=value; if (!this._content)Laya.superSet(Text,this,'color',value); }); /** *

    输入框类型为Input静态常量之一。

    *
      *
    • TYPE_TEXT
    • *
    • TYPE_PASSWORD
    • *
    • TYPE_EMAIL
    • *
    • TYPE_URL
    • *
    • TYPE_NUMBER
    • *
    • TYPE_RANGE
    • *
    • TYPE_DATE
    • *
    • TYPE_MONTH
    • *
    • TYPE_WEEK
    • *
    • TYPE_TIME
    • *
    • TYPE_DATE_TIME
    • *
    • TYPE_DATE_TIME_LOCAL
    • *
    *

    平台兼容性参见http://www.w3school.com.cn/html5/html_5_form_input_types.asp。

    */ __getset(0,__proto,'type',function(){ return this._type; },function(value){ if (value=="password") this._getCSSStyle().password=true; else this._getCSSStyle().password=false; this._type=value; if (Render.isConchApp){ this.nativeInput.setType(value); } }); /** *

    原生输入框 X 轴调整值,用来调整输入框坐标。

    *

    由于即使设置了该值,在各平台和浏览器之间也不一定一致,inputElementXAdjuster已弃用。

    *@deprecated */ __getset(0,__proto,'inputElementXAdjuster',function(){ console.warn("deprecated: 由于即使设置了该值,在各平台和浏览器之间也不一定一致,inputElementXAdjuster已弃用。"); return 0; },function(value){ console.warn("deprecated: 由于即使设置了该值,在各平台和浏览器之间也不一定一致,inputElementXAdjuster已弃用。"); }); //[Deprecated(replacement="Input.type")] __getset(0,__proto,'asPassword',function(){ return this._getCSSStyle().password; },function(value){ this._getCSSStyle().password=value; this._type=/*CLASS CONST:laya.display.Input.TYPE_PASSWORD*/"password"; console.warn("deprecated: 使用type=\"password\"替代设置asPassword, asPassword将在下次重大更新时删去"); this.isChanged=true; }); Input.__init__=function(){ Input._createInputElement(); if (Browser.onMobile){ var isTrue=false; if (Browser.onMiniGame || Browser.onBDMiniGame || Browser.onKGMiniGame || Browser.onQGMiniGame || Browser.onVVMiniGame || Browser.onBLMiniGame || Browser.onAlipayMiniGame || Browser.onQQMiniGame || Browser.onTTMiniGame || Browser.onHWMiniGame||Browser.onTBMiniGame){ isTrue=true; } Render.canvas.addEventListener(Input.IOS_IFRAME ?(isTrue ? "touchend" :"click"):"touchend",Input._popupInputMethod); } } Input._popupInputMethod=function(e){ if (!laya.display.Input.isInputting)return; var input=laya.display.Input.inputElement; input.focus(); } Input._createInputElement=function(){ Input._initInput(Input.area=Browser.createElement("textarea")); Input._initInput(Input.input=Browser.createElement("input")); Input.inputContainer=Browser.createElement("div"); Input.inputContainer.style.position="absolute"; Input.inputContainer.style.zIndex=1E5; Browser.container.appendChild(Input.inputContainer); Input.inputContainer.setPos=function (x,y){Input.inputContainer.style.left=x+'px';Input.inputContainer.style.top=y+'px';}; } Input._initInput=function(input){ var style=input.style; style.cssText="position:absolute;overflow:hidden;resize:none;transform-origin:0 0;-webkit-transform-origin:0 0;-moz-transform-origin:0 0;-o-transform-origin:0 0;"; style.resize='none'; style.backgroundColor='transparent'; style.border='none'; style.outline='none'; style.zIndex=1; input.addEventListener('input',Input._processInputting); input.addEventListener('mousemove',Input._stopEvent); input.addEventListener('mousedown',Input._stopEvent); input.addEventListener('touchmove',Input._stopEvent); input.setFontFace=function (fontFace){input.style.fontFamily=fontFace;}; if(!Render.isConchApp){ input.setColor=function (color){input.style.color=color;}; input.setFontSize=function (fontSize){input.style.fontSize=fontSize+'px';}; } } Input._processInputting=function(e){ var input=laya.display.Input.inputElement.target; if (!input)return; var value=laya.display.Input.inputElement.value; if (input._restrictPattern){ value=value.replace(/\u2006|\x27/g,""); if (input._restrictPattern.test(value)){ value=value.replace(input._restrictPattern,""); laya.display.Input.inputElement.value=value; } } input._text=value; input.event(/*laya.events.Event.INPUT*/"input"); } Input._stopEvent=function(e){ if (e.type=='touchmove') e.preventDefault(); e.stopPropagation && e.stopPropagation(); } Input.TYPE_TEXT="text"; Input.TYPE_PASSWORD="password"; Input.TYPE_EMAIL="email"; Input.TYPE_URL="url"; Input.TYPE_NUMBER="number"; Input.TYPE_RANGE="range"; Input.TYPE_DATE="date"; Input.TYPE_MONTH="month"; Input.TYPE_WEEK="week"; Input.TYPE_TIME="time"; Input.TYPE_DATE_TIME="datetime"; Input.TYPE_DATE_TIME_LOCAL="datetime-local"; Input.TYPE_SEARCH="search"; Input.input=null; Input.area=null; Input.inputElement=null; Input.inputContainer=null; Input.confirmButton=null; Input.promptStyleDOM=null; Input.inputHeight=45; Input.isInputting=false; Input.stageMatrix=null; __static(Input, ['IOS_IFRAME',function(){return this.IOS_IFRAME=(Browser.onIOS && Browser.window.top !=Browser.window.self);} ]); return Input; })(Text) /** *@private *

    HTMLImage 用于创建 HTML Image 元素。

    *

    请使用 HTMLImage.create()获取新实例,不要直接使用 new HTMLImage

    */ //class laya.resource.HTMLImage extends laya.resource.FileBitmap var HTMLImage=(function(_super){ function HTMLImage(src,def){ /**异步加载锁*/ this._recreateLock=false; /**异步加载完成后是否需要释放(有可能在恢复过程中,再次被释放,用此变量做标记)*/ this._needReleaseAgain=false; this._enableMerageInAtlas=true; HTMLImage.__super.call(this); this._init_(src,def); } __class(HTMLImage,'laya.resource.HTMLImage',_super); var __proto=HTMLImage.prototype; __proto._init_=function(src,def){ this._src=src; this._source=new Browser.window.Image(); if (def){ def.onload && (this.onload=def.onload); def.onerror && (this.onerror=def.onerror); def.onCreate && def.onCreate(this); } if (src.indexOf("data:image")!=0)this._source.crossOrigin=""; (src)&& (this._source.src=src); } /** *@inheritDoc */ __proto.recreateResource=function(){ var _$this=this; if (this._src==="") throw new Error("src no null!"); this._needReleaseAgain=false; if (!this._source){ this._recreateLock=true; var _this=this; this._source=new Browser.window.Image(); this._source.crossOrigin=""; this._source.onload=function (){ if (_this._needReleaseAgain){ _this._needReleaseAgain=false; _this._source.onload=null; _this._source=null; return; } _this._source.onload=null; _this.memorySize=_$this._w *_$this._h *4; _this._recreateLock=false; _this.completeCreate(); }; this._source.src=this._src; }else { if (this._recreateLock) return; this.memorySize=this._w *this._h *4; this._recreateLock=false; this.completeCreate(); } } /** *@inheritDoc */ __proto.disposeResource=function(){ if (this._recreateLock) this._needReleaseAgain=true; (this._source)&& (this._source=null,this.memorySize=0); } /***调整尺寸。*/ __proto.onresize=function(){ this._w=this._source.width; this._h=this._source.height; } /** *@inheritDoc */ __getset(0,__proto,'onload',null,function(value){ var _$this=this; this._onload=value; this._source && (this._source.onload=this._onload !=null ? (function(){ _$this.onresize(); _$this._onload(); }):null); }); /** *@inheritDoc */ __getset(0,__proto,'onerror',null,function(value){ var _$this=this; this._onerror=value; this._source && (this._source.onerror=this._onerror !=null ? (function(){ _$this._onerror() }):null); }); __getset(0,__proto,'enableMerageInAtlas',function(){ return this._enableMerageInAtlas; },function(value){ this._enableMerageInAtlas=value; if (Render.isConchApp){ if (this._source)this._source.enableMerageInAtlas=value; } }); HTMLImage.create=function(src,def){ return new HTMLImage(src,def); } return HTMLImage; })(FileBitmap) /** *

    动效模板。用于为指定目标对象添加动画效果。每个动效有唯一的目标对象,而同一个对象可以添加多个动效。 当一个动效开始播放时,其他动效会自动停止播放。

    *

    可以通过LayaAir IDE创建。

    */ //class laya.display.EffectAnimation extends laya.display.FrameAnimation var EffectAnimation=(function(_super){ function EffectAnimation(){ /**@private */ this._target=null; /**@private */ this._playEvents=null; /**@private */ this._initData={}; /**@private */ this._aniKeys=null; /**@private */ this._effectClass=null; EffectAnimation.__super.call(this); } __class(EffectAnimation,'laya.display.EffectAnimation',_super); var __proto=EffectAnimation.prototype; /**@private */ __proto._onOtherBegin=function(effect){ if (effect==this) return; this.stop(); } /**@private */ __proto.addEvent=function(){ if (!this._target || !this._playEvents) return; this._setControlNode(this._target); this._target.on(this._playEvents,this,this._onPlayAction); } /**@private */ __proto._onPlayAction=function(){ this.play(0,false); } __proto.play=function(start,loop,name,showWarn){ (start===void 0)&& (start=0); (loop===void 0)&& (loop=true); (name===void 0)&& (name=""); (showWarn===void 0)&& (showWarn=true); if (!this._target) return; this._target.event("effectanimationbegin",[this]); this._recordInitData(); laya.display.AnimationPlayerBase.prototype.play.call(this,start,loop,name,showWarn); } /**@private */ __proto._recordInitData=function(){ if (!this._aniKeys) return; var i=0,len=0; len=this._aniKeys.length; var key; for (i=0;i < len;i++){ key=this._aniKeys[i]; this._initData[key]=this._target[key]; } } /**@private */ __proto._displayToIndex=function(value){ if (!this._animationData) return; if (value < 0) value=0; if (value > this._count) value=this._count; var nodes=this._animationData.nodes,i=0,len=nodes.length; len=len > 1 ? 1 :len; for (i=0;i < len;i++){ this._displayNodeToFrame(nodes[i],value); } } /**@private */ __proto._displayNodeToFrame=function(node,frame,targetDic){ if (!this._target) return; var target; target=this._target; var frames=node.frames,key,propFrames,value; var keys=node.keys,i=0,len=keys.length; var secondFrames; secondFrames=node.secondFrames; var tSecondFrame=0; var easeFun; var tKeyFrames; var startFrame; var endFrame; for (i=0;i < len;i++){ key=keys[i]; propFrames=frames[key]; tSecondFrame=secondFrames[key]; if (tSecondFrame==-1){ value=this._initData[key]; }else { if (frame < tSecondFrame){ tKeyFrames=node.keyframes[key]; startFrame=tKeyFrames[0]; if (startFrame.tween){ easeFun=Ease[startFrame.tweenMethod]; if (easeFun==null){ easeFun=Ease.linearNone; } endFrame=tKeyFrames[1]; value=easeFun(frame,this._initData[key],endFrame.value-this._initData[key],endFrame.index); }else { value=this._initData[key]; } }else { if (propFrames.length > frame){ value=propFrames[frame]; }else { value=propFrames[propFrames.length-1]; } } } target[key]=value; } } /**@private */ __proto._calculateNodeKeyFrames=function(node){ _super.prototype._calculateNodeKeyFrames.call(this,node); var keyFrames=node.keyframes,key,tKeyFrames,target=node.target; var secondFrames; secondFrames={}; node.secondFrames=secondFrames; for (key in keyFrames){ tKeyFrames=keyFrames[key]; if (tKeyFrames.length <=1){ secondFrames[key]=-1; }else { secondFrames[key]=tKeyFrames[1].index; } } } /** *本实例的目标对象。通过本实例控制目标对象的属性变化。 *@param v 指定的目标对象。 */ __getset(0,__proto,'target',function(){ return this._target; },function(v){ if (this._target){ this._target.off("effectanimationbegin",this,this._onOtherBegin); } this._target=v; if (this._target){ this._target.on("effectanimationbegin",this,this._onOtherBegin); } this.addEvent(); }); /** *设置开始播放的事件。本实例会侦听目标对象的指定事件,触发后播放相应动画效果。 *@param event */ __getset(0,__proto,'playEvent',null,function(event){ this._playEvents=event; if (!event) return; this.addEvent(); }); /** *设置动画数据。 *@param uiData */ __getset(0,__proto,'effectData',null,function(uiData){ if (uiData){ var aniData; aniData=uiData["animations"]; if (aniData && aniData[0]){ this._setUp({},aniData[0]); if (aniData[0].nodes && aniData[0].nodes[0]){ this._aniKeys=aniData[0].nodes[0].keys; } } } }); /** *设置提供数据的类。 *@param classStr 类路径 */ __getset(0,__proto,'effectClass',null,function(classStr){ this._effectClass=ClassUtils.getClass(classStr); if (this._effectClass){ var uiData; uiData=this._effectClass["uiView"]; if (uiData){ var aniData; aniData=uiData["animations"]; if (aniData && aniData[0]){ this._setUp({},aniData[0]); if (aniData[0].nodes && aniData[0].nodes[0]){ this._aniKeys=aniData[0].nodes[0].keys; } } } } }); EffectAnimation.EffectAnimationBegin="effectanimationbegin"; return EffectAnimation; })(FrameAnimation) /** *@private */ //class laya.utils.GraphicAnimation extends laya.display.FrameAnimation var GraphicAnimation=(function(_super){ var GraphicNode; function GraphicAnimation(){ /** *@private */ this.animationList=null; /** *@private */ this.animationDic=null; /** *@private */ this._nodeList=null; /** *@private */ this._nodeDefaultProps=null; /** *@private */ this._gList=null; /** *@private */ this._nodeIDAniDic={}; this._rootNode=null; this._nodeGDic=null; GraphicAnimation.__super.call(this); } __class(GraphicAnimation,'laya.utils.GraphicAnimation',_super); var __proto=GraphicAnimation.prototype; /** *@private */ __proto._parseNodeList=function(uiView){ if (!this._nodeList){ this._nodeList=[]; } this._nodeDefaultProps[uiView.compId]=uiView.props; if (uiView.compId) this._nodeList.push(uiView.compId); var childs=uiView.child; if (childs){ var i=0,len=childs.length; for (i=0;i < len;i++){ this._parseNodeList(childs[i]); } } } /** *@private */ __proto._calGraphicData=function(aniData){ this._setUp(null,aniData); this._createGraphicData(); if (this._nodeIDAniDic){ var key; for (key in this._nodeIDAniDic){ this._nodeIDAniDic[key]=null; } } } /** *@private */ __proto._createGraphicData=function(){ var gList=[]; var i=0,len=this.count; var animationDataNew=this._animationNewFrames; if (!animationDataNew)animationDataNew=[]; var preGraphic; for (i=0;i < len;i++){ if (animationDataNew[i] || !preGraphic){ preGraphic=this._createFrameGraphic(i); } gList.push(preGraphic); } this._gList=gList; } /** *@private */ __proto._createFrameGraphic=function(frame){ var g=RunDriver.createGraphics(); if (!GraphicAnimation._rootMatrix) GraphicAnimation._rootMatrix=new Matrix(); this._updateNodeGraphic(this._rootNode,frame,GraphicAnimation._rootMatrix,g); return g; } __proto._updateNodeGraphic=function(node,frame,parentTransfrom,g,alpha){ (alpha===void 0)&& (alpha=1); var tNodeG; tNodeG=this._nodeGDic[node.compId]=this._getNodeGraphicData(node.compId,frame,this._nodeGDic[node.compId]); var tGraphicAlpha=tNodeG.alpha *alpha; if (tGraphicAlpha < 0.01)return; if (!tNodeG.resultTransform){ tNodeG.resultTransform=Matrix.create(); }; var tResultTransform; tResultTransform=tNodeG.resultTransform; Matrix.mul(tNodeG.transform,parentTransfrom,tResultTransform); var tTex; if (tNodeG.skin){ tTex=this._getTextureByUrl(tNodeG.skin); if (tTex){ if (tResultTransform._checkTransform()){ g.drawTexture(tTex,0,0,tNodeG.width,tNodeG.height,tResultTransform,tGraphicAlpha); tNodeG.resultTransform=null; }else { g.drawTexture(tTex,tResultTransform.tx,tResultTransform.ty,tNodeG.width,tNodeG.height,null,tGraphicAlpha); } } }; var childs; childs=node.child; if (!childs) return; var i=0,len=0; len=childs.length; for (i=0;i < len;i++){ this._updateNodeGraphic(childs[i],frame,tResultTransform,g,tGraphicAlpha); } } __proto._updateNoChilds=function(tNodeG,g){ if (!tNodeG.skin) return; var tTex=this._getTextureByUrl(tNodeG.skin); if (!tTex) return; var tTransform=tNodeG.transform; tTransform._checkTransform(); var onlyTranslate=false; onlyTranslate=!tTransform.bTransform; if (!onlyTranslate){ g.drawTexture(tTex,0,0,tNodeG.width,tNodeG.height,tTransform.clone(),tNodeG.alpha); }else { g.drawTexture(tTex,tTransform.tx,tTransform.ty,tNodeG.width,tNodeG.height,null,tNodeG.alpha); } } __proto._updateNodeGraphic2=function(node,frame,g){ var tNodeG; tNodeG=this._nodeGDic[node.compId]=this._getNodeGraphicData(node.compId,frame,this._nodeGDic[node.compId]); if (!node.child){ this._updateNoChilds(tNodeG,g); return; }; var tTransform=tNodeG.transform; tTransform._checkTransform(); var onlyTranslate=false; onlyTranslate=!tTransform.bTransform; var hasTrans=false; hasTrans=onlyTranslate && (tTransform.tx !=0 || tTransform.ty !=0); var ifSave=false; ifSave=(tTransform.bTransform)|| tNodeG.alpha !=1; if (ifSave){ g.save(); } if (tNodeG.alpha !=1){ g.alpha(tNodeG.alpha); } if (!onlyTranslate){ g.transform(tTransform.clone()); }else if (hasTrans){ g.translate(tTransform.tx,tTransform.ty); }; var childs; childs=node.child; var tTex; if (tNodeG.skin){ tTex=this._getTextureByUrl(tNodeG.skin); if (tTex){ g.drawTexture(tTex,0,0,tNodeG.width,tNodeG.height); } } if (childs){ var i=0,len=0; len=childs.length; for (i=0;i < len;i++){ this._updateNodeGraphic2(childs[i],frame,g); } } if (ifSave){ g.restore(); }else { if (!onlyTranslate){ g.transform(tTransform.clone().invert()); }else if (hasTrans){ g.translate(-tTransform.tx,-tTransform.ty); } } } /** *@private */ __proto._calculateNodeKeyFrames=function(node){ _super.prototype._calculateNodeKeyFrames.call(this,node); this._nodeIDAniDic[node.target]=node; } /** *@private */ __proto.getNodeDataByID=function(nodeID){ return this._nodeIDAniDic[nodeID]; } /** *@private */ __proto._getParams=function(obj,params,frame,obj2){ var rst=GraphicAnimation._temParam; rst.length=params.length; var i=0,len=params.length; for (i=0;i < len;i++){ rst[i]=this._getObjVar(obj,params[i][0],frame,params[i][1],obj2); } return rst; } /** *@private */ __proto._getObjVar=function(obj,key,frame,noValue,obj2){ if (obj.hasOwnProperty(key)){ var vArr=obj[key]; if (frame >=vArr.length) frame=vArr.length-1; if(obj[key][frame]!=undefined) return obj[key][frame]; } if (obj2.hasOwnProperty(key)){ return obj2[key]; } return noValue; } __proto._getNodeGraphicData=function(nodeID,frame,rst){ if (!rst) rst=GraphicNode.create(); if (!rst.transform){ rst.transform=Matrix.create(); }else{ rst.transform.identity(); }; var node=this.getNodeDataByID(nodeID); if (!node) return rst; var frameData=node.frames; var params=this._getParams(frameData,GraphicAnimation._drawTextureCmd,frame,this._nodeDefaultProps[nodeID]); var url=params[0]; var width=NaN,height=NaN; var px=params[5],py=params[6]; var aX=params[13],aY=params[14]; var sx=params[7],sy=params[8]; var rotate=params[9]; var skewX=params[11],skewY=params[12] width=params[3]; height=params[4]; if (width==0 || height==0)url=null; if (width==-1)width=0; if (height==-1)height=0; var tex; rst.skin=url; rst.width=width; rst.height=height; if (url){ tex=this._getTextureByUrl(url); if (tex){ if (!width) width=tex.sourceWidth; if (!height) height=tex.sourceHeight; }else { console.warn("lost skin:",url,",you may load pics first"); } } rst.alpha=params[10]; var m; m=rst.transform; if (aX !=0){ px=aX *width; } if (aY !=0){ py=aY *height; } if (px !=0 || py !=0){ m.translate(-px,-py); }; var tm=null; if (rotate || sx!==1 || sy!==1 || skewX || skewY){ tm=GraphicAnimation._tempMt; tm.identity(); tm.bTransform=true; var skx=(rotate-skewX)*0.0174532922222222; var sky=(rotate+skewY)*0.0174532922222222; var cx=Math.cos(sky); var ssx=Math.sin(sky); var cy=Math.sin(skx); var ssy=Math.cos(skx); tm.a=sx *cx; tm.b=sx *ssx; tm.c=-sy *cy; tm.d=sy *ssy; tm.tx=tm.ty=0; } if (tm){ m=Matrix.mul(m,tm,m); } m.translate(params[1],params[2]); return rst; } /** *@private */ __proto._getTextureByUrl=function(url){ return Loader.getRes(url); } /** *@private */ __proto.setAniData=function(uiView,aniName){ if (uiView.animations){ this._nodeDefaultProps={}; this._nodeGDic={}; if (this._nodeList) this._nodeList.length=0; this._rootNode=uiView; this._parseNodeList(uiView); var aniDic={}; var anilist=[]; var animations=uiView.animations; var i=0,len=animations.length; var tAniO; for (i=0;i < len;i++){ tAniO=animations[i]; this._labels=null; if (aniName && aniName !=tAniO.name){ continue ; } if (!tAniO) continue ; try { this._calGraphicData(tAniO); }catch (e){ console.warn("parse animation fail:"+tAniO.name+",empty animation created"); this._gList=[]; }; var frameO={}; frameO.interval=1000 / tAniO["frameRate"]; frameO.frames=this._gList; frameO.labels=this._labels; frameO.name=tAniO.name; anilist.push(frameO); aniDic[tAniO.name]=frameO; } this.animationList=anilist; this.animationDic=aniDic; } GraphicAnimation._temParam.length=0; } __proto.parseByData=function(aniData){ var rootNode,aniO; rootNode=aniData.nodeRoot; aniO=aniData.aniO; delete aniData.nodeRoot; delete aniData.aniO; this._nodeDefaultProps={}; this._nodeGDic={}; if (this._nodeList) this._nodeList.length=0; this._rootNode=rootNode; this._parseNodeList(rootNode); this._labels=null; try { this._calGraphicData(aniO); }catch (e){ console.warn("parse animation fail:"+aniO.name+",empty animation created"); this._gList=[]; }; var frameO=aniData; frameO.interval=1000 / aniO["frameRate"]; frameO.frames=this._gList; frameO.labels=this._labels; frameO.name=aniO.name; return frameO; } /** *@private */ __proto.setUpAniData=function(uiView){ if (uiView.animations){ var aniDic={}; var anilist=[]; var animations=uiView.animations; var i=0,len=animations.length; var tAniO; for (i=0;i < len;i++){ tAniO=animations[i]; if (!tAniO) continue ; var frameO={}; frameO.name=tAniO.name; frameO.aniO=tAniO; frameO.nodeRoot=uiView; anilist.push(frameO); aniDic[tAniO.name]=frameO; } this.animationList=anilist; this.animationDic=aniDic; } } /** *@private */ __proto._clear=function(){ this.animationList=null; this.animationDic=null; this._gList=null; if (this._nodeGDic){ var key; var tGNode; for (key in this._nodeGDic){ tGNode=this._nodeGDic[key]; if (tGNode)tGNode.recover(); } } this._nodeGDic=null; } GraphicAnimation.parseAnimationByData=function(animationObject){ if (!GraphicAnimation._I) GraphicAnimation._I=new GraphicAnimation(); var rst; rst=GraphicAnimation._I.parseByData(animationObject); GraphicAnimation._I._clear(); return rst; } GraphicAnimation.parseAnimationData=function(aniData){ if (!GraphicAnimation._I) GraphicAnimation._I=new GraphicAnimation(); GraphicAnimation._I.setUpAniData(aniData); var rst; rst={}; rst.animationList=GraphicAnimation._I.animationList; rst.animationDic=GraphicAnimation._I.animationDic; GraphicAnimation._I._clear(); return rst; } GraphicAnimation._drawTextureCmd=[["skin",null],["x",0],["y",0],["width",-1],["height",-1],["pivotX",0],["pivotY",0],["scaleX",1],["scaleY",1],["rotation",0],["alpha",1],["skewX",0],["skewY",0],["anchorX",0],["anchorY",0]]; GraphicAnimation._temParam=[]; GraphicAnimation._I=null; GraphicAnimation._rootMatrix=null; __static(GraphicAnimation, ['_tempMt',function(){return this._tempMt=new Matrix();} ]); GraphicAnimation.__init$=function(){ //class GraphicNode GraphicNode=(function(){ function GraphicNode(){ this.skin=null; this.transform=null; this.resultTransform=null; this.width=NaN; this.height=NaN; this.alpha=1; } __class(GraphicNode,''); var __proto=GraphicNode.prototype; __proto.recover=function(){ this.skin=null; this.width=0; this.height=0; this.alpha=1; if (this.transform){ this.transform.destroy(); this.transform=null; } if (this.resultTransform){ this.resultTransform.destroy(); this.resultTransform=null; } Pool.recover("GraphicNode",this); } GraphicNode.create=function(){ return Pool.getItemByClass("GraphicNode",GraphicNode); } return GraphicNode; })() } return GraphicAnimation; })(FrameAnimation) Laya.__init([EventDispatcher,LoaderManager,GraphicAnimation,Render,Browser,Timer,LocalStorage,TimeLine]); })(window,document,Laya); (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; //class LayaMain var LayaMain=(function(){ /*[COMPILER OPTIONS:normal]*/ function LayaMain(){} __class(LayaMain,'LayaMain'); return LayaMain; })() /**LayaGameStart**/ new LayaMain(); })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.d3.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var AnimationContent=laya.ani.AnimationContent,AnimationPlayer=laya.ani.AnimationPlayer,AnimationState=laya.ani.AnimationState; var AnimationTemplet=laya.ani.AnimationTemplet,Arith=laya.maths.Arith,AtlasResourceManager=laya.webgl.atlas.AtlasResourceManager; var BaseShader=laya.webgl.shader.BaseShader,Browser=laya.utils.Browser,Buffer=laya.webgl.utils.Buffer,Byte=laya.utils.Byte; var CacheAbleSkinMesh=laya.ani.bone.canvasmesh.CacheAbleSkinMesh,ClassUtils=laya.utils.ClassUtils,Config=Laya.Config; var Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher,Handler=laya.utils.Handler,Loader=laya.net.Loader; var LoaderManager=laya.net.LoaderManager,MathUtil=laya.maths.MathUtil,Node=laya.display.Node,Render=laya.renders.Render; var RenderContext=laya.renders.RenderContext,RenderSprite=laya.renders.RenderSprite,RenderState2D=laya.webgl.utils.RenderState2D; var Resource=laya.resource.Resource,RunDriver=laya.utils.RunDriver,Shader=laya.webgl.shader.Shader,ShaderCompile=laya.webgl.utils.ShaderCompile; var Sprite=laya.display.Sprite,Stat=laya.utils.Stat,StringKey=laya.utils.StringKey,Style=laya.display.css.Style; var Texture=laya.resource.Texture,URL=laya.net.URL,Utils=laya.utils.Utils,WebGL=laya.webgl.WebGL,WebGLContext=laya.webgl.WebGLContext; var WebGLContext2D=laya.webgl.canvas.WebGLContext2D; Laya.interface('laya.d3.core.IClone'); Laya.interface('laya.d3.graphics.IVertex'); Laya.interface('laya.d3.core.render.IUpdate'); Laya.interface('laya.d3.core.scene.ITreeNode'); Laya.interface('laya.d3.core.render.IRenderable'); /** *@private */ //class laya.d3.animation.AnimationClipParser01 var AnimationClipParser01=(function(){ function AnimationClipParser01(){} __class(AnimationClipParser01,'laya.d3.animation.AnimationClipParser01'); AnimationClipParser01.READ_DATA=function(){ AnimationClipParser01._DATA.offset=AnimationClipParser01._reader.getUint32(); AnimationClipParser01._DATA.size=AnimationClipParser01._reader.getUint32(); } AnimationClipParser01.READ_BLOCK=function(){ var count=AnimationClipParser01._BLOCK.count=AnimationClipParser01._reader.getUint16(); var blockStarts=AnimationClipParser01._BLOCK.blockStarts=[]; var blockLengths=AnimationClipParser01._BLOCK.blockLengths=[]; for (var i=0;i < count;i++){ blockStarts.push(AnimationClipParser01._reader.getUint32()); blockLengths.push(AnimationClipParser01._reader.getUint32()); } } AnimationClipParser01.READ_STRINGS=function(){ var offset=AnimationClipParser01._reader.getUint32(); var count=AnimationClipParser01._reader.getUint16(); var prePos=AnimationClipParser01._reader.pos; AnimationClipParser01._reader.pos=offset+AnimationClipParser01._DATA.offset; for (var i=0;i < count;i++) AnimationClipParser01._strings[i]=AnimationClipParser01._reader.readUTFString(); AnimationClipParser01._reader.pos=prePos; } AnimationClipParser01.parse=function(clip,reader){ AnimationClipParser01._animationClip=clip; AnimationClipParser01._reader=reader; var arrayBuffer=reader.__getBuffer(); AnimationClipParser01.READ_DATA(); AnimationClipParser01.READ_BLOCK(); AnimationClipParser01.READ_STRINGS(); for (var i=0,n=AnimationClipParser01._BLOCK.count;i < n;i++){ var index=reader.getUint16(); var blockName=AnimationClipParser01._strings[index]; var fn=AnimationClipParser01["READ_"+blockName]; if (fn==null) throw new Error("model file err,no this function:"+index+" "+blockName); else fn.call(); } } AnimationClipParser01.READ_ANIMATIONS=function(){ var i=0,j=0; var node; var reader=AnimationClipParser01._reader; var buffer=reader.__getBuffer(); var lengthTypes=[]; var lenghthTypeCount=reader.getUint8(); lengthTypes.length=lenghthTypeCount; for (i=0;i < lenghthTypeCount;i++) lengthTypes[i]=reader.getUint16(); var startTimeTypes=[]; var startTimeTypeCount=reader.getUint16(); startTimeTypes.length=startTimeTypeCount; for (i=0;i < startTimeTypeCount;i++) startTimeTypes[i]=reader.getFloat32(); var clip=AnimationClipParser01._animationClip; clip.name=AnimationClipParser01._strings[reader.getUint16()]; var clipDur=clip._duration=reader.getFloat32(); clip.islooping=!!reader.getByte(); clip._frameRate=reader.getInt16(); var nodeCount=reader.getInt16(); var nodes=clip._nodes=new Array; nodes.length=nodeCount; var publicDatas=clip._publicClipDatas=[]; publicDatas.length=nodeCount; var nodesMap=clip._nodesMap={}; var cachePropertyToNodeIndex=0,unCachePropertyToNodeIndex=0; for (i=0;i < nodeCount;i++){ node=nodes[i]=new KeyframeNode(); var pathLength=reader.getUint16(); var path=node.path=[]; path.length=pathLength; for (j=0;j < pathLength;j++) path[j]=AnimationClipParser01._strings[reader.getUint16()]; var nodePath=path.join("/"); var mapArray=nodesMap[nodePath]; (mapArray)|| (nodesMap[nodePath]=mapArray=[]); mapArray.push(node); var componentTypeStrIndex=reader.getInt16(); (componentTypeStrIndex!==-1)&& (node.componentType=AnimationClipParser01._strings[componentTypeStrIndex]); var propertyNameID=AnimationNode._propertyIndexDic[AnimationClipParser01._strings[reader.getUint16()]]; if (propertyNameID !=null){ var isTransformProperty=propertyNameID < 4; var cacheProperty=!isTransformProperty || (isTransformProperty && path[0]===""); node._cacheProperty=cacheProperty; if (cacheProperty) cachePropertyToNodeIndex++; else unCachePropertyToNodeIndex++; node.propertyNameID=propertyNameID; }else { throw new Error("AnimationClipParser01:unknown property name."); }; var dataLength=lengthTypes[reader.getUint8()]; node.keyFrameWidth=dataLength / 4; var keyFrames=node.keyFrames=[]; var keyframeCount=keyFrames.length=reader.getUint16(); var lastKeyFrame=null; var startTime=NaN; for (j=0;j < keyframeCount;j++){ var keyFrame=keyFrames[j]=new Keyframe(); startTime=keyFrame.startTime=startTimeTypes[reader.getUint16()]; var offset=reader.pos; keyFrame.inTangent=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; offset=reader.pos; keyFrame.outTangent=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; offset=reader.pos; keyFrame.data=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; if (lastKeyFrame){ lastKeyFrame.next=keyFrame; lastKeyFrame.duration=startTime-lastKeyFrame.startTime; } lastKeyFrame=keyFrame; } keyFrame.next=null; keyFrame.duration=clipDur-startTime; }; var nodeToCachePropertyMap=clip._nodeToCachePropertyMap=new Int32Array(nodeCount); var cachePropertyToNodeMap=clip._cachePropertyMap=new Int32Array(cachePropertyToNodeIndex); var unCachePropertyToNodeMap=clip._unCachePropertyMap=new Int32Array(unCachePropertyToNodeIndex); cachePropertyToNodeIndex=unCachePropertyToNodeIndex=0; for (i=0;i < nodeCount;i++){ node=nodes[i]; if (node._cacheProperty){ nodeToCachePropertyMap[i]=cachePropertyToNodeIndex; cachePropertyToNodeMap[cachePropertyToNodeIndex++]=i; }else { unCachePropertyToNodeMap[unCachePropertyToNodeIndex++]=i; } } } AnimationClipParser01._animationClip=null; AnimationClipParser01._reader=null; AnimationClipParser01._strings=[]; __static(AnimationClipParser01, ['_BLOCK',function(){return this._BLOCK={count:0};},'_DATA',function(){return this._DATA={offset:0,size:0};} ]); return AnimationClipParser01; })() /** *@private */ //class laya.d3.animation.AnimationClipParser02 var AnimationClipParser02=(function(){ function AnimationClipParser02(){} __class(AnimationClipParser02,'laya.d3.animation.AnimationClipParser02'); AnimationClipParser02.READ_DATA=function(){ AnimationClipParser02._DATA.offset=AnimationClipParser02._reader.getUint32(); AnimationClipParser02._DATA.size=AnimationClipParser02._reader.getUint32(); } AnimationClipParser02.READ_BLOCK=function(){ var count=AnimationClipParser02._BLOCK.count=AnimationClipParser02._reader.getUint16(); var blockStarts=AnimationClipParser02._BLOCK.blockStarts=[]; var blockLengths=AnimationClipParser02._BLOCK.blockLengths=[]; for (var i=0;i < count;i++){ blockStarts.push(AnimationClipParser02._reader.getUint32()); blockLengths.push(AnimationClipParser02._reader.getUint32()); } } AnimationClipParser02.READ_STRINGS=function(){ var offset=AnimationClipParser02._reader.getUint32(); var count=AnimationClipParser02._reader.getUint16(); var prePos=AnimationClipParser02._reader.pos; AnimationClipParser02._reader.pos=offset+AnimationClipParser02._DATA.offset; for (var i=0;i < count;i++) AnimationClipParser02._strings[i]=AnimationClipParser02._reader.readUTFString(); AnimationClipParser02._reader.pos=prePos; } AnimationClipParser02.parse=function(clip,reader){ AnimationClipParser02._animationClip=clip; AnimationClipParser02._reader=reader; var arrayBuffer=reader.__getBuffer(); AnimationClipParser02.READ_DATA(); AnimationClipParser02.READ_BLOCK(); AnimationClipParser02.READ_STRINGS(); for (var i=0,n=AnimationClipParser02._BLOCK.count;i < n;i++){ var index=reader.getUint16(); var blockName=AnimationClipParser02._strings[index]; var fn=AnimationClipParser02["READ_"+blockName]; if (fn==null) throw new Error("model file err,no this function:"+index+" "+blockName); else fn.call(); } } AnimationClipParser02.READ_ANIMATIONS=function(){ var i=0,j=0; var node; var reader=AnimationClipParser02._reader; var buffer=reader.__getBuffer(); var lengthTypes=[]; var lenghthTypeCount=reader.getUint8(); lengthTypes.length=lenghthTypeCount; for (i=0;i < lenghthTypeCount;i++) lengthTypes[i]=reader.getUint16(); var startTimeTypes=[]; var startTimeTypeCount=reader.getUint16(); startTimeTypes.length=startTimeTypeCount; for (i=0;i < startTimeTypeCount;i++) startTimeTypes[i]=reader.getFloat32(); var clip=AnimationClipParser02._animationClip; clip.name=AnimationClipParser02._strings[reader.getUint16()]; var clipDur=clip._duration=reader.getFloat32(); clip.islooping=!!reader.getByte(); clip._frameRate=reader.getInt16(); var nodeCount=reader.getInt16(); var nodes=clip._nodes=new Array; nodes.length=nodeCount; var publicDatas=clip._publicClipDatas=[]; publicDatas.length=nodeCount; var nodesMap=clip._nodesMap={}; var cachePropertyToNodeIndex=0,unCachePropertyToNodeIndex=0; for (i=0;i < nodeCount;i++){ node=nodes[i]=new KeyframeNode(); var pathLength=reader.getUint16(); var path=node.path=[]; path.length=pathLength; for (j=0;j < pathLength;j++) path[j]=AnimationClipParser02._strings[reader.getUint16()]; var nodePath=path.join("/"); var mapArray=nodesMap[nodePath]; (mapArray)|| (nodesMap[nodePath]=mapArray=[]); mapArray.push(node); var componentTypeStrIndex=reader.getInt16(); (componentTypeStrIndex!==-1)&& (node.componentType=AnimationClipParser02._strings[componentTypeStrIndex]); var propertyNameID=AnimationNode._propertyIndexDic[AnimationClipParser02._strings[reader.getUint16()]]; if (propertyNameID !=null){ var isTransformProperty=propertyNameID < 4; var cacheProperty=!isTransformProperty || (isTransformProperty && path[0]===""); node._cacheProperty=cacheProperty; if (cacheProperty) cachePropertyToNodeIndex++; else unCachePropertyToNodeIndex++; node.propertyNameID=propertyNameID; }else { throw new Error("AnimationClipParser02:unknown property name."); }; var dataLength=lengthTypes[reader.getUint8()]; node.keyFrameWidth=dataLength / 4; var keyFrames=node.keyFrames=[]; var keyframeCount=keyFrames.length=reader.getUint16(); var lastKeyFrame=null; var startTime=NaN; for (j=0;j < keyframeCount;j++){ var keyFrame=keyFrames[j]=new Keyframe(); startTime=keyFrame.startTime=startTimeTypes[reader.getUint16()]; var offset=reader.pos; keyFrame.inTangent=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; offset=reader.pos; keyFrame.outTangent=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; offset=reader.pos; keyFrame.data=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; if (lastKeyFrame){ lastKeyFrame.next=keyFrame; lastKeyFrame.duration=startTime-lastKeyFrame.startTime; } lastKeyFrame=keyFrame; } keyFrame.next=null; keyFrame.duration=clipDur-startTime; }; var eventCount=reader.getUint16(); for (i=0;i < eventCount;i++){ var event=new AnimationEvent(); event.time=reader.getFloat32(); event.eventName=AnimationClipParser02._strings[reader.getUint16()]; var params; var paramCount=reader.getUint16(); (paramCount > 0)&& (event.params=params=[]); for (j=0;j < paramCount;j++){ var type=reader.getByte(); switch (type){ case 0: params.push(!!reader.getByte()); break ; case 1: params.push(reader.getInt32()); break ; case 2: params.push(reader.getFloat32()); break ; case 3: params.push(AnimationClipParser02._strings[reader.getUint16()]); break ; default : throw new Error("unknown type."); } } clip.addEvent(event); }; var nodeToCachePropertyMap=clip._nodeToCachePropertyMap=new Int32Array(nodeCount); var cachePropertyToNodeMap=clip._cachePropertyMap=new Int32Array(cachePropertyToNodeIndex); var unCachePropertyToNodeMap=clip._unCachePropertyMap=new Int32Array(unCachePropertyToNodeIndex); cachePropertyToNodeIndex=unCachePropertyToNodeIndex=0; for (i=0;i < nodeCount;i++){ node=nodes[i]; if (node._cacheProperty){ nodeToCachePropertyMap[i]=cachePropertyToNodeIndex; cachePropertyToNodeMap[cachePropertyToNodeIndex++]=i; }else { unCachePropertyToNodeMap[unCachePropertyToNodeIndex++]=i; } } } AnimationClipParser02._animationClip=null; AnimationClipParser02._reader=null; AnimationClipParser02._strings=[]; __static(AnimationClipParser02, ['_BLOCK',function(){return this._BLOCK={count:0};},'_DATA',function(){return this._DATA={offset:0,size:0};} ]); return AnimationClipParser02; })() /** *AnimationEvent 类用于实现动画事件。 */ //class laya.d3.animation.AnimationEvent var AnimationEvent=(function(){ function AnimationEvent(){ /**事件触发时间。*/ this.time=NaN; /**事件触发名称。*/ this.eventName=null; /**事件触发参数。*/ this.params=null; } __class(AnimationEvent,'laya.d3.animation.AnimationEvent'); return AnimationEvent; })() /** *BoneNode 类用于实现骨骼节点。 */ //class laya.d3.animation.AnimationNode var AnimationNode=(function(){ function AnimationNode(){ /**@private */ //this._childs=null; /**@private */ //this._parent=null; /**@private [只读]*/ //this.transform=null; /**节点名称。 */ //this.name=null; this._childs=[]; this.transform=new AnimationTransform3D(this); } __class(AnimationNode,'laya.d3.animation.AnimationNode'); var __proto=AnimationNode.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *添加子节点。 *@param child 子节点。 */ __proto.addChild=function(child){ child._parent=this; child.transform.setParent(this.transform); this._childs.push(child); } /** *移除子节点。 *@param child 子节点。 */ __proto.removeChild=function(child){ var index=this._childs.indexOf(child); (index!==-1)&& (this._childs.splice(index,1)); } /** *根据名字获取子节点。 *@param name 名字。 */ __proto.getChildByName=function(name){ for (var i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; if (child.name===name) return child; } return null; } /** *根据索引获取子节点。 *@param index 索引。 */ __proto.getChildByIndex=function(index){ return this._childs[index]; } /** *获取子节点的个数。 */ __proto.getChildCount=function(){ return this._childs.length; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destNode=destObject; destNode.name=this.name; for (var i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; var destChild=child.clone(); destNode.addChild(destChild); var transform=child.transform; var destTransform=destChild.transform; destTransform.setLocalPosition(transform.getLocalPosition()); destTransform.setLocalRotation(transform.getLocalRotation()); destTransform.setLocalScale(transform.getLocalScale()); destTransform._localRotationEuler=transform._localRotationEuler; destTransform._setWorldMatrixIgnoreUpdate(transform.getWorldMatrix()); } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } AnimationNode.__init__=function(){ AnimationNode.registerAnimationNodeProperty("localPosition",AnimationNode._getLocalPosition,AnimationNode._setLocalPosition); AnimationNode.registerAnimationNodeProperty("localRotation",AnimationNode._getLocalRotation,AnimationNode._setLocalRotation); AnimationNode.registerAnimationNodeProperty("localScale",AnimationNode._getLocalScale,AnimationNode._setLocalScale); AnimationNode.registerAnimationNodeProperty("localRotationEuler",AnimationNode._getLocalRotationEuler,AnimationNode._setLocalRotationEuler); AnimationNode.registerAnimationNodeProperty("particleRender.sharedMaterial.tintColor",AnimationNode._getParticleRenderSharedMaterialTintColor,AnimationNode._setParticleRenderSharedMaterialTintColor); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.tilingOffset",AnimationNode._getMeshRenderSharedMaterialTilingOffset,AnimationNode._setMeshRenderSharedMaterialTilingOffset); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.albedoColor",AnimationNode._getMeshRenderSharedMaterialAlbedo,AnimationNode._setMeshRenderSharedMaterialAlbedo); AnimationNode.registerAnimationNodeProperty("skinnedMeshRender.sharedMaterial.tilingOffset",AnimationNode._getSkinnedMeshRenderSharedMaterialTilingOffset,AnimationNode._setSkinnedMeshRenderSharedMaterialTilingOffset); AnimationNode.registerAnimationNodeProperty("skinnedMeshRender.sharedMaterial.albedoColor",AnimationNode._getSkinnedMeshRenderSharedMaterialAlbedo,AnimationNode._setSkinnedMeshRenderSharedMaterialAlbedo); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.albedo",AnimationNode._getMeshRenderSharedMaterialAlbedo,AnimationNode._setMeshRenderSharedMaterialAlbedo); AnimationNode.registerAnimationNodeProperty("skinnedMeshRender.sharedMaterial.albedo",AnimationNode._getSkinnedMeshRenderSharedMaterialAlbedo,AnimationNode._setSkinnedMeshRenderSharedMaterialAlbedo); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.intensity",AnimationNode._getMeshRenderSharedMaterialIntensity,AnimationNode._setMeshRenderSharedMaterialIntensity); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.alpha",AnimationNode._getMeshRenderSharedMaterialAlpha,AnimationNode._setMeshRenderSharedMaterialAlpha); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.alphaColor",AnimationNode._getMeshRenderSharedMaterialAlphaColor,AnimationNode._setMeshRenderSharedMaterialAlphaColor); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.baseColor",AnimationNode._getMeshRenderSharedMaterialBaseColor,AnimationNode._setMeshRenderSharedMaterialBaseColor); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.dissolve",AnimationNode._getMeshRenderSharedMaterialDissolve,AnimationNode._setMeshRenderSharedMaterialDissolve); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.dissolveSpeed",AnimationNode._getMeshRenderSharedMaterialDissolveSpeed,AnimationNode._setMeshRenderSharedMaterialDissolveSpeed); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.mMultiplier",AnimationNode._getMeshRenderSharedMaterialMMultiplier,AnimationNode._setMeshRenderSharedMaterialMMultiplier); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.baseScrollSpeedX",AnimationNode._getMeshRenderSharedMaterialBaseScrollSpeedX,AnimationNode._setMeshRenderSharedMaterialBaseScrollSpeedX); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.baseScrollSpeedY",AnimationNode._getMeshRenderSharedMaterialBaseScrollSpeedY,AnimationNode._setMeshRenderSharedMaterialBaseScrollSpeedY); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.secondScrollSpeedX",AnimationNode._getMeshRenderSharedMaterialSecondScrollSpeedX,AnimationNode._setMeshRenderSharedMaterialSecondScrollSpeedX); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.secondScrollSpeedY",AnimationNode._getMeshRenderSharedMaterialSecondScrollSpeedY,AnimationNode._setMeshRenderSharedMaterialSecondScrollSpeedY); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.detailTilingOffset",AnimationNode._getMeshRenderSharedMaterialDetailTilingOffset,AnimationNode._setMeshRenderSharedMaterialDetailTilingOffset); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.dissolveTilingOffset",AnimationNode._getMeshRenderSharedMaterialDissolveTilingOffset,AnimationNode._setMeshRenderSharedMaterialDissolveTilingOffset); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.maskTilingOffset",AnimationNode._getMeshRenderSharedMaterialMaskTilingOffset,AnimationNode._setMeshRenderSharedMaterialMaskTilingOffset); } AnimationNode.registerAnimationNodeProperty=function(propertyName,getFunc,setFunc){ if (AnimationNode._propertyIndexDic[propertyName]){ throw new Error("AnimationNode: this propertyName has registered."); }else { AnimationNode._propertyIndexDic[propertyName]=AnimationNode._propertyIDCounter; AnimationNode._propertyGetFuncs[AnimationNode._propertyIDCounter]=getFunc; AnimationNode._propertySetFuncs[AnimationNode._propertyIDCounter]=setFunc; AnimationNode._propertyIDCounter++; } } AnimationNode._getLocalPosition=function(animationNode,sprite3D){ if (animationNode) return animationNode.transform.getLocalPosition(); else return sprite3D._transform.localPosition.elements; } AnimationNode._setLocalPosition=function(animationNode,sprite3D,value){ if (animationNode){ animationNode.transform.setLocalPosition(value); }else { var spriteTransform=sprite3D._transform; var localPosition=spriteTransform.localPosition; localPosition.elements=value; spriteTransform.localPosition=localPosition; } } AnimationNode._getLocalRotation=function(animationNode,sprite3D){ if (animationNode) return animationNode.transform.getLocalRotation(); else return sprite3D._transform.localRotation.elements; } AnimationNode._setLocalRotation=function(animationNode,sprite3D,value){ if (animationNode){ animationNode.transform.setLocalRotation(value); }else { var spriteTransform=sprite3D._transform; var localRotation=spriteTransform.localRotation; localRotation.elements=value; spriteTransform.localRotation=localRotation; } } AnimationNode._getLocalScale=function(animationNode,sprite3D){ if (animationNode) return animationNode.transform.getLocalScale(); else return sprite3D._transform.localScale.elements; } AnimationNode._setLocalScale=function(animationNode,sprite3D,value){ if (animationNode){ animationNode.transform.setLocalScale(value); }else { var spriteTransform=sprite3D._transform; var localScale=spriteTransform.localScale; localScale.elements=value; spriteTransform.localScale=localScale; } } AnimationNode._getLocalRotationEuler=function(animationNode,sprite3D){ if (animationNode) return animationNode.transform.getLocalRotationEuler(); else return sprite3D._transform.localRotationEuler.elements; } AnimationNode._setLocalRotationEuler=function(animationNode,sprite3D,value){ if (animationNode){ animationNode.transform.setLocalRotationEuler(value); }else { var spriteTransform=sprite3D._transform; var localRotationEuler=spriteTransform.localRotationEuler; localRotationEuler.elements=value; spriteTransform.localRotationEuler=localRotationEuler; } } AnimationNode._getMeshRenderSharedMaterialTilingOffset=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.tilingOffset.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.tilingOffset.elements; } } AnimationNode._setMeshRenderSharedMaterialTilingOffset=function(animationNode,sprite3D,value){ var material,tilingOffset; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; tilingOffset=material.tilingOffset; tilingOffset.elements=value; material.tilingOffset=tilingOffset; } }else { material=(sprite3D).meshRender.material; tilingOffset=material.tilingOffset; tilingOffset.elements=value; material.tilingOffset=tilingOffset; } } AnimationNode._getMeshRenderSharedMaterialAlbedo=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.albedoColor.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.albedoColor.elements; } } AnimationNode._setMeshRenderSharedMaterialAlbedo=function(animationNode,sprite3D,value){ var material,albedo; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; albedo=material.albedoColor; albedo.elements=value; material.albedoColor=albedo; } }else { material=(sprite3D).meshRender.material; albedo=material.albedoColor; albedo.elements=value; material.albedoColor=albedo; } } AnimationNode._getSkinnedMeshRenderSharedMaterialTilingOffset=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).skinnedMeshRender.sharedMaterial; return material.tilingOffset.elements; }else return null; }else { material=(sprite3D).skinnedMeshRender.sharedMaterial; return material.tilingOffset.elements; } } AnimationNode._setSkinnedMeshRenderSharedMaterialTilingOffset=function(animationNode,sprite3D,value){ var material,tilingOffset; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).skinnedMeshRender.material; tilingOffset=material.tilingOffset; tilingOffset.elements=value; material.tilingOffset=tilingOffset; } }else { material=(sprite3D).skinnedMeshRender.material; tilingOffset=material.tilingOffset; tilingOffset.elements=value; material.tilingOffset=tilingOffset; } } AnimationNode._getSkinnedMeshRenderSharedMaterialAlbedo=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).skinnedMeshRender.sharedMaterial; return material.albedoColor.elements; }else { return null; } }else { material=(sprite3D).skinnedMeshRender.sharedMaterial; return material.albedoColor.elements; } } AnimationNode._setSkinnedMeshRenderSharedMaterialAlbedo=function(animationNode,sprite3D,value){ var material,albedo; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).skinnedMeshRender.material; albedo=material.albedoColor; albedo.elements=value; material.albedoColor=albedo; } }else { material=(sprite3D).skinnedMeshRender.material; albedo=material.albedoColor; albedo.elements=value; material.albedoColor=albedo; } } AnimationNode._getParticleRenderSharedMaterialTintColor=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).particleRender.sharedMaterial; return material.tintColor.elements; }else return null; }else { material=(sprite3D).particleRender.sharedMaterial; return material.tintColor.elements; } } AnimationNode._setParticleRenderSharedMaterialTintColor=function(animationNode,sprite3D,value){ var material,tintColor; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).particleRender.material; tintColor=material.tintColor; tintColor.elements=value; material.tintColor=tintColor; } }else { material=(sprite3D).particleRender.material; tintColor=material.tintColor; tintColor.elements=value; material.tintColor=tintColor; } } AnimationNode._getMeshRenderSharedMaterialAlphaColor=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.alphaColor.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.alphaColor.elements; } } AnimationNode._setMeshRenderSharedMaterialAlphaColor=function(animationNode,sprite3D,value){ var material,alphaColor; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; alphaColor=material.alphaColor; alphaColor.elements=value; material.alphaColor=alphaColor; } }else { material=(sprite3D).meshRender.material; alphaColor=material.alphaColor; alphaColor.elements=value; material.alphaColor=alphaColor; } } AnimationNode._getMeshRenderSharedMaterialBaseColor=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.baseColor.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.baseColor.elements; } } AnimationNode._setMeshRenderSharedMaterialBaseColor=function(animationNode,sprite3D,value){ var material,baseColor; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; baseColor=material.baseColor; baseColor.elements=value; material.baseColor=baseColor; } }else { material=(sprite3D).meshRender.material; baseColor=material.baseColor; baseColor.elements=value; material.baseColor=baseColor; } } AnimationNode._getMeshRenderSharedMaterialDissolve=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.dissolve; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.dissolve; } } AnimationNode._setMeshRenderSharedMaterialDissolve=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.dissolve=value[0]; } }else { material=(sprite3D).meshRender.material; material.dissolve=value[0]; } } AnimationNode._getMeshRenderSharedMaterialDissolveSpeed=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.dissolveSpeed; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.dissolveSpeed; } } AnimationNode._setMeshRenderSharedMaterialDissolveSpeed=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.dissolveSpeed=value[0]; } }else { material=(sprite3D).meshRender.material; material.dissolveSpeed=value[0]; } } AnimationNode._getMeshRenderSharedMaterialMMultiplier=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.mMultiplier; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.mMultiplier; } } AnimationNode._setMeshRenderSharedMaterialMMultiplier=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.mMultiplier=value[0]; } }else { material=(sprite3D).meshRender.material; material.mMultiplier=value[0]; } } AnimationNode._getMeshRenderSharedMaterialBaseScrollSpeedX=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.baseScrollSpeedX; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.baseScrollSpeedX; } } AnimationNode._setMeshRenderSharedMaterialBaseScrollSpeedX=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.baseScrollSpeedX=value[0]; } }else { material=(sprite3D).meshRender.material; material.baseScrollSpeedX=value[0]; } } AnimationNode._getMeshRenderSharedMaterialBaseScrollSpeedY=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.baseScrollSpeedY; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.baseScrollSpeedY; } } AnimationNode._setMeshRenderSharedMaterialBaseScrollSpeedY=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.baseScrollSpeedY=value[0]; } }else { material=(sprite3D).meshRender.material; material.baseScrollSpeedY=value[0]; } } AnimationNode._getMeshRenderSharedMaterialSecondScrollSpeedX=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.secondScrollSpeedX; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.secondScrollSpeedX; } } AnimationNode._setMeshRenderSharedMaterialSecondScrollSpeedX=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.secondScrollSpeedX=value[0]; } }else { material=(sprite3D).meshRender.material; material.secondScrollSpeedX=value[0]; } } AnimationNode._getMeshRenderSharedMaterialSecondScrollSpeedY=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.secondScrollSpeedY; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.secondScrollSpeedY; } } AnimationNode._setMeshRenderSharedMaterialSecondScrollSpeedY=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.secondScrollSpeedY=value[0]; } }else { material=(sprite3D).meshRender.material; material.secondScrollSpeedY=value[0]; } } AnimationNode._getMeshRenderSharedMaterialAlpha=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.alpha; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.alpha; } } AnimationNode._setMeshRenderSharedMaterialAlpha=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.alpha=value[0]; } }else { material=(sprite3D).meshRender.material; material.alpha=value[0]; } } AnimationNode._getMeshRenderSharedMaterialIntensity=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.intensity; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.intensity; } } AnimationNode._setMeshRenderSharedMaterialIntensity=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.intensity=value[0]; } }else { material=(sprite3D).meshRender.material; material.intensity=value[0]; } } AnimationNode._getMeshRenderSharedMaterialDetailTilingOffset=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.detailTilingOffset.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.detailTilingOffset.elements; } } AnimationNode._setMeshRenderSharedMaterialDetailTilingOffset=function(animationNode,sprite3D,value){ var material,detailTilingOffset; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; detailTilingOffset=material.detailTilingOffset; detailTilingOffset.elements=value; material.detailTilingOffset=detailTilingOffset; } }else { material=(sprite3D).meshRender.material; detailTilingOffset=material.detailTilingOffset; detailTilingOffset.elements=value; material.detailTilingOffset=detailTilingOffset; } } AnimationNode._getMeshRenderSharedMaterialDissolveTilingOffset=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.dissolveTilingOffset.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.dissolveTilingOffset.elements; } } AnimationNode._setMeshRenderSharedMaterialDissolveTilingOffset=function(animationNode,sprite3D,value){ var material,dissolveTilingOffset; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; dissolveTilingOffset=material.dissolveTilingOffset; dissolveTilingOffset.elements=value; material.dissolveTilingOffset=dissolveTilingOffset; } }else { material=(sprite3D).meshRender.material; dissolveTilingOffset=material.dissolveTilingOffset; dissolveTilingOffset.elements=value; material.dissolveTilingOffset=dissolveTilingOffset; } } AnimationNode._getMeshRenderSharedMaterialMaskTilingOffset=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.maskTilingOffset.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.maskTilingOffset.elements; } } AnimationNode._setMeshRenderSharedMaterialMaskTilingOffset=function(animationNode,sprite3D,value){ var material,maskTilingOffset; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; maskTilingOffset=material.maskTilingOffset; maskTilingOffset.elements=value; material.maskTilingOffset=maskTilingOffset; } }else { material=(sprite3D).meshRender.material; maskTilingOffset=material.maskTilingOffset; maskTilingOffset.elements=value; material.maskTilingOffset=maskTilingOffset; } } AnimationNode._propertyIDCounter=0; AnimationNode._propertyIndexDic={}; AnimationNode._propertySetFuncs=[]; AnimationNode._propertyGetFuncs=[]; return AnimationNode; })() /** *@private */ //class laya.d3.animation.Keyframe var Keyframe=(function(){ function Keyframe(){ this.startTime=NaN; this.inTangent=null; this.outTangent=null; this.data=null; this.duration=NaN; this.next=null; } __class(Keyframe,'laya.d3.animation.Keyframe'); return Keyframe; })() /** *@private */ //class laya.d3.animation.KeyframeNode var KeyframeNode=(function(){ function KeyframeNode(){ this._cacheProperty=false; this.path=null; this.componentType=null; //TODO:是否去掉 this.propertyNameID=0; this.keyFrameWidth=0; this.defaultData=null; this.keyFrames=null; } __class(KeyframeNode,'laya.d3.animation.KeyframeNode'); return KeyframeNode; })() /** *SplineCurvePositionVelocity 类用于通过顶点和速度创建闪光插值。 */ //class laya.d3.core.glitter.SplineCurvePositionVelocity var SplineCurvePositionVelocity=(function(){ function SplineCurvePositionVelocity(){ this._tempVector30=new Vector3(); this._tempVector31=new Vector3(); this._tempVector32=new Vector3(); this._a=new Vector3(); this._b=new Vector3(); this._c=new Vector3(); this._d=new Vector3(); } __class(SplineCurvePositionVelocity,'laya.d3.core.glitter.SplineCurvePositionVelocity'); var __proto=SplineCurvePositionVelocity.prototype; /** *初始化插值所需信息。 *@param position0 顶点0的位置。 *@param velocity0 顶点0的速度。 *@param position1 顶点1的位置。 *@param velocity1 顶点1的速度。 */ __proto.Init=function(position0,velocity0,position1,velocity1){ position0.cloneTo(this._d); velocity0.cloneTo(this._c); Vector3.scale(position0,2.0,this._a); Vector3.scale(position1,2.0,this._tempVector30); Vector3.subtract(this._a,this._tempVector30,this._a); Vector3.add(this._a,velocity0,this._a); Vector3.add(this._a,velocity1,this._a); Vector3.scale(position1,3.0,this._b); Vector3.scale(position0,3.0,this._tempVector30); Vector3.subtract(this._b,this._tempVector30,this._b); Vector3.subtract(this._b,velocity1,this._b); Vector3.scale(velocity0,2.0,this._tempVector30); Vector3.subtract(this._b,this._tempVector30,this._b); } /** *初始化插值所需信息。 *@param t 插值比例 *@param out 输出结果 */ __proto.Slerp=function(t,out){ Vector3.scale(this._a,t *t *t,this._tempVector30); Vector3.scale(this._b,t *t,this._tempVector31); Vector3.scale(this._c,t,this._tempVector32); Vector3.add(this._tempVector30,this._tempVector31,out); Vector3.add(out,this._tempVector32,out); Vector3.add(out,this._d,out); } return SplineCurvePositionVelocity; })() /** *HeightMap 类用于实现高度图数据。 */ //class laya.d3.core.HeightMap var HeightMap=(function(){ function HeightMap(width,height,minHeight,maxHeight){ /**@private */ this._datas=null; /**@private */ this._w=0; /**@private */ this._h=0; /**@private */ this._minHeight=NaN; /**@private */ this._maxHeight=NaN; this._datas=[]; this._w=width; this._h=height; this._minHeight=minHeight; this._maxHeight=maxHeight; } __class(HeightMap,'laya.d3.core.HeightMap'); var __proto=HeightMap.prototype; /**@private */ __proto._inBounds=function(row,col){ return row >=0 && row < this._h && col >=0 && col < this._w; } /** *获取高度。 *@param row 列数。 *@param col 行数。 *@return 高度。 */ __proto.getHeight=function(row,col){ if (this._inBounds(row,col)) return this._datas[row][col]; else return NaN; } /** *获取宽度。 *@return value 宽度。 */ __getset(0,__proto,'width',function(){ return this._w; }); /** *获取高度。 *@return value 高度。 */ __getset(0,__proto,'height',function(){ return this._h; }); /** *最大高度。 *@return value 最大高度。 */ __getset(0,__proto,'maxHeight',function(){ return this._maxHeight; }); /** *最大高度。 *@return value 最大高度。 */ __getset(0,__proto,'minHeight',function(){ return this._minHeight; }); HeightMap.creatFromMesh=function(mesh,width,height,outCellSize){ var vertices=[]; var indexs=[]; var submesheCount=mesh.getSubMeshCount(); for (var i=0;i < submesheCount;i++){ var subMesh=mesh.getSubMesh(i); var vertexBuffer=subMesh._getVertexBuffer(); var verts=vertexBuffer.getData(); var subMeshVertices=[]; for (var j=0;j < verts.length;j+=vertexBuffer.vertexDeclaration.vertexStride / 4){ var position=new Vector3(verts[j+0],verts[j+1],verts[j+2]); subMeshVertices.push(position); } vertices.push(subMeshVertices); var ib=subMesh._getIndexBuffer(); indexs.push(ib.getData()); }; var boundingBox=mesh.boundingBox; var minX=boundingBox.min.x; var minZ=boundingBox.min.z; var maxX=boundingBox.max.x; var maxZ=boundingBox.max.z; var minY=boundingBox.min.y; var maxY=boundingBox.max.y; var widthSize=maxX-minX; var heightSize=maxZ-minZ; var cellWidth=outCellSize.elements[0]=widthSize / (width-1); var cellHeight=outCellSize.elements[1]=heightSize / (height-1); var heightMap=new HeightMap(width,height,minY,maxY); var ray=HeightMap._tempRay; var rayDirE=ray.direction.elements; rayDirE[0]=0; rayDirE[1]=-1; rayDirE[2]=0; var heightOffset=0.1; var rayY=maxY+heightOffset; ray.origin.elements[1]=rayY; for (var h=0;h < height;h++){ var posZ=minZ+h *cellHeight; heightMap._datas[h]=[]; for (var w=0;w < width;w++){ var posX=minX+w *cellWidth; var rayOriE=ray.origin.elements; rayOriE[0]=posX; rayOriE[2]=posZ; var closestIntersection=HeightMap._getPosition(ray,vertices,indexs); heightMap._datas[h][w]=(closestIntersection===Number.MAX_VALUE)? NaN :rayY-closestIntersection; } } return heightMap; } HeightMap.createFromImage=function(texture,minHeight,maxHeight){ var textureWidth=texture.width; var textureHeight=texture.height; var heightMap=new HeightMap(textureWidth,textureHeight,minHeight,maxHeight); var compressionRatio=(maxHeight-minHeight)/ 254; var pixelsInfo=texture.getPixels(); var index=0; for (var h=0;h Layer
    类用于实现层。 */ //class laya.d3.core.Layer var Layer=(function(){ function Layer(){ /**@private 编号。*/ //this._number=0; /**@private 蒙版值。*/ //this._mask=0; /**@private 是否显示。*/ //this._visible=false; /**@private 只读,不允许修改。*/ //this._nonRigidbodyOffset=0; /**@private 只读,不允许修改。*/ //this._colliders=null; /**名字。*/ //this.name=null; this._visible=true; this._nonRigidbodyOffset=0; this._colliders=[]; } __class(Layer,'laya.d3.core.Layer'); var __proto=Layer.prototype; /** *@private */ __proto._binarySearchIndex=function(){ var start=0; var end=Layer._collsionTestList.length-1; var mid=0; while (start <=end){ mid=Math.floor((start+end)/ 2); var midValue=Layer._collsionTestList[mid]; if (midValue==this._number) return mid; else if (midValue > this._number) end=mid-1; else start=mid+1; } return start; } /** *@private */ __proto._addCollider=function(collider){ (this._colliders.length===0)&& (Layer._collsionTestList.splice(this._binarySearchIndex(),0,this._number)); if (collider._isRigidbody){ this._colliders.unshift(collider); this._nonRigidbodyOffset++; }else { this._colliders.push(collider); } } /** *@private */ __proto._removeCollider=function(collider){ var index=this._colliders.indexOf(collider); if (index < this._nonRigidbodyOffset) this._nonRigidbodyOffset--; this._colliders.splice(index,1); (this._colliders.length===0)&& (Layer._collsionTestList.splice(Layer._collsionTestList.indexOf(this._number),1)); } /** *获取编号。 *@return 编号。 */ __getset(0,__proto,'number',function(){ return this._number; }); /** *设置是否显示。 *@param value 是否显示。 */ /** *获取是否显示。 *@return 是否显示。 */ __getset(0,__proto,'visible',function(){ return this._visible; },function(value){ this._visible=value; if (value) Layer._visibleLayers=Layer._visibleLayers | this.mask; else Layer._visibleLayers=Layer._visibleLayers & ~this.mask; }); /** *获取蒙版值。 *@return 蒙版值。 */ __getset(0,__proto,'mask',function(){ return this._mask; }); /** *设置Layer显示层。 *@param value 显示层。 */ /** *获取Layer显示层。 *@return 显示层。 */ __getset(1,Layer,'visibleLayers',function(){ return Layer._visibleLayers; },function(value){ Layer._visibleLayers=value; for (var i=0,n=Layer._layerList.length;i < n;i++){ var layer=Layer._layerList[i]; layer._visible=(layer._mask & Layer._visibleLayers)!==0; } }); Layer.__init__=function(){ Layer._layerList.length=31; for (var i=0;i < 31;i++){ var layer=new Layer(); Layer._layerList[i]=layer; if (i===0){ layer.name="Default Layer"; layer.visible=true; }else { layer.name="Layer-"+i; layer.visible=false; } layer._number=i; layer._mask=Math.pow(2,i); } Layer.currentCreationLayer=Layer._layerList[0]; } Layer.getLayerByNumber=function(number){ if (number < 0 || number > 30) throw new Error("无法返回指定Layer,该number超出范围!"); return Layer._layerList[number]; } Layer.getLayerByName=function(name){ for (var i=0;i < 31;i++){ if (Layer._layerList[i].name===name) return Layer._layerList[i]; } throw new Error("无法返回指定Layer,该name不存在"); } Layer.isVisible=function(mask){ return (mask & Layer._currentCameraCullingMask & Layer._visibleLayers)!=0; } Layer._layerList=[]; Layer._visibleLayers=2147483647; Layer._collsionTestList=[]; Layer._currentCameraCullingMask=2147483647; Layer.maxCount=31; Layer.currentCreationLayer=null; return Layer; })() /** *Burst 类用于粒子的爆裂描述。 */ //class laya.d3.core.particleShuriKen.module.Burst var Burst=(function(){ function Burst(time,minCount,maxCount){ /**@private 爆裂时间,单位为秒。*/ this._time=NaN; /**@private 爆裂的最小数量。*/ this._minCount=0; /**@private 爆裂的最大数量。*/ this._maxCount=0; this._time=time; this._minCount=minCount; this._maxCount=maxCount; } __class(Burst,'laya.d3.core.particleShuriKen.module.Burst'); var __proto=Burst.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destBurst=destObject; destBurst._time=this._time destBurst._minCount=this._minCount; destBurst._maxCount=this._maxCount; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destBurst=/*__JS__ */new this.constructor(); this.cloneTo(destBurst); return destBurst; } /** *获取爆裂时间,单位为秒。 *@return 爆裂时间,单位为秒。 */ __getset(0,__proto,'time',function(){ return this._time; }); /** *获取爆裂的最小数量。 *@return 爆裂的最小数量。 */ __getset(0,__proto,'minCount',function(){ return this._minCount; }); /** *获取爆裂的最大数量。 *@return 爆裂的最大数量。 */ __getset(0,__proto,'maxCount',function(){ return this._maxCount; }); return Burst; })() /** *ColorOverLifetime 类用于粒子的生命周期颜色。 */ //class laya.d3.core.particleShuriKen.module.ColorOverLifetime var ColorOverLifetime=(function(){ function ColorOverLifetime(color){ /**@private */ this._color=null; /**是否启用。*/ this.enbale=false; this._color=color; } __class(ColorOverLifetime,'laya.d3.core.particleShuriKen.module.ColorOverLifetime'); var __proto=ColorOverLifetime.prototype; /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destColorOverLifetime=destObject; this._color.cloneTo(destColorOverLifetime._color); destColorOverLifetime.enbale=this.enbale; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destColor; switch (this._color.type){ case 0: destColor=GradientColor.createByConstant(this._color.constant.clone()); break ; case 1: destColor=GradientColor.createByGradient(this._color.gradient.clone()); break ; case 2: destColor=GradientColor.createByRandomTwoConstant(this._color.constantMin.clone(),this._color.constantMax.clone()); break ; case 3: destColor=GradientColor.createByRandomTwoGradient(this._color.gradientMin.clone(),this._color.gradientMax.clone()); break ; }; var destColorOverLifetime=/*__JS__ */new this.constructor(destColor); destColorOverLifetime.enbale=this.enbale; return destColorOverLifetime; } /** *获取颜色。 */ __getset(0,__proto,'color',function(){ return this._color; }); return ColorOverLifetime; })() /** *Emission 类用于粒子发射器。 */ //class laya.d3.core.particleShuriKen.module.Emission var Emission=(function(){ function Emission(){ /**@private */ this._destroyed=false; /**@private 粒子发射速率,每秒发射的个数。*/ this._emissionRate=0; /**@private 粒子的爆裂,不允许修改。*/ this._bursts=null; /**是否启用。*/ this.enbale=false; this._destroyed=false; this.emissionRate=10; this._bursts=[]; } __class(Emission,'laya.d3.core.particleShuriKen.module.Emission'); var __proto=Emission.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true,"laya.resource.IDestroy":true}) /** *@private */ __proto._destroy=function(){ this._bursts=null; this._destroyed=true; } /** *获取粒子爆裂个数。 *@return 粒子爆裂个数。 */ __proto.getBurstsCount=function(){ return this._bursts.length; } /** *通过索引获取粒子爆裂。 *@param index 爆裂索引。 *@return 粒子爆裂。 */ __proto.getBurstByIndex=function(index){ return this._bursts[index]; } /** *增加粒子爆裂。 *@param burst 爆裂。 */ __proto.addBurst=function(burst){ var burstsCount=this._bursts.length; if (burstsCount > 0) for (var i=0;i < burstsCount;i++){ if (this._bursts[i].time > burst.time) this._bursts.splice(i,0,burst); } this._bursts.push(burst); } /** *移除粒子爆裂。 *@param burst 爆裂。 */ __proto.removeBurst=function(burst){ var index=this._bursts.indexOf(burst); if (index!==-1){ this._bursts.splice(index,1); } } /** *通过索引移除粒子爆裂。 *@param index 爆裂索引。 */ __proto.removeBurstByIndex=function(index){ this._bursts.splice(index,1); } /** *清空粒子爆裂。 */ __proto.clearBurst=function(){ this._bursts.length=0; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destEmission=destObject; var destBursts=destEmission._bursts; destBursts.length=this._bursts.length; for (var i=0,n=this._bursts.length;i < n;i++){ var destBurst=destBursts[i]; if (destBurst) this._bursts[i].cloneTo(destBurst); else destBursts[i]=this._bursts[i].clone(); } destEmission._emissionRate=this._emissionRate; destEmission.enbale=this.enbale; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destEmission=/*__JS__ */new this.constructor(); this.cloneTo(destEmission); return destEmission; } /** *获取是否已销毁。 *@return 是否已销毁。 */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); /** *设置粒子发射速率。 *@param emissionRate 粒子发射速率 (个/秒)。 */ /** *获取粒子发射速率。 *@return 粒子发射速率 (个/秒)。 */ __getset(0,__proto,'emissionRate',function(){ return this._emissionRate; },function(value){ if (value < 0) throw new Error("ParticleBaseShape:emissionRate value must large or equal than 0."); this._emissionRate=value; }); return Emission; })() /** *FrameOverTime 类用于创建时间帧。 */ //class laya.d3.core.particleShuriKen.module.FrameOverTime var FrameOverTime=(function(){ function FrameOverTime(){ /**@private */ this._type=0; /**@private */ this._constant=0; /**@private */ this._overTime=null; /**@private */ this._constantMin=0; /**@private */ this._constantMax=0; /**@private */ this._overTimeMin=null; /**@private */ this._overTimeMax=null; } __class(FrameOverTime,'laya.d3.core.particleShuriKen.module.FrameOverTime'); var __proto=FrameOverTime.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destFrameOverTime=destObject; destFrameOverTime._type=this._type; destFrameOverTime._constant=this._constant; this._overTime.cloneTo(destFrameOverTime._overTime); destFrameOverTime._constantMin=this._constantMin; destFrameOverTime._constantMax=this._constantMax; this._overTimeMin.cloneTo(destFrameOverTime._overTimeMin); this._overTimeMax.cloneTo(destFrameOverTime._overTimeMax); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destFrameOverTime=/*__JS__ */new this.constructor(); this.cloneTo(destFrameOverTime); return destFrameOverTime; } /** *时间帧。 */ __getset(0,__proto,'frameOverTimeData',function(){ return this._overTime; }); /** *固定帧。 */ __getset(0,__proto,'constant',function(){ return this._constant; }); /** *生命周期旋转类型,0常量模式,1曲线模式,2随机双常量模式,3随机双曲线模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *最小时间帧。 */ __getset(0,__proto,'frameOverTimeDataMin',function(){ return this._overTimeMin; }); /** *最小固定帧。 */ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *最大时间帧。 */ __getset(0,__proto,'frameOverTimeDataMax',function(){ return this._overTimeMax; }); /** *最大固定帧。 */ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); FrameOverTime.createByConstant=function(constant){ var rotationOverLifetime=new FrameOverTime(); rotationOverLifetime._type=0; rotationOverLifetime._constant=constant; return rotationOverLifetime; } FrameOverTime.createByOverTime=function(overTime){ var rotationOverLifetime=new FrameOverTime(); rotationOverLifetime._type=1; rotationOverLifetime._overTime=overTime; return rotationOverLifetime; } FrameOverTime.createByRandomTwoConstant=function(constantMin,constantMax){ var rotationOverLifetime=new FrameOverTime(); rotationOverLifetime._type=2; rotationOverLifetime._constantMin=constantMin; rotationOverLifetime._constantMax=constantMax; return rotationOverLifetime; } FrameOverTime.createByRandomTwoOverTime=function(gradientFrameMin,gradientFrameMax){ var rotationOverLifetime=new FrameOverTime(); rotationOverLifetime._type=3; rotationOverLifetime._overTimeMin=gradientFrameMin; rotationOverLifetime._overTimeMax=gradientFrameMax; return rotationOverLifetime; } return FrameOverTime; })() /** *GradientRotation 类用于创建渐变角速度。 */ //class laya.d3.core.particleShuriKen.module.GradientAngularVelocity var GradientAngularVelocity=(function(){ function GradientAngularVelocity(){ /**@private */ this._type=0; /**@private */ this._separateAxes=false; /**@private */ this._constant=NaN; /**@private */ this._constantSeparate=null; /**@private */ this._gradient=null; /**@private */ this._gradientX=null; /**@private */ this._gradientY=null; /**@private */ this._gradientZ=null; /**@private */ this._gradientW=null; /**@private */ this._constantMin=NaN; /**@private */ this._constantMax=NaN; /**@private */ this._constantMinSeparate=null; /**@private */ this._constantMaxSeparate=null; /**@private */ this._gradientMin=null; /**@private */ this._gradientMax=null; /**@private */ this._gradientXMin=null; /**@private */ this._gradientXMax=null; /**@private */ this._gradientYMin=null; /**@private */ this._gradientYMax=null; /**@private */ this._gradientZMin=null; /**@private */ this._gradientZMax=null; /**@private */ this._gradientWMin=null; /**@private */ this._gradientWMax=null; } __class(GradientAngularVelocity,'laya.d3.core.particleShuriKen.module.GradientAngularVelocity'); var __proto=GradientAngularVelocity.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientAngularVelocity=destObject; destGradientAngularVelocity._type=this._type; destGradientAngularVelocity._separateAxes=this._separateAxes; destGradientAngularVelocity._constant=this._constant; this._constantSeparate.cloneTo(destGradientAngularVelocity._constantSeparate); this._gradient.cloneTo(destGradientAngularVelocity._gradient); this._gradientX.cloneTo(destGradientAngularVelocity._gradientX); this._gradientY.cloneTo(destGradientAngularVelocity._gradientY); this._gradientZ.cloneTo(destGradientAngularVelocity._gradientZ); destGradientAngularVelocity._constantMin=this._constantMin; destGradientAngularVelocity._constantMax=this._constantMax; this._constantMinSeparate.cloneTo(destGradientAngularVelocity._constantMinSeparate); this._constantMaxSeparate.cloneTo(destGradientAngularVelocity._constantMaxSeparate); this._gradientMin.cloneTo(destGradientAngularVelocity._gradientMin); this._gradientMax.cloneTo(destGradientAngularVelocity._gradientMax); this._gradientXMin.cloneTo(destGradientAngularVelocity._gradientXMin); this._gradientXMax.cloneTo(destGradientAngularVelocity._gradientXMax); this._gradientYMin.cloneTo(destGradientAngularVelocity._gradientYMin); this._gradientYMax.cloneTo(destGradientAngularVelocity._gradientYMax); this._gradientZMin.cloneTo(destGradientAngularVelocity._gradientZMin); this._gradientZMax.cloneTo(destGradientAngularVelocity._gradientZMax); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientAngularVelocity=/*__JS__ */new this.constructor(); this.cloneTo(destGradientAngularVelocity); return destGradientAngularVelocity; } /** *渐变角速度Z。 */ __getset(0,__proto,'gradientZ',function(){ return this._gradientZ; }); /** *固定角速度。 */ __getset(0,__proto,'constant',function(){ return this._constant; }); /** *渐变角速度。 */ __getset(0,__proto,'gradient',function(){ return this._gradient; }); /** *是否分轴。 */ __getset(0,__proto,'separateAxes',function(){ return this._separateAxes; }); /** *生命周期角速度类型,0常量模式,1曲线模式,2随机双常量模式,3随机双曲线模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *分轴固定角速度。 */ __getset(0,__proto,'constantSeparate',function(){ return this._constantSeparate; }); /** *渐变角角速度X。 */ __getset(0,__proto,'gradientX',function(){ return this._gradientX; }); /** *渐变角速度Y。 */ __getset(0,__proto,'gradientY',function(){ return this._gradientY; }); /** *渐变角速度Z。 */ __getset(0,__proto,'gradientW',function(){ return this._gradientW; }); /** *最小渐变角速度。 */ __getset(0,__proto,'gradientMin',function(){ return this._gradientMin; }); /** *最小随机双固定角速度。 */ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *最大渐变角速度。 */ __getset(0,__proto,'gradientMax',function(){ return this._gradientMax; }); /** *最大随机双固定角速度。 */ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); /** *最小渐变角速度Z。 */ __getset(0,__proto,'gradientWMin',function(){ return this._gradientWMin; }); /** *最小分轴随机双固定角速度。 */ __getset(0,__proto,'constantMinSeparate',function(){ return this._constantMinSeparate; }); /** *最大分轴随机双固定角速度。 */ __getset(0,__proto,'constantMaxSeparate',function(){ return this._constantMaxSeparate; }); /** *最小渐变角速度X。 */ __getset(0,__proto,'gradientXMin',function(){ return this._gradientXMin; }); /** *最大渐变角速度X。 */ __getset(0,__proto,'gradientXMax',function(){ return this._gradientXMax; }); /** *最大渐变角速度Z。 */ __getset(0,__proto,'gradientWMax',function(){ return this._gradientWMax; }); /** *最小渐变角速度Y。 */ __getset(0,__proto,'gradientYMin',function(){ return this._gradientYMin; }); /** *最大渐变角速度Y。 */ __getset(0,__proto,'gradientYMax',function(){ return this._gradientYMax; }); /** *最小渐变角速度Z。 */ __getset(0,__proto,'gradientZMin',function(){ return this._gradientZMin; }); /** *最大渐变角速度Z。 */ __getset(0,__proto,'gradientZMax',function(){ return this._gradientZMax; }); GradientAngularVelocity.createByConstant=function(constant){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=0; gradientAngularVelocity._separateAxes=false; gradientAngularVelocity._constant=constant; return gradientAngularVelocity; } GradientAngularVelocity.createByConstantSeparate=function(separateConstant){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=0; gradientAngularVelocity._separateAxes=true; gradientAngularVelocity._constantSeparate=separateConstant; return gradientAngularVelocity; } GradientAngularVelocity.createByGradient=function(gradient){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=1; gradientAngularVelocity._separateAxes=false; gradientAngularVelocity._gradient=gradient; return gradientAngularVelocity; } GradientAngularVelocity.createByGradientSeparate=function(gradientX,gradientY,gradientZ,gradientW){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=1; gradientAngularVelocity._separateAxes=true; gradientAngularVelocity._gradientX=gradientX; gradientAngularVelocity._gradientY=gradientY; gradientAngularVelocity._gradientZ=gradientZ; gradientAngularVelocity._gradientW=gradientW; return gradientAngularVelocity; } GradientAngularVelocity.createByRandomTwoConstant=function(constantMin,constantMax){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=2; gradientAngularVelocity._separateAxes=false; gradientAngularVelocity._constantMin=constantMin; gradientAngularVelocity._constantMax=constantMax; return gradientAngularVelocity; } GradientAngularVelocity.createByRandomTwoConstantSeparate=function(separateConstantMin,separateConstantMax){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=2; gradientAngularVelocity._separateAxes=true; gradientAngularVelocity._constantMinSeparate=separateConstantMin; gradientAngularVelocity._constantMaxSeparate=separateConstantMax; return gradientAngularVelocity; } GradientAngularVelocity.createByRandomTwoGradient=function(gradientMin,gradientMax){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=3; gradientAngularVelocity._separateAxes=false; gradientAngularVelocity._gradientMin=gradientMin; gradientAngularVelocity._gradientMax=gradientMax; return gradientAngularVelocity; } GradientAngularVelocity.createByRandomTwoGradientSeparate=function(gradientXMin,gradientXMax,gradientYMin,gradientYMax,gradientZMin,gradientZMax,gradientWMin,gradientWMax){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=3; gradientAngularVelocity._separateAxes=true; gradientAngularVelocity._gradientXMin=gradientXMin; gradientAngularVelocity._gradientXMax=gradientXMax; gradientAngularVelocity._gradientYMin=gradientYMin; gradientAngularVelocity._gradientYMax=gradientYMax; gradientAngularVelocity._gradientZMin=gradientZMin; gradientAngularVelocity._gradientZMax=gradientZMax; gradientAngularVelocity._gradientWMin=gradientWMin; gradientAngularVelocity._gradientWMax=gradientWMax; return gradientAngularVelocity; } return GradientAngularVelocity; })() /** *GradientColor 类用于创建渐变颜色。 */ //class laya.d3.core.particleShuriKen.module.GradientColor var GradientColor=(function(){ function GradientColor(){ /**@private */ this._type=0; /**@private */ this._constant=null; /**@private */ this._constantMin=null; /**@private */ this._constantMax=null; /**@private */ this._gradient=null; /**@private */ this._gradientMin=null; /**@private */ this._gradientMax=null; } __class(GradientColor,'laya.d3.core.particleShuriKen.module.GradientColor'); var __proto=GradientColor.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientColor=destObject; destGradientColor._type=this._type; this._constant.cloneTo(destGradientColor._constant); this._constantMin.cloneTo(destGradientColor._constantMin); this._constantMax.cloneTo(destGradientColor._constantMax); this._gradient.cloneTo(destGradientColor._gradient); this._gradientMin.cloneTo(destGradientColor._gradientMin); this._gradientMax.cloneTo(destGradientColor._gradientMax); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientColor=/*__JS__ */new this.constructor(); this.cloneTo(destGradientColor); return destGradientColor; } /** *渐变颜色。 */ __getset(0,__proto,'gradient',function(){ return this._gradient; }); /** *固定颜色。 */ __getset(0,__proto,'constant',function(){ return this._constant; }); /** *生命周期颜色类型,0为固定颜色模式,1渐变模式,2为随机双固定颜色模式,3随机双渐变模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *最小渐变颜色。 */ __getset(0,__proto,'gradientMin',function(){ return this._gradientMin; }); /** *最小固定颜色。 */ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *最大渐变颜色。 */ __getset(0,__proto,'gradientMax',function(){ return this._gradientMax; }); /** *最大固定颜色。 */ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); GradientColor.createByConstant=function(constant){ var gradientColor=new GradientColor(); gradientColor._type=0; gradientColor._constant=constant; return gradientColor; } GradientColor.createByGradient=function(gradient){ var gradientColor=new GradientColor(); gradientColor._type=1; gradientColor._gradient=gradient; return gradientColor; } GradientColor.createByRandomTwoConstant=function(minConstant,maxConstant){ var gradientColor=new GradientColor(); gradientColor._type=2; gradientColor._constantMin=minConstant; gradientColor._constantMax=maxConstant; return gradientColor; } GradientColor.createByRandomTwoGradient=function(minGradient,maxGradient){ var gradientColor=new GradientColor(); gradientColor._type=3; gradientColor._gradientMin=minGradient; gradientColor._gradientMax=maxGradient; return gradientColor; } return GradientColor; })() /** *GradientDataColor 类用于创建颜色渐变。 */ //class laya.d3.core.particleShuriKen.module.GradientDataColor var GradientDataColor=(function(){ function GradientDataColor(){ /**@private */ this._alphaCurrentLength=0; /**@private */ this._rgbCurrentLength=0; /**@private 开发者禁止修改。*/ this._alphaElements=null; /**@private 开发者禁止修改。*/ this._rgbElements=null; this._alphaElements=new Float32Array(8); this._rgbElements=new Float32Array(16); } __class(GradientDataColor,'laya.d3.core.particleShuriKen.module.GradientDataColor'); var __proto=GradientDataColor.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *增加Alpha渐变。 *@param key 生命周期,范围为0到1。 *@param value rgb值。 */ __proto.addAlpha=function(key,value){ if (this._alphaCurrentLength < 8){ if ((this._alphaCurrentLength===6)&& ((key!==1))){ key=1; console.log("GradientDataColor warning:the forth key is be force set to 1."); } this._alphaElements[this._alphaCurrentLength++]=key; this._alphaElements[this._alphaCurrentLength++]=value; }else { console.log("GradientDataColor warning:data count must lessEqual than 4"); } } /** *增加RGB渐变。 *@param key 生命周期,范围为0到1。 *@param value RGB值。 */ __proto.addRGB=function(key,value){ if (this._rgbCurrentLength < 16){ if ((this._rgbCurrentLength===12)&& ((key!==1))){ key=1; console.log("GradientDataColor warning:the forth key is be force set to 1."); } this._rgbElements[this._rgbCurrentLength++]=key; this._rgbElements[this._rgbCurrentLength++]=value.x; this._rgbElements[this._rgbCurrentLength++]=value.y; this._rgbElements[this._rgbCurrentLength++]=value.z; }else { console.log("GradientDataColor warning:data count must lessEqual than 4"); } } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientDataColor=destObject; var i=0,n=0; destGradientDataColor._alphaCurrentLength=this._alphaCurrentLength; var destAlphaElements=destGradientDataColor._alphaElements; destAlphaElements.length=this._alphaElements.length; for (i=0,n=this._alphaElements.length;i < n;i++) destAlphaElements[i]=this._alphaElements[i]; destGradientDataColor._rgbCurrentLength=this._rgbCurrentLength; var destRGBElements=destGradientDataColor._rgbElements; destRGBElements.length=this._rgbElements.length; for (i=0,n=this._rgbElements.length;i < n;i++) destRGBElements[i]=this._rgbElements[i]; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientDataColor=/*__JS__ */new this.constructor(); this.cloneTo(destGradientDataColor); return destGradientDataColor; } /**渐变Alpha数量。*/ __getset(0,__proto,'alphaGradientCount',function(){ return this._alphaCurrentLength / 2; }); /**渐变RGB数量。*/ __getset(0,__proto,'rgbGradientCount',function(){ return this._rgbCurrentLength / 4; }); return GradientDataColor; })() /** *GradientDataInt 类用于创建整形渐变。 */ //class laya.d3.core.particleShuriKen.module.GradientDataInt var GradientDataInt=(function(){ function GradientDataInt(){ /**@private */ this._currentLength=0; /**@private 开发者禁止修改。*/ this._elements=null; this._elements=new Float32Array(8); } __class(GradientDataInt,'laya.d3.core.particleShuriKen.module.GradientDataInt'); var __proto=GradientDataInt.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *增加整形渐变。 *@param key 生命周期,范围为0到1。 *@param value 整形值。 */ __proto.add=function(key,value){ if (this._currentLength < 8){ if ((this._currentLength===6)&& ((key!==1))){ key=1; console.log("Warning:the forth key is be force set to 1."); } this._elements[this._currentLength++]=key; this._elements[this._currentLength++]=value; }else { console.log("Warning:data count must lessEqual than 4"); } } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientDataInt=destObject; destGradientDataInt._currentLength=this._currentLength; var destElements=destGradientDataInt._elements; destElements.length=this._elements.length; for (var i=0,n=this._elements.length;i < n;i++){ destElements[i]=this._elements[i]; } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientDataInt=/*__JS__ */new this.constructor(); this.cloneTo(destGradientDataInt); return destGradientDataInt; } /**整形渐变数量。*/ __getset(0,__proto,'gradientCount',function(){ return this._currentLength / 2; }); return GradientDataInt; })() /** *GradientDataNumber 类用于创建浮点渐变。 */ //class laya.d3.core.particleShuriKen.module.GradientDataNumber var GradientDataNumber=(function(){ function GradientDataNumber(){ /**@private */ this._currentLength=0; /**@private 开发者禁止修改。*/ this._elements=null; this._elements=new Float32Array(8); } __class(GradientDataNumber,'laya.d3.core.particleShuriKen.module.GradientDataNumber'); var __proto=GradientDataNumber.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *增加浮点渐变。 *@param key 生命周期,范围为0到1。 *@param value 浮点值。 */ __proto.add=function(key,value){ if (this._currentLength < 8){ if ((this._currentLength===6)&& ((key!==1))){ key=1; console.log("GradientDataNumber warning:the forth key is be force set to 1."); } this._elements[this._currentLength++]=key; this._elements[this._currentLength++]=value; }else { console.log("GradientDataNumber warning:data count must lessEqual than 4"); } } /** *通过索引获取键。 *@param index 索引。 *@return value 键。 */ __proto.getKeyByIndex=function(index){ return this._elements[index *2]; } /** *通过索引获取值。 *@param index 索引。 *@return value 值。 */ __proto.getValueByIndex=function(index){ return this._elements[index *2+1]; } /** *获取平均值。 */ __proto.getAverageValue=function(){ var total=0; for (var i=0,n=this._currentLength-2;i < n;i+=2){ var subValue=this._elements[i+1]; subValue+=this._elements[i+3]; subValue=subValue *(this._elements[i+2]-this._elements[i]); } return total / 2; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientDataNumber=destObject; destGradientDataNumber._currentLength=this._currentLength; var destElements=destGradientDataNumber._elements; destElements.length=this._elements.length; for (var i=0,n=this._elements.length;i < n;i++) destElements[i]=this._elements[i]; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientDataNumber=/*__JS__ */new this.constructor(); this.cloneTo(destGradientDataNumber); return destGradientDataNumber; } /**渐变浮点数量。*/ __getset(0,__proto,'gradientCount',function(){ return this._currentLength / 2; }); return GradientDataNumber; })() /** *GradientDataVector2 类用于创建二维向量渐变。 */ //class laya.d3.core.particleShuriKen.module.GradientDataVector2 var GradientDataVector2=(function(){ function GradientDataVector2(){ /**@private */ this._currentLength=0; /**@private 开发者禁止修改。*/ this._elements=null; this._elements=new Float32Array(12); } __class(GradientDataVector2,'laya.d3.core.particleShuriKen.module.GradientDataVector2'); var __proto=GradientDataVector2.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *增加二维向量渐变。 *@param key 生命周期,范围为0到1。 *@param value 二维向量值。 */ __proto.add=function(key,value){ if (this._currentLength < 8){ if ((this._currentLength===6)&& ((key!==1))){ key=1; console.log("GradientDataVector2 warning:the forth key is be force set to 1."); } this._elements[this._currentLength++]=key; this._elements[this._currentLength++]=value.x; this._elements[this._currentLength++]=value.y; }else { console.log("GradientDataVector2 warning:data count must lessEqual than 4"); } } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientDataVector2=destObject; destGradientDataVector2._currentLength=this._currentLength; var destElements=destGradientDataVector2._elements; destElements.length=this._elements.length; for (var i=0,n=this._elements.length;i < n;i++){ destElements[i]=this._elements[i]; } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientDataVector2=/*__JS__ */new this.constructor(); this.cloneTo(destGradientDataVector2); return destGradientDataVector2; } /**二维向量渐变数量。*/ __getset(0,__proto,'gradientCount',function(){ return this._currentLength / 3; }); return GradientDataVector2; })() /** *GradientSize 类用于创建渐变尺寸。 */ //class laya.d3.core.particleShuriKen.module.GradientSize var GradientSize=(function(){ function GradientSize(){ /**@private */ this._type=0; /**@private */ this._separateAxes=false; /**@private */ this._gradient=null; /**@private */ this._gradientX=null; /**@private */ this._gradientY=null; /**@private */ this._gradientZ=null; /**@private */ this._constantMin=NaN; /**@private */ this._constantMax=NaN; /**@private */ this._constantMinSeparate=null; /**@private */ this._constantMaxSeparate=null; /**@private */ this._gradientMin=null; /**@private */ this._gradientMax=null; /**@private */ this._gradientXMin=null; /**@private */ this._gradientXMax=null; /**@private */ this._gradientYMin=null; /**@private */ this._gradientYMax=null; /**@private */ this._gradientZMin=null; /**@private */ this._gradientZMax=null; } __class(GradientSize,'laya.d3.core.particleShuriKen.module.GradientSize'); var __proto=GradientSize.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *获取最大尺寸。 */ __proto.getMaxSizeInGradient=function(){ var i=0,n=0; var maxSize=-Number.MAX_VALUE; switch (this._type){ case 0: if (this._separateAxes){ for (i=0,n=this._gradientX.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientX.getValueByIndex(i)); for (i=0,n=this._gradientY.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientY.getValueByIndex(i)); }else { for (i=0,n=this._gradient.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradient.getValueByIndex(i)); } break ; case 1: if (this._separateAxes){ maxSize=Math.max(this._constantMinSeparate.x,this._constantMaxSeparate.x); maxSize=Math.max(maxSize,this._constantMinSeparate.y); maxSize=Math.max(maxSize,this._constantMaxSeparate.y); }else { maxSize=Math.max(this._constantMin,this._constantMax); } break ; case 2: if (this._separateAxes){ for (i=0,n=this._gradientXMin.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientXMin.getValueByIndex(i)); for (i=0,n=this._gradientXMax.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientXMax.getValueByIndex(i)); for (i=0,n=this._gradientYMin.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientYMin.getValueByIndex(i)); for (i=0,n=this._gradientZMax.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientZMax.getValueByIndex(i)); }else { for (i=0,n=this._gradientMin.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientMin.getValueByIndex(i)); for (i=0,n=this._gradientMax.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientMax.getValueByIndex(i)); } break ; } return maxSize; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientSize=destObject; destGradientSize._type=this._type; destGradientSize._separateAxes=this._separateAxes; this._gradient.cloneTo(destGradientSize._gradient); this._gradientX.cloneTo(destGradientSize._gradientX); this._gradientY.cloneTo(destGradientSize._gradientY); this._gradientZ.cloneTo(destGradientSize._gradientZ); destGradientSize._constantMin=this._constantMin; destGradientSize._constantMax=this._constantMax; this._constantMinSeparate.cloneTo(destGradientSize._constantMinSeparate); this._constantMaxSeparate.cloneTo(destGradientSize._constantMaxSeparate); this._gradientMin.cloneTo(destGradientSize._gradientMin); this._gradientMax.cloneTo(destGradientSize._gradientMax); this._gradientXMin.cloneTo(destGradientSize._gradientXMin); this._gradientXMax.cloneTo(destGradientSize._gradientXMax); this._gradientYMin.cloneTo(destGradientSize._gradientYMin); this._gradientYMax.cloneTo(destGradientSize._gradientYMax); this._gradientZMin.cloneTo(destGradientSize._gradientZMin); this._gradientZMax.cloneTo(destGradientSize._gradientZMax); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientSize=/*__JS__ */new this.constructor(); this.cloneTo(destGradientSize); return destGradientSize; } /** *渐变尺寸Z。 */ __getset(0,__proto,'gradientZ',function(){ return this._gradientZ; }); /** *渐变尺寸。 */ __getset(0,__proto,'gradient',function(){ return this._gradient; }); /** *是否分轴。 */ __getset(0,__proto,'separateAxes',function(){ return this._separateAxes; }); /** *生命周期尺寸类型,0曲线模式,1随机双常量模式,2随机双曲线模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *渐变最小尺寸。 */ __getset(0,__proto,'gradientMin',function(){ return this._gradientMin; }); /** *最小随机双固定尺寸。 */ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *渐变尺寸X。 */ __getset(0,__proto,'gradientX',function(){ return this._gradientX; }); /** *渐变尺寸Y。 */ __getset(0,__proto,'gradientY',function(){ return this._gradientY; }); /** *渐变最大尺寸。 */ __getset(0,__proto,'gradientMax',function(){ return this._gradientMax; }); /** *最大随机双固定尺寸。 */ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); /** *最小分轴随机双固定尺寸。 */ __getset(0,__proto,'constantMinSeparate',function(){ return this._constantMinSeparate; }); /** *最小分轴随机双固定尺寸。 */ __getset(0,__proto,'constantMaxSeparate',function(){ return this._constantMaxSeparate; }); /** *渐变最小尺寸X。 */ __getset(0,__proto,'gradientXMin',function(){ return this._gradientXMin; }); /** *渐变最大尺寸X。 */ __getset(0,__proto,'gradientXMax',function(){ return this._gradientXMax; }); /** *渐变最小尺寸Y。 */ __getset(0,__proto,'gradientYMin',function(){ return this._gradientYMin; }); /** *渐变最大尺寸Y。 */ __getset(0,__proto,'gradientYMax',function(){ return this._gradientYMax; }); /** *渐变最小尺寸Z。 */ __getset(0,__proto,'gradientZMin',function(){ return this._gradientZMin; }); /** *渐变最大尺寸Z。 */ __getset(0,__proto,'gradientZMax',function(){ return this._gradientZMax; }); GradientSize.createByGradient=function(gradient){ var gradientSize=new GradientSize(); gradientSize._type=0; gradientSize._separateAxes=false; gradientSize._gradient=gradient; return gradientSize; } GradientSize.createByGradientSeparate=function(gradientX,gradientY,gradientZ){ var gradientSize=new GradientSize(); gradientSize._type=0; gradientSize._separateAxes=true; gradientSize._gradientX=gradientX; gradientSize._gradientY=gradientY; gradientSize._gradientZ=gradientZ; return gradientSize; } GradientSize.createByRandomTwoConstant=function(constantMin,constantMax){ var gradientSize=new GradientSize(); gradientSize._type=1; gradientSize._separateAxes=false; gradientSize._constantMin=constantMin; gradientSize._constantMax=constantMax; return gradientSize; } GradientSize.createByRandomTwoConstantSeparate=function(constantMinSeparate,constantMaxSeparate){ var gradientSize=new GradientSize(); gradientSize._type=1; gradientSize._separateAxes=true; gradientSize._constantMinSeparate=constantMinSeparate; gradientSize._constantMaxSeparate=constantMaxSeparate; return gradientSize; } GradientSize.createByRandomTwoGradient=function(gradientMin,gradientMax){ var gradientSize=new GradientSize(); gradientSize._type=2; gradientSize._separateAxes=false; gradientSize._gradientMin=gradientMin; gradientSize._gradientMax=gradientMax; return gradientSize; } GradientSize.createByRandomTwoGradientSeparate=function(gradientXMin,gradientXMax,gradientYMin,gradientYMax,gradientZMin,gradientZMax){ var gradientSize=new GradientSize(); gradientSize._type=2; gradientSize._separateAxes=true; gradientSize._gradientXMin=gradientXMin; gradientSize._gradientXMax=gradientXMax; gradientSize._gradientYMin=gradientYMin; gradientSize._gradientYMax=gradientYMax; gradientSize._gradientZMin=gradientZMin; gradientSize._gradientZMax=gradientZMax; return gradientSize; } return GradientSize; })() /** *GradientVelocity 类用于创建渐变速度。 */ //class laya.d3.core.particleShuriKen.module.GradientVelocity var GradientVelocity=(function(){ function GradientVelocity(){ /**@private */ this._type=0; /**@private */ this._constant=null; /**@private */ this._gradientX=null; /**@private */ this._gradientY=null; /**@private */ this._gradientZ=null; /**@private */ this._constantMin=null; /**@private */ this._constantMax=null; /**@private */ this._gradientXMin=null; /**@private */ this._gradientXMax=null; /**@private */ this._gradientYMin=null; /**@private */ this._gradientYMax=null; /**@private */ this._gradientZMin=null; /**@private */ this._gradientZMax=null; } __class(GradientVelocity,'laya.d3.core.particleShuriKen.module.GradientVelocity'); var __proto=GradientVelocity.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientVelocity=destObject; destGradientVelocity._type=this._type; this._constant.cloneTo(destGradientVelocity._constant); this._gradientX.cloneTo(destGradientVelocity._gradientX); this._gradientY.cloneTo(destGradientVelocity._gradientY); this._gradientZ.cloneTo(destGradientVelocity._gradientZ); this._constantMin.cloneTo(destGradientVelocity._constantMin); this._constantMax.cloneTo(destGradientVelocity._constantMax); this._gradientXMin.cloneTo(destGradientVelocity._gradientXMin); this._gradientXMax.cloneTo(destGradientVelocity._gradientXMax); this._gradientYMin.cloneTo(destGradientVelocity._gradientYMin); this._gradientYMax.cloneTo(destGradientVelocity._gradientYMax); this._gradientZMin.cloneTo(destGradientVelocity._gradientZMin); this._gradientZMax.cloneTo(destGradientVelocity._gradientZMax); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientVelocity=/*__JS__ */new this.constructor(); this.cloneTo(destGradientVelocity); return destGradientVelocity; } /** *渐变速度Z。 */ __getset(0,__proto,'gradientZ',function(){ return this._gradientZ; }); /**固定速度。*/ __getset(0,__proto,'constant',function(){ return this._constant; }); /** *生命周期速度类型,0常量模式,1曲线模式,2随机双常量模式,3随机双曲线模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *渐变最大速度X。 */ __getset(0,__proto,'gradientXMax',function(){ return this._gradientXMax; }); /**最小固定速度。*/ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *渐变速度X。 */ __getset(0,__proto,'gradientX',function(){ return this._gradientX; }); /** *渐变速度Y。 */ __getset(0,__proto,'gradientY',function(){ return this._gradientY; }); /** *渐变最小速度X。 */ __getset(0,__proto,'gradientXMin',function(){ return this._gradientXMin; }); /**最大固定速度。*/ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); /** *渐变最小速度Y。 */ __getset(0,__proto,'gradientYMin',function(){ return this._gradientYMin; }); /** *渐变最大速度Y。 */ __getset(0,__proto,'gradientYMax',function(){ return this._gradientYMax; }); /** *渐变最小速度Z。 */ __getset(0,__proto,'gradientZMin',function(){ return this._gradientZMin; }); /** *渐变最大速度Z。 */ __getset(0,__proto,'gradientZMax',function(){ return this._gradientZMax; }); GradientVelocity.createByConstant=function(constant){ var gradientVelocity=new GradientVelocity(); gradientVelocity._type=0; gradientVelocity._constant=constant; return gradientVelocity; } GradientVelocity.createByGradient=function(gradientX,gradientY,gradientZ){ var gradientVelocity=new GradientVelocity(); gradientVelocity._type=1; gradientVelocity._gradientX=gradientX; gradientVelocity._gradientY=gradientY; gradientVelocity._gradientZ=gradientZ; return gradientVelocity; } GradientVelocity.createByRandomTwoConstant=function(constantMin,constantMax){ var gradientVelocity=new GradientVelocity(); gradientVelocity._type=2; gradientVelocity._constantMin=constantMin; gradientVelocity._constantMax=constantMax; return gradientVelocity; } GradientVelocity.createByRandomTwoGradient=function(gradientXMin,gradientXMax,gradientYMin,gradientYMax,gradientZMin,gradientZMax){ var gradientVelocity=new GradientVelocity(); gradientVelocity._type=3; gradientVelocity._gradientXMin=gradientXMin; gradientVelocity._gradientXMax=gradientXMax; gradientVelocity._gradientYMin=gradientYMin; gradientVelocity._gradientYMax=gradientYMax; gradientVelocity._gradientZMin=gradientZMin; gradientVelocity._gradientZMax=gradientZMax; return gradientVelocity; } return GradientVelocity; })() /** *RotationOverLifetime 类用于粒子的生命周期旋转。 */ //class laya.d3.core.particleShuriKen.module.RotationOverLifetime var RotationOverLifetime=(function(){ function RotationOverLifetime(angularVelocity){ /**@private */ this._angularVelocity=null; /**是否启用*/ this.enbale=false; this._angularVelocity=angularVelocity; } __class(RotationOverLifetime,'laya.d3.core.particleShuriKen.module.RotationOverLifetime'); var __proto=RotationOverLifetime.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destRotationOverLifetime=destObject; this._angularVelocity.cloneTo(destRotationOverLifetime._angularVelocity); destRotationOverLifetime.enbale=this.enbale; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destAngularVelocity; switch (this._angularVelocity.type){ case 0: if (this._angularVelocity.separateAxes) destAngularVelocity=GradientAngularVelocity.createByConstantSeparate(this._angularVelocity.constantSeparate.clone()); else destAngularVelocity=GradientAngularVelocity.createByConstant(this._angularVelocity.constant); break ; case 1: if (this._angularVelocity.separateAxes) destAngularVelocity=GradientAngularVelocity.createByGradientSeparate(this._angularVelocity.gradientX.clone(),this._angularVelocity.gradientY.clone(),this._angularVelocity.gradientZ.clone(),this._angularVelocity.gradientW.clone()); else destAngularVelocity=GradientAngularVelocity.createByGradient(this._angularVelocity.gradient.clone()); break ; case 2: if (this._angularVelocity.separateAxes) destAngularVelocity=GradientAngularVelocity.createByRandomTwoConstantSeparate(this._angularVelocity.constantMinSeparate.clone(),this._angularVelocity.constantMaxSeparate.clone()); else destAngularVelocity=GradientAngularVelocity.createByRandomTwoConstant(this._angularVelocity.constantMin,this._angularVelocity.constantMax); break ; case 3: if (this._angularVelocity.separateAxes) destAngularVelocity=GradientAngularVelocity.createByRandomTwoGradientSeparate(this._angularVelocity.gradientXMin.clone(),this._angularVelocity.gradientYMin.clone(),this._angularVelocity.gradientZMin.clone(),this._angularVelocity.gradientWMin.clone(),this._angularVelocity.gradientXMax.clone(),this._angularVelocity.gradientYMax.clone(),this._angularVelocity.gradientZMax.clone(),this._angularVelocity.gradientWMax.clone()); else destAngularVelocity=GradientAngularVelocity.createByRandomTwoGradient(this._angularVelocity.gradientMin.clone(),this._angularVelocity.gradientMax.clone()); break ; }; var destRotationOverLifetime=/*__JS__ */new this.constructor(destAngularVelocity); destRotationOverLifetime.enbale=this.enbale; return destRotationOverLifetime; } /** *获取角速度。 */ __getset(0,__proto,'angularVelocity',function(){ return this._angularVelocity; }); return RotationOverLifetime; })() /** *BaseShape 类用于粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.BaseShape var BaseShape=(function(){ function BaseShape(){ /**是否启用。*/ this.enable=false; /**随机方向。*/ this.randomDirection=false; } __class(BaseShape,'laya.d3.core.particleShuriKen.module.shape.BaseShape'); var __proto=BaseShape.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /**@private */ __proto._getShapeBoundBox=function(boundBox){ throw new Error("BaseShape: must override it."); } /**@private */ __proto._getSpeedBoundBox=function(boundBox){ throw new Error("BaseShape: must override it."); } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ throw new Error("BaseShape: must override it."); } /** *@private */ __proto._calculateProceduralBounds=function(boundBox,emitterPosScale,minMaxBounds){ this._getShapeBoundBox(boundBox); var min=boundBox.min; var max=boundBox.max; Vector3.multiply(min,emitterPosScale,min); Vector3.multiply(max,emitterPosScale,max); var speedBounds=new BoundBox(new Vector3(),new Vector3()); if (this.randomDirection){ speedBounds.min=new Vector3(-1,-1,-1); speedBounds.max=new Vector3(1,1,1); } else{ this._getSpeedBoundBox(speedBounds); }; var maxSpeedBound=new BoundBox(new Vector3(),new Vector3()); var maxSpeedMin=maxSpeedBound.min; var maxSpeedMax=maxSpeedBound.max; Vector3.scale(speedBounds.min,minMaxBounds.y,maxSpeedMin); Vector3.scale(speedBounds.max,minMaxBounds.y,maxSpeedMax); Vector3.add(boundBox.min,maxSpeedMin,maxSpeedMin); Vector3.add(boundBox.max,maxSpeedMax,maxSpeedMax); Vector3.min(boundBox.min,maxSpeedMin,boundBox.min); Vector3.max(boundBox.max,maxSpeedMin,boundBox.max); var minSpeedBound=new BoundBox(new Vector3(),new Vector3()); var minSpeedMin=minSpeedBound.min; var minSpeedMax=minSpeedBound.max; Vector3.scale(speedBounds.min,minMaxBounds.x,minSpeedMin); Vector3.scale(speedBounds.max,minMaxBounds.x,minSpeedMax); Vector3.min(minSpeedBound.min,minSpeedMax,maxSpeedMin); Vector3.max(minSpeedBound.min,minSpeedMax,maxSpeedMax); Vector3.min(boundBox.min,maxSpeedMin,boundBox.min); Vector3.max(boundBox.max,maxSpeedMin,boundBox.max); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destShape=destObject; destShape.enable=this.enable; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destShape=/*__JS__ */new this.constructor(); this.cloneTo(destShape); return destShape; } return BaseShape; })() /** *... *@author ... */ //class laya.d3.core.particleShuriKen.module.shape.ShapeUtils var ShapeUtils=(function(){ function ShapeUtils(){} __class(ShapeUtils,'laya.d3.core.particleShuriKen.module.shape.ShapeUtils'); ShapeUtils._randomPointUnitArcCircle=function(arc,out,rand){ var outE=out.elements; var angle=NaN; if (rand) angle=rand.getFloat()*arc; else angle=Math.random()*arc; outE[0]=Math.cos(angle); outE[1]=Math.sin(angle); } ShapeUtils._randomPointInsideUnitArcCircle=function(arc,out,rand){ var outE=out.elements; ShapeUtils._randomPointUnitArcCircle(arc,out,rand); var range=NaN; if (rand) range=Math.pow(rand.getFloat(),1.0 / 2.0); else range=Math.pow(Math.random(),1.0 / 2.0); outE[0]=outE[0] *range; outE[1]=outE[1] *range; } ShapeUtils._randomPointUnitCircle=function(out,rand){ var outE=out.elements; var angle=NaN; if (rand) angle=rand.getFloat()*Math.PI *2; else angle=Math.random()*Math.PI *2; outE[0]=Math.cos(angle); outE[1]=Math.sin(angle); } ShapeUtils._randomPointInsideUnitCircle=function(out,rand){ var outE=out.elements; ShapeUtils._randomPointUnitCircle(out); var range=NaN; if (rand) range=Math.pow(rand.getFloat(),1.0 / 2.0); else range=Math.pow(Math.random(),1.0 / 2.0); outE[0]=outE[0] *range; outE[1]=outE[1] *range; } ShapeUtils._randomPointUnitSphere=function(out,rand){ var outE=out.elements; var z=NaN; var a=NaN; if (rand){ z=outE[2]=rand.getFloat()*2-1.0; a=rand.getFloat()*Math.PI *2; }else { z=outE[2]=Math.random()*2-1.0; a=Math.random()*Math.PI *2; }; var r=Math.sqrt(1.0-z *z); outE[0]=r *Math.cos(a); outE[1]=r *Math.sin(a); } ShapeUtils._randomPointInsideUnitSphere=function(out,rand){ var outE=out.elements; ShapeUtils._randomPointUnitSphere(out); var range=NaN; if (rand) range=Math.pow(rand.getFloat(),1.0 / 3.0); else range=Math.pow(Math.random(),1.0 / 3.0); outE[0]=outE[0] *range; outE[1]=outE[1] *range; outE[2]=outE[2] *range; } ShapeUtils._randomPointInsideHalfUnitBox=function(out,rand){ var outE=out.elements; if (rand){ outE[0]=(rand.getFloat()-0.5); outE[1]=(rand.getFloat()-0.5); outE[2]=(rand.getFloat()-0.5); }else { outE[0]=(Math.random()-0.5); outE[1]=(Math.random()-0.5); outE[2]=(Math.random()-0.5); } } return ShapeUtils; })() /** *SizeOverLifetime 类用于粒子的生命周期尺寸。 */ //class laya.d3.core.particleShuriKen.module.SizeOverLifetime var SizeOverLifetime=(function(){ function SizeOverLifetime(size){ /**@private */ this._size=null; /**是否启用*/ this.enbale=false; this._size=size; } __class(SizeOverLifetime,'laya.d3.core.particleShuriKen.module.SizeOverLifetime'); var __proto=SizeOverLifetime.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destSizeOverLifetime=destObject; this._size.cloneTo(destSizeOverLifetime._size); destSizeOverLifetime.enbale=this.enbale; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destSize; switch (this._size.type){ case 0: if (this._size.separateAxes) destSize=GradientSize.createByGradientSeparate(this._size.gradientX.clone(),this._size.gradientY.clone(),this._size.gradientZ.clone()); else destSize=GradientSize.createByGradient(this._size.gradient.clone()); break ; case 1: if (this._size.separateAxes) destSize=GradientSize.createByRandomTwoConstantSeparate(this._size.constantMinSeparate.clone(),this._size.constantMaxSeparate.clone()); else destSize=GradientSize.createByRandomTwoConstant(this._size.constantMin,this._size.constantMax); break ; case 2: if (this._size.separateAxes) destSize=GradientSize.createByRandomTwoGradientSeparate(this._size.gradientXMin.clone(),this._size.gradientYMin.clone(),this._size.gradientZMin.clone(),this._size.gradientXMax.clone(),this._size.gradientYMax.clone(),this._size.gradientZMax.clone()); else destSize=GradientSize.createByRandomTwoGradient(this._size.gradientMin.clone(),this._size.gradientMax.clone()); break ; }; var destSizeOverLifetime=/*__JS__ */new this.constructor(destSize); destSizeOverLifetime.enbale=this.enbale; return destSizeOverLifetime; } /** *获取尺寸。 */ __getset(0,__proto,'size',function(){ return this._size; }); return SizeOverLifetime; })() /** *StartFrame 类用于创建开始帧。 */ //class laya.d3.core.particleShuriKen.module.StartFrame var StartFrame=(function(){ function StartFrame(){ /**@private */ this._type=0; /**@private */ this._constant=NaN; /**@private */ this._constantMin=NaN; /**@private */ this._constantMax=NaN; } __class(StartFrame,'laya.d3.core.particleShuriKen.module.StartFrame'); var __proto=StartFrame.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destStartFrame=destObject; destStartFrame._type=this._type; destStartFrame._constant=this._constant; destStartFrame._constantMin=this._constantMin; destStartFrame._constantMax=this._constantMax; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destStartFrame=/*__JS__ */new this.constructor(); this.cloneTo(destStartFrame); return destStartFrame; } /** *固定帧。 */ __getset(0,__proto,'constant',function(){ return this._constant; }); /** *开始帧类型,0常量模式,1随机双常量模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *最小固定帧。 */ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *最大固定帧。 */ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); StartFrame.createByConstant=function(constant){ var rotationOverLifetime=new StartFrame(); rotationOverLifetime._type=0; rotationOverLifetime._constant=constant; return rotationOverLifetime; } StartFrame.createByRandomTwoConstant=function(constantMin,constantMax){ var rotationOverLifetime=new StartFrame(); rotationOverLifetime._type=1; rotationOverLifetime._constantMin=constantMin; rotationOverLifetime._constantMax=constantMax; return rotationOverLifetime; } return StartFrame; })() /** *TextureSheetAnimation 类用于创建粒子帧动画。 */ //class laya.d3.core.particleShuriKen.module.TextureSheetAnimation var TextureSheetAnimation=(function(){ function TextureSheetAnimation(frame,startFrame){ /**@private */ this._frame=null; /**@private */ this._startFrame=null; /**纹理平铺。*/ this.tiles=null; /**类型,0为whole sheet、1为singal row。*/ this.type=0; /**是否随机行,type为1时有效。*/ this.randomRow=false; /**行索引,type为1时有效。*/ this.rowIndex=0; /**循环次数。*/ this.cycles=0; /**UV通道类型,0为Noting,1为Everything,待补充,暂不支持。*/ this.enableUVChannels=0; /**是否启用*/ this.enable=false; this.tiles=new Vector2(1,1); this.type=0; this.randomRow=true; this.rowIndex=0; this.cycles=1; this.enableUVChannels=1; this._frame=frame; this._startFrame=startFrame; } __class(TextureSheetAnimation,'laya.d3.core.particleShuriKen.module.TextureSheetAnimation'); var __proto=TextureSheetAnimation.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destTextureSheetAnimation=destObject; this.tiles.cloneTo(destTextureSheetAnimation.tiles); destTextureSheetAnimation.type=this.type; destTextureSheetAnimation.randomRow=this.randomRow; this._frame.cloneTo(destTextureSheetAnimation._frame); this._startFrame.cloneTo(destTextureSheetAnimation._startFrame); destTextureSheetAnimation.cycles=this.cycles; destTextureSheetAnimation.enableUVChannels=this.enableUVChannels; destTextureSheetAnimation.enable=this.enable; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destFrame; switch (this._frame.type){ case 0: destFrame=FrameOverTime.createByConstant(this._frame.constant); break ; case 1: destFrame=FrameOverTime.createByOverTime(this._frame.frameOverTimeData.clone()); break ; case 2: destFrame=FrameOverTime.createByRandomTwoConstant(this._frame.constantMin,this._frame.constantMax); break ; case 3: destFrame=FrameOverTime.createByRandomTwoOverTime(this._frame.frameOverTimeDataMin.clone(),this._frame.frameOverTimeDataMax.clone()); break ; }; var destStartFrame; switch (this._startFrame.type){ case 0: destStartFrame=StartFrame.createByConstant(this._startFrame.constant); break ; case 1: destStartFrame=StartFrame.createByRandomTwoConstant(this._startFrame.constantMin,this._startFrame.constantMax); break ; }; var destTextureSheetAnimation=/*__JS__ */new this.constructor(destFrame,destStartFrame); this.tiles.cloneTo(destTextureSheetAnimation.tiles); destTextureSheetAnimation.type=this.type; destTextureSheetAnimation.randomRow=this.randomRow; destTextureSheetAnimation.cycles=this.cycles; destTextureSheetAnimation.enableUVChannels=this.enableUVChannels; destTextureSheetAnimation.enable=this.enable; return destTextureSheetAnimation; } /**获取时间帧率。*/ __getset(0,__proto,'frame',function(){ return this._frame; }); /**获取开始帧率。*/ __getset(0,__proto,'startFrame',function(){ return this._startFrame; }); return TextureSheetAnimation; })() /** *VelocityOverLifetime 类用于粒子的生命周期速度。 */ //class laya.d3.core.particleShuriKen.module.VelocityOverLifetime var VelocityOverLifetime=(function(){ function VelocityOverLifetime(velocity){ /**@private */ this._velocity=null; /**是否启用*/ this.enbale=false; /**速度空间,0为local,1为world。*/ this.space=0; this._velocity=velocity; } __class(VelocityOverLifetime,'laya.d3.core.particleShuriKen.module.VelocityOverLifetime'); var __proto=VelocityOverLifetime.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destVelocityOverLifetime=destObject; this._velocity.cloneTo(destVelocityOverLifetime._velocity); destVelocityOverLifetime.enbale=this.enbale; destVelocityOverLifetime.space=this.space; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destVelocity; switch(this._velocity.type){ case 0: destVelocity=GradientVelocity.createByConstant(this._velocity.constant.clone()); break ; case 1: destVelocity=GradientVelocity.createByGradient(this._velocity.gradientX.clone(),this._velocity.gradientY.clone(),this._velocity.gradientZ.clone()); break ; case 2: destVelocity=GradientVelocity.createByRandomTwoConstant(this._velocity.constantMin.clone(),this._velocity.constantMax.clone()); break ; case 3: destVelocity=GradientVelocity.createByRandomTwoGradient(this._velocity.gradientXMin.clone(),this._velocity.gradientYMin.clone(),this._velocity.gradientZMin.clone(),this._velocity.gradientXMax.clone(),this._velocity.gradientYMax.clone(),this._velocity.gradientZMax.clone()); break ; }; var destVelocityOverLifetime=/*__JS__ */new this.constructor(destVelocity); destVelocityOverLifetime.enbale=this.enbale; destVelocityOverLifetime.space=this.space; return destVelocityOverLifetime; } /** *获取尺寸。 */ __getset(0,__proto,'velocity',function(){ return this._velocity; }); return VelocityOverLifetime; })() /** *@private */ //class laya.d3.core.particleShuriKen.ShurikenParticleData var ShurikenParticleData=(function(){ function ShurikenParticleData(){} __class(ShurikenParticleData,'laya.d3.core.particleShuriKen.ShurikenParticleData'); ShurikenParticleData._getStartLifetimeFromGradient=function(startLifeTimeGradient,emissionTime){ for (var i=1,n=startLifeTimeGradient.gradientCount;i < n;i++){ var key=startLifeTimeGradient.getKeyByIndex(i); if (key >=emissionTime){ var lastKey=startLifeTimeGradient.getKeyByIndex(i-1); var age=(emissionTime-lastKey)/ (key-lastKey); return MathUtil.lerp(startLifeTimeGradient.getValueByIndex(i-1),startLifeTimeGradient.getValueByIndex(i),age) } } throw new Error("ShurikenParticleData: can't get value foam startLifeTimeGradient."); } ShurikenParticleData._randomInvertRoationArray=function(rotatonE,outE,randomizeRotationDirection,rand,randomSeeds){ var randDic=NaN; if (rand){ rand.seed=randomSeeds[6]; randDic=rand.getFloat(); randomSeeds[6]=rand.seed; }else { randDic=Math.random(); } if (randDic < randomizeRotationDirection){ outE[0]=-rotatonE[0]; outE[1]=-rotatonE[1]; outE[2]=-rotatonE[2]; }else { outE[0]=rotatonE[0]; outE[1]=rotatonE[1]; outE[2]=rotatonE[2]; } } ShurikenParticleData._randomInvertRoation=function(rotaton,randomizeRotationDirection,rand,randomSeeds){ var randDic=NaN; if (rand){ rand.seed=randomSeeds[6]; randDic=rand.getFloat(); randomSeeds[6]=rand.seed; }else { randDic=Math.random(); } if (randDic < randomizeRotationDirection) rotaton=-rotaton; return rotaton; } ShurikenParticleData.create=function(particleSystem,particleRender,transform){ var autoRandomSeed=particleSystem.autoRandomSeed; var rand=particleSystem._rand; var randomSeeds=particleSystem._randomSeeds; switch (particleSystem.startColorType){ case 0:; var constantStartColorE=particleSystem.startColorConstant.elements; ShurikenParticleData.startColor[0]=constantStartColorE[0]; ShurikenParticleData.startColor[1]=constantStartColorE[1]; ShurikenParticleData.startColor[2]=constantStartColorE[2]; ShurikenParticleData.startColor[3]=constantStartColorE[3]; break ; case 2: if (autoRandomSeed){ MathUtil.lerpVector4(particleSystem.startColorConstantMin.elements,particleSystem.startColorConstantMax.elements,Math.random(),ShurikenParticleData.startColor); }else { rand.seed=randomSeeds[3]; MathUtil.lerpVector4(particleSystem.startColorConstantMin.elements,particleSystem.startColorConstantMax.elements,rand.getFloat(),ShurikenParticleData.startColor); randomSeeds[3]=rand.seed; } break ; }; var colorOverLifetime=particleSystem.colorOverLifetime; if (colorOverLifetime && colorOverLifetime.enbale){ var color=colorOverLifetime.color; switch (color.type){ case 0: ShurikenParticleData.startColor[0]=ShurikenParticleData.startColor[0] *color.constant.x; ShurikenParticleData.startColor[1]=ShurikenParticleData.startColor[1] *color.constant.y; ShurikenParticleData.startColor[2]=ShurikenParticleData.startColor[2] *color.constant.z; ShurikenParticleData.startColor[3]=ShurikenParticleData.startColor[3] *color.constant.w; break ; case 2:; var colorRandom=NaN; if (autoRandomSeed){ colorRandom=Math.random(); }else { rand.seed=randomSeeds[10]; colorRandom=rand.getFloat(); randomSeeds[10]=rand.seed; }; var minConstantColor=color.constantMin; var maxConstantColor=color.constantMax; ShurikenParticleData.startColor[0]=ShurikenParticleData.startColor[0] *MathUtil.lerp(minConstantColor.x,maxConstantColor.x,colorRandom); ShurikenParticleData.startColor[1]=ShurikenParticleData.startColor[1] *MathUtil.lerp(minConstantColor.y,maxConstantColor.y,colorRandom); ShurikenParticleData.startColor[2]=ShurikenParticleData.startColor[2] *MathUtil.lerp(minConstantColor.z,maxConstantColor.z,colorRandom); ShurikenParticleData.startColor[3]=ShurikenParticleData.startColor[3] *MathUtil.lerp(minConstantColor.w,maxConstantColor.w,colorRandom); break ; } }; var particleSize=ShurikenParticleData.startSize; switch (particleSystem.startSizeType){ case 0: if (particleSystem.threeDStartSize){ var startSizeConstantSeparate=particleSystem.startSizeConstantSeparate; particleSize[0]=startSizeConstantSeparate.x; particleSize[1]=startSizeConstantSeparate.y; particleSize[2]=startSizeConstantSeparate.z; }else { particleSize[0]=particleSize[1]=particleSize[2]=particleSystem.startSizeConstant; } break ; case 2: if (particleSystem.threeDStartSize){ var startSizeConstantMinSeparate=particleSystem.startSizeConstantMinSeparate; var startSizeConstantMaxSeparate=particleSystem.startSizeConstantMaxSeparate; if (autoRandomSeed){ particleSize[0]=MathUtil.lerp(startSizeConstantMinSeparate.x,startSizeConstantMaxSeparate.x,Math.random()); particleSize[1]=MathUtil.lerp(startSizeConstantMinSeparate.y,startSizeConstantMaxSeparate.y,Math.random()); particleSize[2]=MathUtil.lerp(startSizeConstantMinSeparate.z,startSizeConstantMaxSeparate.z,Math.random()); }else { rand.seed=randomSeeds[4]; particleSize[0]=MathUtil.lerp(startSizeConstantMinSeparate.x,startSizeConstantMaxSeparate.x,rand.getFloat()); particleSize[1]=MathUtil.lerp(startSizeConstantMinSeparate.y,startSizeConstantMaxSeparate.y,rand.getFloat()); particleSize[2]=MathUtil.lerp(startSizeConstantMinSeparate.z,startSizeConstantMaxSeparate.z,rand.getFloat()); randomSeeds[4]=rand.seed; } }else { if (autoRandomSeed){ particleSize[0]=particleSize[1]=particleSize[2]=MathUtil.lerp(particleSystem.startSizeConstantMin,particleSystem.startSizeConstantMax,Math.random()); }else { rand.seed=randomSeeds[4]; particleSize[0]=particleSize[1]=particleSize[2]=MathUtil.lerp(particleSystem.startSizeConstantMin,particleSystem.startSizeConstantMax,rand.getFloat()); randomSeeds[4]=rand.seed; } } break ; }; var sizeOverLifetime=particleSystem.sizeOverLifetime; if (sizeOverLifetime && sizeOverLifetime.enbale && sizeOverLifetime.size.type===1){ var size=sizeOverLifetime.size; if (size.separateAxes){ if (autoRandomSeed){ particleSize[0]=particleSize[0] *MathUtil.lerp(size.constantMinSeparate.x,size.constantMaxSeparate.x,Math.random()); particleSize[1]=particleSize[1] *MathUtil.lerp(size.constantMinSeparate.y,size.constantMaxSeparate.y,Math.random()); particleSize[2]=particleSize[2] *MathUtil.lerp(size.constantMinSeparate.z,size.constantMaxSeparate.z,Math.random()); }else { rand.seed=randomSeeds[11]; particleSize[0]=particleSize[0] *MathUtil.lerp(size.constantMinSeparate.x,size.constantMaxSeparate.x,rand.getFloat()); particleSize[1]=particleSize[1] *MathUtil.lerp(size.constantMinSeparate.y,size.constantMaxSeparate.y,rand.getFloat()); particleSize[2]=particleSize[2] *MathUtil.lerp(size.constantMinSeparate.z,size.constantMaxSeparate.z,rand.getFloat()); randomSeeds[11]=rand.seed; } }else { var randomSize=NaN; if (autoRandomSeed){ randomSize=MathUtil.lerp(size.constantMin,size.constantMax,Math.random()); }else { rand.seed=randomSeeds[11]; randomSize=MathUtil.lerp(size.constantMin,size.constantMax,rand.getFloat()); randomSeeds[11]=rand.seed; } particleSize[0]=particleSize[0] *randomSize; particleSize[1]=particleSize[1] *randomSize; particleSize[2]=particleSize[2] *randomSize; } }; var renderMode=particleRender.renderMode; if (renderMode!==1){ switch (particleSystem.startRotationType){ case 0: if (particleSystem.threeDStartRotation){ var startRotationConstantSeparate=particleSystem.startRotationConstantSeparate; var randomRotationE=ShurikenParticleData._tempVector30.elements; ShurikenParticleData._randomInvertRoationArray(startRotationConstantSeparate.elements,randomRotationE,particleSystem.randomizeRotationDirection,autoRandomSeed ? null :rand,randomSeeds); ShurikenParticleData.startRotation[0]=randomRotationE[0]; ShurikenParticleData.startRotation[1]=randomRotationE[1]; if (renderMode!==4) ShurikenParticleData.startRotation[2]=-randomRotationE[2]; else ShurikenParticleData.startRotation[2]=randomRotationE[2]; }else { ShurikenParticleData.startRotation[0]=ShurikenParticleData._randomInvertRoation(particleSystem.startRotationConstant,particleSystem.randomizeRotationDirection,autoRandomSeed ? null :rand,randomSeeds); } break ; case 2: if (particleSystem.threeDStartRotation){ var startRotationConstantMinSeparate=particleSystem.startRotationConstantMinSeparate; var startRotationConstantMaxSeparate=particleSystem.startRotationConstantMaxSeparate; var lerpRoationE=ShurikenParticleData._tempVector30.elements; if (autoRandomSeed){ lerpRoationE[0]=MathUtil.lerp(startRotationConstantMinSeparate.x,startRotationConstantMaxSeparate.x,Math.random()); lerpRoationE[1]=MathUtil.lerp(startRotationConstantMinSeparate.y,startRotationConstantMaxSeparate.y,Math.random()); lerpRoationE[2]=MathUtil.lerp(startRotationConstantMinSeparate.z,startRotationConstantMaxSeparate.z,Math.random()); }else { rand.seed=randomSeeds[5]; lerpRoationE[0]=MathUtil.lerp(startRotationConstantMinSeparate.x,startRotationConstantMaxSeparate.x,rand.getFloat()); lerpRoationE[1]=MathUtil.lerp(startRotationConstantMinSeparate.y,startRotationConstantMaxSeparate.y,rand.getFloat()); lerpRoationE[2]=MathUtil.lerp(startRotationConstantMinSeparate.z,startRotationConstantMaxSeparate.z,rand.getFloat()); randomSeeds[5]=rand.seed; } ShurikenParticleData._randomInvertRoationArray(lerpRoationE,lerpRoationE,particleSystem.randomizeRotationDirection,autoRandomSeed ? null :rand,randomSeeds); ShurikenParticleData.startRotation[0]=lerpRoationE[0]; ShurikenParticleData.startRotation[1]=lerpRoationE[1]; if (renderMode!==4) ShurikenParticleData.startRotation[2]=-lerpRoationE[2]; else ShurikenParticleData.startRotation[2]=lerpRoationE[2]; }else { if (autoRandomSeed){ ShurikenParticleData.startRotation[0]=ShurikenParticleData._randomInvertRoation(MathUtil.lerp(particleSystem.startRotationConstantMin,particleSystem.startRotationConstantMax,Math.random()),particleSystem.randomizeRotationDirection,autoRandomSeed ? null :rand,randomSeeds); }else { rand.seed=randomSeeds[5]; ShurikenParticleData.startRotation[0]=ShurikenParticleData._randomInvertRoation(MathUtil.lerp(particleSystem.startRotationConstantMin,particleSystem.startRotationConstantMax,rand.getFloat()),particleSystem.randomizeRotationDirection,autoRandomSeed ? null :rand,randomSeeds); randomSeeds[5]=rand.seed; } } break ; } } switch (particleSystem.startLifetimeType){ case 0: ShurikenParticleData.startLifeTime=particleSystem.startLifetimeConstant; break ; case 1: ShurikenParticleData.startLifeTime=ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradient,particleSystem.emissionTime); break ; case 2: if (autoRandomSeed){ ShurikenParticleData.startLifeTime=MathUtil.lerp(particleSystem.startLifetimeConstantMin,particleSystem.startLifetimeConstantMax,Math.random()); }else { rand.seed=randomSeeds[7]; ShurikenParticleData.startLifeTime=MathUtil.lerp(particleSystem.startLifetimeConstantMin,particleSystem.startLifetimeConstantMax,rand.getFloat()); randomSeeds[7]=rand.seed; } break ; case 3:; var emissionTime=particleSystem.emissionTime; if (autoRandomSeed){ ShurikenParticleData.startLifeTime=MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin,emissionTime),ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax,emissionTime),Math.random()); }else { rand.seed=randomSeeds[7]; ShurikenParticleData.startLifeTime=MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin,emissionTime),ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax,emissionTime),rand.getFloat()); randomSeeds[7]=rand.seed; } break ; } switch (particleSystem.startSpeedType){ case 0: ShurikenParticleData.startSpeed=particleSystem.startSpeedConstant; break ; case 2: if (autoRandomSeed){ ShurikenParticleData.startSpeed=MathUtil.lerp(particleSystem.startSpeedConstantMin,particleSystem.startSpeedConstantMax,Math.random()); }else { rand.seed=randomSeeds[8]; ShurikenParticleData.startSpeed=MathUtil.lerp(particleSystem.startSpeedConstantMin,particleSystem.startSpeedConstantMax,rand.getFloat()); randomSeeds[8]=rand.seed; } break ; }; var textureSheetAnimation=particleSystem.textureSheetAnimation; var enableSheetAnimation=textureSheetAnimation && textureSheetAnimation.enable; if (enableSheetAnimation){ var title=textureSheetAnimation.tiles; var titleX=title.x,titleY=title.y; var subU=1.0 / titleX,subV=1.0 / titleY; var startFrameCount=0; var startFrame=textureSheetAnimation.startFrame; switch (startFrame.type){ case 0: startFrameCount=startFrame.constant; break ; case 1: if (autoRandomSeed){ startFrameCount=MathUtil.lerp(startFrame.constantMin,startFrame.constantMax,Math.random()); }else { rand.seed=randomSeeds[14]; startFrameCount=MathUtil.lerp(startFrame.constantMin,startFrame.constantMax,rand.getFloat()); randomSeeds[14]=rand.seed; } break ; }; var frame=textureSheetAnimation.frame; switch (frame.type){ case 0: startFrameCount+=frame.constant; break ; case 2: if (autoRandomSeed){ startFrameCount+=MathUtil.lerp(frame.constantMin,frame.constantMax,Math.random()); }else { rand.seed=randomSeeds[15]; startFrameCount+=MathUtil.lerp(frame.constantMin,frame.constantMax,rand.getFloat()); randomSeeds[15]=rand.seed; } break ; }; var startRow=0; switch (textureSheetAnimation.type){ case 0: startRow=Math.floor(startFrameCount / titleX); break ; case 1: if (textureSheetAnimation.randomRow){ if (autoRandomSeed){ startRow=Math.floor(Math.random()*titleY); }else { rand.seed=randomSeeds[13]; startRow=Math.floor(rand.getFloat()*titleY); randomSeeds[13]=rand.seed; } }else { startRow=textureSheetAnimation.rowIndex; } break ; }; var startCol=Math.floor(startFrameCount % titleX); ShurikenParticleData.startUVInfo=ShurikenParticleData.startUVInfo; ShurikenParticleData.startUVInfo[0]=subU; ShurikenParticleData.startUVInfo[1]=subV; ShurikenParticleData.startUVInfo[2]=startCol *subU; ShurikenParticleData.startUVInfo[3]=startRow *subV; }else { ShurikenParticleData.startUVInfo=ShurikenParticleData.startUVInfo; ShurikenParticleData.startUVInfo[0]=1.0; ShurikenParticleData.startUVInfo[1]=1.0; ShurikenParticleData.startUVInfo[2]=0.0; ShurikenParticleData.startUVInfo[3]=0.0; } switch (particleSystem.simulationSpace){ case 0:; var positionE=transform.position.elements; ShurikenParticleData.simulationWorldPostion[0]=positionE[0]; ShurikenParticleData.simulationWorldPostion[1]=positionE[1]; ShurikenParticleData.simulationWorldPostion[2]=positionE[2]; var rotationE=transform.rotation.elements; ShurikenParticleData.simulationWorldRotation[0]=rotationE[0]; ShurikenParticleData.simulationWorldRotation[1]=rotationE[1]; ShurikenParticleData.simulationWorldRotation[2]=rotationE[2]; ShurikenParticleData.simulationWorldRotation[3]=rotationE[3]; break ; case 1: break ; default : throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid."); break ; } } ShurikenParticleData.startLifeTime=NaN; ShurikenParticleData.startSpeed=NaN; __static(ShurikenParticleData, ['_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempQuaternion',function(){return this._tempQuaternion=new Quaternion();},'startColor',function(){return this.startColor=new Float32Array(4);},'startSize',function(){return this.startSize=new Float32Array(3);},'startRotation',function(){return this.startRotation=new Float32Array(3);},'startUVInfo',function(){return this.startUVInfo=new Float32Array(4);},'simulationWorldPostion',function(){return this.simulationWorldPostion=new Float32Array(3);},'simulationWorldRotation',function(){return this.simulationWorldRotation=new Float32Array(4);} ]); return ShurikenParticleData; })() /** *@private *PhasorSpriter3D 类用于创建矢量笔刷。 */ //class laya.d3.core.PhasorSpriter3D var PhasorSpriter3D=(function(){ function PhasorSpriter3D(){ this._tempInt0=0; this._tempInt1=0; this._tempUint0=0; this._tempUint1=0; this._tempUint2=0; this._tempUint3=0; this._tempUint4=0; this._tempUint5=0; this._tempUint6=0; this._tempUint7=0; this._tempNumver0=NaN; this._tempNumver1=NaN; this._tempNumver2=NaN; this._tempNumver3=NaN; this._floatSizePerVer=7; //顶点结构为Position(3个float)+Color(4个float) this._defaultBufferSize=600 *this._floatSizePerVer; this._vb=null; this._posInVBData=0; this._ib=null; this._posInIBData=0; this._primitiveType=NaN; this._hasBegun=false; this._numVertsPerPrimitive=0; this._camera=null; this._sharderNameID=0; this._shader=null; /**@private */ this._shaderCompile=null; this._vbData=new Float32Array(this._defaultBufferSize); this._ibData=new Uint16Array(this._defaultBufferSize); this._spriteShaderValue=new ValusArray(); ; this._vb=VertexBuffer3D.create(PhasorSpriter3D._vertexDeclaration,this._defaultBufferSize / this._floatSizePerVer,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._ib=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._defaultBufferSize,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._sharderNameID=Shader3D.nameKey.getID("LINE"); this._shaderCompile=ShaderCompile3D._preCompileShader[this._sharderNameID]; } __class(PhasorSpriter3D,'laya.d3.core.PhasorSpriter3D'); var __proto=PhasorSpriter3D.prototype; __proto.line=function(startPosition,startColor,endPosition,endColor){ if (!this._hasBegun || this._primitiveType!==/*laya.webgl.WebGLContext.LINES*/0x0001) this.drawLinesException(); if (this._posInVBData+2 *this._floatSizePerVer > this._vbData.length || this._posInIBData+2 > this._ibData.length) this.flush(); this._tempUint0=this._posInVBData / this._floatSizePerVer; this.addVertex(startPosition.x,startPosition.y,startPosition.z,startColor.x,startColor.y,startColor.z,startColor.w); this.addVertex(endPosition.x,endPosition.y,endPosition.z,endColor.x,endColor.y,endColor.z,endColor.w); this.addIndexes(this._tempUint0,this._tempUint0+1); return this; } __proto.circle=function(radius,numberOfPoints,r,g,b,a){ if (!this._hasBegun || (this._primitiveType!==/*laya.webgl.WebGLContext.LINES*/0x0001)) this.drawLinesException(); this._tempUint0=numberOfPoints *2; if (this._posInVBData+this._tempUint0 *this._floatSizePerVer > this._vbData.length || this._posInIBData+2 *this._tempUint0 > this._ibData.length) this.flush(); this._tempUint1=this._posInVBData / this._floatSizePerVer; for (this._tempNumver0=0,this._tempInt0=0;this._tempNumver0 < 3.1416 *2;this._tempNumver0=this._tempNumver0+(3.1416 / numberOfPoints),this._tempInt0++){ this.addVertex(Math.sin(this._tempNumver0)*radius,Math.cos(this._tempNumver0)*radius,0,r,g,b,a); if (this._tempInt0===0){ this.addIndexes(this._tempUint1); }else if (this._tempInt0===this._tempUint0-1){ this._tempUint2=this._tempUint1+this._tempInt0; this.addIndexes(this._tempUint2,this._tempUint2,this._tempUint1); }else { this._tempUint2=this._tempUint1+this._tempInt0; this.addIndexes(this._tempUint2,this._tempUint2); } } return this; } __proto.plane=function(positionX,positionY,positionZ,width,height,r,g,b,a){ if (!this._hasBegun || this._primitiveType!==/*laya.webgl.WebGLContext.TRIANGLES*/0x0004) this.drawTrianglesException(); if (this._posInVBData+4 *this._floatSizePerVer > this._vbData.length || this._posInIBData+6 > this._ibData.length) this.flush(); this._tempNumver0=width / 2; this._tempNumver1=height / 2; this._tempUint0=this._posInVBData / this._floatSizePerVer; this.addVertex(positionX-this._tempNumver0,positionY+this._tempNumver1,positionZ,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY+this._tempNumver1,positionZ,r,g,b,a); this.addVertex(positionX-this._tempNumver0,positionY-this._tempNumver1,positionZ,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY-this._tempNumver1,positionZ,r,g,b,a); this._tempUint1=this._tempUint0+1; this._tempUint2=this._tempUint0+2; this.addIndexes(this._tempUint0,this._tempUint1,this._tempUint2,this._tempUint2,this._tempUint1,this._tempUint0+3); return this; } __proto.box=function(positionX,positionY,positionZ,width,height,depth,r,g,b,a){ if (!this._hasBegun || this._primitiveType!==/*laya.webgl.WebGLContext.TRIANGLES*/0x0004) this.drawTrianglesException(); if (this._posInVBData+8 *this._floatSizePerVer > this._vbData.length || this._posInIBData+36 > this._ibData.length) this.flush(); this._tempNumver0=width / 2; this._tempNumver1=height / 2; this._tempNumver2=depth / 2; this._tempUint0=this._posInVBData / this._floatSizePerVer; this.addVertex(positionX-this._tempNumver0,positionY+this._tempNumver1,positionZ+this._tempNumver2,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY+this._tempNumver1,positionZ+this._tempNumver2,r,g,b,a); this.addVertex(positionX-this._tempNumver0,positionY-this._tempNumver1,positionZ+this._tempNumver2,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY-this._tempNumver1,positionZ+this._tempNumver2,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY+this._tempNumver1,positionZ-this._tempNumver2,r,g,b,a); this.addVertex(positionX-this._tempNumver0,positionY+this._tempNumver1,positionZ-this._tempNumver2,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY-this._tempNumver1,positionZ-this._tempNumver2,r,g,b,a); this.addVertex(positionX-this._tempNumver0,positionY-this._tempNumver1,positionZ-this._tempNumver2,r,g,b,a); this._tempUint1=this._tempUint0+1; this._tempUint2=this._tempUint0+2; this._tempUint3=this._tempUint0+3; this._tempUint4=this._tempUint0+4; this._tempUint5=this._tempUint0+5; this._tempUint6=this._tempUint0+6; this._tempUint7=this._tempUint0+7; this.addIndexes(this._tempUint0,this._tempUint1,this._tempUint2,this._tempUint2,this._tempUint1,this._tempUint3, this._tempUint4,this._tempUint5,this._tempUint6,this._tempUint6,this._tempUint5,this._tempUint7, this._tempUint5,this._tempUint0,this._tempUint7,this._tempUint7,this._tempUint0,this._tempUint2, this._tempUint1,this._tempUint4,this._tempUint3,this._tempUint3,this._tempUint4,this._tempUint6, this._tempUint5,this._tempUint4,this._tempUint0,this._tempUint0,this._tempUint4,this._tempUint1, this._tempUint2,this._tempUint3,this._tempUint7,this._tempUint7,this._tempUint3,this._tempUint6); return this; } __proto.cone=function(radius,length,Slices,r,g,b,a){ if (!this._hasBegun || this._primitiveType!==/*laya.webgl.WebGLContext.TRIANGLES*/0x0004) this.drawTrianglesException(); if (this._posInVBData+(2 *Slices+2)*this._floatSizePerVer > this._vbData.length || this._posInIBData+6 *Slices > this._ibData.length) this.flush(); this._tempUint0=this._posInVBData; this._tempUint1=this._posInVBData / this._floatSizePerVer; this._tempNumver0=Math.PI *2 / Slices; this.addVertexIndex(0,length,0,r,g,b,a,this._tempUint0); this.addVertexIndex(0,0,0,r,g,b,a,this._tempUint0+this._floatSizePerVer); this._tempInt0=2; this._tempNumver1=0; for (this._tempInt1=0;this._tempInt1 < Slices;this._tempInt1++){ this._tempNumver2=Math.cos(this._tempNumver1); this._tempNumver3=Math.sin(this._tempNumver1); this.addVertexIndex(radius *this._tempNumver2,0,radius *this._tempNumver3,r,g,b,a,this._tempUint0+this._tempInt0 *this._floatSizePerVer); this.addIndexes(this._tempUint1,this._tempUint1+this._tempInt0); if (this._tempInt1==Slices-1) this.addIndexes(this._tempUint1+2); else this.addIndexes(this._tempUint1+this._tempInt0+1); this.addVertexIndex(radius *this._tempNumver2,0,radius *this._tempNumver3,r,g,b,a,this._tempUint0+(this._tempInt0+Slices)*this._floatSizePerVer); this.addIndexes(this._tempUint1+1); if (this._tempInt1==Slices-1) this.addIndexes(this._tempUint1+Slices+2); else this.addIndexes(this._tempUint1+this._tempInt0+Slices+1); this.addIndexes(this._tempUint1+this._tempInt0+Slices); this._tempInt0++; this._tempNumver1+=this._tempNumver0; } return this; } __proto.boundingBoxLine=function(minX,minY,minZ,maxX,maxY,maxZ,r,g,b,a){ if (!this._hasBegun || this._primitiveType!==/*laya.webgl.WebGLContext.LINES*/0x0001) this.drawLinesException(); if (this._posInVBData+8 *this._floatSizePerVer > this._vbData.length || this._posInIBData+48 > this._ibData.length) this.flush(); this._tempUint0=this._posInVBData / this._floatSizePerVer; this.addVertex(minX,maxY,maxZ,r,g,b,a); this.addVertex(maxX,maxY,maxZ,r,g,b,a); this.addVertex(minX,minY,maxZ,r,g,b,a); this.addVertex(maxX,minY,maxZ,r,g,b,a); this.addVertex(maxX,maxY,minZ,r,g,b,a); this.addVertex(minX,maxY,minZ,r,g,b,a); this.addVertex(maxX,minY,minZ,r,g,b,a); this.addVertex(minX,minY,minZ,r,g,b,a); this._tempUint1=this._tempUint0+1; this._tempUint2=this._tempUint0+2; this._tempUint3=this._tempUint0+3; this._tempUint4=this._tempUint0+4; this._tempUint5=this._tempUint0+5; this._tempUint6=this._tempUint0+6; this._tempUint7=this._tempUint0+7; this.addIndexes(this._tempUint0,this._tempUint1,this._tempUint1,this._tempUint3,this._tempUint3,this._tempUint2,this._tempUint2,this._tempUint0, this._tempUint4,this._tempUint5,this._tempUint5,this._tempUint7,this._tempUint7,this._tempUint6,this._tempUint6,this._tempUint4, this._tempUint5,this._tempUint0,this._tempUint0,this._tempUint2,this._tempUint2,this._tempUint7,this._tempUint7,this._tempUint5, this._tempUint1,this._tempUint4,this._tempUint4,this._tempUint6,this._tempUint6,this._tempUint3,this._tempUint3,this._tempUint1, this._tempUint5,this._tempUint4,this._tempUint4,this._tempUint1,this._tempUint1,this._tempUint0,this._tempUint0,this._tempUint5, this._tempUint2,this._tempUint3,this._tempUint3,this._tempUint6,this._tempUint6,this._tempUint7,this._tempUint7,this._tempUint2); return this; } __proto.addVertex=function(x,y,z,r,g,b,a){ if (!this._hasBegun) this.addVertexIndexException(); this._vbData[this._posInVBData]=x,this._vbData[this._posInVBData+1]=y,this._vbData[this._posInVBData+2]=z; this._vbData[this._posInVBData+3]=r,this._vbData[this._posInVBData+4]=g,this._vbData[this._posInVBData+5]=b,this._vbData[this._posInVBData+6]=a; this._posInVBData+=this._floatSizePerVer; return this; } __proto.addVertexIndex=function(x,y,z,r,g,b,a,index){ if (!this._hasBegun) this.addVertexIndexException(); this._vbData[index]=x,this._vbData[index+1]=y,this._vbData[index+2]=z; this._vbData[index+3]=r,this._vbData[index+4]=g,this._vbData[index+5]=b,this._vbData[index+6]=a; index+=this._floatSizePerVer; if (index > this._posInVBData) this._posInVBData=index; return this; } __proto.addIndexes=function(__indexes){ var indexes=arguments; if (!this._hasBegun) this.addVertexIndexException(); for (var i=0;i < indexes.length;i++){ this._ibData[this._posInIBData]=indexes[i]; this._posInIBData++; } return this; } __proto.begin=function(primitive,camera){ if (this._hasBegun) this.beginException0(); if (primitive!==/*laya.webgl.WebGLContext.LINES*/0x0001 && primitive!==/*laya.webgl.WebGLContext.TRIANGLES*/0x0004) this.beginException1(); this._primitiveType=primitive; this._camera=camera; this._hasBegun=true; return this; } __proto.end=function(){ if (!this._hasBegun) this.endException(); this.flush(); this._hasBegun=false; return this; } __proto.flush=function(){ if (this._posInVBData===0) return; this._ib.setData(this._ibData); this._vb.setData(this._vbData); this._vb._bind(); this._ib._bind(); this._shader=this._shaderCompile.withCompile(0,0,0); this._shader.bind(); this._shader.uploadAttributes(PhasorSpriter3D._vertexDeclaration.shaderValues.data,null); this._spriteShaderValue.setValue(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,(this._camera).projectionViewMatrix.elements); this._shader.uploadSpriteUniforms(this._spriteShaderValue.data); Stat.drawCall++; WebGL.mainContext.drawElements(this._primitiveType,this._posInIBData,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); this._posInIBData=0; this._posInVBData=0; } __proto.addVertexIndexException=function(){ throw new Error("请先调用begin()函数"); } __proto.beginException0=function(){ throw new Error("调用begin()前请确保已成功调用end()!"); } __proto.beginException1=function(){ throw new Error("只支持“LINES”和“TRIANGLES”两种基元!"); } __proto.endException=function(){ throw new Error("调用end()前请确保已成功调用begin()!"); } __proto.drawLinesException=function(){ throw new Error("您必须确保在此之前已调用begin()且使用“LINES”基元!"); } __proto.drawTrianglesException=function(){ throw new Error("您必须确保在此之前已调用begin()且使用“TRIANGLES”基元!"); } __static(PhasorSpriter3D, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(28,[new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0),new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1)]);} ]); return PhasorSpriter3D; })() /** *@private *RenderElement 类用于实现渲染物体。 */ //class laya.d3.core.render.RenderElement var RenderElement=(function(){ function RenderElement(){ /**@private */ this._id=0; /**@private 类型0为默认,2为DynamicBatch。*/ this._type=0; /**@private 排序ID。*/ this._mainSortID=0; /**@private */ this._render=null; /**@private 所属Sprite3D精灵。*/ this._sprite3D=null; /**@private 渲染所用材质。*/ this._material=null; /**@private 渲染元素。*/ this._renderObj=null; /**@private */ this._staticBatch=null; //...............临时........................... this._tempBatchIndexStart=0; //TODO: this._tempBatchIndexEnd=0; /**@private */ this._canDynamicBatch=false; /**当前ShaderValue。*/ this._shaderValue=null; this._onPreRenderFunction=null; this._id=++RenderElement._uniqueIDCounter; this._canDynamicBatch=true; this._shaderValue=new ValusArray(); } __class(RenderElement,'laya.d3.core.render.RenderElement'); var __proto=RenderElement.prototype; /** *@private */ __proto.getDynamicBatchBakedVertexs=function(index){ var byteSizeInFloat=4; var vb=this._renderObj._getVertexBuffer(index); var bakedVertexes=vb.getData().slice(); var vertexDeclaration=vb.vertexDeclaration; var positionOffset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.POSITION0*/0).offset / byteSizeInFloat; var normalOffset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3).offset / byteSizeInFloat; var transform=this._sprite3D.transform; var worldMatrix=transform.worldMatrix; var rotation=transform.rotation; var vertexFloatCount=vertexDeclaration.vertexStride / byteSizeInFloat; for (var i=0,n=bakedVertexes.length;i < n;i+=vertexFloatCount){ var posOffset=i+positionOffset; var norOffset=i+normalOffset; Utils3D.transformVector3ArrayToVector3ArrayCoordinate(bakedVertexes,posOffset,worldMatrix,bakedVertexes,posOffset); Utils3D.transformVector3ArrayByQuat(bakedVertexes,norOffset,rotation,bakedVertexes,norOffset); } return bakedVertexes; } /** *@private */ __proto.getBakedIndices=function(){ return this._renderObj._getIndexBuffer().getData(); } /** *@private */ __proto._destroy=function(){ (this._staticBatch)&& (this._staticBatch._manager._garbageCollection(this)); } /** *获取唯一标识ID,通常用于识别。 */ __getset(0,__proto,'id',function(){ return this._id; }); __getset(0,__proto,'renderObj',function(){ return this._renderObj; },function(value){ if (this._renderObj!==value){ this._renderObj=value; } }); RenderElement._uniqueIDCounter=0; return RenderElement; })() /** *@private *RenderQuene 类用于实现渲染队列。 */ //class laya.d3.core.render.RenderQueue var RenderQueue=(function(){ function RenderQueue(scene){ /**@private */ this._id=0; /**@private */ this._needSort=false; /**@private */ this._renderElements=null; /**@private */ this._renderableRenderObjects=null; /**@private */ this._dynamicBatchCombineRenderElements=null; /**@private */ this._finalElements=null; /**@private */ this._scene=null; this._id=++RenderQueue._uniqueIDCounter; this._needSort=false; this._scene=scene; this._renderElements=[]; this._renderableRenderObjects=[]; this._dynamicBatchCombineRenderElements=[]; } __class(RenderQueue,'laya.d3.core.render.RenderQueue'); var __proto=RenderQueue.prototype; __proto._sortOpaqueFunc=function(a,b){ if (a._render && b._render){ var renderQueue=a._material.renderQueue-b._material.renderQueue; if (renderQueue===0){ return a._render._distanceForSort-b._render._distanceForSort; }else { return renderQueue } }else { return 0; } } __proto._sortAlphaFunc=function(a,b){ if (a._render && b._render){ var renderQueue=a._material.renderQueue-b._material.renderQueue; if (renderQueue===0){ return b._render._distanceForSort-a._render._distanceForSort; }else { return renderQueue; } }else return 0; } /** *@private */ __proto._begainRenderElement=function(state,renderObj,material){ if (renderObj._beforeRender(state)){ return true; } return false; } /** *@private */ __proto._sortAlpha=function(cameraPos){ RenderQueue._cameraPosition=cameraPos; this._finalElements.sort(this._sortAlphaFunc); } /** *@private */ __proto._sortOpaque=function(cameraPos){ RenderQueue._cameraPosition=cameraPos; this._finalElements.sort(this._sortOpaqueFunc); } /** *@private *准备渲染队列。 *@param state 渲染状态。 */ __proto._preRender=function(state){ this._finalElements=this._renderElements.concat(this._dynamicBatchCombineRenderElements); } /** *@private *渲染队列。 *@param state 渲染状态。 */ __proto._render=function(state,isTarget){ var loopCount=Stat.loopCount; var scene=this._scene; var camera=state.camera; var cameraID=camera.id; var vbs; var vertexBuffer,vertexDeclaration,shader; var forceUploadParams=false; var lastStateMaterial,lastStateOwner; for (var i=0,n=this._finalElements.length;i < n;i++){ var renderElement=this._finalElements[i]; var renderObj,material,owner; if (renderElement._onPreRenderFunction !=null){ renderElement._onPreRenderFunction.call(renderElement._sprite3D,state); } if (renderElement._type===0){ state.owner=owner=renderElement._sprite3D; state.renderElement=renderElement; owner._preRenderUpdateComponents(state); renderObj=renderElement.renderObj,material=renderElement._material; if (this._begainRenderElement(state,renderObj,material)){ vbs=renderObj._getVertexBuffers(); vertexBuffer=renderObj._getVertexBuffer(0); vertexDeclaration=vertexBuffer.vertexDeclaration; shader=state._shader=material._getShader(scene._shaderDefineValue,vertexDeclaration.shaderDefineValue,owner._shaderDefineValue); forceUploadParams=shader.bind()|| (loopCount!==shader._uploadLoopCount); if (vbs){ if (shader._uploadVertexBuffer!==vbs || forceUploadParams){ for (var j=0;j < vbs.length;j++){ var vb=vbs[j]; shader.uploadAttributesX(vb.vertexDeclaration.shaderValues.data,vb); } shader._uploadVertexBuffer=vbs; } }else { if (shader._uploadVertexBuffer!==vertexBuffer || forceUploadParams){ shader.uploadAttributes(vertexDeclaration.shaderValues.data,null); shader._uploadVertexBuffer=vertexBuffer; } } if (shader._uploadScene!==scene || forceUploadParams){ shader.uploadSceneUniforms(scene._shaderValues.data); shader._uploadScene=scene; } if (camera!==shader._uploadCamera || shader._uploadSprite3D!==owner || forceUploadParams){ shader.uploadSpriteUniforms(owner._shaderValues.data); shader._uploadSprite3D=owner; } if (camera!==shader._uploadCamera || forceUploadParams){ shader.uploadCameraUniforms(camera._shaderValues.data); shader._uploadCamera=camera; } if (shader._uploadMaterial!==material || forceUploadParams){ material._upload(); shader._uploadMaterial=material; } if (lastStateMaterial!==material){ material._setRenderStateBlendDepth(); material._setRenderStateFrontFace(isTarget,owner.transform); lastStateMaterial=material; lastStateOwner=owner; }else { if (lastStateOwner!==owner){ material._setRenderStateFrontFace(isTarget,owner.transform); lastStateOwner=owner; } } renderObj._render(state); shader._uploadLoopCount=loopCount; } owner._postRenderUpdateComponents(state); }else if (renderElement._type===2){ var dynamicBatch=renderElement.renderObj; state.owner=owner=renderElement._sprite3D; state.renderElement=renderElement; state._batchIndexStart=renderElement._tempBatchIndexStart; state._batchIndexEnd=renderElement._tempBatchIndexEnd; renderObj=renderElement.renderObj,material=renderElement._material; if (this._begainRenderElement(state,renderObj,material)){ vertexBuffer=renderObj._getVertexBuffer(0); vertexDeclaration=vertexBuffer.vertexDeclaration; shader=state._shader=material._getShader(scene._shaderDefineValue,vertexDeclaration.shaderDefineValue,owner._shaderDefineValue); forceUploadParams=shader.bind()|| (loopCount!==shader._uploadLoopCount); if (shader._uploadVertexBuffer!==vertexBuffer || forceUploadParams){ shader.uploadAttributes(vertexDeclaration.shaderValues.data,null); shader._uploadVertexBuffer=vertexBuffer; } if (shader._uploadScene!==scene || forceUploadParams){ shader.uploadSceneUniforms(scene._shaderValues.data); shader._uploadScene=scene; } if (camera!==shader._uploadCamera || shader._uploadSprite3D!==owner || forceUploadParams){ shader.uploadSpriteUniforms(owner._shaderValues.data); shader._uploadSprite3D=owner; } if (camera!==shader._uploadCamera || forceUploadParams){ shader.uploadCameraUniforms(camera._shaderValues.data); shader._uploadCamera=camera; } if (shader._uploadMaterial!==material || forceUploadParams){ material._upload(); shader._uploadMaterial=material; } if (lastStateMaterial!==material){ material._setRenderStateBlendDepth(); material._setRenderStateFrontFace(isTarget,owner.transform); lastStateMaterial=material; lastStateOwner=owner; }else { if (lastStateOwner!==owner){ material._setRenderStateFrontFace(isTarget,owner.transform); lastStateOwner=owner; } } renderObj._render(state); shader._uploadLoopCount=loopCount; } } } } /** *@private *渲染队列。 *@param state 渲染状态。 */ __proto._renderShadow=function(state,isOnePSSM){ var loopCount=Stat.loopCount; var scene=this._scene; var camera=state.camera; var vertexBuffer,vertexDeclaration,shader; var forceUploadParams=false; var lastStateMaterial,lastStateOwner; for (var i=0,n=this._finalElements.length;i < n;i++){ var renderElement=this._finalElements[i]; var renderObj,material,owner; if (renderElement._type===0){ state.owner=owner=renderElement._sprite3D; if (!isOnePSSM && (owner._projectionViewWorldUpdateCamera!==camera || owner._projectionViewWorldUpdateLoopCount!==Stat.loopCount)){ owner._render._renderUpdate(state._projectionViewMatrix); owner._projectionViewWorldUpdateLoopCount=Stat.loopCount; owner._projectionViewWorldUpdateCamera=camera; } state.renderElement=renderElement; owner._preRenderUpdateComponents(state); renderObj=renderElement.renderObj,material=renderElement._material; if (this._begainRenderElement(state,renderObj,null)){ vertexBuffer=renderObj._getVertexBuffer(0); vertexDeclaration=vertexBuffer.vertexDeclaration; shader=state._shader=material._getShader(scene._shaderDefineValue,vertexDeclaration.shaderDefineValue,owner._shaderDefineValue); forceUploadParams=shader.bind()|| (loopCount!==shader._uploadLoopCount); if (shader._uploadVertexBuffer!==vertexBuffer || forceUploadParams){ shader.uploadAttributes(vertexDeclaration.shaderValues.data,null); shader._uploadVertexBuffer=vertexBuffer; } if (camera!==shader._uploadCamera || shader._uploadSprite3D!==owner || forceUploadParams){ shader.uploadSpriteUniforms(owner._shaderValues.data); shader._uploadSprite3D=owner; } if (camera!==shader._uploadCamera || forceUploadParams){ shader.uploadCameraUniforms(camera._shaderValues.data); shader._uploadCamera=camera; } if (shader._uploadMaterial!==material || forceUploadParams){ material._upload(); shader._uploadMaterial=material; } if (shader._uploadRenderElement!==renderElement || forceUploadParams){} if (lastStateMaterial!==material){ material._setRenderStateFrontFace(false,owner.transform); lastStateMaterial=material; lastStateOwner=owner; }else { if (lastStateOwner!==owner){ material._setRenderStateFrontFace(false,owner.transform); lastStateOwner=owner; } } renderObj._render(state); shader._uploadLoopCount=loopCount; } owner._postRenderUpdateComponents(state); } } } /** *清空队列中的渲染物体。 */ __proto._clearRenderElements=function(){ this._dynamicBatchCombineRenderElements.length=0; this._renderElements.length=0; this._needSort=true; } /** *添加渲染物体。 *@param renderObj 渲染物体。 */ __proto._addRenderElement=function(renderElement){ this._renderElements.push(renderElement); this._needSort=true; } /** *添加动态批处理。 *@param renderObj 动态批处理。 */ __proto._addDynamicBatchElement=function(dynamicBatchElement){ this._dynamicBatchCombineRenderElements.push(dynamicBatchElement); } /** *获取唯一标识ID(通常用于优化或识别)。 */ __getset(0,__proto,'id',function(){ return this._id; }); RenderQueue._uniqueIDCounter=0; RenderQueue._cameraPosition=null; return RenderQueue; })() /** *RenderState 类用于实现渲染状态。 */ //class laya.d3.core.render.RenderState var RenderState=(function(){ function RenderState(){ /**@private */ this._staticBatch=null; /**@private */ this._batchIndexStart=0; /**@private */ this._batchIndexEnd=0; /**@private */ this._viewMatrix=null; /**@private */ this._projectionMatrix=null; /**@private */ this._projectionViewMatrix=null; /**@private */ this._viewport=null; /**@private */ this._shader=null; /**距上一帧间隔时间。*/ this.elapsedTime=NaN; /**当前场景。*/ this.scene=null; /**当前渲染3D精灵。*/ this.owner=null; /**当前渲染物体。*/ this.renderElement=null; /**当前摄像机。*/ this.camera=null; } __class(RenderState,'laya.d3.core.render.RenderState'); RenderState.clientWidth=0; RenderState.clientHeight=0; return RenderState; })() //class laya.d3.core.scene.OctreeNode var OctreeNode=(function(){ function OctreeNode(scene,currentDepth){ this._exactBox=null; this._relaxBox=null; this._scene=null; this._parent=null; this._currentDepth=0; this._boundingSphere=new BoundSphere(new Vector3(),0); this._corners=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3()]; this._boundingBoxCenter=new Vector3(); this._children=__newvec(8); this._objects=[]; this._tempBoundBoxCorners=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3()]; this._scene=scene; this._currentDepth=currentDepth; } __class(OctreeNode,'laya.d3.core.scene.OctreeNode'); var __proto=OctreeNode.prototype; Laya.imps(__proto,{"laya.d3.core.scene.ITreeNode":true}) __proto.init=function(center,treeSize){ var min=new Vector3(); var max=new Vector3(); Vector3.scale(treeSize,-0.5,min); Vector3.scale(treeSize,0.5,max); Vector3.add(min,center,min); Vector3.add(max,center,max); this.exactBox=new BoundBox(min,max); this.relaxBox=new BoundBox(min,max); } __proto.addTreeNode=function(render){ if (Collision.boxContainsBox(this._relaxBox,render.boundingBox)===/*laya.d3.math.ContainmentType.Contains*/1) this.addNodeDown(render,0); else this.addObject(render); } __proto.addChild=function(index){ var child=this._children[index]; if (child==null){ child=new OctreeNode(this._scene,this._currentDepth+1); this._children[index]=child; child._parent=this; Vector3.subtract(this._exactBox.max,this._exactBox.min,OctreeNode.tempSize); Vector3.multiply(OctreeNode.tempSize,OctreeNode._octreeSplit[index],OctreeNode.tempCenter); Vector3.add(this._exactBox.min,OctreeNode.tempCenter,OctreeNode.tempCenter); Vector3.scale(OctreeNode.tempSize,0.25,OctreeNode.tempSize); var min=new Vector3(); var max=new Vector3(); Vector3.subtract(OctreeNode.tempCenter,OctreeNode.tempSize,min); Vector3.add(OctreeNode.tempCenter,OctreeNode.tempSize,max); child.exactBox=new BoundBox(min,max); Vector3.scale(OctreeNode.tempSize,OctreeNode.relax,OctreeNode.tempSize); var relaxMin=new Vector3(); var relaxMax=new Vector3(); Vector3.subtract(OctreeNode.tempCenter,OctreeNode.tempSize,relaxMin); Vector3.add(OctreeNode.tempCenter,OctreeNode.tempSize,relaxMax); child.relaxBox=new BoundBox(relaxMin,relaxMax); } return child; } __proto.addObject=function(object){ object._treeNode=this; this._objects.push(object); } __proto.removeObject=function(object){ if (object._treeNode !=this){ console.log("OctreeNode::removeObject error"); return false; }; var index=this._objects.indexOf(object); if (index!==-1){ this._objects.splice(index,1); return true; } return false; } __proto.clearObject=function(){ this._objects.length=0; } __proto.addNodeUp=function(render,depth){ if (this._parent && (Collision.boxContainsBox(this._exactBox,render.boundingBox)!==/*laya.d3.math.ContainmentType.Contains*/1)){ this._parent.addNodeUp(render,depth-1); }else this.addNodeDown(render,depth); } __proto.addNodeDown=function(render,depth){ if (depth < this._scene.treeLevel){ var childIndex=this.inChildIndex(render.boundingBoxCenter); var child=this.addChild(childIndex); if (Collision.boxContainsBox(child._relaxBox,render.boundingBox)===/*laya.d3.math.ContainmentType.Contains*/1){ child.addNodeDown(render,++depth); }else this.addObject(render); }else { this.addObject(render); } } __proto.inChildIndex=function(objectCenter){ var z=objectCenter.z < this._boundingBoxCenter.z ? 0 :1; var y=objectCenter.y < this._boundingBoxCenter.y ? 0 :1; var x=objectCenter.x < this._boundingBoxCenter.x ? 0 :1; return z *4+y *2+x; } __proto.updateObject=function(render){ if (Collision.boxContainsBox(this._relaxBox,render.boundingBox)===/*laya.d3.math.ContainmentType.Contains*/1){ this.removeObject(render); render._treeNode=null; this.addNodeDown(render,this._currentDepth); }else if (this._parent){ this.removeObject(render); render._treeNode=null; this._parent.addNodeUp(render,this._currentDepth-1); } } __proto.cullingObjects=function(boundFrustum,testVisible,flags,cameraPosition,projectionView){ var i=0,j=0,n=0,m=0; var dynamicBatchManager=this._scene._dynamicBatchManager; for (i=0,n=this._objects.length;i < n;i++){ var render=this._objects[i]; if (Layer.isVisible(render._owner.layer.mask)&& render.enable){ if (testVisible){ Stat.treeSpriteCollision+=1; if (boundFrustum.containsBoundSphere(render.boundingSphere)===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; } render._renderUpdate(projectionView); render._distanceForSort=Vector3.distance(render.boundingSphere.center,cameraPosition)+render.sortingFudge; var renderElements=render._renderElements; for (j=0,m=renderElements.length;j < m;j++){ var renderElement=renderElements[j]; var staticBatch=renderElement._staticBatch; if (staticBatch && (staticBatch._material===renderElement._material)){ staticBatch._addBatchRenderElement(renderElement); }else { var renderObj=renderElement.renderObj; if ((renderObj.triangleCount < /*laya.d3.graphics.DynamicBatch.maxCombineTriangleCount*/10)&& (renderObj._vertexBufferCount===1)&& (renderObj._getIndexBuffer())&& (renderElement._material.renderQueue < 2)&& renderElement._canDynamicBatch && (!render._owner.isStatic)) dynamicBatchManager._addPrepareRenderElement(renderElement); else this._scene.getRenderQueue(renderElement._material.renderQueue)._addRenderElement(renderElement); } } } } for (i=0;i < 8;i++){ var child=this._children[i]; if (child==null) continue ; var testVisibleChild=testVisible; if (testVisible){ var type=boundFrustum.containsBoundBox(child._relaxBox); Stat.treeNodeCollision+=1; if (type===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; testVisibleChild=(type===/*laya.d3.math.ContainmentType.Intersects*/2); } child.cullingObjects(boundFrustum,testVisibleChild,flags,cameraPosition,projectionView); } } /** *@private */ __proto.cullingShadowObjects=function(lightBoundFrustum,splitShadowQueues,testVisible,flags,scene){ var i=0,j=0,n=0,m=0; var dynamicBatchManager=this._scene._dynamicBatchManager; for (i=0,n=this._objects.length;i < n;i++){ var baseRender=this._objects[i]; if (baseRender.castShadow && Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable){ if (testVisible && lightBoundFrustum[0].containsBoundSphere(baseRender.boundingSphere)===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; for (var k=1,kNum=lightBoundFrustum.length;k < kNum;k++){ var shadowQueue=splitShadowQueues[k-1]; if (lightBoundFrustum[k].containsBoundSphere(baseRender.boundingSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ var renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++) shadowQueue._addRenderElement(renderElements[j]); } } } } for (i=0;i < 8;i++){ var child=this._children[i]; if (child==null) continue ; var testVisibleChild=testVisible; if (testVisible){ var type=lightBoundFrustum[0].containsBoundBox(child._relaxBox); if (type===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; testVisibleChild=(type===/*laya.d3.math.ContainmentType.Intersects*/2); } child.cullingShadowObjects(lightBoundFrustum,splitShadowQueues,testVisibleChild,flags,scene); } } /** *@private */ __proto.cullingShadowObjectsOnePSSM=function(lightBoundFrustum,splitShadowQueues,lightViewProjectMatrix,testVisible,flags,scene){ var shadowQueue=splitShadowQueues[0]; var i=0,j=0,n=0,m=0; for (i=0,n=this._objects.length;i < n;i++){ var baseRender=this._objects[i]; if (baseRender.castShadow && Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable){ if (testVisible && lightBoundFrustum.containsBoundSphere(baseRender.boundingSphere)===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; baseRender._renderUpdate(lightViewProjectMatrix); var renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++) shadowQueue._addRenderElement(renderElements[j]); } } for (i=0;i < 8;i++){ var child=this._children[i]; if (child==null) continue ; var testVisibleChild=testVisible; if (testVisible){ var type=lightBoundFrustum.containsBoundBox(child._relaxBox); if (type===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; testVisibleChild=(type===/*laya.d3.math.ContainmentType.Intersects*/2); } child.cullingShadowObjectsOnePSSM(lightBoundFrustum,splitShadowQueues,lightViewProjectMatrix,testVisibleChild,flags,scene); } } __proto.renderBoudingBox=function(linePhasor){ this._renderBoudingBox(linePhasor); for (var i=0;i < 8;++i){ var pChild=this._children[i]; if (pChild){ pChild.renderBoudingBox(linePhasor); } } } __proto.buildAllChild=function(depth){ if (depth < this._scene.treeLevel){ for (var i=0;i < 8;i++){ var child=this.addChild(i); child.buildAllChild(depth+1); } } } __proto._renderBoudingBox=function(linePhasor){} __getset(0,__proto,'exactBox',function(){ return this._exactBox; },function(value){ this._exactBox=value; Vector3.add(value.min,value.max,this._boundingBoxCenter); Vector3.scale(this._boundingBoxCenter,0.5,this._boundingBoxCenter); }); __getset(0,__proto,'relaxBox',function(){ return this._relaxBox; },function(value){ this._relaxBox=value; value.getCorners(this._corners); BoundSphere.createfromPoints(this._corners,this._boundingSphere); }); OctreeNode.debugMode=false; OctreeNode.relax=1.15; OctreeNode.CHILDNUM=8; __static(OctreeNode, ['tempVector0',function(){return this.tempVector0=new Vector3();},'tempSize',function(){return this.tempSize=new Vector3();},'tempCenter',function(){return this.tempCenter=new Vector3();},'_octreeSplit',function(){return this._octreeSplit=[new Vector3(0.250,0.250,0.250),new Vector3(0.750,0.250,0.250),new Vector3(0.250,0.750,0.250),new Vector3(0.750,0.750,0.250),new Vector3(0.250,0.250,0.750),new Vector3(0.750,0.250,0.750),new Vector3(0.250,0.750,0.750),new Vector3(0.750,0.750,0.750)];} ]); return OctreeNode; })() /** *... *@author ... */ //class laya.d3.core.scene.SceneManager var SceneManager=(function(){ function SceneManager(){} __class(SceneManager,'laya.d3.core.scene.SceneManager'); return SceneManager; })() //class laya.d3.core.trail.module.Color var Color$1=(function(){ function Color(r,g,b,a){ this._r=NaN; this._g=NaN; this._b=NaN; this._a=NaN; (r===void 0)&& (r=1); (g===void 0)&& (g=1); (b===void 0)&& (b=1); (a===void 0)&& (a=1); this._r=r; this._g=g; this._b=b; this._a=a; } __class(Color,'laya.d3.core.trail.module.Color',null,'Color$1'); var __proto=Color.prototype; __proto.cloneTo=function(destObject){ destObject._r=this._r; destObject._g=this._g; destObject._b=this._b; destObject._a=this._a; } __static(Color, ['RED',function(){return this.RED=new Color(1,0,0,1);},'GREEN',function(){return this.GREEN=new Color(0,1,0,1);},'BLUE',function(){return this.BLUE=new Color(0,0,1,1);},'CYAN',function(){return this.CYAN=new Color(0,1,1,1);},'YELLOW',function(){return this.YELLOW=new Color(1,0.92,0.016,1);},'MAGENTA',function(){return this.MAGENTA=new Color(1,0,1,1);},'GRAY',function(){return this.GRAY=new Color(0.5,0.5,0.5,1);},'WHITE',function(){return this.WHITE=new Color(1,1,1,1);},'BLACK',function(){return this.BLACK=new Color(0,0,0,1);} ]); return Color; })() //class laya.d3.core.trail.module.Gradient var Gradient=(function(){ function Gradient(){ /** *梯度模式 */ this._mode=0; /** *颜色值关键帧数据,最大长度为10 */ this._colorKeys=null; /** *透明度关键帧数据,最大长度为10 */ this._alphaKeys=null; this.index=0; this._colorKeyData=new Float32Array(40); this._alphaKeyData=new Float32Array(20); this._colorKeys=[]; this._alphaKeys=[]; } __class(Gradient,'laya.d3.core.trail.module.Gradient'); var __proto=Gradient.prototype; /** *设置渐变,使用一组颜色关键帧数据和透明度关键帧数据。 *@param colorKeys 渐变的颜色值关键帧数据(最大长度为10)。 *@param alphaKeys 渐变的透明度关键帧数据(最大长度为10)。 */ __proto.setKeys=function(colorKeys,alphaKeys){ this._colorKeys=colorKeys; this.index=0; var gradientColorKey; for (var i=0;i < colorKeys.length;i++){ gradientColorKey=colorKeys[i]; var color=gradientColorKey.color; this._colorKeyData[this.index++]=color._r; this._colorKeyData[this.index++]=color._g; this._colorKeyData[this.index++]=color._b; this._colorKeyData[this.index++]=gradientColorKey.time; } this._alphaKeys=alphaKeys; this.index=0; var gradientAlphaKey; for (var j=0;j < alphaKeys.length;j++){ gradientAlphaKey=alphaKeys[j]; this._alphaKeyData[this.index++]=gradientAlphaKey.alpha; this._alphaKeyData[this.index++]=gradientAlphaKey.time; } } __proto.cloneTo=function(destObject){ var i=0,j=0; var cks=this.colorKeys; var _cks=[]; for (i=0,j=cks.length;i < j;i++){ var _ck=new GradientColorKey(); cks[i].cloneTo(_ck); _cks.push(_ck); }; var aks=this.alphaKeys; var _aks=[]; for (i=0,j=aks.length;i < j;i++){ var _ak=new GradientAlphaKey(); aks[i].cloneTo(_ak); _aks.push(_ak); } destObject.setKeys(_cks,_aks); } /** *设置梯度模式。 *@param value 梯度模式。 */ /** *获取梯度模式。 *@return 梯度模式。 */ __getset(0,__proto,'mode',function(){ return this._mode; },function(value){ this._mode=value; }); /** *设置颜色值关键帧数据 */ /** *获取颜色值关键帧数据 */ __getset(0,__proto,'colorKeys',function(){ return this._colorKeys; },function(values){ this._colorKeys=values; this.index=0; for (var i=0;i < values.length;i++){ var value=values[i]; var color=value.color; this._colorKeyData[this.index++]=color._r; this._colorKeyData[this.index++]=color._g; this._colorKeyData[this.index++]=color._b; this._colorKeyData[this.index++]=value.time; } }); /** *设置透明度关键帧数据 */ /** *获取透明度关键帧数据 */ __getset(0,__proto,'alphaKeys',function(){ return this._alphaKeys; },function(values){ this._alphaKeys=values; this.index=0; for (var i=0;i < values.length;i++){ var value=values[i]; this._alphaKeyData[this.index++]=value.alpha; this._alphaKeyData[this.index++]=value.time; } }); return Gradient; })() //class laya.d3.core.trail.module.GradientAlphaKey var GradientAlphaKey=(function(){ function GradientAlphaKey(alpha,time){ this._alpha=NaN; this._time=NaN; (alpha===void 0)&& (alpha=0); (time===void 0)&& (time=0); this._alpha=alpha; this._time=time; } __class(GradientAlphaKey,'laya.d3.core.trail.module.GradientAlphaKey'); var __proto=GradientAlphaKey.prototype; __proto.cloneTo=function(destObject){ destObject.alpha=this.alpha; destObject.time=this.time; } /** *设置透明度。 *@param value 透明度。 */ /** *获取透明度。 *@return 透明度。 */ __getset(0,__proto,'alpha',function(){ return this._alpha; },function(value){ this._alpha=value; }); /** *设置时间。 *@param value 时间。 */ /** *获取时间。 *@return 时间。 */ __getset(0,__proto,'time',function(){ return this._time; },function(value){ this._time=value; }); return GradientAlphaKey; })() //class laya.d3.core.trail.module.GradientColorKey var GradientColorKey=(function(){ function GradientColorKey(color,time){ this._color=null; this._time=NaN; (time===void 0)&& (time=0); this._color=color||new Color$1(); this._time=time; } __class(GradientColorKey,'laya.d3.core.trail.module.GradientColorKey'); var __proto=GradientColorKey.prototype; __proto.cloneTo=function(destObject){ this.color.cloneTo(destObject.color); destObject.time=this.time; } /** *设置颜色值。 *@param value 颜色值。 */ /** *获取颜色值。 *@return 颜色值。 */ __getset(0,__proto,'color',function(){ return this._color; },function(value){ this._color=value; }); /** *设置时间。 *@param value 时间。 */ /** *获取时间。 *@return 时间。 */ __getset(0,__proto,'time',function(){ return this._time; },function(value){ this._time=value; }); return GradientColorKey; })() /** *... *@author ... */ //class laya.d3.core.trail.module.GradientMode var GradientMode=(function(){ function GradientMode(){} __class(GradientMode,'laya.d3.core.trail.module.GradientMode'); GradientMode.Blend=0; GradientMode.Fixed=1; return GradientMode; })() /** *... *@author ... */ //class laya.d3.core.trail.module.TextureMode var TextureMode=(function(){ function TextureMode(){} __class(TextureMode,'laya.d3.core.trail.module.TextureMode'); TextureMode.Stretch=0; TextureMode.Tile=1; return TextureMode; })() //class laya.d3.core.trail.module.TrailKeyFrame var TrailKeyFrame=(function(){ function TrailKeyFrame(){ this.time=NaN; this.inTangent=NaN; this.outTangent=NaN; this.value=NaN; } __class(TrailKeyFrame,'laya.d3.core.trail.module.TrailKeyFrame'); var __proto=TrailKeyFrame.prototype; __proto.cloneTo=function(destObject){ destObject.time=this.time; destObject.inTangent=this.inTangent; destObject.outTangent=this.outTangent; destObject.value=this.value; } return TrailKeyFrame; })() /** *... *@author ... */ //class laya.d3.core.trail.TrailRenderElement var TrailRenderElement=(function(){ function TrailRenderElement(owner){ this._id=0; this._owner=null; this._camera=null; this._vertexBuffers=null; //固定顶点个数 this._verticesCount=0; //虚拟顶点个数 this._virtualVerticesCount=0; this._maxVerticesCount=256; this._vertices1=null; this._vertexBuffer1=null; this._floatCountPerVertices1=8; this._verticesIndex1=0; this._everyAddVerticeCount1=0; this._delLength=0; this._vertices2=null; this._vertexBuffer2=null; this._floatCountPerVertices2=1; this._everyGroupVertexBirthTime=null; this._VerticesToTailLength=null; this._everyVertexToPreVertexDistance=null; this._pointe=null; this._pointAtoBVector3e=null; this._isStart=false; this._isFinish=false; this._isDead=false; this._curtime=NaN; this._curDisappearIndex=0; this._lastPosition=new Vector3(); this._curPosition=new Vector3(); this._delVector3=new Vector3(); this._lastFixedVertexPosition=new Vector3(); this._pointAtoBVector3=new Vector3(); this._pointA=new Vector3(); this._pointB=new Vector3(); this._owner=owner; this._id=TrailRenderElement.renderElementCount++; if (this._id==0){ owner._owner.transform.position.cloneTo(this._lastPosition); }else { owner._curSubTrailFinishPosition.cloneTo(this._lastPosition); } this._everyGroupVertexBirthTime=[]; this._VerticesToTailLength=new Float32Array(this._maxVerticesCount); this._everyVertexToPreVertexDistance=new Float32Array(this._maxVerticesCount); this._vertices1=new Float32Array(this._maxVerticesCount *this._floatCountPerVertices1); this._vertices2=new Float32Array(this._maxVerticesCount *this._floatCountPerVertices2); this._vertexBuffer1=new VertexBuffer3D(VertexTrail.vertexDeclaration1,this._maxVerticesCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer2=new VertexBuffer3D(VertexTrail.vertexDeclaration2,this._maxVerticesCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffers=[]; this._vertexBuffers.push(this._vertexBuffer1); this._vertexBuffers.push(this._vertexBuffer2); } __class(TrailRenderElement,'laya.d3.core.trail.TrailRenderElement'); var __proto=TrailRenderElement.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) /** *@private *更新Trail数据 */ __proto._updateTrail=function(){ this._everyAddVerticeCount1=0; if (!this._isStart){ this._addTrailByFirstPosition(this._lastPosition,this._curPosition); } this._addTrailByNextPosition(this._curPosition); this._vertexBuffer1.setData(this._vertices1,this._verticesIndex1,this._verticesIndex1,this._everyAddVerticeCount1); this._verticesIndex1+=this._everyAddVerticeCount1; this._curPosition.cloneTo(this._lastPosition); if (this._virtualVerticesCount==2){ this._verticesIndex1-=this._floatCountPerVertices1 *2; } } /** *@private *通过起始位置添加TrailRenderElement起始数据 *@param firstPosition 起始位置 *@param secondPosition 第二次位置 */ __proto._addTrailByFirstPosition=function(firstPosition,secondPosition){ Vector3.subtract(secondPosition,firstPosition,this._delVector3); Vector3.cross(this._delVector3,this._camera.forward,this._pointAtoBVector3); Vector3.normalize(this._pointAtoBVector3,this._pointAtoBVector3); Vector3.scale(this._pointAtoBVector3,this._owner.widthMultiplier / 2,this._pointAtoBVector3); this._updateVerticesByPosition(firstPosition); firstPosition.cloneTo(this._lastFixedVertexPosition); this._verticesCount+=2; this._curtime=this._owner._hasLifeSubTrail ? this._owner._curSubTrailFinishCurTime :this._owner._curtime; this._everyGroupVertexBirthTime.push(this._curtime); this._isStart=true; this._owner._hasLifeSubTrail=true; } /** *@private *通过位置更新TrailRenderElement数据 *@param position 位置 */ __proto._addTrailByNextPosition=function(position){ Vector3.subtract(position,this._lastFixedVertexPosition,this._delVector3); Vector3.cross(this._delVector3,this._camera.forward,this._pointAtoBVector3); Vector3.normalize(this._pointAtoBVector3,this._pointAtoBVector3); Vector3.scale(this._pointAtoBVector3,this._owner.widthMultiplier / 2,this._pointAtoBVector3); this._delLength=Vector3.scalarLength(this._delVector3); if (this._delLength-this._owner.minVertexDistance >=MathUtils3D.zeroTolerance){ this._owner._trailTotalLength+=this._delLength; this._owner._trailSupplementLength=0; this._updateVerticesByPosition(position); position.cloneTo(this._lastFixedVertexPosition); this._verticesCount+=2; this._virtualVerticesCount=0; this._everyGroupVertexBirthTime.push(this._owner._curtime); if (this._verticesCount==this._maxVerticesCount){ this._onTrailRenderElementFinish(); } } else { this._owner._trailSupplementLength=this._delLength; this._updateVerticesByPosition(position); this._virtualVerticesCount=2; } } /** *@private *通过位置更新顶点数据 *@param position 位置 */ __proto._updateVerticesByPosition=function(position){ this._pointe=position.elements; this._pointAtoBVector3e=this._pointAtoBVector3.elements; this._curtime=this._owner._curtime; if (this._owner._hasLifeSubTrail && this._isStart==false){ this._pointe=this._owner._curSubTrailFinishPosition.elements; this._pointAtoBVector3e=this._owner._curSubTrailFinishDirection.elements; this._curtime=this._owner._curSubTrailFinishCurTime; } this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=-this._pointAtoBVector3e[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=-this._pointAtoBVector3e[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=-this._pointAtoBVector3e[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._curtime; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=1.0; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointAtoBVector3e[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointAtoBVector3e[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointAtoBVector3e[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._curtime; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=0.0; this._VerticesToTailLength[this._verticesCount / 2]=this._owner._trailTotalLength+this._owner._trailSupplementLength; if (this._owner._trailSupplementLength==0){ this._everyVertexToPreVertexDistance[this._verticesCount / 2]=this._delLength; }else { this._everyVertexToPreVertexDistance[this._verticesCount / 2]=this._isStart ? this._owner._trailSupplementLength :0; } } /** *更新VertexBuffer2数据 */ __proto._updateVertexBuffer2=function(){ var _uvIndex=0; var _uvX=0.0; var i=0,j=0; for (i=0,j=(this._verticesCount+this._virtualVerticesCount)/ 2;i < j;i++){ if (this._owner.textureMode==/*laya.d3.core.trail.module.TextureMode.Stretch*/0){ _uvX=(this._VerticesToTailLength[i]-this._owner._trailDeadLength)/ (this._owner._trailTotalLength+this._owner._trailSupplementLength-this._owner._trailDeadLength); }else { _uvX=this._owner._trailTotalLength+this._owner._trailSupplementLength-this._VerticesToTailLength[i]; } this._vertices2[_uvIndex++]=1.0-_uvX; this._vertices2[_uvIndex++]=1.0-_uvX; } this._vertexBuffer2.setData(this._vertices2,0,0,this._verticesCount+this._virtualVerticesCount); } /** *trailRenderElement完成时调用 *@param finishedPosition */ __proto._onTrailRenderElementFinish=function(){ this._lastFixedVertexPosition.cloneTo(this._owner._curSubTrailFinishPosition); this._pointAtoBVector3.cloneTo(this._owner._curSubTrailFinishDirection); this._owner._curSubTrailFinishCurTime=this._owner._curtime; this._isFinish=true; } /** *@private */ __proto._updateDisappear=function(){ var i=0,j=0; for (i=this._curDisappearIndex,j=(this._verticesCount+this._virtualVerticesCount)/ 2;i < j;i++){ if (this._owner._curtime-this._everyGroupVertexBirthTime[i] >=this._owner.time+MathUtils3D.zeroTolerance){ this._curDisappearIndex++; this._owner._trailDeadLength+=this._everyVertexToPreVertexDistance[this._curDisappearIndex]; if (this._curDisappearIndex >=(this._verticesCount+this._virtualVerticesCount)/ 2){ this._isDead=true; } } } } /** *渲染前调用 *@param state 渲染状态 *@return 是否渲染 */ __proto._beforeRender=function(state){ this._camera=state.camera; if (this._camera==null) return false; this._owner._owner.transform.position.cloneTo(this._curPosition); if (!this._isDead){ if (this._verticesCount < this._maxVerticesCount){ if (!this._owner._isStart){ this._owner._owner.transform.position.cloneTo(this._lastPosition); this._owner._isStart=true; } if (!Vector3.equals(this._lastPosition,this._curPosition)){ this._updateTrail(); } }else { if (this._isFinish){ this._isFinish=false; this._owner._curSubTrailFinished=true; } } if (this._verticesCount > 0){ this._updateVertexBuffer2(); this._updateDisappear(); return true; } } return false; } /** *渲染时调用 *@param state 渲染状态 */ __proto._render=function(state){ if (this._isDead) return; WebGL.mainContext.drawArrays(/*laya.webgl.WebGLContext.TRIANGLE_STRIP*/0x0005,this._curDisappearIndex *2,this._verticesCount+this._virtualVerticesCount-this._curDisappearIndex *2); Stat.drawCall++; Stat.trianglesFaces+=(this._verticesCount+this._virtualVerticesCount-this._curDisappearIndex *2-2); } /** *获取vertexBuffer *@param index vertexBuffer索引 *@return vertexBuffer */ __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer1; else if (index===1) return this._vertexBuffer2; else return null; } /** *获取vertexBuffer数组 *@return vertexBuffer数组 */ __proto._getVertexBuffers=function(){ return this._vertexBuffers; } /** *获取顶点索引缓冲 *@return 顶点索引缓冲 */ __proto._getIndexBuffer=function(){ return null; } /** *重新激活该renderElement */ __proto.reActivate=function(){ this._id=laya.d3.core.trail.TrailRenderElement.renderElementCount++; this._isStart=false; this._isFinish=false; this._isDead=false; this._verticesCount=0; this._virtualVerticesCount=0; this._verticesIndex1=0; this._delLength=0; this._curDisappearIndex=0; this._everyGroupVertexBirthTime=[]; this._owner._curSubTrailFinishPosition.cloneTo(this._lastPosition); } /** *@private */ __proto._destroy=function(){ this._vertexBuffer1.dispose(); this._vertexBuffer2.dispose(); this._vertices1=null; this._vertexBuffer1=null; this._vertices2=null; this._vertexBuffer2=null; this._vertexBuffers=null; this._everyGroupVertexBirthTime=null; this._VerticesToTailLength=null; this._everyVertexToPreVertexDistance=null; this._lastPosition=null; this._curPosition=null; this._delVector3=null; this._lastFixedVertexPosition=null; this._pointAtoBVector3=null; this._pointe=null; this._pointAtoBVector3e=null; this._pointA=null; this._pointB=null; } /** *获取vertexBuffer数量 *@return vertexBuffer数量 */ __getset(0,__proto,'_vertexBufferCount',function(){ return this._vertexBuffers.length; }); /** *获取三角面数量 *@return 三角面数量 */ __getset(0,__proto,'triangleCount',function(){ return 0; }); TrailRenderElement.renderElementCount=0; return TrailRenderElement; })() /** *VertexTrail 类用于创建拖尾顶点结构。 */ //class laya.d3.core.trail.VertexTrail var VertexTrail=(function(){ function VertexTrail(){} __class(VertexTrail,'laya.d3.core.trail.VertexTrail'); var __proto=VertexTrail.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'vertexDeclaration',function(){ return VertexTrail._vertexDeclaration1; }); __getset(1,VertexTrail,'vertexDeclaration1',function(){ return VertexTrail._vertexDeclaration1; }); __getset(1,VertexTrail,'vertexDeclaration2',function(){ return VertexTrail._vertexDeclaration2; }); __static(VertexTrail, ['_vertexDeclaration1',function(){return this._vertexDeclaration1=new VertexDeclaration(32, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.OFFSETVECTOR*/41), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TIME0*/33), new VertexElement(28,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0Y*/40)]);},'_vertexDeclaration2',function(){return this._vertexDeclaration2=new VertexDeclaration(4, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0X*/38)]);} ]); return VertexTrail; })() /** *... *@author */ //class laya.d3.extension.domino.DominoKeyFrame var DominoKeyFrame=(function(){ function DominoKeyFrame(){ this.position=Vector3.ZERO; this.rotation=Quaternion.DEFAULT; this.scale=new Vector3(0.3,0.6,0.1); } __class(DominoKeyFrame,'laya.d3.extension.domino.DominoKeyFrame'); return DominoKeyFrame; })() /** *... *@author */ //class laya.d3.extension.domino.DominoRenderElement var DominoRenderElement=(function(){ function DominoRenderElement(owner){ this._owner=null; this.id=0; this._curDominoCount=0; this._perDominoVertexCount=24; this._perDominoIndiceCount=36; this._vertexBuffers=null; this._vertices1=null; this._vertexBuffer1=null; this._floatCountPerVertices1=4; this._verticesIndex1=0; this._everyAddVerticeCount1=0; this._vertices2=null; this._vertexBuffer2=null; this._floatCountPerVertices2=6; this._verticesIndex2=0; this._everyAddVerticeCount2=0; this._everyUpdateVerticeCount2=0; this._indices=null; this._indexBuffer=null; this._indicesIndex=0; this._everyAddindiceCount=0; this._index=0; this._color=new Vector4(Math.random(),Math.random(),Math.random(),1); this._topColor=this._color; this._buttomColor=this._color; this._leftColor=this._color; this._rightColor=this._color; this._frontColor=this._color; this._backColor=this._color; this._localMatrix=new Matrix4x4(); this._localPostion=new Vector3(); this._localNormal=new Vector3(); this._owner=owner; this.id=DominoRenderElement.renderElementCount++; var _maxVertexCount=this._owner.DominoRenderElementMaxDominoCount *this._perDominoVertexCount; this._vertices1=new Float32Array(_maxVertexCount *this._floatCountPerVertices1); this._vertices2=new Float32Array(_maxVertexCount *this._floatCountPerVertices2); this._vertexBuffer1=new VertexBuffer3D(DominoVertex.vertexDeclaration1,_maxVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer2=new VertexBuffer3D(DominoVertex.vertexDeclaration2,_maxVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffers=[]; this._vertexBuffers.push(this._vertexBuffer1); this._vertexBuffers.push(this._vertexBuffer2); var _maxIndiceCount=this._owner.DominoRenderElementMaxDominoCount *this._perDominoIndiceCount; this._indices=new Uint16Array(_maxIndiceCount); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",_maxIndiceCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); } __class(DominoRenderElement,'laya.d3.extension.domino.DominoRenderElement'); var __proto=DominoRenderElement.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) __proto.addDomino=function(position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=Vector3.ONE); this._curDominoCount++; this._owner.dominoCount++; this._owner.dominoPosition.push(position); this.addDataForVertexBuffer1(); this.addDataForVertexBuffer2(position,rotation,scale); this.addDataForIndexBuffer(); } __proto.updateDomino=function(index,position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=Vector3.ONE); this._everyUpdateVerticeCount2=0; var offset=this._perDominoVertexCount *this._floatCountPerVertices2 *index; var positions=DominoFilter._positions; var positione,positionX=NaN,positionY=NaN,positionZ=NaN; var normals=DominoFilter._normals; var normale,normalX=NaN,normalY=NaN,normalZ=NaN; var i=0,length=positions.length; Matrix4x4.createAffineTransformation(position,rotation,scale,this._localMatrix); for (i=0;i < length;i++){ Vector3.transformCoordinate(positions[i],this._localMatrix,this._localPostion); positione=this._localPostion.elements; positionX=positione[0]; positionY=positione[1]; positionZ=positione[2]; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionX; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionY; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionZ; Vector3.TransformNormal(normals[i],this._localMatrix,this._localNormal); normale=this._localNormal.elements; normalX=normale[0]; normalY=normale[1]; normalZ=normale[2]; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalX; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalY; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalZ; } this._vertexBuffer2.setData(this._vertices2,offset,offset,this._everyUpdateVerticeCount2); } __proto.updateDominos=function(startIndex,count,keyFrames){ this._everyUpdateVerticeCount2=0; var offset=this._perDominoVertexCount *this._floatCountPerVertices2 *startIndex; var positions=DominoFilter._positions; var positione,positionX=NaN,positionY=NaN,positionZ=NaN; var normals=DominoFilter._normals; var normale,normalX=NaN,normalY=NaN,normalZ=NaN; var i=0,j=0,length=positions.length; var keyFrame; for (i=0;i < count;i++){ keyFrame=keyFrames[i]; Matrix4x4.createAffineTransformation(keyFrame.position,keyFrame.rotation,keyFrame.scale,this._localMatrix); for (j=0;j < length;j++){ Vector3.transformCoordinate(positions[j],this._localMatrix,this._localPostion); positione=this._localPostion.elements; positionX=positione[0]; positionY=positione[1]; positionZ=positione[2]; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionX; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionY; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionZ; Vector3.TransformNormal(normals[j],this._localMatrix,this._localNormal); normale=this._localNormal.elements; normalX=normale[0]; normalY=normale[1]; normalZ=normale[2]; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalX; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalY; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalZ; } } this._vertexBuffer2.setData(this._vertices2,offset,offset,this._everyUpdateVerticeCount2); } __proto.addDataForVertexBuffer1=function(){ this._everyAddVerticeCount1=0; this.addDataForVertices1(this._topColor); this.addDataForVertices1(this._buttomColor); this.addDataForVertices1(this._leftColor); this.addDataForVertices1(this._rightColor); this.addDataForVertices1(this._frontColor); this.addDataForVertices1(this._backColor); this._vertexBuffer1.setData(this._vertices1,this._verticesIndex1,this._verticesIndex1,this._everyAddVerticeCount1); this._verticesIndex1+=this._everyAddVerticeCount1; } __proto.addDataForVertexBuffer2=function(position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=Vector3.ONE); this._everyAddVerticeCount2=0; var positions=DominoFilter._positions; var positione,positionX=NaN,positionY=NaN,positionZ=NaN; var normals=DominoFilter._normals; var normale,normalX=NaN,normalY=NaN,normalZ=NaN; var i=0,j=0,length=positions.length; Matrix4x4.createAffineTransformation(position,rotation,scale,this._localMatrix); for (i=0;i < length;i++){ Vector3.transformCoordinate(positions[i],this._localMatrix,this._localPostion); positione=this._localPostion.elements; positionX=positione[0]; positionY=positione[1]; positionZ=positione[2]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=positionX; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=positionY; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=positionZ; Vector3.TransformNormal(normals[i],this._localMatrix,this._localNormal); normale=this._localNormal.elements; normalX=normale[0]; normalY=normale[1]; normalZ=normale[2]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=normalX; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=normalY; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=normalZ; } this._vertexBuffer2.setData(this._vertices2,this._verticesIndex2,this._verticesIndex2,this._everyAddVerticeCount2); this._verticesIndex2+=this._everyAddVerticeCount2; } __proto.addDataForIndexBuffer=function(){ this._everyAddindiceCount=0; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+0; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+1; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+2; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+2; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+3; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+0; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+4; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+7; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+6; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+6; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+5; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+4; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+8; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+9; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+10; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+10; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+11; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+8; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+12; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+15; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+14; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+14; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+13; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+12; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+16; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+17; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+18; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+18; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+19; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+16; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+20; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+23; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+22; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+22; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+21; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+20; this._indexBuffer.setData(this._indices,this._indicesIndex,this._indicesIndex,this._everyAddindiceCount); this._indicesIndex+=this._everyAddindiceCount; this._index+=this._perDominoVertexCount; } __proto.addDataForVertices1=function(color){ var colore=color.elements; var colorX=colore[0]; var colorY=colore[1]; var colorZ=colore[2]; var colorW=colore[3]; for (var i=0;i < 4;i++){ this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=colorX; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=colorY; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=colorZ; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=colorW; } } __proto._beforeRender=function(state){ this._indexBuffer._bind(); return true; } __proto._render=function(state){ WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._indicesIndex,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.drawCall++; Stat.trianglesFaces+=this._indicesIndex / 3; } __proto._getIndexBuffer=function(){ return this._indexBuffer; } __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer1; else if (index===1) return this._vertexBuffer2; else return null; } __proto._getVertexBuffers=function(){ return this._vertexBuffers; } __proto._getIndexBuffer=function(){ return null; } __getset(0,__proto,'_vertexBufferCount',function(){ return this._vertexBuffers.length; }); __getset(0,__proto,'triangleCount',function(){ return this._indicesIndex / 3; }); DominoRenderElement.renderElementCount=0; return DominoRenderElement; })() /** *DominoVertex 类用于创建多米诺顶点结构。 */ //class laya.d3.extension.domino.DominoVertex var DominoVertex=(function(){ function DominoVertex(){} __class(DominoVertex,'laya.d3.extension.domino.DominoVertex'); var __proto=DominoVertex.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'vertexDeclaration',function(){ return DominoVertex._vertexDeclaration1; }); __getset(1,DominoVertex,'vertexDeclaration1',function(){ return DominoVertex._vertexDeclaration1; }); __getset(1,DominoVertex,'vertexDeclaration2',function(){ return DominoVertex._vertexDeclaration2; }); __static(DominoVertex, ['_vertexDeclaration1',function(){return this._vertexDeclaration1=new VertexDeclaration(16, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1)]);},'_vertexDeclaration2',function(){return this._vertexDeclaration2=new VertexDeclaration(24, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3)]);} ]); return DominoVertex; })() /** *... *@author */ //class laya.d3.extension.lineRender.LineVertex var LineVertex=(function(){ function LineVertex(){} __class(LineVertex,'laya.d3.extension.lineRender.LineVertex'); var __proto=LineVertex.prototype; __getset(0,__proto,'vertexDeclaration',function(){ return LineVertex._vertexDeclaration1; }); __getset(1,LineVertex,'vertexDeclaration1',function(){ return LineVertex._vertexDeclaration1; }); __getset(1,LineVertex,'vertexDeclaration2',function(){ return LineVertex._vertexDeclaration2; }); __getset(1,LineVertex,'vertexDeclaration3',function(){ return LineVertex._vertexDeclaration3; }); __static(LineVertex, ['_vertexDeclaration1',function(){return this._vertexDeclaration1=new VertexDeclaration(16, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0Y*/40)]);},'_vertexDeclaration2',function(){return this._vertexDeclaration2=new VertexDeclaration(12, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.OFFSETVECTOR*/41)]);},'_vertexDeclaration3',function(){return this._vertexDeclaration3=new VertexDeclaration(8, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0X*/38), new VertexElement(4,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0X1*/39)]);} ]); return LineVertex; })() /** *@private *DynamicBatch 类用于动态批处理。 */ //class laya.d3.graphics.DynamicBatch var DynamicBatch=(function(){ function DynamicBatch(vertexDeclaration){ this._vertexDeclaration=null; this._vertexDatas=null; this._indexDatas=null; this._vertexBuffer=null; this._indexBuffer=null; this._currentCombineVertexCount=0; this._currentCombineIndexCount=0; this._combineRenderElements=null; this._materials=null; this._materialToRenderElementsOffsets=null; this._merageElements=null; this._combineRenderElementPool=null; this._combineRenderElementPoolIndex=0; this._currentCombineVertexCount=0; this._currentCombineIndexCount=0; this._combineRenderElements=[]; this._materialToRenderElementsOffsets=[]; this._materials=[]; this._merageElements=[]; this._combineRenderElementPool=[]; this._combineRenderElementPoolIndex=0; this._vertexDeclaration=vertexDeclaration; } __class(DynamicBatch,'laya.d3.graphics.DynamicBatch'); var __proto=DynamicBatch.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer; else return null; } __proto._getIndexBuffer=function(){ return this._indexBuffer; } __proto._getCombineRenderElementFromPool=function(view,projection,projectionView){ var renderElement=this._combineRenderElementPool[this._combineRenderElementPoolIndex++]; if (!renderElement){ this._combineRenderElementPool[this._combineRenderElementPoolIndex-1]=renderElement=new RenderElement(); renderElement._sprite3D=new MeshSprite3D(); } renderElement._sprite3D._render._renderUpdate(projectionView); return renderElement; } __proto._getRenderElement=function(view,projection,projectionView){ if (!this._vertexDatas){ this._vertexDatas=new Float32Array(this._vertexDeclaration.vertexStride / 4 *DynamicBatch.maxVertexCount); this._indexDatas=new Uint16Array(DynamicBatch.maxIndexCount); this._vertexBuffer=VertexBuffer3D.create(this._vertexDeclaration,DynamicBatch.maxVertexCount,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",DynamicBatch.maxIndexCount,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); } this._merageElements.length=0; var curMerVerCount=0; var curIndexCount=0; for (var i=0,n=this._combineRenderElements.length;i < n;i++){ var renderElement=this._combineRenderElements[i]; var subVertexDatas=renderElement.getDynamicBatchBakedVertexs(0); var subIndexDatas=renderElement.getBakedIndices(); var isInvert=renderElement._sprite3D.transform._isFrontFaceInvert; var indexOffset=curMerVerCount / (this._vertexDeclaration.vertexStride / 4); var indexStart=curIndexCount; var indexEnd=indexStart+subIndexDatas.length; renderElement._tempBatchIndexStart=indexStart; renderElement._tempBatchIndexEnd=indexEnd; this._indexDatas.set(subIndexDatas,curIndexCount); var k=0; if (isInvert){ for (k=indexStart;k < indexEnd;k+=3){ this._indexDatas[k]=indexOffset+this._indexDatas[k]; var index1=this._indexDatas[k+1]; var index2=this._indexDatas[k+2]; this._indexDatas[k+1]=indexOffset+index2; this._indexDatas[k+2]=indexOffset+index1; } }else { for (k=indexStart;k < indexEnd;k+=3){ this._indexDatas[k]=indexOffset+this._indexDatas[k]; this._indexDatas[k+1]=indexOffset+this._indexDatas[k+1]; this._indexDatas[k+2]=indexOffset+this._indexDatas[k+2]; } } curIndexCount+=subIndexDatas.length; this._vertexDatas.set(subVertexDatas,curMerVerCount); curMerVerCount+=subVertexDatas.length; } this._vertexBuffer.setData(this._vertexDatas); this._indexBuffer.setData(this._indexDatas); this._combineRenderElementPoolIndex=0; for (i=0,n=this._materials.length;i < n;i++){ var merageElement=this._getCombineRenderElementFromPool(view,projection,projectionView); merageElement._type=2; merageElement._staticBatch=null; merageElement.renderObj=this; var renderElementStartIndex=this._combineRenderElements[this._materialToRenderElementsOffsets[i]]._tempBatchIndexStart; var renderElementEndIndex=(i+1===this._materialToRenderElementsOffsets.length)? curIndexCount :this._combineRenderElements[this._materialToRenderElementsOffsets[i+1]]._tempBatchIndexStart; merageElement._tempBatchIndexStart=renderElementStartIndex; merageElement._tempBatchIndexEnd=renderElementEndIndex; merageElement._material=this._materials[i]; this._merageElements.push(merageElement); } } __proto._addCombineRenderObjTest=function(renderElement){ var renderObj=renderElement.renderObj; var indexCount=this._currentCombineIndexCount+renderObj._getIndexBuffer().indexCount; var vertexCount=this._currentCombineVertexCount+renderObj._getVertexBuffer().vertexCount; if (vertexCount > DynamicBatch.maxVertexCount || indexCount > DynamicBatch.maxIndexCount){ return false; } return true; } __proto._addCombineRenderObj=function(renderElement){ var renderObj=renderElement.renderObj; this._combineRenderElements.push(renderElement); this._currentCombineIndexCount=this._currentCombineIndexCount+renderObj._getIndexBuffer().indexCount; this._currentCombineVertexCount=this._currentCombineVertexCount+renderObj._getVertexBuffer().vertexCount; } __proto._addCombineMaterial=function(material){ this._materials.push(material); } __proto._addMaterialToRenderElementOffset=function(offset){ this._materialToRenderElementsOffsets.push(offset); } __proto._clearRenderElements=function(){ this._combineRenderElements.length=0; this._materials.length=0; this._materialToRenderElementsOffsets.length=0; this._currentCombineVertexCount=0; this._currentCombineIndexCount=0; } __proto._addToRenderQueue=function(scene,view,projection,projectionView){ this._getRenderElement(view,projection,projectionView); for (var i=0,n=this._materials.length;i < n;i++) scene.getRenderQueue(this._materials[i].renderQueue)._addDynamicBatchElement(this._merageElements[i]); } __proto._beforeRender=function(state){ this._vertexBuffer._bind(); this._indexBuffer._bind(); return true; } __proto._render=function(state){ var indexCount=state._batchIndexEnd-state._batchIndexStart; WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,state._batchIndexStart *2); Stat.drawCall++; Stat.trianglesFaces+=indexCount / 3; } /** *@private */ __proto._getVertexBuffers=function(){ return null; } __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); __getset(0,__proto,'triangleCount',function(){ return this._indexBuffer.indexCount / 3; }); __getset(0,__proto,'combineRenderElementsCount',function(){ return this._combineRenderElements.length; }); DynamicBatch.maxVertexCount=20000; DynamicBatch.maxIndexCount=40000; DynamicBatch.maxCombineTriangleCount=10; return DynamicBatch; })() /** *@private *DynamicBatchManager 类用于管理动态批处理。 */ //class laya.d3.graphics.DynamicBatchManager var DynamicBatchManager=(function(){ function DynamicBatchManager(){ this._dynamicBatches=null; this._prepareDynamicBatchCombineElements=null; this._dynamicBatches={}; this._prepareDynamicBatchCombineElements=[]; } __class(DynamicBatchManager,'laya.d3.graphics.DynamicBatchManager'); var __proto=DynamicBatchManager.prototype; __proto.getDynamicBatch=function(_vertexDeclaration,number){ var dynamicBatch; var key=_vertexDeclaration.id.toString()+number; if (!this._dynamicBatches[key]){ this._dynamicBatches[key]=dynamicBatch=new DynamicBatch(_vertexDeclaration); }else { dynamicBatch=this._dynamicBatches[key]; } return dynamicBatch; } /**需手动调用*/ __proto._garbageCollection=function(){ for (var key in this._dynamicBatches) if (this._dynamicBatches[key].combineRenderElementsCount===0) delete this._dynamicBatches[key]; } __proto._addPrepareRenderElement=function(renderElement){ this._prepareDynamicBatchCombineElements.push(renderElement); } /**@private */ __proto._finishCombineDynamicBatch=function(scene){ this._prepareDynamicBatchCombineElements.sort(DynamicBatchManager._sortPrepareDynamicBatch); var lastMaterial; var lastVertexDeclaration; var lastRenderElement; var lastBatchNumber=-1; var lastCanMerage=true; var curMaterial; var curRenderElement; var curDynamicBatch; var curbatchNumber=0; var laterAddMaterial; var laterAddRenderElement; var laterAddMatToElementOffset=-1; for (var i=0,n=this._prepareDynamicBatchCombineElements.length;i < n;i++){ curRenderElement=this._prepareDynamicBatchCombineElements[i]; var curDeclaration=curRenderElement.renderObj._getVertexBuffer(0).vertexDeclaration; var declarationChanged=(lastVertexDeclaration!==curDeclaration); declarationChanged && (curbatchNumber=0,lastVertexDeclaration=curDeclaration); var batchNumbrChanged=(curbatchNumber!==lastBatchNumber); batchNumbrChanged && (lastBatchNumber=curbatchNumber); if ((declarationChanged)|| batchNumbrChanged){ curDynamicBatch=this.getDynamicBatch(curDeclaration,curbatchNumber); lastMaterial=null; } if (lastCanMerage){ if (curDynamicBatch._addCombineRenderObjTest(curRenderElement)){ curMaterial=curRenderElement._material; if (lastMaterial!==curMaterial){ if (laterAddMaterial){ scene.getRenderQueue(laterAddRenderElement._material.renderQueue)._addRenderElement(laterAddRenderElement); laterAddMaterial=null; laterAddRenderElement=null; laterAddMatToElementOffset=-1; } laterAddMaterial=curMaterial; laterAddMatToElementOffset=curDynamicBatch.combineRenderElementsCount; laterAddRenderElement=curRenderElement; lastMaterial=curMaterial; }else { if (laterAddMaterial){ var lastRenderObj=laterAddRenderElement.renderObj; var curRenderObj=curRenderElement.renderObj; if (((lastRenderObj._getVertexBuffer().vertexCount+curRenderObj._getVertexBuffer().vertexCount)> DynamicBatch.maxVertexCount)|| ((lastRenderObj._getIndexBuffer().indexCount+curRenderObj._getIndexBuffer().indexCount)> DynamicBatch.maxIndexCount)){ scene.getRenderQueue(laterAddRenderElement._material.renderQueue)._addRenderElement(laterAddRenderElement); laterAddMaterial=curMaterial; laterAddMatToElementOffset=curDynamicBatch.combineRenderElementsCount; laterAddRenderElement=curRenderElement; }else { curDynamicBatch._addCombineMaterial(laterAddMaterial); curDynamicBatch._addMaterialToRenderElementOffset(laterAddMatToElementOffset); curDynamicBatch._addCombineRenderObj(laterAddRenderElement); laterAddMaterial=null; laterAddRenderElement=null; laterAddMatToElementOffset=-1; curDynamicBatch._addCombineRenderObj(curRenderElement); } }else { curDynamicBatch._addCombineRenderObj(curRenderElement); } } lastCanMerage=true; }else { if (laterAddMaterial){ scene.getRenderQueue(laterAddRenderElement._material.renderQueue)._addRenderElement(laterAddRenderElement); laterAddMaterial=null; laterAddRenderElement=null; laterAddMatToElementOffset=-1; } curbatchNumber++; lastCanMerage=false; } }else { lastRenderElement=this._prepareDynamicBatchCombineElements[i-1]; curDynamicBatch._addMaterialToRenderElementOffset(curDynamicBatch.combineRenderElementsCount); lastMaterial=lastRenderElement._material; curDynamicBatch._addCombineMaterial(lastMaterial); curDynamicBatch._addCombineRenderObj(lastRenderElement); lastCanMerage=true; curMaterial=curRenderElement._material; if (lastMaterial!==curMaterial){ laterAddMaterial=curMaterial; laterAddMatToElementOffset=curDynamicBatch.combineRenderElementsCount; laterAddRenderElement=curRenderElement; }else { curDynamicBatch._addCombineRenderObj(curRenderElement); } lastMaterial=curMaterial; } } if (laterAddMaterial){ scene.getRenderQueue(laterAddRenderElement._material.renderQueue)._addRenderElement(laterAddRenderElement); laterAddMaterial=null; laterAddRenderElement=null; laterAddMatToElementOffset=-1; } this._prepareDynamicBatchCombineElements.length=0; } __proto._clearRenderElements=function(){ for (var key in this._dynamicBatches) this._dynamicBatches[key]._clearRenderElements(); } __proto._addToRenderQueue=function(scene,view,projection,projectionView){ for (var key in this._dynamicBatches){ var dynamicBatch=this._dynamicBatches[key]; (dynamicBatch.combineRenderElementsCount > 0)&& (dynamicBatch._addToRenderQueue(scene,view,projection,projectionView)); } } __proto.dispose=function(){ this._dynamicBatches=null; } DynamicBatchManager._sortPrepareDynamicBatch=function(a,b){ return a._mainSortID-b._mainSortID; } return DynamicBatchManager; })() /** *@private */ //class laya.d3.graphics.FrustumCulling var FrustumCulling=(function(){ function FrustumCulling(){} __class(FrustumCulling,'laya.d3.graphics.FrustumCulling'); FrustumCulling.renderShadowObjectCulling=function(scene,lightFrustum,shadowQueues,lightViewProjectMatrix,nPSSMNum){ var i=0,j=0,n=0,m=0; for (i=0,n=shadowQueues.length;i < n;i++){ var quene=shadowQueues[i]; (quene)&& (quene._clearRenderElements()); }; var frustumCullingObjects=scene._cullingRenders; var baseRender,shadowQueue,renderElements; if (nPSSMNum > 1){ for (i=0,n=scene._cullingRendersLength;i < n;i++){ baseRender=frustumCullingObjects[i]; if (baseRender.castShadow && Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable){ for (var k=1,kNum=lightFrustum.length;k < kNum;k++){ shadowQueue=shadowQueues[k-1]; if (lightFrustum[k].containsBoundSphere(baseRender.boundingSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++) shadowQueue._addRenderElement(renderElements[j]); } } } } }else { for (i=0,n=scene._cullingRendersLength;i < n;i++){ baseRender=frustumCullingObjects[i]; if (baseRender.castShadow && Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable){ if (lightFrustum[0].containsBoundSphere(baseRender.boundingSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ baseRender._renderUpdate(lightViewProjectMatrix); shadowQueue=shadowQueues[0]; renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++) shadowQueue._addRenderElement(renderElements[j]); } } } } } FrustumCulling.renderShadowObjectCullingOctree=function(scene,lightFrustum,quenesResult,lightViewProjectMatrix,nPSSMNum){ for (var i=0,n=quenesResult.length;i < n;i++){ var quene=quenesResult[i]; (quene)&& (quene._clearRenderElements()); } if (nPSSMNum > 1){ scene.treeRoot.cullingShadowObjects(lightFrustum,quenesResult,true,0,scene); }else { scene.treeRoot.cullingShadowObjectsOnePSSM(lightFrustum[0],quenesResult,lightViewProjectMatrix,true,0,scene); } } FrustumCulling.renderObjectCulling=function(boundFrustum,scene,camera,view,projection,projectionView){ var i=0,n=0,j=0,m=0; var queues=scene._quenes; var dynamicBatchManager=scene._dynamicBatchManager; var frustumCullingObjects=scene._cullingRenders; for (i=0,n=queues.length;i < n;i++){ var queue=queues[i]; (queue)&& (queue._clearRenderElements()); }; var staticBatchManagers=StaticBatchManager._staticBatchManagers; for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._clearRenderElements(); dynamicBatchManager._clearRenderElements(); var cameraPosition=camera.transform.position; for (i=0,n=scene._cullingRendersLength;i < n;i++){ var baseRender=frustumCullingObjects[i]; if (Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable && (boundFrustum.containsBoundSphere(baseRender.boundingSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0)){ if (baseRender._renderUpdate(projectionView)){ baseRender._distanceForSort=Vector3.distance(baseRender.boundingSphere.center,cameraPosition)+baseRender.sortingFudge; var renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++){ var renderElement=renderElements[j]; var staticBatch=renderElement._staticBatch; if (staticBatch && (staticBatch._material===renderElement._material)){ staticBatch._addBatchRenderElement(renderElement); }else { var renderObj=renderElement.renderObj; if ((renderObj.triangleCount < /*laya.d3.graphics.DynamicBatch.maxCombineTriangleCount*/10)&& (renderObj._vertexBufferCount===1)&& (renderObj._getIndexBuffer())&& (renderElement._material.renderQueue < 2)&& renderElement._canDynamicBatch && (!baseRender._owner.isStatic)) dynamicBatchManager._addPrepareRenderElement(renderElement); else scene.getRenderQueue(renderElement._material.renderQueue)._addRenderElement(renderElement); } } } } } for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._addToRenderQueue(scene,view,projection,projectionView); dynamicBatchManager._finishCombineDynamicBatch(scene); dynamicBatchManager._addToRenderQueue(scene,view,projection,projectionView); } FrustumCulling.renderObjectCullingOctree=function(boundFrustum,scene,camera,view,projection,projectionView){ var i=0,n=0; var queues=scene._quenes; var dynamicBatchManager=scene._dynamicBatchManager; for (i=0,n=queues.length;i < n;i++){ var queue=queues[i]; (queue)&& (queue._clearRenderElements()); }; var staticBatchManagers=StaticBatchManager._staticBatchManagers; for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._clearRenderElements(); dynamicBatchManager._clearRenderElements(); scene._cullingRenders.length=0; scene.treeRoot.cullingObjects(boundFrustum,true,0,camera.transform.position,projectionView); for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._addToRenderQueue(scene,view,projection,projectionView); dynamicBatchManager._finishCombineDynamicBatch(scene); dynamicBatchManager._addToRenderQueue(scene,view,projection,projectionView); } FrustumCulling.renderObjectCullingNoBoundFrustum=function(scene,camera,view,projection,projectionView){ var i=0,n=0,j=0,m=0; var queues=scene._quenes; var dynamicBatchManager=scene._dynamicBatchManager; var frustumCullingObjects=scene._cullingRenders; for (i=0,n=queues.length;i < n;i++){ var queue=queues[i]; (queue)&& (queue._clearRenderElements()); }; var staticBatchManagers=StaticBatchManager._staticBatchManagers; for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._clearRenderElements(); dynamicBatchManager._clearRenderElements(); var cameraPosition=camera.transform.position; for (i=0,n=scene._cullingRendersLength;i < n;i++){ var baseRender=frustumCullingObjects[i]; if (Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable){ baseRender._renderUpdate(projectionView); baseRender._distanceForSort=Vector3.distance(baseRender.boundingSphere.center,cameraPosition)+baseRender.sortingFudge; var renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++){ var renderElement=renderElements[j]; var staticBatch=renderElement._staticBatch; if (staticBatch && (staticBatch._material===renderElement._material)){ staticBatch._addBatchRenderElement(renderElement); }else { var renderObj=renderElement.renderObj; if ((renderObj.triangleCount < /*laya.d3.graphics.DynamicBatch.maxCombineTriangleCount*/10)&& (renderObj._vertexBufferCount===1)&& (renderObj._getIndexBuffer())&& (renderElement._material.renderQueue < 2)&& renderElement._canDynamicBatch && (!baseRender._owner.isStatic)) dynamicBatchManager._addPrepareRenderElement(renderElement); else scene.getRenderQueue(renderElement._material.renderQueue)._addRenderElement(renderElement); } } } } for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._addToRenderQueue(scene,view,projection,projectionView); dynamicBatchManager._finishCombineDynamicBatch(scene); dynamicBatchManager._addToRenderQueue(scene,view,projection,projectionView); } return FrustumCulling; })() /** *@private *StaticBatchManager 类用于静态批处理管理的父类。 */ //class laya.d3.graphics.StaticBatchManager var StaticBatchManager=(function(){ function StaticBatchManager(){ /**@private */ this._initBatchRenderElements=null; /**@private */ this._staticBatches=null; this._initBatchRenderElements=[]; this._staticBatches={}; } __class(StaticBatchManager,'laya.d3.graphics.StaticBatchManager'); var __proto=StaticBatchManager.prototype; /** *@private */ __proto._finishInit=function(){ for (var key in this._staticBatches) this._staticBatches[key]._finishInit(); this._initBatchRenderElements.length=0; } /** *@private */ __proto._initStaticBatchs=function(rootSprite){ throw new Error("StaticBatchManager:must override this function."); } /** *@private */ __proto._addInitBatchSprite=function(renderableSprite3D){ var renderElements=renderableSprite3D._render._renderElements; for (var i=0,n=renderElements.length;i < n;i++) this._initBatchRenderElements.push(renderElements[i]); } /** *@private */ __proto._clearRenderElements=function(){ for (var key in this._staticBatches) this._staticBatches[key]._clearRenderElements(); } /** *@private */ __proto._garbageCollection=function(renderElement){ var staticBatch=renderElement._staticBatch; var initBatchRenderElements=staticBatch._initBatchRenderElements; var index=initBatchRenderElements.indexOf(renderElement); initBatchRenderElements.splice(index,1); if (initBatchRenderElements.length===0){ staticBatch.dispose(); delete this._staticBatches[staticBatch._key]; } } /** *@private */ __proto._addToRenderQueue=function(scene,view,projection,projectionView){ for (var key in this._staticBatches){ var staticBatch=this._staticBatches[key]; if (staticBatch._batchRenderElements.length > 0) staticBatch._updateToRenderQueue(scene,projectionView); } } __proto.dispose=function(){ this._staticBatches=null; } StaticBatchManager._addToStaticBatchQueue=function(sprite3D){ if ((sprite3D instanceof laya.d3.core.RenderableSprite3D )) (sprite3D)._addToInitStaticBatchManager(); for (var i=0,n=sprite3D.numChildren;i < n;i++) StaticBatchManager._addToStaticBatchQueue(sprite3D._childs [i]); } StaticBatchManager.combine=function(staticBatchRoot,renderableSprite3Ds){ var i=0,n=0,staticBatchManager; if (renderableSprite3Ds){ for (i=0,n=renderableSprite3Ds.length;i < n;i++){ var renderableSprite3D=renderableSprite3Ds[i]; renderableSprite3D._addToInitStaticBatchManager(); } }else { if (staticBatchRoot) StaticBatchManager._addToStaticBatchQueue(staticBatchRoot); } for (i=0,n=StaticBatchManager._staticBatchManagers.length;i < n;i++){ staticBatchManager=StaticBatchManager._staticBatchManagers[i]; staticBatchManager._initStaticBatchs(staticBatchRoot); staticBatchManager._finishInit(); } } StaticBatchManager._staticBatchManagers=[]; return StaticBatchManager; })() /** *StaticBatch 类用于静态合并的父类,该类为抽象类。 */ //class laya.d3.graphics.StaticBatch var StaticBatch=(function(){ function StaticBatch(key,manager,rootOwner){ /**@private */ this._combineRenderElementPoolIndex=0; /**@private */ this._combineRenderElementPool=null; /**@private */ this._initBatchRenderElements=null; /**@private */ this._batchRenderElements=null; /**@private */ this._material=null; /**@private */ this._rootOwner=null; /**@private */ this._key=null; /**@private */ this._manager=null; this._key=key; this._manager=manager; this._combineRenderElementPoolIndex=0; this._combineRenderElementPool=[]; this._initBatchRenderElements=[]; this._batchRenderElements=[]; this._rootOwner=rootOwner; } __class(StaticBatch,'laya.d3.graphics.StaticBatch'); var __proto=StaticBatch.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true,"laya.resource.IDispose":true}) /** *@private */ __proto._binarySearch=function(renderElement){ var start=0; var end=this._batchRenderElements.length-1; var mid=0; while (start <=end){ mid=Math.floor((start+end)/ 2); if (this._compareBatchRenderElement(this._batchRenderElements[mid],renderElement)) end=mid-1; else start=mid+1; } return start; } /** *@private */ __proto._compareBatchRenderElement=function(a,b){ throw new Error("StaticBatch:must override this function."); } /** *@private */ __proto._getVertexDecLightMap=function(vertexDeclaration){ if (vertexDeclaration===VertexPositionNormalTextureSkinSTangent.vertexDeclaration){ return VertexPositionNormalTexture0Texture1SkinSTangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTextureSkin.vertexDeclaration){ return VertexPositionNormalTexture0Texture1Skin.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalColorTextureSTangent.vertexDeclaration){ return VertexPositionNormalColorTexture0Texture1STangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNTBTexture.vertexDeclaration){ return null; }else if (vertexDeclaration===VertexPositionNormalColorTexture.vertexDeclaration){ return VertexPositionNormalColorTexture0Texture1.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTextureSTangent.vertexDeclaration){ return VertexPositionNormalTexture0Texture1STangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTexture.vertexDeclaration){ return VertexPositionNormalTexture0Texture1.vertexDeclaration; } if (vertexDeclaration===VertexPositionNormalTextureSkinTangent.vertexDeclaration){ return VertexPositionNormalTexture0Texture1SkinTangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTextureSkin.vertexDeclaration){ return VertexPositionNormalTexture0Texture1Skin.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalColorTextureTangent.vertexDeclaration){ return VertexPositionNormalColorTexture0Texture1Tangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNTBTexture.vertexDeclaration){ return null; }else if (vertexDeclaration===VertexPositionNormalColorTexture.vertexDeclaration){ return VertexPositionNormalColorTexture0Texture1.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTextureTangent.vertexDeclaration){ return VertexPositionNormalTexture0Texture1Tangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTexture.vertexDeclaration){ return VertexPositionNormalTexture0Texture1.vertexDeclaration; }else { return vertexDeclaration; } } /** *@private */ __proto._getCombineRenderElementFromPool=function(){ throw new Error("StaticBatch:must override this function."); } /** *@private */ __proto._addBatchRenderElement=function(renderElement){ this._batchRenderElements.splice(this._binarySearch(renderElement),0,renderElement); } /** *@private */ __proto._updateToRenderQueue=function(scene,projectionView){ this._combineRenderElementPoolIndex=0; this._getRenderElement(scene.getRenderQueue(this._material.renderQueue)._renderElements,scene,projectionView); } /** *@private */ __proto._getRenderElement=function(mergeElements,scene,projectionView){ throw new Error("StaticBatch:must override this function."); } /** *@private */ __proto._finishInit=function(){ throw new Error("StaticBatch:must override this function."); } /** *@private */ __proto._clearRenderElements=function(){ this._batchRenderElements.length=0; } /** *@private */ __proto.dispose=function(){} //..................临时................................. __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); return null; } __proto._getIndexBuffer=function(){ return null; } __proto._beforeRender=function(state){ return true; } __proto._render=function(state){} /** *@private */ __proto._getVertexBuffers=function(){ return null; } //..................临时................................. __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); __getset(0,__proto,'triangleCount',function(){ return 0; }); StaticBatch.combine=function(staticBatchRoot){ console.log("StaticBatch: discard property,please use StaticBatchManager.combine() function instead."); StaticBatchManager.combine(staticBatchRoot); } StaticBatch.maxBatchVertexCount=65535; return StaticBatch; })() /** *... *@author ... */ //class laya.d3.graphics.VertexDeclaration var VertexDeclaration=(function(){ function VertexDeclaration(vertexStride,vertexElements){ this._id=0; this._shaderValues=null; this._shaderDefineValue=0; //private var _shaderAttribute:*; this._vertexStride=0; this._vertexElements=null; this._vertexElementsDic=null; this._id=++VertexDeclaration._uniqueIDCounter; if (this._id > VertexDeclaration.maxVertexDeclaration) throw new Error("VertexDeclaration: VertexDeclaration count should not large than ",VertexDeclaration.maxVertexDeclaration); this._shaderValues=new ValusArray(); this._vertexElementsDic={}; this._vertexStride=vertexStride; this._vertexElements=vertexElements; for (var i=0;i < vertexElements.length;i++){ var vertexElement=vertexElements[i]; var attributeName=vertexElement.elementUsage; this._vertexElementsDic[attributeName]=vertexElement; var value=[VertexDeclaration._getTypeSize(vertexElement.elementFormat)/ 4,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,this._vertexStride,vertexElement.offset]; this._shaderValues.setValue(attributeName,value); switch (attributeName){ case /*laya.d3.graphics.VertexElementUsage.COLOR0*/1: this._addShaderDefine(ShaderCompile3D.SHADERDEFINE_COLOR); break case /*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2: this._addShaderDefine(ShaderCompile3D.SHADERDEFINE_UV0); break ; case /*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15: this._addShaderDefine(ShaderCompile3D.SHADERDEFINE_UV1); break ; } } } __class(VertexDeclaration,'laya.d3.graphics.VertexDeclaration'); var __proto=VertexDeclaration.prototype; /** *增加Shader宏定义。 *@param value 宏定义。 */ __proto._addShaderDefine=function(value){ this._shaderDefineValue |=value; } /** *移除Shader宏定义。 *@param value 宏定义。 */ __proto._removeShaderDefine=function(value){ this._shaderDefineValue &=~value; } __proto.getVertexElements=function(){ return this._vertexElements.slice(); } __proto.getVertexElementByUsage=function(usage){ return this._vertexElementsDic[usage]; } __proto.unBinding=function(){} __getset(0,__proto,'shaderDefineValue',function(){ return this._shaderDefineValue; }); /** *获取唯一标识ID(通常用于优化或识别)。 *@return 唯一标识ID */ __getset(0,__proto,'id',function(){ return this._id; }); __getset(0,__proto,'vertexStride',function(){ return this._vertexStride; }); __getset(0,__proto,'shaderValues',function(){ return this._shaderValues; }); VertexDeclaration._getTypeSize=function(format){ switch (format){ case /*laya.d3.graphics.VertexElementFormat.Single*/"single": return 4; case /*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2": return 8; case /*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3": return 12; case /*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4": return 16; case /*laya.d3.graphics.VertexElementFormat.Color*/"color": return 4; case /*laya.d3.graphics.VertexElementFormat.Byte4*/"byte4": return 4; case /*laya.d3.graphics.VertexElementFormat.Short2*/"short2": return 4; case /*laya.d3.graphics.VertexElementFormat.Short4*/"short4": return 8; case /*laya.d3.graphics.VertexElementFormat.NormalizedShort2*/"normalizedshort2": return 4; case /*laya.d3.graphics.VertexElementFormat.NormalizedShort4*/"normalizedshort4": return 8; case /*laya.d3.graphics.VertexElementFormat.HalfVector2*/"halfvector2": return 4; case /*laya.d3.graphics.VertexElementFormat.HalfVector4*/"halfvector4": return 8; } return 0; } VertexDeclaration.getVertexStride=function(vertexElements){ var curStride=0; for (var i=0;i < vertexElements.Length;i++){ var element=vertexElements[i]; var stride=element.offset+VertexDeclaration._getTypeSize(element.elementFormat); if (curStride < stride){ curStride=stride; } } return curStride; } VertexDeclaration._maxVertexDeclarationBit=1000; VertexDeclaration._uniqueIDCounter=1; __static(VertexDeclaration, ['maxVertexDeclaration',function(){return this.maxVertexDeclaration=2147483647-Math.floor(2147483647 / 1000)*1000;} ]); return VertexDeclaration; })() /** *VertexElement 类用于创建顶点结构分配。 */ //class laya.d3.graphics.VertexElement var VertexElement=(function(){ function VertexElement(offset,elementFormat,elementUsage){ this.offset=0; this.elementFormat=null; this.elementUsage=0; this.offset=offset; this.elementFormat=elementFormat; this.elementUsage=elementUsage; } __class(VertexElement,'laya.d3.graphics.VertexElement'); return VertexElement; })() /** *... *@author ... */ //class laya.d3.graphics.VertexElementFormat var VertexElementFormat=(function(){ function VertexElementFormat(){} __class(VertexElementFormat,'laya.d3.graphics.VertexElementFormat'); VertexElementFormat.Single="single"; VertexElementFormat.Vector2="vector2"; VertexElementFormat.Vector3="vector3"; VertexElementFormat.Vector4="vector4"; VertexElementFormat.Color="color"; VertexElementFormat.Byte4="byte4"; VertexElementFormat.Short2="short2"; VertexElementFormat.Short4="short4"; VertexElementFormat.NormalizedShort2="normalizedshort2"; VertexElementFormat.NormalizedShort4="normalizedshort4"; VertexElementFormat.HalfVector2="halfvector2"; VertexElementFormat.HalfVector4="halfvector4"; return VertexElementFormat; })() /** *... *@author ... */ //class laya.d3.graphics.VertexElementUsage var VertexElementUsage=(function(){ function VertexElementUsage(){} __class(VertexElementUsage,'laya.d3.graphics.VertexElementUsage'); VertexElementUsage.POSITION0=0; VertexElementUsage.COLOR0=1; VertexElementUsage.TEXTURECOORDINATE0=2; VertexElementUsage.NORMAL0=3; VertexElementUsage.BINORMAL0=4; VertexElementUsage.TANGENT0=5; VertexElementUsage.BLENDINDICES0=6; VertexElementUsage.BLENDWEIGHT0=7; VertexElementUsage.DEPTH0=8; VertexElementUsage.FOG0=9; VertexElementUsage.POINTSIZE0=10; VertexElementUsage.SAMPLE0=11; VertexElementUsage.TESSELLATEFACTOR0=12; VertexElementUsage.COLOR1=13; VertexElementUsage.NEXTTEXTURECOORDINATE0=14; VertexElementUsage.TEXTURECOORDINATE1=15; VertexElementUsage.NEXTTEXTURECOORDINATE1=16; VertexElementUsage.CORNERTEXTURECOORDINATE0=17; VertexElementUsage.VELOCITY0=18; VertexElementUsage.STARTCOLOR0=19; VertexElementUsage.STARTSIZE=20; VertexElementUsage.AGEADDSCALE0=21; VertexElementUsage.STARTROTATION=22; VertexElementUsage.ENDCOLOR0=23; VertexElementUsage.STARTLIFETIME=24; VertexElementUsage.TIME0=33; VertexElementUsage.SHAPEPOSITIONSTARTLIFETIME=30; VertexElementUsage.DIRECTIONTIME=32; VertexElementUsage.SIZEROTATION0=27; VertexElementUsage.RADIUS0=28; VertexElementUsage.RADIAN0=29; VertexElementUsage.STARTSPEED=31; VertexElementUsage.RANDOM0=34; VertexElementUsage.RANDOM1=35; VertexElementUsage.SIMULATIONWORLDPOSTION=36; VertexElementUsage.SIMULATIONWORLDROTATION=37; VertexElementUsage.TEXTURECOORDINATE0X=38; VertexElementUsage.TEXTURECOORDINATE0X1=39; VertexElementUsage.TEXTURECOORDINATE0Y=40; VertexElementUsage.OFFSETVECTOR=41; return VertexElementUsage; })() /** *VertexPositionNormalColorTangent 类用于创建粒子顶点结构。 */ //class laya.d3.graphics.VertexGlitter var VertexGlitter=(function(){ function VertexGlitter(position,textureCoordinate,time){ this._position=null; this._textureCoordinate0=null; this._time=NaN; this._position=position; this._textureCoordinate0=textureCoordinate; this._time=time; } __class(VertexGlitter,'laya.d3.graphics.VertexGlitter'); var __proto=VertexGlitter.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'time',function(){ return this._time; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexGlitter._vertexDeclaration; }); __getset(1,VertexGlitter,'vertexDeclaration',function(){ return VertexGlitter._vertexDeclaration; }); __static(VertexGlitter, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(24, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(20,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TIME0*/33)]);} ]); return VertexGlitter; })() /** *VertexPositionNormalColorTangent 类用于创建粒子顶点结构。 */ //class laya.d3.graphics.VertexParticle var VertexParticle=(function(){ function VertexParticle(cornerTextureCoordinate,position,velocity,startColor,endColor,sizeRotation,radius,radian,ageAddScale,time){ this._cornerTextureCoordinate=null; this._position=null; this._velocity=null; this._startColor=null; this._endColor=null; this._sizeRotation=null; this._radius=null; this._radian=null; this._ageAddScale=NaN; this._time=NaN; this._cornerTextureCoordinate=cornerTextureCoordinate; this._position=position; this._velocity=velocity; this._startColor=startColor; this._endColor=endColor; this._sizeRotation=sizeRotation; this._radius=radius; this._radian=radian; this._ageAddScale=ageAddScale; this._time=time; } __class(VertexParticle,'laya.d3.graphics.VertexParticle'); var __proto=VertexParticle.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'endColor',function(){ return this._endColor; }); __getset(0,__proto,'cornerTextureCoordinate',function(){ return this._cornerTextureCoordinate; }); __getset(0,__proto,'sizeRotation',function(){ return this._sizeRotation; }); __getset(0,__proto,'velocity',function(){ return this._velocity; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'startColor',function(){ return this._startColor; }); __getset(0,__proto,'radius',function(){ return this._radius; }); __getset(0,__proto,'radian',function(){ return this._radian; }); __getset(0,__proto,'ageAddScale',function(){ return this._ageAddScale; }); __getset(0,__proto,'time',function(){ return this._time; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexParticle._vertexDeclaration; }); __getset(1,VertexParticle,'vertexDeclaration',function(){ return VertexParticle._vertexDeclaration; }); __static(VertexParticle, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(116, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.CORNERTEXTURECOORDINATE0*/17), new VertexElement(16,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(28,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.VELOCITY0*/18), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.STARTCOLOR0*/19), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.ENDCOLOR0*/23), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.SIZEROTATION0*/27), new VertexElement(84,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.RADIUS0*/28), new VertexElement(92,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.RADIAN0*/29), new VertexElement(108,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.STARTLIFETIME*/24), new VertexElement(112,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TIME0*/33)]);} ]); return VertexParticle; })() //class laya.d3.graphics.VertexPosition var VertexPosition=(function(){ function VertexPosition(position){ this._position=null; this._position=position; } __class(VertexPosition,'laya.d3.graphics.VertexPosition'); var __proto=VertexPosition.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPosition._vertexDeclaration; }); /*INTERFACE laya.d3.graphics.IVertex */ __getset(1,VertexPosition,'vertexDeclaration',function(){ return VertexPosition._vertexDeclaration; }); __static(VertexPosition, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(12,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0)]);} ]); return VertexPosition; })() //class laya.d3.graphics.VertexPositionNormal var VertexPositionNormal=(function(){ function VertexPositionNormal(position,normal){ this._position=null; this._normal=null; this._position=position; this._normal=normal; } __class(VertexPositionNormal,'laya.d3.graphics.VertexPositionNormal'); var __proto=VertexPositionNormal.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormal._vertexDeclaration; }); /*INTERFACE laya.d3.graphics.IVertex */ __getset(1,VertexPositionNormal,'vertexDeclaration',function(){ return VertexPositionNormal._vertexDeclaration; }); __static(VertexPositionNormal, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(24,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3)]);} ]); return VertexPositionNormal; })() /** *VertexPositionNormalColor 类用于创建位置、法线、颜色顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColor var VertexPositionNormalColor=(function(){ function VertexPositionNormalColor(position,normal,color){ this._position=null; this._normal=null; this._color=null; this._position=position; this._normal=normal; this._color=color; } __class(VertexPositionNormalColor,'laya.d3.graphics.VertexPositionNormalColor'); var __proto=VertexPositionNormalColor.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColor._vertexDeclaration; }); __getset(1,VertexPositionNormalColor,'vertexDeclaration',function(){ return VertexPositionNormalColor._vertexDeclaration; }); __static(VertexPositionNormalColor, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(40,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1)]);} ]); return VertexPositionNormalColor; })() /** *VertexPositionNormalColorSkin 类用于创建位置、法线、颜色、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorSkin var VertexPositionNormalColorSkin=(function(){ function VertexPositionNormalColorSkin(position,normal,color,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._blendIndex=null; this._blendWeight=null; this._position=position; this._normal=normal; this._color=color; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorSkin,'laya.d3.graphics.VertexPositionNormalColorSkin'); var __proto=VertexPositionNormalColorSkin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorSkin._vertexDeclaration; }); __getset(1,VertexPositionNormalColorSkin,'vertexDeclaration',function(){ return VertexPositionNormalColorSkin._vertexDeclaration; }); __static(VertexPositionNormalColorSkin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(72,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNormalColorSkin; })() /** *VertexPositionNormalColorSkin 类用于创建位置、法线、颜色、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorSkinSTangent var VertexPositionNormalColorSkinSTangent=(function(){ function VertexPositionNormalColorSkinSTangent(position,normal,color,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorSkinSTangent,'laya.d3.graphics.VertexPositionNormalColorSkinSTangent'); var __proto=VertexPositionNormalColorSkinSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorSkinSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorSkinSTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorSkinSTangent._vertexDeclaration; }); __static(VertexPositionNormalColorSkinSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(88,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorSkinSTangent; })() /** *VertexPositionNormalColorSkin 类用于创建位置、法线、颜色、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorSkinTangent var VertexPositionNormalColorSkinTangent=(function(){ function VertexPositionNormalColorSkinTangent(position,normal,color,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorSkinTangent,'laya.d3.graphics.VertexPositionNormalColorSkinTangent'); var __proto=VertexPositionNormalColorSkinTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorSkinTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorSkinTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorSkinTangent._vertexDeclaration; }); __static(VertexPositionNormalColorSkinTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(84,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorSkinTangent; })() /** *VertexPositionNormalColorTangent 类用于创建位置、法线、颜色、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorSTangent var VertexPositionNormalColorSTangent=(function(){ function VertexPositionNormalColorSTangent(position,normal,color,tangent){ this._position=null; this._normal=null; this._color=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._tangent=tangent; } __class(VertexPositionNormalColorSTangent,'laya.d3.graphics.VertexPositionNormalColorSTangent'); var __proto=VertexPositionNormalColorSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorSTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorSTangent._vertexDeclaration; }); __static(VertexPositionNormalColorSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(56,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorSTangent; })() /** *VertexPositionNormalColorTangent 类用于创建位置、法线、颜色、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTangent var VertexPositionNormalColorTangent=(function(){ function VertexPositionNormalColorTangent(position,normal,color,tangent){ this._position=null; this._normal=null; this._color=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._tangent=tangent; } __class(VertexPositionNormalColorTangent,'laya.d3.graphics.VertexPositionNormalColorTangent'); var __proto=VertexPositionNormalColorTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(52,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTangent; })() /** *VertexPositionNormalColorTexture 类用于创建位置、法线、颜色、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture var VertexPositionNormalColorTexture=(function(){ function VertexPositionNormalColorTexture(position,normal,color,textureCoordinate){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; } __class(VertexPositionNormalColorTexture,'laya.d3.graphics.VertexPositionNormalColorTexture'); var __proto=VertexPositionNormalColorTexture.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTexture,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture._vertexDeclaration; }); __static(VertexPositionNormalColorTexture, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(48,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2)]);} ]); return VertexPositionNormalColorTexture; })() /** *VertexPositionNormalColorTexture 类用于创建位置、法线、颜色、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1 var VertexPositionNormalColorTexture0Texture1=(function(){ function VertexPositionNormalColorTexture0Texture1(position,normal,color,textureCoordinate0,textureCoordinate1){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; } __class(VertexPositionNormalColorTexture0Texture1,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1'); var __proto=VertexPositionNormalColorTexture0Texture1.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalColorTexture0Texture1,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(56,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15)]);} ]); return VertexPositionNormalColorTexture0Texture1; })() /** *VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1Skin var VertexPositionNormalColorTexture0Texture1Skin=(function(){ function VertexPositionNormalColorTexture0Texture1Skin(position,normal,color,textureCoordinate0,textureCoordinate1,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorTexture0Texture1Skin,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1Skin'); var __proto=VertexPositionNormalColorTexture0Texture1Skin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1Skin._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(1,VertexPositionNormalColorTexture0Texture1Skin,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1Skin._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1Skin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(88,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNormalColorTexture0Texture1Skin; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1SkinSTangent var VertexPositionNormalColorTexture0Texture1SkinSTangent=(function(){ function VertexPositionNormalColorTexture0Texture1SkinSTangent(position,normal,color,textureCoordinate0,textureCoordinate1,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorTexture0Texture1SkinSTangent,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1SkinSTangent'); var __proto=VertexPositionNormalColorTexture0Texture1SkinSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1SkinSTangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(1,VertexPositionNormalColorTexture0Texture1SkinSTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1SkinSTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1SkinSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(104,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(88,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTexture0Texture1SkinSTangent; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1SkinTangent var VertexPositionNormalColorTexture0Texture1SkinTangent=(function(){ function VertexPositionNormalColorTexture0Texture1SkinTangent(){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; } __class(VertexPositionNormalColorTexture0Texture1SkinTangent,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1SkinTangent'); var __proto=VertexPositionNormalColorTexture0Texture1SkinTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __proto.VertexPositionNormalColorTexture0SkinTangent=function(position,normal,color,textureCoordinate0,textureCoordinate1,tangent,blendIndex,blendWeight){ this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1SkinTangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(1,VertexPositionNormalColorTexture0Texture1SkinTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1SkinTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1SkinTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(100,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(88,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTexture0Texture1SkinTangent; })() /** *VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1STangent var VertexPositionNormalColorTexture0Texture1STangent=(function(){ function VertexPositionNormalColorTexture0Texture1STangent(position,normal,color,textureCoordinate0,textureCoordinate1,tangent){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; } __class(VertexPositionNormalColorTexture0Texture1STangent,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1STangent'); var __proto=VertexPositionNormalColorTexture0Texture1STangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1STangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalColorTexture0Texture1STangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1STangent._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1STangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(72,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTexture0Texture1STangent; })() /** *VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1Tangent var VertexPositionNormalColorTexture0Texture1Tangent=(function(){ function VertexPositionNormalColorTexture0Texture1Tangent(){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._tangent=null; } __class(VertexPositionNormalColorTexture0Texture1Tangent,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1Tangent'); var __proto=VertexPositionNormalColorTexture0Texture1Tangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __proto.VertexPositionNormalColorTexture0Tangent=function(position,normal,color,textureCoordinate0,textureCoordinate1,tangent){ this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; } __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1Tangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalColorTexture0Texture1Tangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1Tangent._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1Tangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(68,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTexture0Texture1Tangent; })() /** *VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTextureSkin var VertexPositionNormalColorTextureSkin=(function(){ function VertexPositionNormalColorTextureSkin(position,normal,color,textureCoordinate,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorTextureSkin,'laya.d3.graphics.VertexPositionNormalColorTextureSkin'); var __proto=VertexPositionNormalColorTextureSkin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkin._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTextureSkin,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkin._vertexDeclaration; }); __static(VertexPositionNormalColorTextureSkin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(80,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNormalColorTextureSkin; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTextureSkinSTangent var VertexPositionNormalColorTextureSkinSTangent=(function(){ function VertexPositionNormalColorTextureSkinSTangent(position,normal,color,textureCoordinate,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorTextureSkinSTangent,'laya.d3.graphics.VertexPositionNormalColorTextureSkinSTangent'); var __proto=VertexPositionNormalColorTextureSkinSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkinSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTextureSkinSTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkinSTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTextureSkinSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(96,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(80,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTextureSkinSTangent; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTextureSkinTangent var VertexPositionNormalColorTextureSkinTangent=(function(){ function VertexPositionNormalColorTextureSkinTangent(position,normal,color,textureCoordinate,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorTextureSkinTangent,'laya.d3.graphics.VertexPositionNormalColorTextureSkinTangent'); var __proto=VertexPositionNormalColorTextureSkinTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkinTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTextureSkinTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkinTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTextureSkinTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(92,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(80,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTextureSkinTangent; })() /** *VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTextureSTangent var VertexPositionNormalColorTextureSTangent=(function(){ function VertexPositionNormalColorTextureSTangent(position,normal,color,textureCoordinate,tangent){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; this._tangent=tangent; } __class(VertexPositionNormalColorTextureSTangent,'laya.d3.graphics.VertexPositionNormalColorTextureSTangent'); var __proto=VertexPositionNormalColorTextureSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTextureSTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTextureSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(64,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTextureSTangent; })() /** *VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTextureTangent var VertexPositionNormalColorTextureTangent=(function(){ function VertexPositionNormalColorTextureTangent(position,normal,color,textureCoordinate,tangent){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; this._tangent=tangent; } __class(VertexPositionNormalColorTextureTangent,'laya.d3.graphics.VertexPositionNormalColorTextureTangent'); var __proto=VertexPositionNormalColorTextureTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTextureTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTextureTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(60,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTextureTangent; })() //class laya.d3.graphics.VertexPositionNormalSTangent var VertexPositionNormalSTangent=(function(){ function VertexPositionNormalSTangent(position,normal,tangent){ this._position=null; this._normal=null; this._tangent=null; this._position=position; this._normal=normal; this._tangent=tangent; } __class(VertexPositionNormalSTangent,'laya.d3.graphics.VertexPositionNormalSTangent'); var __proto=VertexPositionNormalSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalSTangent._vertexDeclaration; }); /*INTERFACE laya.d3.graphics.IVertex */ __getset(1,VertexPositionNormalSTangent,'vertexDeclaration',function(){ return VertexPositionNormalSTangent._vertexDeclaration; }); __static(VertexPositionNormalSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(40,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalSTangent; })() //class laya.d3.graphics.VertexPositionNormalTangent var VertexPositionNormalTangent=(function(){ function VertexPositionNormalTangent(position,normal,tangent){ this._position=null; this._normal=null; this._tangent=null; this._position=position; this._normal=normal; this._tangent=tangent; } __class(VertexPositionNormalTangent,'laya.d3.graphics.VertexPositionNormalTangent'); var __proto=VertexPositionNormalTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTangent._vertexDeclaration; }); /*INTERFACE laya.d3.graphics.IVertex */ __getset(1,VertexPositionNormalTangent,'vertexDeclaration',function(){ return VertexPositionNormalTangent._vertexDeclaration; }); __static(VertexPositionNormalTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(36,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTangent; })() /** *VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture var VertexPositionNormalTexture=(function(){ function VertexPositionNormalTexture(position,normal,textureCoordinate){ this._position=null; this._normal=null; this._textureCoordinate=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; } __class(VertexPositionNormalTexture,'laya.d3.graphics.VertexPositionNormalTexture'); var __proto=VertexPositionNormalTexture.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture._vertexDeclaration; }); __getset(1,VertexPositionNormalTexture,'vertexDeclaration',function(){ return VertexPositionNormalTexture._vertexDeclaration; }); __static(VertexPositionNormalTexture, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(32,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2)]);} ]); return VertexPositionNormalTexture; })() /** *VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1 var VertexPositionNormalTexture0Texture1=(function(){ function VertexPositionNormalTexture0Texture1(position,normal,textureCoordinate0,textureCoordinate1){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; } __class(VertexPositionNormalTexture0Texture1,'laya.d3.graphics.VertexPositionNormalTexture0Texture1'); var __proto=VertexPositionNormalTexture0Texture1.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalTexture0Texture1,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(40,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15)]);} ]); return VertexPositionNormalTexture0Texture1; })() /** *VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1Skin var VertexPositionNormalTexture0Texture1Skin=(function(){ function VertexPositionNormalTexture0Texture1Skin(position,normal,textureCoordinate0,textureCoordinate1,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalTexture0Texture1Skin,'laya.d3.graphics.VertexPositionNormalTexture0Texture1Skin'); var __proto=VertexPositionNormalTexture0Texture1Skin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1Skin._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(1,VertexPositionNormalTexture0Texture1Skin,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1Skin._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1Skin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(72,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNormalTexture0Texture1Skin; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1SkinSTangent var VertexPositionNormalTexture0Texture1SkinSTangent=(function(){ function VertexPositionNormalTexture0Texture1SkinSTangent(position,normal,textureCoordinate0,textureCoordinate1,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalTexture0Texture1SkinSTangent,'laya.d3.graphics.VertexPositionNormalTexture0Texture1SkinSTangent'); var __proto=VertexPositionNormalTexture0Texture1SkinSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1SkinSTangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(1,VertexPositionNormalTexture0Texture1SkinSTangent,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1SkinSTangent._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1SkinSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(88,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTexture0Texture1SkinSTangent; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1SkinTangent var VertexPositionNormalTexture0Texture1SkinTangent=(function(){ function VertexPositionNormalTexture0Texture1SkinTangent(){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; } __class(VertexPositionNormalTexture0Texture1SkinTangent,'laya.d3.graphics.VertexPositionNormalTexture0Texture1SkinTangent'); var __proto=VertexPositionNormalTexture0Texture1SkinTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __proto.VertexPositionNormalTexture0SkinTangent=function(position,normal,textureCoordinate0,textureCoordinate1,tangent,blendIndex,blendWeight){ this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1SkinTangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(1,VertexPositionNormalTexture0Texture1SkinTangent,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1SkinTangent._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1SkinTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(84,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTexture0Texture1SkinTangent; })() /** *VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1STangent var VertexPositionNormalTexture0Texture1STangent=(function(){ function VertexPositionNormalTexture0Texture1STangent(position,normal,textureCoordinate0,textureCoordinate1,tangent){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; } __class(VertexPositionNormalTexture0Texture1STangent,'laya.d3.graphics.VertexPositionNormalTexture0Texture1STangent'); var __proto=VertexPositionNormalTexture0Texture1STangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1STangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalTexture0Texture1STangent,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1STangent._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1STangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(56,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTexture0Texture1STangent; })() /** *VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1Tangent var VertexPositionNormalTexture0Texture1Tangent=(function(){ function VertexPositionNormalTexture0Texture1Tangent(){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._tangent=null; } __class(VertexPositionNormalTexture0Texture1Tangent,'laya.d3.graphics.VertexPositionNormalTexture0Texture1Tangent'); var __proto=VertexPositionNormalTexture0Texture1Tangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __proto.VertexPositionNormalTexture0Tangent=function(position,normal,textureCoordinate0,textureCoordinate1,tangent){ this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; } __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1Tangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalTexture0Texture1Tangent,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1Tangent._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1Tangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(52,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTexture0Texture1Tangent; })() /** *VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTextureSkin var VertexPositionNormalTextureSkin=(function(){ function VertexPositionNormalTextureSkin(position,normal,textureCoordinate,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalTextureSkin,'laya.d3.graphics.VertexPositionNormalTextureSkin'); var __proto=VertexPositionNormalTextureSkin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkin._vertexDeclaration; }); __getset(1,VertexPositionNormalTextureSkin,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkin._vertexDeclaration; }); __static(VertexPositionNormalTextureSkin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(64,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNormalTextureSkin; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTextureSkinSTangent var VertexPositionNormalTextureSkinSTangent=(function(){ function VertexPositionNormalTextureSkinSTangent(position,normal,textureCoordinate,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalTextureSkinSTangent,'laya.d3.graphics.VertexPositionNormalTextureSkinSTangent'); var __proto=VertexPositionNormalTextureSkinSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkinSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalTextureSkinSTangent,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkinSTangent._vertexDeclaration; }); __static(VertexPositionNormalTextureSkinSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(80,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTextureSkinSTangent; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTextureSkinTangent var VertexPositionNormalTextureSkinTangent=(function(){ function VertexPositionNormalTextureSkinTangent(position,normal,textureCoordinate,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalTextureSkinTangent,'laya.d3.graphics.VertexPositionNormalTextureSkinTangent'); var __proto=VertexPositionNormalTextureSkinTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkinTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalTextureSkinTangent,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkinTangent._vertexDeclaration; }); __static(VertexPositionNormalTextureSkinTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(76,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTextureSkinTangent; })() /** *VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTextureSTangent var VertexPositionNormalTextureSTangent=(function(){ function VertexPositionNormalTextureSTangent(position,normal,textureCoordinate,tangent){ this._position=null; this._normal=null; this._textureCoordinate=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; this._tangent=tangent; } __class(VertexPositionNormalTextureSTangent,'laya.d3.graphics.VertexPositionNormalTextureSTangent'); var __proto=VertexPositionNormalTextureSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTextureSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalTextureSTangent,'vertexDeclaration',function(){ return VertexPositionNormalTextureSTangent._vertexDeclaration; }); __static(VertexPositionNormalTextureSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(48,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTextureSTangent; })() /** *VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTextureTangent var VertexPositionNormalTextureTangent=(function(){ function VertexPositionNormalTextureTangent(position,normal,textureCoordinate,tangent){ this._position=null; this._normal=null; this._textureCoordinate=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; this._tangent=tangent; } __class(VertexPositionNormalTextureTangent,'laya.d3.graphics.VertexPositionNormalTextureTangent'); var __proto=VertexPositionNormalTextureTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTextureTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalTextureTangent,'vertexDeclaration',function(){ return VertexPositionNormalTextureTangent._vertexDeclaration; }); __static(VertexPositionNormalTextureTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(44,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTextureTangent; })() /** *VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNTBTexture var VertexPositionNTBTexture=(function(){ function VertexPositionNTBTexture(position,normal,textureCoordinate){ this._position=null; this._normal=null; this._textureCoordinate=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; } __class(VertexPositionNTBTexture,'laya.d3.graphics.VertexPositionNTBTexture'); var __proto=VertexPositionNTBTexture.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNTBTexture._vertexDeclaration; }); __getset(1,VertexPositionNTBTexture,'vertexDeclaration',function(){ return VertexPositionNTBTexture._vertexDeclaration; }); __static(VertexPositionNTBTexture, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(56,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5), new VertexElement(36,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.BINORMAL0*/4), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2)]);} ]); return VertexPositionNTBTexture; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNTBTexture0Texture1Skin var VertexPositionNTBTexture0Texture1Skin=(function(){ function VertexPositionNTBTexture0Texture1Skin(position,normal,binormal,textureCoordinate0,textureCoordinate1,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this.binormal=null; this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; binormal=binormal; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNTBTexture0Texture1Skin,'laya.d3.graphics.VertexPositionNTBTexture0Texture1Skin'); var __proto=VertexPositionNTBTexture0Texture1Skin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNTBTexture0Texture1Skin._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(1,VertexPositionNTBTexture0Texture1Skin,'vertexDeclaration',function(){ return VertexPositionNTBTexture0Texture1Skin._vertexDeclaration; }); __static(VertexPositionNTBTexture0Texture1Skin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(96,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5), new VertexElement(36,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.BINORMAL0*/4), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(80,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNTBTexture0Texture1Skin; })() /** *VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNTBTextureSkin var VertexPositionNTBTextureSkin=(function(){ function VertexPositionNTBTextureSkin(position,normal,textureCoordinate){ this._position=null; this._normal=null; this._textureCoordinate=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; } __class(VertexPositionNTBTextureSkin,'laya.d3.graphics.VertexPositionNTBTextureSkin'); var __proto=VertexPositionNTBTextureSkin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNTBTextureSkin._vertexDeclaration; }); __getset(1,VertexPositionNTBTextureSkin,'vertexDeclaration',function(){ return VertexPositionNTBTextureSkin._vertexDeclaration; }); __static(VertexPositionNTBTextureSkin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(88,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5), new VertexElement(36,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.BINORMAL0*/4), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNTBTextureSkin; })() /** *VertexPositionTerrain 类用于创建位置、法线、纹理1、纹理2顶点结构。 */ //class laya.d3.graphics.VertexPositionTerrain var VertexPositionTerrain=(function(){ function VertexPositionTerrain(position,normal,textureCoord0,textureCoord1){ this._position=null; this._normal=null; this._textureCoord0=null; this._textureCoord1=null; this._position=position; this._normal=normal; this._textureCoord0=textureCoord0; this._textureCoord1=textureCoord1; } __class(VertexPositionTerrain,'laya.d3.graphics.VertexPositionTerrain'); var __proto=VertexPositionTerrain.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoord0',function(){ return this._textureCoord0; }); __getset(0,__proto,'textureCoord1',function(){ return this._textureCoord1; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionTerrain._vertexDeclaration; }); __getset(1,VertexPositionTerrain,'vertexDeclaration',function(){ return VertexPositionTerrain._vertexDeclaration; }); __static(VertexPositionTerrain, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(40,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15)]);} ]); return VertexPositionTerrain; })() /** *VertexPositionNormalTexture 类用于创建位置、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionTexture0 var VertexPositionTexture0=(function(){ function VertexPositionTexture0(position,textureCoordinate0){ this._position=null; this._textureCoordinate0=null; this._position=position; this._textureCoordinate0=textureCoordinate0; } __class(VertexPositionTexture0,'laya.d3.graphics.VertexPositionTexture0'); var __proto=VertexPositionTexture0.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionTexture0._vertexDeclaration; }); __getset(1,VertexPositionTexture0,'vertexDeclaration',function(){ return VertexPositionTexture0._vertexDeclaration; }); __static(VertexPositionTexture0, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(20,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2)]);} ]); return VertexPositionTexture0; })() /** *VertexShurikenParticle 类用于创建粒子顶点结构。 */ //class laya.d3.graphics.VertexShurikenParticleBillboard var VertexShurikenParticleBillboard=(function(){ function VertexShurikenParticleBillboard(cornerTextureCoordinate,positionStartLifeTime,velocity,startColor,startSize,startRotation0,startRotation1,startRotation2,ageAddScale,time,startSpeed,randoms0,randoms1,simulationWorldPostion){ /**@private */ this._cornerTextureCoordinate=null; /**@private */ this._positionStartLifeTime=null; /**@private */ this._velocity=null; /**@private */ this._startColor=null; /**@private */ this._startSize=null; /**@private */ this._startRotation0=null; /**@private */ this._startRotation1=null; /**@private */ this._startRotation2=null; /**@private */ this._startLifeTime=NaN; /**@private */ this._time=NaN; /**@private */ this._startSpeed=NaN; /**@private */ this._randoms0=null; /**@private */ this._randoms1=null; /**@private */ this._simulationWorldPostion=null; this._cornerTextureCoordinate=cornerTextureCoordinate; this._positionStartLifeTime=positionStartLifeTime; this._velocity=velocity; this._startColor=startColor; this._startSize=startSize; this._startRotation0=startRotation0; this._startRotation1=startRotation1; this._startRotation2=startRotation2; this._startLifeTime=ageAddScale; this._time=time; this._startSpeed=startSpeed; this._randoms0=this.random0; this._randoms1=this.random1; this._simulationWorldPostion=simulationWorldPostion; } __class(VertexShurikenParticleBillboard,'laya.d3.graphics.VertexShurikenParticleBillboard'); var __proto=VertexShurikenParticleBillboard.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'cornerTextureCoordinate',function(){ return this._cornerTextureCoordinate; }); __getset(0,__proto,'random1',function(){ return this._randoms1; }); __getset(0,__proto,'startRotation2',function(){ return this._startRotation2; }); __getset(0,__proto,'positionStartLifeTime',function(){ return this._positionStartLifeTime; }); __getset(0,__proto,'velocity',function(){ return this._velocity; }); __getset(0,__proto,'random0',function(){ return this._randoms0; }); __getset(0,__proto,'startSize',function(){ return this._startSize; }); __getset(0,__proto,'startColor',function(){ return this._startColor; }); __getset(0,__proto,'startRotation0',function(){ return this._startRotation0; }); __getset(0,__proto,'startRotation1',function(){ return this._startRotation1; }); __getset(0,__proto,'startLifeTime',function(){ return this._startLifeTime; }); __getset(0,__proto,'time',function(){ return this._time; }); __getset(0,__proto,'startSpeed',function(){ return this._startSpeed; }); __getset(0,__proto,'simulationWorldPostion',function(){ return this._simulationWorldPostion; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexShurikenParticleBillboard._vertexDeclaration; }); __getset(1,VertexShurikenParticleBillboard,'vertexDeclaration',function(){ return VertexShurikenParticleBillboard._vertexDeclaration; }); __static(VertexShurikenParticleBillboard, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(152,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.CORNERTEXTURECOORDINATE0*/17), new VertexElement(16,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.SHAPEPOSITIONSTARTLIFETIME*/30), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.DIRECTIONTIME*/32), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.STARTCOLOR0*/19), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.STARTSIZE*/20), new VertexElement(76,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.STARTROTATION*/22), new VertexElement(88,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.STARTSPEED*/31), new VertexElement(92,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.RANDOM0*/34), new VertexElement(108,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.RANDOM1*/35), new VertexElement(124,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDPOSTION*/36), new VertexElement(136,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDROTATION*/37)]);} ]); return VertexShurikenParticleBillboard; })() /** *VertexShurikenParticle 类用于创建粒子顶点结构。 */ //class laya.d3.graphics.VertexShurikenParticleMesh var VertexShurikenParticleMesh=(function(){ function VertexShurikenParticleMesh(cornerTextureCoordinate,positionStartLifeTime,velocity,startColor,startSize,startRotation0,startRotation1,startRotation2,ageAddScale,time,startSpeed,randoms0,randoms1,simulationWorldPostion){ /**@private */ this._cornerTextureCoordinate=null; /**@private */ this._positionStartLifeTime=null; /**@private */ this._velocity=null; /**@private */ this._startColor=null; /**@private */ this._startSize=null; /**@private */ this._startRotation0=null; /**@private */ this._startRotation1=null; /**@private */ this._startRotation2=null; /**@private */ this._startLifeTime=NaN; /**@private */ this._time=NaN; /**@private */ this._startSpeed=NaN; /**@private */ this._randoms0=null; /**@private */ this._randoms1=null; /**@private */ this._simulationWorldPostion=null; this._cornerTextureCoordinate=cornerTextureCoordinate; this._positionStartLifeTime=positionStartLifeTime; this._velocity=velocity; this._startColor=startColor; this._startSize=startSize; this._startRotation0=startRotation0; this._startRotation1=startRotation1; this._startRotation2=startRotation2; this._startLifeTime=ageAddScale; this._time=time; this._startSpeed=startSpeed; this._randoms0=this.random0; this._randoms1=this.random1; this._simulationWorldPostion=simulationWorldPostion; } __class(VertexShurikenParticleMesh,'laya.d3.graphics.VertexShurikenParticleMesh'); var __proto=VertexShurikenParticleMesh.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'cornerTextureCoordinate',function(){ return this._cornerTextureCoordinate; }); __getset(0,__proto,'velocity',function(){ return this._velocity; }); __getset(0,__proto,'position',function(){ return this._positionStartLifeTime; }); __getset(0,__proto,'random0',function(){ return this._randoms0; }); __getset(0,__proto,'startSize',function(){ return this._startSize; }); __getset(0,__proto,'startColor',function(){ return this._startColor; }); __getset(0,__proto,'startRotation0',function(){ return this._startRotation0; }); __getset(0,__proto,'startRotation1',function(){ return this._startRotation1; }); __getset(0,__proto,'random1',function(){ return this._randoms1; }); __getset(0,__proto,'startRotation2',function(){ return this._startRotation2; }); __getset(0,__proto,'startLifeTime',function(){ return this._startLifeTime; }); __getset(0,__proto,'time',function(){ return this._time; }); __getset(0,__proto,'startSpeed',function(){ return this._startSpeed; }); __getset(0,__proto,'simulationWorldPostion',function(){ return this._simulationWorldPostion; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexShurikenParticleMesh._vertexDeclaration; }); __getset(1,VertexShurikenParticleMesh,'vertexDeclaration',function(){ return VertexShurikenParticleMesh._vertexDeclaration; }); __static(VertexShurikenParticleMesh, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(172,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(28,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(36,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.SHAPEPOSITIONSTARTLIFETIME*/30), new VertexElement(52,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.DIRECTIONTIME*/32), new VertexElement(68,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.STARTCOLOR0*/19), new VertexElement(84,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.STARTSIZE*/20), new VertexElement(96,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.STARTROTATION*/22), new VertexElement(108,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.STARTSPEED*/31), new VertexElement(112,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.RANDOM0*/34), new VertexElement(128,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.RANDOM1*/35), new VertexElement(144,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDPOSTION*/36), new VertexElement(156,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDROTATION*/37)]);} ]); return VertexShurikenParticleMesh; })() /** *@private *LoadModel 类用于模型加载。 */ //class laya.d3.loaders.LoadModelV01 var LoadModelV01=(function(){ function LoadModelV01(readData,version,mesh,materials,subMeshes,materialMap){ /**@private */ this._version=null; /**@private */ this._strings=['BLOCK','DATA',"STRINGS"]; /**@private */ this._materials=null; /**@private */ this._subMeshes=null; /**@private */ this._materialMap=null; /**@private */ this._readData=null; /**@private */ this._mesh=null; /**@private */ this._BLOCK={count:0}; /**@private */ this._DATA={offset:0,size:0}; /**@private */ this._STRINGS={offset:0,size:0}; /**@private */ this._shaderAttributes=null; this._mesh=mesh; this._materials=materials; this._subMeshes=subMeshes; this._materialMap=materialMap; this._version=version; this._onLoaded(readData); } __class(LoadModelV01,'laya.d3.loaders.LoadModelV01'); var __proto=LoadModelV01.prototype; /** *@private */ __proto._onLoaded=function(readData){ this._readData=readData; this.READ_BLOCK(); for (var i=0;i < this._BLOCK.count;i++){ var index=this._readData.getUint16(); var blockName=this._strings[index]; var fn=this["READ_"+blockName]; if (fn==null)throw new Error("model file err,no this function:"+index+" "+blockName); if (!fn.call(this))break ; } return this._mesh; } __proto.onError=function(){} /** *@private */ __proto._readString=function(){ return this._strings[this._readData.getUint16()]; } __proto.READ_BLOCK=function(){ var n=this._readData.getUint16(); this._BLOCK.count=this._readData.getUint16(); return true; } __proto.READ_DATA=function(){ this._DATA.offset=this._readData.getUint32(); this._DATA.size=this._readData.getUint32(); return true; } __proto.READ_STRINGS=function(){ this._STRINGS.offset=this._readData.getUint16(); this._STRINGS.size=this._readData.getUint16(); var ofs=this._readData.pos; this._readData.pos=this._STRINGS.offset+this._DATA.offset; for (var i=0;i < this._STRINGS.size;i++){ this._strings[i]=this._readData.readUTFString(); } this._readData.pos=ofs; return true; } __proto.READ_MATERIAL=function(){ var i=0,n=0; var index=this._readData.getUint16(); var shaderName=this._readString(); var url=this._readString(); if (url!=="null") this._materials[index]=Loader.getRes(this._materialMap[url]); else this._materials[index]=new BaseMaterial(); return true; } __proto.READ_MESH=function(){ var name=this._readString(); switch (this._version){ case "LAYAMODEL:01": console.log("Warning: The (.lm) file is converted by old fbxTools,please reConverted it use lastest fbxTools version,later we will remove the support of old version (.lm) support."); break ; case "LAYASKINANI:01": case "LAYAMODEL:02":; var arrayBuffer=this._readData.__getBuffer(); var i=0,n=0; var bindPoseStart=this._readData.getUint32(); var binPoseLength=this._readData.getUint32(); var bindPoseDatas=new Float32Array(arrayBuffer.slice(bindPoseStart+this._DATA.offset,bindPoseStart+this._DATA.offset+binPoseLength)); var inverseGlobalBindPoseStart=this._readData.getUint32(); var inverseGlobalBinPoseLength=this._readData.getUint32(); var invGloBindPoseDatas=new Float32Array(arrayBuffer.slice(inverseGlobalBindPoseStart+this._DATA.offset,inverseGlobalBindPoseStart+this._DATA.offset+inverseGlobalBinPoseLength)); this.mesh._inverseBindPoses=[]; for (i=0,n=invGloBindPoseDatas.length;i < n;i+=16){ var inverseGlobalBindPose=new Matrix4x4(invGloBindPoseDatas[i+0],invGloBindPoseDatas[i+1],invGloBindPoseDatas[i+2],invGloBindPoseDatas[i+3],invGloBindPoseDatas[i+4],invGloBindPoseDatas[i+5],invGloBindPoseDatas[i+6],invGloBindPoseDatas[i+7],invGloBindPoseDatas[i+8],invGloBindPoseDatas[i+9],invGloBindPoseDatas[i+10],invGloBindPoseDatas[i+11],invGloBindPoseDatas[i+12],invGloBindPoseDatas[i+13],invGloBindPoseDatas[i+14],invGloBindPoseDatas[i+15]); this.mesh._inverseBindPoses.push(inverseGlobalBindPose); } break ; default : throw new Error("LoadModel:unknown version."); } return true; } __proto.READ_SUBMESH=function(){ var className=this._readString(); var material=this._readData.getUint8(); var bufferAttribute=this._readString(); this._shaderAttributes=bufferAttribute.match(LoadModelV01._attrReg); var ibofs=this._readData.getUint32(); var ibsize=this._readData.getUint32(); var vbIndicesofs=this._readData.getUint32(); var vbIndicessize=this._readData.getUint32(); var vbofs=this._readData.getUint32(); var vbsize=this._readData.getUint32(); var boneDicofs=this._readData.getUint32(); var boneDicsize=this._readData.getUint32(); var arrayBuffer=this._readData.__getBuffer(); var submesh=new SubMesh(this._mesh); var vertexDeclaration=this._getVertexDeclaration(); var vb=VertexBuffer3D.create(vertexDeclaration,vbsize / vertexDeclaration.vertexStride,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); var vbStart=vbofs+this._DATA.offset; var vbArrayBuffer=arrayBuffer.slice(vbStart,vbStart+vbsize); vb.setData(new Float32Array(vbArrayBuffer)); submesh._vertexBuffer=vb; var vertexElements=vb.vertexDeclaration.getVertexElements(); for (var i=0;i < vertexElements.length;i++) submesh._bufferUsage[(vertexElements [i]).elementUsage]=vb; var ib=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",ibsize / 2,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); var ibStart=ibofs+this._DATA.offset; var ibArrayBuffer=arrayBuffer.slice(ibStart,ibStart+ibsize); ib.setData(new Uint16Array(ibArrayBuffer)); submesh._indexBuffer=ib; var boneDicArrayBuffer=arrayBuffer.slice(boneDicofs+this._DATA.offset,boneDicofs+this._DATA.offset+boneDicsize); submesh._boneIndicesList[0]=new Uint8Array(boneDicArrayBuffer); this._subMeshes.push(submesh); return true; } __proto.READ_DATAAREA=function(){ return false; } __proto._getVertexDeclaration=function(){ var position=false,normal=false,color=false,texcoord0=false,texcoord1=false,tangent=false,blendWeight=false,blendIndex=false; var binormal=false; for (var i=0;i < this._shaderAttributes.length;i+=8){ switch (this._shaderAttributes[i]){ case "POSITION": position=true; break ; case "NORMAL": normal=true; break ; case "COLOR": color=true; break ; case "UV": texcoord0=true; break ; case "UV1": texcoord1=true; break ; case "BLENDWEIGHT": blendWeight=true; break ; case "BLENDINDICES": blendIndex=true; break ; case "TANGENT": tangent=true; break ; case "BINORMAL": binormal=true; break ; } }; var vertexDeclaration; if (position && normal && color && texcoord0 && texcoord1 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorTexture0Texture1SkinTangent.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorTexture0Texture1Skin.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalTexture0Texture1SkinTangent.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalTexture0Texture1Skin.vertexDeclaration; else if (position && normal && color && texcoord0 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorTextureSkinTangent.vertexDeclaration; else if (position && normal && color && texcoord0 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorTextureSkin.vertexDeclaration; else if (position && normal && tangent && binormal && texcoord0 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNTBTextureSkin.vertexDeclaration; else if (position && normal && texcoord0 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalTextureSkinTangent.vertexDeclaration; else if (position && normal && texcoord0 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalTextureSkin.vertexDeclaration; else if (position && normal && color && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorSkinTangent.vertexDeclaration; else if (position && normal && color && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorSkin.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1 && tangent) vertexDeclaration=VertexPositionNormalColorTexture0Texture1Tangent.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1) vertexDeclaration=VertexPositionNormalColorTexture0Texture1.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && tangent) vertexDeclaration=VertexPositionNormalTexture0Texture1Tangent.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1) vertexDeclaration=VertexPositionNormalTexture0Texture1.vertexDeclaration; else if (position && normal && color && texcoord0 && tangent) vertexDeclaration=VertexPositionNormalColorTextureTangent.vertexDeclaration; else if (position && normal && texcoord0 && tangent && binormal) vertexDeclaration=VertexPositionNTBTexture.vertexDeclaration; else if (position && normal && color && texcoord0) vertexDeclaration=VertexPositionNormalColorTexture.vertexDeclaration; else if (position && normal && texcoord0 && tangent) vertexDeclaration=VertexPositionNormalTextureTangent.vertexDeclaration; else if (position && normal && texcoord0) vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; else if (position && normal && color && tangent) vertexDeclaration=VertexPositionNormalColorTangent.vertexDeclaration; else if (position && normal && color) vertexDeclaration=VertexPositionNormalColor.vertexDeclaration; return vertexDeclaration; } __getset(0,__proto,'mesh',function(){ return this._mesh; }); LoadModelV01._attrReg=new RegExp("(\\w+)|([:,;])","g"); return LoadModelV01; })() /** *@private *LoadModel 类用于模型加载。 */ //class laya.d3.loaders.LoadModelV02 var LoadModelV02=(function(){ function LoadModelV02(){} __class(LoadModelV02,'laya.d3.loaders.LoadModelV02'); LoadModelV02.parse=function(readData,version,mesh,materials,subMeshes,materialMap){ LoadModelV02._mesh=mesh; LoadModelV02._materials=materials; LoadModelV02._subMeshes=subMeshes; LoadModelV02._materialMap=materialMap; LoadModelV02._version=version; LoadModelV02._readData=readData; LoadModelV02.READ_DATA(); LoadModelV02.READ_BLOCK(); LoadModelV02.READ_STRINGS(); for (var i=0,n=LoadModelV02._BLOCK.count;i < n;i++){ LoadModelV02._readData.pos=LoadModelV02._BLOCK.blockStarts[i]; var index=LoadModelV02._readData.getUint16(); var blockName=LoadModelV02._strings[index]; var fn=LoadModelV02["READ_"+blockName]; if (fn==null) throw new Error("model file err,no this function:"+index+" "+blockName); else fn.call(); } LoadModelV02._strings.length=0; LoadModelV02._readData=null; LoadModelV02._version=null; LoadModelV02._mesh=null; LoadModelV02._materials=null; LoadModelV02._subMeshes=null; LoadModelV02._materialMap=null; } LoadModelV02._readString=function(){ return LoadModelV02._strings[LoadModelV02._readData.getUint16()]; } LoadModelV02.READ_DATA=function(){ LoadModelV02._DATA.offset=LoadModelV02._readData.getUint32(); LoadModelV02._DATA.size=LoadModelV02._readData.getUint32(); } LoadModelV02.READ_BLOCK=function(){ var count=LoadModelV02._BLOCK.count=LoadModelV02._readData.getUint16(); var blockStarts=LoadModelV02._BLOCK.blockStarts=[]; var blockLengths=LoadModelV02._BLOCK.blockLengths=[]; for (var i=0;i < count;i++){ blockStarts.push(LoadModelV02._readData.getUint32()); blockLengths.push(LoadModelV02._readData.getUint32()); } } LoadModelV02.READ_STRINGS=function(){ var offset=LoadModelV02._readData.getUint32(); var count=LoadModelV02._readData.getUint16(); var prePos=LoadModelV02._readData.pos; LoadModelV02._readData.pos=offset+LoadModelV02._DATA.offset; for (var i=0;i < count;i++) LoadModelV02._strings[i]=LoadModelV02._readData.readUTFString(); LoadModelV02._readData.pos=prePos; } LoadModelV02.READ_MATERIAL=function(){ var i=0,n=0; var clasName=LoadModelV02._readString(); var shaderName=LoadModelV02._readString(); var url=LoadModelV02._readString(); if (url!=="") LoadModelV02._materials.push(Loader.getRes(LoadModelV02._materialMap[url])); return true; } LoadModelV02.READ_MESH=function(){ var name=LoadModelV02._readString(); var arrayBuffer=LoadModelV02._readData.__getBuffer(); var i=0,n=0; var vertexBufferCount=LoadModelV02._readData.getInt16(); var offset=LoadModelV02._DATA.offset; for (i=0;i < vertexBufferCount;i++){ var vbStart=offset+LoadModelV02._readData.getUint32(); var vbLength=LoadModelV02._readData.getUint32(); var vbDatas=new Float32Array(arrayBuffer.slice(vbStart,vbStart+vbLength)); var bufferAttribute=LoadModelV02._readString(); var shaderAttributes=bufferAttribute.match(LoadModelV02._attrReg); var vertexDeclaration=LoadModelV02._getVertexDeclaration(shaderAttributes); var vertexBuffer=VertexBuffer3D.create(vertexDeclaration,(vbDatas.length *4)/ vertexDeclaration.vertexStride,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); vertexBuffer.setData(vbDatas); LoadModelV02._mesh._vertexBuffers.push(vertexBuffer); }; var ibStart=offset+LoadModelV02._readData.getUint32(); var ibLength=LoadModelV02._readData.getUint32(); var ibDatas=new Uint16Array(arrayBuffer.slice(ibStart,ibStart+ibLength)); var indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",ibLength / 2,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); indexBuffer.setData(ibDatas); LoadModelV02._mesh._indexBuffer=indexBuffer; var boneNames=LoadModelV02._mesh._boneNames=[]; var boneCount=LoadModelV02._readData.getUint16(); boneNames.length=boneCount; for (i=0;i < boneCount;i++) boneNames[i]=LoadModelV02._strings[LoadModelV02._readData.getUint16()]; var bindPoseStart=LoadModelV02._readData.getUint32(); var binPoseLength=LoadModelV02._readData.getUint32(); var bindPoseDatas=new Float32Array(arrayBuffer.slice(offset+bindPoseStart,offset+bindPoseStart+binPoseLength)); var inverseGlobalBindPoseStart=LoadModelV02._readData.getUint32(); var inverseGlobalBinPoseLength=LoadModelV02._readData.getUint32(); var invGloBindPoseDatas=new Float32Array(arrayBuffer.slice(offset+inverseGlobalBindPoseStart,offset+inverseGlobalBindPoseStart+inverseGlobalBinPoseLength)); LoadModelV02._mesh._inverseBindPoses=[]; for (i=0,n=invGloBindPoseDatas.length;i < n;i+=16){ var inverseGlobalBindPose=new Matrix4x4(invGloBindPoseDatas[i+0],invGloBindPoseDatas[i+1],invGloBindPoseDatas[i+2],invGloBindPoseDatas[i+3],invGloBindPoseDatas[i+4],invGloBindPoseDatas[i+5],invGloBindPoseDatas[i+6],invGloBindPoseDatas[i+7],invGloBindPoseDatas[i+8],invGloBindPoseDatas[i+9],invGloBindPoseDatas[i+10],invGloBindPoseDatas[i+11],invGloBindPoseDatas[i+12],invGloBindPoseDatas[i+13],invGloBindPoseDatas[i+14],invGloBindPoseDatas[i+15]); LoadModelV02._mesh._inverseBindPoses.push(inverseGlobalBindPose); } LoadModelV02._mesh._skinnedDatas=new Float32Array(invGloBindPoseDatas.length*16); return true; } LoadModelV02.READ_SUBMESH=function(){ var arrayBuffer=LoadModelV02._readData.__getBuffer(); var submesh=new SubMesh(LoadModelV02._mesh); var vbIndex=LoadModelV02._readData.getInt16(); var vbStart=LoadModelV02._readData.getUint32(); var vbLength=LoadModelV02._readData.getUint32(); submesh._vertexBuffer=LoadModelV02._mesh._vertexBuffers[vbIndex]; submesh._vertexStart=vbStart; submesh._vertexCount=vbLength; var ibStart=LoadModelV02._readData.getUint32(); var ibCount=LoadModelV02._readData.getUint32(); var indexBuffer=LoadModelV02._mesh._indexBuffer; submesh._indexBuffer=indexBuffer; submesh._indexStart=ibStart; submesh._indexCount=ibCount; submesh._indices=new Uint16Array(indexBuffer.getData().buffer,ibStart *2,ibCount); var offset=LoadModelV02._DATA.offset; var subIndexBufferStart=submesh._subIndexBufferStart; var subIndexBufferCount=submesh._subIndexBufferCount; var boneIndicesList=submesh._boneIndicesList; var drawCount=LoadModelV02._readData.getUint16(); subIndexBufferStart.length=drawCount; subIndexBufferCount.length=drawCount; boneIndicesList.length=drawCount; for (var i=0;i < drawCount;i++){ subIndexBufferStart[i]=LoadModelV02._readData.getUint32(); subIndexBufferCount[i]=LoadModelV02._readData.getUint32(); var boneDicofs=LoadModelV02._readData.getUint32(); var boneDicsize=LoadModelV02._readData.getUint32(); submesh._boneIndicesList[i]=new Uint8Array(arrayBuffer.slice(offset+boneDicofs,offset+boneDicofs+boneDicsize)); } LoadModelV02._subMeshes.push(submesh); return true; } LoadModelV02._getVertexDeclaration=function(shaderAttributes){ var position=false,normal=false,color=false,texcoord0=false,texcoord1=false,tangent=false,blendWeight=false,blendIndex=false; var binormal=false; for (var i=0;i < shaderAttributes.length;i++){ switch (shaderAttributes[i]){ case "POSITION": position=true; break ; case "NORMAL": normal=true; break ; case "COLOR": color=true; break ; case "UV": texcoord0=true; break ; case "UV1": texcoord1=true; break ; case "BLENDWEIGHT": blendWeight=true; break ; case "BLENDINDICES": blendIndex=true; break ; case "TANGENT": tangent=true; break ; case "BINORMAL": binormal=true; break ; } }; var vertexDeclaration; if (position && normal && color && texcoord0 && texcoord1 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorTexture0Texture1SkinTangent.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorTexture0Texture1Skin.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalTexture0Texture1SkinTangent.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalTexture0Texture1Skin.vertexDeclaration; else if (position && normal && color && texcoord0 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorTextureSkinTangent.vertexDeclaration; else if (position && normal && color && texcoord0 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorTextureSkin.vertexDeclaration; else if (position && normal && texcoord0 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalTextureSkinTangent.vertexDeclaration; else if (position && normal && texcoord0 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalTextureSkin.vertexDeclaration; else if (position && normal && color && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorSkinTangent.vertexDeclaration; else if (position && normal && color && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorSkin.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1 && tangent) vertexDeclaration=VertexPositionNormalColorTexture0Texture1Tangent.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1) vertexDeclaration=VertexPositionNormalColorTexture0Texture1.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && tangent) vertexDeclaration=VertexPositionNormalTexture0Texture1Tangent.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1) vertexDeclaration=VertexPositionNormalTexture0Texture1.vertexDeclaration; else if (position && normal && color && texcoord0 && tangent) vertexDeclaration=VertexPositionNormalColorTextureTangent.vertexDeclaration; else if (position && normal && texcoord0 && tangent && binormal) vertexDeclaration=VertexPositionNTBTexture.vertexDeclaration; else if (position && normal && color && texcoord0) vertexDeclaration=VertexPositionNormalColorTexture.vertexDeclaration; else if (position && normal && texcoord0 && tangent) vertexDeclaration=VertexPositionNormalTextureTangent.vertexDeclaration; else if (position && normal && texcoord0) vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; else if (position && normal && color && tangent) vertexDeclaration=VertexPositionNormalColorTangent.vertexDeclaration; else if (position && normal && color) vertexDeclaration=VertexPositionNormalColor.vertexDeclaration; return vertexDeclaration; } LoadModelV02._attrReg=new RegExp("(\\w+)|([:,;])","g"); LoadModelV02._strings=[]; LoadModelV02._readData=null; LoadModelV02._version=null; LoadModelV02._mesh=null; LoadModelV02._materials=null; LoadModelV02._subMeshes=null; LoadModelV02._materialMap=null; __static(LoadModelV02, ['_BLOCK',function(){return this._BLOCK={count:0};},'_DATA',function(){return this._DATA={offset:0,size:0};} ]); return LoadModelV02; })() /** *@private *LoadModel 类用于模型加载。 */ //class laya.d3.loaders.LoadModelV03 var LoadModelV03=(function(){ function LoadModelV03(){} __class(LoadModelV03,'laya.d3.loaders.LoadModelV03'); LoadModelV03.parse=function(readData,version,mesh,subMeshes,materialMap){ LoadModelV03._mesh=mesh; LoadModelV03._subMeshes=subMeshes; LoadModelV03._materialMap=materialMap; LoadModelV03._version=version; LoadModelV03._readData=readData; LoadModelV03.READ_DATA(); LoadModelV03.READ_BLOCK(); LoadModelV03.READ_STRINGS(); for (var i=0,n=LoadModelV03._BLOCK.count;i < n;i++){ LoadModelV03._readData.pos=LoadModelV03._BLOCK.blockStarts[i]; var index=LoadModelV03._readData.getUint16(); var blockName=LoadModelV03._strings[index]; var fn=LoadModelV03["READ_"+blockName]; if (fn==null) throw new Error("model file err,no this function:"+index+" "+blockName); else fn.call(); } LoadModelV03._strings.length=0; LoadModelV03._readData=null; LoadModelV03._version=null; LoadModelV03._mesh=null; LoadModelV03._subMeshes=null; LoadModelV03._materialMap=null; } LoadModelV03._readString=function(){ return LoadModelV03._strings[LoadModelV03._readData.getUint16()]; } LoadModelV03.READ_DATA=function(){ LoadModelV03._DATA.offset=LoadModelV03._readData.getUint32(); LoadModelV03._DATA.size=LoadModelV03._readData.getUint32(); } LoadModelV03.READ_BLOCK=function(){ var count=LoadModelV03._BLOCK.count=LoadModelV03._readData.getUint16(); var blockStarts=LoadModelV03._BLOCK.blockStarts=[]; var blockLengths=LoadModelV03._BLOCK.blockLengths=[]; for (var i=0;i < count;i++){ blockStarts.push(LoadModelV03._readData.getUint32()); blockLengths.push(LoadModelV03._readData.getUint32()); } } LoadModelV03.READ_STRINGS=function(){ var offset=LoadModelV03._readData.getUint32(); var count=LoadModelV03._readData.getUint16(); var prePos=LoadModelV03._readData.pos; LoadModelV03._readData.pos=offset+LoadModelV03._DATA.offset; for (var i=0;i < count;i++) LoadModelV03._strings[i]=LoadModelV03._readData.readUTFString(); LoadModelV03._readData.pos=prePos; } LoadModelV03.READ_MESH=function(){ var name=LoadModelV03._readString(); var arrayBuffer=LoadModelV03._readData.__getBuffer(); var i=0,n=0; var vertexBufferCount=LoadModelV03._readData.getInt16(); var offset=LoadModelV03._DATA.offset; for (i=0;i < vertexBufferCount;i++){ var vbStart=offset+LoadModelV03._readData.getUint32(); var vbLength=LoadModelV03._readData.getUint32(); var vbDatas=new Float32Array(arrayBuffer.slice(vbStart,vbStart+vbLength)); var bufferAttribute=LoadModelV03._readString(); var vertexDeclaration; switch(LoadModelV03._version){ case "LAYAMODEL:03": vertexDeclaration=LoadModelV03._vertexDeclarationMap_Discard[bufferAttribute]; break ; case "LAYAMODEL:0301": vertexDeclaration=LoadModelV03._vertexDeclarationMap[bufferAttribute]; break ; default : throw new Error("LoadModelV03: unknown version."); } if (!vertexDeclaration) throw new Error("LoadModelV03: unknown vertexDeclaration."); var vertexBuffer=VertexBuffer3D.create(vertexDeclaration,(vbDatas.length *4)/ vertexDeclaration.vertexStride,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); vertexBuffer.setData(vbDatas); LoadModelV03._mesh._vertexBuffers.push(vertexBuffer); }; var ibStart=offset+LoadModelV03._readData.getUint32(); var ibLength=LoadModelV03._readData.getUint32(); var ibDatas=new Uint16Array(arrayBuffer.slice(ibStart,ibStart+ibLength)); var indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",ibLength / 2,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); indexBuffer.setData(ibDatas); LoadModelV03._mesh._indexBuffer=indexBuffer; var boneNames=LoadModelV03._mesh._boneNames=[]; var boneCount=LoadModelV03._readData.getUint16(); boneNames.length=boneCount; for (i=0;i < boneCount;i++) boneNames[i]=LoadModelV03._strings[LoadModelV03._readData.getUint16()]; LoadModelV03._readData.pos+=8; var inverseGlobalBindPoseStart=LoadModelV03._readData.getUint32(); var inverseGlobalBinPoseLength=LoadModelV03._readData.getUint32(); var invGloBindPoseDatas=new Float32Array(arrayBuffer.slice(offset+inverseGlobalBindPoseStart,offset+inverseGlobalBindPoseStart+inverseGlobalBinPoseLength)); LoadModelV03._mesh._inverseBindPoses=[]; for (i=0,n=invGloBindPoseDatas.length;i < n;i+=16){ var inverseGlobalBindPose=new Matrix4x4(invGloBindPoseDatas[i+0],invGloBindPoseDatas[i+1],invGloBindPoseDatas[i+2],invGloBindPoseDatas[i+3],invGloBindPoseDatas[i+4],invGloBindPoseDatas[i+5],invGloBindPoseDatas[i+6],invGloBindPoseDatas[i+7],invGloBindPoseDatas[i+8],invGloBindPoseDatas[i+9],invGloBindPoseDatas[i+10],invGloBindPoseDatas[i+11],invGloBindPoseDatas[i+12],invGloBindPoseDatas[i+13],invGloBindPoseDatas[i+14],invGloBindPoseDatas[i+15]); LoadModelV03._mesh._inverseBindPoses.push(inverseGlobalBindPose); } LoadModelV03._mesh._skinnedDatas=new Float32Array(invGloBindPoseDatas.length*16); return true; } LoadModelV03.READ_SUBMESH=function(){ var arrayBuffer=LoadModelV03._readData.__getBuffer(); var submesh=new SubMesh(LoadModelV03._mesh); var vbIndex=LoadModelV03._readData.getInt16(); var vbStart=LoadModelV03._readData.getUint32(); var vbLength=LoadModelV03._readData.getUint32(); submesh._vertexBuffer=LoadModelV03._mesh._vertexBuffers[vbIndex]; submesh._vertexStart=vbStart; submesh._vertexCount=vbLength; var ibStart=LoadModelV03._readData.getUint32(); var ibCount=LoadModelV03._readData.getUint32(); var indexBuffer=LoadModelV03._mesh._indexBuffer; submesh._indexBuffer=indexBuffer; submesh._indexStart=ibStart; submesh._indexCount=ibCount; submesh._indices=new Uint16Array(indexBuffer.getData().buffer,ibStart *2,ibCount); var offset=LoadModelV03._DATA.offset; var subIndexBufferStart=submesh._subIndexBufferStart; var subIndexBufferCount=submesh._subIndexBufferCount; var boneIndicesList=submesh._boneIndicesList; var drawCount=LoadModelV03._readData.getUint16(); subIndexBufferStart.length=drawCount; subIndexBufferCount.length=drawCount; boneIndicesList.length=drawCount; for (var i=0;i < drawCount;i++){ subIndexBufferStart[i]=LoadModelV03._readData.getUint32(); subIndexBufferCount[i]=LoadModelV03._readData.getUint32(); var boneDicofs=LoadModelV03._readData.getUint32(); var boneDicsize=LoadModelV03._readData.getUint32(); boneIndicesList[i]=new Uint8Array(arrayBuffer.slice(offset+boneDicofs,offset+boneDicofs+boneDicsize)); } LoadModelV03._subMeshes.push(submesh); return true; } LoadModelV03._strings=[]; LoadModelV03._readData=null; LoadModelV03._version=null; LoadModelV03._mesh=null; LoadModelV03._subMeshes=null; LoadModelV03._materialMap=null; __static(LoadModelV03, ['_vertexDeclarationMap_Discard',function(){return this._vertexDeclarationMap_Discard={ "POSITION,NORMAL,COLOR,UV,UV1,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorTexture0Texture1SkinTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,TANGENT,BINORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES,":VertexPositionNTBTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalTexture0Texture1SkinTangent.vertexDeclaration, "POSITION,NORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorTextureSkinTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorTextureSkin.vertexDeclaration, "POSITION,NORMAL,UV,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalTextureSkinTangent.vertexDeclaration, "POSITION,NORMAL,UV,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalTextureSkin.vertexDeclaration, "POSITION,NORMAL,COLOR,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorSkinTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorSkin.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1,TANGENT":VertexPositionNormalColorTexture0Texture1Tangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1":VertexPositionNormalColorTexture0Texture1.vertexDeclaration, "POSITION,NORMAL,UV,UV1,TANGENT":VertexPositionNormalTexture0Texture1Tangent.vertexDeclaration, "POSITION,NORMAL,UV,UV1":VertexPositionNormalTexture0Texture1.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,TANGENT":VertexPositionNormalColorTextureTangent.vertexDeclaration, "POSITION,NORMAL,UV,TANGENT,BINORMAL":VertexPositionNTBTexture.vertexDeclaration, "POSITION,NORMAL,COLOR,UV":VertexPositionNormalColorTexture.vertexDeclaration, "POSITION,NORMAL,UV,TANGENT":VertexPositionNormalTextureTangent.vertexDeclaration, "POSITION,NORMAL,UV":VertexPositionNormalTexture.vertexDeclaration, "POSITION,NORMAL,COLOR,TANGENT":VertexPositionNormalColorTangent.vertexDeclaration, "POSITION,NORMAL,COLOR":VertexPositionNormalColor.vertexDeclaration, "POSITION,NORMAL,TANGENT":VertexPositionNormalTangent.vertexDeclaration, "POSITION,NORMAL":VertexPositionNormal.vertexDeclaration, "POSITION,UV":VertexPositionTexture0.vertexDeclaration, "POSITION":VertexPosition.vertexDeclaration};},'_vertexDeclarationMap',function(){return this._vertexDeclarationMap={ "POSITION,NORMAL,COLOR,UV,UV1,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorTexture0Texture1SkinSTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,TANGENT,BINORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES,":VertexPositionNTBTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalTexture0Texture1SkinSTangent.vertexDeclaration, "POSITION,NORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorTextureSkinSTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorTextureSkin.vertexDeclaration, "POSITION,NORMAL,UV,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalTextureSkinSTangent.vertexDeclaration, "POSITION,NORMAL,UV,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalTextureSkin.vertexDeclaration, "POSITION,NORMAL,COLOR,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorSkinSTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorSkin.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1,TANGENT":VertexPositionNormalColorTexture0Texture1STangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1":VertexPositionNormalColorTexture0Texture1.vertexDeclaration, "POSITION,NORMAL,UV,UV1,TANGENT":VertexPositionNormalTexture0Texture1STangent.vertexDeclaration, "POSITION,NORMAL,UV,UV1":VertexPositionNormalTexture0Texture1.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,TANGENT":VertexPositionNormalColorTextureSTangent.vertexDeclaration, "POSITION,NORMAL,UV,TANGENT,BINORMAL":VertexPositionNTBTexture.vertexDeclaration, "POSITION,NORMAL,COLOR,UV":VertexPositionNormalColorTexture.vertexDeclaration, "POSITION,NORMAL,UV,TANGENT":VertexPositionNormalTextureSTangent.vertexDeclaration, "POSITION,NORMAL,UV":VertexPositionNormalTexture.vertexDeclaration, "POSITION,NORMAL,COLOR,TANGENT":VertexPositionNormalColorSTangent.vertexDeclaration, "POSITION,NORMAL,COLOR":VertexPositionNormalColor.vertexDeclaration, "POSITION,NORMAL,TANGENT":VertexPositionNormalSTangent.vertexDeclaration, "POSITION,NORMAL":VertexPositionNormal.vertexDeclaration, "POSITION,UV":VertexPositionTexture0.vertexDeclaration, "POSITION":VertexPosition.vertexDeclaration};},'_BLOCK',function(){return this._BLOCK={count:0};},'_DATA',function(){return this._DATA={offset:0,size:0};} ]); return LoadModelV03; })() /** *... *@author ... */ //class laya.d3.loaders.MeshReader var MeshReader=(function(){ function MeshReader(){} __class(MeshReader,'laya.d3.loaders.MeshReader'); MeshReader.read=function(data,mesh,materials,subMeshes,materialMap){ var readData=new Byte(data); readData.pos=0; var version=readData.readUTFString(); switch (version){ case "LAYAMODEL:01": case "LAYASKINANI:01": MeshReader._readVersion01(readData,version,mesh,materials,subMeshes,materialMap); break ; case "LAYAMODEL:02": LoadModelV02.parse(readData,version,mesh,materials,subMeshes,materialMap); break ; case "LAYAMODEL:03": case "LAYAMODEL:0301": LoadModelV03.parse(readData,version,mesh,subMeshes,materialMap); break ; default : throw new Error("MeshReader: unknown mesh version."); } mesh._setSubMeshes(subMeshes); } MeshReader._readVersion01=function(readData,version,mesh,materials,subMeshes,materialMap){ new LoadModelV01(readData,version,mesh,materials,subMeshes,materialMap); } return MeshReader; })() /** *BoundBox 类用于创建包围盒。 */ //class laya.d3.math.BoundBox var BoundBox=(function(){ function BoundBox(min,max){ /**最小顶点。*/ this.min=null; /**最大顶点。*/ this.max=null; this.min=min; this.max=max; } __class(BoundBox,'laya.d3.math.BoundBox'); var __proto=BoundBox.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *获取包围盒的8个角顶点。 *@param corners 返回顶点的输出队列。 */ __proto.getCorners=function(corners){ corners.length=8; var mine=this.min.elements; var maxe=this.max.elements; var minX=mine[0]; var minY=mine[1]; var minZ=mine[2]; var maxX=maxe[0]; var maxY=maxe[1]; var maxZ=maxe[2]; corners[0]=new Vector3(minX,maxY,maxZ); corners[1]=new Vector3(maxX,maxY,maxZ); corners[2]=new Vector3(maxX,minY,maxZ); corners[3]=new Vector3(minX,minY,maxZ); corners[4]=new Vector3(minX,maxY,minZ); corners[5]=new Vector3(maxX,maxY,minZ); corners[6]=new Vector3(maxX,minY,minZ); corners[7]=new Vector3(minX,minY,minZ); } __proto.toDefault=function(){ this.min.toDefault(); this.max.toDefault(); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var dest=destObject; this.min.cloneTo(dest.min); this.max.cloneTo(dest.max); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(new Vector3(),new Vector3()); this.cloneTo(dest); return dest; } BoundBox.createfromPoints=function(points,out){ if (points==null) throw new Error("points"); var min=out.min; var max=out.max; var minE=min.elements; minE[0]=Number.MAX_VALUE; minE[1]=Number.MAX_VALUE; minE[2]=Number.MAX_VALUE; var maxE=max.elements; maxE[0]=-Number.MAX_VALUE; maxE[1]=-Number.MAX_VALUE; maxE[2]=-Number.MAX_VALUE; for (var i=0,n=points.length;i < n;++i){ Vector3.min(min,points[i],min); Vector3.max(max,points[i],max); } } BoundBox.merge=function(box1,box2,out){ Vector3.min(box1.min,box2.min,out.min); Vector3.max(box1.max,box2.max,out.max); } return BoundBox; })() /** *BoundFrustum 类用于创建锥截体。 */ //class laya.d3.math.BoundFrustum var BoundFrustum=(function(){ function BoundFrustum(matrix){ /**4x4矩阵*/ this._matrix=null; /**近平面*/ this._near=null; /**远平面*/ this._far=null; /**左平面*/ this._left=null; /**右平面*/ this._right=null; /**顶平面*/ this._top=null; /**底平面*/ this._bottom=null; this._matrix=matrix; this._near=new Plane(new Vector3()); this._far=new Plane(new Vector3()); this._left=new Plane(new Vector3()); this._right=new Plane(new Vector3()); this._top=new Plane(new Vector3()); this._bottom=new Plane(new Vector3()); BoundFrustum._getPlanesFromMatrix(this._matrix,this._near,this._far,this._left,this._right,this._top,this._bottom); } __class(BoundFrustum,'laya.d3.math.BoundFrustum'); var __proto=BoundFrustum.prototype; /** *判断是否与其他锥截体相等。 *@param other 锥截体。 */ __proto.equalsBoundFrustum=function(other){ return this._matrix.equalsOtherMatrix(other.matrix) } /** *判断是否与其他对象相等。 *@param obj 对象。 */ __proto.equalsObj=function(obj){ if ((obj instanceof laya.d3.math.BoundFrustum )){ var bf=obj; return this.equalsBoundFrustum(bf); } return false; } /** *获取锥截体的任意一平面。 *0:近平面 *1:远平面 *2:左平面 *3:右平面 *4:顶平面 *5:底平面 *@param index 索引。 */ __proto.getPlane=function(index){ switch (index){ case 0: return this._near; case 1: return this._far; case 2: return this._left; case 3: return this._right; case 4: return this._top; case 5: return this._bottom; default : return null; } } /** *锥截体的8个顶点。 *@param corners 返回顶点的输出队列。 */ __proto.getCorners=function(corners){ BoundFrustum._get3PlaneInterPoint(this._near,this._bottom,this._right).cloneTo(corners[0]); BoundFrustum._get3PlaneInterPoint(this._near,this._top,this._right).cloneTo(corners[1]); BoundFrustum._get3PlaneInterPoint(this._near,this._top,this._left).cloneTo(corners[2]); BoundFrustum._get3PlaneInterPoint(this._near,this._bottom,this._left).cloneTo(corners[3]); BoundFrustum._get3PlaneInterPoint(this._far,this._bottom,this._right).cloneTo(corners[4]); BoundFrustum._get3PlaneInterPoint(this._far,this._top,this._right).cloneTo(corners[5]); BoundFrustum._get3PlaneInterPoint(this._far,this._top,this._left).cloneTo(corners[6]); BoundFrustum._get3PlaneInterPoint(this._far,this._bottom,this._left).cloneTo(corners[7]); } /** *与点的位置关系。返回-1,包涵;0,相交;1,不相交 *@param point 点。 */ __proto.containsPoint=function(point){ var result=Plane.PlaneIntersectionType_Front; var planeResult=Plane.PlaneIntersectionType_Front; for (var i=0;i < 6;i++){ switch (i){ case 0: planeResult=Collision.intersectsPlaneAndPoint(this._near,point); break ; case 1: planeResult=Collision.intersectsPlaneAndPoint(this._far,point); break ; case 2: planeResult=Collision.intersectsPlaneAndPoint(this._left,point); break ; case 3: planeResult=Collision.intersectsPlaneAndPoint(this._right,point); break ; case 4: planeResult=Collision.intersectsPlaneAndPoint(this._top,point); break ; case 5: planeResult=Collision.intersectsPlaneAndPoint(this._bottom,point); break ; } switch (planeResult){ case Plane.PlaneIntersectionType_Back: return /*laya.d3.math.ContainmentType.Disjoint*/0; case Plane.PlaneIntersectionType_Intersecting: result=Plane.PlaneIntersectionType_Intersecting; break ; } } switch (result){ case Plane.PlaneIntersectionType_Intersecting: return /*laya.d3.math.ContainmentType.Intersects*/2; default : return /*laya.d3.math.ContainmentType.Contains*/1; } } /** *与包围盒的位置关系。返回-1,包涵;0,相交;1,不相交 *@param box 包围盒。 */ __proto.containsBoundBox=function(box){ var p=BoundFrustum._tempV30,n=BoundFrustum._tempV31; var plane; var result=/*laya.d3.math.ContainmentType.Contains*/1; for (var i=0;i < 6;i++){ plane=this.getPlane(i); this._getBoxToPlanePVertexNVertex(box,plane.normal,p,n); if (Collision.intersectsPlaneAndPoint(plane,p)===Plane.PlaneIntersectionType_Back) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Collision.intersectsPlaneAndPoint(plane,n)===Plane.PlaneIntersectionType_Back) result=/*laya.d3.math.ContainmentType.Intersects*/2; } return result; } /** *与包围球的位置关系。返回-1,包涵;0,相交;1,不相交 *@param sphere 包围球。 */ __proto.containsBoundSphere=function(sphere){ var result=Plane.PlaneIntersectionType_Front; var planeResult=Plane.PlaneIntersectionType_Front; for (var i=0;i < 6;i++){ switch (i){ case 0: planeResult=Collision.intersectsPlaneAndSphere(this._near,sphere); break ; case 1: planeResult=Collision.intersectsPlaneAndSphere(this._far,sphere); break ; case 2: planeResult=Collision.intersectsPlaneAndSphere(this._left,sphere); break ; case 3: planeResult=Collision.intersectsPlaneAndSphere(this._right,sphere); break ; case 4: planeResult=Collision.intersectsPlaneAndSphere(this._top,sphere); break ; case 5: planeResult=Collision.intersectsPlaneAndSphere(this._bottom,sphere); break ; } switch (planeResult){ case Plane.PlaneIntersectionType_Back: return /*laya.d3.math.ContainmentType.Disjoint*/0; case Plane.PlaneIntersectionType_Intersecting: result=Plane.PlaneIntersectionType_Intersecting; break ; } } switch (result){ case Plane.PlaneIntersectionType_Intersecting: return /*laya.d3.math.ContainmentType.Intersects*/2; default : return /*laya.d3.math.ContainmentType.Contains*/1; } } /** *@private */ __proto._getBoxToPlanePVertexNVertex=function(box,planeNormal,outP,outN){ var boxMin=box.min; var boxMinE=boxMin.elements; var boxMax=box.max; var boxMaxE=boxMax.elements; var planeNorE=planeNormal.elements; var planeNorEX=planeNorE[0]; var planeNorEY=planeNorE[1]; var planeNorEZ=planeNorE[2]; boxMin.cloneTo(outP);; var outPE=outP.elements; if (planeNorEX >=0) outPE[0]=boxMaxE[0]; if (planeNorEY >=0) outPE[1]=boxMaxE[1]; if (planeNorEZ >=0) outPE[2]=boxMaxE[2]; boxMax.cloneTo(outN); var outNE=outN.elements; if (planeNorEX >=0) outNE[0]=boxMinE[0]; if (planeNorEY >=0) outNE[1]=boxMinE[1]; if (planeNorEZ >=0) outNE[2]=boxMinE[2]; } /** *获取顶平面。 *@return 顶平面。 */ __getset(0,__proto,'top',function(){ return this._top; }); /** *设置描述矩阵。 *@param matrix 描述矩阵。 */ /** *获取描述矩阵。 *@return 描述矩阵。 */ __getset(0,__proto,'matrix',function(){ return this._matrix; },function(matrix){ this._matrix=matrix; BoundFrustum._getPlanesFromMatrix(this._matrix,this._near,this._far,this._left,this._right,this._top,this._bottom); }); /** *获取近平面。 *@return 近平面。 */ __getset(0,__proto,'near',function(){ return this._near; }); /** *获取远平面。 *@return 远平面。 */ __getset(0,__proto,'far',function(){ return this._far; }); /** *获取左平面。 *@return 左平面。 */ __getset(0,__proto,'left',function(){ return this._left; }); /** *获取右平面。 *@return 右平面。 */ __getset(0,__proto,'right',function(){ return this._right; }); /** *获取底平面。 *@return 底平面。 */ __getset(0,__proto,'bottom',function(){ return this._bottom; }); BoundFrustum._getPlanesFromMatrix=function(m,np,fp,lp,rp,tp,bp){ var matrixE=m.elements; var m11=matrixE[0]; var m12=matrixE[1]; var m13=matrixE[2]; var m14=matrixE[3]; var m21=matrixE[4]; var m22=matrixE[5]; var m23=matrixE[6]; var m24=matrixE[7]; var m31=matrixE[8]; var m32=matrixE[9]; var m33=matrixE[10]; var m34=matrixE[11]; var m41=matrixE[12]; var m42=matrixE[13]; var m43=matrixE[14]; var m44=matrixE[15]; var nearNorE=np.normal.elements; nearNorE[0]=m14+m13; nearNorE[1]=m24+m23; nearNorE[2]=m34+m33; np.distance=m44+m43; np.normalize(); var farNorE=fp.normal.elements; farNorE[0]=m14-m13; farNorE[1]=m24-m23; farNorE[2]=m34-m33; fp.distance=m44-m43; fp.normalize(); var leftNorE=lp.normal.elements; leftNorE[0]=m14+m11; leftNorE[1]=m24+m21; leftNorE[2]=m34+m31; lp.distance=m44+m41; lp.normalize(); var rightNorE=rp.normal.elements; rightNorE[0]=m14-m11; rightNorE[1]=m24-m21; rightNorE[2]=m34-m31; rp.distance=m44-m41; rp.normalize(); var topNorE=tp.normal.elements; topNorE[0]=m14-m12; topNorE[1]=m24-m22; topNorE[2]=m34-m32; tp.distance=m44-m42; tp.normalize(); var bottomNorE=bp.normal.elements; bottomNorE[0]=m14+m12; bottomNorE[1]=m24+m22; bottomNorE[2]=m34+m32; bp.distance=m44+m42; bp.normalize(); } BoundFrustum._get3PlaneInterPoint=function(p1,p2,p3){ var p1Nor=p1.normal; var p2Nor=p2.normal; var p3Nor=p3.normal; Vector3.cross(p2Nor,p3Nor,BoundFrustum._tempV30); Vector3.cross(p3Nor,p1Nor,BoundFrustum._tempV31); Vector3.cross(p1Nor,p2Nor,BoundFrustum._tempV32); var a=Vector3.dot(p1Nor,BoundFrustum._tempV30); var b=Vector3.dot(p2Nor,BoundFrustum._tempV31); var c=Vector3.dot(p3Nor,BoundFrustum._tempV32); Vector3.scale(BoundFrustum._tempV30,-p1.distance / a,BoundFrustum._tempV33); Vector3.scale(BoundFrustum._tempV31,-p2.distance / b,BoundFrustum._tempV34); Vector3.scale(BoundFrustum._tempV32,-p3.distance / c,BoundFrustum._tempV35); Vector3.add(BoundFrustum._tempV33,BoundFrustum._tempV34,BoundFrustum._tempV36); Vector3.add(BoundFrustum._tempV35,BoundFrustum._tempV36,BoundFrustum._tempV37); var v=BoundFrustum._tempV37; return v; } __static(BoundFrustum, ['_tempV30',function(){return this._tempV30=new Vector3();},'_tempV31',function(){return this._tempV31=new Vector3();},'_tempV32',function(){return this._tempV32=new Vector3();},'_tempV33',function(){return this._tempV33=new Vector3();},'_tempV34',function(){return this._tempV34=new Vector3();},'_tempV35',function(){return this._tempV35=new Vector3();},'_tempV36',function(){return this._tempV36=new Vector3();},'_tempV37',function(){return this._tempV37=new Vector3();} ]); return BoundFrustum; })() /** *BoundSphere 类用于创建包围球。 */ //class laya.d3.math.BoundSphere var BoundSphere=(function(){ function BoundSphere(center,radius){ /**包围球的中心。*/ this.center=null; /**包围球的半径。*/ this.radius=NaN; this.center=center; this.radius=radius; } __class(BoundSphere,'laya.d3.math.BoundSphere'); var __proto=BoundSphere.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) __proto.toDefault=function(){ this.center.toDefault(); this.radius=0; } /** *判断射线是否与碰撞球交叉,并返回交叉距离。 *@param ray 射线。 *@return 距离交叉点的距离,-1表示不交叉。 */ __proto.intersectsRayDistance=function(ray){ return Collision.intersectsRayAndSphereRD(ray,this); } /** *判断射线是否与碰撞球交叉,并返回交叉点。 *@param ray 射线。 *@param outPoint 交叉点。 *@return 距离交叉点的距离,-1表示不交叉。 */ __proto.intersectsRayPoint=function(ray,outPoint){ return Collision.intersectsRayAndSphereRP(ray,this,outPoint); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var dest=destObject; this.center.cloneTo(dest.center); dest.radius=this.radius; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(new Vector3(),new Vector3()); this.cloneTo(dest); return dest; } BoundSphere.createFromSubPoints=function(points,start,count,out){ if (points==null){ throw new Error("points"); } if (start < 0 || start >=points.length){ throw new Error("start"+start+"Must be in the range [0, "+(points.length-1)+"]"); } if (count < 0 || (start+count)> points.length){ throw new Error("count"+count+"Must be in the range <= "+points.length+"}"); }; var upperEnd=start+count; var center=BoundSphere._tempVector3; center.elements[0]=0; center.elements[1]=0; center.elements[2]=0; for (var i=start;i < upperEnd;++i){ Vector3.add(points[i],center,center); }; var outCenter=out.center; Vector3.scale(center,1 / count,outCenter); var radius=0.0; for (i=start;i < upperEnd;++i){ var distance=Vector3.distanceSquared(outCenter,points[i]); if (distance > radius) radius=distance; } out.radius=Math.sqrt(radius); } BoundSphere.createfromPoints=function(points,out){ if (points==null){ throw new Error("points"); } BoundSphere.createFromSubPoints(points,0,points.length,out); } __static(BoundSphere, ['_tempVector3',function(){return this._tempVector3=new Vector3();} ]); return BoundSphere; })() /** *Collision 类用于检测碰撞。 */ //class laya.d3.math.Collision var Collision=(function(){ /** *创建一个 Collision 实例。 */ function Collision(){} __class(Collision,'laya.d3.math.Collision'); Collision.distancePlaneToPoint=function(plane,point){ var dot=Vector3.dot(plane.normal,point); return dot-plane.distance; } Collision.distanceBoxToPoint=function(box,point){ var boxMine=box.min.elements; var boxMineX=boxMine[0]; var boxMineY=boxMine[1]; var boxMineZ=boxMine[2]; var boxMaxe=box.max.elements; var boxMaxeX=boxMaxe[0]; var boxMaxeY=boxMaxe[1]; var boxMaxeZ=boxMaxe[2]; var pointe=point.elements; var pointeX=pointe[0]; var pointeY=pointe[1]; var pointeZ=pointe[2]; var distance=0; if (pointeX < boxMineX) distance+=(boxMineX-pointeX)*(boxMineX-pointeX); if (pointeX > boxMaxeX) distance+=(boxMaxeX-pointeX)*(boxMaxeX-pointeX); if (pointeY < boxMineY) distance+=(boxMineY-pointeY)*(boxMineY-pointeY); if (pointeY > boxMaxeY) distance+=(boxMaxeY-pointeY)*(boxMaxeY-pointeY); if (pointeZ < boxMineZ) distance+=(boxMineZ-pointeZ)*(boxMineZ-pointeZ); if (pointeZ > boxMaxeZ) distance+=(boxMaxeZ-pointeZ)*(boxMaxeZ-pointeZ); return Math.sqrt(distance); } Collision.distanceBoxToBox=function(box1,box2){ var box1Mine=box1.min.elements; var box1MineX=box1Mine[0]; var box1MineY=box1Mine[1]; var box1MineZ=box1Mine[2]; var box1Maxe=box1.max.elements; var box1MaxeX=box1Maxe[0]; var box1MaxeY=box1Maxe[1]; var box1MaxeZ=box1Maxe[2]; var box2Mine=box2.min.elements; var box2MineX=box2Mine[0]; var box2MineY=box2Mine[1]; var box2MineZ=box2Mine[2]; var box2Maxe=box2.max.elements; var box2MaxeX=box2Maxe[0]; var box2MaxeY=box2Maxe[1]; var box2MaxeZ=box2Maxe[2]; var distance=0; var delta=NaN; if (box1MineX > box2MaxeX){ delta=box1MineX-box2MaxeX; distance+=delta *delta; }else if (box2MineX > box1MaxeX){ delta=box2MineX-box1MaxeX; distance+=delta *delta; } if (box1MineY > box2MaxeY){ delta=box1MineY-box2MaxeY; distance+=delta *delta; }else if (box2MineY > box1MaxeY){ delta=box2MineY-box1MaxeY; distance+=delta *delta; } if (box1MineZ > box2MaxeZ){ delta=box1MineZ-box2MaxeZ; distance+=delta *delta; }else if (box2MineZ > box1MaxeZ){ delta=box2MineZ-box1MaxeZ; distance+=delta *delta; } return Math.sqrt(distance); } Collision.distanceSphereToPoint=function(sphere,point){ var distance=Math.sqrt(Vector3.distanceSquared(sphere.center,point)); distance-=sphere.radius; return Math.max(distance,0); } Collision.distanceSphereToSphere=function(sphere1,sphere2){ var distance=Math.sqrt(Vector3.distanceSquared(sphere1.center,sphere2.center)); distance-=sphere1.radius+sphere2.radius; return Math.max(distance,0); } Collision.intersectsRayAndTriangleRD=function(ray,vertex1,vertex2,vertex3,out){ var rayO=ray.origin; var rayOe=rayO.elements; var rayOeX=rayOe[0]; var rayOeY=rayOe[1]; var rayOeZ=rayOe[2]; var rayD=ray.direction; var rayDe=rayD.elements; var rayDeX=rayDe[0]; var rayDeY=rayDe[1]; var rayDeZ=rayDe[2]; var v1e=vertex1.elements; var v1eX=v1e[0]; var v1eY=v1e[1]; var v1eZ=v1e[2]; var v2e=vertex2.elements; var v2eX=v2e[0]; var v2eY=v2e[1]; var v2eZ=v2e[2]; var v3e=vertex3.elements; var v3eX=v3e[0]; var v3eY=v3e[1]; var v3eZ=v3e[2]; var _tempV30e=Collision._tempV30.elements; var _tempV30eX=_tempV30e[0]; var _tempV30eY=_tempV30e[1]; var _tempV30eZ=_tempV30e[2]; _tempV30eX=v2eX-v1eX; _tempV30eY=v2eY-v1eY; _tempV30eZ=v2eZ-v1eZ; var _tempV31e=Collision._tempV31.elements; var _tempV31eX=_tempV31e[0]; var _tempV31eY=_tempV31e[1]; var _tempV31eZ=_tempV31e[2]; _tempV31eX=v3eX-v1eX; _tempV31eY=v3eY-v1eY; _tempV31eZ=v3eZ-v1eZ; var _tempV32e=Collision._tempV32.elements; var _tempV32eX=_tempV32e[0]; var _tempV32eY=_tempV32e[1]; var _tempV32eZ=_tempV32e[2]; _tempV32eX=(rayDeY *_tempV31eZ)-(rayDeZ *_tempV31eY); _tempV32eY=(rayDeZ *_tempV31eX)-(rayDeX *_tempV31eZ); _tempV32eZ=(rayDeX *_tempV31eY)-(rayDeY *_tempV31eX); var determinant=(_tempV30eX *_tempV32eX)+(_tempV30eY *_tempV32eY)+(_tempV30eZ *_tempV32eZ); if (MathUtils3D.isZero(determinant)){ out=0; return false; }; var inversedeterminant=1 / determinant; var _tempV33e=Collision._tempV33.elements; var _tempV33eX=_tempV33e[0]; var _tempV33eY=_tempV33e[1]; var _tempV33eZ=_tempV33e[2]; _tempV33eX=rayOeX-v1eX; _tempV33eY=rayOeY-v1eY; _tempV33eZ=rayOeZ-v1eZ; var triangleU=(_tempV33eX *_tempV32eX)+(_tempV33eY *_tempV32eY)+(_tempV33eZ *_tempV32eZ); triangleU *=inversedeterminant; if (triangleU < 0 || triangleU > 1){ out=0; return false; }; var _tempV34e=Collision._tempV34.elements; var _tempV34eX=_tempV34e[0]; var _tempV34eY=_tempV34e[1]; var _tempV34eZ=_tempV34e[2]; _tempV34eX=(_tempV33eY *_tempV30eZ)-(_tempV33eZ *_tempV30eY); _tempV34eY=(_tempV33eZ *_tempV30eX)-(_tempV33eX *_tempV30eZ); _tempV34eZ=(_tempV33eX *_tempV30eY)-(_tempV33eY *_tempV30eX); var triangleV=((rayDeX *_tempV34eX)+(rayDeY *_tempV34eY))+(rayDeZ *_tempV34eZ); triangleV *=inversedeterminant; if (triangleV < 0 || triangleU+triangleV > 1){ out=0; return false; }; var raydistance=(_tempV31eX *_tempV34eX)+(_tempV31eY *_tempV34eY)+(_tempV31eZ *_tempV34eZ); raydistance *=inversedeterminant; if (raydistance < 0){ out=0; return false; } out=raydistance; return true; } Collision.intersectsRayAndTriangleRP=function(ray,vertex1,vertex2,vertex3,out){ var distance=NaN; if (!Collision.intersectsRayAndTriangleRD(ray,vertex1,vertex2,vertex3,distance)){ out=Vector3.ZERO; return false; } Vector3.scale(ray.direction,distance,Collision._tempV30); Vector3.add(ray.origin,Collision._tempV30,out); return true; } Collision.intersectsRayAndPoint=function(ray,point){ Vector3.subtract(ray.origin,point,Collision._tempV30); var b=Vector3.dot(Collision._tempV30,ray.direction); var c=Vector3.dot(Collision._tempV30,Collision._tempV30)-MathUtils3D.zeroTolerance; if (c > 0 && b > 0) return false; var discriminant=b *b-c; if (discriminant < 0) return false; return true; } Collision.intersectsRayAndRay=function(ray1,ray2,out){ var ray1o=ray1.origin; var ray1oe=ray1o.elements; var ray1oeX=ray1oe[0]; var ray1oeY=ray1oe[1]; var ray1oeZ=ray1oe[2]; var ray1d=ray1.direction; var ray1de=ray1d.elements; var ray1deX=ray1de[0]; var ray1deY=ray1de[1]; var ray1deZ=ray1de[2]; var ray2o=ray2.origin; var ray2oe=ray2o.elements; var ray2oeX=ray2oe[0]; var ray2oeY=ray2oe[1]; var ray2oeZ=ray2oe[2]; var ray2d=ray2.direction; var ray2de=ray2d.elements; var ray2deX=ray2de[0]; var ray2deY=ray2de[1]; var ray2deZ=ray2de[2]; Vector3.cross(ray1d,ray2d,Collision._tempV30); var tempV3e=Collision._tempV30.elements; var denominator=Vector3.scalarLengthSquared(Collision._tempV30); if (MathUtils3D.isZero(denominator)){ if (MathUtils3D.nearEqual(ray2oeX,ray1oeX)&& MathUtils3D.nearEqual(ray2oeY,ray1oeY)&& MathUtils3D.nearEqual(ray2oeZ,ray1oeZ)){ Vector3.ZERO.cloneTo(out); return true; } }; var m11=ray2oeX-ray1oeX; var m12=ray2oeY-ray1oeY; var m13=ray2oeZ-ray1oeZ; var m21=ray2deX; var m22=ray2deY; var m23=ray2deZ; var m31=tempV3e[0]; var m32=tempV3e[1]; var m33=tempV3e[2]; var dets=m11 *m22 *m33+m12 *m23 *m31+m13 *m21 *m32-m11 *m23 *m32-m12 *m21 *m33-m13 *m22 *m31; m21=ray1deX; m22=ray1deY; m23=ray1deZ; var dett=m11 *m22 *m33+m12 *m23 *m31+m13 *m21 *m32-m11 *m23 *m32-m12 *m21 *m33-m13 *m22 *m31; var s=dets / denominator; var t=dett / denominator; Vector3.scale(ray1d,s,Collision._tempV30); Vector3.scale(ray2d,t,Collision._tempV31); Vector3.add(ray1o,Collision._tempV30,Collision._tempV32); Vector3.add(ray2o,Collision._tempV31,Collision._tempV33); var point1e=Collision._tempV32.elements; var point2e=Collision._tempV33.elements; if (!MathUtils3D.nearEqual(point2e[0],point1e[0])|| !MathUtils3D.nearEqual(point2e[1],point1e[1])|| !MathUtils3D.nearEqual(point2e[2],point1e[2])){ Vector3.ZERO.cloneTo(out); return false; } Collision._tempV32.cloneTo(out); return true; } Collision.intersectsPlaneAndTriangle=function(plane,vertex1,vertex2,vertex3){ var test1=Collision.intersectsPlaneAndPoint(plane,vertex1); var test2=Collision.intersectsPlaneAndPoint(plane,vertex2); var test3=Collision.intersectsPlaneAndPoint(plane,vertex3); if (test1==Plane.PlaneIntersectionType_Front && test2==Plane.PlaneIntersectionType_Front && test3==Plane.PlaneIntersectionType_Front) return Plane.PlaneIntersectionType_Front; if (test1==Plane.PlaneIntersectionType_Back && test2==Plane.PlaneIntersectionType_Back && test3==Plane.PlaneIntersectionType_Back) return Plane.PlaneIntersectionType_Back; return Plane.PlaneIntersectionType_Intersecting; } Collision.intersectsRayAndPlaneRD=function(ray,plane,out){ var planeNor=plane.normal; var direction=Vector3.dot(planeNor,ray.direction); if (MathUtils3D.isZero(direction)){ out=0; return false; }; var position=Vector3.dot(planeNor,ray.origin); out=(-plane.distance-position)/ direction; if (out < 0){ out=0; return false; } return true; } Collision.intersectsRayAndPlaneRP=function(ray,plane,out){ var distance=NaN; if (!Collision.intersectsRayAndPlaneRD(ray,plane,distance)){ out=Vector3.ZERO; return false; } Vector3.scale(ray.direction,distance,Collision._tempV30); Vector3.add(ray.origin,Collision._tempV30,Collision._tempV31); out=Collision._tempV31; return true; } Collision.intersectsRayAndBoxRD=function(ray,box){ var rayoe=ray.origin.elements; var rayoeX=rayoe[0]; var rayoeY=rayoe[1]; var rayoeZ=rayoe[2]; var rayde=ray.direction.elements; var raydeX=rayde[0]; var raydeY=rayde[1]; var raydeZ=rayde[2]; var boxMine=box.min.elements; var boxMineX=boxMine[0]; var boxMineY=boxMine[1]; var boxMineZ=boxMine[2]; var boxMaxe=box.max.elements; var boxMaxeX=boxMaxe[0]; var boxMaxeY=boxMaxe[1]; var boxMaxeZ=boxMaxe[2]; var out=0; var tmax=MathUtils3D.MaxValue; if (MathUtils3D.isZero(raydeX)){ if (rayoeX < boxMineX || rayoeX > boxMaxeX){ return-1; } }else { var inverse=1 / raydeX; var t1=(boxMineX-rayoeX)*inverse; var t2=(boxMaxeX-rayoeX)*inverse; if (t1 > t2){ var temp=t1; t1=t2; t2=temp; } out=Math.max(t1,out); tmax=Math.min(t2,tmax); if (out > tmax){ return-1; } } if (MathUtils3D.isZero(raydeY)){ if (rayoeY < boxMineY || rayoeY > boxMaxeY){ return-1; } }else { var inverse1=1 / raydeY; var t3=(boxMineY-rayoeY)*inverse1; var t4=(boxMaxeY-rayoeY)*inverse1; if (t3 > t4){ var temp1=t3; t3=t4; t4=temp1; } out=Math.max(t3,out); tmax=Math.min(t4,tmax); if (out > tmax){ return-1; } } if (MathUtils3D.isZero(raydeZ)){ if (rayoeZ < boxMineZ || rayoeZ > boxMaxeZ){ return-1; } }else { var inverse2=1 / raydeZ; var t5=(boxMineZ-rayoeZ)*inverse2; var t6=(boxMaxeZ-rayoeZ)*inverse2; if (t5 > t6){ var temp2=t5; t5=t6; t6=temp2; } out=Math.max(t5,out); tmax=Math.min(t6,tmax); if (out > tmax){ return-1; } } return out; } Collision.intersectsRayAndBoxRP=function(ray,box,out){ var distance=Collision.intersectsRayAndBoxRD(ray,box); if (distance===-1){ Vector3.ZERO.cloneTo(out); return distance; } Vector3.scale(ray.direction,distance,Collision._tempV30); Vector3.add(ray.origin,Collision._tempV30,Collision._tempV31); Collision._tempV31.cloneTo(out); return distance; } Collision.intersectsRayAndSphereRD=function(ray,sphere){ var sphereR=sphere.radius; Vector3.subtract(ray.origin,sphere.center,Collision._tempV30); var b=Vector3.dot(Collision._tempV30,ray.direction); var c=Vector3.dot(Collision._tempV30,Collision._tempV30)-(sphereR *sphereR); if (c > 0 && b > 0){ return-1; }; var discriminant=b *b-c; if (discriminant < 0){ return-1; }; var distance=-b-Math.sqrt(discriminant); if (distance < 0) distance=0; return distance; } Collision.intersectsRayAndSphereRP=function(ray,sphere,out){ var distance=Collision.intersectsRayAndSphereRD(ray,sphere); if (distance===-1){ Vector3.ZERO.cloneTo(out); return distance; } Vector3.scale(ray.direction,distance,Collision._tempV30); Vector3.add(ray.origin,Collision._tempV30,Collision._tempV31); Collision._tempV31.cloneTo(out); return distance; } Collision.intersectsSphereAndTriangle=function(sphere,vertex1,vertex2,vertex3){ var sphereC=sphere.center; var sphereR=sphere.radius; Collision.closestPointPointTriangle(sphereC,vertex1,vertex2,vertex3,Collision._tempV30); Vector3.subtract(Collision._tempV30,sphereC,Collision._tempV31); var dot=Vector3.dot(Collision._tempV31,Collision._tempV31); return dot <=sphereR *sphereR; } Collision.intersectsPlaneAndPoint=function(plane,point){ var distance=Vector3.dot(plane.normal,point)+plane.distance; if (distance > 0) return Plane.PlaneIntersectionType_Front; if (distance < 0) return Plane.PlaneIntersectionType_Back; return Plane.PlaneIntersectionType_Intersecting; } Collision.intersectsPlaneAndPlane=function(plane1,plane2){ Vector3.cross(plane1.normal,plane2.normal,Collision._tempV30); var denominator=Vector3.dot(Collision._tempV30,Collision._tempV30); if (MathUtils3D.isZero(denominator)) return false; return true; } Collision.intersectsPlaneAndPlaneRL=function(plane1,plane2,line){ var plane1nor=plane1.normal; var plane2nor=plane2.normal; Vector3.cross(plane1nor,plane2nor,Collision._tempV34); var denominator=Vector3.dot(Collision._tempV34,Collision._tempV34); if (MathUtils3D.isZero(denominator)) return false; Vector3.scale(plane2nor,plane1.distance,Collision._tempV30); Vector3.scale(plane1nor,plane2.distance,Collision._tempV31); Vector3.subtract(Collision._tempV30,Collision._tempV31,Collision._tempV32); Vector3.cross(Collision._tempV32,Collision._tempV34,Collision._tempV33); Vector3.normalize(Collision._tempV34,Collision._tempV34); line=new Ray(Collision._tempV33,Collision._tempV34); return true; } Collision.intersectsPlaneAndBox=function(plane,box){ var planeD=plane.distance; var planeNor=plane.normal; var planeNore=planeNor.elements; var planeNoreX=planeNore[0]; var planeNoreY=planeNore[1]; var planeNoreZ=planeNore[2]; var boxMine=box.min.elements; var boxMineX=boxMine[0]; var boxMineY=boxMine[1]; var boxMineZ=boxMine[2]; var boxMaxe=box.max.elements; var boxMaxeX=boxMaxe[0]; var boxMaxeY=boxMaxe[1]; var boxMaxeZ=boxMaxe[2]; Collision._tempV30.elements[0]=(planeNoreX > 0)? boxMineX :boxMaxeX; Collision._tempV30.elements[1]=(planeNoreY > 0)? boxMineY :boxMaxeY; Collision._tempV30.elements[2]=(planeNoreZ > 0)? boxMineZ :boxMaxeZ; Collision._tempV31.elements[0]=(planeNoreX > 0)? boxMaxeX :boxMineX; Collision._tempV31.elements[1]=(planeNoreY > 0)? boxMaxeY :boxMineY; Collision._tempV31.elements[2]=(planeNoreZ > 0)? boxMaxeZ :boxMineZ; var distance=Vector3.dot(planeNor,Collision._tempV30); if (distance+planeD > 0) return Plane.PlaneIntersectionType_Front; distance=Vector3.dot(planeNor,Collision._tempV31); if (distance+planeD < 0) return Plane.PlaneIntersectionType_Back; return Plane.PlaneIntersectionType_Intersecting; } Collision.intersectsPlaneAndSphere=function(plane,sphere){ var sphereR=sphere.radius; var distance=Vector3.dot(plane.normal,sphere.center)+plane.distance; if (distance > sphereR) return Plane.PlaneIntersectionType_Front; if (distance <-sphereR) return Plane.PlaneIntersectionType_Back; return Plane.PlaneIntersectionType_Intersecting; } Collision.intersectsBoxAndBox=function(box1,box2){ var box1Mine=box1.min.elements; var box1Maxe=box1.max.elements; var box2Mine=box2.min.elements; var box2Maxe=box2.max.elements; if (box1Mine[0] > box2Maxe[0] || box2Mine[0] > box1Maxe[0]) return false; if (box1Mine[1] > box2Maxe[1] || box2Mine[1] > box1Maxe[1]) return false; if (box1Mine[2] > box2Maxe[2] || box2Mine[2] > box1Maxe[2]) return false; return true; } Collision.intersectsBoxAndSphere=function(box,sphere){ var sphereC=sphere.center; var sphereR=sphere.radius; Vector3.Clamp(sphereC,box.min,box.max,Collision._tempV30); var distance=Vector3.distanceSquared(sphereC,Collision._tempV30); return distance <=sphereR *sphereR; } Collision.intersectsSphereAndSphere=function(sphere1,sphere2){ var radiisum=sphere1.radius+sphere2.radius; return Vector3.distanceSquared(sphere1.center,sphere2.center)<=radiisum *radiisum; } Collision.boxContainsPoint=function(box,point){ var boxMine=box.min.elements; var boxMaxe=box.max.elements; var pointe=point.elements; if (boxMine[0] <=pointe[0] && boxMaxe[0] >=pointe[0] && boxMine[1] <=pointe[1] && boxMaxe[1] >=pointe[1] && boxMine[2] <=pointe[2] && boxMaxe[2] >=pointe[2]) return /*laya.d3.math.ContainmentType.Contains*/1; return /*laya.d3.math.ContainmentType.Disjoint*/0; } Collision.boxContainsBox=function(box1,box2){ var box1Mine=box1.min.elements; var box1MineX=box1Mine[0]; var box1MineY=box1Mine[1]; var box1MineZ=box1Mine[2]; var box1Maxe=box1.max.elements; var box1MaxeX=box1Maxe[0]; var box1MaxeY=box1Maxe[1]; var box1MaxeZ=box1Maxe[2]; var box2Mine=box2.min.elements; var box2MineX=box2Mine[0]; var box2MineY=box2Mine[1]; var box2MineZ=box2Mine[2]; var box2Maxe=box2.max.elements; var box2MaxeX=box2Maxe[0]; var box2MaxeY=box2Maxe[1]; var box2MaxeZ=box2Maxe[2]; if (box1MaxeX < box2MineX || box1MineX > box2MaxeX) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (box1MaxeY < box2MineY || box1MineY > box2MaxeY) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (box1MaxeZ < box2MineZ || box1MineZ > box2MaxeZ) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (box1MineX <=box2MineX && box2MaxeX <=box2MaxeX && box1MineY <=box2MineY && box2MaxeY <=box1MaxeY && box1MineZ <=box2MineZ && box2MaxeZ <=box1MaxeZ){ return /*laya.d3.math.ContainmentType.Contains*/1; } return /*laya.d3.math.ContainmentType.Intersects*/2; } Collision.boxContainsSphere=function(box,sphere){ var boxMin=box.min; var boxMine=boxMin.elements; var boxMineX=boxMine[0]; var boxMineY=boxMine[1]; var boxMineZ=boxMine[2]; var boxMax=box.max; var boxMaxe=boxMax.elements; var boxMaxeX=boxMaxe[0]; var boxMaxeY=boxMaxe[1]; var boxMaxeZ=boxMaxe[2]; var sphereC=sphere.center; var sphereCe=sphereC.elements; var sphereCeX=sphereCe[0]; var sphereCeY=sphereCe[1]; var sphereCeZ=sphereCe[2]; var sphereR=sphere.radius; Vector3.Clamp(sphereC,boxMin,boxMax,Collision._tempV30); var distance=Vector3.distanceSquared(sphereC,Collision._tempV30); if (distance > sphereR *sphereR) return /*laya.d3.math.ContainmentType.Disjoint*/0; if ((((boxMineX+sphereR <=sphereCeX)&& (sphereCeX <=boxMaxeX-sphereR))&& ((boxMaxeX-boxMineX > sphereR)&& (boxMineY+sphereR <=sphereCeY)))&& (((sphereCeY <=boxMaxeY-sphereR)&& (boxMaxeY-boxMineY > sphereR))&& (((boxMineZ+sphereR <=sphereCeZ)&& (sphereCeZ <=boxMaxeZ-sphereR))&& (boxMaxeZ-boxMineZ > sphereR)))) return /*laya.d3.math.ContainmentType.Contains*/1; return /*laya.d3.math.ContainmentType.Intersects*/2; } Collision.sphereContainsPoint=function(sphere,point){ if (Vector3.distanceSquared(point,sphere.center)<=sphere.radius *sphere.radius) return /*laya.d3.math.ContainmentType.Contains*/1; return /*laya.d3.math.ContainmentType.Disjoint*/0; } Collision.sphereContainsTriangle=function(sphere,vertex1,vertex2,vertex3){ var test1=Collision.sphereContainsPoint(sphere,vertex1); var test2=Collision.sphereContainsPoint(sphere,vertex2); var test3=Collision.sphereContainsPoint(sphere,vertex3); if (test1==/*laya.d3.math.ContainmentType.Contains*/1 && test2==/*laya.d3.math.ContainmentType.Contains*/1 && test3==/*laya.d3.math.ContainmentType.Contains*/1) return /*laya.d3.math.ContainmentType.Contains*/1; if (Collision.intersectsSphereAndTriangle(sphere,vertex1,vertex2,vertex3)) return /*laya.d3.math.ContainmentType.Intersects*/2; return /*laya.d3.math.ContainmentType.Disjoint*/0; } Collision.sphereContainsBox=function(sphere,box){ var sphereC=sphere.center; var sphereCe=sphereC.elements; var sphereCeX=sphereCe[0]; var sphereCeY=sphereCe[1]; var sphereCeZ=sphereCe[2]; var sphereR=sphere.radius; var boxMin=box.min; var boxMine=boxMin.elements; var boxMineX=boxMine[0]; var boxMineY=boxMine[1]; var boxMineZ=boxMine[2]; var boxMax=box.max; var boxMaxe=boxMax.elements; var boxMaxeX=boxMaxe[0]; var boxMaxeY=boxMaxe[1]; var boxMaxeZ=boxMaxe[2]; var _tempV30e=Collision._tempV30.elements; var _tempV30eX=_tempV30e[0]; var _tempV30eY=_tempV30e[1]; var _tempV30eZ=_tempV30e[2]; if (!Collision.intersectsBoxAndSphere(box,sphere)) return /*laya.d3.math.ContainmentType.Disjoint*/0; var radiusSquared=sphereR *sphereR; _tempV30eX=sphereCeX-boxMineX; _tempV30eY=sphereCeY-boxMaxeY; _tempV30eZ=sphereCeZ-boxMaxeZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMaxeX; _tempV30eY=sphereCeY-boxMaxeY; _tempV30eZ=sphereCeZ-boxMaxeZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMaxeX; _tempV30eY=sphereCeY-boxMineY; _tempV30eZ=sphereCeZ-boxMaxeZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMineX; _tempV30eY=sphereCeY-boxMineY; _tempV30eZ=sphereCeZ-boxMaxeZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMineX; _tempV30eY=sphereCeY-boxMaxeY; _tempV30eZ=sphereCeZ-boxMineZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMaxeX; _tempV30eY=sphereCeY-boxMaxeY; _tempV30eZ=sphereCeZ-boxMineZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMaxeX; _tempV30eY=sphereCeY-boxMineY; _tempV30eZ=sphereCeZ-boxMineZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMineX; _tempV30eY=sphereCeY-boxMineY; _tempV30eZ=sphereCeZ-boxMineZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; return /*laya.d3.math.ContainmentType.Contains*/1; } Collision.sphereContainsSphere=function(sphere1,sphere2){ var sphere1R=sphere1.radius; var sphere2R=sphere2.radius; var distance=Vector3.distance(sphere1.center,sphere2.center); if (sphere1R+sphere2R < distance) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (sphere1R-sphere2R < distance) return /*laya.d3.math.ContainmentType.Intersects*/2; return /*laya.d3.math.ContainmentType.Contains*/1; } Collision.closestPointPointTriangle=function(point,vertex1,vertex2,vertex3,out){ Vector3.subtract(vertex2,vertex1,Collision._tempV30); Vector3.subtract(vertex3,vertex1,Collision._tempV31); Vector3.subtract(point,vertex1,Collision._tempV32); Vector3.subtract(point,vertex2,Collision._tempV33); Vector3.subtract(point,vertex3,Collision._tempV34); var d1=Vector3.dot(Collision._tempV30,Collision._tempV32); var d2=Vector3.dot(Collision._tempV31,Collision._tempV32); var d3=Vector3.dot(Collision._tempV30,Collision._tempV33); var d4=Vector3.dot(Collision._tempV31,Collision._tempV33); var d5=Vector3.dot(Collision._tempV30,Collision._tempV34); var d6=Vector3.dot(Collision._tempV31,Collision._tempV34); if (d1 <=0 && d2 <=0){ vertex1.cloneTo(out); return; } if (d3 >=0 && d4 <=d3){ vertex2.cloneTo(out); return; }; var vc=d1 *d4-d3 *d2; if (vc <=0 && d1 >=0 && d3 <=0){ var v=d1 / (d1-d3); Vector3.scale(Collision._tempV30,v,out); Vector3.add(vertex1,out,out); return; } if (d6 >=0 && d5 <=d6){ vertex3.cloneTo(out); return; }; var vb=d5 *d2-d1 *d6; if (vb <=0 && d2 >=0 && d6 <=0){ var w=d2 / (d2-d6); Vector3.scale(Collision._tempV31,w,out); Vector3.add(vertex1,out,out); return; }; var va=d3 *d6-d5 *d4; if (va <=0 && (d4-d3)>=0 && (d5-d6)>=0){ var w3=(d4-d3)/ ((d4-d3)+(d5-d6)); Vector3.subtract(vertex3,vertex2,out); Vector3.scale(out,w3,out); Vector3.add(vertex2,out,out); return; }; var denom=1 / (va+vb+vc); var v2=vb *denom; var w2=vc *denom; Vector3.scale(Collision._tempV30,v2,Collision._tempV35); Vector3.scale(Collision._tempV31,w2,Collision._tempV36); Vector3.add(Collision._tempV35,Collision._tempV36,out); Vector3.add(vertex1,out,out); } Collision.closestPointPlanePoint=function(plane,point,out){ var planeN=plane.normal; var t=Vector3.dot(planeN,point)-plane.distance; Vector3.scale(planeN,t,Collision._tempV30); Vector3.subtract(point,Collision._tempV30,out); } Collision.closestPointBoxPoint=function(box,point,out){ Vector3.max(point,box.min,Collision._tempV30); Vector3.min(Collision._tempV30,box.max,out); } Collision.closestPointSpherePoint=function(sphere,point,out){ var sphereC=sphere.center; Vector3.subtract(point,sphereC,out); Vector3.normalize(out,out); Vector3.scale(out,sphere.radius,out); Vector3.add(out,sphereC,out); } Collision.closestPointSphereSphere=function(sphere1,sphere2,out){ var sphere1C=sphere1.center; Vector3.subtract(sphere2.center,sphere1C,out); Vector3.normalize(out,out); Vector3.scale(out,sphere1.radius,out); Vector3.add(out,sphere1C,out); } __static(Collision, ['_tempV30',function(){return this._tempV30=new Vector3();},'_tempV31',function(){return this._tempV31=new Vector3();},'_tempV32',function(){return this._tempV32=new Vector3();},'_tempV33',function(){return this._tempV33=new Vector3();},'_tempV34',function(){return this._tempV34=new Vector3();},'_tempV35',function(){return this._tempV35=new Vector3();},'_tempV36',function(){return this._tempV36=new Vector3();} ]); return Collision; })() /** *ContainmentType 类用于定义空间物体位置关系。 */ //class laya.d3.math.ContainmentType var ContainmentType=(function(){ function ContainmentType(){} __class(ContainmentType,'laya.d3.math.ContainmentType'); ContainmentType.Disjoint=0; ContainmentType.Contains=1; ContainmentType.Intersects=2; return ContainmentType; })() /** *MathUtils 类用于创建数学工具。 */ //class laya.d3.math.MathUtils3D var MathUtils3D=(function(){ /** *创建一个 MathUtils 实例。 */ function MathUtils3D(){} __class(MathUtils3D,'laya.d3.math.MathUtils3D'); MathUtils3D.isZero=function(v){ return Math.abs(v)< MathUtils3D.zeroTolerance; } MathUtils3D.nearEqual=function(n1,n2){ if (MathUtils3D.isZero(n1-n2)) return true; return false; } MathUtils3D.fastInvSqrt=function(value){ if (MathUtils3D.isZero(value)) return value; return 1.0 / Math.sqrt(value); } __static(MathUtils3D, ['zeroTolerance',function(){return this.zeroTolerance=1e-6;},'MaxValue',function(){return this.MaxValue=3.40282347e+38;},'MinValue',function(){return this.MinValue=-3.40282347e+38;} ]); return MathUtils3D; })() /** *Matrix3x3 类用于创建3x3矩阵。 */ //class laya.d3.math.Matrix3x3 var Matrix3x3=(function(){ function Matrix3x3(){ /**矩阵元素数组*/ //this.elements=null; var e=this.elements=new Float32Array(9); e[0]=1; e[1]=0; e[2]=0; e[3]=0; e[4]=1; e[5]=0; e[6]=0; e[7]=0; e[8]=1; } __class(Matrix3x3,'laya.d3.math.Matrix3x3'); var __proto=Matrix3x3.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *计算3x3矩阵的行列式 *@return 矩阵的行列式 */ __proto.determinant=function(){ var f=this.elements; var a00=f[0],a01=f[1],a02=f[2]; var a10=f[3],a11=f[4],a12=f[5]; var a20=f[6],a21=f[7],a22=f[8]; return a00 *(a22 *a11-a12 *a21)+a01 *(-a22 *a10+a12 *a20)+a02 *(a21 *a10-a11 *a20); } /** *通过一个二维向量转换3x3矩阵 *@param tra 转换向量 *@param out 输出矩阵 */ __proto.translate=function(trans,out){ var e=out.elements; var f=this.elements; var g=trans.elements; var a00=f[0],a01=f[1],a02=f[2]; var a10=f[3],a11=f[4],a12=f[5]; var a20=f[6],a21=f[7],a22=f[8]; var x=g[0],y=g[1]; e[0]=a00; e[1]=a01; e[2]=a02; e[3]=a10; e[4]=a11; e[5]=a12; e[6]=x *a00+y *a10+a20; e[7]=x *a01+y *a11+a21; e[8]=x *a02+y *a12+a22; } /** *根据指定角度旋转3x3矩阵 *@param rad 旋转角度 *@param out 输出矩阵 */ __proto.rotate=function(rad,out){ var e=out.elements; var f=this.elements; var a00=f[0],a01=f[1],a02=f[2]; var a10=f[3],a11=f[4],a12=f[5]; var a20=f[6],a21=f[7],a22=f[8]; var s=Math.sin(rad); var c=Math.cos(rad); e[0]=c *a00+s *a10; e[1]=c *a01+s *a11; e[2]=c *a02+s *a12; e[3]=c *a10-s *a00; e[4]=c *a11-s *a01; e[5]=c *a12-s *a02; e[6]=a20; e[7]=a21; e[8]=a22; } /** *根据制定缩放3x3矩阵 *@param scale 缩放值 *@param out 输出矩阵 */ __proto.scale=function(scale,out){ var e=out.elements; var f=this.elements; var g=scale.elements; var x=g[0],y=g[1]; e[0]=x *f[0]; e[1]=x *f[1]; e[2]=x *f[2]; e[3]=y *f[3]; e[4]=y *f[4]; e[5]=y *f[5]; e[6]=f[6]; e[7]=f[7]; e[8]=f[8]; } /** *计算3x3矩阵的逆矩阵 *@param out 输出的逆矩阵 */ __proto.invert=function(out){ var e=out.elements; var f=this.elements; var a00=f[0],a01=f[1],a02=f[2]; var a10=f[3],a11=f[4],a12=f[5]; var a20=f[6],a21=f[7],a22=f[8]; var b01=a22 *a11-a12 *a21; var b11=-a22 *a10+a12 *a20; var b21=a21 *a10-a11 *a20; var det=a00 *b01+a01 *b11+a02 *b21; if (!det){ out=null; } det=1.0 / det; e[0]=b01 *det; e[1]=(-a22 *a01+a02 *a21)*det; e[2]=(a12 *a01-a02 *a11)*det; e[3]=b11 *det; e[4]=(a22 *a00-a02 *a20)*det; e[5]=(-a12 *a00+a02 *a10)*det; e[6]=b21 *det; e[7]=(-a21 *a00+a01 *a20)*det; e[8]=(a11 *a00-a01 *a10)*det; } /** *计算3x3矩阵的转置矩阵 *@param out 输出矩阵 */ __proto.transpose=function(out){ var e=out.elements; var f=this.elements; if (out===this){ var a01=f[1],a02=f[2],a12=f[5]; e[1]=f[3]; e[2]=f[6]; e[3]=a01; e[5]=f[7]; e[6]=a02; e[7]=a12; }else { e[0]=f[0]; e[1]=f[3]; e[2]=f[6]; e[3]=f[1]; e[4]=f[4]; e[5]=f[7]; e[6]=f[2]; e[7]=f[5]; e[8]=f[8]; } } /**设置已有的矩阵为单位矩阵*/ __proto.identity=function(){ var e=this.elements; e[0]=1; e[1]=0; e[2]=0; e[3]=0; e[4]=1; e[5]=0; e[6]=0; e[7]=0; e[8]=1; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var i,s,d; s=this.elements; d=destObject.elements; if (s===d){ return; } for (i=0;i < 9;++i){ d[i]=s[i]; } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } Matrix3x3.createFromTranslation=function(trans,out){ var e=out.elements; var g=trans.elements; out[0]=1; out[1]=0; out[2]=0; out[3]=0; out[4]=1; out[5]=0; out[6]=g[0]; out[7]=g[1]; out[8]=1; } Matrix3x3.createFromRotation=function(rad,out){ var e=out.elements; var s=Math.sin(rad),c=Math.cos(rad); e[0]=c; e[1]=s; e[2]=0; e[3]=-s; e[4]=c; e[5]=0; e[6]=0; e[7]=0; e[8]=1; } Matrix3x3.createFromScaling=function(scale,out){ var e=out.elements; var g=scale.elements; e[0]=g[0]; e[1]=0; e[2]=0; e[3]=0; e[4]=g[1]; e[5]=0; e[6]=0; e[7]=0; e[8]=1; } Matrix3x3.createFromMatrix4x4=function(sou,out){ out[0]=sou[0]; out[1]=sou[1]; out[2]=sou[2]; out[3]=sou[4]; out[4]=sou[5]; out[5]=sou[6]; out[6]=sou[8]; out[7]=sou[9]; out[8]=sou[10]; } Matrix3x3.multiply=function(left,right,out){ var e=out.elements; var f=left.elements; var g=right.elements; var a00=f[0],a01=f[1],a02=f[2]; var a10=f[3],a11=f[4],a12=f[5]; var a20=f[6],a21=f[7],a22=f[8]; var b00=g[0],b01=g[1],b02=g[2]; var b10=g[3],b11=g[4],b12=g[5]; var b20=g[6],b21=g[7],b22=g[8]; e[0]=b00 *a00+b01 *a10+b02 *a20; e[1]=b00 *a01+b01 *a11+b02 *a21; e[2]=b00 *a02+b01 *a12+b02 *a22; e[3]=b10 *a00+b11 *a10+b12 *a20; e[4]=b10 *a01+b11 *a11+b12 *a21; e[5]=b10 *a02+b11 *a12+b12 *a22; e[6]=b20 *a00+b21 *a10+b22 *a20; e[7]=b20 *a01+b21 *a11+b22 *a21; e[8]=b20 *a02+b21 *a12+b22 *a22; } Matrix3x3.lookAt=function(eye,target,up,out){ Vector3.subtract(eye,target,Matrix3x3._tempV30); Vector3.normalize(Matrix3x3._tempV30,Matrix3x3._tempV30); Vector3.cross(up,Matrix3x3._tempV30,Matrix3x3._tempV31); Vector3.normalize(Matrix3x3._tempV31,Matrix3x3._tempV31); Vector3.cross(Matrix3x3._tempV30,Matrix3x3._tempV31,Matrix3x3._tempV32); var v0e=Matrix3x3._tempV30.elements; var v1e=Matrix3x3._tempV31.elements; var v2e=Matrix3x3._tempV32.elements; var me=out.elements; me[0]=v1e[0]; me[3]=v1e[1]; me[6]=v1e[2]; me[1]=v2e[0]; me[4]=v2e[1]; me[7]=v2e[2]; me[2]=v0e[0]; me[5]=v0e[1]; me[8]=v0e[2]; } Matrix3x3.DEFAULT=new Matrix3x3(); __static(Matrix3x3, ['_tempV30',function(){return this._tempV30=new Vector3();},'_tempV31',function(){return this._tempV31=new Vector3();},'_tempV32',function(){return this._tempV32=new Vector3();} ]); return Matrix3x3; })() /** *Matrix4x4 类用于创建4x4矩阵。 */ //class laya.d3.math.Matrix4x4 var Matrix4x4=(function(){ function Matrix4x4(m11,m12,m13,m14,m21,m22,m23,m24,m31,m32,m33,m34,m41,m42,m43,m44){ /**矩阵元素数组*/ //this.elements=null; (m11===void 0)&& (m11=1); (m12===void 0)&& (m12=0); (m13===void 0)&& (m13=0); (m14===void 0)&& (m14=0); (m21===void 0)&& (m21=0); (m22===void 0)&& (m22=1); (m23===void 0)&& (m23=0); (m24===void 0)&& (m24=0); (m31===void 0)&& (m31=0); (m32===void 0)&& (m32=0); (m33===void 0)&& (m33=1); (m34===void 0)&& (m34=0); (m41===void 0)&& (m41=0); (m42===void 0)&& (m42=0); (m43===void 0)&& (m43=0); (m44===void 0)&& (m44=1); var e=this.elements=new Float32Array(16); e[0]=m11; e[1]=m12; e[2]=m13; e[3]=m14; e[4]=m21; e[5]=m22; e[6]=m23; e[7]=m24; e[8]=m31; e[9]=m32; e[10]=m33; e[11]=m34; e[12]=m41; e[13]=m42; e[14]=m43; e[15]=m44; } __class(Matrix4x4,'laya.d3.math.Matrix4x4'); var __proto=Matrix4x4.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) __proto.getElementByRowColumn=function(row,column){ if (row < 0 || row > 3) throw new Error("row","Rows and columns for matrices run from 0 to 3, inclusive."); if (column < 0 || column > 3) throw new Error("column","Rows and columns for matrices run from 0 to 3, inclusive."); return this.elements[(row *4)+column]; } __proto.setElementByRowColumn=function(row,column,value){ if (row < 0 || row > 3) throw new Error("row","Rows and columns for matrices run from 0 to 3, inclusive."); if (column < 0 || column > 3) throw new Error("column","Rows and columns for matrices run from 0 to 3, inclusive."); this.elements[(row *4)+column]=value; } /** *判断两个4x4矩阵的值是否相等。 *@param other 4x4矩阵 */ __proto.equalsOtherMatrix=function(other){ var e=this.elements; var oe=other.elements; return (MathUtils3D.nearEqual(e[0],oe[0])&& MathUtils3D.nearEqual(e[1],oe[1])&& MathUtils3D.nearEqual(e[2],oe[2])&& MathUtils3D.nearEqual(e[3],oe[3])&& MathUtils3D.nearEqual(e[4],oe[4])&& MathUtils3D.nearEqual(e[5],oe[5])&& MathUtils3D.nearEqual(e[6],oe[6])&& MathUtils3D.nearEqual(e[7],oe[7])&& MathUtils3D.nearEqual(e[8],oe[8])&& MathUtils3D.nearEqual(e[9],oe[9])&& MathUtils3D.nearEqual(e[10],oe[10])&& MathUtils3D.nearEqual(e[11],oe[11])&& MathUtils3D.nearEqual(e[12],oe[12])&& MathUtils3D.nearEqual(e[13],oe[13])&& MathUtils3D.nearEqual(e[14],oe[14])&& MathUtils3D.nearEqual(e[15],oe[15])); } /** *分解矩阵为平移向量、旋转四元数、缩放向量。 *@param translation 平移向量。 *@param rotation 旋转四元数。 *@param scale 缩放向量。 *@return 是否分解成功。 */ __proto.decomposeTransRotScale=function(translation,rotation,scale){ var rotationMatrix=Matrix4x4._tempMatrix4x4; if (this.decomposeTransRotMatScale(translation,rotationMatrix,scale)){ Quaternion.createFromMatrix4x4(rotationMatrix,rotation); return true; }else { rotation.identity(); return false; } } /** *分解矩阵为平移向量、旋转矩阵、缩放向量。 *@param translation 平移向量。 *@param rotationMatrix 旋转矩阵。 *@param scale 缩放向量。 *@return 是否分解成功。 */ __proto.decomposeTransRotMatScale=function(translation,rotationMatrix,scale){ var e=this.elements; var te=translation.elements; var re=rotationMatrix.elements; var se=scale.elements; te[0]=e[12]; te[1]=e[13]; te[2]=e[14]; var m11=e[0],m12=e[1],m13=e[2]; var m21=e[4],m22=e[5],m23=e[6]; var m31=e[8],m32=e[9],m33=e[10]; var sX=se[0]=Math.sqrt((m11 *m11)+(m12 *m12)+(m13 *m13)); var sY=se[1]=Math.sqrt((m21 *m21)+(m22 *m22)+(m23 *m23)); var sZ=se[2]=Math.sqrt((m31 *m31)+(m32 *m32)+(m33 *m33)); if (MathUtils3D.isZero(sX)|| MathUtils3D.isZero(sY)|| MathUtils3D.isZero(sZ)){ re[1]=re[2]=re[3]=re[4]=re[6]=re[7]=re[8]=re[9]=re[11]=re[12]=re[13]=re[14]=0; re[0]=re[5]=re[10]=re[15]=1; return false; }; var at=Matrix4x4._tempVector0; var atE=at.elements; atE[0]=m31 / sZ; atE[1]=m32 / sZ; atE[2]=m33 / sZ; var tempRight=Matrix4x4._tempVector1; var tempRightE=tempRight.elements; tempRightE[0]=m11 / sX; tempRightE[1]=m12 / sX; tempRightE[2]=m13 / sX; var up=Matrix4x4._tempVector2; Vector3.cross(at,tempRight,up); var right=Matrix4x4._tempVector1; Vector3.cross(up,at,right); re[3]=re[7]=re[11]=re[12]=re[13]=re[14]=0; re[15]=1; re[0]=right.x; re[1]=right.y; re[2]=right.z; re[4]=up.x; re[5]=up.y; re[6]=up.z; re[8]=at.x; re[9]=at.y; re[10]=at.z; ((re[0] *m11+re[1] *m12+re[2] *m13)< 0.0)&& (se[0]=-sX); ((re[4] *m21+re[5] *m22+re[6] *m23)< 0.0)&& (se[1]=-sY); ((re[8] *m31+re[9] *m32+re[10] *m33)< 0.0)&& (se[2]=-sZ); return true; } /** *分解旋转矩阵的旋转为YawPitchRoll欧拉角。 *@param out float yaw *@param out float pitch *@param out float roll *@return */ __proto.decomposeYawPitchRoll=function(yawPitchRoll){ var yawPitchRollE=yawPitchRoll.elements; var pitch=Math.asin(-this.elements[9]); yawPitchRollE[1]=pitch; var test=Math.cos(pitch); if (test > MathUtils3D.zeroTolerance){ yawPitchRollE[2]=Math.atan2(this.elements[1],this.elements[5]); yawPitchRollE[0]=Math.atan2(this.elements[8],this.elements[10]); }else { yawPitchRollE[2]=Math.atan2(-this.elements[4],this.elements[0]); yawPitchRollE[0]=0.0; } } /**归一化矩阵 */ __proto.normalize=function(){ var v=this.elements; var c=v[0],d=v[1],e=v[2],g=Math.sqrt(c *c+d *d+e *e); if (g){ if (g==1) return; }else { v[0]=0; v[1]=0; v[2]=0; return; } g=1 / g; v[0]=c *g; v[1]=d *g; v[2]=e *g; } /**计算矩阵的转置矩阵*/ __proto.transpose=function(){ var e,t; e=this.elements; t=e[1]; e[1]=e[4]; e[4]=t; t=e[2]; e[2]=e[8]; e[8]=t; t=e[3]; e[3]=e[12]; e[12]=t; t=e[6]; e[6]=e[9]; e[9]=t; t=e[7]; e[7]=e[13]; e[13]=t; t=e[11]; e[11]=e[14]; e[14]=t; return this; } /** *计算一个矩阵的逆矩阵 *@param out 输出矩阵 */ __proto.invert=function(out){ var ae=this.elements; var oe=out.elements; var a00=ae[0],a01=ae[1],a02=ae[2],a03=ae[3],a10=ae[4],a11=ae[5],a12=ae[6],a13=ae[7],a20=ae[8],a21=ae[9],a22=ae[10],a23=ae[11],a30=ae[12],a31=ae[13],a32=ae[14],a33=ae[15], b00=a00 *a11-a01 *a10,b01=a00 *a12-a02 *a10,b02=a00 *a13-a03 *a10,b03=a01 *a12-a02 *a11,b04=a01 *a13-a03 *a11,b05=a02 *a13-a03 *a12,b06=a20 *a31-a21 *a30,b07=a20 *a32-a22 *a30,b08=a20 *a33-a23 *a30,b09=a21 *a32-a22 *a31,b10=a21 *a33-a23 *a31,b11=a22 *a33-a23 *a32, det=b00 *b11-b01 *b10+b02 *b09+b03 *b08-b04 *b07+b05 *b06; if (Math.abs(det)===0.0){ return; } det=1.0 / det; oe[0]=(a11 *b11-a12 *b10+a13 *b09)*det; oe[1]=(a02 *b10-a01 *b11-a03 *b09)*det; oe[2]=(a31 *b05-a32 *b04+a33 *b03)*det; oe[3]=(a22 *b04-a21 *b05-a23 *b03)*det; oe[4]=(a12 *b08-a10 *b11-a13 *b07)*det; oe[5]=(a00 *b11-a02 *b08+a03 *b07)*det; oe[6]=(a32 *b02-a30 *b05-a33 *b01)*det; oe[7]=(a20 *b05-a22 *b02+a23 *b01)*det; oe[8]=(a10 *b10-a11 *b08+a13 *b06)*det; oe[9]=(a01 *b08-a00 *b10-a03 *b06)*det; oe[10]=(a30 *b04-a31 *b02+a33 *b00)*det; oe[11]=(a21 *b02-a20 *b04-a23 *b00)*det; oe[12]=(a11 *b07-a10 *b09-a12 *b06)*det; oe[13]=(a00 *b09-a01 *b07+a02 *b06)*det; oe[14]=(a31 *b01-a30 *b03-a32 *b00)*det; oe[15]=(a20 *b03-a21 *b01+a22 *b00)*det; } /**设置矩阵为单位矩阵*/ __proto.identity=function(){ var e=this.elements; e[1]=e[2]=e[3]=e[4]=e[6]=e[7]=e[8]=e[9]=e[11]=e[12]=e[13]=e[14]=0; e[0]=e[5]=e[10]=e[15]=1; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var i,s,d; s=this.elements; d=destObject.elements; if (s===d){ return; } for (i=0;i < 16;++i){ d[i]=s[i]; } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } /** *获取平移向量。 *@param out 平移向量。 */ __proto.getTranslationVector=function(out){ var me=this.elements; var te=out.elements; te[0]=me[12]; te[1]=me[13]; te[2]=me[14]; } /** *设置平移向量。 *@param translate 平移向量。 */ __proto.setTranslationVector=function(translate){ var me=this.elements; var ve=translate.elements; me[12]=ve[0]; me[13]=ve[1]; me[14]=ve[2]; } /** *获取前向量。 *@param out 前向量。 */ __proto.getForward=function(out){ var me=this.elements; var te=out.elements; te[0]=-me[8]; te[1]=-me[9]; te[2]=-me[10]; } /** *设置前向量。 *@param forward 前向量。 */ __proto.setForward=function(forward){ var me=this.elements; var ve=forward.elements; me[8]=-ve[0]; me[9]=-ve[1]; me[10]=-ve[2]; } Matrix4x4.createRotationX=function(rad,out){ var oe=out.elements; var s=Math.sin(rad),c=Math.cos(rad); oe[1]=oe[2]=oe[3]=oe[4]=oe[7]=oe[8]=oe[11]=oe[12]=oe[13]=oe[14]=0; oe[0]=oe[15]=1; oe[5]=oe[10]=c; oe[6]=s; oe[9]=-s; } Matrix4x4.createRotationY=function(rad,out){ var oe=out.elements; var s=Math.sin(rad),c=Math.cos(rad); oe[1]=oe[3]=oe[4]=oe[6]=oe[7]=oe[9]=oe[11]=oe[12]=oe[13]=oe[14]=0; oe[5]=oe[15]=1; oe[0]=oe[10]=c; oe[2]=-s; oe[8]=s; } Matrix4x4.createRotationZ=function(rad,out){ var oe=out.elements; var s=Math.sin(rad),c=Math.cos(rad); oe[2]=oe[3]=oe[6]=oe[7]=oe[8]=oe[9]=oe[11]=oe[12]=oe[13]=oe[14]=0; oe[10]=oe[15]=1; oe[0]=oe[5]=c; oe[1]=s; oe[4]=-s; } Matrix4x4.createRotationYawPitchRoll=function(yaw,pitch,roll,result){ Quaternion.createFromYawPitchRoll(yaw,pitch,roll,Matrix4x4._tempQuaternion); Matrix4x4.createRotationQuaternion(Matrix4x4._tempQuaternion,result); } Matrix4x4.createRotationAxis=function(axis,angle,result){ var axisE=axis.elements; var x=axisE[0]; var y=axisE[1]; var z=axisE[2]; var cos=Math.cos(angle); var sin=Math.sin(angle); var xx=x *x; var yy=y *y; var zz=z *z; var xy=x *y; var xz=x *z; var yz=y *z; var resultE=result.elements; resultE[3]=resultE[7]=resultE[11]=resultE[12]=resultE[13]=resultE[14]=0; resultE[15]=1.0; resultE[0]=xx+(cos *(1.0-xx)); resultE[1]=(xy-(cos *xy))+(sin *z); resultE[2]=(xz-(cos *xz))-(sin *y); resultE[4]=(xy-(cos *xy))-(sin *z); resultE[5]=yy+(cos *(1.0-yy)); resultE[6]=(yz-(cos *yz))+(sin *x); resultE[8]=(xz-(cos *xz))+(sin *y); resultE[9]=(yz-(cos *yz))-(sin *x); resultE[10]=zz+(cos *(1.0-zz)); } Matrix4x4.createRotationQuaternion=function(rotation,result){ var rotationE=rotation.elements; var resultE=result.elements; var rotationX=rotationE[0]; var rotationY=rotationE[1]; var rotationZ=rotationE[2]; var rotationW=rotationE[3]; var xx=rotationX *rotationX; var yy=rotationY *rotationY; var zz=rotationZ *rotationZ; var xy=rotationX *rotationY; var zw=rotationZ *rotationW; var zx=rotationZ *rotationX; var yw=rotationY *rotationW; var yz=rotationY *rotationZ; var xw=rotationX *rotationW; resultE[3]=resultE[7]=resultE[11]=resultE[12]=resultE[13]=resultE[14]=0; resultE[15]=1.0; resultE[0]=1.0-(2.0 *(yy+zz)); resultE[1]=2.0 *(xy+zw); resultE[2]=2.0 *(zx-yw); resultE[4]=2.0 *(xy-zw); resultE[5]=1.0-(2.0 *(zz+xx)); resultE[6]=2.0 *(yz+xw); resultE[8]=2.0 *(zx+yw); resultE[9]=2.0 *(yz-xw); resultE[10]=1.0-(2.0 *(yy+xx)); } Matrix4x4.createTranslate=function(trans,out){ var te=trans.elements; var oe=out.elements; oe[4]=oe[8]=oe[1]=oe[9]=oe[2]=oe[6]=oe[3]=oe[7]=oe[11]=0; oe[0]=oe[5]=oe[10]=oe[15]=1; oe[12]=te[0]; oe[13]=te[1]; oe[14]=te[2]; } Matrix4x4.createScaling=function(scale,out){ var se=scale.elements; var oe=out.elements; oe[0]=se[0]; oe[5]=se[1]; oe[10]=se[2]; oe[1]=oe[4]=oe[8]=oe[12]=oe[9]=oe[13]=oe[2]=oe[6]=oe[14]=oe[3]=oe[7]=oe[11]=0; oe[15]=1; } Matrix4x4.multiply=function(left,right,out){ var i,e,a,b,ai0,ai1,ai2,ai3; e=out.elements; a=left.elements; b=right.elements; if (e===b){ b=new Float32Array(16); for (i=0;i < 16;++i){ b[i]=e[i]; } } for (i=0;i < 4;i++){ ai0=a[i]; ai1=a[i+4]; ai2=a[i+8]; ai3=a[i+12]; e[i]=ai0 *b[0]+ai1 *b[1]+ai2 *b[2]+ai3 *b[3]; e[i+4]=ai0 *b[4]+ai1 *b[5]+ai2 *b[6]+ai3 *b[7]; e[i+8]=ai0 *b[8]+ai1 *b[9]+ai2 *b[10]+ai3 *b[11]; e[i+12]=ai0 *b[12]+ai1 *b[13]+ai2 *b[14]+ai3 *b[15]; } } Matrix4x4.createFromQuaternion=function(rotation,out){ var e=out.elements; var q=rotation.elements; var x=q[0],y=q[1],z=q[2],w=q[3]; var x2=x+x; var y2=y+y; var z2=z+z; var xx=x *x2; var yx=y *x2; var yy=y *y2; var zx=z *x2; var zy=z *y2; var zz=z *z2; var wx=w *x2; var wy=w *y2; var wz=w *z2; e[0]=1-yy-zz; e[1]=yx+wz; e[2]=zx-wy; e[3]=0; e[4]=yx-wz; e[5]=1-xx-zz; e[6]=zy+wx; e[7]=0; e[8]=zx+wy; e[9]=zy-wx; e[10]=1-xx-yy; e[11]=0; e[12]=0; e[13]=0; e[14]=0; e[15]=1; } Matrix4x4.createAffineTransformation=function(trans,rot,scale,out){ var te=trans.elements; var re=rot.elements; var se=scale.elements; var oe=out.elements; var x=re[0],y=re[1],z=re[2],w=re[3],x2=x+x,y2=y+y,z2=z+z; var xx=x *x2,xy=x *y2,xz=x *z2,yy=y *y2,yz=y *z2,zz=z *z2; var wx=w *x2,wy=w *y2,wz=w *z2,sx=se[0],sy=se[1],sz=se[2]; oe[0]=(1-(yy+zz))*sx; oe[1]=(xy+wz)*sx; oe[2]=(xz-wy)*sx; oe[3]=0; oe[4]=(xy-wz)*sy; oe[5]=(1-(xx+zz))*sy; oe[6]=(yz+wx)*sy; oe[7]=0; oe[8]=(xz+wy)*sz; oe[9]=(yz-wx)*sz; oe[10]=(1-(xx+yy))*sz; oe[11]=0; oe[12]=te[0]; oe[13]=te[1]; oe[14]=te[2]; oe[15]=1; } Matrix4x4.createLookAt=function(eye,target,up,out){ var oE=out.elements; var xaxis=Matrix4x4._tempVector0; var yaxis=Matrix4x4._tempVector1; var zaxis=Matrix4x4._tempVector2; Vector3.subtract(eye,target,zaxis); Vector3.normalize(zaxis,zaxis); Vector3.cross(up,zaxis,xaxis); Vector3.normalize(xaxis,xaxis); Vector3.cross(zaxis,xaxis,yaxis); out.identity(); oE[0]=xaxis.x; oE[4]=xaxis.y; oE[8]=xaxis.z; oE[1]=yaxis.x; oE[5]=yaxis.y; oE[9]=yaxis.z; oE[2]=zaxis.x; oE[6]=zaxis.y; oE[10]=zaxis.z; oE[12]=-Vector3.dot(xaxis,eye); oE[13]=-Vector3.dot(yaxis,eye); oE[14]=-Vector3.dot(zaxis,eye); } Matrix4x4.createPerspective=function(fov,aspect,near,far,out){ var oe=out.elements; var f=1.0 / Math.tan(fov / 2),nf=1 / (near-far); oe[0]=f / aspect; oe[5]=f; oe[10]=(far+near)*nf; oe[11]=-1; oe[14]=(2 *far *near)*nf; oe[1]=oe[2]=oe[3]=oe[4]=oe[6]=oe[7]=oe[8]=oe[9]=oe[12]=oe[13]=oe[15]=0; } Matrix4x4.createOrthoOffCenterRH=function(left,right,bottom,top,near,far,out){ var oe=out.elements; var lr=1 / (left-right); var bt=1 / (bottom-top); var nf=1 / (near-far); oe[1]=oe[2]=oe[3]=oe[4]=oe[6]=oe[7]=oe[8]=oe[9]=oe[11]=0; oe[15]=1; oe[0]=-2 *lr; oe[5]=-2 *bt; oe[10]=2 *nf; oe[12]=(left+right)*lr; oe[13]=(top+bottom)*bt; oe[14]=(far+near)*nf; } Matrix4x4.translation=function(v3,out){ var ve=v3.elements; var oe=out.elements; oe[0]=oe[5]=oe[10]=oe[15]=1; oe[12]=ve[0]; oe[13]=ve[1]; oe[14]=ve[2]; } __static(Matrix4x4, ['_tempMatrix4x4',function(){return this._tempMatrix4x4=new Matrix4x4();},'_tempVector0',function(){return this._tempVector0=new Vector3();},'_tempVector1',function(){return this._tempVector1=new Vector3();},'_tempVector2',function(){return this._tempVector2=new Vector3();},'_tempQuaternion',function(){return this._tempQuaternion=new Quaternion();},'DEFAULT',function(){return this.DEFAULT=new Matrix4x4();},'ZERO',function(){return this.ZERO=new Matrix4x4( 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0);} ]); return Matrix4x4; })() /** *OrientedBoundBox 类用于创建OBB包围盒。 */ //class laya.d3.math.OrientedBoundBox var OrientedBoundBox=(function(){ function OrientedBoundBox(extents,transformation){ /**每个轴长度的一半*/ this.extents=null; /**这个矩阵表示包围盒的位置和缩放,它的平移向量表示该包围盒的中心*/ this.transformation=null; this.extents=extents; this.transformation=transformation; } __class(OrientedBoundBox,'laya.d3.math.OrientedBoundBox'); var __proto=OrientedBoundBox.prototype; /** *获取OBB包围盒的8个顶点。 *@param corners 返回顶点的输出队列。 */ __proto.getCorners=function(corners){ var xve=OrientedBoundBox._tempV30.elements; var yve=OrientedBoundBox._tempV31.elements; var zve=OrientedBoundBox._tempV32.elements; var extentsE=this.extents.elements; xve[0]=extentsE[0]; xve[1]=xve[2]=0; yve[1]=extentsE[1]; yve[0]=yve[2]=0; zve[2]=extentsE[2]; zve[0]=zve[1]=0; Vector3.TransformNormal(OrientedBoundBox._tempV30,this.transformation,OrientedBoundBox._tempV30); Vector3.TransformNormal(OrientedBoundBox._tempV31,this.transformation,OrientedBoundBox._tempV31); Vector3.TransformNormal(OrientedBoundBox._tempV32,this.transformation,OrientedBoundBox._tempV32); var center=OrientedBoundBox._tempV33; this.transformation.getTranslationVector(center); corners.length=8; Vector3.add(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[0]); Vector3.add(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[1]); Vector3.subtract(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[2]); Vector3.subtract(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[3]); Vector3.add(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[4]); Vector3.add(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[5]); Vector3.subtract(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[6]); Vector3.subtract(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[7]); } /** *变换该包围盒的矩阵信息。 *@param mat 矩阵 */ __proto.transform=function(mat){ Matrix4x4.multiply(this.transformation,mat,this.transformation); } /** *缩放该包围盒 *@param scaling 各轴的缩放比。 */ __proto.scale=function(scaling){ Vector3.multiply(this.extents,scaling,this.extents); } /** *平移该包围盒。 *@param translation 平移参数 */ __proto.translate=function(translation){ this.transformation.getTranslationVector(OrientedBoundBox._tempV30); Vector3.add(OrientedBoundBox._tempV30,translation,OrientedBoundBox._tempV31); this.transformation.setTranslationVector(OrientedBoundBox._tempV31); } /** *该包围盒的尺寸。 *@param out 输出 */ __proto.Size=function(out){ Vector3.scale(this.extents,2,out); } /** *该包围盒需要考虑的尺寸 *@param out 输出 */ __proto.getSize=function(out){ var extentsE=this.extents.elements; OrientedBoundBox._tempV30.x=extentsE[0]; OrientedBoundBox._tempV31.y=extentsE[1]; OrientedBoundBox._tempV32.z=extentsE[2]; Vector3.TransformNormal(OrientedBoundBox._tempV30,this.transformation,OrientedBoundBox._tempV30); Vector3.TransformNormal(OrientedBoundBox._tempV31,this.transformation,OrientedBoundBox._tempV31); Vector3.TransformNormal(OrientedBoundBox._tempV31,this.transformation,OrientedBoundBox._tempV32); var oe=out.elements; oe[0]=Vector3.scalarLength(OrientedBoundBox._tempV30); oe[1]=Vector3.scalarLength(OrientedBoundBox._tempV31); oe[2]=Vector3.scalarLength(OrientedBoundBox._tempV32); } /** *该包围盒需要考虑尺寸的平方 *@param out 输出 */ __proto.getSizeSquared=function(out){ var extentsE=this.extents.elements; OrientedBoundBox._tempV30.x=extentsE[0]; OrientedBoundBox._tempV31.y=extentsE[1]; OrientedBoundBox._tempV32.z=extentsE[2]; Vector3.TransformNormal(OrientedBoundBox._tempV30,this.transformation,OrientedBoundBox._tempV30); Vector3.TransformNormal(OrientedBoundBox._tempV31,this.transformation,OrientedBoundBox._tempV31); Vector3.TransformNormal(OrientedBoundBox._tempV31,this.transformation,OrientedBoundBox._tempV32); var oe=out.elements; oe[0]=Vector3.scalarLengthSquared(OrientedBoundBox._tempV30); oe[1]=Vector3.scalarLengthSquared(OrientedBoundBox._tempV31); oe[2]=Vector3.scalarLengthSquared(OrientedBoundBox._tempV32); } /** *该包围盒的几何中心 */ __proto.getCenter=function(center){ this.transformation.getTranslationVector(center); } /** *该包围盒是否包含空间中一点 *@param point 点 *@return 返回位置关系 */ __proto.containsPoint=function(point){ var extentsE=this.extents.elements; var extentsEX=extentsE[0]; var extentsEY=extentsE[1]; var extentsEZ=extentsE[2]; this.transformation.invert(OrientedBoundBox._tempM0); Vector3.transformCoordinate(point,OrientedBoundBox._tempM0,OrientedBoundBox._tempV30); var _tempV30e=OrientedBoundBox._tempV30.elements; var _tempV30ex=Math.abs(_tempV30e[0]); var _tempV30ey=Math.abs(_tempV30e[1]); var _tempV30ez=Math.abs(_tempV30e[2]); if (MathUtils3D.nearEqual(_tempV30ex,extentsEX)&& MathUtils3D.nearEqual(_tempV30ey,extentsEY)&& MathUtils3D.nearEqual(_tempV30ez,extentsEZ)) return /*laya.d3.math.ContainmentType.Intersects*/2; if (_tempV30ex < extentsEX && _tempV30ey < extentsEY && _tempV30ez < extentsEZ) return /*laya.d3.math.ContainmentType.Contains*/1; else return /*laya.d3.math.ContainmentType.Disjoint*/0; } /** *该包围盒是否包含空间中多点 *@param point 点 *@return 返回位置关系 */ __proto.containsPoints=function(points){ var extentse=this.extents.elements; var extentsex=extentse[0]; var extentsey=extentse[1]; var extentsez=extentse[2]; this.transformation.invert(OrientedBoundBox._tempM0); var containsAll=true; var containsAny=false; for (var i=0;i < points.length;i++){ Vector3.transformCoordinate(points[i],OrientedBoundBox._tempM0,OrientedBoundBox._tempV30); var _tempV30e=OrientedBoundBox._tempV30.elements; var _tempV30ex=Math.abs(_tempV30e[0]); var _tempV30ey=Math.abs(_tempV30e[1]); var _tempV30ez=Math.abs(_tempV30e[2]); if (MathUtils3D.nearEqual(_tempV30ex,extentsex)&& MathUtils3D.nearEqual(_tempV30ey,extentsey)&& MathUtils3D.nearEqual(_tempV30ez,extentsez)) containsAny=true; if (_tempV30ex < extentsex && _tempV30ey < extentsey && _tempV30ez < extentsez) containsAny=true; else containsAll=false; } if (containsAll) return /*laya.d3.math.ContainmentType.Contains*/1; else if (containsAny) return /*laya.d3.math.ContainmentType.Intersects*/2; else return /*laya.d3.math.ContainmentType.Disjoint*/0; } /** *该包围盒是否包含空间中一包围球 *@param sphere 包围球 *@param ignoreScale 是否考虑该包围盒的缩放 *@return 返回位置关系 */ __proto.containsSphere=function(sphere,ignoreScale){ (ignoreScale===void 0)&& (ignoreScale=false); var extentsE=this.extents.elements; var extentsEX=extentsE[0]; var extentsEY=extentsE[1]; var extentsEZ=extentsE[2]; var sphereR=sphere.radius; this.transformation.invert(OrientedBoundBox._tempM0); Vector3.transformCoordinate(sphere.center,OrientedBoundBox._tempM0,OrientedBoundBox._tempV30); var locRadius=NaN; if (ignoreScale){ locRadius=sphereR; }else { Vector3.scale(Vector3.UnitX,sphereR,OrientedBoundBox._tempV31); Vector3.TransformNormal(OrientedBoundBox._tempV31,OrientedBoundBox._tempM0,OrientedBoundBox._tempV31); locRadius=Vector3.scalarLength(OrientedBoundBox._tempV31); } Vector3.scale(this.extents,-1,OrientedBoundBox._tempV32); Vector3.Clamp(OrientedBoundBox._tempV30,OrientedBoundBox._tempV32,this.extents,OrientedBoundBox._tempV33); var distance=Vector3.distanceSquared(OrientedBoundBox._tempV30,OrientedBoundBox._tempV33); if (distance > locRadius *locRadius) return /*laya.d3.math.ContainmentType.Disjoint*/0; var tempV30e=OrientedBoundBox._tempV30.elements; var tempV30ex=tempV30e[0]; var tempV30ey=tempV30e[1]; var tempV30ez=tempV30e[2]; var tempV32e=OrientedBoundBox._tempV32.elements; var tempV32ex=tempV32e[0]; var tempV32ey=tempV32e[1]; var tempV32ez=tempV32e[2]; if ((((tempV32ex+locRadius <=tempV30ex)&& (tempV30ex <=extentsEX-locRadius))&& ((extentsEX-tempV32ex > locRadius)&& (tempV32ey+locRadius <=tempV30ey)))&& (((tempV30ey <=extentsEY-locRadius)&& (extentsEY-tempV32ey > locRadius))&& (((tempV32ez+locRadius <=tempV30ez)&& (tempV30ez <=extentsEZ-locRadius))&& (extentsEZ-tempV32ez > locRadius)))){ return /*laya.d3.math.ContainmentType.Contains*/1; } return /*laya.d3.math.ContainmentType.Intersects*/2; } /** *For accuracy,The transformation matrix for both must not have any scaling applied to it. *Anyway,scaling using Scale method will keep this method accurate. *该包围盒是否包含空间中另一OBB包围盒 *@param obb OBB包围盒 *@return 返回位置关系 */ __proto.containsOrientedBoundBox=function(obb){ var i=0,k=0; obb.getCorners(OrientedBoundBox._corners); var cornersCheck=this.containsPoints(OrientedBoundBox._corners); if (cornersCheck !=/*laya.d3.math.ContainmentType.Disjoint*/0) return cornersCheck; var sizeAe=this.extents.elements; obb.extents.cloneTo(OrientedBoundBox._tempV35); var sizeBe=OrientedBoundBox._tempV35.elements; OrientedBoundBox._getRows(this.transformation,OrientedBoundBox._rows1); OrientedBoundBox._getRows(obb.transformation,OrientedBoundBox._rows2); var extentA=NaN,extentB=NaN,separation=NaN,dotNumber=NaN; for (i=0;i < 4;i++){ for (k=0;k < 4;k++){ if (i==3 || k==3){ OrientedBoundBox._tempM0.setElementByRowColumn(i,k,0); OrientedBoundBox._tempM1.setElementByRowColumn(i,k,0); }else { dotNumber=Vector3.dot(OrientedBoundBox._rows1[i],OrientedBoundBox._rows2[k]); OrientedBoundBox._tempM0.setElementByRowColumn(i,k,dotNumber); OrientedBoundBox._tempM1.setElementByRowColumn(i,k,Math.abs(dotNumber)); } } } obb.getCenter(OrientedBoundBox._tempV34); this.getCenter(OrientedBoundBox._tempV36); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV36,OrientedBoundBox._tempV30); var vsepAe=OrientedBoundBox._tempV31.elements; vsepAe[0]=Vector3.dot(OrientedBoundBox._tempV30,OrientedBoundBox._rows1[0]); vsepAe[1]=Vector3.dot(OrientedBoundBox._tempV30,OrientedBoundBox._rows1[1]); vsepAe[2]=Vector3.dot(OrientedBoundBox._tempV30,OrientedBoundBox._rows1[2]); var _tempV32e=OrientedBoundBox._tempV32.elements; var _tempV33e=OrientedBoundBox._tempV33.elements; for (i=0;i < 3;i++){ _tempV32e[0]=OrientedBoundBox._tempM1.getElementByRowColumn(i,0); _tempV32e[1]=OrientedBoundBox._tempM1.getElementByRowColumn(i,1); _tempV32e[2]=OrientedBoundBox._tempM1.getElementByRowColumn(i,2); extentA=sizeAe[i]; extentB=Vector3.dot(OrientedBoundBox._tempV35,OrientedBoundBox._tempV32); separation=Math.abs(vsepAe[i]); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } for (k=0;k < 3;k++){ _tempV32e[0]=OrientedBoundBox._tempM1.getElementByRowColumn(0,k); _tempV32e[1]=OrientedBoundBox._tempM1.getElementByRowColumn(1,k); _tempV32e[2]=OrientedBoundBox._tempM1.getElementByRowColumn(2,k); _tempV33e[0]=OrientedBoundBox._tempM0.getElementByRowColumn(0,k); _tempV33e[1]=OrientedBoundBox._tempM0.getElementByRowColumn(1,k); _tempV33e[2]=OrientedBoundBox._tempM0.getElementByRowColumn(2,k); extentA=Vector3.dot(this.extents,OrientedBoundBox._tempV32); extentB=sizeBe[k]; separation=Math.abs(Vector3.dot(OrientedBoundBox._tempV31,OrientedBoundBox._tempV33)); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } for (i=0;i < 3;i++){ for (k=0;k < 3;k++){ var i1=(i+1)% 3,i2=(i+2)% 3; var k1=(k+1)% 3,k2=(k+2)% 3; extentA=sizeAe[i1] *OrientedBoundBox._tempM1.getElementByRowColumn(i2,k)+sizeAe[i2] *OrientedBoundBox._tempM1.getElementByRowColumn(i1,k); extentB=sizeBe[k1] *OrientedBoundBox._tempM1.getElementByRowColumn(i,k2)+sizeBe[k2] *OrientedBoundBox._tempM1.getElementByRowColumn(i,k1); separation=Math.abs(vsepAe[i2] *OrientedBoundBox._tempM0.getElementByRowColumn(i1,k)-vsepAe[i1] *OrientedBoundBox._tempM0.getElementByRowColumn(i2,k)); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } } return /*laya.d3.math.ContainmentType.Intersects*/2; } /** *该包围盒是否包含空间中一条线 *@param point1 点1 *@param point2 点2 *@return 返回位置关系 */ __proto.containsLine=function(point1,point2){ OrientedBoundBox._corners[0]=point1; OrientedBoundBox._corners[1]=point2; var cornersCheck=this.containsPoints(OrientedBoundBox._corners); if (cornersCheck !=/*laya.d3.math.ContainmentType.Disjoint*/0) return cornersCheck; var extentsE=this.extents.elements; var extentsX=extentsE[0]; var extentsY=extentsE[1]; var extentsZ=extentsE[2]; this.transformation.invert(OrientedBoundBox._tempM0); Vector3.transformCoordinate(point1,OrientedBoundBox._tempM0,OrientedBoundBox._tempV30); Vector3.transformCoordinate(point2,OrientedBoundBox._tempM0,OrientedBoundBox._tempV31); Vector3.add(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV32); Vector3.scale(OrientedBoundBox._tempV32,0.5,OrientedBoundBox._tempV32); Vector3.subtract(OrientedBoundBox._tempV30,OrientedBoundBox._tempV32,OrientedBoundBox._tempV33); var _tempV33e=OrientedBoundBox._tempV33.elements; var _tempV33X=_tempV33e[0]; var _tempV33Y=_tempV33e[1]; var _tempV33Z=_tempV33e[2]; var _tempV34e=OrientedBoundBox._tempV34.elements; var _tempV34X=_tempV34e[0]=Math.abs(_tempV33e[0]); var _tempV34Y=_tempV34e[1]=Math.abs(_tempV33e[1]); var _tempV34Z=_tempV34e[2]=Math.abs(_tempV33e[2]); var _tempV32e=OrientedBoundBox._tempV32.elements; var _tempV32X=_tempV32e[0]; var _tempV32Y=_tempV32e[1]; var _tempV32Z=_tempV32e[2]; if (Math.abs(_tempV32X)> extentsX+_tempV34X) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Math.abs(_tempV32Y)> extentsY+_tempV34Y) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Math.abs(_tempV32Z)> extentsZ+_tempV34Z) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Math.abs(_tempV32Y *_tempV33Z-_tempV32Z *_tempV33Y)> (extentsY *_tempV34Z+extentsZ *_tempV34Y)) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Math.abs(_tempV32X *_tempV33Z-_tempV32Z *_tempV33X)> (extentsX *_tempV34Z+extentsZ *_tempV34X)) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Math.abs(_tempV32X *_tempV33Y-_tempV32Y *_tempV33X)> (extentsX *_tempV34Y+extentsY *_tempV34X)) return /*laya.d3.math.ContainmentType.Disjoint*/0; return /*laya.d3.math.ContainmentType.Intersects*/2; } /** *该包围盒是否包含空间中另一OBB包围盒 *@param box 包围盒 *@return 返回位置关系 */ __proto.containsBoundBox=function(box){ var i=0,k=0; var min=box.min; var max=box.max; box.getCorners(OrientedBoundBox._corners); var cornersCheck=this.containsPoints(OrientedBoundBox._corners); if (cornersCheck !=/*laya.d3.math.ContainmentType.Disjoint*/0) return cornersCheck; Vector3.subtract(max,min,OrientedBoundBox._tempV30); Vector3.scale(OrientedBoundBox._tempV30,0.5,OrientedBoundBox._tempV30); Vector3.add(min,OrientedBoundBox._tempV30,OrientedBoundBox._tempV30); Vector3.subtract(max,OrientedBoundBox._tempV30,OrientedBoundBox._tempV31); var sizeAe=this.extents.elements; var sizeBe=OrientedBoundBox._tempV31.elements; OrientedBoundBox._getRows(this.transformation,OrientedBoundBox._rows1); this.transformation.invert(OrientedBoundBox._tempM0); var extentA=NaN,extentB=NaN,separation=NaN,dotNumber=NaN; for (i=0;i < 3;i++){ for (k=0;k < 3;k++){ OrientedBoundBox._tempM1.setElementByRowColumn(i,k,Math.abs(OrientedBoundBox._tempM0.getElementByRowColumn(i,k))); } } this.getCenter(OrientedBoundBox._tempV35); Vector3.subtract(OrientedBoundBox._tempV30,OrientedBoundBox._tempV35,OrientedBoundBox._tempV32); var vsepAe=OrientedBoundBox._tempV31.elements; vsepAe[0]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[0]); vsepAe[1]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[1]); vsepAe[2]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[2]); var _tempV33e=OrientedBoundBox._tempV33.elements; var _tempV34e=OrientedBoundBox._tempV34.elements; for (i=0;i < 3;i++){ _tempV33e[0]=OrientedBoundBox._tempM1.getElementByRowColumn(i,0); _tempV33e[1]=OrientedBoundBox._tempM1.getElementByRowColumn(i,1); _tempV33e[2]=OrientedBoundBox._tempM1.getElementByRowColumn(i,2); extentA=sizeAe[i]; extentB=Vector3.dot(OrientedBoundBox._tempV31,OrientedBoundBox._tempV33); separation=Math.abs(vsepAe[i]); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } for (k=0;k < 3;k++){ _tempV33e[0]=OrientedBoundBox._tempM1.getElementByRowColumn(0,k); _tempV33e[1]=OrientedBoundBox._tempM1.getElementByRowColumn(1,k); _tempV33e[2]=OrientedBoundBox._tempM1.getElementByRowColumn(2,k); _tempV34e[0]=OrientedBoundBox._tempM0.getElementByRowColumn(0,k); _tempV34e[1]=OrientedBoundBox._tempM0.getElementByRowColumn(1,k); _tempV34e[2]=OrientedBoundBox._tempM0.getElementByRowColumn(2,k); extentA=Vector3.dot(this.extents,OrientedBoundBox._tempV33); extentB=sizeBe[k]; separation=Math.abs(Vector3.dot(OrientedBoundBox._tempV31,OrientedBoundBox._tempV34)); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } for (i=0;i < 3;i++){ for (k=0;k < 3;k++){ var i1=(i+1)% 3,i2=(i+2)% 3; var k1=(k+1)% 3,k2=(k+2)% 3; extentA=sizeAe[i1] *OrientedBoundBox._tempM1.getElementByRowColumn(i2,k)+sizeAe[i2] *OrientedBoundBox._tempM1.getElementByRowColumn(i1,k); extentB=sizeBe[k1] *OrientedBoundBox._tempM1.getElementByRowColumn(i,k2)+sizeBe[k2] *OrientedBoundBox._tempM1.getElementByRowColumn(i,k1); separation=Math.abs(vsepAe[i2] *OrientedBoundBox._tempM0.getElementByRowColumn(i1,k)-vsepAe[i1] *OrientedBoundBox._tempM0.getElementByRowColumn(i2,k)); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } } return /*laya.d3.math.ContainmentType.Intersects*/2; } /** *该包围盒是否与空间中另一射线相交 *@param ray *@param out *@return */ __proto.intersectsRay=function(ray,out){ Vector3.scale(this.extents,-1,OrientedBoundBox._tempV30); this.transformation.invert(OrientedBoundBox._tempM0); Vector3.TransformNormal(ray.direction,OrientedBoundBox._tempM0,OrientedBoundBox._ray.direction); Vector3.transformCoordinate(ray.origin,OrientedBoundBox._tempM0,OrientedBoundBox._ray.origin); OrientedBoundBox._boxBound1.min=OrientedBoundBox._tempV30; OrientedBoundBox._boxBound1.max=this.extents; var intersects=Collision.intersectsRayAndBoxRP(OrientedBoundBox._ray,OrientedBoundBox._boxBound1,out); if (intersects!==-1) Vector3.transformCoordinate(out,this.transformation,out); return intersects; } __proto._getLocalCorners=function(corners){ corners.length=8; var extentsE=this.extents.elements; OrientedBoundBox._tempV30.x=extentsE[0]; OrientedBoundBox._tempV31.y=extentsE[1]; OrientedBoundBox._tempV32.z=extentsE[2]; Vector3.add(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV33); Vector3.add(OrientedBoundBox._tempV33,OrientedBoundBox._tempV32,corners[0]); Vector3.add(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV33); Vector3.subtract(OrientedBoundBox._tempV33,OrientedBoundBox._tempV32,corners[1]); Vector3.subtract(OrientedBoundBox._tempV31,OrientedBoundBox._tempV30,OrientedBoundBox._tempV33); Vector3.subtract(OrientedBoundBox._tempV33,OrientedBoundBox._tempV30,corners[2]); Vector3.subtract(OrientedBoundBox._tempV31,OrientedBoundBox._tempV30,OrientedBoundBox._tempV33); Vector3.add(OrientedBoundBox._tempV33,OrientedBoundBox._tempV32,corners[3]); Vector3.subtract(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV33); Vector3.add(OrientedBoundBox._tempV33,OrientedBoundBox._tempV32,corners[4]); Vector3.subtract(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV33); Vector3.subtract(OrientedBoundBox._tempV33,OrientedBoundBox._tempV32,corners[5]); Vector3.scale(corners[0],-1,corners[6]); Vector3.subtract(OrientedBoundBox._tempV32,OrientedBoundBox._tempV30,OrientedBoundBox._tempV33); Vector3.subtract(OrientedBoundBox._tempV33,OrientedBoundBox._tempV31,corners[7]); } /** *判断两个包围盒是否相等 *@param obb obb包围盒 *@return Boolean */ __proto.equals=function(obb){ return this.extents==obb.extents && this.transformation==obb.transformation; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var dest=destObject; this.extents.cloneTo(dest.extents); this.transformation.cloneTo(dest.transformation); } OrientedBoundBox.createByBoundBox=function(box,out){ var min=box.min; var max=box.max; Vector3.subtract(max,min,OrientedBoundBox._tempV30); Vector3.scale(OrientedBoundBox._tempV30,0.5,OrientedBoundBox._tempV30); Vector3.add(min,OrientedBoundBox._tempV30,OrientedBoundBox._tempV31); Vector3.subtract(max,OrientedBoundBox._tempV31,OrientedBoundBox._tempV32); Matrix4x4.translation(OrientedBoundBox._tempV31,OrientedBoundBox._tempM0); var extents=OrientedBoundBox._tempV32.clone(); var transformation=OrientedBoundBox._tempM0.clone(); out.extents=extents; out.transformation=transformation; } OrientedBoundBox.createByMinAndMaxVertex=function(min,max){ Vector3.subtract(max,min,OrientedBoundBox._tempV30); Vector3.scale(OrientedBoundBox._tempV30,0.5,OrientedBoundBox._tempV30); Vector3.add(min,OrientedBoundBox._tempV30,OrientedBoundBox._tempV31); Vector3.subtract(max,OrientedBoundBox._tempV31,OrientedBoundBox._tempV32); Matrix4x4.translation(OrientedBoundBox._tempV31,OrientedBoundBox._tempM0); var obb=new OrientedBoundBox(OrientedBoundBox._tempV32,OrientedBoundBox._tempM0); return obb; } OrientedBoundBox._getRows=function(mat,out){ out.length=3; var mate=mat.elements; var row0e=out[0].elements; row0e[0]=mate[0]; row0e[1]=mate[1]; row0e[2]=mate[2]; var row1e=out[1].elements; row1e[0]=mate[4]; row1e[1]=mate[5]; row1e[2]=mate[6]; var row2e=out[2].elements; row2e[0]=mate[8]; row2e[1]=mate[9]; row2e[2]=mate[10]; } OrientedBoundBox.getObbtoObbMatrix4x4=function(a,b,noMatrixScaleApplied,out){ var at=a.transformation; var bt=b.transformation; if (noMatrixScaleApplied){ OrientedBoundBox._getRows(at,OrientedBoundBox._rows1); OrientedBoundBox._getRows(bt,OrientedBoundBox._rows2); for (var i=0;i < 3;i++){ for (var k=0;k < 3;k++){ out.setElementByRowColumn(i,k,Vector3.dot(OrientedBoundBox._rows2[i],OrientedBoundBox._rows1[k])); } } b.getCenter(OrientedBoundBox._tempV30); a.getCenter(OrientedBoundBox._tempV31); Vector3.subtract(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV32); var AtoBMe=out.elements; AtoBMe[12]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[0]); AtoBMe[13]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[1]); AtoBMe[14]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[2]); AtoBMe[15]=1; }else { at.invert(OrientedBoundBox._tempM0); Matrix4x4.multiply(bt,OrientedBoundBox._tempM0,out); } } OrientedBoundBox.merge=function(a,b,noMatrixScaleApplied){ var ae=a.extents; var at=a.transformation; OrientedBoundBox.getObbtoObbMatrix4x4(a,b,noMatrixScaleApplied,OrientedBoundBox._tempM0); b._getLocalCorners(OrientedBoundBox._corners); Vector3.transformCoordinate(OrientedBoundBox._corners[0],OrientedBoundBox._tempM0,OrientedBoundBox._corners[0]); Vector3.transformCoordinate(OrientedBoundBox._corners[1],OrientedBoundBox._tempM0,OrientedBoundBox._corners[1]); Vector3.transformCoordinate(OrientedBoundBox._corners[2],OrientedBoundBox._tempM0,OrientedBoundBox._corners[2]); Vector3.transformCoordinate(OrientedBoundBox._corners[3],OrientedBoundBox._tempM0,OrientedBoundBox._corners[3]); Vector3.transformCoordinate(OrientedBoundBox._corners[4],OrientedBoundBox._tempM0,OrientedBoundBox._corners[4]); Vector3.transformCoordinate(OrientedBoundBox._corners[5],OrientedBoundBox._tempM0,OrientedBoundBox._corners[5]); Vector3.transformCoordinate(OrientedBoundBox._corners[6],OrientedBoundBox._tempM0,OrientedBoundBox._corners[6]); Vector3.transformCoordinate(OrientedBoundBox._corners[7],OrientedBoundBox._tempM0,OrientedBoundBox._corners[7]); Vector3.scale(ae,-1,OrientedBoundBox._boxBound1.min); ae.cloneTo(OrientedBoundBox._boxBound1.max); BoundBox.createfromPoints(OrientedBoundBox._corners,OrientedBoundBox._boxBound2); BoundBox.merge(OrientedBoundBox._boxBound2,OrientedBoundBox._boxBound1,OrientedBoundBox._boxBound3); var box3Min=OrientedBoundBox._boxBound3.min; var box3Max=OrientedBoundBox._boxBound3.max; Vector3.subtract(box3Max,box3Min,OrientedBoundBox._tempV30); Vector3.scale(OrientedBoundBox._tempV30,0.5,OrientedBoundBox._tempV30); Vector3.add(box3Min,OrientedBoundBox._tempV30,OrientedBoundBox._tempV32); Vector3.subtract(box3Max,OrientedBoundBox._tempV32,ae); Vector3.transformCoordinate(OrientedBoundBox._tempV32,at,OrientedBoundBox._tempV33); } __static(OrientedBoundBox, ['_tempV30',function(){return this._tempV30=new Vector3();},'_tempV31',function(){return this._tempV31=new Vector3();},'_tempV32',function(){return this._tempV32=new Vector3();},'_tempV33',function(){return this._tempV33=new Vector3();},'_tempV34',function(){return this._tempV34=new Vector3();},'_tempV35',function(){return this._tempV35=new Vector3();},'_tempV36',function(){return this._tempV36=new Vector3();},'_tempM0',function(){return this._tempM0=new Matrix4x4();},'_tempM1',function(){return this._tempM1=new Matrix4x4();},'_corners',function(){return this._corners=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3()];},'_rows1',function(){return this._rows1=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3()];},'_rows2',function(){return this._rows2=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3()];},'_ray',function(){return this._ray=new Ray(new Vector3(),new Vector3());},'_boxBound1',function(){return this._boxBound1=new BoundBox(new Vector3(),new Vector3());},'_boxBound2',function(){return this._boxBound2=new BoundBox(new Vector3(),new Vector3());},'_boxBound3',function(){return this._boxBound3=new BoundBox(new Vector3(),new Vector3());} ]); return OrientedBoundBox; })() /** *Plane 类用于创建平面。 */ //class laya.d3.math.Plane var Plane=(function(){ function Plane(normal,d){ /**平面的向量*/ this.normal=null; /**平面到坐标系原点的距离*/ this.distance=NaN; (d===void 0)&& (d=0); this.normal=normal; this.distance=d; } __class(Plane,'laya.d3.math.Plane'); var __proto=Plane.prototype; /** *更改平面法线向量的系数,使之成单位长度。 */ __proto.normalize=function(){ var normalE=this.normal.elements; var normalEX=normalE[0]; var normalEY=normalE[1]; var normalEZ=normalE[2]; var magnitude=1 / Math.sqrt(normalEX *normalEX+normalEY *normalEY+normalEZ *normalEZ); normalE[0]=normalEX *magnitude; normalE[1]=normalEY *magnitude; normalE[2]=normalEZ *magnitude; this.distance *=magnitude; } Plane.createPlaneBy3P=function(point1,point2,point3){ var point1e=point1.elements; var point2e=point2.elements; var point3e=point3.elements; var x1=point2e[0]-point1e[0]; var y1=point2e[1]-point1e[1]; var z1=point2e[2]-point1e[2]; var x2=point3e[0]-point1e[0]; var y2=point3e[1]-point1e[1]; var z2=point3e[2]-point1e[2]; var yz=(y1 *z2)-(z1 *y2); var xz=(z1 *x2)-(x1 *z2); var xy=(x1 *y2)-(y1 *x2); var invPyth=1 / (Math.sqrt((yz *yz)+(xz *xz)+(xy *xy))); var x=yz *invPyth; var y=xz *invPyth; var z=xy *invPyth; var TEMPVec3e=Plane._TEMPVec3.elements; TEMPVec3e[0]=x; TEMPVec3e[1]=y; TEMPVec3e[2]=z; var d=-((x *point1e[0])+(y *point1e[1])+(z *point1e[2])); var plane=new Plane(Plane._TEMPVec3,d); return plane; } Plane.PlaneIntersectionType_Back=0; Plane.PlaneIntersectionType_Front=1; Plane.PlaneIntersectionType_Intersecting=2; __static(Plane, ['_TEMPVec3',function(){return this._TEMPVec3=new Vector3();} ]); return Plane; })() /** *Quaternion 类用于创建四元数。 */ //class laya.d3.math.Quaternion var Quaternion=(function(){ function Quaternion(x,y,z,w){ this.elements=new Float32Array(4); (x===void 0)&& (x=0); (y===void 0)&& (y=0); (z===void 0)&& (z=0); (w===void 0)&& (w=1); this.elements[0]=x; this.elements[1]=y; this.elements[2]=z; this.elements[3]=w; } __class(Quaternion,'laya.d3.math.Quaternion'); var __proto=Quaternion.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *根据缩放值缩放四元数 *@param scale 缩放值 *@param out 输出四元数 */ __proto.scaling=function(scaling,out){ var e=out.elements; var f=this.elements; e[0]=f[0] *scaling; e[1]=f[1] *scaling; e[2]=f[2] *scaling; e[3]=f[3] *scaling; } /** *归一化四元数 *@param out 输出四元数 */ __proto.normalize=function(out){ var e=out.elements; var f=this.elements; var x=f[0],y=f[1],z=f[2],w=f[3]; var len=x *x+y *y+z *z+w *w; if (len > 0){ len=1 / Math.sqrt(len); e[0]=x *len; e[1]=y *len; e[2]=z *len; e[3]=w *len; } } /** *计算四元数的长度 *@return 长度 */ __proto.length=function(){ var f=this.elements; var x=f[0],y=f[1],z=f[2],w=f[3]; return Math.sqrt(x *x+y *y+z *z+w *w); } /** *根据绕X轴的角度旋转四元数 *@param rad 角度 *@param out 输出四元数 */ __proto.rotateX=function(rad,out){ var e=out.elements; var f=this.elements; rad *=0.5; var ax=f[0],ay=f[1],az=f[2],aw=f[3]; var bx=Math.sin(rad),bw=Math.cos(rad); e[0]=ax *bw+aw *bx; e[1]=ay *bw+az *bx; e[2]=az *bw-ay *bx; e[3]=aw *bw-ax *bx; } /** *根据绕Y轴的制定角度旋转四元数 *@param rad 角度 *@param out 输出四元数 */ __proto.rotateY=function(rad,out){ var e=out.elements; var f=this.elements; rad *=0.5; var ax=f[0],ay=f[1],az=f[2],aw=f[3],by=Math.sin(rad),bw=Math.cos(rad); e[0]=ax *bw-az *by; e[1]=ay *bw+aw *by; e[2]=az *bw+ax *by; e[3]=aw *bw-ay *by; } /** *根据绕Z轴的制定角度旋转四元数 *@param rad 角度 *@param out 输出四元数 */ __proto.rotateZ=function(rad,out){ var e=out.elements; var f=this.elements; rad *=0.5; var ax=f[0],ay=f[1],az=f[2],aw=f[3],bz=Math.sin(rad),bw=Math.cos(rad); e[0]=ax *bw+ay *bz; e[1]=ay *bw-ax *bz; e[2]=az *bw+aw *bz; e[3]=aw *bw-az *bz; } /** *分解四元数到欧拉角(顺序为Yaw、Pitch、Roll),参考自http://xboxforums.create.msdn.com/forums/p/4574/23988.aspx#23988,问题绕X轴翻转超过±90度时有,会产生瞬间反转 *@param quaternion 源四元数 *@param out 欧拉角值 */ __proto.getYawPitchRoll=function(out){ Vector3.transformQuat(Vector3.ForwardRH,this,Quaternion.TEMPVector31); Vector3.transformQuat(Vector3.Up,this,Quaternion.TEMPVector32); var upe=Quaternion.TEMPVector32.elements; Quaternion.angleTo(Vector3.ZERO,Quaternion.TEMPVector31,Quaternion.TEMPVector33); var anglee=Quaternion.TEMPVector33.elements; if (anglee[0]==Math.PI / 2){ anglee[1]=Quaternion.arcTanAngle(upe[2],upe[0]); anglee[2]=0; }else if (anglee[0]==-Math.PI / 2){ anglee[1]=Quaternion.arcTanAngle(-upe[2],-upe[0]); anglee[2]=0; }else { Matrix4x4.createRotationY(-anglee[1],Quaternion.TEMPMatrix0); Matrix4x4.createRotationX(-anglee[0],Quaternion.TEMPMatrix1); Vector3.transformCoordinate(Quaternion.TEMPVector32,Quaternion.TEMPMatrix0,Quaternion.TEMPVector32); Vector3.transformCoordinate(Quaternion.TEMPVector32,Quaternion.TEMPMatrix1,Quaternion.TEMPVector32); anglee[2]=Quaternion.arcTanAngle(upe[1],-upe[0]); } if (anglee[1] <=-Math.PI) anglee[1]=Math.PI; if (anglee[2] <=-Math.PI) anglee[2]=Math.PI; if (anglee[1] >=Math.PI && anglee[2] >=Math.PI){ anglee[1]=0; anglee[2]=0; anglee[0]=Math.PI-anglee[0]; }; var oe=out.elements; oe[0]=anglee[1]; oe[1]=anglee[0]; oe[2]=anglee[2]; } /** *求四元数的逆 *@param out 输出四元数 */ __proto.invert=function(out){ var e=out.elements; var f=this.elements; var a0=f[0],a1=f[1],a2=f[2],a3=f[3]; var dot=a0 *a0+a1 *a1+a2 *a2+a3 *a3; var invDot=dot ? 1.0 / dot :0; e[0]=-a0 *invDot; e[1]=-a1 *invDot; e[2]=-a2 *invDot; e[3]=a3 *invDot; } /** *设置四元数为单位算数 *@param out 输出四元数 */ __proto.identity=function(){ var e=this.elements; e[0]=0; e[1]=0; e[2]=0; e[3]=1; } /** *从Array数组拷贝值。 *@param array 数组。 *@param offset 数组偏移。 */ __proto.fromArray=function(array,offset){ (offset===void 0)&& (offset=0); this.elements[0]=array[offset+0]; this.elements[1]=array[offset+1]; this.elements[2]=array[offset+2]; this.elements[3]=array[offset+3]; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var i,s,d; s=this.elements; d=destObject.elements; if (s===d){ return; } for (i=0;i < 4;++i){ d[i]=s[i]; } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } __proto.equals=function(b){ var ae=this.elements; var be=b.elements; return MathUtils3D.nearEqual(ae[0],be[0])&& MathUtils3D.nearEqual(ae[1],be[1])&& MathUtils3D.nearEqual(ae[2],be[2])&& MathUtils3D.nearEqual(ae[3],be[3]); } /** *计算长度的平方。 *@return 长度的平方。 */ __proto.lengthSquared=function(){ var x=this.elements[0]; var y=this.elements[1]; var z=this.elements[2]; var w=this.elements[3]; return (x *x)+(y *y)+(z *z)+(w *w); } /** *获取四元数的x值 */ __getset(0,__proto,'x',function(){ return this.elements[0]; }); /** *获取四元数的y值 */ __getset(0,__proto,'y',function(){ return this.elements[1]; }); /** *获取四元数的z值 */ __getset(0,__proto,'z',function(){ return this.elements[2]; }); /** *获取四元数的w值 */ __getset(0,__proto,'w',function(){ return this.elements[3]; }); Quaternion.createFromYawPitchRoll=function(yaw,pitch,roll,out){ var halfRoll=roll *0.5; var halfPitch=pitch *0.5; var halfYaw=yaw *0.5; var sinRoll=Math.sin(halfRoll); var cosRoll=Math.cos(halfRoll); var sinPitch=Math.sin(halfPitch); var cosPitch=Math.cos(halfPitch); var sinYaw=Math.sin(halfYaw); var cosYaw=Math.cos(halfYaw); var oe=out.elements; oe[0]=(cosYaw *sinPitch *cosRoll)+(sinYaw *cosPitch *sinRoll); oe[1]=(sinYaw *cosPitch *cosRoll)-(cosYaw *sinPitch *sinRoll); oe[2]=(cosYaw *cosPitch *sinRoll)-(sinYaw *sinPitch *cosRoll); oe[3]=(cosYaw *cosPitch *cosRoll)+(sinYaw *sinPitch *sinRoll); } Quaternion.multiply=function(left,right,out){ var le=left.elements; var re=right.elements; var oe=out.elements; var lx=le[0]; var ly=le[1]; var lz=le[2]; var lw=le[3]; var rx=re[0]; var ry=re[1]; var rz=re[2]; var rw=re[3]; var a=(ly *rz-lz *ry); var b=(lz *rx-lx *rz); var c=(lx *ry-ly *rx); var d=(lx *rx+ly *ry+lz *rz); oe[0]=(lx *rw+rx *lw)+a; oe[1]=(ly *rw+ry *lw)+b; oe[2]=(lz *rw+rz *lw)+c; oe[3]=lw *rw-d; } Quaternion.arcTanAngle=function(x,y){ if (x==0){ if (y==1) return Math.PI / 2; return-Math.PI / 2; } if (x > 0) return Math.atan(y / x); if (x < 0){ if (y > 0) return Math.atan(y / x)+Math.PI; return Math.atan(y / x)-Math.PI; } return 0; } Quaternion.angleTo=function(from,location,angle){ Vector3.subtract(location,from,Quaternion.TEMPVector30); Vector3.normalize(Quaternion.TEMPVector30,Quaternion.TEMPVector30); angle.elements[0]=Math.asin(Quaternion.TEMPVector30.y); angle.elements[1]=Quaternion.arcTanAngle(-Quaternion.TEMPVector30.z,-Quaternion.TEMPVector30.x); } Quaternion.createFromAxisAngle=function(axis,rad,out){ var e=out.elements; var f=axis.elements; rad=rad *0.5; var s=Math.sin(rad); e[0]=s *f[0]; e[1]=s *f[1]; e[2]=s *f[2]; e[3]=Math.cos(rad); } Quaternion.createFromMatrix3x3=function(sou,out){ var e=out.elements; var f=sou.elements; var fTrace=f[0]+f[4]+f[8]; var fRoot; if (fTrace > 0.0){ fRoot=Math.sqrt(fTrace+1.0); e[3]=0.5 *fRoot; fRoot=0.5 / fRoot; e[0]=(f[5]-f[7])*fRoot; e[1]=(f[6]-f[2])*fRoot; e[2]=(f[1]-f[3])*fRoot; }else { var i=0; if (f[4] > f[0]) i=1; if (f[8] > f[i *3+i]) i=2; var j=(i+1)% 3; var k=(i+2)% 3; fRoot=Math.sqrt(f[i *3+i]-f[j *3+j]-f[k *3+k]+1.0); e[i]=0.5 *fRoot; fRoot=0.5 / fRoot; e[3]=(f[j *3+k]-f[k *3+j])*fRoot; e[j]=(f[j *3+i]+f[i *3+j])*fRoot; e[k]=(f[k *3+i]+f[i *3+k])*fRoot; } return; } Quaternion.createFromMatrix4x4=function(mat,out){ var me=mat.elements; var oe=out.elements; var sqrt; var half; var scale=me[0]+me[5]+me[10]; if (scale > 0.0){ sqrt=Math.sqrt(scale+1.0); oe[3]=sqrt *0.5; sqrt=0.5 / sqrt; oe[0]=(me[6]-me[9])*sqrt; oe[1]=(me[8]-me[2])*sqrt; oe[2]=(me[1]-me[4])*sqrt; }else if ((me[0] >=me[5])&& (me[0] >=me[10])){ sqrt=Math.sqrt(1.0+me[0]-me[5]-me[10]); half=0.5 / sqrt; oe[0]=0.5 *sqrt; oe[1]=(me[1]+me[4])*half; oe[2]=(me[2]+me[8])*half; oe[3]=(me[6]-me[9])*half; }else if (me[5] > me[10]){ sqrt=Math.sqrt(1.0+me[5]-me[0]-me[10]); half=0.5 / sqrt; oe[0]=(me[4]+me[1])*half; oe[1]=0.5 *sqrt; oe[2]=(me[9]+me[6])*half; oe[3]=(me[8]-me[2])*half; }else { sqrt=Math.sqrt(1.0+me[10]-me[0]-me[5]); half=0.5 / sqrt; oe[0]=(me[8]+me[2])*half; oe[1]=(me[9]+me[6])*half; oe[2]=0.5 *sqrt; oe[3]=(me[1]-me[4])*half; } } Quaternion.slerp=function(left,right,t,out){ var a=left.elements; var b=right.elements; var oe=out.elements; var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=b[3]; var omega,cosom,sinom,scale0,scale1; cosom=ax *bx+ay *by+az *bz+aw *bw; if (cosom < 0.0){ cosom=-cosom; bx=-bx; by=-by; bz=-bz; bw=-bw; } if ((1.0-cosom)> 0.000001){ omega=Math.acos(cosom); sinom=Math.sin(omega); scale0=Math.sin((1.0-t)*omega)/ sinom; scale1=Math.sin(t *omega)/ sinom; }else { scale0=1.0-t; scale1=t; } oe[0]=scale0 *ax+scale1 *bx; oe[1]=scale0 *ay+scale1 *by; oe[2]=scale0 *az+scale1 *bz; oe[3]=scale0 *aw+scale1 *bw; return oe; } Quaternion.lerp=function(left,right,t,out){ var e=out.elements; var f=left.elements; var g=right.elements; var ax=f[0],ay=f[1],az=f[2],aw=f[3]; e[0]=ax+t *(g[0]-ax); e[1]=ay+t *(g[1]-ay); e[2]=az+t *(g[2]-az); e[3]=aw+t *(g[3]-aw); } Quaternion.add=function(left,right,out){ var e=out.elements; var f=left.elements; var g=right.elements; e[0]=f[0]+g[0]; e[1]=f[1]+g[1]; e[2]=f[2]+g[2]; e[3]=f[3]+g[3]; } Quaternion.dot=function(left,right){ var f=left.elements; var g=right.elements; return f[0] *g[0]+f[1] *g[1]+f[2] *g[2]+f[3] *g[3]; } Quaternion.rotationLookAt=function(forward,up,out){ Quaternion.lookAt(Vector3.ZERO,forward,up,out); } Quaternion.lookAt=function(eye,target,up,out){ Matrix3x3.lookAt(eye,target,up,Quaternion._tempMatrix3x3); Quaternion.rotationMatrix(Quaternion._tempMatrix3x3,out); } Quaternion.invert=function(value,out){ var vE=value.elements; var oE=out.elements; var lengthSq=value.lengthSquared(); if (!MathUtils3D.isZero(lengthSq)){ lengthSq=1.0 / lengthSq; oE[0]=-vE[0] *lengthSq; oE[1]=-vE[1] *lengthSq; oE[2]=-vE[2] *lengthSq; oE[3]=vE[3] *lengthSq; } } Quaternion.rotationMatrix=function(matrix3x3,out){ var me=matrix3x3.elements; var m11=me[0]; var m12=me[1]; var m13=me[2]; var m21=me[3]; var m22=me[4]; var m23=me[5]; var m31=me[6]; var m32=me[7]; var m33=me[8]; var oe=out.elements; var sqrt=NaN,half=NaN; var scale=m11+m22+m33; if (scale > 0){ sqrt=Math.sqrt(scale+1); oe[3]=sqrt *0.5; sqrt=0.5 / sqrt; oe[0]=(m23-m32)*sqrt; oe[1]=(m31-m13)*sqrt; oe[2]=(m12-m21)*sqrt; }else if ((m11 >=m22)&& (m11 >=m33)){ sqrt=Math.sqrt(1+m11-m22-m33); half=0.5 / sqrt; oe[0]=0.5 *sqrt; oe[1]=(m12+m21)*half; oe[2]=(m13+m31)*half; oe[3]=(m23-m32)*half; }else if (m22 > m33){ sqrt=Math.sqrt(1+m22-m11-m33); half=0.5 / sqrt; oe[0]=(m21+m12)*half; oe[1]=0.5 *sqrt; oe[2]=(m32+m23)*half; oe[3]=(m31-m13)*half; }else { sqrt=Math.sqrt(1+m33-m11-m22); half=0.5 / sqrt; oe[0]=(m31+m13)*half; oe[1]=(m32+m23)*half; oe[2]=0.5 *sqrt; oe[3]=(m12-m21)*half; } } Quaternion.DEFAULT=new Quaternion(); __static(Quaternion, ['TEMPVector30',function(){return this.TEMPVector30=new Vector3();},'TEMPVector31',function(){return this.TEMPVector31=new Vector3();},'TEMPVector32',function(){return this.TEMPVector32=new Vector3();},'TEMPVector33',function(){return this.TEMPVector33=new Vector3();},'TEMPMatrix0',function(){return this.TEMPMatrix0=new Matrix4x4();},'TEMPMatrix1',function(){return this.TEMPMatrix1=new Matrix4x4();},'_tempMatrix3x3',function(){return this._tempMatrix3x3=new Matrix3x3();},'NAN',function(){return this.NAN=new Quaternion(NaN,NaN,NaN,NaN);} ]); return Quaternion; })() /** *Rand 类用于通过32位无符号整型随机种子创建随机数。 */ //class laya.d3.math.Rand var Rand=(function(){ function Rand(seed){ this._temp=new Uint32Array(1); this.seeds=new Uint32Array(4); this.seeds[0]=seed; this.seeds[1]=this.seeds[0] *0x6C078965+1; this.seeds[2]=this.seeds[1] *0x6C078965+1; this.seeds[3]=this.seeds[2] *0x6C078965+1; } __class(Rand,'laya.d3.math.Rand'); var __proto=Rand.prototype; /** *获取无符号32位整形随机数。 *@return 无符号32位整形随机数。 */ __proto.getUint=function(){ this._temp[0]=this.seeds[0] ^ (this.seeds[0] << 11); this.seeds[0]=this.seeds[1]; this.seeds[1]=this.seeds[2]; this.seeds[2]=this.seeds[3]; this.seeds[3]=(this.seeds[3] ^ (this.seeds[3] >>> 19))^ (this._temp[0] ^ (this._temp[0] >>> 8)); return this.seeds[3]; } /** *获取0到1之间的浮点随机数。 *@return 0到1之间的浮点随机数。 */ __proto.getFloat=function(){ this.getUint(); return (this.seeds[3] & 0x007FFFFF)*(1.0 / 8388607.0); } /** *获取-1到1之间的浮点随机数。 *@return-1到1之间的浮点随机数。 */ __proto.getSignedFloat=function(){ return this.getFloat()*2.0-1.0; } /** *设置随机种子。 *@param seed 随机种子。 */ /** *获取随机种子。 *@return 随机种子。 */ __getset(0,__proto,'seed',function(){ return this.seeds[0]; },function(seed){ this.seeds[0]=seed; this.seeds[1]=this.seeds[0] *0x6C078965+1; this.seeds[2]=this.seeds[1] *0x6C078965+1; this.seeds[3]=this.seeds[2] *0x6C078965+1; }); Rand.getFloatFromInt=function(v){ return (v & 0x007FFFFF)*(1.0 / 8388607.0) } Rand.getByteFromInt=function(v){ return (v & 0x007FFFFF)>>> 15; } return Rand; })() /** *Rand 类用于通过128位整型种子创建随机数,算法来自:https://github.com/AndreasMadsen/xorshift。 */ //class laya.d3.math.RandX var RandX=(function(){ function RandX(seed){ /**@private */ this._state0U=NaN; /**@private */ this._state0L=NaN; /**@private */ this._state1U=NaN; /**@private */ this._state1L=NaN; if (!((seed instanceof Array))|| seed.length!==4) throw new Error('Rand:Seed must be an array with 4 numbers'); this._state0U=seed[0] | 0; this._state0L=seed[1] | 0; this._state1U=seed[2] | 0; this._state1L=seed[3] | 0; } __class(RandX,'laya.d3.math.RandX'); var __proto=RandX.prototype; /** *通过2x32位的数组,返回64位的随机数。 *@return 64位的随机数。 */ __proto.randomint=function(){ var s1U=this._state0U,s1L=this._state0L; var s0U=this._state1U,s0L=this._state1L; var sumL=(s0L >>> 0)+(s1L >>> 0); var resU=(s0U+s1U+(sumL / 2 >>> 31))>>> 0; var resL=sumL >>> 0; this._state0U=s0U; this._state0L=s0L; var t1U=0,t1L=0; var t2U=0,t2L=0; var a1=23; var m1=0xFFFFFFFF << (32-a1); t1U=(s1U << a1)| ((s1L & m1)>>> (32-a1)); t1L=s1L << a1; s1U=s1U ^ t1U; s1L=s1L ^ t1L; t1U=s1U ^ s0U; t1L=s1L ^ s0L; var a2=18; var m2=0xFFFFFFFF >>> (32-a2); t2U=s1U >>> a2; t2L=(s1L >>> a2)| ((s1U & m2)<< (32-a2)); t1U=t1U ^ t2U; t1L=t1L ^ t2L; var a3=5; var m3=0xFFFFFFFF >>> (32-a3); t2U=s0U >>> a3; t2L=(s0L >>> a3)| ((s0U & m3)<< (32-a3)); t1U=t1U ^ t2U; t1L=t1L ^ t2L; this._state1U=t1U; this._state1L=t1L; return [resU,resL]; } /** *返回[0,1)之间的随机数。 *@return */ __proto.random=function(){ var t2=this.randomint(); var t2U=t2[0]; var t2L=t2[1]; var eU=0x3FF << (52-32); var eL=0; var a1=12; var m1=0xFFFFFFFF >>> (32-a1); var sU=t2U >>> a1; var sL=(t2L >>> a1)| ((t2U & m1)<< (32-a1)); var xU=eU | sU; var xL=eL | sL; RandX._CONVERTION_BUFFER.setUint32(0,xU,false); RandX._CONVERTION_BUFFER.setUint32(4,xL,false); var d=/*__JS__ */Rand._CONVERTION_BUFFER.getFloat64(0,false); return d-1; } __static(RandX, ['_CONVERTION_BUFFER',function(){return this._CONVERTION_BUFFER=new DataView(new ArrayBuffer(8));},'defaultRand',function(){return this.defaultRand=/*__JS__ */new Rand([0,Date.now()/ 65536,0,Date.now()% 65536]);} ]); return RandX; })() /** *Ray 类用于创建射线。 */ //class laya.d3.math.Ray var Ray=(function(){ function Ray(origin,direction){ /**原点*/ this.origin=null; /**方向*/ this.direction=null; this.origin=origin; this.direction=direction; } __class(Ray,'laya.d3.math.Ray'); return Ray; })() /** *Vector2 类用于创建二维向量。 */ //class laya.d3.math.Vector2 var Vector2=(function(){ function Vector2(x,y){ this.elements=new Float32Array(2); (x===void 0)&& (x=0); (y===void 0)&& (y=0); var v=this.elements; v[0]=x; v[1]=y; } __class(Vector2,'laya.d3.math.Vector2'); var __proto=Vector2.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *从Array数组拷贝值。 *@param array 数组。 *@param offset 数组偏移。 */ __proto.fromArray=function(array,offset){ (offset===void 0)&& (offset=0); this.elements[0]=array[offset+0]; this.elements[1]=array[offset+1]; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destVector2=destObject; var destE=destVector2.elements; var s=this.elements; destE[0]=s[0]; destE[1]=s[1]; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destVector2=/*__JS__ */new this.constructor(); this.cloneTo(destVector2); return destVector2; } /** *设置X轴坐标。 *@param value X轴坐标。 */ /** *获取X轴坐标。 *@return X轴坐标。 */ __getset(0,__proto,'x',function(){ return this.elements[0]; },function(value){ this.elements[0]=value; }); /** *设置Y轴坐标。 *@param value Y轴坐标。 */ /** *获取Y轴坐标。 *@return Y轴坐标。 */ __getset(0,__proto,'y',function(){ return this.elements[1]; },function(value){ this.elements[1]=value; }); Vector2.scale=function(a,b,out){ var e=out.elements; var f=a.elements; e[0]=f[0] *b; e[1]=f[1] *b; } __static(Vector2, ['ZERO',function(){return this.ZERO=new Vector2(0.0,0.0);},'ONE',function(){return this.ONE=new Vector2(1.0,1.0);} ]); return Vector2; })() /** *Vector3 类用于创建三维向量。 */ //class laya.d3.math.Vector3 var Vector3=(function(){ function Vector3(x,y,z){ this.elements=new Float32Array(3); (x===void 0)&& (x=0); (y===void 0)&& (y=0); (z===void 0)&& (z=0); var v=this.elements; v[0]=x; v[1]=y; v[2]=z; } __class(Vector3,'laya.d3.math.Vector3'); var __proto=Vector3.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *从Array数组拷贝值。 *@param array 数组。 *@param offset 数组偏移。 */ __proto.fromArray=function(array,offset){ (offset===void 0)&& (offset=0); this.elements[0]=array[offset+0]; this.elements[1]=array[offset+1]; this.elements[2]=array[offset+2]; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destVector3=destObject; var destE=destVector3.elements; var s=this.elements; destE[0]=s[0]; destE[1]=s[1]; destE[2]=s[2]; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destVector3=/*__JS__ */new this.constructor(); this.cloneTo(destVector3); return destVector3; } __proto.toDefault=function(){ this.elements[0]=0; this.elements[1]=0; this.elements[2]=0; } /** *设置X轴坐标。 *@param value X轴坐标。 */ /** *获取X轴坐标。 *@return X轴坐标。 */ __getset(0,__proto,'x',function(){ return this.elements[0]; },function(value){ this.elements[0]=value; }); /** *设置Y轴坐标。 *@param value Y轴坐标。 */ /** *获取Y轴坐标。 *@return Y轴坐标。 */ __getset(0,__proto,'y',function(){ return this.elements[1]; },function(value){ this.elements[1]=value; }); /** *设置Z轴坐标。 *@param value Z轴坐标。 */ /** *获取Z轴坐标。 *@return Z轴坐标。 */ __getset(0,__proto,'z',function(){ return this.elements[2]; },function(value){ this.elements[2]=value; }); Vector3.distanceSquared=function(value1,value2){ var value1e=value1.elements; var value2e=value2.elements; var x=value1e[0]-value2e[0]; var y=value1e[1]-value2e[1]; var z=value1e[2]-value2e[2]; return (x *x)+(y *y)+(z *z); } Vector3.distance=function(value1,value2){ var value1e=value1.elements; var value2e=value2.elements; var x=value1e[0]-value2e[0]; var y=value1e[1]-value2e[1]; var z=value1e[2]-value2e[2]; return Math.sqrt((x *x)+(y *y)+(z *z)); } Vector3.min=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=Math.min(f[0],g[0]); e[1]=Math.min(f[1],g[1]); e[2]=Math.min(f[2],g[2]); } Vector3.max=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=Math.max(f[0],g[0]); e[1]=Math.max(f[1],g[1]); e[2]=Math.max(f[2],g[2]); } Vector3.transformQuat=function(source,rotation,out){ var destination=out.elements; var se=source.elements; var re=rotation.elements; var x=se[0],y=se[1],z=se[2],qx=re[0],qy=re[1],qz=re[2],qw=re[3], ix=qw *x+qy *z-qz *y,iy=qw *y+qz *x-qx *z,iz=qw *z+qx *y-qy *x,iw=-qx *x-qy *y-qz *z; destination[0]=ix *qw+iw *-qx+iy *-qz-iz *-qy; destination[1]=iy *qw+iw *-qy+iz *-qx-ix *-qz; destination[2]=iz *qw+iw *-qz+ix *-qy-iy *-qx; } Vector3.scalarLength=function(a){ var f=a.elements; var x=f[0],y=f[1],z=f[2]; return Math.sqrt(x *x+y *y+z *z); } Vector3.scalarLengthSquared=function(a){ var f=a.elements; var x=f[0],y=f[1],z=f[2]; return x *x+y *y+z *z; } Vector3.normalize=function(s,out){ var se=s.elements; var oe=out.elements; var x=se[0],y=se[1],z=se[2]; var len=x *x+y *y+z *z; if (len > 0){ len=1 / Math.sqrt(len); oe[0]=se[0] *len; oe[1]=se[1] *len; oe[2]=se[2] *len; } } Vector3.multiply=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=f[0] *g[0]; e[1]=f[1] *g[1]; e[2]=f[2] *g[2]; } Vector3.scale=function(a,b,out){ var e=out.elements; var f=a.elements; e[0]=f[0] *b; e[1]=f[1] *b; e[2]=f[2] *b; } Vector3.lerp=function(a,b,t,out){ var e=out.elements; var f=a.elements; var g=b.elements; var ax=f[0],ay=f[1],az=f[2]; e[0]=ax+t *(g[0]-ax); e[1]=ay+t *(g[1]-ay); e[2]=az+t *(g[2]-az); } Vector3.transformV3ToV3=function(vector,transform,result){ var intermediate=Vector3._tempVector4; Vector3.transformV3ToV4(vector,transform,intermediate); var intermediateElem=intermediate.elements; var resultElem=result.elements; resultElem[0]=intermediateElem[0]; resultElem[1]=intermediateElem[1]; resultElem[2]=intermediateElem[2]; } Vector3.transformV3ToV4=function(vector,transform,result){ var vectorElem=vector.elements; var vectorX=vectorElem[0]; var vectorY=vectorElem[1]; var vectorZ=vectorElem[2]; var transformElem=transform.elements; var resultElem=result.elements; resultElem[0]=(vectorX *transformElem[0])+(vectorY *transformElem[4])+(vectorZ *transformElem[8])+transformElem[12]; resultElem[1]=(vectorX *transformElem[1])+(vectorY *transformElem[5])+(vectorZ *transformElem[9])+transformElem[13]; resultElem[2]=(vectorX *transformElem[2])+(vectorY *transformElem[6])+(vectorZ *transformElem[10])+transformElem[14]; resultElem[3]=(vectorX *transformElem[3])+(vectorY *transformElem[7])+(vectorZ *transformElem[11])+transformElem[15]; } Vector3.TransformNormal=function(normal,transform,result){ var normalElem=normal.elements; var normalX=normalElem[0]; var normalY=normalElem[1]; var normalZ=normalElem[2]; var transformElem=transform.elements; var resultElem=result.elements; resultElem[0]=(normalX *transformElem[0])+(normalY *transformElem[4])+(normalZ *transformElem[8]); resultElem[1]=(normalX *transformElem[1])+(normalY *transformElem[5])+(normalZ *transformElem[9]); resultElem[2]=(normalX *transformElem[2])+(normalY *transformElem[6])+(normalZ *transformElem[10]); } Vector3.transformCoordinate=function(coordinate,transform,result){ var vectorElem=Vector3._tempVector4.elements; var coordinateElem=coordinate.elements; var coordinateX=coordinateElem[0]; var coordinateY=coordinateElem[1]; var coordinateZ=coordinateElem[2]; var transformElem=transform.elements; vectorElem[0]=(coordinateX *transformElem[0])+(coordinateY *transformElem[4])+(coordinateZ *transformElem[8])+transformElem[12]; vectorElem[1]=(coordinateX *transformElem[1])+(coordinateY *transformElem[5])+(coordinateZ *transformElem[9])+transformElem[13]; vectorElem[2]=(coordinateX *transformElem[2])+(coordinateY *transformElem[6])+(coordinateZ *transformElem[10])+transformElem[14]; vectorElem[3]=1.0 / ((coordinateX *transformElem[3])+(coordinateY *transformElem[7])+(coordinateZ *transformElem[11])+transformElem[15]); var resultElem=result.elements; resultElem[0]=vectorElem[0] *vectorElem[3]; resultElem[1]=vectorElem[1] *vectorElem[3]; resultElem[2]=vectorElem[2] *vectorElem[3]; } Vector3.Clamp=function(value,min,max,out){ var valuee=value.elements; var x=valuee[0]; var y=valuee[1]; var z=valuee[2]; var mine=min.elements; var mineX=mine[0]; var mineY=mine[1]; var mineZ=mine[2]; var maxe=max.elements; var maxeX=maxe[0]; var maxeY=maxe[1]; var maxeZ=maxe[2]; var oute=out.elements; x=(x > maxeX)? maxeX :x; x=(x < mineX)? mineX :x; y=(y > maxeY)? maxeY :y; y=(y < mineY)? mineY :y; z=(z > maxeZ)? maxeZ :z; z=(z < mineZ)? mineZ :z; oute[0]=x; oute[1]=y; oute[2]=z; } Vector3.add=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=f[0]+g[0]; e[1]=f[1]+g[1]; e[2]=f[2]+g[2]; } Vector3.subtract=function(a,b,o){ var oe=o.elements; var ae=a.elements; var be=b.elements; oe[0]=ae[0]-be[0]; oe[1]=ae[1]-be[1]; oe[2]=ae[2]-be[2]; } Vector3.cross=function(a,b,o){ var ae=a.elements; var be=b.elements; var oe=o.elements; var ax=ae[0],ay=ae[1],az=ae[2],bx=be[0],by=be[1],bz=be[2]; oe[0]=ay *bz-az *by; oe[1]=az *bx-ax *bz; oe[2]=ax *by-ay *bx; } Vector3.dot=function(a,b){ var ae=a.elements; var be=b.elements; var r=(ae[0] *be[0])+(ae[1] *be[1])+(ae[2] *be[2]); return r; } Vector3.equals=function(a,b){ var ae=a.elements; var be=b.elements; return MathUtils3D.nearEqual(Math.abs(ae[0]),Math.abs(be[0]))&& MathUtils3D.nearEqual(Math.abs(ae[1]),Math.abs(be[1]))&& MathUtils3D.nearEqual(Math.abs(ae[2]),Math.abs(be[2])); } Vector3.ZERO=new Vector3(0.0,0.0,0.0); Vector3.ONE=new Vector3(1.0,1.0,1.0); Vector3.NegativeUnitX=new Vector3(-1,0,0); Vector3.UnitX=new Vector3(1,0,0); Vector3.UnitY=new Vector3(0,1,0); Vector3.UnitZ=new Vector3(0,0,1); Vector3.ForwardRH=new Vector3(0,0,-1); Vector3.ForwardLH=new Vector3(0,0,1); Vector3.Up=new Vector3(0,1,0); Vector3.NAN=new Vector3(NaN,NaN,NaN); __static(Vector3, ['_tempVector4',function(){return this._tempVector4=new Vector4();} ]); return Vector3; })() /** *Vector4 类用于创建四维向量。 */ //class laya.d3.math.Vector4 var Vector4=(function(){ function Vector4(x,y,z,w){ this.elements=new Float32Array(4); (x===void 0)&& (x=0); (y===void 0)&& (y=0); (z===void 0)&& (z=0); (w===void 0)&& (w=0); var v=this.elements; v[0]=x; v[1]=y; v[2]=z; v[3]=w; } __class(Vector4,'laya.d3.math.Vector4'); var __proto=Vector4.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *从Array数组拷贝值。 *@param array 数组。 *@param offset 数组偏移。 */ __proto.fromArray=function(array,offset){ (offset===void 0)&& (offset=0); this.elements[0]=array[offset+0]; this.elements[1]=array[offset+1]; this.elements[2]=array[offset+2]; this.elements[3]=array[offset+3]; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destVector4=destObject; var destE=destVector4.elements; var s=this.elements; destE[0]=s[0]; destE[1]=s[1]; destE[2]=s[2]; destE[3]=s[3]; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destVector4=/*__JS__ */new this.constructor(); this.cloneTo(destVector4); return destVector4; } /** *求四维向量的长度。 *@return 长度。 */ __proto.length=function(){ return Math.sqrt(this.x *this.x+this.y *this.y+this.z *this.z+this.w *this.w); } /** *求四维向量长度的平方。 *@return 长度的平方。 */ __proto.lengthSquared=function(){ return this.x *this.x+this.y *this.y+this.z *this.z+this.w *this.w; } /** *设置X轴坐标。 *@param value X轴坐标。 */ /** *获取X轴坐标。 *@return X轴坐标。 */ __getset(0,__proto,'x',function(){ return this.elements[0]; },function(value){ this.elements[0]=value; }); /** *设置Y轴坐标。 *@param value Y轴坐标。 */ /** *获取Y轴坐标。 *@return Y轴坐标。 */ __getset(0,__proto,'y',function(){ return this.elements[1]; },function(value){ this.elements[1]=value; }); /** *设置Z轴坐标。 *@param value Z轴坐标。 */ /** *获取Z轴坐标。 *@return Z轴坐标。 */ __getset(0,__proto,'z',function(){ return this.elements[2]; },function(value){ this.elements[2]=value; }); /** *设置W轴坐标。 *@param value W轴坐标。 */ /** *获取W轴坐标。 *@return W轴坐标。 */ __getset(0,__proto,'w',function(){ return this.elements[3]; },function(value){ this.elements[3]=value; }); Vector4.lerp=function(a,b,t,out){ var e=out.elements; var f=a.elements; var g=b.elements; var ax=f[0],ay=f[1],az=f[2],aw=f[3]; e[0]=ax+t *(g[0]-ax); e[1]=ay+t *(g[1]-ay); e[2]=az+t *(g[2]-az); e[3]=aw+t *(g[3]-aw); } Vector4.transformByM4x4=function(vector4,m4x4,out){ var ve=vector4.elements; var vx=ve[0]; var vy=ve[1]; var vz=ve[2]; var vw=ve[3]; var me=m4x4.elements; var oe=out.elements; oe[0]=vx *me[0]+vy *me[4]+vz *me[8]+vw *me[12]; oe[1]=vx *me[1]+vy *me[5]+vz *me[9]+vw *me[13]; oe[2]=vx *me[2]+vy *me[6]+vz *me[10]+vw *me[14]; oe[3]=vx *me[3]+vy *me[7]+vz *me[11]+vw *me[15]; } Vector4.equals=function(a,b){ var ae=a.elements; var be=b.elements; return MathUtils3D.nearEqual(Math.abs(ae[0]),Math.abs(be[0]))&& MathUtils3D.nearEqual(Math.abs(ae[1]),Math.abs(be[1]))&& MathUtils3D.nearEqual(Math.abs(ae[2]),Math.abs(be[2]))&& MathUtils3D.nearEqual(Math.abs(ae[3]),Math.abs(be[3])); } Vector4.normalize=function(s,out){ var se=s.elements; var oe=out.elements; var len=/*if err,please use iflash.method.xmlLength()*/s.length(); if (len > 0){ oe[0]=se[0] *len; oe[1]=se[1] *len; oe[2]=se[2] *len; oe[3]=se[3] *len; } } Vector4.add=function(a,b,out){ var oe=out.elements; var ae=a.elements; var be=b.elements; oe[0]=ae[0]+be[0]; oe[1]=ae[1]+be[1]; oe[2]=ae[2]+be[2]; oe[3]=ae[3]+be[3]; } Vector4.subtract=function(a,b,out){ var oe=out.elements; var ae=a.elements; var be=b.elements; oe[0]=ae[0]-be[0]; oe[1]=ae[1]-be[1]; oe[2]=ae[2]-be[2]; oe[3]=ae[3]-be[3]; } Vector4.multiply=function(a,b,out){ var oe=out.elements; var ae=a.elements; var be=b.elements; oe[0]=ae[0] *be[0]; oe[1]=ae[1] *be[1]; oe[2]=ae[2] *be[2]; oe[3]=ae[3] *be[3]; } Vector4.scale=function(a,b,out){ var oe=out.elements; var ae=a.elements; oe[0]=ae[0] *b; oe[1]=ae[1] *b; oe[2]=ae[2] *b; oe[3]=ae[3] *b; } Vector4.Clamp=function(value,min,max,out){ var valuee=value.elements; var x=valuee[0]; var y=valuee[1]; var z=valuee[2]; var w=valuee[3]; var mine=min.elements; var mineX=mine[0]; var mineY=mine[1]; var mineZ=mine[2]; var mineW=mine[3]; var maxe=max.elements; var maxeX=maxe[0]; var maxeY=maxe[1]; var maxeZ=maxe[2]; var maxeW=maxe[3]; var oute=out.elements; x=(x > maxeX)? maxeX :x; x=(x < mineX)? mineX :x; y=(y > maxeY)? maxeY :y; y=(y < mineY)? mineY :y; z=(z > maxeZ)? maxeZ :z; z=(z < mineZ)? mineZ :z; w=(w > maxeW)? maxeW :w; w=(w < mineW)? mineW :w; oute[0]=x; oute[1]=y; oute[2]=z; oute[3]=w; } Vector4.distanceSquared=function(value1,value2){ var value1e=value1.elements; var value2e=value2.elements; var x=value1e[0]-value2e[0]; var y=value1e[1]-value2e[1]; var z=value1e[2]-value2e[2]; var w=value1e[3]-value2e[3]; return (x *x)+(y *y)+(z *z)+(w *w); } Vector4.distance=function(value1,value2){ var value1e=value1.elements; var value2e=value2.elements; var x=value1e[0]-value2e[0]; var y=value1e[1]-value2e[1]; var z=value1e[2]-value2e[2]; var w=value1e[3]-value2e[3]; return Math.sqrt((x *x)+(y *y)+(z *z)+(w *w)); } Vector4.dot=function(a,b){ var ae=a.elements; var be=b.elements; var r=(ae[0] *be[0])+(ae[1] *be[1])+(ae[2] *be[2])+(ae[3] *be[3]); return r; } Vector4.min=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=Math.min(f[0],g[0]); e[1]=Math.min(f[1],g[1]); e[2]=Math.min(f[2],g[2]); e[3]=Math.min(f[3],g[3]); } Vector4.max=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=Math.max(f[0],g[0]); e[1]=Math.max(f[1],g[1]); e[2]=Math.max(f[2],g[2]); e[3]=Math.max(f[3],g[3]); } __static(Vector4, ['ZERO',function(){return this.ZERO=new Vector4();},'ONE',function(){return this.ONE=new Vector4(1.0,1.0,1.0,1.0);},'UnitX',function(){return this.UnitX=new Vector4(1.0,0.0,0.0,0.0);},'UnitY',function(){return this.UnitY=new Vector4(0.0,1.0,0.0,0.0);},'UnitZ',function(){return this.UnitZ=new Vector4(0.0,0.0,1.0,0.0);},'UnitW',function(){return this.UnitW=new Vector4(0.0,0.0,0.0,1.0);} ]); return Vector4; })() /** *Viewport 类用于创建视口。 */ //class laya.d3.math.Viewport var Viewport=(function(){ function Viewport(x,y,width,height){ /**X轴坐标*/ //this.x=NaN; /**Y轴坐标*/ //this.y=NaN; /**宽度*/ //this.width=NaN; /**高度*/ //this.height=NaN; /**最小深度*/ //this.minDepth=NaN; /**最大深度*/ //this.maxDepth=NaN; this.minDepth=0.0; this.maxDepth=1.0; this.x=x; this.y=y; this.width=width; this.height=height; } __class(Viewport,'laya.d3.math.Viewport'); var __proto=Viewport.prototype; /** *变换一个三维向量。 *@param source 源三维向量。 *@param matrix 变换矩阵。 *@param vector 输出三维向量。 */ __proto.project=function(source,matrix,out){ Vector3.transformV3ToV3(source,matrix,out); var sourceEleme=source.elements; var matrixEleme=matrix.elements; var outEleme=out.elements; var a=(((sourceEleme[0] *matrixEleme[3])+(sourceEleme[1] *matrixEleme[7]))+(sourceEleme[2] *matrixEleme[11]))+matrixEleme[15]; if (a!==1.0){ outEleme[0]=outEleme[0] / a; outEleme[1]=outEleme[1] / a; outEleme[2]=outEleme[2] / a; } outEleme[0]=(((outEleme[0]+1.0)*0.5)*this.width)+this.x; outEleme[1]=(((-outEleme[1]+1.0)*0.5)*this.height)+this.y; outEleme[2]=(outEleme[2] *(this.maxDepth-this.minDepth))+this.minDepth; } /** *反变换一个三维向量。 *@param source 源三维向量。 *@param matrix 变换矩阵。 *@param vector 输出三维向量。 */ __proto.unprojectFromMat=function(source,matrix,out){ var sourceEleme=source.elements; var matrixEleme=matrix.elements; var outEleme=out.elements; outEleme[0]=(((sourceEleme[0]-this.x)/ (this.width))*2.0)-1.0; outEleme[1]=-((((sourceEleme[1]-this.y)/ (this.height))*2.0)-1.0); var halfDepth=(this.maxDepth-this.minDepth)/ 2; outEleme[2]=(sourceEleme[2]-this.minDepth-halfDepth)/ halfDepth; var a=(((outEleme[0] *matrixEleme[3])+(outEleme[1] *matrixEleme[7]))+(outEleme[2] *matrixEleme[11]))+matrixEleme[15]; Vector3.transformV3ToV3(out,matrix,out); if (a!==1.0){ outEleme[0]=outEleme[0] / a; outEleme[1]=outEleme[1] / a; outEleme[2]=outEleme[2] / a; } } /** *反变换一个三维向量。 *@param source 源三维向量。 *@param projection 透视投影矩阵。 *@param view 视图矩阵。 *@param world 世界矩阵,可设置为null。 *@param out 输出向量。 */ __proto.unprojectFromWVP=function(source,projection,view,world,out){ Matrix4x4.multiply(projection,view,Viewport._tempMatrix4x4); (world)&& (Matrix4x4.multiply(Viewport._tempMatrix4x4,world,Viewport._tempMatrix4x4)); Viewport._tempMatrix4x4.invert(Viewport._tempMatrix4x4); this.unprojectFromMat(source,Viewport._tempMatrix4x4,out); } __static(Viewport, ['_tempMatrix4x4',function(){return this._tempMatrix4x4=new Matrix4x4();} ]); return Viewport; })() /** *Sky 类用于创建天空的父类,抽象类不允许实例。 */ //class laya.d3.resource.models.Sky var Sky=(function(){ function Sky(){ /**@private */ //this.__ownerCamera=null; /**@private 透明混合度。 */ this._alphaBlending=1.0; /**@private 颜色强度。 */ this._colorIntensity=1.0; /**@private */ //this._vertexBuffer=null; /**@private */ //this._indexBuffer=null; /**@private */ //this._sharderNameID=0; /**@private */ //this._shader=null; /**@private */ //this._shaderValue=null; /**@private */ //this._shaderCompile=null; /**@private */ //this._environmentDiffuse=null; /**@private */ //this._environmentSpecular=null; ; this._shaderValue=new ValusArray(); } __class(Sky,'laya.d3.resource.models.Sky'); var __proto=Sky.prototype; /** *@private */ __proto._setEnvironmentDiffuse=function(){ if (this._environmentDiffuse.loaded){ this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.ENVIRONMENTDIFFUSE*/7,this._environmentDiffuse); }else { this._environmentDiffuse.on(/*laya.events.Event.LOADED*/"loaded",this,this._environmentDiffuseLoaded); } } /** *@private */ __proto._setEnvironmentSpecular=function(){ if (this._environmentSpecular.loaded){ var si=this._environmentSpecular['simLodInfo']; if (si && (si instanceof Float32Array)) this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.SIMLODINFO*/9,si); this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.ENVIRONMENTSPECULAR*/8,this._environmentSpecular); }else { this._environmentSpecular.on(/*laya.events.Event.LOADED*/"loaded",this,this._environmentSpecularLoaded); } } /** *@private */ __proto._environmentDiffuseLoaded=function(){ this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.ENVIRONMENTDIFFUSE*/7,this._environmentDiffuse); } /** *@private */ __proto._environmentSpecularLoaded=function(){ var si=this._environmentSpecular['simLodInfo']; if (si && (si instanceof Float32Array)) this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.SIMLODINFO*/9,si); this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.ENVIRONMENTSPECULAR*/8,this._environmentSpecular); } /** *@private */ __proto._render=function(state){} /** *销毁天空。 */ __proto.destroy=function(){ this.__ownerCamera=null; } /** *@private */ __getset(0,__proto,'_ownerCamera',null,function(value){ this.__ownerCamera=value; (this._environmentDiffuse)&& (this._setEnvironmentDiffuse()); (this._environmentSpecular)&& (this._setEnvironmentSpecular()); }); /** *设置透明混合度。 *@param value 透明混合度。 */ /** *获取透明混合度。 *@return 透明混合度。 */ __getset(0,__proto,'alphaBlending',function(){ return this._alphaBlending; },function(value){ this._alphaBlending=value; if (this._alphaBlending < 0) this._alphaBlending=0; if (this._alphaBlending > 1) this._alphaBlending=1; }); __getset(0,__proto,'envDiffuseSHBlue',null,function(value){ this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.DIFFUSEIRRADMATB*/12,value); }); /** *设置颜色强度。 *@param value 颜色强度。 */ /** *获取颜色强度。 *@return 颜色强度。 */ __getset(0,__proto,'colorIntensity',function(){ return this._colorIntensity; },function(value){ this._colorIntensity=value; if (this._colorIntensity < 0) this._colorIntensity=0; }); __getset(0,__proto,'envDiffuseSHGreen',null,function(value){ this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.DIFFUSEIRRADMATG*/11,value); }); __getset(0,__proto,'envDiffuseSHRed',null,function(value){ this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.DIFFUSEIRRADMATR*/10,value); }); /** *设置环境漫反射贴图。 *@param value 环境漫反射贴图。 */ /** *获取环境漫反射贴图。 *@return 环境漫反射贴图。 */ __getset(0,__proto,'environmentDiffuse',function(){ return this._environmentDiffuse; },function(value){ value.minFifter=/*laya.webgl.WebGLContext.NEAREST*/0x2600; this._environmentDiffuse=value; (this.__ownerCamera)&& (this._setEnvironmentDiffuse()); }); /** *设置环境高光贴图。 *@param value 环境高光贴图。 */ /** *获取环境高光贴图。 *@return 环境高光贴图。 */ __getset(0,__proto,'environmentSpecular',function(){ return this._environmentSpecular; },function(value){ this._environmentSpecular=value; (this.__ownerCamera)&& (this._setEnvironmentSpecular()); }); Sky.MVPMATRIX=0; Sky.INTENSITY=1; Sky.ALPHABLENDING=2; Sky.DIFFUSETEXTURE=3; return Sky; })() /** *SubMesh 类用于创建子网格数据模板。 */ //class laya.d3.resource.models.SubMesh var SubMesh=(function(){ function SubMesh(mesh){ /**@private */ this._mesh=null; /**@private */ this._boneIndicesList=null; /**@private */ this._subIndexBufferStart=null; /**@private */ this._subIndexBufferCount=null; /**@private */ this._skinAnimationDatas=null; /**@private */ this._bufferUsage=null; /**@private */ this._indexInMesh=0; /**@private */ this._vertexBuffer=null; /**@private */ this._vertexStart=0; /**@private */ this._vertexCount=0; /**@private */ this._indexBuffer=null; /**@private */ this._indexStart=0; /**@private */ this._indexCount=0; /**@private */ this._indices=null; this._bufferUsage={}; this._mesh=mesh; this._boneIndicesList=[]; this._subIndexBufferStart=[]; this._subIndexBufferCount=[]; } __class(SubMesh,'laya.d3.resource.models.SubMesh'); var __proto=SubMesh.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true,"laya.resource.IDispose":true}) /** *@private */ __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer; else return null; } /** *@private */ __proto._getIndexBuffer=function(){ return this._indexBuffer; } /** *@private */ __proto._getStaticBatchBakedVertexs=function(batchOwnerTransform,owner){ var byteSizeInFloat=4; var vertexBuffer=this._vertexBuffer; var vertexDeclaration=vertexBuffer.vertexDeclaration; var positionOffset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.POSITION0*/0).offset / byteSizeInFloat; var normalOffset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3).offset / byteSizeInFloat; var lightmapScaleOffset=owner.meshRender.lightmapScaleOffset; var i=0,n=0,bakedVertexes,bakedVertexFloatCount=0,lightingMapTexcoordOffset=0,uv1Element; var uv0Offset=0,oriVertexFloatCount=0; if (lightmapScaleOffset){ uv1Element=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15); if (uv1Element){ bakedVertexFloatCount=vertexDeclaration.vertexStride / byteSizeInFloat; if (this._vertexCount > 0) bakedVertexes=vertexBuffer.getData().slice(this._vertexStart *bakedVertexFloatCount,(this._vertexStart+this._vertexCount)*bakedVertexFloatCount); else bakedVertexes=vertexBuffer.getData().slice(); lightingMapTexcoordOffset=uv1Element.offset / byteSizeInFloat; }else { oriVertexFloatCount=vertexDeclaration.vertexStride / byteSizeInFloat; bakedVertexFloatCount=oriVertexFloatCount+2; if (this._vertexCount) bakedVertexes=new Float32Array(this._vertexCount *(vertexBuffer.vertexDeclaration.vertexStride / byteSizeInFloat+2)); else bakedVertexes=new Float32Array(vertexBuffer.vertexCount *(vertexBuffer.vertexDeclaration.vertexStride / byteSizeInFloat+2)); uv0Offset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2).offset / byteSizeInFloat; lightingMapTexcoordOffset=uv0Offset+2; var oriVertexes=vertexBuffer.getData(); for (i=0,n=oriVertexes.length / oriVertexFloatCount;i < n;i++){ var oriVertexOffset=0; if (this._vertexCount > 0) oriVertexOffset=(this._vertexStart+i)*oriVertexFloatCount; else oriVertexOffset=i *oriVertexFloatCount; var bakedVertexOffset=i *bakedVertexFloatCount; var j=0; for (j=0;j < lightingMapTexcoordOffset;j++) bakedVertexes[bakedVertexOffset+j]=oriVertexes[oriVertexOffset+j]; for (j=lightingMapTexcoordOffset;j < oriVertexFloatCount;j++) bakedVertexes[bakedVertexOffset+j+2]=oriVertexes[oriVertexOffset+j]; } } }else { bakedVertexFloatCount=vertexDeclaration.vertexStride / byteSizeInFloat; if (this._vertexCount) bakedVertexes=vertexBuffer.getData().slice(this._vertexStart *bakedVertexFloatCount,(this._vertexStart+this._vertexCount)*bakedVertexFloatCount); else bakedVertexes=vertexBuffer.getData().slice(); } if (batchOwnerTransform){ var rootMat=batchOwnerTransform.worldMatrix; var rootInvertMat=SubMesh._tempMatrix4x40; rootMat.invert(rootInvertMat); var result=SubMesh._tempMatrix4x41; var transform=owner.transform.worldMatrix; Matrix4x4.multiply(rootInvertMat,transform,result); }else { result=owner.transform.worldMatrix; }; var rotation=SubMesh._tempQuaternion0; result.decomposeTransRotScale(SubMesh._tempVector30,rotation,SubMesh._tempVector31); for (i=0,n=bakedVertexes.length / bakedVertexFloatCount;i < n;i++){ var posOffset=i *bakedVertexFloatCount+positionOffset; var norOffset=i *bakedVertexFloatCount+normalOffset; Utils3D.transformVector3ArrayToVector3ArrayCoordinate(bakedVertexes,posOffset,result,bakedVertexes,posOffset); Utils3D.transformVector3ArrayByQuat(bakedVertexes,norOffset,rotation,bakedVertexes,norOffset); if (lightmapScaleOffset){ var lightingMapTexOffset=i *bakedVertexFloatCount+lightingMapTexcoordOffset; if (uv1Element){ Utils3D.transformLightingMapTexcoordByUV1Array(bakedVertexes,lightingMapTexOffset,lightmapScaleOffset,bakedVertexes,lightingMapTexOffset); }else { var tex0Offset=i *oriVertexFloatCount+uv0Offset; Utils3D.transformLightingMapTexcoordByUV0Array(oriVertexes,tex0Offset,lightmapScaleOffset,bakedVertexes,lightingMapTexOffset); } } } return bakedVertexes; } /** *@private */ __proto._getVertexBuffers=function(){ return null; } /** *@private */ __proto._beforeRender=function(state){ this._vertexBuffer._bind(); this._indexBuffer._bind(); return true; } /** *@private *渲染。 *@param state 渲染状态。 */ __proto._render=function(state){ var skinAnimationDatas; var indexCount=0; var renderElement=state.renderElement; if (this._indexCount > 1){ var boneIndicesListCount=this._boneIndicesList.length; if (boneIndicesListCount > 1){ for (var i=0;i < boneIndicesListCount;i++){ skinAnimationDatas=renderElement._skinAnimationDatas || this._skinAnimationDatas; if (skinAnimationDatas){ renderElement._shaderValue.setValue(/*laya.d3.core.SkinnedMeshSprite3D.BONES*/0,skinAnimationDatas[i]); state._shader.uploadRenderElementUniforms(renderElement._shaderValue.data); } WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._subIndexBufferCount[i],/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this._subIndexBufferStart[i] *2); } Stat.drawCall+=boneIndicesListCount; }else { skinAnimationDatas=renderElement._skinAnimationDatas || this._skinAnimationDatas; if (skinAnimationDatas){ renderElement._shaderValue.setValue(/*laya.d3.core.SkinnedMeshSprite3D.BONES*/0,skinAnimationDatas[0]); state._shader.uploadRenderElementUniforms(renderElement._shaderValue.data); } WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this._indexStart *2); Stat.drawCall++; } indexCount=this._indexCount; }else { indexCount=this._indexBuffer.indexCount; skinAnimationDatas=renderElement._skinAnimationDatas || this._skinAnimationDatas; if (skinAnimationDatas){ renderElement._shaderValue.setValue(/*laya.d3.core.SkinnedMeshSprite3D.BONES*/0,skinAnimationDatas[0]); state._shader.uploadRenderElementUniforms(renderElement._shaderValue.data); } WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.drawCall++; } Stat.trianglesFaces+=indexCount / 3; } /** *@private */ __proto.getIndices=function(){ if (this._indexCount > 0) return this._indices; else return this._indexBuffer.getData(); } /** *

    彻底清理资源。

    *

    注意:会强制解锁清理。

    */ __proto.dispose=function(){ this._indexBuffer.destroy(); this._vertexBuffer.destroy(); this._mesh=null; this._boneIndicesList=null; this._subIndexBufferStart=null; this._subIndexBufferCount=null; this._skinAnimationDatas=null; this._bufferUsage=null; this._vertexBuffer=null; this._indexBuffer=null; } /** *@private */ __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); /** *@private */ __getset(0,__proto,'triangleCount',function(){ return this._indexBuffer.indexCount / 3; }); __static(SubMesh, ['_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempVector31',function(){return this._tempVector31=new Vector3();},'_tempQuaternion0',function(){return this._tempQuaternion0=new Quaternion();},'_tempMatrix4x40',function(){return this._tempMatrix4x40=new Matrix4x4();},'_tempMatrix4x41',function(){return this._tempMatrix4x41=new Matrix4x4();} ]); return SubMesh; })() /** *@private */ //class laya.d3.shader.ShaderDefines var ShaderDefines$1=(function(){ function ShaderDefines(shaderdefines){ /**@private [只读]*/ this.defineCounter=0; /**@private [只读]*/ this.defines=null; if (shaderdefines){ this.defineCounter=shaderdefines.defineCounter; this.defines=shaderdefines.defines.slice(); }else { this.defineCounter=0; this.defines=[]; } } __class(ShaderDefines,'laya.d3.shader.ShaderDefines',null,'ShaderDefines$1'); var __proto=ShaderDefines.prototype; /** *@private */ __proto.registerDefine=function(name){ var value=Math.pow(2,this.defineCounter++); this.defines[value]=name; return value; } return ShaderDefines; })() /** *@private *ShaderInit 类用于初始化内置Shader。 */ //class laya.d3.shader.ShaderInit3D var ShaderInit3D=(function(){ /** *创建一个 ShaderInit 实例。 */ function ShaderInit3D(){} __class(ShaderInit3D,'laya.d3.shader.ShaderInit3D'); ShaderInit3D.__init__=function(){ ShaderCompile3D._globalRegDefine("HIGHPRECISION",ShaderCompile3D.SHADERDEFINE_HIGHPRECISION); ShaderCompile3D._globalRegDefine("FOG",ShaderCompile3D.SHADERDEFINE_FOG); ShaderCompile3D._globalRegDefine("DIRECTIONLIGHT",ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); ShaderCompile3D._globalRegDefine("POINTLIGHT",ShaderCompile3D.SHADERDEFINE_POINTLIGHT); ShaderCompile3D._globalRegDefine("SPOTLIGHT",ShaderCompile3D.SHADERDEFINE_SPOTLIGHT); ShaderCompile3D._globalRegDefine("UV",ShaderCompile3D.SHADERDEFINE_UV0); ShaderCompile3D._globalRegDefine("COLOR",ShaderCompile3D.SHADERDEFINE_COLOR); ShaderCompile3D._globalRegDefine("UV1",ShaderCompile3D.SHADERDEFINE_UV1); ShaderCompile3D._globalRegDefine("CASTSHADOW",ParallelSplitShadowMap.SHADERDEFINE_CAST_SHADOW); ShaderCompile3D._globalRegDefine("SHADOWMAP_PSSM1",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1); ShaderCompile3D._globalRegDefine("SHADOWMAP_PSSM2",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2); ShaderCompile3D._globalRegDefine("SHADOWMAP_PSSM3",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3); ShaderCompile3D._globalRegDefine("SHADOWMAP_PCF_NO",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO); ShaderCompile3D._globalRegDefine("SHADOWMAP_PCF1",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1); ShaderCompile3D._globalRegDefine("SHADOWMAP_PCF2",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2); ShaderCompile3D._globalRegDefine("SHADOWMAP_PCF3",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3); ShaderCompile3D._globalRegDefine("DEPTHFOG",ShaderCompile3D.SAHDERDEFINE_DEPTHFOG); Shader3D.addInclude("LightHelper.glsl","\nstruct DirectionLight\n{\n vec3 Direction;\n vec3 Diffuse;\n};\n\nstruct PointLight\n{\n vec3 Diffuse;\n vec3 Attenuation;\n vec3 Position;\n float Range;\n};\n\nstruct SpotLight\n{\n vec3 Diffuse;\n vec3 Attenuation;\n vec3 Position;\n vec3 Direction;\n float Spot;\n float Range;\n};\n\n\nvec3 NormalSampleToWorldSpace(vec3 normalMapSample, vec3 unitNormal, vec3 tangent)\n{\n vec3 normalT = 2.0*normalMapSample - 1.0;\n\n // Build orthonormal basis.\n vec3 N = normalize(unitNormal);\n vec3 T = normalize(tangent- dot(tangent, N)*N);\n vec3 B = cross(T, N);\n\n mat3 TBN = mat3(T, B, N);\n\n // Transform from tangent space to world space.\n vec3 bumpedNormal = TBN*normalT;\n\n return bumpedNormal;\n}\n\n\nvoid computeDirectionLight(in vec3 matDif,in vec3 matAmb,in vec4 matSpe,in DirectionLight dirLight,in vec3 ambinentColor,in vec3 normal,in vec3 toEye,out vec3 dif,out vec3 amb,out vec3 spec)\n{\n dif=vec3(0.0);//不初始化在IOS中闪烁,PC中不会闪烁\n amb=vec3(0.0);\n spec=vec3(0.0);\n vec3 lightVec=-normalize(dirLight.Direction);\n \n amb=matAmb*ambinentColor;\n \n float diffuseFactor=dot(lightVec, normal);\n \n if(diffuseFactor>0.0)\n {\n vec3 v = reflect(-lightVec, normal);\n float specFactor = pow(max(dot(v, toEye), 0.0), matSpe.w);\n \n dif = diffuseFactor * matDif * dirLight.Diffuse;\n spec = specFactor * matSpe.rgb;\n }\n \n}\n\nvoid computePointLight(in vec3 matDif,in vec3 matAmb,in vec4 matSpe,in PointLight poiLight,in vec3 ambinentColor, in vec3 pos,in vec3 normal,in vec3 toEye,out vec3 dif,out vec3 amb,out vec3 spec)\n{\n dif=vec3(0.0);\n amb=vec3(0.0);\n spec=vec3(0.0);\n vec3 lightVec = poiLight.Position - pos;\n \n float d = length(lightVec);\n \n if( d > poiLight.Range )\n return;\n \n lightVec /= d; \n \n amb = matAmb*ambinentColor; \n\n float diffuseFactor = dot(lightVec, normal);\n\n if( diffuseFactor > 0.0 )\n {\n vec3 v= reflect(-lightVec, normal);\n float specFactor = pow(max(dot(v, toEye), 0.0), matSpe.w);\n \n dif = diffuseFactor * matDif * poiLight.Diffuse;\n spec = specFactor * matSpe.rgb;\n }\n\n float attenuate = 1.0 / dot(poiLight.Attenuation, vec3(1.0, d, d*d));\n\n dif *= attenuate;\n spec*= attenuate;\n}\n\nvoid ComputeSpotLight(in vec3 matDif,in vec3 matAmb,in vec4 matSpe,in SpotLight spoLight,in vec3 ambinentColor,in vec3 pos, in vec3 normal,in vec3 toEye,out vec3 dif,out vec3 amb,out vec3 spec)\n{\n amb = vec3(0.0);\n dif =vec3(0.0);\n spec= vec3(0.0);\n vec3 lightVec = spoLight.Position - pos;\n \n float d = length(lightVec);\n \n if( d > spoLight.Range)\n return;\n \n lightVec /= d; \n \n amb = matAmb*ambinentColor; \n\n float diffuseFactor = dot(lightVec, normal);\n\n if(diffuseFactor > 0.0)\n {\n vec3 v= reflect(-lightVec, normal);\n float specFactor = pow(max(dot(v, toEye), 0.0), matSpe.w);\n \n dif = diffuseFactor * matDif * spoLight.Diffuse;\n spec = specFactor * matSpe.rgb;\n }\n \n float spot = pow(max(dot(-lightVec, normalize(spoLight.Direction)), 0.0), spoLight.Spot);\n\n float attenuate = spot/dot(spoLight.Attenuation, vec3(1.0, d, d*d));\n\n amb *= spot;\n dif *= attenuate;\n spec*= attenuate;\n}\n\n"); Shader3D.addInclude("Lighting.glsl","\nstruct DirectionLight\n{\n vec3 Color;\n vec3 Direction;\n};\n\nstruct PointLight\n{\n vec3 Color;\n vec3 Position;\n float Range;\n};\n\nstruct SpotLight\n{\n vec3 Color;\n vec3 Position;\n vec3 Direction;\n float Spot;\n float Range;\n};\n\n// U3D中使用衰减纹理,此函数模拟并非正确\n//float U3DAttenuation(in vec3 L,in float invLightRadius)\n//{\n// float fRatio = clamp(length(L) * invLightRadius,0.0,1.0);\n// fRatio *= fRatio;\n// return 1.0 / (1.0 + 25.0 * fRatio)* clamp(4.0*(1.0 - fRatio),0.0,1.0); //fade to black as if 4 pixel texture\n//} \n\n// Same as Just Cause 2 and Crysis 2 (you can read GPU Pro 1 book for more information)\nfloat BasicAttenuation(in vec3 L,in float invLightRadius)\n{\n vec3 distance = L * invLightRadius;\n float attenuation = clamp(1.0 - dot(distance, distance),0.0,1.0); // Equals float attenuation = saturate(1.0f - dot(L, L) / (lightRadius * lightRadius)); \n return attenuation * attenuation;\n} \n\n// Inspired on http://fools.slindev.com/viewtopic.php?f=11&t=21&view=unread#unread \nfloat NaturalAttenuation(in vec3 L,in float invLightRadius)\n{\n float attenuationFactor = 30.0;\n vec3 distance = L * invLightRadius;\n float attenuation = dot(distance, distance); // Equals float attenuation = dot(L, L) / (lightRadius * lightRadius);\n attenuation = 1.0 / (attenuation * attenuationFactor + 1.0);\n // Second we move down the function therewith it reaches zero at abscissa 1:\n attenuationFactor = 1.0 / (attenuationFactor + 1.0); //attenuationFactor contains now the value we have to subtract\n attenuation = max(attenuation - attenuationFactor, 0.0); // The max fixes a bug.\n // Finally we expand the equation along the y-axis so that it starts with a function value of 1 again.\n attenuation /= 1.0 - attenuationFactor;\n return attenuation;\n} \n\nvoid LayaAirBlinnPhongLight (in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir,in vec3 lightColor, in vec3 lightVec,out vec3 diffuseColor,out vec3 specularColor)\n{\n mediump vec3 h = normalize(viewDir-lightVec);\n lowp float ln = max (0.0, dot (-lightVec,normal));\n float nh = max (0.0, dot (h,normal));\n diffuseColor=lightColor * ln;\n specularColor=lightColor *specColor*pow (nh, specColorIntensity*128.0) * gloss;\n}\n\nvoid LayaAirBlinnPhongDiectionLight (in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in DirectionLight light,out vec3 diffuseColor,out vec3 specularColor)\n{\n vec3 lightVec=normalize(light.Direction);\n LayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.Color,lightVec,diffuseColor,specularColor);\n}\n\nvoid LayaAirBlinnPhongPointLight (in vec3 pos,in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in PointLight light,out vec3 diffuseColor,out vec3 specularColor)\n{\n vec3 lightVec = pos-light.Position;\n //if( length(lightVec) > light.Range )\n // return;\n LayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.Color,lightVec/length(lightVec),diffuseColor,specularColor);\n float attenuate = BasicAttenuation(lightVec, 1.0/light.Range);\n diffuseColor *= attenuate;\n specularColor*= attenuate;\n}\n\nvoid LayaAirBlinnPhongSpotLight (in vec3 pos,in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in SpotLight light,out vec3 diffuseColor,out vec3 specularColor)\n{\n vec3 lightVec = pos-light.Position;\n //if( length(lightVec) > light.Range )\n // return;\n vec3 normalLightVec=lightVec/length(lightVec);\n LayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.Color,normalLightVec,diffuseColor,specularColor);\n float spot = pow(max(dot(normalLightVec, normalize(light.Direction)), 0.0), light.Spot);\n float attenuate = spot*BasicAttenuation(lightVec, 1.0/light.Range);\n diffuseColor *= attenuate;\n specularColor*= attenuate;\n}\n\nvec3 NormalSampleToWorldSpace(vec3 normalMapSample, vec3 unitNormal, vec3 tangent,vec3 binormal)\n{\n vec3 normalT =vec3(2.0*normalMapSample.x - 1.0,1.0-2.0*normalMapSample.y,2.0*normalMapSample.z - 1.0);\n \n // Build orthonormal basis.\n vec3 N = normalize(unitNormal);\n vec3 T = normalize(tangent);\n vec3 B = normalize(binormal);\n mat3 TBN = mat3(T, B, N);\n \n // Transform from tangent space to world space.\n vec3 bumpedNormal = TBN*normalT;\n\n return bumpedNormal;\n}\n\n\n"); Shader3D.addInclude("ShadowHelper.glsl","uniform sampler2D u_shadowMap1;\nuniform sampler2D u_shadowMap2;\nuniform sampler2D u_shadowMap3;\nuniform vec2 u_shadowPCFoffset;\nuniform vec3 u_shadowPSSMDistance;\nvec4 packDepth(const in float depth)\n{\n const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);\n const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);\n vec4 res = mod(depth*bitShift*vec4(255), vec4(256))/vec4(255);\n res -= res.xxyz * bitMask;\n return res;\n}\nfloat unpackDepth(const in vec4 rgbaDepth)\n{\n const vec4 bitShift = vec4(1.0/(256.0*256.0*256.0), 1.0/(256.0*256.0), 1.0/256.0, 1.0);\n float depth = dot(rgbaDepth, bitShift);\n return depth;\n}\nfloat tex2DPCF( sampler2D shadowMap,vec2 texcoord,vec2 invsize,float zRef )\n{\n vec2 texelpos =texcoord / invsize;\n vec2 lerps = fract( texelpos );\n float sourcevals[4];\n sourcevals[0] = float( unpackDepth(texture2D(shadowMap,texcoord)) > zRef );\n sourcevals[1] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(invsize.x,0))) > zRef );\n sourcevals[2] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(0,invsize.y))) > zRef );\n sourcevals[3] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(invsize.x, invsize.y) )) > zRef );\n return mix( mix(sourcevals[0],sourcevals[2],lerps.y),mix(sourcevals[1],sourcevals[3],lerps.y),lerps.x );\n}\nfloat getShadowPSSM3( sampler2D shadowMap1,sampler2D shadowMap2,sampler2D shadowMap3,mat4 lightShadowVP[4],vec3 pssmDistance,vec2 shadowPCFOffset,vec3 worldPos,float posViewZ,float zBias )\n{\n float value = 1.0;\n int nPSNum = int(posViewZ>pssmDistance.x);\n nPSNum += int(posViewZ>pssmDistance.y);\n nPSNum += int(posViewZ>pssmDistance.z);\n //真SB,webgl不支持在PS中直接访问数组\n mat4 lightVP;\n if( nPSNum == 0 )\n {\n lightVP = lightShadowVP[1];\n }\n else if( nPSNum == 1 )\n {\n lightVP = lightShadowVP[2];\n }\n else if( nPSNum == 2 )\n {\n lightVP = lightShadowVP[3];\n }\n vec4 vLightMVPPos = lightVP * vec4(worldPos,1.0);\n //为了效率,在CPU计算/2.0 + 0.5\n //vec3 vText = (vLightMVPPos.xyz / vLightMVPPos.w)/2.0 + 0.5;\n vec3 vText = vLightMVPPos.xyz / vLightMVPPos.w;\n float fMyZ = vText.z - zBias;\n /*\n bvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\n bool bInFrustum = all( bInFrustumVec );\n bvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\n bool bFrustumTest = all( bFrustumTestVec );\n if ( bFrustumTest ) \n */\n if( fMyZ <= 1.0 )\n {\n float zdepth=0.0;\n#ifdef SHADOWMAP_PCF3\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset, fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset, fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset, fMyZ );\n value = value/4.0;\n } \n else if( nPSNum == 1 )\n {\n value = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 2 )\n {\n vec4 color = texture2D( shadowMap3,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n }\n#endif\n#ifdef SHADOWMAP_PCF2\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 1 )\n {\n value = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 2 )\n {\n vec4 color = texture2D( shadowMap3,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n }\n\n#endif\n#ifdef SHADOWMAP_PCF1\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 1 )\n {\n vec4 color = texture2D( shadowMap2,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n }\n else if( nPSNum == 2 )\n {\n vec4 color = texture2D( shadowMap3,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n }\n#endif\n#ifdef SHADOWMAP_PCF_NO\n vec4 color;\n if ( nPSNum == 0 )\n {\n color = texture2D( shadowMap1,vText.xy );\n }\n else if( nPSNum == 1 )\n {\n color = texture2D( shadowMap2,vText.xy );\n }\n else if( nPSNum == 2 )\n {\n color = texture2D( shadowMap3,vText.xy );\n }\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n#endif\n }\n return value;\n}\nfloat getShadowPSSM2( sampler2D shadowMap1,sampler2D shadowMap2,mat4 lightShadowVP[4],vec3 pssmDistance,vec2 shadowPCFOffset,vec3 worldPos,float posViewZ,float zBias )\n{\n float value = 1.0;\n int nPSNum = int(posViewZ>pssmDistance.x);\n nPSNum += int(posViewZ>pssmDistance.y);\n //真SB,webgl不支持在PS中直接访问数组\n mat4 lightVP;\n if( nPSNum == 0 )\n {\n lightVP = lightShadowVP[1];\n }\n else if( nPSNum == 1 )\n {\n lightVP = lightShadowVP[2];\n }\n vec4 vLightMVPPos = lightVP * vec4(worldPos,1.0);\n //为了效率,在CPU计算/2.0 + 0.5\n //vec3 vText = (vLightMVPPos.xyz / vLightMVPPos.w)/2.0 + 0.5;\n vec3 vText = vLightMVPPos.xyz / vLightMVPPos.w;\n float fMyZ = vText.z - zBias;\n /*\n bvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\n bool bInFrustum = all( bInFrustumVec );\n bvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\n bool bFrustumTest = all( bFrustumTestVec );\n if ( bFrustumTest ) \n */\n if( fMyZ <= 1.0 )\n {\n float zdepth=0.0;\n#ifdef SHADOWMAP_PCF3\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset, fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset, fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset, fMyZ );\n value = value/4.0;\n }\n else if( nPSNum == 1 )\n {\n value = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\n }\n#endif\n#ifdef SHADOWMAP_PCF2\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 1 )\n {\n value = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\n }\n#endif\n#ifdef SHADOWMAP_PCF1\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 1 )\n {\n vec4 color = texture2D( shadowMap2,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n }\n#endif\n#ifdef SHADOWMAP_PCF_NO\n vec4 color;\n if ( nPSNum == 0 )\n {\n color = texture2D( shadowMap1,vText.xy );\n }\n else if( nPSNum == 1 )\n {\n color = texture2D( shadowMap2,vText.xy );\n }\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n#endif\n }\n return value;\n}\nfloat getShadowPSSM1( sampler2D shadowMap1,vec4 lightMVPPos,vec3 pssmDistance,vec2 shadowPCFOffset,float posViewZ,float zBias )\n{\n float value = 1.0;\n if( posViewZ < pssmDistance.x )\n {\n vec3 vText = lightMVPPos.xyz / lightMVPPos.w;\n float fMyZ = vText.z - zBias;\n /*\n bvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\n bool bInFrustum = all( bInFrustumVec );\n bvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\n bool bFrustumTest = all( bFrustumTestVec );\n */\n if ( fMyZ <= 1.0 ) \n {\n float zdepth=0.0;\n#ifdef SHADOWMAP_PCF3\n value = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset,fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset,fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset,fMyZ );\n value = value/4.0;\n#endif\n#ifdef SHADOWMAP_PCF2 \n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n#endif\n#ifdef SHADOWMAP_PCF1\n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n#endif\n#ifdef SHADOWMAP_PCF_NO \n vec4 color = texture2D( shadowMap1,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n#endif\n }\n }\n return value;\n}"); Shader3D.addInclude("WaveFunction.glsl","\nuniform vec2 u_WaveInfoD[20];\nuniform vec4 u_WaveInfo[20];\n\nuniform float TEXWAVE_UV_SCALE ;//= 20.0; //每texwidth像素代表的实际距离\n/**\n 这里的计算都是\n*/\n\n/**\n* 计算一个波形\n* 开始计算的时候都按照z向上,最后输出的时候,颠倒一下。\n* @param tm {float} 毫秒\n*/\nvoid calcGerstnerWave(float curtm, vec3 pos, float deep, vec2 uvpos, out vec3 opos, out vec3 B, out vec3 T, out vec3 N, out float foamS){\n float tm = curtm/1000.;\n opos = pos;\n vec3 wpos=vec3(0.); //累加的位置\n N=vec3(0.,0.,0.); //输出的法线初始化一下\n T=vec3(0.,0.,0.);\n B=vec3(0.,0.,0.);\n vec2 cD ;//= D;\n //float deepAtt = max(0.,min(deep,1.0));\n //A*=deepAtt; //TODO\n \n for( int i=0; i<4; i++){\n cD = u_WaveInfoD[i];//vec2(wi.winfo[0],wi.winfo[1]);// wi.vDir;\n float Q = u_WaveInfo[i].x;//wi.QorK;\n float A = u_WaveInfo[i].y;//wi.A;\n float W = u_WaveInfo[i].z;//wi.omega;\n float P = u_WaveInfo[i].w;//wi.phi;\n float dop = dot(cD,uvpos);\n float c = cos(dop*W - tm*P);//TODO 优化\n float s = sin(dop*W - tm*P);\n float AWs = A*W*s;\n float AWc = A*W*c;\n float _QxyAWs = -Q*cD.x*cD.y*AWs;\n \n wpos += vec3(Q*A*cD.x*c,\n Q*A*cD.y*c,\n A*s);\n N += vec3(-cD.x*AWc,\n -cD.y*AWc,\n Q*AWs);//记得最后1-\n T += vec3(_QxyAWs,\n Q*cD.y*cD.y*AWs,//记得1-\n cD.y*AWc\n );\n B += vec3(Q*cD.x*cD.x*AWs,//记得1-\n _QxyAWs,\n cD.x*AWc\n );\n //float v1 = exp(-tan((dop*W - tm*P)/2.+1.07));//除2,+pi/2 这样正好能对齐\n#ifdef USE_FOAM \n float v1 = 0.5-sin((dop*W - tm*P)/1.+2.0)/2.;\n foamS += pow(v1,9.)/4.;\n#endif\n }\n T.y=1.-T.y; B.x=1.-B.x;N.z=1.-N.z;\n opos += vec3(wpos.x,wpos.z*min(deep/10.,1.),wpos.y);\n //y和z交换一下。现在根据uv计算的位置,所以直接交换yz就行。其他情况下有问题么\n T.xyz=T.xzy;\n B.xyz=B.xzy;\n N.xyz=N.xzy;\n}\n\n\nvoid calcWave(float curtm, vec2 uv, out vec3 B, out vec3 T, out vec3 N){\n float tm = curtm/1000.;\n N=vec3(0.,0.,0.); //输出的法线初始化一下\n vec2 uvpos = uv*TEXWAVE_UV_SCALE; //TODO 这个范围是什么 就是1?\n uvpos.y*=-1.;\n vec2 cD;// = D;\n const int NumWaves = 4;\n float scale = 1./float(NumWaves);\n for( int i=0; iShader3D
    主要用数组的方式保存shader变量定义,后期合并ShaderValue不使用for in,性能较高。 */ //class laya.d3.shader.ValusArray var ValusArray=(function(){ function ValusArray(){ this._data=null; this._data=[]; } __class(ValusArray,'laya.d3.shader.ValusArray'); var __proto=ValusArray.prototype; __proto.setValue=function(name,value){ this._data[name]=value; } __getset(0,__proto,'data',function(){ return this._data; }); return ValusArray; })() /** *... *@author ... */ //class laya.d3.shadowMap.ParallelSplitShadowMap var ParallelSplitShadowMap=(function(){ function ParallelSplitShadowMap(){ /**@private */ //this.lastNearPlane=NaN; /**@private */ //this.lastFieldOfView=NaN; /**@private */ //this.lastAspectRatio=NaN; /**@private */ this._currentPSSM=-1; /**@private */ this._numberOfPSSM=3; /**@private */ this._maxDistance=200.0; /**@private */ this._ratioOfDistance=1.0 / this._numberOfPSSM; /**@private */ this._statesDirty=true; /**@private */ this._lightCulling=null; /**@private */ this._renderTarget=null; /**@private */ this._lightVPMatrix=null; /**@private */ this._lightCameras=null; /**@private */ this._shadowQuenes=null; /**@private */ this._shadowMapTextureSize=1024; /**@private */ this._scene=null; /**@private */ this._PCFType=0; /**@private */ this._shaderValueLightVP=null; /**@private */ this._shaderValueVPs=null; this._spiltDistance=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._globalParallelLightDir=new Vector3(0,-1,0); this._boundingSphere=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._boundingBox=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._frustumPos=new Array((/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1)*4); this._uniformDistance=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._logDistance=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._dimension=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._tempLookAt3=new Vector3(); this._tempLookAt4=new Vector4(); this._tempValue=new Vector4(); this._tempPos=new Vector3(); this._tempLightUp=new Vector3(); this._tempMin=new Vector4(); this._tempMax=new Vector4(); this._tempMatrix44=new Matrix4x4; this._splitFrustumCulling=new BoundFrustum(Matrix4x4.DEFAULT); this._tempScaleMatrix44=new Matrix4x4; this._shadowPCFOffset=new Vector2(1.0 / 1024.0,1.0 / 1024.0); this._shaderValueDistance=new Vector4(); var i=0; for (i=0;i < this._spiltDistance.length;i++){ this._spiltDistance[i]=0.0; } for (i=0;i < this._dimension.length;i++){ this._dimension[i]=new Vector2(); } for (i=0;i < this._frustumPos.length;i++){ this._frustumPos[i]=new Vector3(); } for (i=0;i < this._boundingBox.length;i++){ this._boundingBox[i]=new BoundBox(new Vector3(),new Vector3()); } for (i=0;i < this._boundingSphere.length;i++){ this._boundingSphere[i]=new BoundSphere(new Vector3(),0.0); } Matrix4x4.createScaling(new Vector3(0.5,0.5,1.0),this._tempScaleMatrix44); this._tempScaleMatrix44.elements[12]=0.5; this._tempScaleMatrix44.elements[13]=0.5; } __class(ParallelSplitShadowMap,'laya.d3.shadowMap.ParallelSplitShadowMap'); var __proto=ParallelSplitShadowMap.prototype; __proto.setInfo=function(scene,maxDistance,globalParallelDir,shadowMapTextureSize,numberOfPSSM,PCFType){ if (numberOfPSSM > /*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3){ this._numberOfPSSM=/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3; } this._scene=scene; this._maxDistance=maxDistance; this.PSSMNum=numberOfPSSM; this._globalParallelLightDir=globalParallelDir; this._ratioOfDistance=1.0 / this._numberOfPSSM; for (var i=0;i < this._spiltDistance.length;i++){ this._spiltDistance[i]=0.0; } this._shadowMapTextureSize=shadowMapTextureSize; this._shadowPCFOffset.x=1.0 / this._shadowMapTextureSize; this._shadowPCFOffset.y=1.0 / this._shadowMapTextureSize; this.setPCFType(PCFType); this._statesDirty=true; } __proto.setPCFType=function(PCFtype){ this._PCFType=PCFtype; switch (this._PCFType){ case 0: this._scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3); break ; case 1: this._scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3); break ; case 2: this._scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3); break ; case 3: this._scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2); break ; } } __proto.getPCFType=function(){ return this._PCFType; } __proto.setFarDistance=function(value){ if (this._maxDistance !=value){ this._maxDistance=value; this._statesDirty=true; } } __proto.getFarDistance=function(){ return this._maxDistance; } __proto._setGlobalParallelLightDir=function(dir){ this._globalParallelLightDir=dir; } __proto.getGlobalParallelLightDir=function(){ return this._globalParallelLightDir; } __proto.getCurrentPSSM=function(){ return this._currentPSSM; } __proto.getLightCamera=function(index){ return this._lightCameras[index]; } /** *@private */ __proto._beginSampler=function(index,sceneCamera){ if (index < 0 || index > this._numberOfPSSM) throw new Error("ParallelSplitShadowMap: beginSample invalid index"); this._currentPSSM=index; this._update(sceneCamera); } /** *@private */ __proto.endSampler=function(sceneCamera){ this._currentPSSM=-1; } /** *@private */ __proto._calcAllLightCameraInfo=function(sceneCamera){ if (this._numberOfPSSM===1){ this._beginSampler(0,sceneCamera); this.endSampler(sceneCamera); }else { for (var i=0,n=this._numberOfPSSM+1;i < n;i++){ this._beginSampler(i,sceneCamera); this.endSampler(sceneCamera); } } } /** *@private */ __proto._recalculate=function(nearPlane,fieldOfView,aspectRatio){ this._calcSplitDistance(nearPlane); this._calcBoundingBox(fieldOfView,aspectRatio); this._rebuildRenderInfo(); } /** *@private */ __proto._update=function(sceneCamera){ var nearPlane=sceneCamera.nearPlane; var fieldOfView=sceneCamera.fieldOfView; var aspectRatio=(sceneCamera).aspectRatio; if (this._statesDirty || this.lastNearPlane!==nearPlane || this.lastFieldOfView!==fieldOfView || this.lastAspectRatio!==aspectRatio){ this._recalculate(nearPlane,fieldOfView,aspectRatio); this._uploadShaderValue(); this._statesDirty=false; this.lastNearPlane=nearPlane; this.lastFieldOfView=fieldOfView; this.lastAspectRatio=aspectRatio; } this._calcLightViewProject(sceneCamera); } /** *@private */ __proto._uploadShaderValue=function(){ var scene=this._scene; switch (this._numberOfPSSM){ case 1: scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3); break ; case 2: scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3); break ; case 3: scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2); break ; }; var sceneSV=scene._shaderValues; sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWDISTANCE*/15,this._shaderValueDistance.elements); sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWLIGHTVIEWPROJECT*/16,this._shaderValueLightVP); sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPPCFOFFSET*/17,this._shadowPCFOffset.elements); switch (this._numberOfPSSM){ case 3: sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE1*/18,this.getRenderTarget(1)); sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE2*/19,this.getRenderTarget(2)); sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE3*/20,this.getRenderTarget(3)); break ; case 2: sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE1*/18,this.getRenderTarget(1)); sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE2*/19,this.getRenderTarget(2)); break ; case 1: sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE1*/18,this.getRenderTarget(1)); break ; } } /** *@private */ __proto._calcSplitDistance=function(nearPlane){ var far=this._maxDistance; var invNumberOfPSSM=1.0 / this._numberOfPSSM; var i=0; for (i=0;i <=this._numberOfPSSM;i++){ this._uniformDistance[i]=nearPlane+(far-nearPlane)*i *invNumberOfPSSM; }; var farDivNear=far / nearPlane; for (i=0;i <=this._numberOfPSSM;i++){ var n=Math.pow(farDivNear,i *invNumberOfPSSM); this._logDistance[i]=nearPlane *n; } for (i=0;i <=this._numberOfPSSM;i++){ this._spiltDistance[i]=this._uniformDistance[i] *this._ratioOfDistance+this._logDistance[i] *(1.0-this._ratioOfDistance); } this._shaderValueDistance.x=this._spiltDistance[1]; this._shaderValueDistance.y=this._spiltDistance[2]; this._shaderValueDistance.z=this._spiltDistance[3]; } /** *@private */ __proto._calcBoundingBox=function(fieldOfView,aspectRatio){ var fov=3.1415926 *fieldOfView / 180.0; var halfTanValue=Math.tan(fov / 2.0); var height=NaN; var width=NaN; var distance=NaN; var i=0; for (i=0;i <=this._numberOfPSSM;i++){ distance=this._spiltDistance[i]; height=distance *halfTanValue; width=height *aspectRatio; var temp=this._frustumPos[i *4+0].elements; temp[0]=-width; temp[1]=-height; temp[2]=-distance; temp=this._frustumPos[i *4+1].elements; temp[0]=width; temp[1]=-height; temp[2]=-distance; temp=this._frustumPos[i *4+2].elements; temp[0]=-width; temp[1]=height; temp[2]=-distance; temp=this._frustumPos[i *4+3].elements; temp[0]=width; temp[1]=height; temp[2]=-distance; temp=this._dimension[i].elements; temp[0]=width; temp[1]=height; }; var d; var min; var max; var center; for (i=1;i <=this._numberOfPSSM;i++){ d=this._dimension[i].elements; min=this._boundingBox[i].min.elements; min[0]=-d[0]; min[1]=-d[1]; min[2]=-this._spiltDistance[i]; max=this._boundingBox[i].max.elements; max[0]=d[0]; max[1]=d[1]; max[2]=-this._spiltDistance[i-1]; center=this._boundingSphere[i].center.elements; center[0]=(min[0]+max[0])*0.5; center[1]=(min[1]+max[1])*0.5; center[2]=(min[2]+max[2])*0.5; this._boundingSphere[i].radius=Math.sqrt(Math.pow(max[0]-min[0],2)+Math.pow(max[1]-min[1],2)+Math.pow(max[2]-min[2],2))*0.5; } min=this._boundingBox[0].min.elements; d=this._dimension[this._numberOfPSSM].elements; min[0]=-d[0]; min[1]=-d[1]; min[2]=-this._spiltDistance[this._numberOfPSSM]; max=this._boundingBox[0].max.elements; max[0]=d[0]; max[1]=d[1]; max[2]=-this._spiltDistance[0]; center=this._boundingSphere[0].center.elements; center[0]=(min[0]+max[0])*0.5; center[1]=(min[1]+max[1])*0.5; center[2]=(min[2]+max[2])*0.5; this._boundingSphere[0].radius=Math.sqrt(Math.pow(max[0]-min[0],2)+Math.pow(max[1]-min[1],2)+Math.pow(max[2]-min[2],2))*0.5; } __proto.calcSplitFrustum=function(sceneCamera){ if (this._currentPSSM > 0){ Matrix4x4.createPerspective(3.1416 *sceneCamera.fieldOfView / 180.0,(sceneCamera).aspectRatio,this._spiltDistance[this._currentPSSM-1],this._spiltDistance[this._currentPSSM],this._tempMatrix44); }else { Matrix4x4.createPerspective(3.1416 *sceneCamera.fieldOfView / 180.0,(sceneCamera).aspectRatio,this._spiltDistance[0],this._spiltDistance[this._numberOfPSSM],this._tempMatrix44); } Matrix4x4.multiply(this._tempMatrix44,(sceneCamera).viewMatrix,this._tempMatrix44); this._splitFrustumCulling.matrix=this._tempMatrix44; } /** *@private */ __proto._rebuildRenderInfo=function(){ var nNum=this._numberOfPSSM+1; var i=0; if (this._renderTarget==null){ this._renderTarget=__newvec(nNum); this._renderTarget[0]=null; for (i=1;i < nNum;i++){ this._renderTarget[i]=new RenderTexture(this._shadowMapTextureSize,this._shadowMapTextureSize,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5,false,false,/*laya.webgl.WebGLContext.NEAREST*/0x2600,/*laya.webgl.WebGLContext.NEAREST*/0x2600); } }else if (this._renderTarget.length !=nNum){ this.disposeAllRenderTarget(); this._renderTarget.length=nNum; this._renderTarget[0]=null; for (i=1;i < nNum;i++){ this._renderTarget[i]=new RenderTexture(this._shadowMapTextureSize,this._shadowMapTextureSize,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5,false,false,/*laya.webgl.WebGLContext.NEAREST*/0x2600,/*laya.webgl.WebGLContext.NEAREST*/0x2600); } }else { for (i=1;i < nNum;i++){ if (this._renderTarget[i]==null || this._renderTarget[i].width !=this._shadowMapTextureSize || this._renderTarget[i].height !=this._shadowMapTextureSize){ if (this._renderTarget[i] !=null){ this._renderTarget[i].destroy(); } this._renderTarget[i]=new RenderTexture(this._shadowMapTextureSize,this._shadowMapTextureSize,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5,false,false,/*laya.webgl.WebGLContext.NEAREST*/0x2600,/*laya.webgl.WebGLContext.NEAREST*/0x2600); } } } if (this._lightCulling==null || this._lightCulling.length !=nNum){ if (this._lightCulling){ this._lightCulling.length=nNum; }else { this._lightCulling=__newvec(nNum); } for (i=0;i < this._lightCulling.length;i++){ this._lightCulling[i]=new BoundFrustum(Matrix4x4.DEFAULT); } } if (this._lightVPMatrix==null || this._lightVPMatrix.length !=nNum){ if (this._lightVPMatrix){ this._lightVPMatrix.length=nNum; }else { this._lightVPMatrix=__newvec(nNum); } for (i=0;i < this._lightVPMatrix.length;i++){ this._lightVPMatrix[i]=new Matrix4x4(); } } if (this._lightCameras==null || this._lightCameras.length !=nNum){ if (this._lightCameras){ this._lightCameras.length=nNum; }else { this._lightCameras=__newvec(nNum); } for (i=0;i < this._lightCameras.length;i++){ this._lightCameras[i]=new Camera(); this._lightCameras[i].name="lightCamera"+i; } } if (this._shadowQuenes==null || this._shadowQuenes.length !=this._numberOfPSSM){ if (this._shadowQuenes){ this._shadowQuenes.length=this._numberOfPSSM; }else { this._shadowQuenes=__newvec(this._numberOfPSSM); } for (i=0;i < this._shadowQuenes.length;i++){ this._shadowQuenes[i]=new RenderQueue(this._scene); } } if (this._shaderValueVPs==null || this._shaderValueVPs.length !=nNum){ if (this._shaderValueVPs){ this._shaderValueVPs.length=nNum; }else { this._shaderValueVPs=__newvec(nNum); } this._shaderValueLightVP=new Float32Array(nNum *16); for (i=0;i < nNum;i++){ this._shaderValueVPs[i]=new Float32Array(this._shaderValueLightVP.buffer,i *64); } } } /** *@private */ __proto._calcLightViewProject=function(sceneCamera){ var boundSphere=this._boundingSphere[this._currentPSSM]; var cameraMatViewInv=sceneCamera.transform.worldMatrix; var radius=boundSphere.radius; boundSphere.center.cloneTo(this._tempLookAt3); Vector3.transformV3ToV4(this._tempLookAt3,cameraMatViewInv,this._tempLookAt4); var lookAt3Element=this._tempLookAt3.elements; var lookAt4Element=this._tempLookAt4.elements; lookAt3Element[0]=lookAt4Element[0]; lookAt3Element[1]=lookAt4Element[1]; lookAt3Element[2]=lookAt4Element[2]; var lightUpElement=this._tempLightUp.elements; var sceneCameraDir=sceneCamera.forward.elements; lightUpElement[0]=sceneCameraDir[0]; lightUpElement[1]=1.0; lightUpElement[2]=sceneCameraDir[2]; Vector3.normalize(this._tempLightUp,this._tempLightUp); Vector3.scale(this._globalParallelLightDir,boundSphere.radius *4,this._tempPos); Vector3.subtract(this._tempLookAt3,this._tempPos,this._tempPos); var curLightCamera=this._lightCameras[this._currentPSSM]; curLightCamera.transform.position=this._tempPos; curLightCamera.transform.lookAt(this._tempLookAt3,this._tempLightUp,false); var tempMaxElements=this._tempMax.elements; var tempMinElements=this._tempMin.elements; tempMaxElements[0]=tempMaxElements[1]=tempMaxElements[2]=-100000.0; tempMaxElements[3]=1.0; tempMinElements[0]=tempMinElements[1]=tempMinElements[2]=100000.0; tempMinElements[3]=1.0; Matrix4x4.multiply(curLightCamera.viewMatrix,cameraMatViewInv,this._tempMatrix44); var tempValueElement=this._tempValue.elements; var corners=[]; corners.length=8; this._boundingBox[this._currentPSSM].getCorners(corners); for (var i=0;i < 8;i++){ var frustumPosElements=corners[i].elements; tempValueElement[0]=frustumPosElements[0]; tempValueElement[1]=frustumPosElements[1]; tempValueElement[2]=frustumPosElements[2]; tempValueElement[3]=1.0; Vector4.transformByM4x4(this._tempValue,this._tempMatrix44,this._tempValue); tempMinElements[0]=(tempValueElement[0] < tempMinElements[0])? tempValueElement[0] :tempMinElements[0]; tempMinElements[1]=(tempValueElement[1] < tempMinElements[1])? tempValueElement[1] :tempMinElements[1]; tempMinElements[2]=(tempValueElement[2] < tempMinElements[2])? tempValueElement[2] :tempMinElements[2]; tempMaxElements[0]=(tempValueElement[0] > tempMaxElements[0])? tempValueElement[0] :tempMaxElements[0]; tempMaxElements[1]=(tempValueElement[1] > tempMaxElements[1])? tempValueElement[1] :tempMaxElements[1]; tempMaxElements[2]=(tempValueElement[2] > tempMaxElements[2])? tempValueElement[2] :tempMaxElements[2]; } Vector4.add(this._tempMax,this._tempMin,this._tempValue); tempValueElement[0] *=0.5; tempValueElement[1] *=0.5; tempValueElement[2] *=0.5; tempValueElement[3]=1; Vector4.transformByM4x4(this._tempValue,curLightCamera.transform.worldMatrix,this._tempValue); var distance=Math.abs(-this._tempMax.z); var farPlane=distance > this._maxDistance ? distance :this._maxDistance; Vector3.scale(this._globalParallelLightDir,farPlane,this._tempPos); var tempPosElement=this._tempPos.elements; tempPosElement[0]=tempValueElement[0]-tempPosElement[0]; tempPosElement[1]=tempValueElement[1]-tempPosElement[1]; tempPosElement[2]=tempValueElement[2]-tempPosElement[2]; curLightCamera.transform.position=this._tempPos; curLightCamera.transform.lookAt(this._tempLookAt3,this._tempLightUp,false); Matrix4x4.createOrthoOffCenterRH(tempMinElements[0],tempMaxElements[0],tempMinElements[1],tempMaxElements[1],1.0,farPlane+0.5 *(tempMaxElements[2]-tempMinElements[2]),curLightCamera.projectionMatrix); curLightCamera.projectionViewMatrix.cloneTo(this._lightVPMatrix[this._currentPSSM]); this._lightCulling[this._currentPSSM].matrix=this._lightVPMatrix[this._currentPSSM]; ParallelSplitShadowMap.multiplyMatrixOutFloat32Array(this._tempScaleMatrix44,this._lightVPMatrix[this._currentPSSM],this._shaderValueVPs[this._currentPSSM]); } __proto.getLightFrustumCulling=function(currentPSSM){ return this._lightCulling[currentPSSM]; } __proto.getSplitFrustumCulling=function(){ return this._splitFrustumCulling; } __proto.getSplitDistance=function(index){ return this._spiltDistance[index]; } __proto.setShadowMapTextureSize=function(size){ if (size!==this._shadowMapTextureSize){ this._shadowMapTextureSize=size; this._shadowPCFOffset.x=1 / this._shadowMapTextureSize; this._shadowPCFOffset.y=1 / this._shadowMapTextureSize; this._statesDirty=true; } } __proto.getShadowMapTextureSize=function(){ return this._shadowMapTextureSize; } __proto.beginRenderTarget=function(index){ this._renderTarget[index].start(); } __proto.endRenderTarget=function(index){ this._renderTarget[index].end(); } __proto.getRenderTarget=function(index){ return this._renderTarget[index]; } __proto.disposeAllRenderTarget=function(){ for (var i=0,n=this._numberOfPSSM+1;i < n;i++){ if (this._renderTarget[i]){ this._renderTarget[i].destroy(); this._renderTarget[i]=null; } } } __getset(0,__proto,'PSSMNum',function(){ return this._numberOfPSSM; },function(value){ value=value > 0 ? value :1; value=value <=3 ? value :3; if (this._numberOfPSSM !=value){ this._numberOfPSSM=value; this._ratioOfDistance=1.0 / this._numberOfPSSM; this._statesDirty=true; } }); ParallelSplitShadowMap.multiplyMatrixOutFloat32Array=function(left,right,out){ var i,a,b,ai0,ai1,ai2,ai3; a=left.elements; b=right.elements; for (i=0;i < 4;i++){ ai0=a[i]; ai1=a[i+4]; ai2=a[i+8]; ai3=a[i+12]; out[i]=ai0 *b[0]+ai1 *b[1]+ai2 *b[2]+ai3 *b[3]; out[i+4]=ai0 *b[4]+ai1 *b[5]+ai2 *b[6]+ai3 *b[7]; out[i+8]=ai0 *b[8]+ai1 *b[9]+ai2 *b[10]+ai3 *b[11]; out[i+12]=ai0 *b[12]+ai1 *b[13]+ai2 *b[14]+ai3 *b[15]; } } ParallelSplitShadowMap.SHADERDEFINE_RECEIVE_SHADOW=0x1; ParallelSplitShadowMap.SHADERDEFINE_CAST_SHADOW=0x200; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1=0x400; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2=0x800; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3=0x1000; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO=0x2000; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1=0x4000; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2=0x8000; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3=0x10000; ParallelSplitShadowMap.MAX_PSSM_COUNT=3; return ParallelSplitShadowMap; })() /** *TerrainLeaf Terrain的叶子节点 */ //class laya.d3.terrain.TerrainLeaf var TerrainLeaf=(function(){ function TerrainLeaf(){ this._boundingSphere=null; this._boundingBox=null; this._sizeOfY=null; this._currentLODLevel=0; this._lastDistanceToEye=NaN; this._originalBoundingSphere=null; this._originalBoundingBox=null; this._originalBoundingBoxCorners=null; this._bUseStrip=false; this._gridSize=NaN; this._beginGridX=0; //针对整个大地形的偏移 this._beginGridZ=0; //针对整个大地形的偏移 this._LODError=null; TerrainLeaf.__init__(); this._currentLODLevel=0; } __class(TerrainLeaf,'laya.d3.terrain.TerrainLeaf'); var __proto=TerrainLeaf.prototype; __proto.calcVertextNorml=function(x,z,terrainHeightData,heighDataWidth,heightDataHeight,normal){ var dZ=0,dX=0; dX=TerrainLeaf.getHeightFromTerrainHeightData(x-1,z-1,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dX+=TerrainLeaf.getHeightFromTerrainHeightData(x-1,z,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dX+=TerrainLeaf.getHeightFromTerrainHeightData(x-1,z+1,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dX+=TerrainLeaf.getHeightFromTerrainHeightData(x+1,z-1,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; dX+=TerrainLeaf.getHeightFromTerrainHeightData(x+1,z,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; dX+=TerrainLeaf.getHeightFromTerrainHeightData(x+1,z+1,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; dZ=TerrainLeaf.getHeightFromTerrainHeightData(x-1,z-1,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dZ+=TerrainLeaf.getHeightFromTerrainHeightData(x,z-1,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dZ+=TerrainLeaf.getHeightFromTerrainHeightData(x+1,z-1,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dZ+=TerrainLeaf.getHeightFromTerrainHeightData(x-1,z+1,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; dZ+=TerrainLeaf.getHeightFromTerrainHeightData(x,z+1,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; dZ+=TerrainLeaf.getHeightFromTerrainHeightData(x+1,z+1,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; normal.x=-dX; normal.y=6; normal.z=-dZ; Vector3.normalize(normal,normal); } __proto.calcVertextNormlUV=function(x,z,terrainWidth,terrainHeight,normal){ normal.x=x / terrainWidth; normal.y=z / terrainHeight; normal.z=z / terrainHeight; } __proto.calcVertextBuffer=function(offsetChunkX,offsetChunkZ,beginX,beginZ,girdSize,vertextBuffer,offset,strideSize,terrainHeightData,heighDataWidth,heightDataHeight,cameraCoordinateInverse){ if (cameraCoordinateInverse==true && !TerrainLeaf.__ADAPT_MATRIX__){ TerrainLeaf.__ADAPT_MATRIX__=new Matrix4x4(); var mat=new Matrix4x4(); Matrix4x4.createRotationY(Math.PI,TerrainLeaf.__ADAPT_MATRIX__); Matrix4x4.createTranslate(new Vector3(0,0,(heightDataHeight-1)*girdSize),mat); Matrix4x4.multiply(mat,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__ADAPT_MATRIX__); TerrainLeaf.__ADAPT_MATRIX_INV__=new Matrix4x4(); TerrainLeaf.__ADAPT_MATRIX__.invert(TerrainLeaf.__ADAPT_MATRIX_INV__); } this._gridSize=girdSize; this._beginGridX=offsetChunkX *TerrainLeaf.CHUNK_GRID_NUM+beginX; this._beginGridZ=offsetChunkZ *TerrainLeaf.CHUNK_GRID_NUM+beginZ; var nNum=offset *strideSize; var minY=2147483647; var maxY=-2147483648; var normal=new Vector3(); for (var i=0,s=TerrainLeaf.LEAF_GRID_NUM+1;i < s;i++){ for (var j=0,s1=TerrainLeaf.LEAF_GRID_NUM+1;j < s1;j++){ TerrainLeaf.__VECTOR3__.x=(this._beginGridX+j)*this._gridSize; TerrainLeaf.__VECTOR3__.z=(this._beginGridZ+i)*this._gridSize; TerrainLeaf.__VECTOR3__.y=terrainHeightData[(this._beginGridZ+i)*(heighDataWidth)+(this._beginGridX+j)]; minY=TerrainLeaf.__VECTOR3__.y < minY ? TerrainLeaf.__VECTOR3__.y :minY; maxY=TerrainLeaf.__VECTOR3__.y > maxY ? TerrainLeaf.__VECTOR3__.y :maxY; if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(TerrainLeaf.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__VECTOR3__); } vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.x; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.y; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.z; nNum++; this.calcVertextNormlUV(this._beginGridX+j,this._beginGridZ+i,heighDataWidth,heightDataHeight,normal); vertextBuffer[nNum]=normal.x; nNum++; vertextBuffer[nNum]=normal.y; nNum++; vertextBuffer[nNum]=normal.z; nNum++; vertextBuffer[nNum]=(beginX+j)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=(beginZ+i)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=this._beginGridX+j; nNum++; vertextBuffer[nNum]=this._beginGridZ+i; nNum++; } } this._sizeOfY=new Vector2(minY-1,maxY+1); this.calcLODErrors(terrainHeightData,heighDataWidth,heightDataHeight); this.calcOriginalBoudingBoxAndSphere(); } __proto.calcSkirtVertextBuffer=function(offsetChunkX,offsetChunkZ,beginX,beginZ,girdSize,vertextBuffer,offset,strideSize,terrainHeightData,heighDataWidth,heightDataHeight){ this._gridSize=girdSize; this._beginGridX=offsetChunkX *TerrainLeaf.CHUNK_GRID_NUM+beginX; this._beginGridZ=offsetChunkZ *TerrainLeaf.CHUNK_GRID_NUM+beginZ; var nNum=offset *strideSize; var i=0,j=0,s=TerrainLeaf.LEAF_GRID_NUM+1; var normal=new Vector3(); var hZIndex=0; var hXIndex=0; var h=0; var zh=0; var xh=0; for (i=0;i < 2;i++){ for (j=0;j < s;j++){ TerrainLeaf.__VECTOR3__.x=(this._beginGridX+j)*this._gridSize; TerrainLeaf.__VECTOR3__.y=(i==1 ? terrainHeightData[this._beginGridZ *heighDataWidth+(this._beginGridX+j)] :-this._gridSize); TerrainLeaf.__VECTOR3__.z=(this._beginGridZ+0)*this._gridSize; if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(TerrainLeaf.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__VECTOR3__); } vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.x; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.y; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.z; nNum++; if (i==0){ hZIndex=(this._beginGridZ-1); }else { hZIndex=this._beginGridZ; } this.calcVertextNormlUV(this._beginGridX+j,hZIndex,heighDataWidth,heightDataHeight,normal); vertextBuffer[nNum]=normal.x; nNum++; vertextBuffer[nNum]=normal.y; nNum++; vertextBuffer[nNum]=normal.z; nNum++; vertextBuffer[nNum]=(beginX+j)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=(beginZ+0)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=this._beginGridX+j; nNum++; vertextBuffer[nNum]=hZIndex; nNum++; } } for (i=0;i < 2;i++){ for (j=0;j < s;j++){ TerrainLeaf.__VECTOR3__.x=(this._beginGridX+j)*this._gridSize; TerrainLeaf.__VECTOR3__.y=(i==0 ? terrainHeightData[(this._beginGridZ+TerrainLeaf.LEAF_GRID_NUM)*(heighDataWidth)+(this._beginGridX+j)] :-this._gridSize); TerrainLeaf.__VECTOR3__.z=(this._beginGridZ+TerrainLeaf.LEAF_GRID_NUM)*this._gridSize; if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(TerrainLeaf.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__VECTOR3__); } vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.x; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.y; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.z; nNum++; if (i==0){ hZIndex=this._beginGridZ+TerrainLeaf.LEAF_GRID_NUM; }else { hZIndex=(this._beginGridZ+TerrainLeaf.LEAF_GRID_NUM+1); } this.calcVertextNormlUV(this._beginGridX+j,hZIndex,heighDataWidth,heightDataHeight,normal); vertextBuffer[nNum]=normal.x; nNum++; vertextBuffer[nNum]=normal.y; nNum++; vertextBuffer[nNum]=normal.z; nNum++; vertextBuffer[nNum]=(beginX+j)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=(beginZ+TerrainLeaf.LEAF_GRID_NUM)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=this._beginGridX+j; nNum++; vertextBuffer[nNum]=hZIndex; nNum++; } } for (i=0;i < 2;i++){ for (j=0;j < s;j++){ TerrainLeaf.__VECTOR3__.x=(this._beginGridX+0)*this._gridSize; TerrainLeaf.__VECTOR3__.y=(i==0 ? terrainHeightData[(this._beginGridZ+j)*(heighDataWidth)+(this._beginGridX+0)] :-this._gridSize); TerrainLeaf.__VECTOR3__.z=(this._beginGridZ+j)*this._gridSize; if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(TerrainLeaf.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__VECTOR3__); } vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.x; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.y; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.z; nNum++; if (i==0){ hXIndex=this._beginGridX; }else { hXIndex=(this._beginGridX-1); } this.calcVertextNormlUV(hXIndex,this._beginGridZ+j,heighDataWidth,heightDataHeight,normal); vertextBuffer[nNum]=normal.x; nNum++; vertextBuffer[nNum]=normal.y; nNum++; vertextBuffer[nNum]=normal.z; nNum++; vertextBuffer[nNum]=(beginX+0)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=(beginZ+j)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=hXIndex; nNum++; vertextBuffer[nNum]=this._beginGridZ+j; nNum++; } } for (i=0;i < 2;i++){ for (j=0;j < s;j++){ TerrainLeaf.__VECTOR3__.x=(this._beginGridX+TerrainLeaf.LEAF_GRID_NUM)*this._gridSize; TerrainLeaf.__VECTOR3__.y=(i==1 ? terrainHeightData[(this._beginGridZ+j)*(heighDataWidth)+(this._beginGridX+TerrainLeaf.LEAF_GRID_NUM)] :-this._gridSize); TerrainLeaf.__VECTOR3__.z=(this._beginGridZ+j)*this._gridSize; if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(TerrainLeaf.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__VECTOR3__); } vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.x; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.y; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.z; nNum++; if (i==0){ hXIndex=this._beginGridX+TerrainLeaf.LEAF_GRID_NUM+1; }else { hXIndex=this._beginGridX+TerrainLeaf.LEAF_GRID_NUM; } this.calcVertextNormlUV(hXIndex,this._beginGridZ+j,heighDataWidth,heightDataHeight,normal); vertextBuffer[nNum]=normal.x; nNum++; vertextBuffer[nNum]=normal.y; nNum++; vertextBuffer[nNum]=normal.z; nNum++; vertextBuffer[nNum]=(beginX+TerrainLeaf.LEAF_GRID_NUM)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=(beginZ+j)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=hXIndex; nNum++; vertextBuffer[nNum]=this._beginGridZ+j; nNum++; } } } __proto.calcOriginalBoudingBoxAndSphere=function(){ var min=new Vector3(this._beginGridX *this._gridSize,this._sizeOfY.x,this._beginGridZ *this._gridSize); var max=new Vector3((this._beginGridX+TerrainLeaf.LEAF_GRID_NUM)*this._gridSize,this._sizeOfY.y,(this._beginGridZ+TerrainLeaf.LEAF_GRID_NUM)*this._gridSize); if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(min,TerrainLeaf.__ADAPT_MATRIX__,min); Vector3.transformV3ToV3(max,TerrainLeaf.__ADAPT_MATRIX__,max); } this._originalBoundingBox=new BoundBox(min,max); var size=new Vector3(); Vector3.subtract(max,min,size); Vector3.scale(size,0.5,size); var center=new Vector3(); Vector3.add(min,size,center); this._originalBoundingSphere=new BoundSphere(center,Vector3.scalarLength(size)); this._originalBoundingBoxCorners=__newvec(8,null); this._originalBoundingBox.getCorners(this._originalBoundingBoxCorners); this._boundingBox=new BoundBox(new Vector3(-0.5,-0.5,-0.5),new Vector3(0.5,0.5,0.5)); this._boundingSphere=new BoundSphere(new Vector3(0,0,0),1); } __proto.calcLeafBoudingBox=function(worldMatrix){ for (var i=0;i < 8;i++){ Vector3.transformCoordinate(this._originalBoundingBoxCorners[i],worldMatrix,BaseRender._tempBoundBoxCorners[i]); } BoundBox.createfromPoints(BaseRender._tempBoundBoxCorners,this._boundingBox); } __proto.calcLeafBoudingSphere=function(worldMatrix,maxScale){ Vector3.transformCoordinate(this._originalBoundingSphere.center,worldMatrix,this._boundingSphere.center); this._boundingSphere.radius=this._originalBoundingSphere.radius *maxScale; } __proto.calcLODErrors=function(terrainHeightData,heighDataWidth,heightDataHeight){ this._LODError=new Float32Array(TerrainLeaf._maxLODLevel+1); var step=1; for (var i=0,n=TerrainLeaf._maxLODLevel+1;i < n;i++){ var maxError=0; for (var y=0,n1=TerrainLeaf.LEAF_GRID_NUM;y < n1;y+=step){ for (var x=0,n2=TerrainLeaf.LEAF_GRID_NUM;x < n2;x+=step){ var z00=terrainHeightData[(this._beginGridZ+y)*heighDataWidth+(this._beginGridX+x)]; var z10=terrainHeightData[(this._beginGridZ+y)*heighDataWidth+(this._beginGridX+x)+step]; var z01=terrainHeightData[(this._beginGridZ+y+step)*heighDataWidth+(this._beginGridX+x)]; var z11=terrainHeightData[(this._beginGridZ+y+step)*heighDataWidth+(this._beginGridX+x)+step]; for (var j=0;j < step;j++){ var ys=j / step; for (var k=0;k < step;k++){ var xs=k / step; var z=terrainHeightData[(this._beginGridZ+y+j)*heighDataWidth+(this._beginGridX+x)+k]; var iz=(xs+ys <=1)? (z00+(z10-z00)*xs+(z01-z00)*ys):(z11+(z01-z11)*(1-xs)+(z10-z11)*(1-ys)); var error=Math.abs(iz-z); maxError=Math.max(maxError,error); } } } } step *=2; this._LODError[i]=maxError; } } __proto.determineLod=function(eyePos,perspectiveFactor,tolerance,tolerAndPerspectiveChanged){ var nDistanceToEye=Vector3.distance(eyePos,this._boundingSphere.center); var n=TerrainLeaf._maxLODLevel; if (!tolerAndPerspectiveChanged){ if (this._lastDistanceToEye==nDistanceToEye){ return this._currentLODLevel; }else if (this._lastDistanceToEye > nDistanceToEye){ n=this._currentLODLevel; } } for (var i=n;i >=1;i--){ if (Terrain.LOD_DISTANCE_FACTOR *this._LODError[i] / nDistanceToEye *perspectiveFactor < tolerance){ this._currentLODLevel=i; break ; } } this._lastDistanceToEye=nDistanceToEye; return this._currentLODLevel; } TerrainLeaf.__init__=function(){ if (!TerrainLeaf._bInit){ var nLeafNum=(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM)*(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM); TerrainLeaf._planeLODIndex=__newvec(nLeafNum); var i=0,j=0,k=0,n=0,n1=0,nOffset=0; var nOriginIndexArray=null,nTempIndex=null; for (i=0;i < nLeafNum;i++){ TerrainLeaf._planeLODIndex[i]=new Array(TerrainLeaf._maxLODLevel+1); } for (i=0,n=TerrainLeaf._maxLODLevel+1;i < n;i++){ TerrainLeaf._planeLODIndex[0][i]=TerrainLeaf.calcPlaneLODIndex(i); } for (i=1;i < nLeafNum;i++){ nOffset=i *TerrainLeaf.LEAF_PLANE_VERTEXT_COUNT; for (j=0,n1=TerrainLeaf._maxLODLevel+1;j < n1;j++){ nOriginIndexArray=TerrainLeaf._planeLODIndex[0][j]; nTempIndex=new Uint16Array(nOriginIndexArray.length); for (k=0;k < nOriginIndexArray.length;k++){ nTempIndex[k]=nOriginIndexArray[k]+nOffset; } TerrainLeaf._planeLODIndex[i][j]=nTempIndex; } } TerrainLeaf._skirtLODIndex=__newvec(nLeafNum); for (i=0;i < nLeafNum;i++){ TerrainLeaf._skirtLODIndex[i]=new Array(TerrainLeaf._maxLODLevel+1); } for (i=0,n=TerrainLeaf._maxLODLevel+1;i < n;i++){ TerrainLeaf._skirtLODIndex[0][i]=TerrainLeaf.calcSkirtLODIndex(i); } for (i=1;i < nLeafNum;i++){ nOffset=i *TerrainLeaf.LEAF_SKIRT_VERTEXT_COUNT; for (j=0,n1=TerrainLeaf._maxLODLevel+1;j < n1;j++){ nOriginIndexArray=TerrainLeaf._skirtLODIndex[0][j]; nTempIndex=new Uint16Array(nOriginIndexArray.length); for (k=0;k < nOriginIndexArray.length;k++){ nTempIndex[k]=nOriginIndexArray[k]+nOffset; } TerrainLeaf._skirtLODIndex[i][j]=nTempIndex; } } TerrainLeaf._bInit=true; } } TerrainLeaf.getPlaneLODIndex=function(leafIndex,LODLevel){ return TerrainLeaf._planeLODIndex[leafIndex][LODLevel]; } TerrainLeaf.getSkirtLODIndex=function(leafIndex,LODLevel){ return TerrainLeaf._skirtLODIndex[leafIndex][LODLevel]; } TerrainLeaf.calcPlaneLODIndex=function(level){ if (level > TerrainLeaf._maxLODLevel)level=TerrainLeaf._maxLODLevel; var nGridNumAddOne=TerrainLeaf.LEAF_GRID_NUM+1; var nNum=0; var indexBuffer=null; var nLODGridNum=laya.d3.terrain.TerrainLeaf.LEAF_GRID_NUM / Math.pow(2,level); indexBuffer=new Uint16Array(nLODGridNum *nLODGridNum *6); var nGridSpace=laya.d3.terrain.TerrainLeaf.LEAF_GRID_NUM / nLODGridNum; for (var i=0;i < TerrainLeaf.LEAF_GRID_NUM;i+=nGridSpace){ for (var j=0;j < TerrainLeaf.LEAF_GRID_NUM;j+=nGridSpace){ indexBuffer[nNum]=(i+nGridSpace)*nGridNumAddOne+j; nNum++; indexBuffer[nNum]=i *nGridNumAddOne+j; nNum++; indexBuffer[nNum]=i *nGridNumAddOne+j+nGridSpace; nNum++; indexBuffer[nNum]=i *nGridNumAddOne+j+nGridSpace; nNum++; indexBuffer[nNum]=(i+nGridSpace)*nGridNumAddOne+j+nGridSpace; nNum++; indexBuffer[nNum]=(i+nGridSpace)*nGridNumAddOne+j; nNum++; } } return indexBuffer; } TerrainLeaf.calcSkirtLODIndex=function(level){ if (level > TerrainLeaf._maxLODLevel)level=TerrainLeaf._maxLODLevel; var nSkirtIndexOffset=(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM)*(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM)*TerrainLeaf.LEAF_PLANE_VERTEXT_COUNT; var nGridNumAddOne=TerrainLeaf.LEAF_GRID_NUM+1; var nNum=0; var indexBuffer=null; var nLODGridNum=laya.d3.terrain.TerrainLeaf.LEAF_GRID_NUM / Math.pow(2,level); indexBuffer=new Uint16Array(nLODGridNum *4 *6); var nGridSpace=laya.d3.terrain.TerrainLeaf.LEAF_GRID_NUM / nLODGridNum; for (var j=0;j < 4;j++){ for (var i=0;i < TerrainLeaf.LEAF_GRID_NUM;i+=nGridSpace){ indexBuffer[nNum]=nSkirtIndexOffset+nGridNumAddOne+i; nNum++; indexBuffer[nNum]=nSkirtIndexOffset+i; nNum++; indexBuffer[nNum]=nSkirtIndexOffset+i+nGridSpace; nNum++; indexBuffer[nNum]=nSkirtIndexOffset+i+nGridSpace; nNum++; indexBuffer[nNum]=nSkirtIndexOffset+nGridNumAddOne+i+nGridSpace; nNum++; indexBuffer[nNum]=nSkirtIndexOffset+nGridNumAddOne+i; nNum++; } nSkirtIndexOffset+=nGridNumAddOne *2; } return indexBuffer; } TerrainLeaf.getHeightFromTerrainHeightData=function(x,z,terrainHeightData,heighDataWidth,heightDataHeight){ x=x < 0 ? 0 :x; x=(x >=heighDataWidth)? heighDataWidth-1 :x; z=z < 0 ? 0 :z; z=(z >=heightDataHeight)? heightDataHeight-1 :z; return terrainHeightData[z *heighDataWidth+x]; } TerrainLeaf.CHUNK_GRID_NUM=64; TerrainLeaf.LEAF_GRID_NUM=32; TerrainLeaf.__ADAPT_MATRIX__=null; TerrainLeaf.__ADAPT_MATRIX_INV__=null; TerrainLeaf._planeLODIndex=null; TerrainLeaf._skirtLODIndex=null; TerrainLeaf._bInit=false; __static(TerrainLeaf, ['LEAF_PLANE_VERTEXT_COUNT',function(){return this.LEAF_PLANE_VERTEXT_COUNT=(TerrainLeaf.LEAF_GRID_NUM+1)*(TerrainLeaf.LEAF_GRID_NUM+1);},'LEAF_SKIRT_VERTEXT_COUNT',function(){return this.LEAF_SKIRT_VERTEXT_COUNT=(TerrainLeaf.LEAF_GRID_NUM+1)*2 *4;},'LEAF_VERTEXT_COUNT',function(){return this.LEAF_VERTEXT_COUNT=TerrainLeaf.LEAF_PLANE_VERTEXT_COUNT+TerrainLeaf.LEAF_SKIRT_VERTEXT_COUNT;},'LEAF_PLANE_MAX_INDEX_COUNT',function(){return this.LEAF_PLANE_MAX_INDEX_COUNT=TerrainLeaf.LEAF_GRID_NUM *TerrainLeaf.LEAF_GRID_NUM *6;},'LEAF_SKIRT_MAX_INDEX_COUNT',function(){return this.LEAF_SKIRT_MAX_INDEX_COUNT=TerrainLeaf.LEAF_GRID_NUM *4 *6;},'LEAF_MAX_INDEX_COUNT',function(){return this.LEAF_MAX_INDEX_COUNT=TerrainLeaf.LEAF_PLANE_MAX_INDEX_COUNT+TerrainLeaf.LEAF_SKIRT_MAX_INDEX_COUNT;},'__VECTOR3__',function(){return this.__VECTOR3__=new Vector3();},'_maxLODLevel',function(){return this._maxLODLevel=/*__JS__ */Math.log2(TerrainLeaf.LEAF_GRID_NUM);} ]); return TerrainLeaf; })() /** *DetailTextureInfo 类用于描述地形细节纹理。 */ //class laya.d3.terrain.unit.ChunkInfo var ChunkInfo=(function(){ function ChunkInfo(){ this.alphaMap=null; this.detailID=null; this.normalMap=null; ; } __class(ChunkInfo,'laya.d3.terrain.unit.ChunkInfo'); return ChunkInfo; })() /** *DetailTextureInfo 类用于描述地形细节纹理。 */ //class laya.d3.terrain.unit.DetailTextureInfo var DetailTextureInfo=(function(){ function DetailTextureInfo(){ this.diffuseTexture=null; this.normalTexture=null; this.scale=null; this.offset=null; ; } __class(DetailTextureInfo,'laya.d3.terrain.unit.DetailTextureInfo'); return DetailTextureInfo; })() /** *MaterialInfo 类用于描述地形材质信息。 */ //class laya.d3.terrain.unit.MaterialInfo var MaterialInfo=(function(){ function MaterialInfo(){ this.ambientColor=null; this.diffuseColor=null; this.specularColor=null; ; } __class(MaterialInfo,'laya.d3.terrain.unit.MaterialInfo'); return MaterialInfo; })() /** *Physics 类用于简单物理检测。 */ //class laya.d3.utils.Physics var Physics=(function(){ /** *创建一个 Physics 实例。 */ function Physics(){} __class(Physics,'laya.d3.utils.Physics'); Physics.__init__=function(){ var maxCount=/*laya.d3.core.Layer.maxCount*/31; Physics._layerCollsionMatrix.length=maxCount; for (var i=0;i < maxCount;i++){ var collArray=[]; var count=maxCount-i; collArray.length=count; for (var j=0;j < count;j++) if (j===count-1) collArray[j]=true; else collArray[j]=false; Physics._layerCollsionMatrix[i]=collArray; } } Physics.setLayerCollision=function(layer1,layer2,collison){ Physics._layerCollsionMatrix[layer1.number][(/*laya.d3.core.Layer.maxCount*/31-1)-layer2.number]=collison; } Physics.getLayerCollision=function(layer1,layer2){ return Physics._layerCollsionMatrix[layer1.number][(/*laya.d3.core.Layer.maxCount*/31-1)-layer2.number]; } Physics.setColliderCollision=function(collider1,collider2,collsion){ if (collsion){ delete collider1._ignoreCollisonMap[collider2.id]; delete collider2._ignoreCollisonMap[collider1.id]; }else { collider1._ignoreCollisonMap[collider2.id]=collider2; collider2._ignoreCollisonMap[collider1.id]=collider1; } } Physics.getIColliderCollision=function(collider1,collider2){ return collider1._ignoreCollisonMap[collider2.id] ? true :false; } Physics.rayCast=function(ray,outHitInfo,distance,layer){ (distance===void 0)&& (distance=1.79e+308); (layer===void 0)&& (layer=0); Physics._outHitAllInfo.length=0; var colliders=Layer.getLayerByNumber(layer)._colliders; for (var i=0,n=colliders.length;i < n;i++){ var collider=colliders[i]; if (collider.enable){ collider.raycast(ray,Physics._outHitInfo,distance); if (Physics._outHitInfo.distance!==-1 && Physics._outHitInfo.distance <=distance){ var outHit=new RaycastHit(); Physics._outHitInfo.cloneTo(outHit); Physics._outHitAllInfo.push(outHit); } } } if (Physics._outHitAllInfo.length==0){ outHitInfo.sprite3D=null; outHitInfo.distance=-1; return; }; var minDistance=Number.MAX_VALUE; var minIndex=0; for (var j=0;j < Physics._outHitAllInfo.length;j++){ if (Physics._outHitAllInfo[j].distance < minDistance){ minDistance=Physics._outHitAllInfo[j].distance; minIndex=j; } } Physics._outHitAllInfo[minIndex].cloneTo(outHitInfo); } Physics.rayCastAll=function(ray,outHitAllInfo,distance,layer){ (distance===void 0)&& (distance=1.79e+308); (layer===void 0)&& (layer=0); outHitAllInfo.length=0; var colliders=Layer.getLayerByNumber(layer)._colliders; for (var i=0,n=colliders.length;i < n;i++){ var collider=colliders[i]; if (collider.enable){ Physics._outHitInfo.distance=-1; Physics._outHitInfo.sprite3D=null; collider.raycast(ray,Physics._outHitInfo,distance); if (Physics._outHitInfo.distance!==-1 && Physics._outHitInfo.distance <=distance){ var outHit=new RaycastHit(); Physics._outHitInfo.cloneTo(outHit); outHitAllInfo.push(outHit); } } } } Physics._outHitAllInfo=[]; Physics._layerCollsionMatrix=[]; __static(Physics, ['_outHitInfo',function(){return this._outHitInfo=new RaycastHit();},'collisionManager',function(){return this.collisionManager=new CollisionManager();},'gravity',function(){return this.gravity=new Vector3(0,-9.81,0);} ]); return Physics; })() /** *Picker 类用于创建拾取。 */ //class laya.d3.utils.Picker var Picker=(function(){ /** *创建一个 Picker 实例。 */ function Picker(){} __class(Picker,'laya.d3.utils.Picker'); Picker.calculateCursorRay=function(point,viewPort,projectionMatrix,viewMatrix,world,out){ var x=point.elements[0]; var y=point.elements[1]; var nearSource=Picker._tempVector30; var nerSourceE=nearSource.elements; nerSourceE[0]=x; nerSourceE[1]=y; nerSourceE[2]=viewPort.minDepth; var farSource=Picker._tempVector31; var farSourceE=farSource.elements; farSourceE[0]=x; farSourceE[1]=y; farSourceE[2]=viewPort.maxDepth; var nearPoint=out.origin; var farPoint=Picker._tempVector32; viewPort.unprojectFromWVP(nearSource,projectionMatrix,viewMatrix,world,nearPoint); viewPort.unprojectFromWVP(farSource,projectionMatrix,viewMatrix,world,farPoint); var outDire=out.direction.elements; outDire[0]=farPoint.x-nearPoint.x; outDire[1]=farPoint.y-nearPoint.y; outDire[2]=farPoint.z-nearPoint.z; Vector3.normalize(out.direction,out.direction); } Picker.rayIntersectsPositionsAndIndices=function(ray,vertexDatas,vertexDeclaration,indices,outHitInfo){ var vertexStrideFloatCount=vertexDeclaration.vertexStride / 4; var positionVertexElementOffset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.POSITION0*/0).offset / 4; var closestIntersection=Number.MAX_VALUE; var closestTriangleVertexIndex1=-1; var closestTriangleVertexIndex2=-1; var closestTriangleVertexIndex3=-1; for (var j=0;j < indices.length;j+=3){ var vertex1=Picker._tempVector35; var vertex1E=vertex1.elements; var vertex1Index=indices[j] *vertexStrideFloatCount; var vertex1PositionIndex=vertex1Index+positionVertexElementOffset; vertex1E[0]=vertexDatas[vertex1PositionIndex]; vertex1E[1]=vertexDatas[vertex1PositionIndex+1]; vertex1E[2]=vertexDatas[vertex1PositionIndex+2]; var vertex2=Picker._tempVector36; var vertex2E=vertex2.elements; var vertex2Index=indices[j+1] *vertexStrideFloatCount; var vertex2PositionIndex=vertex2Index+positionVertexElementOffset; vertex2E[0]=vertexDatas[vertex2PositionIndex]; vertex2E[1]=vertexDatas[vertex2PositionIndex+1]; vertex2E[2]=vertexDatas[vertex2PositionIndex+2]; var vertex3=Picker._tempVector37; var vertex3E=vertex3.elements; var vertex3Index=indices[j+2] *vertexStrideFloatCount; var vertex3PositionIndex=vertex3Index+positionVertexElementOffset; vertex3E[0]=vertexDatas[vertex3PositionIndex]; vertex3E[1]=vertexDatas[vertex3PositionIndex+1]; vertex3E[2]=vertexDatas[vertex3PositionIndex+2]; var intersection=laya.d3.utils.Picker.rayIntersectsTriangle(ray,vertex1,vertex2,vertex3); if (!isNaN(intersection)&& intersection < closestIntersection){ closestIntersection=intersection; closestTriangleVertexIndex1=vertex1Index; closestTriangleVertexIndex2=vertex2Index; closestTriangleVertexIndex3=vertex3Index; } } if (closestIntersection!==Number.MAX_VALUE){ outHitInfo.distance=closestIntersection; Vector3.scale(ray.direction,closestIntersection,outHitInfo.position); Vector3.add(ray.origin,outHitInfo.position,outHitInfo.position); var trianglePositions=outHitInfo.trianglePositions; var position0=trianglePositions[0]; var position1=trianglePositions[1]; var position2=trianglePositions[2]; var position0E=position0.elements; var position1E=position1.elements; var position2E=position2.elements; var closestVertex1PositionIndex=closestTriangleVertexIndex1+positionVertexElementOffset; position0E[0]=vertexDatas[closestVertex1PositionIndex]; position0E[1]=vertexDatas[closestVertex1PositionIndex+1]; position0E[2]=vertexDatas[closestVertex1PositionIndex+2]; var closestVertex2PositionIndex=closestTriangleVertexIndex2+positionVertexElementOffset; position1E[0]=vertexDatas[closestVertex2PositionIndex]; position1E[1]=vertexDatas[closestVertex2PositionIndex+1]; position1E[2]=vertexDatas[closestVertex2PositionIndex+2]; var closestVertex3PositionIndex=closestTriangleVertexIndex3+positionVertexElementOffset; position2E[0]=vertexDatas[closestVertex3PositionIndex]; position2E[1]=vertexDatas[closestVertex3PositionIndex+1]; position2E[2]=vertexDatas[closestVertex3PositionIndex+2]; var normalVertexElement=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3); if (normalVertexElement){ var normalVertexElementOffset=normalVertexElement.offset / 4; var triangleNormals=outHitInfo.triangleNormals; var normal0=triangleNormals[0]; var normal1=triangleNormals[1]; var normal2=triangleNormals[2]; var normal0E=normal0.elements; var normal1E=normal1.elements; var normal2E=normal2.elements; var closestVertex1NormalIndex=closestTriangleVertexIndex1+normalVertexElementOffset; normal0E[0]=vertexDatas[closestVertex1NormalIndex]; normal0E[1]=vertexDatas[closestVertex1NormalIndex+1]; normal0E[2]=vertexDatas[closestVertex1NormalIndex+2]; var closestVertex2NormalIndex=closestTriangleVertexIndex2+normalVertexElementOffset; normal1E[0]=vertexDatas[closestVertex2NormalIndex]; normal1E[1]=vertexDatas[closestVertex2NormalIndex+1]; normal1E[2]=vertexDatas[closestVertex2NormalIndex+2]; var closestVertex3NormalIndex=closestTriangleVertexIndex3+normalVertexElementOffset; normal2E[0]=vertexDatas[closestVertex3NormalIndex]; normal2E[1]=vertexDatas[closestVertex3NormalIndex+1]; normal2E[2]=vertexDatas[closestVertex3NormalIndex+2]; } return true; }else { outHitInfo.position.toDefault(); outHitInfo.distance=Number.MAX_VALUE; outHitInfo.trianglePositions[0].toDefault(); outHitInfo.trianglePositions[1].toDefault(); outHitInfo.trianglePositions[2].toDefault(); outHitInfo.triangleNormals[0].toDefault(); outHitInfo.triangleNormals[1].toDefault(); outHitInfo.triangleNormals[2].toDefault(); return false; } } Picker.rayIntersectsTriangle=function(ray,vertex1,vertex2,vertex3){ var result; var edge1=Picker._tempVector30,edge2=Picker._tempVector31; Vector3.subtract(vertex2,vertex1,edge1); Vector3.subtract(vertex3,vertex1,edge2); var directionCrossEdge2=Picker._tempVector32; Vector3.cross(ray.direction,edge2,directionCrossEdge2); var determinant; determinant=Vector3.dot(edge1,directionCrossEdge2); if (determinant >-Number.MIN_VALUE && determinant < Number.MIN_VALUE){ result=Number.NaN; return result; }; var inverseDeterminant=1.0 / determinant; var distanceVector=Picker._tempVector33; Vector3.subtract(ray.origin,vertex1,distanceVector); var triangleU; triangleU=Vector3.dot(distanceVector,directionCrossEdge2); triangleU *=inverseDeterminant; if (triangleU < 0 || triangleU > 1){ result=Number.NaN; return result; }; var distanceCrossEdge1=Picker._tempVector34; Vector3.cross(distanceVector,edge1,distanceCrossEdge1); var triangleV; triangleV=Vector3.dot(ray.direction,distanceCrossEdge1); triangleV *=inverseDeterminant; if (triangleV < 0 || triangleU+triangleV > 1){ result=Number.NaN; return result; }; var rayDistance; rayDistance=Vector3.dot(edge2,distanceCrossEdge1); rayDistance *=inverseDeterminant; if (rayDistance < 0){ result=Number.NaN; return result; } result=rayDistance; return result; } __static(Picker, ['_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempVector31',function(){return this._tempVector31=new Vector3();},'_tempVector32',function(){return this._tempVector32=new Vector3();},'_tempVector33',function(){return this._tempVector33=new Vector3();},'_tempVector34',function(){return this._tempVector34=new Vector3();},'_tempVector35',function(){return this._tempVector35=new Vector3();},'_tempVector36',function(){return this._tempVector36=new Vector3();},'_tempVector37',function(){return this._tempVector37=new Vector3();} ]); return Picker; })() /** *... *@author ... */ //class laya.d3.utils.RaycastHit var RaycastHit=(function(){ function RaycastHit(){ this.distance=NaN; this.trianglePositions=null; this.triangleNormals=null; this.position=null; this.sprite3D=null; this.distance=-1; this.trianglePositions=[new Vector3(),new Vector3(),new Vector3()]; this.trianglePositions.length=3; this.triangleNormals=[new Vector3(),new Vector3(),new Vector3()]; this.triangleNormals.length=3; this.position=new Vector3(); } __class(RaycastHit,'laya.d3.utils.RaycastHit'); var __proto=RaycastHit.prototype; __proto.cloneTo=function(dec){ dec.distance=this.distance; this.trianglePositions[0].cloneTo(dec.trianglePositions[0]); this.trianglePositions[1].cloneTo(dec.trianglePositions[1]); this.trianglePositions[2].cloneTo(dec.trianglePositions[2]); this.triangleNormals[0].cloneTo(dec.triangleNormals[0]); this.triangleNormals[1].cloneTo(dec.triangleNormals[1]); this.triangleNormals[2].cloneTo(dec.triangleNormals[2]); this.position.cloneTo(dec.position); dec.sprite3D=this.sprite3D; } return RaycastHit; })() //class laya.d3.utils.Size var Size=(function(){ function Size(width,height){ this._width=0; this._height=0; this._width=width; this._height=height; } __class(Size,'laya.d3.utils.Size'); var __proto=Size.prototype; __getset(0,__proto,'width',function(){ if (this._width===-1) return RenderState.clientWidth; return this._width; }); __getset(0,__proto,'height',function(){ if (this._height===-1) return RenderState.clientHeight; return this._height; }); __getset(1,Size,'fullScreen',function(){ return new Size(-1,-1); }); return Size; })() /** *Utils3D 类用于创建3D工具。 */ //class laya.d3.utils.Utils3D var Utils3D=(function(){ function Utils3D(){} __class(Utils3D,'laya.d3.utils.Utils3D'); Utils3D._rotationTransformScaleSkinAnimation=function(tx,ty,tz,qx,qy,qz,qw,sx,sy,sz,outArray,outOffset){ var re=Utils3D._tempArray16_0; var se=Utils3D._tempArray16_1; var tse=Utils3D._tempArray16_2; var x2=qx+qx; var y2=qy+qy; var z2=qz+qz; var xx=qx *x2; var yx=qy *x2; var yy=qy *y2; var zx=qz *x2; var zy=qz *y2; var zz=qz *z2; var wx=qw *x2; var wy=qw *y2; var wz=qw *z2; re[15]=1; re[0]=1-yy-zz; re[1]=yx+wz; re[2]=zx-wy; re[4]=yx-wz; re[5]=1-xx-zz; re[6]=zy+wx; re[8]=zx+wy; re[9]=zy-wx; re[10]=1-xx-yy; se[15]=1; se[0]=sx; se[5]=sy; se[10]=sz; var i,a,b,e,ai0,ai1,ai2,ai3; for (i=0;i < 4;i++){ ai0=re[i]; ai1=re[i+4]; ai2=re[i+8]; ai3=re[i+12]; tse[i]=ai0; tse[i+4]=ai1; tse[i+8]=ai2; tse[i+12]=ai0 *tx+ai1 *ty+ai2 *tz+ai3; } for (i=0;i < 4;i++){ ai0=tse[i]; ai1=tse[i+4]; ai2=tse[i+8]; ai3=tse[i+12]; outArray[i+outOffset]=ai0 *se[0]+ai1 *se[1]+ai2 *se[2]+ai3 *se[3]; outArray[i+outOffset+4]=ai0 *se[4]+ai1 *se[5]+ai2 *se[6]+ai3 *se[7]; outArray[i+outOffset+8]=ai0 *se[8]+ai1 *se[9]+ai2 *se[10]+ai3 *se[11]; outArray[i+outOffset+12]=ai0 *se[12]+ai1 *se[13]+ai2 *se[14]+ai3 *se[15]; } } Utils3D._createNodeByJson=function(rootNode,nodeData,node,innerResouMap){ if (!node){ switch (nodeData.type){ case "Sprite3D": node=new Sprite3D(); break ; case "MeshSprite3D": node=new MeshSprite3D(); break ; case "SkinnedMeshSprite3D": node=new SkinnedMeshSprite3D(); break ; case "ShuriKenParticle3D": node=new ShuriKenParticle3D(); break ; case "TrailSprite3D": node=new TrailSprite3D(); break ; break ; case "Terrain": node=new Terrain(); break ; case "Camera": node=new Camera(); break ; case "DirectionLight": node=new DirectionLight(); break ; default : throw new Error("Utils3D:unidentified class type in (.lh) file."); } }; var props=nodeData.props; if (props) for (var key in props) node[key]=props[key]; var customProps=nodeData.customProps; if (customProps){ if ((node instanceof laya.d3.core.Sprite3D )){ node._parseBaseCustomProps(customProps); node._parseCustomProps(rootNode,innerResouMap,customProps,nodeData); node._parseCustomComponent(rootNode,innerResouMap,nodeData.components); }else { node._parseCustomProps(rootNode,innerResouMap,customProps,nodeData); } }; var childData=nodeData.child; if (childData){ for (var i=0,n=childData.length;i < n;i++){ var child=Utils3D._createNodeByJson(rootNode,childData[i],null,innerResouMap) node.addChild(child); } } return node; } Utils3D._computeBoneAndAnimationDatasByBindPoseMatrxix=function(bones,curData,inverGlobalBindPose,outBonesDatas,outAnimationDatas,boneIndexToMesh){ var offset=0; var matOffset=0; var i; var parentOffset; var boneLength=bones.length; for (i=0;i < boneLength;offset+=bones[i].keyframeWidth,matOffset+=16,i++){ laya.d3.utils.Utils3D._rotationTransformScaleSkinAnimation(curData[offset+0],curData[offset+1],curData[offset+2],curData[offset+3],curData[offset+4],curData[offset+5],curData[offset+6],curData[offset+7],curData[offset+8],curData[offset+9],outBonesDatas,matOffset); if (i !=0){ parentOffset=bones[i].parentIndex *16; laya.d3.utils.Utils3D.mulMatrixByArray(outBonesDatas,parentOffset,outBonesDatas,matOffset,outBonesDatas,matOffset); } }; var n=inverGlobalBindPose.length; for (i=0;i < n;i++){ laya.d3.utils.Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas,boneIndexToMesh[i] *16,inverGlobalBindPose[i],outAnimationDatas,i *16); } } Utils3D._computeAnimationDatasByArrayAndMatrixFast=function(inverGlobalBindPose,bonesDatas,outAnimationDatas,boneIndexToMesh){ for (var i=0,n=inverGlobalBindPose.length;i < n;i++) laya.d3.utils.Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas,boneIndexToMesh[i] *16,inverGlobalBindPose[i],outAnimationDatas,i *16); } Utils3D._computeBoneAndAnimationDatasByBindPoseMatrxixOld=function(bones,curData,inverGlobalBindPose,outBonesDatas,outAnimationDatas){ var offset=0; var matOffset=0; var i; var parentOffset; var boneLength=bones.length; for (i=0;i < boneLength;offset+=bones[i].keyframeWidth,matOffset+=16,i++){ laya.d3.utils.Utils3D._rotationTransformScaleSkinAnimation(curData[offset+7],curData[offset+8],curData[offset+9],curData[offset+3],curData[offset+4],curData[offset+5],curData[offset+6],curData[offset+0],curData[offset+1],curData[offset+2],outBonesDatas,matOffset); if (i !=0){ parentOffset=bones[i].parentIndex *16; laya.d3.utils.Utils3D.mulMatrixByArray(outBonesDatas,parentOffset,outBonesDatas,matOffset,outBonesDatas,matOffset); } }; var n=inverGlobalBindPose.length; for (i=0;i < n;i++){ var arrayOffset=i *16; laya.d3.utils.Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas,arrayOffset,inverGlobalBindPose[i],outAnimationDatas,arrayOffset); } } Utils3D._computeAnimationDatasByArrayAndMatrixFastOld=function(inverGlobalBindPose,bonesDatas,outAnimationDatas){ var n=inverGlobalBindPose.length; for (var i=0;i < n;i++){ var arrayOffset=i *16; laya.d3.utils.Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas,arrayOffset,inverGlobalBindPose[i],outAnimationDatas,arrayOffset); } } Utils3D._computeRootAnimationData=function(bones,curData,animationDatas){ for (var i=0,offset=0,matOffset=0,boneLength=bones.length;i < boneLength;offset+=bones[i].keyframeWidth,matOffset+=16,i++) laya.d3.utils.Utils3D.createAffineTransformationArray(curData[offset+0],curData[offset+1],curData[offset+2],curData[offset+3],curData[offset+4],curData[offset+5],curData[offset+6],curData[offset+7],curData[offset+8],curData[offset+9],animationDatas,matOffset); } Utils3D.transformVector3ArrayByQuat=function(sourceArray,sourceOffset,rotation,outArray,outOffset){ var re=rotation.elements; var x=sourceArray[sourceOffset],y=sourceArray[sourceOffset+1],z=sourceArray[sourceOffset+2],qx=re[0],qy=re[1],qz=re[2],qw=re[3],ix=qw *x+qy *z-qz *y,iy=qw *y+qz *x-qx *z,iz=qw *z+qx *y-qy *x,iw=-qx *x-qy *y-qz *z; outArray[outOffset]=ix *qw+iw *-qx+iy *-qz-iz *-qy; outArray[outOffset+1]=iy *qw+iw *-qy+iz *-qx-ix *-qz; outArray[outOffset+2]=iz *qw+iw *-qz+ix *-qy-iy *-qx; } Utils3D.mulMatrixByArray=function(leftArray,leftOffset,rightArray,rightOffset,outArray,outOffset){ var i,ai0,ai1,ai2,ai3; if (outArray===rightArray){ rightArray=Utils3D._tempArray16_3; for (i=0;i < 16;++i){ rightArray[i]=outArray[outOffset+i]; } rightOffset=0; } for (i=0;i < 4;i++){ ai0=leftArray[leftOffset+i]; ai1=leftArray[leftOffset+i+4]; ai2=leftArray[leftOffset+i+8]; ai3=leftArray[leftOffset+i+12]; outArray[outOffset+i]=ai0 *rightArray[rightOffset+0]+ai1 *rightArray[rightOffset+1]+ai2 *rightArray[rightOffset+2]+ai3 *rightArray[rightOffset+3]; outArray[outOffset+i+4]=ai0 *rightArray[rightOffset+4]+ai1 *rightArray[rightOffset+5]+ai2 *rightArray[rightOffset+6]+ai3 *rightArray[rightOffset+7]; outArray[outOffset+i+8]=ai0 *rightArray[rightOffset+8]+ai1 *rightArray[rightOffset+9]+ai2 *rightArray[rightOffset+10]+ai3 *rightArray[rightOffset+11]; outArray[outOffset+i+12]=ai0 *rightArray[rightOffset+12]+ai1 *rightArray[rightOffset+13]+ai2 *rightArray[rightOffset+14]+ai3 *rightArray[rightOffset+15]; } } Utils3D.mulMatrixByArrayFast=function(leftArray,leftOffset,rightArray,rightOffset,outArray,outOffset){ var i,ai0,ai1,ai2,ai3; for (i=0;i < 4;i++){ ai0=leftArray[leftOffset+i]; ai1=leftArray[leftOffset+i+4]; ai2=leftArray[leftOffset+i+8]; ai3=leftArray[leftOffset+i+12]; outArray[outOffset+i]=ai0 *rightArray[rightOffset+0]+ai1 *rightArray[rightOffset+1]+ai2 *rightArray[rightOffset+2]+ai3 *rightArray[rightOffset+3]; outArray[outOffset+i+4]=ai0 *rightArray[rightOffset+4]+ai1 *rightArray[rightOffset+5]+ai2 *rightArray[rightOffset+6]+ai3 *rightArray[rightOffset+7]; outArray[outOffset+i+8]=ai0 *rightArray[rightOffset+8]+ai1 *rightArray[rightOffset+9]+ai2 *rightArray[rightOffset+10]+ai3 *rightArray[rightOffset+11]; outArray[outOffset+i+12]=ai0 *rightArray[rightOffset+12]+ai1 *rightArray[rightOffset+13]+ai2 *rightArray[rightOffset+14]+ai3 *rightArray[rightOffset+15]; } } Utils3D.mulMatrixByArrayAndMatrixFast=function(leftArray,leftOffset,rightMatrix,outArray,outOffset){ var i,ai0,ai1,ai2,ai3; var rightMatrixE=rightMatrix.elements; var m11=rightMatrixE[0],m12=rightMatrixE[1],m13=rightMatrixE[2],m14=rightMatrixE[3]; var m21=rightMatrixE[4],m22=rightMatrixE[5],m23=rightMatrixE[6],m24=rightMatrixE[7]; var m31=rightMatrixE[8],m32=rightMatrixE[9],m33=rightMatrixE[10],m34=rightMatrixE[11]; var m41=rightMatrixE[12],m42=rightMatrixE[13],m43=rightMatrixE[14],m44=rightMatrixE[15]; var ai0LeftOffset=leftOffset; var ai1LeftOffset=leftOffset+4; var ai2LeftOffset=leftOffset+8; var ai3LeftOffset=leftOffset+12; var ai0OutOffset=outOffset; var ai1OutOffset=outOffset+4; var ai2OutOffset=outOffset+8; var ai3OutOffset=outOffset+12; for (i=0;i < 4;i++){ ai0=leftArray[ai0LeftOffset+i]; ai1=leftArray[ai1LeftOffset+i]; ai2=leftArray[ai2LeftOffset+i]; ai3=leftArray[ai3LeftOffset+i]; outArray[ai0OutOffset+i]=ai0 *m11+ai1 *m12+ai2 *m13+ai3 *m14; outArray[ai1OutOffset+i]=ai0 *m21+ai1 *m22+ai2 *m23+ai3 *m24; outArray[ai2OutOffset+i]=ai0 *m31+ai1 *m32+ai2 *m33+ai3 *m34; outArray[ai3OutOffset+i]=ai0 *m41+ai1 *m42+ai2 *m43+ai3 *m44; } } Utils3D.createAffineTransformationArray=function(tX,tY,tZ,rX,rY,rZ,rW,sX,sY,sZ,outArray,outOffset){ var x2=rX+rX,y2=rY+rY,z2=rZ+rZ; var xx=rX *x2,xy=rX *y2,xz=rX *z2,yy=rY *y2,yz=rY *z2,zz=rZ *z2; var wx=rW *x2,wy=rW *y2,wz=rW *z2; outArray[outOffset+0]=(1-(yy+zz))*sX; outArray[outOffset+1]=(xy+wz)*sX; outArray[outOffset+2]=(xz-wy)*sX; outArray[outOffset+3]=0; outArray[outOffset+4]=(xy-wz)*sY; outArray[outOffset+5]=(1-(xx+zz))*sY; outArray[outOffset+6]=(yz+wx)*sY; outArray[outOffset+7]=0; outArray[outOffset+8]=(xz+wy)*sZ; outArray[outOffset+9]=(yz-wx)*sZ; outArray[outOffset+10]=(1-(xx+yy))*sZ; outArray[outOffset+11]=0; outArray[outOffset+12]=tX; outArray[outOffset+13]=tY; outArray[outOffset+14]=tZ; outArray[outOffset+15]=1; } Utils3D.transformVector3ArrayToVector3ArrayCoordinate=function(source,sourceOffset,transform,result,resultOffset){ var vectorElem=Utils3D._tempArray4_0; var coordinateX=source[sourceOffset+0]; var coordinateY=source[sourceOffset+1]; var coordinateZ=source[sourceOffset+2]; var transformElem=transform.elements; vectorElem[0]=(coordinateX *transformElem[0])+(coordinateY *transformElem[4])+(coordinateZ *transformElem[8])+transformElem[12]; vectorElem[1]=(coordinateX *transformElem[1])+(coordinateY *transformElem[5])+(coordinateZ *transformElem[9])+transformElem[13]; vectorElem[2]=(coordinateX *transformElem[2])+(coordinateY *transformElem[6])+(coordinateZ *transformElem[10])+transformElem[14]; vectorElem[3]=1.0 / ((coordinateX *transformElem[3])+(coordinateY *transformElem[7])+(coordinateZ *transformElem[11])+transformElem[15]); result[resultOffset+0]=vectorElem[0] *vectorElem[3]; result[resultOffset+1]=vectorElem[1] *vectorElem[3]; result[resultOffset+2]=vectorElem[2] *vectorElem[3]; } Utils3D.transformLightingMapTexcoordByUV0Array=function(source,sourceOffset,lightingMapScaleOffset,result,resultOffset){ var lightingMapScaleOffsetE=lightingMapScaleOffset.elements; result[resultOffset+0]=source[sourceOffset+0] *lightingMapScaleOffsetE[0]+lightingMapScaleOffsetE[2]; result[resultOffset+1]=(source[sourceOffset+1]-1.0)*lightingMapScaleOffsetE[1]+lightingMapScaleOffsetE[3]; } Utils3D.transformLightingMapTexcoordByUV1Array=function(source,sourceOffset,lightingMapScaleOffset,result,resultOffset){ var lightingMapScaleOffsetE=lightingMapScaleOffset.elements; result[resultOffset+0]=source[sourceOffset+0] *lightingMapScaleOffsetE[0]+lightingMapScaleOffsetE[2]; result[resultOffset+1]=1.0+source[sourceOffset+1] *lightingMapScaleOffsetE[1]+lightingMapScaleOffsetE[3]; } Utils3D.getURLVerion=function(url){ var index=url.indexOf("?"); return index >=0 ? url.substr(index):null; } Utils3D._quaternionCreateFromYawPitchRollArray=function(yaw,pitch,roll,out){ var halfRoll=roll *0.5; var halfPitch=pitch *0.5; var halfYaw=yaw *0.5; var sinRoll=Math.sin(halfRoll); var cosRoll=Math.cos(halfRoll); var sinPitch=Math.sin(halfPitch); var cosPitch=Math.cos(halfPitch); var sinYaw=Math.sin(halfYaw); var cosYaw=Math.cos(halfYaw); out[0]=(cosYaw *sinPitch *cosRoll)+(sinYaw *cosPitch *sinRoll); out[1]=(sinYaw *cosPitch *cosRoll)-(cosYaw *sinPitch *sinRoll); out[2]=(cosYaw *cosPitch *sinRoll)-(sinYaw *sinPitch *cosRoll); out[3]=(cosYaw *cosPitch *cosRoll)+(sinYaw *sinPitch *sinRoll); } Utils3D._createAffineTransformationArray=function(trans,rot,scale,outE){ var x=rot[0],y=rot[1],z=rot[2],w=rot[3],x2=x+x,y2=y+y,z2=z+z; var xx=x *x2,xy=x *y2,xz=x *z2,yy=y *y2,yz=y *z2,zz=z *z2; var wx=w *x2,wy=w *y2,wz=w *z2,sx=scale[0],sy=scale[1],sz=scale[2]; outE[0]=(1-(yy+zz))*sx; outE[1]=(xy+wz)*sx; outE[2]=(xz-wy)*sx; outE[3]=0; outE[4]=(xy-wz)*sy; outE[5]=(1-(xx+zz))*sy; outE[6]=(yz+wx)*sy; outE[7]=0; outE[8]=(xz+wy)*sz; outE[9]=(yz-wx)*sz; outE[10]=(1-(xx+yy))*sz; outE[11]=0; outE[12]=trans[0]; outE[13]=trans[1]; outE[14]=trans[2]; outE[15]=1; } Utils3D._mulMatrixArray=function(leftMatrixE,rightMatrix,outArray,outOffset){ var i,ai0,ai1,ai2,ai3; var rightMatrixE=rightMatrix.elements; var m11=rightMatrixE[0],m12=rightMatrixE[1],m13=rightMatrixE[2],m14=rightMatrixE[3]; var m21=rightMatrixE[4],m22=rightMatrixE[5],m23=rightMatrixE[6],m24=rightMatrixE[7]; var m31=rightMatrixE[8],m32=rightMatrixE[9],m33=rightMatrixE[10],m34=rightMatrixE[11]; var m41=rightMatrixE[12],m42=rightMatrixE[13],m43=rightMatrixE[14],m44=rightMatrixE[15]; var ai0OutOffset=outOffset; var ai1OutOffset=outOffset+4; var ai2OutOffset=outOffset+8; var ai3OutOffset=outOffset+12; for (i=0;i < 4;i++){ ai0=leftMatrixE[i]; ai1=leftMatrixE[i+4]; ai2=leftMatrixE[i+8]; ai3=leftMatrixE[i+12]; outArray[ai0OutOffset+i]=ai0 *m11+ai1 *m12+ai2 *m13+ai3 *m14; outArray[ai1OutOffset+i]=ai0 *m21+ai1 *m22+ai2 *m23+ai3 *m24; outArray[ai2OutOffset+i]=ai0 *m31+ai1 *m32+ai2 *m33+ai3 *m34; outArray[ai3OutOffset+i]=ai0 *m41+ai1 *m42+ai2 *m43+ai3 *m44; } } Utils3D.getYawPitchRoll=function(quaternion,out){ Utils3D.transformQuat(Vector3.ForwardRH,quaternion,Quaternion.TEMPVector31); Utils3D.transformQuat(Vector3.Up,quaternion,Quaternion.TEMPVector32); var upe=Quaternion.TEMPVector32.elements; Utils3D.angleTo(Vector3.ZERO,Quaternion.TEMPVector31,Quaternion.TEMPVector33); var anglee=Quaternion.TEMPVector33.elements; if (anglee[0]==Math.PI / 2){ anglee[1]=Utils3D.arcTanAngle(upe[2],upe[0]); anglee[2]=0; }else if (anglee[0]==-Math.PI / 2){ anglee[1]=Utils3D.arcTanAngle(-upe[2],-upe[0]); anglee[2]=0; }else { Matrix4x4.createRotationY(-anglee[1],Quaternion.TEMPMatrix0); Matrix4x4.createRotationX(-anglee[0],Quaternion.TEMPMatrix1); Vector3.transformCoordinate(Quaternion.TEMPVector32,Quaternion.TEMPMatrix0,Quaternion.TEMPVector32); Vector3.transformCoordinate(Quaternion.TEMPVector32,Quaternion.TEMPMatrix1,Quaternion.TEMPVector32); anglee[2]=Utils3D.arcTanAngle(upe[1],-upe[0]); } if (anglee[1] <=-Math.PI) anglee[1]=Math.PI; if (anglee[2] <=-Math.PI) anglee[2]=Math.PI; if (anglee[1] >=Math.PI && anglee[2] >=Math.PI){ anglee[1]=0; anglee[2]=0; anglee[0]=Math.PI-anglee[0]; } out[0]=anglee[1]; out[1]=anglee[0]; out[2]=anglee[2]; } Utils3D.arcTanAngle=function(x,y){ if (x==0){ if (y==1) return Math.PI / 2; return-Math.PI / 2; } if (x > 0) return Math.atan(y / x); if (x < 0){ if (y > 0) return Math.atan(y / x)+Math.PI; return Math.atan(y / x)-Math.PI; } return 0; } Utils3D.angleTo=function(from,location,angle){ Vector3.subtract(location,from,Quaternion.TEMPVector30); Vector3.normalize(Quaternion.TEMPVector30,Quaternion.TEMPVector30); angle.elements[0]=Math.asin(Quaternion.TEMPVector30.y); angle.elements[1]=Utils3D.arcTanAngle(-Quaternion.TEMPVector30.z,-Quaternion.TEMPVector30.x); } Utils3D.transformQuat=function(source,rotation,out){ var destination=out.elements; var se=source.elements; var re=rotation; var x=se[0],y=se[1],z=se[2],qx=re[0],qy=re[1],qz=re[2],qw=re[3], ix=qw *x+qy *z-qz *y,iy=qw *y+qz *x-qx *z,iz=qw *z+qx *y-qy *x,iw=-qx *x-qy *y-qz *z; destination[0]=ix *qw+iw *-qx+iy *-qz-iz *-qy; destination[1]=iy *qw+iw *-qy+iz *-qx-ix *-qz; destination[2]=iz *qw+iw *-qz+ix *-qy-iy *-qx; } Utils3D.quaterionNormalize=function(f,e){ var x=f[0],y=f[1],z=f[2],w=f[3]; var len=x *x+y *y+z *z+w *w; if (len > 0){ len=1 / Math.sqrt(len); e[0]=x *len; e[1]=y *len; e[2]=z *len; e[3]=w *len; } } Utils3D.matrix4x4MultiplyFFF=function(a,b,e){ var i,ai0,ai1,ai2,ai3; if (e===b){ b=new Float32Array(16); for (i=0;i < 16;++i){ b[i]=e[i]; } } for (i=0;i < 4;i++){ ai0=a[i]; ai1=a[i+4]; ai2=a[i+8]; ai3=a[i+12]; e[i]=ai0 *b[0]+ai1 *b[1]+ai2 *b[2]+ai3 *b[3]; e[i+4]=ai0 *b[4]+ai1 *b[5]+ai2 *b[6]+ai3 *b[7]; e[i+8]=ai0 *b[8]+ai1 *b[9]+ai2 *b[10]+ai3 *b[11]; e[i+12]=ai0 *b[12]+ai1 *b[13]+ai2 *b[14]+ai3 *b[15]; } } Utils3D.matrix4x4MultiplyMFM=function(left,right,out){ Utils3D.matrix4x4MultiplyFFF(left.elements,right,out.elements); } __static(Utils3D, ['_typeToFunO',function(){return this._typeToFunO={"INT16":"writeInt16","SHORT":"writeInt16","UINT16":"writeUint16","UINT32":"writeUint32","FLOAT32":"writeFloat32","INT":"writeInt32","UINT":"writeUint32","BYTE":"writeByte","STRING":"writeUTFString"};},'_tempVector3_0',function(){return this._tempVector3_0=new Vector3();},'_tempVector3_1',function(){return this._tempVector3_1=new Vector3();},'_tempVector3_2',function(){return this._tempVector3_2=new Vector3();},'_tempVector3_3',function(){return this._tempVector3_3=new Vector3();},'_tempVector3_4',function(){return this._tempVector3_4=new Vector3();},'_tempVector3_5',function(){return this._tempVector3_5=new Vector3();},'_tempVector3_6',function(){return this._tempVector3_6=new Vector3();},'_tempArray4_0',function(){return this._tempArray4_0=new Float32Array(4);},'_tempArray16_0',function(){return this._tempArray16_0=new Float32Array(16);},'_tempArray16_1',function(){return this._tempArray16_1=new Float32Array(16);},'_tempArray16_2',function(){return this._tempArray16_2=new Float32Array(16);},'_tempArray16_3',function(){return this._tempArray16_3=new Float32Array(16);} ]); return Utils3D; })() /** *Laya3D 类用于初始化3D设置。 */ //class Laya3D var Laya3D=(function(){ /** *创建一个 Laya3D 实例。 */ function Laya3D(){} __class(Laya3D,'Laya3D'); Laya3D._cancelLoadByUrl=function(url){ Laya.loader.cancelLoadByUrl(url); Laya3D._innerFirstLevelLoaderManager.cancelLoadByUrl(url); Laya3D._innerSecondLevelLoaderManager.cancelLoadByUrl(url); Laya3D._innerThirdLevelLoaderManager.cancelLoadByUrl(url); Laya3D._innerFourthLevelLoaderManager.cancelLoadByUrl(url); } Laya3D._changeWebGLSize=function(width,height){ WebGL.onStageResize(width,height); RenderState.clientWidth=width; RenderState.clientHeight=height; } Laya3D.__init__=function(){ var createMap=LoaderManager.createMap; createMap["lh"]=[Sprite3D,/*CLASS CONST:Laya3D.HIERARCHY*/"SPRITE3DHIERARCHY"]; createMap["ls"]=[Scene,/*CLASS CONST:Laya3D.HIERARCHY*/"SPRITE3DHIERARCHY"]; createMap["lm"]=[Mesh,/*CLASS CONST:Laya3D.MESH*/"MESH"]; createMap["lmat"]=[StandardMaterial,/*CLASS CONST:Laya3D.MATERIAL*/"MATERIAL"]; createMap["lpbr"]=[PBRMaterial,/*CLASS CONST:Laya3D.MATERIAL*/"MATERIAL"]; createMap["ltc"]=[TextureCube,/*CLASS CONST:Laya3D.TEXTURECUBE*/"TEXTURECUBE"]; createMap["jpg"]=[Texture2D,"nativeimage"]; createMap["jpeg"]=[Texture2D,"nativeimage"]; createMap["png"]=[Texture2D,"nativeimage"]; createMap["pkm"]=[Texture2D,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["lsani"]=[AnimationTemplet,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["lrani"]=[AnimationTemplet,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["raw"]=[DataTexture2D,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["mipmaps"]=[DataTexture2D,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["thdata"]=[TerrainHeightData,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["lt"]=[TerrainRes,/*CLASS CONST:Laya3D.TERRAIN*/"TERRAIN"]; createMap["lani"]=[AnimationClip,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["lav"]=[Avatar,/*laya.net.Loader.JSON*/"json"]; createMap["ani"]=[AnimationTemplet,/*laya.net.Loader.BUFFER*/"arraybuffer"]; Loader.parserMap[ /*CLASS CONST:Laya3D.HIERARCHY*/"SPRITE3DHIERARCHY"]=Laya3D._loadHierarchy; Loader.parserMap[ /*CLASS CONST:Laya3D.MESH*/"MESH"]=Laya3D._loadMesh; Loader.parserMap[ /*CLASS CONST:Laya3D.MATERIAL*/"MATERIAL"]=Laya3D._loadMaterial; Loader.parserMap[ /*CLASS CONST:Laya3D.TEXTURECUBE*/"TEXTURECUBE"]=Laya3D._loadTextureCube; Loader.parserMap[ /*CLASS CONST:Laya3D.TERRAIN*/"TERRAIN"]=Laya3D._loadTerrain; Laya3D._innerFirstLevelLoaderManager.on(/*laya.events.Event.ERROR*/"error",null,Laya3D._eventLoadManagerError); Laya3D._innerSecondLevelLoaderManager.on(/*laya.events.Event.ERROR*/"error",null,Laya3D._eventLoadManagerError); Laya3D._innerThirdLevelLoaderManager.on(/*laya.events.Event.ERROR*/"error",null,Laya3D._eventLoadManagerError); Laya3D._innerFourthLevelLoaderManager.on(/*laya.events.Event.ERROR*/"error",null,Laya3D._eventLoadManagerError); } Laya3D.READ_BLOCK=function(){ Laya3D._readData.pos+=4; return true; } Laya3D.READ_DATA=function(){ Laya3D._DATA.offset=Laya3D._readData.getUint32(); Laya3D._DATA.size=Laya3D._readData.getUint32(); return true; } Laya3D.READ_STRINGS=function(){ var materialUrls=[]; var _STRINGS={offset:0,size:0}; _STRINGS.offset=Laya3D._readData.getUint16(); _STRINGS.size=Laya3D._readData.getUint16(); var ofs=Laya3D._readData.pos; Laya3D._readData.pos=_STRINGS.offset+Laya3D._DATA.offset; for (var i=0;i < _STRINGS.size;i++){ var string=Laya3D._readData.readUTFString(); if (string.lastIndexOf(".lmat")!==-1 || string.lastIndexOf(".lpbr")!==-1) materialUrls.push(string); } return materialUrls; } Laya3D.formatRelativePath=function(base,value){ var path; var char1=value.charAt(0); if (char1==="."){ var parts=(base+value).split("/"); for (var i=0,len=parts.length;i < len;i++){ if (parts[i]=='..'){ var index=i-1; if (index > 0 && parts[index]!=='..'){ parts.splice(index,2); i-=2; } } } path=parts.join('/'); }else { path=base+value; } (URL.customFormat !=null)&&(path=URL.customFormat(path,null)); return path; } Laya3D._eventLoadManagerError=function(msg){ Laya.loader.event(/*laya.events.Event.ERROR*/"error",msg); } Laya3D._addHierarchyInnerUrls=function(urls,urlMap,urlVersion,hierarchyBasePath,path,clas){ var formatSubUrl=Laya3D.formatRelativePath(hierarchyBasePath,path); (urlVersion)&& (formatSubUrl=formatSubUrl+urlVersion); urls.push({url:formatSubUrl,clas:clas}); urlMap[path]=formatSubUrl; } Laya3D._getSprite3DHierarchyInnerUrls=function(node,firstLevelUrls,secondLevelUrls,fourthLelUrls,urlMap,urlVersion,hierarchyBasePath){ var i=0,n=0; var customProps; switch (node.type){ case "Scene":; var lightmaps=node.customProps.lightmaps; for (i=0,n=lightmaps.length;i < n;i++){ var lightMap=lightmaps[i].replace(".exr",".png"); Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,lightMap,Texture2D); } break ; case "MeshSprite3D": case "TrailSprite3D": case "LineSprite3D": case "SkinnedMeshSprite3D":; var meshPath; if (node.instanceParams){ meshPath=node.instanceParams.loadPath; (meshPath)&& (Laya3D._addHierarchyInnerUrls(firstLevelUrls,urlMap,urlVersion,hierarchyBasePath,meshPath,Mesh)); }else { customProps=node.customProps; meshPath=customProps.meshPath; (meshPath)&& (Laya3D._addHierarchyInnerUrls(firstLevelUrls,urlMap,urlVersion,hierarchyBasePath,meshPath,Mesh)); var materials=customProps.materials; if (materials) for (i=0,n=materials.length;i < n;i++){ var mat=materials[i]; var clasPaths=mat.type.split('.'); var clas=Browser.window; clasPaths.forEach(function(cls){ clas=clas[cls]; }); if (typeof(clas)=='function')Laya3D._addHierarchyInnerUrls(secondLevelUrls,urlMap,urlVersion,hierarchyBasePath,mat.path,clas); else { throw('_getSprite3DHierarchyInnerUrls 错误: '+mat.type+' 不是类'); } } } break ; case "ShuriKenParticle3D": customProps=node.customProps; var parMeshPath=customProps.meshPath; (parMeshPath)&& (Laya3D._addHierarchyInnerUrls(firstLevelUrls,urlMap,urlVersion,hierarchyBasePath,parMeshPath,Mesh)); var materialData=customProps.material; if (materialData){ clasPaths=materialData.type.split('.'); clas=Browser.window; clasPaths.forEach(function(cls){ clas=clas[cls]; }); Laya3D._addHierarchyInnerUrls(secondLevelUrls,urlMap,urlVersion,hierarchyBasePath,materialData.path,clas); }else { var materialPath=customProps.materialPath; if (materialPath){ Laya3D._addHierarchyInnerUrls(secondLevelUrls,urlMap,urlVersion,hierarchyBasePath,materialPath,ShurikenParticleMaterial); }else { var texturePath=customProps.texturePath; if (texturePath) Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,texturePath,Texture2D); } } break ; case "Terrain": Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,node.customProps.dataPath,TerrainRes); break ; }; var components=node.components; for (var k in components){ var component=components[k]; switch (k){ case "Animator":; var avatarPath=component.avatarPath; if (avatarPath){ Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,avatarPath,Avatar); }else { var avatarData=component.avatar; (avatarData)&& (Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,avatarData.path,Avatar)); }; var clipPaths=component.clipPaths; for (i=0,n=clipPaths.length;i < n;i++) Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,clipPaths[i],AnimationClip); break ; } }; var children=node.child; for (i=0,n=children.length;i < n;i++) Laya3D._getSprite3DHierarchyInnerUrls(children[i],firstLevelUrls,secondLevelUrls,fourthLelUrls,urlMap,urlVersion,hierarchyBasePath); } Laya3D._loadHierarchy=function(loader){ loader.on(/*laya.events.Event.LOADED*/"loaded",null,Laya3D._onHierarchylhLoaded,[loader,loader._class._getGroup()]); loader.load(loader.url,/*laya.net.Loader.JSON*/"json",false,null,true); } Laya3D._onHierarchylhLoaded=function(loader,group,lhData){ if (loader._class.destroyed){ loader.endLoad(); }else { var url=loader.url; var urlVersion=Utils3D.getURLVerion(url); var hierarchyBasePath=URL.getPath(url); var firstLevUrls=[]; var secondLevUrls=[]; var forthLevUrls=[]; var urlMap={}; Laya3D._getSprite3DHierarchyInnerUrls(lhData,firstLevUrls,secondLevUrls,forthLevUrls,urlMap,urlVersion,hierarchyBasePath); var urlCount=firstLevUrls.length+secondLevUrls.length+forthLevUrls.length; var totalProcessCount=urlCount+1; var weight=1 / totalProcessCount; Laya3D._onProcessChange(loader,0,weight,1.0); if (forthLevUrls.length > 0){ var processCeil=urlCount / totalProcessCount; var processHandler=Handler.create(null,Laya3D._onProcessChange,[loader,weight,processCeil],false); Laya3D._innerFourthLevelLoaderManager.create(forthLevUrls,Handler.create(null,Laya3D._onHierarchyInnerForthLevResouLoaded,[loader,group,processHandler,lhData,urlMap,firstLevUrls,secondLevUrls,weight+processCeil *forthLevUrls.length,processCeil]),processHandler,null,null,1,true,group); }else { Laya3D._onHierarchyInnerForthLevResouLoaded(loader,group,null,lhData,urlMap,firstLevUrls,secondLevUrls,weight,processCeil); } } } Laya3D._onHierarchyInnerForthLevResouLoaded=function(loader,group,processHandler,lhData,urlMap,firstLevUrls,secondLevUrls,processOffset,processCeil){ if (loader._class.destroyed){ loader.endLoad(); }else { (processHandler)&& (processHandler.recover()); if (secondLevUrls.length > 0){ var process=Handler.create(null,Laya3D._onProcessChange,[loader,processOffset,processCeil],false); Laya3D._innerSecondLevelLoaderManager.create(secondLevUrls,Handler.create(null,Laya3D._onHierarchyInnerSecondLevResouLoaded,[loader,group,process,lhData,urlMap,firstLevUrls,processOffset+processCeil *secondLevUrls.length,processCeil]),processHandler,null,null,1,true,group); }else { Laya3D._onHierarchyInnerSecondLevResouLoaded(loader,group,null,lhData,urlMap,firstLevUrls,processOffset,processCeil); } } } Laya3D._onHierarchyInnerSecondLevResouLoaded=function(loader,group,processHandler,lhData,urlMap,firstLevUrls,processOffset,processCeil){ if (loader._class.destroyed){ loader.endLoad(); }else { (processHandler)&& (processHandler.recover()); if (firstLevUrls.length > 0){ var process=Handler.create(null,Laya3D._onProcessChange,[loader,processOffset,processCeil],false); Laya3D._innerFirstLevelLoaderManager.create(firstLevUrls,Handler.create(null,Laya3D._onHierarchyInnerFirstLevResouLoaded,[loader,process,lhData,urlMap,]),processHandler,null,null,1,true,group); }else { Laya3D._onHierarchyInnerFirstLevResouLoaded(loader,null,lhData,urlMap); } } } Laya3D._onHierarchyInnerFirstLevResouLoaded=function(loader,processHandler,lhData,urlMap){ (processHandler)&& (processHandler.recover()); loader.endLoad([lhData,urlMap]); } Laya3D._loadTerrain=function(loader){ loader.on(/*laya.events.Event.LOADED*/"loaded",null,Laya3D._onTerrainLtLoaded,[loader,loader._class._getGroup()]); loader.load(loader.url,/*laya.net.Loader.JSON*/"json",false,null,true); } Laya3D._onTerrainLtLoaded=function(loader,group,ltData){ if (loader._class.destroyed){ loader.endLoad(); }else { var url=loader.url; var urlVersion=Utils3D.getURLVerion(url); var terrainBasePath=URL.getPath(url); var heightMapURL,textureURLs=[]; var urlMap={}; var formatUrl; var i=0,n=0,count=0; var heightData=ltData.heightData; heightMapURL=heightData.url; formatUrl=Laya3D.formatRelativePath(terrainBasePath,heightMapURL); (urlVersion)&& (formatUrl=formatUrl+urlVersion); urlMap[heightMapURL]=formatUrl; heightMapURL=formatUrl; var detailTextures=ltData.detailTexture; for (i=0,n=detailTextures.length;i < n;i++) textureURLs.push({url:detailTextures[i].diffuse}); var normalMaps=ltData.normalMap; for (i=0,n=normalMaps.length;i < n;i++) textureURLs.push({url:normalMaps[i]}); var alphaMaps=ltData.alphaMap; for (i=0,n=alphaMaps.length;i < n;i++) textureURLs.push({url:alphaMaps[i],params:[false,false,/*laya.webgl.WebGLContext.RGBA*/0x1908,true]}); for (i=0,n=textureURLs.length;i < n;i++){ var subUrl=textureURLs[i].url; formatUrl=Laya3D.formatRelativePath(terrainBasePath,subUrl); (urlVersion)&& (formatUrl=formatUrl+urlVersion); textureURLs[i].url=formatUrl; urlMap[subUrl]=formatUrl; }; var texsUrlCount=textureURLs.length; var totalProcessCount=texsUrlCount+2; var weight=1 / totalProcessCount; Laya3D._onProcessChange(loader,0,weight,1.0); var loadInfo={heightMapLoaded:false,texturesLoaded:false}; var hmProcessHandler=Handler.create(null,Laya3D._onProcessChange,[loader,weight,weight],false); Laya3D._innerFourthLevelLoaderManager.create(heightMapURL,Handler.create(null,Laya3D._onTerrainHeightMapLoaded,[loader,hmProcessHandler,ltData,urlMap,loadInfo]),hmProcessHandler,null,[heightData.numX,heightData.numZ,heightData.bitType,heightData.value],1,true,group); var texsProcessHandler=Handler.create(null,Laya3D._onProcessChange,[loader,weight *2,texsUrlCount / totalProcessCount],false); Laya3D._innerFourthLevelLoaderManager.create(textureURLs,Handler.create(null,Laya3D._onTerrainTexturesLoaded,[loader,texsProcessHandler,ltData,urlMap,loadInfo]),texsProcessHandler,null,null,1,true,group); } } Laya3D._onTerrainHeightMapLoaded=function(loader,processHandler,ltData,urlMap,loadInfo){ loadInfo.heightMapLoaded=true; if (loadInfo.texturesLoaded){ loader.endLoad([ltData,urlMap]); processHandler.recover(); } } Laya3D._onTerrainTexturesLoaded=function(loader,processHandler,ltData,urlMap,loadInfo){ loadInfo.texturesLoaded=true; if (loadInfo.heightMapLoaded){ loader.endLoad([ltData,urlMap]); processHandler.recover(); } } Laya3D._loadMesh=function(loader){ loader.on(/*laya.events.Event.LOADED*/"loaded",null,Laya3D._onMeshLmLoaded,[loader,loader._class._getGroup()]); loader.load(loader.url,/*laya.net.Loader.BUFFER*/"arraybuffer",false,null,true); } Laya3D._onMeshLmLoaded=function(loader,group,lmData){ if (loader._class.destroyed){ loader.endLoad(); }else { var url=loader.url; var urlVersion=Utils3D.getURLVerion(url); var meshBasePath=URL.getPath(url); var urls; var urlMap={}; var formatSubUrl; var i=0,n=0,count=0; Laya3D._readData=new Byte(lmData); Laya3D._readData.pos=0; var version=Laya3D._readData.readUTFString(); switch (version){ case "LAYAMODEL:02": case "LAYAMODEL:03": case "LAYAMODEL:0301":; var dataOffset=Laya3D._readData.getUint32(); Laya3D._readData.pos=Laya3D._readData.pos+4; count=Laya3D._readData.getUint16(); Laya3D._readData.pos=Laya3D._readData.pos+count *8; var offset=Laya3D._readData.getUint32(); count=Laya3D._readData.getUint16(); Laya3D._readData.pos=dataOffset+offset; urls=[]; for (i=0;i < count;i++){ var string=Laya3D._readData.readUTFString(); if (string.lastIndexOf(".lmat")!==-1) urls.push(string); } break ; default : Laya3D.READ_BLOCK(); for (i=0;i < 2;i++){ var index=Laya3D._readData.getUint16(); var blockName=Laya3D._strings[index]; var fn=Laya3D["READ_"+blockName]; if (fn==null)throw new Error("model file err,no this function:"+index+" "+blockName); if (i===1) urls=fn.call(); else fn.call() } } for (i=0,n=urls.length;i < n;i++){ var subUrl=urls[i]; formatSubUrl=Laya3D.formatRelativePath(meshBasePath,subUrl); (urlVersion)&& (formatSubUrl=formatSubUrl+urlVersion); urls[i]=formatSubUrl; urlMap[subUrl]=formatSubUrl; } if (urls.length > 0){ var urlCount=1; var totalProcessCount=urlCount+1; var lmatWeight=1 / totalProcessCount; Laya3D._onProcessChange(loader,0,lmatWeight,1.0); var processHandler=Handler.create(null,Laya3D._onProcessChange,[loader,lmatWeight,urlCount / totalProcessCount],false); Laya3D._innerSecondLevelLoaderManager.create(urls,Handler.create(null,Laya3D._onMeshMateialLoaded,[loader,processHandler,lmData,urlMap]),processHandler,null,null,1,true,group); }else { loader.endLoad([lmData,urlMap]); } } } Laya3D._onMeshMateialLoaded=function(loader,processHandler,lmData,urlMap){ loader.endLoad([lmData,urlMap]); processHandler.recover(); } Laya3D._getMaterialTexturePath=function(path,urlVersion,materialBath){ var extenIndex=path.length-4; if (path.indexOf(".dds")==extenIndex || path.indexOf(".tga")==extenIndex || path.indexOf(".exr")==extenIndex || path.indexOf(".DDS")==extenIndex || path.indexOf(".TGA")==extenIndex || path.indexOf(".EXR")==extenIndex) path=path.substr(0,extenIndex)+".png"; path=Laya3D.formatRelativePath(materialBath,path); (urlVersion)&& (path=path+urlVersion); return path; } Laya3D._loadMaterial=function(loader){ loader.on(/*laya.events.Event.LOADED*/"loaded",null,Laya3D._onMaterilLmatLoaded,[loader,loader._class._getGroup()]); loader.load(loader.url,/*laya.net.Loader.JSON*/"json",false,null,true); } Laya3D._onMaterilLmatLoaded=function(loader,group,lmatData){ if (loader._class.destroyed){ loader.endLoad(); }else { var url=loader.url; var urlVersion=Utils3D.getURLVerion(url); var materialBasePath=URL.getPath(url); var urls=[]; var urlMap={}; var customProps=lmatData.customProps; var formatSubUrl; var version=lmatData.version; if (version){ switch (version){ case "LAYAMATERIAL:01": case "LAYAMATERIAL:02":; var textures=lmatData.props.textures; for (var i=0,n=textures.length;i < n;i++){ var tex=textures[i]; var path=tex.path; if (path){ var extenIndex=path.length-4; if (path.indexOf(".exr")==extenIndex || path.indexOf(".EXR")==extenIndex) path=path.substr(0,extenIndex)+".png"; formatSubUrl=Laya3D.formatRelativePath(materialBasePath,path); (urlVersion)&& (formatSubUrl=formatSubUrl+urlVersion); urls.push({url:formatSubUrl,params:tex.params}); urlMap[path]=formatSubUrl; } } break ; default : throw new Error("Laya3D:unkonwn version."); } }else { var diffuseTexture=customProps.diffuseTexture.texture2D; if (diffuseTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(diffuseTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[diffuseTexture]=formatSubUrl; } if (customProps.normalTexture){ var normalTexture=customProps.normalTexture.texture2D; if (normalTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(normalTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[normalTexture]=formatSubUrl; } } if (customProps.specularTexture){ var specularTexture=customProps.specularTexture.texture2D; if (specularTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(specularTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[specularTexture]=formatSubUrl; } } if (customProps.emissiveTexture){ var emissiveTexture=customProps.emissiveTexture.texture2D; if (emissiveTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(emissiveTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[emissiveTexture]=formatSubUrl; } } if (customProps.ambientTexture){ var ambientTexture=customProps.ambientTexture.texture2D; if (ambientTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(ambientTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[ambientTexture]=formatSubUrl; } } if (customProps.reflectTexture){ var reflectTexture=customProps.reflectTexture.texture2D; if (reflectTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(reflectTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[reflectTexture]=formatSubUrl; } } }; var urlCount=urls.length; var totalProcessCount=urlCount+1; var lmatWeight=1 / totalProcessCount; Laya3D._onProcessChange(loader,0,lmatWeight,1.0); if (urlCount > 0){ var processHandler=Handler.create(null,Laya3D._onProcessChange,[loader,lmatWeight,urlCount / totalProcessCount],false); Laya3D._innerFourthLevelLoaderManager.create(urls,Handler.create(null,Laya3D._onMateialTexturesLoaded,[loader,processHandler,lmatData,urlMap]),processHandler,Texture2D,null,1,true,group); }else { Laya3D._onMateialTexturesLoaded(loader,null,lmatData,null); } } } Laya3D._onMateialTexturesLoaded=function(loader,processHandler,lmatData,urlMap){ loader.endLoad([lmatData,urlMap]); (processHandler)&& (processHandler.recover()); } Laya3D._loadTextureCube=function(loader){ loader.on(/*laya.events.Event.LOADED*/"loaded",null,Laya3D._onTextureCubeLtcLoaded,[loader]); loader.load(loader.url,/*laya.net.Loader.JSON*/"json",false,null,true); } Laya3D._onTextureCubeLtcLoaded=function(loader,ltcData){ if (loader._class.destroyed){ loader.endLoad(); }else { var ltcBasePath=URL.getPath(loader.url); var urls=[Laya3D.formatRelativePath(ltcBasePath,ltcData.px),Laya3D.formatRelativePath(ltcBasePath,ltcData.nx),Laya3D.formatRelativePath(ltcBasePath,ltcData.py),Laya3D.formatRelativePath(ltcBasePath,ltcData.ny),Laya3D.formatRelativePath(ltcBasePath,ltcData.pz),Laya3D.formatRelativePath(ltcBasePath,ltcData.nz)]; var ltcWeight=1.0 / 7.0; Laya3D._onProcessChange(loader,0,ltcWeight,1.0); var processHandler=Handler.create(null,Laya3D._onProcessChange,[loader,ltcWeight,6 / 7],false); Laya3D._innerFourthLevelLoaderManager.load(urls,Handler.create(null,Laya3D._onTextureCubeImagesLoaded,[loader,urls,processHandler]),processHandler,"nativeimage"); } } Laya3D._onTextureCubeImagesLoaded=function(loader,urls,processHandler){ var images=[]; images.length=6; for (var i=0;i < 6;i++){ var url=urls[i]; images[i]=Loader.getRes(url); Loader.clearRes(url); } loader.endLoad(images); processHandler.recover(); } Laya3D._onProcessChange=function(loader,offset,weight,process){ process=offset+process *weight; (process < 1.0)&& (loader.event(/*laya.events.Event.PROGRESS*/"progress",process)); } Laya3D.init=function(width,height,antialias,alpha,premultipliedAlpha,stencil){ (antialias===void 0)&& (antialias=false); (alpha===void 0)&& (alpha=false); (premultipliedAlpha===void 0)&& (premultipliedAlpha=true); (stencil===void 0)&& (stencil=true); if (Laya3D._isinit)return; Laya3D._isinit=true; RunDriver.update3DLoop=function (){ CollisionManager._triggerCollision(); } RunDriver.cancelLoadByUrl=function (url){ Laya3D._cancelLoadByUrl(url); } Config.isAntialias=antialias; Config.isAlpha=alpha; Config.premultipliedAlpha=premultipliedAlpha; Config.isStencil=stencil; if (!WebGL.enable()){ alert("Laya3D init error,must support webGL!"); return; } RunDriver.changeWebGLSize=Laya3D._changeWebGLSize; Render.is3DMode=true; Laya.init(width,height); Layer.__init__(); Physics.__init__(); ExtendTerrainMaterial.__init__(); ShaderInit3D.__init__(); MeshSprite3D.__init__(); AnimationNode.__init__(); Laya3D.__init__(); AtlasResourceManager.maxTextureCount=2; if (Laya3D.debugMode || OctreeNode.debugMode) Laya3D._debugPhasorSprite=new PhasorSpriter3D(); } Laya3D.HIERARCHY="SPRITE3DHIERARCHY"; Laya3D.MESH="MESH"; Laya3D.MATERIAL="MATERIAL"; Laya3D.PBRMATERIAL="PBRMTL"; Laya3D.TEXTURECUBE="TEXTURECUBE"; Laya3D.TERRAIN="TERRAIN"; Laya3D._readData=null; Laya3D._debugPhasorSprite=null; Laya3D.debugMode=false; Laya3D._isinit=false; __static(Laya3D, ['_DATA',function(){return this._DATA={offset:0,size:0};},'_strings',function(){return this._strings=['BLOCK','DATA',"STRINGS"];},'_innerFirstLevelLoaderManager',function(){return this._innerFirstLevelLoaderManager=new LoaderManager();},'_innerSecondLevelLoaderManager',function(){return this._innerSecondLevelLoaderManager=new LoaderManager();},'_innerThirdLevelLoaderManager',function(){return this._innerThirdLevelLoaderManager=new LoaderManager();},'_innerFourthLevelLoaderManager',function(){return this._innerFourthLevelLoaderManager=new LoaderManager();} ]); return Laya3D; })() /** *Transform3D 类用于实现3D变换。 */ //class laya.d3.animation.AnimationTransform3D extends laya.events.EventDispatcher var AnimationTransform3D=(function(_super){ function AnimationTransform3D(owner){ /**@private */ //this._localMatrix=null; /**@private */ //this._worldMatrix=null; /**@private */ //this._localPosition=null; /**@private */ //this._localRotation=null; /**@private */ //this._localScale=null; /**@private */ //this._localQuaternionUpdate=false; /**@private */ //this._locaEulerlUpdate=false; /**@private */ //this._localUpdate=false; /**@private */ //this._parent=null; /**@private */ //this._childs=null; /**@private */ //this._localRotationEuler=null; /**@private */ //this._owner=null; /**@private */ //this._worldUpdate=false; /**@private */ //this._entity=null; AnimationTransform3D.__super.call(this); this._owner=owner; this._childs=[]; this._localMatrix=new Float32Array(16); this._localQuaternionUpdate=false; this._locaEulerlUpdate=false; this._localUpdate=false; this._worldUpdate=true; } __class(AnimationTransform3D,'laya.d3.animation.AnimationTransform3D',_super); var __proto=AnimationTransform3D.prototype; /** *@private */ __proto._getlocalMatrix=function(){ if (this._localUpdate){ Utils3D._createAffineTransformationArray(this._localPosition,this._localRotation,this._localScale,this._localMatrix); this._localUpdate=false; } return this._localMatrix; } /** *@private */ __proto._onWorldTransform=function(){ if (!this._worldUpdate){ this._worldUpdate=true; for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldTransform(); } } /** *@private */ __proto._setWorldMatrixAndUpdate=function(matrix){ this._worldMatrix=matrix; if (this._parent==null){ throw new Error("don't need to set worldMatrix to root Node."); }else { if (this._parent._parent==null){ var locMat=this._getlocalMatrix(); for (var i=0;i < 16;++i) this._worldMatrix[i]=locMat[i]; }else { Utils3D.matrix4x4MultiplyFFF(this._parent.getWorldMatrix(),this._getlocalMatrix(),this._worldMatrix); } } this._worldUpdate=false; } /** *@private */ __proto._setWorldMatrixNoUpdate=function(matrix){ this._worldMatrix=matrix; } /** *@private */ __proto._setWorldMatrixIgnoreUpdate=function(matrix){ this._worldMatrix=matrix; this._worldUpdate=false; } /** *获取局部位置。 *@return 局部位置。 */ __proto.getLocalPosition=function(){ return this._localPosition; } /** *设置局部位置。 *@param value 局部位置。 */ __proto.setLocalPosition=function(value){ if (this._parent){ this._localPosition=value; this._localUpdate=true; this._onWorldTransform(); }else { var entityTransform=this._entity.owner._transform; var entityPosition=this._entity.localPosition; var entityPositionE=entityPosition.elements; entityPositionE[0]=value[0]; entityPositionE[1]=value[1]; entityPositionE[2]=value[2]; entityTransform.localPosition=entityPosition; } } /** *获取局部旋转。 *@return 局部旋转。 */ __proto.getLocalRotation=function(){ if (this._localQuaternionUpdate){ var eulerE=this._localRotationEuler; Utils3D._quaternionCreateFromYawPitchRollArray(eulerE[1] / AnimationTransform3D._angleToRandin,eulerE[0] / AnimationTransform3D._angleToRandin,eulerE[2] / AnimationTransform3D._angleToRandin,this._localRotation); this._localQuaternionUpdate=false; } return this._localRotation; } /** *设置局部旋转。 *@param value 局部旋转。 */ __proto.setLocalRotation=function(value){ if (this._parent){ this._localRotation=value; Utils3D.quaterionNormalize(this._localRotation,this._localRotation); this._locaEulerlUpdate=true; this._localQuaternionUpdate=false; this._localUpdate=true; this._onWorldTransform(); }else { var entityTransform=this._entity.owner._transform; var entityRotation=this._entity.localRotation; var entityRotationE=entityRotation.elements; entityRotationE[0]=value[0]; entityRotationE[1]=value[1]; entityRotationE[2]=value[2]; entityRotationE[3]=value[3]; entityTransform.localRotation=entityRotation; } } /** *获取局部缩放。 *@return 局部缩放。 */ __proto.getLocalScale=function(){ return this._localScale; } /** *设置局部缩放。 *@param value 局部缩放。 */ __proto.setLocalScale=function(value){ if (this._parent){ this._localScale=value; this._localUpdate=true; this._onWorldTransform(); }else { var entityTransform=this._entity.owner._transform; var entityScale=this._entity.localScale; var entityScaleE=entityScale.elements; entityScaleE[0]=value[0]; entityScaleE[1]=value[1]; entityScaleE[2]=value[2]; entityTransform.localScale=entityScale; } } /** *获取局部空间的旋转角度。 *@return 欧拉角的旋转值,顺序为x、y、z。 */ __proto.getLocalRotationEuler=function(){ if (this._locaEulerlUpdate){ Utils3D.getYawPitchRoll(this._localRotation,AnimationTransform3D._tempVector3); var eulerE=AnimationTransform3D._tempVector3; var localRotationEulerE=this._localRotationEuler; localRotationEulerE[0]=eulerE[1] *AnimationTransform3D._angleToRandin; localRotationEulerE[1]=eulerE[0] *AnimationTransform3D._angleToRandin; localRotationEulerE[2]=eulerE[2] *AnimationTransform3D._angleToRandin; this._locaEulerlUpdate=false; } return this._localRotationEuler; } /** *设置局部空间的旋转角度。 *@param value 欧拉角的旋转值,顺序为x、y、z。 */ __proto.setLocalRotationEuler=function(value){ if (this._parent){ Utils3D._quaternionCreateFromYawPitchRollArray(value[1] / AnimationTransform3D._angleToRandin,value[0] / AnimationTransform3D._angleToRandin,value[2] / AnimationTransform3D._angleToRandin,this._localRotation); this._localRotationEuler=value; this._locaEulerlUpdate=false; this._localQuaternionUpdate=false; this._localUpdate=true; this._onWorldTransform(); }else { var entityTransform=this._entity.owner._transform; var entityLocalRotationEuler=this._entity.localRotationEuler; var elements=entityLocalRotationEuler.elements; elements[0]=value[0]; elements[1]=value[1]; elements[2]=value[2]; entityTransform.localRotationEuler=entityLocalRotationEuler; } } /** *获取世界矩阵。 *@return 世界矩阵。 */ __proto.getWorldMatrix=function(){ if (this._worldUpdate){ if (this._parent._parent !=null){ Utils3D.matrix4x4MultiplyFFF(this._parent.getWorldMatrix(),this._getlocalMatrix(),this._worldMatrix); }else { var locMat=this._getlocalMatrix(); for (var i=0;i < 16;++i) this._worldMatrix[i]=locMat[i]; } this._worldUpdate=false; } return this._worldMatrix; } /** *设置父3D变换。 *@param value 父3D变换。 */ __proto.setParent=function(value){ if (this._parent!==value){ if (this._parent){ var parentChilds=this._parent._childs; var index=parentChilds.indexOf(this); parentChilds.splice(index,1); } if (value){ value._childs.push(this); (value)&& (this._onWorldTransform()); } this._parent=value; } } __static(AnimationTransform3D, ['_tempVector3',function(){return this._tempVector3=new Float32Array(3);},'_angleToRandin',function(){return this._angleToRandin=180 / Math.PI;} ]); return AnimationTransform3D; })(EventDispatcher) /** *Component3D 类用于创建组件的父类。 */ //class laya.d3.component.Component3D extends laya.events.EventDispatcher var Component3D=(function(_super){ function Component3D(){ /**@private */ this._destroyed=false; /**@private 唯一标识ID。*/ this._id=0; /**@private 是否启动。*/ this._enable=false; /**@private 所属Sprite3D节点。*/ this._owner=null; /**是否已执行start函数。*/ this.started=false; Component3D.__super.call(this); this._destroyed=false; this._id=Component3D._uniqueIDCounter; Component3D._uniqueIDCounter++; } __class(Component3D,'laya.d3.component.Component3D',_super); var __proto=Component3D.prototype; Laya.imps(__proto,{"laya.d3.core.render.IUpdate":true,"laya.resource.IDestroy":true}) /** *@private *初始化组件。 *@param owner 所属Sprite3D节点。 */ __proto._initialize=function(owner){ this._owner=owner; this._enable=true; this.started=false; this._load(owner); } /** *@private *销毁组件。 */ __proto._destroy=function(){ this._unload(this._owner); this._owner=null; this._destroyed=true; } /** *@private *载入组件时执行,可重写此函数。 */ __proto._load=function(owner){} /** *@private *在任意第一次更新时执行,可重写此函数。 */ __proto._start=function(state){} /** *@private *更新组件,可重写此函数。 *@param state 渲染状态参数。 */ __proto._update=function(state){} /** *@private *更新的最后阶段执行,可重写此函数。 *@param state 渲染状态参数。 */ __proto._lateUpdate=function(state){} /** *@private *渲染前设置组件相关参数,可重写此函数。 *@param state 渲染状态参数。 */ __proto._preRenderUpdate=function(state){} /** *@private *渲染的最后阶段执行,可重写此函数。 *@param state 渲染状态参数。 */ __proto._postRenderUpdate=function(state){} /** *@private *卸载组件时执行,可重写此函数。 */ __proto._unload=function(owner){ this.offAll(); } /** *@private */ __proto._cloneTo=function(dest){} /** *获取唯一标识ID。 *@return 唯一标识ID。 */ __getset(0,__proto,'id',function(){ return this._id; }); /** *获取是否已销毁。 *@return 是否已销毁。 */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); /** *获取所属Sprite3D节点。 *@return 所属Sprite3D节点。 */ __getset(0,__proto,'owner',function(){ return this._owner; }); /** *设置是否启用。 *@param value 是否启动 */ /** *获取是否启用。 *@return 是否启动。 */ __getset(0,__proto,'enable',function(){ return this._enable; },function(value){ if (this._enable!==value){ this._enable=value; this.event(/*laya.events.Event.ENABLE_CHANGED*/"enablechanged",this._enable); } }); /** *获取是否为单实例组件。 *@return 是否为单实例组件。 */ __getset(0,__proto,'isSingleton',function(){ return Component3D._isSingleton; }); Component3D._isSingleton=true; Component3D._uniqueIDCounter=1; return Component3D; })(EventDispatcher) /** *GeometryFilter 类用于创建集合体过滤器,抽象类不允许实例。 */ //class laya.d3.core.GeometryFilter extends laya.events.EventDispatcher var GeometryFilter=(function(_super){ function GeometryFilter(){ /**@private */ this._destroyed=false; GeometryFilter.__super.call(this); this._destroyed=false; } __class(GeometryFilter,'laya.d3.core.GeometryFilter',_super); var __proto=GeometryFilter.prototype; Laya.imps(__proto,{"laya.resource.IDestroy":true}) /** *@private */ __proto._destroy=function(){ this.offAll(); this._destroyed=true; } /**@private */ __getset(0,__proto,'_isAsyncLoaded',function(){ return true; }); /** *@private */ __getset(0,__proto,'_originalBoundingBoxCorners',function(){ throw new Error("BaseRender: must override it."); }); /** *@private */ __getset(0,__proto,'_originalBoundingSphere',function(){ throw new Error("BaseRender: must override it."); }); /** *@private */ __getset(0,__proto,'_originalBoundingBox',function(){ throw new Error("BaseRender: must override it."); }); /** *获取是否已销毁。 *@return 是否已销毁。 */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); return GeometryFilter; })(EventDispatcher) /** *Render 类用于渲染器的父类,抽象类不允许实例。 */ //class laya.d3.core.render.BaseRender extends laya.events.EventDispatcher var BaseRender=(function(_super){ function BaseRender(owner){ /**@private */ //this._id=0; /**@private */ //this._destroyed=false; /**@private */ //this._lightmapScaleOffset=null; /**@private */ //this._lightmapIndex=0; /**@private */ //this._enable=false; /**@private */ //this._receiveShadow=false; /**@private */ //this._materialsInstance=null; /**@private */ //this._boundingSphere=null; /**@private */ //this._boundingBox=null; /**@private */ //this._boundingBoxCenter=null; /**@private */ //this._boundingSphereNeedChange=false; /**@private */ //this._boundingBoxNeedChange=false; /**@private */ //this._boundingBoxCenterNeedChange=false; /**@private */ //this._octreeNodeNeedChange=false; /**@private */ //this._indexInSceneFrustumCullingObjects=0; /**@private */ //this._materials=null; /**@private */ //this._owner=null; /**@private */ //this._renderElements=null; /**@private */ //this._distanceForSort=NaN; /**@private */ //this._treeNode=null; /**@private */ //this._isPartOfStaticBatch=false; /**@private */ //this._staticBatchRootSprite3D=null; /**@private */ //this._staticBatchRenderElements=null; /**排序矫正值。*/ //this.sortingFudge=NaN; /**是否产生阴影。 */ //this.castShadow=false; BaseRender.__super.call(this); this._id=++BaseRender._uniqueIDCounter; this._indexInSceneFrustumCullingObjects=-1; this._boundingBox=new BoundBox(new Vector3(),new Vector3()); this._boundingBoxCenter=new Vector3(); this._boundingSphere=new BoundSphere(new Vector3(),0); this._boundingSphereNeedChange=true; this._boundingBoxNeedChange=true; this._boundingBoxCenterNeedChange=true; this._octreeNodeNeedChange=true; this._materials=[]; this._renderElements=[]; this._isPartOfStaticBatch=false; this._destroyed=false; this._owner=owner; this._enable=true; this._materialsInstance=[]; this.lightmapIndex=-1; this.castShadow=false; this.receiveShadow=false; this.sortingFudge=0.0; this._owner.transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatNeedChange); } __class(BaseRender,'laya.d3.core.render.BaseRender',_super); var __proto=BaseRender.prototype; Laya.imps(__proto,{"laya.resource.IDestroy":true}) /** *@private */ __proto._changeMaterialReference=function(lastValue,value){ (lastValue)&& (lastValue._removeReference()); value._addReference(); } /** *@private */ __proto._getInstanceMaterial=function(material,index){ var insMat=/*__JS__ */new material.constructor(); material.cloneTo(insMat); insMat.name=insMat.name+"(Instance)"; this._materialsInstance[index]=true; this._changeMaterialReference(this._materials[index],insMat); this._materials[index]=insMat; return insMat; } /** *@private */ __proto._setShaderValuelightMap=function(lightMap){ this._setShaderValueTexture(/*laya.d3.core.RenderableSprite3D.LIGHTMAP*/3,lightMap); } /** *@private */ __proto._onWorldMatNeedChange=function(){ this._boundingSphereNeedChange=true; this._boundingBoxNeedChange=true; this._boundingBoxCenterNeedChange=true; this._octreeNodeNeedChange=true; } /** *@private */ __proto._renderRenderableBoundBox=function(){ var linePhasor=Laya3D._debugPhasorSprite; var boundBox=this.boundingBox; var corners=BaseRender._tempBoundBoxCorners; boundBox.getCorners(corners); linePhasor.line(corners[0],BaseRender._greenColor,corners[1],BaseRender._greenColor); linePhasor.line(corners[2],BaseRender._greenColor,corners[3],BaseRender._greenColor); linePhasor.line(corners[4],BaseRender._greenColor,corners[5],BaseRender._greenColor); linePhasor.line(corners[6],BaseRender._greenColor,corners[7],BaseRender._greenColor); linePhasor.line(corners[0],BaseRender._greenColor,corners[3],BaseRender._greenColor); linePhasor.line(corners[1],BaseRender._greenColor,corners[2],BaseRender._greenColor); linePhasor.line(corners[2],BaseRender._greenColor,corners[6],BaseRender._greenColor); linePhasor.line(corners[3],BaseRender._greenColor,corners[7],BaseRender._greenColor); linePhasor.line(corners[0],BaseRender._greenColor,corners[4],BaseRender._greenColor); linePhasor.line(corners[1],BaseRender._greenColor,corners[5],BaseRender._greenColor); linePhasor.line(corners[4],BaseRender._greenColor,corners[7],BaseRender._greenColor); linePhasor.line(corners[5],BaseRender._greenColor,corners[6],BaseRender._greenColor); } /** *@private */ __proto._calculateBoundingSphere=function(){ throw("BaseRender: must override it."); } /** *@private */ __proto._calculateBoundingBox=function(){ throw("BaseRender: must override it."); } /** *@private */ __proto._setShaderValueTexture=function(shaderName,texture){ this._owner._shaderValues.setValue(shaderName,texture); } /** *@private */ __proto._setShaderValueMatrix4x4=function(shaderName,matrix4x4){ this._owner._shaderValues.setValue(shaderName,matrix4x4 ? matrix4x4.elements :null); } /** *设置颜色。 *@param shaderIndex shader索引。 *@param color 颜色向量。 */ __proto._setShaderValueColor=function(shaderIndex,color){ this._owner._shaderValues.setValue(shaderIndex,color ? color.elements :null); } /** *设置Buffer。 *@param shaderIndex shader索引。 *@param buffer buffer数据。 */ __proto._setShaderValueBuffer=function(shaderIndex,buffer){ this._owner._shaderValues.setValue(shaderIndex,buffer); } /** *设置整型。 *@param shaderIndex shader索引。 *@param i 整形。 */ __proto._setShaderValueInt=function(shaderIndex,i){ this._owner._shaderValues.setValue(shaderIndex,i); } /** *设置布尔。 *@param shaderIndex shader索引。 *@param b 布尔。 */ __proto._setShaderValueBool=function(shaderIndex,b){ this._owner._shaderValues.setValue(shaderIndex,b); } /** *设置浮点。 *@param shaderIndex shader索引。 *@param i 浮点。 */ __proto._setShaderValueNumber=function(shaderIndex,number){ this._owner._shaderValues.setValue(shaderIndex,number); } /** *设置二维向量。 *@param shaderIndex shader索引。 *@param vector2 二维向量。 */ __proto._setShaderValueVector2=function(shaderIndex,vector2){ this._owner._shaderValues.setValue(shaderIndex,vector2 ? vector2.elements :null); } /** *增加Shader宏定义。 *@param value 宏定义。 */ __proto._addShaderDefine=function(value){ this._owner._shaderDefineValue |=value; } /** *移除Shader宏定义。 *@param value 宏定义。 */ __proto._removeShaderDefine=function(value){ this._owner._shaderDefineValue &=~value; } /** *@private */ __proto._renderUpdate=function(projectionView){ return true; } /** *@private */ __proto._applyLightMapParams=function(){ if (this._lightmapIndex >=0){ var scene=this._owner.scene; if (scene){ var lightMaps=scene.getlightmaps(); var lightMap=lightMaps[this._lightmapIndex]; if (lightMap){ this._addShaderDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP); if (lightMap.loaded) this._setShaderValuelightMap(lightMap); else lightMap.once(/*laya.events.Event.LOADED*/"loaded",this,this._setShaderValuelightMap); }else { this._removeShaderDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP); } }else { this._removeShaderDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP); } }else { this._removeShaderDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP); } } /** *@private */ __proto._updateOctreeNode=function(){ var treeNode=this._treeNode; if (treeNode && this._octreeNodeNeedChange){ treeNode.updateObject(this); this._octreeNodeNeedChange=false; } } /** *@private */ __proto._destroy=function(){ this.offAll(); var i=0,n=0; for (i=0,n=this._renderElements.length;i < n;i++) this._renderElements[i]._destroy(); for (i=0,n=this._materials.length;i < n;i++) this._materials[i]._removeReference(); this._renderElements=null; this._owner=null; this._materials=null; this._boundingBox=null; this._boundingBoxCenter=null; this._boundingSphere=null; this._lightmapScaleOffset=null; this._destroyed=true; } /** *获取包围球,只读,不允许修改其值。 *@return 包围球。 */ __getset(0,__proto,'boundingSphere',function(){ if (this._boundingSphereNeedChange){ this._calculateBoundingSphere(); this._boundingSphereNeedChange=false; } return this._boundingSphere; }); /** *获取唯一标识ID,通常用于识别。 */ __getset(0,__proto,'id',function(){ return this._id; }); /** *设置第一个实例材质。 *@param value 第一个实例材质。 */ /** *返回第一个实例材质,第一次使用会拷贝实例对象。 *@return 第一个实例材质。 */ __getset(0,__proto,'material',function(){ var material=this._materials[0]; if (material && !this._materialsInstance[0]){ var insMat=this._getInstanceMaterial(material,0); this.event(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",[this,0,insMat]); } return this._materials[0]; },function(value){ this.sharedMaterial=value; }); /** *设置第一个材质。 *@param value 第一个材质。 */ /** *返回第一个材质。 *@return 第一个材质。 */ __getset(0,__proto,'sharedMaterial',function(){ return this._materials[0]; },function(value){ var lastValue=this._materials[0]; if (lastValue!==value){ this._materials[0]=value; this._materialsInstance[0]=false; this._changeMaterialReference(lastValue,value); this.event(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",[this,0,value]); } }); /** *设置光照贴图的索引。 *@param value 光照贴图的索引。 */ /** *获取光照贴图的索引。 *@return 光照贴图的索引。 */ __getset(0,__proto,'lightmapIndex',function(){ return this._lightmapIndex; },function(value){ this._lightmapIndex=value; this._applyLightMapParams(); }); /** *设置光照贴图的缩放和偏移。 *@param 光照贴图的缩放和偏移。 */ /** *获取光照贴图的缩放和偏移。 *@return 光照贴图的缩放和偏移。 */ __getset(0,__proto,'lightmapScaleOffset',function(){ return this._lightmapScaleOffset; },function(value){ this._lightmapScaleOffset=value; this._setShaderValueColor(/*laya.d3.core.RenderableSprite3D.LIGHTMAPSCALEOFFSET*/2,value); this._addShaderDefine(RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV); }); /** *设置是否可用。 *@param value 是否可用。 */ /** *获取是否可用。 *@return 是否可用。 */ __getset(0,__proto,'enable',function(){ return this._enable; },function(value){ this._enable=value; this.event(/*laya.events.Event.ENABLE_CHANGED*/"enablechanged",[this,value]); }); /** *设置实例材质列表。 *@param value 实例材质列表。 */ /** *获取潜拷贝实例材质列表,第一次使用会拷贝实例对象。 *@return 浅拷贝实例材质列表。 */ __getset(0,__proto,'materials',function(){ for (var i=0,n=this._materials.length;i < n;i++){ if (!this._materialsInstance[i]){ var insMat=this._getInstanceMaterial(this._materials[i],i); this.event(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",[this,i,insMat]); } } return this._materials.slice(); },function(value){ this.sharedMaterials=value; }); /** *设置材质列表。 *@param value 材质列表。 */ /** *获取浅拷贝材质列表。 *@return 浅拷贝材质列表。 */ __getset(0,__proto,'sharedMaterials',function(){ var materials=this._materials.slice(); return materials; },function(value){ if (!value) throw new Error("MeshRender: shadredMaterials value can't be null."); var len=value.length; this._materialsInstance.length=len; for (var i=0;i < len;i++){ var lastValue=this._materials[i]; if (lastValue!==value[i]){ this._materialsInstance[i]=false; this._changeMaterialReference(lastValue,value[i]); this.event(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",[this,i,value[i]]); } } this._materials=value; }); /** *获取包围盒,只读,不允许修改其值。 *@return 包围盒。 */ __getset(0,__proto,'boundingBox',function(){ if (this._boundingBoxNeedChange){ this._calculateBoundingBox(); this._boundingBoxNeedChange=false; } return this._boundingBox; }); /** *获取包围盒中心,不允许修改其值。 *@return 包围盒中心。 */ __getset(0,__proto,'boundingBoxCenter',function(){ if (this._boundingBoxCenterNeedChange){ var boundBox=this.boundingBox; Vector3.add(boundBox.min,boundBox.max,this._boundingBoxCenter); Vector3.scale(this._boundingBoxCenter,0.5,this._boundingBoxCenter); this._boundingBoxCenterNeedChange=false; } return this._boundingBoxCenter; }); /** *设置是否接收阴影属性 */ /** *获得是否接收阴影属性 */ __getset(0,__proto,'receiveShadow',function(){ return this._receiveShadow; },function(value){ if (this._receiveShadow!==value){ this._receiveShadow=value; if (value) this._addShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_RECEIVE_SHADOW); else this._removeShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_RECEIVE_SHADOW); } }); /** *获取是否已销毁。 *@return 是否已销毁。 */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); BaseRender._uniqueIDCounter=0; __static(BaseRender, ['_tempBoundBoxCorners',function(){return this._tempBoundBoxCorners=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3()];},'_greenColor',function(){return this._greenColor=new Vector4(0.0,1.0,0.0,1.0);} ]); return BaseRender; })(EventDispatcher) /** *Transform3D 类用于实现3D变换。 */ //class laya.d3.core.Transform3D extends laya.events.EventDispatcher var Transform3D=(function(_super){ function Transform3D(owner){ /**@private */ this._owner=null; /**@private */ this._localQuaternionUpdate=false; /**@private */ this._locaEulerlUpdate=false; /**@private */ this._localUpdate=false; /**@private */ this._worldUpdate=true; /**@private */ this._positionUpdate=true; /**@private */ this._rotationUpdate=true; /**@private */ this._scaleUpdate=true; /**@private */ this._parent=null; /**@private */ this._childs=null; /**@private */ this._dummy=null; /**变换中心点,注意:该中心点不受变换的影响。*/ this.pivot=null; Transform3D.__super.call(this); this._localPosition=new Vector3(); this._localRotation=new Quaternion(0,0,0,1); this._localScale=new Vector3(1,1,1); this._localRotationEuler=new Vector3(); this._localMatrix=new Matrix4x4(); this._position=new Vector3(); this._rotation=new Quaternion(0,0,0,1); this._scale=new Vector3(1,1,1); this._worldMatrix=new Matrix4x4(); this._forward=new Vector3(); this._up=new Vector3(); this._right=new Vector3(); this._owner=owner; this._childs=[]; } __class(Transform3D,'laya.d3.core.Transform3D',_super); var __proto=Transform3D.prototype; /** *@private */ __proto._updateLocalMatrix=function(){ if (this.pivot && (this.pivot.x!==0 || this.pivot.y!==0 || this.pivot.z!==0)){ var scalePivot=Transform3D._tempVector30; Vector3.multiply(this.pivot,this._localScale,scalePivot); var scaleOffsetPosition=Transform3D._tempVector31; Vector3.subtract(scalePivot,this.pivot,scaleOffsetPosition); var rotationOffsetPosition=Transform3D._tempVector32; var localRot=this.localRotation; Vector3.transformQuat(scalePivot,localRot,rotationOffsetPosition); Vector3.subtract(rotationOffsetPosition,scalePivot,rotationOffsetPosition); var resultLocalPosition=Transform3D._tempVector33; Vector3.subtract(this._localPosition,scaleOffsetPosition,resultLocalPosition); Vector3.subtract(resultLocalPosition,rotationOffsetPosition,resultLocalPosition); Matrix4x4.createAffineTransformation(resultLocalPosition,localRot,this._localScale,this._localMatrix); }else { Matrix4x4.createAffineTransformation(this._localPosition,this.localRotation,this._localScale,this._localMatrix); } } /** *@private */ __proto._onWorldPositionRotationTransform=function(){ if (!this._worldUpdate || !this._positionUpdate || !this._rotationUpdate){ this._worldUpdate=this._positionUpdate=this._rotationUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldPositionRotationTransform(); } } /** *@private */ __proto._onWorldPositionScaleTransform=function(){ if (!this._worldUpdate || !this._positionUpdate || !this._scaleUpdate){ this._worldUpdate=this._positionUpdate=this._scaleUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldPositionScaleTransform(); } } /** *@private */ __proto._onWorldPositionTransform=function(){ if (!this._worldUpdate || !this._positionUpdate){ this._worldUpdate=this._positionUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldPositionTransform(); } } /** *@private */ __proto._onWorldRotationTransform=function(){ if (!this._worldUpdate || !this._rotationUpdate){ this._worldUpdate=this._rotationUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldPositionRotationTransform(); } } /** *@private */ __proto._onWorldScaleTransform=function(){ if (!this._worldUpdate || !this._scaleUpdate){ this._worldUpdate=this._scaleUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldPositionScaleTransform(); } } /** *@private */ __proto._onWorldTransform=function(){ if (!this._worldUpdate || !this._positionUpdate || !this._rotationUpdate || !this._scaleUpdate){ this._worldUpdate=this._positionUpdate=this._rotationUpdate=this._scaleUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldTransform(); } } /** *平移变换。 *@param translation 移动距离。 *@param isLocal 是否局部空间。 */ __proto.translate=function(translation,isLocal){ (isLocal===void 0)&& (isLocal=true); if (isLocal){ Matrix4x4.createFromQuaternion(this.localRotation,Transform3D._tempMatrix0); Vector3.transformCoordinate(translation,Transform3D._tempMatrix0,Transform3D._tempVector30); Vector3.add(this.localPosition,Transform3D._tempVector30,this._localPosition); this.localPosition=this._localPosition; }else { Vector3.add(this.position,translation,this._position); this.position=this._position; } } /** *旋转变换。 *@param rotations 旋转幅度。 *@param isLocal 是否局部空间。 *@param isRadian 是否弧度制。 */ __proto.rotate=function(rotation,isLocal,isRadian){ (isLocal===void 0)&& (isLocal=true); (isRadian===void 0)&& (isRadian=true); var rot; if (isRadian){ rot=rotation; }else { Vector3.scale(rotation,Math.PI / 180.0,Transform3D._tempVector30); rot=Transform3D._tempVector30; } Quaternion.createFromYawPitchRoll(rot.y,rot.x,rot.z,Transform3D._tempQuaternion0); if (isLocal){ Quaternion.multiply(this._localRotation,Transform3D._tempQuaternion0,this._localRotation); this.localRotation=this._localRotation; }else { Quaternion.multiply(Transform3D._tempQuaternion0,this.rotation,this._rotation); this.rotation=this._rotation; } } /** *观察目标位置。 *@param target 观察目标。 *@param up 向上向量。 *@param isLocal 是否局部空间。 */ __proto.lookAt=function(target,up,isLocal){ (isLocal===void 0)&& (isLocal=false); var targetE=target.elements; var eyeE; if (isLocal){ eyeE=this._localPosition.elements; if (Math.abs(eyeE[0]-targetE[0])< MathUtils3D.zeroTolerance && Math.abs(eyeE[1]-targetE[1])< MathUtils3D.zeroTolerance && Math.abs(eyeE[2]-targetE[2])< MathUtils3D.zeroTolerance) return; Quaternion.lookAt(this._localPosition,target,up,this._localRotation); this._localRotation.invert(this._localRotation); this.localRotation=this._localRotation; }else { var worldPosition=this.position; eyeE=worldPosition.elements; if (Math.abs(eyeE[0]-targetE[0])< MathUtils3D.zeroTolerance && Math.abs(eyeE[1]-targetE[1])< MathUtils3D.zeroTolerance && Math.abs(eyeE[2]-targetE[2])< MathUtils3D.zeroTolerance) return; Quaternion.lookAt(worldPosition,target,up,this._rotation); this._rotation.invert(this._rotation); this.rotation=this._rotation; } } /** *@private */ __getset(0,__proto,'_isFrontFaceInvert',function(){ var scale=this.scale; var isInvert=scale.x < 0; (scale.y < 0)&& (isInvert=!isInvert); (scale.z < 0)&& (isInvert=!isInvert); return isInvert; }); /** *获取所属精灵。 */ __getset(0,__proto,'owner',function(){ return this._owner; }); /** *设置局部旋转。 *@param value 局部旋转。 */ /** *获取局部旋转。 *@return 局部旋转。 */ __getset(0,__proto,'localRotation',function(){ if (this._localQuaternionUpdate){ var eulerE=this._localRotationEuler.elements; Quaternion.createFromYawPitchRoll(eulerE[1] / Transform3D._angleToRandin,eulerE[0] / Transform3D._angleToRandin,eulerE[2] / Transform3D._angleToRandin,this._localRotation); } return this._localRotation; },function(value){ this._localRotation=value; this._localRotation.normalize(this._localRotation); this._locaEulerlUpdate=true; this._localQuaternionUpdate=false; this._localUpdate=true; if (this.pivot && (this.pivot.x!==0 || this.pivot.y!==0 || this.pivot.z!==0)) this._onWorldPositionRotationTransform(); else this._onWorldRotationTransform(); }); /** *设置世界矩阵。 *@param value 世界矩阵。 */ /** *获取世界矩阵。 *@return 世界矩阵。 */ __getset(0,__proto,'worldMatrix',function(){ if (this._worldUpdate){ if (this._parent !=null) Matrix4x4.multiply(this._parent.worldMatrix,this.localMatrix,this._worldMatrix); else this.localMatrix.cloneTo(this._worldMatrix); this._worldUpdate=false; } return this._worldMatrix; },function(value){ if (this._parent===null){ value.cloneTo(this._localMatrix); }else { this._parent.worldMatrix.invert(this._localMatrix); Matrix4x4.multiply(this._localMatrix,value,this._localMatrix); } this.localMatrix=this._localMatrix; this._worldMatrix=value; this._worldUpdate=false; }); /** *获取世界矩阵是否需要更新。 *@return 世界矩阵是否需要更新。 */ __getset(0,__proto,'worldNeedUpdate',function(){ return this._worldUpdate; }); /** *设置局部矩阵。 *@param value 局部矩阵。 */ /** *获取局部矩阵。 *@return 局部矩阵。 */ __getset(0,__proto,'localMatrix',function(){ if (this._localUpdate){ this._updateLocalMatrix(); this._localUpdate=false; } return this._localMatrix; },function(value){ this._localMatrix=value; this._localMatrix.decomposeTransRotScale(this._localPosition,this._localRotation,this._localScale); this._localUpdate=false; this._onWorldTransform(); }); /** *设置关联虚拟变换。 *@param value 虚拟变换。 */ /** *获取关联虚拟变换。 *@return 虚拟变换。 */ __getset(0,__proto,'dummy',function(){ return this._dummy; },function(value){ if (this._dummy!==value){ (this._dummy)&& (this._dummy._entity=null); (value)&& (value._entity=this); this._dummy=value; } }); /** *设置局部位置。 *@param value 局部位置。 */ /** *获取局部位置。 *@return 局部位置。 */ __getset(0,__proto,'localPosition',function(){ return this._localPosition; },function(value){ this._localPosition=value; this._localUpdate=true; this._onWorldPositionTransform(); }); /** *设置世界位置。 *@param value 世界位置。 */ /** *获取世界位置。 *@return 世界位置。 */ __getset(0,__proto,'position',function(){ if (this._positionUpdate){ if (this._parent !=null){ var parentPosition=this._parent.position; Vector3.multiply(this._localPosition,this._parent.scale,Transform3D._tempVector30); Vector3.transformQuat(Transform3D._tempVector30,this._parent.rotation,Transform3D._tempVector30); Vector3.add(parentPosition,Transform3D._tempVector30,this._position); }else { this._localPosition.cloneTo(this._position); } this._positionUpdate=false; } return this._position; },function(value){ if (this._parent !=null){ Vector3.subtract(value,this._parent.position,this._localPosition); var parentScaleE=this._parent.scale.elements; var psX=parentScaleE[0],psY=parentScaleE[1],psZ=parentScaleE[2]; if (psX!==1.0 || psY!==1.0 || psZ!==1.0){ var invertScale=Transform3D._tempVector30; var invertScaleE=invertScale.elements; invertScaleE[0]=1.0 / psX; invertScaleE[1]=1.0 / psY; invertScaleE[2]=1.0 / psZ; Vector3.multiply(this._localPosition,invertScale,this._localPosition); }; var parentRotation=this._parent.rotation; parentRotation.invert(Transform3D._tempQuaternion0); Vector3.transformQuat(this._localPosition,Transform3D._tempQuaternion0,this._localPosition); }else { value.cloneTo(this._localPosition); } this.localPosition=this._localPosition; this._position=value; this._positionUpdate=false; }); /** *设置局部缩放。 *@param value 局部缩放。 */ /** *获取局部缩放。 *@return 局部缩放。 */ __getset(0,__proto,'localScale',function(){ return this._localScale; },function(value){ this._localScale=value; this._localUpdate=true; if (this.pivot && (this.pivot.x!==0 || this.pivot.y!==0 || this.pivot.z!==0)) this._onWorldPositionScaleTransform(); else this._onWorldScaleTransform(); }); /** *设置局部空间的旋转角度。 *@param value 欧拉角的旋转值,顺序为x、y、z。 */ /** *获取局部空间的旋转角度。 *@return 欧拉角的旋转值,顺序为x、y、z。 */ __getset(0,__proto,'localRotationEuler',function(){ if (this._locaEulerlUpdate){ this._localRotation.getYawPitchRoll(Transform3D._tempVector30); var eulerE=Transform3D._tempVector30.elements; var localRotationEulerE=this._localRotationEuler.elements; localRotationEulerE[0]=eulerE[1] *Transform3D._angleToRandin; localRotationEulerE[1]=eulerE[0] *Transform3D._angleToRandin; localRotationEulerE[2]=eulerE[2] *Transform3D._angleToRandin; } return this._localRotationEuler; },function(value){ this._localRotationEuler=value; this._locaEulerlUpdate=false; this._localQuaternionUpdate=true; this._localUpdate=true; if (this.pivot && (this.pivot.x!==0 || this.pivot.y!==0 || this.pivot.z!==0)) this._onWorldPositionRotationTransform(); else this._onWorldRotationTransform(); }); /** *设置世界旋转。 *@param value 世界旋转。 */ /** *获取世界旋转。 *@return 世界旋转。 */ __getset(0,__proto,'rotation',function(){ if (this._rotationUpdate){ if (this._parent !=null) Quaternion.multiply(this._parent.rotation,this.localRotation,this._rotation); else this.localRotation.cloneTo(this._rotation); this._rotationUpdate=false; } return this._rotation; },function(value){ if (this._parent !=null){ this._parent.rotation.invert(Transform3D._tempQuaternion0); Quaternion.multiply(value,Transform3D._tempQuaternion0,this._localRotation); }else { value.cloneTo(this._localRotation); } this.localRotation=this._localRotation; this._rotation=value; this._rotationUpdate=false; }); /** *设置世界缩放。 *@param value 世界缩放。 */ /** *获取世界缩放。 *@return 世界缩放。 */ __getset(0,__proto,'scale',function(){ if (!this._scaleUpdate) return this._scale; if (this._parent!==null) Vector3.multiply(this._parent.scale,this._localScale,this._scale); else this._localScale.cloneTo(this._scale); this._scaleUpdate=false; return this._scale; },function(value){ if (this._parent!==null){ var pScaleE=this._parent.scale.elements; var invPScaleE=Transform3D._tempVector30.elements; invPScaleE[0]=1.0 / pScaleE[0]; invPScaleE[1]=1.0 / pScaleE[1]; invPScaleE[2]=1.0 / pScaleE[2]; Vector3.multiply(value,Transform3D._tempVector30,this._localScale); }else { value.cloneTo(this._localScale); } this.localScale=this._localScale; this._scale=value; this._scaleUpdate=false; }); /** *设置局部空间的旋转角度。 *@param 欧拉角的旋转值,顺序为x、y、z。 */ __getset(0,__proto,'rotationEuler',null,function(value){ Quaternion.createFromYawPitchRoll(value.y,value.x,value.z,this._rotation); this.rotation=this._rotation; }); /** *获取向前方向。 *@return 向前方向。 */ __getset(0,__proto,'forward',function(){ var worldMatElem=this.worldMatrix.elements; this._forward.elements[0]=-worldMatElem[8]; this._forward.elements[1]=-worldMatElem[9]; this._forward.elements[2]=-worldMatElem[10]; return this._forward; }); /** *获取向上方向。 *@return 向上方向。 */ __getset(0,__proto,'up',function(){ var worldMatElem=this.worldMatrix.elements; this._up.elements[0]=worldMatElem[4]; this._up.elements[1]=worldMatElem[5]; this._up.elements[2]=worldMatElem[6]; return this._up; }); /** *获取向右方向。 *@return 向右方向。 */ __getset(0,__proto,'right',function(){ var worldMatElem=this.worldMatrix.elements; this._right.elements[0]=worldMatElem[0]; this._right.elements[1]=worldMatElem[1]; this._right.elements[2]=worldMatElem[2]; return this._right; }); /** *设置父3D变换。 *@param value 父3D变换。 */ /** *获取父3D变换。 *@return 父3D变换。 */ __getset(0,__proto,'parent',function(){ return this._parent; },function(value){ if (this._parent!==value){ if (this._parent){ var parentChilds=this._parent._childs; var index=parentChilds.indexOf(this); parentChilds.splice(index,1); } if (value){ value._childs.push(this); (value)&& (this._onWorldTransform()); } this._parent=value; } }); __static(Transform3D, ['_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempVector31',function(){return this._tempVector31=new Vector3();},'_tempVector32',function(){return this._tempVector32=new Vector3();},'_tempVector33',function(){return this._tempVector33=new Vector3();},'_tempQuaternion0',function(){return this._tempQuaternion0=new Quaternion();},'_tempMatrix0',function(){return this._tempMatrix0=new Matrix4x4();},'_angleToRandin',function(){return this._angleToRandin=180 / Math.PI;} ]); return Transform3D; })(EventDispatcher) /** *TransformUV 类用于实现UV变换。 */ //class laya.d3.core.TransformUV extends laya.events.EventDispatcher var TransformUV=(function(_super){ function TransformUV(){ /**@private */ this._rotation=0; /**@private */ //this._tiling=null; /**@private */ this._matNeedUpdte=false; TransformUV.__super.call(this); this._matrix=new Matrix4x4(); this._offset=new Vector2(); this._tiling=new Vector2(1.0,1.0); } __class(TransformUV,'laya.d3.core.TransformUV',_super); var __proto=TransformUV.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *@private */ __proto._updateMatrix=function(){ TransformUV._tempOffsetV3.elements[0]=this._offset.x; TransformUV._tempOffsetV3.elements[1]=this._offset.y; Quaternion.createFromYawPitchRoll(0,0,this._rotation,TransformUV._tempRotationQua); TransformUV._tempTitlingV3.elements[0]=this._tiling.x; TransformUV._tempTitlingV3.elements[1]=this._tiling.y; Matrix4x4.createAffineTransformation(TransformUV._tempOffsetV3,TransformUV._tempRotationQua,TransformUV._tempTitlingV3,this._matrix); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ destObject._matrix=this._matrix.clone(); destObject._offset=this._offset.clone(); destObject._rotation=this._rotation; destObject._tiling=this._tiling.clone(); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } /** *获取变换矩阵。 *@return 变换矩阵。 */ __getset(0,__proto,'matrix',function(){ if (this._matNeedUpdte){ this._updateMatrix(); this._matNeedUpdte=false; } return this._matrix; }); /** *设置平铺次数。 *@param value 平铺次数。 */ /** *获取平铺次数。 *@return 平铺次数。 */ __getset(0,__proto,'tiling',function(){ return this._tiling; },function(value){ this._tiling=value; this._matNeedUpdte=true; }); /** *设置偏移。 *@param value 偏移。 */ /** *获取偏移。 *@return 偏移。 */ __getset(0,__proto,'offset',function(){ return this._offset; },function(value){ this._offset=value; this._matNeedUpdte=true; }); /** *设置旋转。 *@param value 旋转。 */ /** *获取旋转。 *@return 旋转。 */ __getset(0,__proto,'rotation',function(){ return this._rotation; },function(value){ this._rotation=value; this._matNeedUpdte=true; }); __static(TransformUV, ['_tempOffsetV3',function(){return this._tempOffsetV3=new Vector3(0,0,0);},'_tempRotationQua',function(){return this._tempRotationQua=new Quaternion();},'_tempTitlingV3',function(){return this._tempTitlingV3=new Vector3(1,1,1);} ]); return TransformUV; })(EventDispatcher) /** *CollsionManager 类用于碰撞管理器。 */ //class laya.d3.utils.CollisionManager extends laya.events.EventDispatcher var CollisionManager=(function(_super){ /** *创建一个新的 CollsionManager 实例。 */ function CollisionManager(){ CollisionManager.__super.call(this); } __class(CollisionManager,'laya.d3.utils.CollisionManager',_super); CollisionManager._onTrigger=function(rigidCol,receiveCol,rigidScripts,receiveScripts,bothRigid){ var i=0,n=0; var rigidID=rigidCol.id; var receiveID=receiveCol.id; if (!rigidCol._ignoreCollisonMap[receiveID]){ var colMan=Physics.collisionManager; var needTest=rigidCol._runtimeCollisonTestMap[receiveID]; if (needTest !=null){ if (needTest){ if (rigidCol._collisonTo(receiveCol)){ if (rigidCol._runtimeCollisonMap[receiveID]){ for (i=0,n=rigidScripts.length;i < n;i++) rigidScripts[i].onTriggerStay(receiveCol); for (i=0,n=receiveScripts.length;i < n;i++) receiveScripts[i].onTriggerStay(rigidCol); colMan.event(/*laya.events.Event.TRIGGER_STAY*/"triggerstay",[rigidCol,receiveCol]); }else { rigidCol._runtimeCollisonMap[receiveID]=receiveCol; rigidCol._runtimeCollisonTestMap[receiveID]=false; receiveCol._runtimeCollisonMap[rigidID]=rigidCol; if (bothRigid) receiveCol._runtimeCollisonTestMap[rigidID]=false; for (i=0,n=rigidScripts.length;i < n;i++) rigidScripts[i].onTriggerEnter(receiveCol); for (i=0,n=receiveScripts.length;i < n;i++) receiveScripts[i].onTriggerEnter(rigidCol); colMan.event(/*laya.events.Event.TRIGGER_ENTER*/"triggerenter",[rigidCol,receiveCol]); } }else { var rigidMap=rigidCol._runtimeCollisonMap; if (rigidMap[receiveID]){ delete rigidMap[receiveID]; delete rigidCol._runtimeCollisonTestMap[receiveID]; delete receiveCol._runtimeCollisonMap[rigidID]; if (bothRigid) delete receiveCol._runtimeCollisonTestMap[rigidID]; for (i=0,n=rigidScripts.length;i < n;i++) rigidScripts[i].onTriggerExit(receiveCol); for (i=0,n=receiveScripts.length;i < n;i++) receiveScripts[i].onTriggerExit(rigidCol); colMan.event(/*laya.events.Event.TRIGGER_EXIT*/"triggerexit",[rigidCol,receiveCol]); } } }else { for (i=0,n=rigidScripts.length;i < n;i++) rigidScripts[i].onTriggerStay(receiveCol); for (i=0,n=receiveScripts.length;i < n;i++) receiveScripts[i].onTriggerStay(rigidCol); colMan.event(/*laya.events.Event.TRIGGER_STAY*/"triggerstay",[rigidCol,receiveCol]); } }else { if (rigidCol._collisonTo(receiveCol)){ rigidCol._runtimeCollisonMap[receiveID]=receiveCol; rigidCol._runtimeCollisonTestMap[receiveID]=false; receiveCol._runtimeCollisonMap[rigidID]=rigidCol; if (bothRigid) receiveCol._runtimeCollisonTestMap[rigidID]=false; for (i=0,n=rigidScripts.length;i < n;i++) rigidScripts[i].onTriggerEnter(receiveCol); for (i=0,n=receiveScripts.length;i < n;i++) receiveScripts[i].onTriggerEnter(rigidCol); colMan.event(/*laya.events.Event.TRIGGER_ENTER*/"triggerenter",[rigidCol,receiveCol]); } } } } CollisionManager._triggerCollision=function(){ var colList=Layer._collsionTestList; var colCount=colList.length; var colMat=Physics._layerCollsionMatrix; for (var i=0;i < colCount;i++){ var row=colList[i]; var rowLayer=Layer.getLayerByNumber(row); var rowColliders=rowLayer._colliders; var rowRigOffset=rowLayer._nonRigidbodyOffset; for (var j=colCount-1;j >=i;j--){ var col=colList[j]; var test=colMat[row][(/*laya.d3.core.Layer.maxCount*/31-1)-col]; if (test){ var k=0,c=0,x=0,z=0; var rowCol,colCol,rowScripts; var colLayer=Layer.getLayerByNumber(col); var colColliders=colLayer._colliders; var colRigOffset=colLayer._nonRigidbodyOffset; if (rowLayer!==colLayer){ for (k=0;k < rowRigOffset;k++){ rowCol=rowColliders[k]; if (rowCol.enable){ rowScripts=rowCol.owner._scripts; for (x=0,z=colRigOffset;x < z;x++){ colCol=colColliders[x]; (colCol.enable)&& (CollisionManager._onTrigger(rowCol,colCol,rowScripts,colCol.owner._scripts,true)); } for (x=colRigOffset,z=colColliders.length;x < z;x++){ colCol=colColliders[x]; (colCol.enable)&& (CollisionManager._onTrigger(rowCol,colCol,rowScripts,colCol.owner._scripts,false)); } } } for (k=rowRigOffset,c=rowColliders.length;k < c;k++){ rowCol=rowColliders[k]; if (rowCol.enable){ rowScripts=rowCol.owner._scripts; for (x=0,z=colLayer._nonRigidbodyOffset;x < z;x++){ colCol=colColliders[x]; (colCol.enable)&& (CollisionManager._onTrigger(colCol,rowCol,rowScripts,colCol.owner._scripts,false)); } } } }else { for (k=0;k < rowRigOffset;k++){ rowCol=rowColliders[k]; if (rowCol.enable){ rowScripts=rowCol.owner._scripts; for (x=k+1,z=rowRigOffset;x < z;x++){ colCol=colColliders[x]; (colCol.enable)&& (CollisionManager._onTrigger(rowCol,colCol,rowScripts,colCol.owner._scripts,true)); } for (x=rowRigOffset,z=rowColliders.length;x < z;x++){ colCol=colColliders[x]; (colCol.enable)&& (CollisionManager._onTrigger(rowCol,colCol,rowScripts,colCol.owner._scripts,false)); } } } } } } } } return CollisionManager; })(EventDispatcher) /** *SplineCurvePosition 类用于通过顶点创建闪光插值。 */ //class laya.d3.core.glitter.SplineCurvePosition extends laya.d3.core.glitter.SplineCurvePositionVelocity var SplineCurvePosition=(function(_super){ /** *创建一个 SplineCurvePosition 实例。 */ function SplineCurvePosition(){ SplineCurvePosition.__super.call(this); } __class(SplineCurvePosition,'laya.d3.core.glitter.SplineCurvePosition',_super); var __proto=SplineCurvePosition.prototype; /** *@private *计算速度。 */ __proto._CalcVelocity=function(left,right,out){ Vector3.subtract(left,right,out); Vector3.scale(out,0.5,out); } /** *初始化插值所需信息。 *@param lastPosition0 顶点0的上次位置。 *@param position0 顶点0的位置。 *@param lastPosition1 顶点1的上次位置。 *@param position1 顶点1的位置。 */ __proto.Init=function(lastPosition0,position0,lastPosition1,position1){ this._CalcVelocity(position0,lastPosition0,this._tempVector30); this._CalcVelocity(position1,lastPosition1,this._tempVector31); _super.prototype.Init.call(this,position0,this._tempVector30,position1,this._tempVector31); } return SplineCurvePosition; })(SplineCurvePositionVelocity) /** *BoxShape 类用于创建球形粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.BoxShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape var BoxShape=(function(_super){ function BoxShape(){ /**发射器X轴长度。*/ this.x=NaN; /**发射器Y轴长度。*/ this.y=NaN; /**发射器Z轴长度。*/ this.z=NaN; BoxShape.__super.call(this); this.x=1.0; this.y=1.0; this.z=1.0; this.randomDirection=false; } __class(BoxShape,'laya.d3.core.particleShuriKen.module.shape.BoxShape',_super); var __proto=BoxShape.prototype; /** *@inheritDoc */ __proto._getShapeBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=-this.x *0.5; minE[1]=-this.y *0.5; minE[2]=-this.z *0.5; var maxE=boundBox.max.elements; maxE[0]=this.x *0.5; maxE[1]=this.y *0.5; maxE[2]=this.z *0.5; } /** *@inheritDoc */ __proto._getSpeedBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=0.0; minE[1]=0.0; minE[2]=0.0; var maxE=boundBox.max.elements; maxE[0]=0.0; maxE[1]=1.0; maxE[2]=0.0; } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ var rpE=position.elements; var rdE=direction.elements; if (rand){ rand.seed=randomSeeds[16]; ShapeUtils._randomPointInsideHalfUnitBox(position,rand); randomSeeds[16]=rand.seed; }else { ShapeUtils._randomPointInsideHalfUnitBox(position); } rpE[0]=this.x *rpE[0]; rpE[1]=this.y *rpE[1]; rpE[2]=this.z *rpE[2]; if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } }else { rdE[0]=0.0; rdE[1]=0.0; rdE[2]=1.0; } } __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destShape=destObject; destShape.x=this.x; destShape.y=this.y; destShape.z=this.z; destShape.randomDirection=this.randomDirection; } return BoxShape; })(BaseShape) /** *CircleShape 类用于创建环形粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.CircleShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape var CircleShape=(function(_super){ function CircleShape(){ /**发射器半径。*/ this.radius=NaN; /**环形弧度。*/ this.arc=NaN; /**从边缘发射。*/ this.emitFromEdge=false; CircleShape.__super.call(this); this.radius=1.0; this.arc=360.0 / 180.0 *Math.PI; this.emitFromEdge=false; this.randomDirection=false; } __class(CircleShape,'laya.d3.core.particleShuriKen.module.shape.CircleShape',_super); var __proto=CircleShape.prototype; /** *@inheritDoc */ __proto._getShapeBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[2]=-this.radius; minE[1]=0; var maxE=boundBox.max.elements; maxE[0]=maxE[2]=this.radius; maxE[1]=0; } /** *@inheritDoc */ __proto._getSpeedBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[1]=-1; minE[2]=0; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=1; maxE[2]=0; } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ var rpE=position.elements; var positionPointE=CircleShape._tempPositionPoint.elements; if (rand){ rand.seed=randomSeeds[16]; if (this.emitFromEdge) ShapeUtils._randomPointUnitArcCircle(this.arc,CircleShape._tempPositionPoint,rand); else ShapeUtils._randomPointInsideUnitArcCircle(this.arc,CircleShape._tempPositionPoint,rand); randomSeeds[16]=rand.seed; }else { if (this.emitFromEdge) ShapeUtils._randomPointUnitArcCircle(this.arc,CircleShape._tempPositionPoint); else ShapeUtils._randomPointInsideUnitArcCircle(this.arc,CircleShape._tempPositionPoint); } rpE[0]=-positionPointE[0]; rpE[1]=positionPointE[1]; rpE[2]=0; Vector3.scale(position,this.radius,position); if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } }else { position.cloneTo(direction); } } __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destShape=destObject; destShape.radius=this.radius; destShape.arc=this.arc; destShape.emitFromEdge=this.emitFromEdge; destShape.randomDirection=this.randomDirection; } __static(CircleShape, ['_tempPositionPoint',function(){return this._tempPositionPoint=new Vector2();} ]); return CircleShape; })(BaseShape) /** *ConeShape 类用于创建锥形粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.ConeShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape var ConeShape=(function(_super){ function ConeShape(){ /**发射角度。*/ this.angle=NaN; /**发射器半径。*/ this.radius=NaN; /**椎体长度。*/ this.length=NaN; /**发射类型,0为Base,1为BaseShell,2为Volume,3为VolumeShell。*/ this.emitType=0; ConeShape.__super.call(this); this.angle=25.0 / 180.0 *Math.PI; this.radius=1.0; this.length=5.0; this.emitType=0; this.randomDirection=false; } __class(ConeShape,'laya.d3.core.particleShuriKen.module.shape.ConeShape',_super); var __proto=ConeShape.prototype; /** *@inheritDoc */ __proto._getShapeBoundBox=function(boundBox){ var coneRadius2=this.radius+this.length *Math.sin(this.angle); var coneLength=this.length *Math.cos(this.angle); var minE=boundBox.min.elements; minE[0]=minE[1]=-coneRadius2; minE[2]=0; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=coneRadius2; maxE[2]=coneLength; } /** *@inheritDoc */ __proto._getSpeedBoundBox=function(boundBox){ var sinA=Math.sin(this.angle); var minE=boundBox.min.elements; minE[0]=minE[1]=-sinA; minE[2]=0; var maxE=boundBox.max.elements; maxE[0]=minE[1]=sinA; maxE[2]=1; } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ var rpE=position.elements; var rdE=direction.elements; var positionPointE=ConeShape._tempPositionPoint.elements; var positionX=NaN; var positionY=NaN; var directionPointE; var dirCosA=Math.cos(this.angle); var dirSinA=Math.sin(this.angle); switch (this.emitType){ case 0: if (rand){ rand.seed=randomSeeds[16]; ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint,rand); randomSeeds[16]=rand.seed; }else { ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint); } positionX=positionPointE[0]; positionY=positionPointE[1]; rpE[0]=positionX *this.radius; rpE[1]=positionY *this.radius; rpE[2]=0; if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint); } directionPointE=ConeShape._tempDirectionPoint.elements; rdE[0]=directionPointE[0] *dirSinA; rdE[1]=directionPointE[1] *dirSinA; }else { rdE[0]=positionX *dirSinA; rdE[1]=positionY *dirSinA; } rdE[2]=dirCosA; break ; case 1: if (rand){ rand.seed=randomSeeds[16]; ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint,rand); randomSeeds[16]=rand.seed; }else { ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint); } positionX=positionPointE[0]; positionY=positionPointE[1]; rpE[0]=positionX *this.radius; rpE[1]=positionY *this.radius; rpE[2]=0; if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint); } directionPointE=ConeShape._tempDirectionPoint.elements; rdE[0]=directionPointE[0] *dirSinA; rdE[1]=directionPointE[1] *dirSinA; }else { rdE[0]=positionX *dirSinA; rdE[1]=positionY *dirSinA; } rdE[2]=dirCosA; break ; case 2: if (rand){ rand.seed=randomSeeds[16]; ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint,rand); }else { ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint); } positionX=positionPointE[0]; positionY=positionPointE[1]; rpE[0]=positionX *this.radius; rpE[1]=positionY *this.radius; rpE[2]=0; rdE[0]=positionX *dirSinA; rdE[1]=positionY *dirSinA; rdE[2]=dirCosA; Vector3.normalize(direction,direction); if (rand){ Vector3.scale(direction,this.length *rand.getFloat(),direction); randomSeeds[16]=rand.seed; }else { Vector3.scale(direction,this.length *Math.random(),direction); } Vector3.add(position,direction,position); if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } } break ; case 3: if (rand){ rand.seed=randomSeeds[16]; ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint,rand); }else { ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint); } positionX=positionPointE[0]; positionY=positionPointE[1]; rpE[0]=positionX *this.radius; rpE[1]=positionY *this.radius; rpE[2]=0; rdE[0]=positionX *dirSinA; rdE[1]=positionY *dirSinA; rdE[2]=dirCosA; Vector3.normalize(direction,direction); if (rand){ Vector3.scale(direction,this.length *rand.getFloat(),direction); randomSeeds[16]=rand.seed; }else { Vector3.scale(direction,this.length *Math.random(),direction); } Vector3.add(position,direction,position); if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } } break ; default : throw new Error("ConeShape:emitType is invalid."); } } __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destShape=destObject; destShape.angle=this.angle; destShape.radius=this.radius; destShape.length=this.length; destShape.emitType=this.emitType; destShape.randomDirection=this.randomDirection; } __static(ConeShape, ['_tempPositionPoint',function(){return this._tempPositionPoint=new Vector2();},'_tempDirectionPoint',function(){return this._tempDirectionPoint=new Vector2();} ]); return ConeShape; })(BaseShape) /** *HemisphereShape 类用于创建半球形粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.HemisphereShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape var HemisphereShape=(function(_super){ function HemisphereShape(){ /**发射器半径。*/ this.radius=NaN; /**从外壳发射。*/ this.emitFromShell=false; HemisphereShape.__super.call(this); this.radius=1.0; this.emitFromShell=false; this.randomDirection=false; } __class(HemisphereShape,'laya.d3.core.particleShuriKen.module.shape.HemisphereShape',_super); var __proto=HemisphereShape.prototype; /** *@inheritDoc */ __proto._getShapeBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[1]=minE[2]=-this.radius; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=this.radius; maxE[2]=0; } /** *@inheritDoc */ __proto._getSpeedBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[1]=-1; minE[2]=0; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=maxE[2]=1; } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ var rpE=position.elements; if (rand){ rand.seed=randomSeeds[16]; if (this.emitFromShell) ShapeUtils._randomPointUnitSphere(position,rand); else ShapeUtils._randomPointInsideUnitSphere(position,rand); randomSeeds[16]=rand.seed; }else { if (this.emitFromShell) ShapeUtils._randomPointUnitSphere(position); else ShapeUtils._randomPointInsideUnitSphere(position); } Vector3.scale(position,this.radius,position); var z=rpE[2]; (z < 0.0)&& (rpE[2]=z *-1.0); if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } }else { position.cloneTo(direction); } } __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destShape=destObject; destShape.radius=this.radius; destShape.emitFromShell=this.emitFromShell; destShape.randomDirection=this.randomDirection; } return HemisphereShape; })(BaseShape) /** *SphereShape 类用于创建球形粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.SphereShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape var SphereShape=(function(_super){ function SphereShape(){ /**发射器半径。*/ this.radius=NaN; /**从外壳发射。*/ this.emitFromShell=false; SphereShape.__super.call(this); this.radius=1.0; this.emitFromShell=false; this.randomDirection=false; } __class(SphereShape,'laya.d3.core.particleShuriKen.module.shape.SphereShape',_super); var __proto=SphereShape.prototype; /** *@inheritDoc */ __proto._getShapeBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[1]=minE[2]=-this.radius; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=maxE[2]=this.radius; } /** *@inheritDoc */ __proto._getSpeedBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[1]=minE[2]=-1; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=maxE[2]=1; } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ if (rand){ rand.seed=randomSeeds[16]; if (this.emitFromShell) ShapeUtils._randomPointUnitSphere(position,rand); else ShapeUtils._randomPointInsideUnitSphere(position,rand); randomSeeds[16]=rand.seed; }else { if (this.emitFromShell) ShapeUtils._randomPointUnitSphere(position); else ShapeUtils._randomPointInsideUnitSphere(position); } Vector3.scale(position,this.radius,position); if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } }else { position.cloneTo(direction); } } __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destShape=destObject; destShape.radius=this.radius; destShape.emitFromShell=this.emitFromShell; destShape.randomDirection=this.randomDirection; } return SphereShape; })(BaseShape) /** *@private */ //class laya.d3.core.render.SubMeshRenderElement extends laya.d3.core.render.RenderElement var SubMeshRenderElement=(function(_super){ function SubMeshRenderElement(){ /**@private */ this._batchIndexStart=0; /**@private */ this._batchIndexEnd=0; /**@private */ this._skinAnimationDatas=null; SubMeshRenderElement.__super.call(this); } __class(SubMeshRenderElement,'laya.d3.core.render.SubMeshRenderElement',_super); return SubMeshRenderElement; })(RenderElement) /** *@private *ShaderCompile 类用于创建Shader编译类型。 */ //class laya.d3.shader.ShaderCompile3D extends laya.webgl.utils.ShaderCompile var ShaderCompile3D=(function(_super){ function ShaderCompile3D(name,vs,ps,attributeMap,uniformMap,includeFiles){ /**@private */ this._name=NaN; /**@private */ this._attributeMap=null; /**@private */ this._renderElementUniformMap=null; /**@private */ this._materialUniformMap=null; /**@private */ this._spriteUniformMap=null; /**@private */ this._cameraUniformMap=null; /**@private */ this._sceneUniformMap=null; this.sharders=null; /**@private */ this._spriteDefineCounter=3; /**@private */ this._spriteInt2name=[]; /**@private */ this._spriteName2Int={}; /**@private */ this._materialDefineCounter=1; /**@private */ this._materialInt2name=[]; /**@private */ this._materialName2Int={}; this._conchShader=null; this._name=name; this._renderElementUniformMap={}; this._materialUniformMap={}; this._spriteUniformMap={}; this._cameraUniformMap={}; this._sceneUniformMap={}; this.sharders=[]; this._spriteInt2name[ParallelSplitShadowMap.SHADERDEFINE_RECEIVE_SHADOW]="RECEIVESHADOW"; this._spriteInt2name[RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV]="SCALEOFFSETLIGHTINGMAPUV"; this._spriteInt2name[RenderableSprite3D.SAHDERDEFINE_LIGHTMAP]="LIGHTMAP"; this._spriteInt2name[SkinnedMeshSprite3D.SHADERDEFINE_BONE]="BONE"; this._materialInt2name[BaseMaterial.SHADERDEFINE_ALPHATEST]="ALPHATEST"; var defineMap={}; ShaderCompile3D.__super.call(this,name,vs,ps,null,defineMap); this._attributeMap=attributeMap; var renderElementUnifCount=0,materialUnifCount=0,spriteUnifCount=0; var key; for (key in uniformMap){ var uniformParam=uniformMap[key]; switch (uniformParam[1]){ case /*laya.d3.shader.Shader3D.PERIOD_RENDERELEMENT*/0: this._renderElementUniformMap[key]=uniformParam[0]; break ; case /*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1: this._materialUniformMap[key]=uniformParam[0]; break ; case /*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2: this._spriteUniformMap[key]=uniformParam[0]; break ; case /*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3: this._cameraUniformMap[key]=uniformParam[0]; break ; case /*laya.d3.shader.Shader3D.PERIOD_SCENE*/4: this._sceneUniformMap[key]=uniformParam[0]; break ; default : throw new Error("ShaderCompile3D: period is unkonw."); } } } __class(ShaderCompile3D,'laya.d3.shader.ShaderCompile3D',_super); var __proto=ShaderCompile3D.prototype; /** *@private */ __proto._definesToNameDic=function(value,int2Name){ var o={}; var d=1; for (var i=0;i < 32;i++){ d=1 << i; if (d > value)break ; if (value & d){ var name=int2Name[d]; name && (o[name]=""); } } return o; } /** *根据宏动态生成shader文件,支持#include?COLOR_FILTER "parts/ColorFilter_ps_logic.glsl";条件嵌入文件 *@param name *@param vs *@param ps *@param define 宏定义,格式:{name:value...} *@return */ __proto.withCompile=function(publicDefine,spriteDefine,materialDefine){ var shader; var spriteDefShaders,materialDefShaders; spriteDefShaders=this.sharders[publicDefine]; if (spriteDefShaders){ materialDefShaders=spriteDefShaders[spriteDefine]; if (materialDefShaders){ shader=materialDefShaders[materialDefine]; if (shader) return shader; }else { materialDefShaders=spriteDefShaders[spriteDefine]=[]; } }else { spriteDefShaders=this.sharders[publicDefine]=[]; materialDefShaders=spriteDefShaders[spriteDefine]=[]; }; var publicDefGroup=this._definesToNameDic(publicDefine,ShaderCompile3D._globalInt2name); var spriteDefGroup=this._definesToNameDic(spriteDefine,this._spriteInt2name); var materialDefGroup=this._definesToNameDic(materialDefine,this._materialInt2name); var key; if (laya.d3.shader.ShaderCompile3D.debugMode){ var publicDefGroupStr=""; for (key in publicDefGroup) publicDefGroupStr+=key+" "; var spriteDefGroupStr=""; for (key in spriteDefGroup) spriteDefGroupStr+=key+" "; var materialDefGroupStr=""; for (key in materialDefGroup) materialDefGroupStr+=key+" "; console.log("ShaderCompile3DDebugMode---(Name:"+Shader3D.nameKey.getName(this._name)+" PublicDefine:"+publicDefine+" SpriteDefine:"+spriteDefine+" MaterialDefine:"+materialDefine+" PublicDefineGroup:"+publicDefGroupStr+" SpriteDefineGroup:"+spriteDefGroupStr+"MaterialDefineGroup: "+materialDefGroupStr+")---ShaderCompile3DDebugMode"); }; var defMap={}; var defineStr=""; if (publicDefGroup){ for (key in publicDefGroup){ defineStr+="#define "+key+"\n"; defMap[key]=true; } } if (spriteDefGroup){ for (key in spriteDefGroup){ defineStr+="#define "+key+"\n"; defMap[key]=true; } } if (materialDefGroup){ for (key in materialDefGroup){ defineStr+="#define "+key+"\n"; defMap[key]=true; } }; var vs=this._VS.toscript(defMap,[]); var ps=this._PS.toscript(defMap,[]); shader=Shader3D.create(defineStr+vs.join('\n'),defineStr+ps.join('\n'),this._attributeMap,this._sceneUniformMap,this._cameraUniformMap,this._spriteUniformMap,this._materialUniformMap,this._renderElementUniformMap); materialDefShaders[materialDefine]=shader; return shader; } /** *通过宏定义预编译shader。 *@param spriteIntToNameDic 精灵宏定义数组。 *@param publicDefine 公共宏定义值。 *@param spriteDefine 精灵宏定义值。 *@param materialDefine 材质宏定义值。 */ __proto.precompileShaderWithShaderDefine=function(publicDefine,spriteDefine,materialDefine){ this.withCompile(publicDefine,spriteDefine,materialDefine); } /** *注册材质宏定义。 *@param name 宏定义名称。 *@return */ __proto.addMaterialDefines=function(shaderdefines){ var defines=shaderdefines.defines; for (var k in defines){ var name=defines[k]; var i=parseInt(k); this._materialInt2name[i]=name; this._materialName2Int[name]=i; } } /** *注册精灵宏定义。 *@param name 宏定义名称。 *@return */ __proto.addSpriteDefines=function(shaderdefines){ var defines=shaderdefines.defines; for (var k in defines){ var name=defines[k]; var i=parseInt(k); this._spriteInt2name[i]=name; this._spriteName2Int[name]=i; } } /** *通过名称获取宏定义值。 *@param name 名称。 *@return 宏定义值。 */ __proto.getMaterialDefineByName=function(name){ return this._materialName2Int[name]; } /** *注册材质宏定义。 *@param name 宏定义名称。 *@return */ __proto.registerMaterialDefine=function(name){ var value=Math.pow(2,this._materialDefineCounter++); this._materialInt2name[value]=name; this._materialName2Int[name]=value; return value; } /** *注册精灵宏定义。 *@param name 宏定义名称。 *@return */ __proto.registerSpriteDefine=function(name){ var value=Math.pow(2,this._spriteDefineCounter++); this._spriteInt2name[value]=name; this._spriteName2Int[name]=value; return value; } ShaderCompile3D._globalRegDefine=function(name,value){ ShaderCompile3D._globalInt2name[value]=name; } ShaderCompile3D.add=function(nameID,vs,ps,attributeMap,uniformMap){ return laya.d3.shader.ShaderCompile3D._preCompileShader[nameID]=new ShaderCompile3D(nameID,vs,ps,attributeMap,uniformMap,ShaderCompile.includes); } ShaderCompile3D.get=function(name){ return laya.d3.shader.ShaderCompile3D._preCompileShader[Shader3D.nameKey.getID(name)]; } ShaderCompile3D._preCompileShader={}; ShaderCompile3D._globalInt2name=[]; ShaderCompile3D.debugMode=false; ShaderCompile3D.SHADERDEFINE_HIGHPRECISION=0x1; ShaderCompile3D.SHADERDEFINE_FOG=0x4; ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT=0x8; ShaderCompile3D.SHADERDEFINE_POINTLIGHT=0x10; ShaderCompile3D.SHADERDEFINE_SPOTLIGHT=0x20; ShaderCompile3D.SHADERDEFINE_UV0=0x40; ShaderCompile3D.SHADERDEFINE_COLOR=0x80; ShaderCompile3D.SHADERDEFINE_UV1=0x100; ShaderCompile3D.SAHDERDEFINE_DEPTHFOG=0x20000; return ShaderCompile3D; })(ShaderCompile) /** *@private *MeshSprite3DStaticBatchManager 类用于网格精灵静态批处理管理。 */ //class laya.d3.graphics.MeshSprite3DStaticBatchManager extends laya.d3.graphics.StaticBatchManager var MeshSprite3DStaticBatchManager=(function(_super){ /**i *创建一个 MeshSprite3DStaticBatchManager 实例。 */ function MeshSprite3DStaticBatchManager(){ MeshSprite3DStaticBatchManager.__super.call(this); } __class(MeshSprite3DStaticBatchManager,'laya.d3.graphics.MeshSprite3DStaticBatchManager',_super); var __proto=MeshSprite3DStaticBatchManager.prototype; /** *@private */ __proto._getStaticBatch=function(rootOwner,vertexDeclaration,material,number){ var staticBatch; var key; if (rootOwner) key=rootOwner.id.toString()+material.id.toString()+vertexDeclaration.id.toString()+number.toString(); else key=material.id.toString()+vertexDeclaration.id.toString()+number.toString(); if (!this._staticBatches[key]) this._staticBatches[key]=staticBatch=new SubMeshStaticBatch(key,this,rootOwner,vertexDeclaration,material); else staticBatch=this._staticBatches[key]; return staticBatch; } /** *@inheritDoc */ __proto._initStaticBatchs=function(rootOwner){ this._initBatchRenderElements.sort(MeshSprite3DStaticBatchManager._sortPrepareStaticBatch); var lastMaterial; var lastVertexDeclaration; var lastCanMerage=false; var curStaticBatch; var batchNumber=0; for (var i=0,n=this._initBatchRenderElements.length;i < n;i++){ var renderElement=this._initBatchRenderElements[i]; var vb=renderElement.renderObj._getVertexBuffer(0); var originalOwner=renderElement._sprite3D; if ((lastVertexDeclaration===vb.vertexDeclaration)&& (lastMaterial===renderElement._material)){ var oldStaticBatch; if (!lastCanMerage){ var lastRenderObj=this._initBatchRenderElements[i-1]; var lastRenderElement=lastRenderObj.renderObj; var curRenderElement=renderElement.renderObj; if (((lastRenderElement._getVertexBuffer().vertexCount+curRenderElement._getVertexBuffer().vertexCount)> /*laya.d3.graphics.StaticBatch.maxBatchVertexCount*/65535)){ lastCanMerage=false; }else { curStaticBatch=this._getStaticBatch(rootOwner,lastVertexDeclaration,lastMaterial,batchNumber); oldStaticBatch=lastRenderObj._staticBatch; if (oldStaticBatch!==curStaticBatch){ (oldStaticBatch)&& (oldStaticBatch._deleteCombineBatchRenderObj(lastRenderObj)); curStaticBatch._addCombineBatchRenderObj(lastRenderObj); } oldStaticBatch=renderElement._staticBatch; if (oldStaticBatch!==curStaticBatch){ (oldStaticBatch)&& (oldStaticBatch._deleteCombineBatchRenderObj(renderElement)); curStaticBatch._addCombineBatchRenderObj(renderElement); } lastCanMerage=true; } }else { if (!curStaticBatch._addCombineBatchRenderObjTest(renderElement)){ lastCanMerage=false; batchNumber++; }else { oldStaticBatch=renderElement._staticBatch; if (oldStaticBatch!==curStaticBatch){ (oldStaticBatch)&& (oldStaticBatch._deleteCombineBatchRenderObj(renderElement)); curStaticBatch._addCombineBatchRenderObj(renderElement) } } } }else { lastCanMerage=false; batchNumber=0; } lastMaterial=renderElement._material; lastVertexDeclaration=vb.vertexDeclaration; } } MeshSprite3DStaticBatchManager._sortPrepareStaticBatch=function(a,b){ var aRender=a._render,bRender=b._render; var lightMapIndexOffset=aRender.lightmapIndex-bRender.lightmapIndex; if (lightMapIndexOffset===0){ var receiveShadowValue=/*__JS__ */aRender.receiveShadow-bRender.receiveShadow; if (receiveShadowValue===0){ var mainID=a._mainSortID-b._mainSortID; if (mainID===0){ return a.renderObj.triangleCount-b.renderObj.triangleCount; }else { return mainID; } }else { return receiveShadowValue; } }else { return lightMapIndexOffset; } } return MeshSprite3DStaticBatchManager; })(StaticBatchManager) /** *SubMeshStaticBatch 类用于网格静态合并。 */ //class laya.d3.graphics.SubMeshStaticBatch extends laya.d3.graphics.StaticBatch var SubMeshStaticBatch=(function(_super){ function SubMeshStaticBatch(key,manager,rootOwner,vertexDeclaration,material){ /**@private */ this._batchOwnerIndices=null; /**@private */ this._batchOwners=null; /**@private */ this._needFinishCombine=false; /**@private */ this._currentCombineVertexCount=0; /**@private */ this._currentCombineIndexCount=0; /**@private */ this._vertexDeclaration=null; /**@private */ this._vertexBuffer=null; /**@private */ this._indexBuffer=null; SubMeshStaticBatch.__super.call(this,key,manager,rootOwner); this._batchOwnerIndices=[]; this._batchOwners=[]; this._needFinishCombine=false; this._currentCombineVertexCount=0; this._currentCombineIndexCount=0; this._vertexDeclaration=vertexDeclaration; this._material=material; } __class(SubMeshStaticBatch,'laya.d3.graphics.SubMeshStaticBatch',_super); var __proto=SubMeshStaticBatch.prototype; /** *@inheritDoc */ __proto._compareBatchRenderElement=function(a,b){ return (a)._batchIndexStart > (b)._batchIndexStart; } /** *@private */ __proto._addCombineBatchRenderObjTest=function(renderElement){ var vertexCount=0; var subMeshVertexCount=(renderElement.renderObj)._vertexCount; if (subMeshVertexCount > 0) vertexCount=this._currentCombineVertexCount+subMeshVertexCount; else vertexCount=this._currentCombineVertexCount+renderElement.renderObj._getVertexBuffer().vertexCount; if (vertexCount > 65535) return false; return true; } /** *@private */ __proto._addCombineBatchRenderObj=function(renderElement){ var subMesh=renderElement.renderObj; var subMeshVertexCount=subMesh._vertexCount; this._initBatchRenderElements.push(renderElement); renderElement._staticBatch=this; if (subMeshVertexCount > 0){ this._currentCombineIndexCount+=subMesh._indexCount; this._currentCombineVertexCount+=subMeshVertexCount; }else { this._currentCombineIndexCount=this._currentCombineIndexCount+subMesh._getIndexBuffer().indexCount; this._currentCombineVertexCount=this._currentCombineVertexCount+subMesh._getVertexBuffer().vertexCount; } this._needFinishCombine=true; } /** *@private */ __proto._deleteCombineBatchRenderObj=function(renderElement){ var subMesh=renderElement.renderObj; var index=this._initBatchRenderElements.indexOf(renderElement); if (index!==-1){ this._initBatchRenderElements.splice(index,1); renderElement._staticBatch=null; var subMeshVertexCount=subMesh._vertexCount; if (subMeshVertexCount > 0){ this._currentCombineIndexCount=this._currentCombineIndexCount-subMesh._indexCount; this._currentCombineVertexCount=this._currentCombineVertexCount-subMeshVertexCount; }else { this._currentCombineIndexCount=this._currentCombineIndexCount-subMesh._getIndexBuffer().indexCount; this._currentCombineVertexCount=this._currentCombineVertexCount-subMesh._getVertexBuffer().vertexCount; } this._needFinishCombine=true; } } /** *@inheritDoc */ __proto._finishInit=function(){ if (this._needFinishCombine){ var curMerVerCount=0; var curIndexCount=0; if (this._initBatchRenderElements[0]._sprite3D._render.lightmapIndex >=0){ this._vertexDeclaration=this._getVertexDecLightMap(this._vertexDeclaration); }else { if ((this._material instanceof laya.d3.core.material.StandardMaterial )){ if ((this._material).ambientTexture) this._vertexDeclaration=this._getVertexDecLightMap(this._vertexDeclaration); } }; var vertexDatas=new Float32Array(this._vertexDeclaration.vertexStride / 4 *this._currentCombineVertexCount); var indexDatas=new Uint16Array(this._currentCombineIndexCount); if (this._vertexBuffer){ this._vertexBuffer.destroy(); this._indexBuffer.destroy(); } this._vertexBuffer=VertexBuffer3D.create(this._vertexDeclaration,this._currentCombineVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); this._indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._currentCombineIndexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); for (var i=0,n=this._initBatchRenderElements.length;i < n;i++){ var renderElement=this._initBatchRenderElements [i]; var subMesh=renderElement.renderObj; var subVertexDatas=subMesh._getStaticBatchBakedVertexs(this._rootOwner ? this._rootOwner._transform :null,renderElement._sprite3D); var subIndexDatas=subMesh.getIndices(); var isInvert=renderElement._sprite3D.transform._isFrontFaceInvert; var indexOffset=curMerVerCount / (this._vertexDeclaration.vertexStride / 4)-subMesh._vertexStart; var indexStart=curIndexCount; var indexEnd=indexStart+subIndexDatas.length; renderElement._batchIndexStart=indexStart; renderElement._batchIndexEnd=indexEnd; indexDatas.set(subIndexDatas,curIndexCount); var k=0; if (isInvert){ for (k=indexStart;k < indexEnd;k+=3){ indexDatas[k]=indexOffset+indexDatas[k]; var index1=indexDatas[k+1]; var index2=indexDatas[k+2]; indexDatas[k+1]=indexOffset+index2; indexDatas[k+2]=indexOffset+index1; } }else { for (k=indexStart;k < indexEnd;k+=3){ indexDatas[k]=indexOffset+indexDatas[k]; indexDatas[k+1]=indexOffset+indexDatas[k+1]; indexDatas[k+2]=indexOffset+indexDatas[k+2]; } } curIndexCount+=subIndexDatas.length; vertexDatas.set(subVertexDatas,curMerVerCount); curMerVerCount+=subVertexDatas.length; } this._vertexBuffer.setData(vertexDatas); this._indexBuffer.setData(indexDatas); this._needFinishCombine=false; } } /** *@inheritDoc */ __proto._getCombineRenderElementFromPool=function(){ var renderElement=this._combineRenderElementPool[this._combineRenderElementPoolIndex++]; return renderElement || (this._combineRenderElementPool[this._combineRenderElementPoolIndex-1]=new SubMeshRenderElement()); } /** *@inheritDoc */ __proto._getRenderElement=function(renderQueueElements,scene,projectionView){ var lastRenderElement,renderElement; var count=this._batchRenderElements.length; var canMerge=true; for (var i=0;i < count;i++){ renderElement=this._batchRenderElements [i]; var render=renderElement._sprite3D._render; var lastRender; if (i!==0){ lastRenderElement=this._batchRenderElements [i-1]; lastRender=lastRenderElement._sprite3D._render; canMerge=(lastRender.lightmapIndex!==render.lightmapIndex || lastRender.receiveShadow!==render.receiveShadow || lastRenderElement._batchIndexEnd!==renderElement._batchIndexStart); }; var merageElement; if (canMerge){ merageElement=this._getCombineRenderElementFromPool(); merageElement.renderObj=this; merageElement._material=this._material; merageElement._batchIndexStart=(renderElement)._batchIndexStart; merageElement._batchIndexEnd=(renderElement)._batchIndexEnd; var lightMapIndex=render.lightmapIndex; var cacheLightMapIndex=lightMapIndex+1; var lightMapBatchOwnerIndices=this._batchOwnerIndices[cacheLightMapIndex]; (lightMapBatchOwnerIndices)|| (lightMapBatchOwnerIndices=this._batchOwnerIndices[cacheLightMapIndex]=[]); var batchOwnerIndex=lightMapBatchOwnerIndices[renderElement._render.receiveShadow ? 1 :0]; var batchOwner; if (batchOwnerIndex===undefined){ lightMapBatchOwnerIndices[render.receiveShadow ? 1 :0]=this._batchOwners.length; batchOwner=new MeshSprite3D(null,"StaticBatchMeshSprite3D"); batchOwner._scene=scene; batchOwner._transform=this._rootOwner ? this._rootOwner._transform :null; batchOwner._render.lightmapIndex=lightMapIndex; batchOwner._render.receiveShadow=renderElement._render.receiveShadow; this._batchOwners.push(batchOwner); }else { batchOwner=this._batchOwners[batchOwnerIndex]; } batchOwner._render._renderUpdate(projectionView); merageElement._sprite3D=batchOwner; renderQueueElements.push(merageElement); }else { merageElement._batchIndexEnd=(renderElement)._batchIndexEnd; } } } /** *@inheritDoc */ __proto._beforeRender=function(state){ this._vertexBuffer._bind(); this._indexBuffer._bind(); return true; } /** *@inheritDoc */ __proto._render=function(state){ var renderElement=state.renderElement; var batchIndexStart=renderElement._batchIndexStart; var indexCount=renderElement._batchIndexEnd-batchIndexStart; WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,batchIndexStart *2); Stat.drawCall++; Stat.trianglesFaces+=indexCount / 3; } /** *@inheritDoc */ __proto.dispose=function(){ this._batchOwnerIndices=null; this._batchOwners=null; this._vertexDeclaration=null; this._vertexBuffer.destroy(); this._indexBuffer.destroy(); } //..................临时................................. __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); return this._vertexBuffer; } return SubMeshStaticBatch; })(StaticBatch) /** *Sky 类用于创建天空盒。 */ //class laya.d3.resource.models.SkyBox extends laya.d3.resource.models.Sky var SkyBox=(function(_super){ function SkyBox(){ /**@private */ //this._numberVertices=0; /**@private */ //this._numberIndices=0; /**@private 天空立方体纹理。 */ //this._textureCube=null; SkyBox.__super.call(this); SkyBox._nameNumber++; this.loadShaderParams(); this.createResource(); this.alphaBlending=1; this.colorIntensity=1; } __class(SkyBox,'laya.d3.resource.models.SkyBox',_super); var __proto=SkyBox.prototype; /** *@private */ __proto._getShader=function(state){ var shaderDefineValue=state.scene._shaderDefineValue; this._shader=this._shaderCompile.withCompile(shaderDefineValue,0,0); return this._shader; } /** *@private */ __proto.createResource=function(){ this._numberVertices=36; this._numberIndices=36; var indices=new Uint16Array(this._numberIndices); var vertexFloatStride=SkyBox._vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var width=1.0; var height=1.0; var depth=1.0; var halfWidth=width / 2.0; var halfHeight=height / 2.0; var halfDepth=depth / 2.0; var topLeftFront=new Vector3(-halfWidth,halfHeight,halfDepth); var bottomLeftFront=new Vector3(-halfWidth,-halfHeight,halfDepth); var topRightFront=new Vector3(halfWidth,halfHeight,halfDepth); var bottomRightFront=new Vector3(halfWidth,-halfHeight,halfDepth); var topLeftBack=new Vector3(-halfWidth,halfHeight,-halfDepth); var topRightBack=new Vector3(halfWidth,halfHeight,-halfDepth); var bottomLeftBack=new Vector3(-halfWidth,-halfHeight,-halfDepth); var bottomRightBack=new Vector3(halfWidth,-halfHeight,-halfDepth); var vertexCount=0; vertexCount=this._addVertex(vertices,vertexCount,topLeftFront); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftFront); vertexCount=this._addVertex(vertices,vertexCount,topRightFront); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftFront); vertexCount=this._addVertex(vertices,vertexCount,bottomRightFront); vertexCount=this._addVertex(vertices,vertexCount,topRightFront); vertexCount=this._addVertex(vertices,vertexCount,topLeftBack); vertexCount=this._addVertex(vertices,vertexCount,topRightBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftBack); vertexCount=this._addVertex(vertices,vertexCount,topRightBack); vertexCount=this._addVertex(vertices,vertexCount,bottomRightBack); vertexCount=this._addVertex(vertices,vertexCount,topLeftFront); vertexCount=this._addVertex(vertices,vertexCount,topRightBack); vertexCount=this._addVertex(vertices,vertexCount,topLeftBack); vertexCount=this._addVertex(vertices,vertexCount,topLeftFront); vertexCount=this._addVertex(vertices,vertexCount,topRightFront); vertexCount=this._addVertex(vertices,vertexCount,topRightBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftFront); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftBack); vertexCount=this._addVertex(vertices,vertexCount,bottomRightBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftFront); vertexCount=this._addVertex(vertices,vertexCount,bottomRightBack); vertexCount=this._addVertex(vertices,vertexCount,bottomRightFront); vertexCount=this._addVertex(vertices,vertexCount,topLeftFront); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftFront); vertexCount=this._addVertex(vertices,vertexCount,topLeftBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftBack); vertexCount=this._addVertex(vertices,vertexCount,topLeftFront); vertexCount=this._addVertex(vertices,vertexCount,topRightFront); vertexCount=this._addVertex(vertices,vertexCount,bottomRightFront); vertexCount=this._addVertex(vertices,vertexCount,bottomRightBack); vertexCount=this._addVertex(vertices,vertexCount,topRightBack); vertexCount=this._addVertex(vertices,vertexCount,topRightFront); vertexCount=this._addVertex(vertices,vertexCount,bottomRightBack); for (var i=0;i < 36;i++) indices[i]=i; this._vertexBuffer=new VertexBuffer3D(SkyBox._vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); } /** *@private */ __proto._addVertex=function(vertices,index,position){ var posE=position.elements; vertices[index+0]=posE[0]; vertices[index+1]=posE[1]; vertices[index+2]=posE[2]; return index+3; } /** *@private */ __proto.loadShaderParams=function(){ this._sharderNameID=Shader3D.nameKey.getID("SkyBox"); this._shaderCompile=ShaderCompile3D._preCompileShader[this._sharderNameID]; } __proto._render=function(state){ if (this._textureCube && this._textureCube.loaded){ this._vertexBuffer._bind(); this._indexBuffer._bind(); this._shader=this._getShader(state); this._shader.bind(); state.camera.transform.worldMatrix.cloneTo(SkyBox._tempMatrix4x40); SkyBox._tempMatrix4x40.transpose(); Matrix4x4.multiply(state._projectionMatrix,SkyBox._tempMatrix4x40,SkyBox._tempMatrix4x41); state.camera._shaderValues.setValue(/*laya.d3.core.BaseCamera.VPMATRIX_NO_TRANSLATE*/4,SkyBox._tempMatrix4x41.elements); this._shader.uploadCameraUniforms(state.camera._shaderValues.data); this._shaderValue.setValue(1,this._colorIntensity); this._shaderValue.setValue(2,this._alphaBlending); this._shaderValue.setValue(3,this.textureCube); this._shader.uploadAttributes(SkyBox._vertexDeclaration.shaderValues.data,null); this._shader.uploadMaterialUniforms(this._shaderValue.data); WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,36,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.trianglesFaces+=12; Stat.drawCall++; } } /** *@inheritDoc */ __proto.destroy=function(){ _super.prototype.destroy.call(this); (this._textureCube)&& (this._textureCube._removeReference(),this._textureCube=null); } /** *设置天空立方体纹理。 *@param value 天空立方体纹理。 */ /** *获取天空立方体纹理。 *@return 天空立方体纹理。 */ __getset(0,__proto,'textureCube',function(){ return this._textureCube; },function(value){ if (this._textureCube!==value){ (this._textureCube)&& (this._textureCube._removeReference()); this._textureCube=value; (value)&& (value._addReference()); } }); SkyBox._nameNumber=1; __static(SkyBox, ['_tempMatrix4x40',function(){return this._tempMatrix4x40=new Matrix4x4();},'_tempMatrix4x41',function(){return this._tempMatrix4x41=new Matrix4x4();},'_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(12,[new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0)]);} ]); return SkyBox; })(Sky) /** *Sky 类用于创建天空盒。 */ //class laya.d3.resource.models.SkyDome extends laya.d3.resource.models.Sky var SkyDome=(function(_super){ function SkyDome(){ /**@private */ //this._numberVertices=0; /**@private */ //this._numberIndices=0; /**@private 天空立方体纹理。 */ //this._texture=null; this._stacks=16; this._slices=16; this._radius=1; SkyDome.__super.call(this); SkyDome._nameNumber++; this.loadShaderParams(); this.recreateResource(); this.alphaBlending=1; this.colorIntensity=1; } __class(SkyDome,'laya.d3.resource.models.SkyDome',_super); var __proto=SkyDome.prototype; /** *@private */ __proto._getShader=function(state){ var shaderDefineValue=state.scene._shaderDefineValue; this._shader=this._shaderCompile.withCompile(shaderDefineValue,0,0); return this._shader; } /** *@private */ __proto.recreateResource=function(){ this._numberVertices=(this._stacks+1)*(this._slices+1); this._numberIndices=(3 *this._stacks *(this._slices+1))*2; var indices=new Uint16Array(this._numberIndices); var vertexFloatStride=SkyDome._vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var stackAngle=Math.PI / this._stacks; var sliceAngle=(Math.PI *2.0)/ this._slices; var vertexIndex=0; var vertexCount=0; var indexCount=0; for (var stack=0;stack < (this._stacks+1);stack++){ var r=Math.sin(stack *stackAngle); var y=Math.cos(stack *stackAngle); for (var slice=0;slice < (this._slices+1);slice++){ var x=r *Math.sin(slice *sliceAngle); var z=r *Math.cos(slice *sliceAngle); vertices[vertexCount+0]=x *this._radius; vertices[vertexCount+1]=y *this._radius; vertices[vertexCount+2]=z *this._radius; vertices[vertexCount+3]=-(slice / this._slices)+0.75; vertices[vertexCount+4]=stack / this._stacks; vertexCount+=vertexFloatStride; if (stack !=(this._stacks-1)){ indices[indexCount++]=vertexIndex+1; indices[indexCount++]=vertexIndex; indices[indexCount++]=vertexIndex+(this._slices+1); indices[indexCount++]=vertexIndex+(this._slices+1); indices[indexCount++]=vertexIndex; indices[indexCount++]=vertexIndex+(this._slices); vertexIndex++; } } } this._vertexBuffer=new VertexBuffer3D(SkyDome._vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); } /** *@private */ __proto.loadShaderParams=function(){ this._sharderNameID=Shader3D.nameKey.getID("SkyDome"); this._shaderCompile=ShaderCompile3D._preCompileShader[this._sharderNameID]; } __proto._render=function(state){ if (this._texture && this._texture.loaded){ this._vertexBuffer._bind(); this._indexBuffer._bind(); this._shader=this._getShader(state); this._shader.bind(); state.camera.transform.worldMatrix.cloneTo(SkyDome._tempMatrix4x40); SkyDome._tempMatrix4x40.transpose(); Matrix4x4.multiply(state._projectionMatrix,SkyDome._tempMatrix4x40,SkyDome._tempMatrix4x41); state.camera._shaderValues.setValue(/*laya.d3.core.BaseCamera.VPMATRIX_NO_TRANSLATE*/4,SkyDome._tempMatrix4x41.elements); this._shader.uploadCameraUniforms(state.camera._shaderValues.data); this._shaderValue.setValue(1,this._colorIntensity); this._shaderValue.setValue(2,this._alphaBlending); this._shaderValue.setValue(3,this.texture); this._shader.uploadAttributes(SkyDome._vertexDeclaration.shaderValues.data,null); this._shader.uploadMaterialUniforms(this._shaderValue.data); WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._indexBuffer.indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.trianglesFaces+=this._numberIndices / 3; Stat.drawCall++; } } __proto.onEnvDescLoaded=function(envInfoFile){ var envPath=''; var ppos=Math.max(envInfoFile.lastIndexOf('/'),envInfoFile.lastIndexOf('\\')); if (ppos > 0){ envPath=envInfoFile.substr(0,ppos+1); }; var envinfoobj=Laya.loader.getRes(envInfoFile); if (envinfoobj.ev !=undefined && this.__ownerCamera) this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.HDREXPOSURE*/13,Math.pow(2,envinfoobj.ev)); else this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.HDREXPOSURE*/13,Math.pow(2,0.0)); this.texture=Texture2D.load(envPath+envinfoobj.skytex); this.environmentSpecular=DataTexture2D.load(envPath+envinfoobj.prefiltedEnv); var irrdMat=new Float32Array(envinfoobj.IrradianceMat); this.envDiffuseSHRed=irrdMat.slice(0,16); this.envDiffuseSHGreen=irrdMat.slice(16,32); this.envDiffuseSHBlue=irrdMat.slice(32,48); } __proto.loadEnvInfo=function(envInfo){ Laya.loader.load(envInfo,Handler.create(this,this.onEnvDescLoaded,[envInfo])); } /** *@inheritDoc */ __proto.destroy=function(){ _super.prototype.destroy.call(this); (this._texture)&& (this._texture._removeReference(),this._texture=null); } /** *设置天空纹理。 *@param value 天空纹理。 */ /** *获取天空立方体纹理。 *@return 天空立方体纹理。 */ __getset(0,__proto,'texture',function(){ return this._texture; },function(value){ if (this._texture!==value){ (this._texture)&& (this._texture._removeReference()); this._texture=value; (value)&& (value._addReference()); } }); SkyDome._nameNumber=1; __static(SkyDome, ['_tempMatrix4x40',function(){return this._tempMatrix4x40=new Matrix4x4();},'_tempMatrix4x41',function(){return this._tempMatrix4x41=new Matrix4x4();},'_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(20,[new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0),new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2)]);} ]); return SkyDome; })(Sky) /** *@private *ComponentNode 类用于实现组件精灵,该类为抽象类。 */ //class laya.d3.core.ComponentNode extends laya.display.Node var ComponentNode=(function(_super){ function ComponentNode(){ /**@private */ this._componentsMap=null; /**@private */ this._typeComponentsIndices=null; /**@private */ this._components=null; /**@private */ this._scripts=null; ComponentNode.__super.call(this); this._componentsMap=[]; this._typeComponentsIndices=[]; this._components=[]; this._scripts=[]; } __class(ComponentNode,'laya.d3.core.ComponentNode',_super); var __proto=ComponentNode.prototype; /** *添加指定类型组件。 *@param type 组件类型。 *@return 组件。 */ __proto.addComponent=function(type){ var typeComponentIndex; var index=this._componentsMap.indexOf(type); if (index===-1){ typeComponentIndex=[]; this._componentsMap.push(type); this._typeComponentsIndices.push(typeComponentIndex); }else { typeComponentIndex=this._typeComponentsIndices[index]; if (this._components[typeComponentIndex[0]].isSingleton) throw new Error("无法单实例创建"+type+"组件"+","+type+"组件已存在!"); }; var component=ClassUtils.getInstance(type); typeComponentIndex.push(this._components.length); this._components.push(component); if ((component instanceof laya.d3.component.Script )) this._scripts.push(component); component._initialize(this); return component; } /** *@private */ __proto._removeComponent=function(mapIndex,index){ var componentIndices=this._typeComponentsIndices[mapIndex]; var componentIndex=componentIndices[index]; var component=this._components[componentIndex]; this._components.splice(componentIndex,1); if ((component instanceof laya.d3.component.Script )) this._scripts.splice(this._scripts.indexOf(component),1); componentIndices.splice(index,1); (componentIndices.length===0)&& (this._typeComponentsIndices.splice(mapIndex,1),this._componentsMap.splice(mapIndex,1)); for (var i=0,n=this._componentsMap.length;i < n;i++){ componentIndices=this._typeComponentsIndices[i]; for (var j=componentIndices.length-1;j >=0;j--){ var oldComponentIndex=componentIndices[j]; if (oldComponentIndex > componentIndex) componentIndices[j]=--oldComponentIndex; else break ; } } component._destroy(); } /** *通过指定类型和类型索引获得组件。 *@param type 组件类型。 *@param typeIndex 类型索引。 *@return 组件。 */ __proto.getComponentByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return null; return this._components[this._typeComponentsIndices[mapIndex][typeIndex]]; } /** *通过指定类型获得所有组件。 *@param type 组件类型。 *@param components 组件输出队列。 */ __proto.getComponentsByType=function(type,components){ var index=this._componentsMap.indexOf(type); if (index===-1){ components.length=0; return; }; var typeComponents=this._typeComponentsIndices[index]; var count=typeComponents.length; components.length=count; for (var i=0;i < count;i++) components[i]=this._components[typeComponents[i]]; } /** *通过指定索引获得组件。 *@param index 索引。 *@return 组件。 */ __proto.getComponentByIndex=function(index){ return this._components[index]; } /** *通过指定类型和类型索引移除组件。 *@param type 组件类型。 *@param typeIndex 类型索引。 */ __proto.removeComponentByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return; this._removeComponent(mapIndex,typeIndex); } /** *通过指定类型移除所有组件。 *@param type 组件类型。 */ __proto.removeComponentsByType=function(type){ var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return; var componentIndices=this._typeComponentsIndices[mapIndex]; for (var i=0,n=componentIndices.length;i < n;componentIndices.length < n ? n--:i++) this._removeComponent(mapIndex,i); } /** *移除全部组件。 */ __proto.removeAllComponent=function(){ for (var i=0,n=this._componentsMap.length;i < n;this._componentsMap.length < n ? n--:i++) this.removeComponentsByType(this._componentsMap[i]); } /** *@private */ __proto._updateComponents=function(state){ for (var i=0,n=this._components.length;i < n;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._update(state)); } } /** *@private */ __proto._lateUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._lateUpdate(state)); } } /** *@private */ __proto._preRenderUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._preRenderUpdate(state)); } } /** *@private */ __proto._postRenderUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._postRenderUpdate(state)); } } return ComponentNode; })(Node) /** *AnimationClip 类用于动画片段资源。 */ //class laya.d3.animation.AnimationClip extends laya.resource.Resource var AnimationClip=(function(_super){ function AnimationClip(){ /**@private */ this._realTimeCurrentFrameIndexes=null; /**@private */ this._realTimeCurrentTimes=null; /**@private */ this._fullKeyframeIndicesCache=null; /**@private */ this._animationDatasCache=null; /**@private */ this._avatarDatasCache=null; /**@private */ this._skinnedDatasCache=null; /**@private */ this._version=null; /**@private */ this._nodes=null; /**@private */ this._nodesMap=null; /**@private */ this._cachePropertyMap=null; /**@private */ this._nodeToCachePropertyMap=null; /**@private */ this._unCachePropertyMap=null; /**@private */ this._duration=NaN; /**@private */ this._frameRate=0; /**@private */ this._animationEvents=null; /**@private */ this._publicClipDatas=null; /**是否循环。*/ this.islooping=false; AnimationClip.__super.call(this); this._fullKeyframeIndicesCache={}; this._animationDatasCache=[]; this._avatarDatasCache=[]; this._skinnedDatasCache=[]; this._animationEvents=[]; } __class(AnimationClip,'laya.d3.animation.AnimationClip',_super); var __proto=AnimationClip.prototype; /** *获取动画片段时长。 */ __proto.duration=function(){ return this._duration; } /** *@private */ __proto._hermiteInterpolate=function(frame,t,dur,out){ var p0=frame.data; var tan0=frame.outTangent; var nextFrame=frame.next; var p1=nextFrame.data; var tan1=nextFrame.inTangent; var isComputeParams=false; var a=NaN,b=NaN,c=NaN,d=NaN; for (var i=0,n=out.length;i < n;i++){ var t0=tan0[i],t1=tan1[i]; if (/*__JS__ */Number.isFinite(t0)&& Number.isFinite(t1)){ if (!isComputeParams){ var t2=t *t; var t3=t2 *t; a=2.0 *t3-3.0 *t2+1.0; b=t3-2.0 *t2+t; c=t3-t2; d=-2.0 *t3+3.0 *t2; isComputeParams=true; } out[i]=a *p0[i]+b *t0 *dur+c *t1 *dur+d *p1[i]; }else out[i]=p0[i]; } } /** *@private */ __proto._getFullKeyframeIndicesWithCache=function(cacheInterval){ return this._fullKeyframeIndicesCache[cacheInterval]; } /** *@private */ __proto._cacheFullKeyframeIndices=function(cacheInterval,datas){ this._fullKeyframeIndicesCache[cacheInterval]=datas; } /** *@private */ __proto._getAnimationDataWithCache=function(cacheRate,frameIndex){ var cacheDatas=this._animationDatasCache[cacheRate]; if (!cacheDatas) return null; else { return cacheDatas[frameIndex]; } } /** *@private */ __proto._cacheAnimationData=function(cacheRate,frameIndex,datas){ var aniDatasCache=(this._animationDatasCache[cacheRate])|| (this._animationDatasCache[cacheRate]=[]); aniDatasCache[frameIndex]=datas; } /** *@private */ __proto._getAvatarDataWithCache=function(avatar,cacheRate,frameIndex){ var clipCache=this._avatarDatasCache[avatar.id]; if (!clipCache){ return null; }else { var rateCache=clipCache[cacheRate]; if (!rateCache) return null; else { return rateCache[frameIndex]; } } } /** *@private */ __proto._cacheAvatarData=function(avatar,cacheRate,frameIndex,datas){ var clipCache=(this._avatarDatasCache[avatar.id])|| (this._avatarDatasCache[avatar.id]=[]); var rateCache=(clipCache[cacheRate])|| (clipCache[cacheRate]=[]); rateCache[frameIndex]=datas; } /** *@private */ __proto._evaluateAnimationlDatasCacheMode=function(nodeOwners,nodesFrameIndices,animator,clipDatas,propertyMap){ var j=0,m=0; for (var i=0,n=propertyMap ? propertyMap.length :this._nodes.length;i < n;i++){ var nodeIndex=propertyMap ? propertyMap[i] :i; var node=this._nodes[nodeIndex]; var cacheProperty=node._cacheProperty; if (!nodeOwners[nodeIndex]) continue ; var frameIndices=nodesFrameIndices[nodeIndex]; var realFrameIndex=frameIndices[animator.currentFrameIndex]; var outDatas; var lastFrameIndex=0; if (realFrameIndex!==-1){ var frame=node.keyFrames[realFrameIndex]; var nextKeyFrame=frame.next; if (nextKeyFrame){ if (propertyMap && !cacheProperty){ outDatas=clipDatas[nodeIndex]; (outDatas)|| (outDatas=clipDatas[nodeIndex]=new Float32Array(node.keyFrameWidth)); }else { outDatas=new Float32Array(node.keyFrameWidth); clipDatas[i]=outDatas; }; var t=NaN; var d=frame.duration; if (d!==0) t=(animator.currentFrameTime-frame.startTime)/ d; else t=0; this._hermiteInterpolate(frame,t,d,outDatas); }else { if (propertyMap && !cacheProperty){ outDatas=clipDatas[nodeIndex]; (outDatas)|| (outDatas=clipDatas[nodeIndex]=new Float32Array(node.keyFrameWidth)); }else { lastFrameIndex=animator._lastFrameIndex; if (lastFrameIndex!==-1 && frameIndices[lastFrameIndex]===realFrameIndex) continue ; outDatas=new Float32Array(node.keyFrameWidth); clipDatas[i]=outDatas; }; var frameData=frame.data; for (j=0,m=outDatas.length;j < m;j++) outDatas[j]=frameData[j]; } }else { if (propertyMap && !cacheProperty){ outDatas=clipDatas[nodeIndex]; (outDatas)|| (outDatas=clipDatas[nodeIndex]=new Float32Array(node.keyFrameWidth)); }else { lastFrameIndex=animator._lastFrameIndex; if (lastFrameIndex!==-1 && frameIndices[lastFrameIndex]===realFrameIndex) continue ; outDatas=new Float32Array(node.keyFrameWidth); clipDatas[i]=outDatas; }; var firstFrameDatas=node.keyFrames[0].data; for (j=0,m=outDatas.length;j < m;j++) outDatas[j]=firstFrameDatas[j]; } } } /** *@private */ __proto._evaluateAnimationlDatasRealTime=function(nodeOwners,playCurTime,outAnimationDatas,propertyMap){ var i=0,n=0; var nodes=this._nodes; if (!this._realTimeCurrentFrameIndexes){ this._realTimeCurrentFrameIndexes=new Int32Array(nodes.length); for (i=0,n=nodes.length;i < n;i++) this._realTimeCurrentFrameIndexes[i]=-1; this._realTimeCurrentTimes=new Float32Array(nodes.length); } for (i=0,n=propertyMap ? propertyMap.length :this._nodes.length;i < n;i++){ var index=propertyMap ? propertyMap[i] :i; var node=nodes[index]; if (playCurTime < this._realTimeCurrentTimes[index]) this._realTimeCurrentFrameIndexes[index]=-1; this._realTimeCurrentTimes[index]=playCurTime; var nextFrameIndex=this._realTimeCurrentFrameIndexes[index]+1; var keyFrames=node.keyFrames; var keyFramesCount=keyFrames.length; while (nextFrameIndex < keyFramesCount){ if (keyFrames[nextFrameIndex].startTime > playCurTime){ this._realTimeCurrentFrameIndexes[index]=nextFrameIndex-1; break ; } nextFrameIndex++; } (nextFrameIndex===keyFramesCount)&& (this._realTimeCurrentFrameIndexes[index]=keyFramesCount-1); var j=0,m=0; var outDatas=outAnimationDatas[index]; (outDatas)|| (outDatas=outAnimationDatas[index]=new Float32Array(node.keyFrameWidth)); var frame=keyFrames[this._realTimeCurrentFrameIndexes[index]]; if (frame){ var nextFarme=frame.next; if (nextFarme){ var d=frame.duration; var t=NaN; if (d!==0) t=(playCurTime-frame.startTime)/ d; else t=0; this._hermiteInterpolate(frame,t,d,outDatas); }else { var frameData=frame.data; for (j=0,m=outDatas.length;j < m;j++) outDatas[j]=frameData[j]; } }else { var firstFrameDatas=node.keyFrames[0].data; for (j=0,m=outDatas.length;j < m;j++) outDatas[j]=firstFrameDatas[j]; }; var owner=nodeOwners[index]; if (owner){ if (propertyMap) AnimationNode._propertySetFuncs[node.propertyNameID](owner,null,outDatas); else AnimationNode._propertySetFuncs[node.propertyNameID](null,owner,outDatas); } } } /** *@private */ __proto._binarySearchEventIndex=function(time){ var start=0; var end=this._animationEvents.length-1; var mid=0; while (start <=end){ mid=Math.floor((start+end)/ 2); var midValue=this._animationEvents[mid].time; if (midValue==time) return mid; else if (midValue > time) end=mid-1; else start=mid+1; } return start; } /** *添加动画事件。 */ __proto.addEvent=function(event){ var index=this._binarySearchEventIndex(event.time); this._animationEvents.splice(index,0,event); } /** *@inheritDoc */ __proto.onAsynLoaded=function(url,data,params){ var reader=new Byte(data); this._version=reader.readUTFString(); switch (this._version){ case "LAYAANIMATION:01": AnimationClipParser01.parse(this,reader); break ; case "LAYAANIMATION:02": AnimationClipParser02.parse(this,reader); break ; } this.completeCreate(); this._endLoaded(); } /** *@inheritDoc */ __proto.disposeResource=function(){ this._realTimeCurrentFrameIndexes=null; this._realTimeCurrentTimes=null; this._fullKeyframeIndicesCache=null; this._animationDatasCache=null; this._avatarDatasCache=null; this._skinnedDatasCache=null; this._version=null; this._nodes=null; this._nodesMap=null; this._cachePropertyMap=null; this._nodeToCachePropertyMap=null; this._unCachePropertyMap=null; this._publicClipDatas=null; } AnimationClip.load=function(url){ return Laya.loader.create(url,null,null,AnimationClip); } return AnimationClip; })(Resource) /** *Avatar 类用于创建Avatar。 */ //class laya.d3.core.Avatar extends laya.resource.Resource var Avatar=(function(_super){ function Avatar(){ /**@private */ //this._version=null; /**@private */ //this._rootNode=null; Avatar.__super.call(this); } __class(Avatar,'laya.d3.core.Avatar',_super); var __proto=Avatar.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *@private */ __proto._initCloneToAnimator=function(destNode,destAnimator){ destAnimator._avatarNodeMap[destNode.name]=destNode; destAnimator._avatarNodes.push(destNode); for (var i=0,n=destNode.getChildCount();i < n;i++) this._initCloneToAnimator(destNode.getChildByIndex(i),destAnimator); } /** *@private */ __proto._parseNode=function(nodaData,node){ var name=nodaData.props.name; node.name=name; if (node._parent){ var customProps=nodaData.customProps; var transform=node.transform; transform._localRotationEuler=new Float32Array(3); transform.setLocalPosition(new Float32Array(customProps.translate)); transform.setLocalRotation(new Float32Array(customProps.rotation)); transform.setLocalScale(new Float32Array(customProps.scale)); transform._setWorldMatrixAndUpdate(new Float32Array(16)); }; var childrenData=nodaData.child; for (var i=0,n=childrenData.length;i < n;i++){ var childData=childrenData[i]; var childBone=new AnimationNode(); node.addChild(childBone); this._parseNode(childData,childBone); } } /** *@inheritDoc */ __proto.onAsynLoaded=function(url,data,params){ this._rootNode=new AnimationNode(); if (data.version){ this._version=data.version; var rootNode=data.rootNode; (rootNode)&& (this._parseNode(rootNode,this._rootNode)); }else { this._parseNode(data,this._rootNode); } this._endLoaded(); } /** *克隆数据到Avatr。 *@param destObject 克隆源。 */ __proto._cloneDatasToAnimator=function(destAnimator){ var destRoot=this._rootNode.clone(); destRoot.transform._setWorldMatrixIgnoreUpdate(null); var avatarNodes=[]; destAnimator._avatarNodeMap={}; destAnimator._avatarNodes=avatarNodes; this._initCloneToAnimator(destRoot,destAnimator); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destAvatar=destObject; var destRoot=this._rootNode.clone(); destAvatar._rootNode=destRoot; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } Avatar.load=function(url){ return Laya.loader.create(url,null,null,Avatar); } return Avatar; })(Resource) /** *BaseMaterial 类用于创建材质,抽象类,不允许实例。 */ //class laya.d3.core.material.BaseMaterial extends laya.resource.Resource var BaseMaterial=(function(_super){ function BaseMaterial(){ /**@private */ //this._shader=null; /**@private */ //this._shaderCompile=null; /**@private */ //this._shaderDefineValue=0; /**@private */ //this._disablePublicShaderDefine=0; /**@private */ //this._alphaTest=false; /**@private */ //this._shaderValues=null; /**@private */ //this._values=null; /**渲染剔除状态。*/ //this.cull=0; /**透明混合。*/ //this.blend=0; /**源混合参数,在blend为BLEND_ENABLE_ALL时生效。*/ //this.srcBlend=0; /**目标混合参数,在blend为BLEND_ENABLE_ALL时生效。*/ //this.dstBlend=0; /**RGB源混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ //this.srcBlendRGB=0; /**RGB目标混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ //this.dstBlendRGB=0; /**Alpha源混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ //this.srcBlendAlpha=0; /**Alpha目标混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ //this.dstBlendAlpha=0; /**混合常量颜色。*/ //this.blendConstColor=null; /**混合方程。*/ //this.blendEquation=0; /**RGB混合方程。*/ //this.blendEquationRGB=0; /**Alpha混合方程。*/ //this.blendEquationAlpha=0; /**深度测试函数。*/ //this.depthTest=0; /**是否深度写入。*/ //this.depthWrite=false; /**所属渲染队列. */ //this.renderQueue=0; /**@private */ //this._conchMaterial=null; BaseMaterial.__super.call(this); this._shaderDefineValue=0; this._disablePublicShaderDefine=0; this._shaderValues=new ValusArray(); this._values=[]; this.renderQueue=/*CLASS CONST:laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this._alphaTest=false; this.cull=2; this.blend=0; this.srcBlend=1; this.dstBlend=0; this.srcBlendRGB=1; this.dstBlendRGB=0; this.srcBlendAlpha=1; this.dstBlendAlpha=0; this.blendConstColor=new Vector4(1,1,1,1); this.blendEquation=0; this.blendEquationRGB=0; this.blendEquationAlpha=0; this.depthTest=0x0201; this.depthWrite=true; } __class(BaseMaterial,'laya.d3.core.material.BaseMaterial',_super); var __proto=BaseMaterial.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *增加Shader宏定义。 *@param value 宏定义。 */ __proto._addShaderDefine=function(value){ this._shaderDefineValue |=value; } /** *移除Shader宏定义。 *@param value 宏定义。 */ __proto._removeShaderDefine=function(value){ this._shaderDefineValue &=~value; } /** *增加禁用宏定义。 *@param value 宏定义。 */ __proto._addDisablePublicShaderDefine=function(value){ this._disablePublicShaderDefine |=value; } /** *移除禁用宏定义。 *@param value 宏定义。 */ __proto._removeDisablePublicShaderDefine=function(value){ this._disablePublicShaderDefine &=~value; } /** *设置Buffer。 *@param shaderIndex shader索引。 *@param buffer buffer数据。 */ __proto._setBuffer=function(shaderIndex,buffer){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,buffer); this._values[shaderIndex]=buffer; } /** *获取Buffer。 *@param shaderIndex shader索引。 *@return */ __proto._getBuffer=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置矩阵。 *@param shaderIndex shader索引。 *@param matrix4x4 矩阵。 */ __proto._setMatrix4x4=function(shaderIndex,matrix4x4){ this._shaderValues.setValue(shaderIndex,matrix4x4 ? matrix4x4.elements :null); this._values[shaderIndex]=matrix4x4; } /** *获取矩阵。 *@param shaderIndex shader索引。 *@return 矩阵。 */ __proto._getMatrix4x4=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置整型。 *@param shaderIndex shader索引。 *@param i 整形。 */ __proto._setInt=function(shaderIndex,i){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,i); this._values[shaderIndex]=i; } /** *获取整形。 *@param shaderIndex shader索引。 *@return 整形。 */ __proto._getInt=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置浮点。 *@param shaderIndex shader索引。 *@param i 浮点。 */ __proto._setNumber=function(shaderIndex,number){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,number); this._values[shaderIndex]=number; } /** *获取浮点。 *@param shaderIndex shader索引。 *@return 浮点。 */ __proto._getNumber=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置布尔。 *@param shaderIndex shader索引。 *@param b 布尔。 */ __proto._setBool=function(shaderIndex,b){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,b); this._values[shaderIndex]=b; } /** *获取布尔。 *@param shaderIndex shader索引。 *@return 布尔。 */ __proto._getBool=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置二维向量。 *@param shaderIndex shader索引。 *@param vector2 二维向量。 */ __proto._setVector2=function(shaderIndex,vector2){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,vector2 ? vector2.elements :null); this._values[shaderIndex]=vector2; } /** *获取二维向量。 *@param shaderIndex shader索引。 *@return 二维向量。 */ __proto._getVector2=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置颜色。 *@param shaderIndex shader索引。 *@param color 颜色向量。 */ __proto._setColor=function(shaderIndex,color){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,color ? color.elements :null); this._values[shaderIndex]=color; } /** *获取颜色。 *@param shaderIndex shader索引。 *@return 颜色向量。 */ __proto._getColor=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置纹理。 *@param shaderIndex shader索引。 *@param texture 纹理。 */ __proto._setTexture=function(shaderIndex,texture){ var lastValue=this._values[shaderIndex]; this._values[shaderIndex]=texture; this._shaderValues.setValue(shaderIndex,texture); if (this.referenceCount > 0){ (lastValue)&& (lastValue._removeReference()); (texture)&& (texture._addReference()); } } /** *获取纹理。 *@param shaderIndex shader索引。 *@return 纹理。 */ __proto._getTexture=function(shaderIndex){ return this._values[shaderIndex]; } /** *上传材质。 *@param state 相关渲染状态。 *@param bufferUsageShader Buffer相关绑定。 *@param shader 着色器。 *@return 是否成功。 */ __proto._upload=function(){ this._shader.uploadMaterialUniforms(this._shaderValues.data); } /** *@private */ __proto._getShader=function(sceneDefineValue,vertexDefineValue,spriteDefineValue){ var publicDefineValue=(sceneDefineValue | vertexDefineValue)& (~this._disablePublicShaderDefine); this._shader=this._shaderCompile.withCompile(publicDefineValue,spriteDefineValue,this._shaderDefineValue); return this._shader; } /** *设置渲染相关状态。 */ __proto._setRenderStateBlendDepth=function(){ var gl=WebGL.mainContext; WebGLContext.setDepthMask(gl,this.depthWrite); if (this.depthTest===0) WebGLContext.setDepthTest(gl,false); else { WebGLContext.setDepthTest(gl,true); WebGLContext.setDepthFunc(gl,this.depthTest); } switch (this.blend){ case 0: WebGLContext.setBlend(gl,false); break ; case 1: WebGLContext.setBlend(gl,true); WebGLContext.setBlendFunc(gl,this.srcBlend,this.dstBlend); break ; case 2: WebGLContext.setBlend(gl,true); break ; } } /** *设置渲染相关状态。 */ __proto._setRenderStateFrontFace=function(isTarget,transform){ var gl=WebGL.mainContext; var forntFace=0; switch (this.cull){ case 0: WebGLContext.setCullFace(gl,false); break ; case 1: WebGLContext.setCullFace(gl,true); if (isTarget){ if (transform && transform._isFrontFaceInvert) forntFace=/*laya.webgl.WebGLContext.CCW*/0x0901; else forntFace=/*laya.webgl.WebGLContext.CW*/0x0900; }else { if (transform && transform._isFrontFaceInvert) forntFace=/*laya.webgl.WebGLContext.CW*/0x0900; else forntFace=/*laya.webgl.WebGLContext.CCW*/0x0901; } WebGLContext.setFrontFace(gl,forntFace); break ; case 2: WebGLContext.setCullFace(gl,true); if (isTarget){ if (transform && transform._isFrontFaceInvert) forntFace=/*laya.webgl.WebGLContext.CW*/0x0900; else forntFace=/*laya.webgl.WebGLContext.CCW*/0x0901; }else { if (transform && transform._isFrontFaceInvert) forntFace=/*laya.webgl.WebGLContext.CCW*/0x0901; else forntFace=/*laya.webgl.WebGLContext.CW*/0x0900; } WebGLContext.setFrontFace(gl,forntFace); break ; } } /** *@inheritDoc */ __proto.onAsynLoaded=function(url,data,params){ var jsonData=data[0]; var textureMap=data[1]; switch (jsonData.version){ case "LAYAMATERIAL:01":; var i=0,n=0; var props=jsonData.props; for (var key in props){ switch (key){ case "vectors":; var vectors=props[key]; for (i=0,n=vectors.length;i < n;i++){ var vector=vectors[i]; var vectorValue=vector.value; switch (vectorValue.length){ case 2: this[vector.name]=new Vector2(vectorValue[0],vectorValue[1]); break ; case 3: this[vector.name]=new Vector3(vectorValue[0],vectorValue[1],vectorValue[2]); break ; case 4: this[vector.name]=new Vector4(vectorValue[0],vectorValue[1],vectorValue[2],vectorValue[3]); break ; default : throw new Error("BaseMaterial:unkonwn color length."); } } break ; case "textures":; var textures=props[key]; for (i=0,n=textures.length;i < n;i++){ var texture=textures[i]; var path=texture.path; (path)&& (this[texture.name]=Loader.getRes(textureMap[path])); } break ; case "defines":; var defineNames=props[key]; for (i=0,n=defineNames.length;i < n;i++){ var define=this._shaderCompile.getMaterialDefineByName(defineNames[i]); this._addShaderDefine(define); } break ; case "cull": case "blend": case "srcBlend": case "dstBlend": case "depthWrite": this[key]=props[key]; break ; case "renderQueue":; var queue=props[key]; switch (queue){ case 1: this.renderQueue=2000; break ; case 2: this.renderQueue=3000; break ; default : } break ; default : this[key]=props[key]; } } break ; case "LAYAMATERIAL:02": props=jsonData.props; for (key in props){ switch (key){ case "vectors": vectors=props[key]; for (i=0,n=vectors.length;i < n;i++){ vector=vectors[i]; vectorValue=vector.value; switch (vectorValue.length){ case 2: this[vector.name]=new Vector2(vectorValue[0],vectorValue[1]); break ; case 3: this[vector.name]=new Vector3(vectorValue[0],vectorValue[1],vectorValue[2]); break ; case 4: this[vector.name]=new Vector4(vectorValue[0],vectorValue[1],vectorValue[2],vectorValue[3]); break ; default : throw new Error("BaseMaterial:unkonwn color length."); } } break ; case "textures": textures=props[key]; for (i=0,n=textures.length;i < n;i++){ texture=textures[i]; path=texture.path; (path)&& (this[texture.name]=Loader.getRes(textureMap[path])); } break ; case "defines": defineNames=props[key]; for (i=0,n=defineNames.length;i < n;i++){ define=this._shaderCompile.getMaterialDefineByName(defineNames[i]); this._addShaderDefine(define); } break ; default : this[key]=props[key]; } } break ; default : throw new Error("BaseMaterial:unkonwn version."); } this._endLoaded(); } /** *@inheritDoc */ __proto._addReference=function(){ _super.prototype._addReference.call(this); var valueCount=this._values.length; for (var i=0,n=valueCount;i < n;i++){ var value=this._values[i]; if (value && (value instanceof laya.d3.resource.BaseTexture )) (value)._addReference(); } } /** *@inheritDoc */ __proto._removeReference=function(){ _super.prototype._removeReference.call(this); var valueCount=this._values.length; for (var i=0,n=valueCount;i < n;i++){ var value=this._values[i]; if (value && (value instanceof laya.d3.resource.BaseTexture )) (value)._removeReference(); } } /** *@inheritDoc */ __proto.disposeResource=function(){ this.blendConstColor=null; this._shader=null; this._shaderValues=null; var valueCount=this._values.length; for (var i=0,n=valueCount;i < n;i++){ var value=this._values[i]; if (value && (value instanceof laya.d3.resource.BaseTexture )) (value)._removeReference(); } this._values=null; } /** *设置使用Shader名字。 *@param name 名称。 */ __proto.setShaderName=function(name){ var nameID=Shader3D.nameKey.getID(name); if (nameID===-1) throw new Error("BaseMaterial: unknown shader name."); this._shaderCompile=ShaderCompile3D._preCompileShader[nameID]; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destBaseMaterial=destObject; destBaseMaterial.name=this.name; destBaseMaterial.cull=this.cull; destBaseMaterial.blend=this.blend; destBaseMaterial.srcBlend=this.srcBlend; destBaseMaterial.dstBlend=this.dstBlend; destBaseMaterial.srcBlendRGB=this.srcBlendRGB; destBaseMaterial.dstBlendRGB=this.dstBlendRGB; destBaseMaterial.srcBlendAlpha=this.srcBlendAlpha; destBaseMaterial.dstBlendAlpha=this.dstBlendAlpha; this.blendConstColor.cloneTo(destBaseMaterial.blendConstColor); destBaseMaterial.blendEquation=this.blendEquation; destBaseMaterial.blendEquationRGB=this.blendEquationRGB; destBaseMaterial.blendEquationAlpha=this.blendEquationAlpha; destBaseMaterial.depthTest=this.depthTest; destBaseMaterial.depthWrite=this.depthWrite; destBaseMaterial.renderQueue=this.renderQueue; destBaseMaterial._shader=this._shader; destBaseMaterial._disablePublicShaderDefine=this._disablePublicShaderDefine; destBaseMaterial._shaderDefineValue=this._shaderDefineValue; var i=0,n=0; var destShaderValues=destBaseMaterial._shaderValues; destBaseMaterial._shaderValues.data.length=this._shaderValues.data.length; var valueCount=this._values.length; var destValues=destBaseMaterial._values; destValues.length=valueCount; for (i=0,n=valueCount;i < n;i++){ var value=this._values[i]; if (value){ if ((typeof value=='number')){ destValues[i]=value; destShaderValues.data[i]=value; }else if (((typeof value=='number')&& Math.floor(value)==value)){ destValues[i]=value; destShaderValues.data[i]=value; }else if ((typeof value=='boolean')){ destValues[i]=value; destShaderValues.data[i]=value; }else if ((value instanceof laya.d3.math.Vector2 )){ var v2=(destValues[i])|| (destValues[i]=new Vector2()); (value).cloneTo(v2); destShaderValues.data[i]=v2.elements; }else if ((value instanceof laya.d3.math.Vector3 )){ var v3=(destValues[i])|| (destValues[i]=new Vector3()); (value).cloneTo(v3); destShaderValues.data[i]=v3.elements; }else if ((value instanceof laya.d3.math.Vector4 )){ var v4=(destValues[i])|| (destValues[i]=new Vector4()); (value).cloneTo(v4); destShaderValues.data[i]=v4.elements; }else if ((value instanceof laya.d3.math.Matrix4x4 )){ var mat=(destValues[i])|| (destValues[i]=new Matrix4x4()); (value).cloneTo(mat); destShaderValues.data[i]=mat.elements; }else if ((value instanceof laya.d3.resource.BaseTexture )){ destValues[i]=value; destShaderValues.data[i]=value; } } } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destBaseMaterial=/*__JS__ */new this.constructor(); this.cloneTo(destBaseMaterial); return destBaseMaterial; } /** *设置透明测试模式裁剪值。 *@param value 透明测试模式裁剪值。 */ /** *获取透明测试模式裁剪值。 *@return 透明测试模式裁剪值。 */ __getset(0,__proto,'alphaTestValue',function(){ return this._getNumber(0); },function(value){ this._setNumber(0,value); }); /** *设置是否透明裁剪。 *@param value 是否透明裁剪。 */ /** *获取是否透明裁剪。 *@return 是否透明裁剪。 */ __getset(0,__proto,'alphaTest',function(){ return this._alphaTest; },function(value){ this._alphaTest=value; if (value) this._addShaderDefine(laya.d3.core.material.BaseMaterial.SHADERDEFINE_ALPHATEST); else this._removeShaderDefine(laya.d3.core.material.BaseMaterial.SHADERDEFINE_ALPHATEST); }); BaseMaterial.__init__=function(){ BaseMaterial.SHADERDEFINE_ALPHATEST=BaseMaterial.shaderDefines.registerDefine("ALPHATEST"); } BaseMaterial.RENDERQUEUE_OPAQUE=2000; BaseMaterial.RENDERQUEUE_ALPHATEST=2450; BaseMaterial.RENDERQUEUE_TRANSPARENT=3000; BaseMaterial.CULL_NONE=0; BaseMaterial.CULL_FRONT=1; BaseMaterial.CULL_BACK=2; BaseMaterial.BLEND_DISABLE=0; BaseMaterial.BLEND_ENABLE_ALL=1; BaseMaterial.BLEND_ENABLE_SEPERATE=2; BaseMaterial.BLENDPARAM_ZERO=0; BaseMaterial.BLENDPARAM_ONE=1; BaseMaterial.BLENDPARAM_SRC_COLOR=0x0300; BaseMaterial.BLENDPARAM_ONE_MINUS_SRC_COLOR=0x0301; BaseMaterial.BLENDPARAM_DST_COLOR=0x0306; BaseMaterial.BLENDPARAM_ONE_MINUS_DST_COLOR=0x0307; BaseMaterial.BLENDPARAM_SRC_ALPHA=0x0302; BaseMaterial.BLENDPARAM_ONE_MINUS_SRC_ALPHA=0x0303; BaseMaterial.BLENDPARAM_DST_ALPHA=0x0304; BaseMaterial.BLENDPARAM_ONE_MINUS_DST_ALPHA=0x0305; BaseMaterial.BLENDPARAM_SRC_ALPHA_SATURATE=0x0308; BaseMaterial.BLENDEQUATION_ADD=0; BaseMaterial.BLENDEQUATION_SUBTRACT=1; BaseMaterial.BLENDEQUATION_REVERSE_SUBTRACT=2; BaseMaterial.DEPTHTEST_OFF=0; BaseMaterial.DEPTHTEST_NEVER=0x0200; BaseMaterial.DEPTHTEST_LESS=0x0201; BaseMaterial.DEPTHTEST_EQUAL=0x0202; BaseMaterial.DEPTHTEST_LEQUAL=0x0203; BaseMaterial.DEPTHTEST_GREATER=0x0204; BaseMaterial.DEPTHTEST_NOTEQUAL=0x0205; BaseMaterial.DEPTHTEST_GEQUAL=0x0206; BaseMaterial.DEPTHTEST_ALWAYS=0x0207; BaseMaterial.SHADERDEFINE_ALPHATEST=0x1; BaseMaterial.ALPHATESTVALUE=0; __static(BaseMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1();} ]); return BaseMaterial; })(Resource) /** *BaseTexture 纹理的父类,抽象类,不允许实例。 */ //class laya.d3.resource.BaseTexture extends laya.resource.Resource var BaseTexture=(function(_super){ function BaseTexture(){ /**@private */ this._type=0; /**@private */ this._width=0; /**@private */ this._height=0; /**@private */ this._size=null; /**@private */ this._repeat=false; /**@private */ this._mipmap=false; /**@private */ this._minFifter=0; /**@private */ this._magFifter=0; /**@private */ this._format=0; /**@private */ this._source=null; /**@private */ this._conchTexture=null; /**@private */ this._wrapModeU=0; /**@private */ this._wrapModeV=0; BaseTexture.__super.call(this); this._repeat=true; this.mipmap=true; this.minFifter=-1; this.magFifter=-1; } __class(BaseTexture,'laya.d3.resource.BaseTexture',_super); var __proto=BaseTexture.prototype; /** *获取宽度。 */ __getset(0,__proto,'width',function(){ return this._width; }); /** *是否使用重复模式纹理寻址 */ /** *是否使用重复模式纹理寻址 */ __getset(0,__proto,'repeat',function(){ return this._repeat; },function(value){ if (this._repeat!==value){ this._repeat=value; if (this._source){ var gl=WebGL.mainContext; WebGLContext.bindTexture(gl,this._type,this._source); var isPot=Arith.isPOT(this._width,this._height); if (isPot && this._repeat){ gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.REPEAT*/0x2901); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.REPEAT*/0x2901); }else { gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } } } }); /** *获取高度。 */ __getset(0,__proto,'height',function(){ return this._height; }); /** *放大过滤器 */ /** *放大过滤器 */ __getset(0,__proto,'magFifter',function(){ return this._magFifter; },function(value){ this._magFifter=value; if (value !=this._magFifter){ this._conchTexture && this._conchTexture.setMaxFifter(value); } }); /** *获取纹理纵向循环模式。 */ __getset(0,__proto,'wrapModeV',function(){ return this._wrapModeV; }); /** *获取尺寸。 */ __getset(0,__proto,'size',function(){ return this._size; }); /** *获取纹理横向循环模式。 */ __getset(0,__proto,'wrapModeU',function(){ return this._wrapModeU; }); /** *是否使用mipLevel */ /** *是否使用mipLevel */ __getset(0,__proto,'mipmap',function(){ return this._mipmap; },function(value){ this._mipmap=value; if (this._mipmap !=value){ this._conchTexture && this._conchTexture.setMipMap(value); } }); /** *缩小过滤器 */ /** *缩小过滤器 */ __getset(0,__proto,'minFifter',function(){ return this._minFifter; },function(value){ this._minFifter=value; if (this._minFifter !=value){ this._conchTexture && this._conchTexture.setMinFifter(value); } }); /** *纹理格式 */ __getset(0,__proto,'format',function(){ return this._format; }); /** *获取纹理资源。 */ __getset(0,__proto,'source',function(){ this.activeResource(); return this._source; }); /** *获取纹理资源。 */ __getset(0,__proto,'defaulteTexture',function(){ return SolidColorTexture2D.grayTexture; }); BaseTexture.WARPMODE_REPEAT=0; BaseTexture.WARPMODE_CLAMP=1; return BaseTexture; })(Resource) /** *BaseMesh 类用于创建网格,抽象类,不允许实例。 */ //class laya.d3.resource.models.BaseMesh extends laya.resource.Resource var BaseMesh=(function(_super){ function BaseMesh(){ /**@private */ this._subMeshCount=0; /**@private */ this._boundingBox=null; /**@private */ this._boundingSphere=null; /**@private */ this._boundingBoxCorners=null; /**@private 只读,不允许修改。*/ this._positions=null; BaseMesh.__super.call(this); this._boundingBoxCorners=__newvec(8,null); } __class(BaseMesh,'laya.d3.resource.models.BaseMesh',_super); var __proto=BaseMesh.prototype; /** *获取网格顶点,请重载此方法。 *@return 网格顶点。 */ __proto._getPositions=function(){ throw new Error("未Override,请重载该属性!"); } /** *@private */ __proto._generateBoundingObject=function(){ this._boundingSphere=new BoundSphere(new Vector3(),0); BoundSphere.createfromPoints(this._positions,this._boundingSphere); this._boundingBox=new BoundBox(new Vector3(),new Vector3()); BoundBox.createfromPoints(this._positions,this._boundingBox); this._boundingBox.getCorners(this._boundingBoxCorners); } /** *获取渲染单元数量,请重载此方法。 *@return 渲染单元数量。 */ __proto.getRenderElementsCount=function(){ throw new Error("未Override,请重载该属性!"); } /** *获取渲染单元,请重载此方法。 *@param index 索引。 *@return 渲染单元。 */ __proto.getRenderElement=function(index){ throw new Error("未Override,请重载该属性!"); } /** *获取SubMesh的个数。 *@return SubMesh的个数。 */ __getset(0,__proto,'subMeshCount',function(){ return this._subMeshCount; }); /** *获取AABB包围盒,禁止修改其数据。 *@return AABB包围盒。 */ __getset(0,__proto,'boundingBox',function(){ return this._boundingBox; }); /** *获取包围球顶点,禁止修改其数据。 *@return 包围球。 */ __getset(0,__proto,'boundingBoxCorners',function(){ return this._boundingBoxCorners; }); /** *获取包围球,禁止修改其数据。 *@return 包围球。 */ __getset(0,__proto,'boundingSphere',function(){ return this._boundingSphere; }); return BaseMesh; })(Resource) /** *TerrainHeightData 类用于描述地形高度信息。 */ //class laya.d3.terrain.TerrainHeightData extends laya.resource.Resource var TerrainHeightData=(function(_super){ function TerrainHeightData(){ this._terrainHeightData=null; this._width=0; this._height=0; this._bitType=0; this._value=NaN; TerrainHeightData.__super.call(this); } __class(TerrainHeightData,'laya.d3.terrain.TerrainHeightData',_super); var __proto=TerrainHeightData.prototype; /** *异步回调 */ __proto.onAsynLoaded=function(url,data,params){ this._width=params[0]; this._height=params[1]; this._bitType=params[2]; this._value=params[3]; var buffer; var ratio=NaN; if (this._bitType==8){ buffer=new Uint8Array(data); ratio=1.0 / 255.0; } else if (this._bitType==16){ buffer=new Int16Array(data); ratio=1.0 / 32766.0; } this._terrainHeightData=new Float32Array(this._height *this._width); for (var i=0,n=this._height *this._width;i < n;i++){ this._terrainHeightData[i]=(buffer[i] *ratio *this._value)/2; } this._endLoaded(); } TerrainHeightData.load=function(url,widht,height,bitType,value){ return Laya.loader.create(url,null,null,TerrainHeightData,[widht,height,bitType,value],1,false); } return TerrainHeightData; })(Resource) /** *TerrainRes 类用于描述地形信息。 */ //class laya.d3.terrain.TerrainRes extends laya.resource.Resource var TerrainRes=(function(_super){ function TerrainRes(){ this._version=NaN; this._cameraCoordinateInverse=false; this._gridSize=NaN; this._chunkNumX=0; this._chunkNumZ=0; this._heightDataX=0; this._heightDataZ=0; this._heightDataBitType=0; this._heightDataValue=NaN; this._heightDataUrl=null; this._detailTextureInfos=null; this._chunkInfos=null; this._heightData=null; this._materialInfo=null; this._alphaMaps=null; this._normalMaps=null; TerrainRes.__super.call(this); } __class(TerrainRes,'laya.d3.terrain.TerrainRes',_super); var __proto=TerrainRes.prototype; __proto.parseData=function(data){ var json=data[0]; var resouMap=data[1]; this._version=json.version; if (this._version==1.0){ this._cameraCoordinateInverse=json.cameraCoordinateInverse; this._gridSize=json.gridSize; this._chunkNumX=json.chunkNumX; this._chunkNumZ=json.chunkNumZ; var heightData=json.heightData; this._heightDataX=heightData.numX; this._heightDataZ=heightData.numZ; this._heightDataBitType=heightData.bitType; this._heightDataValue=heightData.value; this._heightDataUrl=resouMap[heightData.url]; this._materialInfo=new MaterialInfo(); if (json.material){ var ambient=json.material.ambient; var diffuse=json.material.diffuse; var specular=json.material.specular; this._materialInfo.ambientColor=new Vector3(ambient[0],ambient[1],ambient[2]); this._materialInfo.diffuseColor=new Vector3(diffuse[0],diffuse[1],diffuse[2]); this._materialInfo.specularColor=new Vector4(specular[0],specular[1],specular[2],specular[3]); }; var detailTextures=json.detailTexture; this._detailTextureInfos=__newvec(detailTextures.length); for (var i=0;i < detailTextures.length;i++){ var detail=detailTextures[i]; var info=new DetailTextureInfo(); info.diffuseTexture=resouMap[detail.diffuse]; info.normalTexture=detail.normal ? resouMap[detail.normal] :null; if (detail.scale){ info.scale=new Vector2(detail.scale[0],detail.scale[1]); }else { info.scale=new Vector2(1,1); } if (detail.offset){ info.offset=new Vector2(detail.offset[0],detail.offset[1]); }else { info.offset=new Vector2(0,0); } this._detailTextureInfos[i]=info; }; var alphaMaps=json.alphaMap; this._alphaMaps=__newvec(alphaMaps.length); for (i=0;i < this._alphaMaps.length;i++){ this._alphaMaps[i]=json.alphaMap[i]; }; var normalMaps=json.normalMap; this._normalMaps=__newvec(normalMaps.length); for (i=0;i < this._normalMaps.length;i++){ this._normalMaps[i]=json.normalMap[i]; }; var jchunks=json.chunkInfo; if (this._chunkNumX *this._chunkNumZ !=jchunks.length){ alert("terrain data error"); return false; } this._chunkInfos=__newvec(jchunks.length); for (i=0;i < jchunks.length;i++){ var jchunk=jchunks[i]; var chunkinfo=new ChunkInfo(); var nAlphaMapNum=jchunk.alphaMap.length; var nDetailIDNum=jchunk.detailID.length; if (nAlphaMapNum !=nDetailIDNum){ alert("terrain chunk data error"); return false; } chunkinfo.alphaMap=__newvec(nAlphaMapNum); chunkinfo.detailID=__newvec(nDetailIDNum); chunkinfo.normalMap=resouMap[this._normalMaps[jchunk.normalMap]]; for (var j=0;j < nAlphaMapNum;j++){ chunkinfo.alphaMap[j]=resouMap[this._alphaMaps[jchunk.alphaMap[j]]]; var jid=jchunk.detailID[j]; var nIDNum=jid.length; chunkinfo.detailID[j]=new Uint8Array(nIDNum); for (var k=0;k < nIDNum;k++){ chunkinfo.detailID[j][k]=jid[k]; } } this._chunkInfos[i]=chunkinfo; } this._heightData=Loader.getRes(this._heightDataUrl); this.onLoadTerrainComplete(this._heightData); } return true; } __proto.onLoadTerrainComplete=function(heightData){ this._endLoaded(); } /** *异步回调 */ __proto.onAsynLoaded=function(url,data,params){ this.parseData(data); } TerrainRes.load=function(url){ return Laya.loader.create(url,null,null,TerrainRes,null,1,false); } return TerrainRes; })(Resource) /** *KeyframeAnimation 类用于帧动画组件的父类。 */ //class laya.d3.component.animation.KeyframeAnimations extends laya.d3.component.Component3D var KeyframeAnimations=(function(_super){ function KeyframeAnimations(){ /**动画播放器。*/ this._player=null; /**@private */ this._templet=null; KeyframeAnimations.__super.call(this); this._player=new AnimationPlayer(); } __class(KeyframeAnimations,'laya.d3.component.animation.KeyframeAnimations',_super); var __proto=KeyframeAnimations.prototype; /** *@private */ __proto._updateAnimtionPlayer=function(){ this._player._update(Laya.timer.delta); } /** *@private */ __proto._addUpdatePlayerToTimer=function(){ Laya.timer.frameLoop(1,this,this._updateAnimtionPlayer); } /** *@private */ __proto._removeUpdatePlayerToTimer=function(){ Laya.timer.clear(this,this._updateAnimtionPlayer); } /** *@private */ __proto._onOwnerActiveHierarchyChanged=function(active){ if ((this._owner).displayedInStage){ if (active) this._addUpdatePlayerToTimer(); else this._removeUpdatePlayerToTimer(); } } /** *@private *载入组件时执行 */ __proto._load=function(owner){ ((owner).activeInHierarchy)&& (this._addUpdatePlayerToTimer()); owner.on(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onOwnerActiveHierarchyChanged); } /** *@private *卸载组件时执行 */ __proto._unload=function(owner){ _super.prototype._unload.call(this,owner); ((owner).activeInHierarchy)&& (this._removeUpdatePlayerToTimer()); owner.off(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onOwnerActiveHierarchyChanged); this._player._destroy(); this._player=null; this._templet=null; } /** *设置url地址。 *@param value 地址。 */ __getset(0,__proto,'url',null,function(value){ console.log("Warning: discard property,please use templet property instead."); var templet=Laya.loader.create(value,null,null,AnimationTemplet); if (this._templet!==templet){ if (this._player.state!==/*laya.ani.AnimationState.stopped*/0) this._player.stop(true); this._templet=templet; this._player.templet=templet; this.event(/*laya.events.Event.ANIMATION_CHANGED*/"animationchanged",this); } }); /** *获取动画播放器。 *@return 动画播放器。 */ __getset(0,__proto,'player',function(){ return this._player; }); /** *设置动画模板。 *@param value 设置动画模板。 */ /** *获取动画模板。 *@return value 动画模板。 */ __getset(0,__proto,'templet',function(){ return this._templet; },function(value){ if (this._templet!==value){ if (this._player.state!==/*laya.ani.AnimationState.stopped*/0) this._player.stop(true); this._templet=value; this._player.templet=value; this.event(/*laya.events.Event.ANIMATION_CHANGED*/"animationchanged",this); } }); /** *获取播放器帧数。 *@return 播放器帧数。 */ __getset(0,__proto,'currentFrameIndex',function(){ return this._player.currentKeyframeIndex; }); /** *获取播放器的动画索引。 *@return 动画索引。 */ __getset(0,__proto,'currentAnimationClipIndex',function(){ return this._player.currentAnimationClipIndex; }); /** *获取播放器当前动画的节点数量。 *@return 节点数量。 */ __getset(0,__proto,'nodeCount',function(){ return this._templet.getNodeCount(this._player.currentAnimationClipIndex); }); return KeyframeAnimations; })(Component3D) /** *Animations 类用于创建动画组件。 */ //class laya.d3.component.Animator extends laya.d3.component.Component3D var Animator=(function(_super){ function Animator(){ /**@private */ //this._updateTransformPropertyLoopCount=0; /**@private */ //this._cacheFrameRateInterval=NaN; /**@private */ //this._cacheFrameRate=0; /**@private */ //this._cachePlayRate=NaN; /**@private */ //this._currentPlayClip=null; /**@private */ //this._currentPlayClipIndex=0; /**@private */ //this._stoped=false; /**@private */ //this._currentTime=NaN; /**@private */ //this._currentFrameTime=NaN; /**@private */ //this._currentFrameIndex=0; /**@private */ //this._elapsedPlaybackTime=NaN; /**@private */ //this._startUpdateLoopCount=NaN; /**@private */ //this._clipNames=null; /**@private */ //this._clips=null; /**@private */ //this._playStartFrames=null; /**@private */ //this._playEndFrames=null; /**@private */ //this._playEventIndex=0; /**@private */ //this._defaultClipIndex=0; /**@private */ //this._avatar=null; /**@private */ //this._cacheNodesDefaultlValues=null; /**@private 无Avatar时缓存场景树中的精灵节点。*/ //this._cacheNodesSpriteOwners=null; /**@private 有Avatar时缓存Avatar树中的AnimationNode节点。*/ //this._cacheNodesAvatarOwners=null; /**@private */ //this._lastPlayAnimationClip=null; /**@private */ //this._lastPlayAnimationClipIndex=0; /**@private */ //this._publicClipsDatas=null; /**@private */ //this._publicAvatarNodeDatas=null; /**@private */ //this._curAvatarNodeDatas=null; /**@private */ //this._cacheNodesToSpriteMap=null; /**@private */ //this._cacheSpriteToNodesMap=null; /**@private */ //this._cacheFullFrames=null; /**@private */ //this._linkSpritesData=null; /**@private */ //this._avatarNodeMap=null; /**@private */ //this._avatarNodes=null; /**@private */ //this._canCache=false; /**@private */ //this._lastFrameIndex=0; /**是否为缓存模式*/ //this.isCache=false; /**播放速率*/ //this.playbackRate=NaN; /**激活时是否自动播放*/ //this.playOnWake=false; Animator.__super.call(this); this._clipNames=[]; this._clips=[]; this._playStartFrames=[]; this._playEndFrames=[]; this._cacheNodesSpriteOwners=[]; this._cacheNodesAvatarOwners=[]; this._cacheNodesDefaultlValues=[]; this._cacheNodesToSpriteMap=[]; this._cacheSpriteToNodesMap=[]; this._cacheFullFrames=[]; this._publicClipsDatas=[]; this._playEventIndex=-1; this._updateTransformPropertyLoopCount=-1; this._lastFrameIndex=-1; this._defaultClipIndex=-1; this._cachePlayRate=1.0; this._currentPlayClip=null; this._currentFrameIndex=-1; this._currentTime=0.0; this._elapsedPlaybackTime=0; this._startUpdateLoopCount=-1; this.isCache=true; this.cacheFrameRate=60; this.playbackRate=1.0; this.playOnWake=true; } __class(Animator,'laya.d3.component.Animator',_super); var __proto=Animator.prototype; Laya.imps(__proto,{"laya.resource.IDestroy":true}) /** *@private */ __proto._getAvatarOwnersByClip=function(clipIndex){ var frameNodes=this._clips[clipIndex]._nodes; var frameNodesCount=frameNodes.length; var owners=this._cacheNodesAvatarOwners[clipIndex]; owners.length=frameNodesCount; var defaultValues=this._cacheNodesDefaultlValues[clipIndex]; defaultValues.length=frameNodesCount; for (var i=0;i < frameNodesCount;i++){ var nodeOwner=this._avatarNodes[0]; var node=frameNodes[i]; var path=node.path; for (var j=0,m=path.length;j < m;j++){ var p=path[j]; if (p===""){ break ; }else { nodeOwner=nodeOwner.getChildByName(p); if (!nodeOwner) break ; } } if (!nodeOwner) continue ; owners[i]=nodeOwner; var datas=AnimationNode._propertyGetFuncs[node.propertyNameID](nodeOwner); if (datas){ var cacheDatas=new Float32Array(node.keyFrameWidth); defaultValues[i]=cacheDatas; for (j=0,m=datas.length;j < m;j++) cacheDatas[j]=datas[j]; } } } /** *@private */ __proto._handleSpriteOwnersByClip=function(clipIndex){ var frameNodes=this._clips[clipIndex]._nodes; var frameNodesCount=frameNodes.length; var owners=this._cacheNodesSpriteOwners[clipIndex]; owners.length=frameNodesCount; var defaultValues=this._cacheNodesDefaultlValues[clipIndex]; defaultValues.length=frameNodesCount; for (var i=0;i < frameNodesCount;i++){ var nodeOwner=this._owner; var node=frameNodes[i]; var path=node.path; var j=0,m=0; for (j=0,m=path.length;j < m;j++){ var p=path[j]; if (p===""){ break ; }else { nodeOwner=nodeOwner.getChildByName(p); if (!nodeOwner) break ; } } if (nodeOwner){ owners[i]=nodeOwner; var datas=AnimationNode._propertyGetFuncs[node.propertyNameID](null,nodeOwner); if (datas){ var cacheDatas=new Float32Array(node.keyFrameWidth); defaultValues[i]=cacheDatas; for (j=0,m=datas.length;j < m;j++) cacheDatas[j]=datas[j]; } } } } /** *@private */ __proto._offClipAndAvatarRelateEvent=function(avatar,clip){ if (avatar.loaded){ if (!clip.loaded) clip.off(/*laya.events.Event.LOADED*/"loaded",this,this._getAvatarOwnersByClip); }else { avatar.off(/*laya.events.Event.LOADED*/"loaded",this,this._getAvatarOwnersAndInitDatasAsync); } } /** *@private */ __proto._getAvatarOwnersByClipAsync=function(clipIndex,clip){ if (clip.loaded) this._getAvatarOwnersByClip(clipIndex); else clip.once(/*laya.events.Event.LOADED*/"loaded",this,this._getAvatarOwnersByClip,[clipIndex]); } /** *@private */ __proto._offGetSpriteOwnersByClipAsyncEvent=function(clip){ if (!clip.loaded) clip.off(/*laya.events.Event.LOADED*/"loaded",this,this._getSpriteOwnersByClipAsync); } /** *@private */ __proto._getSpriteOwnersByClipAsync=function(clipIndex,clip){ if (clip.loaded) this._handleSpriteOwnersByClip(clipIndex); else clip.once(/*laya.events.Event.LOADED*/"loaded",this,this._handleSpriteOwnersByClip,[clipIndex]); } /** *@private */ __proto._getAvatarOwnersAndInitDatasAsync=function(){ for (var i=0,n=this._clips.length;i < n;i++) this._getAvatarOwnersByClipAsync(i,this._clips[i]); this._avatar._cloneDatasToAnimator(this); for (i=0,n=this._avatarNodes.length;i < n;i++) this._checkAnimationNode(this._avatarNodes[i],this._owner); } /** *@private */ __proto._offGetClipCacheFullKeyframeIndicesEvent=function(clip){ (clip.loaded)|| (clip.off(/*laya.events.Event.LOADED*/"loaded",this,this._computeCacheFullKeyframeIndices)); } /** *@private */ __proto._computeCacheFullKeyframeIndices=function(clipIndex){ var clip=this._clips[clipIndex]; var cacheInterval=this._cacheFrameRateInterval *this._cachePlayRate; var clipCacheFullFrames=clip._getFullKeyframeIndicesWithCache(cacheInterval); if (clipCacheFullFrames){ this._cacheFullFrames[clipIndex]=clipCacheFullFrames; return; }else { clipCacheFullFrames=this._cacheFullFrames[clipIndex]=[]; var nodes=clip._nodes; var nodeCount=nodes.length; clipCacheFullFrames.length=nodeCount; var frameCount=Math.ceil(clip._duration / cacheInterval-0.00001)+1; for (var i=0;i < nodeCount;i++){ var node=nodes[i]; var nodeFullFrames=new Int32Array(frameCount); (nodeFullFrames).fill(-1); var keyFrames=node.keyFrames; for (var j=0,n=keyFrames.length;j < n;j++){ var keyFrame=keyFrames[j]; var startTime=keyFrame.startTime; var endTime=startTime+keyFrame.duration; while (startTime <=endTime){ var frameIndex=Math.ceil(startTime / cacheInterval-0.00001); nodeFullFrames[frameIndex]=j; startTime+=cacheInterval; } } clipCacheFullFrames[i]=nodeFullFrames; } clip._cacheFullKeyframeIndices(cacheInterval,clipCacheFullFrames); } } /** *@private */ __proto._updateAnimtionPlayer=function(){ this._updatePlayer(Laya.timer.delta / 1000.0); } /** *@private */ __proto._onOwnerActiveHierarchyChanged=function(){ var owner=this._owner; if (owner.activeInHierarchy){ Laya.timer.frameLoop(1,this,this._updateAnimtionPlayer); (this.playOnWake && this.clip)&& (this.play()); }else { (this.playState!==/*laya.ani.AnimationState.stopped*/0)&& (this._stoped=true); Laya.timer.clear(this,this._updateAnimtionPlayer); } } /** *@private */ __proto._eventScript=function(from,to){ var events=this._currentPlayClip._animationEvents; for (var n=events.length;this._playEventIndex < n;this._playEventIndex++){ var eve=events[this._playEventIndex]; var eventTime=eve.time; if (from <=eventTime && eventTime < to){ var scripts=this._owner._scripts; for (var j=0,m=scripts.length;j < m;j++){ var script=scripts[j]; var fun=script[eve.eventName]; (fun)&& (fun.apply(script,eve.params)); } }else { break ; } } } /** *@private */ __proto._setPlayParams=function(time,cacheFrameInterval){ var lastTime=this._currentTime; this._currentTime=time; this._currentFrameIndex=Math.max(Math.floor(this.currentPlayTime / cacheFrameInterval-0.00001),0); this._currentFrameTime=this._currentFrameIndex *cacheFrameInterval; this._eventScript(lastTime,time); } /** *@private */ __proto._setPlayParamsWhenStop=function(aniClipPlayDuration,cacheFrameInterval){ var lastTime=this._currentTime; this._currentTime=aniClipPlayDuration; this._currentFrameIndex=Math.max(Math.floor(aniClipPlayDuration / cacheFrameInterval-0.00001),0); this._currentFrameTime=this._currentFrameIndex *cacheFrameInterval; this._eventScript(lastTime,aniClipPlayDuration); this._currentPlayClip=null; } /** *@private */ __proto._revertKeyframeNodes=function(clip,clipIndex){ var originalValues=this._cacheNodesDefaultlValues[clipIndex]; var frameNodes=clip._nodes; if (this._avatar){ var avatarOwners=this._cacheNodesAvatarOwners[clipIndex]; for (var i=0,n=avatarOwners.length;i < n;i++){ var avatarOwner=avatarOwners[i]; (avatarOwner)&& (AnimationNode._propertySetFuncs[frameNodes[i].propertyNameID](avatarOwner,null,originalValues[i])); } }else { var spriteOwners=this._cacheNodesSpriteOwners[clipIndex]; for (i=0,n=spriteOwners.length;i < n;i++){ var spriteOwner=spriteOwners[i]; (spriteOwner)&& (AnimationNode._propertySetFuncs[frameNodes[i].propertyNameID](null,spriteOwner,originalValues[i])); } } } /** *@private */ __proto._onAnimationStop=function(){ var i=0,n=0; var frameNode,keyFrames,endKeyframeData; this._lastFrameIndex=-1; var frameNodes=this._currentPlayClip._nodes; if (this._avatar){ var avatarOwners=this._cacheNodesAvatarOwners[this._currentPlayClipIndex]; for (i=0,n=avatarOwners.length;i < n;i++){ var nodeOwner=avatarOwners[i]; frameNode=frameNodes[i]; keyFrames=frameNode.keyFrames; endKeyframeData=keyFrames[keyFrames.length-1].data; (nodeOwner)&& (AnimationNode._propertySetFuncs[frameNode.propertyNameID](nodeOwner,null,endKeyframeData)); } }else { var spriteOwners=this._cacheNodesSpriteOwners[this._currentPlayClipIndex]; for (i=0,n=spriteOwners.length;i < n;i++){ var spriteOwner=spriteOwners[i]; frameNode=frameNodes[i]; keyFrames=frameNode.keyFrames; endKeyframeData=keyFrames[keyFrames.length-1].data; (spriteOwner)&& (AnimationNode._propertySetFuncs[frameNode.propertyNameID](null,spriteOwner,endKeyframeData)); } } } /** *@private */ __proto._setAnimationClipPropertyToAnimationNode=function(nodeOwners,propertyMap,clipDatas){ for (var i=0,n=propertyMap.length;i < n;i++){ var nodexIndex=propertyMap[i]; var owner=nodeOwners[nodexIndex]; if (owner){ var ketframeNode=this._currentPlayClip._nodes[nodexIndex]; var datas=clipDatas[nodexIndex]; (datas)&& (AnimationNode._propertySetFuncs[ketframeNode.propertyNameID](owner,null,datas)); } } } /** *@private */ __proto._setAnimationClipPropertyToSprite3D=function(nodeOwners,curClipAnimationDatas){ for (var i=0,n=nodeOwners.length;i < n;i++){ var owner=nodeOwners[i]; if (owner){ var ketframeNode=this._currentPlayClip._nodes[i]; var datas=curClipAnimationDatas[i]; (datas)&& (AnimationNode._propertySetFuncs[ketframeNode.propertyNameID](null,owner,datas)); } } } /** *@private */ __proto._handleSpriteOwnersBySprite=function(clipIndex,isLink,path,sprite){ var clip=this._clips[clipIndex]; var nodePath=path.join("/"); var ownersNodes=clip._nodesMap[nodePath]; if (ownersNodes){ var owners=this._cacheNodesSpriteOwners[clipIndex]; var nodes=clip._nodes; var defaultValues=this._cacheNodesDefaultlValues[clipIndex]; for (var i=0,n=ownersNodes.length;i < n;i++){ var node=ownersNodes[i]; var index=nodes.indexOf(node); if (isLink){ owners[index]=sprite; var datas=AnimationNode._propertyGetFuncs[node.propertyNameID](null,sprite); if (datas){ var cacheDatas=defaultValues[index]; (cacheDatas)|| (defaultValues[index]=cacheDatas=new Float32Array(node.keyFrameWidth)); for (var j=0,m=datas.length;j < m;j++) cacheDatas[j]=datas[j]; } }else { owners[index]=null; } } } } /** *@private */ __proto._evaluateAvatarNodesCacheMode=function(avatarOwners,clip,publicClipDatas,avatarNodeDatas,unCacheMap){ clip._evaluateAnimationlDatasCacheMode(avatarOwners,this._cacheFullFrames[this._currentPlayClipIndex],this,publicClipDatas,unCacheMap); this._setAnimationClipPropertyToAnimationNode(avatarOwners,unCacheMap,publicClipDatas); for (var i=0,n=this._avatarNodes.length;i < n;i++){ var node=this._avatarNodes[i]; var nodeTransform=node.transform; if (nodeTransform._worldUpdate){ var nodeMatrix=new Float32Array(16); avatarNodeDatas[i]=nodeMatrix; nodeTransform._setWorldMatrixAndUpdate(nodeMatrix); }else { var mat=nodeTransform.getWorldMatrix(); avatarNodeDatas[i]=mat ? mat :Animator.deafaultMatrix; } } } /** *@private */ __proto._evaluateAvatarNodesRealTime=function(avatarOwners,clip,publicClipDatas,avatarNodeDatas,unCacheMap){ clip._evaluateAnimationlDatasRealTime(avatarOwners,this.currentPlayTime,publicClipDatas,unCacheMap); this._setAnimationClipPropertyToAnimationNode(avatarOwners,unCacheMap,publicClipDatas); for (var i=0,n=this._avatarNodes.length;i < n;i++){ var transform=this._avatarNodes[i].transform; if (transform._worldUpdate) transform._setWorldMatrixNoUpdate(avatarNodeDatas[i]); else avatarNodeDatas[i]=Animator.deafaultMatrix; } } /** *@private */ __proto._updateAvatarNodesToSpriteCacheMode=function(clip,avatarNodeDatas){ for (var i=0,n=this._cacheSpriteToNodesMap.length;i < n;i++){ var nodeIndex=this._cacheSpriteToNodesMap[i]; var nodeMatrix=avatarNodeDatas[nodeIndex]; if (nodeMatrix!==Animator.deafaultMatrix){ var spriteTransform=this._avatarNodes[nodeIndex].transform._entity; var spriteWorldMatrix=spriteTransform.worldMatrix; Utils3D.matrix4x4MultiplyMFM((this._owner)._transform.worldMatrix,nodeMatrix,spriteWorldMatrix); spriteTransform.worldMatrix=spriteWorldMatrix; } } } /** *@private */ __proto._updateAvatarNodesToSpriteRealTime=function(){ for (var i=0,n=this._cacheSpriteToNodesMap.length;i < n;i++){ var node=this._avatarNodes[this._cacheSpriteToNodesMap[i]]; var spriteTransform=node.transform._entity; var nodeTransform=node.transform; if (nodeTransform._worldUpdate){ var nodeMatrix=Animator._tempMatrix4x40; nodeTransform._setWorldMatrixAndUpdate(nodeMatrix); var spriteWorldMatrix=spriteTransform.worldMatrix; Utils3D.matrix4x4MultiplyMFM((this._owner)._transform.worldMatrix,nodeMatrix,spriteWorldMatrix); spriteTransform.worldMatrix=spriteWorldMatrix; } } } /** *@private */ __proto._updatePlayer=function(elapsedTime){ if (this._currentPlayClip==null || this._stoped || !this._currentPlayClip.loaded) return; var cacheFrameInterval=this._cacheFrameRateInterval *this._cachePlayRate; var time=0; (this._startUpdateLoopCount!==Stat.loopCount)&& (time=elapsedTime *this.playbackRate,this._elapsedPlaybackTime+=time); var frameRate=this._currentPlayClip._frameRate; var playStart=this._playStartFrames[this._currentPlayClipIndex] / frameRate; var playEnd=Math.min(this._playEndFrames[this._currentPlayClipIndex] / frameRate,this._currentPlayClip._duration); var aniClipPlayDuration=playEnd-playStart; if ((!this._currentPlayClip.islooping && this._elapsedPlaybackTime >=aniClipPlayDuration)){ this._onAnimationStop(); this._setPlayParamsWhenStop(aniClipPlayDuration,cacheFrameInterval); this.event(/*laya.events.Event.STOPPED*/"stopped"); return; } time+=this._currentTime; if (aniClipPlayDuration > 0){ if (time >=aniClipPlayDuration){ do { time-=aniClipPlayDuration; if (time < aniClipPlayDuration){ this._setPlayParams(time,cacheFrameInterval); this.event(/*laya.events.Event.COMPLETE*/"complete"); } this._playEventIndex=0; this._eventScript(0,time); }while (time >=aniClipPlayDuration) }else { this._setPlayParams(time,cacheFrameInterval); } }else { this._currentTime=this._currentFrameTime=this._currentFrameIndex=this._playEventIndex=0; this.event(/*laya.events.Event.COMPLETE*/"complete"); } } /** *@private *更新蒙皮动画组件。 *@param state 渲染状态参数。 */ __proto._update=function(state){ var clip=this._currentPlayClip; if (this.playState!==/*laya.ani.AnimationState.playing*/2 || !clip || !clip.loaded) return; var rate=this.playbackRate *Laya.timer.scale; var cacheRate=this._cachePlayRate; this._canCache=this.isCache && rate >=cacheRate; var frameIndex=-1; var clipDatas; if (this._canCache){ frameIndex=this._currentFrameIndex; if (this._lastFrameIndex===frameIndex) return; clipDatas=clip._getAnimationDataWithCache(cacheRate,frameIndex); if (this._avatar){ var avatarOwners=this._cacheNodesAvatarOwners[this._currentPlayClipIndex]; var cacheMap=clip._cachePropertyMap; var cacheMapCount=cacheMap.length; if (cacheMapCount > 0){ if (!clipDatas){ clipDatas=[]; clipDatas.length=cacheMapCount; clip._cacheAnimationData(cacheRate,frameIndex,clipDatas); clip._evaluateAnimationlDatasCacheMode(avatarOwners,this._cacheFullFrames[this._currentPlayClipIndex],this,clipDatas,cacheMap); } this._setAnimationClipPropertyToAnimationNode(avatarOwners,cacheMap,clipDatas); } this._curAvatarNodeDatas=clip._getAvatarDataWithCache(this._avatar,this._cachePlayRate,frameIndex); if (!this._curAvatarNodeDatas){ this._curAvatarNodeDatas=[]; this._curAvatarNodeDatas.length=this._avatarNodes.length; clip._cacheAvatarData(this._avatar,this._cachePlayRate,frameIndex,this._curAvatarNodeDatas); this._evaluateAvatarNodesCacheMode(avatarOwners,clip,clip._publicClipDatas,this._curAvatarNodeDatas,clip._unCachePropertyMap); } this._updateAvatarNodesToSpriteCacheMode(clip,this._curAvatarNodeDatas); }else { var spriteOwners=this._cacheNodesSpriteOwners[this._currentPlayClipIndex]; if (!clipDatas){ clipDatas=[]; clipDatas.length=this._currentPlayClip._nodes.length; clip._evaluateAnimationlDatasCacheMode(spriteOwners,this._cacheFullFrames[this._currentPlayClipIndex],this,clipDatas,null); clip._cacheAnimationData(cacheRate,frameIndex,clipDatas); } this._setAnimationClipPropertyToSprite3D(spriteOwners,clipDatas); } }else { clipDatas=clip._publicClipDatas; if (this._avatar){ clip._evaluateAnimationlDatasRealTime(this._cacheNodesAvatarOwners[this._currentPlayClipIndex],this.currentPlayTime,clipDatas,clip._cachePropertyMap); if (!this._publicAvatarNodeDatas){ this._publicAvatarNodeDatas=[]; var nodeCount=this._avatarNodes.length; this._publicAvatarNodeDatas.length=nodeCount; for (var i=1;i < nodeCount;i++) this._publicAvatarNodeDatas[i]=new Float32Array(16); } this._curAvatarNodeDatas=this._publicAvatarNodeDatas; this._evaluateAvatarNodesRealTime(this._cacheNodesAvatarOwners[this._currentPlayClipIndex],clip,clipDatas,this._curAvatarNodeDatas,clip._unCachePropertyMap); this._updateAvatarNodesToSpriteRealTime(); }else { clip._evaluateAnimationlDatasRealTime(this._cacheNodesSpriteOwners[this._currentPlayClipIndex],this.currentPlayTime,clipDatas,null); } } this._lastFrameIndex=frameIndex; } /** *@private */ __proto._checkAnimationNode=function(node,sprite){ if (node.name===sprite.name && !sprite._transform.dummy) sprite._isLinkSpriteToAnimationNode(this,node,true); for (var i=0,n=sprite._childs.length;i < n;i++) this._checkAnimationNode(node,sprite.getChildAt(i)); } /** *@inheritDoc */ __proto._load=function(owner){ ((owner).activeInHierarchy)&& (Laya.timer.frameLoop(1,this,this._updateAnimtionPlayer)); this._owner.on(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onOwnerActiveHierarchyChanged); } /** *@inheritDoc */ __proto._unload=function(owner){ _super.prototype._unload.call(this,owner); ((owner).activeInHierarchy)&& (Laya.timer.clear(this,this._updateAnimtionPlayer)); this._owner.off(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onOwnerActiveHierarchyChanged); this._curAvatarNodeDatas=null; } /** *@private */ __proto._destroy=function(){ _super.prototype._destroy.call(this); for (var i=0,n=this._clips.length;i < n;i++) this._clips[i]._removeReference(); this._currentPlayClip=null; this._clipNames=null; this._cacheNodesSpriteOwners=null; this._cacheNodesAvatarOwners=null; this._cacheNodesDefaultlValues=null; this._clips=null; this._cacheFullFrames=null; } /** *@private */ __proto._cloneTo=function(dest){ var animator=dest; animator.avatar=this.avatar; var clipCount=this._clips.length; for (var i=0,n=this._clips.length;i < n;i++) animator.addClip(this._clips[i]); if (this.clip){ animator.clip=this.clip; } if (this._linkSpritesData){ animator._linkSpritesData={}; for (var k in this._linkSpritesData) animator._linkSpritesData[k]=this._linkSpritesData[k].slice(); } } /** *添加动画片段。 *@param clip 动画片段。 *@param playName 动画片段播放名称,如果为null,则使用clip.name作为播放名称。 *@param 开始帧率。 *@param 结束帧率。 */ __proto.addClip=function(clip,playName,startFrame,endFrame){ (startFrame===void 0)&& (startFrame=0); (endFrame===void 0)&& (endFrame=4294967295); playName=playName || clip.name; var index=this._clipNames.indexOf(playName); if (index!==-1){ if (this._clips[index]!==clip) throw new Error("Animation:this playName has exist with another clip."); }else { var clipIndex=this._clips.indexOf(clip); if (startFrame < 0 || endFrame < 0) throw new Error("Animator:startFrame and endFrame must large than zero."); if (startFrame > endFrame) throw new Error("Animator:startFrame must less than endFrame."); this._clipNames.push(playName); this._clips.push(clip); this._playStartFrames.push(startFrame); this._playEndFrames.push(endFrame); this._cacheNodesSpriteOwners.push([]); this._cacheNodesAvatarOwners.push([]); this._cacheNodesDefaultlValues.push([]); this._publicClipsDatas.push([]); clip._addReference(); clipIndex=this._clips.length-1; if (this._avatar){ if (this._avatar.loaded) this._getAvatarOwnersByClipAsync(clipIndex,clip); else this._avatar.once(/*laya.events.Event.LOADED*/"loaded",this,this._getAvatarOwnersByClipAsync,[clipIndex,clip]); }else { this._getSpriteOwnersByClipAsync(clipIndex,clip); } if (clip.loaded) this._computeCacheFullKeyframeIndices(clipIndex); else clip.once(/*laya.events.Event.LOADED*/"loaded",this,this._computeCacheFullKeyframeIndices,[clipIndex]); } } /** *移除动画片段。 *@param clip 动画片段。 */ __proto.removeClip=function(clip){ var index=this._clips.indexOf(clip); if (index!==-1){ if (this._avatar) this._offClipAndAvatarRelateEvent(this._avatar,clip) else this._offGetSpriteOwnersByClipAsyncEvent(clip); this._offGetClipCacheFullKeyframeIndicesEvent(clip); this._clipNames.splice(index,1); this._clips.splice(index,1); this._playStartFrames.splice(index,1); this._playEndFrames.splice(index,1); this._cacheNodesSpriteOwners.splice(index,1); this._cacheNodesAvatarOwners.splice(index,1); this._cacheNodesDefaultlValues.splice(index,1); this._publicClipsDatas.splice(index,1); clip._removeReference(); } } /** *通过播放名字移除动画片段。 *@param playName 播放名字。 */ __proto.removeClipByName=function(playName){ var index=this._clipNames.indexOf(playName); if (index!==-1){ var clip=this._clips[index]; if (this._avatar) this._offClipAndAvatarRelateEvent(this._avatar,clip); else this._offGetSpriteOwnersByClipAsyncEvent(clip); this._offGetClipCacheFullKeyframeIndicesEvent(clip); this._clipNames.splice(index,1); this._clips.splice(index,1); this._playStartFrames.splice(index,1); this._playEndFrames.splice(index,1); this._cacheNodesSpriteOwners.splice(index,1); this._cacheNodesAvatarOwners.splice(index,1); this._cacheNodesDefaultlValues.splice(index,1); this._publicClipsDatas.splice(index,1); } } /** *通过播放名字获取动画片段。 *@param playName 播放名字。 *@return 动画片段。 */ __proto.getClip=function(playName){ var index=this._clipNames.indexOf(playName); if (index!==-1){ return this._clips[index]; }else { return null; } } /** *获取动画片段个数。 *@return 动画个数。 */ __proto.getClipCount=function(){ return this._clips.length; } /** *播放动画。 *@param name 如果为null则播放默认动画,否则按名字播放动画片段。 *@param playbackRate 播放速率。 *@param startFrame 开始帧率。 *@param endFrame 结束帧率.-1表示为最大结束帧率。 */ __proto.play=function(name,playbackRate){ (playbackRate===void 0)&& (playbackRate=1.0); if (!name && this._defaultClipIndex==-1) throw new Error("Animator:must have default clip value,please set clip property."); if (name){ this._currentPlayClipIndex=this._clipNames.indexOf(name); this._currentPlayClip=this._clips[this._currentPlayClipIndex]; }else { this._currentPlayClipIndex=this._defaultClipIndex; this._currentPlayClip=this._clips[this._defaultClipIndex]; } this._currentTime=0; this._currentFrameTime=0; this._elapsedPlaybackTime=0; this._playEventIndex=0; this.playbackRate=playbackRate; this._stoped=false; this._currentFrameIndex=0; this._startUpdateLoopCount=Stat.loopCount; if (this._lastPlayAnimationClip) (this._lastPlayAnimationClip!==this._currentPlayClip)&& (this._revertKeyframeNodes(this._lastPlayAnimationClip,this._lastPlayAnimationClipIndex)); this._updatePlayer(0); this._lastPlayAnimationClip=this._currentPlayClip; this._lastPlayAnimationClipIndex=this._currentPlayClipIndex; } /** *停止播放当前动画 */ __proto.stop=function(){ if (this.playState!==/*laya.ani.AnimationState.stopped*/0){ this._stoped=true; this.event(/*laya.events.Event.STOPPED*/"stopped"); } } /** *@private */ __proto._getLinkSpritePath=function(sprite3D,path){ path.unshift(sprite3D.name); var parent=sprite3D._parent; if (parent._hierarchyAnimator===this) this._getLinkSpritePath(parent,path); else path.shift(); } /** *关联精灵节点到Avatar节点,此Animator必须有Avatar文件。 *@param nodeName 关联节点的名字。 *@param sprite3D 精灵节点。 *@return 是否关联成功。 */ __proto.linkSprite3DToAvatarNode=function(nodeName,sprite3D){ if (sprite3D._hierarchyAnimator===this){ if (this._avatar){ var node=this._avatarNodeMap[nodeName]; if (node){this._linkSpritesData=this._linkSpritesData|| {}; var path=[]; this._getLinkSpritePath(sprite3D,path); this._linkSpritesData[nodeName]=path; sprite3D._isLinkSpriteToAnimationNode(this,node,true); return true; }else { return false; } }else { return false; } }else { throw("Animator:sprite3D must belong to this Animator"); return false; } } /** *解除精灵节点到Avatar节点的关联,此Animator必须有Avatar文件。 *@param sprite3D 精灵节点。 *@return 是否解除关联成功。 */ __proto.unLinkSprite3DToAvatarNode=function(sprite3D){ if (this._avatar){ var dummy=sprite3D.transform.dummy; if (dummy){ var node=this._avatarNodeMap[dummy._owner.name]; sprite3D._isLinkSpriteToAnimationNode(this,node,false); return true; }else { return false; } }else { return false; } } /** *获取当前播放状态 *@return 当前播放状态 */ __getset(0,__proto,'playState',function(){ if (this._currentPlayClip==null) return /*laya.ani.AnimationState.stopped*/0; if (this._stoped) return /*laya.ani.AnimationState.stopped*/0; return /*laya.ani.AnimationState.playing*/2; }); /** *设置avatar。 *@param value avatar。 */ /** *获取avatar。 *@return avator。 */ __getset(0,__proto,'avatar',function(){ return this._avatar; },function(value){ if (this._avatar!==value){ var lastAvatar=this._avatar; this._avatar=value; var clipLength=this._clips.length; for (var i=0;i < clipLength;i++) this._offClipAndAvatarRelateEvent(lastAvatar,this._clips[i]); if (value){ if (value.loaded) this._getAvatarOwnersAndInitDatasAsync(); else value.once(/*laya.events.Event.LOADED*/"loaded",this,this._getAvatarOwnersAndInitDatasAsync); } } }); /** *设置缓存播放帧率,缓存模式下生效。注意:修改此值会有计算开销。* *@return value 缓存播放帧率 */ /** *获取缓存播放帧,缓存模式下生效。 *@return value 缓存播放帧率。 */ __getset(0,__proto,'cacheFrameRate',function(){ return this._cacheFrameRate; },function(value){ if (this._cacheFrameRate!==value){ this._cacheFrameRate=value; this._cacheFrameRateInterval=1.0 / this._cacheFrameRate; for (var i=0,n=this._clips.length;i < n;i++) (this._clips[i].loaded)&& (this._computeCacheFullKeyframeIndices(i)); } }); /** *设置默认动画片段,AnimationClip名称为默认playName。 *@param value 默认动画片段。 */ /** *获取默认动画片段。 *@return 默认动画片段。 */ __getset(0,__proto,'clip',function(){ return this._clips[this._defaultClipIndex]; },function(value){ var index=value ? this._clips.indexOf(value):-1; if (this._defaultClipIndex!==index){ (this._defaultClipIndex!==-1)&& (this.removeClip(this._clips[this._defaultClipIndex])); (index!==-1)&& (this.addClip(value,value.name)); this._defaultClipIndex=index; } }); /** *获取当前帧数 *@return 当前帧数 */ __getset(0,__proto,'currentFrameIndex',function(){ return this._currentFrameIndex; }); /** *设置缓存播放速率,缓存模式下生效。注意:修改此值会有计算开销。* *@return value 缓存播放速率。 */ /** *获取缓存播放速率,缓存模式下生效。* *@return 缓存播放速率。 */ __getset(0,__proto,'cachePlayRate',function(){ return this._cachePlayRate; },function(value){ if (this._cachePlayRate!==value){ this._cachePlayRate=value; for (var i=0,n=this._clips.length;i < n;i++) (this._clips[i].loaded)&& (this._computeCacheFullKeyframeIndices(i)); } }); /** *获取当前帧时间,不包括重播时间 *@return value 当前时间 */ __getset(0,__proto,'currentFrameTime',function(){ return this._currentFrameTime; }); /** *获取当前动画索引 *@return value 当前动画索引 */ __getset(0,__proto,'currentPlayClip',function(){ return this._currentPlayClip; }); /** *获取当前精确时间,不包括重播时间 *@return value 当前时间 */ __getset(0,__proto,'currentPlayTime',function(){ return this._currentTime+(this._playStartFrames[this._currentPlayClipIndex] / this._currentPlayClip._frameRate); }); /** *设置当前播放位置 *@param value 当前时间 */ __getset(0,__proto,'playbackTime',null,function(value){ if (this._currentPlayClip==null || !this._currentPlayClip || !this._currentPlayClip.loaded) return; this._startUpdateLoopCount=Stat.loopCount; var cacheFrameInterval=this._cacheFrameRateInterval *this._cachePlayRate; this._currentTime=value; this._currentFrameIndex=Math.floor(this.currentPlayTime / cacheFrameInterval); this._currentFrameTime=this._currentFrameIndex *cacheFrameInterval; }); /** *设置是否暂停 *@param value 是否暂停 */ /** *获取当前是否暂停 *@return 是否暂停 */ __getset(0,__proto,'paused',function(){ return this._stoped; },function(value){ this._stoped=value; value && this.event(/*laya.events.Event.PAUSED*/"paused"); }); __static(Animator, ['deafaultMatrix',function(){return this.deafaultMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);},'_tempMatrix4x40',function(){return this._tempMatrix4x40=new Float32Array(16);} ]); return Animator; })(Component3D) /** *AttachPoint 类用于创建挂点组件。 */ //class laya.d3.component.AttachPoint extends laya.d3.component.Component3D var AttachPoint=(function(_super){ function AttachPoint(){ /**@private */ this._attachSkeleton=null; /**@private */ this._extenData=null; /**挂点骨骼的名称。*/ this.attachBones=null; /**挂点骨骼的变换矩阵。*/ this.matrixs=null; AttachPoint.__super.call(this); this.attachBones=[]; this.matrixs=[]; } __class(AttachPoint,'laya.d3.component.AttachPoint',_super); var __proto=AttachPoint.prototype; /** *@private *初始化载入挂点组件。 *@param owner 所属精灵对象。 */ __proto._load=function(owner){ _super.prototype._load.call(this,owner); this._attachSkeleton=(owner).getComponentByType(SkinAnimations); } /** *@private *更新挂点组件。 *@param state 渲染状态。 */ __proto._update=function(state){ if (!this._attachSkeleton||this._attachSkeleton.destroyed || this._attachSkeleton.player.state===/*laya.ani.AnimationState.stopped*/0 || !this._attachSkeleton.curBonesDatas) return; var player=this._attachSkeleton.player; var templet=this._attachSkeleton.templet; this.matrixs.length=this.attachBones.length; var boneDatas=this._attachSkeleton.curBonesDatas; var worldMatrix=(this.owner).transform.worldMatrix; for (var i=0,n=this.attachBones.length;i < n;i++){ var startIndex=templet.getNodeIndexWithName(player.currentAnimationClipIndex,this.attachBones[i])*16; var matrix=this.matrixs[i]; matrix || (matrix=this.matrixs[i]=new Matrix4x4()); var matrixE=matrix.elements; for (var j=0;j < 16;j++) matrixE[j]=boneDatas[startIndex+j]; Matrix4x4.multiply(worldMatrix,matrix,matrix); } this.event(/*laya.events.Event.COMPLETE*/"complete"); } return AttachPoint; })(Component3D) /** *Collider 类用于创建碰撞器的父类,抽象类,不允许实例。 */ //class laya.d3.component.physics.Collider extends laya.d3.component.Component3D var Collider=(function(_super){ function Collider(){ /**@private */ //this._needUpdate=false; /**@private 只读,不允许修改。*/ //this._isRigidbody=false; /**@private */ //this._runtimeCollisonMap=null; /**@private */ //this._runtimeCollisonTestMap=null; /**@private */ //this._ignoreCollisonMap=null; /**是否为触发器。*/ //this.isTrigger=false; Collider.__super.call(this); this._isRigidbody=false; this._runtimeCollisonMap={}; this._runtimeCollisonTestMap={}; this._ignoreCollisonMap={}; this.isTrigger=true; } __class(Collider,'laya.d3.component.physics.Collider',_super); var __proto=Collider.prototype; /** *@private */ __proto._clearCollsionMap=function(){ for (var k in this._runtimeCollisonMap){ var otherCollider=this._runtimeCollisonMap[k]; delete otherCollider._runtimeCollisonMap[this.id]; if (otherCollider._isRigidbody) delete otherCollider._runtimeCollisonTestMap[this.id]; var otherID=otherCollider.id; delete this._runtimeCollisonMap[otherID]; if (this._isRigidbody) delete this._runtimeCollisonTestMap[otherID]; } } /** *@inheritDoc */ __proto._unload=function(owner){ for (var k in this._runtimeCollisonMap){ var otherCollider=this._runtimeCollisonMap[k]; delete otherCollider._runtimeCollisonMap[this.id]; if (otherCollider._isRigidbody) delete otherCollider._runtimeCollisonTestMap[this.id]; delete this._ignoreCollisonMap[k]._ignoreCollisonMap[this.id]; } } /** *@private */ __proto._setIsRigidbody=function(value){ if (this._isRigidbody!==value){ this._isRigidbody=value; var owner=this._owner; if (owner.displayedInStage){ var layer=owner.layer; layer._removeCollider(this); layer._addCollider(this); } } } /** *@private */ __proto._getType=function(){ return-1; } /** *@private */ __proto._collisonTo=function(other){ return false; } /** *在场景中投下可与球体碰撞器碰撞的一条光线,获取发生碰撞的球体碰撞器信息。 *@param ray 射线 *@param outHitInfo 与该射线发生碰撞球体碰撞器的碰撞信息 *@param distance 射线长度,默认为最大值 */ __proto.raycast=function(ray,hitInfo,maxDistance){ (maxDistance===void 0)&& (maxDistance=1.79e+308); throw new Error("Collider:Must override it."); } /** *@inheritDoc */ __getset(0,__proto,'enable',_super.prototype._$get_enable,function(value){ if (this._enable!==value){ var owner=this._owner; if (owner.displayedInStage) (value)|| (this._clearCollsionMap()); this._enable=value; this.event(/*laya.events.Event.ENABLE_CHANGED*/"enablechanged",this._enable); } }); /** *@inheritDoc */ __getset(0,__proto,'isSingleton',function(){ return Collider._isSingleton; }); Collider._isSingleton=false; return Collider; })(Component3D) /** *Rigidbody 类用于创建动画组件。 */ //class laya.d3.component.Rigidbody extends laya.d3.component.Component3D var Rigidbody=(function(_super){ /** *创建一个 Rigidbody 实例。 */ function Rigidbody(){ Rigidbody.__super.call(this); } __class(Rigidbody,'laya.d3.component.Rigidbody',_super); var __proto=Rigidbody.prototype; /** *@inheritDoc */ __getset(0,__proto,'enable',_super.prototype._$get_enable,function(value){ if (this._enable!==value){ var colliders=(this._owner)._colliders; for (var i=0,n=colliders.length;i < n;i++){ var collider=colliders[i]; collider._setIsRigidbody(value); var runtimeCollisonMap=collider._runtimeCollisonMap; var runtimeCollisonTestMap=collider._runtimeCollisonTestMap; if (!value){ for (var k in runtimeCollisonMap) delete runtimeCollisonTestMap[k]; } } this._enable=value; this.event(/*laya.events.Event.ENABLE_CHANGED*/"enablechanged",this._enable); } }); return Rigidbody; })(Component3D) /** *Script 类用于创建脚本的父类。 */ //class laya.d3.component.Script extends laya.d3.component.Component3D var Script=(function(_super){ /** *创建一个新的 Script 实例。 */ function Script(){ Script.__super.call(this); } __class(Script,'laya.d3.component.Script',_super); var __proto=Script.prototype; /** *当其他碰撞器进入时触发。 */ __proto.onTriggerEnter=function(other){} /** *当其他碰撞器退出时触发。 */ __proto.onTriggerExit=function(other){} /** *当其他碰撞器保持进入状态时逐帧触发。 */ __proto.onTriggerStay=function(other){} /** *@inheritDoc */ __getset(0,__proto,'isSingleton',function(){ return Script._isSingleton; }); Script._isSingleton=false; return Script; })(Component3D) /** *... *@author ... */ //class laya.d3.core.GlitterRender extends laya.d3.core.render.BaseRender var GlitterRender=(function(_super){ function GlitterRender(owner){ GlitterRender.__super.call(this,owner); } __class(GlitterRender,'laya.d3.core.GlitterRender',_super); var __proto=GlitterRender.prototype; __proto._calculateBoundingBox=function(){ var minE=this._boundingBox.min.elements; minE[0]=-Number.MAX_VALUE; minE[1]=-Number.MAX_VALUE; minE[2]=-Number.MAX_VALUE; var maxE=this._boundingBox.min.elements; maxE[0]=Number.MAX_VALUE; maxE[1]=Number.MAX_VALUE; maxE[2]=Number.MAX_VALUE; } __proto._calculateBoundingSphere=function(){ var centerE=this._boundingSphere.center.elements; centerE[0]=0; centerE[1]=0; centerE[2]=0; this._boundingSphere.radius=Number.MAX_VALUE; } /** *@private */ __proto._renderUpdate=function(projectionView){ this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,this._owner.transform.worldMatrix); var projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); var templet=(this._owner).templet; this._setShaderValueNumber(/*laya.d3.core.glitter.Glitter.DURATION*/3,templet.lifeTime); this._setShaderValueNumber(/*laya.d3.core.glitter.Glitter.CURRENTTIME*/2,templet._currentTime); return true; } return GlitterRender; })(BaseRender) /** *MeshFilter 类用于创建网格过滤器。 */ //class laya.d3.core.MeshFilter extends laya.d3.core.GeometryFilter var MeshFilter=(function(_super){ function MeshFilter(owner){ /**@private */ this._owner=null; /**@private */ this._sharedMesh=null; MeshFilter.__super.call(this); this._owner=owner; } __class(MeshFilter,'laya.d3.core.MeshFilter',_super); var __proto=MeshFilter.prototype; /** *@private */ __proto._sharedMeshLoaded=function(){ this.event(/*laya.events.Event.LOADED*/"loaded"); } /** *@inheritDoc */ __proto._destroy=function(){ _super.prototype._destroy.call(this); this._owner=null; (this._sharedMesh)&& (this._sharedMesh._removeReference(),this._sharedMesh=null); } /** *设置共享网格。 *@return value 共享网格。 */ /** *获取共享网格。 *@return 共享网格。 */ __getset(0,__proto,'sharedMesh',function(){ return this._sharedMesh; },function(value){ var lastValue=this._sharedMesh; (lastValue)&& (lastValue._removeReference()); this._sharedMesh=value; value._addReference(); this.event(/*laya.events.Event.MESH_CHANGED*/"meshchanged",[this,lastValue,value]); if (!value.loaded){ this._sharedMesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._sharedMeshLoaded); } }); /** *@inheritDoc */ __getset(0,__proto,'_isAsyncLoaded',function(){ return this._sharedMesh.loaded; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBoxCorners',function(){ return this._sharedMesh.boundingBoxCorners; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingSphere',function(){ return this._sharedMesh.boundingSphere; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBox',function(){ return this._sharedMesh.boundingBox; }); return MeshFilter; })(GeometryFilter) /** *MeshRender 类用于网格渲染器。 */ //class laya.d3.core.MeshRender extends laya.d3.core.render.BaseRender var MeshRender=(function(_super){ /** *创建一个新的 MeshRender 实例。 */ function MeshRender(owner){ MeshRender.__super.call(this,owner); (owner).meshFilter.on(/*laya.events.Event.MESH_CHANGED*/"meshchanged",this,this._onMeshChanged); } __class(MeshRender,'laya.d3.core.MeshRender',_super); var __proto=MeshRender.prototype; /** *@private */ __proto._onMeshChanged=function(meshFilter,oldMesh,mesh){ if (mesh.loaded){ this._boundingSphereNeedChange=this._boundingBoxNeedChange=this._boundingBoxCenterNeedChange=this._octreeNodeNeedChange=true; }else { mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._onMeshLoaed); } } /** *@private */ __proto._onMeshLoaed=function(sender,enable){ this._boundingSphereNeedChange=this._boundingBoxNeedChange=this._boundingBoxCenterNeedChange=this._octreeNodeNeedChange=true; } /** *@private */ __proto._calculateBoundingSphereByInitSphere=function(boundSphere){ var maxScale=NaN; var transform=this._owner.transform; var scaleE=transform.scale.elements; var scaleX=Math.abs(scaleE[0]); var scaleY=Math.abs(scaleE[1]); var scaleZ=Math.abs(scaleE[2]); if (scaleX >=scaleY && scaleX >=scaleZ) maxScale=scaleX; else maxScale=scaleY >=scaleZ ? scaleY :scaleZ; Vector3.transformCoordinate(boundSphere.center,transform.worldMatrix,this._boundingSphere.center); this._boundingSphere.radius=boundSphere.radius *maxScale; } /** *@private */ __proto._calculateBoundBoxByInitCorners=function(corners){ var worldMat=(this._owner).transform.worldMatrix; for (var i=0;i < 8;i++) Vector3.transformCoordinate(corners[i],worldMat,BaseRender._tempBoundBoxCorners[i]); BoundBox.createfromPoints(BaseRender._tempBoundBoxCorners,this._boundingBox); } /** *@inheritDoc */ __proto._calculateBoundingSphere=function(){ var sharedMesh=(this._owner).meshFilter.sharedMesh; if (sharedMesh==null || sharedMesh.boundingSphere==null) this._boundingSphere.toDefault(); else this._calculateBoundingSphereByInitSphere(sharedMesh.boundingSphere); } /** *@inheritDoc */ __proto._calculateBoundingBox=function(){ var sharedMesh=(this._owner).meshFilter.sharedMesh; if (sharedMesh==null || sharedMesh.boundingBox==null) this._boundingBox.toDefault(); else this._calculateBoundBoxByInitCorners(sharedMesh.boundingBoxCorners); } /** *@private */ __proto._renderUpdate=function(projectionView){ var transform=this._owner.transform; if (transform){ this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,transform.worldMatrix); var projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); }else { this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,Matrix4x4.DEFAULT); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projectionView); } if (Laya3D.debugMode) this._renderRenderableBoundBox(); return true; } return MeshRender; })(BaseRender) /** *ShurikenParticleSystem 类用于创建3D粒子数据模板。 */ //class laya.d3.core.particleShuriKen.ShurikenParticleSystem extends laya.d3.core.GeometryFilter var ShurikenParticleSystem=(function(_super){ function ShurikenParticleSystem(owner){ /**@private */ //this._boundingSphere=null; /**@private */ //this._boundingBox=null; /**@private */ //this._boundingBoxCorners=null; /**@private */ //this._owner=null; /**@private */ //this._ownerRender=null; /**@private */ //this._vertices=null; /**@private */ //this._floatCountPerVertex=0; /**@private */ //this._startLifeTimeIndex=0; /**@private */ //this._timeIndex=0; /**@private */ //this._simulateUpdate=false; /**@private */ //this._firstActiveElement=0; /**@private */ //this._firstNewElement=0; /**@private */ //this._firstFreeElement=0; /**@private */ //this._firstRetiredElement=0; /**@private */ //this._drawCounter=0; /**@private */ //this._vertexBuffer=null; /**@private */ //this._indexBuffer=null; /**@private */ //this._bufferMaxParticles=0; /**@private */ //this._emission=null; /**@private */ //this._shape=null; /**@private */ //this._isEmitting=false; /**@private */ //this._isPlaying=false; /**@private */ //this._isPaused=false; /**@private */ //this._playStartDelay=NaN; /**@private 发射的累计时间。*/ //this._frameRateTime=NaN; /**@private 一次循环内的累计时间。*/ //this._emissionTime=NaN; /**@private */ //this._totalDelayTime=NaN; /**@private */ //this._burstsIndex=0; /**@private */ //this._velocityOverLifetime=null; /**@private */ //this._colorOverLifetime=null; /**@private */ //this._sizeOverLifetime=null; /**@private */ //this._rotationOverLifetime=null; /**@private */ //this._textureSheetAnimation=null; /**@private */ //this._startLifetimeType=0; /**@private */ //this._startLifetimeConstant=NaN; /**@private */ //this._startLifeTimeGradient=null; /**@private */ //this._startLifetimeConstantMin=NaN; /**@private */ //this._startLifetimeConstantMax=NaN; /**@private */ //this._startLifeTimeGradientMin=null; /**@private */ //this._startLifeTimeGradientMax=null; /**@private */ //this._maxStartLifetime=NaN; /**@private */ //this._vertexStride=0; /**@private */ //this._indexStride=0; /**@private */ //this._currentTime=NaN; /**@private */ //this._startUpdateLoopCount=0; /**@private */ //this._rand=null; /**@private */ //this._randomSeeds=null; /**粒子运行的总时长,单位为秒。*/ //this.duration=NaN; /**是否循环。*/ //this.looping=false; /**是否预热。暂不支持*/ //this.prewarm=false; /**开始延迟类型,0为常量模式,1为随机随机双常量模式,不能和prewarm一起使用。*/ //this.startDelayType=0; /**开始播放延迟,不能和prewarm一起使用。*/ //this.startDelay=NaN; /**开始播放最小延迟,不能和prewarm一起使用。*/ //this.startDelayMin=NaN; /**开始播放最大延迟,不能和prewarm一起使用。*/ //this.startDelayMax=NaN; /**开始速度模式,0为恒定速度,2为两个恒定速度的随机插值。缺少1、3模式*/ //this.startSpeedType=0; /**开始速度,0模式。*/ //this.startSpeedConstant=NaN; /**最小开始速度,1模式。*/ //this.startSpeedConstantMin=NaN; /**最大开始速度,1模式。*/ //this.startSpeedConstantMax=NaN; /**开始尺寸是否为3D模式。*/ //this.threeDStartSize=false; /**开始尺寸模式,0为恒定尺寸,2为两个恒定尺寸的随机插值。缺少1、3模式和对应的二种3D模式*/ //this.startSizeType=0; /**开始尺寸,0模式。*/ //this.startSizeConstant=NaN; /**开始三维尺寸,0模式。*/ //this.startSizeConstantSeparate=null; /**最小开始尺寸,2模式。*/ //this.startSizeConstantMin=NaN; /**最大开始尺寸,2模式。*/ //this.startSizeConstantMax=NaN; /**最小三维开始尺寸,2模式。*/ //this.startSizeConstantMinSeparate=null; /**最大三维开始尺寸,2模式。*/ //this.startSizeConstantMaxSeparate=null; /**3D开始旋转,暂不支持*/ //this.threeDStartRotation=false; /**开始旋转模式,0为恒定尺寸,2为两个恒定旋转的随机插值,缺少2种模式,和对应的四种3D模式。*/ //this.startRotationType=0; /**开始旋转,0模式。*/ //this.startRotationConstant=NaN; /**开始三维旋转,0模式。*/ //this.startRotationConstantSeparate=null; /**最小开始旋转,1模式。*/ //this.startRotationConstantMin=NaN; /**最大开始旋转,1模式。*/ //this.startRotationConstantMax=NaN; /**最小开始三维旋转,1模式。*/ //this.startRotationConstantMinSeparate=null; /**最大开始三维旋转,1模式。*/ //this.startRotationConstantMaxSeparate=null; /**随机旋转方向,范围为0.0到1.0*/ //this.randomizeRotationDirection=NaN; /**开始颜色模式,0为恒定颜色,2为两个恒定颜色的随机插值,缺少2种模式。*/ //this.startColorType=0; /**开始颜色,0模式。*/ //this.startColorConstant=null; /**最小开始颜色,1模式。*/ //this.startColorConstantMin=null; /**最大开始颜色,1模式。*/ //this.startColorConstantMax=null; /**重力敏感度。*/ //this.gravityModifier=NaN; /**模拟器空间,0为World,1为Local。暂不支持Custom。*/ //this.simulationSpace=0; /**缩放模式,0为Hiercachy,1为Local,2为World。暂不支持1,2*/ //this.scaleMode=0; /**激活时是否自动播放。*/ //this.playOnAwake=false; /**随机种子,注:play()前设置有效。*/ //this.randomSeed=null; /**是否使用随机种子。 */ //this.autoRandomSeed=false; /**是否为性能模式,性能模式下会延迟粒子释放。*/ //this.isPerformanceMode=false; ShurikenParticleSystem.__super.call(this); this._tempRotationMatrix=new Matrix4x4(); this._uvLength=new Vector2(); this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._owner=owner; this._ownerRender=owner.particleRender; this._boundingBoxCorners=__newvec(8,null); this._boundingSphere=new BoundSphere(new Vector3(),Number.MAX_VALUE); this._boundingBox=new BoundBox(new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)); this._currentTime=0; this._isEmitting=false; this._isPlaying=false; this._isPaused=false; this._burstsIndex=0; this._frameRateTime=0; this._emissionTime=0; this._totalDelayTime=0; this._simulateUpdate=false; this._bufferMaxParticles=1; this.duration=5.0; this.looping=true; this.prewarm=false; this.startDelayType=0; this.startDelay=0.0; this.startDelayMin=0.0; this.startDelayMax=0.0; this._startLifetimeType=0; this._startLifetimeConstant=5.0; this._startLifeTimeGradient=new GradientDataNumber(); this._startLifetimeConstantMin=0.0; this._startLifetimeConstantMax=5.0; this._startLifeTimeGradientMin=new GradientDataNumber(); this._startLifeTimeGradientMax=new GradientDataNumber(); this._maxStartLifetime=5.0; this.startSpeedType=0; this.startSpeedConstant=5.0; this.startSpeedConstantMin=0.0; this.startSpeedConstantMax=5.0; this.threeDStartSize=false; this.startSizeType=0; this.startSizeConstant=1; this.startSizeConstantSeparate=new Vector3(1,1,1); this.startSizeConstantMin=0; this.startSizeConstantMax=1; this.startSizeConstantMinSeparate=new Vector3(0,0,0); this.startSizeConstantMaxSeparate=new Vector3(1,1,1); this.threeDStartRotation=false; this.startRotationType=0; this.startRotationConstant=0; this.startRotationConstantSeparate=new Vector3(0,0,0); this.startRotationConstantMin=0.0; this.startRotationConstantMax=0.0; this.startRotationConstantMinSeparate=new Vector3(0,0,0); this.startRotationConstantMaxSeparate=new Vector3(0,0,0); this.randomizeRotationDirection=0.0; this.startColorType=0; this.startColorConstant=new Vector4(1,1,1,1); this.startColorConstantMin=new Vector4(1,1,1,1); this.startColorConstantMax=new Vector4(1,1,1,1); this.gravityModifier=0.0; this.simulationSpace=1; this.scaleMode=0; this.playOnAwake=true; this._rand=new Rand(0); this.autoRandomSeed=true; this.randomSeed=new Uint32Array(1); this._randomSeeds=new Uint32Array(ShurikenParticleSystem._RANDOMOFFSET.length); this.isPerformanceMode=true; this._emission=new Emission(); this._emission.enbale=true; this._owner.on(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onOwnerActiveHierarchyChanged); } __class(ShurikenParticleSystem,'laya.d3.core.particleShuriKen.ShurikenParticleSystem',_super); var __proto=ShurikenParticleSystem.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true,"laya.d3.core.IClone":true}) __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer; else return null; } __proto._getIndexBuffer=function(){ return this._indexBuffer; } /** *@private */ __proto._generateBoundingSphere=function(){ var centerE=this._boundingSphere.center.elements; centerE[0]=0; centerE[1]=0; centerE[2]=0; this._boundingSphere.radius=Number.MAX_VALUE; } /** *@private */ __proto._generateBoundingBox=function(){ var particle=this._owner; var particleRender=particle.particleRender; var boundMin=this._boundingBox.min; var boundMax=this._boundingBox.max; var i=0,n=0; var maxStartLifeTime=NaN; switch (this.startLifetimeType){ case 0: maxStartLifeTime=this.startLifetimeConstant; break ; case 1: maxStartLifeTime=-Number.MAX_VALUE; var startLifeTimeGradient=startLifeTimeGradient; for (i=0,n=startLifeTimeGradient.gradientCount;i < n;i++) maxStartLifeTime=Math.max(maxStartLifeTime,startLifeTimeGradient.getValueByIndex(i)); break ; case 2: maxStartLifeTime=Math.max(this.startLifetimeConstantMin,this.startLifetimeConstantMax); break ; case 3: maxStartLifeTime=-Number.MAX_VALUE; var startLifeTimeGradientMin=startLifeTimeGradientMin; for (i=0,n=startLifeTimeGradientMin.gradientCount;i < n;i++) maxStartLifeTime=Math.max(maxStartLifeTime,startLifeTimeGradientMin.getValueByIndex(i)); var startLifeTimeGradientMax=startLifeTimeGradientMax; for (i=0,n=startLifeTimeGradientMax.gradientCount;i < n;i++) maxStartLifeTime=Math.max(maxStartLifeTime,startLifeTimeGradientMax.getValueByIndex(i)); break ; }; var minStartSpeed=NaN,maxStartSpeed=NaN; switch (this.startSpeedType){ case 0: minStartSpeed=maxStartSpeed=this.startSpeedConstant; break ; case 1: break ; case 2: minStartSpeed=this.startLifetimeConstantMin; maxStartSpeed=this.startLifetimeConstantMax; break ; case 3: break ; }; var minPosition,maxPosition,minDirection,maxDirection; if (this._shape && this._shape.enable){ }else { minPosition=maxPosition=Vector3.ZERO; minDirection=Vector3.ZERO; maxDirection=Vector3.UnitZ; }; var startMinVelocity=new Vector3(minDirection.x *minStartSpeed,minDirection.y *minStartSpeed,minDirection.z *minStartSpeed); var startMaxVelocity=new Vector3(maxDirection.x *maxStartSpeed,maxDirection.y *maxStartSpeed,maxDirection.z *maxStartSpeed); if (this._velocityOverLifetime && this._velocityOverLifetime.enbale){ var lifeMinVelocity; var lifeMaxVelocity; var velocity=this._velocityOverLifetime.velocity; switch (velocity.type){ case 0: lifeMinVelocity=lifeMaxVelocity=velocity.constant; break ; case 1: lifeMinVelocity=lifeMaxVelocity=new Vector3(velocity.gradientX.getAverageValue(),velocity.gradientY.getAverageValue(),velocity.gradientZ.getAverageValue()); break ; case 2: lifeMinVelocity=velocity.constantMin; lifeMaxVelocity=velocity.constantMax; break ; case 3: lifeMinVelocity=new Vector3(velocity.gradientXMin.getAverageValue(),velocity.gradientYMin.getAverageValue(),velocity.gradientZMin.getAverageValue()); lifeMaxVelocity=new Vector3(velocity.gradientXMax.getAverageValue(),velocity.gradientYMax.getAverageValue(),velocity.gradientZMax.getAverageValue()); break ; } }; var positionScale,velocityScale; var transform=this._owner.transform; var worldPosition=transform.position; var sizeScale=ShurikenParticleSystem._tempVector39; var sizeScaleE=sizeScale.elements; var renderMode=particleRender.renderMode; switch (this.scaleMode){ case 0:; var scale=transform.scale; positionScale=scale; sizeScaleE[0]=scale.x; sizeScaleE[1]=scale.z; sizeScaleE[2]=scale.y; (renderMode===1)&& (velocityScale=scale); break ; case 1:; var localScale=transform.localScale; positionScale=localScale; sizeScaleE[0]=localScale.x; sizeScaleE[1]=localScale.z; sizeScaleE[2]=localScale.y; (renderMode===1)&& (velocityScale=localScale); break ; case 2: positionScale=transform.scale; sizeScaleE[0]=sizeScaleE[1]=sizeScaleE[2]=1; (renderMode===1)&& (velocityScale=Vector3.ONE); break ; }; var minStratPosition,maxStratPosition; if (this._velocityOverLifetime && this._velocityOverLifetime.enbale){ }else { minStratPosition=new Vector3(startMinVelocity.x *maxStartLifeTime,startMinVelocity.y *maxStartLifeTime,startMinVelocity.z *maxStartLifeTime); maxStratPosition=new Vector3(startMaxVelocity.x *maxStartLifeTime,startMaxVelocity.y *maxStartLifeTime,startMaxVelocity.z *maxStartLifeTime); if (this.scaleMode !=2){ Vector3.add(minPosition,minStratPosition,boundMin); Vector3.multiply(positionScale,boundMin,boundMin); Vector3.add(maxPosition,maxStratPosition,boundMax); Vector3.multiply(positionScale,boundMax,boundMax); }else { Vector3.multiply(positionScale,minPosition,boundMin); Vector3.add(boundMin,minStratPosition,boundMin); Vector3.multiply(positionScale,maxPosition,boundMax); Vector3.add(boundMax,maxStratPosition,boundMax); } } switch (this.simulationSpace){ case 0: break ; case 1: Vector3.add(boundMin,worldPosition,boundMin); Vector3.add(boundMax,worldPosition,boundMax); break ; }; var maxSize=NaN,maxSizeY=NaN; switch (this.startSizeType){ case 0: if (this.threeDStartSize){ var startSizeConstantSeparate=startSizeConstantSeparate; maxSize=Math.max(startSizeConstantSeparate.x,startSizeConstantSeparate.y); if (renderMode===1) maxSizeY=startSizeConstantSeparate.y; }else { maxSize=this.startSizeConstant; if (renderMode===1) maxSizeY=this.startSizeConstant; } break ; case 1: break ; case 2: if (this.threeDStartSize){ var startSizeConstantMaxSeparate=startSizeConstantMaxSeparate; maxSize=Math.max(startSizeConstantMaxSeparate.x,startSizeConstantMaxSeparate.y); if (renderMode===1) maxSizeY=startSizeConstantMaxSeparate.y; }else { maxSize=this.startSizeConstantMax; if (renderMode===1) maxSizeY=this.startSizeConstantMax; } break ; case 3: break ; } if (this._sizeOverLifetime && this._sizeOverLifetime.enbale){ var size=this._sizeOverLifetime.size; maxSize *=this._sizeOverLifetime.size.getMaxSizeInGradient(); }; var threeDMaxSize=ShurikenParticleSystem._tempVector30; var threeDMaxSizeE=threeDMaxSize.elements; var rotSize=NaN,nonRotSize=NaN; switch (renderMode){ case 0: rotSize=maxSize *ShurikenParticleSystem.halfKSqrtOf2; Vector3.scale(sizeScale,maxSize,threeDMaxSize); Vector3.subtract(boundMin,threeDMaxSize,boundMin); Vector3.add(boundMax,threeDMaxSize,boundMax); break ; case 1:; var maxStretchPosition=ShurikenParticleSystem._tempVector31; var maxStretchVelocity=ShurikenParticleSystem._tempVector32; var minStretchVelocity=ShurikenParticleSystem._tempVector33; var minStretchPosition=ShurikenParticleSystem._tempVector34; if (this._velocityOverLifetime && this._velocityOverLifetime.enbale){ }else { Vector3.multiply(velocityScale,startMaxVelocity,maxStretchVelocity); Vector3.multiply(velocityScale,startMinVelocity,minStretchVelocity); }; var sizeStretch=maxSizeY *particleRender.stretchedBillboardLengthScale; var maxStretchLength=Vector3.scalarLength(maxStretchVelocity)*particleRender.stretchedBillboardSpeedScale+sizeStretch; var minStretchLength=Vector3.scalarLength(minStretchVelocity)*particleRender.stretchedBillboardSpeedScale+sizeStretch; var norMaxStretchVelocity=ShurikenParticleSystem._tempVector35; var norMinStretchVelocity=ShurikenParticleSystem._tempVector36; Vector3.normalize(maxStretchVelocity,norMaxStretchVelocity); Vector3.scale(norMaxStretchVelocity,maxStretchLength,minStretchPosition); Vector3.subtract(maxStratPosition,minStretchPosition,minStretchPosition); Vector3.normalize(minStretchVelocity,norMinStretchVelocity); Vector3.scale(norMinStretchVelocity,minStretchLength,maxStretchPosition); Vector3.add(minStratPosition,maxStretchPosition,maxStretchPosition); rotSize=maxSize *ShurikenParticleSystem.halfKSqrtOf2; Vector3.scale(sizeScale,rotSize,threeDMaxSize); var halfNorMaxStretchVelocity=ShurikenParticleSystem._tempVector37; var halfNorMinStretchVelocity=ShurikenParticleSystem._tempVector38; Vector3.scale(norMaxStretchVelocity,0.5,halfNorMaxStretchVelocity); Vector3.scale(norMinStretchVelocity,0.5,halfNorMinStretchVelocity); Vector3.multiply(halfNorMaxStretchVelocity,sizeScale,halfNorMaxStretchVelocity); Vector3.multiply(halfNorMinStretchVelocity,sizeScale,halfNorMinStretchVelocity); Vector3.add(boundMin,halfNorMinStretchVelocity,boundMin); Vector3.min(boundMin,minStretchPosition,boundMin); Vector3.subtract(boundMin,threeDMaxSize,boundMin); Vector3.subtract(boundMax,halfNorMaxStretchVelocity,boundMax); Vector3.max(boundMax,maxStretchPosition,boundMax); Vector3.add(boundMax,threeDMaxSize,boundMax); break ; case 2: maxSize *=Math.cos(0.78539816339744830961566084581988); nonRotSize=maxSize *0.5; threeDMaxSizeE[0]=sizeScale.x *nonRotSize; threeDMaxSizeE[1]=sizeScale.z *nonRotSize; Vector3.subtract(boundMin,threeDMaxSize,boundMin); Vector3.add(boundMax,threeDMaxSize,boundMax); break ; case 3: maxSize *=Math.cos(0.78539816339744830961566084581988); nonRotSize=maxSize *0.5; Vector3.scale(sizeScale,nonRotSize,threeDMaxSize); Vector3.subtract(boundMin,threeDMaxSize,boundMin); Vector3.add(boundMax,threeDMaxSize,boundMax); break ; } this._boundingBox.getCorners(this._boundingBoxCorners); } /** *@private */ __proto._updateEmission=function(){ if (!Laya.stage.isVisibility||!this.isAlive) return; if (this._simulateUpdate){ this._simulateUpdate=false; } else{ var elapsedTime=(this._startUpdateLoopCount!==Stat.loopCount && !this._isPaused)?Laya.timer.delta / 1000.0:0; elapsedTime=Math.min(ShurikenParticleSystem._maxElapsedTime,elapsedTime); this._updateParticles(elapsedTime); } } /** *@private */ __proto._updateParticles=function(elapsedTime){ if (this._ownerRender.renderMode===4 && !this._ownerRender.mesh) return; this._currentTime+=elapsedTime; this._retireActiveParticles(); this._freeRetiredParticles(); this._totalDelayTime+=elapsedTime; if (this._totalDelayTime < this._playStartDelay){ return; } if (this._emission.enbale&&this._isEmitting &&!this._isPaused) this._advanceTime(elapsedTime,this._currentTime); } /** *@private */ __proto._updateParticlesSimulationRestart=function(time){ this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._burstsIndex=0; this._frameRateTime=time; this._emissionTime=0; this._totalDelayTime=0; this._currentTime=time; var delayTime=time; if (delayTime < this._playStartDelay){ this._totalDelayTime=delayTime; return; } if (this._emission.enbale) this._advanceTime(time,time); } /** *@private */ __proto._addUpdateEmissionToTimer=function(){ Laya.timer.frameLoop(1,this,this._updateEmission); } /** *@private */ __proto._removeUpdateEmissionToTimer=function(){ Laya.timer.clear(this,this._updateEmission); } /** *@private */ __proto._onOwnerActiveHierarchyChanged=function(active){ if (this._owner.displayedInStage){ if (active) this._addUpdateEmissionToTimer(); else this._removeUpdateEmissionToTimer(); } } /** *@private */ __proto._retireActiveParticles=function(){ var epsilon=0.0001; while (this._firstActiveElement !=this._firstNewElement){ var index=this._firstActiveElement *this._floatCountPerVertex *this._vertexStride; var timeIndex=index+this._timeIndex; var particleAge=this._currentTime-this._vertices[timeIndex]; if (particleAge+epsilon < this._vertices[index+this._startLifeTimeIndex]) break ; this._vertices[timeIndex]=this._drawCounter; this._firstActiveElement++; if (this._firstActiveElement >=this._bufferMaxParticles) this._firstActiveElement=0; } } /** *@private */ __proto._freeRetiredParticles=function(){ while (this._firstRetiredElement !=this._firstActiveElement){ var age=this._drawCounter-this._vertices[this._firstRetiredElement *this._floatCountPerVertex *this._vertexStride+this._timeIndex]; if (this.isPerformanceMode) if (age < 3) break ; this._firstRetiredElement++; if (this._firstRetiredElement >=this._bufferMaxParticles) this._firstRetiredElement=0; } } /** *@private */ __proto._burst=function(fromTime,toTime){ var totalEmitCount=0; var bursts=this._emission._bursts; for (var n=bursts.length;this._burstsIndex < n;this._burstsIndex++){ var burst=bursts[this._burstsIndex]; var burstTime=burst.time; if (fromTime<=burstTime && burstTime < toTime){ var emitCount=0; if (this.autoRandomSeed){ emitCount=MathUtil.lerp(burst.minCount,burst.maxCount,Math.random()); }else { this._rand.seed=this._randomSeeds[0]; emitCount=MathUtil.lerp(burst.minCount,burst.maxCount,this._rand.getFloat()); this._randomSeeds[0]=this._rand.seed; } totalEmitCount+=emitCount; }else { break ; } } return totalEmitCount; } /** *@private */ __proto._advanceTime=function(elapsedTime,emitTime){ var i=0; var lastEmissionTime=this._emissionTime; this._emissionTime+=elapsedTime; var totalEmitCount=0; if (this._emissionTime > this.duration){ if (this.looping){ totalEmitCount+=this._burst(lastEmissionTime,this._emissionTime); this._emissionTime-=this.duration; this.event(/*laya.events.Event.COMPLETE*/"complete"); this._burstsIndex=0; totalEmitCount+=this._burst(0,this._emissionTime); }else { totalEmitCount=Math.min(this.maxParticles-this.aliveParticleCount,totalEmitCount); for (i=0;i < totalEmitCount;i++) this.emit(emitTime); this._isPlaying=false; this.stop(); return; } }else { totalEmitCount+=this._burst(lastEmissionTime,this._emissionTime); } totalEmitCount=Math.min(this.maxParticles-this.aliveParticleCount,totalEmitCount); for (i=0;i < totalEmitCount;i++) this.emit(emitTime); var emissionRate=this.emission.emissionRate; if (emissionRate>0){ var minEmissionTime=1/emissionRate; this._frameRateTime+=minEmissionTime; this._frameRateTime=this._currentTime-(this._currentTime-this._frameRateTime)% this._maxStartLifetime; while (this._frameRateTime <=emitTime){ if (this.emit(this._frameRateTime)) this._frameRateTime+=minEmissionTime; else break ; } this._frameRateTime=Math.floor(emitTime / minEmissionTime)*minEmissionTime; } } /** *@private */ __proto._initBufferDatas=function(){ if (this._vertexBuffer){ this._vertexBuffer.destroy(); this._indexBuffer.destroy(); }; var render=this._ownerRender; var renderMode=render.renderMode; if (renderMode!==-1 && this.maxParticles > 0){ var indices,i=0,j=0,m=0,indexOffset=0,perPartOffset=0,vertexDeclaration;; var mesh=render.mesh; if (renderMode===4){ if(mesh){ var vertexBufferCount=mesh._vertexBuffers.length; if (vertexBufferCount > 1){ throw new Error("ShurikenParticleSystem: submesh Count mesh be One or all subMeshes have the same vertexDeclaration."); }else { vertexDeclaration=VertexShurikenParticleMesh.vertexDeclaration; this._floatCountPerVertex=vertexDeclaration.vertexStride/4; this._startLifeTimeIndex=12; this._timeIndex=16; this._vertexStride=mesh._vertexBuffers[0].vertexCount; var totalVertexCount=this._bufferMaxParticles *this._vertexStride; var vbCount=Math.floor(totalVertexCount / 65535)+1; var lastVBVertexCount=totalVertexCount % 65535; if (vbCount > 1){ throw new Error("ShurikenParticleSystem:the maxParticleCount multiply mesh vertexCount is large than 65535."); } this._vertexBuffer=VertexBuffer3D.create(vertexDeclaration,lastVBVertexCount,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._vertices=new Float32Array(this._floatCountPerVertex *lastVBVertexCount); this._indexStride=mesh._indexBuffer.indexCount; var indexDatas=mesh._indexBuffer.getData(); var indexCount=this._bufferMaxParticles *this._indexStride; this._indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",indexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); indices=new Uint16Array(indexCount); indexOffset=0; for (i=0;i < this._bufferMaxParticles;i++){ var indexValueOffset=i *this._vertexStride; for (j=0,m=indexDatas.length;j < m;j++) indices[indexOffset++]=indexValueOffset+indexDatas[j]; } this._indexBuffer.setData(indices); } } }else { vertexDeclaration=VertexShurikenParticleBillboard.vertexDeclaration; this._floatCountPerVertex=vertexDeclaration.vertexStride/4; this._startLifeTimeIndex=7; this._timeIndex=11; this._vertexStride=4; this._vertexBuffer=VertexBuffer3D.create(vertexDeclaration,this._bufferMaxParticles *this._vertexStride,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._vertices=new Float32Array(this._floatCountPerVertex *this._bufferMaxParticles *this._vertexStride); for (i=0;i < this._bufferMaxParticles;i++){ perPartOffset=i *this._floatCountPerVertex *this._vertexStride; this._vertices[perPartOffset]=-0.5; this._vertices[perPartOffset+1]=-0.5; this._vertices[perPartOffset+2]=0; this._vertices[perPartOffset+3]=1; perPartOffset+=this._floatCountPerVertex; this._vertices[perPartOffset]=0.5; this._vertices[perPartOffset+1]=-0.5; this._vertices[perPartOffset+2]=1; this._vertices[perPartOffset+3]=1; perPartOffset+=this._floatCountPerVertex this._vertices[perPartOffset]=0.5; this._vertices[perPartOffset+1]=0.5; this._vertices[perPartOffset+2]=1; this._vertices[perPartOffset+3]=0; perPartOffset+=this._floatCountPerVertex this._vertices[perPartOffset]=-0.5; this._vertices[perPartOffset+1]=0.5; this._vertices[perPartOffset+2]=0; this._vertices[perPartOffset+3]=0; } this._indexStride=6; this._indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._bufferMaxParticles *6,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); indices=new Uint16Array(this._bufferMaxParticles *6); for (i=0;i < this._bufferMaxParticles;i++){ indexOffset=i *6; var firstVertex=i *this._vertexStride,secondVertex=firstVertex+2; indices[indexOffset++]=firstVertex; indices[indexOffset++]=secondVertex; indices[indexOffset++]=firstVertex+1; indices[indexOffset++]=firstVertex; indices[indexOffset++]=firstVertex+3; indices[indexOffset++]=secondVertex; } this._indexBuffer.setData(indices); } } } /** *@private */ __proto._destroy=function(){ _super.prototype._destroy.call(this); (this._owner.activeInHierarchy)&& (this._removeUpdateEmissionToTimer()); this._vertexBuffer.destroy(); this._indexBuffer.destroy(); this._emission._destroy(); this._owner=null; this._vertices=null; this._vertexBuffer=null; this._indexBuffer=null; this._emission=null; this._shape=null; this.startLifeTimeGradient=null; this.startLifeTimeGradientMin=null; this.startLifeTimeGradientMax=null; this.startSizeConstantSeparate=null; this.startSizeConstantMinSeparate=null; this.startSizeConstantMaxSeparate=null; this.startRotationConstantSeparate=null; this.startRotationConstantMinSeparate=null; this.startRotationConstantMaxSeparate=null; this.startColorConstant=null; this.startColorConstantMin=null; this.startColorConstantMax=null; this._velocityOverLifetime=null; this._colorOverLifetime=null; this._sizeOverLifetime=null; this._rotationOverLifetime=null; this._textureSheetAnimation=null; } /** *发射一个粒子。 */ __proto.emit=function(time){ var position=ShurikenParticleSystem._tempPosition; var direction=ShurikenParticleSystem._tempDirection; if (this._shape&&this._shape.enable){ if (this.autoRandomSeed) this._shape.generatePositionAndDirection(position,direction); else this._shape.generatePositionAndDirection(position,direction,this._rand,this._randomSeeds); }else { var positionE=position.elements; var directionE=direction.elements; positionE[0]=positionE[1]=positionE[2]=0; directionE[0]=directionE[1]=0; directionE[2]=1; } return this.addParticle(position,direction,time); } //TODO:提前判断优化 __proto.addParticle=function(position,direction,time){ Vector3.normalize(direction,direction); var nextFreeParticle=this._firstFreeElement+1; if (nextFreeParticle >=this._bufferMaxParticles) nextFreeParticle=0; if (nextFreeParticle===this._firstRetiredElement) return false; ShurikenParticleData.create(this,this._ownerRender,this._owner.transform); var particleAge=this._currentTime-time; if (particleAge >=ShurikenParticleData.startLifeTime) return true; var randomVelocityX=NaN,randomVelocityY=NaN,randomVelocityZ=NaN,randomColor=NaN,randomSize=NaN,randomRotation=NaN,randomTextureAnimation=NaN; var needRandomVelocity=this._velocityOverLifetime && this._velocityOverLifetime.enbale; if (needRandomVelocity){ var velocityType=this._velocityOverLifetime.velocity.type; if (velocityType===2 || velocityType===3){ if (this.autoRandomSeed){ randomVelocityX=Math.random(); randomVelocityY=Math.random(); randomVelocityZ=Math.random(); }else { this._rand.seed=this._randomSeeds[9]; randomVelocityX=this._rand.getFloat(); randomVelocityY=this._rand.getFloat(); randomVelocityZ=this._rand.getFloat(); this._randomSeeds[9]=this._rand.seed; } }else { needRandomVelocity=false; } }else { needRandomVelocity=false; }; var needRandomColor=this._colorOverLifetime && this._colorOverLifetime.enbale; if (needRandomColor){ var colorType=this._colorOverLifetime.color.type; if (colorType===3){ if (this.autoRandomSeed){ randomColor=Math.random(); }else { this._rand.seed=this._randomSeeds[10]; randomColor=this._rand.getFloat(); this._randomSeeds[10]=this._rand.seed; } }else { needRandomColor=false; } }else { needRandomColor=false; }; var needRandomSize=this._sizeOverLifetime && this._sizeOverLifetime.enbale; if (needRandomSize){ var sizeType=this._sizeOverLifetime.size.type; if (sizeType===3){ if (this.autoRandomSeed){ randomSize=Math.random(); }else { this._rand.seed=this._randomSeeds[11]; randomSize=this._rand.getFloat(); this._randomSeeds[11]=this._rand.seed; } }else { needRandomSize=false; } }else { needRandomSize=false; }; var needRandomRotation=this._rotationOverLifetime && this._rotationOverLifetime.enbale; if (needRandomRotation){ var rotationType=this._rotationOverLifetime.angularVelocity.type; if (rotationType===2 || rotationType===3){ if (this.autoRandomSeed){ randomRotation=Math.random(); }else { this._rand.seed=this._randomSeeds[12]; randomRotation=this._rand.getFloat(); this._randomSeeds[12]=this._rand.seed; } }else { needRandomRotation=false; } }else { needRandomRotation=false; }; var needRandomTextureAnimation=this._textureSheetAnimation && this._textureSheetAnimation.enable; if (needRandomTextureAnimation){ var textureAnimationType=this._textureSheetAnimation.frame.type; if (textureAnimationType===3){ if (this.autoRandomSeed){ randomTextureAnimation=Math.random(); }else { this._rand.seed=this._randomSeeds[15]; randomTextureAnimation=this._rand.getFloat(); this._randomSeeds[15]=this._rand.seed; } }else { needRandomTextureAnimation=false; } }else { needRandomTextureAnimation=false; }; var startIndex=this._firstFreeElement *this._floatCountPerVertex *this._vertexStride; var subU=ShurikenParticleData.startUVInfo[0]; var subV=ShurikenParticleData.startUVInfo[1]; var startU=ShurikenParticleData.startUVInfo[2]; var startV=ShurikenParticleData.startUVInfo[3]; var positionE=position.elements; var directionE=direction.elements; var meshVertices,meshVertexStride=0,meshPosOffset=0,meshCorOffset=0,meshUVOffset=0,meshVertexIndex=0; var render=this._ownerRender; if (render.renderMode===4){ var meshVB=render.mesh._vertexBuffers[0]; meshVertices=meshVB.getData(); var meshVertexDeclaration=meshVB.vertexDeclaration; meshPosOffset=meshVertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.POSITION0*/0).offset / 4; var colorElement=meshVertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.COLOR0*/1); meshCorOffset=colorElement?colorElement.offset / 4:-1; var uvElement=meshVertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2); meshUVOffset=uvElement?uvElement.offset / 4:-1; meshVertexStride=meshVertexDeclaration.vertexStride / 4; meshVertexIndex=0; }else { this._vertices[startIndex+2]=startU; this._vertices[startIndex+3]=startV+subV; var secondOffset=startIndex+this._floatCountPerVertex; this._vertices[secondOffset+2]=startU+subU; this._vertices[secondOffset+3]=startV+subV; var thirdOffset=secondOffset+this._floatCountPerVertex; this._vertices[thirdOffset+2]=startU+subU; this._vertices[thirdOffset+3]=startV; var fourthOffset=thirdOffset+this._floatCountPerVertex; this._vertices[fourthOffset+2]=startU; this._vertices[fourthOffset+3]=startV; } for (var i=startIndex,n=startIndex+this._floatCountPerVertex *this._vertexStride;i < n;i+=this._floatCountPerVertex){ var offset=0; if (render.renderMode===4){ offset=i; var vertexOffset=meshVertexStride *(meshVertexIndex++); var meshOffset=vertexOffset+meshPosOffset; this._vertices[offset++]=meshVertices[meshOffset++]; this._vertices[offset++]=meshVertices[meshOffset++]; this._vertices[offset++]=meshVertices[meshOffset]; if (meshCorOffset===-1){ this._vertices[offset++]=1.0; this._vertices[offset++]=1.0; this._vertices[offset++]=1.0; this._vertices[offset++]=1.0; } else{ meshOffset=vertexOffset+meshCorOffset; this._vertices[offset++]=meshVertices[meshOffset++]; this._vertices[offset++]=meshVertices[meshOffset++]; this._vertices[offset++]=meshVertices[meshOffset++]; this._vertices[offset++]=meshVertices[meshOffset]; } if (meshUVOffset===-1){ this._vertices[offset++]=0.0; this._vertices[offset++]=0.0; } else{ meshOffset=vertexOffset+meshUVOffset; this._vertices[offset++]=startU+meshVertices[meshOffset++] *subU; this._vertices[offset++]=startV+meshVertices[meshOffset] *subV; } }else { offset=i+4; } this._vertices[offset++]=positionE[0]; this._vertices[offset++]=positionE[1]; this._vertices[offset++]=positionE[2]; this._vertices[offset++]=ShurikenParticleData.startLifeTime; this._vertices[offset++]=directionE[0]; this._vertices[offset++]=directionE[1]; this._vertices[offset++]=directionE[2]; this._vertices[offset++]=time; this._vertices[offset++]=ShurikenParticleData.startColor[0]; this._vertices[offset++]=ShurikenParticleData.startColor[1]; this._vertices[offset++]=ShurikenParticleData.startColor[2]; this._vertices[offset++]=ShurikenParticleData.startColor[3]; this._vertices[offset++]=ShurikenParticleData.startSize[0]; this._vertices[offset++]=ShurikenParticleData.startSize[1]; this._vertices[offset++]=ShurikenParticleData.startSize[2]; this._vertices[offset++]=ShurikenParticleData.startRotation[0]; this._vertices[offset++]=ShurikenParticleData.startRotation[1]; this._vertices[offset++]=ShurikenParticleData.startRotation[2]; this._vertices[offset++]=ShurikenParticleData.startSpeed; needRandomColor && (this._vertices[offset+1]=randomColor); needRandomSize && (this._vertices[offset+2]=randomSize); needRandomRotation && (this._vertices[offset+3]=randomRotation); needRandomTextureAnimation && (this._vertices[offset+4]=randomTextureAnimation); if (needRandomVelocity){ this._vertices[offset+5]=randomVelocityX; this._vertices[offset+6]=randomVelocityY; this._vertices[offset+7]=randomVelocityZ; } switch(this.simulationSpace){ case 0: offset+=8; this._vertices[offset++]=ShurikenParticleData.simulationWorldPostion[0]; this._vertices[offset++]=ShurikenParticleData.simulationWorldPostion[1]; this._vertices[offset++]=ShurikenParticleData.simulationWorldPostion[2]; this._vertices[offset++]=ShurikenParticleData.simulationWorldRotation[0]; this._vertices[offset++]=ShurikenParticleData.simulationWorldRotation[1]; this._vertices[offset++]=ShurikenParticleData.simulationWorldRotation[2]; this._vertices[offset++]=ShurikenParticleData.simulationWorldRotation[3]; break ; case 1: break ; default : throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid."); } } this._firstFreeElement=nextFreeParticle; return true; } __proto.addNewParticlesToVertexBuffer=function(){ var start=0; if (this._firstNewElement < this._firstFreeElement){ start=this._firstNewElement *this._vertexStride *this._floatCountPerVertex; this._vertexBuffer.setData(this._vertices,start,start,(this._firstFreeElement-this._firstNewElement)*this._vertexStride *this._floatCountPerVertex); }else { start=this._firstNewElement *this._vertexStride *this._floatCountPerVertex; this._vertexBuffer.setData(this._vertices,start,start,(this._bufferMaxParticles-this._firstNewElement)*this._vertexStride *this._floatCountPerVertex); if (this._firstFreeElement > 0){ this._vertexBuffer.setData(this._vertices,0,0,this._firstFreeElement *this._vertexStride *this._floatCountPerVertex); } } this._firstNewElement=this._firstFreeElement; } __proto._beforeRender=function(state){ if (this._firstNewElement !=this._firstFreeElement) this.addNewParticlesToVertexBuffer(); this._drawCounter++; if (this._firstActiveElement !=this._firstFreeElement){ this._vertexBuffer._bind(); this._indexBuffer._bind(); return true; } return false; } /** *@private */ __proto._render=function(state){ var indexCount=0; var gl=WebGL.mainContext; if (this._firstActiveElement < this._firstFreeElement){ indexCount=(this._firstFreeElement-this._firstActiveElement)*this._indexStride; gl.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,2 *this._firstActiveElement *this._indexStride); Stat.trianglesFaces+=indexCount / 3; Stat.drawCall++; }else { indexCount=(this._bufferMaxParticles-this._firstActiveElement)*this._indexStride; gl.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,2 *this._firstActiveElement *this._indexStride); Stat.trianglesFaces+=indexCount / 3; Stat.drawCall++; if (this._firstFreeElement > 0){ indexCount=this._firstFreeElement *this._indexStride; gl.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.trianglesFaces+=indexCount / 3; Stat.drawCall++; } } } /** *开始发射粒子。 */ __proto.play=function(){ this._burstsIndex=0; this._isEmitting=true; this._isPlaying=true; this._isPaused=false; this._emissionTime=0; this._totalDelayTime=0; if (!this.autoRandomSeed){ for (var i=0,n=this._randomSeeds.length;i < n;i++) this._randomSeeds[i]=this.randomSeed[0]+ShurikenParticleSystem._RANDOMOFFSET[i]; } switch (this.startDelayType){ case 0: this._playStartDelay=this.startDelay; break ; case 1: if (this.autoRandomSeed){ this._playStartDelay=MathUtil.lerp(this.startDelayMin,this.startDelayMax,Math.random()); }else { this._rand.seed=this._randomSeeds[2]; this._playStartDelay=MathUtil.lerp(this.startDelayMin,this.startDelayMax,this._rand.getFloat()); this._randomSeeds[2]=this._rand.seed; } break ; default : throw new Error("Utils3D: startDelayType is invalid."); } this._frameRateTime=this._currentTime+this._playStartDelay; this._startUpdateLoopCount=Stat.loopCount; this.event(/*laya.events.Event.PLAYED*/"played"); } /** *暂停发射粒子。 */ __proto.pause=function(){ this._isPaused=true; this.event(/*laya.events.Event.PAUSED*/"paused"); } /** *通过指定时间增加粒子播放进度,并暂停播放。 *@param time 进度时间.如果restart为true,粒子播放时间会归零后再更新进度。 *@param restart 是否重置播放状态。 */ __proto.simulate=function(time,restart){ (restart===void 0)&& (restart=true); this._simulateUpdate=true; if (restart){ this._updateParticlesSimulationRestart(time); } else{ this._isPaused=false; this._updateParticles(time); } this.pause(); } /** *停止发射粒子。 */ __proto.stop=function(){ this._burstsIndex=0; this._isEmitting=false; this._emissionTime=0; this.event(/*laya.events.Event.STOPPED*/"stopped"); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var dest=destObject; dest.duration=this.duration; dest.looping=this.looping; dest.prewarm=this.prewarm; dest.startDelayType=this.startDelayType; dest.startDelay=this.startDelay; dest.startDelayMin=this.startDelayMin; dest.startDelayMax=this.startDelayMax; dest._maxStartLifetime=this._maxStartLifetime; dest.startLifetimeType=this.startLifetimeType; dest.startLifetimeConstant=this.startLifetimeConstant; this.startLifeTimeGradient.cloneTo(dest.startLifeTimeGradient); dest.startLifetimeConstantMin=this.startLifetimeConstantMin; dest.startLifetimeConstantMax=this.startLifetimeConstantMax; this.startLifeTimeGradientMin.cloneTo(dest.startLifeTimeGradientMin); this.startLifeTimeGradientMax.cloneTo(dest.startLifeTimeGradientMax); dest.startSpeedType=this.startSpeedType; dest.startSpeedConstant=this.startSpeedConstant; dest.startSpeedConstantMin=this.startSpeedConstantMin; dest.startSpeedConstantMax=this.startSpeedConstantMax; dest.threeDStartSize=this.threeDStartSize; dest.startSizeType=this.startSizeType; dest.startSizeConstant=this.startSizeConstant; this.startSizeConstantSeparate.cloneTo(dest.startSizeConstantSeparate); dest.startSizeConstantMin=this.startSizeConstantMin; dest.startSizeConstantMax=this.startSizeConstantMax; this.startSizeConstantMinSeparate.cloneTo(dest.startSizeConstantMinSeparate); this.startSizeConstantMaxSeparate.cloneTo(dest.startSizeConstantMaxSeparate); dest.threeDStartRotation=this.threeDStartRotation; dest.startRotationType=this.startRotationType; dest.startRotationConstant=this.startRotationConstant; this.startRotationConstantSeparate.cloneTo(dest.startRotationConstantSeparate); dest.startRotationConstantMin=this.startRotationConstantMin; dest.startRotationConstantMax=this.startRotationConstantMax; this.startRotationConstantMinSeparate.cloneTo(dest.startRotationConstantMinSeparate); this.startRotationConstantMaxSeparate.cloneTo(dest.startRotationConstantMaxSeparate); dest.randomizeRotationDirection=this.randomizeRotationDirection; dest.startColorType=this.startColorType; this.startColorConstant.cloneTo(dest.startColorConstant); this.startColorConstantMin.cloneTo(dest.startColorConstantMin); this.startColorConstantMax.cloneTo(dest.startColorConstantMax); dest.gravityModifier=this.gravityModifier; dest.simulationSpace=this.simulationSpace; dest.scaleMode=this.scaleMode; dest.playOnAwake=this.playOnAwake; dest.maxParticles=this.maxParticles; (this._emission)&& (dest._emission=this._emission.clone()); (this.shape)&& (dest.shape=this.shape.clone()); (this.velocityOverLifetime)&& (dest.velocityOverLifetime=this.velocityOverLifetime.clone()); (this.colorOverLifetime)&& (dest.colorOverLifetime=this.colorOverLifetime.clone()); (this.sizeOverLifetime)&& (dest.sizeOverLifetime=this.sizeOverLifetime.clone()); (this.rotationOverLifetime)&& (dest.rotationOverLifetime=this.rotationOverLifetime.clone()); (this.textureSheetAnimation)&& (dest.textureSheetAnimation=this.textureSheetAnimation.clone()); dest.isPerformanceMode=this.isPerformanceMode; dest._isEmitting=this._isEmitting; dest._isPlaying=this._isPlaying; dest._isPaused=this._isPaused; dest._playStartDelay=this._playStartDelay; dest._frameRateTime=this._frameRateTime; dest._emissionTime=this._emissionTime; dest._totalDelayTime=this._totalDelayTime; dest._burstsIndex=this._burstsIndex; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } /** *@private */ __proto._getVertexBuffers=function(){ return null; } /**设置最大粒子数,注意:谨慎修改此属性,有性能损耗。*/ /**获取最大粒子数。*/ __getset(0,__proto,'maxParticles',function(){ return this._bufferMaxParticles-1; },function(value){ var newMaxParticles=value+1; if (newMaxParticles!==this._bufferMaxParticles){ this._bufferMaxParticles=newMaxParticles; this._initBufferDatas(); } }); /** *是否正在发射。 */ __getset(0,__proto,'isEmitting',function(){ return this._isEmitting; }); /** *是否存活。 */ __getset(0,__proto,'isAlive',function(){ if (this._isPlaying || this.aliveParticleCount > 0) return true; return false; }); /** *设置形状。 */ /** *获取形状。 */ __getset(0,__proto,'shape',function(){ return this._shape; },function(value){ if (this._shape!==value){ if (value&&value.enable) this._ownerRender._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SHAPE); else this._ownerRender._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SHAPE); this._shape=value; } }); /** *设置生命周期旋转,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@param value 生命周期旋转。 */ /** *获取生命周期旋转,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@return 生命周期旋转。 */ __getset(0,__proto,'rotationOverLifetime',function(){ return this._rotationOverLifetime; },function(value){ var render=this._ownerRender; if (value){ var rotation=value.angularVelocity; if (!rotation) return; var rotationSeparate=rotation.separateAxes; var rotationType=rotation.type; if (value.enbale){ if (rotationSeparate) render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE); else render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME); switch (rotationType){ case 0: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT); break ; case 1: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE); break ; case 2: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS); break ; case 3: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES); } switch (rotationType){ case 0: if (rotationSeparate){ render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTSEPRARATE*/35,rotation.constantSeparate); }else { render._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONST*/34,rotation.constant); } break ; case 1: if (rotationSeparate){ render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTX*/37,rotation.gradientX._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTY*/38,rotation.gradientY._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZ*/39,rotation.gradientZ._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTW*/40,rotation.gradientW._elements); }else { render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENT*/36,rotation.gradient._elements); } break ; case 2: if (rotationSeparate){ render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTSEPRARATE*/35,rotation.constantMinSeparate); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAXSEPRARATE*/42,rotation.constantMaxSeparate); }else { render._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONST*/34,rotation.constantMin); render._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAX*/41,rotation.constantMax); } break ; case 3: if (rotationSeparate){ render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTX*/37,rotation.gradientXMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTXMAX*/44,rotation.gradientXMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTY*/38,rotation.gradientYMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTYMAX*/45,rotation.gradientYMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZ*/39,rotation.gradientZMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZMAX*/46,rotation.gradientZMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTW*/40,rotation.gradientWMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTWMAX*/47,rotation.gradientWMax._elements); }else { render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENT*/36,rotation.gradientMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTMAX*/43,rotation.gradientMax._elements); } break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTSEPRARATE*/35,null); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAXSEPRARATE*/42,null); render._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONST*/34,undefined); render._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAX*/41,undefined); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTX*/37,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTXMAX*/44,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTY*/38,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTYMAX*/45,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZ*/39,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZMAX*/46,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTW*/40,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTWMAX*/47,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENT*/36,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTMAX*/43,null); } this._rotationOverLifetime=value; }); /** *获取发射器。 */ __getset(0,__proto,'emission',function(){ return this._emission; }); /** *获取一次循环内的累计时间。 *@return 一次循环内的累计时间。 */ __getset(0,__proto,'emissionTime',function(){ return this._emissionTime > this.duration ? this.duration :this._emissionTime; }); /** *粒子存活个数。 */ __getset(0,__proto,'aliveParticleCount',function(){ if (this._firstNewElement >=this._firstRetiredElement) return this._firstNewElement-this._firstRetiredElement; else return this._bufferMaxParticles-this._firstRetiredElement+this._firstNewElement; }); /** *是否正在播放。 */ __getset(0,__proto,'isPlaying',function(){ return this._isPlaying; }); /** *是否已暂停。 */ __getset(0,__proto,'isPaused',function(){ return this._isPaused; }); /** *设置开始生命周期模式,0为固定时间,1为渐变时间,2为两个固定之间的随机插值,3为两个渐变时间的随机插值。 */ /** *获取开始生命周期模式,0为固定时间,1为渐变时间,2为两个固定之间的随机插值,3为两个渐变时间的随机插值。 */ __getset(0,__proto,'startLifetimeType',function(){ return this._startLifetimeType; },function(value){ var i=0,n=0; switch (this.startLifetimeType){ case 0: this._maxStartLifetime=this.startLifetimeConstant; break ; case 1: this._maxStartLifetime=-Number.MAX_VALUE; var startLifeTimeGradient=startLifeTimeGradient; for (i=0,n=startLifeTimeGradient.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,startLifeTimeGradient.getValueByIndex(i)); break ; case 2: this._maxStartLifetime=Math.max(this.startLifetimeConstantMin,this.startLifetimeConstantMax); break ; case 3: this._maxStartLifetime=-Number.MAX_VALUE; var startLifeTimeGradientMin=startLifeTimeGradientMin; for (i=0,n=startLifeTimeGradientMin.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,startLifeTimeGradientMin.getValueByIndex(i)); var startLifeTimeGradientMax=startLifeTimeGradientMax; for (i=0,n=startLifeTimeGradientMax.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,startLifeTimeGradientMax.getValueByIndex(i)); break ; } this._startLifetimeType=value; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingSphere',function(){ return this._boundingSphere; }); /** *设置开始生命周期,0模式,单位为秒。 */ /** *获取开始生命周期,0模式,单位为秒。 */ __getset(0,__proto,'startLifetimeConstant',function(){ return this._startLifetimeConstant; },function(value){ if(this._startLifetimeType===0) this._maxStartLifetime=value; this._startLifetimeConstant=value; }); /** *设置最小开始生命周期,2模式,单位为秒。 */ /** *获取最小开始生命周期,2模式,单位为秒。 */ __getset(0,__proto,'startLifetimeConstantMin',function(){ return this._startLifetimeConstantMin; },function(value){ if (this._startLifetimeType===2) this._maxStartLifetime=Math.max(value,this._startLifetimeConstantMax); this._startLifetimeConstantMin=value; }); /** *设置开始渐变生命周期,1模式,单位为秒。 */ /** *获取开始渐变生命周期,1模式,单位为秒。 */ __getset(0,__proto,'startLifeTimeGradient',function(){ return this._startLifeTimeGradient; },function(value){ if (this._startLifetimeType===1){ this._maxStartLifetime=-Number.MAX_VALUE; for (var i=0,n=value.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,value.getValueByIndex(i)); } this._startLifeTimeGradient=value; }); /** *设置最大开始生命周期,2模式,单位为秒。 */ /** *获取最大开始生命周期,2模式,单位为秒。 */ __getset(0,__proto,'startLifetimeConstantMax',function(){ return this._startLifetimeConstantMax; },function(value){ if (this._startLifetimeType===2) this._maxStartLifetime=Math.max(this._startLifetimeConstantMin,value); this._startLifetimeConstantMax=value; }); /** *设置开始渐变最小生命周期,3模式,单位为秒。 */ /** *获取开始渐变最小生命周期,3模式,单位为秒。 */ __getset(0,__proto,'startLifeTimeGradientMin',function(){ return this._startLifeTimeGradientMin; },function(value){ if (this._startLifetimeType===3){ var i=0,n=0; this._maxStartLifetime=-Number.MAX_VALUE; for (i=0,n=value.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,value.getValueByIndex(i)); for (i=0,n=this._startLifeTimeGradientMax.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,this._startLifeTimeGradientMax.getValueByIndex(i)); } this._startLifeTimeGradientMin=value; }); /** *设置开始渐变最大生命周期,3模式,单位为秒。 */ /** *获取开始渐变最大生命周期,3模式,单位为秒。 */ __getset(0,__proto,'startLifeTimeGradientMax',function(){ return this._startLifeTimeGradientMax; },function(value){ if (this._startLifetimeType===3){ var i=0,n=0; this._maxStartLifetime=-Number.MAX_VALUE; for (i=0,n=this._startLifeTimeGradientMin.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,this._startLifeTimeGradientMin.getValueByIndex(i)); for (i=0,n=value.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,value.getValueByIndex(i)); } this._startLifeTimeGradientMax=value; }); /** *设置生命周期速度,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@param value 生命周期速度. */ /** *获取生命周期速度,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@return 生命周期速度. */ __getset(0,__proto,'velocityOverLifetime',function(){ return this._velocityOverLifetime; },function(value){ var render=this._ownerRender; if (value){ var velocity=value.velocity; var velocityType=velocity.type; if (value.enbale){ switch (velocityType){ case 0: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT); break ; case 1: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE); break ; case 2: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT); break ; case 3: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE); } switch (velocityType){ case 0: render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONST*/13,velocity.constant); break ; case 1: render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTX*/14,velocity.gradientX._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTY*/15,velocity.gradientY._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZ*/16,velocity.gradientZ._elements); break ; case 2: render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONST*/13,velocity.constantMin); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONSTMAX*/17,velocity.constantMax); break ; case 3: render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTX*/14,velocity.gradientXMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTXMAX*/18,velocity.gradientXMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTY*/15,velocity.gradientYMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTYMAX*/19,velocity.gradientYMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZ*/16,velocity.gradientZMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZMAX*/20,velocity.gradientZMax._elements); break ; } render._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLSPACETYPE*/21,value.space); }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONST*/13,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTX*/14,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTY*/15,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZ*/16,null); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONST*/13,null); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONSTMAX*/17,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTX*/14,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTXMAX*/18,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTY*/15,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTYMAX*/19,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZ*/16,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZMAX*/20,null); render._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLSPACETYPE*/21,undefined); } this._velocityOverLifetime=value; }); /** *设置生命周期颜色,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@param value 生命周期颜色 */ /** *获取生命周期颜色,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@return 生命周期颜色 */ __getset(0,__proto,'colorOverLifetime',function(){ return this._colorOverLifetime; },function(value){ var render=this._ownerRender; if (value){ var color=value.color; if (value.enbale){ switch (color.type){ case 1: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME); break ; case 3: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME); } switch (color.type){ case 1:; var gradientColor=color.gradient; render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS*/22,gradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS*/23,gradientColor._rgbElements); break ; case 3:; var minGradientColor=color.gradientMin; var maxGradientColor=color.gradientMax; render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS*/22,minGradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS*/23,minGradientColor._rgbElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTALPHAS*/24,maxGradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTCOLORS*/25,maxGradientColor._rgbElements); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS*/22,gradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS*/23,gradientColor._rgbElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS*/22,minGradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS*/23,minGradientColor._rgbElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTALPHAS*/24,maxGradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTCOLORS*/25,maxGradientColor._rgbElements); } this._colorOverLifetime=value; }); /** *设置生命周期尺寸,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@param value 生命周期尺寸 */ /** *获取生命周期尺寸,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@return 生命周期尺寸 */ __getset(0,__proto,'sizeOverLifetime',function(){ return this._sizeOverLifetime; },function(value){ var render=this._ownerRender; if (value){ var size=value.size; var sizeSeparate=size.separateAxes; var sizeType=size.type; if (value.enbale){ switch (sizeType){ case 0: if (sizeSeparate) render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE); else render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE); break ; case 2: if (sizeSeparate) render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE); else render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE); } switch (sizeType){ case 0: if (sizeSeparate){ render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTX*/27,size.gradientX._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTY*/28,size.gradientY._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZ*/29,size.gradientZ._elements); }else { render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENT*/26,size.gradient._elements); } break ; case 2: if (sizeSeparate){ render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTX*/27,size.gradientXMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTXMAX*/31,size.gradientXMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTY*/28,size.gradientYMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTYMAX*/32,size.gradientYMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZ*/29,size.gradientZMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZMAX*/33,size.gradientZMax._elements); }else { render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENT*/26,size.gradientMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientMax*/30,size.gradientMax._elements); } break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTX*/27,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTXMAX*/31,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTY*/28,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTYMAX*/32,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZ*/29,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZMAX*/33,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENT*/26,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientMax*/30,null); } this._sizeOverLifetime=value; }); /** *设置生命周期纹理动画,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@param value 生命周期纹理动画。 */ /** *获取生命周期纹理动画,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@return 生命周期纹理动画。 */ __getset(0,__proto,'textureSheetAnimation',function(){ return this._textureSheetAnimation; },function(value){ var render=this._ownerRender; if (value){ var frameOverTime=value.frame; var textureAniType=frameOverTime.type; if (value.enable){ switch (textureAniType){ case 1: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE); break ; case 3: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE); } if (textureAniType===1 || textureAniType===3){ render._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONCYCLES*/48,value.cycles); var title=value.tiles; var _uvLengthE=this._uvLength.elements; _uvLengthE[0]=1.0 / title.x; _uvLengthE[1]=1.0 / title.y; render._setShaderValueVector2(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONSUBUVLENGTH*/49,this._uvLength); } switch (textureAniType){ case 1: render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTUVS*/50,frameOverTime.frameOverTimeData._elements); break ; case 3: render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTUVS*/50,frameOverTime.frameOverTimeDataMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTMAXUVS*/51,frameOverTime.frameOverTimeDataMax._elements); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE); render._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONCYCLES*/48,undefined); render._setShaderValueVector2(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONSUBUVLENGTH*/49,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTUVS*/50,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTMAXUVS*/51,null); } this._textureSheetAnimation=value; }); __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); __getset(0,__proto,'triangleCount',function(){ return this._indexBuffer?this._indexBuffer.indexCount / 3:0; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBox',function(){ return this._boundingBox; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBoxCorners',function(){ return this._boundingBoxCorners; }); ShurikenParticleSystem.halfKSqrtOf2=1.42 *0.5; __static(ShurikenParticleSystem, ['_RANDOMOFFSET',function(){return this._RANDOMOFFSET=new Uint32Array([0x23571a3e,0xc34f56fe,0x13371337,0x12460f3b,0x6aed452e,0xdec4aea1,0x96aa4de3,0x8d2c8431,0xf3857f6f,0xe0fbd834,0x13740583,0x591bc05c,0x40eb95e4,0xbc524e5f,0xaf502044,0xa614b381,0x1034e524,0xfc524e5f]);},'_maxElapsedTime',function(){return this._maxElapsedTime=1.0 / 3.0;},'_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempVector31',function(){return this._tempVector31=new Vector3();},'_tempVector32',function(){return this._tempVector32=new Vector3();},'_tempVector33',function(){return this._tempVector33=new Vector3();},'_tempVector34',function(){return this._tempVector34=new Vector3();},'_tempVector35',function(){return this._tempVector35=new Vector3();},'_tempVector36',function(){return this._tempVector36=new Vector3();},'_tempVector37',function(){return this._tempVector37=new Vector3();},'_tempVector38',function(){return this._tempVector38=new Vector3();},'_tempVector39',function(){return this._tempVector39=new Vector3();},'_tempPosition',function(){return this._tempPosition=new Vector3();},'_tempDirection',function(){return this._tempDirection=new Vector3();} ]); return ShurikenParticleSystem; })(GeometryFilter) /** *ShurikenParticleRender 类用于创建3D粒子渲染器。 */ //class laya.d3.core.particleShuriKen.ShurikenParticleRender extends laya.d3.core.render.BaseRender var ShurikenParticleRender=(function(_super){ function ShurikenParticleRender(owner){ /**@private */ //this._defaultBoundBox=null; /**@private */ //this._renderMode=0; /**@private */ //this._mesh=null; /**拉伸广告牌模式摄像机速度缩放,暂不支持。*/ //this.stretchedBillboardCameraSpeedScale=NaN; /**拉伸广告牌模式速度缩放。*/ //this.stretchedBillboardSpeedScale=NaN; /**拉伸广告牌模式长度缩放。*/ //this.stretchedBillboardLengthScale=NaN; this._finalGravity=new Vector3(); this._tempRotationMatrix=new Matrix4x4(); ShurikenParticleRender.__super.call(this,owner); this._defaultBoundBox=new BoundBox(new Vector3(),new Vector3()); this._renderMode=-1; this.stretchedBillboardCameraSpeedScale=0.0; this.stretchedBillboardSpeedScale=0.0; this.stretchedBillboardLengthScale=1.0; } __class(ShurikenParticleRender,'laya.d3.core.particleShuriKen.ShurikenParticleRender',_super); var __proto=ShurikenParticleRender.prototype; /** *@inheritDoc */ __proto._calculateBoundingBox=function(){ var minE=this._boundingBox.min.elements; minE[0]=-Number.MAX_VALUE; minE[1]=-Number.MAX_VALUE; minE[2]=-Number.MAX_VALUE; var maxE=this._boundingBox.min.elements; maxE[0]=Number.MAX_VALUE; maxE[1]=Number.MAX_VALUE; maxE[2]=Number.MAX_VALUE; } /** *@inheritDoc */ __proto._calculateBoundingSphere=function(){ var oriBoundSphere=(this._owner).particleSystem._boundingSphere; var maxScale=NaN; var transform=this._owner.transform; var scaleE=transform.scale.elements; var scaleX=Math.abs(scaleE[0]); var scaleY=Math.abs(scaleE[1]); var scaleZ=Math.abs(scaleE[2]); if (scaleX >=scaleY && scaleX >=scaleZ) maxScale=scaleX; else maxScale=scaleY >=scaleZ ? scaleY :scaleZ; Vector3.transformCoordinate(oriBoundSphere.center,transform.worldMatrix,this._boundingSphere.center); this._boundingSphere.radius=oriBoundSphere.radius *maxScale; } /** *@inheritDoc */ __proto._renderUpdate=function(projectionView){ var particleSystem=(this._owner).particleSystem; if (!Laya.stage.isVisibility||!particleSystem.isAlive) return false; var transform=this._owner.transform; switch (particleSystem.simulationSpace){ case 0: break ; case 1: this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.WORLDPOSITION*/0,transform.position); this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.WORLDROTATION*/1,transform.rotation); break ; default : throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid."); } switch (particleSystem.scaleMode){ case 0:; var scale=transform.scale; this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.POSITIONSCALE*/4,scale); this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIZESCALE*/5,scale); break ; case 1:; var localScale=transform.localScale; this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.POSITIONSCALE*/4,localScale); this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIZESCALE*/5,localScale); break ; case 2: this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.POSITIONSCALE*/4,transform.scale); this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIZESCALE*/5,Vector3.ONE); break ; }; var finalGravityE=this._finalGravity.elements; var gravityE=Physics.gravity.elements; var gravityModifier=particleSystem.gravityModifier; finalGravityE[0]=gravityE[0] *gravityModifier; finalGravityE[1]=gravityE[1] *gravityModifier; finalGravityE[2]=gravityE[2] *gravityModifier; this._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.GRAVITY*/7,finalGravityE); this._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIMULATIONSPACE*/11,particleSystem.simulationSpace); this._setShaderValueBool(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.THREEDSTARTROTATION*/8,particleSystem.threeDStartRotation); this._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SCALINGMODE*/6,particleSystem.scaleMode); this._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.STRETCHEDBILLBOARDLENGTHSCALE*/9,this.stretchedBillboardLengthScale); this._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.STRETCHEDBILLBOARDSPEEDSCALE*/10,this.stretchedBillboardSpeedScale); this._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.CURRENTTIME*/12,particleSystem._currentTime); if (Laya3D.debugMode) this._renderRenderableBoundBox(); return true; } /** *@inheritDoc */ __proto._destroy=function(){ _super.prototype._destroy.call(this); (this._mesh)&& (this._mesh._removeReference(),this._mesh=null); } /** *@inheritDoc */ __getset(0,__proto,'boundingBox',function(){ if (!(this._owner).particleSystem.isAlive){ return this._defaultBoundBox; }else { if (this._boundingBoxNeedChange){ this._calculateBoundingBox(); this._boundingBoxNeedChange=false; } return this._boundingBox; } }); /** *设置渲染模式,0为BILLBOARD、1为STRETCHEDBILLBOARD、2为HORIZONTALBILLBOARD、3为VERTICALBILLBOARD、4为MESH。 *@param value 渲染模式。 */ /** *获取渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',function(){ return this._renderMode; },function(value){ if (this._renderMode!==value){ switch (this._renderMode){ case 0: this._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_BILLBOARD); break ; case 1: this._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD); break ; case 2: this._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD); break ; case 3: this._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD); break ; case 4: this._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_MESH); break ; } this._renderMode=value; switch (value){ case 0: this._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_BILLBOARD); break ; case 1: this._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD); break ; case 2: this._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD); break ; case 3: this._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD); break ; case 4: this._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_MESH); break ; default : throw new Error("ShurikenParticleRender: unknown renderMode Value."); } (this._owner).particleSystem._initBufferDatas(); } }); /** *设置网格渲染模式所使用的Mesh,rendderMode为4时生效。 *@param value 网格模式所使用Mesh。 */ /** *获取网格渲染模式所使用的Mesh,rendderMode为4时生效。 *@return 网格模式所使用Mesh。 */ __getset(0,__proto,'mesh',function(){ return this._mesh },function(value){ if (this._mesh!==value){ (this._mesh)&& (this._mesh._removeReference()); this._mesh=value; (value)&& (value._addReference()); (this._owner).particleSystem._initBufferDatas(); } }); return ShurikenParticleRender; })(BaseRender) /** *... *@author ... */ //class laya.d3.core.trail.TrailFilter extends laya.d3.core.GeometryFilter var TrailFilter=(function(_super){ function TrailFilter(owner){ this._owner=null; this._trailRenderElements=null; this._minVertexDistance=NaN; this._widthMultiplier=NaN; this._time=NaN; this._widthCurve=null; this._colorGradient=null; this._textureMode=0; this._curtime=0; this._curSubTrailFinishCurTime=0; this._curSubTrailFinished=false; this._hasLifeSubTrail=false; this._trailTotalLength=0; this._trailSupplementLength=0; this._trailDeadLength=0; this._isStart=false; this._trailRenderElementIndex=0; TrailFilter.__super.call(this); this._curSubTrailFinishPosition=new Vector3(); this._curSubTrailFinishDirection=new Vector3(); this._owner=owner; this._trailRenderElements=[]; this.addRenderElement(); } __class(TrailFilter,'laya.d3.core.trail.TrailFilter',_super); var __proto=TrailFilter.prototype; __proto.getRenderElementsCount=function(){ return this._trailRenderElements.length; } __proto.addRenderElement=function(){ for (var i=0;i < this._trailRenderElements.length;i++){ if (this._trailRenderElements[i]._isDead==true){ this._trailRenderElements[i].reActivate(); return i; } }; var _trailRenderElement=new TrailRenderElement(this); this._trailRenderElements.push(_trailRenderElement); return this._trailRenderElements.length-1; } __proto.getRenderElement=function(index){ return this._trailRenderElements[index]; } __proto._update=function(state){ this._curtime+=state.elapsedTime / 1000; this._owner._render._setShaderValueNumber(/*laya.d3.core.trail.TrailSprite3D.CURTIME*/3,this._curtime); if (this._curSubTrailFinished){ this._curSubTrailFinished=false; this._trailRenderElementIndex=this.addRenderElement(); this.event(/*laya.events.Event.TRAIL_FILTER_CHANGE*/"trailfilterchange",[this._trailRenderElementIndex,this._trailRenderElements[this._trailRenderElementIndex]]); } } __proto.reset=function(){ for (var i=0;i < this._trailRenderElements.length;i++){ this._trailRenderElements[i].reActivate(); } this._isStart=false; this._hasLifeSubTrail=false; this._curSubTrailFinished=false; this._curSubTrailFinishCurTime=0; this._trailTotalLength=0; this._trailSupplementLength=0; this._trailDeadLength=0; } /** *@private */ __proto._destroy=function(){ _super.prototype._destroy.call(this); for (var i=0;i < this._trailRenderElements.length;i++){ this._trailRenderElements[i]._destroy(); } this._trailRenderElements=null; this._widthCurve=null; this._colorGradient=null; this._curSubTrailFinishPosition=null; this._curSubTrailFinishDirection=null; } /** *设置宽度倍数。 *@param value 宽度倍数。 */ /** *获取宽度倍数。 *@return 宽度倍数。 */ __getset(0,__proto,'widthMultiplier',function(){ return this._widthMultiplier; },function(value){ this._widthMultiplier=value; }); /** *设置淡出时间。 *@param value 淡出时间。 */ /** *获取淡出时间。 *@return 淡出时间。 */ __getset(0,__proto,'time',function(){ return this._time; },function(value){ this._time=value; this._owner._render._setShaderValueNumber(/*laya.d3.core.trail.TrailSprite3D.LIFETIME*/4,value); }); /** *设置宽度曲线。 *@param value 宽度曲线。 */ /** *获取宽度曲线。 *@return 宽度曲线。 */ __getset(0,__proto,'widthCurve',function(){ return this._widthCurve; },function(value){ this._widthCurve=value; var widthCurveFloatArray=new Float32Array(value.length *4); var i=0,j=0,index=0; for (i=0,j=value.length;i < j;i++){ widthCurveFloatArray[index++]=value[i].time; widthCurveFloatArray[index++]=value[i].inTangent; widthCurveFloatArray[index++]=value[i].outTangent; widthCurveFloatArray[index++]=value[i].value; } this._owner._render._setShaderValueBuffer(/*laya.d3.core.trail.TrailSprite3D.WIDTHCURVE*/5,widthCurveFloatArray); this._owner._render._setShaderValueInt(/*laya.d3.core.trail.TrailSprite3D.WIDTHCURVEKEYLENGTH*/6,value.length); }); /** *设置新旧顶点之间最小距离。 *@param value 新旧顶点之间最小距离。 */ /** *获取新旧顶点之间最小距离。 *@return 新旧顶点之间最小距离。 */ __getset(0,__proto,'minVertexDistance',function(){ return this._minVertexDistance; },function(value){ this._minVertexDistance=value; }); /** *设置颜色梯度。 *@param value 颜色梯度。 */ /** *获取颜色梯度。 *@return 颜色梯度。 */ __getset(0,__proto,'colorGradient',function(){ return this._colorGradient; },function(value){ this._colorGradient=value; this._owner._render._setShaderValueBuffer(/*laya.d3.core.trail.TrailSprite3D.GRADIENTCOLORKEY*/7,value._colorKeyData); this._owner._render._setShaderValueBuffer(/*laya.d3.core.trail.TrailSprite3D.GRADIENTALPHAKEY*/8,value._alphaKeyData); if (value.mode==/*laya.d3.core.trail.module.GradientMode.Blend*/0){ this._owner._render._addShaderDefine(TrailSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND); } else{ this._owner._render._removeShaderDefine(TrailSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND); } }); /** *设置纹理模式。 *@param value 纹理模式。 */ /** *获取纹理模式。 *@return 纹理模式。 */ __getset(0,__proto,'textureMode',function(){ return this._textureMode; },function(value){ this._textureMode=value; }); return TrailFilter; })(GeometryFilter) /** *... *@author ... */ //class laya.d3.core.trail.TrailRenderer extends laya.d3.core.render.BaseRender var TrailRenderer=(function(_super){ function TrailRenderer(owner){ TrailRenderer.__super.call(this,owner); } __class(TrailRenderer,'laya.d3.core.trail.TrailRenderer',_super); var __proto=TrailRenderer.prototype; __proto._calculateBoundingBox=function(){ var minE=this._boundingBox.min.elements; minE[0]=-Number.MAX_VALUE; minE[1]=-Number.MAX_VALUE; minE[2]=-Number.MAX_VALUE; var maxE=this._boundingBox.min.elements; maxE[0]=Number.MAX_VALUE; maxE[1]=Number.MAX_VALUE; maxE[2]=Number.MAX_VALUE; } __proto._calculateBoundingSphere=function(){ var centerE=this._boundingSphere.center.elements; centerE[0]=0; centerE[1]=0; centerE[2]=0; this._boundingSphere.radius=Number.MAX_VALUE; } __proto._renderUpdate=function(projectionView){ return true; } return TrailRenderer; })(BaseRender) /** *... *@author */ //class laya.d3.extension.domino.DominoFilter extends laya.d3.core.GeometryFilter var DominoFilter=(function(_super){ function DominoFilter(owner){ this._owner=null; this.dominoCount=0; this.DominoRenderElementMaxDominoCount=2000; this._dominoRenderElements=null; DominoFilter.__super.call(this); this.dominoPosition=[]; this._owner=owner; this.initPositionsAndNormal(); this._dominoRenderElements=[]; this.addDominoRenderElement(); } __class(DominoFilter,'laya.d3.extension.domino.DominoFilter',_super); var __proto=DominoFilter.prototype; __proto.addDomino=function(position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=Vector3.ZERO); var curDominoRenderElement=this._dominoRenderElements[this._dominoRenderElements.length-1]; if (curDominoRenderElement._curDominoCount >=this.DominoRenderElementMaxDominoCount){ var index=this.addDominoRenderElement(); this.event(/*laya.events.Event.DOMINO_FILTER_CHANGE*/"dominofilterchange",[index,this._dominoRenderElements[index]]); } curDominoRenderElement=this._dominoRenderElements[this._dominoRenderElements.length-1]; curDominoRenderElement.addDomino(position,rotation,scale); } __proto.updateDomino=function(index,position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=Vector3.ZERO); var needUpdateDominoRenderElementId=Math.floor(index / this.DominoRenderElementMaxDominoCount); var needUpdateDominoRenderElementIndex=index % this.DominoRenderElementMaxDominoCount; var needUpdateDominoRenderElement=this._dominoRenderElements[needUpdateDominoRenderElementId]; needUpdateDominoRenderElement.updateDomino(needUpdateDominoRenderElementIndex,position,rotation,scale); } __proto.updateDominos=function(startIndex,count,keyFrames){ var endIndex=startIndex+count-1; var startNeedUpdateDominoRenderElementId=Math.floor(startIndex / this.DominoRenderElementMaxDominoCount); var endNeedUpdateDominoRenderElementId=Math.floor(endIndex / this.DominoRenderElementMaxDominoCount); var startNeedUpdateDominoRenderElementIndex=startIndex % this.DominoRenderElementMaxDominoCount; var endNeedUpdateDominoRenderElementIndex=endIndex % this.DominoRenderElementMaxDominoCount; var needUpdateDominoRenderElementCount=endNeedUpdateDominoRenderElementId-startNeedUpdateDominoRenderElementId+1; var needUpdateDominoRenderElement; if (needUpdateDominoRenderElementCount <=1){ needUpdateDominoRenderElement=this._dominoRenderElements[startNeedUpdateDominoRenderElementId]; needUpdateDominoRenderElement.updateDominos(startNeedUpdateDominoRenderElementIndex,count,keyFrames); return; }; var keyFrameDatas; var curStartIndex=0,curCount=0,curSliceIndex=0; for (var i=0;i < needUpdateDominoRenderElementCount;i++){ needUpdateDominoRenderElement=this._dominoRenderElements[startNeedUpdateDominoRenderElementId+i]; if (i==0){ curStartIndex=startNeedUpdateDominoRenderElementIndex; curCount=this.DominoRenderElementMaxDominoCount-curStartIndex; keyFrameDatas=keyFrames.slice(0,curCount); curSliceIndex+=curCount; }else if (i==needUpdateDominoRenderElementCount-1){ curStartIndex=0; curCount=endNeedUpdateDominoRenderElementIndex+1; keyFrameDatas=keyFrames.slice(curSliceIndex,keyFrames.length); }else { curStartIndex=0; curCount=this.DominoRenderElementMaxDominoCount; keyFrameDatas=keyFrames.slice(curSliceIndex,curSliceIndex+this.DominoRenderElementMaxDominoCount); curSliceIndex+=this.DominoRenderElementMaxDominoCount; } needUpdateDominoRenderElement.updateDominos(curStartIndex,curCount,keyFrameDatas); } } __proto.addDominoRenderElement=function(){ var _dominoRenderElement=new DominoRenderElement(this); this._dominoRenderElements.push(_dominoRenderElement); return this._dominoRenderElements.length-1; } __proto.getDominoRenderElementsCount=function(){ return this._dominoRenderElements.length; } __proto.getRenderElement=function(index){ return this._dominoRenderElements[index]; } __proto._update=function(state){} __proto.initPositionsAndNormal=function(){ if (DominoFilter._positions.length !=0 && DominoFilter._normals.length !=0){ return; } DominoFilter._positions.push(new Vector3(-0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(-0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,-0.5)); DominoFilter._positions.push(new Vector3(-0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,-0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,-0.5)); DominoFilter._normals.push(new Vector3(0,1,0)); DominoFilter._normals.push(new Vector3(0,1,0)); DominoFilter._normals.push(new Vector3(0,1,0)); DominoFilter._normals.push(new Vector3(0,1,0)); DominoFilter._normals.push(new Vector3(0,-1,0)); DominoFilter._normals.push(new Vector3(0,-1,0)); DominoFilter._normals.push(new Vector3(0,-1,0)); DominoFilter._normals.push(new Vector3(0,-1,0)); DominoFilter._normals.push(new Vector3(-1,0,0)); DominoFilter._normals.push(new Vector3(-1,0,0)); DominoFilter._normals.push(new Vector3(-1,0,0)); DominoFilter._normals.push(new Vector3(-1,0,0)); DominoFilter._normals.push(new Vector3(1,0,0)); DominoFilter._normals.push(new Vector3(1,0,0)); DominoFilter._normals.push(new Vector3(1,0,0)); DominoFilter._normals.push(new Vector3(1,0,0)); DominoFilter._normals.push(new Vector3(0,0,1)); DominoFilter._normals.push(new Vector3(0,0,1)); DominoFilter._normals.push(new Vector3(0,0,1)); DominoFilter._normals.push(new Vector3(0,0,1)); DominoFilter._normals.push(new Vector3(0,0,-1)); DominoFilter._normals.push(new Vector3(0,0,-1)); DominoFilter._normals.push(new Vector3(0,0,-1)); DominoFilter._normals.push(new Vector3(0,0,-1)); } DominoFilter._positions=[]; DominoFilter._normals=[]; return DominoFilter; })(GeometryFilter) /** *... *@author */ //class laya.d3.extension.lineRender.LineFilter extends laya.d3.core.GeometryFilter var LineFilter=(function(_super){ function LineFilter(owner){ this._owner=null; this._camera=null; this._useWorldSpace=false; this._widthMultiplier=0.02; this._widthCurve=null; this._colorGradient=null; this._textureMode=0; this._curFixedNum=0; this._vertexBuffers=null; this._maxVertexCount=512; this._vertexCount=0; this._vertices1=null; this._vertexBuffer1=null; this._verticesIndex1=0; this._everyAddVerticeCount1=0; this._floatCountPerVertices1=4; this._vertices2=null; this._vertexBuffer2=null; this._verticesIndex2=0; this._everyAddVerticeCount2=0; this._floatCountPerVertices2=3; this._vertices3=null; this._vertexBuffer3=null; this._verticesIndex3=0; this._everyAddVerticeCount3=0; this._floatCountPerVertices3=2; this._delLength=0; this._pointe=null; this._pointAtoBVector3e=null; this._everyToFirstDistance=null; this._curTotalLength=0; LineFilter.__super.call(this); this._positions=[]; this._normals=[]; this._firstPosition=new Vector3(); this._delVector3=new Vector3(); this._lastPosition=new Vector3(); this._pointAtoBVector3=new Vector3(); this._cameraToPointV3=new Vector3(); this._curDirection=new Vector3(); this._lastDirection=new Vector3(); this._fixedDirection=new Vector3(); this._owner=owner; this._initData(); this._vertices1=new Float32Array(this._maxVertexCount *this._floatCountPerVertices1); this._vertices2=new Float32Array(this._maxVertexCount *this._floatCountPerVertices2); this._vertices3=new Float32Array(this._maxVertexCount *this._floatCountPerVertices3); this._vertexBuffer1=new VertexBuffer3D(LineVertex.vertexDeclaration1,this._maxVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer2=new VertexBuffer3D(LineVertex.vertexDeclaration2,this._maxVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer3=new VertexBuffer3D(LineVertex.vertexDeclaration3,this._maxVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffers=[]; this._vertexBuffers.push(this._vertexBuffer1); this._vertexBuffers.push(this._vertexBuffer2); this._vertexBuffers.push(this._vertexBuffer3); this._everyToFirstDistance=new Float32Array(this._maxVertexCount / 2); } __class(LineFilter,'laya.d3.extension.lineRender.LineFilter',_super); var __proto=LineFilter.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) __proto.addPosition=function(position,normal){ var v30=new Vector3(); position.cloneTo(v30); this._positions.push(v30); var v31=new Vector3(); normal.cloneTo(v31); this._normals.push(v31); this._updateVertexBuffer1(v30); this._vertexCount+=2; } __proto._updateVertexBuffer1=function(position){ this._everyAddVerticeCount1=0; this._pointe=position.elements; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=1.0; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=0.0; this._vertexBuffer1.setData(this._vertices1,this._verticesIndex1,this._verticesIndex1,this._everyAddVerticeCount1); this._verticesIndex1+=this._everyAddVerticeCount1; } __proto._updateVertexBuffer2=function(){ this._verticesIndex2=0; for (var i=this._curFixedNum;i < this._positions.length;i++){ if (i==0){ Vector3.subtract(this._positions[1],this._positions[0],this._delVector3); Vector3.cross(this._delVector3,this._normals[0],this._pointAtoBVector3); Vector3.normalize(this._pointAtoBVector3,this._pointAtoBVector3); Vector3.scale(this._pointAtoBVector3,this._widthMultiplier / 2,this._pointAtoBVector3); this._everyToFirstDistance[i]=0; this._updateVertices2(this._positions[0],0); } else{ Vector3.subtract(this._positions[i],this._positions[i-1],this._delVector3); Vector3.cross(this._delVector3,this._normals[i],this._pointAtoBVector3); Vector3.normalize(this._pointAtoBVector3,this._pointAtoBVector3); Vector3.scale(this._pointAtoBVector3,this._widthMultiplier / 2,this._pointAtoBVector3); this._delLength=Vector3.scalarLength(this._delVector3); this._curTotalLength=this._everyToFirstDistance[i]=this._curTotalLength+this._delLength; this._updateVertices2(this._positions[i],i); } this._curFixedNum=i+1; } this._vertexBuffer2.setData(this._vertices2,0,0,this._verticesIndex2); } __proto._updateVertexBuffer3=function(){ var _uvIndex=0; var _uvX=0.0; var _uvX1=0.0; var i=0,j=0; for (i=0,j=this._vertexCount / 2;i < j;i++){ _uvX=this._everyToFirstDistance[i] / this._curTotalLength; _uvX1=this._everyToFirstDistance[i]; this._vertices3[_uvIndex++]=_uvX; this._vertices3[_uvIndex++]=_uvX1; this._vertices3[_uvIndex++]=_uvX; this._vertices3[_uvIndex++]=_uvX1; } this._vertexBuffer3.setData(this._vertices3,0,0,this._vertexCount *2); } __proto._beforeRender=function(state){ if (this._camera==null){ this._camera=state.camera; return false; } if (this._vertexCount > 0){ this._updateVertexBuffer2(); this._updateVertexBuffer3(); return true; } return false; } __proto._render=function(state){ WebGL.mainContext.drawArrays(/*laya.webgl.WebGLContext.TRIANGLE_STRIP*/0x0005,0,this._vertexCount); Stat.drawCall++; } __proto._updateVertices2=function(position,index){ this._everyAddVerticeCount2=0; this._pointAtoBVector3e=this._pointAtoBVector3.elements; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=this._pointAtoBVector3e[0]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=this._pointAtoBVector3e[1]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=this._pointAtoBVector3e[2]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=-this._pointAtoBVector3e[0]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=-this._pointAtoBVector3e[1]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=-this._pointAtoBVector3e[2]; this._verticesIndex2+=this._everyAddVerticeCount2; } __proto._initData=function(){ this.useWorldSpace=true; this.widthMultiplier=0.02; this.textureMode=0; var widthKeyFrames=[]; var widthKeyFrame1=new TrailKeyFrame(); widthKeyFrame1.time=0; widthKeyFrame1.inTangent=0; widthKeyFrame1.outTangent=0; widthKeyFrame1.value=1; widthKeyFrames.push(widthKeyFrame1); var widthKeyFrame2=new TrailKeyFrame(); widthKeyFrame2.time=1; widthKeyFrame2.inTangent=0; widthKeyFrame2.outTangent=0; widthKeyFrame2.value=1; widthKeyFrames.push(widthKeyFrame2); this.widthCurve=widthKeyFrames; var gradient=new Gradient(); gradient.mode=/*laya.d3.core.trail.module.GradientMode.Blend*/0; var colorKeys=[]; var colorKey1=new GradientColorKey(); colorKey1.time=0; colorKey1.color=Color$1.WHITE; colorKeys.push(colorKey1); var colorKey2=new GradientColorKey(); colorKey2.time=1; colorKey2.color=Color$1.WHITE; colorKeys.push(colorKey2); var alphaKeys=[]; var alphaKey1=new GradientAlphaKey(); alphaKey1.time=0; alphaKey1.alpha=1; alphaKeys.push(alphaKey1); var alphaKey2=new GradientAlphaKey(); alphaKey2.time=1; alphaKey2.alpha=1; alphaKeys.push(alphaKey2); gradient.setKeys(colorKeys,alphaKeys); this.colorGradient=gradient; } __proto._update=function(state){} __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer1; else return null; } __proto._getVertexBuffers=function(){ return this._vertexBuffers; } __proto._getIndexBuffer=function(){ return null; } /** *@private */ __proto._destroy=function(){ _super.prototype._destroy.call(this); this._vertexBuffer1.destroy(); this._vertexBuffer2.destroy(); this._vertexBuffer3.destroy(); this._vertexBuffers=null; this._vertices1=null; this._vertices2=null; this._vertices3=null; this._owner=null; this._camera=null; this._widthCurve=null; this._colorGradient=null; this._positions=null; this._normals=null; this._firstPosition=null; this._delVector3=null; this._lastPosition=null; this._pointAtoBVector3=null; this._cameraToPointV3=null; this._delVector3=null; this._pointe=null; this._pointAtoBVector3e=null; this._curDirection=null; this._lastDirection=null; this._fixedDirection=null; this._everyToFirstDistance=null; } /** *设置宽度曲线。 *@param value 宽度曲线。 */ /** *获取宽度曲线。 *@return 宽度曲线。 */ __getset(0,__proto,'widthCurve',function(){ return this._widthCurve; },function(value){ this._widthCurve=value; var widthCurveFloatArray=new Float32Array(value.length *4); var i=0,j=0,index=0; for (i=0,j=value.length;i < j;i++){ widthCurveFloatArray[index++]=value[i].time; widthCurveFloatArray[index++]=value[i].inTangent; widthCurveFloatArray[index++]=value[i].outTangent; widthCurveFloatArray[index++]=value[i].value; } this._owner._render._setShaderValueBuffer(/*laya.d3.extension.lineRender.LineSprite3D.WIDTHCURVE*/3,widthCurveFloatArray); this._owner._render._setShaderValueInt(/*laya.d3.extension.lineRender.LineSprite3D.WIDTHCURVEKEYLENGTH*/4,value.length); }); /** *设置是否世界空间。 *@param value 是否世界空间。 */ /** *获取是否世界空间。 *@return 是否世界空间。 */ __getset(0,__proto,'useWorldSpace',function(){ return this._useWorldSpace; },function(value){ this._useWorldSpace=value; if (value){ this._owner._render._addShaderDefine(LineSprite3D.SHADERDEFINE_WORLDSPACE); } else{ this._owner._render._removeShaderDefine(LineSprite3D.SHADERDEFINE_WORLDSPACE); } }); __getset(0,__proto,'triangleCount',function(){ return 0; }); /** *设置宽度倍数。 *@param value 宽度倍数。 */ /** *获取宽度倍数。 *@return 宽度倍数。 */ __getset(0,__proto,'widthMultiplier',function(){ return this._widthMultiplier; },function(value){ this._widthMultiplier=value; }); /** *设置颜色梯度。 *@param value 颜色梯度。 */ /** *获取颜色梯度。 *@return 颜色梯度。 */ __getset(0,__proto,'colorGradient',function(){ return this._colorGradient; },function(value){ this._colorGradient=value; this._owner._render._setShaderValueBuffer(/*laya.d3.extension.lineRender.LineSprite3D.GRADIENTCOLORKEY*/5,value._colorKeyData); this._owner._render._setShaderValueBuffer(/*laya.d3.extension.lineRender.LineSprite3D.GRADIENTALPHAKEY*/6,value._alphaKeyData); if (value.mode==/*laya.d3.core.trail.module.GradientMode.Blend*/0){ this._owner._render._addShaderDefine(LineSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND); } else{ this._owner._render._removeShaderDefine(LineSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND); } }); /** *设置纹理模式。 *@param value 纹理模式。 */ /** *获取纹理模式。 *@return 纹理模式。 */ __getset(0,__proto,'textureMode',function(){ return this._textureMode; },function(value){ this._textureMode=value; if (value==/*laya.d3.core.trail.module.TextureMode.Stretch*/0){ this._owner._render._addShaderDefine(LineSprite3D.SHADERDEFINE_TEXTUREMODE_STRETCH); } else{ this._owner._render._removeShaderDefine(LineSprite3D.SHADERDEFINE_TEXTUREMODE_STRETCH); } }); __getset(0,__proto,'_vertexBufferCount',function(){ return this._vertexBuffers.length; }); return LineFilter; })(GeometryFilter) /** *... *@author */ //class laya.d3.extension.domino.DominoRenderer extends laya.d3.core.render.BaseRender var DominoRenderer=(function(_super){ function DominoRenderer(owner){ DominoRenderer.__super.call(this,owner); } __class(DominoRenderer,'laya.d3.extension.domino.DominoRenderer',_super); var __proto=DominoRenderer.prototype; __proto._calculateBoundingBox=function(){ var minE=this._boundingBox.min.elements; minE[0]=-Number.MAX_VALUE; minE[1]=-Number.MAX_VALUE; minE[2]=-Number.MAX_VALUE; var maxE=this._boundingBox.min.elements; maxE[0]=Number.MAX_VALUE; maxE[1]=Number.MAX_VALUE; maxE[2]=Number.MAX_VALUE; } __proto._calculateBoundingSphere=function(){ var centerE=this._boundingSphere.center.elements; centerE[0]=0; centerE[1]=0; centerE[2]=0; this._boundingSphere.radius=Number.MAX_VALUE; } __proto._renderUpdate=function(projectionView){ var transform=this._owner.transform; if (transform){ this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,transform.worldMatrix); var projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); }else { this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,Matrix4x4.DEFAULT); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projectionView); } return true; } return DominoRenderer; })(BaseRender) /** *... *@author */ //class laya.d3.extension.lineRender.LineRenderer extends laya.d3.core.render.BaseRender var LineRenderer=(function(_super){ function LineRenderer(owner){ LineRenderer.__super.call(this,owner); } __class(LineRenderer,'laya.d3.extension.lineRender.LineRenderer',_super); var __proto=LineRenderer.prototype; __proto._calculateBoundingBox=function(){ var minE=this._boundingBox.min.elements; minE[0]=-Number.MAX_VALUE; minE[1]=-Number.MAX_VALUE; minE[2]=-Number.MAX_VALUE; var maxE=this._boundingBox.min.elements; maxE[0]=Number.MAX_VALUE; maxE[1]=Number.MAX_VALUE; maxE[2]=Number.MAX_VALUE; } __proto._calculateBoundingSphere=function(){ var centerE=this._boundingSphere.center.elements; centerE[0]=0; centerE[1]=0; centerE[2]=0; this._boundingSphere.radius=Number.MAX_VALUE; } __proto._renderUpdate=function(projectionView){ var transform=this._owner.transform; if (transform){ this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,transform.worldMatrix); var projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); }else { this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,Matrix4x4.DEFAULT); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projectionView); } return true; } return LineRenderer; })(BaseRender) /** *@private *GlitterTemplet 类用于创建闪光数据模板。 */ //class laya.d3.resource.tempelet.GlitterTemplet extends laya.d3.core.GeometryFilter var GlitterTemplet=(function(_super){ function GlitterTemplet(owner){ this._floatCountPerVertex=6; //顶点结构为Position(3个float)+UV(2个float)+Time(1个float) this._owner=null; this._vertices=null; this._vertexBuffer=null; this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._currentTime=NaN; this._drawCounter=0; this.scLeft=null; this.scRight=null; this._numPositionMode=0; this._numPositionVelocityMode=0; this._lastTime=NaN; this._needPatch=false; this._lastPatchAddPos0=null; this._lastPatchAddPos1=null; this._lastPatchAddTime=NaN; /**声明周期。 */ this.lifeTime=NaN; /**最小分段距离。 */ this.minSegmentDistance=NaN; /**最小插值距离。 */ this.minInterpDistance=NaN; /**最大插值数量。 */ this.maxSlerpCount=0; /**最大段数。 */ this._maxSegments=0; GlitterTemplet.__super.call(this); this._tempVector0=new Vector3(); this._tempVector1=new Vector3(); this._tempVector2=new Vector3(); this._tempVector3=new Vector3(); this._posModeLastPosition0=new Vector3(); this._posModeLastPosition1=new Vector3(); this._posModePosition0=new Vector3(); this._posModePosition1=new Vector3(); this._posVelModePosition0=new Vector3(); this._posVelModeVelocity0=new Vector3(); this._posVelModePosition1=new Vector3(); this._posVelModeVelocity1=new Vector3(); this._owner=owner; this._lastTime=0 this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._currentTime=0; this._drawCounter=0; this._needPatch=false; this._lastPatchAddPos0=new Vector3(); this._lastPatchAddPos1=new Vector3(); this.scLeft=new SplineCurvePositionVelocity(); this.scRight=new SplineCurvePositionVelocity(); this.lifeTime=0.5; this.minSegmentDistance=0.1; this.minInterpDistance=0.6; this.maxSlerpCount=128; this._maxSegments=200; this._owner.on(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onActiveHierarchyChanged); } __class(GlitterTemplet,'laya.d3.resource.tempelet.GlitterTemplet',_super); var __proto=GlitterTemplet.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer; else return null; } __proto._getIndexBuffer=function(){ return null; } /** *@private */ __proto._initialize=function(){ this._vertexBuffer=VertexBuffer3D.create(VertexGlitter.vertexDeclaration,this.maxSegments *2,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._vertices=new Float32Array(this.maxSegments *this._floatCountPerVertex *2); } __proto._onActiveHierarchyChanged=function(active){ if (!active){ this._numPositionMode=0; this._numPositionVelocityMode=0; this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._currentTime=0; this._drawCounter=0; } } /** *@private */ __proto._updateTextureCoordinates=function(){ if (this._firstActiveElement < this._firstFreeElement){ this._updateSubTextureCoordinates(this._firstActiveElement,(this._firstFreeElement-this._firstActiveElement)*2); }else { this._updateSubTextureCoordinates(this._firstActiveElement,(this.maxSegments-this._firstActiveElement)*2); if (this._firstFreeElement > 0) this._updateSubTextureCoordinates(0,this._firstFreeElement *2); } } /** *@private */ __proto._updateSubTextureCoordinates=function(start,count){ var startOffset=start *2; for (var i=0;i < count;i+=2){ var vertexOffset=startOffset+i; var upVertexOffset=vertexOffset *this._floatCountPerVertex; var downVertexOffset=(vertexOffset+1)*this._floatCountPerVertex; this._vertices[upVertexOffset+3]=this._vertices[downVertexOffset+3]=(this._vertices[upVertexOffset+5]-this._currentTime)/ this.lifeTime; } } /** *@private */ __proto._retireActiveGlitter=function(){ var particleDuration=this.lifeTime; var _floatCountOneSegement=this._floatCountPerVertex *2; while (this._firstActiveElement !=this._firstNewElement){ var index=this._firstActiveElement *_floatCountOneSegement+5; var particleAge=this._currentTime-this._vertices[index]; if (particleAge < particleDuration) break ; this._vertices[index]=this._drawCounter; this._firstActiveElement++; if (this._firstActiveElement >=this.maxSegments) this._firstActiveElement=0; } } /** *@private */ __proto._freeRetiredGlitter=function(){ var _floatCountOneSegement=this._floatCountPerVertex *2; while (this._firstRetiredElement !=this._firstActiveElement){ var age=this._drawCounter-this._vertices[this._firstRetiredElement *_floatCountOneSegement+5]; if (age < 3) break ; this._firstRetiredElement++; if (this._firstRetiredElement >=this.maxSegments) this._firstRetiredElement=0; } } /** *@private */ __proto._calcVelocity=function(left,right,out){ Vector3.subtract(left,right,out); Vector3.scale(out,0.5,out); } /** *@private */ __proto._addNewGlitterSegementToVertexBuffer=function(){ var start=0; if (this._firstActiveElement < this._firstFreeElement){ start=this._firstActiveElement *2 *this._floatCountPerVertex; this._vertexBuffer.setData(this._vertices,start,start,(this._firstFreeElement-this._firstActiveElement)*2 *this._floatCountPerVertex); }else { start=this._firstActiveElement *2 *this._floatCountPerVertex; this._vertexBuffer.setData(this._vertices,start,start,(this.maxSegments-this._firstActiveElement)*2 *this._floatCountPerVertex); if (this._firstFreeElement > 0){ this._vertexBuffer.setData(this._vertices,0,0,this._firstFreeElement *2 *this._floatCountPerVertex); } } this._firstNewElement=this._firstFreeElement; } /** *@private */ __proto._addGlitter=function(position0,position1,time){ if (this._needPatch){ this._needPatch=false; this._addGlitter(this._lastPatchAddPos0,this._lastPatchAddPos1,this._lastPatchAddTime); }; var nextFreeParticle=this._firstFreeElement+1; if (nextFreeParticle >=this.maxSegments){ nextFreeParticle=0; position0.cloneTo(this._lastPatchAddPos0); position1.cloneTo(this._lastPatchAddPos1); this._lastPatchAddTime=time; this._needPatch=true; } if (nextFreeParticle===this._firstRetiredElement) console.log("GlitterTemplet:current segement count have large than maxSegments,please adjust the value of maxSegments or add Glitter Vertex Frequency."); var position0e=position0.elements; var position1e=position1.elements; var j=0; var positionIndex=this._firstFreeElement *this._floatCountPerVertex *2; for (j=0;j < 3;j++) this._vertices[positionIndex+j]=position0e[j]; this._vertices[positionIndex+3]=0.0; this._vertices[positionIndex+4]=0.0; this._vertices[positionIndex+5]=time; var nextPositionIndex=positionIndex+this._floatCountPerVertex; for (j=0;j < 3;j++) this._vertices[nextPositionIndex+j]=position1e[j]; this._vertices[nextPositionIndex+3]=0.0; this._vertices[nextPositionIndex+4]=1.0; this._vertices[nextPositionIndex+5]=time; this._firstFreeElement=nextFreeParticle; } /** *@private *更新闪光。 *@param elapsedTime 间隔时间 */ __proto._update=function(elapsedTime){ this._currentTime+=elapsedTime / 1000; this._retireActiveGlitter(); this._freeRetiredGlitter(); if (this._firstActiveElement==this._firstFreeElement) this._currentTime=0; if (this._firstRetiredElement==this._firstActiveElement) this._drawCounter=0; this._updateTextureCoordinates(); } //实时更新纹理坐标 __proto._beforeRender=function(state){ if (this._firstNewElement !=this._firstFreeElement){ this._addNewGlitterSegementToVertexBuffer(); } this._drawCounter++; if (this._firstActiveElement !=this._firstFreeElement){ this._vertexBuffer.bindWithIndexBuffer(null); return true; } return false; } /** *@private *渲染闪光。 *@param state 相关渲染状态 */ __proto._render=function(state){ var drawVertexCount=0; var glContext=WebGL.mainContext; if (this._firstActiveElement < this._firstFreeElement){ drawVertexCount=(this._firstFreeElement-this._firstActiveElement)*2; glContext.drawArrays(/*laya.webgl.WebGLContext.TRIANGLE_STRIP*/0x0005,this._firstActiveElement *2,drawVertexCount); Stat.trianglesFaces+=drawVertexCount-2; Stat.drawCall++; }else { drawVertexCount=(this.maxSegments-this._firstActiveElement)*2; glContext.drawArrays(/*laya.webgl.WebGLContext.TRIANGLE_STRIP*/0x0005,this._firstActiveElement *2,drawVertexCount); Stat.trianglesFaces+=drawVertexCount-2; Stat.drawCall++; if (this._firstFreeElement > 0){ drawVertexCount=this._firstFreeElement *2; glContext.drawArrays(/*laya.webgl.WebGLContext.TRIANGLE_STRIP*/0x0005,0,drawVertexCount); Stat.trianglesFaces+=drawVertexCount-2; Stat.drawCall++; } } } /** *通过位置添加刀光。 *@param position0 位置0。 *@param position1 位置1。 */ __proto.addVertexPosition=function(position0,position1){ if (this._owner.activeInHierarchy){ if (this._numPositionMode < 2){ if (this._numPositionMode===0){ position0.cloneTo(this._posModeLastPosition0); position1.cloneTo(this._posModeLastPosition1); }else { position0.cloneTo(this._posModePosition0); position1.cloneTo(this._posModePosition1); } this._numPositionMode++; }else { var v0=this._tempVector2; this._calcVelocity(position0,this._posModeLastPosition0,v0); var v1=this._tempVector3; this._calcVelocity(position1,this._posModeLastPosition1,v1); this.addVertexPositionVelocity(this._posModePosition0,v0,this._posModePosition1,v1); this._posModePosition0.cloneTo(this._posModeLastPosition0); this._posModePosition1.cloneTo(this._posModeLastPosition1); position0.cloneTo(this._posModePosition0); position1.cloneTo(this._posModePosition1); } } } /** *通过位置和速度添加刀光。 *@param position0 位置0。 *@param velocity0 速度0。 *@param position1 位置1。 *@param velocity1 速度1。 */ __proto.addVertexPositionVelocity=function(position0,velocity0,position1,velocity1){ if (this._owner.activeInHierarchy){ if (this._numPositionVelocityMode===0){ this._numPositionVelocityMode++; }else { var d=this._tempVector0; Vector3.subtract(position0,this._posVelModePosition0,d); var distance0=Vector3.scalarLength(d); Vector3.subtract(position1,this._posVelModePosition1,d); var distance1=Vector3.scalarLength(d); var slerpCount=0; var minSegmentDistance=minSegmentDistance; if (distance0 < minSegmentDistance && distance1 < minSegmentDistance) return; slerpCount=1+Math.floor(Math.max(distance0,distance1)/ this.minInterpDistance); if (slerpCount===1){ this._addGlitter(position0,position1,this._currentTime); }else { slerpCount=Math.min(slerpCount,this.maxSlerpCount); this.scLeft.Init(this._posVelModePosition0,this._posVelModeVelocity0,position0,velocity0); this.scRight.Init(this._posVelModePosition1,this._posVelModeVelocity1,position1,velocity1); var segment=1.0 / slerpCount; var addSegment=segment; var timeOffset=this._currentTime-this._lastTime; for (var i=1;i <=slerpCount;i++){ var pos0=this._tempVector0; this.scLeft.Slerp(addSegment,pos0); var pos1=this._tempVector1; this.scRight.Slerp(addSegment,pos1); var time=this._lastTime+timeOffset *i / slerpCount; this._addGlitter(pos0,pos1,time); addSegment+=segment; } } } this._lastTime=this._currentTime; position0.cloneTo(this._posVelModePosition0); velocity0.cloneTo(this._posVelModeVelocity0); position1.cloneTo(this._posVelModePosition1); velocity1.cloneTo(this._posVelModeVelocity1); } } __proto._destroy=function(){ _super.prototype._destroy.call(this); this._tempVector0=null; this._tempVector1=null; this._tempVector2=null; this._tempVector3=null; this._owner=null; this._vertices=null; this._vertexBuffer.destroy(); this._vertexBuffer=null; this.scLeft=null; this.scRight=null; this._posModeLastPosition0=null; this._posModeLastPosition1=null; this._posModePosition0=null; this._posModePosition1=null; this._posVelModePosition0=null; this._posVelModeVelocity0=null; this._posVelModePosition1=null; this._posVelModeVelocity1=null; this._lastPatchAddPos0=null; this._lastPatchAddPos1=null; } /** *@private */ __proto._getVertexBuffers=function(){ return null; } /**设置最大分段数,注意:谨慎修改此属性,有性能损耗。*/ /**获取最大分段数。*/ __getset(0,__proto,'maxSegments',function(){ return this._maxSegments-1; },function(value){ var newMaxSegments=value+1; if (newMaxSegments!==this._maxSegments){ this._maxSegments=newMaxSegments; if (this._vertexBuffer){ this._vertexBuffer.destroy(); } this._initialize(); } }); __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); __getset(0,__proto,'triangleCount',function(){ var drawVertexCount=0; if (this._firstActiveElement < this._firstFreeElement){ drawVertexCount=(this._firstFreeElement-this._firstActiveElement)*2-2; }else { drawVertexCount=(this.maxSegments-this._firstActiveElement)*2-2; drawVertexCount+=this._firstFreeElement *2-2; } return drawVertexCount; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingSphere',function(){ return Laya.superGet(GeometryFilter,this,'_originalBoundingSphere'); }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBox',function(){ return Laya.superGet(GeometryFilter,this,'_originalBoundingBox'); }); return GlitterTemplet; })(GeometryFilter) /** *TerrainFilter 类用于创建TerrainFilter过滤器。 */ //class laya.d3.terrain.TerrainFilter extends laya.d3.core.GeometryFilter var TerrainFilter=(function(_super){ function TerrainFilter(owner,chunkOffsetX,chunkOffsetZ,gridSize,terrainHeightData,heightDataWidth,heightDataHeight,cameraCoordinateInverse){ this._owner=null; this._gridSize=NaN; this.memorySize=0; this._numberVertices=0; this._maxNumberIndices=0; this._currentNumberIndices=0; this._numberTriangle=0; this._vertexBuffer=null; this._indexBuffer=null; this._boundingSphere=null; this._boundingBox=null; this._indexArrayBuffer=null; this._boundingBoxCorners=null; this._leafs=null; this._leafNum=0; this._terrainHeightData=null; this._terrainHeightDataWidth=0; this._terrainHeightDataHeight=0; this._chunkOffsetX=0; this._chunkOffsetZ=0; this._cameraCoordinateInverse=false; this._cameraPos=null; this._currentLOD=0; //LOD级别 4个叶子节点 第1个叶子的level<<24+第2个叶子的level<<16+第3个叶子的level<<8+第4个叶子的level this._perspectiveFactor=NaN; this._LODTolerance=0; TerrainFilter.__super.call(this); this._owner=owner; this._cameraPos=new Vector3(); this._chunkOffsetX=chunkOffsetX; this._chunkOffsetZ=chunkOffsetZ; this._gridSize=gridSize; this._terrainHeightData=terrainHeightData; this._terrainHeightDataWidth=heightDataWidth; this._terrainHeightDataHeight=heightDataHeight; this._leafNum=(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM)*(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM); this._leafs=__newvec(this._leafNum); this._cameraCoordinateInverse=cameraCoordinateInverse; for (var i=0;i < this._leafNum;i++){ this._leafs[i]=new TerrainLeaf(); } this.recreateResource(); } __class(TerrainFilter,'laya.d3.terrain.TerrainFilter',_super); var __proto=TerrainFilter.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) /** *@inheritDoc */ __proto._destroy=function(){ _super.prototype._destroy.call(this); this._owner=null; if (this._vertexBuffer)this._vertexBuffer.destroy(); if (this._indexBuffer)this._indexBuffer.destroy(); } __proto.recreateResource=function(){ this._currentNumberIndices=0; this._numberTriangle=0; var nLeafVertexCount=TerrainLeaf.LEAF_VERTEXT_COUNT; var nLeafIndexCount=TerrainLeaf.LEAF_MAX_INDEX_COUNT; this._numberVertices=nLeafVertexCount *this._leafNum; this._maxNumberIndices=nLeafIndexCount *this._leafNum; this._indexArrayBuffer=new Uint16Array(this._maxNumberIndices); var vertexDeclaration=VertexPositionTerrain.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var nNum=TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM; var i=0,x=0,z=0; for (i=0;i < this._leafNum;i++){ x=i % nNum; z=Math.floor(i / nNum); this._leafs[i].calcVertextBuffer(this._chunkOffsetX,this._chunkOffsetZ,x *TerrainLeaf.LEAF_GRID_NUM,z *TerrainLeaf.LEAF_GRID_NUM,this._gridSize,vertices,i *TerrainLeaf.LEAF_PLANE_VERTEXT_COUNT,vertexFloatStride,this._terrainHeightData,this._terrainHeightDataWidth,this._terrainHeightDataHeight,this._cameraCoordinateInverse); } for (i=0;i < this._leafNum;i++){ x=i % nNum; z=Math.floor(i / nNum); this._leafs[i].calcSkirtVertextBuffer(this._chunkOffsetX,this._chunkOffsetZ,x *TerrainLeaf.LEAF_GRID_NUM,z *TerrainLeaf.LEAF_GRID_NUM,this._gridSize,vertices,this._leafNum *TerrainLeaf.LEAF_PLANE_VERTEXT_COUNT+i *TerrainLeaf.LEAF_SKIRT_VERTEXT_COUNT,vertexFloatStride,this._terrainHeightData,this._terrainHeightDataWidth,this._terrainHeightDataHeight); } this.assembleIndexInit(); this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,false); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._maxNumberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,false); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(this._indexArrayBuffer); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.calcOriginalBoudingBoxAndSphere(); } __proto.setLODLevel=function(leafsLODLevel){ if (leafsLODLevel.length !=4)return true; var nLOD=((leafsLODLevel[0]+1)<< 24)+((leafsLODLevel[1]+1)<< 16)+((leafsLODLevel[2]+1)<< 8)+(leafsLODLevel[3]+1); if (this._currentLOD==nLOD){ return false; } this._currentLOD=nLOD; return true; } __proto.assembleIndexInit=function(){ this._currentNumberIndices=0; this._numberTriangle=0; var nOffsetIndex=0; for (var i=0;i < this._leafNum;i++){ var planeLODIndex=TerrainLeaf.getPlaneLODIndex(i,0); this._indexArrayBuffer.set(planeLODIndex,nOffsetIndex); nOffsetIndex+=planeLODIndex.length; var skirtLODIndex=TerrainLeaf.getSkirtLODIndex(i,0); this._indexArrayBuffer.set(skirtLODIndex,nOffsetIndex); nOffsetIndex+=skirtLODIndex.length; this._currentNumberIndices+=(planeLODIndex.length+skirtLODIndex.length); } this._numberTriangle=this._currentNumberIndices / 3; } __proto.isNeedAssemble=function(camera,cameraPostion){ var perspectiveFactor=Math.min(camera.viewport.width,camera.viewport.height)/ (2 *Math.tan(Math.PI *camera.fieldOfView / 180.0)); if (this._perspectiveFactor !=perspectiveFactor){ this._perspectiveFactor=perspectiveFactor; return 1; } if (this._LODTolerance !=Terrain.LOD_TOLERANCE_VALUE){ this._LODTolerance=Terrain.LOD_TOLERANCE_VALUE; return 1; } if (Vector3.equals(cameraPostion,this._cameraPos)==false){ this._cameraPos.x=cameraPostion.x; this._cameraPos.y=cameraPostion.y; this._cameraPos.z=cameraPostion.z; return 2; } return 0; } __proto.assembleIndex=function(camera,cameraPostion){ var nNeedType=this.isNeedAssemble(camera,cameraPostion); if (nNeedType > 0){ for (var i=0;i < this._leafNum;i++){ TerrainFilter._TEMP_ARRAY_BUFFER[i]=this._leafs[i].determineLod(cameraPostion,this._perspectiveFactor,Terrain.LOD_TOLERANCE_VALUE,nNeedType==1); } if (this.setLODLevel(TerrainFilter._TEMP_ARRAY_BUFFER)){ this._currentNumberIndices=0; this._numberTriangle=0; var nOffsetIndex=0; for (i=0;i < this._leafNum;i++){ var nLODLevel=TerrainFilter._TEMP_ARRAY_BUFFER[i]; var planeLODIndex=TerrainLeaf.getPlaneLODIndex(i,nLODLevel); this._indexArrayBuffer.set(planeLODIndex,nOffsetIndex); nOffsetIndex+=planeLODIndex.length; var skirtLODIndex=TerrainLeaf.getSkirtLODIndex(i,nLODLevel); this._indexArrayBuffer.set(skirtLODIndex,nOffsetIndex); nOffsetIndex+=skirtLODIndex.length; this._currentNumberIndices+=(planeLODIndex.length+skirtLODIndex.length); } this._numberTriangle=this._currentNumberIndices / 3; return true; } } return false; } __proto.calcOriginalBoudingBoxAndSphere=function(){ var sizeOfY=new Vector2(2147483647,-2147483647); for (var i=0;i < this._leafNum;i++){ sizeOfY.x=this._leafs[i]._sizeOfY.x < sizeOfY.x ? this._leafs[i]._sizeOfY.x :sizeOfY.x; sizeOfY.y=this._leafs[i]._sizeOfY.y > sizeOfY.y ? this._leafs[i]._sizeOfY.y :sizeOfY.y; }; var min=new Vector3(this._chunkOffsetX *TerrainLeaf.CHUNK_GRID_NUM *this._gridSize,sizeOfY.x,this._chunkOffsetZ *TerrainLeaf.CHUNK_GRID_NUM *this._gridSize); var max=new Vector3((this._chunkOffsetX+1)*TerrainLeaf.CHUNK_GRID_NUM *this._gridSize,sizeOfY.y,(this._chunkOffsetZ+1)*TerrainLeaf.CHUNK_GRID_NUM *this._gridSize); if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(min,TerrainLeaf.__ADAPT_MATRIX__,min); Vector3.transformV3ToV3(max,TerrainLeaf.__ADAPT_MATRIX__,max); } this._boundingBox=new BoundBox(min,max); var size=new Vector3(); Vector3.subtract(max,min,size); Vector3.scale(size,0.5,size); var center=new Vector3(); Vector3.add(min,size,center); this._boundingSphere=new BoundSphere(center,Vector3.scalarLength(size)); this._boundingBoxCorners=__newvec(8,null); this._boundingBox.getCorners(this._boundingBoxCorners); } __proto.calcLeafBoudingBox=function(worldMatrix){ for (var i=0;i < this._leafNum;i++){ this._leafs[i].calcLeafBoudingBox(worldMatrix); } } __proto.calcLeafBoudingSphere=function(worldMatrix,maxScale){ for (var i=0;i < this._leafNum;i++){ this._leafs[i].calcLeafBoudingSphere(worldMatrix,maxScale); } } __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index==0){ return this._vertexBuffer; } return null; } __proto._getIndexBuffer=function(){ return this._indexBuffer; } __proto._beforeRender=function(state){ this._vertexBuffer._bind(); this._indexBuffer._bind(); var terrainMaterial=state.renderElement._material; if (terrainMaterial.blend==/*laya.d3.core.material.BaseMaterial.BLEND_DISABLE*/0){ var camera=state.camera; if (this.assembleIndex(camera,camera.position)){ this._indexBuffer.setData(this._indexArrayBuffer); } } return true; } /** *@private */ __proto._getVertexBuffers=function(){ return null; } __proto._render=function(state){ WebGL.mainContext.drawElements(Terrain.RENDER_LINE_MODEL ? /*laya.webgl.WebGLContext.LINES*/0x0001 :/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._currentNumberIndices,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.trianglesFaces+=this._numberTriangle; Stat.drawCall++; } /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingSphere',function(){ return this._boundingSphere; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBox',function(){ return this._boundingBox; }); __getset(0,__proto,'_vertexBufferCount',function(){ return this._numberVertices; }); __getset(0,__proto,'triangleCount',function(){ return this._numberTriangle; }); __static(TerrainFilter, ['_TEMP_ARRAY_BUFFER',function(){return this._TEMP_ARRAY_BUFFER=new Uint32Array(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM *TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM);} ]); return TerrainFilter; })(GeometryFilter) /** *MeshRender 类用于网格渲染器。 */ //class laya.d3.terrain.TerrainRender extends laya.d3.core.render.BaseRender var TerrainRender=(function(_super){ function TerrainRender(owner){ /**@private */ this._terrainSprite3DOwner=null; TerrainRender.__super.call(this,owner); this._terrainSprite3DOwner=owner; } __class(TerrainRender,'laya.d3.terrain.TerrainRender',_super); var __proto=TerrainRender.prototype; __proto._calculateBoundingSphere=function(){ var terrainFilter=this._terrainSprite3DOwner.terrainFilter; if (terrainFilter==null){ this._boundingSphere.toDefault(); }else { var meshBoundingSphere=terrainFilter._originalBoundingSphere; var maxScale=NaN; var transform=this._terrainSprite3DOwner.transform; var scale=transform.scale; if (scale.x >=scale.y && scale.x >=scale.z) maxScale=scale.x; else maxScale=scale.y >=scale.z ? scale.y :scale.z; Vector3.transformCoordinate(meshBoundingSphere.center,transform.worldMatrix,this._boundingSphere.center); this._boundingSphere.radius=meshBoundingSphere.radius *maxScale; terrainFilter.calcLeafBoudingSphere(transform.worldMatrix,maxScale); } } __proto._calculateBoundingBox=function(){ var terrainFilter=this._terrainSprite3DOwner.terrainFilter; if (terrainFilter==null){ this._boundingBox.toDefault(); }else { var worldMat=this._terrainSprite3DOwner.transform.worldMatrix; var corners=terrainFilter._boundingBoxCorners; for (var i=0;i < 8;i++) Vector3.transformCoordinate(corners[i],worldMat,BaseRender._tempBoundBoxCorners[i]); BoundBox.createfromPoints(BaseRender._tempBoundBoxCorners,this._boundingBox); terrainFilter.calcLeafBoudingBox(worldMat); } } /** *@private */ __proto._renderUpdate=function(projectionView){ this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,this._owner.transform.worldMatrix); var projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); return true; } /** *@private */ __proto._destroy=function(){ _super.prototype._destroy.call(this); this._terrainSprite3DOwner=null; } return TerrainRender; })(BaseRender) /** *... *@author ... */ //class laya.d3.water.WaterRender extends laya.d3.core.render.BaseRender var WaterRender=(function(_super){ function WaterRender(owner){ WaterRender.__super.call(this,owner); } __class(WaterRender,'laya.d3.water.WaterRender',_super); var __proto=WaterRender.prototype; __proto._calculateBoundingSphere=function(){} __proto._calculateBoundingBox=function(){} __proto._destroy=function(){ _super.prototype._destroy.call(this); } return WaterRender; })(BaseRender) /** *BaseScene 类用于实现场景。 */ //class laya.d3.core.scene.Scene extends laya.display.Sprite var Scene=(function(_super){ function Scene(){ this._time=0; /**@private */ //this.__loaded=false; /**@private */ //this._url=null; /**@private */ //this._group=null; /**@private */ //this._lightmaps=null; /**@private */ this._enableLightCount=3; /**@private */ //this._renderTargetTexture=null; /**@private */ this._customRenderQueneIndex=11; /**@private */ //this._lastCurrentTime=NaN; /**@private */ //this._enableFog=false; /**@private */ //this._enableDepthFog=false; /**@private */ //this._fogStart=NaN; /**@private */ //this._fogRange=NaN; /**@private */ //this._fogColor=null; /**@private */ //this._ambientColor=null; /**@private */ //this._shaderValues=null; /**@private */ //this._shaderDefineValue=0; /**@private */ //this._cullingRendersLength=0; /**@private */ //this._cullingRenders=null; /**@private */ //this._dynamicBatchManager=null; /**是否启用灯光。*/ this.enableLight=true; /**四/八叉树的根节点。*/ //this.treeRoot=null; /**四/八叉树的尺寸。*/ //this.treeSize=null; /**四/八叉树的层数。*/ //this.treeLevel=0; //阴影相关变量 //this.parallelSplitShadowMaps=null; /**@private */ //this._componentsMap=null; /**@private */ //this._typeComponentsIndices=null; /**@private */ //this._components=null; Scene.__super.call(this); this._renderState=new RenderState(); this._lights=[]; this._quenes=[]; this._cameraPool=[]; this._renderableSprite3Ds=[]; this.__loaded=true; this._lightmaps=[]; this._shaderValues=new ValusArray(); this.parallelSplitShadowMaps=[]; this._dynamicBatchManager=new DynamicBatchManager(); this._cullingRenders=[]; this._cullingRendersLength=0; this.enableFog=false; this.fogStart=300; this.fogRange=1000; this.fogColor=new Vector3(0.7,0.7,0.7); this.ambientColor=new Vector3(0.212,0.227,0.259); (WebGL.shaderHighPrecision)&& (this.addShaderDefine(ShaderCompile3D.SHADERDEFINE_HIGHPRECISION)); this.on(/*laya.events.Event.DISPLAY*/"display",this,this._display); this.on(/*laya.events.Event.UNDISPLAY*/"undisplay",this,this._unDisplay); this._componentsMap=[]; this._typeComponentsIndices=[]; this._components=[]; } __class(Scene,'laya.d3.core.scene.Scene',_super); var __proto=Scene.prototype; Laya.imps(__proto,{"laya.webgl.submit.ISubmit":true,"laya.resource.ICreateResource":true}) /** *@private */ __proto._setUrl=function(url){ this._url=url; } /** *@private */ __proto._getGroup=function(){ return this._group; } /** *@private */ __proto._setGroup=function(value){ this._group=value; } /** *@private */ __proto._display=function(){ Laya.stage._scenes.push(this); Laya.stage._scenes.sort(Scene._sortScenes); for (var i=0,n=this._childs.length;i < n;i++){ var spr=this._childs[i]; (spr.active)&& (spr._activeHierarchy()); } } /** *@private */ __proto._unDisplay=function(){ var scenes=Laya.stage._scenes; scenes.splice(scenes.indexOf(this),1); for (var i=0,n=this._childs.length;i < n;i++){ var spr=this._childs[i]; (spr.active)&& (spr._inActiveHierarchy()); } } /** *@private */ __proto._addChild3D=function(sprite3D){ sprite3D.transform._onWorldTransform(); sprite3D._setBelongScene(this); (this.displayedInStage && sprite3D.active)&& (sprite3D._activeHierarchy()); } /** *@private */ __proto._removeChild3D=function(sprite3D){ sprite3D.transform.parent=null; (this.displayedInStage && sprite3D.active)&& (sprite3D._inActiveHierarchy()); sprite3D._setUnBelongScene(); } /** *初始化八叉树。 *@param width 八叉树宽度。 *@param height 八叉树高度。 *@param depth 八叉树深度。 *@param center 八叉树中心点 *@param level 八叉树层级。 */ __proto.initOctree=function(width,height,depth,center,level){ (level===void 0)&& (level=6); this.treeSize=new Vector3(width,height,depth); this.treeLevel=level; this.treeRoot=new OctreeNode(this,0); this.treeRoot.init(center,this.treeSize); } /** *@private *场景相关渲染准备设置。 *@param gl WebGL上下文。 *@return state 渲染状态。 */ __proto._prepareUpdateToRenderState=function(gl,state){ state.elapsedTime=this._lastCurrentTime ? this.timer.currTimer-this._lastCurrentTime :0; this._lastCurrentTime=this.timer.currTimer; state.scene=this; } /** *@private */ __proto._prepareSceneToRender=function(state){ var lightCount=this._lights.length; if (lightCount > 0){ var renderLightCount=0; for (var i=0;i < lightCount;i++){ if (!this._lights[i]._prepareToScene(state)) continue ; renderLightCount++; if (renderLightCount >=this._enableLightCount) break ; } } } /** *@private */ __proto._updateChilds=function(state){ for (var i=0,n=this._childs.length;i < n;++i) this._childs[i]._update(state); } /** *@private */ __proto._preRenderScene=function(gl,state,boundFrustum){ var view=state._viewMatrix; var projection=state._projectionMatrix; var projectionView=state._projectionViewMatrix; var i=0,iNum=0; var camera=state.camera; if (camera.useOcclusionCulling){ if (this.treeRoot) FrustumCulling.renderObjectCullingOctree(boundFrustum,this,camera,view,projection,projectionView); else FrustumCulling.renderObjectCulling(boundFrustum,this,camera,view,projection,projectionView); }else { FrustumCulling.renderObjectCullingNoBoundFrustum(this,camera,view,projection,projectionView); } for (i=0,iNum=this._quenes.length;i < iNum;i++) (this._quenes[i])&& (this._quenes[i]._preRender(state)); } /** *@private */ __proto._clear=function(gl,state){ var viewport=state._viewport; var camera=state.camera; var vpX=viewport.x; var vpY=camera.renderTargetSize.height-viewport.y-viewport.height; var vpWidth=viewport.width; var vpHeight=viewport.height; gl.viewport(vpX,vpY,vpWidth,vpHeight); var flag=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; var renderTarget=camera.renderTarget; switch (camera.clearFlag){ case /*laya.d3.core.BaseCamera.CLEARFLAG_SOLIDCOLOR*/0:; var clearColor=camera.clearColor; if (clearColor){ gl.enable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); gl.scissor(vpX,vpY,vpWidth,vpHeight); var clearColorE=clearColor.elements; gl.clearColor(clearColorE[0],clearColorE[1],clearColorE[2],clearColorE[3]); flag |=/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000; } if (renderTarget){ (clearColor)|| (flag=/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000); switch (renderTarget.depthStencilFormat){ case /*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5: flag |=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; break ; case /*laya.webgl.WebGLContext.STENCIL_INDEX8*/0x8D48: flag |=/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400; break ; case /*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9: flag |=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; flag |=/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400; break ; } } gl.clear(flag); if (clearColor) gl.disable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); break ; case /*laya.d3.core.BaseCamera.CLEARFLAG_SKY*/1: case /*laya.d3.core.BaseCamera.CLEARFLAG_DEPTHONLY*/2: if (renderTarget){ flag=/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000; switch (renderTarget.depthStencilFormat){ case /*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5: flag |=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; break ; case /*laya.webgl.WebGLContext.STENCIL_INDEX8*/0x8D48: flag |=/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400; break ; case /*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9: flag |=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; flag |=/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400 break ; } } gl.clear(flag); break ; case /*laya.d3.core.BaseCamera.CLEARFLAG_NONE*/3: break ; default : throw new Error("BaseScene:camera clearFlag invalid."); } } /** *@private */ __proto._renderScene=function(gl,state){ var camera=state.camera; var i=0,n=0; var queue; for (i=0;i < 2;i++){ queue=this._quenes[i]; if (queue){ camera.renderTarget ? queue._render(state,true):queue._render(state,false); } } if (camera.clearFlag===/*laya.d3.core.BaseCamera.CLEARFLAG_SKY*/1){ var sky=camera.sky; if (sky){ WebGLContext.setCullFace(gl,false); WebGLContext.setDepthFunc(gl,/*laya.webgl.WebGLContext.LEQUAL*/0x0203); WebGLContext.setDepthMask(gl,false); sky._render(state); WebGLContext.setDepthFunc(gl,/*laya.webgl.WebGLContext.LESS*/0x0201); WebGLContext.setDepthMask(gl,true); } } for (i=2,n=this._quenes.length;i < n;i++){ queue=this._quenes[i]; if (queue){ queue._sortAlpha(state.camera.transform.position); camera.renderTarget ? queue._render(state,true):queue._render(state,false); } } } /** *@private */ __proto._set3DRenderConfig=function(gl){ gl.disable(/*laya.webgl.WebGLContext.BLEND*/0x0BE2); WebGLContext._blend=false; gl.blendFunc(/*laya.webgl.WebGLContext.SRC_ALPHA*/0x0302,/*laya.webgl.WebGLContext.ONE_MINUS_SRC_ALPHA*/0x0303); WebGLContext._sFactor=/*laya.webgl.WebGLContext.SRC_ALPHA*/0x0302; WebGLContext._dFactor=/*laya.webgl.WebGLContext.ONE_MINUS_SRC_ALPHA*/0x0303; gl.disable(/*laya.webgl.WebGLContext.DEPTH_TEST*/0x0B71); WebGLContext._depthTest=false; gl.enable(/*laya.webgl.WebGLContext.CULL_FACE*/0x0B44); WebGLContext._cullFace=true; gl.depthMask(1); WebGLContext._depthMask=true; gl.frontFace(/*laya.webgl.WebGLContext.CW*/0x0900); WebGLContext._frontFace=/*laya.webgl.WebGLContext.CW*/0x0900; } /** *@private */ __proto._set2DRenderConfig=function(gl){ WebGLContext.setBlend(gl,true); WebGLContext.setBlendFunc(gl,/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.ONE_MINUS_SRC_ALPHA*/0x0303); WebGLContext.setDepthTest(gl,false); WebGLContext.setCullFace(gl,false); WebGLContext.setDepthMask(gl,true); WebGLContext.setFrontFace(gl,/*laya.webgl.WebGLContext.CCW*/0x0901); gl.viewport(0,0,RenderState2D.width,RenderState2D.height); } /** *@private */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,nodeData){ var lightMapsData=nodeData.customProps.lightmaps; var lightMapCount=lightMapsData.length; var lightmaps=this._lightmaps; lightmaps.length=lightMapCount; for (var i=0;i < lightMapCount;i++) lightmaps[i]=Loader.getRes(innerResouMap[lightMapsData[i].replace(".exr",".png")]); this.setlightmaps(lightmaps); var ambientColorData=nodeData.customProps.ambientColor; (ambientColorData)&& (this.ambientColor=new Vector3(ambientColorData[0],ambientColorData[1],ambientColorData[2])); var fogColorData=nodeData.customProps.fogColor; (fogColorData)&& (this.fogColor=new Vector3(fogColorData[0],fogColorData[1],fogColorData[2])); } /** *@private */ __proto._addLight=function(light){ if (this._lights.indexOf(light)< 0)this._lights.push(light); } /** *@private */ __proto._removeLight=function(light){ var index=this._lights.indexOf(light); index >=0 && (this._lights.splice(index,1)); } /** *@private */ __proto._updateScene=function(){ var renderState=this._renderState; this._prepareUpdateToRenderState(WebGL.mainContext,renderState); this._updateComponents(renderState); this._updateChilds(renderState); this._lateUpdateComponents(renderState); this._time+=renderState.elapsedTime / 1000; this._shaderValues.setValue(/*CLASS CONST:laya.d3.core.scene.Scene.TIME*/22,this._time); } /** *@private */ __proto._updateSceneConch=function(){ var renderState=this._renderState; this._prepareUpdateToRenderState(WebGL.mainContext,renderState); this._updateComponents(renderState); this._lateUpdateComponents(renderState); this._prepareSceneToRender(renderState); for (var i=0,n=this._cameraPool.length;i < n;i++){ var camera=this._cameraPool[i]; renderState.camera=camera; camera._prepareCameraToRender(); } } /** *@private */ __proto._preRenderShadow=function(state,lightFrustum,shdowQueues,lightViewProjectMatrix,nPSSMNum){ if (this.treeRoot){ FrustumCulling.renderShadowObjectCullingOctree(this,lightFrustum,shdowQueues,lightViewProjectMatrix,nPSSMNum); }else { FrustumCulling.renderShadowObjectCulling(this,lightFrustum,shdowQueues,lightViewProjectMatrix,nPSSMNum); } for (var i=0,iNum=shdowQueues.length;i < iNum;i++) (shdowQueues[i])&& (shdowQueues[i]._preRender(state)); } /** *@private */ __proto._renderShadowMap=function(gl,state,sceneCamera){ var parallelSplitShadowMap=this.parallelSplitShadowMaps[0]; parallelSplitShadowMap._calcAllLightCameraInfo(sceneCamera); var pssmNum=parallelSplitShadowMap.PSSMNum; this._preRenderShadow(state,parallelSplitShadowMap._lightCulling,parallelSplitShadowMap._shadowQuenes,parallelSplitShadowMap._lightVPMatrix[0],pssmNum); this.addShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_CAST_SHADOW); var renderTarget,shadowQuene,lightCamera; if (pssmNum > 1){ for (var i=0;i < pssmNum;i++){ renderTarget=parallelSplitShadowMap.getRenderTarget(i+1); parallelSplitShadowMap.beginRenderTarget(i+1); gl.clearColor(1,1,1,1); gl.clear(/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000 | /*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100); gl.viewport(0,0,renderTarget.width,renderTarget.height); state.camera=lightCamera=parallelSplitShadowMap.getLightCamera(i); lightCamera._prepareCameraToRender(); lightCamera._prepareCameraViewProject(lightCamera.viewMatrix,lightCamera.projectionMatrix); state._projectionViewMatrix=parallelSplitShadowMap._lightVPMatrix[i+1]; shadowQuene=parallelSplitShadowMap._shadowQuenes[i]; shadowQuene._preRender(state); shadowQuene._renderShadow(state,false); parallelSplitShadowMap.endRenderTarget(i+1); } }else { renderTarget=parallelSplitShadowMap.getRenderTarget(1); parallelSplitShadowMap.beginRenderTarget(1); gl.clearColor(1,1,1,1); gl.clear(/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000 | /*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100); gl.viewport(0,0,renderTarget.width,renderTarget.height); state.camera=lightCamera=parallelSplitShadowMap.getLightCamera(0); lightCamera._prepareCameraToRender(); lightCamera._prepareCameraViewProject(lightCamera.viewMatrix,lightCamera.projectionMatrix); state._projectionViewMatrix=parallelSplitShadowMap._lightVPMatrix[0]; shadowQuene=parallelSplitShadowMap._shadowQuenes[0]; shadowQuene._preRender(state); shadowQuene._renderShadow(state,true); parallelSplitShadowMap.endRenderTarget(1); } this.removeShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_CAST_SHADOW); } /** *@private */ __proto.addTreeNode=function(renderObj){ this.treeRoot.addTreeNode(renderObj); } /** *@private */ __proto.removeTreeNode=function(renderObj){ if (!this.treeSize)return; if (renderObj._treeNode){ renderObj._treeNode.removeObject(renderObj); } } /** *设置光照贴图。 *@param value 光照贴图。 */ __proto.setlightmaps=function(value){ this._lightmaps=value; for (var i=0,n=this._renderableSprite3Ds.length;i < n;i++) this._renderableSprite3Ds[i]._render._applyLightMapParams(); } /** *获取光照贴图。 *@return 获取光照贴图。 */ __proto.getlightmaps=function(){ return this._lightmaps; } /** *@inheritDoc */ __proto.addChildAt=function(node,index){ if (!((node instanceof laya.d3.core.Sprite3D ))) throw new Error("Sprite3D:Node type must Sprite3D."); if (!node || this.destroyed || node===this)return node; if ((node).zOrder)this._set$P("hasZorder",true); if (index >=0 && index <=this._childs.length){ if (node._parent===this){ var oldIndex=this.getChildIndex(node); this._childs.splice(oldIndex,1); this._childs.splice(index,0,node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,index); } this._childChanged(); }else { node.parent && node.parent.removeChild(node); this._childs===Node.ARRAY_EMPTY && (this._childs=[]); this._childs.splice(index,0,node); this.conchModel && this.conchModel.addChildAt(node.conchModel,index); node.parent=this; this._addChild3D(node); } return node; }else { throw new Error("appendChildAt:The index is out of bounds"); } } /** *@inheritDoc */ __proto.addChild=function(node){ if (!((node instanceof laya.d3.core.Sprite3D ))) throw new Error("Sprite3D:Node type must Sprite3D."); if (!node || this.destroyed || node===this)return node; if ((node).zOrder)this._set$P("hasZorder",true); if (node._parent===this){ var index=this.getChildIndex(node); if (index!==this._childs.length-1){ this._childs.splice(index,1); this._childs.push(node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,this._childs.length-1); } this._childChanged(); } }else { node.parent && node.parent.removeChild(node); this._childs===Node.ARRAY_EMPTY && (this._childs=[]); this._childs.push(node); this.conchModel && this.conchModel.addChildAt(node.conchModel,this._childs.length-1); node.parent=this; this._childChanged(); this._addChild3D(node); } return node; } /** *@inheritDoc */ __proto.removeChildAt=function(index){ var node=this.getChildAt(index); if (node){ this._removeChild3D(node); this._childs.splice(index,1); this.conchModel && this.conchModel.removeChild(node.conchModel); node.parent=null; } return node; } /** *@inheritDoc */ __proto.removeChildren=function(beginIndex,endIndex){ (beginIndex===void 0)&& (beginIndex=0); (endIndex===void 0)&& (endIndex=0x7fffffff); if (this._childs && this._childs.length > 0){ var childs=this._childs; if (beginIndex===0 && endIndex >=n){ var arr=childs; this._childs=Node.ARRAY_EMPTY; }else { arr=childs.splice(beginIndex,endIndex-beginIndex); } for (var i=0,n=arr.length;i < n;i++){ this._removeChild3D(arr [i]); arr[i].parent=null; this.conchModel && this.conchModel.removeChild(arr[i].conchModel); } } return this; } /** *@inheritDoc */ __proto.addFrustumCullingObject=function(renderObject){ if (this.treeRoot){ this.addTreeNode(renderObject); }else { if (this._cullingRendersLength===this._cullingRenders.length) this._cullingRenders.push(renderObject); else this._cullingRenders[this._cullingRendersLength]=renderObject; renderObject._indexInSceneFrustumCullingObjects=this._cullingRendersLength++; } } /** *@private */ __proto.removeFrustumCullingObject=function(renderObject){ if (this.treeRoot){ this.removeTreeNode(renderObject); }else { this._cullingRendersLength--; var indexInSceneFrustumCullingObjects=renderObject._indexInSceneFrustumCullingObjects; if (indexInSceneFrustumCullingObjects!==this._cullingRendersLength){ var endRender=this._cullingRenders[this._cullingRendersLength]; this._cullingRenders[indexInSceneFrustumCullingObjects]=endRender; endRender._indexInSceneFrustumCullingObjects=indexInSceneFrustumCullingObjects; renderObject._indexInSceneFrustumCullingObjects=-1; } } } /** *获得某个渲染队列。 *@param index 渲染队列索引。 *@return 渲染队列。 */ __proto.getRenderQueue=function(index){ if (index < 3000) return this._quenes[1] || (this._quenes[1]=new RenderQueue(this)); else return this._quenes[2] || (this._quenes[2]=new RenderQueue(this)); } /** *添加渲染队列。 *@param renderConfig 渲染队列配置文件。 */ __proto.addRenderQuene=function(){ this._quenes[this._customRenderQueneIndex++]=new RenderQueue(this); } /** *增加shader宏定义。 *@param define shader宏定义。 */ __proto.addShaderDefine=function(define){ this._shaderDefineValue |=define; } /** *移除shader宏定义。 *@param define shader宏定义。 */ __proto.removeShaderDefine=function(define){ this._shaderDefineValue &=~define; } /** *添加指定类型脚本。 *@param type 脚本类型。 *@return 组件。 */ __proto.addScript=function(type){ return this._addComponent(type); } /** *通过指定类型和类型索引获得脚本。 *@param type 脚本类型。 *@param typeIndex 脚本索引。 *@return 脚本。 */ __proto.getScriptByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); return this._getComponentByType(type,typeIndex); } /** *通过指定类型获得所有脚本。 *@param type 脚本类型。 *@param scripts 脚本输出队列。 */ __proto.getScriptsByType=function(type,scripts){ this._getComponentsByType(type,scripts); } /** *通过指定索引获得脚本。 *@param index 索引。 *@return 脚本。 */ __proto.getScriptByIndex=function(index){ return this._getComponentByIndex(index); } /** *通过指定类型和类型索引移除脚本。 *@param type 脚本类型。 *@param typeIndex 类型索引。 */ __proto.removeScriptByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); this._removeComponentByType(type,typeIndex); } /** *通过指定类型移除所有脚本。 *@param type 组件类型。 */ __proto.removeScriptsByType=function(type){ this._removeComponentByType(type); } /** *移除全部脚本。 */ __proto.removeAllScript=function(){ this._removeAllComponent(); } /** *@private */ __proto.render=function(context,x,y){ (Render._context.ctx)._renderKey=0; this._childs.length > 0 && context.addRenderObject(this); } /** *@private */ __proto.renderSubmit=function(){ var gl=WebGL.mainContext; var renderState=this._renderState; this._set3DRenderConfig(gl); this._prepareSceneToRender(this._renderState); var i=0,n=0,camera; if (Laya3D.debugMode || OctreeNode.debugMode){ for (i=0,n=this._cameraPool.length;i < n;i++){ camera=this._cameraPool[i]; Laya3D._debugPhasorSprite.begin(/*laya.webgl.WebGLContext.LINES*/0x0001,camera); (camera.activeInHierarchy)&& (camera._renderCamera(gl,renderState,this)); Laya3D._debugPhasorSprite.end(); } }else { for (i=0,n=this._cameraPool.length;i < n;i++){ camera=this._cameraPool[i]; (camera.activeInHierarchy)&& (camera._renderCamera(gl,renderState,this)); } } this._set2DRenderConfig(gl); return 1; } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ var json=data[0] if (json.type!=="Scene") throw new Error("Scene: the .lh file root type must be Scene,please use other function to load this file."); var innerResouMap=data[1]; Utils3D._createNodeByJson(this,json,this,innerResouMap); this.event(/*laya.events.Event.HIERARCHY_LOADED*/"hierarchyloaded",[this]); this.__loaded=true; } /** *@private */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); this._renderState=null; this._lights=null; this._lightmaps=null; this._renderTargetTexture=null; this._shaderValues=null; this._cullingRenders=null; this._dynamicBatchManager=null; this._quenes=null; this._cameraPool=null; this._renderableSprite3Ds=null; this.treeRoot=null; this.treeSize=null; this.parallelSplitShadowMaps=null; this._typeComponentsIndices=null; this._components=null; Loader.clearRes(this.url); (this.loaded)|| (Laya3D._cancelLoadByUrl(this.url)); } /** *@private */ __proto.getRenderType=function(){ return 0; } /** *@private */ __proto.releaseRender=function(){} /** *@private */ __proto._addComponent=function(type){ var typeComponentIndex; var index=this._componentsMap.indexOf(type); if (index===-1){ typeComponentIndex=[]; this._componentsMap.push(type); this._typeComponentsIndices.push(typeComponentIndex); }else { typeComponentIndex=this._typeComponentsIndices[index]; if (this._components[typeComponentIndex[0]].isSingleton) throw new Error("无法单实例创建"+type+"组件"+","+type+"组件已存在!"); }; var component=ClassUtils.getInstance(type); typeComponentIndex.push(this._components.length); this._components.push(component); var _this=this; component._initialize(_this); return component; } /** *@private */ __proto._removeComponent=function(mapIndex,index){ var componentIndices=this._typeComponentsIndices[mapIndex]; var componentIndex=componentIndices[index]; var component=this._components[componentIndex]; this._components.splice(componentIndex,1); componentIndices.splice(index,1); (componentIndices.length===0)&& (this._typeComponentsIndices.splice(mapIndex,1),this._componentsMap.splice(mapIndex,1)); for (var i=0,n=this._componentsMap.length;i < n;i++){ componentIndices=this._typeComponentsIndices[i]; for (var j=componentIndices.length-1;j >=0;j--){ var oldComponentIndex=componentIndices[j]; if (oldComponentIndex > componentIndex) componentIndices[j]=--oldComponentIndex; else break ; } } component._destroy(); } /** *@private */ __proto._getComponentByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return null; return this._components[this._typeComponentsIndices[mapIndex][typeIndex]]; } /** *@private */ __proto._getComponentsByType=function(type,components){ var index=this._componentsMap.indexOf(type); if (index===-1){ components.length=0; return; }; var typeComponents=this._typeComponentsIndices[index]; var count=typeComponents.length; components.length=count; for (var i=0;i < count;i++) components[i]=this._components[typeComponents[i]]; } /** *@private */ __proto._getComponentByIndex=function(index){ return this._components[index]; } /** *@private */ __proto._removeComponentByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return; this._removeComponent(mapIndex,typeIndex); } /** *@private */ __proto._removeComponentsByType=function(type){ var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return; var componentIndices=this._typeComponentsIndices[mapIndex]; for (var i=0,n=componentIndices.length;i < n;componentIndices.length < n ? n--:i++) this._removeComponent(mapIndex,i); } /** *@private */ __proto._removeAllComponent=function(){ for (var i=0,n=this._componentsMap.length;i < n;this._componentsMap.length < n ? n--:i++) this._removeComponentsByType(this._componentsMap[i]); } /** *@private */ __proto._updateComponents=function(state){ for (var i=0,n=this._components.length;i < n;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._update(state)); } } /** *@private */ __proto._lateUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._lateUpdate(state)); } } /** *@private */ __proto._preRenderUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._preRenderUpdate(state)); } } /** *@private */ __proto._postRenderUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._postRenderUpdate(state)); } } /** *@private */ __getset(0,__proto,'_loaded',null,function(value){ this.__loaded=value; }); /** *设置雾化颜色。 *@param value 雾化颜色。 */ /** *获取雾化颜色。 *@return 雾化颜色。 */ __getset(0,__proto,'fogColor',function(){ return this._fogColor; },function(value){ this._fogColor=value; this._shaderValues.setValue(/*CLASS CONST:laya.d3.core.scene.Scene.FOGCOLOR*/0,value.elements); }); /** *设置是否允许雾化。 *@param value 是否允许雾化。 */ /** *获取是否允许雾化。 *@return 是否允许雾化。 */ __getset(0,__proto,'enableFog',function(){ return this._enableFog; },function(value){ if (this._enableFog!==value){ this._enableFog=value; if (value){ this.addShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); this.removeShaderDefine(ShaderCompile3D.SAHDERDEFINE_DEPTHFOG); }else this.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); } }); /** *获取资源的URL地址。 *@return URL地址。 */ __getset(0,__proto,'url',function(){ return this._url; }); /** *获取是否已加载完成。 */ __getset(0,__proto,'loaded',function(){ return this.__loaded; }); __getset(0,__proto,'enableDepthFog',function(){ return this._enableDepthFog; },function(v){ if (this._enableDepthFog !=v){ this._enableDepthFog=v; if (v){ this.addShaderDefine(ShaderCompile3D.SAHDERDEFINE_DEPTHFOG); this.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); }else { this.removeShaderDefine(ShaderCompile3D.SAHDERDEFINE_DEPTHFOG); } } }); /** *设置雾化起始位置。 *@param value 雾化起始位置。 */ /** *获取雾化起始位置。 *@return 雾化起始位置。 */ __getset(0,__proto,'fogStart',function(){ return this._fogStart; },function(value){ this._fogStart=value; this._shaderValues.setValue(/*CLASS CONST:laya.d3.core.scene.Scene.FOGSTART*/1,value); }); /** *设置雾化范围。 *@param value 雾化范围。 */ /** *获取雾化范围。 *@return 雾化范围。 */ __getset(0,__proto,'fogRange',function(){ return this._fogRange; },function(value){ this._fogRange=value; this._shaderValues.setValue(/*CLASS CONST:laya.d3.core.scene.Scene.FOGRANGE*/2,value); }); /** *设置环境光颜色。 *@param value 环境光颜色。 */ /** *获取环境光颜色。 *@return 环境光颜色。 */ __getset(0,__proto,'ambientColor',function(){ return this._ambientColor; },function(value){ this._ambientColor=value; this._shaderValues.setValue(/*CLASS CONST:laya.d3.core.scene.Scene.AMBIENTCOLOR*/21,value.elements); }); /** *获取当前场景。 *@return 当前场景。 */ __getset(0,__proto,'scene',function(){ return this; }); /** *获取场景的可渲染精灵。 */ __getset(0,__proto,'renderableSprite3Ds',function(){ return this._renderableSprite3Ds.slice(); }); Scene._sortScenes=function(a,b){ if (a.parent===Laya.stage && b.parent===Laya.stage){ var stageChildren=Laya.stage._childs; return stageChildren.indexOf(a)-stageChildren.indexOf(b); }else if (a.parent!==Laya.stage && b.parent!==Laya.stage){ return Scene._sortScenes(a.parent,b.parent); }else { return (a.parent===Laya.stage)?-1 :1; } } Scene.load=function(url){ return Laya.loader.create(url,null,null,Scene); } Scene.FOGCOLOR=0; Scene.FOGSTART=1; Scene.FOGRANGE=2; Scene.LIGHTDIRECTION=3; Scene.LIGHTDIRCOLOR=4; Scene.POINTLIGHTPOS=5; Scene.POINTLIGHTRANGE=6; Scene.POINTLIGHTATTENUATION=7; Scene.POINTLIGHTCOLOR=8; Scene.SPOTLIGHTPOS=9; Scene.SPOTLIGHTDIRECTION=10; Scene.SPOTLIGHTSPOT=11; Scene.SPOTLIGHTRANGE=12; Scene.SPOTLIGHTATTENUATION=13; Scene.SPOTLIGHTCOLOR=14; Scene.SHADOWDISTANCE=15; Scene.SHADOWLIGHTVIEWPROJECT=16; Scene.SHADOWMAPPCFOFFSET=17; Scene.SHADOWMAPTEXTURE1=18; Scene.SHADOWMAPTEXTURE2=19; Scene.SHADOWMAPTEXTURE3=20; Scene.AMBIENTCOLOR=21; Scene.TIME=22; return Scene; })(Sprite) /** *Sprite3D 类用于实现3D精灵。 */ //class laya.d3.core.Sprite3D extends laya.d3.core.ComponentNode var Sprite3D=(function(_super){ function Sprite3D(name){ /**@private */ //this._projectionViewWorldMatrix=null; /**@private */ //this._projectionViewWorldUpdateLoopCount=0; /**@private */ //this._projectionViewWorldUpdateCamera=null; /**@private */ //this._id=0; /**@private */ //this.__loaded=false; /**@private */ //this._url=null; /**@private */ //this._group=null; /**@private */ //this._active=false; /**@private */ //this._activeInHierarchy=false; /**@private */ //this._layer=null; /**@private */ //this._shaderDefineValue=0; /**@private */ //this._shaderValues=null; /**@private */ //this._colliders=null; /**@private */ //this._scene=null; /**@private */ //this._transform=null; /**@private */ //this._hierarchyAnimator=null; /**是否静态,静态包含一系列的静态处理。*/ //this.isStatic=false; Sprite3D.__super.call(this); this.__loaded=true; this._projectionViewWorldUpdateLoopCount=-1; this._activeInHierarchy=false; this._projectionViewWorldMatrix=new Matrix4x4(); this._shaderValues=new ValusArray(); this._colliders=[]; this._id=++Sprite3D._uniqueIDCounter; this._transform=new Transform3D(this); this.name=name ? name :"Sprite3D-"+Sprite3D._nameNumberCounter++; this.layer=Layer.currentCreationLayer; this.active=true; } __class(Sprite3D,'laya.d3.core.Sprite3D',_super); var __proto=Sprite3D.prototype; Laya.imps(__proto,{"laya.d3.core.render.IUpdate":true,"laya.resource.ICreateResource":true,"laya.d3.core.IClone":true}) /** *@private */ __proto._setUrl=function(url){ this._url=url; } /** *@private */ __proto._getGroup=function(){ return this._group; } /** *@private */ __proto._setGroup=function(value){ this._group=value; } /** *@private */ __proto._addChild3D=function(sprite3D){ sprite3D.transform.parent=this.transform; if (this._hierarchyAnimator){ (!sprite3D._hierarchyAnimator)&& (sprite3D._setHierarchyAnimator(this._hierarchyAnimator,null)); this._getAnimatorToLinkSprite3D(sprite3D,true,/*new vector.<>*/[sprite3D.name]); } if (this._scene){ sprite3D._setBelongScene(this._scene); (this._activeInHierarchy && sprite3D._active)&& (sprite3D._activeHierarchy()); } } /** *@private */ __proto._removeChild3D=function(sprite3D){ sprite3D.transform.parent=null; if (this._scene){ (this._activeInHierarchy && sprite3D._active)&& (sprite3D._inActiveHierarchy()); sprite3D._setUnBelongScene(); } if (this._hierarchyAnimator){ ((sprite3D._hierarchyAnimator==this._hierarchyAnimator))&& (sprite3D._clearHierarchyAnimator(this._hierarchyAnimator,null)); this._getAnimatorToLinkSprite3D(sprite3D,false,/*new vector.<>*/[sprite3D.name]); } } /** *@private */ __proto._parseBaseCustomProps=function(customProps){ var loccalPosition=this.transform.localPosition; loccalPosition.fromArray(customProps.translate); this.transform.localPosition=loccalPosition; var localRotation=this.transform.localRotation; localRotation.fromArray(customProps.rotation); this.transform.localRotation=localRotation; var localScale=this.transform.localScale; localScale.fromArray(customProps.scale); this.transform.localScale=localScale; var layerData=customProps.layer; (layerData !=null)&& (this.layer=Layer.getLayerByNumber(layerData)); } /** *@private */ __proto._parseCustomComponent=function(rootNode,innerResouMap,componentsData){ for (var k in componentsData){ var component=componentsData[k]; switch (k){ case "Animator":; var animator=this.addComponent(Animator); if (component.avatarPath){ animator.avatar=Loader.getRes(innerResouMap[component.avatarPath]); }else { var avatarData=component.avatar; if (avatarData){ animator.avatar=Loader.getRes(innerResouMap[avatarData.path]); var linkSprites=avatarData.linkSprites; (linkSprites)&& (rootNode.once(/*laya.events.Event.HIERARCHY_LOADED*/"hierarchyloaded",this,this._onRootNodeHierarchyLoaded,[animator,linkSprites])); } }; var clipPaths=component.clipPaths; var clipCount=clipPaths.length; for (var i=0;i < clipCount;i++) animator.addClip(Loader.getRes(innerResouMap[clipPaths[i]])); animator.clip=Loader.getRes(innerResouMap[clipPaths[0]]); var playOnWake=component.playOnWake; (playOnWake!==undefined)&& (animator.playOnWake=playOnWake); break ; case "Rigidbody":; var rigidbody=this.addComponent(Rigidbody); break ; case "SphereCollider":; var sphereCollider=this.addComponent(SphereCollider); sphereCollider.isTrigger=component.isTrigger; var center=sphereCollider.center; center.fromArray(component.center); sphereCollider.center=center; sphereCollider.radius=component.radius; break ; case "BoxCollider":; var boxCollider=this.addComponent(BoxCollider); boxCollider.isTrigger=component.isTrigger; boxCollider.center.fromArray(component.center); var size=boxCollider.size; size.fromArray(component.size); boxCollider.size=size; break ; case "MeshCollider":; var meshCollider=this.addComponent(MeshCollider); break ; default : } } } /** *@private */ __proto._onRootNodeHierarchyLoaded=function(animator,linkSprites){ for (var k in linkSprites){ var nodeOwner=this; var path=linkSprites[k]; for (var j=0,m=path.length;j < m;j++){ var p=path[j]; if (p===""){ break ; }else { nodeOwner=nodeOwner.getChildByName(p); if (!nodeOwner) break ; } } (nodeOwner)&& (animator.linkSprite3DToAvatarNode(k,nodeOwner)); } } /** *@private */ __proto._setHierarchyAnimator=function(animator,parentAnimator){ this._changeHierarchyAnimator(animator); for (var i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; (child._hierarchyAnimator==parentAnimator)&& (child._setHierarchyAnimator(animator,parentAnimator)); } } /** *@private */ __proto._clearHierarchyAnimator=function(animator,parentAnimator){ this._changeHierarchyAnimator(parentAnimator); for (var i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; (child._hierarchyAnimator==animator)&& (child._clearHierarchyAnimator(animator,parentAnimator)); } } /** *@private */ __proto._getAnimatorToLinkSprite3D=function(sprite3D,isLink,path){ var animator=this.getComponentByType(Animator); if (animator){ if (animator.avatar){ (animator.avatar._version)|| (sprite3D._setAnimatorToLinkAvatar(animator,isLink)); }else { sprite3D._setAnimatorToLinkSprite3DNoAvatar(animator,isLink,path); } } if (this._parent && (this._parent instanceof laya.d3.core.Sprite3D )){ path.unshift(this._parent.name); var p=this._parent; (p._hierarchyAnimator)&& (p._getAnimatorToLinkSprite3D(sprite3D,isLink,path)); } } /** *@private */ __proto._setAnimatorToLinkSprite3DNoAvatar=function(animator,isLink,path){ var i=0,n=0; for (i=0,n=animator.getClipCount();i < n;i++) animator._handleSpriteOwnersBySprite(i,isLink,path,this); for (i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; var index=path.length; path.push(child.name); child._setAnimatorToLinkSprite3DNoAvatar(animator,isLink,path); path.splice(index,1); } } /** *@private */ __proto._changeHierarchyAnimator=function(animator){ this._hierarchyAnimator=animator; } /** *@private */ __proto._isLinkSpriteToAnimationNode=function(animator,node,isLink){ var nodeIndex=animator._avatarNodes.indexOf(node); var cacheSpriteToNodesMap=animator._cacheSpriteToNodesMap; if (isLink){ this._transform.dummy=node.transform; animator._cacheNodesToSpriteMap[nodeIndex]=cacheSpriteToNodesMap.length; cacheSpriteToNodesMap.push(nodeIndex); }else { this._transform.dummy=null; var index=animator._cacheNodesToSpriteMap[nodeIndex]; animator._cacheNodesToSpriteMap[nodeIndex]=null; cacheSpriteToNodesMap.splice(index,1); } } /** *@private */ __proto._setBelongScene=function(scene){ this._scene=scene; for (var i=0,n=this._childs.length;i < n;i++) (this._childs [i])._setBelongScene(scene); } /** *@private */ __proto._setUnBelongScene=function(){ this._scene=null; for (var i=0,n=this._childs.length;i < n;i++) (this._childs [i])._setUnBelongScene(); } /** *@private */ __proto._activeHierarchy=function(){ var i=0,n=0; this._activeInHierarchy=true; this._addSelfRenderObjects(); for (i=0,n=this._colliders.length;i < n;i++) this._layer._addCollider(this._colliders[i]); this.event(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",true); for (i=0,n=this._childs.length;i < n;i++){ var child=this._childs [i]; (child._active)&& (child._activeHierarchy()); } } /** *@private */ __proto._inActiveHierarchy=function(){ var i=0,n=0; this._activeInHierarchy=false; this._clearSelfRenderObjects(); for (i=0,n=this._colliders.length;i < n;i++){ var col=this._colliders[i]; col._clearCollsionMap(); this._layer._removeCollider(col); } this.event(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",false); for (i=0,n=this._childs.length;i < n;i++){ var child=this._childs [i]; (child._active)&& (child._inActiveHierarchy()); } } /** *@private */ __proto.addComponent=function(type){ var typeComponentIndex; var index=this._componentsMap.indexOf(type); if (index===-1){ typeComponentIndex=[]; this._componentsMap.push(type); this._typeComponentsIndices.push(typeComponentIndex); }else { typeComponentIndex=this._typeComponentsIndices[index]; if (this._components[typeComponentIndex[0]].isSingleton) throw new Error("无法单实例创建"+type+"组件"+","+type+"组件已存在!"); }; var component=ClassUtils.getInstance(type); typeComponentIndex.push(this._components.length); this._components.push(component); if ((component instanceof laya.d3.component.physics.Collider )){ var rigidbody=this.getComponentByType(Rigidbody); (rigidbody)&& ((component)._isRigidbody=true); (this._activeInHierarchy)&& (this._layer._addCollider(component)); this._colliders.push(component); }else if ((component instanceof laya.d3.component.Animator )){ var animator=component; this._setHierarchyAnimator(animator,this._parent ? (this._parent)._hierarchyAnimator :null); this._setAnimatorToLinkSprite3DNoAvatar(animator,true,/*new vector.<>*/[]); }else if ((component instanceof laya.d3.component.Rigidbody )){ for (var i=0,n=this._colliders.length;i < n;i++) this._colliders[i]._setIsRigidbody(true); } if ((component instanceof laya.d3.component.Script )) this._scripts.push(component); component._initialize(this); return component; } /** *@inheritDoc */ __proto._removeComponent=function(mapIndex,index){ var i=0,n=0; var componentIndices=this._typeComponentsIndices[mapIndex]; var componentIndex=componentIndices[index]; var component=this._components[componentIndex]; if ((component instanceof laya.d3.component.physics.Collider )){ var colliderComponent=component; (this._activeInHierarchy)&& (this._layer._removeCollider(colliderComponent)); this._colliders.splice(this._colliders.indexOf(colliderComponent),1); }else if ((component instanceof laya.d3.component.Animator )){ var animator=component; this._clearHierarchyAnimator(animator,this._parent ? (this._parent)._hierarchyAnimator :null); }else if ((component instanceof laya.d3.component.Rigidbody )){ for (i=0,n=this._colliders.length;i < n;i++){ var collider=this._colliders[i]; collider._setIsRigidbody(false); var runtimeCollisonMap=collider._runtimeCollisonMap; var runtimeCollisonTestMap=collider._runtimeCollisonTestMap; for (var k in runtimeCollisonMap) delete runtimeCollisonTestMap[k]; } } this._components.splice(componentIndex,1); if ((component instanceof laya.d3.component.Script )) this._scripts.splice(this._scripts.indexOf(component),1); componentIndices.splice(index,1); (componentIndices.length===0)&& (this._typeComponentsIndices.splice(mapIndex,1),this._componentsMap.splice(mapIndex,1)); for (i=0,n=this._componentsMap.length;i < n;i++){ componentIndices=this._typeComponentsIndices[i]; for (var j=componentIndices.length-1;j >=0;j--){ var oldComponentIndex=componentIndices[j]; if (oldComponentIndex > componentIndex) componentIndices[j]=--oldComponentIndex; else break ; } } component._destroy(); } /** *清理自身渲染物体,请重载此函数。 */ __proto._clearSelfRenderObjects=function(){} /** *添加自身渲染物体,请重载此函数。 */ __proto._addSelfRenderObjects=function(){} /** *@private */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,nodeData){} /** *更新子节点。 *@param state 渲染相关状态。 */ __proto._updateChilds=function(state){ var n=this._childs.length; if (n===0)return; for (var i=0;i < n;++i) this._childs[i]._update((state)); } /** *排序函数。 *@param state 渲染相关状态。 */ __proto._getSortID=function(renderElement,material){ return material.id */*laya.d3.graphics.VertexDeclaration._maxVertexDeclarationBit*/1000+renderElement._getVertexBuffer().vertexDeclaration.id; } /** *更新 *@param state 渲染相关状态 */ __proto._update=function(state){ state.owner=this; if (this._activeInHierarchy){ this._updateComponents(state); this._lateUpdateComponents(state); Stat.spriteCount++; this._childs.length && this._updateChilds(state); } } /** *获取投影视图世界矩阵。 *@param projectionViewMatrix 投影视图矩阵。 *@return 投影视图世界矩阵。 */ __proto.getProjectionViewWorldMatrix=function(projectionViewMatrix){ Matrix4x4.multiply(projectionViewMatrix,this.transform.worldMatrix,this._projectionViewWorldMatrix); return this._projectionViewWorldMatrix; } /** *加载层级文件,并作为该节点的子节点。 *@param url */ __proto.loadHierarchy=function(url){ this.addChild(laya.d3.core.Sprite3D.load(url)); } /** *@inheritDoc */ __proto.addChildAt=function(node,index){ if (!((node instanceof laya.d3.core.Sprite3D ))) throw new Error("Sprite3D:Node type must Sprite3D."); if (!node || this.destroyed || node===this)return node; if ((node).zOrder)this._set$P("hasZorder",true); if (index >=0 && index <=this._childs.length){ if (node._parent===this){ var oldIndex=this.getChildIndex(node); this._childs.splice(oldIndex,1); this._childs.splice(index,0,node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,index); } this._childChanged(); }else { node.parent && node.parent.removeChild(node); this._childs===Node.ARRAY_EMPTY && (this._childs=[]); this._childs.splice(index,0,node); this.conchModel && this.conchModel.addChildAt(node.conchModel,index); node.parent=this; this._addChild3D(node); } return node; }else { throw new Error("appendChildAt:The index is out of bounds"); } } /** *@inheritDoc */ __proto.addChild=function(node){ if (!((node instanceof laya.d3.core.Sprite3D ))) throw new Error("Sprite3D:Node type must Sprite3D."); if (!node || this.destroyed || node===this)return node; if ((node).zOrder)this._set$P("hasZorder",true); if (node._parent===this){ var index=this.getChildIndex(node); if (index!==this._childs.length-1){ this._childs.splice(index,1); this._childs.push(node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,this._childs.length-1); } this._childChanged(); } }else { node.parent && node.parent.removeChild(node); this._childs===Node.ARRAY_EMPTY && (this._childs=[]); this._childs.push(node); this.conchModel && this.conchModel.addChildAt(node.conchModel,this._childs.length-1); node.parent=this; this._childChanged(); this._addChild3D(node); } return node; } /** *@inheritDoc */ __proto.removeChildAt=function(index){ var node=this.getChildAt(index); if (node){ this._removeChild3D(node); this._childs.splice(index,1); this.conchModel && this.conchModel.removeChild(node.conchModel); node.parent=null; } return node; } /** *@inheritDoc */ __proto.removeChildren=function(beginIndex,endIndex){ (beginIndex===void 0)&& (beginIndex=0); (endIndex===void 0)&& (endIndex=0x7fffffff); if (this._childs && this._childs.length > 0){ var childs=this._childs; if (beginIndex===0 && endIndex >=n){ var arr=childs; this._childs=Node.ARRAY_EMPTY; }else { arr=childs.splice(beginIndex,endIndex-beginIndex); } for (var i=0,n=arr.length;i < n;i++){ this._removeChild3D(arr [i]); arr[i].parent=null; this.conchModel && this.conchModel.removeChild(arr[i].conchModel); } } return this; } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ var json=data[0]; if (json.type!=="Sprite3D") throw new Error("Sprite3D: The .lh file root type must be Sprite3D,please use other function to load this file."); var innerResouMap=data[1]; Utils3D._createNodeByJson(this,json,this,innerResouMap); this.event(/*laya.events.Event.HIERARCHY_LOADED*/"hierarchyloaded",[this]); this.__loaded=true; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ if (this.destroyed) throw new Error("Sprite3D: Can't be cloned if the Sprite3D has destroyed."); var destSprite3D=destObject; destSprite3D.name=this.name; destSprite3D._destroyed=this._destroyed; destSprite3D.timer=this.timer; destSprite3D._$P=this._$P; destSprite3D.active=this._active; var destLocalPosition=destSprite3D.transform.localPosition; this.transform.localPosition.cloneTo(destLocalPosition); destSprite3D.transform.localPosition=destLocalPosition; var destLocalRotation=destSprite3D.transform.localRotation; this.transform.localRotation.cloneTo(destLocalRotation); destSprite3D.transform.localRotation=destLocalRotation; var destLocalScale=destSprite3D.transform.localScale; this.transform.localScale.cloneTo(destLocalScale); destSprite3D.transform.localScale=destLocalScale; destSprite3D.isStatic=this.isStatic; var i=0,n=0; for (i=0,n=this._componentsMap.length;i < n;i++){ var destComponent=destSprite3D.addComponent(this._componentsMap[i]); this._components[i]._cloneTo(destComponent); } for (i=0,n=this._childs.length;i < n;i++) destSprite3D.addChild(this._childs[i].clone()); var destAnimator=destSprite3D.getComponentByType(Animator); if (destAnimator){ var destLinkSpritesData=destAnimator._linkSpritesData; if (destLinkSpritesData){ for (var k in destLinkSpritesData){ var path=destLinkSpritesData[k]; var sp=destSprite3D; for (var j=0,m=path.length;j < m;j++){ sp=sp.getChildByName(path[j]); if (!sp) break ; } if (sp){ var node=destAnimator._avatarNodeMap[k]; sp._isLinkSpriteToAnimationNode(destAnimator,node,true); } } } } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destSprite3D=/*__JS__ */new this.constructor(); this.cloneTo(destSprite3D); return destSprite3D; } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; laya.display.Node.prototype.destroy.call(this,destroyChild); var i=0,n=0; for (i=0,n=this._components.length;i < n;i++) this._components[i]._destroy(); this._components=null; this._componentsMap=null; this._typeComponentsIndices=null; this._transform=null; this._colliders=null; Loader.clearRes(this.url); (this.loaded)|| (Laya3D._cancelLoadByUrl(this.url)); } /** *@private */ __proto._handleSpriteToAvatar=function(animator,isLink){ var i=0,n=0; var avatarNodes=animator._avatarNodes; var node=animator._avatarNodeMap[this.name]; if (node && node.name===this.name && !this._transform.dummy) this._isLinkSpriteToAnimationNode(animator,node,isLink); } /** *@private */ __proto._setAnimatorToLinkAvatar=function(animator,isLink){ this._handleSpriteToAvatar(animator,isLink); for (var i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; child._setAnimatorToLinkAvatar(animator,isLink); } } /** *获取在场景中是否激活。 *@return 在场景中是否激活。 */ __getset(0,__proto,'activeInHierarchy',function(){ return this._activeInHierarchy; }); /** *@private */ __getset(0,__proto,'_loaded',null,function(value){ this.__loaded=value; }); /** *设置是否激活。 *@param value 是否激活。 */ /** *获取自身是否激活。 *@return 自身是否激活。 */ __getset(0,__proto,'active',function(){ return this._active; },function(value){ if (this._active!==value){ this._active=value; if (this._parent){ if ((this._parent===this._scene && this._parent.displayedInStage)|| (this._parent)._activeInHierarchy){ if (value) this._activeHierarchy(); else this._inActiveHierarchy(); } } } }); /** *获得组件的数量。 *@return 组件数量。 */ __getset(0,__proto,'componentsCount',function(){ return this._components.length; }); /** *获取是否已加载完成。 */ __getset(0,__proto,'loaded',function(){ return this.__loaded; }); /** *获取唯一标识ID。 *@return 唯一标识ID。 */ __getset(0,__proto,'id',function(){ return this._id; }); /** *获取资源的URL地址。 *@return URL地址。 */ __getset(0,__proto,'url',function(){ return this._url; }); /** *设置蒙版。 *@param value 蒙版。 */ /** *获取蒙版。 *@return 蒙版。 */ __getset(0,__proto,'layer',function(){ return this._layer; },function(value){ if (this._layer!==value){ if (value){ if (this._activeInHierarchy){ var i=0,n=this._colliders.length; if (this._layer){ for (i=0;i < n;i++) this._layer._removeCollider(this._colliders[i]); } for (i=0;i < n;i++) value._addCollider(this._colliders[i]); } this._layer=value; this.event(/*laya.events.Event.LAYER_CHANGED*/"layerchanged",value); }else { throw new Error("Layer value can be null."); } } }); /** *获得所属场景。 *@return 场景。 */ __getset(0,__proto,'scene',function(){ return this._scene; }); /** *获取精灵变换。 */ __getset(0,__proto,'transform',function(){ return this._transform; }); Sprite3D.instantiate=function(original,parent,worldPositionStays,position,rotation){ (worldPositionStays===void 0)&& (worldPositionStays=true); var destSprite3D=original.clone(); (parent)&& (parent.addChild(destSprite3D)); var transform=destSprite3D.transform; if (worldPositionStays){ var worldMatrix=transform.worldMatrix; original.transform.worldMatrix.cloneTo(worldMatrix); transform.worldMatrix=worldMatrix; }else { (position)&& (transform.position=position); (rotation)&& (transform.rotation=rotation); } return destSprite3D; } Sprite3D.load=function(url){ return Laya.loader.create(url,null,null,Sprite3D); } Sprite3D.WORLDMATRIX=0; Sprite3D.MVPMATRIX=1; Sprite3D._uniqueIDCounter=0; Sprite3D._nameNumberCounter=0; return Sprite3D; })(ComponentNode) /** *BlinnPhongMaterial 类用于实现Blinn-Phong材质。 */ //class laya.d3.core.material.BlinnPhongMaterial extends laya.d3.core.material.BaseMaterial var BlinnPhongMaterial=(function(_super){ function BlinnPhongMaterial(){ /**@private */ //this._albedoColor=null; /**@private */ //this._albedoIntensity=NaN; /**@private */ //this._enableLighting=false; BlinnPhongMaterial.__super.call(this); this.setShaderName("BLINNPHONG"); this._albedoIntensity=1.0; this._albedoColor=new Vector4(1.0,1.0,1.0,1.0); this._setColor(6,new Vector4(1.0,1.0,1.0,1.0)); this._setColor(8,new Vector3(1.0,1.0,1.0)); this._setNumber(9,0.078125); this._setColor(10,new Vector3(1.0,1.0,1.0)); this._setNumber(0,0.5); this._setColor(11,new Vector4(1.0,1.0,0.0,0.0)); this._enableLighting=true; this.renderMode=0; } __class(BlinnPhongMaterial,'laya.d3.core.material.BlinnPhongMaterial',_super); var __proto=BlinnPhongMaterial.prototype; /** *禁用灯光。 */ __proto.disableLight=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } /** *禁用雾化。 */ __proto.disableFog=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); } /** *@inheritDoc */ __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destMaterial=destObject; destMaterial._enableLighting=this._enableLighting; destMaterial._albedoIntensity=this._albedoIntensity; this._albedoColor.cloneTo(destMaterial._albedoColor); } /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 0: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.alphaTest=false; this.depthTest=0x0201; this._removeShaderDefine(BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 1: this.depthWrite=true; this.cull=2; this.blend=0; this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.alphaTest=true; this.depthTest=0x0201; this._removeShaderDefine(BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this.depthTest=0x0201; this._removeShaderDefine(BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 3: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this.depthTest=0x0201; this._addShaderDefine(BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG); break ; default : throw new Error("Material:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_NORMALMAP); else this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_NORMALMAP); this._setTexture(2,value); }); /** *设置反射颜色。 *@param value 反射颜色。 */ /** *获取反射颜色。 *@return value 反射颜色。 */ __getset(0,__proto,'reflectColor',function(){ return this._getColor(10); },function(value){ this._setColor(10,value); }); /** *获取纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(11); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(11,value); }); /** *设置高光颜色。 *@param value 高光颜色。 */ /** *获取高光颜色。 *@return 高光颜色。 */ __getset(0,__proto,'specularColor',function(){ return this._getColor(8); },function(value){ this._setColor(8,value); }); /** *设置漫反射颜色。 *@param value 漫反射颜色。 */ /** *获取漫反射颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._albedoColor; },function(value){ var finalAlbedo=this._getColor(6); Vector4.scale(value,this._albedoIntensity,finalAlbedo); this._albedoColor=value; }); /** *设置漫反射颜色。 *@param value 漫反射颜色。 */ /** *获取漫反射颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'albedoIntensity',function(){ return this._albedoIntensity; },function(value){ if (this._albedoIntensity!==value){ var finalAlbedo=this._getColor(6); Vector4.scale(this._albedoColor,value,finalAlbedo); this._albedoIntensity=value; } }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'albedoTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP); else this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP); this._setTexture(1,value); }); /** *设置高光强度,范围为0到1。 *@param value 高光强度。 */ /** *获取高光强度,范围为0到1。 *@return 高光强度。 */ __getset(0,__proto,'shininess',function(){ return this._getNumber(9); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(9,value); }); /** *设置高光贴图,高光强度则从该贴图RGB值中获取,如果该值为空则从漫反射贴图的Alpha通道获取。 *@param value 高光贴图。 */ /** *获取高光贴图。 *@return 高光贴图。 */ __getset(0,__proto,'specularTexture',function(){ return this._getTexture(3); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP); else this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP); this._setTexture(3,value); }); /** *设置反射贴图。 *@param value 反射贴图。 */ /** *获取反射贴图。 *@return 反射贴图。 */ __getset(0,__proto,'reflectTexture',function(){ return this._getTexture(5); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_REFLECTMAP); else this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_REFLECTMAP); this._setTexture(5,value); }); /** *设置是否启用光照。 *@param value 是否启用光照。 */ /** *获取是否启用光照。 *@return 是否启用光照。 */ __getset(0,__proto,'enableLighting',function(){ return this._enableLighting; },function(value){ if (this._enableLighting!==value){ if (value) this._removeDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); else this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); this._enableLighting=value; } }); BlinnPhongMaterial.__init__=function(){ BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP=BlinnPhongMaterial.shaderDefines.registerDefine("DIFFUSEMAP"); BlinnPhongMaterial.SHADERDEFINE_NORMALMAP=BlinnPhongMaterial.shaderDefines.registerDefine("NORMALMAP"); BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP=BlinnPhongMaterial.shaderDefines.registerDefine("SPECULARMAP"); BlinnPhongMaterial.SHADERDEFINE_REFLECTMAP=BlinnPhongMaterial.shaderDefines.registerDefine("REFLECTMAP"); BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET=BlinnPhongMaterial.shaderDefines.registerDefine("TILINGOFFSET"); BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG=BlinnPhongMaterial.shaderDefines.registerDefine("ADDTIVEFOG"); } BlinnPhongMaterial.load=function(url){ return Laya.loader.create(url,null,null,BlinnPhongMaterial); } BlinnPhongMaterial.SPECULARSOURCE_DIFFUSEMAPALPHA=0; BlinnPhongMaterial.SPECULARSOURCE_SPECULARMAP=0; BlinnPhongMaterial.RENDERMODE_OPAQUE=0; BlinnPhongMaterial.RENDERMODE_CUTOUT=1; BlinnPhongMaterial.RENDERMODE_TRANSPARENT=2; BlinnPhongMaterial.RENDERMODE_ADDTIVE=3; BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP=0; BlinnPhongMaterial.SHADERDEFINE_NORMALMAP=0; BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP=0; BlinnPhongMaterial.SHADERDEFINE_REFLECTMAP=0; BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET=0; BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG=0; BlinnPhongMaterial.ALBEDOTEXTURE=1; BlinnPhongMaterial.NORMALTEXTURE=2; BlinnPhongMaterial.SPECULARTEXTURE=3; BlinnPhongMaterial.EMISSIVETEXTURE=4; BlinnPhongMaterial.REFLECTTEXTURE=5; BlinnPhongMaterial.ALBEDOCOLOR=6; BlinnPhongMaterial.MATERIALSPECULAR=8; BlinnPhongMaterial.SHININESS=9; BlinnPhongMaterial.MATERIALREFLECT=10; BlinnPhongMaterial.TILINGOFFSET=11; __static(BlinnPhongMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new BlinnPhongMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return BlinnPhongMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.core.material.ExtendTerrainMaterial extends laya.d3.core.material.BaseMaterial var ExtendTerrainMaterial=(function(_super){ //NATIVE function ExtendTerrainMaterial(){ ExtendTerrainMaterial.__super.call(this); this.setShaderName("ExtendTerrain"); this.renderMode=1; } __class(ExtendTerrainMaterial,'laya.d3.core.material.ExtendTerrainMaterial',_super); var __proto=ExtendTerrainMaterial.prototype; __proto._setDetailNum=function(value){ switch (value){ case 1: this._addShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5); break ; case 2: this._addShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5); break ; case 3: this._addShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5); break ; case 4: this._addShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5); break ; case 5: this._addShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4); break ; } } /** *设置禁受光照影响。 */ __proto.disableLight=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } __getset(0,__proto,'diffuseScaleOffset2',null,function(scaleOffset2){ this._setColor(7,scaleOffset2); }); /** *设置splatAlpha贴图。 *@param value splatAlpha贴图。 */ /** *获取splatAlpha贴图。 *@return splatAlpha贴图。 */ __getset(0,__proto,'splatAlphaTexture',function(){ return this._getTexture(0); },function(value){ this._setTexture(0,value); }); __getset(0,__proto,'diffuseScaleOffset3',null,function(scaleOffset3){ this._setColor(8,scaleOffset3); }); /** *设置第一层贴图。 *@param value 第一层贴图。 */ __getset(0,__proto,'diffuseTexture1',null,function(value){ this._setTexture(1,value); this._setDetailNum(1); }); /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.depthTest=0x0201; break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.depthTest=0x0203; break ; default : throw new Error("ExtendTerrainMaterial:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置第二层贴图。 *@param value 第二层贴图。 */ /** *获取第二层贴图。 *@return 第二层贴图。 */ __getset(0,__proto,'diffuseTexture2',function(){ return this._getTexture(2); },function(value){ this._setTexture(2,value); this._setDetailNum(2); }); __getset(0,__proto,'diffuseScaleOffset1',null,function(scaleOffset1){ this._setColor(6,scaleOffset1); }); /** *设置第三层贴图。 *@param value 第三层贴图。 */ /** *获取第三层贴图。 *@return 第三层贴图。 */ __getset(0,__proto,'diffuseTexture3',function(){ return this._getTexture(3); },function(value){ this._setTexture(3,value); this._setDetailNum(3); }); /** *设置第四层贴图。 *@param value 第四层贴图。 */ /** *获取第四层贴图。 *@return 第四层贴图。 */ __getset(0,__proto,'diffuseTexture4',function(){ return this._getTexture(4); },function(value){ this._setTexture(4,value); this._setDetailNum(4); }); /** *设置第五层贴图。 *@param value 第五层贴图。 */ /** *获取第五层贴图。 *@return 第五层贴图。 */ __getset(0,__proto,'diffuseTexture5',function(){ return this._getTexture(5); },function(value){ this._setTexture(5,value); this._setDetailNum(5); }); __getset(0,__proto,'diffuseScaleOffset4',null,function(scaleOffset4){ this._setColor(9,scaleOffset4); }); __getset(0,__proto,'diffuseScaleOffset5',null,function(scaleOffset5){ this._setColor(10,scaleOffset5); }); /** *设置反射率颜色。 *@param value 反射率颜色。 */ /** *获取反射率颜色。 *@return 反射率颜色。 */ __getset(0,__proto,'albedo',function(){ return this._getColor(14); },function(value){ this._setColor(14,value); }); /** *设置环境光颜色。 *@param value 环境光颜色 */ /** *获取环境光颜色。 *@return 环境光颜色。 */ __getset(0,__proto,'ambientColor',function(){ return this._getColor(11); },function(value){ this._setColor(11,value); }); /** *设置漫反射颜色。 *@param value 漫反射颜色。 */ /** *获取漫反射颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'diffuseColor',function(){ return this._getColor(12); },function(value){ this._setColor(12,value); }); /** *设置高光颜色。 *@param value 高光颜色。 */ /** *获取高光颜色。 *@return 高光颜色。 */ __getset(0,__proto,'specularColor',function(){ return this._getColor(13); },function(value){ this._setColor(13,value); }); ExtendTerrainMaterial.__init__=function(){ ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1=ExtendTerrainMaterial.shaderDefines.registerDefine("ExtendTerrain_DETAIL_NUM1"); ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2=ExtendTerrainMaterial.shaderDefines.registerDefine("ExtendTerrain_DETAIL_NUM2"); ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3=ExtendTerrainMaterial.shaderDefines.registerDefine("ExtendTerrain_DETAIL_NUM3"); ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4=ExtendTerrainMaterial.shaderDefines.registerDefine("ExtendTerrain_DETAIL_NUM4"); ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5=ExtendTerrainMaterial.shaderDefines.registerDefine("ExtendTerrain_DETAIL_NUM5"); } ExtendTerrainMaterial.RENDERMODE_OPAQUE=1; ExtendTerrainMaterial.RENDERMODE_TRANSPARENT=2; ExtendTerrainMaterial.SPLATALPHATEXTURE=0; ExtendTerrainMaterial.DIFFUSETEXTURE1=1; ExtendTerrainMaterial.DIFFUSETEXTURE2=2; ExtendTerrainMaterial.DIFFUSETEXTURE3=3; ExtendTerrainMaterial.DIFFUSETEXTURE4=4; ExtendTerrainMaterial.DIFFUSETEXTURE5=5; ExtendTerrainMaterial.DIFFUSESCALEOFFSET1=6; ExtendTerrainMaterial.DIFFUSESCALEOFFSET2=7; ExtendTerrainMaterial.DIFFUSESCALEOFFSET3=8; ExtendTerrainMaterial.DIFFUSESCALEOFFSET4=9; ExtendTerrainMaterial.DIFFUSESCALEOFFSET5=10; ExtendTerrainMaterial.MATERIALAMBIENT=11; ExtendTerrainMaterial.MATERIALDIFFUSE=12; ExtendTerrainMaterial.MATERIALSPECULAR=13; ExtendTerrainMaterial.MATERIALALBEDO=14; ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1=0; ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2=0; ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3=0; ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4=0; ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5=0; __static(ExtendTerrainMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return ExtendTerrainMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.core.material.GlitterMaterial extends laya.d3.core.material.BaseMaterial var GlitterMaterial=(function(_super){ function GlitterMaterial(){ GlitterMaterial.__super.call(this); this.setShaderName("GLITTER"); this.renderMode=1; this._setColor(3,new Vector4(1.0,1.0,1.0,1.0)); this._setColor(2,new Vector4(1.0,1.0,1.0,1.0)); } __class(GlitterMaterial,'laya.d3.core.material.GlitterMaterial',_super); var __proto=GlitterMaterial.prototype; /** *@inheritDoc */ __proto.setShaderName=function(name){ _super.prototype.setShaderName.call(this,name); } /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; break ; case 13: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 14: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 15: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; case 16: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; case 5: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 6: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 7: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; case 8: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; case 9: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 10: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 11: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; case 12: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; default : throw new Error("Material:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ this._setTexture(1,value); }); /** *设置反射率。 *@param value 反射率。 */ /** *获取反射率。 *@return 反射率。 */ __getset(0,__proto,'albedo',function(){ return this._getColor(2); },function(value){ this._setColor(2,value); }); /** *设置颜色。 *@param value 颜色。 */ /** *获取颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'color',function(){ return this._getColor(3); },function(value){ this._setColor(3,value); }); GlitterMaterial.load=function(url){ return Laya.loader.create(url,null,null,GlitterMaterial); } GlitterMaterial.RENDERMODE_OPAQUE=1; GlitterMaterial.RENDERMODE_OPAQUEDOUBLEFACE=2; GlitterMaterial.RENDERMODE_TRANSPARENT=13; GlitterMaterial.RENDERMODE_TRANSPARENTDOUBLEFACE=14; GlitterMaterial.RENDERMODE_ADDTIVE=15; GlitterMaterial.RENDERMODE_ADDTIVEDOUBLEFACE=16; GlitterMaterial.RENDERMODE_DEPTHREAD_TRANSPARENT=5; GlitterMaterial.RENDERMODE_DEPTHREAD_TRANSPARENTDOUBLEFACE=6; GlitterMaterial.RENDERMODE_DEPTHREAD_ADDTIVE=7; GlitterMaterial.RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE=8; GlitterMaterial.RENDERMODE_NONDEPTH_TRANSPARENT=9; GlitterMaterial.RENDERMODE_NONDEPTH_TRANSPARENTDOUBLEFACE=10; GlitterMaterial.RENDERMODE_NONDEPTH_ADDTIVE=11; GlitterMaterial.RENDERMODE_NONDEPTH_ADDTIVEDOUBLEFACE=12; GlitterMaterial.DIFFUSETEXTURE=1; GlitterMaterial.ALBEDO=2; GlitterMaterial.UNICOLOR=3; __static(GlitterMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new GlitterMaterial();} ]); return GlitterMaterial; })(BaseMaterial) //class laya.d3.shader.Shader3D extends laya.webgl.shader.BaseShader var Shader3D=(function(_super){ function Shader3D(vs,ps,attributeMap,sceneUniformMap,cameraUniformMap,spriteUniformMap,materialUniformMap,renderElementUniformMap){ //this._attributeMap=null; //this._sceneUniformMap=null; //this._cameraUniformMap=null; //this._spriteUniformMap=null; //this._materialUniformMap=null; //this._renderElementUniformMap=null; //this._vs=null; //this._ps=null; this._curActTexIndex=0; //this._reCompile=false; //this._vshader=null; //this._pshader=null; this._program=null; this._attributeParams=null; this._uniformParams=null; this._attributeParamsMap=[]; this._sceneUniformParamsMap=[]; this._cameraUniformParamsMap=[]; this._spriteUniformParamsMap=[]; this._materialUniformParamsMap=[]; this._renderElementUniformParamsMap=[]; //this._id=0; /**@private */ //this._uploadLoopCount=0; /**@private */ //this._uploadRenderElement=null; /**@private */ //this._uploadMaterial=null; /**@private */ //this._uploadSprite3D=null; /**@private */ //this._uploadCamera=null; /**@private */ //this._uploadScene=null; /**@private */ //this._uploadVertexBuffer=null; Shader3D.__super.call(this); if ((!vs)|| (!ps))throw "Shader Error"; this._id=++Shader3D._count; this._vs=vs; this._ps=ps; this._attributeMap=attributeMap; this._sceneUniformMap=sceneUniformMap; this._cameraUniformMap=cameraUniformMap; this._spriteUniformMap=spriteUniformMap; this._materialUniformMap=materialUniformMap; this._renderElementUniformMap=renderElementUniformMap; this.recreateResource(); } __class(Shader3D,'laya.d3.shader.Shader3D',_super); var __proto=Shader3D.prototype; __proto.recreateResource=function(){ this._compile(); this.completeCreate(); this.memorySize=0; } //忽略尺寸尺寸 __proto.disposeResource=function(){ WebGL.mainContext.deleteShader(this._vshader); WebGL.mainContext.deleteShader(this._pshader); WebGL.mainContext.deleteProgram(this._program); this._vshader=this._pshader=this._program=null; this._attributeParams=null; this._uniformParams=null; this.memorySize=0; this._curActTexIndex=0; } __proto._compile=function(){ if (!this._vs || !this._ps || this._attributeParams || this._uniformParams) return; this._reCompile=true; this._attributeParams=[]; this._uniformParams=[]; var text=[this._vs,this._ps]; var result; var gl=WebGL.mainContext; this._program=gl.createProgram(); this._vshader=Shader3D._createShader(gl,text[0],/*laya.webgl.WebGLContext.VERTEX_SHADER*/0x8B31); this._pshader=Shader3D._createShader(gl,text[1],/*laya.webgl.WebGLContext.FRAGMENT_SHADER*/0x8B30); gl.attachShader(this._program,this._vshader); gl.attachShader(this._program,this._pshader); gl.linkProgram(this._program); if (!Render.isConchApp && ShaderCompile3D.debugMode && !gl.getProgramParameter(this._program,/*laya.webgl.WebGLContext.LINK_STATUS*/0x8B82)) throw gl.getProgramInfoLog(this._program); var one,i=0,j=0,n=0,location; var attribNum=0; if (Render.isConchApp){ attribNum=gl.getProgramParameterEx(this._vs,this._ps,"",/*laya.webgl.WebGLContext.ACTIVE_ATTRIBUTES*/0x8B89); } else{ attribNum=gl.getProgramParameter(this._program,/*laya.webgl.WebGLContext.ACTIVE_ATTRIBUTES*/0x8B89); } for (i=0;i < attribNum;i++){ var attrib=null; if (Render.isConchApp){ attrib=gl.getActiveAttribEx(this._vs,this._ps,"",i); } else{ attrib=gl.getActiveAttrib(this._program,i); } location=gl.getAttribLocation(this._program,attrib.name); one={vartype:"attribute",ivartype:0,attrib:attrib,location:location,name:attrib.name,type:attrib.type,isArray:false,isSame:false,preValue:null,indexOfParams:0}; this._attributeParams.push(one); }; var nUniformNum=0; if (Render.isConchApp){ nUniformNum=gl.getProgramParameterEx(this._vs,this._ps,"",/*laya.webgl.WebGLContext.ACTIVE_UNIFORMS*/0x8B86); } else{ nUniformNum=gl.getProgramParameter(this._program,/*laya.webgl.WebGLContext.ACTIVE_UNIFORMS*/0x8B86); } for (i=0;i < nUniformNum;i++){ var uniform=null; if (Render.isConchApp){ uniform=gl.getActiveUniformEx(this._vs,this._ps,"",i); } else{ uniform=gl.getActiveUniform(this._program,i); } location=gl.getUniformLocation(this._program,uniform.name); one={vartype:"uniform",ivartype:1,attrib:attrib,location:location,name:uniform.name,type:uniform.type,isArray:false,isSame:false,preValue:null,indexOfParams:0}; if (one.name.indexOf('[0]')> 0){ one.name=one.name.substr(0,one.name.length-3); one.isArray=true; one.location=gl.getUniformLocation(this._program,one.name); } this._uniformParams.push(one); } for (i=0,n=this._attributeParams.length;i < n;i++){ one=this._attributeParams[i]; one.indexOfParams=i; one.index=1; one.value=[one.location,null]; one.codename=one.name; one.name=(this._attributeMap[one.codename] !=null)? this._attributeMap[one.codename] :one.codename; this._attributeParamsMap.push(one.name); this._attributeParamsMap.push(one); one._this=this; one.uploadedValue=[]; one.fun=this._attribute; } for (i=0,n=this._uniformParams.length;i < n;i++){ one=this._uniformParams[i]; one.indexOfParams=i; one.index=1; one.value=[one.location,null]; one.codename=one.name; if (this._sceneUniformMap[one.codename] !=null){ one.name=this._sceneUniformMap[one.codename]; this._sceneUniformParamsMap.push(one.name); this._sceneUniformParamsMap.push(one); }else if (this._cameraUniformMap[one.codename] !=null){ one.name=this._cameraUniformMap[one.codename]; this._cameraUniformParamsMap.push(one.name); this._cameraUniformParamsMap.push(one); }else if (this._spriteUniformMap[one.codename] !=null){ one.name=this._spriteUniformMap[one.codename]; this._spriteUniformParamsMap.push(one.name); this._spriteUniformParamsMap.push(one); }else if (this._materialUniformMap[one.codename] !=null){ one.name=this._materialUniformMap[one.codename]; this._materialUniformParamsMap.push(one.name); this._materialUniformParamsMap.push(one); }else if (this._renderElementUniformMap[one.codename] !=null){ one.name=this._renderElementUniformMap[one.codename]; this._renderElementUniformParamsMap.push(one.name); this._renderElementUniformParamsMap.push(one); }else { console.log("Shader:can't find uinform name:"+one.codename+" in shader file."); } one._this=this; one.uploadedValue=[]; switch (one.type){ case /*laya.webgl.WebGLContext.INT*/0x1404: one.fun=one.isArray ? this._uniform1iv :this._uniform1i; break ; case /*laya.webgl.WebGLContext.FLOAT*/0x1406: one.fun=one.isArray ? this._uniform1fv :this._uniform1f; break ; case /*laya.webgl.WebGLContext.FLOAT_VEC2*/0x8B50: one.fun=one.isArray ? this._uniform_vec2v :this._uniform_vec2; break ; case /*laya.webgl.WebGLContext.FLOAT_VEC3*/0x8B51: one.fun=one.isArray ? this._uniform_vec3v :this._uniform_vec3; break ; case /*laya.webgl.WebGLContext.FLOAT_VEC4*/0x8B52: one.fun=one.isArray ? this._uniform_vec4v :this._uniform_vec4; break ; case /*laya.webgl.WebGLContext.SAMPLER_2D*/0x8B5E: one.fun=this._uniform_sampler2D; break ; case /*laya.webgl.WebGLContext.SAMPLER_CUBE*/0x8B60: one.fun=this._uniform_samplerCube; break ; case /*laya.webgl.WebGLContext.FLOAT_MAT4*/0x8B5C: one.fun=this._uniformMatrix4fv; break ; case /*laya.webgl.WebGLContext.BOOL*/0x8B56: one.fun=this._uniform1i; break ; case /*laya.webgl.WebGLContext.FLOAT_MAT2*/0x8B5A: one.fun=this._uinformMatrix2fv; break ; case /*laya.webgl.WebGLContext.FLOAT_MAT3*/0x8B5B: one.fun=this._uinformMatrix3fv; break ; default : throw new Error("compile shader err!"); break ; } } } __proto._attribute=function(one,value){ var gl=WebGL.mainContext; var enableAtributes=Buffer._enableAtributes; var location=one.location; (enableAtributes[location])|| (gl.enableVertexAttribArray(location)); gl.vertexAttribPointer(location,value[0],value[1],value[2],value[3],value[4]); enableAtributes[location]=Buffer._bindVertexBuffer; return 1; } __proto._uniform1f=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value){ WebGL.mainContext.uniform1f(one.location,uploadedValue[0]=value); return 1; } return 0; } __proto._uniform1fv=function(one,value){ if (value.length < 4){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform1fv(one.location,value); uploadedValue[0]=value[0]; uploadedValue[1]=value[1]; uploadedValue[2]=value[2]; uploadedValue[3]=value[3]; return 1; } return 0; }else { WebGL.mainContext.uniform1fv(one.location,value); return 1; } } __proto._uniform_vec2=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1]){ WebGL.mainContext.uniform2f(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1]); return 1; } return 0; } __proto._uniform_vec2v=function(one,value){ if (value.length < 2){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform2fv(one.location,value); uploadedValue[0]=value[0]; uploadedValue[1]=value[1]; uploadedValue[2]=value[2]; uploadedValue[3]=value[3]; return 1; } return 0; }else { WebGL.mainContext.uniform2fv(one.location,value); return 1; } } __proto._uniform_vec3=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2]){ WebGL.mainContext.uniform3f(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2]); return 1; } return 0; } __proto._uniform_vec3v=function(one,value){ WebGL.mainContext.uniform3fv(one.location,value); return 1; } __proto._uniform_vec4=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform4f(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2],uploadedValue[3]=value[3]); return 1; } return 0; } __proto._uniform_vec4v=function(one,value){ WebGL.mainContext.uniform4fv(one.location,value); return 1; } __proto._uniformMatrix2fv=function(one,value){ WebGL.mainContext.uniformMatrix2fv(one.location,false,value); return 1; } __proto._uniformMatrix3fv=function(one,value){ WebGL.mainContext.uniformMatrix3fv(one.location,false,value); return 1; } __proto._uniformMatrix4fv=function(one,value){ WebGL.mainContext.uniformMatrix4fv(one.location,false,value); return 1; } __proto._uinformMatrix2fv=function(one,value){ WebGL.mainContext.uniformMatrix2fv(one.location,false,value); return 1; } __proto._uinformMatrix3fv=function(one,value){ WebGL.mainContext.uniformMatrix3fv(one.location,false,value); return 1; } __proto._uniform1i=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value){ WebGL.mainContext.uniform1i(one.location,uploadedValue[0]=value); return 1; } return 0; } __proto._uniform1iv=function(one,value){ WebGL.mainContext.uniform1iv(one.location,value); return 1; } __proto._uniform_ivec2=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1]){ WebGL.mainContext.uniform2i(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1]); return 1; } return 0; } __proto._uniform_ivec2v=function(one,value){ WebGL.mainContext.uniform2iv(one.location,value); return 1; } __proto._uniform_vec3i=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2]){ WebGL.mainContext.uniform3i(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2]); return 1; } return 0; } __proto._uniform_vec3vi=function(one,value){ WebGL.mainContext.uniform3iv(one.location,value); return 1; } __proto._uniform_vec4i=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform4i(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2],uploadedValue[3]=value[3]); return 1; } return 0; } __proto._uniform_vec4vi=function(one,value){ WebGL.mainContext.uniform4iv(one.location,value); return 1; } __proto._uniform_sampler2D=function(one,texture){ var value=texture.source || texture.defaulteTexture.source; var gl=WebGL.mainContext; var uploadedValue=one.uploadedValue; if (uploadedValue[0]==null){ if (this._curActTexIndex > 7) throw new Error("Shader3D: shader support textures max count is 8,can't large than it."); uploadedValue[0]=this._curActTexIndex; gl.uniform1i(one.location,this._curActTexIndex); gl.activeTexture(Shader3D._TEXTURES[this._curActTexIndex]); if (value) WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,value); this._curActTexIndex++; return 1; }else { gl.activeTexture(Shader3D._TEXTURES[uploadedValue[0]]); if (value) WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,value); return 0; } } __proto._uniform_samplerCube=function(one,texture){ var value=texture.source || texture.defaulteTexture.source; var gl=WebGL.mainContext; var uploadedValue=one.uploadedValue; if (uploadedValue[0]==null){ if (this._curActTexIndex > 7) throw new Error("Shader3D: shader support textures max count is 8,can't large than it."); uploadedValue[0]=this._curActTexIndex; gl.uniform1i(one.location,this._curActTexIndex); gl.activeTexture(Shader3D._TEXTURES[this._curActTexIndex]); if (value) WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513,value); else WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513,SolidColorTextureCube.grayTexture.source); this._curActTexIndex++; return 1; }else { gl.activeTexture(Shader3D._TEXTURES[uploadedValue[0]]); if (value) WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513,value); else WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513,SolidColorTextureCube.grayTexture.source); return 0; } } __proto._noSetValue=function(one){ console.log("no....:"+one.name); } //throw new Error("upload shader err,must set value:"+one.name); __proto.bind=function(){ BaseShader.activeShader=this; BaseShader.bindShader=this; this.activeResource(); return WebGLContext.UseProgram(this._program); } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadAttributes=function(attributeShaderValue,_bufferUsage){ var value; var one,shaderCall=0; for (var i=0,n=this._attributeParamsMap.length;i < n;i+=2){ one=this._attributeParamsMap[i+1]; value=attributeShaderValue[this._attributeParamsMap[i]]; if (value !=null){ _bufferUsage && _bufferUsage[one.name] && _bufferUsage[one.name].bind(); shaderCall+=one.fun.call(this,one,value); } } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadAttributesX=function(attributeShaderValue,vb){ var value; var one,shaderCall=0; for (var i=0,n=this._attributeParamsMap.length;i < n;i+=2){ one=this._attributeParamsMap[i+1]; value=attributeShaderValue[this._attributeParamsMap[i]]; if (value !=null){ vb._bind(); shaderCall+=one.fun.call(this,one,value); } } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadSceneUniforms=function(shaderValue){ var value; var one,shaderCall=0; for (var i=0,n=this._sceneUniformParamsMap.length;i < n;i+=2){ one=this._sceneUniformParamsMap[i+1]; value=shaderValue[this._sceneUniformParamsMap[i]]; if (value !=null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadCameraUniforms=function(shaderValue){ var value; var one,shaderCall=0; for (var i=0,n=this._cameraUniformParamsMap.length;i < n;i+=2){ one=this._cameraUniformParamsMap[i+1]; value=shaderValue[this._cameraUniformParamsMap[i]]; if (value !=null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadSpriteUniforms=function(shaderValue){ var value; var one,shaderCall=0; for (var i=0,n=this._spriteUniformParamsMap.length;i < n;i+=2){ one=this._spriteUniformParamsMap[i+1]; value=shaderValue[this._spriteUniformParamsMap[i]]; if (value !=null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadMaterialUniforms=function(shaderValue){ var value; var one,shaderCall=0; for (var i=0,n=this._materialUniformParamsMap.length;i < n;i+=2){ one=this._materialUniformParamsMap[i+1]; value=shaderValue[this._materialUniformParamsMap[i]]; if (value !=null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadRenderElementUniforms=function(shaderValue){ var value; var one,shaderCall=0; for (var i=0,n=this._renderElementUniformParamsMap.length;i < n;i+=2){ one=this._renderElementUniformParamsMap[i+1]; value=shaderValue[this._renderElementUniformParamsMap[i]]; if (value !=null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } Shader3D.create=function(vs,ps,attributeMap,sceneUniformMap,cameraUniformMap,spriteUniformMap,materialUniformMap,renderElementUniformMap){ return new Shader3D(vs,ps,attributeMap,sceneUniformMap,cameraUniformMap,spriteUniformMap,materialUniformMap,renderElementUniformMap); } Shader3D.addInclude=function(fileName,txt){ ShaderCompile.addInclude(fileName,txt); } Shader3D._createShader=function(gl,str,type){ var shader=gl.createShader(type); gl.shaderSource(shader,str); gl.compileShader(shader); if (ShaderCompile3D.debugMode && !gl.getShaderParameter(shader,/*laya.webgl.WebGLContext.COMPILE_STATUS*/0x8B81)) throw gl.getShaderInfoLog(shader); return shader; } Shader3D.PERIOD_RENDERELEMENT=0; Shader3D.PERIOD_MATERIAL=1; Shader3D.PERIOD_SPRITE=2; Shader3D.PERIOD_CAMERA=3; Shader3D.PERIOD_SCENE=4; Shader3D._TEXTURES=[ /*laya.webgl.WebGLContext.TEXTURE0*/0x84C0,/*laya.webgl.WebGLContext.TEXTURE1*/0x84C1,/*laya.webgl.WebGLContext.TEXTURE2*/0x84C2,/*laya.webgl.WebGLContext.TEXTURE3*/0x84C3,/*laya.webgl.WebGLContext.TEXTURE4*/0x84C4,/*laya.webgl.WebGLContext.TEXTURE5*/0x84C5,/*laya.webgl.WebGLContext.TEXTURE6*/0x84C6,/*laya.webgl.WebGLContext.TEXTURE7*/0x84C7]; Shader3D._count=0; __static(Shader3D, ['shaderParamsMap',function(){return this.shaderParamsMap={"float":/*laya.webgl.WebGLContext.FLOAT*/0x1406,"int":/*laya.webgl.WebGLContext.INT*/0x1404,"bool":/*laya.webgl.WebGLContext.BOOL*/0x8B56,"vec2":/*laya.webgl.WebGLContext.FLOAT_VEC2*/0x8B50,"vec3":/*laya.webgl.WebGLContext.FLOAT_VEC3*/0x8B51,"vec4":/*laya.webgl.WebGLContext.FLOAT_VEC4*/0x8B52,"ivec2":/*laya.webgl.WebGLContext.INT_VEC2*/0x8B53,"ivec3":/*laya.webgl.WebGLContext.INT_VEC3*/0x8B54,"ivec4":/*laya.webgl.WebGLContext.INT_VEC4*/0x8B55,"bvec2":/*laya.webgl.WebGLContext.BOOL_VEC2*/0x8B57,"bvec3":/*laya.webgl.WebGLContext.BOOL_VEC3*/0x8B58,"bvec4":/*laya.webgl.WebGLContext.BOOL_VEC4*/0x8B59,"mat2":/*laya.webgl.WebGLContext.FLOAT_MAT2*/0x8B5A,"mat3":/*laya.webgl.WebGLContext.FLOAT_MAT3*/0x8B5B,"mat4":/*laya.webgl.WebGLContext.FLOAT_MAT4*/0x8B5C,"sampler2D":/*laya.webgl.WebGLContext.SAMPLER_2D*/0x8B5E,"samplerCube":/*laya.webgl.WebGLContext.SAMPLER_CUBE*/0x8B60};},'nameKey',function(){return this.nameKey=new StringKey();} ]); return Shader3D; })(BaseShader) //class laya.d3.core.material.PBRMaterial extends laya.d3.core.material.BaseMaterial var PBRMaterial=(function(_super){ function PBRMaterial(){ /**@private */ this._transformUV=null; PBRMaterial.__super.call(this); if (!laya.d3.core.material.PBRMaterial.pbrlutTex){ var lutdt=Browser.window['__pbrlutdata']; if (!lutdt){ alert('no pbr lutdata, need pbrlut.js'); throw 'no pbr lutdata, need pbrlut.js'; }; var luttex=DataTexture2D.create((new Uint32Array(lutdt)).buffer,256,256,/*laya.webgl.WebGLContext.NEAREST*/0x2600,/*laya.webgl.WebGLContext.NEAREST*/0x2600,false); laya.d3.core.material.PBRMaterial.pbrlutTex=luttex; } this._setTexture(4,laya.d3.core.material.PBRMaterial.pbrlutTex); this.setShaderName("PBR"); this._setNumber(0,0.5); this.use_groundtruth=false; } __class(PBRMaterial,'laya.d3.core.material.PBRMaterial',_super); var __proto=PBRMaterial.prototype; /** *禁用灯光。 */ __proto.disableLight=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } /** *禁用雾化。 */ __proto.disableFog=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); } __proto.onAsynLoaded=function(url,data,params){ _super.prototype.onAsynLoaded.call(this,url,data,params); } /** *vdc算法产生的序列。这个比random要均匀一些。 */ __proto.radicalInverse_VdC=function(bits){ var tmpUint=new Uint32Array(1); return (function(bits){ bits=(bits << 16)| (bits >>> 16); bits=((bits & 0x55555555)<< 1)| ((bits & 0xAAAAAAAA)>>> 1); bits=((bits & 0x33333333)<< 2)| ((bits & 0xCCCCCCCC)>>> 2); bits=((bits & 0x0F0F0F0F)<< 4)| ((bits & 0xF0F0F0F0)>>> 4); bits=((bits & 0x00FF00FF)<< 8)| ((bits & 0xFF00FF00)>>> 8); tmpUint[0]=bits; return tmpUint[0] *2.3283064365386963e-10; })(bits); } /** * */ __proto.createHammersleyTex=function(w,h){ var ret=new Uint8Array(w *h *4); var ri=0; var ci=0; for (ci=0;ci < w *h;ci++){ var v=this.radicalInverse_VdC(ci); ret[ri++]=v *255; ret[ri++]=0; ret[ri++]=0; ret[ri++]=255; } return ret; } /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(2); },function(value){ this._setTexture(2,value); }); __getset(0,__proto,'has_tangent',null,function(v){ this._addShaderDefine(PBRMaterial.SHADERDEFINE_HAS_TANGENT); }); /** *设置粗糙度的值,0为特别光滑,1为特别粗糙。 *@param value 粗糙度。 */ /** *获取粗糙度的值,0为特别光滑,1为特别粗糙。 *@return 粗糙度的值。 */ __getset(0,__proto,'roughness',function(){ return this._getNumber(6); },function(value){ this._setNumber(6,value); this._addShaderDefine(PBRMaterial.SHADERDEFINE_FIX_ROUGHNESS); }); __getset(0,__proto,'metaless',function(){ return this._getNumber(7); },function(v){ this._setNumber(7,v); this._addShaderDefine(PBRMaterial.SHADERDEFINE_FIX_METALESS); }); /** *设置PBRLUT贴图。 *@param value PBRLUT贴图。 */ /** *获取PBRLUT贴图。 *@return PBRLUT贴图。 */ __getset(0,__proto,'pbrlutTexture',function(){ return this._getTexture(4); },function(value){ this._setTexture(4,value); }); __getset(0,__proto,'use_groundtruth',null,function(v){ if (v){ this._addShaderDefine(PBRMaterial.SHADERDEFINE_USE_GROUNDTRUTH); if (!laya.d3.core.material.PBRMaterial.HammersleyNoiseTex){ var texdata=this.createHammersleyTex(32,32); laya.d3.core.material.PBRMaterial.HammersleyNoiseTex=DataTexture2D.create(texdata.buffer,32,32,/*laya.webgl.WebGLContext.NEAREST*/0x2600,/*laya.webgl.WebGLContext.NEAREST*/0x2600,false); } this._setTexture(15,PBRMaterial.HammersleyNoiseTex); }else { laya.d3.core.material.PBRMaterial.HammersleyNoiseTex=null; this._removeShaderDefine(PBRMaterial.SHADERDEFINE_USE_GROUNDTRUTH); } }); /** *设置UV变换。 *@param value UV变换。 */ /** *获取UV变换。 *@return UV变换。 */ __getset(0,__proto,'transformUV',function(){ return this._transformUV; },function(value){ this._transformUV=value; this._setMatrix4x4(8,value.matrix); if (this._conchMaterial){ this._conchMaterial.setShaderValue(8,value.matrix.elements,0); } }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ this._setTexture(1,value); }); __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.alphaTest=false; break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=false; break ; case 3: this.depthWrite=true; this.cull=2; this.blend=0; this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; break ; case 13: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; default : throw new Error("PBRMaterial:renderMode value error."); } }); /** *设置pbr信息贴图。 *@param value pbr信息贴图。 */ /** *获取pbr信息贴图。 *@return pbr信息贴图。 */ __getset(0,__proto,'pbrInfoTexture',function(){ return this._getTexture(3); },function(value){ this._setTexture(3,value); this._addShaderDefine(PBRMaterial.SHADERDEFINE_HAS_PBRINFO); }); __getset(0,__proto,'testClipZ',null,function(v){ this._addShaderDefine(PBRMaterial.SHADERDEFINE_TEST_CLIPZ); }); PBRMaterial.__init__=function(){ PBRMaterial.SHADERDEFINE_FIX_METALESS=PBRMaterial.shaderDefines.registerDefine("FIX_METALESS"); PBRMaterial.SHADERDEFINE_FIX_ROUGHNESS=PBRMaterial.shaderDefines.registerDefine("FIX_ROUGHNESS"); PBRMaterial.SHADERDEFINE_HAS_TANGENT=PBRMaterial.shaderDefines.registerDefine("HAS_TANGENT"); PBRMaterial.SHADERDEFINE_HAS_PBRINFO=PBRMaterial.shaderDefines.registerDefine("HAS_PBRINFO"); PBRMaterial.SHADERDEFINE_USE_GROUNDTRUTH=PBRMaterial.shaderDefines.registerDefine("USE_GROUNDTRUTH"); PBRMaterial.SHADERDEFINE_TEST_CLIPZ=PBRMaterial.shaderDefines.registerDefine("CLIPZ"); } PBRMaterial.load=function(url){ return Laya.loader.create(url,null,null,PBRMaterial); } PBRMaterial.DIFFUSETEXTURE=1; PBRMaterial.NORMALTEXTURE=2; PBRMaterial.PBRINFOTEXTURE=3; PBRMaterial.PBRLUTTEXTURE=4; PBRMaterial.UVANIAGE=5; PBRMaterial.MATERIALROUGHNESS=6; PBRMaterial.MATERIALMETALESS=7; PBRMaterial.UVMATRIX=8; PBRMaterial.UVAGE=9; PBRMaterial.AOOBJPOS=14; PBRMaterial.HSNOISETEXTURE=15; PBRMaterial.SHADERDEFINE_FIX_ROUGHNESS=0; PBRMaterial.SHADERDEFINE_FIX_METALESS=0; PBRMaterial.SHADERDEFINE_HAS_TANGENT=0; PBRMaterial.SHADERDEFINE_TEST_CLIPZ=0; PBRMaterial.SHADERDEFINE_HAS_PBRINFO=0; PBRMaterial.SHADERDEFINE_USE_GROUNDTRUTH=0; PBRMaterial.RENDERMODE_OPAQUE=1; PBRMaterial.RENDERMODE_OPAQUEDOUBLEFACE=2; PBRMaterial.RENDERMODE_CUTOUT=3; PBRMaterial.RENDERMODE_CUTOUTDOUBLEFACE=4; PBRMaterial.RENDERMODE_TRANSPARENT=13; PBRMaterial.pbrlutTex=null; PBRMaterial.HammersleyNoiseTex=null; __static(PBRMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new PBRMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return PBRMaterial; })(BaseMaterial) /** *... *@author WuTaiLang */ //class laya.d3.core.material.PBRSpecularMaterial extends laya.d3.core.material.BaseMaterial var PBRSpecularMaterial=(function(_super){ function PBRSpecularMaterial(){ PBRSpecularMaterial.__super.call(this); this.setShaderName("PBRSpecular"); this._setColor(7,new Vector4(1.0,1.0,1.0,1.0)); this._setColor(9,new Vector4(0.0,0.0,0.0,0.0)); this._setColor(8,new Vector4(0.2,0.2,0.2,0.2)); this._setNumber(10,0.5); this._setNumber(11,1.0); this._setNumber(12,0); this._setNumber(13,1.0); this._setNumber(14,1.0); this._setNumber(15,0.001); this._setBool(16,false); this._setNumber(0,0.5); } __class(PBRSpecularMaterial,'laya.d3.core.material.PBRSpecularMaterial',_super); var __proto=PBRSpecularMaterial.prototype; /** *设置漫反射颜色。 *@param value 漫反射颜色。 */ /** *获取漫反射颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(7); },function(value){ this._setColor(7,value); }); /** *设置高光贴图。 *@param value 高光贴图。 */ /** *获取高光贴图。 *@return 高光贴图。 */ __getset(0,__proto,'specularTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE); this._setTexture(2,value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'albedoTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_DIFFUSETEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_DIFFUSETEXTURE); this._setTexture(1,value); }); /** *设置遮挡贴图。 *@param value 遮挡贴图。 */ /** *获取遮挡贴图。 *@return 遮挡贴图。 */ __getset(0,__proto,'occlusionTexture',function(){ return this._getTexture(5); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE); this._setTexture(5,value); }); /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(3); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE); this._setTexture(3,value); }); /** *设置视差贴图。 *@param value 视察贴图。 */ /** *获取视差贴图。 *@return 视察贴图。 */ __getset(0,__proto,'parallaxTexture',function(){ return this._getTexture(4); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE); this._setTexture(4,value); }); /** *设置放射颜色。 *@param value 放射颜色。 */ /** *获取放射颜色。 *@return 放射颜色。 */ __getset(0,__proto,'emissionColor',function(){ return this._getColor(9); },function(value){ this._setColor(9,value); }); /** *设置法线贴图缩放系数。 *@param value 法线贴图缩放系数。 */ /** *获取法线贴图缩放系数。 *@return 法线贴图缩放系数。 */ __getset(0,__proto,'normalTextureScale',function(){ return this._getNumber(14); },function(value){ this._setNumber(14,value); }); /** *设置视差贴图缩放系数。 *@param value 视差缩放系数。 */ /** *获取视差贴图缩放系数。 *@return 视差缩放系数。 */ __getset(0,__proto,'parallaxTextureScale',function(){ return this._getNumber(15); },function(value){ value=Math.max(0.005,Math.min(0.08,value)); this._setNumber(15,value); }); /** *设置遮挡贴图强度。 *@param value 遮挡贴图强度,范围为0到1。 */ /** *获取遮挡贴图强度。 *@return 遮挡贴图强度,范围为0到1。 */ __getset(0,__proto,'occlusionTextureStrength',function(){ return this._getNumber(13); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(13,value); }); /** *设置高光颜色。 *@param value 高光颜色。 */ /** *获取高光颜色。 *@return 高光颜色。 */ __getset(0,__proto,'specularColor',function(){ return this._getColor(8); },function(value){ this._setColor(8,value); }); /** *设置光滑度。 *@param value 光滑度,范围为0到1。 */ /** *获取光滑度。 *@return 光滑度,范围为0到1。 */ __getset(0,__proto,'smoothness',function(){ return this._getNumber(10); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(10,value); }); /** *设置光滑度缩放系数。 *@param value 光滑度缩放系数,范围为0到1。 */ /** *获取光滑度缩放系数。 *@return 光滑度缩放系数,范围为0到1。 */ __getset(0,__proto,'smoothnessTextureScale',function(){ return this._getNumber(11); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(11,value); }); /** *设置光滑度数据源。 *@param value 光滑滑度数据源,0或1。 */ /** *获取光滑度数据源 *@return 光滑滑度数据源,0或1。 */ __getset(0,__proto,'smoothnessSource',function(){ return this._getNumber(12); },function(value){ if (value==1) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA); else{ this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA); value=0; } this._setNumber(12,value); }); /** *设置是否激活放射属性。 *@param value 是否激活放射属性 */ /** *获取是否激活放射属性。 *@return 是否激活放射属性。 */ __getset(0,__proto,'enableEmission',function(){ return this._getBool(16); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_EMISSION); else{ this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_EMISSION); } this._setBool(16,value); }); /** *设置放射贴图。 *@param value 放射贴图。 */ /** *获取放射贴图。 *@return 放射贴图。 */ __getset(0,__proto,'emissionTexture',function(){ return this._getTexture(6); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE); this._setTexture(6,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(17); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(17,value); }); PBRSpecularMaterial.__init__=function(){ PBRSpecularMaterial.SHADERDEFINE_DIFFUSETEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("DIFFUSETEXTURE"); PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("SPECULARTEXTURE"); PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA=PBRSpecularMaterial.shaderDefines.registerDefine("SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA"); PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("NORMALTEXTURE"); PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("PARALLAXTEXTURE"); PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("OCCLUSIONTEXTURE"); PBRSpecularMaterial.SHADERDEFINE_EMISSION=PBRSpecularMaterial.shaderDefines.registerDefine("EMISSION"); PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("EMISSIONTEXTURE"); PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET=PBRSpecularMaterial.shaderDefines.registerDefine("TILINGOFFSET"); } PBRSpecularMaterial.SmoothnessSource_MetallicGlossTexture_Alpha=0; PBRSpecularMaterial.SmoothnessSource_DiffuseTexture_Alpha=1; PBRSpecularMaterial.SHADERDEFINE_DIFFUSETEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA=0; PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_EMISSION=0; PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET=0; PBRSpecularMaterial.DIFFUSETEXTURE=1; PBRSpecularMaterial.SPECULARTEXTURE=2; PBRSpecularMaterial.NORMALTEXTURE=3; PBRSpecularMaterial.PARALLAXTEXTURE=4; PBRSpecularMaterial.OCCLUSIONTEXTURE=5; PBRSpecularMaterial.EMISSIONTEXTURE=6; PBRSpecularMaterial.DIFFUSECOLOR=7; PBRSpecularMaterial.SPECULARCOLOR=8; PBRSpecularMaterial.EMISSIONCOLOR=9; PBRSpecularMaterial.SMOOTHNESS=10; PBRSpecularMaterial.SMOOTHNESSSCALE=11; PBRSpecularMaterial.SMOOTHNESSSOURCE=12; PBRSpecularMaterial.OCCLUSIONSTRENGTH=13; PBRSpecularMaterial.NORMALSCALE=14; PBRSpecularMaterial.PARALLAXSCALE=15; PBRSpecularMaterial.ENABLEEMISSION=16; PBRSpecularMaterial.TILINGOFFSET=17; __static(PBRSpecularMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return PBRSpecularMaterial; })(BaseMaterial) /** *... *@author WuTaiLang */ //class laya.d3.core.material.PBRStandardMaterial extends laya.d3.core.material.BaseMaterial var PBRStandardMaterial=(function(_super){ function PBRStandardMaterial(){ PBRStandardMaterial.__super.call(this); this.setShaderName("PBRStandard"); this._setColor(7,new Vector4(1.0,1.0,1.0,1.0)); this._setColor(8,new Vector4(0.0,0.0,0.0,0.0)); this._setNumber(9,0.0); this._setNumber(10,0.5); this._setNumber(11,1.0); this._setNumber(12,0); this._setNumber(13,1.0); this._setNumber(14,1.0); this._setNumber(15,0.001); this._setBool(16,false); this._setNumber(0,0.5); } __class(PBRStandardMaterial,'laya.d3.core.material.PBRStandardMaterial',_super); var __proto=PBRStandardMaterial.prototype; /** *设置漫反射颜色。 *@param value 漫反射颜色。 */ /** *获取漫反射颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(7); },function(value){ this._setColor(7,value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'albedoTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_DIFFUSETEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_DIFFUSETEXTURE); this._setTexture(1,value); }); /** *设置是否激活放射属性。 *@param value 是否激活放射属性 */ /** *获取是否激活放射属性。 *@return 是否激活放射属性。 */ __getset(0,__proto,'enableEmission',function(){ return this._getBool(16); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_EMISSION); else { this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_EMISSION); } this._setBool(16,value); }); /** *设置金属光滑度贴图。 *@param value 金属光滑度贴图。 */ /** *获取金属光滑度贴图。 *@return 金属光滑度贴图。 */ __getset(0,__proto,'metallicGlossTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE); this._setTexture(2,value); }); /** *设置遮挡贴图。 *@param value 遮挡贴图。 */ /** *获取遮挡贴图。 *@return 遮挡贴图。 */ __getset(0,__proto,'occlusionTexture',function(){ return this._getTexture(5); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE); this._setTexture(5,value); }); /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(3); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE); this._setTexture(3,value); }); /** *设置视差贴图。 *@param value 视察贴图。 */ /** *获取视差贴图。 *@return 视察贴图。 */ __getset(0,__proto,'parallaxTexture',function(){ return this._getTexture(4); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE); this._setTexture(4,value); }); /** *设置放射颜色。 *@param value 放射颜色。 */ /** *获取放射颜色。 *@return 放射颜色。 */ __getset(0,__proto,'emissionColor',function(){ return this._getColor(8); },function(value){ this._setColor(8,value); }); /** *设置法线贴图缩放系数。 *@param value 法线贴图缩放系数。 */ /** *获取法线贴图缩放系数。 *@return 法线贴图缩放系数。 */ __getset(0,__proto,'normalTextureScale',function(){ return this._getNumber(14); },function(value){ this._setNumber(14,value); }); /** *设置视差贴图缩放系数。 *@param value 视差缩放系数。 */ /** *获取视差贴图缩放系数。 *@return 视差缩放系数。 */ __getset(0,__proto,'parallaxTextureScale',function(){ return this._getNumber(15); },function(value){ value=Math.max(0.005,Math.min(0.08,value)); this._setNumber(15,value); }); /** *设置遮挡贴图强度。 *@param value 遮挡贴图强度,范围为0到1。 */ /** *获取遮挡贴图强度。 *@return 遮挡贴图强度,范围为0到1。 */ __getset(0,__proto,'occlusionTextureStrength',function(){ return this._getNumber(13); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(13,value); }); /** *设置金属度。 *@param value 金属度,范围为0到1。 */ /** *获取金属度。 *@return 金属度,范围为0到1。 */ __getset(0,__proto,'metallic',function(){ return this._getNumber(9); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(9,value); }); /** *设置光滑度。 *@param value 光滑度,范围为0到1。 */ /** *获取光滑度。 *@return 光滑度,范围为0到1。 */ __getset(0,__proto,'smoothness',function(){ return this._getNumber(10); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(10,value); }); /** *设置光滑度缩放系数。 *@param value 光滑度缩放系数,范围为0到1。 */ /** *获取光滑度缩放系数。 *@return 光滑度缩放系数,范围为0到1。 */ __getset(0,__proto,'smoothnessTextureScale',function(){ return this._getNumber(11); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(11,value); }); /** *设置光滑度数据源。 *@param value 光滑滑度数据源,0或1。 */ /** *获取光滑度数据源 *@return 光滑滑度数据源,0或1。 */ __getset(0,__proto,'smoothnessSource',function(){ return this._getNumber(12); },function(value){ if (value==1) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA); else { this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA); value=0; } this._setNumber(12,value); }); /** *设置放射贴图。 *@param value 放射贴图。 */ /** *获取放射贴图。 *@return 放射贴图。 */ __getset(0,__proto,'emissionTexture',function(){ return this._getTexture(6); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE); this._setTexture(6,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(17); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(17,value); }); PBRStandardMaterial.__init__=function(){ PBRStandardMaterial.SHADERDEFINE_DIFFUSETEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("DIFFUSETEXTURE"); PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("METALLICGLOSSTEXTURE"); PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA=PBRStandardMaterial.shaderDefines.registerDefine("SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA"); PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("NORMALTEXTURE"); PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("PARALLAXTEXTURE"); PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("OCCLUSIONTEXTURE"); PBRStandardMaterial.SHADERDEFINE_EMISSION=PBRStandardMaterial.shaderDefines.registerDefine("EMISSION"); PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("EMISSIONTEXTURE"); PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET=PBRStandardMaterial.shaderDefines.registerDefine("TILINGOFFSET"); } PBRStandardMaterial.SmoothnessSource_MetallicGlossTexture_Alpha=0; PBRStandardMaterial.SmoothnessSource_DiffuseTexture_Alpha=1; PBRStandardMaterial.SHADERDEFINE_DIFFUSETEXTURE=0; PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE=0; PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA=0; PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE=0; PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE=0; PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE=0; PBRStandardMaterial.SHADERDEFINE_EMISSION=0; PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE=0; PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET=0; PBRStandardMaterial.DIFFUSETEXTURE=1; PBRStandardMaterial.METALLICGLOSSTEXTURE=2; PBRStandardMaterial.NORMALTEXTURE=3; PBRStandardMaterial.PARALLAXTEXTURE=4; PBRStandardMaterial.OCCLUSIONTEXTURE=5; PBRStandardMaterial.EMISSIONTEXTURE=6; PBRStandardMaterial.DIFFUSECOLOR=7; PBRStandardMaterial.EMISSIONCOLOR=8; PBRStandardMaterial.METALLIC=9; PBRStandardMaterial.SMOOTHNESS=10; PBRStandardMaterial.SMOOTHNESSSCALE=11; PBRStandardMaterial.SMOOTHNESSSOURCE=12; PBRStandardMaterial.OCCLUSIONSTRENGTH=13; PBRStandardMaterial.NORMALSCALE=14; PBRStandardMaterial.PARALLAXSCALE=15; PBRStandardMaterial.ENABLEEMISSION=16; PBRStandardMaterial.TILINGOFFSET=17; __static(PBRStandardMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return PBRStandardMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.core.material.StandardMaterial extends laya.d3.core.material.BaseMaterial var StandardMaterial=(function(_super){ function StandardMaterial(){ /**@private */ this._transformUV=null; StandardMaterial.__super.call(this); this.setShaderName("SIMPLE"); this._setColor(9,new Vector3(0.6,0.6,0.6)); this._setColor(10,new Vector3(1.0,1.0,1.0)); this._setColor(11,new Vector4(1.0,1.0,1.0,8.0)); this._setColor(12,new Vector3(1.0,1.0,1.0)); this._setColor(7,new Vector4(1.0,1.0,1.0,1.0)); this._setNumber(0,0.5); this._setColor(15,new Vector4(1.0,1.0,0.0,0.0)); this.renderMode=1; } __class(StandardMaterial,'laya.d3.core.material.StandardMaterial',_super); var __proto=StandardMaterial.prototype; /** *禁用灯光。 */ __proto.disableLight=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } /** *禁用雾化。 */ __proto.disableFog=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); } /** *@inheritDoc */ __proto.onAsynLoaded=function(url,data,params){ var jsonData=data[0]; if (jsonData.version){ _super.prototype.onAsynLoaded.call(this,url,data,params); }else { var textureMap=data[1]; var props=jsonData.props; for (var prop in props) this[prop]=props[prop]; StandardMaterial._parseStandardMaterial(textureMap,this,jsonData); this._endLoaded(); } } /** *@inheritDoc */ __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var dest=destObject; (this._transformUV)&& (dest._transformUV=this._transformUV.clone()); } /** *设置环境光颜色。 *@param value 环境光颜色。 */ __getset(0,__proto,'ambientColor',function(){ return this._getColor(9); },function(value){ this._setColor(9,value); }); /** *设置环境贴图。 *@param value 环境贴图。 */ /** *获取环境贴图。 *@return 环境贴图。 */ __getset(0,__proto,'ambientTexture',function(){ return this._getTexture(5); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_AMBIENTMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_AMBIENTMAP); } this._setTexture(5,value); }); /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 3: this.depthWrite=true; this.cull=2; this.blend=0; this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.alphaTest=true; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 4: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=true; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 13: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 14: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 15: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 16: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 5: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 6: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 7: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 8: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 9: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 10: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 11: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 12: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; default : throw new Error("Material:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置反射颜色。 *@param value 反射颜色。 */ __getset(0,__proto,'reflectColor',function(){ return this._getColor(12); },function(value){ this._setColor(12,value); }); /** *获取纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(15); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(15,value); }); /** *设置反射率。 *@param value 反射率。 */ __getset(0,__proto,'albedo',function(){ return this._getColor(7); },function(value){ this._setColor(7,value); }); /** *设置漫反射光颜色。 *@param value 漫反射光颜色。 */ __getset(0,__proto,'diffuseColor',function(){ return this._getColor(10); },function(value){ this._setColor(10,value); }); /** *设置反射率。 *@param value 反射率。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(7); },function(value){ this._setColor(7,value); }); /** *设置高光颜色。 *@param value 高光颜色。 */ __getset(0,__proto,'specularColor',function(){ return this._getColor(11); },function(value){ this._setColor(11,value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_DIFFUSEMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_DIFFUSEMAP); } this._setTexture(1,value); }); /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(2); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_NORMALMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_NORMALMAP); } this._setTexture(2,value); }); /** *设置高光贴图。 *@param value 高光贴图。 */ /** *获取高光贴图。 *@return 高光贴图。 */ __getset(0,__proto,'specularTexture',function(){ return this._getTexture(3); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_SPECULARMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_SPECULARMAP); } this._setTexture(3,value); }); /** *设置放射贴图。 *@param value 放射贴图。 */ /** *获取放射贴图。 *@return 放射贴图。 */ __getset(0,__proto,'emissiveTexture',function(){ return this._getTexture(4); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_EMISSIVEMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_EMISSIVEMAP); } this._setTexture(4,value); }); /** *设置反射贴图。 *@param value 反射贴图。 */ /** *获取反射贴图。 *@return 反射贴图。 */ __getset(0,__proto,'reflectTexture',function(){ return this._getTexture(6); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_REFLECTMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_REFLECTMAP); } this._setTexture(6,value); }); /** *设置UV变换。 *@param value UV变换。 */ /** *获取UV变换。 *@return UV变换。 */ __getset(0,__proto,'transformUV',function(){ return this._transformUV; },function(value){ this._transformUV=value; this._setMatrix4x4(13,value.matrix); if (value) this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_UVTRANSFORM); else this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_UVTRANSFORM); if (this._conchMaterial){ this._conchMaterial.setShaderValue(13,value.matrix.elements,0); } }); StandardMaterial.__init__=function(){ StandardMaterial.SHADERDEFINE_DIFFUSEMAP=StandardMaterial.shaderDefines.registerDefine("DIFFUSEMAP"); StandardMaterial.SHADERDEFINE_NORMALMAP=StandardMaterial.shaderDefines.registerDefine("NORMALMAP"); StandardMaterial.SHADERDEFINE_SPECULARMAP=StandardMaterial.shaderDefines.registerDefine("SPECULARMAP"); StandardMaterial.SHADERDEFINE_EMISSIVEMAP=StandardMaterial.shaderDefines.registerDefine("EMISSIVEMAP"); StandardMaterial.SHADERDEFINE_AMBIENTMAP=StandardMaterial.shaderDefines.registerDefine("AMBIENTMAP"); StandardMaterial.SHADERDEFINE_REFLECTMAP=StandardMaterial.shaderDefines.registerDefine("REFLECTMAP"); StandardMaterial.SHADERDEFINE_UVTRANSFORM=StandardMaterial.shaderDefines.registerDefine("UVTRANSFORM"); StandardMaterial.SHADERDEFINE_TILINGOFFSET=StandardMaterial.shaderDefines.registerDefine("TILINGOFFSET"); StandardMaterial.SHADERDEFINE_ADDTIVEFOG=StandardMaterial.shaderDefines.registerDefine("ADDTIVEFOG"); } StandardMaterial.load=function(url){ return Laya.loader.create(url,null,null,StandardMaterial); } StandardMaterial._parseStandardMaterial=function(textureMap,material,json){ var customProps=json.customProps; var ambientColorValue=customProps.ambientColor; material.ambientColor=new Vector3(ambientColorValue[0],ambientColorValue[1],ambientColorValue[2]); var diffuseColorValue=customProps.diffuseColor; material.diffuseColor=new Vector3(diffuseColorValue[0],diffuseColorValue[1],diffuseColorValue[2]); var specularColorValue=customProps.specularColor; material.specularColor=new Vector4(specularColorValue[0],specularColorValue[1],specularColorValue[2],specularColorValue[3]); var reflectColorValue=customProps.reflectColor; material.reflectColor=new Vector3(reflectColorValue[0],reflectColorValue[1],reflectColorValue[2]); var albedoColorValue=customProps.albedoColor; (albedoColorValue)&& (material.albedo=new Vector4(albedoColorValue[0],albedoColorValue[1],albedoColorValue[2],albedoColorValue[3])); var diffuseTexture=customProps.diffuseTexture.texture2D; (diffuseTexture)&& (material.diffuseTexture=Loader.getRes(textureMap[diffuseTexture])); var normalTexture=customProps.normalTexture.texture2D; (normalTexture)&& (material.normalTexture=Loader.getRes(textureMap[normalTexture])); var specularTexture=customProps.specularTexture.texture2D; (specularTexture)&& (material.specularTexture=Loader.getRes(textureMap[specularTexture])); var emissiveTexture=customProps.emissiveTexture.texture2D; (emissiveTexture)&& (material.emissiveTexture=Loader.getRes(textureMap[emissiveTexture])); var ambientTexture=customProps.ambientTexture.texture2D; (ambientTexture)&& (material.ambientTexture=Loader.getRes(textureMap[ambientTexture])); var reflectTexture=customProps.reflectTexture.texture2D; (reflectTexture)&& (material.reflectTexture=Loader.getRes(textureMap[reflectTexture])); } StandardMaterial.RENDERMODE_OPAQUE=1; StandardMaterial.RENDERMODE_OPAQUEDOUBLEFACE=2; StandardMaterial.RENDERMODE_CUTOUT=3; StandardMaterial.RENDERMODE_CUTOUTDOUBLEFACE=4; StandardMaterial.RENDERMODE_TRANSPARENT=13; StandardMaterial.RENDERMODE_TRANSPARENTDOUBLEFACE=14; StandardMaterial.RENDERMODE_ADDTIVE=15; StandardMaterial.RENDERMODE_ADDTIVEDOUBLEFACE=16; StandardMaterial.RENDERMODE_DEPTHREAD_TRANSPARENT=5; StandardMaterial.RENDERMODE_DEPTHREAD_TRANSPARENTDOUBLEFACE=6; StandardMaterial.RENDERMODE_DEPTHREAD_ADDTIVE=7; StandardMaterial.RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE=8; StandardMaterial.RENDERMODE_NONDEPTH_TRANSPARENT=9; StandardMaterial.RENDERMODE_NONDEPTH_TRANSPARENTDOUBLEFACE=10; StandardMaterial.RENDERMODE_NONDEPTH_ADDTIVE=11; StandardMaterial.RENDERMODE_NONDEPTH_ADDTIVEDOUBLEFACE=12; StandardMaterial.SHADERDEFINE_DIFFUSEMAP=0; StandardMaterial.SHADERDEFINE_NORMALMAP=0; StandardMaterial.SHADERDEFINE_SPECULARMAP=0; StandardMaterial.SHADERDEFINE_EMISSIVEMAP=0; StandardMaterial.SHADERDEFINE_AMBIENTMAP=0; StandardMaterial.SHADERDEFINE_REFLECTMAP=0; StandardMaterial.SHADERDEFINE_UVTRANSFORM=0; StandardMaterial.SHADERDEFINE_TILINGOFFSET=0; StandardMaterial.SHADERDEFINE_ADDTIVEFOG=0; StandardMaterial.DIFFUSETEXTURE=1; StandardMaterial.NORMALTEXTURE=2; StandardMaterial.SPECULARTEXTURE=3; StandardMaterial.EMISSIVETEXTURE=4; StandardMaterial.AMBIENTTEXTURE=5; StandardMaterial.REFLECTTEXTURE=6; StandardMaterial.ALBEDO=7; StandardMaterial.UVANIAGE=8; StandardMaterial.MATERIALAMBIENT=9; StandardMaterial.MATERIALDIFFUSE=10; StandardMaterial.MATERIALSPECULAR=11; StandardMaterial.MATERIALREFLECT=12; StandardMaterial.UVMATRIX=13; StandardMaterial.UVAGE=14; StandardMaterial.TILINGOFFSET=15; __static(StandardMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new StandardMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return StandardMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.core.material.TerrainMaterial extends laya.d3.core.material.BaseMaterial var TerrainMaterial=(function(_super){ function TerrainMaterial(){ this._diffuseScale1=null; this._diffuseScale2=null; this._diffuseScale3=null; this._diffuseScale4=null; TerrainMaterial.__super.call(this); this.setShaderName("Terrain"); this.renderMode=1; this._diffuseScale1=new Vector2(); this._diffuseScale2=new Vector2(); this._diffuseScale3=new Vector2(); this._diffuseScale4=new Vector2(); this.ambientColor=new Vector3(0.6,0.6,0.6); this.diffuseColor=new Vector3(1.0,1.0,1.0); this.specularColor=new Vector4(0.2,0.2,0.2,32.0); } __class(TerrainMaterial,'laya.d3.core.material.TerrainMaterial',_super); var __proto=TerrainMaterial.prototype; __proto.setDiffuseScale1=function(x,y){ this._diffuseScale1.x=x; this._diffuseScale1.y=y; this._setColor(6,this._diffuseScale1); } __proto.setDiffuseScale2=function(x,y){ this._diffuseScale2.x=x; this._diffuseScale2.y=y; this._setColor(7,this._diffuseScale2); } __proto.setDiffuseScale3=function(x,y){ this._diffuseScale3.x=x; this._diffuseScale3.y=y; this._setColor(8,this._diffuseScale3); } __proto.setDiffuseScale4=function(x,y){ this._diffuseScale4.x=x; this._diffuseScale4.y=y; this._setColor(9,this._diffuseScale4); } __proto.setDetailNum=function(value){ switch (value){ case 1: this._addShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM4); break ; case 2: this._addShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM4); break ; case 3: this._addShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM4); break ; case 4: this._addShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM4); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM3); break ; } } __proto.disableLight=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } /** *@inheritDoc */ __proto.setShaderName=function(name){ _super.prototype.setShaderName.call(this,name); } /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.depthTest=0x0201; break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.depthTest=0x0203; break ; default : throw new Error("TerrainMaterial:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置第二层贴图。 *@param value 第二层贴图。 */ /** *获取第二层贴图。 *@return 第二层贴图。 */ __getset(0,__proto,'diffuseTexture2',function(){ return this._getTexture(3); },function(value){ this._setTexture(3,value); }); __getset(0,__proto,'ambientColor',function(){ return this._getColor(10); },function(value){ this._setColor(10,value); }); /** *设置第四层贴图。 *@param value 第四层贴图。 */ /** *获取第四层贴图。 *@return 第四层贴图。 */ __getset(0,__proto,'diffuseTexture4',function(){ return this._getTexture(5); },function(value){ this._setTexture(5,value); }); __getset(0,__proto,'diffuseColor',function(){ return this._getColor(11); },function(value){ this._setColor(11,value); }); /** *设置第一层贴图。 *@param value 第一层贴图。 */ /** *获取第一层贴图。 *@return 第一层贴图。 */ __getset(0,__proto,'diffuseTexture1',function(){ return this._getTexture(2); },function(value){ this._setTexture(2,value); }); __getset(0,__proto,'specularColor',function(){ return this._getColor(12); },function(value){ this._setColor(12,value); }); /** *设置第三层贴图。 *@param value 第三层贴图。 */ /** *获取第三层贴图。 *@return 第三层贴图。 */ __getset(0,__proto,'diffuseTexture3',function(){ return this._getTexture(4); },function(value){ this._setTexture(4,value); }); /** *设置splatAlpha贴图。 *@param value splatAlpha贴图。 */ /** *获取splatAlpha贴图。 *@return splatAlpha贴图。 */ __getset(0,__proto,'splatAlphaTexture',function(){ return this._getTexture(0); },function(value){ this._setTexture(0,value); }); __getset(0,__proto,'normalTexture',function(){ return this._getTexture(1); },function(value){ this._setTexture(1,value); }); TerrainMaterial.__init__=function(){ TerrainMaterial.SHADERDEFINE_DETAIL_NUM1=TerrainMaterial.shaderDefines.registerDefine("DETAIL_NUM1"); TerrainMaterial.SHADERDEFINE_DETAIL_NUM2=TerrainMaterial.shaderDefines.registerDefine("DETAIL_NUM2"); TerrainMaterial.SHADERDEFINE_DETAIL_NUM4=TerrainMaterial.shaderDefines.registerDefine("DETAIL_NUM4"); TerrainMaterial.SHADERDEFINE_DETAIL_NUM3=TerrainMaterial.shaderDefines.registerDefine("DETAIL_NUM3"); } TerrainMaterial.load=function(url){ return Laya.loader.create(url,null,null,TerrainMaterial); } TerrainMaterial.RENDERMODE_OPAQUE=1; TerrainMaterial.RENDERMODE_TRANSPARENT=2; TerrainMaterial.SPLATALPHATEXTURE=0; TerrainMaterial.NORMALTEXTURE=1; TerrainMaterial.DIFFUSETEXTURE1=2; TerrainMaterial.DIFFUSETEXTURE2=3; TerrainMaterial.DIFFUSETEXTURE3=4; TerrainMaterial.DIFFUSETEXTURE4=5; TerrainMaterial.DIFFUSESCALE1=6; TerrainMaterial.DIFFUSESCALE2=7; TerrainMaterial.DIFFUSESCALE3=8; TerrainMaterial.DIFFUSESCALE4=9; TerrainMaterial.MATERIALAMBIENT=10; TerrainMaterial.MATERIALDIFFUSE=11; TerrainMaterial.MATERIALSPECULAR=12; TerrainMaterial.SHADERDEFINE_DETAIL_NUM1=0; TerrainMaterial.SHADERDEFINE_DETAIL_NUM2=0; TerrainMaterial.SHADERDEFINE_DETAIL_NUM3=0; TerrainMaterial.SHADERDEFINE_DETAIL_NUM4=0; __static(TerrainMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new TerrainMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return TerrainMaterial; })(BaseMaterial) //class laya.d3.core.material.WaterMaterial extends laya.d3.core.material.BaseMaterial var WaterMaterial=(function(_super){ function WaterMaterial(){ this._useVertexDeep=false; WaterMaterial.__super.call(this); this.setShaderName("Water"); } __class(WaterMaterial,'laya.d3.core.material.WaterMaterial',_super); var __proto=WaterMaterial.prototype; /** *禁用雾化。 */ __proto.disableFog=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); } __proto.onAsynLoaded=function(url,data,params){ _super.prototype.onAsynLoaded.call(this,url,data,params); } /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ this._setTexture(1,value); }); /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(2); },function(value){ this._setTexture(2,value); }); __getset(0,__proto,'underWaterTexture',function(){ return this._getTexture(3); },function(value){ this._setTexture(3,value); }); __getset(0,__proto,'deepColorTexture',function(){ return this._getTexture(10); },function(v){ this._setTexture(10,v); }); __getset(0,__proto,'useFoam',null,function(v){ if (v){ this._addShaderDefine(WaterMaterial.SHADERDEFINE_USE_FOAM); }else { this._removeShaderDefine(WaterMaterial.SHADERDEFINE_USE_FOAM); } }); __getset(0,__proto,'skyTexture',function(){ return this._getTexture(11); },function(v){ this._setTexture(11,v); }); __getset(0,__proto,'deepScale',function(){ return this._getNumber(20); },function(v){ this._setNumber(20,v); }); __getset(0,__proto,'detailTexture',function(){ return this._getTexture(9); },function(value){ this._setTexture(9,value); }); __getset(0,__proto,'foamTexture',function(){ return this._getTexture(17); },function(v){ this._setTexture(17,v); }); __getset(0,__proto,'waterInfoTexture',function(){ return this._getTexture(16); },function(v){ this._setTexture(16,v); }); /** *对定点进行变换的纹理。现在不用 */ __getset(0,__proto,'vertexDispTexture',function(){ return this._getTexture(4); },function(value){ this._setTexture(4,value); }); __getset(0,__proto,'currentTm',function(){ return this._getNumber(8); },function(v){ this._setNumber(8,v); }); __getset(0,__proto,'waveInfo',function(){ return this._getBuffer(12); },function(v){ this._setBuffer(12,v); }); __getset(0,__proto,'waveInfoD',function(){ return this._getBuffer(13); },function(v){ this._setBuffer(13,v); }); __getset(0,__proto,'waveMainDir',function(){ return this._getNumber(14); },function(deg){ this._setNumber(14,deg *Math.PI / 180); }); __getset(0,__proto,'geoWaveUVScale',function(){ return this._getNumber(18); },function(v){ this._setNumber(18,v); }); __getset(0,__proto,'windSpeed',function(){ return 0; },function(s){ }); __getset(0,__proto,'scrsize',null,function(v){ this._setBuffer(15,v); }); __getset(0,__proto,'seaColor',function(){ return this._getBuffer(19); },function(v){ this._setBuffer(19,v); }); __getset(0,__proto,'useVertexDeep',function(){ return this._useVertexDeep; },function(v){ this._useVertexDeep=v; if (v) this._addShaderDefine(WaterMaterial.SHADERDEFINE_USEVERTEXHEIGHT); else { this._removeShaderDefine(WaterMaterial.SHADERDEFINE_USEVERTEXHEIGHT); } }); __getset(0,__proto,'windDir',function(){ return 0; },function(d){ }); __getset(0,__proto,'useRefractTexture',null,function(v){ if (v){ this._addShaderDefine(WaterMaterial.SHADERDEFINE_USE_REFRACT_TEX); }else { this._removeShaderDefine(WaterMaterial.SHADERDEFINE_USE_REFRACT_TEX); } }); __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.alphaTest=false; break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=false; break ; case 3: this.depthWrite=true; this.cull=2; this.blend=0; this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; break ; case 13: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; default : throw new Error("PBRMaterial:renderMode value error."); } }); WaterMaterial.__init__=function(){ WaterMaterial.SHADERDEFINE_CUBE_ENV=WaterMaterial.shaderDefines.registerDefine("CUBE_ENV"); WaterMaterial.SHADERDEFINE_HDR_ENV=WaterMaterial.shaderDefines.registerDefine("HDR_ENV"); WaterMaterial.SHADERDEFINE_SHOW_NORMAL=WaterMaterial.shaderDefines.registerDefine("SHOW_NORMAL"); WaterMaterial.SHADERDEFINE_USEVERTEXHEIGHT=WaterMaterial.shaderDefines.registerDefine("USE_VERTEX_DEEPINFO"); WaterMaterial.SHADERDEFINE_USE_FOAM=WaterMaterial.shaderDefines.registerDefine("USE_FOAM"); WaterMaterial.SHADERDEFINE_USE_REFRACT_TEX=WaterMaterial.shaderDefines.registerDefine("USE_REFR_TEX"); } WaterMaterial.load=function(url){ return Laya.loader.create(url,null,null,WaterMaterial); } WaterMaterial.DIFFUSETEXTURE=1; WaterMaterial.NORMALTEXTURE=2; WaterMaterial.UNDERWATERTEXTURE=3; WaterMaterial.VERTEXDISPTEXTURE=4; WaterMaterial.UVANIAGE=5; WaterMaterial.UVMATRIX=6; WaterMaterial.UVAGE=7; WaterMaterial.CURTM=8; WaterMaterial.DETAILTEXTURE=9; WaterMaterial.DEEPCOLORTEXTURE=10; WaterMaterial.SKYTEXTURE=11; WaterMaterial.WAVEINFO=12; WaterMaterial.WAVEINFOD=13; WaterMaterial.WAVEMAINDIR=14; WaterMaterial.SCRSIZE=15; WaterMaterial.WATERINFO=16; WaterMaterial.FOAMTEXTURE=17; WaterMaterial.GEOWAVE_UV_SCALE=18; WaterMaterial.SEA_COLOR=19; WaterMaterial.WAVEINFODEEPSCALE=20; WaterMaterial.SHADERDEFINE_SHOW_NORMAL=0; WaterMaterial.SHADERDEFINE_CUBE_ENV=0; WaterMaterial.SHADERDEFINE_HDR_ENV=0; WaterMaterial.SHADERDEFINE_USE_FOAM=0; WaterMaterial.SHADERDEFINE_USE_REFRACT_TEX=0; WaterMaterial.SHADERDEFINE_USEVERTEXHEIGHT=0; WaterMaterial.RENDERMODE_OPAQUE=1; WaterMaterial.RENDERMODE_OPAQUEDOUBLEFACE=2; WaterMaterial.RENDERMODE_CUTOUT=3; WaterMaterial.RENDERMODE_CUTOUTDOUBLEFACE=4; WaterMaterial.RENDERMODE_TRANSPARENT=13; __static(WaterMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new WaterMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return WaterMaterial; })(BaseMaterial) /** *IndexBuffer3D 类用于创建索引缓冲。 */ //class laya.d3.graphics.IndexBuffer3D extends laya.webgl.utils.Buffer var IndexBuffer3D=(function(_super){ function IndexBuffer3D(indexType,indexCount,bufferUsage,canRead){ /**@private */ this._indexType=null; /**@private */ this._indexTypeByteCount=0; /**@private */ this._indexCount=0; /**@private */ this._canRead=false; (bufferUsage===void 0)&& (bufferUsage=/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); (canRead===void 0)&& (canRead=false); IndexBuffer3D.__super.call(this); this._indexType=indexType; this._indexCount=indexCount; this._bufferUsage=bufferUsage; this._bufferType=/*laya.webgl.WebGLContext.ELEMENT_ARRAY_BUFFER*/0x8893; this._canRead=canRead; var byteLength=0; if (indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort") this._indexTypeByteCount=2; else if (indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_UBYTE*/"ubyte") this._indexTypeByteCount=1; else throw new Error("unidentification index type."); byteLength=this._indexTypeByteCount *indexCount; this._byteLength=byteLength; this._bind(); Buffer._gl.bufferData(this._bufferType,byteLength,this._bufferUsage); if (canRead){ if (indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort") this._buffer=new Uint16Array(indexCount); else if (indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_UBYTE*/"ubyte") this._buffer=new Uint8Array(indexCount); this.memorySize=byteLength *2; }else { this.memorySize=byteLength; } } __class(IndexBuffer3D,'laya.d3.graphics.IndexBuffer3D',_super); var __proto=IndexBuffer3D.prototype; /** *设置数据。 *@param data 索引数据。 *@param bufferOffset 索引缓冲中的偏移。 *@param dataStartIndex 索引数据的偏移。 *@param dataCount 索引数据的数量。 */ __proto.setData=function(data,bufferOffset,dataStartIndex,dataCount){ (bufferOffset===void 0)&& (bufferOffset=0); (dataStartIndex===void 0)&& (dataStartIndex=0); (dataCount===void 0)&& (dataCount=4294967295); var byteCount=0; if (this._indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort"){ byteCount=2; if (dataStartIndex!==0 || dataCount!==4294967295) data=new Uint16Array(data.buffer,dataStartIndex *byteCount,dataCount); }else if (this._indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_UBYTE*/"ubyte"){ byteCount=1; if (dataStartIndex!==0 || dataCount!==4294967295) data=new Uint8Array(data.buffer,dataStartIndex *byteCount,dataCount); } this._bind(); Buffer._gl.bufferSubData(this._bufferType,bufferOffset *byteCount,data); if (this._canRead){ if (bufferOffset!==0 || dataStartIndex!==0 || dataCount!==4294967295){ var maxLength=this._buffer.length-bufferOffset; if (dataCount > maxLength) dataCount=maxLength; for (var i=0;i < dataCount;i++) this._buffer[bufferOffset+i]=data[i]; }else { this._buffer=data; } } } /** *获取索引数据。 *@return 索引数据。 */ __proto.getData=function(){ if (this._canRead) return this._buffer; else throw new Error("Can't read data from VertexBuffer with only write flag!"); } /** *@inheritDoc */ __proto.disposeResource=function(){ _super.prototype.disposeResource.call(this); this._buffer=null; this.memorySize=0; } /** *获取索引类型。 *@return 索引类型。 */ __getset(0,__proto,'indexType',function(){ return this._indexType; }); /** *获取索引类型字节数量。 *@return 索引类型字节数量。 */ __getset(0,__proto,'indexTypeByteCount',function(){ return this._indexTypeByteCount; }); /** *获取索引个数。 *@return 索引个数。 */ __getset(0,__proto,'indexCount',function(){ return this._indexCount; }); /** *获取是否可读。 *@return 是否可读。 */ __getset(0,__proto,'canRead',function(){ return this._canRead; }); IndexBuffer3D.INDEXTYPE_UBYTE="ubyte"; IndexBuffer3D.INDEXTYPE_USHORT="ushort"; IndexBuffer3D.create=function(indexType,indexCount,bufferUsage,canRead){ (bufferUsage===void 0)&& (bufferUsage=/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); (canRead===void 0)&& (canRead=false); return new IndexBuffer3D(indexType,indexCount,bufferUsage,canRead); } return IndexBuffer3D; })(Buffer) /** *... *@author ... */ //class laya.d3.core.particleShuriKen.ShurikenParticleMaterial extends laya.d3.core.material.BaseMaterial var ShurikenParticleMaterial=(function(_super){ function ShurikenParticleMaterial(){ ShurikenParticleMaterial.__super.call(this); this.setShaderName("PARTICLESHURIKEN"); this.renderMode=6; } __class(ShurikenParticleMaterial,'laya.d3.core.particleShuriKen.ShurikenParticleMaterial',_super); var __proto=ShurikenParticleMaterial.prototype; /** *@private */ __proto.onAsynLoaded=function(url,data,params){ var jsonData=data[0]; if (jsonData.version){ _super.prototype.onAsynLoaded.call(this,url,data,params); }else { var textureMap=data[1]; var props=jsonData.props; for (var prop in props) this[prop]=props[prop]; ShurikenParticleMaterial._parseShurikenParticleMaterial(textureMap,this,jsonData); this._endLoaded(); } } /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 3: this.depthWrite=true; this.cull=2; this.blend=0; this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.alphaTest=true; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 4: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=true; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 13: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 14: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 15: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 16: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 5: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 6: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 7: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 8: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 9: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 10: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 11: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 12: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; default : throw new Error("Material:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置颜色。 *@param value 颜色。 */ /** *获取颜色。 *@return 颜色。 */ __getset(0,__proto,'tintColor',function(){ return this._getColor(2); },function(value){ if (value) this._addShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR); else this._removeShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR); this._setColor(2,value); }); /** *获取纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(3); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(3,value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP); else this._removeShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP); this._setTexture(1,value); }); ShurikenParticleMaterial.__init__=function(){ ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP=ShurikenParticleMaterial.shaderDefines.registerDefine("DIFFUSEMAP"); ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR=ShurikenParticleMaterial.shaderDefines.registerDefine("TINTCOLOR"); ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG=ShurikenParticleMaterial.shaderDefines.registerDefine("ADDTIVEFOG"); ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET=ShurikenParticleMaterial.shaderDefines.registerDefine("TILINGOFFSET"); } ShurikenParticleMaterial.load=function(url){ return Laya.loader.create(url,null,null,ShurikenParticleMaterial); } ShurikenParticleMaterial._parseShurikenParticleMaterial=function(textureMap,material,json){ var customProps=json.customProps; var diffuseTexture=customProps.diffuseTexture.texture2D; (diffuseTexture)&& (material.diffuseTexture=Loader.getRes(textureMap[diffuseTexture])); var tintColorValue=customProps.tintColor; (tintColorValue)&& (material.tintColor=new Vector4(tintColorValue[0],tintColorValue[1],tintColorValue[2],tintColorValue[3])); } ShurikenParticleMaterial.RENDERMODE_OPAQUE=1; ShurikenParticleMaterial.RENDERMODE_OPAQUEDOUBLEFACE=2; ShurikenParticleMaterial.RENDERMODE_CUTOUT=3; ShurikenParticleMaterial.RENDERMODE_CUTOUTDOUBLEFACE=4; ShurikenParticleMaterial.RENDERMODE_TRANSPARENT=13; ShurikenParticleMaterial.RENDERMODE_TRANSPARENTDOUBLEFACE=14; ShurikenParticleMaterial.RENDERMODE_ADDTIVE=15; ShurikenParticleMaterial.RENDERMODE_ADDTIVEDOUBLEFACE=16; ShurikenParticleMaterial.RENDERMODE_DEPTHREAD_TRANSPARENT=5; ShurikenParticleMaterial.RENDERMODE_DEPTHREAD_TRANSPARENTDOUBLEFACE=6; ShurikenParticleMaterial.RENDERMODE_DEPTHREAD_ADDTIVE=7; ShurikenParticleMaterial.RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE=8; ShurikenParticleMaterial.RENDERMODE_NONDEPTH_TRANSPARENT=9; ShurikenParticleMaterial.RENDERMODE_NONDEPTH_TRANSPARENTDOUBLEFACE=10; ShurikenParticleMaterial.RENDERMODE_NONDEPTH_ADDTIVE=11; ShurikenParticleMaterial.RENDERMODE_NONDEPTH_ADDTIVEDOUBLEFACE=12; ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP=0; ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR=0; ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET=0; ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG=0; ShurikenParticleMaterial.DIFFUSETEXTURE=1; ShurikenParticleMaterial.TINTCOLOR=2; ShurikenParticleMaterial.TILINGOFFSET=3; __static(ShurikenParticleMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new ShurikenParticleMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return ShurikenParticleMaterial; })(BaseMaterial) /** *VertexBuffer3D 类用于创建顶点缓冲。 */ //class laya.d3.graphics.VertexBuffer3D extends laya.webgl.utils.Buffer var VertexBuffer3D=(function(_super){ function VertexBuffer3D(vertexDeclaration,vertexCount,bufferUsage,canRead){ /**@private */ this._vertexDeclaration=null; /**@private */ this._vertexCount=0; /**@private */ this._canRead=false; (canRead===void 0)&& (canRead=false); VertexBuffer3D.__super.call(this); this._vertexDeclaration=vertexDeclaration; this._vertexCount=vertexCount; this._bufferUsage=bufferUsage; this._bufferType=/*laya.webgl.WebGLContext.ARRAY_BUFFER*/0x8892; this._canRead=canRead; this.memorySize=this._byteLength=this._vertexDeclaration.vertexStride *vertexCount; this._bind(); Buffer._gl.bufferData(this._bufferType,this._byteLength,this._bufferUsage); canRead && (this._buffer=new Float32Array(this._byteLength / 4)); } __class(VertexBuffer3D,'laya.d3.graphics.VertexBuffer3D',_super); var __proto=VertexBuffer3D.prototype; /** *和索引缓冲一起绑定。 *@param ib 索引缓冲。 */ __proto.bindWithIndexBuffer=function(ib){ (ib)&& (ib._bind()); this._bind(); } /** *设置数据。 *@param data 顶点数据。 *@param bufferOffset 顶点缓冲中的偏移。 *@param dataStartIndex 顶点数据的偏移。 *@param dataCount 顶点数据的数量。 */ __proto.setData=function(data,bufferOffset,dataStartIndex,dataCount){ (bufferOffset===void 0)&& (bufferOffset=0); (dataStartIndex===void 0)&& (dataStartIndex=0); (dataCount===void 0)&& (dataCount=4294967295); if (dataStartIndex!==0 || dataCount!==4294967295) data=new Float32Array(data.buffer,dataStartIndex *4,dataCount); this._bind(); Buffer._gl.bufferSubData(this._bufferType,bufferOffset *4,data); if (this._canRead){ if (bufferOffset!==0 || dataStartIndex!==0 || dataCount!==4294967295){ var maxLength=this._buffer.length-bufferOffset; if (dataCount > maxLength) dataCount=maxLength; for (var i=0;i < dataCount;i++) this._buffer[bufferOffset+i]=data[i]; }else { this._buffer=data; } } } /** *获取顶点数据。 *@return 顶点数据。 */ __proto.getData=function(){ if (this._canRead) return this._buffer; else throw new Error("Can't read data from VertexBuffer with only write flag!"); } /**销毁顶点缓冲。*/ __proto.disposeResource=function(){ var gl=WebGL.mainContext; var elements=this._vertexDeclaration.getVertexElements(); var enableAtributes=Buffer._enableAtributes; for (var i=0,n=elements.length;i < n;i++){ if (enableAtributes[i]===this._glBuffer){ gl.disableVertexAttribArray(i); enableAtributes[i]=null; } } _super.prototype.disposeResource.call(this); this._buffer=null; this._vertexDeclaration=null; this.memorySize=0; } /** *获取顶点结构声明。 *@return 顶点结构声明。 */ __getset(0,__proto,'vertexDeclaration',function(){ return this._vertexDeclaration; }); /** *获取顶点个数。 *@return 顶点个数。 */ __getset(0,__proto,'vertexCount',function(){ return this._vertexCount; }); /** *获取是否可读。 *@return 是否可读。 */ __getset(0,__proto,'canRead',function(){ return this._canRead; }); VertexBuffer3D.create=function(vertexDeclaration,vertexCount,bufferUsage,canRead){ (bufferUsage===void 0)&& (bufferUsage=/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); (canRead===void 0)&& (canRead=false); return new VertexBuffer3D(vertexDeclaration,vertexCount,bufferUsage,canRead); } return VertexBuffer3D; })(Buffer) /** *... *@author ... */ //class laya.d3.core.trail.TrailMaterial extends laya.d3.core.material.BaseMaterial var TrailMaterial=(function(_super){ function TrailMaterial(){ TrailMaterial.__super.call(this); this.setShaderName("Trail"); this._setColor(2,new Vector4(1.0,1.0,1.0,1.0)); } __class(TrailMaterial,'laya.d3.core.trail.TrailMaterial',_super); var __proto=TrailMaterial.prototype; /** *设置颜色。 *@param value 颜色。 */ /** *获取颜色。 *@return 颜色。 */ __getset(0,__proto,'tintColor',function(){ return this._getColor(2); },function(value){ this._setColor(2,value); }); /** *设置贴图。 *@param value 贴图。 */ /** *获取贴图。 *@return 贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.core.trail.TrailMaterial.SHADERDEFINE_DIFFUSETEXTURE); else this._removeShaderDefine(laya.d3.core.trail.TrailMaterial.SHADERDEFINE_DIFFUSETEXTURE); this._setTexture(1,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(3); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.trail.TrailMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.trail.TrailMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.trail.TrailMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(3,value); }); TrailMaterial.__init__=function(){ TrailMaterial.SHADERDEFINE_DIFFUSETEXTURE=TrailMaterial.shaderDefines.registerDefine("DIFFUSETEXTURE"); TrailMaterial.SHADERDEFINE_TILINGOFFSET=TrailMaterial.shaderDefines.registerDefine("TILINGOFFSET"); } TrailMaterial.load=function(url){ return Laya.loader.create(url,null,null,TrailMaterial); } TrailMaterial.SHADERDEFINE_DIFFUSETEXTURE=0; TrailMaterial.SHADERDEFINE_TILINGOFFSET=0; TrailMaterial.DIFFUSETEXTURE=1; TrailMaterial.TINTCOLOR=2; TrailMaterial.TILINGOFFSET=3; __static(TrailMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new TrailMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return TrailMaterial; })(BaseMaterial) //class laya.d3.extension.cartoonRender.CartoonMaterial extends laya.d3.core.material.BaseMaterial var CartoonMaterial=(function(_super){ function CartoonMaterial(){ CartoonMaterial.__super.call(this); this.setShaderName("CartoonShader"); this._setColor(5,new Vector4(0.6663285,0.6544118,1,1)); this._setNumber(6,0); this._setNumber(7,0.7956449); this._setNumber(8,0.9820514); this._setNumber(9,1); } __class(CartoonMaterial,'laya.d3.extension.cartoonRender.CartoonMaterial',_super); var __proto=CartoonMaterial.prototype; /** *设置高光贴图。 *@param value 高光贴图。 */ /** *获取高光贴图。 *@return 高光贴图。 */ __getset(0,__proto,'specularTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_SPECULARTEXTURE); else this._removeShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_SPECULARTEXTURE); this._setTexture(2,value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'albedoTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE); else this._removeShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE); this._setTexture(1,value); }); /** *设置阴影颜色。 *@param value 阴影颜色。 */ /** *获取阴影颜色。 *@return 阴影颜色。 */ __getset(0,__proto,'shadowColor',function(){ return this._getColor(5); },function(value){ this._setColor(5,value); }); /** *设置阴影强度。 *@param value 阴影强度,范围为0到1。 */ /** *获取阴影强度。 *@return 阴影强度,范围为0到1。 */ __getset(0,__proto,'shadowIntensity',function(){ return this._getNumber(7); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(7,value); }); /** *设置阴影范围。 *@param value 阴影范围,范围为0到1。 */ /** *获取阴影范围。 *@return 阴影范围,范围为0到1。 */ __getset(0,__proto,'shadowRange',function(){ return this._getNumber(6); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(6,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(4); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(4,value); }); /** *设置高光范围。 *@param value 高光范围,范围为0.9到1。 */ /** *获取高光范围。 *@return 高光范围,范围为0.9到1。 */ __getset(0,__proto,'specularRange',function(){ return this._getNumber(8); },function(value){ value=Math.max(0.9,Math.min(1.0,value)); this._setNumber(8,value); }); /** *设置高光强度。 *@param value 高光范围,范围为0到1。 */ /** *获取高光强度。 *@return 高光强度,范围为0到1。 */ __getset(0,__proto,'specularIntensity',function(){ return this._getNumber(9); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(9,value); }); CartoonMaterial.__init__=function(){ CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE=CartoonMaterial.shaderDefines.registerDefine("DIFFUSETEXTURE"); CartoonMaterial.SHADERDEFINE_SPECULARTEXTURE=CartoonMaterial.shaderDefines.registerDefine("SPECULARTEXTURE"); } CartoonMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Texcoord0':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_WorldMat':[ /*laya.d3.core.Sprite3D.WORLDMATRIX*/0,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_CameraPos':[ /*laya.d3.core.BaseCamera.CAMERAPOS*/0,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_AlbedoTexture':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.ALBEDOTEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SpecularTexture':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SPECULARTEXTURE*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_ShadowColor':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SHADOWCOLOR*/5,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_ShadowRange':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SHADOWRANGE*/6,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_ShadowIntensity':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SHADOWINTENSITY*/7,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SpecularRange':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SPECULARRANGE*/8,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SpecularIntensity':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SPECULARINTENSITY*/9,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_DirectionLight.Direction':[ /*laya.d3.core.scene.Scene.LIGHTDIRECTION*/3,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], 'u_DirectionLight.Color':[ /*laya.d3.core.scene.Scene.LIGHTDIRCOLOR*/4,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4] }; var cartoonShader=Shader3D.nameKey.add("CartoonShader"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\n\nuniform mat4 u_MvpMatrix;\nuniform mat4 u_WorldMat;\nuniform vec3 u_CameraPos;\n\nvarying vec2 v_Texcoord0;\nvarying vec3 v_Normal;\nvarying vec3 v_PositionWorld;\nvarying vec3 v_ViewDir;\n\nvoid main()\n{\n gl_Position = u_MvpMatrix * a_Position;\n \n mat3 worldMat = mat3(u_WorldMat);\n v_PositionWorld = (u_WorldMat * a_Position).xyz;\n v_Normal = worldMat * a_Normal;\n v_Texcoord0 = a_Texcoord0;\n \n v_ViewDir = u_CameraPos - v_PositionWorld;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nstruct DirectionLight\n{\n vec3 Color;\n vec3 Direction;\n};\n\nvarying vec2 v_Texcoord0;\nvarying vec3 v_Normal;\nvarying vec3 v_PositionWorld;\nvarying vec3 v_ViewDir;\n\n#ifdef ALBEDOTEXTURE\n uniform sampler2D u_AlbedoTexture;\n#endif\n\n#ifdef SPECULARTEXTURE\n uniform sampler2D u_SpecularTexture;\n#endif\n\nuniform vec4 u_ShadowColor;\nuniform float u_ShadowRange;\nuniform float u_ShadowIntensity;\nuniform float u_SpecularRange;\nuniform float u_SpecularIntensity;\n\nuniform DirectionLight u_DirectionLight;\n\nvoid main()\n{\n vec3 normal = normalize(v_Normal);\n vec3 viewdir = normalize(v_ViewDir);\n vec3 lightDir = normalize(u_DirectionLight.Direction);\n \n vec4 albedoTextureColor = vec4(1.0);\n #ifdef ALBEDOTEXTURE\n albedoTextureColor = texture2D(u_AlbedoTexture, v_Texcoord0);\n #endif\n \n vec4 specularTextureColor = vec4(1.0); \n #ifdef SPECULARTEXTURE\n specularTextureColor = texture2D(u_SpecularTexture, v_Texcoord0);\n #endif\n \n specularTextureColor = specularTextureColor;\n \n //specularTextureColor = vec4(1.0, 1.0, 1.0, 1.0);\n \n float specTexColorG = specularTextureColor.g;\n \n //Overlay BlendMode 叠加\n vec3 albedoColor;\n albedoColor.r = albedoTextureColor.r > 0.5 ? 1.0 - 2.0 * (1.0 - albedoTextureColor.r) * (1.0 - specTexColorG) : 2.0 * albedoTextureColor.r * specTexColorG;\n albedoColor.g = albedoTextureColor.g > 0.5 ? 1.0 - 2.0 * (1.0 - albedoTextureColor.g) * (1.0 - specTexColorG) : 2.0 * albedoTextureColor.g * specTexColorG;\n albedoColor.b = albedoTextureColor.b > 0.5 ? 1.0 - 2.0 * (1.0 - albedoTextureColor.b) * (1.0 - specTexColorG) : 2.0 * albedoTextureColor.b * specTexColorG;\n \n albedoColor = clamp(albedoColor, 0.0, 1.0);\n \n float nl = max(dot(normal, -lightDir), 0.0);\n \n float shadowValue = nl + specTexColorG - 0.5;\n float shadow = step(shadowValue, u_ShadowRange);\n if(u_ShadowRange > (shadowValue + 0.01))\n shadow = 1.0;\n else if(u_ShadowRange < (shadowValue - 0.01))\n shadow = 0.0;\n else\n shadow = (u_ShadowRange - (shadowValue - 0.01)) / 0.02;\n \n shadow = clamp(shadow, 0.0, 1.0);\n \n //specularTextureColor.r 影响高光范围\n float specular = step(u_SpecularRange, clamp(pow(nl, specularTextureColor.r), 0.0, 1.0));\n //specularTextureColor.b 影响高光强度\n specular = step(0.1, specular * specularTextureColor.b);\n \n vec3 albedoAreaColor = (1.0 - shadow) * albedoColor;\n vec3 shadowAreaColor = shadow * albedoColor * u_ShadowColor.rgb * u_ShadowIntensity;\n vec3 speculAreaColor = (1.0 - shadow) * albedoColor * u_SpecularIntensity * specular;\n \n vec3 finalColor = albedoAreaColor + speculAreaColor + shadowAreaColor;\n \n gl_FragColor = vec4(finalColor, 1.0);\n}\n"; var cartoonShaderCompile3D=ShaderCompile3D.add(cartoonShader,vs,ps,attributeMap,uniformMap); laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE=cartoonShaderCompile3D.registerMaterialDefine("ALBEDOTEXTURE"); laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_SPECULARTEXTURE=cartoonShaderCompile3D.registerMaterialDefine("SPECULARTEXTURE"); laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_TILINGOFFSET=cartoonShaderCompile3D.registerMaterialDefine("TILINGOFFSET"); } CartoonMaterial.ALBEDOTEXTURE=1; CartoonMaterial.SPECULARTEXTURE=2; CartoonMaterial.TILINGOFFSET=4; CartoonMaterial.SHADOWCOLOR=5; CartoonMaterial.SHADOWRANGE=6; CartoonMaterial.SHADOWINTENSITY=7; CartoonMaterial.SPECULARRANGE=8; CartoonMaterial.SPECULARINTENSITY=9; CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE=0; CartoonMaterial.SHADERDEFINE_SPECULARTEXTURE=0; CartoonMaterial.SHADERDEFINE_TILINGOFFSET=0; __static(CartoonMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return CartoonMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.extension.cartoonRender.OutlineMaterial extends laya.d3.core.material.BaseMaterial var OutlineMaterial=(function(_super){ function OutlineMaterial(){ OutlineMaterial.__super.call(this); this.setShaderName("OutlineShader"); this._setNumber(2,0.01581197); this._setNumber(3,1); } __class(OutlineMaterial,'laya.d3.extension.cartoonRender.OutlineMaterial',_super); var __proto=OutlineMaterial.prototype; /** *设置轮廓贴图。 *@param value 轮廓贴图。 */ /** *获取漫轮廓贴图。 *@return 轮廓贴图。 */ __getset(0,__proto,'outlineTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.cartoonRender.OutlineMaterial.SHADERDEFINE_OUTLINETEXTURE); else this._removeShaderDefine(laya.d3.extension.cartoonRender.OutlineMaterial.SHADERDEFINE_OUTLINETEXTURE); this._setTexture(1,value); }); /** *设置轮廓宽度。 *@param value 轮廓宽度,范围为0到0.05。 */ /** *获取轮廓宽度。 *@return 轮廓宽度,范围为0到0.05。 */ __getset(0,__proto,'outlineWidth',function(){ return this._getNumber(2); },function(value){ value=Math.max(0.0,Math.min(0.05,value)); this._setNumber(2,value); }); /** *设置轮廓亮度。 *@param value 轮廓亮度,范围为0到1。 */ /** *获取轮廓亮度。 *@return 轮廓亮度,范围为0到1。 */ __getset(0,__proto,'outlineLightness',function(){ return this._getNumber(3); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(3,value); }); OutlineMaterial.__init__=function(){ OutlineMaterial.SHADERDEFINE_OUTLINETEXTURE=OutlineMaterial.shaderDefines.registerDefine("OUTLINETEXTURE"); } OutlineMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Texcoord0':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_OutlineTexture':[ /*CLASS CONST:laya.d3.extension.cartoonRender.OutlineMaterial.OUTLINETEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_OutlineWidth':[ /*CLASS CONST:laya.d3.extension.cartoonRender.OutlineMaterial.OUTLINEWIDTH*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_OutlineLightness':[ /*CLASS CONST:laya.d3.extension.cartoonRender.OutlineMaterial.OUTLINELIGHTNESS*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1] }; var outlineShader=Shader3D.nameKey.add("OutlineShader"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\n\nuniform mat4 u_MvpMatrix;\nuniform float u_OutlineWidth;\n\nvarying vec2 v_Texcoord0;\n\nvoid main()\n{\n v_Texcoord0 = a_Texcoord0;\n \n vec4 position = vec4(a_Position.xyz + a_Normal * u_OutlineWidth, 1.0);\n gl_Position = u_MvpMatrix * position;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nstruct DirectionLight\n{\n vec3 Color;\n vec3 Direction;\n};\n\nvarying vec2 v_Texcoord0;\n\n#ifdef OUTLINETEXTURE\n uniform sampler2D u_OutlineTexture;\n#endif\nuniform float u_OutlineLightness;\n\nvoid main()\n{\n vec4 outlineTextureColor = vec4(1.0);\n #ifdef OUTLINETEXTURE\n outlineTextureColor = texture2D(u_OutlineTexture, v_Texcoord0);\n #endif\n \n vec3 finalColor = outlineTextureColor.rgb * u_OutlineLightness;\n \n gl_FragColor = vec4(finalColor,0.0);\n}\n"; var outlineShaderCompile3D=ShaderCompile3D.add(outlineShader,vs,ps,attributeMap,uniformMap); laya.d3.extension.cartoonRender.OutlineMaterial.SHADERDEFINE_OUTLINETEXTURE=outlineShaderCompile3D.registerMaterialDefine("OUTLINETEXTURE"); } OutlineMaterial.OUTLINETEXTURE=1; OutlineMaterial.OUTLINEWIDTH=2; OutlineMaterial.OUTLINELIGHTNESS=3; OutlineMaterial.SHADERDEFINE_OUTLINETEXTURE=0; __static(OutlineMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return OutlineMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.domino.DominoMaterial extends laya.d3.core.material.BaseMaterial var DominoMaterial=(function(_super){ function DominoMaterial(){ DominoMaterial.__super.call(this); this.setShaderName("DominoShader"); } __class(DominoMaterial,'laya.d3.extension.domino.DominoMaterial',_super); DominoMaterial.__init__=function(){} DominoMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Color' :/*laya.d3.graphics.VertexElementUsage.COLOR0*/1 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_WorldMat':[ /*laya.d3.core.Sprite3D.WORLDMATRIX*/0,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_CameraPos':[ /*laya.d3.core.BaseCamera.CAMERAPOS*/0,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_DirectionLight.Direction':[ /*laya.d3.core.scene.Scene.LIGHTDIRECTION*/3,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], 'u_DirectionLight.Color':[ /*laya.d3.core.scene.Scene.LIGHTDIRCOLOR*/4,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], }; var dominoShader=Shader3D.nameKey.add("DominoShader"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\nattribute vec4 a_Color;\n\nuniform mat4 u_MvpMatrix;\nuniform mat4 u_WorldMat;\nuniform vec3 u_CameraPos;\n\nvarying vec2 v_Texcoord0;\nvarying vec4 v_Color;\nvarying vec3 v_PositionWorld;\nvarying vec3 v_Normal;\nvarying vec3 v_ViewDir;\n\nvoid main()\n{\n v_Texcoord0 = a_Texcoord0;\n v_Color = a_Color;\n \n gl_Position = u_MvpMatrix * a_Position;\n \n v_Normal = mat3(u_WorldMat) * a_Normal;\n v_PositionWorld = (u_WorldMat * a_Position).xyz;\n v_ViewDir = u_CameraPos - v_PositionWorld;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nstruct DirectionLight\n{\n vec3 Color;\n vec3 Direction;\n};\nuniform DirectionLight u_DirectionLight;\n\nvarying vec2 v_Texcoord0;\nvarying vec4 v_Color;\nvarying vec3 v_ViewDir; \nvarying vec3 v_Normal;\n\nvoid LayaAirBlinnPhongDiectionLight (in vec3 normal, in vec3 viewDir, in DirectionLight light,out vec3 diffuseColor)\n{\n vec3 lightVec = normalize(light.Direction);\n \n //mediump vec3 h = normalize(viewDir-light.Direction);\n //float nh = max (0.0, dot (h,normal));\n \n lowp float ln = max (0.0, dot (-lightVec,normal));\n diffuseColor = light.Color * ln;\n}\n\nvoid main()\n{\n vec3 diffuseColor;\n vec3 normal = normalize(v_Normal);\n vec3 viewDir = normalize(v_ViewDir);\n LayaAirBlinnPhongDiectionLight(normal, viewDir, u_DirectionLight, diffuseColor);\n \n gl_FragColor.xyz = diffuseColor * v_Color.xyz * 2.0;\n}\n\n"; var dominoShaderCompile3D=ShaderCompile3D.add(dominoShader,vs,ps,attributeMap,uniformMap); } __static(DominoMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new DominoMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return DominoMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.lineRender.LineMaterial extends laya.d3.core.material.BaseMaterial var LineMaterial=(function(_super){ function LineMaterial(){ LineMaterial.__super.call(this); this.setShaderName("LineShader"); this._setColor(2,new Vector4(1.0,1.0,1.0,1.0)); this.cull=0; } __class(LineMaterial,'laya.d3.extension.lineRender.LineMaterial',_super); var __proto=LineMaterial.prototype; /** *设置颜色。 *@param value 颜色。 */ /** *获取颜色。 *@return 颜色。 */ __getset(0,__proto,'tintColor',function(){ return this._getColor(2); },function(value){ this._setColor(2,value); }); /** *设置贴图。 *@param value 贴图。 */ /** *获取贴图。 *@return 贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_DIFFUSETEXTURE); else this._removeShaderDefine(laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_DIFFUSETEXTURE); this._setTexture(1,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(3); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(3,value); }); LineMaterial.__init__=function(){ LineMaterial.SHADERDEFINE_DIFFUSETEXTURE=LineMaterial.shaderDefines.registerDefine("DIFFUSETEXTURE"); LineMaterial.SHADERDEFINE_TILINGOFFSET=LineMaterial.shaderDefines.registerDefine("TILINGOFFSET"); } LineMaterial.load=function(url){ return Laya.loader.create(url,null,null,LineMaterial); } LineMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_OffsetVector':/*laya.d3.graphics.VertexElementUsage.OFFSETVECTOR*/41, 'a_Texcoord0X' :/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0X*/38, 'a_Texcoord0X1' :/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0X1*/39, 'a_Texcoord0Y' :/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0Y*/40 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VMatrix':[ /*laya.d3.core.BaseCamera.VIEWMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_PMatrix':[ /*laya.d3.core.BaseCamera.PROJECTMATRIX*/2,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_TilingOffset':[ /*CLASS CONST:laya.d3.extension.lineRender.LineMaterial.TILINGOFFSET*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MainTexture':[ /*CLASS CONST:laya.d3.extension.lineRender.LineMaterial.DIFFUSETEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MainColor':[ /*CLASS CONST:laya.d3.extension.lineRender.LineMaterial.TINTCOLOR*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_WidthCurve' :[ /*laya.d3.extension.lineRender.LineSprite3D.WIDTHCURVE*/3,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_WidthCurveKeyLength' :[ /*laya.d3.extension.lineRender.LineSprite3D.WIDTHCURVEKEYLENGTH*/4,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_GradientColorkey' :[ /*laya.d3.extension.lineRender.LineSprite3D.GRADIENTCOLORKEY*/5,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_GradientAlphakey' :[ /*laya.d3.extension.lineRender.LineSprite3D.GRADIENTALPHAKEY*/6,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2] }; var lineShader=Shader3D.nameKey.add("LineShader"); var vs="attribute vec3 a_Position;\nattribute vec3 a_OffsetVector;\nattribute float a_Texcoord0X;\nattribute float a_Texcoord0X1;\nattribute float a_Texcoord0Y;\n\nuniform mat4 u_MvpMatrix;\nuniform mat4 u_VMatrix;\nuniform mat4 u_PMatrix;\n\nuniform vec4 u_TilingOffset;\n\nuniform vec4 u_WidthCurve[10];\nuniform int u_WidthCurveKeyLength;\n\nuniform vec4 u_GradientColorkey[10];\nuniform vec2 u_GradientAlphakey[10];\n\nvarying vec4 v_Color;\nvarying vec2 v_Texcoord0;\n\nfloat hermiteInterpolate(float t, float outTangent, float inTangent, float duration, float value1, float value2)\n{\n float t2 = t * t;\n float t3 = t2 * t;\n float a = 2.0 * t3 - 3.0 * t2 + 1.0;\n float b = t3 - 2.0 * t2 + t;\n float c = t3 - t2;\n float d = -2.0 * t3 + 3.0 * t2;\n return a * value1 + b * outTangent * duration + c * inTangent * duration + d * value2;\n}\n\nfloat getCurWidth(in float normalizeTime)\n{\n if(normalizeTime == 0.0){\n return u_WidthCurve[0].w;\n }\n else if(normalizeTime >= 1.0){\n return u_WidthCurve[u_WidthCurveKeyLength - 1].w;\n }\n else{\n for(int i = 0; i < 10; i ++ )\n {\n if(normalizeTime == u_WidthCurve[i].x)\n {\n return u_WidthCurve[i].w;\n }\n \n vec4 lastFrame = u_WidthCurve[i];\n vec4 nextFrame = u_WidthCurve[i + 1];\n if(normalizeTime > lastFrame.x && normalizeTime < nextFrame.x)\n {\n float duration = nextFrame.x - lastFrame.x;\n float t = (normalizeTime - lastFrame.x) / duration;\n float outTangent = lastFrame.z;\n float inTangent = nextFrame.y;\n float value1 = lastFrame.w;\n float value2 = nextFrame.w;\n return hermiteInterpolate(t, outTangent, inTangent, duration, value1, value2);\n }\n } \n }\n} \n\nvec4 getColorFromGradientByBlend(in vec4 gradientColors[10], in vec2 gradientAlphas[10], in float normalizeTime)\n{\n vec4 color;\n for(int i = 1; i < 10; i++)\n {\n vec4 gradientColor = gradientColors[i];\n float colorKey = gradientColor.w;\n if(colorKey >= normalizeTime)\n {\n vec4 lastGradientColor = gradientColors[i-1];\n float lastColorKey = lastGradientColor.w;\n float age = (normalizeTime - lastColorKey) / (colorKey - lastColorKey);\n color.rgb = mix(gradientColors[i-1].xyz, gradientColor.xyz, age);\n break;\n }\n }\n for(int i = 1; i < 10; i++)\n {\n vec2 gradientAlpha = gradientAlphas[i];\n float alphaKey = gradientAlpha.y;\n if(alphaKey >= normalizeTime)\n {\n vec2 lastGradientAlpha = gradientAlphas[i-1];\n float lastAlphaKey = lastGradientAlpha.y;\n float age = (normalizeTime - lastAlphaKey) / (alphaKey - lastAlphaKey);\n color.a = mix(lastGradientAlpha.x, gradientAlpha.x, age);\n break;\n }\n }\n return color;\n}\n\nvec4 getColorFromGradientByFixed(in vec4 gradientColors[10], in vec2 gradientAlphas[10], in float normalizeTime)\n{\n vec4 color;\n for(int i = 0; i < 10; i++)\n {\n vec4 gradientColor = gradientColors[i];\n if(gradientColor.w >= normalizeTime)\n {\n color.rgb = gradientColor.xyz;\n break;\n }\n }\n for(int i = 0; i < 10; i++)\n {\n vec2 gradientAlpha = gradientAlphas[i];\n if(gradientAlpha.y >= normalizeTime)\n {\n color.a = gradientAlpha.x;\n break;\n }\n }\n return color;\n}\n\nvoid main()\n{\n #ifdef TEXTUREMODE_STRETCH\n v_Texcoord0 = vec2(a_Texcoord0X, a_Texcoord0Y);\n #else\n v_Texcoord0 = vec2(a_Texcoord0X1, a_Texcoord0Y);\n #endif\n \n #ifdef TILINGOFFSET\n v_Texcoord0 = v_Texcoord0 * u_TilingOffset.xy + u_TilingOffset.zw;\n #endif\n \n #ifdef GRADIENTMODE_BLEND\n v_Color = getColorFromGradientByBlend(u_GradientColorkey, u_GradientAlphakey, a_Texcoord0X);\n #else\n v_Color = getColorFromGradientByFixed(u_GradientColorkey, u_GradientAlphakey, a_Texcoord0X);\n #endif\n \n #ifdef WORLDSPACE\n gl_Position = u_PMatrix * u_VMatrix * vec4(a_Position + a_OffsetVector * getCurWidth(a_Texcoord0X),1.0);\n #else\n gl_Position = u_MvpMatrix * vec4(a_Position + a_OffsetVector * getCurWidth(a_Texcoord0X),1.0);\n #endif\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nuniform sampler2D u_MainTexture;\nuniform vec4 u_MainColor;\n\nvarying vec2 v_Texcoord0;\nvarying vec4 v_Color;\n\nvoid main()\n{\n vec4 color = 2.0 * u_MainColor * v_Color;\n #ifdef DIFFUSETEXTURE\n vec4 mainTextureColor = texture2D(u_MainTexture, v_Texcoord0);\n color *= mainTextureColor;\n #endif\n gl_FragColor = color;\n}\n\n"; var lineShaderCompile3D=ShaderCompile3D.add(lineShader,vs,ps,attributeMap,uniformMap); laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_DIFFUSETEXTURE=lineShaderCompile3D.registerMaterialDefine("DIFFUSETEXTURE"); laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_TILINGOFFSET=lineShaderCompile3D.registerMaterialDefine("TILINGOFFSET"); LineSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND=lineShaderCompile3D.registerSpriteDefine("GRADIENTMODE_BLEND"); LineSprite3D.SHADERDEFINE_TEXTUREMODE_STRETCH=lineShaderCompile3D.registerSpriteDefine("TEXTUREMODE_STRETCH"); LineSprite3D.SHADERDEFINE_WORLDSPACE=lineShaderCompile3D.registerSpriteDefine("WORLDSPACE"); } LineMaterial.SHADERDEFINE_DIFFUSETEXTURE=0; LineMaterial.SHADERDEFINE_TILINGOFFSET=0; LineMaterial.DIFFUSETEXTURE=1; LineMaterial.TINTCOLOR=2; LineMaterial.TILINGOFFSET=3; __static(LineMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new LineMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return LineMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.lulingmen.DissolveMaterial extends laya.d3.core.material.BaseMaterial var DissolveMaterial=(function(_super){ function DissolveMaterial(){ DissolveMaterial.__super.call(this); this.setShaderName("Dissolve"); this._setColor(9,new Vector4(1,1,1,1)); this._setNumber(7,0.0); this._setNumber(8,5.0); } __class(DissolveMaterial,'laya.d3.extension.lulingmen.DissolveMaterial',_super); var __proto=DissolveMaterial.prototype; /** *设置基础颜色。 *@param value 基础颜色。 */ /** *获取基础颜色。 *@return 基础颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(9); },function(value){ this._setColor(9,value); }); /** *设置主贴图。 *@param value 主贴图。 */ /** *获取主贴图。 *@return 主贴图。 */ __getset(0,__proto,'mainTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTEXTURE); this._setTexture(1,value); }); /** *设置溶解速率。 *@param value 溶解速率。 */ /** *获取溶解速率。 *@return 溶解速率。 */ __getset(0,__proto,'dissolveSpeed',function(){ return this._getNumber(8); },function(value){ this._setNumber(8,value); }); /** *设置主纹理平铺和偏移。 *@param value 主纹理平铺和偏移。 */ /** *获取主纹理平铺和偏移。 *@return 主纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(4); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET); } this._setColor(4,value); }); /** *设置溶解贴图。 *@param value 溶解贴图。 */ /** *获取溶解贴图。 *@return 溶解贴图。 */ __getset(0,__proto,'dissolveTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETEXTURE); this._setTexture(2,value); }); /** *设置遮罩贴图。 *@param value 遮罩贴图。 */ /** *获取遮罩贴图。 *@return 遮罩贴图。 */ __getset(0,__proto,'maskTexture',function(){ return this._getTexture(3); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTEXTURE); this._setTexture(3,value); }); /** *设置溶解纹理平铺和偏移。 *@param value 溶解纹理平铺和偏移。 */ /** *获取溶解纹理平铺和偏移。 *@return 溶解纹理平铺和偏移。 */ __getset(0,__proto,'dissolveTilingOffset',function(){ return this._getColor(5); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET); } this._setColor(5,value); }); /** *设置遮罩纹理平铺和偏移。 *@param value 遮罩纹理平铺和偏移。 */ /** *获取遮罩纹理平铺和偏移。 *@return 遮罩纹理平铺和偏移。 */ __getset(0,__proto,'maskTilingOffset',function(){ return this._getColor(6); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET); } this._setColor(6,value); }); /** *设置溶解值。 *@param value 溶解值。 */ /** *获取溶解值。 *@return 溶解值。 */ __getset(0,__proto,'dissolve',function(){ return this._getNumber(7); },function(value){ this._setNumber(7,value); }); DissolveMaterial.__init__=function(){ DissolveMaterial.SHADERDEFINE_MAINTEXTURE=DissolveMaterial.shaderDefines.registerDefine("MAINTEXTURE"); DissolveMaterial.SHADERDEFINE_DISSOLVETEXTURE=DissolveMaterial.shaderDefines.registerDefine("DISSOLVETEXTURE"); DissolveMaterial.SHADERDEFINE_MASKTEXTURE=DissolveMaterial.shaderDefines.registerDefine("MASKTEXTURE"); DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET=DissolveMaterial.shaderDefines.registerDefine("MAINTILINGOFFSET"); DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET=DissolveMaterial.shaderDefines.registerDefine("DISSOLVETILINGOFFSET"); DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET=DissolveMaterial.shaderDefines.registerDefine("MASKTILINGOFFSET"); } DissolveMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Texcoord0':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_MainTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.MAINTEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_DissolveTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.DISSOLVETEXTURE*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MaskTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.MASKTEXTURE*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseColor':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.BASECOLOR*/9,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MainTilingOffset':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.MAINTILINGOFFSET*/4,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_DissolveTilingOffset':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.DISSOLVETILINGOFFSET*/5,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MaskTilingOffset':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.MASKTILINGOFFSET*/6,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Dissolve':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.DISSOLVE*/7,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_DissolveSpeed':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.DISSOLVESPEED*/8,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1] }; var shader=Shader3D.nameKey.add("Dissolve"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\n\nuniform mat4 u_MvpMatrix;\n\nuniform vec4 u_MainTilingOffset;\nuniform vec4 u_DissolveTilingOffset;\nuniform vec4 u_MaskTilingOffset;\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec2 v_Texcoord2;\n\nvoid main()\n{\n v_Texcoord0 = a_Texcoord0;\n #ifdef MAINTILINGOFFSET\n v_Texcoord0 = (vec2(v_Texcoord0.x, v_Texcoord0.y - 1.0) * u_MainTilingOffset.xy) + u_MainTilingOffset.zw;\n v_Texcoord0 = vec2(v_Texcoord0.x, 1.0 + v_Texcoord0.y);\n #endif\n \n v_Texcoord1 = a_Texcoord0;\n #ifdef DISSOLVETILINGOFFSET\n v_Texcoord1 = (vec2(v_Texcoord1.x, v_Texcoord1.y - 1.0) * u_DissolveTilingOffset.xy) + u_DissolveTilingOffset.zw;\n v_Texcoord1 = vec2(v_Texcoord1.x, 1.0 + v_Texcoord1.y);\n #endif\n \n v_Texcoord2 = a_Texcoord0;\n \n gl_Position = u_MvpMatrix * a_Position;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec2 v_Texcoord2;\n\n#ifdef MAINTEXTURE\n uniform sampler2D u_MainTexture;\n#endif\n\n#ifdef DISSOLVETEXTURE\n uniform sampler2D u_DissolveTexture;\n#endif\n\n#ifdef MASKTEXTURE\n uniform sampler2D u_MaskTexture;\n#endif\n\nuniform vec4 u_BaseColor;\nuniform float u_Dissolve;\nuniform float u_DissolveSpeed;\n\nvoid main()\n{\n vec4 mainColor = u_BaseColor;\n mainColor.a = 1.0;\n #ifdef MAINTEXTURE\n mainColor *= texture2D(u_MainTexture, v_Texcoord0);\n #endif\n \n vec4 dissolveColor = vec4(1.0);\n #ifdef DISSOLVETEXTURE\n dissolveColor = texture2D(u_DissolveTexture, v_Texcoord1);\n #endif\n \n vec4 maskColor = vec4(1.0);\n #ifdef MASKTEXTURE\n maskColor = texture2D(u_MaskTexture, v_Texcoord2);\n #endif\n \n vec4 outColor = mix(vec4(0.0), mainColor, maskColor);\n if(dissolveColor.a <= u_Dissolve){\n float alpha = clamp(outColor.a - u_Dissolve * 2.0 + dissolveColor.a, 0.0, 1.0);\n alpha = pow(alpha, u_DissolveSpeed);\n outColor.a = alpha;\n }\n \n gl_FragColor = outColor;\n}\n"; var shaderCompile3D=ShaderCompile3D.add(shader,vs,ps,attributeMap,uniformMap); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTEXTURE=shaderCompile3D.registerMaterialDefine("MAINTEXTURE"); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETEXTURE=shaderCompile3D.registerMaterialDefine("DISSOLVETEXTURE"); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTEXTURE=shaderCompile3D.registerMaterialDefine("MASKTEXTURE"); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET=shaderCompile3D.registerMaterialDefine("MAINTILINGOFFSET"); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET=shaderCompile3D.registerMaterialDefine("DISSOLVETILINGOFFSET"); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET=shaderCompile3D.registerMaterialDefine("MASKTILINGOFFSET"); } DissolveMaterial.MAINTEXTURE=1; DissolveMaterial.DISSOLVETEXTURE=2; DissolveMaterial.MASKTEXTURE=3; DissolveMaterial.MAINTILINGOFFSET=4; DissolveMaterial.DISSOLVETILINGOFFSET=5; DissolveMaterial.MASKTILINGOFFSET=6; DissolveMaterial.DISSOLVE=7; DissolveMaterial.DISSOLVESPEED=8; DissolveMaterial.BASECOLOR=9; DissolveMaterial.SHADERDEFINE_MAINTEXTURE=0; DissolveMaterial.SHADERDEFINE_DISSOLVETEXTURE=0; DissolveMaterial.SHADERDEFINE_MASKTEXTURE=0; DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET=0; DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET=0; DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET=0; __static(DissolveMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return DissolveMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.lulingmen.MeshParticleMaterial extends laya.d3.core.material.BaseMaterial var MeshParticleMaterial=(function(_super){ function MeshParticleMaterial(){ MeshParticleMaterial.__super.call(this); this.setShaderName("MeshParticle"); this._setColor(3,new Vector4(1,1,1,1)); this._setColor(4,new Vector4(1,1,1,1)); this._setNumber(5,1.0); this._setNumber(6,1.0); } __class(MeshParticleMaterial,'laya.d3.extension.lulingmen.MeshParticleMaterial',_super); var __proto=MeshParticleMaterial.prototype; __getset(0,__proto,'alpha',function(){ return this._getNumber(6); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(6,value); }); /** *设置第一层贴图。 *@param value 第一层贴图。 */ /** *获取第一层贴图。 *@return 第一层贴图。 */ __getset(0,__proto,'mainTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE); this._setTexture(1,value); }); /** *设置第二层贴图。 *@param value 第二层贴图。 */ /** *获取第二层贴图。 *@return 第二层贴图。 */ __getset(0,__proto,'maskTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE); this._setTexture(2,value); }); /** *设置基础颜色。 *@param value 基础颜色。 */ /** *获取基础颜色。 *@return 基础颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(3); },function(value){ this._setColor(3,value); }); __getset(0,__proto,'intensity',function(){ return this._getNumber(5); },function(value){ this._setNumber(5,value); }); /** *设置透明颜色。 *@param value 透明颜色。 */ /** *获取透明颜色。 *@return 透明颜色。 */ __getset(0,__proto,'alphaColor',function(){ return this._getColor(4); },function(value){ this._setColor(4,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(7); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); else this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); } this._setColor(7,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'maskTilingOffset',function(){ return this._getColor(8); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); else this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); } this._setColor(8,value); }); MeshParticleMaterial.__init__=function(){ MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE=MeshParticleMaterial.shaderDefines.registerDefine("MAINTEXTURE"); MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE=MeshParticleMaterial.shaderDefines.registerDefine("MASKTEXTURE"); MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1=MeshParticleMaterial.shaderDefines.registerDefine("TILINGOFFSET1"); MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2=MeshParticleMaterial.shaderDefines.registerDefine("TILINGOFFSET2"); } MeshParticleMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Color':/*laya.d3.graphics.VertexElementUsage.COLOR0*/1, 'a_Texcoord0':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_MainTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.MAINTEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MaskTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.MASKTEXTURE*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseColor':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.BASECOLOR*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_AlphaColor':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.ALPHACOLOR*/4,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Instensity':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.INTENSITY*/5,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Alpha':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.ALPHA*/6,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset1':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.TILINGOFFSET1*/7,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset2':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.TILINGOFFSET2*/8,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1] }; var shader=Shader3D.nameKey.add("MeshParticle"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\nattribute vec4 a_Color;\n\nuniform mat4 u_MvpMatrix;\n\nuniform vec4 u_TilingOffset1;\nuniform vec4 u_TilingOffset2;\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec4 v_Color;\n\nvoid main()\n{\n v_Texcoord0 = a_Texcoord0;\n #ifdef TILINGOFFSET1\n v_Texcoord0 = (vec2(v_Texcoord0.x, v_Texcoord0.y - 1.0) * u_TilingOffset1.xy) + u_TilingOffset1.zw;\n v_Texcoord0 = vec2(v_Texcoord0.x, 1.0 + v_Texcoord0.y);\n #endif\n \n v_Texcoord1 = a_Texcoord0;\n #ifdef TILINGOFFSET2\n v_Texcoord1 = (vec2(v_Texcoord1.x, v_Texcoord1.y - 1.0) * u_TilingOffset2.xy) + u_TilingOffset2.zw;\n v_Texcoord1 = vec2(v_Texcoord1.x, 1.0 + v_Texcoord1.y);\n #endif\n \n v_Color = vec4(1.0);\n #ifdef COLOR\n v_Color = a_Color;\n #endif\n \n gl_Position = u_MvpMatrix * a_Position;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec4 v_Color;\n\n#ifdef MAINTEXTURE\n uniform sampler2D u_MainTexture;\n#endif\n\n#ifdef MASKTEXTURE\n uniform sampler2D u_MaskTexture;\n#endif\n\nuniform vec4 u_BaseColor;\nuniform vec4 u_AlphaColor;\nuniform float u_Instensity;\nuniform float u_Alpha;\n\nvoid main()\n{\n vec4 mainTextureColor = vec4(1.0);\n #ifdef MAINTEXTURE\n mainTextureColor = texture2D(u_MainTexture, v_Texcoord0);\n #endif\n \n vec4 maskTextureColor = vec4(1.0);\n #ifdef MASKTEXTURE\n maskTextureColor = texture2D(u_MaskTexture, v_Texcoord1);\n #endif\n \n vec4 outColor = mix(vec4(0.0), mainTextureColor, maskTextureColor);\n \n gl_FragColor = 2.0 * outColor * u_BaseColor * u_AlphaColor * u_Instensity * v_Color;\n gl_FragColor.a *= u_Alpha;\n}\n"; var shaderCompile3D=ShaderCompile3D.add(shader,vs,ps,attributeMap,uniformMap); laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE=shaderCompile3D.registerMaterialDefine("MAINTEXTURE"); laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE=shaderCompile3D.registerMaterialDefine("MASKTEXTURE"); laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1=shaderCompile3D.registerMaterialDefine("TILINGOFFSET1"); laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2=shaderCompile3D.registerMaterialDefine("TILINGOFFSET2"); } MeshParticleMaterial.MAINTEXTURE=1; MeshParticleMaterial.MASKTEXTURE=2; MeshParticleMaterial.BASECOLOR=3; MeshParticleMaterial.ALPHACOLOR=4; MeshParticleMaterial.INTENSITY=5; MeshParticleMaterial.ALPHA=6; MeshParticleMaterial.TILINGOFFSET1=7; MeshParticleMaterial.TILINGOFFSET2=8; MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE=0; MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE=0; MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1=0; MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2=0; __static(MeshParticleMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return MeshParticleMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.lulingmen.ParticleMaterial extends laya.d3.core.material.BaseMaterial var ParticleMaterial=(function(_super){ function ParticleMaterial(){ ParticleMaterial.__super.call(this); this.setShaderName("Particle"); this._setColor(3,new Vector4(1,1,1,1)); this._setColor(4,new Vector4(1,1,1,1)); this._setNumber(5,1.0); this._setNumber(6,1.0); } __class(ParticleMaterial,'laya.d3.extension.lulingmen.ParticleMaterial',_super); var __proto=ParticleMaterial.prototype; __getset(0,__proto,'alpha',function(){ return this._getNumber(6); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(6,value); }); /** *设置基础颜色。 *@param value 基础颜色。 */ /** *获取基础颜色。 *@return 基础颜色。 */ __getset(0,__proto,'tintColor',function(){ return this._getColor(3); },function(value){ this._setColor(3,value); }); /** *设置第一层贴图。 *@param value 第一层贴图。 */ /** *获取第一层贴图。 *@return 第一层贴图。 */ __getset(0,__proto,'mainTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE); else this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE); this._setTexture(1,value); }); /** *设置第二层贴图。 *@param value 第二层贴图。 */ /** *获取第二层贴图。 *@return 第二层贴图。 */ __getset(0,__proto,'maskTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE); else this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE); this._setTexture(2,value); }); __getset(0,__proto,'intensity',function(){ return this._getNumber(5); },function(value){ this._setNumber(5,value); }); /** *设置透明颜色。 *@param value 透明颜色。 */ /** *获取透明颜色。 *@return 透明颜色。 */ __getset(0,__proto,'alphaColor',function(){ return this._getColor(4); },function(value){ this._setColor(4,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(7); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); else this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); }else { this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); } this._setColor(7,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'maskTilingOffset',function(){ return this._getColor(8); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); else this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); }else { this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); } this._setColor(8,value); }); ParticleMaterial.__init__=function(){ ParticleMaterial.SHADERDEFINE_MAINTEXTURE=ParticleMaterial.shaderDefines.registerDefine("MAINTEXTURE"); ParticleMaterial.SHADERDEFINE_MASKTEXTURE=ParticleMaterial.shaderDefines.registerDefine("MASKTEXTURE"); ParticleMaterial.SHADERDEFINE_TILINGOFFSET1=ParticleMaterial.shaderDefines.registerDefine("TILINGOFFSET1"); ParticleMaterial.SHADERDEFINE_TILINGOFFSET2=ParticleMaterial.shaderDefines.registerDefine("TILINGOFFSET2"); } ParticleMaterial.initShader=function(){ var attributeMap={ 'a_CornerTextureCoordinate':/*laya.d3.graphics.VertexElementUsage.CORNERTEXTURECOORDINATE0*/17, 'a_MeshPosition':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_MeshColor':/*laya.d3.graphics.VertexElementUsage.COLOR0*/1, 'a_MeshTextureCoordinate':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2, 'a_ShapePositionStartLifeTime':/*laya.d3.graphics.VertexElementUsage.SHAPEPOSITIONSTARTLIFETIME*/30, 'a_DirectionTime':/*laya.d3.graphics.VertexElementUsage.DIRECTIONTIME*/32, 'a_StartColor':/*laya.d3.graphics.VertexElementUsage.STARTCOLOR0*/19, 'a_EndColor':/*laya.d3.graphics.VertexElementUsage.ENDCOLOR0*/23, 'a_StartSize':/*laya.d3.graphics.VertexElementUsage.STARTSIZE*/20, 'a_StartRotation0':/*laya.d3.graphics.VertexElementUsage.STARTROTATION*/22, 'a_StartSpeed':/*laya.d3.graphics.VertexElementUsage.STARTSPEED*/31, 'a_Random0':/*laya.d3.graphics.VertexElementUsage.RANDOM0*/34, 'a_Random1':/*laya.d3.graphics.VertexElementUsage.RANDOM1*/35, 'a_SimulationWorldPostion':/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDPOSTION*/36, 'a_SimulationWorldRotation':/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDROTATION*/37 }; var uniformMap={ 'u_MainTexture':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.MAINTEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MaskTexture':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.MASKTEXTURE*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseColor':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.BASECOLOR*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_AlphaColor':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.ALPHACOLOR*/4,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Instensity':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.INTENSITY*/5,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Alpha':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.ALPHA*/6,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset1':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.TILINGOFFSET1*/7,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset2':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.TILINGOFFSET2*/8,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_WorldPosition':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.WORLDPOSITION*/0,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_WorldRotation':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.WORLDROTATION*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_PositionScale':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.POSITIONSCALE*/4,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SizeScale':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIZESCALE*/5,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ScalingMode':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SCALINGMODE*/6,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_Gravity':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.GRAVITY*/7,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ThreeDStartRotation':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.THREEDSTARTROTATION*/8,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_StretchedBillboardLengthScale':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.STRETCHEDBILLBOARDLENGTHSCALE*/9,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_StretchedBillboardSpeedScale':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.STRETCHEDBILLBOARDSPEEDSCALE*/10,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SimulationSpace':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIMULATIONSPACE*/11,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_CurrentTime':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.CURRENTTIME*/12,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ColorOverLifeGradientAlphas':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS*/22,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ColorOverLifeGradientColors':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS*/23,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_MaxColorOverLifeGradientAlphas':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTALPHAS*/24,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_MaxColorOverLifeGradientColors':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTCOLORS*/25,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityConst':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONST*/13,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTX*/14,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTY*/15,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZ*/16,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityConstMax':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONSTMAX*/17,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientMaxX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTXMAX*/18,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientMaxY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTYMAX*/19,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientMaxZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZMAX*/20,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLSpaceType':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLSPACETYPE*/21,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradient':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENT*/26,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTX*/27,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTY*/28,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZ*/29,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientMax':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientMax*/30,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientMaxX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTXMAX*/31,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientMaxY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTYMAX*/32,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientMaxZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZMAX*/33,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityConst':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONST*/34,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityConstSeprarate':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTSEPRARATE*/35,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradient':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENT*/36,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTX*/37,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTY*/38,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZ*/39,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientW':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTW*/40,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityConstMax':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAX*/41,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityConstMaxSeprarate':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAXSEPRARATE*/42,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientMax':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTMAX*/43,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientMaxX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTXMAX*/44,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientMaxY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTYMAX*/45,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientMaxZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZMAX*/46,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientMaxW':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTWMAX*/47,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_TSACycles':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONCYCLES*/48,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_TSASubUVLength':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONSUBUVLENGTH*/49,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_TSAGradientUVs':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTUVS*/50,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_TSAMaxGradientUVs':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTMAXUVS*/51,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_CameraPosition':[ /*laya.d3.core.BaseCamera.CAMERAPOS*/0,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_CameraDirection':[ /*laya.d3.core.BaseCamera.CAMERADIRECTION*/5,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_CameraUp':[ /*laya.d3.core.BaseCamera.CAMERAUP*/6,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_View':[ /*laya.d3.core.BaseCamera.VIEWMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_Projection':[ /*laya.d3.core.BaseCamera.PROJECTMATRIX*/2,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_FogStart':[ /*laya.d3.core.scene.Scene.FOGSTART*/1,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], 'u_FogRange':[ /*laya.d3.core.scene.Scene.FOGRANGE*/2,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], 'u_FogColor':[ /*laya.d3.core.scene.Scene.FOGCOLOR*/0,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4] }; var PARTICLESHURIKEN=Shader3D.nameKey.add("Particle"); var vs="#ifdef HIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\n#if defined(SPHERHBILLBOARD)||defined(STRETCHEDBILLBOARD)||defined(HORIZONTALBILLBOARD)||defined(VERTICALBILLBOARD)\n attribute vec4 a_CornerTextureCoordinate;\n#endif\n#ifdef RENDERMODE_MESH\n attribute vec3 a_MeshPosition;\n attribute vec4 a_MeshColor;\n attribute vec2 a_MeshTextureCoordinate;\n varying vec4 v_MeshColor;\n#endif\n\nattribute vec4 a_ShapePositionStartLifeTime;\nattribute vec4 a_DirectionTime;\nattribute vec4 a_StartColor;\nattribute vec3 a_StartSize;\nattribute vec3 a_StartRotation0;\nattribute float a_StartSpeed;\n#if defined(COLOROVERLIFETIME)||defined(RANDOMCOLOROVERLIFETIME)||defined(SIZEOVERLIFETIMERANDOMCURVES)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\n attribute vec4 a_Random0;\n#endif\n#if defined(TEXTURESHEETANIMATIONRANDOMCURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n attribute vec4 a_Random1;\n#endif\nattribute vec3 a_SimulationWorldPostion;\nattribute vec4 a_SimulationWorldRotation;\n\nvarying float v_Discard;\nvarying vec4 v_Color;\n#ifdef MAINTEXTURE\n varying vec2 v_TextureCoordinate;\n #ifdef TILINGOFFSET1\n uniform vec4 u_TilingOffset1;\n #endif\n#endif\n\n#ifdef MASKTEXTURE\n #ifdef TILINGOFFSET2\n uniform vec4 u_TilingOffset2;\n #endif\n#endif\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\n\nuniform float u_CurrentTime;\nuniform vec3 u_Gravity;\n\nuniform vec3 u_WorldPosition;\nuniform vec4 u_WorldRotation;\nuniform bool u_ThreeDStartRotation;\nuniform int u_ScalingMode;\nuniform vec3 u_PositionScale;\nuniform vec3 u_SizeScale;\nuniform mat4 u_View;\nuniform mat4 u_Projection;\n\n#ifdef STRETCHEDBILLBOARD\n uniform vec3 u_CameraPosition;\n#endif\nuniform vec3 u_CameraDirection;//TODO:只有几种广告牌模式需要用\nuniform vec3 u_CameraUp;\n\nuniform float u_StretchedBillboardLengthScale;\nuniform float u_StretchedBillboardSpeedScale;\nuniform int u_SimulationSpace;\n\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n uniform int u_VOLSpaceType;\n#endif\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)\n uniform vec3 u_VOLVelocityConst;\n#endif\n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n uniform vec2 u_VOLVelocityGradientX[4];//x为key,y为速度\n uniform vec2 u_VOLVelocityGradientY[4];//x为key,y为速度\n uniform vec2 u_VOLVelocityGradientZ[4];//x为key,y为速度\n#endif\n#ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\n uniform vec3 u_VOLVelocityConstMax;\n#endif\n#ifdef VELOCITYOVERLIFETIMERANDOMCURVE\n uniform vec2 u_VOLVelocityGradientMaxX[4];//x为key,y为速度\n uniform vec2 u_VOLVelocityGradientMaxY[4];//x为key,y为速度\n uniform vec2 u_VOLVelocityGradientMaxZ[4];//x为key,y为速度\n#endif\n\n#ifdef COLOROVERLIFETIME\n uniform vec4 u_ColorOverLifeGradientColors[4];//x为key,yzw为Color\n uniform vec2 u_ColorOverLifeGradientAlphas[4];//x为key,y为Alpha\n#endif\n#ifdef RANDOMCOLOROVERLIFETIME\n uniform vec4 u_ColorOverLifeGradientColors[4];//x为key,yzw为Color\n uniform vec2 u_ColorOverLifeGradientAlphas[4];//x为key,y为Alpha\n uniform vec4 u_MaxColorOverLifeGradientColors[4];//x为key,yzw为Color\n uniform vec2 u_MaxColorOverLifeGradientAlphas[4];//x为key,y为Alpha\n#endif\n\n\n#if defined(SIZEOVERLIFETIMECURVE)||defined(SIZEOVERLIFETIMERANDOMCURVES)\n uniform vec2 u_SOLSizeGradient[4];//x为key,y为尺寸\n#endif\n#ifdef SIZEOVERLIFETIMERANDOMCURVES\n uniform vec2 u_SOLSizeGradientMax[4];//x为key,y为尺寸\n#endif\n#if defined(SIZEOVERLIFETIMECURVESEPERATE)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)\n uniform vec2 u_SOLSizeGradientX[4];//x为key,y为尺寸\n uniform vec2 u_SOLSizeGradientY[4];//x为key,y为尺寸\n uniform vec2 u_SOLSizeGradientZ[4];//x为key,y为尺寸\n#endif\n#ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\n uniform vec2 u_SOLSizeGradientMaxX[4];//x为key,y为尺寸\n uniform vec2 u_SOLSizeGradientMaxY[4];//x为key,y为尺寸\n uniform vec2 u_SOLSizeGradientMaxZ[4];//x为key,y为尺寸\n#endif\n\n\n#ifdef ROTATIONOVERLIFETIME\n #if defined(ROTATIONOVERLIFETIMECONSTANT)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)\n uniform float u_ROLAngularVelocityConst;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n uniform float u_ROLAngularVelocityConstMax;\n #endif\n #if defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\n uniform vec2 u_ROLAngularVelocityGradient[4];//x为key,y为旋转\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n uniform vec2 u_ROLAngularVelocityGradientMax[4];//x为key,y为旋转\n #endif\n#endif\n#ifdef ROTATIONOVERLIFETIMESEPERATE\n #if defined(ROTATIONOVERLIFETIMECONSTANT)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)\n uniform vec3 u_ROLAngularVelocityConstSeprarate;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n uniform vec3 u_ROLAngularVelocityConstMaxSeprarate;\n #endif\n #if defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\n uniform vec2 u_ROLAngularVelocityGradientX[4];\n uniform vec2 u_ROLAngularVelocityGradientY[4];\n uniform vec2 u_ROLAngularVelocityGradientZ[4];\n uniform vec2 u_ROLAngularVelocityGradientW[4];\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n uniform vec2 u_ROLAngularVelocityGradientMaxX[4];\n uniform vec2 u_ROLAngularVelocityGradientMaxY[4];\n uniform vec2 u_ROLAngularVelocityGradientMaxZ[4];\n uniform vec2 u_ROLAngularVelocityGradientMaxW[4];\n #endif\n#endif\n\n#if defined(TEXTURESHEETANIMATIONCURVE)||defined(TEXTURESHEETANIMATIONRANDOMCURVE)\n uniform float u_TSACycles;\n uniform vec2 u_TSASubUVLength;\n uniform vec2 u_TSAGradientUVs[4];//x为key,y为frame\n#endif\n#ifdef TEXTURESHEETANIMATIONRANDOMCURVE\n uniform vec2 u_TSAMaxGradientUVs[4];//x为key,y为frame\n#endif\n\n#ifdef FOG\n varying vec3 v_PositionWorld;\n#endif\n\nvec3 rotationByEuler(in vec3 vector,in vec3 rot)\n{\n float halfRoll = rot.z * 0.5;\n float halfPitch = rot.x * 0.5;\n float halfYaw = rot.y * 0.5;\n\n float sinRoll = sin(halfRoll);\n float cosRoll = cos(halfRoll);\n float sinPitch = sin(halfPitch);\n float cosPitch = cos(halfPitch);\n float sinYaw = sin(halfYaw);\n float cosYaw = cos(halfYaw);\n\n float quaX = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);\n float quaY = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);\n float quaZ = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);\n float quaW = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);\n \n //vec4 q=vec4(quaX,quaY,quaZ,quaW);\n //vec3 temp = cross(q.xyz, vector) + q.w * vector;\n //return (cross(temp, -q.xyz) + dot(q.xyz,vector) * q.xyz + q.w * temp);\n \n float x = quaX + quaX;\n float y = quaY + quaY;\n float z = quaZ + quaZ;\n float wx = quaW * x;\n float wy = quaW * y;\n float wz = quaW * z;\n float xx = quaX * x;\n float xy = quaX * y;\n float xz = quaX * z;\n float yy = quaY * y;\n float yz = quaY * z;\n float zz = quaZ * z;\n\n return vec3(((vector.x * ((1.0 - yy) - zz)) + (vector.y * (xy - wz))) + (vector.z * (xz + wy)),\n ((vector.x * (xy + wz)) + (vector.y * ((1.0 - xx) - zz))) + (vector.z * (yz - wx)),\n ((vector.x * (xz - wy)) + (vector.y * (yz + wx))) + (vector.z * ((1.0 - xx) - yy)));\n \n}\n\n//假定axis已经归一化\nvec3 rotationByAxis(in vec3 vector,in vec3 axis, in float angle)\n{\n float halfAngle = angle * 0.5;\n float sin = sin(halfAngle);\n \n float quaX = axis.x * sin;\n float quaY = axis.y * sin;\n float quaZ = axis.z * sin;\n float quaW = cos(halfAngle);\n \n //vec4 q=vec4(quaX,quaY,quaZ,quaW);\n //vec3 temp = cross(q.xyz, vector) + q.w * vector;\n //return (cross(temp, -q.xyz) + dot(q.xyz,vector) * q.xyz + q.w * temp);\n \n float x = quaX + quaX;\n float y = quaY + quaY;\n float z = quaZ + quaZ;\n float wx = quaW * x;\n float wy = quaW * y;\n float wz = quaW * z;\n float xx = quaX * x;\n float xy = quaX * y;\n float xz = quaX * z;\n float yy = quaY * y;\n float yz = quaY * z;\n float zz = quaZ * z;\n\n return vec3(((vector.x * ((1.0 - yy) - zz)) + (vector.y * (xy - wz))) + (vector.z * (xz + wy)),\n ((vector.x * (xy + wz)) + (vector.y * ((1.0 - xx) - zz))) + (vector.z * (yz - wx)),\n ((vector.x * (xz - wy)) + (vector.y * (yz + wx))) + (vector.z * ((1.0 - xx) - yy)));\n \n}\n\nvec3 rotationByQuaternions(in vec3 v,in vec4 q) \n{\n return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);\n}\n\n \n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)||defined(SIZEOVERLIFETIMECURVE)||defined(SIZEOVERLIFETIMECURVESEPERATE)||defined(SIZEOVERLIFETIMERANDOMCURVES)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)\nfloat getCurValueFromGradientFloat(in vec2 gradientNumbers[4],in float normalizedAge)\n{\n float curValue;\n for(int i=1;i<4;i++)\n {\n vec2 gradientNumber=gradientNumbers[i];\n float key=gradientNumber.x;\n if(key>=normalizedAge)\n {\n vec2 lastGradientNumber=gradientNumbers[i-1];\n float lastKey=lastGradientNumber.x;\n float age=(normalizedAge-lastKey)/(key-lastKey);\n curValue=mix(lastGradientNumber.y,gradientNumber.y,age);\n break;\n }\n }\n return curValue;\n}\n#endif\n\n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)||defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\nfloat getTotalValueFromGradientFloat(in vec2 gradientNumbers[4],in float normalizedAge)\n{\n float totalValue=0.0;\n for(int i=1;i<4;i++)\n {\n vec2 gradientNumber=gradientNumbers[i];\n float key=gradientNumber.x;\n vec2 lastGradientNumber=gradientNumbers[i-1];\n float lastValue=lastGradientNumber.y;\n \n if(key>=normalizedAge){\n float lastKey=lastGradientNumber.x;\n float age=(normalizedAge-lastKey)/(key-lastKey);\n totalValue+=(lastValue+mix(lastValue,gradientNumber.y,age))/2.0*a_ShapePositionStartLifeTime.w*(normalizedAge-lastKey);\n break;\n }\n else{\n totalValue+=(lastValue+gradientNumber.y)/2.0*a_ShapePositionStartLifeTime.w*(key-lastGradientNumber.x);\n }\n }\n return totalValue;\n}\n#endif\n\n#if defined(COLOROVERLIFETIME)||defined(RANDOMCOLOROVERLIFETIME)\nvec4 getColorFromGradient(in vec2 gradientAlphas[4],in vec4 gradientColors[4],in float normalizedAge)\n{\n vec4 overTimeColor;\n for(int i=1;i<4;i++)\n {\n vec2 gradientAlpha=gradientAlphas[i];\n float alphaKey=gradientAlpha.x;\n if(alphaKey>=normalizedAge)\n {\n vec2 lastGradientAlpha=gradientAlphas[i-1];\n float lastAlphaKey=lastGradientAlpha.x;\n float age=(normalizedAge-lastAlphaKey)/(alphaKey-lastAlphaKey);\n overTimeColor.a=mix(lastGradientAlpha.y,gradientAlpha.y,age);\n break;\n }\n }\n \n for(int i=1;i<4;i++)\n {\n vec4 gradientColor=gradientColors[i];\n float colorKey=gradientColor.x;\n if(colorKey>=normalizedAge)\n {\n vec4 lastGradientColor=gradientColors[i-1];\n float lastColorKey=lastGradientColor.x;\n float age=(normalizedAge-lastColorKey)/(colorKey-lastColorKey);\n overTimeColor.rgb=mix(gradientColors[i-1].yzw,gradientColor.yzw,age);\n break;\n }\n }\n return overTimeColor;\n}\n#endif\n\n\n#if defined(TEXTURESHEETANIMATIONCURVE)||defined(TEXTURESHEETANIMATIONRANDOMCURVE)\nfloat getFrameFromGradient(in vec2 gradientFrames[4],in float normalizedAge)\n{\n float overTimeFrame;\n for(int i=1;i<4;i++)\n {\n vec2 gradientFrame=gradientFrames[i];\n float key=gradientFrame.x;\n if(key>=normalizedAge)\n {\n vec2 lastGradientFrame=gradientFrames[i-1];\n float lastKey=lastGradientFrame.x;\n float age=(normalizedAge-lastKey)/(key-lastKey);\n overTimeFrame=mix(lastGradientFrame.y,gradientFrame.y,age);\n break;\n }\n }\n return floor(overTimeFrame);\n}\n#endif\n\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\nvec3 computeParticleLifeVelocity(in float normalizedAge)\n{\n vec3 outLifeVelocity;\n #ifdef VELOCITYOVERLIFETIMECONSTANT\n outLifeVelocity=u_VOLVelocityConst; \n #endif\n #ifdef VELOCITYOVERLIFETIMECURVE\n outLifeVelocity= vec3(getCurValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge));\n #endif\n #ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\n outLifeVelocity=mix(u_VOLVelocityConst,u_VOLVelocityConstMax,vec3(a_Random1.y,a_Random1.z,a_Random1.w)); \n #endif\n #ifdef VELOCITYOVERLIFETIMERANDOMCURVE\n outLifeVelocity=vec3(mix(getCurValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxX,normalizedAge),a_Random1.y),\n mix(getCurValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxY,normalizedAge),a_Random1.z),\n mix(getCurValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxZ,normalizedAge),a_Random1.w));\n #endif\n \n return outLifeVelocity;\n} \n#endif\n\nvec3 computeParticlePosition(in vec3 startVelocity, in vec3 lifeVelocity,in float age,in float normalizedAge,vec3 gravityVelocity,vec4 worldRotation)\n{\n vec3 startPosition;\n vec3 lifePosition;\n #if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n #ifdef VELOCITYOVERLIFETIMECONSTANT\n startPosition=startVelocity*age;\n lifePosition=lifeVelocity*age;\n #endif\n #ifdef VELOCITYOVERLIFETIMECURVE\n startPosition=startVelocity*age;\n lifePosition=vec3(getTotalValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge));\n #endif\n #ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\n startPosition=startVelocity*age;\n lifePosition=lifeVelocity*age;\n #endif\n #ifdef VELOCITYOVERLIFETIMERANDOMCURVE\n startPosition=startVelocity*age;\n lifePosition=vec3(mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxX,normalizedAge),a_Random1.y)\n ,mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxY,normalizedAge),a_Random1.z)\n ,mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxZ,normalizedAge),a_Random1.w));\n #endif\n \n vec3 finalPosition;\n if(u_VOLSpaceType==0){\n if(u_ScalingMode!=2)\n finalPosition =rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition+lifePosition),worldRotation);\n else\n finalPosition =rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition+lifePosition,worldRotation);\n }\n else{\n if(u_ScalingMode!=2)\n finalPosition = rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition),worldRotation)+lifePosition;\n else\n finalPosition = rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition,worldRotation)+lifePosition;\n }\n #else\n startPosition=startVelocity*age;\n vec3 finalPosition;\n if(u_ScalingMode!=2)\n finalPosition = rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition),worldRotation);\n else\n finalPosition = rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition,worldRotation);\n #endif\n \n if(u_SimulationSpace==0)\n finalPosition=finalPosition+a_SimulationWorldPostion;\n else if(u_SimulationSpace==1) \n finalPosition=finalPosition+u_WorldPosition;\n \n finalPosition+=0.5*gravityVelocity*age;\n \n return finalPosition;\n}\n\n\nvec4 computeParticleColor(in vec4 color,in float normalizedAge)\n{\n #ifdef COLOROVERLIFETIME\n color*=getColorFromGradient(u_ColorOverLifeGradientAlphas,u_ColorOverLifeGradientColors,normalizedAge);\n #endif\n \n #ifdef RANDOMCOLOROVERLIFETIME\n color*=mix(getColorFromGradient(u_ColorOverLifeGradientAlphas,u_ColorOverLifeGradientColors,normalizedAge),getColorFromGradient(u_MaxColorOverLifeGradientAlphas,u_MaxColorOverLifeGradientColors,normalizedAge),a_Random0.y);\n #endif\n\n return color;\n}\n\nvec2 computeParticleSizeBillbard(in vec2 size,in float normalizedAge)\n{\n #ifdef SIZEOVERLIFETIMECURVE\n size*=getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge);\n #endif\n #ifdef SIZEOVERLIFETIMERANDOMCURVES\n size*=mix(getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMax,normalizedAge),a_Random0.z); \n #endif\n #ifdef SIZEOVERLIFETIMECURVESEPERATE\n size*=vec2(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge));\n #endif\n #ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\n size*=vec2(mix(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxX,normalizedAge),a_Random0.z)\n ,mix(getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxY,normalizedAge),a_Random0.z));\n #endif\n return size;\n}\n\n#ifdef RENDERMODE_MESH\nvec3 computeParticleSizeMesh(in vec3 size,in float normalizedAge)\n{\n #ifdef SIZEOVERLIFETIMECURVE\n size*=getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge);\n #endif\n #ifdef SIZEOVERLIFETIMERANDOMCURVES\n size*=mix(getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMax,normalizedAge),a_Random0.z); \n #endif\n #ifdef SIZEOVERLIFETIMECURVESEPERATE\n size*=vec3(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientZ,normalizedAge));\n #endif\n #ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\n size*=vec3(mix(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxX,normalizedAge),a_Random0.z)\n ,mix(getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxY,normalizedAge),a_Random0.z)\n ,mix(getCurValueFromGradientFloat(u_SOLSizeGradientZ,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxZ,normalizedAge),a_Random0.z));\n #endif\n return size;\n}\n#endif\n\nfloat computeParticleRotationFloat(in float rotation,in float age,in float normalizedAge)\n{ \n #ifdef ROTATIONOVERLIFETIME\n #ifdef ROTATIONOVERLIFETIMECONSTANT\n float ageRot=u_ROLAngularVelocityConst*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMECURVE\n rotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge);\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n float ageRot=mix(u_ROLAngularVelocityConst,u_ROLAngularVelocityConstMax,a_Random0.w)*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n rotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMax,normalizedAge),a_Random0.w);\n #endif\n #endif\n #ifdef ROTATIONOVERLIFETIMESEPERATE\n #ifdef ROTATIONOVERLIFETIMECONSTANT\n float ageRot=u_ROLAngularVelocityConstSeprarate.z*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMECURVE\n rotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge);\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n float ageRot=mix(u_ROLAngularVelocityConstSeprarate.z,u_ROLAngularVelocityConstMaxSeprarate.z,a_Random0.w)*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n rotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxZ,normalizedAge),a_Random0.w));\n #endif\n #endif\n return rotation;\n}\n\n\n#if defined(RENDERMODE_MESH)&&(defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE))\nvec3 computeParticleRotationVec3(in vec3 rotation,in float age,in float normalizedAge)\n{ \n #ifdef ROTATIONOVERLIFETIME\n #ifdef ROTATIONOVERLIFETIMECONSTANT\n float ageRot=u_ROLAngularVelocityConst*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMECURVE\n rotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge);\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n float ageRot=mix(u_ROLAngularVelocityConst,u_ROLAngularVelocityConstMax,a_Random0.w)*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n rotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMax,normalizedAge),a_Random0.w);\n #endif\n #endif\n #ifdef ROTATIONOVERLIFETIMESEPERATE\n #ifdef ROTATIONOVERLIFETIMECONSTANT\n vec3 ageRot=u_ROLAngularVelocityConstSeprarate*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMECURVE\n rotation+=vec3(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge));\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n vec3 ageRot=mix(u_ROLAngularVelocityConstSeprarate,u_ROLAngularVelocityConstMaxSeprarate,a_Random0.w)*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n rotation+=vec3(mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxX,normalizedAge),a_Random0.w)\n ,mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxY,normalizedAge),a_Random0.w)\n ,mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxZ,normalizedAge),a_Random0.w));\n #endif\n #endif\n return rotation;\n}\n#endif\n\nvec2 computeParticleUV(in vec2 uv,in float normalizedAge)\n{ \n #ifdef TEXTURESHEETANIMATIONCURVE\n float cycleNormalizedAge=normalizedAge*u_TSACycles;\n float frame=getFrameFromGradient(u_TSAGradientUVs,cycleNormalizedAge-floor(cycleNormalizedAge));\n float totalULength=frame*u_TSASubUVLength.x;\n float floorTotalULength=floor(totalULength);\n uv.x+=totalULength-floorTotalULength;\n uv.y+=floorTotalULength*u_TSASubUVLength.y;\n #endif\n #ifdef TEXTURESHEETANIMATIONRANDOMCURVE\n float cycleNormalizedAge=normalizedAge*u_TSACycles;\n float uvNormalizedAge=cycleNormalizedAge-floor(cycleNormalizedAge);\n float frame=floor(mix(getFrameFromGradient(u_TSAGradientUVs,uvNormalizedAge),getFrameFromGradient(u_TSAMaxGradientUVs,uvNormalizedAge),a_Random1.x));\n float totalULength=frame*u_TSASubUVLength.x;\n float floorTotalULength=floor(totalULength);\n uv.x+=totalULength-floorTotalULength;\n uv.y+=floorTotalULength*u_TSASubUVLength.y;\n #endif\n return uv;\n}\n\nvoid main()\n{\n float age = u_CurrentTime - a_DirectionTime.w;\n float normalizedAge = age/a_ShapePositionStartLifeTime.w;\n vec3 lifeVelocity;\n if(normalizedAge<1.0){ \n vec3 startVelocity=a_DirectionTime.xyz*a_StartSpeed;\n #if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n lifeVelocity= computeParticleLifeVelocity(normalizedAge);//计算粒子生命周期速度\n #endif \n vec3 gravityVelocity=u_Gravity*age;\n \n vec4 worldRotation;\n if(u_SimulationSpace==0)\n worldRotation=a_SimulationWorldRotation;\n else\n worldRotation=u_WorldRotation;\n \n vec3 center=computeParticlePosition(startVelocity, lifeVelocity, age, normalizedAge,gravityVelocity,worldRotation);//计算粒子位置\n \n \n #ifdef SPHERHBILLBOARD\n vec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\n vec3 cameraUpVector =normalize(u_CameraUp);//TODO:是否外面归一化\n vec3 sideVector = normalize(cross(u_CameraDirection,cameraUpVector));\n vec3 upVector = normalize(cross(sideVector,u_CameraDirection));\n corner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\n #if defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE)\n if(u_ThreeDStartRotation){\n vec3 rotation=vec3(a_StartRotation0.xy,computeParticleRotationFloat(a_StartRotation0.z,age,normalizedAge));\n center += u_SizeScale.xzy*rotationByEuler(corner.x*sideVector+corner.y*upVector,rotation);\n }\n else{\n float rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\n float c = cos(rot);\n float s = sin(rot);\n mat2 rotation= mat2(c, -s, s, c);\n corner=rotation*corner;\n center += u_SizeScale.xzy*(corner.x*sideVector+corner.y*upVector);\n }\n #else\n if(u_ThreeDStartRotation){\n center += u_SizeScale.xzy*rotationByEuler(corner.x*sideVector+corner.y*upVector,a_StartRotation0);\n }\n else{\n float c = cos(a_StartRotation0.x);\n float s = sin(a_StartRotation0.x);\n mat2 rotation= mat2(c, -s, s, c);\n corner=rotation*corner;\n center += u_SizeScale.xzy*(corner.x*sideVector+corner.y*upVector);\n }\n #endif\n #endif\n \n #ifdef STRETCHEDBILLBOARD\n vec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\n vec3 velocity;\n #if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n if(u_VOLSpaceType==0)\n velocity=rotationByQuaternions(u_SizeScale*(startVelocity+lifeVelocity),worldRotation)+gravityVelocity;\n else\n velocity=rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+lifeVelocity+gravityVelocity;\n #else\n velocity= rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+gravityVelocity;\n #endif \n vec3 cameraUpVector = normalize(velocity);\n vec3 direction = normalize(center-u_CameraPosition);\n vec3 sideVector = normalize(cross(direction,normalize(velocity)));\n \n sideVector=u_SizeScale.xzy*sideVector;\n cameraUpVector=length(vec3(u_SizeScale.x,0.0,0.0))*cameraUpVector;\n \n vec2 size=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\n \n const mat2 rotaionZHalfPI=mat2(0.0, -1.0, 1.0, 0.0);\n corner=rotaionZHalfPI*corner;\n corner.y=corner.y-abs(corner.y);\n \n float speed=length(velocity);//TODO:\n center +=sign(u_SizeScale.x)*(sign(u_StretchedBillboardLengthScale)*size.x*corner.x*sideVector+(speed*u_StretchedBillboardSpeedScale+size.y*u_StretchedBillboardLengthScale)*corner.y*cameraUpVector);\n #endif\n \n #ifdef HORIZONTALBILLBOARD\n vec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\n const vec3 cameraUpVector=vec3(0.0,0.0,1.0);\n const vec3 sideVector = vec3(-1.0,0.0,0.0);\n \n float rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\n float c = cos(rot);\n float s = sin(rot);\n mat2 rotation= mat2(c, -s, s, c);\n corner=rotation*corner*cos(0.78539816339744830961566084581988);//TODO:临时缩小cos45,不确定U3D原因\n corner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\n center +=u_SizeScale.xzy*(corner.x*sideVector+ corner.y*cameraUpVector);\n #endif\n \n #ifdef VERTICALBILLBOARD\n vec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\n const vec3 cameraUpVector =vec3(0.0,1.0,0.0);\n vec3 sideVector = normalize(cross(u_CameraDirection,cameraUpVector));\n \n float rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\n float c = cos(rot);\n float s = sin(rot);\n mat2 rotation= mat2(c, -s, s, c);\n corner=rotation*corner*cos(0.78539816339744830961566084581988);//TODO:临时缩小cos45,不确定U3D原因\n corner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\n center +=u_SizeScale.xzy*(corner.x*sideVector+ corner.y*cameraUpVector);\n #endif\n \n #ifdef RENDERMODE_MESH\n vec3 size=computeParticleSizeMesh(a_StartSize,normalizedAge);\n #if defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE)\n if(u_ThreeDStartRotation){\n vec3 rotation=vec3(a_StartRotation0.xy,-computeParticleRotationFloat(a_StartRotation0.z, age,normalizedAge));\n center+= rotationByQuaternions(u_SizeScale*rotationByEuler(a_MeshPosition*size,rotation),worldRotation);\n }\n else{\n #ifdef ROTATIONOVERLIFETIME\n float angle=computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\n if(a_ShapePositionStartLifeTime.x!=0.0||a_ShapePositionStartLifeTime.y!=0.0){\n center+= (rotationByQuaternions(rotationByAxis(u_SizeScale*a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),angle),worldRotation));//已验证\n }\n else{\n #ifdef SHAPE\n center+= u_SizeScale.xzy*(rotationByQuaternions(rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),angle),worldRotation));\n #else\n if(u_SimulationSpace==0)\n center+=rotationByAxis(u_SizeScale*a_MeshPosition*size,vec3(0.0,0.0,-1.0),angle);//已验证\n else if(u_SimulationSpace==1)\n center+=rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,0.0,-1.0),angle),worldRotation);//已验证\n #endif\n }\n #endif\n #ifdef ROTATIONOVERLIFETIMESEPERATE\n //TODO:是否应合并if(u_ThreeDStartRotation)分支代码,待测试\n vec3 angle=computeParticleRotationVec3(vec3(0.0,0.0,a_StartRotation0.z), age,normalizedAge);\n center+= (rotationByQuaternions(rotationByEuler(u_SizeScale*a_MeshPosition*size,vec3(angle.x,angle.y,angle.z)),worldRotation));//已验证\n #endif \n }\n #else\n if(u_ThreeDStartRotation){\n center+= rotationByQuaternions(u_SizeScale*rotationByEuler(a_MeshPosition*size,a_StartRotation0),worldRotation);//已验证\n }\n else{\n if(a_ShapePositionStartLifeTime.x!=0.0||a_ShapePositionStartLifeTime.y!=0.0){\n if(u_SimulationSpace==0)\n center+= rotationByAxis(u_SizeScale*a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),a_StartRotation0.x);\n else if(u_SimulationSpace==1)\n center+= (rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),a_StartRotation0.x),worldRotation));//已验证\n }\n else{\n #ifdef SHAPE\n if(u_SimulationSpace==0)\n center+= u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),a_StartRotation0.x);\n else if(u_SimulationSpace==1)\n center+= rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),a_StartRotation0.x),worldRotation); \n #else\n if(u_SimulationSpace==0)\n center+= rotationByAxis(u_SizeScale*a_MeshPosition*size,vec3(0.0,0.0,-1.0),a_StartRotation0.x);\n else if(u_SimulationSpace==1)\n center+= rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,0.0,-1.0),a_StartRotation0.x),worldRotation);//已验证\n #endif\n }\n }\n #endif\n v_MeshColor=a_MeshColor;\n #endif\n \n gl_Position=u_Projection*u_View*vec4(center,1.0);\n v_Color = computeParticleColor(a_StartColor, normalizedAge);\n #ifdef MAINTEXTURE\n #if defined(SPHERHBILLBOARD)||defined(STRETCHEDBILLBOARD)||defined(HORIZONTALBILLBOARD)||defined(VERTICALBILLBOARD)\n v_TextureCoordinate =computeParticleUV(a_CornerTextureCoordinate.zw, normalizedAge);\n #endif\n #ifdef RENDERMODE_MESH\n v_TextureCoordinate =computeParticleUV(a_MeshTextureCoordinate, normalizedAge);\n #endif\n \n v_Texcoord0 = v_TextureCoordinate;\n #ifdef TILINGOFFSET1 \n v_Texcoord0=vec2(v_TextureCoordinate.x,1.0-v_TextureCoordinate.y)*u_TilingOffset1.xy+vec2(u_TilingOffset1.z,-u_TilingOffset1.w);//需要特殊处理\n v_Texcoord0=vec2(v_TextureCoordinate.x,1.0-v_TextureCoordinate.y);//需要特殊处理\n #endif\n \n v_Texcoord1 = v_TextureCoordinate;\n #ifdef TILINGOFFSET2 \n v_Texcoord1=vec2(v_TextureCoordinate.x,1.0-v_TextureCoordinate.y)*u_TilingOffset2.xy+vec2(u_TilingOffset2.z,-u_TilingOffset2.w);//需要特殊处理\n v_Texcoord1=vec2(v_TextureCoordinate.x,1.0-v_TextureCoordinate.y);//需要特殊处理\n #endif\n \n #endif\n v_Discard=0.0;\n \n #ifdef FOG\n v_PositionWorld=center;\n #endif\n }\n else\n {\n v_Discard=1.0;\n }\n}\n\n"; var ps="#ifdef HIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nvarying float v_Discard;\nvarying vec4 v_Color;\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\n\nuniform vec4 u_BaseColor;\nuniform vec4 u_AlphaColor;\nuniform float u_Instensity;\nuniform float u_Alpha;\n\n#ifdef MAINTEXTURE\n uniform sampler2D u_MainTexture;\n#endif\n\n#ifdef MASKTEXTURE\n uniform sampler2D u_MaskTexture;\n#endif\n\n#ifdef RENDERMODE_MESH\n varying vec4 v_MeshColor;\n#endif\n\n#ifdef FOG\n varying vec3 v_PositionWorld;\n uniform vec3 u_CameraPosition;\n uniform float u_FogStart;\n uniform float u_FogRange;\n #ifdef ADDTIVEFOG\n #else\n uniform vec3 u_FogColor;\n #endif\n#endif\n\n\nvoid main()\n{ \n #ifdef RENDERMODE_MESH\n gl_FragColor=v_MeshColor;\n #else\n gl_FragColor=vec4(1.0); \n #endif\n \n vec4 mainTextureColor = vec4(1.0);\n #ifdef MAINTEXTURE\n mainTextureColor = texture2D(u_MainTexture, v_Texcoord0);\n #endif\n \n vec4 maskTextureColor = vec4(1.0);\n #ifdef MASKTEXTURE\n maskTextureColor = texture2D(u_MaskTexture, v_Texcoord1);\n #endif\n \n vec4 outColor = mix(vec4(0.0), mainTextureColor, maskTextureColor);\n \n gl_FragColor *= 2.0 * outColor * u_BaseColor * u_AlphaColor * v_Color * u_Instensity;\n gl_FragColor.a *= u_Alpha;\n \n #ifdef FOG\n vec3 toEye=u_CameraPosition-v_PositionWorld;\n float toEyeLength=length(toEye);\n toEye/=toEyeLength;\n \n float lerpFact=clamp((toEyeLength-u_FogStart)/u_FogRange,0.0,1.0);\n #ifdef ADDTIVEFOG\n gl_FragColor.rgb=mix(gl_FragColor.rgb,vec3(0.0,0.0,0.0),lerpFact);\n #else\n gl_FragColor.rgb=mix(gl_FragColor.rgb,u_FogColor,lerpFact);\n #endif\n #endif\n}"; var shaderCompile=ShaderCompile3D.add(PARTICLESHURIKEN,vs,ps,attributeMap,uniformMap); MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE=shaderCompile.registerMaterialDefine("MAINTEXTURE"); MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE=shaderCompile.registerMaterialDefine("MASKTEXTURE"); MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1=shaderCompile.registerMaterialDefine("TILINGOFFSET1"); MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2=shaderCompile.registerMaterialDefine("TILINGOFFSET2"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_BILLBOARD=shaderCompile.registerSpriteDefine("SPHERHBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD=shaderCompile.registerSpriteDefine("STRETCHEDBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD=shaderCompile.registerSpriteDefine("HORIZONTALBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD=shaderCompile.registerSpriteDefine("VERTICALBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME=shaderCompile.registerSpriteDefine("COLOROVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME=shaderCompile.registerSpriteDefine("RANDOMCOLOROVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT=shaderCompile.registerSpriteDefine("VELOCITYOVERLIFETIMECONSTANT"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE=shaderCompile.registerSpriteDefine("VELOCITYOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT=shaderCompile.registerSpriteDefine("VELOCITYOVERLIFETIMERANDOMCONSTANT"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE=shaderCompile.registerSpriteDefine("VELOCITYOVERLIFETIMERANDOMCURVE"); ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE=shaderCompile.registerSpriteDefine("TEXTURESHEETANIMATIONCURVE"); ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE=shaderCompile.registerSpriteDefine("TEXTURESHEETANIMATIONRANDOMCURVE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIMESEPERATE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIMECONSTANT"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIMERANDOMCONSTANTS"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIMERANDOMCURVES"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE=shaderCompile.registerSpriteDefine("SIZEOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE=shaderCompile.registerSpriteDefine("SIZEOVERLIFETIMECURVESEPERATE"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES=shaderCompile.registerSpriteDefine("SIZEOVERLIFETIMERANDOMCURVES"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE=shaderCompile.registerSpriteDefine("SIZEOVERLIFETIMERANDOMCURVESSEPERATE"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_MESH=shaderCompile.registerSpriteDefine("RENDERMODE_MESH"); ShuriKenParticle3D.SHADERDEFINE_SHAPE=shaderCompile.registerSpriteDefine("SHAPE"); } ParticleMaterial.MAINTEXTURE=1; ParticleMaterial.MASKTEXTURE=2; ParticleMaterial.BASECOLOR=3; ParticleMaterial.ALPHACOLOR=4; ParticleMaterial.INTENSITY=5; ParticleMaterial.ALPHA=6; ParticleMaterial.TILINGOFFSET1=7; ParticleMaterial.TILINGOFFSET2=8; ParticleMaterial.SHADERDEFINE_MAINTEXTURE=0; ParticleMaterial.SHADERDEFINE_MASKTEXTURE=0; ParticleMaterial.SHADERDEFINE_TILINGOFFSET1=0; ParticleMaterial.SHADERDEFINE_TILINGOFFSET2=0; __static(ParticleMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return ParticleMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.lulingmen.UVSineMaterial extends laya.d3.core.material.BaseMaterial var UVSineMaterial=(function(_super){ function UVSineMaterial(){ UVSineMaterial.__super.call(this); this.setShaderName("UVSine"); this._setColor(3,new Vector4(1,1,1,1)); this._setNumber(4,0.0); this._setNumber(5,0.0); this._setNumber(6,0.0); this._setNumber(7,0.0); this._setNumber(8,1.0); this._setNumber(9,1.0); } __class(UVSineMaterial,'laya.d3.extension.lulingmen.UVSineMaterial',_super); var __proto=UVSineMaterial.prototype; __getset(0,__proto,'alpha',function(){ return this._getNumber(9); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(9,value); }); /** *设置第一层贴图。 *@param value 第一层贴图。 */ /** *获取第一层贴图。 *@return 第一层贴图。 */ __getset(0,__proto,'baseTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_BASETEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_BASETEXTURE); this._setTexture(1,value); }); /** *设置第一层滚动速度X。 *@param value 第一层滚动速度X。 */ /** *获取第一层滚动速度X。 *@return 第一层滚动速度X。 */ __getset(0,__proto,'baseScrollSpeedX',function(){ return this._getNumber(4); },function(value){ this._setNumber(4,value); }); /** *设置第二层贴图。 *@param value 第二层贴图。 */ /** *获取第二层贴图。 *@return 第二层贴图。 */ __getset(0,__proto,'secondTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_SECONDTEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_SECONDTEXTURE); this._setTexture(2,value); }); __getset(0,__proto,'mMultiplier',function(){ return this._getNumber(8); },function(value){ this._setNumber(8,value); }); /** *设置第一层滚动速度Y。 *@param value 第一层滚动速度Y。 */ /** *获取第一层滚动速度Y。 *@return 第一层滚动速度Y。 */ __getset(0,__proto,'baseScrollSpeedY',function(){ return this._getNumber(5); },function(value){ this._setNumber(5,value); }); /** *设置基础颜色。 *@param value 基础颜色。 */ /** *获取基础颜色。 *@return 基础颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(3); },function(value){ this._setColor(3,value); }); /** *设置第二层滚动速度X。 *@param value 第二层滚动速度X。 */ /** *获取第二层滚动速度X。 *@return 第二层滚动速度X。 */ __getset(0,__proto,'secondScrollSpeedX',function(){ return this._getNumber(6); },function(value){ this._setNumber(6,value); }); /** *设置第二层滚动速度Y。 *@param value 第二层滚动速度Y。 */ /** *获取第二层滚动速度Y。 *@return 第二层滚动速度Y。 */ __getset(0,__proto,'secondScrollSpeedY',function(){ return this._getNumber(7); },function(value){ this._setNumber(7,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(10); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET1); else this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET1); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET1); } this._setColor(10,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'detailTilingOffset',function(){ return this._getColor(11); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET2); else this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET2); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET2); } this._setColor(11,value); }); UVSineMaterial.__init__=function(){ UVSineMaterial.SHADERDEFINE_BASETEXTURE=UVSineMaterial.shaderDefines.registerDefine("BASETEXTURE"); UVSineMaterial.SHADERDEFINE_SECONDTEXTURE=UVSineMaterial.shaderDefines.registerDefine("SECONDTEXTURE"); UVSineMaterial.SHADERDEFINE_TILINGOFFSET1=UVSineMaterial.shaderDefines.registerDefine("TILINGOFFSET1"); UVSineMaterial.SHADERDEFINE_TILINGOFFSET2=UVSineMaterial.shaderDefines.registerDefine("TILINGOFFSET2"); } UVSineMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Color':/*laya.d3.graphics.VertexElementUsage.COLOR0*/1, 'a_Texcoord0':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_Time':[ /*laya.d3.core.scene.Scene.TIME*/22,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], 'u_BaseTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.BASETEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SecondTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.SECONDTEXTURE*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseColor':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.BASECOLOR*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseScrollSpeedX':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.BASESCROLLSPEEDX*/4,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseScrollSpeedY':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.BASESCROLLSPEEDY*/5,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SecondScrollSpeedX':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.SECONDSCROLLSPEEDX*/6,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SecondScrollSpeedY':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.SECONDSCROLLSPEEDY*/7,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MMultiplier':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.MMULTIPLIER*/8,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Alpha':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.ALPHA*/9,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset1':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.TILINGOFFSET1*/10,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset2':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.TILINGOFFSET2*/11,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1] }; var shader=Shader3D.nameKey.add("UVSine"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\nattribute vec4 a_Color;\n\nuniform mat4 u_MvpMatrix;\nuniform float u_Time;\nuniform float u_BaseScrollSpeedX;\nuniform float u_BaseScrollSpeedY;\nuniform float u_SecondScrollSpeedX;\nuniform float u_SecondScrollSpeedY;\n\nuniform vec4 u_TilingOffset1;\nuniform vec4 u_TilingOffset2;\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec4 v_Color;\n\nvoid main()\n{\n v_Texcoord0 = a_Texcoord0;\n #ifdef TILINGOFFSET1\n v_Texcoord0 = (vec2(v_Texcoord0.x, v_Texcoord0.y - 1.0) * u_TilingOffset1.xy) + u_TilingOffset1.zw;\n v_Texcoord0 = vec2(v_Texcoord0.x, 1.0 + v_Texcoord0.y);\n #endif\n \n v_Texcoord1 = a_Texcoord0;\n #ifdef TILINGOFFSET2\n v_Texcoord1 = (vec2(v_Texcoord1.x, v_Texcoord1.y - 1.0) * u_TilingOffset2.xy) + u_TilingOffset2.zw;\n v_Texcoord1 = vec2(v_Texcoord1.x, 1.0 + v_Texcoord1.y);\n #endif\n \n v_Texcoord0 = v_Texcoord0 + vec2(fract(u_BaseScrollSpeedX * u_Time / 20.0), fract(-u_BaseScrollSpeedY * u_Time));\n v_Texcoord1 = v_Texcoord1 + vec2(fract(u_SecondScrollSpeedX * u_Time / 20.0), fract(-u_SecondScrollSpeedY * u_Time));\n \n v_Color = vec4(1.0);\n #ifdef COLOR\n v_Color = a_Color;\n #endif\n \n gl_Position = u_MvpMatrix * a_Position;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec4 v_Color;\n\n#ifdef BASETEXTURE\n uniform sampler2D u_BaseTexture;\n#endif\n\n#ifdef SECONDTEXTURE\n uniform sampler2D u_SecondTexture;\n#endif\n\nuniform vec4 u_BaseColor;\nuniform float u_MMultiplier;\nuniform float u_Alpha;\n\nvoid main()\n{\n vec4 baseTextureColor = vec4(1.0);\n #ifdef BASETEXTURE\n baseTextureColor = texture2D(u_BaseTexture, v_Texcoord0);\n #endif\n \n vec4 secondTextureColor = vec4(1.0);\n #ifdef SECONDTEXTURE\n secondTextureColor = texture2D(u_SecondTexture, v_Texcoord1);\n #endif\n \n gl_FragColor = baseTextureColor * secondTextureColor * u_BaseColor * u_MMultiplier * v_Color;\n gl_FragColor.a *= u_Alpha;\n}\n"; var shaderCompile3D=ShaderCompile3D.add(shader,vs,ps,attributeMap,uniformMap); laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_BASETEXTURE=shaderCompile3D.registerMaterialDefine("BASETEXTURE"); laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_SECONDTEXTURE=shaderCompile3D.registerMaterialDefine("SECONDTEXTURE"); laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET1=shaderCompile3D.registerMaterialDefine("TILINGOFFSET1"); laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET2=shaderCompile3D.registerMaterialDefine("TILINGOFFSET2"); } UVSineMaterial.BASETEXTURE=1; UVSineMaterial.SECONDTEXTURE=2; UVSineMaterial.BASECOLOR=3; UVSineMaterial.BASESCROLLSPEEDX=4; UVSineMaterial.BASESCROLLSPEEDY=5; UVSineMaterial.SECONDSCROLLSPEEDX=6; UVSineMaterial.SECONDSCROLLSPEEDY=7; UVSineMaterial.MMULTIPLIER=8; UVSineMaterial.ALPHA=9; UVSineMaterial.TILINGOFFSET1=10; UVSineMaterial.TILINGOFFSET2=11; UVSineMaterial.SHADERDEFINE_BASETEXTURE=0; UVSineMaterial.SHADERDEFINE_SECONDTEXTURE=0; UVSineMaterial.SHADERDEFINE_TILINGOFFSET1=0; UVSineMaterial.SHADERDEFINE_TILINGOFFSET2=0; __static(UVSineMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return UVSineMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.water.WaterDetailMaterial extends laya.d3.core.material.BaseMaterial var WaterDetailMaterial=(function(_super){ function WaterDetailMaterial(){ this._startTm=0; WaterDetailMaterial.__super.call(this); laya.d3.water.WaterDetailMaterial.init(); this.setShaderName('WaterDetail'); this.cull=0; this._startTm=Laya.timer.currTimer; } __class(WaterDetailMaterial,'laya.d3.water.WaterDetailMaterial',_super); var __proto=WaterDetailMaterial.prototype; __getset(0,__proto,'currentTm',function(){ return this._getNumber(1); },function(v){ this._setNumber(1,v-this._startTm); }); __getset(0,__proto,'waveInfo',function(){ return this._getBuffer(12); },function(v){ this._setBuffer(12,v); }); __getset(0,__proto,'waveInfoD',function(){ return this._getBuffer(13); },function(v){ this._setBuffer(13,v); }); __getset(0,__proto,'texWaveUVScale',function(){ return this._getNumber(15); },function(v){ this._setNumber(15,v); }); WaterDetailMaterial.init=function(){ if (laya.d3.water.WaterDetailMaterial._bInited) return; laya.d3.water.WaterDetailMaterial._bInited=true; var attributeMap={ 'a_position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'uv':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_curTm':[1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_WaveInfo':[12,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_WaveInfoD':[13,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'TEXWAVE_UV_SCALE':[15,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1] }; var WaterDetail=Shader3D.nameKey.add("WaterDetail"); var vs="\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 uv;\n\nvarying vec2 vUv;\nvarying vec3 vWorldNorm;\nvarying vec3 vWorldTangent;\nvarying vec3 vWorldBinormal;\n\n\nvoid main() {\n vec3 pos = a_position;\n if(pos.z!=0.)pos.y=pos.z;\n pos.z=0.5;\n gl_Position = vec4(pos,1.);\n vUv = uv;\n //vWorldNorm = normalize((modelMat*vec4(a_normal,0.0)).xyz);\n //vWorldTangent = normalize((modelMat*vec4(tangent,0.0)).xyz);\n //vWorldBinormal = normalize((modelMat*vec4(binormal,0.0)).xyz);\n}\n"; var ps="precision highp float;\nprecision lowp int;\n\nconst float PI = 3.14159265358979323846264;\nconst float _2PI = 6.2831853071796;\nvarying vec2 vUv;\nvarying vec3 vWorldNorm;\nvarying vec3 vWorldTangent;\nvarying vec3 vWorldBinormal;\n\nuniform float u_curTm;\n\n#include \"WaveFunction.glsl\"\n\nvoid main() {\n vec3 wave_N,wave_B,wave_T;\n calcWave(u_curTm, vUv,wave_B,wave_T,wave_N);\n gl_FragColor.rgb = normalize(wave_N)*0.5+vec3(0.5);// vec3(0.1,.4,0.1);\n gl_FragColor.a = 1.0;\n}\n"; var shaderCompile=ShaderCompile3D.add(WaterDetail,vs,ps,attributeMap,uniformMap); } WaterDetailMaterial.CURTM=1; WaterDetailMaterial.WAVEINFO=12; WaterDetailMaterial.WAVEINFOD=13; WaterDetailMaterial.WAVEMAINDIR=14; WaterDetailMaterial.TEXWAVE_UV_SCALE=15; WaterDetailMaterial._bInited=false; return WaterDetailMaterial; })(BaseMaterial) /** *RigidAnimations 类用于创建变换动画组件。 */ //class laya.d3.component.animation.RigidAnimations extends laya.d3.component.animation.KeyframeAnimations var RigidAnimations=(function(_super){ function RigidAnimations(){ /**@private */ this._animationSprites=null; /**@private */ this._animationSpritesInitLocalMatrix=null; /**@private */ this._tempCurAnimationData=null; /**@private */ this._curOriginalData=null; /**@private */ this._lastFrameIndex=-1; /**@private */ this._curAnimationDatas=null; RigidAnimations.__super.call(this); this._animationSprites=[]; this._animationSpritesInitLocalMatrix=[]; } __class(RigidAnimations,'laya.d3.component.animation.RigidAnimations',_super); var __proto=RigidAnimations.prototype; /** *@private */ __proto._init=function(){ var nodes=this._templet.getNodes(this.currentAnimationClipIndex); var curParentSprite=this._owner; var nodeLength=nodes.length; var pathStart=0; var extentDatas=new Uint16Array(this._templet.getPublicExtData()); for (var i=0;i < nodeLength;i++){ var hierarchys=extentDatas.slice(pathStart+1,pathStart+1+extentDatas[pathStart]); pathStart+=(extentDatas[pathStart]+1); for (var j=1;j < hierarchys.length;j++){ var childIndex=hierarchys[j]; curParentSprite=curParentSprite._childs[hierarchys[j]]; }; var curSprite=curParentSprite.getChildByName(nodes[i].name); if (!curSprite) break ; this._animationSprites[i]=curSprite; var localMatrix=this._animationSpritesInitLocalMatrix[i]; (localMatrix)|| (localMatrix=this._animationSpritesInitLocalMatrix[i]=new Matrix4x4()); curSprite.transform.localMatrix.cloneTo(localMatrix); curParentSprite=this._owner; } } /** *@private */ __proto._animtionPlay=function(){ if (this._templet.loaded) this._init(); else this._templet.once(/*laya.events.Event.LOADED*/"loaded",this,this._init); } /** *@private */ __proto._animtionStop=function(){ this._lastFrameIndex=-1; if (this._player.returnToZeroStopped){ this._curAnimationDatas=null; for (var i=0;i < this._animationSprites.length;i++) this._animationSprites[i].transform.localMatrix=this._animationSpritesInitLocalMatrix[i]; } } /** *@private *摄像机动画作用函数。 */ __proto._effectAnimation=function(nodes){ for (var nodeIndex=0,nodeLength=this._animationSprites.length;nodeIndex < nodeLength;nodeIndex++){ var sprite=this._animationSprites[nodeIndex]; var matrix=sprite.transform.localMatrix; var matrixE=matrix.elements; for (var i=0;i < 16;i++) matrixE[i]=this._curAnimationDatas[nodeIndex *16+i]; sprite.transform.localMatrix=matrix; } } /** *@private *初始化载入摄像机动画组件。 *@param owner 所属精灵对象。 */ __proto._load=function(owner){ _super.prototype._load.call(this,owner); this._player.on(/*laya.events.Event.STOPPED*/"stopped",this,this._animtionStop); this._player.on(/*laya.events.Event.PLAYED*/"played",this,this._animtionPlay); } /** *@private *更新摄像机动画组件。 *@param state 渲染状态。 */ __proto._update=function(state){ if (this._player.state!==/*laya.ani.AnimationState.playing*/2 || !this._templet || !this._templet.loaded) return; var rate=this._player.playbackRate *Laya.timer.scale; var cachePlayRate=this._player.cachePlayRate; var isCache=this._player.isCache && rate >=cachePlayRate; var frameIndex=isCache ? this.currentFrameIndex :-1; if (frameIndex!==-1 && this._lastFrameIndex===frameIndex) return; var animationClipIndex=this.currentAnimationClipIndex; var nodes=this._templet.getNodes(animationClipIndex); var animationDatasCache=this._templet._animationDatasCache; if (isCache){ var cacheData=this._templet.getAnimationDataWithCache(cachePlayRate,animationDatasCache,animationClipIndex,frameIndex); if (cacheData){ this._curAnimationDatas=cacheData; this._lastFrameIndex=frameIndex; this._effectAnimation(nodes); return; } }; var nodeFloatCount=nodes.length *16; if (isCache){ this._curAnimationDatas=new Float32Array(nodeFloatCount); }else{ (this._tempCurAnimationData)|| (this._tempCurAnimationData=new Float32Array(nodeFloatCount)); this._curAnimationDatas=this._tempCurAnimationData; } this._curOriginalData || (this._curOriginalData=new Float32Array(this._templet.getTotalkeyframesLength(animationClipIndex))); if (isCache) this._templet.getOriginalData(animationClipIndex,this._curOriginalData,this._player._fullFrames[animationClipIndex],frameIndex,this._player.currentFrameTime); else this._templet.getOriginalDataUnfixedRate(animationClipIndex,this._curOriginalData,this._player.currentPlayTime); Utils3D._computeRootAnimationData(nodes,this._curOriginalData,this._curAnimationDatas); if (isCache){ this._templet.setAnimationDataWithCache(cachePlayRate,animationDatasCache,animationClipIndex,frameIndex,this._curAnimationDatas); } this._lastFrameIndex=frameIndex; this._effectAnimation(nodes); } /** *@private *卸载组件时执行。 */ __proto._unload=function(owner){ _super.prototype._unload.call(this,owner); this._animationSprites=null; this._animationSpritesInitLocalMatrix=null; this._tempCurAnimationData=null; this._curOriginalData=null; this._curAnimationDatas=null; } /** *设置url地址。 *@param value 地址。 */ __getset(0,__proto,'url',null,function(value){ console.log("Warning: discard property,please use templet property instead."); var templet=Laya.loader.create(value,null,null,AnimationTemplet); if (this._templet!==templet){ if (this._player.state!==/*laya.ani.AnimationState.stopped*/0) this._player.stop(true); this._templet=templet; this._player.templet=templet; this._curOriginalData=null; this._curAnimationDatas=null; this._tempCurAnimationData=null; (this._templet._animationDatasCache)|| (this._templet._animationDatasCache=[]); this.event(/*laya.events.Event.ANIMATION_CHANGED*/"animationchanged",this); } }); __getset(0,__proto,'templet',_super.prototype._$get_templet,function(value){ if (this._templet!==value){ if (this._player.state!==/*laya.ani.AnimationState.stopped*/0) this._player.stop(true); this._templet=value; this._player.templet=value; this._curOriginalData=null; this._curAnimationDatas=null; this._tempCurAnimationData=null; (this._templet._animationDatasCache)|| (this._templet._animationDatasCache=[]); this.event(/*laya.events.Event.ANIMATION_CHANGED*/"animationchanged",this); } }); return RigidAnimations; })(KeyframeAnimations) /** *SkinAnimations 类用于创建蒙皮动画组件。 */ //class laya.d3.component.animation.SkinAnimations extends laya.d3.component.animation.KeyframeAnimations var SkinAnimations=(function(_super){ function SkinAnimations(){ /**@private */ this._tempCurAnimationData=null; /**@private */ this._tempCurBonesData=null; /**@private */ this._curOriginalData=null; /**@private */ this._lastFrameIndex=-1; /**@private */ this._curMeshAnimationData=null; /**@private */ this._curBonesDatas=null; /**@private */ this._curAnimationDatas=null; /**@private */ this._ownerMesh=null; /**@private */ this._boneIndexToMeshList=null; /**@private */ this._oldVersion=false; SkinAnimations.__super.call(this); this._boneIndexToMeshList=[]; } __class(SkinAnimations,'laya.d3.component.animation.SkinAnimations',_super); var __proto=SkinAnimations.prototype; /** *@private */ __proto._computeBoneIndexToMeshOnTemplet=function(){ if (this._templet.loaded) this._computeBoneIndexToMeshOnMesh(); else this._templet.once(/*laya.events.Event.LOADED*/"loaded",this,this._computeBoneIndexToMeshOnMesh); } /** *@private */ __proto._computeBoneIndexToMeshOnMesh=function(){ if (this._templet._aniVersion==="LAYAANIMATION:02") this._oldVersion=false; else this._oldVersion=true; var mesh=(this._owner).meshFilter.sharedMesh; if (mesh.loaded) this._computeBoneIndexToMesh(mesh); else mesh.on(/*laya.events.Event.LOADED*/"loaded",this,this._computeBoneIndexToMesh); } /** *@private */ __proto._computeBoneIndexToMesh=function(mesh){ var meshBoneNames=mesh._boneNames; if (meshBoneNames){ var binPoseCount=meshBoneNames.length; var anis=this._templet._anis; for (var i=0,n=anis.length;i < n;i++){ var boneIndexToMesh=this._boneIndexToMeshList[i]; (boneIndexToMesh)|| (boneIndexToMesh=this._boneIndexToMeshList[i]=[]); boneIndexToMesh.length=binPoseCount; var ani=anis[i]; for (var j=0;j < binPoseCount;j++) boneIndexToMesh[j]=ani.bone3DMap[meshBoneNames[j]]; } } } /**@private */ __proto._getAnimationDatasWithCache=function(rate,mesh,cacheDatas,aniIndex,frameIndex){ var aniDatas=cacheDatas[aniIndex]; if (!aniDatas){ return null; }else { var rateDatas=aniDatas[rate]; if (!rateDatas) return null; else { var meshDatas=rateDatas[mesh.id]; if (!meshDatas) return null; else return meshDatas[frameIndex]; } } } /**@private */ __proto._setAnimationDatasWithCache=function(rate,mesh,cacheDatas,aniIndex,frameIndex,animationDatas){ var aniDatas=(cacheDatas[aniIndex])|| (cacheDatas[aniIndex]={}); var rateDatas=(aniDatas[rate])|| (aniDatas[rate]={}); var meshDatas=(rateDatas[mesh.id])|| (rateDatas[mesh.id]=[]); meshDatas[frameIndex]=animationDatas; } /**@private */ __proto._onAnimationPlayMeshLoaded=function(){ var renderElements=this._ownerMesh.meshRender._renderElements; for (var i=0,n=renderElements.length;i < n;i++) renderElements[i]._canDynamicBatch=false; } /**@private */ __proto._onAnimationPlay=function(){ this._ownerMesh._render._addShaderDefine(SkinnedMeshSprite3D.SHADERDEFINE_BONE); var mesh=this._ownerMesh.meshFilter.sharedMesh; if (mesh.loaded) this._onAnimationPlayMeshLoaded(); else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._onAnimationPlayMeshLoaded); } /**@private */ __proto._onAnimationStop=function(){ this._lastFrameIndex=-1; if (this._player.returnToZeroStopped){ this._curBonesDatas=null; this._curAnimationDatas=null; this._ownerMesh._render._removeShaderDefine(SkinnedMeshSprite3D.SHADERDEFINE_BONE); }; var renderElements=this._ownerMesh.meshRender._renderElements; for (var i=0,n=renderElements.length;i < n;i++) renderElements[i]._canDynamicBatch=true; } /** *@private *初始化载入蒙皮动画组件。 *@param owner 所属精灵对象。 */ __proto._load=function(owner){ _super.prototype._load.call(this,owner); this._ownerMesh=(owner); this._player.on(/*laya.events.Event.PLAYED*/"played",this,this._onAnimationPlay); this._player.on(/*laya.events.Event.STOPPED*/"stopped",this,this._onAnimationStop); (this._owner).meshFilter.on(/*laya.events.Event.MESH_CHANGED*/"meshchanged",this,this._computeBoneIndexToMeshOnTemplet); } /** *@private *更新蒙皮动画组件。 *@param state 渲染状态参数。 */ __proto._update=function(state){ var mesh=this._ownerMesh.meshFilter.sharedMesh; if (this._player.state!==/*laya.ani.AnimationState.playing*/2 || !this._templet || !this._templet.loaded || !mesh.loaded) return; var rate=this._player.playbackRate *Laya.timer.scale; var cachePlayRate=this._player.cachePlayRate; var isCache=this._player.isCache && rate >=cachePlayRate; var frameIndex=isCache ? this.currentFrameIndex :-1; if (frameIndex!==-1 && this._lastFrameIndex===frameIndex) return; var animationClipIndex=this.currentAnimationClipIndex; var boneDatasCache=this._templet._animationDatasCache[0]; var animationDatasCache=this._templet._animationDatasCache[1]; if (isCache){ var cacheAnimationDatas=this._getAnimationDatasWithCache(cachePlayRate,mesh,animationDatasCache,animationClipIndex,frameIndex); if (cacheAnimationDatas){ this._curAnimationDatas=cacheAnimationDatas; this._curBonesDatas=this._templet.getAnimationDataWithCache(cachePlayRate,boneDatasCache,animationClipIndex,frameIndex); this._lastFrameIndex=frameIndex; return; } }; var isCacheBonesDatas=false; if (isCache){ this._curBonesDatas=this._templet.getAnimationDataWithCache(cachePlayRate,boneDatasCache,animationClipIndex,frameIndex); isCacheBonesDatas=this._curBonesDatas ? true :false; }; var bones=this._templet.getNodes(animationClipIndex); var boneFloatCount=bones.length *16; var inverseAbsoluteBindPoses=mesh.InverseAbsoluteBindPoses; if (this._oldVersion) (this._curMeshAnimationData)|| (this._curMeshAnimationData=new Float32Array(boneFloatCount)); else (this._curMeshAnimationData)|| (this._curMeshAnimationData=new Float32Array(inverseAbsoluteBindPoses.length *16)); var i=0,n=0,j=0; var curSubAnimationDatas,subMesh,boneIndicesCount=0; var subMeshCount=mesh.getSubMeshCount(); if (isCache){ this._curAnimationDatas=[]; this._curAnimationDatas.length=subMeshCount; for (i=0;i < subMeshCount;i++){ curSubAnimationDatas=this._curAnimationDatas[i]=[]; subMesh=mesh.getSubMesh(i); boneIndicesCount=subMesh._boneIndicesList.length; curSubAnimationDatas.length=boneIndicesCount; for (j=0;j < boneIndicesCount;j++) curSubAnimationDatas[j]=new Float32Array(subMesh._boneIndicesList[j].length *16); } (isCacheBonesDatas)|| (this._curBonesDatas=new Float32Array(boneFloatCount)); }else { if (!this._tempCurAnimationData){ this._tempCurAnimationData=[]; this._tempCurAnimationData.length=subMeshCount; for (i=0;i < subMeshCount;i++){ curSubAnimationDatas=this._tempCurAnimationData[i]=[]; subMesh=mesh.getSubMesh(i); boneIndicesCount=subMesh._boneIndicesList.length; curSubAnimationDatas.length=boneIndicesCount; for (j=0;j < boneIndicesCount;j++) curSubAnimationDatas[j]=new Float32Array(subMesh._boneIndicesList[j].length *16); } } (this._tempCurBonesData)|| (this._tempCurBonesData=new Float32Array(boneFloatCount)); this._curAnimationDatas=this._tempCurAnimationData; this._curBonesDatas=this._tempCurBonesData; } this._curOriginalData || (this._curOriginalData=new Float32Array(this._templet.getTotalkeyframesLength(animationClipIndex))); if (isCache) this._templet.getOriginalData(animationClipIndex,this._curOriginalData,this._player._fullFrames[animationClipIndex],frameIndex,this._player.currentFrameTime); else this._templet.getOriginalDataUnfixedRate(animationClipIndex,this._curOriginalData,this._player.currentPlayTime); if (this._oldVersion){ if (isCache && isCacheBonesDatas) Utils3D._computeAnimationDatasByArrayAndMatrixFastOld(inverseAbsoluteBindPoses,this._curBonesDatas,this._curMeshAnimationData); else Utils3D._computeBoneAndAnimationDatasByBindPoseMatrxixOld(bones,this._curOriginalData,inverseAbsoluteBindPoses,this._curBonesDatas,this._curMeshAnimationData); }else { var boneIndexToMesh=this._boneIndexToMeshList[animationClipIndex]; if (isCache && isCacheBonesDatas) Utils3D._computeAnimationDatasByArrayAndMatrixFast(inverseAbsoluteBindPoses,this._curBonesDatas,this._curMeshAnimationData,boneIndexToMesh); else Utils3D._computeBoneAndAnimationDatasByBindPoseMatrxix(bones,this._curOriginalData,inverseAbsoluteBindPoses,this._curBonesDatas,this._curMeshAnimationData,boneIndexToMesh); } for (i=0;i < subMeshCount;i++){ var boneIndicesList=mesh.getSubMesh(i)._boneIndicesList; boneIndicesCount=boneIndicesList.length; curSubAnimationDatas=this._curAnimationDatas[i] for (j=0;j < boneIndicesCount;j++) SkinAnimations._splitAnimationDatas(boneIndicesList[j],this._curMeshAnimationData,curSubAnimationDatas[j]); } if (isCache){ this._setAnimationDatasWithCache(cachePlayRate,mesh,animationDatasCache,animationClipIndex,frameIndex,this._curAnimationDatas); (isCacheBonesDatas)|| (this._templet.setAnimationDataWithCache(cachePlayRate,boneDatasCache,animationClipIndex,frameIndex,this._curBonesDatas)); } this._lastFrameIndex=frameIndex; } /** *@private *在渲染前更新蒙皮动画组件渲染参数。 *@param state 渲染状态参数。 */ __proto._preRenderUpdate=function(state){ var subMesh=state.renderElement.renderObj; if (this._curAnimationDatas) subMesh._skinAnimationDatas=this._curAnimationDatas[subMesh._indexInMesh]; else subMesh._skinAnimationDatas=null; } /** *@private *卸载组件时执行 */ __proto._unload=function(owner){ (this.player.state==/*laya.ani.AnimationState.playing*/2)&& (this._ownerMesh._render._removeShaderDefine(SkinnedMeshSprite3D.SHADERDEFINE_BONE)); (this._templet && !this._templet.loaded)&& (this._templet.off(/*laya.events.Event.LOADED*/"loaded",this,this._computeBoneIndexToMeshOnMesh)); var mesh=this._ownerMesh.meshFilter.sharedMesh; (mesh.loaded)|| (mesh.off(/*laya.events.Event.LOADED*/"loaded",this,this._onAnimationPlayMeshLoaded)); _super.prototype._unload.call(this,owner); this._tempCurAnimationData=null; this._tempCurBonesData=null; this._curOriginalData=null; this._curMeshAnimationData=null; this._curBonesDatas=null; this._curAnimationDatas=null; this._ownerMesh=null; } /** *获取骨骼数据。 *@return 骨骼数据。 */ __getset(0,__proto,'curBonesDatas',function(){ return this._curBonesDatas; }); __getset(0,__proto,'templet',_super.prototype._$get_templet,function(value){ if (this._templet!==value){ if (this._player.state!==/*laya.ani.AnimationState.stopped*/0) this._player.stop(true); this._templet=value; this._player.templet=value; this._computeBoneIndexToMeshOnTemplet(); this._curOriginalData=null; this._curMeshAnimationData=null; this._tempCurBonesData=null; this._tempCurAnimationData=null; (this._templet._animationDatasCache)|| (this._templet._animationDatasCache=[[],[]]); this.event(/*laya.events.Event.ANIMATION_CHANGED*/"animationchanged",this); } }); SkinAnimations._splitAnimationDatas=function(indices,bonesData,subAnimationDatas){ for (var i=0,n=indices.length,ii=0;i < n;i++){ for (var j=0;j < 16;j++,ii++){ subAnimationDatas[ii]=bonesData[(indices[i] << 4)+j]; } } } return SkinAnimations; })(KeyframeAnimations) /** *BoxCollider 类用于创建盒子碰撞器。 */ //class laya.d3.component.physics.BoxCollider extends laya.d3.component.physics.Collider var BoxCollider=(function(_super){ function BoxCollider(){ /**@private */ this._size=null; /**@private */ this._transformOrientedBoundBox=null; /**中心点 */ this.center=null; BoxCollider.__super.call(this); this._needUpdate=false; } __class(BoxCollider,'laya.d3.component.physics.BoxCollider',_super); var __proto=BoxCollider.prototype; /** *@private */ __proto._updateCollider=function(){ if (this._needUpdate){ var obbMat=this._transformOrientedBoundBox.transformation; var transform=(this._owner).transform; var rotation=transform.rotation; var scale=transform.scale; var centerE=this.center.elements; if (centerE[0]===0.0 && centerE[1]===0.0 && centerE[2]===0.0){ Matrix4x4.createAffineTransformation(transform.position,rotation,Vector3.ONE,obbMat); }else { Vector3.multiply(this.center,scale,BoxCollider._deviationV3); Vector3.transformQuat(BoxCollider._deviationV3,rotation,BoxCollider._deviationV3); Vector3.add(transform.position,BoxCollider._deviationV3,BoxCollider._deviationV3); Matrix4x4.createAffineTransformation(BoxCollider._deviationV3,rotation,Vector3.ONE,obbMat); } this._transformOrientedBoundBox.transformation=obbMat; var extentsE=this._transformOrientedBoundBox.extents.elements; var sizeE=this._size.elements; var scaleE=scale.elements; extentsE[0]=sizeE[0] *0.5 *scaleE[0]; extentsE[1]=sizeE[1] *0.5 *scaleE[1]; extentsE[2]=sizeE[2] *0.5 *scaleE[2]; this._needUpdate=false; } } /** *@private */ __proto._onWorldMatrixChanged=function(){ this._needUpdate=true; for (var k in this._runtimeCollisonMap){ this._runtimeCollisonTestMap[k]=true; this._runtimeCollisonMap[k]._runtimeCollisonTestMap[this.id]=true; } } /** *@inheritDoc */ __proto._initialize=function(owner){ laya.d3.component.Component3D.prototype._initialize.call(this,owner); this._transformOrientedBoundBox=new OrientedBoundBox(new Vector3(),new Matrix4x4()); this._size=new Vector3(); this.center=new Vector3(); (owner).transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChanged); this._needUpdate=true; } /** *@inheritDoc */ __proto._getType=function(){ return 1; } /** *@inheritDoc */ __proto._collisonTo=function(other){ switch (other._getType()){ case 0: return this.boundBox.containsSphere((other).boundSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0; break ; case 1: return this.boundBox.containsOrientedBoundBox((other).boundBox)!==/*laya.d3.math.ContainmentType.Disjoint*/0; break ; case 2:; var meshCollider=other; if (this.boundBox.containsBoundBox(meshCollider._boundBox)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ var positions=(other).mesh._positions; for (var i=0,n=positions.length;i < n;i++){ if (this.boundBox.containsPoint(positions[i])===/*laya.d3.math.ContainmentType.Contains*/1) return true } return false; }else { return false; } break ; default : throw new Error("BoxCollider:unknown collider type."); } } /** *@inheritDoc */ __proto._cloneTo=function(dest){ var destBoxCollider=dest; var destSize=destBoxCollider.size; this.size.cloneTo(destSize); destBoxCollider.size=destSize; this.center.cloneTo(destBoxCollider.center); } /** *@inheritDoc */ __proto.raycast=function(ray,hitInfo,maxDistance){ (maxDistance===void 0)&& (maxDistance=1.79e+308); this._updateCollider(); var distance=this._transformOrientedBoundBox.intersectsRay(ray,hitInfo.position); if (distance!==-1 && distance <=maxDistance){ hitInfo.distance=distance; hitInfo.sprite3D=this._owner; return true; }else { hitInfo.distance=-1; hitInfo.sprite3D=null; return false; } } /** *从AABB碰撞盒设置center和Size。 *@param boundBox 碰撞盒。 */ __proto.setFromBoundBox=function(boundBox){ OrientedBoundBox.createByBoundBox(boundBox,this._transformOrientedBoundBox); var extents=this._transformOrientedBoundBox.extents; this._size=new Vector3(extents.x *2,extents.y *2,extents.z *2); this.center=new Vector3(); Vector3.add(boundBox.min,boundBox.max,this.center); Vector3.scale(this.center,0.5,this.center); this._needUpdate=true; } /** *获取包围盒子,只读,不允许修改。 *@return 包围球。 */ __getset(0,__proto,'boundBox',function(){ this._updateCollider(); return this._transformOrientedBoundBox; }); /** *设置盒子碰撞器长宽高的一半。 *@param 长宽高的一半。 */ /** *获取盒子碰撞器长宽高的一半。 *@return 长宽高的一半。 */ __getset(0,__proto,'size',function(){ return this._size; },function(value){ this._size=value; this._needUpdate=true; }); __static(BoxCollider, ['_deviationV3',function(){return this._deviationV3=new Vector3();},'_obbCenterV3',function(){return this._obbCenterV3=new Vector3();} ]); return BoxCollider; })(Collider) /** *MeshCollider 类用于创建网格碰撞器。 */ //class laya.d3.component.physics.MeshCollider extends laya.d3.component.physics.Collider var MeshCollider=(function(_super){ function MeshCollider(){ /**@private */ this._transformBoundingBox=null; /**@private */ this._mesh=null; MeshCollider.__super.call(this); this._transformBoundingBox=new BoundBox(new Vector3(),new Vector3()); this._needUpdate=false; } __class(MeshCollider,'laya.d3.component.physics.MeshCollider',_super); var __proto=MeshCollider.prototype; /** *@private */ __proto._updateBoundBoxCollider=function(){ if (this._needUpdate){ var worldMat=(this._owner).transform.worldMatrix; var corners=this._mesh.boundingBoxCorners; for (var i=0;i < 8;i++) Vector3.transformCoordinate(corners[i],worldMat,MeshCollider._tempBoundBoxCorners[i]); BoundBox.createfromPoints(MeshCollider._tempBoundBoxCorners,this._transformBoundingBox); this._needUpdate=false; } } /** *@private */ __proto._raycastMesh=function(ray,sprite3D,outHitInfo,maxDistance){ (maxDistance===void 0)&& (maxDistance=1.79e+308); var worldMatrix=sprite3D.transform.worldMatrix; var invertWorldMatrix=MeshCollider._tempMatrix4x40; worldMatrix.invert(invertWorldMatrix); var rayOrigin=ray.origin; var rayDirection=ray.direction; var transformRay=MeshCollider._tempRay0; Vector3.transformCoordinate(rayOrigin,invertWorldMatrix,transformRay.origin); Vector3.TransformNormal(rayDirection,invertWorldMatrix,transformRay.direction); var curMinDistance=Number.MAX_VALUE; for (var i=0,n=this._mesh.getRenderElementsCount();i < n;i++){ var renderObj=this._mesh.getRenderElement(i); var vertexBuffer=renderObj._getVertexBuffer(0); var vertexDatas=vertexBuffer.getData(); var indexDatas=renderObj._getIndexBuffer().getData(); var elementRaycastHit=MeshCollider._tempRaycastHit; var isHit=Picker.rayIntersectsPositionsAndIndices(transformRay,vertexDatas,vertexBuffer.vertexDeclaration,indexDatas,elementRaycastHit); if (isHit){ Vector3.transformCoordinate(elementRaycastHit.position,worldMatrix,elementRaycastHit.position); var rayOriToPos=MeshCollider._tempVector30; Vector3.subtract(rayOrigin,elementRaycastHit.position,rayOriToPos); var distance=Vector3.scalarLength(rayOriToPos); if ((distance < maxDistance)&& (distance < curMinDistance)){ elementRaycastHit.distance=distance; elementRaycastHit.sprite3D=sprite3D; var trianglePositions=elementRaycastHit.trianglePositions; Vector3.transformCoordinate(trianglePositions[0],worldMatrix,trianglePositions[0]); Vector3.transformCoordinate(trianglePositions[1],worldMatrix,trianglePositions[1]); Vector3.transformCoordinate(trianglePositions[2],worldMatrix,trianglePositions[2]); var triangleNormals=elementRaycastHit.triangleNormals; Vector3.transformCoordinate(triangleNormals[0],worldMatrix,triangleNormals[0]); Vector3.transformCoordinate(triangleNormals[1],worldMatrix,triangleNormals[1]); Vector3.transformCoordinate(triangleNormals[2],worldMatrix,triangleNormals[2]); curMinDistance=distance; elementRaycastHit.cloneTo(outHitInfo); return true; } return false; } } return false; } /** *@private */ __proto._onWorldMatrixChanged=function(){ this._needUpdate=true; } /** *@inheritDoc */ __proto._initialize=function(owner){ laya.d3.component.Component3D.prototype._initialize.call(this,owner); (owner).transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChanged); this._needUpdate=true; } /** *@inheritDoc */ __proto._getType=function(){ return 2; } /** *@inheritDoc */ __proto._collisonTo=function(other){ var i=0,n=0; var positions=this.mesh._positions; switch (other._getType()){ case 0:; var otherSphere=other; if (Collision.sphereContainsBox(otherSphere.boundSphere,this._boundBox)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ for (i=0,n=positions.length;i < n;i++){ if (Collision.sphereContainsPoint(otherSphere.boundSphere,positions[i])===/*laya.d3.math.ContainmentType.Contains*/1) return true } return false; }else { return false; } break ; case 1:; var otherBox=other; if (otherBox.boundBox.containsBoundBox(this._boundBox)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ for (i=0,n=positions.length;i < n;i++){ if (otherBox.boundBox.containsPoint(positions[i])===/*laya.d3.math.ContainmentType.Contains*/1) return true } return false; break ; }else { return false; } case 2:; var otherMesh=other; if (Collision.intersectsBoxAndBox(otherMesh._boundBox,this._boundBox)!==/*laya.d3.math.ContainmentType.Contains*/1){ return true; }else { return false; } throw new Error("MeshCollider:unknown collider type."); break ; default : throw new Error("MeshCollider:unknown collider type."); } } /** *@inheritDoc */ __proto._cloneTo=function(dest){ var destCollider=dest; destCollider.mesh=this._mesh; } /** *@inheritDoc */ __proto.raycast=function(ray,hitInfo,maxDistance){ (maxDistance===void 0)&& (maxDistance=1.79e+308); if (this._mesh==null || !this._mesh.loaded) return false; var distance=Collision.intersectsRayAndBoxRD(ray,this._boundBox); if (distance!==-1 && distance <=maxDistance && this._raycastMesh(ray,this._owner,hitInfo,maxDistance)){ return true; }else { hitInfo.distance=-1; hitInfo.sprite3D=null; return false; } } /** *@private 只读,不允许修改。 */ __getset(0,__proto,'_boundBox',function(){ this._updateBoundBoxCollider(); return this._transformBoundingBox; }); /** *设置碰撞器网格。 *@param value 碰撞其网格。 */ /** *获取碰撞器网格。 *@return 碰撞其网格。 */ __getset(0,__proto,'mesh',function(){ return this._mesh; },function(value){ this._mesh=value; }); __static(MeshCollider, ['_tempRay0',function(){return this._tempRay0=new Ray(new Vector3(),new Vector3());},'_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempMatrix4x40',function(){return this._tempMatrix4x40=new Matrix4x4();},'_tempRaycastHit',function(){return this._tempRaycastHit=new RaycastHit();},'_tempBoundBoxCorners',function(){return this._tempBoundBoxCorners=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3()];} ]); return MeshCollider; })(Collider) /** *SphereCollider 类用于创建球碰撞器。 */ //class laya.d3.component.physics.SphereCollider extends laya.d3.component.physics.Collider var SphereCollider=(function(_super){ function SphereCollider(){ /**@private */ this._originalBoundSphere=null; /**@private */ this._transformBoundSphere=null; SphereCollider.__super.call(this); this._needUpdate=false; } __class(SphereCollider,'laya.d3.component.physics.SphereCollider',_super); var __proto=SphereCollider.prototype; /** *@private */ __proto._updateCollider=function(){ if (this._needUpdate){ var maxScale=NaN; var transform=(this._owner).transform; var scale=transform.scale; if (scale.x >=scale.y && scale.x >=scale.z) maxScale=scale.x; else maxScale=scale.y >=scale.z ? scale.y :scale.z; Vector3.transformCoordinate(this._originalBoundSphere.center,transform.worldMatrix,this._transformBoundSphere.center); this._transformBoundSphere.radius=this._originalBoundSphere.radius *maxScale; this._needUpdate=false; } } /** *@private */ __proto._onWorldMatrixChanged=function(){ this._needUpdate=true; for (var k in this._runtimeCollisonMap){ this._runtimeCollisonTestMap[k]=true; this._runtimeCollisonMap[k]._runtimeCollisonTestMap[this.id]=true; } } /** *@inheritDoc */ __proto._initialize=function(owner){ laya.d3.component.Component3D.prototype._initialize.call(this,owner); this._originalBoundSphere=new BoundSphere(new Vector3(0,0,0),0.5); this._transformBoundSphere=new BoundSphere(new Vector3(0,0,0),0.5); (owner).transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChanged); this._needUpdate=true; } /** *@inheritDoc */ __proto._getType=function(){ return 0; } /** *@inheritDoc */ __proto._collisonTo=function(other){ switch (other._getType()){ case 0: return Collision.sphereContainsSphere(this.boundSphere,(other).boundSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0; break ; case 1: return (other).boundBox.containsSphere(this.boundSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0; break ; case 2:; var meshCollider=other; if (Collision.sphereContainsBox(this.boundSphere,meshCollider._boundBox)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ var positions=meshCollider.mesh._positions; for (var i=0,n=positions.length;i < n;i++){ if (Collision.sphereContainsPoint(this.boundSphere,positions[i])===/*laya.d3.math.ContainmentType.Contains*/1) return true } return false; }else { return false; } break ; default : throw new Error("SphereCollider:unknown collider type."); } } /** *@inheritDoc */ __proto._cloneTo=function(dest){ var destCollider=dest; destCollider.radius=this.radius; var destCenter=destCollider.center; this.center.cloneTo(destCenter); destCollider.center=destCenter; } /** *@inheritDoc */ __proto.raycast=function(ray,hitInfo,maxDistance){ (maxDistance===void 0)&& (maxDistance=1.79e+308); this._updateCollider(); var distance=this._transformBoundSphere.intersectsRayPoint(ray,hitInfo.position); if (distance!==-1 && distance <=maxDistance){ hitInfo.distance=distance; hitInfo.sprite3D=this._owner; return true; }else { hitInfo.distance=-1; hitInfo.sprite3D=null; return false; } } /** *设置中心点。 *@param value 中心点。 */ /** *获取中心点。 *@return 中心点。 */ __getset(0,__proto,'center',function(){ return this._originalBoundSphere.center; },function(value){ this._originalBoundSphere.center=value; }); /** *设置半径。 *@param value 半径。 */ /** *获取半径。 *@return 半径。 */ __getset(0,__proto,'radius',function(){ return this._originalBoundSphere.radius; },function(value){ this._originalBoundSphere.radius=value; }); /** *获取包围球,只读,不允许修改。 *@return 包围球。 */ __getset(0,__proto,'boundSphere',function(){ this._updateCollider(); return this._transformBoundSphere; }); return SphereCollider; })(Collider) //class laya.d3.resource.DataTexture2D extends laya.d3.resource.BaseTexture var DataTexture2D=(function(_super){ function DataTexture2D(){ this.simLodInfo=null; /**@private 文件路径全名。*/ this._src=null; /**@private Imagedata */ this._buffer=null; this._mipmaps=null; /**@private 异步加载锁*/ this._recreateLock=false; /**@private 异步加载完成后是否需要释放(有可能在恢复过程中,再次被释放,用此变量做标记)*/ this._needReleaseAgain=false; DataTexture2D.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1; } __class(DataTexture2D,'laya.d3.resource.DataTexture2D',_super); var __proto=DataTexture2D.prototype; __proto.genDebugMipmaps=function(){ var ret=[]; ret.push(new Uint8Array((new Uint32Array(512 *256)).fill(0xff0000ff).buffer)); ret.push(new Uint8Array((new Uint32Array(256 *128)).fill(0xff0080ff).buffer)); ret.push(new Uint8Array((new Uint32Array(128 *64)).fill(0xff00ffff).buffer)); ret.push(new Uint8Array((new Uint32Array(64 *32)).fill(0xff00ff00).buffer)); ret.push(new Uint8Array((new Uint32Array(32 *16)).fill(0xff804000).buffer)); ret.push(new Uint8Array((new Uint32Array(16 *8)).fill(0xffff0000).buffer)); ret.push(new Uint8Array((new Uint32Array(8 *4)).fill(0xffff0080).buffer)); ret.push(new Uint8Array((new Uint32Array(4 *2)).fill(0x0).buffer)); ret.push(new Uint8Array((new Uint32Array(2 *1)).fill(0xff808080).buffer)); ret.push(new Uint8Array((new Uint32Array(1 *1)).fill(0xffffffff).buffer)); return ret; } /** *@private */ __proto._onTextureLoaded=function(buff){} /** *@private */ __proto._createWebGlTexture=function(){ if (!this._buffer && !this._mipmaps) throw "create GLTextur err:no data"; var gl=WebGL.mainContext; gl.getExtension("EXT_shader_texture_lod"); var glTexture=this._source=gl.createTexture(); var w=this._width; var h=this._height; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,glTexture); if (this._mipmaps){ if (laya.d3.resource.DataTexture2D.lodasatlas){ var infoi=0; gl.texImage2D(this._type,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,this._width,this._height,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,null); for (var i=0;i < this._mipmaps.length;i++){ if (this._mipmaps[i].byteLength !=cw *ch *4){ throw "mipmap size error level:"+i; } gl.texSubImage2D(this._type,0,DataTexture2D.simLodRect[infoi++],DataTexture2D.simLodRect[infoi++],DataTexture2D.simLodRect[infoi++],DataTexture2D.simLodRect[infoi++],/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,new Uint8Array(this._mipmaps[i])); } this.minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601; this.magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601; }else { var cw=this._width; var ch=this._height; infoi=0; gl.texImage2D(this._type,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,this._width,this._height,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,null); for (i=0;i < this._mipmaps.length;i++){ if (this._mipmaps[i].byteLength !=cw *ch *4){ throw "mipmap size error level:"+i; } gl.texImage2D(this._type,i,/*laya.webgl.WebGLContext.RGBA*/0x1908,cw,ch,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,new Uint8Array(this._mipmaps[i])); cw /=2; ch /=2; if (cw < 1)cw=1; if (ch < 1)ch=1; this.minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703; this.magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601; } } this.mipmap=false; }else { gl.texImage2D(this._type,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,new Uint8Array(this._buffer)); }; var minFifter=this._minFifter; var magFifter=this._magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPot=Arith.isPOT(w,h); if (isPot){ if (this._mipmap || this._mipmaps) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); if (this._mipmaps) gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); else gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this._mipmap && gl.generateMipmap(this._type); }else { throw "data texture must be POT"; } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); if (this.src && this.src.length > 0) this._buffer=null; if (isPot) this.memorySize=w *h *4 *(1+1 / 3); else this.memorySize=w *h *4; this._recreateLock=false; } /** *重新创建资源,如果异步创建中被强制释放再创建,则需等待释放完成后再重新加载创建。 */ __proto.recreateResource=function(){ if (!this._buffer && (this._src==null || this._src==="")) return; this._needReleaseAgain=false; if (!this._buffer && !this._mipmaps){ this._recreateLock=true; var _this=this; }else { if (this._recreateLock){ return; } this._createWebGlTexture(); this.completeCreate(); } } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ var imgdata; if (params){ imgdata=params[0].call(this,data); } if (imgdata){ this._width=imgdata.width; this._height=imgdata.height; this._buffer=imgdata.data; } this._src=url; this._size=new Size(this._width,this._height); if (this._conchTexture){ alert('怎么给runtime传递datatexture数据'); }else this.activeResource(); this._endLoaded(); } /** *返回图片像素。 *@return 图片像素。 */ __proto.getPixels=function(){ return new Uint8Array(this._buffer); } /** *销毁资源。 */ __proto.disposeResource=function(){ if (this._recreateLock){ this._needReleaseAgain=true; } if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this._buffer=null; this.memorySize=0; } } /** *获取文件路径全名。 */ __getset(0,__proto,'src',function(){ return this._src; }); DataTexture2D.create=function(data,w,h,magfilter,minfilter,mipmap){ (magfilter===void 0)&& (magfilter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (minfilter===void 0)&& (minfilter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (mipmap===void 0)&& (mipmap=true); if (!data || data.byteLength < (w *h *4)) throw 'DataTexture2D create error'; var ret=new DataTexture2D(); ret._buffer=data; ret._width=w; ret._height=h; ret._mipmap=mipmap; ret._magFifter=magfilter; ret._minFifter=minfilter; ret._size=new Size(ret._width,ret._height); if (ret._conchTexture){ alert('怎么给runtime传递datatexture数据'); }else ret.activeResource(); return ret; } DataTexture2D.load=function(url,w,h,magfilter,minfilter){ (w===void 0)&& (w=0); (h===void 0)&& (h=0); (magfilter===void 0)&& (magfilter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (minfilter===void 0)&& (minfilter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); var extension=Utils.getFileExtension(url); if (extension==='mipmaps'){ var ret=Laya.loader.create(url,null,null,DataTexture2D,[function(data){ this._mipmaps=[]; var szinfo=new Uint32Array(data); this._width=szinfo[0]; var validw=512; if (laya.d3.resource.DataTexture2D.lodasatlas){ this._width *=2; validw=1024; } if (this._width !=validw){ console.error("现在只支持512x256的环境贴图。当前的是"+szinfo[0]); throw "现在只支持512x256的环境贴图。当前的是"+szinfo[0]; } this._height=szinfo[1]; var curw=laya.d3.resource.DataTexture2D.lodasatlas ? this._width / 2 :this._width; var curh=this._height; var cursz=8; while (true){ var curbufsz=curw *curh *4; if (cursz+curbufsz > data.byteLength){ throw "load mipmaps data size error "; }; var tbuf=new Uint8Array(data,cursz,curbufsz); this._mipmaps.push(tbuf); cursz+=curbufsz; if (curw==1 && curh==1){ break ; } curw /=2; curh /=2; if (curw < 1)curw=1; if (curh < 1)curh=1; } return null; }]); if (laya.d3.resource.DataTexture2D.lodasatlas){ ret.simLodInfo=new Float32Array(40); for (var i=0;i < ret.simLodInfo.length;){ ret.simLodInfo[i]=(DataTexture2D.simLodRect[i]+0.5)/ 1024; i++; ret.simLodInfo[i]=(DataTexture2D.simLodRect[i]+0.5)/ 256; i++; ret.simLodInfo[i]=Math.max(DataTexture2D.simLodRect[i]-1,0.1)/ 1024; i++; ret.simLodInfo[i]=Math.max(DataTexture2D.simLodRect[i]-1.5,0.1)/ 256; i++; } } return ret; }else if (typeof(w)=='number'){ return Laya.loader.create(url,null,null,DataTexture2D,[function(data){ this._width=w; this._height=h; this._buffer=data; return null; }]); }else if (typeof(w)=='function'){ return Laya.loader.create(url,null,null,DataTexture2D,[w]); }else { throw new Error("unknown params."); } } DataTexture2D.lodasatlas=false; __static(DataTexture2D, ['simLodRect',function(){return this.simLodRect=new Uint32Array([ 0,0,512,256, 512,0,256,128, 512+256,0,128,64, 512+256+128,0,64,32, 512+256+128+64,0,32,16, 512+256+128+64+32,0,16,8, 512+256+128+64+32+16,0,8,4, 512+256+128+64+32+16+8,0,4,2, 512+256+128+64+32+16+8+4,0,2,1, 512+256+128+64+32+16+8+4+2,0,1,1]);} ]); return DataTexture2D; })(BaseTexture) /** *@private *PrimitiveMesh 类用于创建基本网格的父类。 */ //class laya.d3.resource.models.PrimitiveMesh extends laya.d3.resource.models.BaseMesh var PrimitiveMesh=(function(_super){ function PrimitiveMesh(){ this._numberVertices=0; this._numberIndices=0; this._vertexBuffer=null; this._indexBuffer=null; PrimitiveMesh.__super.call(this); } __class(PrimitiveMesh,'laya.d3.resource.models.PrimitiveMesh',_super); var __proto=PrimitiveMesh.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer; else return null; } __proto._getVertexBuffers=function(){ return null; } __proto._getIndexBuffer=function(){ return this._indexBuffer; } /** *获取网格顶点 *@return 网格顶点。 */ __proto._getPositions=function(){ var vertices=[]; var positionElement; var vertexElements=this._vertexBuffer.vertexDeclaration.getVertexElements(); var j=0; for (j=0;j < vertexElements.length;j++){ var vertexElement=vertexElements[j]; if (vertexElement.elementFormat===/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3" && vertexElement.elementUsage===/*laya.d3.graphics.VertexElementUsage.POSITION0*/0){ positionElement=vertexElement; break ; } }; var verticesData=this._vertexBuffer.getData(); for (j=0;j < verticesData.length;j+=this._vertexBuffer.vertexDeclaration.vertexStride / 4){ var ofset=j+positionElement.offset / 4; var position=new Vector3(verticesData[ofset+0],verticesData[ofset+1],verticesData[ofset+2]); vertices.push(position); } return vertices; } __proto.getRenderElement=function(index){ return this; } __proto.getRenderElementsCount=function(){ return 1; } __proto.disposeResource=function(){ (this._vertexBuffer)&& (this._vertexBuffer.destroy(),this._vertexBuffer=null); (this._indexBuffer)&& (this._indexBuffer.destroy(),this._indexBuffer=null); this.memorySize=0; } __proto._beforeRender=function(state){ this._vertexBuffer._bind(); this._indexBuffer._bind(); return true; } __proto._render=function(state){ WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._numberIndices,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.drawCall++; Stat.trianglesFaces+=this._numberIndices / 3; } __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); __getset(0,__proto,'triangleCount',function(){ return this._indexBuffer.indexCount / 3; }); return PrimitiveMesh; })(BaseMesh) /** *Mesh 类用于创建文件网格数据模板。 */ //class laya.d3.resource.models.Mesh extends laya.d3.resource.models.BaseMesh var Mesh=(function(_super){ function Mesh(){ /**@private */ this._materials=null; /**@private */ this._subMeshes=null; /**@private */ this._vertexBuffers=null; /**@private */ this._indexBuffer=null; /**@private */ this._boneNames=null; /**@private */ this._inverseBindPoses=null; /**@private */ this._skinnedDatas=null; Mesh.__super.call(this); this._subMeshes=[]; this._materials=[]; this._vertexBuffers=[]; } __class(Mesh,'laya.d3.resource.models.Mesh',_super); var __proto=Mesh.prototype; /** *获取网格顶点,并产生数据 *@return 网格顶点。 */ __proto._getPositions=function(){ var vertices=[]; var i=0,j=0,vertexBuffer,positionElement,vertexElements,vertexElement,ofset=0,verticesData; if (this._vertexBuffers.length!==0){ var vertexBufferCount=this._vertexBuffers.length; for (i=0;i < vertexBufferCount;i++){ vertexBuffer=this._vertexBuffers[i]; vertexElements=vertexBuffer.vertexDeclaration.getVertexElements(); for (j=0;j < vertexElements.length;j++){ vertexElement=vertexElements[j]; if (vertexElement.elementFormat===/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3" && vertexElement.elementUsage===/*laya.d3.graphics.VertexElementUsage.POSITION0*/0){ positionElement=vertexElement; break ; } } verticesData=vertexBuffer.getData(); for (j=0;j < verticesData.length;j+=vertexBuffer.vertexDeclaration.vertexStride / 4){ ofset=j+positionElement.offset / 4; vertices.push(new Vector3(verticesData[ofset+0],verticesData[ofset+1],verticesData[ofset+2])); } } }else { var submesheCount=this._subMeshes.length; for (i=0;i < submesheCount;i++){ var subMesh=this._subMeshes[i]; vertexBuffer=subMesh._getVertexBuffer(); vertexElements=vertexBuffer.vertexDeclaration.getVertexElements(); for (j=0;j < vertexElements.length;j++){ vertexElement=vertexElements[j]; if (vertexElement.elementFormat===/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3" && vertexElement.elementUsage===/*laya.d3.graphics.VertexElementUsage.POSITION0*/0){ positionElement=vertexElement; break ; } } verticesData=vertexBuffer.getData(); for (j=0;j < verticesData.length;j+=vertexBuffer.vertexDeclaration.vertexStride / 4){ ofset=j+positionElement.offset / 4; vertices.push(new Vector3(verticesData[ofset+0],verticesData[ofset+1],verticesData[ofset+2])); } } } return vertices; } /** *添加子网格(开发者禁止修改)。 *@param subMesh 子网格。 */ __proto._setSubMeshes=function(subMeshes){ this._subMeshes=subMeshes this._subMeshCount=subMeshes.length; for (var i=0;i < this._subMeshCount;i++) subMeshes[i]._indexInMesh=i; this._positions=this._getPositions(); this._generateBoundingObject(); } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ var bufferData=data[0]; var textureMap=data[1]; MeshReader.read(bufferData,this,this._materials,this._subMeshes,textureMap); this.completeCreate(); this._endLoaded(); } /** *获得子网格。 *@param index 子网格索引。 *@return 子网格。 */ __proto.getSubMesh=function(index){ return this._subMeshes[index]; } /** *获得子网格数量。 *@return 子网格数量。 */ __proto.getSubMeshCount=function(){ return this._subMeshes.length; } /** *@inheritDoc */ __proto.getRenderElementsCount=function(){ return this._subMeshes.length; } /** *@inheritDoc */ __proto.getRenderElement=function(index){ return this._subMeshes[index]; } /** *@inheritDoc */ __proto.disposeResource=function(){ for (var i=0;i < this._subMeshes.length;i++) this._subMeshes[i].dispose(); this._materials=null; this._subMeshes=null; this._vertexBuffers=null; this._indexBuffer=null; this._boneNames=null; this._inverseBindPoses=null; } /** *获取材质队列的浅拷贝。 *@return 材质队列的浅拷贝。 */ __getset(0,__proto,'materials',function(){ return this._materials.slice(); }); /** *获取网格的全局默认绑定动作逆矩阵。 *@return 网格的全局默认绑定动作逆矩阵。 */ __getset(0,__proto,'InverseAbsoluteBindPoses',function(){ return this._inverseBindPoses; }); Mesh.load=function(url){ return Laya.loader.create(url,null,null,Mesh); } return Mesh; })(BaseMesh) /** *RenderTarget 类用于创建渲染目标。 */ //class laya.d3.resource.RenderTexture extends laya.d3.resource.BaseTexture var RenderTexture=(function(_super){ function RenderTexture(width,height,surfaceFormat,surfaceType,depthStencilFormat,mipMap,repeat,minFifter,magFifter){ /**@private */ this._alreadyResolved=false; /**@private */ this._surfaceFormat=0; /**@private */ this._surfaceType=0; /**@private */ this._depthStencilFormat=0; /**@private */ this._frameBuffer=null; /**@private */ this._depthStencilBuffer=null; (surfaceFormat===void 0)&& (surfaceFormat=/*laya.webgl.WebGLContext.RGBA*/0x1908); (surfaceType===void 0)&& (surfaceType=/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401); (depthStencilFormat===void 0)&& (depthStencilFormat=/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5); (mipMap===void 0)&& (mipMap=false); (repeat===void 0)&& (repeat=false); (minFifter===void 0)&& (minFifter=-1); (magFifter===void 0)&& (magFifter=-1); RenderTexture.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1; this._width=width; this._height=height; this._size=new Size(width,height); this._surfaceFormat=surfaceFormat; this._surfaceType=surfaceType; this._depthStencilFormat=depthStencilFormat; if (Render.isConchWebGL && this._depthStencilFormat===/*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9){ this._depthStencilFormat=/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5; } this._mipmap=mipMap; this._repeat=repeat; this._minFifter=minFifter; this._magFifter=magFifter; this.activeResource(); this._alreadyResolved=true; } __class(RenderTexture,'laya.d3.resource.RenderTexture',_super); var __proto=RenderTexture.prototype; __proto.recreateResource=function(){ var gl=WebGL.mainContext; this._frameBuffer=gl.createFramebuffer(); this._source=gl.createTexture(); var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,this._source); gl.texImage2D(this._type,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,this._width,this._height,0,this._surfaceFormat,this._surfaceType,null); var minFifter=this._minFifter; var magFifter=this._magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPot=Arith.isPOT(this._width,this._height); if (isPot){ if (this._mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this._mipmap && gl.generateMipmap(this._type); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,this._frameBuffer); gl.framebufferTexture2D(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.COLOR_ATTACHMENT0*/0x8CE0,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,this._source,0); if (this._depthStencilFormat){ this._depthStencilBuffer=gl.createRenderbuffer(); gl.bindRenderbuffer(/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); gl.renderbufferStorage(/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilFormat,this._width,this._height); switch (this._depthStencilFormat){ case /*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5: gl.framebufferRenderbuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.DEPTH_ATTACHMENT*/0x8D00,/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); break ; case /*laya.webgl.WebGLContext.STENCIL_INDEX8*/0x8D48: gl.framebufferRenderbuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.STENCIL_ATTACHMENT*/0x8D20,/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); break ; case /*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9: gl.framebufferRenderbuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.DEPTH_STENCIL_ATTACHMENT*/0x821A,/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); break ; } } gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); gl.bindRenderbuffer(/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,null); this.memorySize=this._width *this._height *4; this.completeCreate(); } /** *开始绑定。 */ __proto.start=function(){ WebGL.mainContext.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,this.frameBuffer); RenderTexture._currentRenderTarget=this; this._alreadyResolved=false; } /** *结束绑定。 */ __proto.end=function(){ WebGL.mainContext.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); RenderTexture._currentRenderTarget=null; this._alreadyResolved=true; } /** *获得像素数据。 *@param x X像素坐标。 *@param y Y像素坐标。 *@param width 宽度。 *@param height 高度。 *@return 像素数据。 */ __proto.getData=function(x,y,width,height){ var gl=WebGL.mainContext; gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,this._frameBuffer); var canRead=(gl.checkFramebufferStatus(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40)===/*laya.webgl.WebGLContext.FRAMEBUFFER_COMPLETE*/0x8CD5); if (!canRead){ gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); return null; }; var pixels=new Uint8Array(this._width *this._height *4); gl.readPixels(x,y,width,height,this._surfaceFormat,this._surfaceType,pixels); gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); return pixels; } /** *销毁资源。 */ __proto.disposeResource=function(){ if (this._frameBuffer){ var gl=WebGL.mainContext; gl.deleteTexture(this._source); gl.deleteFramebuffer(this._frameBuffer); gl.deleteRenderbuffer(this._depthStencilBuffer); this._source=null; this._frameBuffer=null; this._depthStencilBuffer=null; this.memorySize=0; } } /** *获取表面格式。 *@return 表面格式。 */ __getset(0,__proto,'surfaceFormat',function(){ return this._surfaceFormat; }); /** *获取表面类型。 *@return 表面类型。 */ __getset(0,__proto,'surfaceType',function(){ return this._surfaceType; }); /** *获取深度格式。 *@return 深度格式。 */ __getset(0,__proto,'depthStencilFormat',function(){ return this._depthStencilFormat; }); /** *获取RenderTarget数据源,如果alreadyResolved等于false,则返回null。 *@return RenderTarget数据源。 */ __getset(0,__proto,'source',function(){ if (this._alreadyResolved) return Laya.superGet(BaseTexture,this,'source'); else return null; }); __getset(0,__proto,'depthStencilBuffer',function(){ return this._depthStencilBuffer; }); __getset(0,__proto,'frameBuffer',function(){ return this._frameBuffer; }); RenderTexture._currentRenderTarget=null; return RenderTexture; })(BaseTexture) /** *SolidColorTexture2D 二维纯色纹理。 */ //class laya.d3.resource.SolidColorTexture2D extends laya.d3.resource.BaseTexture var SolidColorTexture2D=(function(_super){ function SolidColorTexture2D(color){ /**@private */ this._color=null; /**@private */ this._pixels=null; SolidColorTexture2D.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1; this._width=1; this._height=1; this._size=new Size(this.width,this.height); this._color=color; this._pixels=new Uint8Array([color.x *255,color.y *255,color.z *255,color.w *255]); } __class(SolidColorTexture2D,'laya.d3.resource.SolidColorTexture2D',_super); var __proto=SolidColorTexture2D.prototype; /** *@private */ __proto._createWebGlTexture=function(){ var gl=WebGL.mainContext; var glTex=this._source=gl.createTexture(); var w=this._width; var h=this._height; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,glTex); gl.texImage2D(this._type,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); var minFifter=this._minFifter; var magFifter=this._magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPot=Arith.isPOT(w,h); if (isPot){ if (this._mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this._mipmap && gl.generateMipmap(this._type); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); if (isPot) this.memorySize=w *h *4 *(1+1 / 3); else this.memorySize=w *h *4; } /** *重新创建资源,如果异步创建中被强制释放再创建,则需等待释放完成后再重新加载创建。 */ __proto.recreateResource=function(){ this._createWebGlTexture(); this.completeCreate(); } /** *销毁资源。 */ __proto.disposeResource=function(){ if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this.memorySize=0; } } __static(SolidColorTexture2D, ['magentaTexture',function(){return this.magentaTexture=new SolidColorTexture2D(new Vector4(1.0,0.0,1.0,1.0));},'grayTexture',function(){return this.grayTexture=new SolidColorTexture2D(new Vector4(0.5,0.5,0.5,1.0));} ]); return SolidColorTexture2D; })(BaseTexture) //class laya.d3.resource.SolidColorTextureCube extends laya.d3.resource.BaseTexture var SolidColorTextureCube=(function(_super){ function SolidColorTextureCube(color){ /**@private */ this._color=null; /**@private */ this._pixels=null; /**@private */ this._texCount=6; SolidColorTextureCube.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513; this._width=1; this._height=1; this._size=new Size(this.width,this.height); this._color=color; this._pixels=new Uint8Array([color.x *255,color.y *255,color.z *255,color.w *255]); } __class(SolidColorTextureCube,'laya.d3.resource.SolidColorTextureCube',_super); var __proto=SolidColorTextureCube.prototype; __proto._createWebGlTexture=function(){ var gl=WebGL.mainContext; var glTex=this._source=gl.createTexture(); var w=this._width; var h=this._height; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,glTex); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_X*/0x8515,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_X*/0x8516,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_Y*/0x8517,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_Y*/0x8518,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_Z*/0x8519,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_Z*/0x851A,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); var minFifter=this.minFifter; var magFifter=this.magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPOT=Arith.isPOT(w,h); if (isPOT){ if (this.mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this.mipmap && gl.generateMipmap(this._type); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); if (isPOT) this.memorySize=w *h *4 *(1+1 / 3)*this._texCount; else this.memorySize=w *h *4 *this._texCount; } __proto.recreateResource=function(){ this._createWebGlTexture(); this.completeCreate(); } //处理创建完成后相关操作 __proto.disposeResource=function(){ if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this.memorySize=0; } } __static(SolidColorTextureCube, ['magentaTexture',function(){return this.magentaTexture=new SolidColorTextureCube(new Vector4(1.0,0.0,1.0,1.0));},'grayTexture',function(){return this.grayTexture=new SolidColorTextureCube(new Vector4(0.5,0.5,0.5,1.0));} ]); return SolidColorTextureCube; })(BaseTexture) /** *Texture2D 二维纹理。 */ //class laya.d3.resource.Texture2D extends laya.d3.resource.BaseTexture var Texture2D=(function(_super){ function Texture2D(canRead,reapeat,format,mipmap){ /**@private */ this._canRead=false; /**@private HTML Image*/ this._image=null; /**@private */ this._pixels=null; (canRead===void 0)&& (canRead=false); (reapeat===void 0)&& (reapeat=true); (format===void 0)&& (format=/*laya.webgl.WebGLContext.RGBA*/0x1908); (mipmap===void 0)&& (mipmap=true); Texture2D.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1; this._repeat=reapeat; this._canRead=canRead; this._format=format; this._mipmap=mipmap; } __class(Texture2D,'laya.d3.resource.Texture2D',_super); var __proto=Texture2D.prototype; /** *@private */ __proto._createWebGlTexture=function(){ if (!this._image) throw "create GLTextur err:no data:"+this._image; var gl=WebGL.mainContext; var glTexture=this._source=gl.createTexture(); var w=this._width; var h=this._height; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,glTexture); switch (this._format){ case /*laya.webgl.WebGLContext.RGB*/0x1907: case /*laya.webgl.WebGLContext.RGBA*/0x1908: if (this._canRead) gl.texImage2D(this._type,0,this._format,w,h,0,this._format,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); else gl.texImage2D(this._type,0,this._format,this._format,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._image); break ; case WebGL.compressEtc1.COMPRESSED_RGB_ETC1_WEBGL: gl.compressedTexImage2D(this._type,0,this._format,this._width,this._height,0,this._image); break ; }; var minFifter=this._minFifter; var magFifter=this._magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var wrapModeU=this._wrapModeU==0 ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var wrapModeV=this._wrapModeV==0 ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPot=Arith.isPOT(w,h); if (isPot){ if (this._mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,wrapModeU); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,wrapModeV); this._mipmap && gl.generateMipmap(this._type); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); this._image.onload=null; this._image=null; if (isPot) this.memorySize=w *h *4 *(1+1 / 3); else this.memorySize=w *h *4; } /** *重新创建资源,如果异步创建中被强制释放再创建,则需等待释放完成后再重新加载创建。 */ __proto.recreateResource=function(){ this._createWebGlTexture(); this.completeCreate(); } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ if (params){ var canRead=params[0]; (canRead!==undefined)&& (this._canRead=canRead); var repeat=params[1]; (repeat!==undefined)&& (this._repeat=repeat); var format=params[2]; (format!==undefined)&& (this._format=format); var mipmap=params[3]; (mipmap!==undefined)&& (this._mipmap=mipmap); var wrapModeU=params.wrapModeU; (wrapModeU!==undefined)&& (this._wrapModeU=wrapModeU); var wrapModeV=params.wrapModeV; (wrapModeV!==undefined)&& (this._wrapModeV=wrapModeV); } switch (this._format){ case /*laya.webgl.WebGLContext.RGB*/0x1907: case /*laya.webgl.WebGLContext.RGBA*/0x1908: this._image=data; var w=data.width; var h=data.height; this._width=w; this._height=h; this._size=new Size(w,h); if (this._canRead){ if (Render.isConchApp){ if (/*__JS__ */data instanceof window.HTMLElement){ this._pixels=new Uint8Array(data.getImageData(0,0,w,h)); } } else { Browser.canvas.size(w,h); Browser.canvas.clear(); Browser.context.drawImage(data,0,0,w,h); this._pixels=new Uint8Array(Browser.context.getImageData(0,0,w,h).data.buffer); } } break ; case WebGL.compressEtc1.COMPRESSED_RGB_ETC1_WEBGL:; var readData=new Byte(data); var magicNumber=readData.readUTFBytes(4); var version=readData.readUTFBytes(2); var dataType=readData.getInt16(); readData.endian=/*laya.utils.Byte.BIG_ENDIAN*/"bigEndian"; this._width=readData.getInt16(); this._height=readData.getInt16(); this._size=new Size(this._width,this._height); var originalWidth=readData.getInt16(); var originalHeight=readData.getInt16(); this._image=new Uint8Array(data,readData.pos); } this.recreateResource(); this._endLoaded(); } /** *返回图片像素。 *@return 图片像素。 */ __proto.getPixels=function(){ if (this._canRead) return this._pixels; else throw new Error("Texture2D: must set texture canRead is true."); } /** *销毁资源。 */ __proto.disposeResource=function(){ if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this._image=null; this.memorySize=0; } } /**@private */ __getset(0,__proto,'_src',function(){ return this.url; }); /**@private */ __getset(0,__proto,'src',function(){ return this.url; }); Texture2D.load=function(url){ return Laya.loader.create(url,null,null,Texture2D); } return Texture2D; })(BaseTexture) //class laya.d3.resource.TextureCube extends laya.d3.resource.BaseTexture var TextureCube=(function(_super){ function TextureCube(){ /**@private */ //this._images=null; TextureCube.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513; } __class(TextureCube,'laya.d3.resource.TextureCube',_super); var __proto=TextureCube.prototype; /** *@private */ __proto._onTextureLoaded=function(images){ this._images=images; var minWidth=2147483647; var minHeight=2147483647; for (var i=0;i < 6;i++){ var image=images[i]; minWidth=Math.min(minWidth,image.width); minHeight=Math.min(minHeight,image.height); } this._width=minWidth; this._height=minHeight; this._size=new Size(minWidth,minHeight); } __proto._createWebGlTexture=function(){ var texCount=6; var i=0; for (i=0;i < texCount;i++){ if (!this._images[i]){ throw "create GLTextur err:no data:"+this._images[i]; } }; var gl=WebGL.mainContext; var glTex=this._source=gl.createTexture(); var w=this._width; var h=this._height; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,glTex); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_X*/0x8515,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[0]); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_X*/0x8516,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[1]); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_Y*/0x8517,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[2]); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_Y*/0x8518,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[3]); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_Z*/0x8519,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[4]); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_Z*/0x851A,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[5]); var minFifter=this.minFifter; var magFifter=this.magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPOT=Arith.isPOT(w,h); if (isPOT){ if (this.mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this.mipmap && gl.generateMipmap(this._type); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); for (i=0;i < 6;i++){ this._images[i].onload=null; this._images[i]=null; } if (isPOT) this.memorySize=w *h *4 *(1+1 / 3)*texCount; else this.memorySize=w *h *4 *texCount; } __proto.recreateResource=function(){ if (this._url==null) return; this._createWebGlTexture(); this.completeCreate(); } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ this._onTextureLoaded(data); this.activeResource(); this._endLoaded(); } __proto.disposeResource=function(){ if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this.memorySize=0; } } /** *@inheritDoc */ __getset(0,__proto,'defaulteTexture',function(){ return SolidColorTextureCube.grayTexture; }); TextureCube.load=function(url){ return Laya.loader.create(url,null,null,TextureCube); } return TextureCube; })(BaseTexture) /** *SkinMeshRender 类用于蒙皮渲染器。 */ //class laya.d3.core.SkinnedMeshRender extends laya.d3.core.MeshRender var SkinnedMeshRender=(function(_super){ function SkinnedMeshRender(owner){ /**@private */ //this._cacheAvatar=null; /**@private */ //this._cacheMesh=null; /**@private */ //this._cacheAnimationNode=null; /**@private */ //this._cacheAnimationNodeIndex=null; /**@private */ //this._subSkinnedDatas=null; /**@private */ //this._localBoundingBoxCorners=null; /**@private */ //this._localBoundBox=null; /**@private */ //this._cacheAnimator=null; /**@private */ //this._rootIndex=0; /**@private */ //this._rootBone=null; /**用于裁剪的包围球。 */ //this.localBoundSphere=null; //.......................................兼容代码........................................ this._hasIndependentBound=true; SkinnedMeshRender.__super.call(this,owner); this._owner.transform.off(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatNeedChange); this._cacheAnimationNodeIndex=[]; this._cacheAnimationNode=[]; this._localBoundingBoxCorners=__newvec(8,null); (this._owner).meshFilter.on(/*laya.events.Event.MESH_CHANGED*/"meshchanged",this,this._$3__onMeshChanged); } __class(SkinnedMeshRender,'laya.d3.core.SkinnedMeshRender',_super); var __proto=SkinnedMeshRender.prototype; /** *@private */ __proto._getCacheAnimationNodes=function(){ var meshBoneNames=this._cacheMesh._boneNames; var binPoseCount=meshBoneNames.length; this._cacheAnimationNode.length=binPoseCount; this._cacheAnimationNodeIndex.length=binPoseCount; var avatarNodes=this._cacheAnimator._avatarNodes; var nodeMap=this._cacheAnimator._avatarNodeMap; for (var i=0;i < binPoseCount;i++){ var node=nodeMap[meshBoneNames[i]]; this._cacheAnimationNode[i]=node; this._cacheAnimationNodeIndex[i]=avatarNodes.indexOf(node); } } /** *@private */ __proto._offComputeBoneIndexToMeshEvent=function(avatar,mesh){ if (avatar.loaded){ if (!mesh.loaded) mesh.off(/*laya.events.Event.LOADED*/"loaded",this,this._getCacheAnimationNodes); }else { avatar.off(/*laya.events.Event.LOADED*/"loaded",this,this._computeBoneIndexToMeshWithAsyncMesh); } } /** *@private */ __proto._computeBoneIndexToMeshWithAsyncAvatar=function(){ if (this._cacheAvatar.loaded) this._computeBoneIndexToMeshWithAsyncMesh(); else this._cacheAvatar.once(/*laya.events.Event.LOADED*/"loaded",this,this._computeBoneIndexToMeshWithAsyncMesh); } /** *@private */ __proto._computeBoneIndexToMeshWithAsyncMesh=function(){ if (this._cacheMesh.loaded) this._getCacheAnimationNodes(); else this._cacheMesh.on(/*laya.events.Event.LOADED*/"loaded",this,this._getCacheAnimationNodes); } /** *@private */ __proto._$3__onMeshChanged=function(meshFilter,lastMesh,mesh){ this._cacheMesh=mesh; (lastMesh && !lastMesh.loaded)&& (mesh.off(/*laya.events.Event.LOADED*/"loaded",this,this._onMeshLoaded)); if (mesh.loaded) this._onMeshLoaded(mesh); else mesh.on(/*laya.events.Event.LOADED*/"loaded",this,this._onMeshLoaded); if (this._cacheAvatar){ (lastMesh)&& (this._offComputeBoneIndexToMeshEvent(this._cacheAvatar,lastMesh)); (mesh)&& (this._computeBoneIndexToMeshWithAsyncAvatar()); } } /** *@private */ __proto._onMeshLoaded=function(mesh){ var subMeshCount=mesh.subMeshCount; this._subSkinnedDatas=[]; this._subSkinnedDatas.length=subMeshCount; for (var i=0;i < subMeshCount;i++){ var subMeshDatas=this._subSkinnedDatas[i]=[]; var boneIndicesList=mesh.getSubMesh(i)._boneIndicesList; for (var j=0,m=boneIndicesList.length;j < m;j++) subMeshDatas[j]=new Float32Array(boneIndicesList[j].length *16); } } /** *@private */ __proto._setCacheAnimator=function(animator){ this._cacheAnimator=animator; (this._rootBone)&& (this._rootIndex=animator._avatarNodes.indexOf(animator._avatarNodeMap[this._rootBone])); } /** *@private */ __proto._setRootBone=function(name){ this._rootBone=name; (this._cacheAnimator)&& (this._rootIndex=this._cacheAnimator._avatarNodes.indexOf(this._cacheAnimator._avatarNodeMap[name])); } /** *@private */ __proto._setCacheAvatar=function(value){ if (this._cacheAvatar!==value){ if (this._cacheMesh){ (this._cacheAvatar)&& (this._offComputeBoneIndexToMeshEvent(this._cacheAvatar,this._cacheMesh)); this._cacheAvatar=value; if (value){ this._addShaderDefine(SkinnedMeshSprite3D.SHADERDEFINE_BONE); this._computeBoneIndexToMeshWithAsyncAvatar(); } }else { this._cacheAvatar=value; } } } /** *@inheritDoc */ __proto._calculateBoundingBox=function(){ if (this._hasIndependentBound){ if (this._cacheAnimator){ var ownerTrans=this._owner.transform; var ownWorMat=ownerTrans.worldMatrix; if (this._cacheAnimator._canCache){ var curAvatarAnimationDatas=this._cacheAnimator._curAvatarNodeDatas; Utils3D.matrix4x4MultiplyMFM((this._cacheAnimator.owner).transform.worldMatrix,curAvatarAnimationDatas[this._rootIndex],ownWorMat); }else { Utils3D.matrix4x4MultiplyMFM((this._cacheAnimator.owner).transform.worldMatrix,this._cacheAnimator._avatarNodeMap[this._rootBone].transform.getWorldMatrix(),ownWorMat); } ownerTrans.worldMatrix=ownWorMat; var rootBone=this._cacheAnimator._avatarNodeMap[this._rootBone]; if (rootBone==null || this._localBoundBox==null) this._boundingBox.toDefault(); else this._calculateBoundBoxByInitCorners(this._localBoundingBoxCorners); } }else { _super.prototype._calculateBoundingBox.call(this); } } /** *@inheritDoc */ __proto._calculateBoundingSphere=function(){ if (this._hasIndependentBound){ if (this._cacheAnimator){ var ownerTrans=this._owner.transform; var ownWorMat=ownerTrans.worldMatrix; if (this._cacheAnimator._canCache){ var curAvatarAnimationDatas=this._cacheAnimator._curAvatarNodeDatas; Utils3D.matrix4x4MultiplyMFM((this._cacheAnimator.owner).transform.worldMatrix,curAvatarAnimationDatas[this._rootIndex],ownWorMat); }else Utils3D.matrix4x4MultiplyMFM((this._cacheAnimator.owner).transform.worldMatrix,this._cacheAnimator._avatarNodeMap[this._rootBone].transform.getWorldMatrix(),ownWorMat); ownerTrans.worldMatrix=ownWorMat; var rootBone=this._cacheAnimator._avatarNodeMap[this._rootBone]; if (rootBone==null || this.localBoundSphere==null) this._boundingSphere.toDefault(); else this._calculateBoundingSphereByInitSphere(this.localBoundSphere); } }else { _super.prototype._calculateBoundingSphere.call(this); } } /** *@inheritDoc */ __proto._updateOctreeNode=function(){ var treeNode=this._treeNode; if (treeNode){ treeNode.updateObject(this); } } /** *@inheritDoc */ __proto._renderUpdate=function(projectionView){ var projViewWorld; var animator=this._cacheAnimator; var subMeshCount=this._cacheMesh.subMeshCount; var ownerTrans=this._owner.transform; if (animator){ var cache=animator._canCache; var curAvatarAnimationDatas=this._cacheAnimator._curAvatarNodeDatas; var aniOwner=animator.owner; this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,aniOwner._transform.worldMatrix); projViewWorld=aniOwner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); if (this._cacheMesh && this._cacheMesh.loaded && this._cacheAvatar && this._cacheAvatar.loaded){ var i=0,n=0; var inverseBindPoses=this._cacheMesh._inverseBindPoses; var skinnedDatas=this._cacheMesh._skinnedDatas; if (cache){ for (i=0,n=inverseBindPoses.length;i < n;i++) Utils3D._mulMatrixArray(curAvatarAnimationDatas[this._cacheAnimationNodeIndex[i]],inverseBindPoses[i],skinnedDatas,i *16); }else { for (i=0,n=inverseBindPoses.length;i < n;i++) Utils3D._mulMatrixArray(this._cacheAnimationNode[i].transform.getWorldMatrix(),inverseBindPoses[i],skinnedDatas,i *16); } for (i=0;i < subMeshCount;i++){ var boneIndicesList=this._cacheMesh.getSubMesh(i)._boneIndicesList; var boneIndicesCount=boneIndicesList.length; var subSkinnedDatas=this._subSkinnedDatas[i]; for (var j=0;j < boneIndicesCount;j++) SkinnedMeshRender._splitAnimationDatas(boneIndicesList[j],skinnedDatas,subSkinnedDatas[j]); (this._renderElements [i])._skinAnimationDatas=subSkinnedDatas; } } }else { this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,ownerTrans.worldMatrix); projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); } if (Laya3D.debugMode) this._renderRenderableBoundBox(); return true; } /** *设置包围球。 *@param value */ /** *获取包围球。 *@return 包围球。 */ __getset(0,__proto,'localBoundBox',function(){ return this._localBoundBox; },function(value){ this._localBoundBox=value; value.getCorners(this._localBoundingBoxCorners); }); /** *@inheritDoc */ __getset(0,__proto,'boundingSphere',function(){ this._calculateBoundingSphere(); return this._boundingSphere; }); /** *@inheritDoc */ __getset(0,__proto,'boundingBox',function(){ this._calculateBoundingBox(); return this._boundingBox; }); /** *@inheritDoc */ __getset(0,__proto,'boundingBoxCenter',function(){ var boundBox=this.boundingBox; Vector3.add(boundBox.min,boundBox.max,this._boundingBoxCenter); Vector3.scale(this._boundingBoxCenter,0.5,this._boundingBoxCenter); return this._boundingBoxCenter; }); SkinnedMeshRender._splitAnimationDatas=function(indices,bonesData,subAnimationDatas){ for (var i=0,n=indices.length,ii=0;i < n;i++){ var index=indices[i] << 4; for (var j=0;j < 16;j++,ii++) subAnimationDatas[ii]=bonesData[index+j]; } } return SkinnedMeshRender; })(MeshRender) /** *BaseCamera 类用于创建摄像机的父类。 */ //class laya.d3.core.BaseCamera extends laya.d3.core.Sprite3D var BaseCamera=(function(_super){ function BaseCamera(nearPlane,farPlane){ /**@private */ //this._tempVector3=null; /**@private 位置。*/ //this._position=null; /**@private 向上向量。*/ //this._up=null; /**@private 前向量。*/ //this._forward=null; /**@private 右向量。*/ //this._right=null; /**@private 渲染顺序。*/ //this._renderingOrder=0; /**@private 渲染目标尺寸。*/ //this._renderTargetSize=null; /**@private 近裁剪面。*/ //this._nearPlane=NaN; /**@private 远裁剪面。*/ //this._farPlane=NaN; /**@private 视野。*/ //this._fieldOfView=NaN; /**@private 正交投影的垂直尺寸。*/ //this._orthographicVerticalSize=NaN; /**@private 天空。*/ //this._sky=null; /**@private */ //this._orthographic=false; /**@private 渲染目标。*/ //this._renderTarget=null; /**@private 是否使用用户自定义投影矩阵,如果使用了用户投影矩阵,摄像机投影矩阵相关的参数改变则不改变投影矩阵的值,需调用ResetProjectionMatrix方法。*/ //this._useUserProjectionMatrix=false; /**@private 表明视口是否使用裁剪空间表达。*/ //this._viewportExpressedInClipSpace=false; /**清楚标记。*/ //this.clearFlag=0; /**摄像机的清除颜色。*/ //this.clearColor=null; /**可视遮罩图层。 */ //this.cullingMask=0; /**渲染时是否用遮挡剔除。 */ //this.useOcclusionCulling=false; BaseCamera.__super.call(this); (nearPlane===void 0)&& (nearPlane=0.3); (farPlane===void 0)&& (farPlane=1000); this._tempVector3=new Vector3(); this._position=new Vector3(); this._up=new Vector3(); this._forward=new Vector3(); this._right=new Vector3(); this._fieldOfView=60; this._useUserProjectionMatrix=false; this._orthographic=false; this._viewportExpressedInClipSpace=true; this._renderTargetSize=Size.fullScreen; this._orthographicVerticalSize=10; this.renderingOrder=0; this._nearPlane=nearPlane; this._farPlane=farPlane; this.cullingMask=2147483647; this.clearFlag=/*CLASS CONST:laya.d3.core.BaseCamera.CLEARFLAG_SOLIDCOLOR*/0; this.useOcclusionCulling=true; this._calculateProjectionMatrix(); Laya.stage.on(/*laya.events.Event.RESIZE*/"resize",this,this._onScreenSizeChanged); } __class(BaseCamera,'laya.d3.core.BaseCamera',_super); var __proto=BaseCamera.prototype; /** *通过RenderingOrder属性对摄像机机型排序。 */ __proto._sortCamerasByRenderingOrder=function(){ if (this._displayedInStage){ var cameraPool=this.scene._cameraPool; var n=cameraPool.length-1; for (var i=0;i < n;i++){ if (cameraPool[i].renderingOrder > cameraPool[n].renderingOrder){ var tempCamera=cameraPool[i]; cameraPool[i]=cameraPool[n]; cameraPool[n]=tempCamera; } } } } /** *@private */ __proto._calculateProjectionMatrix=function(){} /** *@private */ __proto._onScreenSizeChanged=function(){ this._calculateProjectionMatrix(); } /** *@private */ __proto._prepareCameraToRender=function(){ Layer._currentCameraCullingMask=this.cullingMask; var cameraSV=this._shaderValues; cameraSV.setValue(/*CLASS CONST:laya.d3.core.BaseCamera.CAMERAPOS*/0,this.transform.position.elements); cameraSV.setValue(/*CLASS CONST:laya.d3.core.BaseCamera.CAMERADIRECTION*/5,this.forward.elements); cameraSV.setValue(/*CLASS CONST:laya.d3.core.BaseCamera.CAMERAUP*/6,this.up.elements); } /** *@private */ __proto._prepareCameraViewProject=function(viewMatrix,projectMatrix){ var cameraSV=this._shaderValues; cameraSV.setValue(/*CLASS CONST:laya.d3.core.BaseCamera.VIEWMATRIX*/1,viewMatrix.elements); cameraSV.setValue(/*CLASS CONST:laya.d3.core.BaseCamera.PROJECTMATRIX*/2,projectMatrix.elements); } /** *@private */ __proto._renderCamera=function(gl,state,scene){} /** *增加可视图层。 *@param layer 图层。 */ __proto.addLayer=function(layer){ if (layer.number===29 || layer.number==30) return; this.cullingMask=this.cullingMask | layer.mask; } /** *移除可视图层。 *@param layer 图层。 */ __proto.removeLayer=function(layer){ if (layer.number===29 || layer.number==30) return; this.cullingMask=this.cullingMask & ~layer.mask; } /** *增加所有图层。 */ __proto.addAllLayers=function(){ this.cullingMask=2147483647; } /** *移除所有图层。 */ __proto.removeAllLayers=function(){ this.cullingMask=0 | Layer.getLayerByNumber(29).mask | Layer.getLayerByNumber(30).mask; } __proto.ResetProjectionMatrix=function(){ this._useUserProjectionMatrix=false; this._calculateProjectionMatrix(); } /** *向前移动。 *@param distance 移动距离。 */ __proto.moveForward=function(distance){ this._tempVector3.elements[0]=this._tempVector3.elements[1]=0; this._tempVector3.elements[2]=distance; this.transform.translate(this._tempVector3); } /** *向右移动。 *@param distance 移动距离。 */ __proto.moveRight=function(distance){ this._tempVector3.elements[1]=this._tempVector3.elements[2]=0; this._tempVector3.elements[0]=distance; this.transform.translate(this._tempVector3); } /** *向上移动。 *@param distance 移动距离。 */ __proto.moveVertical=function(distance){ this._tempVector3.elements[0]=this._tempVector3.elements[2]=0; this._tempVector3.elements[1]=distance; this.transform.translate(this._tempVector3,false); } //}// BoundingFrustumWorldSpace __proto._addSelfRenderObjects=function(){ var cameraPool=this.scene._cameraPool; var cmaeraCount=cameraPool.length; if (cmaeraCount > 0){ for (var i=cmaeraCount-1;i >=0;i--){ if (this.renderingOrder <=cameraPool[i].renderingOrder){ cameraPool.splice(i+1,0,this); break ; } } }else { cameraPool.push(this); if (this.scene.conchModel){ this.scene.conchModel.setCurrentCamera(this.conchModel); } } } __proto._clearSelfRenderObjects=function(){ var cameraPool=this.scene._cameraPool; cameraPool.splice(cameraPool.indexOf(this),1); } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); (this._sky)&& (this._sky.destroy()); this.renderTarget=null; Laya.stage.off(/*laya.events.Event.RESIZE*/"resize",this,this._onScreenSizeChanged); _super.prototype.destroy.call(this,destroyChild); } /**设置天空。*/ /**获取天空。*/ __getset(0,__proto,'sky',function(){ return this._sky; },function(value){ this._sky=value; value._ownerCamera=this; }); /** *获取前向量。 *@return 前向量。 */ __getset(0,__proto,'forward',function(){ var worldMatrixe=this.transform.worldMatrix.elements; var forwarde=this._forward.elements; forwarde[0]=-worldMatrixe[8]; forwarde[1]=-worldMatrixe[9]; forwarde[2]=-worldMatrixe[10]; return this._forward; }); /**获取位置。*/ __getset(0,__proto,'position',function(){ var worldMatrixe=this.transform.worldMatrix.elements; var positione=this._position.elements; positione[0]=worldMatrixe[12]; positione[1]=worldMatrixe[13]; positione[2]=worldMatrixe[14]; return this._position; }); /** *设置渲染场景的渲染目标。 *@param value 渲染场景的渲染目标。 */ /** *获取渲染场景的渲染目标。 *@return 渲染场景的渲染目标。 */ __getset(0,__proto,'renderTarget',function(){ return this._renderTarget; },function(value){ this._renderTarget=value; if (value !=null) this._renderTargetSize=value.size; }); /** *获取上向量。 *@return 上向量。 */ __getset(0,__proto,'up',function(){ var worldMatrixe=this.transform.worldMatrix.elements; var upe=this._up.elements; upe[0]=worldMatrixe[4]; upe[1]=worldMatrixe[5]; upe[2]=worldMatrixe[6]; return this._up; }); /** *获取右向量。 *@return 右向量。 */ __getset(0,__proto,'right',function(){ var worldMatrixe=this.transform.worldMatrix.elements; var righte=this._right.elements; righte[0]=worldMatrixe[0]; righte[1]=worldMatrixe[1]; righte[2]=worldMatrixe[2]; return this._right; }); /** *设置渲染目标的尺寸 *@param value 渲染目标的尺寸。 */ /** *获取渲染目标的尺寸 *@return 渲染目标的尺寸。 */ __getset(0,__proto,'renderTargetSize',function(){ return this._renderTargetSize; },function(value){ if (this.renderTarget !=null && this._renderTargetSize !=value){} this._renderTargetSize=value; this._calculateProjectionMatrix(); }); /** *设置视野。 *@param value 视野。 */ /** *获取视野。 *@return 视野。 */ __getset(0,__proto,'fieldOfView',function(){ return this._fieldOfView; },function(value){ this._fieldOfView=value; this._calculateProjectionMatrix(); }); /** *设置近裁面。 *@param value 近裁面。 */ /** *获取近裁面。 *@return 近裁面。 */ __getset(0,__proto,'nearPlane',function(){ return this._nearPlane; },function(value){ this._nearPlane=value; this._calculateProjectionMatrix(); }); /** *设置远裁面。 *@param value 远裁面。 */ /** *获取远裁面。 *@return 远裁面。 */ __getset(0,__proto,'farPlane',function(){ return this._farPlane; },function(vaule){ this._farPlane=vaule; this._calculateProjectionMatrix(); }); /** *设置是否正交投影矩阵。 *@param 是否正交投影矩阵。 */ /** *获取是否正交投影矩阵。 *@return 是否正交投影矩阵。 */ __getset(0,__proto,'orthographic',function(){ return this._orthographic; },function(vaule){ this._orthographic=vaule; this._calculateProjectionMatrix(); }); /** *设置正交投影垂直矩阵尺寸。 *@param 正交投影垂直矩阵尺寸。 */ /** *获取正交投影垂直矩阵尺寸。 *@return 正交投影垂直矩阵尺寸。 */ __getset(0,__proto,'orthographicVerticalSize',function(){ return this._orthographicVerticalSize; },function(vaule){ this._orthographicVerticalSize=vaule; this._calculateProjectionMatrix(); }); __getset(0,__proto,'renderingOrder',function(){ return this._renderingOrder; },function(value){ this._renderingOrder=value; this._sortCamerasByRenderingOrder(); }); BaseCamera.CAMERAPOS=0; BaseCamera.VIEWMATRIX=1; BaseCamera.PROJECTMATRIX=2; BaseCamera.VPMATRIX=3; BaseCamera.VPMATRIX_NO_TRANSLATE=4; BaseCamera.CAMERADIRECTION=5; BaseCamera.CAMERAUP=6; BaseCamera.ENVIRONMENTDIFFUSE=7; BaseCamera.ENVIRONMENTSPECULAR=8; BaseCamera.SIMLODINFO=9; BaseCamera.DIFFUSEIRRADMATR=10; BaseCamera.DIFFUSEIRRADMATG=11; BaseCamera.DIFFUSEIRRADMATB=12; BaseCamera.HDREXPOSURE=13; BaseCamera.RENDERINGTYPE_DEFERREDLIGHTING="DEFERREDLIGHTING"; BaseCamera.RENDERINGTYPE_FORWARDRENDERING="FORWARDRENDERING"; BaseCamera.CLEARFLAG_SOLIDCOLOR=0; BaseCamera.CLEARFLAG_SKY=1; BaseCamera.CLEARFLAG_DEPTHONLY=2; BaseCamera.CLEARFLAG_NONE=3; __static(BaseCamera, ['_invertYScaleMatrix',function(){return this._invertYScaleMatrix=new Matrix4x4(1,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,1);},'_invertYProjectionMatrix',function(){return this._invertYProjectionMatrix=new Matrix4x4();},'_invertYProjectionViewMatrix',function(){return this._invertYProjectionViewMatrix=new Matrix4x4();} ]); return BaseCamera; })(Sprite3D) /** *RenderableSprite3D 类用于可渲染3D精灵的父类,抽象类不允许实例。 */ //class laya.d3.core.RenderableSprite3D extends laya.d3.core.Sprite3D var RenderableSprite3D=(function(_super){ function RenderableSprite3D(name){ /**@private */ this._render=null; /**@private */ this._geometryFilter=null; RenderableSprite3D.__super.call(this,name) } __class(RenderableSprite3D,'laya.d3.core.RenderableSprite3D',_super); var __proto=RenderableSprite3D.prototype; /** *@private */ __proto._addToInitStaticBatchManager=function(){} /** *@inheritDoc */ __proto._setBelongScene=function(scene){ _super.prototype._setBelongScene.call(this,scene); scene._renderableSprite3Ds.push(this); this._render._applyLightMapParams(); } /** *@inheritDoc */ __proto._setUnBelongScene=function(){ var renderableSprite3Ds=this._scene._renderableSprite3Ds; var index=renderableSprite3Ds.indexOf(this); renderableSprite3Ds.splice(index,1); this._render._removeShaderDefine(laya.d3.core.RenderableSprite3D.SAHDERDEFINE_LIGHTMAP); _super.prototype._setUnBelongScene.call(this); } /** *@inheritDoc */ __proto._update=function(state){ state.owner=this; if (this._activeInHierarchy){ this._updateComponents(state); this._render._updateOctreeNode(); this._lateUpdateComponents(state); Stat.spriteCount++; this._childs.length && this._updateChilds(state); } } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._render._destroy(); this._render=null; } RenderableSprite3D.__init__=function(){ RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV=RenderableSprite3D.shaderDefines.registerDefine("SCALEOFFSETLIGHTINGMAPUV"); RenderableSprite3D.SAHDERDEFINE_LIGHTMAP=RenderableSprite3D.shaderDefines.registerDefine("LIGHTMAP"); } RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV=0x2; RenderableSprite3D.SAHDERDEFINE_LIGHTMAP=0x4; RenderableSprite3D.LIGHTMAPSCALEOFFSET=2; RenderableSprite3D.LIGHTMAP=3; __static(RenderableSprite3D, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1();} ]); return RenderableSprite3D; })(Sprite3D) /** *LightSprite 类用于创建灯光的父类。 */ //class laya.d3.core.light.LightSprite extends laya.d3.core.Sprite3D var LightSprite=(function(_super){ function LightSprite(){ /**@private */ this._intensityColor=null; /**@private */ this._intensity=NaN; /**@private */ this._shadow=false; /**@private */ this._shadowFarPlane=0; /**@private */ this._shadowMapSize=0; /**@private */ this._shadowMapCount=0; /**@private */ this._shadowMapPCFType=0; /**@private */ this._parallelSplitShadowMap=null; /**@private */ this._lightmapBakedType=0; /**灯光颜色。 */ this.color=null; LightSprite.__super.call(this); this._intensity=1.0; this._intensityColor=new Vector3(); this.color=new Vector3(1.0,1.0,1.0); this._shadow=false; this._shadowFarPlane=8; this._shadowMapSize=512; this._shadowMapCount=1; this._shadowMapPCFType=0; this._lightmapBakedType=LightSprite.LIGHTMAPBAKEDTYPE_REALTIME; } __class(LightSprite,'laya.d3.core.light.LightSprite',_super); var __proto=LightSprite.prototype; /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,nodeData){ var colorData=customProps.color; var colorE=this.color.elements; colorE[0]=colorData[0]; colorE[1]=colorData[1]; colorE[2]=colorData[2]; } /** *@inheritDoc */ __proto._addSelfRenderObjects=function(){ (this.lightmapBakedType!==LightSprite.LIGHTMAPBAKEDTYPE_BAKED)&& (this._scene._addLight(this)); } /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ (this.lightmapBakedType!==LightSprite.LIGHTMAPBAKEDTYPE_BAKED)&& (this._scene._removeLight(this)); } /** *更新灯光相关渲染状态参数。 *@param state 渲染状态参数。 */ __proto._prepareToScene=function(state){ return false; } /** *设置灯光烘培类型。 */ /** *获取灯光烘培类型。 */ __getset(0,__proto,'lightmapBakedType',function(){ return this._lightmapBakedType; },function(value){ if (this._lightmapBakedType!==value){ this._lightmapBakedType=value; if (this._activeInHierarchy){ if (value!==LightSprite.LIGHTMAPBAKEDTYPE_BAKED) this._scene._addLight(this); else this._scene._removeLight(this); } } }); /** *设置阴影PCF类型。 *@param value PCF类型。 */ /** *获取阴影PCF类型。 *@return PCF类型。 */ __getset(0,__proto,'shadowPCFType',function(){ return this._shadowMapPCFType; },function(value){ this._shadowMapPCFType=value; (this._parallelSplitShadowMap)&& (this._parallelSplitShadowMap.setPCFType(value)); }); /** *设置灯光强度。 *@param value 灯光强度 */ /** *获取灯光强度。 *@return 灯光强度 */ __getset(0,__proto,'intensity',function(){ return this._intensity; },function(value){ this._intensity=value; }); /** *设置是否产生阴影。 *@param value 是否产生阴影。 */ /** *获取是否产生阴影。 *@return 是否产生阴影。 */ __getset(0,__proto,'shadow',function(){ return this._shadow; },function(value){ throw new Error("LightSprite: must override it."); }); /** *设置阴影最远范围。 *@param value 阴影最远范围。 */ /** *获取阴影最远范围。 *@return 阴影最远范围。 */ __getset(0,__proto,'shadowDistance',function(){ return this._shadowFarPlane; },function(value){ this._shadowFarPlane=value; (this._parallelSplitShadowMap)&& (this._parallelSplitShadowMap.setFarDistance(value)); }); /** *设置阴影分段数。 *@param value 阴影分段数。 */ /** *获取阴影分段数。 *@return 阴影分段数。 */ __getset(0,__proto,'shadowPSSMCount',function(){ return this._shadowMapCount; },function(value){ this._shadowMapCount=value; (this._parallelSplitShadowMap)&& (this._parallelSplitShadowMap.PSSMNum=value); }); /** *设置阴影贴图尺寸。 *@param value 阴影贴图尺寸。 */ /** *获取阴影贴图尺寸。 *@return 阴影贴图尺寸。 */ __getset(0,__proto,'shadowResolution',function(){ return this._shadowMapSize; },function(value){ this._shadowMapSize=value; (this._parallelSplitShadowMap)&& (this._parallelSplitShadowMap.setShadowMapTextureSize(value)); }); /** *设置灯光的漫反射颜色。 *@param value 灯光的漫反射颜色。 */ /** *获取灯光的漫反射颜色。 *@return 灯光的漫反射颜色。 */ __getset(0,__proto,'diffuseColor',function(){ console.log("LightSprite: discard property,please use color property instead."); return this.color; },function(value){ console.log("LightSprite: discard property,please use color property instead."); this.color=value; }); LightSprite.LIGHTMAPBAKEDTYPE_REALTIME=0; LightSprite.LIGHTMAPBAKEDTYPE_MIXED=1; LightSprite.LIGHTMAPBAKEDTYPE_BAKED=2; return LightSprite; })(Sprite3D) /** *Terrain 类用于创建地块。 */ //class laya.d3.terrain.Terrain extends laya.d3.core.Sprite3D var Terrain=(function(_super){ function Terrain(terrainRes){ this._terrainRes=null; this._lightmapScaleOffset=null; Terrain.__super.call(this); this._lightmapScaleOffset=new Vector4(1,1,0,0); if (terrainRes){ this._terrainRes=terrainRes; if (terrainRes.loaded) this.buildTerrain(terrainRes); else terrainRes.once(/*laya.events.Event.LOADED*/"loaded",this,this.buildTerrain); } } __class(Terrain,'laya.d3.terrain.Terrain',_super); var __proto=Terrain.prototype; /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ this.terrainRes=Loader.getRes(innerResouMap[customProps.dataPath]); var lightmapIndex=customProps.lightmapIndex; if (lightmapIndex !=null) this.setLightmapIndex(lightmapIndex); var lightmapScaleOffsetArray=customProps.lightmapScaleOffset; if (lightmapScaleOffsetArray) this.setLightmapScaleOffset(new Vector4(lightmapScaleOffsetArray[0],lightmapScaleOffsetArray[1],lightmapScaleOffsetArray[2],lightmapScaleOffsetArray[3])); } __proto.setLightmapIndex=function(value){ for (var i=0;i < this._childs.length;i++){ var terrainChunk=this._childs[i]; terrainChunk.terrainRender.lightmapIndex=value; } } __proto.setLightmapScaleOffset=function(value){ if (!value)return; value.cloneTo(this._lightmapScaleOffset); for (var i=0;i < this._childs.length;i++){ var terrainChunk=this._childs[i]; terrainChunk.terrainRender.lightmapScaleOffset=this._lightmapScaleOffset; } } __proto.disableLight=function(){ for (var i=0,n=this._childs.length;i < n;i++){ var terrainChunk=this._childs[i]; for (var j=0,m=terrainChunk._render.sharedMaterials.length;j < m;j++){ var terrainMaterial=terrainChunk._render.sharedMaterials [j]; terrainMaterial.disableLight(); } } } __proto.buildTerrain=function(terrainRes){ var chunkNumX=terrainRes._chunkNumX; var chunkNumZ=terrainRes._chunkNumZ; var heightData=terrainRes._heightData; var n=0; for (var i=0;i < chunkNumZ;i++){ for (var j=0;j < chunkNumX;j++){ var terrainChunk=new TerrainChunk(j,i,terrainRes._gridSize,heightData._terrainHeightData,heightData._width,heightData._height,terrainRes._cameraCoordinateInverse); var chunkInfo=terrainRes._chunkInfos[n++]; for (var k=0;k < chunkInfo.alphaMap.length;k++){ var nNum=chunkInfo.detailID[k].length; var sDetialTextureUrl1=(nNum > 0)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][0]].diffuseTexture :null; var sDetialTextureUrl2=(nNum > 1)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][1]].diffuseTexture :null; var sDetialTextureUrl3=(nNum > 2)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][2]].diffuseTexture :null; var sDetialTextureUrl4=(nNum > 3)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][3]].diffuseTexture :null; var detialScale1=(nNum > 0)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][0]].scale :null; var detialScale2=(nNum > 1)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][1]].scale :null; var detialScale3=(nNum > 2)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][2]].scale :null; var detialScale4=(nNum > 3)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][3]].scale :null; terrainChunk.buildRenderElementAndMaterial(nNum,chunkInfo.normalMap,chunkInfo.alphaMap[k],sDetialTextureUrl1,sDetialTextureUrl2,sDetialTextureUrl3,sDetialTextureUrl4,terrainRes._materialInfo.ambientColor,terrainRes._materialInfo.diffuseColor,terrainRes._materialInfo.specularColor,detialScale1 ? detialScale1.x :1,detialScale1 ? detialScale1.y :1,detialScale2 ? detialScale2.x :1,detialScale2 ? detialScale2.y :1,detialScale3 ? detialScale3.x :1,detialScale3 ? detialScale3.y :1,detialScale4 ? detialScale4.x :1,detialScale4 ? detialScale4.y :1); } terrainChunk.terrainRender.receiveShadow=true; terrainChunk.terrainRender.lightmapScaleOffset=this._lightmapScaleOffset; this.addChild(terrainChunk); } } } /** *获取地形X轴长度。 *@return 地形X轴长度。 */ __proto.width=function(){ return this._terrainRes._chunkNumX *TerrainLeaf.CHUNK_GRID_NUM *this._terrainRes._gridSize; } /** *获取地形Z轴长度。 *@return 地形Z轴长度。 */ __proto.depth=function(){ return this._terrainRes._chunkNumZ *TerrainLeaf.CHUNK_GRID_NUM *this._terrainRes._gridSize; } /** *获取地形高度。 *@param x X轴坐标。 *@param z Z轴坐标。 */ __proto.getHeightXZ=function(x,z){ if (!this._terrainRes || !this._terrainRes.loaded) return NaN; x-=this.transform.position.x; z-=this.transform.position.z; if (!Terrain.__VECTOR3__){ Terrain.__VECTOR3__=new Vector3(); } Terrain.__VECTOR3__.elements[0]=x; Terrain.__VECTOR3__.elements[1]=0; Terrain.__VECTOR3__.elements[2]=z; Vector3.transformV3ToV3(Terrain.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX_INV__,Terrain.__VECTOR3__); x=Terrain.__VECTOR3__.elements[0]; z=Terrain.__VECTOR3__.elements[2]; if (x < 0 || x > this.width()|| z < 0 || z > this.depth()) return NaN; var gridSize=this._terrainRes._gridSize; var nIndexX=parseInt(""+x / gridSize); var nIndexZ=parseInt(""+z / gridSize); var offsetX=x-nIndexX *gridSize; var offsetZ=z-nIndexZ *gridSize; var h1=NaN; var h2=NaN; var h3=NaN; var u=NaN; var v=NaN; var heightData=this._terrainRes._heightData; if (offsetX+offsetZ > gridSize){ h1=heightData._terrainHeightData[(nIndexZ+1-1)*heightData._width+nIndexX+1]; h2=heightData._terrainHeightData[(nIndexZ+1-1)*heightData._width+nIndexX]; h3=heightData._terrainHeightData[(nIndexZ-1)*heightData._width+nIndexX+1]; u=(gridSize-offsetX)/ gridSize; v=(gridSize-offsetZ)/ gridSize; return h1+(h2-h1)*u+(h3-h1)*v; }else { h1=heightData._terrainHeightData[Math.max(0.0,nIndexZ-1)*heightData._width+nIndexX]; h2=heightData._terrainHeightData[Math.min(heightData._width *heightData._height-1,(nIndexZ+1-1)*heightData._width+nIndexX)]; h3=heightData._terrainHeightData[Math.min(heightData._width *heightData._height-1,Math.max(0.0,nIndexZ-1)*heightData._width+nIndexX+1)]; u=offsetX / gridSize; v=offsetZ / gridSize; return h1+(h2-h1)*v+(h3-h1)*u; } } __getset(0,__proto,'terrainRes',null,function(value){ if (value){ this._terrainRes=value; if (value.loaded) this.buildTerrain(value); else value.once(/*laya.events.Event.LOADED*/"loaded",this,this.buildTerrain); } }); Terrain.load=function(url){ return Laya.loader.create(url,null,null,Terrain,null,1,false); } Terrain.RENDER_LINE_MODEL=false; Terrain.LOD_TOLERANCE_VALUE=4; Terrain.LOD_DISTANCE_FACTOR=2.0; Terrain.__VECTOR3__=null; return Terrain; })(Sprite3D) /** *Sphere 类用于创建方体。 */ //class laya.d3.resource.models.BoxMesh extends laya.d3.resource.models.PrimitiveMesh var BoxMesh=(function(_super){ function BoxMesh(long,width,height){ /**@private */ this._long=NaN; /**@private */ this._width=NaN; /**@private */ this._height=NaN; (long===void 0)&& (long=1); (width===void 0)&& (width=1); (height===void 0)&& (height=1); BoxMesh.__super.call(this); this._long=long; this._width=width; this._height=height; this.activeResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(BoxMesh,'laya.d3.resource.models.BoxMesh',_super); var __proto=BoxMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=24; this._numberIndices=36; var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var halfLong=this._long / 2; var halfHeight=this._height / 2; var halfWidth=this._width / 2; var vertices=new Float32Array([ -halfLong,halfHeight,-halfWidth,0,1,0,0,0,halfLong,halfHeight,-halfWidth,0,1,0,1,0,halfLong,halfHeight,halfWidth,0,1,0,1,1,-halfLong,halfHeight,halfWidth,0,1,0,0,1, -halfLong,-halfHeight,-halfWidth,0,-1,0,0,1,halfLong,-halfHeight,-halfWidth,0,-1,0,1,1,halfLong,-halfHeight,halfWidth,0,-1,0,1,0,-halfLong,-halfHeight,halfWidth,0,-1,0,0,0, -halfLong,halfHeight,-halfWidth,-1,0,0,0,0,-halfLong,halfHeight,halfWidth,-1,0,0,1,0,-halfLong,-halfHeight,halfWidth,-1,0,0,1,1,-halfLong,-halfHeight,-halfWidth,-1,0,0,0,1, halfLong,halfHeight,-halfWidth,1,0,0,1,0,halfLong,halfHeight,halfWidth,1,0,0,0,0,halfLong,-halfHeight,halfWidth,1,0,0,0,1,halfLong,-halfHeight,-halfWidth,1,0,0,1,1, -halfLong,halfHeight,halfWidth,0,0,1,0,0,halfLong,halfHeight,halfWidth,0,0,1,1,0,halfLong,-halfHeight,halfWidth,0,0,1,1,1,-halfLong,-halfHeight,halfWidth,0,0,1,0,1, -halfLong,halfHeight,-halfWidth,0,0,-1,1,0,halfLong,halfHeight,-halfWidth,0,0,-1,0,0,halfLong,-halfHeight,-halfWidth,0,0,-1,0,1,-halfLong,-halfHeight,-halfWidth,0,0,-1,1,1]); var indices=new Uint16Array([ 0,1,2,2,3,0, 4,7,6,6,5,4, 8,9,10,10,11,8, 12,15,14,14,13,12, 16,17,18,18,19,16, 20,23,22,22,21,20]); this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置长度(改变此属性会重新生成顶点和索引) *@param value 长度 */ /** *返回长度 *@return 长 */ __getset(0,__proto,'long',function(){ return this._long; },function(value){ if (this._long!==value){ this._long=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度(改变此属性会重新生成顶点和索引) *@param value 宽度 */ /** *返回宽度 *@return 宽 */ __getset(0,__proto,'width',function(){ return this._width; },function(value){ if (this._width!==value){ this._width=value; this.releaseResource(); this.activeResource(); } }); /** *设置高度(改变此属性会重新生成顶点和索引) *@param value 高度 */ /** *返回高度 *@return 高 */ __getset(0,__proto,'height',function(){ return this._height; },function(value){ if (this._height!==value){ this._height=value; this.releaseResource(); this.activeResource(); } }); return BoxMesh; })(PrimitiveMesh) /** *CapsuleMesh 类用于创建胶囊体。 */ //class laya.d3.resource.models.CapsuleMesh extends laya.d3.resource.models.PrimitiveMesh var CapsuleMesh=(function(_super){ function CapsuleMesh(radius,height,stacks,slices){ /**@private */ this._radius=NaN; /**@private */ this._height=NaN; /**@private */ this._slices=0; /**@private */ this._stacks=0; (radius===void 0)&& (radius=0.5); (height===void 0)&& (height=2); (stacks===void 0)&& (stacks=16); (slices===void 0)&& (slices=32); CapsuleMesh.__super.call(this); this._radius=radius; this._height=height < radius *2 ? radius *2 :height; this._stacks=stacks; this._slices=slices; this.recreateResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(CapsuleMesh,'laya.d3.resource.models.CapsuleMesh',_super); var __proto=CapsuleMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=(this._stacks+1)*(this.slices+1)*2+(this._slices+1)*2; this._numberIndices=(3 *this._stacks *(this._slices+1))*2 *2+2 *this._slices *3; var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var indices=new Uint16Array(this._numberIndices); var stackAngle=(Math.PI / 2.0)/ this._stacks; var sliceAngle=(Math.PI *2.0)/ this._slices; var hcHeight=this._height / 2-this._radius; var posX=0; var posY=0; var posZ=0; var vc=0; var ic=0; var verticeCount=0; var stack=0,slice=0; for (stack=0;stack <=this._stacks;stack++){ for (slice=0;slice <=this._slices;slice++){ posX=this._radius *Math.cos(stack *stackAngle)*Math.cos(slice *sliceAngle+Math.PI); posY=this._radius *Math.sin(stack *stackAngle); posZ=this._radius *Math.cos(stack *stackAngle)*Math.sin(slice *sliceAngle+Math.PI); vertices[vc++]=posX; vertices[vc++]=posY+hcHeight; vertices[vc++]=posZ; vertices[vc++]=posX; vertices[vc++]=posY; vertices[vc++]=posZ; vertices[vc++]=1-slice / this._slices; vertices[vc++]=(1-stack / this._stacks)*((Math.PI *this._radius / 2)/ (this._height+Math.PI *this._radius)); if (stack < this._stacks){ indices[ic++]=(stack *(this._slices+1))+slice+(this._slices+1); indices[ic++]=(stack *(this._slices+1))+slice; indices[ic++]=(stack *(this._slices+1))+slice+1; indices[ic++]=(stack *(this._slices+1))+slice+(this._slices); indices[ic++]=(stack *(this._slices+1))+slice; indices[ic++]=(stack *(this._slices+1))+slice+(this._slices+1); } } } verticeCount+=(this._stacks+1)*(this._slices+1); for (stack=0;stack <=this._stacks;stack++){ for (slice=0;slice <=this._slices;slice++){ posX=this._radius *Math.cos(stack *stackAngle)*Math.cos(slice *sliceAngle+Math.PI); posY=this._radius *Math.sin(-stack *stackAngle); posZ=this._radius *Math.cos(stack *stackAngle)*Math.sin(slice *sliceAngle+Math.PI); vertices[vc++]=posX; vertices[vc++]=posY-hcHeight; vertices[vc++]=posZ; vertices[vc++]=posX; vertices[vc++]=posY; vertices[vc++]=posZ; vertices[vc++]=1-slice / this._slices; vertices[vc++]=((stack / this._stacks)*(Math.PI *this._radius / 2)+(this._height+Math.PI *this._radius / 2))/ (this._height+Math.PI *this._radius); if (stack < this._stacks){ indices[ic++]=verticeCount+(stack *(this._slices+1))+slice; indices[ic++]=verticeCount+(stack *(this._slices+1))+slice+(this._slices+1); indices[ic++]=verticeCount+(stack *(this._slices+1))+slice+1; indices[ic++]=verticeCount+(stack *(this._slices+1))+slice; indices[ic++]=verticeCount+(stack *(this._slices+1))+slice+(this._slices); indices[ic++]=verticeCount+(stack *(this._slices+1))+slice+(this._slices+1); } } } verticeCount+=(this._stacks+1)*(this._slices+1); for (slice=0;slice <=this._slices;slice++){ posX=this._radius *Math.cos(slice *sliceAngle+Math.PI); posY=hcHeight; posZ=this._radius *Math.sin(slice *sliceAngle+Math.PI); vertices[vc++]=posX; vertices[vc+(this._slices+1)*8-1]=posX; vertices[vc++]=posY; vertices[vc+(this._slices+1)*8-1]=-posY; vertices[vc++]=posZ; vertices[vc+(this._slices+1)*8-1]=posZ; vertices[vc++]=posX; vertices[vc+(this._slices+1)*8-1]=posX; vertices[vc++]=0; vertices[vc+(this._slices+1)*8-1]=0; vertices[vc++]=posZ; vertices[vc+(this._slices+1)*8-1]=posZ; vertices[vc++]=1-slice *1 / this._slices; vertices[vc+(this._slices+1)*8-1]=1-slice *1 / this._slices; vertices[vc++]=(Math.PI *this._radius / 2)/ (this._height+Math.PI *this._radius); vertices[vc+(this._slices+1)*8-1]=(Math.PI *this._radius / 2+this._height)/ (this._height+Math.PI *this._radius); } for (slice=0;slice < this._slices;slice++){ indices[ic++]=slice+verticeCount+(this._slices+1); indices[ic++]=slice+verticeCount+1; indices[ic++]=slice+verticeCount; indices[ic++]=slice+verticeCount+(this._slices+1); indices[ic++]=slice+verticeCount+(this._slices+1)+1; indices[ic++]=slice+verticeCount+1; } verticeCount+=2 *(this._slices+1); this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置半径(改变此属性会重新生成顶点和索引) *@param value 半径 */ /** *返回半径 *@return 半径 */ __getset(0,__proto,'radius',function(){ return this._radius; },function(value){ if (this._radius!==value){ this._radius=value; this.releaseResource(); this.activeResource(); } }); /** *设置高度(改变此属性会重新生成顶点和索引) *@param value 高度 */ /** *返回高度 *@return 高度 */ __getset(0,__proto,'height',function(){ return this._height; },function(value){ if (this._height!==value){ this._height=value; this.releaseResource(); this.activeResource(); } }); /** *设置高度分段(改变此属性会重新生成顶点和索引) *@param value高度分段 */ /** *获取高度分段 *@return 高度分段 */ __getset(0,__proto,'stacks',function(){ return this._stacks; },function(value){ if (this._stacks!==value){ this._stacks=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度分段(改变此属性会重新生成顶点和索引) *@param value 宽度分段 */ /** *获取宽度分段 *@return 宽度分段 */ __getset(0,__proto,'slices',function(){ return this._slices; },function(value){ if (this._slices!==value){ this._slices=value; this.releaseResource(); this.activeResource(); } }); return CapsuleMesh; })(PrimitiveMesh) /** *CylinderMesh 类用于创建圆柱体。 */ //class laya.d3.resource.models.CylinderMesh extends laya.d3.resource.models.PrimitiveMesh var CylinderMesh=(function(_super){ function CylinderMesh(radius,height,slices){ /**@private */ this._radius=NaN; /**@private */ this._height=NaN; /**@private */ this._slices=0; (radius===void 0)&& (radius=0.5); (height===void 0)&& (height=2); (slices===void 0)&& (slices=32); CylinderMesh.__super.call(this); this._radius=radius; this._height=height; this._slices=slices; this.recreateResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(CylinderMesh,'laya.d3.resource.models.CylinderMesh',_super); var __proto=CylinderMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=(this._slices+1+1)+(this._slices+1)*2+(this._slices+1+1); this._numberIndices=3 *this._slices+6 *this._slices+3 *this._slices; var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var indices=new Uint16Array(this._numberIndices); var sliceAngle=(Math.PI *2.0)/ this._slices; var halfHeight=this._height / 2; var curAngle=0; var verticeCount=0; var posX=0; var posY=0; var posZ=0; var vc=0; var ic=0; for (var tv=0;tv <=this._slices;tv++){ if (tv===0){ vertices[vc++]=0; vertices[vc++]=halfHeight; vertices[vc++]=0; vertices[vc++]=0; vertices[vc++]=1; vertices[vc++]=0; vertices[vc++]=0.5; vertices[vc++]=0.5; } curAngle=tv *sliceAngle; posX=Math.cos(curAngle)*this._radius; posY=halfHeight; posZ=Math.sin(curAngle)*this._radius; vertices[vc++]=posX; vertices[vc++]=posY; vertices[vc++]=posZ; vertices[vc++]=0; vertices[vc++]=1; vertices[vc++]=0; vertices[vc++]=0.5+Math.cos(curAngle)*0.5; vertices[vc++]=0.5+Math.sin(curAngle)*0.5; } for (var ti=0;ti < this._slices;ti++){ indices[ic++]=0; indices[ic++]=ti+1; indices[ic++]=ti+2; } verticeCount+=this._slices+1+1; for (var rv=0;rv <=this._slices;rv++){ curAngle=rv *sliceAngle; posX=Math.cos(curAngle+Math.PI)*this._radius; posY=halfHeight; posZ=Math.sin(curAngle+Math.PI)*this._radius; vertices[vc++]=posX; vertices[vc+(this._slices+1)*8-1]=posX; vertices[vc++]=posY; vertices[vc+(this._slices+1)*8-1]=-posY; vertices[vc++]=posZ; vertices[vc+(this._slices+1)*8-1]=posZ; vertices[vc++]=posX; vertices[vc+(this._slices+1)*8-1]=posX; vertices[vc++]=0; vertices[vc+(this._slices+1)*8-1]=0; vertices[vc++]=posZ; vertices[vc+(this._slices+1)*8-1]=posZ; vertices[vc++]=1-rv *1 / this._slices; vertices[vc+(this._slices+1)*8-1]=1-rv *1 / this._slices; vertices[vc++]=0; vertices[vc+(this._slices+1)*8-1]=1; } vc+=(this._slices+1)*8; for (var ri=0;ri < this._slices;ri++){ indices[ic++]=ri+verticeCount+(this._slices+1); indices[ic++]=ri+verticeCount+1; indices[ic++]=ri+verticeCount; indices[ic++]=ri+verticeCount+(this._slices+1); indices[ic++]=ri+verticeCount+(this._slices+1)+1; indices[ic++]=ri+verticeCount+1; } verticeCount+=2 *(this._slices+1); for (var bv=0;bv <=this._slices;bv++){ if (bv===0){ vertices[vc++]=0; vertices[vc++]=-halfHeight; vertices[vc++]=0; vertices[vc++]=0; vertices[vc++]=-1; vertices[vc++]=0; vertices[vc++]=0.5; vertices[vc++]=0.5; } curAngle=bv *sliceAngle; posX=Math.cos(curAngle+Math.PI)*this._radius; posY=-halfHeight; posZ=Math.sin(curAngle+Math.PI)*this._radius; vertices[vc++]=posX; vertices[vc++]=posY; vertices[vc++]=posZ; vertices[vc++]=0; vertices[vc++]=-1; vertices[vc++]=0; vertices[vc++]=0.5+Math.cos(curAngle)*0.5; vertices[vc++]=0.5+Math.sin(curAngle)*0.5; } for (var bi=0;bi < this._slices;bi++){ indices[ic++]=0+verticeCount; indices[ic++]=bi+2+verticeCount; indices[ic++]=bi+1+verticeCount; } verticeCount+=this._slices+1+1; this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置半径(改变此属性会重新生成顶点和索引) *@param value 半径 */ /** *返回半径 *@return 半径 */ __getset(0,__proto,'radius',function(){ return this._radius; },function(value){ if (this._radius!==value){ this._radius=value; this.releaseResource(); this.activeResource(); } }); /** *设置高度(改变此属性会重新生成顶点和索引) *@param value 高度 */ /** *返回高度 *@return 高度 */ __getset(0,__proto,'height',function(){ return this._height; },function(value){ if (this._height!==value){ this._height=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度分段(改变此属性会重新生成顶点和索引) *@param value 宽度分段 */ /** *获取宽度分段 *@return 宽度分段 */ __getset(0,__proto,'slices',function(){ return this._slices; },function(value){ if (this._slices!==value){ this._slices=value; this.releaseResource(); this.activeResource(); } }); return CylinderMesh; })(PrimitiveMesh) /** *QuadMesh 类用于创建平面。 */ //class laya.d3.resource.models.PlaneMesh extends laya.d3.resource.models.PrimitiveMesh var PlaneMesh=(function(_super){ function PlaneMesh(long,width,stacks,slices){ /**@private */ this._long=NaN; /**@private */ this._width=NaN; /**@private */ this._stacks=0; /**@private */ this._slices=0; (long===void 0)&& (long=10); (width===void 0)&& (width=10); (stacks===void 0)&& (stacks=10); (slices===void 0)&& (slices=10); PlaneMesh.__super.call(this); this._long=long; this._width=width; this._stacks=stacks; this._slices=slices; this.activeResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(PlaneMesh,'laya.d3.resource.models.PlaneMesh',_super); var __proto=PlaneMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=(this._stacks+1)*(this._slices+1); this._numberIndices=this._stacks *this._slices *2 *3; var indices=new Uint16Array(this._numberIndices); var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var halfLong=this._long / 2; var halfWidth=this._width / 2; var stacksLong=this._long / this._stacks; var slicesWidth=this._width / this._slices; var verticeCount=0; for (var i=0;i <=this._slices;i++){ for (var j=0;j <=this._stacks;j++){ vertices[verticeCount++]=j *stacksLong-halfLong; vertices[verticeCount++]=0; vertices[verticeCount++]=i *slicesWidth-halfWidth; vertices[verticeCount++]=0; vertices[verticeCount++]=1; vertices[verticeCount++]=0; vertices[verticeCount++]=j *1 / this._stacks; vertices[verticeCount++]=i *1 / this._slices; } }; var indiceIndex=0; for (i=0;i < this._slices;i++){ for (j=0;j < this._stacks;j++){ indices[indiceIndex++]=(i+1)*(this._stacks+1)+j; indices[indiceIndex++]=i *(this._stacks+1)+j; indices[indiceIndex++]=(i+1)*(this._stacks+1)+j+1; indices[indiceIndex++]=i *(this._stacks+1)+j; indices[indiceIndex++]=i *(this._stacks+1)+j+1; indices[indiceIndex++]=(i+1)*(this._stacks+1)+j+1; } } this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置长度(改变此属性会重新生成顶点和索引) *@param value 长度 */ /** *返回长度 *@return 长 */ __getset(0,__proto,'long',function(){ return this._long; },function(value){ if (this._long!==value){ this._long=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度(改变此属性会重新生成顶点和索引) *@param value 宽度 */ /** *返回宽度 *@return 宽 */ __getset(0,__proto,'width',function(){ return this._width; },function(value){ if (this._width!==value){ this._width=value; this.releaseResource(); this.activeResource(); } }); /** *设置长度分段(改变此属性会重新生成顶点和索引) *@param value长度分段 */ /** *获取长度分段 *@return 长度分段 */ __getset(0,__proto,'stacks',function(){ return this._stacks; },function(value){ if (this._stacks!==value){ this._stacks=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度分段(改变此属性会重新生成顶点和索引) *@param value 宽度分段 */ /** *获取宽度分段 *@return 宽度分段 */ __getset(0,__proto,'slices',function(){ return this._slices; },function(value){ if (this._slices!==value){ this._slices=value; this.releaseResource(); this.activeResource(); } }); return PlaneMesh; })(PrimitiveMesh) /** *QuadMesh 类用于创建四边形。 */ //class laya.d3.resource.models.QuadMesh extends laya.d3.resource.models.PrimitiveMesh var QuadMesh=(function(_super){ function QuadMesh(long,width){ /**@private */ this._long=NaN; /**@private */ this._width=NaN; (long===void 0)&& (long=1); (width===void 0)&& (width=1); QuadMesh.__super.call(this); this._long=long; this._width=width; this.activeResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(QuadMesh,'laya.d3.resource.models.QuadMesh',_super); var __proto=QuadMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=4; this._numberIndices=6; var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var halfLong=this._long / 2; var halfWidth=this._width / 2; var vertices=new Float32Array([ -halfLong,halfWidth,0,0,0,1,0,0,halfLong,halfWidth,0,0,0,1,1,0,-halfLong,-halfWidth,0,0,0,1,0,1,halfLong,-halfWidth,0,0,0,1,1,1,]); var indices=new Uint16Array([ 0,1,2,3,2,1,]); this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置长度(改变此属性会重新生成顶点和索引) *@param value 长度 */ /** *返回长度 *@return 长 */ __getset(0,__proto,'long',function(){ return this._long; },function(value){ if (this._long!==value){ this._long=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度(改变此属性会重新生成顶点和索引) *@param value 宽度 */ /** *返回宽度 *@return 宽 */ __getset(0,__proto,'width',function(){ return this._width; },function(value){ if (this._width!==value){ this._width=value; this.releaseResource(); this.activeResource(); } }); return QuadMesh; })(PrimitiveMesh) /** *Sphere 类用于创建球体。 */ //class laya.d3.resource.models.SphereMesh extends laya.d3.resource.models.PrimitiveMesh var SphereMesh=(function(_super){ function SphereMesh(radius,stacks,slices){ /**@private */ this._radius=NaN; /**@private */ this._slices=0; /**@private */ this._stacks=0; (radius===void 0)&& (radius=0.5); (stacks===void 0)&& (stacks=32); (slices===void 0)&& (slices=32); SphereMesh.__super.call(this); this._radius=radius; this._stacks=stacks; this._slices=slices; this.activeResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(SphereMesh,'laya.d3.resource.models.SphereMesh',_super); var __proto=SphereMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=(this._stacks+1)*(this._slices+1); this._numberIndices=(3 *this._stacks *(this._slices+1))*2; var indices=new Uint16Array(this._numberIndices); var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var stackAngle=Math.PI / this._stacks; var sliceAngle=(Math.PI *2.0)/ this._slices; var vertexIndex=0; var vertexCount=0; var indexCount=0; for (var stack=0;stack < (this._stacks+1);stack++){ var r=Math.sin(stack *stackAngle); var y=Math.cos(stack *stackAngle); for (var slice=0;slice < (this._slices+1);slice++){ var x=r *Math.sin(slice *sliceAngle+Math.PI *1 / 2); var z=r *Math.cos(slice *sliceAngle+Math.PI *1 / 2); vertices[vertexCount+0]=x *this._radius; vertices[vertexCount+1]=y *this._radius; vertices[vertexCount+2]=z *this._radius; vertices[vertexCount+3]=x; vertices[vertexCount+4]=y; vertices[vertexCount+5]=z; vertices[vertexCount+6]=slice / this._slices; vertices[vertexCount+7]=stack / this._stacks; vertexCount+=vertexFloatStride; if (stack !=(this._stacks-1)){ indices[indexCount++]=vertexIndex+(this._slices+1); indices[indexCount++]=vertexIndex; indices[indexCount++]=vertexIndex+1; indices[indexCount++]=vertexIndex+(this._slices); indices[indexCount++]=vertexIndex; indices[indexCount++]=vertexIndex+(this._slices+1); vertexIndex++; } } } this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置半径(改变此属性会重新生成顶点和索引) *@param value 半径 */ /** *返回半径 *@return 半径 */ __getset(0,__proto,'radius',function(){ return this._radius; },function(value){ if (this._radius!==value){ this._radius=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度分段(改变此属性会重新生成顶点和索引) *@param value 宽度分段 */ /** *获取宽度分段 *@return 宽度分段 */ __getset(0,__proto,'slices',function(){ return this._slices; },function(value){ if (this._slices!==value){ this._slices=value; this.releaseResource(); this.activeResource(); } }); /** *设置高度分段(改变此属性会重新生成顶点和索引) *@param value高度分段 */ /** *获取高度分段 *@return 高度分段 */ __getset(0,__proto,'stacks',function(){ return this._stacks; },function(value){ if (this._stacks!==value){ this._stacks=value; this.releaseResource(); this.activeResource(); } }); return SphereMesh; })(PrimitiveMesh) /** *Camera 类用于创建摄像机。 */ //class laya.d3.core.Camera extends laya.d3.core.BaseCamera var Camera=(function(_super){ function Camera(aspectRatio,nearPlane,farPlane){ /**@private */ //this._aspectRatio=NaN; /**@private */ //this._viewport=null; /**@private */ //this._normalizedViewport=null; /**@private */ //this._viewMatrix=null; /**@private */ //this._projectionMatrix=null; /**@private */ //this._projectionViewMatrix=null; /**@private */ //this._boundFrustumUpdate=false; /**@private */ //this._boundFrustum=null; /**@private */ //this._orientedBoundBox=null; (aspectRatio===void 0)&& (aspectRatio=0); (nearPlane===void 0)&& (nearPlane=0.3); (farPlane===void 0)&& (farPlane=1000); this._viewMatrix=new Matrix4x4(); this._projectionMatrix=new Matrix4x4(); this._projectionViewMatrix=new Matrix4x4(); this._viewport=new Viewport(0,0,0,0); this._normalizedViewport=new Viewport(0,0,1,1); this._aspectRatio=aspectRatio; this._boundFrustumUpdate=true; this._boundFrustum=new BoundFrustum(Matrix4x4.DEFAULT); Camera.__super.call(this,nearPlane,farPlane); this.transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChanged); } __class(Camera,'laya.d3.core.Camera',_super); var __proto=Camera.prototype; /** *@private */ __proto._onWorldMatrixChanged=function(){ this._boundFrustumUpdate=true; } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ var color=customProps.clearColor; this.clearColor=new Vector4(color[0],color[1],color[2],color[3]); var viewport=customProps.viewport; this.normalizedViewport=new Viewport(viewport[0],viewport[1],viewport[2],viewport[3]); } /** *@inheritDoc */ __proto._calculateProjectionMatrix=function(){ if (!this._useUserProjectionMatrix){ if (this._orthographic){ var halfWidth=this.orthographicVerticalSize *this.aspectRatio *0.5; var halfHeight=this.orthographicVerticalSize *0.5; Matrix4x4.createOrthoOffCenterRH(-halfWidth,halfWidth,-halfHeight,halfHeight,this.nearPlane,this.farPlane,this._projectionMatrix); }else { Matrix4x4.createPerspective(3.1416 *this.fieldOfView / 180.0,this.aspectRatio,this.nearPlane,this.farPlane,this._projectionMatrix); } } this._boundFrustumUpdate=true; } /** *@inheritDoc */ __proto._update=function(state){ if (this.conchModel){ this.conchModel.setViewMatrix(this.viewMatrix.elements); this.conchModel.setProjectMatrix(this.projectionMatrix.elements); } laya.d3.core.Sprite3D.prototype._update.call(this,state); } /** *@inheritDoc */ __proto._renderCamera=function(gl,state,scene){ (scene.parallelSplitShadowMaps[0])&& (scene._renderShadowMap(gl,state,this)); state.camera=this; this._prepareCameraToRender(); scene._preRenderUpdateComponents(state); var viewMat,projectMat; viewMat=state._viewMatrix=this.viewMatrix; var renderTar=this._renderTarget; if (renderTar){ renderTar.start(); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this._projectionMatrix,BaseCamera._invertYProjectionMatrix); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this.projectionViewMatrix,BaseCamera._invertYProjectionViewMatrix); projectMat=state._projectionMatrix=BaseCamera._invertYProjectionMatrix; state._projectionViewMatrix=BaseCamera._invertYProjectionViewMatrix; }else { projectMat=state._projectionMatrix=this._projectionMatrix; state._projectionViewMatrix=this.projectionViewMatrix; } this._prepareCameraViewProject(viewMat,projectMat); state._viewport=this.viewport; scene._preRenderScene(gl,state,this.boundFrustum); scene._clear(gl,state); scene._renderScene(gl,state); scene._postRenderUpdateComponents(state); (renderTar)&& (renderTar.end()); } /** *计算从屏幕空间生成的射线。 *@param point 屏幕空间的位置位置。 *@return out 输出射线。 */ __proto.viewportPointToRay=function(point,out){ Picker.calculateCursorRay(point,this.viewport,this._projectionMatrix,this.viewMatrix,null,out); } /** *计算从裁切空间生成的射线。 *@param point 裁切空间的位置。。 *@return out 输出射线。 */ __proto.normalizedViewportPointToRay=function(point,out){ var finalPoint=Camera._tempVector20; var vp=this.viewport; var nVpPosE=point.elements; var vpPosE=finalPoint.elements; vpPosE[0]=nVpPosE[0] *vp.width; vpPosE[1]=nVpPosE[1] *vp.height; Picker.calculateCursorRay(finalPoint,this.viewport,this._projectionMatrix,this.viewMatrix,null,out); } /** *计算从世界空间准换三维坐标到屏幕空间。 *@param position 世界空间的位置。 *@return out 输出位置。 */ __proto.worldToViewportPoint=function(position,out){ Matrix4x4.multiply(this._projectionMatrix,this._viewMatrix,this._projectionViewMatrix); this.viewport.project(position,this._projectionViewMatrix,out); var outE=out.elements; outE[0]=outE[0] / Laya.stage.clientScaleX; outE[1]=outE[1] / Laya.stage.clientScaleY; } /** *计算从世界空间准换三维坐标到裁切空间。 *@param position 世界空间的位置。 *@return out 输出位置。 */ __proto.worldToNormalizedViewportPoint=function(position,out){ Matrix4x4.multiply(this._projectionMatrix,this._viewMatrix,this._projectionViewMatrix); this.normalizedViewport.project(position,this._projectionViewMatrix,out); var outE=out.elements; outE[0]=outE[0] / Laya.stage.clientScaleX; outE[1]=outE[1] / Laya.stage.clientScaleY; } /** *转换2D屏幕坐标系统到3D正交投影下的坐标系统,注:只有正交模型下有效。 *@param source 源坐标。 *@param out 输出坐标。 *@return 是否转换成功。 */ __proto.convertScreenCoordToOrthographicCoord=function(source,out){ if (this._orthographic){ var clientWidth=RenderState.clientWidth; var clientHeight=RenderState.clientHeight; var ratioX=this.orthographicVerticalSize *this.aspectRatio / clientWidth; var ratioY=this.orthographicVerticalSize / clientHeight; var sE=source.elements; var oE=out.elements; oE[0]=(-clientWidth / 2+sE[0])*ratioX; oE[1]=(clientHeight / 2-sE[1])*ratioY; oE[2]=(this.nearPlane-this.farPlane)*(sE[2]+1)/ 2-this.nearPlane; Vector3.transformCoordinate(out,this.transform.worldMatrix,out); return true; }else { return false; } } /** *获取视图投影矩阵。 *@return 视图投影矩阵。 */ __getset(0,__proto,'projectionViewMatrix',function(){ Matrix4x4.multiply(this.projectionMatrix,this.viewMatrix,this._projectionViewMatrix); return this._projectionViewMatrix; }); /** *设置横纵比。 *@param value 横纵比。 */ /** *获取横纵比。 *@return 横纵比。 */ __getset(0,__proto,'aspectRatio',function(){ if (this._aspectRatio===0){ var vp=this.viewport; return vp.width / vp.height; } return this._aspectRatio; },function(value){ if (value < 0) throw new Error("Camera: the aspect ratio has to be a positive real number."); this._aspectRatio=value; this._calculateProjectionMatrix(); }); /** *获取摄像机视锥。 */ __getset(0,__proto,'boundFrustum',function(){ if (this._boundFrustumUpdate) this._boundFrustum.matrix=this.projectionViewMatrix; return this._boundFrustum; }); __getset(0,__proto,'needViewport',function(){ var nVp=this.normalizedViewport; return nVp.x===0 && nVp.y===0 && nVp.width===1 && nVp.height===1; }); /** *设置屏幕空间的视口。 *@param 屏幕空间的视口。 */ /** *获取屏幕空间的视口。 *@return 屏幕空间的视口。 */ __getset(0,__proto,'viewport',function(){ if (this._viewportExpressedInClipSpace){ var nVp=this._normalizedViewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._viewport.x=nVp.x *sizeW; this._viewport.y=nVp.y *sizeH; this._viewport.width=nVp.width *sizeW; this._viewport.height=nVp.height *sizeH; } return this._viewport; },function(value){ if (this.renderTarget !=null && (value.x < 0 || value.y < 0 || value.width==0 || value.height==0)) throw new Error("Camera: viewport size invalid.","value"); this._viewportExpressedInClipSpace=false; this._viewport=value; this._calculateProjectionMatrix(); }); /** *设置裁剪空间的视口。 *@return 裁剪空间的视口。 */ /** *获取裁剪空间的视口。 *@return 裁剪空间的视口。 */ __getset(0,__proto,'normalizedViewport',function(){ if (!this._viewportExpressedInClipSpace){ var vp=this._viewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._normalizedViewport.x=vp.x / sizeW; this._normalizedViewport.y=vp.y / sizeH; this._normalizedViewport.width=vp.width / sizeW; this._normalizedViewport.height=vp.height / sizeH; } return this._normalizedViewport; },function(value){ if (value.x < 0){ value.x=0; console.warn("Camera: viewport.x must large than 0.0."); } if (value.y < 0){ value.y=0; console.warn("Camera: viewport.y must large than 0.0."); } if (value.x+value.width > 1.0){ value.width=1.0-value.x; console.warn("Camera: viewport.width + viewport.x must less than 1.0."); } if ((value.y+value.height)> 1.0){ value.height=1.0-value.y; console.warn("Camera: viewport.height + viewport.y must less than 1.0."); } this._viewportExpressedInClipSpace=true; this._normalizedViewport=value; this._calculateProjectionMatrix(); }); /**设置投影矩阵。*/ /**获取投影矩阵。*/ __getset(0,__proto,'projectionMatrix',function(){ return this._projectionMatrix; },function(value){ this._projectionMatrix=value; this._useUserProjectionMatrix=true; }); /** *获取视图矩阵。 *@return 视图矩阵。 */ __getset(0,__proto,'viewMatrix',function(){ this.transform.worldMatrix.invert(this._viewMatrix); return this._viewMatrix; }); __static(Camera, ['_tempVector20',function(){return this._tempVector20=new Vector2();} ]); return Camera; })(BaseCamera) /** *Glitter 类用于创建闪光。 */ //class laya.d3.core.glitter.Glitter extends laya.d3.core.RenderableSprite3D var Glitter=(function(_super){ /** *创建一个 Glitter 实例。 *@param settings 配置信息。 */ function Glitter(){ Glitter.__super.call(this); this._render=new GlitterRender(this); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._onMaterialChanged); var material=new GlitterMaterial(); this._render.sharedMaterial=material; this._geometryFilter=new GlitterTemplet(this); material.renderMode=/*laya.d3.core.material.GlitterMaterial.RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE*/8; this._changeRenderObject(0); } __class(Glitter,'laya.d3.core.glitter.Glitter',_super); var __proto=Glitter.prototype; /**@private */ __proto._changeRenderObject=function(index){ var renderObjects=this._render._renderElements; var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._render=this._render; var material=this._render.sharedMaterials[index]; (material)|| (material=GlitterMaterial.defaultMaterial); var element=this._geometryFilter; renderElement._mainSortID=0; renderElement._sprite3D=this; renderElement.renderObj=element; renderElement._material=material; return renderElement; } /**@private */ __proto._onMaterialChanged=function(_glitterRender,index,material){ var renderElementCount=_glitterRender._renderElements.length; (index < renderElementCount)&& this._changeRenderObject(index); } /**@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /**@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } __proto._update=function(state){ (this._geometryFilter)._update(state.elapsedTime); _super.prototype._update.call(this,state); } /** *通过位置添加刀光。 *@param position0 位置0。 *@param position1 位置1。 */ __proto.addGlitterByPositions=function(position0,position1){ (this._geometryFilter).addVertexPosition(position0,position1); } /** *通过位置和速度添加刀光。 *@param position0 位置0。 *@param velocity0 速度0。 *@param position1 位置1。 *@param velocity1 速度1。 */ __proto.addGlitterByPositionsVelocitys=function(position0,velocity0,position1,velocity1){ (this._geometryFilter).addVertexPositionVelocity(position0,velocity0,position1,velocity1); } __proto.cloneTo=function(destObject){ var destGlitter=destObject; var destTemplet=destGlitter.templet; var templet=this._geometryFilter; destTemplet.lifeTime=templet.lifeTime; destTemplet.minSegmentDistance=templet.minSegmentDistance; destTemplet.minInterpDistance=templet.minInterpDistance; destTemplet.maxSlerpCount=templet.maxSlerpCount; destTemplet._maxSegments=templet._maxSegments; var destGlitterRender=destGlitter._render; var glitterRender=this._render; destGlitterRender.sharedMaterials=glitterRender.sharedMaterials; destGlitterRender.enable=glitterRender.enable; laya.d3.core.Sprite3D.prototype.cloneTo.call(this,destObject); } /** *

    销毁此对象。

    *@param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); this._geometryFilter._destroy(); this._geometryFilter=null; } /** *获取闪光模板。 *@return 闪光模板。 */ __getset(0,__proto,'templet',function(){ return this._geometryFilter; }); /** *获取刀光渲染器。 *@return 刀光渲染器。 */ __getset(0,__proto,'glitterRender',function(){ return this._render; }); Glitter.CURRENTTIME=2; Glitter.DURATION=3; return Glitter; })(RenderableSprite3D) /** *DirectionLight 类用于创建平行光。 */ //class laya.d3.core.light.DirectionLight extends laya.d3.core.light.LightSprite var DirectionLight=(function(_super){ function DirectionLight(){ /**@private */ this._direction=null; /**@private */ this._updateDirection=false; DirectionLight.__super.call(this); this._updateDirection=false; this._direction=new Vector3(); this.transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChange); } __class(DirectionLight,'laya.d3.core.light.DirectionLight',_super); var __proto=DirectionLight.prototype; /** *@private */ __proto._initShadow=function(){ if (this._shadow){ this._parallelSplitShadowMap=new ParallelSplitShadowMap(); this.scene.parallelSplitShadowMaps.push(this._parallelSplitShadowMap); this.transform.worldMatrix.getForward(this._direction); Vector3.normalize(this._direction,this._direction); this._parallelSplitShadowMap.setInfo(this.scene,this._shadowFarPlane,this._direction,this._shadowMapSize,this._shadowMapCount,this._shadowMapPCFType); }else { var parallelSplitShadowMaps=this.scene.parallelSplitShadowMaps; parallelSplitShadowMaps.splice(parallelSplitShadowMaps.indexOf(this._parallelSplitShadowMap),1); this._parallelSplitShadowMap.disposeAllRenderTarget(); this._parallelSplitShadowMap=null; this.scene.removeShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1); this.scene.removeShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2); this.scene.removeShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3); } } /** *@inheritDoc */ __proto._addSelfRenderObjects=function(){ _super.prototype._addSelfRenderObjects.call(this); this._shadow && (this._initShadow()); } /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ var scene=this.scene; var shaderValue=scene._shaderValues; shaderValue.setValue(/*laya.d3.core.scene.Scene.LIGHTDIRCOLOR*/4,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.LIGHTDIRECTION*/3,null); scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } /** *更新平行光相关渲染状态参数。 *@param state 渲染状态参数。 */ __proto._prepareToScene=function(state){ var scene=state.scene; if (scene.enableLight && this._activeInHierarchy){ var shaderValue=scene._shaderValues; scene.addShaderDefine(ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); Vector3.scale(this.color,this._intensity,this._intensityColor); shaderValue.setValue(/*laya.d3.core.scene.Scene.LIGHTDIRCOLOR*/4,this._intensityColor.elements); this.transform.worldMatrix.getForward(this._direction); Vector3.normalize(this._direction,this._direction); shaderValue.setValue(/*laya.d3.core.scene.Scene.LIGHTDIRECTION*/3,this._direction.elements); return true; }else { scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); return false; } } /** *@private */ __proto._onWorldMatrixChange=function(){ this._updateDirection=true; } /** *@inheritDoc */ __getset(0,__proto,'shadow',_super.prototype._$get_shadow,function(value){ if (this._shadow!==value){ this._shadow=value; (this.scene)&& (this._initShadow()); } }); /** *设置平行光的方向。 *@param value 平行光的方向。 */ /** *获取平行光的方向。 *@return 平行光的方向。 */ __getset(0,__proto,'direction',function(){ console.log("Warning: discard property,please use transform's property instead."); if (this._updateDirection){ this.transform.worldMatrix.getForward(this._direction); Vector3.normalize(this._direction,this._direction); this._updateDirection=false; } return this._direction; },function(value){ console.log("Warning: discard property,please use transform's property instead."); var worldMatrix=this.transform.worldMatrix; worldMatrix.setForward(value); this.transform.worldMatrix=worldMatrix; Vector3.normalize(value,value); this._direction=value; (this.shadow && this._parallelSplitShadowMap)&& (this._parallelSplitShadowMap._setGlobalParallelLightDir(this._direction)); }); return DirectionLight; })(LightSprite) /** *PointLight 类用于创建点光。 */ //class laya.d3.core.light.PointLight extends laya.d3.core.light.LightSprite var PointLight=(function(_super){ function PointLight(){ /**@private */ this._range=NaN; /**@private */ this._attenuation=null; PointLight.__super.call(this); this._range=6.0; this._attenuation=new Vector3(0.6,0.6,0.6); } __class(PointLight,'laya.d3.core.light.PointLight',_super); var __proto=PointLight.prototype; /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ var scene=this.scene; var shaderValue=scene._shaderValues; shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTCOLOR*/8,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTPOS*/5,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTRANGE*/6,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTATTENUATION*/7,null); scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT); } /** *更新点光相关渲染状态参数。 *@param state 渲染状态参数。 */ __proto._prepareToScene=function(state){ var scene=state.scene; if (scene.enableLight && this._activeInHierarchy){ var shaderValue=scene._shaderValues; scene.addShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT); Vector3.scale(this.color,this._intensity,this._intensityColor); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTCOLOR*/8,this._intensityColor.elements); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTPOS*/5,this.transform.position.elements); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTRANGE*/6,this.range); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTATTENUATION*/7,this.attenuation.elements); return true; }else { scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT); return false; } } /** *设置点光的范围。 *@param value 点光的范围。 */ /** *获取点光的范围。 *@return 点光的范围。 */ __getset(0,__proto,'range',function(){ return this._range; },function(value){ this._range=value; }); /** *设置点光的衰减。 *@param value 点光的衰减。 */ /** *获取点光的衰减。 *@return 点光的衰减。 */ __getset(0,__proto,'attenuation',function(){ return this._attenuation; },function(value){ this._attenuation=value; }); return PointLight; })(LightSprite) /** *SpotLight 类用于创建聚光。 */ //class laya.d3.core.light.SpotLight extends laya.d3.core.light.LightSprite var SpotLight=(function(_super){ function SpotLight(){ /**@private */ this._updateDirection=false; /**@private */ this._direction=null; /**@private */ this._spot=NaN; /**@private */ this._range=NaN; /**@private */ this._attenuation=null; SpotLight.__super.call(this); this._updateDirection=false; this.direction=new Vector3(0.0,-1.0,-1.0); this._attenuation=new Vector3(0.6,0.6,0.6); this._spot=96.0; this._range=6.0; this.transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChange); } __class(SpotLight,'laya.d3.core.light.SpotLight',_super); var __proto=SpotLight.prototype; /** *@private */ __proto._onWorldMatrixChange=function(){ this._updateDirection=true; } /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ var scene=this.scene; var shaderValue=scene._shaderValues; shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTCOLOR*/14,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTPOS*/9,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTDIRECTION*/10,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTRANGE*/12,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTSPOT*/11,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTATTENUATION*/13,null); scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_SPOTLIGHT); } /** *更新聚光相关渲染状态参数。 *@param state 渲染状态参数。 */ __proto._prepareToScene=function(state){ var scene=state.scene; if (scene.enableLight && this._activeInHierarchy){ var shaderValue=scene._shaderValues; scene.addShaderDefine(ShaderCompile3D.SHADERDEFINE_SPOTLIGHT); Vector3.scale(this.color,this._intensity,this._intensityColor); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTCOLOR*/14,this._intensityColor.elements); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTPOS*/9,this.transform.position.elements); this.transform.worldMatrix.getForward(this._direction); Vector3.normalize(this._direction,this._direction); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTDIRECTION*/10,this._direction.elements); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTRANGE*/12,this.range); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTSPOT*/11,this.spot); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTATTENUATION*/13,this.attenuation.elements); return true; }else { scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_SPOTLIGHT); return false; } } /** *设置聚光的聚光值。 *@param value 聚光的聚光值。 */ /** *获取聚光的聚光值。 *@return 聚光的聚光值。 */ __getset(0,__proto,'spot',function(){ return this._spot; },function(value){ this._spot=value; }); /** *设置平行光的方向。 *@param value 平行光的方向。 */ /** *获取平行光的方向。 *@return 平行光的方向。 */ __getset(0,__proto,'direction',function(){ console.log("Warning: discard property,please use transform's property instead."); if (this._updateDirection){ this.transform.worldMatrix.getForward(this._direction); this._updateDirection=false; } return this._direction; },function(value){ console.log("Warning: discard property,please use transform's property instead."); var worldMatrix=this.transform.worldMatrix; worldMatrix.setForward(value); this.transform.worldMatrix=worldMatrix; this._direction=value; }); /** *设置聚光的范围。 *@param value 聚光的范围值。 */ /** *获取聚光的范围。 *@return 聚光的范围值。 */ __getset(0,__proto,'range',function(){ return this._range; },function(value){ this._range=value; }); /** *设置聚光的衰减。 *@param value 聚光的衰减。 */ /** *获取聚光的衰减。 *@return 聚光的衰减。 */ __getset(0,__proto,'attenuation',function(){ return this._attenuation; },function(value){ this._attenuation=value; }); return SpotLight; })(LightSprite) /** *MeshSprite3D 类用于创建网格。 */ //class laya.d3.core.MeshSprite3D extends laya.d3.core.RenderableSprite3D var MeshSprite3D=(function(_super){ /** *创建一个 MeshSprite3D 实例。 *@param mesh 网格,同时会加载网格所用默认材质。 *@param name 名字。 */ function MeshSprite3D(mesh,name){ MeshSprite3D.__super.call(this,name); this._geometryFilter=new MeshFilter(this); this._render=new MeshRender(this); this._geometryFilter.on(/*laya.events.Event.MESH_CHANGED*/"meshchanged",this,this._onMeshChanged); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._onMaterialChanged); if (mesh){ (this._geometryFilter).sharedMesh=mesh; if ((mesh instanceof laya.d3.resource.models.Mesh )) if (mesh.loaded) this._render.sharedMaterials=(mesh).materials; else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._applyMeshMaterials); } } __class(MeshSprite3D,'laya.d3.core.MeshSprite3D',_super); var __proto=MeshSprite3D.prototype; /** *@private */ __proto._changeRenderObjectByMesh=function(index){ var renderObjects=this._render._renderElements; var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new SubMeshRenderElement()); renderElement._render=this._render; var material=this._render.sharedMaterials[index]; (material)|| (material=StandardMaterial.defaultMaterial); var renderObj=(this._geometryFilter).sharedMesh.getRenderElement(index); renderElement._mainSortID=this._getSortID(renderObj,material); renderElement._sprite3D=this; renderElement.renderObj=renderObj; renderElement._material=material; return renderElement; } /** *@private */ __proto._changeRenderObjectByMaterial=function(index,material){ var renderElement=this._render._renderElements[index]; (material)|| (material=StandardMaterial.defaultMaterial); var renderObj=(this._geometryFilter).sharedMesh.getRenderElement(index); renderElement._mainSortID=this._getSortID(renderObj,material); renderElement._sprite3D=this; renderElement.renderObj=renderObj; renderElement._material=material; return renderElement; } /** *@private */ __proto._changeRenderObjectsByMesh=function(){ var renderElementsCount=(this._geometryFilter).sharedMesh.getRenderElementsCount(); this._render._renderElements.length=renderElementsCount; for (var i=0;i < renderElementsCount;i++) this._changeRenderObjectByMesh(i); } /** *@private */ __proto._onMeshChanged=function(meshFilter){ var mesh=meshFilter.sharedMesh; if (mesh.loaded) this._changeRenderObjectsByMesh(); else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._onMeshLoaded); } /** *@private */ __proto._onMeshLoaded=function(sender){ (sender===this.meshFilter.sharedMesh)&& (this._changeRenderObjectsByMesh()); } /** *@private */ __proto._onMaterialChanged=function(meshRender,index,material){ var renderElementCount=this._render._renderElements.length; (index < renderElementCount)&& this._changeRenderObjectByMaterial(index,material); } /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /** *@inheritDoc */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ var render=this.meshRender; var lightmapIndex=customProps.lightmapIndex; (lightmapIndex !=null)&& (render.lightmapIndex=lightmapIndex); var lightmapScaleOffsetArray=customProps.lightmapScaleOffset; (lightmapScaleOffsetArray)&& (render.lightmapScaleOffset=new Vector4(lightmapScaleOffsetArray[0],lightmapScaleOffsetArray[1],lightmapScaleOffsetArray[2],lightmapScaleOffsetArray[3])); var meshPath,mesh; if (json.instanceParams){ meshPath=json.instanceParams.loadPath; if (meshPath){ mesh=Loader.getRes(innerResouMap[meshPath]); this.meshFilter.sharedMesh=mesh; if (mesh.loaded) render.sharedMaterials=mesh.materials; else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._applyMeshMaterials); } }else { meshPath=customProps.meshPath; if (meshPath){ mesh=Loader.getRes(innerResouMap[meshPath]); this.meshFilter.sharedMesh=mesh; }; var materials=customProps.materials; if (materials){ var sharedMaterials=render.sharedMaterials; var materialCount=materials.length; sharedMaterials.length=materialCount; for (var i=0;i < materialCount;i++) sharedMaterials[i]=Loader.getRes(innerResouMap[materials[i].path]); render.sharedMaterials=sharedMaterials; } } } /** *@private */ __proto._applyMeshMaterials=function(mesh){ var shaderMaterials=this._render.sharedMaterials; var meshMaterials=mesh.materials; for (var i=0,n=meshMaterials.length;i < n;i++) (shaderMaterials[i])|| (shaderMaterials[i]=meshMaterials[i]); this._render.sharedMaterials=shaderMaterials; } /** *@inheritDoc */ __proto._addToInitStaticBatchManager=function(){ MeshSprite3D._staticBatchManager._addInitBatchSprite(this); } /** *@inheritDoc */ __proto.cloneTo=function(destObject){ var meshSprite3D=destObject; (meshSprite3D._geometryFilter).sharedMesh=(this._geometryFilter).sharedMesh; var meshRender=this._render; var destMeshRender=meshSprite3D._render; destMeshRender.enable=meshRender.enable; destMeshRender.sharedMaterials=meshRender.sharedMaterials; destMeshRender.castShadow=meshRender.castShadow; var lightmapScaleOffset=meshRender.lightmapScaleOffset; lightmapScaleOffset && (destMeshRender.lightmapScaleOffset=lightmapScaleOffset.clone()); destMeshRender.lightmapIndex=meshRender.lightmapIndex; destMeshRender.receiveShadow=meshRender.receiveShadow; destMeshRender.sortingFudge=meshRender.sortingFudge; laya.d3.core.Sprite3D.prototype.cloneTo.call(this,destObject); } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; var mesh=this.meshFilter.sharedMesh; (mesh.loaded)|| (mesh.off(/*laya.events.Event.LOADED*/"loaded",this,this._applyMeshMaterials)); _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); } /** *获取网格过滤器。 *@return 网格过滤器。 */ __getset(0,__proto,'meshFilter',function(){ return this._geometryFilter; }); /** *获取网格渲染器。 *@return 网格渲染器。 */ __getset(0,__proto,'meshRender',function(){ return this._render; }); MeshSprite3D.__init__=function(){ StaticBatchManager._staticBatchManagers.push(MeshSprite3D._staticBatchManager); } MeshSprite3D.load=function(url){ return Laya.loader.create(url,null,null,MeshSprite3D); } __static(MeshSprite3D, ['_staticBatchManager',function(){return this._staticBatchManager=new MeshSprite3DStaticBatchManager();} ]); return MeshSprite3D; })(RenderableSprite3D) /** *ShuriKenParticle3D 3D粒子。 */ //class laya.d3.core.particleShuriKen.ShuriKenParticle3D extends laya.d3.core.RenderableSprite3D var ShuriKenParticle3D=(function(_super){ /** *创建一个 Particle3D 实例。 *@param settings value 粒子配置。 */ function ShuriKenParticle3D(material){ ShuriKenParticle3D.__super.call(this); this._render=new ShurikenParticleRender(this); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._onMaterialChanged); this._geometryFilter=new ShurikenParticleSystem(this); this._createRenderElement(0); (material)&& (this._render.sharedMaterial=material); } __class(ShuriKenParticle3D,'laya.d3.core.particleShuriKen.ShuriKenParticle3D',_super); var __proto=ShuriKenParticle3D.prototype; /** *@private */ __proto._initParticleVelocity=function(gradientData){ var gradient=new GradientDataNumber(); var velocitysData=gradientData.velocitys; for (var i=0,n=velocitysData.length;i < n;i++){ var valueData=velocitysData[i]; gradient.add(valueData.key,valueData.value); } return gradient; } /** *@private */ __proto._initParticleColor=function(gradientColorData){ var gradientColor=new GradientDataColor(); var alphasData=gradientColorData.alphas; var i=0,n=0; for (i=0,n=alphasData.length;i < n;i++){ var alphaData=alphasData[i]; gradientColor.addAlpha(alphaData.key,alphaData.value); }; var rgbsData=gradientColorData.rgbs; for (i=0,n=rgbsData.length;i < n;i++){ var rgbData=rgbsData[i]; var rgbValue=rgbData.value; gradientColor.addRGB(rgbData.key,new Vector3(rgbValue[0],rgbValue[1],rgbValue[2])); } return gradientColor; } /** *@private */ __proto._initParticleSize=function(gradientSizeData){ var gradientSize=new GradientDataNumber(); var sizesData=gradientSizeData.sizes; for (var i=0,n=sizesData.length;i < n;i++){ var valueData=sizesData[i]; gradientSize.add(valueData.key,valueData.value); } return gradientSize; } /** *@private */ __proto._initParticleRotation=function(gradientData){ var gradient=new GradientDataNumber(); var angularVelocitysData=gradientData.angularVelocitys; for (var i=0,n=angularVelocitysData.length;i < n;i++){ var valueData=angularVelocitysData[i]; gradient.add(valueData.key,valueData.value / 180.0 *Math.PI); } return gradient; } /** *@private */ __proto._initParticleFrame=function(overTimeFramesData){ var overTimeFrame=new GradientDataInt(); var framesData=overTimeFramesData.frames; for (var i=0,n=framesData.length;i < n;i++){ var frameData=framesData[i]; overTimeFrame.add(frameData.key,frameData.value); } return overTimeFrame; } /** *@private */ __proto._createRenderElement=function(index){ var elements=this._render._renderElements; var element=elements[index]=new RenderElement(); element._render=this._render; var material=this._render.sharedMaterials[index]; (material)|| (material=ShurikenParticleMaterial.defaultMaterial); var renderable=this._geometryFilter; element._mainSortID=0; element._sprite3D=this; element.renderObj=renderable; element._material=material; } /**@private */ __proto._onMaterialChanged=function(_particleRender,index,material){ var elements=_particleRender._renderElements; if (index < elements.length){ var element=elements[index]; element._material=material || ShurikenParticleMaterial.defaultMaterial; } } /**@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /**@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,nodeData){ var anglelToRad=Math.PI / 180.0; var i=0,n=0; var particleRender=this.particleRender; var material; var materialData=customProps.material; if (materialData){ material=Loader.getRes(innerResouMap[materialData.path]); }else { var materialPath=customProps.materialPath; if (materialPath){ material=Loader.getRes(innerResouMap[materialPath]); }else { material=new ShurikenParticleMaterial(); material.diffuseTexture=innerResouMap ? Loader.getRes(innerResouMap[customProps.texturePath]):Texture2D.load(customProps.texturePath); } } particleRender.sharedMaterial=material; var meshPath=customProps.meshPath; (meshPath)&& (particleRender.mesh=Loader.getRes(innerResouMap[meshPath])); particleRender.renderMode=customProps.renderMode; particleRender.stretchedBillboardCameraSpeedScale=customProps.stretchedBillboardCameraSpeedScale; particleRender.stretchedBillboardSpeedScale=customProps.stretchedBillboardSpeedScale; particleRender.stretchedBillboardLengthScale=customProps.stretchedBillboardLengthScale; particleRender.sortingFudge=customProps.sortingFudge ? customProps.sortingFudge :0.0; var particleSystem=this.particleSystem; particleSystem.isPerformanceMode=customProps.isPerformanceMode; particleSystem.duration=customProps.duration; particleSystem.looping=customProps.looping; particleSystem.prewarm=customProps.prewarm; particleSystem.startDelayType=customProps.startDelayType; particleSystem.startDelay=customProps.startDelay; particleSystem.startDelayMin=customProps.startDelayMin; particleSystem.startDelayMax=customProps.startDelayMax; particleSystem.startLifetimeType=customProps.startLifetimeType; particleSystem.startLifetimeConstant=customProps.startLifetimeConstant; particleSystem.startLifeTimeGradient=ShuriKenParticle3D._initStartLife(customProps.startLifetimeGradient); particleSystem.startLifetimeConstantMin=customProps.startLifetimeConstantMin; particleSystem.startLifetimeConstantMax=customProps.startLifetimeConstantMax; particleSystem.startLifeTimeGradientMin=ShuriKenParticle3D._initStartLife(customProps.startLifetimeGradientMin); particleSystem.startLifeTimeGradientMax=ShuriKenParticle3D._initStartLife(customProps.startLifetimeGradientMax); particleSystem.startSpeedType=customProps.startSpeedType; particleSystem.startSpeedConstant=customProps.startSpeedConstant; particleSystem.startSpeedConstantMin=customProps.startSpeedConstantMin; particleSystem.startSpeedConstantMax=customProps.startSpeedConstantMax; particleSystem.threeDStartSize=customProps.threeDStartSize; particleSystem.startSizeType=customProps.startSizeType; particleSystem.startSizeConstant=customProps.startSizeConstant; var startSizeConstantSeparateArray=customProps.startSizeConstantSeparate; var startSizeConstantSeparateElement=particleSystem.startSizeConstantSeparate.elements; startSizeConstantSeparateElement[0]=startSizeConstantSeparateArray[0]; startSizeConstantSeparateElement[1]=startSizeConstantSeparateArray[1]; startSizeConstantSeparateElement[2]=startSizeConstantSeparateArray[2]; particleSystem.startSizeConstantMin=customProps.startSizeConstantMin; particleSystem.startSizeConstantMax=customProps.startSizeConstantMax; var startSizeConstantMinSeparateArray=customProps.startSizeConstantMinSeparate; var startSizeConstantMinSeparateElement=particleSystem.startSizeConstantMinSeparate.elements; startSizeConstantMinSeparateElement[0]=startSizeConstantMinSeparateArray[0]; startSizeConstantMinSeparateElement[1]=startSizeConstantMinSeparateArray[1]; startSizeConstantMinSeparateElement[2]=startSizeConstantMinSeparateArray[2]; var startSizeConstantMaxSeparateArray=customProps.startSizeConstantMaxSeparate; var startSizeConstantMaxSeparateElement=particleSystem.startSizeConstantMaxSeparate.elements; startSizeConstantMaxSeparateElement[0]=startSizeConstantMaxSeparateArray[0]; startSizeConstantMaxSeparateElement[1]=startSizeConstantMaxSeparateArray[1]; startSizeConstantMaxSeparateElement[2]=startSizeConstantMaxSeparateArray[2]; particleSystem.threeDStartRotation=customProps.threeDStartRotation; particleSystem.startRotationType=customProps.startRotationType; particleSystem.startRotationConstant=customProps.startRotationConstant *anglelToRad; var startRotationConstantSeparateArray=customProps.startRotationConstantSeparate; var startRotationConstantSeparateElement=particleSystem.startRotationConstantSeparate.elements; startRotationConstantSeparateElement[0]=startRotationConstantSeparateArray[0] *anglelToRad; startRotationConstantSeparateElement[1]=startRotationConstantSeparateArray[1] *anglelToRad; startRotationConstantSeparateElement[2]=startRotationConstantSeparateArray[2] *anglelToRad; particleSystem.startRotationConstantMin=customProps.startRotationConstantMin *anglelToRad; particleSystem.startRotationConstantMax=customProps.startRotationConstantMax *anglelToRad; var startRotationConstantMinSeparateArray=customProps.startRotationConstantMinSeparate; var startRotationConstantMinSeparateElement=particleSystem.startRotationConstantMinSeparate.elements; startRotationConstantMinSeparateElement[0]=startRotationConstantMinSeparateArray[0] *anglelToRad; startRotationConstantMinSeparateElement[1]=startRotationConstantMinSeparateArray[1] *anglelToRad; startRotationConstantMinSeparateElement[2]=startRotationConstantMinSeparateArray[2] *anglelToRad; var startRotationConstantMaxSeparateArray=customProps.startRotationConstantMaxSeparate; var startRotationConstantMaxSeparateElement=particleSystem.startRotationConstantMaxSeparate.elements; startRotationConstantMaxSeparateElement[0]=startRotationConstantMaxSeparateArray[0] *anglelToRad; startRotationConstantMaxSeparateElement[1]=startRotationConstantMaxSeparateArray[1] *anglelToRad; startRotationConstantMaxSeparateElement[2]=startRotationConstantMaxSeparateArray[2] *anglelToRad; particleSystem.randomizeRotationDirection=customProps.randomizeRotationDirection; particleSystem.startColorType=customProps.startColorType; var startColorConstantArray=customProps.startColorConstant; var startColorConstantElement=particleSystem.startColorConstant.elements; startColorConstantElement[0]=startColorConstantArray[0]; startColorConstantElement[1]=startColorConstantArray[1]; startColorConstantElement[2]=startColorConstantArray[2]; startColorConstantElement[3]=startColorConstantArray[3]; var startColorConstantMinArray=customProps.startColorConstantMin; var startColorConstantMinElement=particleSystem.startColorConstantMin.elements; startColorConstantMinElement[0]=startColorConstantMinArray[0]; startColorConstantMinElement[1]=startColorConstantMinArray[1]; startColorConstantMinElement[2]=startColorConstantMinArray[2]; startColorConstantMinElement[3]=startColorConstantMinArray[3]; var startColorConstantMaxArray=customProps.startColorConstantMax; var startColorConstantMaxElement=particleSystem.startColorConstantMax.elements; startColorConstantMaxElement[0]=startColorConstantMaxArray[0]; startColorConstantMaxElement[1]=startColorConstantMaxArray[1]; startColorConstantMaxElement[2]=startColorConstantMaxArray[2]; startColorConstantMaxElement[3]=startColorConstantMaxArray[3]; particleSystem.gravityModifier=customProps.gravityModifier; particleSystem.simulationSpace=customProps.simulationSpace; particleSystem.scaleMode=customProps.scaleMode; particleSystem.playOnAwake=customProps.playOnAwake; particleSystem.maxParticles=customProps.maxParticles; var autoRandomSeed=customProps.autoRandomSeed; (autoRandomSeed !=null)&& (particleSystem.autoRandomSeed=autoRandomSeed); var randomSeed=customProps.randomSeed; (randomSeed !=null)&& (particleSystem.randomSeed[0]=randomSeed); var emissionData=customProps.emission; var emission=particleSystem.emission; if (emissionData){ emission.emissionRate=emissionData.emissionRate; var burstsData=emissionData.bursts; if (burstsData) for (i=0,n=burstsData.length;i < n;i++){ var brust=burstsData[i]; emission.addBurst(new Burst(brust.time,brust.min,brust.max)); } emission.enbale=emissionData.enable; }else { emission.enbale=false; }; var shapeData=customProps.shape; if (shapeData){ var shape; switch (shapeData.shapeType){ case 0:; var sphereShape; shape=sphereShape=new SphereShape(); sphereShape.radius=shapeData.sphereRadius; sphereShape.emitFromShell=shapeData.sphereEmitFromShell; sphereShape.randomDirection=shapeData.sphereRandomDirection; break ; case 1:; var hemiSphereShape; shape=hemiSphereShape=new HemisphereShape(); hemiSphereShape.radius=shapeData.hemiSphereRadius; hemiSphereShape.emitFromShell=shapeData.hemiSphereEmitFromShell; hemiSphereShape.randomDirection=shapeData.hemiSphereRandomDirection; break ; case 2:; var coneShape; shape=coneShape=new ConeShape(); coneShape.angle=shapeData.coneAngle *anglelToRad; coneShape.radius=shapeData.coneRadius; coneShape.length=shapeData.coneLength; coneShape.emitType=shapeData.coneEmitType; coneShape.randomDirection=shapeData.coneRandomDirection; break ; case 3:; var boxShape; shape=boxShape=new BoxShape(); boxShape.x=shapeData.boxX; boxShape.y=shapeData.boxY; boxShape.z=shapeData.boxZ; boxShape.randomDirection=shapeData.boxRandomDirection; break ; case 7:; var circleShape; shape=circleShape=new CircleShape(); circleShape.radius=shapeData.circleRadius; circleShape.arc=shapeData.circleArc *anglelToRad; circleShape.emitFromEdge=shapeData.circleEmitFromEdge; circleShape.randomDirection=shapeData.circleRandomDirection; break ; default :; var tempShape; shape=tempShape=new CircleShape(); tempShape.radius=shapeData.circleRadius; tempShape.arc=shapeData.circleArc *anglelToRad; tempShape.emitFromEdge=shapeData.circleEmitFromEdge; tempShape.randomDirection=shapeData.circleRandomDirection; break ; } shape.enable=shapeData.enable; particleSystem.shape=shape; }; var velocityOverLifetimeData=customProps.velocityOverLifetime; if (velocityOverLifetimeData){ var velocityData=velocityOverLifetimeData.velocity; var velocity; switch (velocityData.type){ case 0:; var constantData=velocityData.constant; velocity=GradientVelocity.createByConstant(new Vector3(constantData[0],constantData[1],constantData[2])); break ; case 1: velocity=GradientVelocity.createByGradient(this._initParticleVelocity(velocityData.gradientX),this._initParticleVelocity(velocityData.gradientY),this._initParticleVelocity(velocityData.gradientZ)); break ; case 2:; var constantMinData=velocityData.constantMin; var constantMaxData=velocityData.constantMax; velocity=GradientVelocity.createByRandomTwoConstant(new Vector3(constantMinData[0],constantMinData[1],constantMinData[2]),new Vector3(constantMaxData[0],constantMaxData[1],constantMaxData[2])); break ; case 3: velocity=GradientVelocity.createByRandomTwoGradient(this._initParticleVelocity(velocityData.gradientXMin),this._initParticleVelocity(velocityData.gradientXMax),this._initParticleVelocity(velocityData.gradientYMin),this._initParticleVelocity(velocityData.gradientYMax),this._initParticleVelocity(velocityData.gradientZMin),this._initParticleVelocity(velocityData.gradientZMax)); break ; }; var velocityOverLifetime=new VelocityOverLifetime(velocity); velocityOverLifetime.space=velocityOverLifetimeData.space; velocityOverLifetime.enbale=velocityOverLifetimeData.enable; particleSystem.velocityOverLifetime=velocityOverLifetime; }; var colorOverLifetimeData=customProps.colorOverLifetime; if (colorOverLifetimeData){ var colorData=colorOverLifetimeData.color; var color; switch (colorData.type){ case 0:; var constColorData=colorData.constant; color=GradientColor.createByConstant(new Vector4(constColorData[0],constColorData[1],constColorData[2],constColorData[3])); break ; case 1: color=GradientColor.createByGradient(this._initParticleColor(colorData.gradient)); break ; case 2:; var minConstColorData=colorData.constantMin; var maxConstColorData=colorData.constantMax; color=GradientColor.createByRandomTwoConstant(new Vector4(minConstColorData[0],minConstColorData[1],minConstColorData[2],minConstColorData[3]),new Vector4(maxConstColorData[0],maxConstColorData[1],maxConstColorData[2],maxConstColorData[3])); break ; case 3: color=GradientColor.createByRandomTwoGradient(this._initParticleColor(colorData.gradientMin),this._initParticleColor(colorData.gradientMax)); break ; }; var colorOverLifetime=new ColorOverLifetime(color); colorOverLifetime.enbale=colorOverLifetimeData.enable; particleSystem.colorOverLifetime=colorOverLifetime; }; var sizeOverLifetimeData=customProps.sizeOverLifetime; if (sizeOverLifetimeData){ var sizeData=sizeOverLifetimeData.size; var size; switch (sizeData.type){ case 0: if (sizeData.separateAxes){ size=GradientSize.createByGradientSeparate(this._initParticleSize(sizeData.gradientX),this._initParticleSize(sizeData.gradientY),this._initParticleSize(sizeData.gradientZ)); }else { size=GradientSize.createByGradient(this._initParticleSize(sizeData.gradient)); } break ; case 1: if (sizeData.separateAxes){ var constantMinSeparateData=sizeData.constantMinSeparate; var constantMaxSeparateData=sizeData.constantMaxSeparate; size=GradientSize.createByRandomTwoConstantSeparate(new Vector3(constantMinSeparateData[0],constantMinSeparateData[1],constantMinSeparateData[2]),new Vector3(constantMaxSeparateData[0],constantMaxSeparateData[1],constantMaxSeparateData[2])); }else { size=GradientSize.createByRandomTwoConstant(sizeData.constantMin,sizeData.constantMax); } break ; case 2: if (sizeData.separateAxes){ size=GradientSize.createByRandomTwoGradientSeparate(this._initParticleSize(sizeData.gradientXMin),this._initParticleSize(sizeData.gradientYMin),this._initParticleSize(sizeData.gradientZMin),this._initParticleSize(sizeData.gradientXMax),this._initParticleSize(sizeData.gradientYMax),this._initParticleSize(sizeData.gradientZMax)); }else { size=GradientSize.createByRandomTwoGradient(this._initParticleSize(sizeData.gradientMin),this._initParticleSize(sizeData.gradientMax)); } break ; }; var sizeOverLifetime=new SizeOverLifetime(size); sizeOverLifetime.enbale=sizeOverLifetimeData.enable; particleSystem.sizeOverLifetime=sizeOverLifetime; }; var rotationOverLifetimeData=customProps.rotationOverLifetime; if (rotationOverLifetimeData){ var angularVelocityData=rotationOverLifetimeData.angularVelocity; var angularVelocity; switch (angularVelocityData.type){ case 0: if (angularVelocityData.separateAxes){ }else { angularVelocity=GradientAngularVelocity.createByConstant(angularVelocityData.constant *anglelToRad); } break ; case 1: if (angularVelocityData.separateAxes){ }else { angularVelocity=GradientAngularVelocity.createByGradient(this._initParticleRotation(angularVelocityData.gradient)); } break ; case 2: if (angularVelocityData.separateAxes){ var minSep=angularVelocityData.constantMinSeparate; var maxSep=angularVelocityData.constantMaxSeparate; angularVelocity=GradientAngularVelocity.createByRandomTwoConstantSeparate(new Vector3(minSep[0]*anglelToRad,minSep[1]*anglelToRad,minSep[2]*anglelToRad),new Vector3(maxSep[0]*anglelToRad,maxSep[1]*anglelToRad,maxSep[2]*anglelToRad)); }else { angularVelocity=GradientAngularVelocity.createByRandomTwoConstant(angularVelocityData.constantMin *anglelToRad,angularVelocityData.constantMax *anglelToRad); } break ; case 3: if (angularVelocityData.separateAxes){ }else { angularVelocity=GradientAngularVelocity.createByRandomTwoGradient(this._initParticleRotation(angularVelocityData.gradientMin),this._initParticleRotation(angularVelocityData.gradientMax)); } break ; }; var rotationOverLifetime=new RotationOverLifetime(angularVelocity); rotationOverLifetime.enbale=rotationOverLifetimeData.enable; particleSystem.rotationOverLifetime=rotationOverLifetime; }; var textureSheetAnimationData=customProps.textureSheetAnimation; if (textureSheetAnimationData){ var frameData=textureSheetAnimationData.frame; var frameOverTime; switch (frameData.type){ case 0: frameOverTime=FrameOverTime.createByConstant(frameData.constant); break ; case 1: frameOverTime=FrameOverTime.createByOverTime(this._initParticleFrame(frameData.overTime)); break ; case 2: frameOverTime=FrameOverTime.createByRandomTwoConstant(frameData.constantMin,frameData.constantMax); break ; case 3: frameOverTime=FrameOverTime.createByRandomTwoOverTime(this._initParticleFrame(frameData.overTimeMin),this._initParticleFrame(frameData.overTimeMax)); break ; }; var startFrameData=textureSheetAnimationData.startFrame; var startFrame; switch (startFrameData.type){ case 0: startFrame=StartFrame.createByConstant(startFrameData.constant); break ; case 1: startFrame=StartFrame.createByRandomTwoConstant(startFrameData.constantMin,startFrameData.constantMax); break ; }; var textureSheetAnimation=new TextureSheetAnimation(frameOverTime,startFrame); textureSheetAnimation.enable=textureSheetAnimationData.enable; var tilesData=textureSheetAnimationData.tiles; textureSheetAnimation.tiles=new Vector2(tilesData[0],tilesData[1]); textureSheetAnimation.type=textureSheetAnimationData.type; textureSheetAnimation.randomRow=textureSheetAnimationData.randomRow; var rowIndex=textureSheetAnimationData.rowIndex; (rowIndex!==undefined)&& (textureSheetAnimation.rowIndex=rowIndex); textureSheetAnimation.cycles=textureSheetAnimationData.cycles; particleSystem.textureSheetAnimation=textureSheetAnimation; } } /** *@inheritDoc */ __proto._activeHierarchy=function(){ laya.d3.core.Sprite3D.prototype._activeHierarchy.call(this); (this.particleSystem.playOnAwake)&& (this.particleSystem.play()); } /** *@inheritDoc */ __proto._inActiveHierarchy=function(){ laya.d3.core.Sprite3D.prototype._inActiveHierarchy.call(this); (this.particleSystem.isAlive)&& (this.particleSystem.simulate(0,true)); } /** *@private */ __proto.cloneTo=function(destObject){ var destShuriKenParticle3D=destObject; var destParticleSystem=destShuriKenParticle3D._geometryFilter; (this._geometryFilter).cloneTo(destParticleSystem); var destParticleRender=destShuriKenParticle3D._render; var particleRender=this._render; destParticleRender.sharedMaterials=particleRender.sharedMaterials; destParticleRender.enable=particleRender.enable; destParticleRender.renderMode=particleRender.renderMode; destParticleRender.mesh=particleRender.mesh; destParticleRender.stretchedBillboardCameraSpeedScale=particleRender.stretchedBillboardCameraSpeedScale; destParticleRender.stretchedBillboardSpeedScale=particleRender.stretchedBillboardSpeedScale; destParticleRender.stretchedBillboardLengthScale=particleRender.stretchedBillboardLengthScale; destParticleRender.sortingFudge=particleRender.sortingFudge; laya.d3.core.Sprite3D.prototype.cloneTo.call(this,destObject); } /** *

    销毁此对象。

    *@param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); this._geometryFilter=null; } /** *获取粒子系统。 *@return 粒子系统。 */ __getset(0,__proto,'particleSystem',function(){ return this._geometryFilter; }); /** *获取粒子渲染器。 *@return 粒子渲染器。 */ __getset(0,__proto,'particleRender',function(){ return this._render; }); ShuriKenParticle3D.__init__=function(){ ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_BILLBOARD=ShuriKenParticle3D.shaderDefines.registerDefine("SPHERHBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD=ShuriKenParticle3D.shaderDefines.registerDefine("STRETCHEDBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD=ShuriKenParticle3D.shaderDefines.registerDefine("HORIZONTALBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD=ShuriKenParticle3D.shaderDefines.registerDefine("VERTICALBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME=ShuriKenParticle3D.shaderDefines.registerDefine("COLOROVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME=ShuriKenParticle3D.shaderDefines.registerDefine("RANDOMCOLOROVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT=ShuriKenParticle3D.shaderDefines.registerDefine("VELOCITYOVERLIFETIMECONSTANT"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE=ShuriKenParticle3D.shaderDefines.registerDefine("VELOCITYOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT=ShuriKenParticle3D.shaderDefines.registerDefine("VELOCITYOVERLIFETIMERANDOMCONSTANT"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE=ShuriKenParticle3D.shaderDefines.registerDefine("VELOCITYOVERLIFETIMERANDOMCURVE"); ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE=ShuriKenParticle3D.shaderDefines.registerDefine("TEXTURESHEETANIMATIONCURVE"); ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE=ShuriKenParticle3D.shaderDefines.registerDefine("TEXTURESHEETANIMATIONRANDOMCURVE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIMESEPERATE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIMECONSTANT"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIMERANDOMCURVES"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIMERANDOMCURVES"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE=ShuriKenParticle3D.shaderDefines.registerDefine("SIZEOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE=ShuriKenParticle3D.shaderDefines.registerDefine("SIZEOVERLIFETIMECURVESEPERATE"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES=ShuriKenParticle3D.shaderDefines.registerDefine("SIZEOVERLIFETIMERANDOMCURVES"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE=ShuriKenParticle3D.shaderDefines.registerDefine("SIZEOVERLIFETIMERANDOMCURVESSEPERATE"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_MESH=ShuriKenParticle3D.shaderDefines.registerDefine("RENDERMODE_MESH"); ShuriKenParticle3D.SHADERDEFINE_SHAPE=ShuriKenParticle3D.shaderDefines.registerDefine("SHAPE"); } ShuriKenParticle3D.load=function(url){ return Laya.loader.create(url,null,null,ShuriKenParticle3D); } ShuriKenParticle3D._initStartLife=function(gradientData){ var gradient=new GradientDataNumber(); var startLifetimesData=gradientData.startLifetimes; for (var i=0,n=startLifetimesData.length;i < n;i++){ var valueData=startLifetimesData[i]; gradient.add(valueData.key,valueData.value); } return gradient; } ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_BILLBOARD=0; ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD=0; ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD=0; ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD=0; ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME=0; ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME=0; ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT=0; ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE=0; ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT=0; ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE=0; ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE=0; ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES=0; ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE=0; ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE=0; ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES=0; ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE=0; ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_MESH=0; ShuriKenParticle3D.SHADERDEFINE_SHAPE=0; ShuriKenParticle3D.WORLDPOSITION=0; ShuriKenParticle3D.WORLDROTATION=1; ShuriKenParticle3D.POSITIONSCALE=4; ShuriKenParticle3D.SIZESCALE=5; ShuriKenParticle3D.SCALINGMODE=6; ShuriKenParticle3D.GRAVITY=7; ShuriKenParticle3D.THREEDSTARTROTATION=8; ShuriKenParticle3D.STRETCHEDBILLBOARDLENGTHSCALE=9; ShuriKenParticle3D.STRETCHEDBILLBOARDSPEEDSCALE=10; ShuriKenParticle3D.SIMULATIONSPACE=11; ShuriKenParticle3D.CURRENTTIME=12; ShuriKenParticle3D.VOLVELOCITYCONST=13; ShuriKenParticle3D.VOLVELOCITYGRADIENTX=14; ShuriKenParticle3D.VOLVELOCITYGRADIENTY=15; ShuriKenParticle3D.VOLVELOCITYGRADIENTZ=16; ShuriKenParticle3D.VOLVELOCITYCONSTMAX=17; ShuriKenParticle3D.VOLVELOCITYGRADIENTXMAX=18; ShuriKenParticle3D.VOLVELOCITYGRADIENTYMAX=19; ShuriKenParticle3D.VOLVELOCITYGRADIENTZMAX=20; ShuriKenParticle3D.VOLSPACETYPE=21; ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS=22; ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS=23; ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTALPHAS=24; ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTCOLORS=25; ShuriKenParticle3D.SOLSIZEGRADIENT=26; ShuriKenParticle3D.SOLSIZEGRADIENTX=27; ShuriKenParticle3D.SOLSIZEGRADIENTY=28; ShuriKenParticle3D.SOLSizeGradientZ=29; ShuriKenParticle3D.SOLSizeGradientMax=30; ShuriKenParticle3D.SOLSIZEGRADIENTXMAX=31; ShuriKenParticle3D.SOLSIZEGRADIENTYMAX=32; ShuriKenParticle3D.SOLSizeGradientZMAX=33; ShuriKenParticle3D.ROLANGULARVELOCITYCONST=34; ShuriKenParticle3D.ROLANGULARVELOCITYCONSTSEPRARATE=35; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENT=36; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTX=37; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTY=38; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZ=39; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTW=40; ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAX=41; ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAXSEPRARATE=42; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTMAX=43; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTXMAX=44; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTYMAX=45; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZMAX=46; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTWMAX=47; ShuriKenParticle3D.TEXTURESHEETANIMATIONCYCLES=48; ShuriKenParticle3D.TEXTURESHEETANIMATIONSUBUVLENGTH=49; ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTUVS=50; ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTMAXUVS=51; __static(ShuriKenParticle3D, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(RenderableSprite3D.shaderDefines);} ]); return ShuriKenParticle3D; })(RenderableSprite3D) /** *SkinnedMeshSprite3D 类用于创建网格。 */ //class laya.d3.core.SkinnedMeshSprite3D extends laya.d3.core.RenderableSprite3D var SkinnedMeshSprite3D=(function(_super){ function SkinnedMeshSprite3D(mesh,name){ /**@private */ this._subMeshOffset=null; SkinnedMeshSprite3D.__super.call(this,name); this._subMeshOffset=[]; this._geometryFilter=new MeshFilter(this); this._render=new SkinnedMeshRender(this); this._geometryFilter.on(/*laya.events.Event.MESH_CHANGED*/"meshchanged",this,this._onMeshChanged); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._onMaterialChanged); (mesh)&& ((this._geometryFilter).sharedMesh=mesh); } __class(SkinnedMeshSprite3D,'laya.d3.core.SkinnedMeshSprite3D',_super); var __proto=SkinnedMeshSprite3D.prototype; /** *@private */ __proto._changeRenderObjectByMesh=function(index){ var renderObjects=this._render._renderElements; var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new SubMeshRenderElement()); renderElement._render=this._render; var material=this._render.sharedMaterials[index]; (material)|| (material=StandardMaterial.defaultMaterial); var renderObj=(this._geometryFilter).sharedMesh.getRenderElement(index); renderElement._mainSortID=this._getSortID(renderObj,material); renderElement._sprite3D=this; renderElement.renderObj=renderObj; renderElement._material=material; return renderElement; } /** *@private */ __proto._changeRenderObjectByMaterial=function(index,material){ var renderElement=this._render._renderElements[index]; (material)|| (material=StandardMaterial.defaultMaterial); var renderObj=(this._geometryFilter).sharedMesh.getRenderElement(index); renderElement._mainSortID=this._getSortID(renderObj,material); renderElement._sprite3D=this; renderElement.renderObj=renderObj; renderElement._material=material; return renderElement; } /** *@private */ __proto._changeRenderObjectsByMesh=function(){ var renderElementsCount=(this._geometryFilter).sharedMesh.getRenderElementsCount(); this._render._renderElements.length=renderElementsCount; for (var i=0;i < renderElementsCount;i++) this._changeRenderObjectByMesh(i); } /** *@private */ __proto._onMeshChanged=function(meshFilter){ var mesh=meshFilter.sharedMesh; if (mesh.loaded) this._changeRenderObjectsByMesh(); else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._changeRenderObjectsByMesh); } /** *@private */ __proto._onMaterialChanged=function(meshRender,index,material){ var renderElementCount=this._render._renderElements.length; (index < renderElementCount)&& this._changeRenderObjectByMaterial(index,material); } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ var render=this.skinnedMeshRender; var lightmapIndex=customProps.lightmapIndex; (lightmapIndex !=null)&& (render.lightmapIndex=lightmapIndex); var lightmapScaleOffsetArray=customProps.lightmapScaleOffset; (lightmapScaleOffsetArray)&& (render.lightmapScaleOffset=new Vector4(lightmapScaleOffsetArray[0],lightmapScaleOffsetArray[1],lightmapScaleOffsetArray[2],lightmapScaleOffsetArray[3])); var meshPath,mesh; if (json.instanceParams){ meshPath=json.instanceParams.loadPath; if (meshPath){ mesh=Loader.getRes(innerResouMap[meshPath]); this.meshFilter.sharedMesh=mesh; if (mesh.loaded) render.sharedMaterials=mesh.materials; else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._applyMeshMaterials); } }else { meshPath=customProps.meshPath; if (meshPath){ mesh=Loader.getRes(innerResouMap[meshPath]); this.meshFilter.sharedMesh=mesh; }; var materials=customProps.materials; if (materials){ var sharedMaterials=render.sharedMaterials; var materialCount=materials.length; sharedMaterials.length=materialCount; for (var i=0;i < materialCount;i++) sharedMaterials[i]=Loader.getRes(innerResouMap[materials[i].path]); render.sharedMaterials=sharedMaterials; }; var rootBone=customProps.rootBone; (rootBone)&& (render._setRootBone(rootBone)); var boundBox=customProps.boundBox; if (boundBox){ var min=boundBox.min; var max=boundBox.max; var localBoundBox=new BoundBox(new Vector3(min[0],min[1],min[2]),new Vector3(max[0],max[1],max[2])); render.localBoundBox=localBoundBox; }else { render._hasIndependentBound=false; }; var boundSphere=customProps.boundSphere; if (boundSphere){ var center=boundSphere.center; var localBoundSphere=new BoundSphere(new Vector3(center[0],center[1],center[2]),boundSphere.radius); render.localBoundSphere=localBoundSphere; } } } /** *@inheritDoc */ __proto._changeHierarchyAnimator=function(animator){ if (animator){ var render=this.skinnedMeshRender; render._setCacheAnimator(animator); var avatar=animator.avatar; (avatar)&& (render._setCacheAvatar(avatar)); } laya.d3.core.Sprite3D.prototype._changeHierarchyAnimator.call(this,animator); } /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ this._scene.removeFrustumCullingObject(this._render); } /** *@inheritDoc */ __proto._addSelfRenderObjects=function(){ this._scene.addFrustumCullingObject(this._render); } /** *@private */ __proto._applyMeshMaterials=function(mesh){ var shaderMaterials=this._render.sharedMaterials; var meshMaterials=mesh.materials; for (var i=0,n=meshMaterials.length;i < n;i++) (shaderMaterials[i])|| (shaderMaterials[i]=meshMaterials[i]); this._render.sharedMaterials=shaderMaterials; } /** *@inheritDoc */ __proto.cloneTo=function(destObject){ var meshSprite3D=destObject; (meshSprite3D._geometryFilter).sharedMesh=(this._geometryFilter).sharedMesh; var meshRender=this._render; var destMeshRender=meshSprite3D._render; destMeshRender.enable=meshRender.enable; destMeshRender.sharedMaterials=meshRender.sharedMaterials; destMeshRender.castShadow=meshRender.castShadow; var lightmapScaleOffset=meshRender.lightmapScaleOffset; lightmapScaleOffset && (destMeshRender.lightmapScaleOffset=lightmapScaleOffset.clone()); destMeshRender.receiveShadow=meshRender.receiveShadow; destMeshRender.sortingFudge=meshRender.sortingFudge; destMeshRender._rootBone=meshRender._rootBone; var lbp=meshRender.localBoundSphere; (lbp)&& (destMeshRender.localBoundSphere=lbp.clone()); var lbb=meshRender.localBoundBox; (lbb)&& (destMeshRender.localBoundBox=lbb.clone()); destMeshRender._hasIndependentBound=meshRender._hasIndependentBound; laya.d3.core.Sprite3D.prototype.cloneTo.call(this,destObject); } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); } /** *获取网格过滤器。 *@return 网格过滤器。 */ __getset(0,__proto,'meshFilter',function(){ return this._geometryFilter; }); /** *获取网格渲染器。 *@return 网格渲染器。 */ __getset(0,__proto,'skinnedMeshRender',function(){ return this._render; }); SkinnedMeshSprite3D.__init__=function(){ SkinnedMeshSprite3D.SHADERDEFINE_BONE=SkinnedMeshSprite3D.shaderDefines.registerDefine("BONE"); } SkinnedMeshSprite3D.load=function(url){ return Laya.loader.create(url,null,null,SkinnedMeshSprite3D); } SkinnedMeshSprite3D.SHADERDEFINE_BONE=0x8; SkinnedMeshSprite3D.BONES=0; __static(SkinnedMeshSprite3D, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(RenderableSprite3D.shaderDefines);} ]); return SkinnedMeshSprite3D; })(RenderableSprite3D) /** *Camera 类用于创建VR摄像机。 */ //class laya.d3.core.VRCamera extends laya.d3.core.BaseCamera var VRCamera=(function(_super){ function VRCamera(pupilDistande,leftAspectRatio,rightAspectRatio,nearPlane,farPlane){ /**@private */ //this._tempMatrix=null; /**@private 左横纵比。*/ //this._leftAspectRatio=NaN; /**@private 在屏幕空间中摄像机的左视口。*/ //this._leftViewport=null; /**@private 在裁剪空间中摄像机的视口。*/ //this._leftNormalizedViewport=null; /**@private 左视图矩阵。*/ //this._leftViewMatrix=null; /**@private 左投影矩阵。*/ //this._leftProjectionMatrix=null; /**@private 左投影视图矩阵。*/ //this._leftProjectionViewMatrix=null; /**@private 左横纵比。*/ //this._rightAspectRatio=NaN; /**@private 在屏幕空间中摄像机的左视口。*/ //this._rightViewport=null; /**@private 在裁剪空间中摄像机的视口。*/ //this._rightNormalizedViewport=null; /**@private 左视图矩阵。*/ //this._rightViewMatrix=null; /**@private 左投影矩阵。*/ //this._rightProjectionMatrix=null; /**@private 左投影视图矩阵。*/ //this._rightProjectionViewMatrix=null; /**@private 瞳距。*/ //this._pupilDistande=0; /**@private */ //this._leftBoundFrustumUpdate=false; /**@private */ //this._rightBoundFrustumUpdate=false; /**@private */ //this._leftBoundFrustum=null; /**@private */ //this._rightBoundFrustum=null; (pupilDistande===void 0)&& (pupilDistande=0.1); (leftAspectRatio===void 0)&& (leftAspectRatio=0); (rightAspectRatio===void 0)&& (rightAspectRatio=0); (nearPlane===void 0)&& (nearPlane=0.3); (farPlane===void 0)&& (farPlane=1000); this._tempMatrix=new Matrix4x4(); this._leftViewMatrix=new Matrix4x4(); this._leftProjectionMatrix=new Matrix4x4(); this._leftProjectionViewMatrix=new Matrix4x4(); this._leftViewport=new Viewport(0,0,0,0); this._leftNormalizedViewport=new Viewport(0,0,0.5,1); this._leftAspectRatio=leftAspectRatio; this._rightViewMatrix=new Matrix4x4(); this._rightProjectionMatrix=new Matrix4x4(); this._rightProjectionViewMatrix=new Matrix4x4(); this._rightViewport=new Viewport(0,0,0,0); this._rightNormalizedViewport=new Viewport(0.5,0,0.5,1); this._rightAspectRatio=rightAspectRatio; this._pupilDistande=pupilDistande; this._leftBoundFrustumUpdate=true; this._leftBoundFrustum=new BoundFrustum(Matrix4x4.DEFAULT); this._rightBoundFrustumUpdate=true; this._rightBoundFrustum=new BoundFrustum(Matrix4x4.DEFAULT); VRCamera.__super.call(this,nearPlane,farPlane); this.transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChanged); } __class(VRCamera,'laya.d3.core.VRCamera',_super); var __proto=VRCamera.prototype; /** *@private */ __proto._onWorldMatrixChanged=function(){ this._leftBoundFrustumUpdate=this._rightBoundFrustumUpdate=true; } /** *@private *计算瞳距。 */ __proto._calculatePupilOffset=function(){ var offset=this._tempVector3; Vector3.scale(this.right,this._pupilDistande / 2,offset); return offset.elements; } /** *@private *计算左投影矩阵。 */ __proto._calculateLeftProjectionMatrix=function(){ if (!this._useUserProjectionMatrix){ if (this._orthographic){ var leftHalfWidth=this.orthographicVerticalSize *this.leftAspectRatio *0.5; var leftHalfHeight=this.orthographicVerticalSize *0.5; Matrix4x4.createOrthoOffCenterRH(-leftHalfWidth,leftHalfWidth,-leftHalfHeight,leftHalfHeight,this.nearPlane,this.farPlane,this._leftProjectionMatrix); }else { Matrix4x4.createPerspective(3.1416 *this.fieldOfView / 180.0,this.leftAspectRatio,this.nearPlane,this.farPlane,this._rightProjectionMatrix); } } this._leftBoundFrustumUpdate=true; } /** *@private *计算右投影矩阵。 */ __proto._calculateRightProjectionMatrix=function(){ if (!this._useUserProjectionMatrix){ if (this._orthographic){ var rightHalfWidth=this.orthographicVerticalSize *this.rightAspectRatio *0.5; var rightHalfHeight=this.orthographicVerticalSize *0.5; Matrix4x4.createOrthoOffCenterRH(-rightHalfWidth,rightHalfWidth,rightHalfHeight,rightHalfHeight,this.nearPlane,this.farPlane,this._rightProjectionMatrix); }else { Matrix4x4.createPerspective(3.1416 *this.fieldOfView / 180.0,this.rightAspectRatio,this.nearPlane,this.farPlane,this._rightProjectionMatrix); } } this._rightBoundFrustumUpdate=true; } /** *@inheritDoc */ __proto._calculateProjectionMatrix=function(){ if (!this._useUserProjectionMatrix){ if (this._orthographic){ var leftHalfWidth=this.orthographicVerticalSize *this.leftAspectRatio *0.5; var leftHalfHeight=this.orthographicVerticalSize *0.5; var rightHalfWidth=this.orthographicVerticalSize *this.rightAspectRatio *0.5; var rightHalfHeight=this.orthographicVerticalSize *0.5; Matrix4x4.createOrthoOffCenterRH(-leftHalfWidth,leftHalfWidth,-leftHalfHeight,leftHalfHeight,this.nearPlane,this.farPlane,this._leftProjectionMatrix); Matrix4x4.createOrthoOffCenterRH(-rightHalfWidth,rightHalfWidth,rightHalfHeight,rightHalfHeight,this.nearPlane,this.farPlane,this._rightProjectionMatrix); }else { Matrix4x4.createPerspective(3.1416 *this.fieldOfView / 180.0,this.leftAspectRatio,this.nearPlane,this.farPlane,this._leftProjectionMatrix); Matrix4x4.createPerspective(3.1416 *this.fieldOfView / 180.0,this.rightAspectRatio,this.nearPlane,this.farPlane,this._rightProjectionMatrix); } } this._leftBoundFrustumUpdate=this._rightBoundFrustumUpdate=true; } /** *@inheritDoc */ __proto._renderCamera=function(gl,state,scene){ state.camera=this; this._prepareCameraToRender(); scene._preRenderUpdateComponents(state); var leftViewMat,leftProjectMatrix; leftViewMat=state._viewMatrix=this.leftViewMatrix; var renderTar=this._renderTarget; if (renderTar){ renderTar.start(); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this._leftProjectionMatrix,BaseCamera._invertYProjectionMatrix); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this.leftProjectionViewMatrix,BaseCamera._invertYProjectionViewMatrix); leftProjectMatrix=state._projectionMatrix=BaseCamera._invertYProjectionMatrix; state._projectionViewMatrix=BaseCamera._invertYProjectionViewMatrix; }else { leftProjectMatrix=state._projectionMatrix=this._leftProjectionMatrix; state._projectionViewMatrix=this.leftProjectionViewMatrix; } this._prepareCameraViewProject(leftViewMat,leftProjectMatrix); state._viewport=this.leftViewport; scene._preRenderScene(gl,state,this.leftBoundFrustum); scene._clear(gl,state); scene._renderScene(gl,state); var rightViewMat,rightProjectMatrix; rightViewMat=state._viewMatrix=this.rightViewMatrix; if (renderTar){ renderTar.start(); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this._rightProjectionMatrix,BaseCamera._invertYProjectionMatrix); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this.rightProjectionViewMatrix,BaseCamera._invertYProjectionViewMatrix); state._projectionMatrix=BaseCamera._invertYProjectionMatrix; rightProjectMatrix=state._projectionViewMatrix=BaseCamera._invertYProjectionViewMatrix; }else { rightProjectMatrix=state._projectionMatrix=this._rightProjectionMatrix; state._projectionViewMatrix=this.rightProjectionViewMatrix; } this._prepareCameraViewProject(rightViewMat,rightProjectMatrix); state._viewport=this.rightViewport; scene._preRenderScene(gl,state,this.rightBoundFrustum); scene._clear(gl,state); scene._renderScene(gl,state); scene._postRenderUpdateComponents(state); (renderTar)&& (renderTar.end()); } /** *获取摄像机右视锥。 */ __getset(0,__proto,'rightBoundFrustum',function(){ if (this._rightBoundFrustumUpdate) this._rightBoundFrustum.matrix=this.rightProjectionViewMatrix; return this._rightBoundFrustum; }); /** *获取裁剪空间的左视口。 *@return 裁剪空间的左视口。 */ __getset(0,__proto,'leftNormalizedViewport',function(){ if (!this._viewportExpressedInClipSpace){ var vp=this._leftViewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._leftNormalizedViewport.x=vp.x / sizeW; this._leftNormalizedViewport.y=vp.y / sizeH; this._leftNormalizedViewport.width=vp.width / sizeW; this._leftNormalizedViewport.height=vp.height / sizeH; } return this._leftNormalizedViewport; }); /** *获取屏幕空间的右视口。 *@return 屏幕空间的右视口。 */ __getset(0,__proto,'rightViewport',function(){ if (this._viewportExpressedInClipSpace){ var nVp=this._rightNormalizedViewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._rightViewport.x=nVp.x *sizeW; this._rightViewport.y=nVp.y *sizeH; this._rightViewport.width=nVp.width *sizeW; this._rightViewport.height=nVp.height *sizeH; } return this._rightViewport; }); /** *设置屏幕空间的视口。 *@param 屏幕空间的视口。 */ __getset(0,__proto,'viewport',null,function(value){ if (this.renderTarget !=null && (value.x < 0 || value.y < 0 || value.width==0 || value.height==0)) throw new Error("VRCamera: viewport size invalid.","value"); this._viewportExpressedInClipSpace=false; this._leftViewport=new Viewport(0,0,value.width / 2,value.height); this._rightViewport=new Viewport(value.width / 2,0,value.width / 2,value.height); this._calculateProjectionMatrix(); }); /** *获取左横纵比。 *@return 左横纵比。 */ __getset(0,__proto,'leftAspectRatio',function(){ if (this._leftAspectRatio===0){ var lVp=this.leftViewport; return lVp.width / lVp.height; } return this._leftAspectRatio; }); /** *获取右横纵比。 *@return 右横纵比。 */ __getset(0,__proto,'rightAspectRatio',function(){ if (this._rightAspectRatio===0){ var rVp=this.rightViewport; return rVp.width / rVp.height; } return this._rightAspectRatio; }); /** *设置横纵比。 *@param value 横纵比。 */ __getset(0,__proto,'aspectRatio',null,function(value){ if (value < 0) throw new Error("VRCamera: the aspect ratio has to be a positive real number."); this._leftAspectRatio=value; this._rightAspectRatio=value; this._calculateRightProjectionMatrix(); }); /** *获取裁剪空间的右视口。 *@return 裁剪空间的右视口。 */ __getset(0,__proto,'rightNormalizedViewport',function(){ if (!this._viewportExpressedInClipSpace){ var vp=this._rightViewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._rightNormalizedViewport.x=vp.x / sizeW; this._rightNormalizedViewport.y=vp.y / sizeH; this._rightNormalizedViewport.width=vp.width / sizeW; this._rightNormalizedViewport.height=vp.height / sizeH; } return this._rightNormalizedViewport; }); /** *设置裁剪空间的视口。 *@return 裁剪空间的视口。 */ __getset(0,__proto,'normalizedViewport',null,function(value){ if (value.x < 0 || value.y < 0 || (value.x+value.width)> 1 || (value.x+value.height)> 1) throw new Error("VRCamera: viewport size invalid.","value"); this._viewportExpressedInClipSpace=true; this._leftNormalizedViewport=new Viewport(0,0,value.width / 2,value.height); this._rightNormalizedViewport=new Viewport(value.width / 2,0,value.width / 2,value.height); this._calculateProjectionMatrix(); }); /** *获取屏幕空间的左视口。 *@return 屏幕空间的左视口。 */ __getset(0,__proto,'leftViewport',function(){ if (this._viewportExpressedInClipSpace){ var nVp=this._leftNormalizedViewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._leftViewport.x=nVp.x *sizeW; this._leftViewport.y=nVp.y *sizeH; this._leftViewport.width=nVp.width *sizeW; this._leftViewport.height=nVp.height *sizeH; } return this._leftViewport; }); __getset(0,__proto,'needLeftViewport',function(){ var nVp=this.leftNormalizedViewport; return nVp.x===0 && nVp.y===0 && nVp.width===1 && nVp.height===1; }); __getset(0,__proto,'needRightViewport',function(){ var nVp=this.rightNormalizedViewport; return nVp.x===0 && nVp.y===0 && nVp.width===1 && nVp.height===1; }); /** *获取左视图矩阵。 *@return 左视图矩阵。 */ __getset(0,__proto,'leftViewMatrix',function(){ var offsetE=this._calculatePupilOffset(); var tempWorldMat=this._tempMatrix; this.transform.worldMatrix.cloneTo(tempWorldMat); var worldMatE=tempWorldMat.elements; worldMatE[12]-=offsetE[0]; worldMatE[13]-=offsetE[1]; worldMatE[14]-=offsetE[2]; tempWorldMat.invert(this._leftViewMatrix); return this._leftViewMatrix; }); /** *获取右视图矩阵。 *@return 右视图矩阵。 */ __getset(0,__proto,'rightViewMatrix',function(){ var offsetE=this._calculatePupilOffset(); var tempWorldMat=this._tempMatrix; this.transform.worldMatrix.cloneTo(tempWorldMat); var worldMatE=tempWorldMat.elements; worldMatE[12]+=offsetE[0]; worldMatE[13]+=offsetE[1]; worldMatE[14]+=offsetE[2]; tempWorldMat.invert(this._rightViewMatrix); return this._rightViewMatrix; }); /** *获取左投影矩阵。 *@return 左投影矩阵。 */ __getset(0,__proto,'leftProjectionMatrix',function(){ return this._leftProjectionMatrix; }); /** *获取左投影视图矩阵。 *@return 左投影视图矩阵。 */ __getset(0,__proto,'leftProjectionViewMatrix',function(){ Matrix4x4.multiply(this.leftProjectionMatrix,this.leftViewMatrix,this._leftProjectionViewMatrix); return this._leftProjectionViewMatrix; }); /** *获取右投影矩阵。 *@return 右投影矩阵。 */ __getset(0,__proto,'rightProjectionMatrix',function(){ return this._rightProjectionMatrix; }); /** *获取右投影视图矩阵。 *@return 右投影视图矩阵。 */ __getset(0,__proto,'rightProjectionViewMatrix',function(){ Matrix4x4.multiply(this.rightProjectionMatrix,this.rightViewMatrix,this._rightProjectionViewMatrix); return this._rightProjectionViewMatrix; }); /** *获取摄像机左视锥。 */ __getset(0,__proto,'leftBoundFrustum',function(){ if (this._leftBoundFrustumUpdate) this._leftBoundFrustum.matrix=this.leftProjectionViewMatrix; return this._leftBoundFrustum; }); return VRCamera; })(BaseCamera) /** *... *@author ... */ //class laya.d3.core.trail.TrailSprite3D extends laya.d3.core.RenderableSprite3D var TrailSprite3D=(function(_super){ function TrailSprite3D(){ TrailSprite3D.__super.call(this); this._geometryFilter=new TrailFilter(this); this._render=new TrailRenderer(this); this._changeRenderObjectsByMaterial(this._render,0,TrailMaterial.defaultMaterial); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._changeRenderObjectsByMaterial); this._geometryFilter.on(/*laya.events.Event.TRAIL_FILTER_CHANGE*/"trailfilterchange",this,this._changeRenderObjectsByRenderElement); } __class(TrailSprite3D,'laya.d3.core.trail.TrailSprite3D',_super); var __proto=TrailSprite3D.prototype; __proto._changeRenderObjectsByMaterial=function(sender,index,material){ var renderElementsCount=(this._geometryFilter).getRenderElementsCount(); this._render._renderElements.length=renderElementsCount; for (var i=0;i < renderElementsCount;i++){ this._changeRenderObjectByMaterial(i,material); } } __proto._changeRenderObjectByMaterial=function(index,material){ var renderObjects=this._render._renderElements; (material)|| (material=TrailMaterial.defaultMaterial); var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._sprite3D=this; renderElement.renderObj=(this._geometryFilter).getRenderElement(index); renderElement._render=this._render; renderElement._material=material; } __proto._changeRenderObjectsByRenderElement=function(index,trailRenderElement){ var renderObjects=this._render._renderElements; var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._sprite3D=this; renderElement.renderObj=trailRenderElement; renderElement._render=this._render; renderElement._material=this._render.sharedMaterial; } /**@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /**@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } __proto._update=function(state){ _super.prototype._update.call(this,state); (this._geometryFilter)._update(state); } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ var render=this._render; var filter=this._geometryFilter; var i=0,j=0; var materials=customProps.materials; if (materials){ var sharedMaterials=render.sharedMaterials; var materialCount=materials.length; sharedMaterials.length=materialCount; for (i=0;i < materialCount;i++) sharedMaterials[i]=Loader.getRes(innerResouMap[materials[i].path]); render.sharedMaterials=sharedMaterials; }; var props=json.props; filter.time=props.time; filter.minVertexDistance=props.minVertexDistance; filter.widthMultiplier=props.widthMultiplier; filter.textureMode=props.textureMode; var _widthCurve=[]; var widthCurve=customProps.widthCurve; for (i=0,j=widthCurve.length;i < j;i++){ var trailkeyframe=new TrailKeyFrame(); trailkeyframe.time=widthCurve[i].time; trailkeyframe.inTangent=widthCurve[i].inTangent; trailkeyframe.outTangent=widthCurve[i].outTangent; trailkeyframe.value=widthCurve[i].value; _widthCurve.push(trailkeyframe); } filter.widthCurve=_widthCurve; var colorGradientNode=customProps.colorGradient; var _colorGradient=new Gradient(); _colorGradient.mode=colorGradientNode.mode; var colorKeys=[]; var colorKey; var _colorKeys=colorGradientNode.colorKeys; var _colorKey; for (i=0,j=_colorKeys.length;i < j;i++){ _colorKey=_colorKeys[i]; colorKey=new GradientColorKey(new Color$1(_colorKey.value[0],_colorKey.value[1],_colorKey.value[2],1.0),_colorKey.time); colorKeys.push(colorKey); }; var alphaKeys=[]; var alphaKey; var _alphaKeys=colorGradientNode.alphaKeys; var _alphaKey; for (i=0,j=_alphaKeys.length;i < j;i++){ _alphaKey=_alphaKeys[i]; alphaKey=new GradientAlphaKey(_alphaKey.value,_alphaKey.time); alphaKeys.push(alphaKey); } _colorGradient.setKeys(colorKeys,alphaKeys); filter.colorGradient=_colorGradient; } __proto.reset=function(){ this.trailFilter.reset(); } /** *@inheritDoc */ __proto.cloneTo=function(destObject){ laya.d3.core.Sprite3D.prototype.cloneTo.call(this,destObject); var i=0,j=0; var _trailSprite3D=destObject; var _trailFilter=_trailSprite3D.trailFilter; _trailFilter.time=this.trailFilter.time; _trailFilter.minVertexDistance=this.trailFilter.minVertexDistance; _trailFilter.widthMultiplier=this.trailFilter.widthMultiplier; var widthCurve=this.trailFilter.widthCurve; var _widthCurve=[]; for (i=0,j=widthCurve.length;i < j;i++){ var _keyFrame=new TrailKeyFrame(); widthCurve[i].cloneTo(_keyFrame); _widthCurve.push(_keyFrame); } _trailFilter.widthCurve=_widthCurve; var _colorGradient=new Gradient(); this.trailFilter.colorGradient.cloneTo(_colorGradient); _trailFilter.colorGradient=_colorGradient; _trailFilter.textureMode=this.trailFilter.textureMode; var _trailRender=_trailSprite3D.trailRender; _trailRender.sharedMaterial=this.trailRender.sharedMaterial; } /** *

    销毁此对象。

    *@param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); this._geometryFilter=null; } /** *获取Trail过滤器。 *@return Trail过滤器。 */ __getset(0,__proto,'trailFilter',function(){ return this._geometryFilter; }); /** *获取Trail渲染器。 *@return Trail渲染器。 */ __getset(0,__proto,'trailRender',function(){ return this._render; }); TrailSprite3D.__init__=function(){ TrailSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND=TrailSprite3D.shaderDefines.registerDefine("GRADIENTMODE_BLEND"); } TrailSprite3D.CURTIME=3; TrailSprite3D.LIFETIME=4; TrailSprite3D.WIDTHCURVE=5; TrailSprite3D.WIDTHCURVEKEYLENGTH=6; TrailSprite3D.GRADIENTCOLORKEY=7; TrailSprite3D.GRADIENTALPHAKEY=8; TrailSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND=0; __static(TrailSprite3D, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(RenderableSprite3D.shaderDefines);} ]); return TrailSprite3D; })(RenderableSprite3D) /** *... *@author */ //class laya.d3.extension.domino.DominoSprite3D extends laya.d3.core.RenderableSprite3D var DominoSprite3D=(function(_super){ function DominoSprite3D(){ DominoSprite3D.__super.call(this); this._defaultScale=new Vector3(0.4,1.0,0.12); this._geometryFilter=new DominoFilter(this); this._render=new DominoRenderer(this); this._changeRenderObjects(this._render,0,DominoMaterial.defaultMaterial); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._changeRenderObjects); this._geometryFilter.on(/*laya.events.Event.DOMINO_FILTER_CHANGE*/"dominofilterchange",this,this._changeRenderObjectsByRenderElement); } __class(DominoSprite3D,'laya.d3.extension.domino.DominoSprite3D',_super); var __proto=DominoSprite3D.prototype; __proto.addDomino=function(position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=this._defaultScale); (this._geometryFilter).addDomino(position,rotation,scale); } __proto.updateDomino=function(index,position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=this._defaultScale); (this._geometryFilter).updateDomino(index,position,rotation,scale); } __proto.updateDominos=function(startIndex,count,keyFrames){ if (count > keyFrames.length){ throw Error("Update domino count can't more than keyFrames Count!"); } (this._geometryFilter).updateDominos(startIndex,count,keyFrames); } __proto._changeRenderObjects=function(sender,index,material){ var renderElementsCount=(this._geometryFilter).getDominoRenderElementsCount(); this._render._renderElements.length=renderElementsCount; for (var i=0;i < renderElementsCount;i++){ this._changeRenderObject(i,material); } } __proto._changeRenderObject=function(index,material){ var renderObjects=this._render._renderElements; (material)|| (material=DominoMaterial.defaultMaterial); var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._sprite3D=this; renderElement.renderObj=(this._geometryFilter).getRenderElement(index); renderElement._render=this._render; renderElement._material=material; } __proto._changeRenderObjectsByRenderElement=function(index,dominoRenderElement){ var renderObjects=this._render._renderElements; var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._sprite3D=this; renderElement.renderObj=dominoRenderElement; renderElement._render=this._render; renderElement._material=this._render.sharedMaterial ? this._render.sharedMaterial :DominoMaterial.defaultMaterial; } /**@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /**@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } __proto._update=function(state){ _super.prototype._update.call(this,state); (this._geometryFilter)._update(state); } /** *获取多米诺过滤器。 *@return 多米诺过滤器。 */ __getset(0,__proto,'dominoFilter',function(){ return this._geometryFilter; }); /** *获取多米诺渲染器。 *@return 多米诺渲染器。 */ __getset(0,__proto,'dominoRender',function(){ return this._render; }); return DominoSprite3D; })(RenderableSprite3D) /** *... *@author */ //class laya.d3.extension.lineRender.LineSprite3D extends laya.d3.core.RenderableSprite3D var LineSprite3D=(function(_super){ function LineSprite3D(){ LineSprite3D.__super.call(this); this._position=new Vector3(); this._render=new LineRenderer(this); this._geometryFilter=new LineFilter(this); this._changeRenderObjects(this._render,0,LineMaterial.defaultMaterial); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._changeRenderObjects); } __class(LineSprite3D,'laya.d3.extension.lineRender.LineSprite3D',_super); var __proto=LineSprite3D.prototype; __proto.addPosition=function(position,normal){ (this._geometryFilter).addPosition(position,normal); } __proto._changeRenderObjects=function(sender,index,material){ var renderObjects=this._render._renderElements; (material)|| (material=LineMaterial.defaultMaterial); var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._sprite3D=this; renderElement.renderObj=this._geometryFilter; renderElement._render=this._render; renderElement._material=material; } /**@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /**@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } __proto._update=function(state){ _super.prototype._update.call(this,state); (this._geometryFilter)._update(state); } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ var render=this._render; var filter=this._geometryFilter; var i=0,j=0; var materials=customProps.materials; if (materials){ var sharedMaterials=render.sharedMaterials; var materialCount=materials.length; sharedMaterials.length=materialCount; for (i=0;i < materialCount;i++) sharedMaterials[i]=Loader.getRes(innerResouMap[materials[i].path]); render.sharedMaterials=sharedMaterials; }; var props=json.props; filter.widthMultiplier=props.widthMultiplier; filter.textureMode=props.textureMode; var _widthCurve=[]; var widthCurve=customProps.widthCurve; for (i=0,j=widthCurve.length;i < j;i++){ var trailkeyframe=new TrailKeyFrame(); trailkeyframe.time=widthCurve[i].time; trailkeyframe.inTangent=widthCurve[i].inTangent; trailkeyframe.outTangent=widthCurve[i].outTangent; trailkeyframe.value=widthCurve[i].value; _widthCurve.push(trailkeyframe); } filter.widthCurve=_widthCurve; var colorGradientNode=customProps.colorGradient; var _colorGradient=new Gradient(); _colorGradient.mode=colorGradientNode.mode; var colorKeys=[]; var colorKey; var _colorKeys=colorGradientNode.colorKeys; var _colorKey; for (i=0,j=_colorKeys.length;i < j;i++){ _colorKey=_colorKeys[i]; colorKey=new GradientColorKey(new Color$1(_colorKey.value[0],_colorKey.value[1],_colorKey.value[2],1.0),_colorKey.time); colorKeys.push(colorKey); }; var alphaKeys=[]; var alphaKey; var _alphaKeys=colorGradientNode.alphaKeys; var _alphaKey; for (i=0,j=_alphaKeys.length;i < j;i++){ _alphaKey=_alphaKeys[i]; alphaKey=new GradientAlphaKey(_alphaKey.value,_alphaKey.time); alphaKeys.push(alphaKey); } _colorGradient.setKeys(colorKeys,alphaKeys); filter.colorGradient=_colorGradient; var positions=customProps.positions; var positionSize=positions.size; var positionsValue=positions.values; var position; for (i=0;i < positionSize;i++){ position=positionsValue[i]; this._position.x=position[0]; this._position.y=position[1]; this._position.z=position[2]; this.addPosition(this._position); } } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); this._position=null; } /** *获取line过滤器。 *@return line过滤器。 */ __getset(0,__proto,'lineFilter',function(){ return this._geometryFilter; }); /** *获取line渲染器。 *@return line渲染器。 */ __getset(0,__proto,'lineRender',function(){ return this._render; }); LineSprite3D.__init__=function(){ LineSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND=LineSprite3D.shaderDefines.registerDefine("GRADIENTMODE_BLEND"); LineSprite3D.SHADERDEFINE_TEXTUREMODE_STRETCH=LineSprite3D.shaderDefines.registerDefine("TEXTUREMODE"); LineSprite3D.SHADERDEFINE_WORLDSPACE=LineSprite3D.shaderDefines.registerDefine("WORLDSPACE"); } LineSprite3D.WIDTHCURVE=3; LineSprite3D.WIDTHCURVEKEYLENGTH=4; LineSprite3D.GRADIENTCOLORKEY=5; LineSprite3D.GRADIENTALPHAKEY=6; LineSprite3D.SHADERDEFINE_WORLDSPACE=0; LineSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND=0; LineSprite3D.SHADERDEFINE_TEXTUREMODE_STRETCH=0; __static(LineSprite3D, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(RenderableSprite3D.shaderDefines);} ]); return LineSprite3D; })(RenderableSprite3D) /** *TerrainChunk 类用于创建地块。 */ //class laya.d3.terrain.TerrainChunk extends laya.d3.core.RenderableSprite3D var TerrainChunk=(function(_super){ /** *创建一个 MeshSprite3D 实例。 *@param mesh 网格,同时会加载网格所用默认材质。 *@param name 名字。 */ function TerrainChunk(chunkOffsetX,chunkOffsetZ,girdSize,terrainHeightData,heightDataWidth,heightDataHeight,cameraCoordinateInverse,name){ TerrainChunk.__super.call(this,name); this._geometryFilter=new TerrainFilter(this,chunkOffsetX,chunkOffsetZ,girdSize,terrainHeightData,heightDataWidth,heightDataHeight,cameraCoordinateInverse); this._render=new TerrainRender(this); } __class(TerrainChunk,'laya.d3.terrain.TerrainChunk',_super); var __proto=TerrainChunk.prototype; __proto.buildRenderElementAndMaterial=function(detailNum,normalMap,alphaMapUrl,detailUrl1,detailUrl2,detailUrl3,detailUrl4,ambientColor,diffuseColor,specularColor,sx1,sy1,sx2,sy2,sx3,sy3,sx4,sy4){ (sx1===void 0)&& (sx1=1); (sy1===void 0)&& (sy1=1); (sx2===void 0)&& (sx2=1); (sy2===void 0)&& (sy2=1); (sx3===void 0)&& (sx3=1); (sy3===void 0)&& (sy3=1); (sx4===void 0)&& (sx4=1); (sy4===void 0)&& (sy4=1); var terrainMaterial=new TerrainMaterial(); if (diffuseColor)terrainMaterial.diffuseColor=diffuseColor; if (ambientColor)terrainMaterial.ambientColor=ambientColor; if (specularColor)terrainMaterial.specularColor=specularColor; terrainMaterial.splatAlphaTexture=Loader.getRes(alphaMapUrl); terrainMaterial.normalTexture=normalMap ? Loader.getRes(normalMap):null; terrainMaterial.diffuseTexture1=detailUrl1 ? Loader.getRes(detailUrl1):null; terrainMaterial.diffuseTexture2=detailUrl2 ? Loader.getRes(detailUrl2):null; terrainMaterial.diffuseTexture3=detailUrl3 ? Loader.getRes(detailUrl3):null; terrainMaterial.diffuseTexture4=detailUrl4 ? Loader.getRes(detailUrl4):null; terrainMaterial.setDiffuseScale1(sx1,sy1); terrainMaterial.setDiffuseScale2(sx2,sy2); terrainMaterial.setDiffuseScale3(sx3,sy3); terrainMaterial.setDiffuseScale4(sx4,sy4); terrainMaterial.setDetailNum(detailNum); if (this._render._renderElements.length !=0){ terrainMaterial.renderMode=/*laya.d3.core.material.TerrainMaterial.RENDERMODE_TRANSPARENT*/2; }; var renderElement=new RenderElement(); renderElement._mainSortID=0; renderElement._sprite3D=this; renderElement.renderObj=this._geometryFilter; renderElement._material=terrainMaterial; this._render._materials.push(terrainMaterial); this._render._renderElements.push(renderElement); } /** *@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /** *@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } /** *@private */ __proto._applyMeshMaterials=function(mesh){ var shaderMaterials=this._render.sharedMaterials; var meshMaterials=mesh.materials; for (var i=0,n=meshMaterials.length;i < n;i++) (shaderMaterials[i])|| (shaderMaterials[i]=meshMaterials[i]); this._render.sharedMaterials=shaderMaterials; } __proto.cloneTo=function(destObject){ console.log("Terrain Chunk can't clone"); } __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); } /** *获取地形过滤器。 *@return 地形过滤器。 */ __getset(0,__proto,'terrainFilter',function(){ return this._geometryFilter; }); /** *获取地形渲染器。 *@return 地形渲染器。 */ __getset(0,__proto,'terrainRender',function(){ return this._render; }); TerrainChunk.load=function(url){ return Laya.loader.create(url,null,null,TerrainChunk,null,1,false); } return TerrainChunk; })(RenderableSprite3D) /** *TerrainMeshSprite3D 类用于创建网格。 */ //class laya.d3.core.MeshTerrainSprite3D extends laya.d3.core.MeshSprite3D var MeshTerrainSprite3D=(function(_super){ function MeshTerrainSprite3D(mesh,heightMap,name){ /**@private */ this._minX=NaN; /**@private */ this._minZ=NaN; /**@private */ this._cellSize=null; /**@private */ this._heightMap=null; MeshTerrainSprite3D.__super.call(this,mesh,name); this._heightMap=heightMap; this._cellSize=new Vector2(); } __class(MeshTerrainSprite3D,'laya.d3.core.MeshTerrainSprite3D',_super); var __proto=MeshTerrainSprite3D.prototype; /** *@private */ __proto._disableRotation=function(){ var rotation=this.transform.rotation; rotation.elements[0]=0; rotation.elements[1]=0; rotation.elements[2]=0; rotation.elements[3]=1; this.transform.rotation=rotation; } /** *@private */ __proto._getScaleX=function(){ var worldMat=this.transform.worldMatrix; var worldMatE=worldMat.elements; var m11=worldMatE[0]; var m12=worldMatE[1]; var m13=worldMatE[2]; return Math.sqrt((m11 *m11)+(m12 *m12)+(m13 *m13)); } /** *@private */ __proto._getScaleZ=function(){ var worldMat=this.transform.worldMatrix; var worldMatE=worldMat.elements; var m31=worldMatE[8]; var m32=worldMatE[9]; var m33=worldMatE[10]; return Math.sqrt((m31 *m31)+(m32 *m32)+(m33 *m33)); } /** *@private */ __proto._initCreateFromMesh=function(heightMapWidth,heightMapHeight){ this._heightMap=HeightMap.creatFromMesh(this.meshFilter.sharedMesh,heightMapWidth,heightMapHeight,this._cellSize); var boundingBox=this.meshFilter.sharedMesh.boundingBox; var min=boundingBox.min; var max=boundingBox.max; this._minX=min.x; this._minZ=min.z; } /** *@private */ __proto._initCreateFromMeshHeightMap=function(texture,minHeight,maxHeight){ var _$this=this; var boundingBox=this.meshFilter.sharedMesh.boundingBox; if (texture.loaded){ this._heightMap=HeightMap.createFromImage(texture,minHeight,maxHeight); this._computeCellSize(boundingBox); }else { texture.once(/*laya.events.Event.LOADED*/"loaded",null,function(){ _$this._heightMap=HeightMap.createFromImage(texture,minHeight,maxHeight); _$this._computeCellSize(boundingBox); }); }; var min=boundingBox.min; var max=boundingBox.max; this._minX=min.x; this._minZ=min.z; } /** *@private */ __proto._computeCellSize=function(boundingBox){ var min=boundingBox.min; var max=boundingBox.max; var minX=min.x; var minZ=min.z; var maxX=max.x; var maxZ=max.z; var widthSize=maxX-minX; var heightSize=maxZ-minZ; this._cellSize.elements[0]=widthSize / (this._heightMap.width-1); this._cellSize.elements[1]=heightSize / (this._heightMap.height-1); } /** *@private */ __proto._update=function(state){ this._disableRotation(); laya.d3.core.RenderableSprite3D.prototype._update.call(this,state); } /** *获取地形高度。 *@param x X轴坐标。 *@param z Z轴坐标。 */ __proto.getHeight=function(x,z){ MeshTerrainSprite3D._tempVector3.elements[0]=x; MeshTerrainSprite3D._tempVector3.elements[1]=0; MeshTerrainSprite3D._tempVector3.elements[2]=z; this._disableRotation(); var worldMat=this.transform.worldMatrix; worldMat.invert(MeshTerrainSprite3D._tempMatrix4x4); Vector3.transformCoordinate(MeshTerrainSprite3D._tempVector3,MeshTerrainSprite3D._tempMatrix4x4,MeshTerrainSprite3D._tempVector3); x=MeshTerrainSprite3D._tempVector3.elements[0]; z=MeshTerrainSprite3D._tempVector3.elements[2]; var c=(x-this._minX)/ this._cellSize.x; var d=(z-this._minZ)/ this._cellSize.y; var row=Math.floor(d); var col=Math.floor(c); var s=c-col; var t=d-row; var uy=NaN; var vy=NaN; var worldMatE=worldMat.elements; var m21=worldMatE[4]; var m22=worldMatE[5]; var m23=worldMatE[6]; var scaleY=Math.sqrt((m21 *m21)+(m22 *m22)+(m23 *m23)); var translateY=worldMatE[13]; var h01=this._heightMap.getHeight(row,col+1); var h10=this._heightMap.getHeight((row+1),col); if (isNaN(h01)|| isNaN(h10)) return NaN; if (s+t <=1.0){ var h00=this._heightMap.getHeight(row,col); if (isNaN(h00)) return NaN; uy=h01-h00; vy=h10-h00; return (h00+s *uy+t *vy)*scaleY+translateY; }else { var h11=this._heightMap.getHeight((row+1),col+1); if (isNaN(h11)) return NaN; uy=h10-h11; vy=h01-h11; return (h11+(1.0-s)*uy+(1.0-t)*vy)*scaleY+translateY; } } /** *获取地形X轴最小位置。 *@return 地形X轴最小位置。 */ __getset(0,__proto,'minX',function(){ var worldMat=this.transform.worldMatrix; var worldMatE=worldMat.elements; return this._minX *this._getScaleX()+worldMatE[12]; }); /** *获取地形X轴长度。 *@return 地形X轴长度。 */ __getset(0,__proto,'width',function(){ return (this._heightMap.width-1)*this._cellSize.x *this._getScaleX(); }); /** *获取地形Z轴最小位置。 *@return 地形X轴最小位置。 */ __getset(0,__proto,'minZ',function(){ var worldMat=this.transform.worldMatrix; var worldMatE=worldMat.elements; return this._minZ *this._getScaleZ()+worldMatE[14]; }); /** *获取地形Z轴长度。 *@return 地形Z轴长度。 */ __getset(0,__proto,'depth',function(){ return (this._heightMap.height-1)*this._cellSize.y *this._getScaleZ(); }); MeshTerrainSprite3D.createFromMesh=function(mesh,heightMapWidth,heightMapHeight,name){ var meshTerrainSprite3D=new MeshTerrainSprite3D(mesh,null,name); if (mesh.loaded) meshTerrainSprite3D._initCreateFromMesh(heightMapWidth,heightMapHeight); else mesh.once(/*laya.events.Event.LOADED*/"loaded",meshTerrainSprite3D,meshTerrainSprite3D._initCreateFromMesh,[heightMapWidth,heightMapHeight]); return meshTerrainSprite3D; } MeshTerrainSprite3D.createFromMeshAndHeightMap=function(mesh,texture,minHeight,maxHeight,name){ var meshTerrainSprite3D=new MeshTerrainSprite3D(mesh,null,name); if (mesh.loaded) meshTerrainSprite3D._initCreateFromMeshHeightMap(texture,minHeight,maxHeight); else mesh.once(/*laya.events.Event.LOADED*/"loaded",meshTerrainSprite3D,meshTerrainSprite3D._initCreateFromMeshHeightMap,[texture,minHeight,maxHeight]); return meshTerrainSprite3D; } __static(MeshTerrainSprite3D, ['_tempVector3',function(){return this._tempVector3=new Vector3();},'_tempMatrix4x4',function(){return this._tempMatrix4x4=new Matrix4x4();} ]); return MeshTerrainSprite3D; })(MeshSprite3D) /** *... *@author ... */ //class laya.d3.water.WaterSprite extends laya.d3.core.MeshSprite3D var WaterSprite=(function(_super){ function WaterSprite(mesh,name){ this.mtl=null; this.detailMtl=null; this.mesh=null; this.useRefrTex=true; this.renderDetailWav=true; this._stop=false; this._texWave=null; this._texRefract=null; this._detailMesh=null; //贴图纹理的旋转矩阵 this._texWaveDegTest=0; this._shownormal=false; this._refractQueue=null; this._waterLoaded=false; this._waterFogStart=0; this._waterFogRange=20; this.startTm=0; this.curTm=0; this._syncObj=null; this.afterDescLoaded=null; this._geoWaveInfo=new Float32Array(WaterSprite._waveInfoEleNum *4); this._geoWaveInfoDir=new Float32Array(2 *4); this._texWaveInfo=new Float32Array(WaterSprite._waveInfoEleNum *15); this._texWaveInfoDir=new Float32Array(2 *15); this._texWaveTrans=new Float32Array(9); this._refractObjStack=[]; this._refractObjecs=[]; this._scrSizeInfo=new Float32Array(2); this._waterColor=new Vector3(); WaterSprite.__super.call(this,mesh,name); this.mtl=new WaterMaterial(); this.startTm=Laya.timer.currTimer; this.curTm=0; } __class(WaterSprite,'laya.d3.water.WaterSprite',_super); var __proto=WaterSprite.prototype; __proto._getWaveInfo=function(out,outdir,i,deg,L,Q,A){ var st=i *WaterSprite._waveInfoEleNum; var dirst=i *2; var r=deg *WaterSprite.deg2rad; outdir[dirst++]=Math.cos(r); outdir[dirst++]=Math.sin(r); out[st++]=Q; out[st++]=A; out[st++]=WaterSprite._2pi / L; out[st++]=7.846987702957 / Math.sqrt(L); } __proto.onDescLoaded=function(desc){ var _$this=this; var mesh=Mesh.load(desc.mesh); this._texWave=new RenderTexture(desc.detailTexSize[0],desc.detailTexSize[1],/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5,false,false); if(this.useRefrTex){ this._texRefract=new RenderTexture(desc.refracTexSize[0],desc.refracTexSize[1]); this._texRefract.repeat=false; this._texRefract.mipmap=true; this.mtl.useRefractTexture=true; }else { this.mtl.useRefractTexture=false; } (this._geometryFilter).sharedMesh=mesh; mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._applyMeshMaterials); mesh.on(/*laya.events.Event.LOADED*/"loaded",this,this.onMeshLoaded); if (desc.skyTexture.substr(desc.skyTexture.length-4).toLowerCase()==='.ltc'){ this.mtl.skyTexture=TextureCube.load(desc.skyTexture); this.mtl._addShaderDefine(WaterMaterial.SHADERDEFINE_CUBE_ENV); }else { this.mtl.skyTexture=Texture2D.load(desc.skyTexture); this.mtl._removeShaderDefine(WaterMaterial.SHADERDEFINE_CUBE_ENV); } if (desc.hdrsky){ this.mtl._addShaderDefine(WaterMaterial.SHADERDEFINE_HDR_ENV); } if (desc.deepScale !=undefined) this.mtl.deepScale=desc.deepScale; if (desc.useVertexDeep){ this.mtl.useVertexDeep=true; } this.mtl.skyTexture.repeat=true; var infotex=Texture2D.load(desc.infoTexture); infotex.repeat=false; this.mtl.waterInfoTexture=infotex; var foamTex=Texture2D.load(desc.foamTexture); foamTex.repeat=true; this.mtl.foamTexture=foamTex; this.mtl.renderMode=/*laya.d3.core.material.WaterMaterial.RENDERMODE_TRANSPARENT*/13; this.mtl.waveMainDir=desc.geoWaveData[0].dir; this.mtl.geoWaveUVScale=desc.geoWaveUVScale; this._detailMesh=new QuadMesh(2,2); this.detailMtl=new WaterDetailMaterial(); this.detailMtl.texWaveUVScale=desc.detailWaveUVScale; if (desc.geoWaveData.length !=4)throw "error 3"; if (desc.detailData.length !=4)throw "error 4"; (desc.geoWaveData).forEach(function(v,i){ _$this._getWaveInfo(_$this._geoWaveInfo,_$this._geoWaveInfoDir,i,v.dir,v.L,v.Q,v.A); }); var kAmp_over_L=0.01; (desc.detailData).forEach(function(v,i){ _$this._getWaveInfo(_$this._texWaveInfo,_$this._texWaveInfoDir,i,v.dir,v.L,1.5,v.L *kAmp_over_L); }); this._waterColor.x=desc.color[0]/255;this._waterColor.y=desc.color[1]/255;this._waterColor.z=desc.color[2]/255; this.mtl.seaColor=new Float32Array([this._waterColor.x,this._waterColor.y,this._waterColor.z]); this._waterFogStart=desc.fogStart; this._waterFogRange=desc.fogRange; if (this.afterDescLoaded){ this.afterDescLoaded.call(this); } } __proto.onMeshLoaded=function(){ this._refractQueue=new RenderQueue(this._scene); this._scrSizeInfo[0]=Laya.stage.width; this._scrSizeInfo[1]=Laya.stage.height; this.mtl.scrsize=this._scrSizeInfo; this.meshRender.sharedMaterial=this.mtl; if (this._render._renderElements.length > 0){ this._render._renderElements[0]._onPreRenderFunction=this.onPreRender; }else { throw "error2"; } this._waterLoaded=true; } __proto.stop=function(){ this._stop=!this._stop; } __proto.addRefractObj=function(obj){ this._refractObjStack.push(obj); this._refractObjecs.push(obj); } /** *渲染之前,生成必要的数据。 *@param state */ __proto.onPreRender=function(state){ var _$this=this; if (!this._waterLoaded) return; if (this._refractObjStack.length){ for (var i=0;i < this._refractObjStack.length;i++){ var obj=this._refractObjStack[i]; if (obj._render._renderElements.length){ obj._render._renderElements.forEach(function(v){_$this._refractQueue._addRenderElement(v);}); this._refractObjStack.splice(i,1); i--; } } }; var gl=WebGL.mainContext; var olddf=gl.getParameter(/*laya.webgl.WebGLContext.DEPTH_TEST*/0x0B71); var oldcf=gl.getParameter(/*laya.webgl.WebGLContext.CULL_FACE*/0x0B44); var oldvp=gl.getParameter(/*laya.webgl.WebGLContext.VIEWPORT*/0x0BA2); var needRestoreVP=false; if(this.useRefrTex){ this._texRefract.start(); needRestoreVP=true; gl.viewport(0,0,this._texRefract.width,this._texRefract.height); gl.clearColor(this._waterColor.x,this._waterColor.y,this._waterColor.z,1.); gl.clear(/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100 | /*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000); this._refractObjecs.forEach(function(v){ v._renderUpdate(state._projectionViewMatrix); }); this._refractQueue._preRender(state); this._refractQueue._render(state,false); this._texRefract.end(); this._texRefract.repeat=true; } if(this.renderDetailWav){ this._texWave.start(); gl.disable(/*laya.webgl.WebGLContext.DEPTH_TEST*/0x0B71); gl.disable(/*laya.webgl.WebGLContext.CULL_FACE*/0x0B44); needRestoreVP=true; gl.viewport(0,0,WaterSprite.detailTexWidth,WaterSprite.detailTexHeight); var re=this._detailMesh.getRenderElement(0); re._beforeRender(state); this.detailMtl.currentTm=Laya.timer.currTimer; this.detailMtl.waveInfo=this._texWaveInfo; this.detailMtl.waveInfoD=this._texWaveInfoDir; var detailShader=this.detailMtl._getShader(0,0,0); detailShader.bind(); var vb=this._detailMesh._getVertexBuffer(0); detailShader.uploadAttributes(vb.vertexDeclaration.shaderValues.data,null); this.detailMtl._upload(); re._render(state); this._texWave.end(); olddf && gl.enable(/*laya.webgl.WebGLContext.DEPTH_TEST*/0x0B71); oldcf && gl.enable(/*laya.webgl.WebGLContext.CULL_FACE*/0x0B44); } if(needRestoreVP) gl.viewport(oldvp[0],oldvp[1],oldvp[2],oldvp[3]); if (this._syncObj){ this.mtl.detailTexture=this._syncObj._texWave; }else this.mtl.detailTexture=this._texWave; this.mtl.waveInfo=this._geoWaveInfo; this.mtl.waveInfoD=this._geoWaveInfoDir; this.mtl.underWaterTexture=this._texRefract; if (!this._stop){ if (this._syncObj)this.curTm=this._syncObj.curTm; else this.curTm=Laya.timer.currTimer-this.startTm; this.mtl._setNumber(/*laya.d3.core.material.WaterMaterial.CURTM*/8,this.curTm); }else {} if (/*__JS__ */window.shownormal && !this._shownormal){ this._shownormal=true; this.mtl._addShaderDefine(WaterMaterial.SHADERDEFINE_SHOW_NORMAL); } if(/*__JS__ */window.shownormal && this._shownormal){ this._shownormal=false; this.mtl._removeShaderDefine(WaterMaterial.SHADERDEFINE_SHOW_NORMAL); } } __proto._update=function(state){ laya.d3.core.RenderableSprite3D.prototype._update.call(this,state); } __getset(0,__proto,'src',null,function(v){ var ld=new Loader(); ld.on(/*laya.events.Event.COMPLETE*/"complete",this,this.onDescLoaded); ld.load(v); }); __getset(0,__proto,'syncObj',null,function(obj){ this._syncObj=obj; this.renderDetailWav=false; }); WaterSprite._waveInfoEleNum=4; WaterSprite.detailTexWidth=256; WaterSprite.detailTexHeight=256; __static(WaterSprite, ['deg2rad',function(){return this.deg2rad=Math.PI / 180;},'_2pi',function(){return this._2pi=2 *Math.PI;} ]); return WaterSprite; })(MeshSprite3D) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.d3Plugin.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Component3D=laya.d3.component.Component3D,ComponentNode=laya.d3.core.ComponentNode,MeshTerrainSprite3D=laya.d3.core.MeshTerrainSprite3D; var Sprite3D=laya.d3.core.Sprite3D; /** *PathFinding 类用于创建寻路。 */ //class laya.d3.component.PathFind extends laya.d3.component.Component3D var PathFind=(function(_super){ function PathFind(){ /**@private */ this._meshTerrainSprite3D=null; /**@private */ this._finder=null; /**@private */ this._setting=null; /**寻路网格。*/ this.grid=null; PathFind.__super.call(this); } __class(PathFind,'laya.d3.component.PathFind',_super); var __proto=PathFind.prototype; /** *@private *初始化载入蒙皮动画组件。 *@param owner 所属精灵对象。 */ __proto._load=function(owner){ if (! (owner instanceof laya.d3.core.MeshTerrainSprite3D )) throw new Error("PathFinding: The owner must MeshTerrainSprite3D!"); _super.prototype._load.call(this,owner); this._meshTerrainSprite3D=owner; } /** *寻找路径。 *@param startX 开始X。 *@param startZ 开始Z。 *@param endX 结束X。 *@param endZ 结束Z。 *@return 路径。 */ __proto.findPath=function(startX,startZ,endX,endZ){ var minX=this._meshTerrainSprite3D.minX; var minZ=this._meshTerrainSprite3D.minZ; var cellX=this._meshTerrainSprite3D.width / this.grid.width; var cellZ=this._meshTerrainSprite3D.depth / this.grid.height; var halfCellX=cellX / 2; var halfCellZ=cellZ / 2; var gridStartX=Math.floor((startX-minX)/ cellX); var gridStartZ=Math.floor((startZ-minZ)/ cellZ); var gridEndX=Math.floor((endX-minX)/ cellX); var gridEndZ=Math.floor((endZ-minZ)/ cellZ); var boundWidth=this.grid.width-1; var boundHeight=this.grid.height-1; (gridStartX > boundWidth)&& (gridStartX=boundWidth); (gridStartZ > boundHeight)&& (gridStartZ=boundHeight); (gridStartX < 0)&& (gridStartX=0); (gridStartZ < 0)&& (gridStartZ=0); (gridEndX > boundWidth)&& (gridEndX=boundWidth); (gridEndZ > boundHeight)&& (gridEndZ=boundHeight); (gridEndX < 0)&& (gridEndX=0); (gridEndZ < 0)&& (gridEndZ=0); var path=this._finder.findPath(gridStartX,gridStartZ,gridEndX,gridEndZ,this.grid); this.grid.reset(); for (var i=1;i < path.length-1;i++){ var gridPos=path[i]; gridPos[0]=gridPos[0] *cellX+halfCellX+minX; gridPos[1]=gridPos[1] *cellZ+halfCellZ+minZ; } if (path.length==1){ path[0][0]=endX; path[0][1]=endX; }else if (path.length > 1){ path[0][0]=startX; path[0][1]=startZ; path[path.length-1][0]=endX; path[path.length-1][1]=endZ; } return path; } /** *设置寻路设置。 *@param value 寻路设置。 */ /** *获取寻路设置。 *@return 寻路设置。 */ __getset(0,__proto,'setting',function(){ return this._setting; },function(value){ (value)&& (this._finder=new PathFinding.finders.AStarFinder(value)); this._setting=value; }); return PathFind; })(Component3D) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.debugtool.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Box=laya.ui.Box,Browser=laya.utils.Browser,Button=laya.ui.Button,Byte=laya.utils.Byte,CSSStyle=laya.display.css.CSSStyle; var Component=laya.ui.Component,Config=Laya.Config,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var Filter=laya.filters.Filter,GrahamScan=laya.maths.GrahamScan,Graphics=laya.display.Graphics,HTMLCanvas=laya.resource.HTMLCanvas; var Handler=laya.utils.Handler,HitArea=laya.utils.HitArea,Image=laya.ui.Image,Input=laya.display.Input,Label=laya.ui.Label; var List=laya.ui.List,Loader=laya.net.Loader,LoaderManager=laya.net.LoaderManager,LocalStorage=laya.net.LocalStorage; var MathUtil=laya.maths.MathUtil,Matrix=laya.maths.Matrix,Node=laya.display.Node,Point=laya.maths.Point,Pool=laya.utils.Pool; var Rectangle=laya.maths.Rectangle,Render=laya.renders.Render,RenderContext=laya.renders.RenderContext,RenderSprite=laya.renders.RenderSprite; var Resource=laya.resource.Resource,ResourceManager=laya.resource.ResourceManager,RunDriver=laya.utils.RunDriver; var Sprite=laya.display.Sprite,Stage=laya.display.Stage,Stat=laya.utils.Stat,Style=laya.display.css.Style; var Text=laya.display.Text,TextInput=laya.ui.TextInput,Texture=laya.resource.Texture,Timer=laya.utils.Timer; var Tree=laya.ui.Tree,UIEvent=laya.ui.UIEvent,URL=laya.net.URL,Utils=laya.utils.Utils,View=laya.ui.View; //class laya.debug.data.Base64AtlasManager var Base64AtlasManager=(function(){ function Base64AtlasManager(){} __class(Base64AtlasManager,'laya.debug.data.Base64AtlasManager'); Base64AtlasManager.replaceRes=function(uiO){ Base64AtlasManager.base64.replaceRes(uiO); } __static(Base64AtlasManager, ['dataO',function(){return this.dataO={"comp/button1.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGIAAABRCAYAAAApS3MNAAABSUlEQVR4Xu3a0QmFMADFUJ1JXM0h3moPZ6qg4AoNeLqAIenFn65jjLE40w2sQkxvcAMI0eggRKSDEEJUDEQ4/COEiBiIYFiEEBEDEQyLECJiIIJhEUJEDEQwLEKIiIEIhkUIETEQwbAIISIGIhgWIUTEQATDIoSIGIhgWIQQEQMRDIsQImIggnEvYvv9IzjfxDiP/XlgJsTcCyDEXP/v14UQImIggmERQkQMRDAsQoiIgQiGRQgRMRDBsAghIgYiGBYhRMRABMMihIgYiGBYhBARAxEMixAiYiCCYRFCRAxEMCxCiIiBCMa7iAjPpzG8fY3kF0KIiIEIhkUIETEQwbAIISIGIhgWIUTEQATDIoSIGIhgWIQQEQMRDIsQImIggmERQkQMRDAsQoiIgQiGRQgRMRDBsAghIgYiGBYhRMRABMMihIgYiGBcGJiOHTRZjZAAAAAASUVORK5CYII=","comp/line2.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAECAYAAACOXx+WAAAAG0lEQVQYV2NkoDJgpLJ5DIxtra3/qWko1V0IAJvgApS1libIAAAAAElFTkSuQmCC","view/create.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAkCAYAAAC9itu8AAAAdElEQVQ4T2NkwAIWLFjwH5t4QkICIyM2CXQxmAHka/j///9mXDYxMjL6YtgwBDUg+w8crIT8MBQ0oEca55JvWNPS9xgu4tISzADyNfz///8MnrRkgmHDENSALWng9fRQ0DA40xLecglbWhpqGoZCMUNKUQkANAHAJVkE5XwAAAAASUVORK5CYII=","view/rendertime.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAkCAYAAAC9itu8AAABeUlEQVQ4T+2Uv0tCURSAvyNdcwiXBlsaaomWFgeHlqAtCPsDJHwIiUtDSxERtErtmQ6CjkHo4FpDBQ0tbVFR0BYE0eQvOnFF7T17QlOTd3m88873OD8+rtA9uVzOBIPBlIisAwvd8B1QajQahXQ63bIx6QHFYrEEJHrv7qeqZhzHOfYA+Xw+Yow5B+YHoGwymdxW1QAQEFWNAk8i8uEDuZM3gUcLZIEJYNcNqWrVcZyd7p9t8jLwYIFTYBx47UHlcjmcSCQ+B5JtpU0LnAFj3br7kE+yTalb4BCYczVqoT3AjteW4T73FlgFNgY+1IGQz4hPLGCAI2DGbweu2Auw1Vmcqk4C+8DsEOgZOBCR9/6mVdU2vgIsAdOuIVwANRFpezatuahpTYVSop1m+y6pasm8NQqSvvW61KwslkSHuCRkgvErr0taiUXaal1Sr0siWRO/9HfpF+RN9nfpB/qqmrXrv7mktVhYVm5GLo1cct9LI5e8d84/3UvfAgdlKH0EO7MAAAAASUVORK5CYII=","view/cache.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAkCAYAAABSSLCCAAAAcElEQVQ4T2NcsGDB/4SEBEYGBgYGYtmMxCpENhhsA6mA8f///5tHNTEwkBcQpIYcSD15kUtWigi51vR/jVYdOGUQy2YkViGywWSnvTOkhiAonkY1gZIRqSEHTntkRe4g10RWQIyWe5Bgo2O5R7dkBADztyP+yFzirAAAAABJRU5ErkJggg==","comp/clip_selectBox.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAoCAYAAAAIeF9DAAAAsElEQVRoQ+3ZQQ0AMQzEwAuqEgh/Sj2pKObhIrBsrfLonHPu12MMTEGYFg+kIFaPgmA9ClIQzQDG0w0pCGYAw2khBcEMYDgtpCCYAQynhRQEM4DhtJCCYAYwnBZSEMwAhtNCCoIZwHBmd/tTh6IUBIrx/tRbiFWkIFaPFoL1KEhBNAMYTzekIJgBDKeFFAQzgOG0kIJgBjCcFlIQzACG00IKghnAcFpIQTADGE4LwYL8U/BE1dCJ3PsAAAAASUVORK5CYII=","comp/label.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAASCAYAAACQCxruAAAAmElEQVRoQ+3aMQqAQBBDUef+hx4Zq1mrbPnhWylECHmghVZ397OOqqp97TlugdNzgEXFIaaFuwROt0LmBEay5aXb920+FjIpMJItLy1wvhUyKTCSLS8tcL4VMikwki0vLXC+FTIpMJItLy1wvhUyKTCSLS89wPP1Qeh8M0zy+84gMMbruqjA15OxbtjAu7mPa5bj0fb/A8cLgD4n/wQKNiIAAAAASUVORK5CYII=","comp/clip_tree_arrow.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAQCAYAAAArij59AAAAwUlEQVQoU5WRPRKCMBCFWUt6vYQeB06RUDpoBbFDa7yDwm30FGi9dHnOMiQDBgvT5c3b7+0PRVEUlVV9A3NmzL6T//SRfMz5CgCdtVafjlmzaHAigAbM2tE8YVo1pf0yvABoc9D3wACgBbMKIgD4qqDJsqqlMV8VGL5n/88geCJKlijSMBXFZUNx/CSi9WwX1r7R99thzKKqkxXRbMUWSE2u2sEwHsxHCbrMVSq6N4xRD9HAvJstylEkarhurlqnfQC58YP5+CvQNwAAAABJRU5ErkJggg==","view/bg_panel.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAMUlEQVRYR+3QQREAAAjDMGZk/l2CDD6pgl7SduexGCBAgAABAgQIECBAgAABAgS+BQ4oyStBhXcy5AAAAABJRU5ErkJggg==","view/bg_top.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAMUlEQVRYR+3QQREAAAjDMKZp/rWBDD6pgl7SduexGCBAgAABAgQIECBAgAABAgS+BQ6WyDMhXMLeQgAAAABJRU5ErkJggg==","view/clickselect.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAqCAYAAACDdWrxAAACfElEQVRIS8WVO2iTYRSGn5OWqpMOurg0VRBdVVCsg7GgDjpZECyirl4GEYfSgBlaB5VSpApdxCJIoeKgg7dKC21ALahIiyiKKUjxAiI4qCH1lRP/hPhfAnHpGZPv+c4573nP95ukO/xHmINmtq8RtswsPiipB/gAPAFem5nCbcSWKukIsD84/A2YBh4DL8ysWLkk0qOkDcD5GLF+Ac+Ap35ZHGjAdWB5gtJvgZFYVSWdBHaFwBlg1Mw8K0ngFiAbAm+a2XBij/6HpBbgBrAEmAVeAZ1AFU40QDCWrcBZL0/S4Vq4HtgB7DWzU5XyauDBMhhWz70ryVVdb2ZuhGpI2g1MODjfiMFrxZk3s9WNwJ6snHFxQUlXgXfAPeC5mf2O2Y5oqZLcMceCw1+AseCSSTP7mSiOpM3A7RixfvgYgAd+WUQcSSnfPWBlgtIvgf5YVSVdBA6GQF/mS2bmWcvbERmHJF+payFw0MzO1TWApKXBViwL3h5/Pk4AVTjRAMFY9njJXl6wLccrcD3wAHDUzBwuRw18JtbkbkFJruomM7sf2o4u4Jals/mFRgxeFcfBQm97UyOwM+WMiwums/k3QnMps+HWpuLIRC5TCrcRW2pbT35MRiY4XDRsVmiU5uJQIZfxb0k5Ij229eQPySJ287MLGO8Rd1M0XY6AO3LjzYVSy3fAH+VICL4a6o9VtTWbnzbYGKI+IrtQ6Ns2EFuq/5jOTnWD9f4DikeFvvbqhyg2Yzo3voJSy2fAjfEJMYPRQQ2caAAfC7AW2WkvrzU79dCwnRW4Hjgg6JrrbV9VKbkKw1Csyd2Ca7on1y2krHOub3t16//2n79SarbsH7BKtfejoCjmAAAAAElFTkSuQmCC","view/resize.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAqCAYAAACDdWrxAAABeUlEQVRIS+2UvUpdURCFvxXRKJpIEBURsVAIiiBoaaGCjY2VLyH4MBaCPoWlnQlpI6SxsQmkURQL5eK/6JK57iuRnMPZtxAkuOFUhzWz96xvjcg8tluAT5LOQqJMHba/AgPAD0nOEtruAOaB6Lon6U+ucAoYTLe7Bb5XCm1/BCaAXqAVOAHyOkYn27PA5/TGWmXHxvBeT2i7TVIM4MUp7ZhGPlY3V/pVKUxEjAIjyac74LIAjK70PwCoyfYXYDJwyqDoHtiRdFOfql0naBgIrILF/ZIi1yH6h1XbYXCPpKOq7s34GEX7JB00m445YBzYlPSQ1dF2N7CaWN2W9DNXuJxAj1uGVeuVQtvh32LyuR34DexWCv+CfAXoBzYkHb8Boe1OSRcFkBdfNY18IQiUtFUpTJjNAPEFHVfAaQFyjZ3zNBzbQ8BSWkZViEbk1uIpjXR8AKbT7jwEvpVUqEk6L0pHLN5hSWWxeq7XjI/v6Sgz0vZ7Ov7DdDwCkcb1m86tSukAAAAASUVORK5CYII=","view/clickanalyse.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAqCAYAAACDdWrxAAAC7UlEQVRIS5WWT2hUZxTFfyfGFolkoUVKrHQiEaX+IfgHa54UQzUqpWYhLbQU6ULNwgYXuog6yiiTgK2LgtAu6yqbFkpRBEURQzJEBN200NqKkxoDLnQhFUrizJU7vje8SSbzZr7FwDy+c75z7z3nfU80uMxMDin9JC0zewvYAHwIrAH65wWaWQuwOdy8CVgUHnBd0sUKoJktBbYC24B1QHMVNeck3ZWZrYhtXpUg/3/gS0kzDnT2/cDqpFqBUUnnK5pjZutDgo01Tr0g6XbVrprZypBgO9AUU/EK+ErSyzLQzC5XkTkCfBR7fl/Smeh/qasOlPRp9DAkOgp8H5P9o6SriUAnMrOzgNdswNeSntcL9IYNAQ8kHYuXU5Y6u8ZIupldAO5I+nkOsNb8wjk/ljTZKFCSvMbSMrPSiOpNx9uAz3UP4IbfWSsdrcDH4eZuYHF46LCk47PT8S6wG9gbJmRhlfoPSLrhJvdERJs7E+S73dZKmnagsx8JB50UEHdY3+x0dIUEO2qcekTSr/OlY21I4N5dEJMwA6yX9CKejqkqGn8DemPPb0v6YrZXpyS1xYbsRD3AtZjsk5IuJQKdyMyGAa/ZnbNR0tN6gd6wXwAP8SfV0jGnxki6mV1xyf4ubdTkPue/Jf3TEJCMNZFRMQLtyNwqvaTrSkdHZry1MFM8bLLPgY5U8/SyeYHvncotb5b1A/t8c2QGg3sT2WBLBbD95PiGogr9Ej0Gbap8r4ZJ5kR+MPhW7WdGd5npEFaa15IE+YWW5uklf2S6/1N7OnfasG+Ad5KiAfyVzwYfVDQnlc71YTaA8Ntrvtq/y2eDgapdTZ0a60UMhjdvmcCgWDClJge7npSBqfRYYY5M6U/M/NqO1mQ+G7xf4VUH5rNBOXtviLQfzH0afizop0fZroOJQCdKpcfyUKrZFhTpfDgU/F4nMNcH9gPwLJ8Nls3xarUaI+mp9NhTg5GJbPBZQyb3OReayP17rutmHPga1PpCOk+zrlEAAAAASUVORK5CYII=","view/res.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAoCAYAAAD6xArmAAADwUlEQVRIS+3WT2gcdRQH8O/b2SwNC7l4MAEPvbilUkoPOUmLjSDrZn4hxYKH/kGwyB4tQogiu/N+GymyoWguhVBQKKkHQTHsW9fUQwqKp4AgtMXkInhILl4CkoTdmSe/6XZp2pntLli8uMedt9/3mze/33yW8Jw+9Jxy0TeYmV8FcFVVTxPRiwA6AP5U1TvZbHapUqn8nrawxGBVJWvtNVWdJ6K05h1V/dhaW08KT/wRM1sAVQCRqn5JRLdyudw9Iora7faJKIrKqnrBNSWiahAEC0+GHwpm5utEdD+KopsuBMDbzPxt0oqstRdV9Za7lslkzlar1Z8erzsUHATBJhG93C34fmJi4ly5XG6nzTEIgjoRzanqkrX2amowM98F8Fq3wK34PWb+Ii14cXExv7e3V6hWq78+axQrANwt/kVEl5j5h0G2IzMfUdWCtfa3R/VPzvhTAG8AOM/MfwwYehTANwB+ZOYPE4ODIDhJRJvMvD9IqLW2GEXRbSJ6AcBtZr6UGPzoS2Y+lc/nt+bm5v5Oa2CtvaKqywC8bs06M7+eGszMn7nTBqDOzPNpwcvLyyPb29vfAZh2Naq6Za0tpAbXarUzURS53eGKL1trv0oKZ+a3AHytqplMJlOOoui4tfaDvqOw1lZUtabubBOtqOqN0dHRB/v7++62XwHwDoB33dkAUGPmoO92e/yitXZeVT8BkE1acbdpPQiCj4hIBw52hQsLC8c6nc77AN4E8FK3yQ4R/Qzgc2b+Je0ZDPU+fjiZp1eXFD5U8CB7u+/DGybgXxnFMA3/m1GISGwegNMAeuYBuON53lKpVBrePBG5RkTuSPc1b2ZmZnDzRKRnHoDYvIODg3u5XM69/E8AKAO40G1aNcb0N6/ZbF5X1fsAbjpInXnGmETzGo3GRdew+0DPGmPSzRORTQA988bHx89NTk6mmtdoNGLziGjJ9/1085rN5l1VPWSeMSbVvLW1tXwYhoXp6en+5olIbB6A2Dzf9wcyb319/cju7m5hdnY22TwRic3zPO98qVQayLxWq3U0DMPYPGNMsnmrq6snx8bGNqempgYyT0SKzjoAsXnGmP7mNZvNU9lsdqtYLKaaJyJXABwyzxiTbp6IxOYRUd33/VTzNjY2RnZ2dnrmAdgyxqSbJyJnAMTmEdFl3/cTzROR2DzHk6qWiei4Maa/eSJScZY99FRXPM+7MTIy8iAMQ6/dbsfmEVHPPGPM4OaJiBtDqnmuqfuL4Pv+8Oa1Wq1jYRg+ZR6A2DxjzP/mPRupfwAf56Q4urCh6QAAAABJRU5ErkJggg==","view/tab_panel.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAABICAYAAADyMAW8AAAAcUlEQVRYR+3WsQ3AMAhE0TCMeyTvP1tShRQo7lxYegxA8fUPLuac97VhwuKXKhTlFxRQ9GPDClawYvGEDwxIZu7pFRZXr4ACinY1ghWsYMX/NxWQr22edyvGGHt6hcV1NqGAon8QVrCCFYteISDnBuQB3xJuQcDkEngAAAAASUVORK5CYII=","view/btn_close.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAqCAYAAACz+XvQAAACmUlEQVRIS7WWS0/bUBCFz7mJmyZxENm06mNVoVZC7LqGn9FNqy55/BSWSEhs2/4uuqFVoA150JLKJvGdaiIH2TfXNoKQpeP5PHPO3GMTK/5xxTwsAUWkBeBZ+qAByb/Zh4pIA8CL9NqY5Dj7vw9YA/ABwDsAfwB8ITnUIhF5CuATgNcAfgH4RnJSCkwLl6AA/lXBtLZQQxFxoTr6q6LOFl2WmuJAtcY7ZuXIixsczfRyTlPfhpSN7BpwBeBtFdQLFJE2gI8AXi7GBBBl3Fdnv5L87XbpWxuFfQbw3NXM0dQLLdrDIH3ylGTiLLYB8CS9lpCc3tmU+xzL1Z9lEXl/n06KavjowCiK1uM4fqMd1Ov1s3a7fZntZjabtSeTiQYHgiC4aLVavZwpbofT6TQYDAaH1tod3bMwDHc7nc5PLZrNZmG/3z8WkS1jzGm32z1oNBqjUqD+6YM2m81xFWyeNkUaulAAlyKyWdTZbdqUmZKFakEVrLRDV7P5zY6m3rQp6tA1AMC5tXY7he51Op0fdwbGcdwdDodHWc2MMdcL9wGM1tbW9sMw/L6UNm6HChuNRifW2g1XM0dTL3TJZS1KkkTDFbVaLQqCIJcm6k0URRpxuvg39Xo9rtzDh5zt1Z/lXq+32rR5dKC1dt0YM08bAGd65BxN1ZB52ojIBcl82rgdWmsDkocAdgDoW22X5DxtSIZJkhyT3AJwCuCAZD5tfCP7oMaYcRVs/tAiDT1QHX2zqLPbtCkzxYFqjXfM3GKXAR3NtC6nqTccioAeA84BbCuU5B4Af9r4gCLSBXCU1UxErjPuj0Rk3xiznDYuMIWdANhwNXM09UKXXNai9LtQ9y4yxuS/XUijr9L0lXBDMp82j370HhJdWvsftiHJYFPSIqEAAAAASUVORK5CYII=","comp/combobox.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFsAAABCCAYAAAA476rKAAACfElEQVR4Xu3bMYsTURQF4PMmExgIWkgEU5hskyJYxGYKY5VS7NzCylL8Bftj3NbKQjuxTBWbaUwhKdIYLCJotlACA5m8kQTZZZkkeN9dbuNJOXPPu/DN5ZHkMa7dbpfgx0TAEdvEedeE2HbWxDa0JjaxLQUMe3HPJrahQECrNE3RarUOJheLBbIsq9znZAdgJ0mC4XCIer1eSa/Xa4xGI+R5TuwA272RTqeDfr9fuTeZTDCfz/dmONkK/cFggGazebnCcrnEeDw+uCKxFdiNRmO3nURRBO/9bvtYrVbEVpgejXa7XfR6PUynU8xms6O1nGzlU3DO7fbu7V5dlsf/0yO2ElsSJ7ZES1lLbCWgJE5siZaylthKQEmc2BItZS2xlYCSOLElWspaYisBJXFiS7SUtcRWAkrixJZoKWuJrQSUxIkt0VLWElsJKIkTW6L1t5an6wFooRGerofKBeZ4uh4IFxrj6XqoXECOp+sBaJoIT9c1esIsT9eFYFbl/J5tJc13agyliU1sWwHDbtyziW0oYNiKk22JfXJ6xnfXjcDdFttnb43a/b9tovQ5iG30/IltBL1tQ2xiGwoYtuJkE9tQILBV/ugl4rh2MF1sPJJP59fuc7IDsTe37mHz8Bki+MoKHhFqn9+j9vs7sQN9K7G89xRx837levHzG5Lph8p1TrZK3iF//ApxdLVI4YFk/BpA9Uc5sVXYwObOCfyDJ3AoUcIh+vIRtYuve1clthJ7G8/7p4hv30Xx6weSybuDKxL7BrARxcjTF0iyN4AviH0Tpto1ONlaQUGe2AIsbSmxtYKCPLEFWNpSYmsFBXliC7C0pZfY2oWY/zeBP8uaLni/AFTVAAAAAElFTkSuQmCC","comp/textinput.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFsAAAAWCAYAAACv8OArAAAAZElEQVRYR+3UQQkAMAwEwcZI/LtsoSL2NTGwMByZ3b3HJQIDO3H+EdidNezQGjbsUiBs+dmwQ4EwZdmwQ4EwZdmwQ4EwZdmwQ4EwZdmwQ4EwZdmwQ4EwZdmwQ4EwZdmwQ4Ew9QBe0R29X9x+dwAAAABJRU5ErkJggg==","comp/vscroll.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAhCAYAAAA/F0BXAAAAOklEQVRIS2N8+OzVf2YWFgYmJiYGcgHjqCEYQTcaJpipaTRMRsOEmDJmNJ2MppPRdEJMCIymE2JCCQAYonwDuu2VMAAAAABJRU5ErkJggg==","comp/vscroll$down.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAzCAYAAABxCePHAAAC/klEQVRIS+2WS0wTURSG/zszBcrLFVvjio0LiAqRRDAmGpRodFE1MQQQkOKGqBujRo3ExLjB4MaKgDzUaGQhvoJGYwAjYoioERcuDGxYEIwPkBY6nWvObXuLnXZaSklYOIu5M/fxzZn/nvPPsInJKa5qGhRFQaIH+w8xSbcymtTd+gBFYXAdyjM9sf7ORxgGR0t5/j9jpkhq2t5B0xQwBrgqNsnJ9V0j4BzQdQNtNYXWkKz0NDiaXkBTFTCFoaWmCHVtQ+AGh+4z0HNiO2bmPNYQGiXQvkuPoaqqiIgi8Pl8eHBqtwlA86MKS6Cy8z1gjIFzjqcXHBEBlpBgRNuOd+HVlYqogJiQIChcg/BtW5k8SaSSkxPJ5PRPTttHfkI7kcghIpn8NYfp33NLXp+TnYG1OWvA3ox9499nPSjdkCsgHJxOIjc43VMrugL9dEUD4Oj/PA4CsUfDX/jOjbmisHTDCCzi4t4QgLDrQF+qTYOmqhgYGw9BvLpv0ZNjQwieaU9b7ZCDriFhSt3VBSZNartHA6aUJ7SK+jqO5n5pSp1HiqSw1e3Di0ypwBpiU1XsudwnTanraDEqrg2GmZLbGkJh2jQVZY29JlPqPe03JX/uxLE7Nk3DjjP3pCn1Ne7HrNsjdYoLQsmWYtNQ3NCBgeZKzLrn/foEoogbQgvSUmz4454P7VQikGhpHzGSZdVOUqqYTGli6gemZ9yJ+0lSTalk/TrxtQOYaBnESbTinokev4UG+p+9/xoyJQKQn8x7vf7JjEFZ1FJBBvuC12RINIdAwtkIQuksnxgHhKBUZ6scQtLSNyiWJpav47z9STjbjfJ8k5iVN0eEs911bhZjUTWpbR+RztZ6uFBERNCq1rfS2e43lFhDsjPscDS9lM7W4dyCquuvpbM9PFkq0iHm7mSl2yP+bj05uxdeXZe5FHOL6Xdr17nQ79bziwew4NXFqwUTMiaEtKBPwtZjnRi8WgXPglfqsyQITc60pwpAeNpH1GRZtRM0pWVVcTJM6S+dYaRsIf025wAAAABJRU5ErkJggg==","comp/vscroll$bar.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAA/CAYAAAAGyyO8AAABYElEQVRYR+2Wv0sDMRTH30tarCg6dRWnQnFT6OiqoP+tk+Cig+AiHayDiNSlg+jgD47K1US+Lwm5s4o/mkElN1xy73KfcF/efTi+Ht3Y0X1Btw8FffdoLy3QSnuZ+HhwZe+exrS13hGGJYsTWSszN0rJ1zHDDbJ0eDYkgHjv5Nxub3TIGEsTY/xDVq6NAN7MfW2u2aCG1nQ0GEZIOXmp7Pw5BPDF+VaGIGQfbM6k0ng5kw8/wF/eJzP5JInZkjg2CSS8zk6vCys7Wb8r5qqsncAP+pdR1Lu9rvgVT4uYg+3F+PCtAzjzu/taKdKKBSS2/wkEMBg/Q+rB50zqzZb7ZPoD/GeZ1HySxGxJHJsEEl5nc22VmCFalpFJTjLKNUtFxlDfP72IogYAP8PPZekWM5OqjErFWpjjbxprABJRA/JYjOOOX4Bgo6bWGYKsfMg5k+lmy5n8uUxm8kkSs6Vw7Cstibc9Fv5vWQAAAABJRU5ErkJggg==","comp/vscroll$up.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAzCAYAAABxCePHAAADF0lEQVRIS92WTUhUURTHz31vPv0KKmkXrtxUGNomkCANLdCUpEatJFuIClIEFRl9kGH0BYWQElLpotGKEJXAtKQooYUFpi1axLQZMCyyZJqv926cM2/uTM288emoUHfx3v16v3fuuef+72Hume/c7/cBAwaLKWaLBZjLPc0Zk0CSJGBs4SDOObDP7i9ckuXkIbLJRJDFFrJk2SGNvZNwy7ExoZEJLWnqfQ+4SlUFaHNs0gXpQhq6x0GWGe0Y7oCicGivyYsLigup7XgFJlkCJjFwNm2HqrZR4CqHoKLC3fr8GFAMpPLqEJhMoZjpay6Bnx4vpKfYoLx1kCwKBlXoOV78BygGsudCH1nwtNVBgHBBUFFzL1n0+Gx5YghOxhINiAbFG1uZODESxf+bJShKrulv8HUusp1G/IBz1qTZIGvdamBjU584Aopzs+lbDhwfFFgc2/imLq0fazgAHF5MumBtuh3YwJsPfGdeNqgY1qqqfcSprRLgr7rWZzWbwCTL8HLKFYEEgkrUn+eHIDzNbltBSG33O+jcnxNZmrYcw5Yc7hoXotRenRPyz0IgBzrGYkTp9qEtxiEV10eEKD08Wgh7bzwTonSvIV/soK5jd53rE6I0eGY3/PL5wWYxQ+nFgShRKqK6LqTwhJNEafRKNQHCcWK3WmDHqR5NlMoSQzAWUV+9vkBMsKXYLCSbs3Oe+SGqqupGrIL3h3YclifYkjo7yZ7izIzUUGrhnvXAzA+PURkR8xCwPnMVsCUVpW0bsiCUKOH9S0980JvaLJSQUTal9Q+9/RgRJQSgnvgCgdBkxkCKektSpC9cR0HCOQgiZUMI3njijwYg+COzLP9rkLr7E3Dn4Gbhp7BPDC+n0TkhlK2zJpccuSBIfVdsutVdt9U4pLbjtVC2B0cKYN/N50LZHh0rFGGguztV14aFsvWfLiVhSrVboaSlXyjbk/NlBNKFVLT0k7INX3KAx+sXfkBlKzjpJItGLlcmhmSkptAB83h9MTuCICxBRUkMwUmY5+uFPY7LmJ7GW05SZycsSos9xUsmSr8BfgGeWI6+BgEAAAAASUVORK5CYII=","comp/button.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAE0AAABFCAYAAAAPWmvdAAABA0lEQVR4Xu3ZMRGDUBRFwXwfKSgxFhfRgAbUxEakkCEO3qmX+p9m5w7NW9v7cz18I4EFbeT1fwxtbgYtmEGDVgRC458GLQiExNKgBYGQWBq0IBASS4MWBEJiadCCQEgsDVoQCImlQQsCIbE0aEEgJJZW0Pbj64Q3hFvQhmL3CQ8atLlAKCwNWhAIiaVBCwIhsTRoQSAklgYtCITE0qAFgZBYGrQgEBJLgxYEQmJp0IJASCwNWhAIiaUVtOfrdMIbwi1oQ7H7hAcN2lwgFJYGLQiExNKgBYGQWBq0IBASS4MWBEJiadCCQEgsDVoQCImlQQsCIbE0aEEgJJYGLQiExNIC2g/MxaMp6CSauwAAAABJRU5ErkJggg==","view/bg_tool.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAMklEQVRYR+3QQREAAAjDMCYG/DsEGXxSBb2ke7YeiwECBAgQIECAAAECBAgQIEDgW+AAAeIuAVS/mngAAAAASUVORK5CYII=","comp/minBtn.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAA8CAYAAAB1odqiAAAArUlEQVRYR+3X0QmAMAwE0GQN19B9nM193CmiIH7ZXOAoRc/fpjl8jVDdOj/eOc8USBcXqUjLAtDQRMSOdHb3JatTYCZUXodIy10bGxTI1Lx6/YA0Ima6W2tKFcjmdpGKtCow7NBAdxozy+804Gfx/cDqbLzWDzs0ekNY4B9nOMEehMKTVIEEyKeFSKmc18+MppRtipJuYPCa1SkwEyqvo6Tlxm8bFEijvBt9n/QA/fOPydLHcUIAAAAASUVORK5CYII=","view/zoom_out.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAoCAYAAAD6xArmAAACy0lEQVRIS92WQU8TQRTH/28oQkj0CL0QOMAJQkz4DkS6A+GA+A00Hrhj0uy8NiTwEdBPAOrB0Fnq3U8g6gkOSjxUjpCQCu08M5u2qaVAt7YmOqfNZPa3b9/+Z35L6NOgPnHx98Gbm5sTlUplA0AGQBpACcBBKpXazmaz3+5607YVM/MjEXlNRPdbASJyTkRrzPz+Nvg1MDNPAvgI4AGA10qpvHPuSCk17ZwLAazV4HPM/PUmeDvwSwBPAbxl5sf+RmYWZo7XMvOehwPYYebnScAnAMaVUrNhGH5pBefz+Rnn3GcAJ8w8kQT8E8A9AEMA/HXrqM9fMrO/bjvataJvFdd7/IaZfS9/67ExZpeIngB4xczPklQ8KSKHPmoispdKpXKjo6PHp6enU5VKxXhoV6moVXhnjpVS5wDOwjD81K7qG7e033lXV1cviMjvvDEAP0TkYHBwcKtarT4UkXcALolo1RhTaIV3dVYYY9aIyOfZDw9fMcYUm+FdgWvtYgCmBisrpRbCMPxQh3cNbgM3zJzvCdhDcrncuojMA8gy8/eegTvO8U0Lk87/UY9ve9h/BI6iyJ+1GyLScB4RHQDYDoKgO+dFURSfFQCuOQ9A7LwgCJI5r1gsTlar1YbznHP5crl8NDw8PK2Uip3n4QMDA3OLi4udO89a23Ce1jp2nrVWtNbxh7bWxs4jop0gCDp3XhRFJyIy7pybXV5ejp3XDN7f359RSsXO01p37jxrbey8i4uLoZGRkWvOa5q/1Fp37rx+VtxwntY6dl5zK6Io2hWR2Hla686dV0vFoY+aP8xFJJdOp49LpdIUEZkaNHkqfIWd5JiIzkXkLAiCZM7zO09EYueJyBgRxc4joi0ADeeJyOrS0lJvnBdFkf8xbDhPKbWSyWR647xCocC+53XnAVjQWvfGeS1wo7XunfOstesA5pVS2Uwm8w877xeHf444cscwYAAAAABJRU5ErkJggg==","view/refresh2.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAA/CAYAAAAPIIPGAAAEIElEQVRYR+2XTUhjVxTH/+fGpBrGT/xoBQdFFMMQLNLNbLooLbaFzqKMUhCSZwsuhGG6KCNd6DuRLgqzmGVxUd8LUrpoYWZTKO1yNi2F1oVtceEHflSLqNEav8bklPuqgsl75sUPSsucTQj33v895+R/7y+XcA1B16CJ/6GoYRiDItKfzWZjExMTv5/XtoLlx2Kxm0qp1wH0AHgTwC4RfWRZ1mdewp6ig4ODN9Lp9CMieh+AchH41Lbtj92EXUUHBgaCh4eH3wJ4zSObGSLqtSzrZ9+ihmF8CODR8YIflFL3MplMNxF9IiJWIBC4Pz4+/ldR5RuG8QuAlwGsAWi3bTsVj8dvAWhOJpPfFPK2a/mGYewDeAHAV7Zt9+aK9PX1VYRCoVcApNxa4CX6J4B6AE9t2341V9QwjO8AvAFg27btytxxL9EvAbynJxNRj2VZX58sjMfjd4joyT9D9NiyrHf9iup+/gggBCALQPfxVwARAO8cWywD4LZt2z/5EtWT+vv774rIBIBSlx/mmT5dyWTyC9+WOpkYi8XalVIPRKQbwItEpHv9PRE9tCzrt6IsVcgyhcYLnv1CAkWXfxFBxzEXXXipq+8imz7P9CJdO3+N754y86A+vYFAIDY8PHw58DHzTQB54DNNs3jwMfONY6R4go+Z/YNvbGwsuLKyci74APQys3/wMfMZ8InIPaVUt4g44AuHw/eHhoaKAx8znwEfM6dGR0dviUizaZoXA59pmvtE5ICPmfPAx8wVABzwubXA1VLM7IBPRJ4mEok88DHzKfiY2R/4mPkUfCLSk0gkTsHHzHdE5Immnog8TiQS/sDHzK7gE5EIEZ2CTyl1e2RkxD/4TNO8S0Su4BORZ0qpftM0iwefaZrtAB4QkQM+AA74ADxk5ufgc78CfV99xdy61yMajUbfAvA5gJeKycZj7gqADygajf5xRYIn+6xoUbmCDM9I/LuidXV1qK2txdzcHPb39ZPAOwpmGgqFUFFRgerqauczm81iaWkJa2v64eLhU6+eKqXQ1NTkZOcWq6urWF5edh1zzZSI0NbWhvLyctdFBwcHmJ2dxe7urn/R+vp6J0sd6XQaCwsLqKysRGNjI9bX17G4uIhMRr8jiig/EokgHA7j6OgIU1NTjkBZWRl0f7e2tgo60LX8rq4u/UjC5uamU2ZuBAIBZ1O9mVsLXEU7OztRUlKCnZ0dTE9P54nqfmsnaNHJycm8cVfRlpYW1NTUOJN1pjrjk6iqqkJra6vzNZVKYWZmxp+oLq2jo8NpgQ7dx729PZSWlkKL6hARpwr9Q+aGp/m12Zubm6H9mhtacH5+HhsbG/4tdTJTZ9bQ0OD0LxgMOm7Y3t6GNv55R7XgMS3oH5cJ/y3Rq775V3X5bx8zSv8DuWzoa2vgb5tumbHGlerDAAAAAElFTkSuQmCC","view/settings2.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAA/CAYAAAAPIIPGAAAD2ElEQVRYR+1Xz08bRxT+ZjAGYQoH4rS9IBJBQJEsUC8VKNdQtamUE0fLayqhKHeOaGbFkT8gFVLZtXzk1qqKSs4NUg8RXCIQVoOQ2jRFHHCwBRj2VW+zttY/14BXVaPOyR7NfPN9771536xACEOEgImPDHRhYaHv/Pz8kEMVjUbjq6urxVZhayo/lUo9chzndTabfWMYxkMAGx7QrG3bL5LJ5B0p5f1MJvNz7QENQdPp9LdE9CMAZrcHYAaoxJ8AvARwD8AtAI9t2/7JD9wQdH5+/q7jOLzx04DqeCelnFlbW/s9EJQXGIbxq8eQ//4mhPieiJjlEwBf8qQQYtOyLFZRNeqYJpPJWCQSeUBEzz3JrwqFwvT6+vo575ybm4vGYrFNAF8AICnlbKlU2sxms4Uych2oYRh5AJ9UFggxb1mW5aeSTqfTRLTmm3tv2/bAVUCfWpb1zA9qGAaHwD/XGjQU+WVGHU0Ug4ZSUjXFnwMwXVP8nP1RAPG2i5/Z+q9pKpWaFUL8wvNE9FUmk9m48jWtLWavofztNZTb124oN2neH1mTvmoo/pcfHDGtdZ9nLbw4rrW+nvGZpvlISvl6aWnpjWmaD4nINT4hxKxS6sXy8vIdx3HuK6XaMz6ttWt8QohDInKNTwjhJtWzlJdCiHtEdEtK+VgpFWx8Wuu7RMQbWxofEb0TQsxordszPq11Q+MjoidCCNf4AGxqrYONb2VlJVYsFh84jvPck/yKW5/W2jU+rXWUwdj4OBQcYzbCxcXF5sanlMoLIaqMTylVZXymaVYZHxG9N02zufE1AH2qlKoyPqUUh6AyFwgaivzyVehoorxkdL6k/MUPIEdE0/7i5zcUGx8Rxdsufmbrv6ZKqSrjM01z48rXtLbFeA3FNT4At6/dUIJ7V/MV/6HOn0gkvgbwA4DPbyLZ2/sWwHcikUj82SHAMqe3DMrv+I6Ofw9USonJyUlXzfb2NhzHaamsKdPBwUGcnp7i7OwMAwMDGBsbc4H29vaQz+fR09OD3t5eHB8f1x3QEJQBR0dHcXFx4QL39/dXbTw5OXEBI5EIcrlcHXBDUGYxPj6O7u7uljJLpRJ2d3ddNf7RVD6DlhkWCgUcHrof0YjH44jFYu5vnt/Z2QmWz0lhsHIMi8Wiu/HDF6T7mMDExAT6+vjR8iHGHA5/8uqYTk1Noaurq3L6/v4+jo6OqtgMDQ1hZGSkMnd5eYmtra3K/0DQg4ODivTyLg7B8PBw+6ChyC8f39FEMWgoJRVK8TPbjl/T2mruWEO5SYMNo/P/xaDfeB712U3YeXv/ALDwD+TbY8Dbd9BBAAAAAElFTkSuQmCC","view/setting.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAkCAYAAAC9itu8AAACAklEQVQ4T5XUS4iOcRTH8c9xCeVeiiiXhSJRJFIusRO2lEtZKFlgY6GxZDUrk2TFwii22JJLlERRLKRQJmXBkHIb8+hM/2d6ememed93957n93v+55zf9/mHll9VVTNxopTPR8T3piTyT1VVs7AL9zEd+4roOn5gK25HxLfacAjL8A8TWw6ta28jorc2LMLhIu7Ds2Jah4XlRVci4mNUVTUDadiLFF/G5GL4iyOYjxsYMnQ1BDfxujk0VmJPecFAO4bV2Nk05Bqzz3Za6ut86JJDx2vN4Hbj3hjBbcOt4eCaQZXUj5daT4pGoNFimI1zpdYVEf2jsTQX+5MX5NaOFdFFJHzJ2bWI+FJv6SRWYACTWliqa68ioqc2LMWpwtJ7PCymzVhSWOqOiHeZdPachqNIcXdBJV/2B6cLa5cwZLjQYOkqnuNsOeEM1uJgE43xDBsaH9QQfJ21VNBoHfpBaWHLiKGLoeO1ZnAHkpcxgkvOeoeDa0FjTnNLEfF1PJamYkcR3YmIX6OxNA35Kb7BFKwvoqf4jeV4GRE/azQ2Yh4GMaGFpbr2OSKe1Ibse1MRJ84fimkxMqc0Pc55MrjsOYvZRoofNW6/vPUSwEQ+2+tPQ14h9fX4Ap+aQ2MB1pQTB9sx5K24qmnorKWCRvtDF0PHa+0suBaW0ry91O5mus3n/wHmQwUTIH+tVgAAAABJRU5ErkJggg==","view/refresh.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAkCAYAAAC9itu8AAACiElEQVQ4T4WVS4iPYRTGf4/7/X6XcivXcktEUhTKQkqyYCOKjWyUhezFThbIlJ3LYrIRkoWGUhhhTMko4zJujYRpxgxHj9737/P3zfh239c57/uc5/zO+UQ3T0QsBRYCtZI+5jBVx0fEcGA6MA+YCXQCVyXddWwlISL6ARuARcXvhQPrJF3/nRARvYHtwLRuFLYCFyW15ITl6XTHvwIuJzlrgHrgiqSOiqSI2ANMAL4BxyW1R8RYYKSkp8Vb8w2HgD7AE0kXSozoD0wC2nPCAWAw0CyppiRhBzAD6MgJW4D5KdDFNeSkiJgFbEvONeYE698N2K0ArPsDMAZwguN+AmeKfZgLbAb6llj7A7gk6eFfnY6I0cDKpNc1tQFNwG1JvvFPp0sKXQ2sAGokveuJpVHAHGBJ4ul76vLNapbs9dYk6R8oU7driyztA2Z3w5L1n5LUnBPWptMd/xw4l+RscsHAeeNSZMloTAG+AIcltUXERPdB0qMylk4klu5LOlni2ABgqm3Oko4BQ4Fnko6WJOxPzlXg2wV4hv2czuOYhmsBsDf1rD7fYP0HkyyzZN0twHjACZmlI0WWFgM7e2DprKQ71SyNA9YDBnFYcq0RuOZ5/h9LdsVS6yV97YmlgYDn2X3wjUa7QdKLapY8015ePrWMJVtembhewLI0YWU4eZvck/Q525pXo4M/AY+TLMP40u+SuooseVjsitm/IakzItz5QcXhKSZsBCyrpdjlwuZwfSO8mLOkdYAHqFXSrRKWvErtXFdOcJcnp0AX96ZwuldQ5uxtTrD+VUmWWXqfujwk8eQ4f68rsuRG+d/gZVb9eIk9kPS6miXvIv91rNc12TXPc5MkTyO/AFhJCujHqZlCAAAAAElFTkSuQmCC","comp/checkbox.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAqCAYAAACDdWrxAAABbUlEQVRIS+2TP0gCURzHv88GRYsrExyOo5cEQVEtWdQQpE4N0R+HxmirXXCrKYigqMF2IRqCQByaLJqNIFpyUIzu4rIwpExODy88ITD/cJ603Rsf7/OGz+/zI5TSEAE20cZRgBMySKni8XrbwICrWAwG2ESZIadFS53J0R25brCyHZNud1vbcRuPV7fDAOu9GXJatNSZHN2R6wb/PfJCrxOZCR8Gbk6hWc6Xg8PrcgBETMIVPdIGSjYG/NoOSHcfkLqDK3qsBSRIrgRAuBF1quUPEUPhYGMwb2dhywrqQ3F0Dt++jSokJMBdhmDO52pB2WwFP7OK8rgH9os99IgppNf3QWwMFP4RNHKALrmoflIj53l6CaWpRcBkgiIkYHl6gDTrh5JJg57v/kJ1YOUixw7jfWELxMpAKUmAXAR7tg3LZ7am3IbjKDBOvPiDqkUmcoj+9H1d7k3nmHdweBubB70ON9wRzQH8pVVQb+Q/zZAEfpwDCU4AAAAASUVORK5CYII=","comp/btn_close.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAA8CAYAAAB1odqiAAAE6UlEQVRYR+3Y30+bVRgH8G/T0t/0Jy0USrIsC0E2GMKAVYcRpmSbEzIGZhqyxCxeceGVF3pjvJl/wYyJWZYY4hZBFnBuBBUW2ewYAxlsSMiyLKH8aEt/0vZtSxvM+562We15C6jlxr53zfO8z+ec5z2nOTmCk598tY19fAQs+Hlvz76QX1zpAwd+1NMNXzieU1QtFeKbvn4CXvqgC95wLKegRirC1e8GCPjh+53wMnRwedkG54aLG4yhSI/ycnPawHaKJ5M1MhGuXR8k4MX3OnjBx3NPcLX3DPfepSu3odfrYC4r5X7bVlbhcrnT4kdrjlA7xYLffj9EwJ6udnhCW9TEJ08XUgWTqE6n5XLdbk9G7MjhKmodrbwAfQPDBLxw7h1ecH3dDq/Xm1GYrZqceXIgGo0GJSXFvOCNmz8RsLv9NNyhKO+icTqc8Pl8acDLyWyr1Wo1DEYDbw2dXIz+4TsE7DzbBneQH2SruDZc8Pv9GSiLqVQq6Iv0WVe5TiHG4K1RAnaceguuYCTrCx63G4FAgAoqlUpodbqs7+sVEgyN/ELAs20t2Ajwgz6vF6FgMGtL5QoF1BoNL1qklODW6DgBT518gxcM+P1gQqFdLRqZXA6lSkVFWXDk198I2NZyAs7NMDXR7XRmYBKZjMuNMEzmljHQF46hUIrR8XsEbG228IJ+T/rGFkskkMoVHBgOBRGNRNI2vkpL/5YsODZhJeCbJ47D4WeoM4wyDLai5PsWiCUQJ2aXTN4pnswzqmS4e+8BAZstDbxg1qW3hyALTlinCPh6Uz1C0Rg2w/S/tz3UpaYWSgsgF4twf3IagvOXr297PR5YGuv+bd2s71sfzkCj1ULQe+3u9vraGlg0lw+LlZhMEIzUNu7vmYYFmz/9LJeTS9We+PIymaGl6wLizo2cokJDEawDNxLg+W7EHTkGjUWw/tBPwOMdnYg7nNQZep4/Q2B9jYspS0zQHjyUlrdTPJksNBrwYGiQgE3vtiNup4O2SSuOzk5y7z2ubYKyuBiaAwe5394XzxGw29Pi5iYLdeDCYgMmfxxOgKfPIG53UBNt049SBVNo4g864HRmxMz1x3hAIybv3CZg49ttiK/bqYneFRuCLldGYTY5OfPkQBR6PTRl6cfIVEtLivHw51ECNrS2Ir62zrtKfWtrCHo8acDLyWyrFVot1CYTbw2hqQRTY2MJsLk5K8hW8TkcCPp8GSiHqdVQG41ZtxUHTkwQ8NhrFsRXyUrke3wuF0L+TSooVxVCrc9+iBKWmvDodysB65saEFtZ5cX8Hi+YQDBrS2VKBVRa/jONqKwU05NTBKyrexWxlRUquOnfBBNidrVoZHIZClWF1DqisjLMzPxBwNraasRsdHDD6c7ApDIJVzTMRDJiRQb6EUNkLsPs7DwBa6qrELPZqCNzu/1pG1siEUOhkHK5wWAYkUg0La7T0U9tIrMZc/MLBKw+XImtZTrIMBFEouQkIBEXQJaYXXJ0O8WTeQXlZsw/XSRg1SsVvGDWpbuHIAsu/LlEwMrKCsQDAcQ93j2U2H2qUKuBUKnE4uISBF9f/Hj7wJwVhyordl/hH2Q+W1zCixoLOdNUj98Ei+byYbH5lnPkmJhL6O+18/c0/1m38/c0qVbm72nYVuTvadgu5O9pUtsif0+Tv6dhF8P/657mLz4NfQVdLmZiAAAAAElFTkSuQmCC","comp/textarea.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFsAAAAXCAYAAABkrDOOAAAA4klEQVRoQ+3ZvQrCMBiF4e9rU+sPOErRqxDRe/KG9Fp0EAc3VzuIg1ML4uDmlkaaquDenMUTyJoDD+8W3ZyKlaoshSeogHOy1m1euOmoI1EU+auqQUf/8XHnnBzLp3jsWdaVJEnEGEPsADXU2Ifro8Gej/uSpqnHruvmaVegqirZX+4N9mIy8Nh13XEct7vE18RaK7vzjdiIFoiNUH5vEJvYQAHgFMsmNlAAOMWyiQ0UAE6xbGIDBYBTLJvYQAHgFMsmNlAAOMWyiQ0UAE79lM2fmrDy358a/q6Hhf68ng175QueKdEXxUGVVwAAAABJRU5ErkJggg==","view/re.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAoCAYAAAD6xArmAAACpklEQVRIS+WWPUgcQRiG3+8O70QEUwTB1EJgsTGdRRrhOMjOtEtSRbBIBMFKuCtkZleES2uRQoWQJggKKW7Of7GyTRvBLkVShhS73OXMfWGOU85Es7uXs0m2XeZh+OZ95xnCHX10R1ykBvu+P5fP59+VSqVvf9pUarBS6jWAR0Q0rbWOboP3BCaiOQAHAKTW+vtN8L8BW96W4zjPPM/78Ss8FlypVEYajYbHzALAJIAHALJdoDWl1Esi4m74rWBmpiAI5pk5AHAvJj0VrXU5Fmyhvu+/AfA8YRxfaa1LsWDf92eZeSMJlJnXtdYvEo1Ca30G4GEH/ImI1lqt1nE+nz9vNBrLnVTY39uO4zxNdHgrKytjzWbzs13FzKfDw8PFxcXF8HL3Nscd8BEAN3HcgiCYbLVaHyyIiGaUUm+7R9JzQZRSo0T0BUCGmRd831/tBttK53K5zXK5/DV1pZVSG0Q0C2BXa/0kySEmKojWeoiZD4hoKpvNTiwtLX1MC7+1IFrrQWZeJaJxx3EKN5186lF0LwiC4DEz31dKvU+z69i7Ig0stnm9wv4zsDGm7bxCodBf5xlj2s5j5mkpZf+c1wHPEdFBGIbS87z+OO8S3EnAVhRFvTnv8PBwpF6ve0QkiGiSmX9znuu66ZxXq9XmAcQ6j5krUspkzqvVaqmcJ4SId54xxl6ZiZwHYN113WTOq1arZ0R05TwAa5lM5rher5/ncrllAPYl1HZeFEXJnLe3tzd2cXHRdh6A04GBgWKxWLxyXlcqjqIochPHbWdn58p5AGaEENec13NB9vf3R5vNZtt5RLTguu4159lKA9gUQqR3njHGHpx9tOxKKfvnvGq1OmQrC2AKwIQQon/OOzk5GQzD0I5hPIqi/jvPGNN2npTyH3feTzoJOzgswwlqAAAAAElFTkSuQmCC","view/search.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAqCAYAAABcOxDuAAABX0lEQVRIS+3VsUrEQBAG4H9HiDZiJQg+gJVaiKAoWClYXWeZ7D6CtbWFr5Ai2ayQxkLQRgsLGwtBUQsRC6sDCxHxEIvIZSRwxRGSu83pNUe23c0H+89kR2AISwzBxAiinuctCSH2AawD+AFwRkR7QRC85CO0ur5SaoOZzwGM54A3IlrJw1aolPIewEJJUY+01jvde31RKeUMgNceXdLSWk9VQl3XnSWiZhnKzF9RFE1WQrPDUsonAHNFsBDiJAzDRmXUdd1tIjoFMJaDW0KI1TAMH61RpdQ0Mx8z8zMzHxLRAYBlAG0Al2ma7hpjHqxbqgNeAJgHcKW1XutEMeE4Ttv3/axXC1dh9XPgbZqmW8aYd9t3ohCVUt4BWARwkyTJZhzHH7Zgdq4MvQbw7ThOw/f9zypgKVoVsS7UX+C+v+kgeI0Oklrvb0Yw03rwlZW8Hnz14OvqjXrw1e/pPyfwCww91CttlMG7AAAAAElFTkSuQmCC","view/save.png":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAoCAYAAAD6xArmAAAA1klEQVRIS+2VzQ3DIAyFwxwdoMMAA/VQ8ZByyEBhmA7QOVxxKLIaOcIoSZUfrlifHw/wM91Ky6zE7SZgANTaDEDhzYJ5odSMC7nA5U7+b4X2dVQr3ic4hHCTlMcY33xPZUUGcwBvdEJwjcfGGIQQ4rd2qenWA3hyAUuABwCP31NtN+i1v02qP4DicRybM885J2ceB/NCyUupfuLxBS4WbmKF9rNUv4p9gq21d0l5SunF91RWZDAH8EYnBNd4nDPPWitnXst0I6Leez+feVowEQ3e+wNk3ge7C/Qp3GfwkgAAAABJRU5ErkJggg=="};},'base64',function(){return this.base64=new Base64Atlas(Base64AtlasManager.dataO);} ]); return Base64AtlasManager; })() /** *... *@author ww */ //class laya.debug.DebugPanel var DebugPanel=(function(){ function DebugPanel(){ this.tShowObj=null; this.preValueO={}; this.div=null; this.debug_view=null; this.height=300; this.clickedHandler=null; this.fromMe=false; this._treeDataList=null; this._init(); } __class(DebugPanel,'laya.debug.DebugPanel'); var __proto=DebugPanel.prototype; __proto.removeNoDisplayKeys=function(arr){ var i=0; for (i=arr.length-1;i >=0;i--){ if (DebugPanel.noDisplayKeys[arr[i]]){ arr.splice(i,1); } } } __proto.updateShowKeys=function(){ DebugPanel.tObjKeys.length=0; if (!this.tShowObj) return; DebugPanel.tObjKeys=ClassTool.getObjectDisplayAbleKeys(this.tShowObj,DebugPanel.tObjKeys); if (this.tShowObj==Laya.stage){ this.removeNoDisplayKeys(DebugPanel.tObjKeys); } DebugPanel.tObjKeys.sort(MathUtil.sortSmallFirst); } __proto._init=function(){ var _$this=this; this.div=Browser.document.createElement('div'); Browser.document.body.appendChild(this.div); this.clickedHandler=new Handler(this,this.onClickSelected); this.debug_view=Browser.window.layaair_debug_view; this.debug_view.initLayaAirDebugView(this.div); this.debug_view.tree.attachEvent("onSelect",function(id){ var dataO; dataO=_$this.getDataByID(id,_$this._treeDataList[0]); if (dataO.target){ DebugTool.showDisBound(dataO.target); _$this.showTargetInfo(dataO.target); } }); this.debug_view.setValueChangeHandler(function(data,new_value){ _$this.onValueChange(data,new_value); }); this.debug_view.onRefresh(function(){ DebugPanel.I.setRoot(Laya.stage); }); this.debug_view.onInspectElement(function(){ ClickSelectTool.I.beginClickSelect(_$this.clickedHandler); }); this.debug_view.onLogInfo(function(){ console.log(_$this.tShowObj); }); this.debug_view.onPrintEnabledNodeChain(function(){ DebugTool.traceDisMouseEnable(_$this.tShowObj); }); this.debug_view.onPrintSizeChain(function(){ DebugTool.traceDisSizeChain(_$this.tShowObj); }); this.debug_view.onToggleVisibility(function(selectd){ if (_$this.tShowObj){ _$this.tShowObj.visible=_$this.debug_view.getVisibility(); } }); this.debug_view.onToggleDebugBorder(function(selectd){ if (!_$this.tShowObj) return; SpriteRenderHook.showDisplayBorder(_$this.tShowObj,_$this.debug_view.getShowDebugBorder()); }); this.debug_view.onToggleShowCurrentCache(function(selectd){ CacheAnalyser.showRecacheSprite=_$this.debug_view.getShowCurrentCache(); }); this.debug_view.onToggleShowAllCache(function(selectd){ CacheAnalyser.showCacheSprite=_$this.debug_view.getShowAllCache(); }); this.debug_view.onToggleShowAtlas(function(selectd){ console.log("toggle show atlas:",_$this.debug_view.getShowAtlas()); if (_$this.debug_view.getShowAtlas()){ AtlasTools.getInstance().start(); } else { AtlasTools.getInstance().end(); } }); JSTools.showToBody(this.div,0,0); Laya.stage.on(/*laya.events.Event.RESIZE*/"resize",this,this.adptPos); this.adptPos(); } __proto.onClickSelected=function(target){ var dataO; if (!this._treeDataList) return; this.debug_view.tree.selectItem(IDTools.getObjID(target)); this.debug_view.bounceUpInspectButton(); } __proto.updateLoop=function(){ if (this.tShowObj){ this.showTargetInfo(this.tShowObj); } } __proto.onSelectItem=function(obj){ var tTarget; tTarget=obj.target; this.showTargetInfo(tTarget); } __proto.onValueChange=function(obj,newValue){ if (obj["type"]=="number"){ newValue=DebugPanel.mParseFloat(newValue); } if (obj["type"]=="boolean"){ newValue=newValue.toString()=="true"; } if (this.tShowObj){ var key; key=obj["key"]; this.preValueO[key]=this.tShowObj[key]=newValue; } } __proto.showTargetInfo=function(tTarget){ if (!tTarget) return; this.debug_view.setVisibility(tTarget.visible); this.debug_view.setShowDebugBorder(SpriteRenderHook.isDisplayShowBorder(tTarget)); var i=0,len=0; len=DebugPanel.tObjKeys.length; var key; if (this.tShowObj==tTarget){ for (i=0;i < len;i++){ key=DebugPanel.tObjKeys[i]; if (this.preValueO[key] !=tTarget[key]){ this.debug_view.changeValueByLabel(key,tTarget[key]); } } } else { this.tShowObj=tTarget; this.updateShowKeys(); var dataList; dataList=DebugPanel.getObjectData(tTarget); this.debug_view.setContents(dataList); } for (i=0;i < len;i++){ key=DebugPanel.tObjKeys[i]; this.preValueO[key]=tTarget[key]; } } __proto.adptPos=function(){ if (this.fromMe)return; this.fromMe=true; JSTools.setPos(this.div,0,Browser.clientHeight-this.height); this.debug_view.resize(Browser.clientWidth,this.height); if (!DebugPanel.overlay){ Laya.stage.setScreenSize(Browser.clientWidth *Browser.pixelRatio,(Browser.clientHeight-this.height)*Browser.pixelRatio); } this.fromMe=false; } __proto.setRoot=function(sprite){ var mtreeo; mtreeo=DebugPanel.getSpriteTreeArr(sprite); this._treeDataList=[mtreeo]; var wraped; wraped={}; wraped.id=0; wraped.item=[mtreeo]; this.debug_view.setTree(wraped); Laya.timer.loop(500,this,this.updateLoop); } __proto.getDataByID=function(targetID,nodeO){ if (!nodeO) return null; if (targetID==nodeO.id) return nodeO; var childs; childs=nodeO["item"]; if (!childs) return null; var i=0,len=0; len=childs.length; var tRst; for (i=0;i < len;i++){ tRst=this.getDataByID(targetID,childs[i]); if (tRst) return tRst; } return null; } __proto.getDataByTarget=function(target,nodeO){ if (!nodeO) return null; if (target==nodeO.target) return nodeO; var childs; childs=nodeO["item"]; if (!childs) return null; var i=0,len=0; len=childs.length; var tRst; for (i=0;i < len;i++){ tRst=this.getDataByTarget(target,childs[i]); if (tRst) return tRst; } return null; } DebugPanel.init=function(underGame,bgColor){ (underGame===void 0)&& (underGame=true); (bgColor===void 0)&& (bgColor="#ffffff"); if (!DebugPanel.I){ DebugPanel.overlay=!underGame; DivScripts.init(); DebugTool.initBasicFunctions(); RenderSpriteHook.init(); SpriteRenderHook.init(); DebugPanel.I=new DebugPanel(); DebugPanel.I.setRoot(Laya.stage); CacheAnalyser.showRecacheSprite=false; if (bgColor){ DebugPanel.I.div.style.background=bgColor; } } } DebugPanel.getSpriteTreeArr=function(sprite){ var rst; rst={}; rst["text"]=""+ClassTool.getNodeClassAndName(sprite); rst.target=sprite; IDTools.idObj(sprite); rst.id=IDTools.getObjID(sprite); var childs; childs=sprite._childs; var i=0,len=0; len=childs.length; var tchild; var childsList; childsList=[]; rst["item"]=childsList; for (i=0;i < len;i++){ childsList.push(DebugPanel.getSpriteTreeArr(childs[i])); } return rst; } DebugPanel.getObjectData=function(data){ var dataList; var tData; var key; var tValue; var tType; dataList=[]; var keys; keys=DebugPanel.tObjKeys; var i=0,len=0; len=keys.length; for (i=0;i < len;i++){ key=keys[i]; tValue=data[key]; tType=typeof(tValue); if (key.charAt(0)=="_") continue ; if (DebugPanel.displayTypes[tType]){ tData={}; tData["key"]=key; tData["value"]=tValue; tData["type"]=tType; dataList.push(tData); } } return dataList; } DebugPanel.mParseFloat=function(v){ var rst=NaN; rst=parseFloat(v); if (isNaN(rst)) return 0; return rst; } DebugPanel.I=null; DebugPanel.overlay=false; DebugPanel.ChildrenSign="item"; DebugPanel.LabelSign="text"; DebugPanel.tObjKeys=[]; __static(DebugPanel, ['displayTypes',function(){return this.displayTypes={"boolean":true,"number":true,"string":true};},'displayKeys',function(){return this.displayKeys=[["x","number"],["y","number"],["width","number"],["width","number"],["width","number"],["width","number"],["width","number"],["width","number"],["width","number"],["width","number"],["width","number"],];},'noDisplayKeys',function(){return this.noDisplayKeys={"desginWidth":true,"desginHeight":true };} ]); return DebugPanel; })() /** * *@author ww *@version 1.0 * *@created 2015-9-24 下午3:00:38 */ //class laya.debug.DebugTool var DebugTool=(function(){ function DebugTool(){} __class(DebugTool,'laya.debug.DebugTool'); __getset(1,DebugTool,'target',function(){ return DebugTool._target; },function(v){ DebugTool._target=v; }); __getset(1,DebugTool,'isThisShow',function(){ return false; }); /** *设置是否显示帧率信息 *@param value 是否显示true|false */ __getset(1,DebugTool,'showStatu',null,function(value){ if (value){ Stat.show(); } else{ Stat.hide(); DebugTool.clearDebugLayer(); } }); /** *是否自动显示点击对象的边框 *@param value */ __getset(1,DebugTool,'showBound',function(){ return DebugTool._showBound; },function(value){ DebugTool._showBound=value; if (!DebugTool._showBound){ DebugTool.clearDebugLayer(); } }); DebugTool.getMenuShowEvent=function(){ if (Browser.onMobile){ return /*laya.events.Event.DOUBLE_CLICK*/"doubleclick"; }else{ return /*laya.events.Event.RIGHT_CLICK*/"rightclick"; } } DebugTool.init=function(cacheAnalyseEnable,loaderAnalyseEnable,createAnalyseEnable,renderAnalyseEnable,showCacheRec){ (cacheAnalyseEnable===void 0)&& (cacheAnalyseEnable=true); (loaderAnalyseEnable===void 0)&& (loaderAnalyseEnable=true); (createAnalyseEnable===void 0)&& (createAnalyseEnable=true); (renderAnalyseEnable===void 0)&& (renderAnalyseEnable=true); (showCacheRec===void 0)&& (showCacheRec=false); DebugTool.enableCacheAnalyse=cacheAnalyseEnable; if (DebugTool.enableCacheAnalyse){ RenderSpriteHook.init(); } if (renderAnalyseEnable){ SpriteRenderHook.init(); } DebugTool.enableNodeCreateAnalyse=createAnalyseEnable; if (DebugTool.enableNodeCreateAnalyse){ ClassCreateHook.I.hookClass(Node); } if (loaderAnalyseEnable){ LoaderHook.init(); } CacheAnalyser.showCacheSprite=showCacheRec; NodeInfoPanel.init(); DebugTool.initBasicFunctions(); } DebugTool.initBasicFunctions=function(){ DisplayHook.initMe(); if (!DebugTool.debugLayer){ DebugInfoLayer.init(); DebugTool.debugLayer=DebugInfoLayer.I.graphicLayer; DebugTool.debugLayer.mouseEnabled=false; DebugTool.debugLayer.mouseThrough=true; DebugTool.showStatu=true; Laya.stage.on(/*laya.events.Event.KEY_DOWN*/"keydown",null,DebugTool.keyHandler); DebugTool.cmdToTypeO[ /*laya.renders.RenderSprite.IMAGE*/0x01]="IMAGE"; DebugTool.cmdToTypeO[ /*laya.renders.RenderSprite.ALPHA*/0x02]="ALPHA"; DebugTool.cmdToTypeO[ /*laya.renders.RenderSprite.TRANSFORM*/0x04]="TRANSFORM"; DebugTool.cmdToTypeO[ /*laya.renders.RenderSprite.CANVAS*/0x10]="CANVAS"; DebugTool.cmdToTypeO[ /*laya.renders.RenderSprite.GRAPHICS*/0x200]="GRAPHICS"; DebugTool.cmdToTypeO[ /*laya.renders.RenderSprite.CUSTOM*/0x400]="CUSTOM"; DebugTool.cmdToTypeO[ /*laya.renders.RenderSprite.CHILDS*/0x800]="CHILDS"; DebugExport.export(); } } DebugTool.dTrace=function(str){ if (DebugTool._traceFun !=null){ DebugTool._traceFun(str); } console.log(str); } DebugTool.keyHandler=function(e){ var key; key=String.fromCharCode(e.keyCode); if (!e.altKey) return; switch (e.keyCode){ case 38: DebugTool.showParent(); break ; case 40: DebugTool.showChild(); break ; case 37: DebugTool.showBrother(DebugTool.target,1); break ; case 39: DebugTool.showBrother(DebugTool.target,-1); break ; } DebugTool.dealCMDKey(key); } DebugTool.dealCMDKey=function(key){ switch (key){ case "上": DebugTool.showParent(); break ; case "下": DebugTool.showChild(); break ; case "左": DebugTool.showBrother(DebugTool.target,1); break ; case "右": DebugTool.showBrother(DebugTool.target,-1); break ; case "B": DebugTool.showAllBrother(); break ; case "C": DebugTool.showAllChild(); break ; case "E": DebugTool.traceDisMouseEnable(); break ; case "S": DebugTool.traceDisSizeChain(); break ; case "D": DisControlTool.downDis(DebugTool.target); break ; case "U": DisControlTool.upDis(DebugTool.target); break ; case "N": DebugTool.getNodeInfo(); break ; case "M": DebugTool.showAllUnderMosue(); break ; case "I": break ; case "O": ObjectCreateView.I.show(); break ; case "L": DisController.I.switchType(); break ; case "Q": DebugTool.showNodeInfo(); break ; case "F": DebugTool.showToolPanel(); break ; case "P": DebugTool.showToolFilter(); break ; case "V": DebugTool.selectNodeUnderMouse(); break ; case "A": if (NodeToolView.I.target){ MouseEventAnalyser.analyseNode(NodeToolView.I.target); } break ; case "K": NodeUtils.traceStage(); break ; case "T": DebugTool.switchNodeTree(); break ; case "R": RenderCostRankView.I.show(); break ; case "X": NodeTree.I.fresh(); break ; case "mCMD": DebugTool.traceCMD(); break ; case "allCMD": DebugTool.traceCMDR(); break ; } } DebugTool.switchNodeTree=function(){ ToolPanel.I.switchShow(/*laya.debug.view.nodeInfo.ToolPanel.Tree*/"Tree"); } DebugTool.analyseMouseHit=function(){ if (DebugTool.target) MouseEventAnalyser.analyseNode(DebugTool.target); } DebugTool.selectNodeUnderMouse=function(){ DisplayHook.instance.selectDisUnderMouse(); DebugTool.showDisBound(); return; } DebugTool.showToolPanel=function(){ ToolPanel.I.switchShow(/*laya.debug.view.nodeInfo.ToolPanel.Find*/"Find"); } DebugTool.showToolFilter=function(){ ToolPanel.I.switchShow(/*laya.debug.view.nodeInfo.ToolPanel.Filter*/"Filter"); } DebugTool.showNodeInfo=function(){ if (NodeInfoPanel.I.isWorkState){ NodeInfoPanel.I.recoverNodes(); } else{ NodeInfoPanel.I.showDisInfo(DebugTool.target); } } DebugTool.switchDisController=function(){ if (DisController.I.target){ DisController.I.target=null; } else{ if (DebugTool.target){ DisController.I.target=DebugTool.target; } } } DebugTool.showParent=function(sprite){ if (!sprite) sprite=DebugTool.target; if (!sprite){ console.log("no targetAvalible"); return null; } DebugTool.target=sprite.parent; DebugTool.autoWork(); } DebugTool.showChild=function(sprite){ if (!sprite) sprite=DebugTool.target; if (!sprite){ console.log("no targetAvalible"); return null; } if (sprite.numChildren > 0){ DebugTool.target=sprite.getChildAt(0); DebugTool.autoWork(); } } DebugTool.showAllChild=function(sprite){ if (!sprite) sprite=DebugTool.target; if (!sprite){ console.log("no targetAvalible"); return null; } DebugTool.selectedNodes=DisControlTool.getAllChild(sprite); DebugTool.showSelected(); } DebugTool.showAllUnderMosue=function(){ DebugTool.selectedNodes=DisControlTool.getObjectsUnderGlobalPoint(Laya.stage); DebugTool.showSelected(); } DebugTool.showParentChain=function(sprite){ if (!sprite) return; DebugTool.selectedNodes=[]; var tar; tar=sprite.parent; while (tar){ DebugTool.selectedNodes.push(tar); tar=tar.parent; } DebugTool.showSelected(); } DebugTool.showAllBrother=function(sprite){ if (!sprite) sprite=DebugTool.target; if (!sprite){ console.log("no targetAvalible"); return null; } if (!sprite.parent) return; DebugTool.selectedNodes=DisControlTool.getAllChild(sprite.parent); DebugTool.showSelected(); } DebugTool.showBrother=function(sprite,dID){ (dID===void 0)&& (dID=1); if (!sprite) sprite=DebugTool.target; if (!sprite){ console.log("no targetAvalible"); return null; }; var p; p=sprite.parent; if (!p) return; var n=0; n=p.getChildIndex(sprite); n+=dID; if (n < 0) n+=p.numChildren; if (n >=p.numChildren) n-=p.numChildren; DebugTool.target=p.getChildAt(n); DebugTool.autoWork(); } DebugTool.clearDebugLayer=function(){ if (DebugTool.debugLayer.graphics) DebugTool.debugLayer.graphics.clear(); } DebugTool.showSelected=function(){ if (!DebugTool.autoShowSelected) return; if (!DebugTool.selectedNodes || DebugTool.selectedNodes.length < 1) return; console.log("selected:",DebugTool.selectedNodes); var i=0; var len=0; len=DebugTool.selectedNodes.length; DebugTool.clearDebugLayer(); for (i=0;i < len;i++){ DebugTool.showDisBound(DebugTool.selectedNodes[i],false); } } DebugTool.getClassCreateInfo=function(className){ return RunProfile.getRunInfo(className); } DebugTool.autoWork=function(){ if (!DebugTool.isThisShow) return; if (DebugTool.showBound) DebugTool.showDisBound(); if (DebugTool.autoTraceSpriteInfo && DebugTool.target){ TraceTool.traceSpriteInfo(DebugTool.target,DebugTool.autoTraceBounds,DebugTool.autoTraceSize,DebugTool.autoTraceTree); } if (!DebugTool.target) return; if (DebugTool.autoTraceCMD){ DebugTool.traceCMD(); } if (DebugTool.autoTraceCMDR){ DebugTool.traceCMDR(); } if (DebugTool.autoTraceEnable){ DebugTool.traceDisMouseEnable(DebugTool.target); } } DebugTool.traceDisMouseEnable=function(tar){ console.log("----------------traceDisMouseEnable--------------------"); if (!tar) tar=DebugTool.target; if (!tar){ console.log("no targetAvalible"); return null; }; var strArr; strArr=[]; DebugTool.selectedNodes=[]; while (tar){ strArr.push(ClassTool.getNodeClassAndName(tar)+": mouseEnabled:"+tar.mouseEnabled+" hitFirst:"+tar.hitTestPrior); DebugTool.selectedNodes.push(tar); tar=tar.parent; } console.log(strArr.join("\n")); DebugTool.showSelected(); return strArr.join("\n"); } DebugTool.traceDisSizeChain=function(tar){ console.log("---------------------traceDisSizeChain-------------------"); if (!tar) tar=DebugTool.target; if (!tar){ console.log("no targetAvalible"); return null; } DebugTool.selectedNodes=[]; var strArr; strArr=[]; while (tar){ strArr.push(ClassTool.getNodeClassAndName(tar)+": x:"+tar.x+" y:"+tar.y+" w:"+tar.width+" h:"+tar.height+" scaleX:"+tar.scaleX+" scaleY:"+tar.scaleY); DebugTool.selectedNodes.push(tar); tar=tar.parent; } console.log(strArr.join("\n")); DebugTool.showSelected(); return strArr.join("\n"); } DebugTool.showDisBound=function(sprite,clearPre,color){ (clearPre===void 0)&& (clearPre=true); (color===void 0)&& (color="#ff0000"); if (!sprite) sprite=DebugTool.target; if (!sprite){ console.log("no targetAvalible"); return null; } if (clearPre) DebugTool.clearDebugLayer(); var pointList; pointList=sprite._getBoundPointsM(true); if (!pointList || pointList.length < 1) return; pointList=GrahamScan.pListToPointList(pointList,true); WalkTools.walkArr(pointList,sprite.localToGlobal,sprite); pointList=GrahamScan.pointListToPlist(pointList); DebugTool._disBoundRec=Rectangle._getWrapRec(pointList,DebugTool._disBoundRec); DebugTool.debugLayer.graphics.drawRect(DebugTool._disBoundRec.x,DebugTool._disBoundRec.y,DebugTool._disBoundRec.width,DebugTool._disBoundRec.height,null,color); DebugInfoLayer.I.setTop(); } DebugTool.showDisBoundToSprite=function(sprite,graphicSprite,color,lineWidth){ (color===void 0)&& (color="#ff0000"); (lineWidth===void 0)&& (lineWidth=1); var pointList; pointList=sprite._getBoundPointsM(true); if (!pointList || pointList.length < 1) return; pointList=GrahamScan.pListToPointList(pointList,true); WalkTools.walkArr(pointList,sprite.localToGlobal,sprite); pointList=GrahamScan.pointListToPlist(pointList); DebugTool._disBoundRec=Rectangle._getWrapRec(pointList,DebugTool._disBoundRec); graphicSprite.graphics.drawRect(DebugTool._disBoundRec.x,DebugTool._disBoundRec.y,DebugTool._disBoundRec.width,DebugTool._disBoundRec.height,null,color,lineWidth); } DebugTool.getNodeInfo=function(){ DebugTool.counter.reset(); WalkTools.walkTarget(Laya.stage,DebugTool.addNodeInfo); console.log("node info:"); DebugTool.counter.traceSelf(); return DebugTool.counter.data; } DebugTool.findByClass=function(className){ DebugTool._classList=[]; DebugTool._tFindClass=className; WalkTools.walkTarget(Laya.stage,DebugTool.addClassNode); DebugTool.selectedNodes=DebugTool._classList; DebugTool.showSelected(); return DebugTool._classList; } DebugTool.addClassNode=function(node){ var type; type=node["constructor"].name; if (type==DebugTool._tFindClass){ DebugTool._classList.push(node); } } DebugTool.traceCMD=function(sprite){ if (!sprite) sprite=DebugTool.target; if (!sprite){ console.log("no targetAvalible"); return null; } console.log("self CMDs:"); console.log(sprite.graphics.cmds); var renderSprite; renderSprite=RenderSprite.renders[sprite._renderType]; console.log("renderSprite:",renderSprite); DebugTool._rSpList.length=0; while (renderSprite && renderSprite["_sign"] > 0){ DebugTool._rSpList.push(DebugTool.cmdToTypeO[renderSprite["_sign"]]); renderSprite=renderSprite._next; } console.log("fun:",DebugTool._rSpList.join(",")); DebugTool.counter.reset(); DebugTool.addCMDs(sprite.graphics.cmds); DebugTool.counter.traceSelf(); return DebugTool.counter.data; } DebugTool.addCMDs=function(cmds){ WalkTools.walkArr(cmds,DebugTool.addCMD); } DebugTool.addCMD=function(cmd){ DebugTool.counter.add(cmd.callee); } DebugTool.traceCMDR=function(sprite){ if (!sprite) sprite=DebugTool.target; if (!sprite){ console.log("no targetAvalible"); return 0; } DebugTool.counter.reset(); WalkTools.walkTarget(sprite,DebugTool.getCMdCount); console.log("cmds include children"); DebugTool.counter.traceSelf(); return DebugTool.counter.data; } DebugTool.getCMdCount=function(target){ if (!target) return 0; if (! (target instanceof laya.display.Sprite )) return 0; if (!target.graphics.cmds) return 0; DebugTool.addCMDs(target.graphics.cmds); var rst=target.graphics.cmds.length; return rst; } DebugTool.addNodeInfo=function(node){ var type; type=node["constructor"].name; DebugTool.counter.add(type); } DebugTool.find=function(filter,ifShowSelected){ (ifShowSelected===void 0)&& (ifShowSelected=true); var rst; rst=DebugTool.findTarget(Laya.stage,filter); DebugTool.selectedNodes=rst; if (DebugTool.selectedNodes){ DebugTool.target=DebugTool.selectedNodes[0]; } if (ifShowSelected) DebugTool.showSelected(); return rst; } DebugTool.findByName=function(name){ DebugTool.nameFilter.name=name; return DebugTool.find(DebugTool.nameFilter); } DebugTool.findNameStartWith=function(startStr){ DebugTool.nameFilter.name=DebugTool.getStartWithFun(startStr); return DebugTool.find(DebugTool.nameFilter); } DebugTool.findNameHas=function(hasStr,showSelected){ (showSelected===void 0)&& (showSelected=true); DebugTool.nameFilter.name=DebugTool.getHasFun(hasStr); return DebugTool.find(DebugTool.nameFilter,showSelected); } DebugTool.getStartWithFun=function(startStr){ var rst=function (str){ if (!str) return false; if (str.indexOf(startStr)==0) return true; return false; }; return rst; } DebugTool.getHasFun=function(hasStr){ var rst=function (str){ if (!str) return false; if (str.indexOf(hasStr)>=0) return true; return false; }; return rst; } DebugTool.findTarget=function(target,filter){ var rst=[]; if (DebugTool.isFit(target,filter)) rst.push(target); var i=0; var len=0; var tChild; len=target.numChildren; for (i=0;i < len;i++){ tChild=target.getChildAt(i); if ((tChild instanceof laya.display.Sprite )){ rst=rst.concat(DebugTool.findTarget(tChild,filter)); } } return rst; } DebugTool.findClassHas=function(target,str){ var rst=[]; if (ClassTool.getClassName(target).indexOf(str)>=0) rst.push(target); var i=0; var len=0; var tChild; len=target.numChildren; for (i=0;i < len;i++){ tChild=target.getChildAt(i); if ((tChild instanceof laya.display.Sprite )){ rst=rst.concat(DebugTool.findClassHas(tChild,str)); } } return rst; } DebugTool.isFit=function(tar,filter){ if (!tar) return false; if (!filter) return true; if ((typeof filter=='function')){ return (filter)(tar); }; var key; for (key in filter){ if ((typeof (filter[key])=='function')){ if (!filter[key](tar[key])) return false; } else{ if (tar[key] !=filter[key]) return false; } } return true; } DebugTool.log=function(__args){ var args=arguments; var arr; arr=DTrace.getArgArr(args); if (DebugTool._logFun!=null){ DebugTool._logFun(arr.join(" ")); } } DebugTool.enableCacheAnalyse=false; DebugTool.enableNodeCreateAnalyse=true; DebugTool._traceFun=null; DebugTool.debugLayer=null; DebugTool._target=null; DebugTool.selectedNodes=[]; DebugTool.autoShowSelected=true; DebugTool._showBound=true; DebugTool._disBoundRec=null; DebugTool.autoTraceEnable=false; DebugTool.autoTraceBounds=false; DebugTool.autoTraceSize=false; DebugTool.autoTraceTree=true; DebugTool.autoTraceCMD=true; DebugTool.autoTraceCMDR=false; DebugTool.autoTraceSpriteInfo=true; DebugTool._classList=null; DebugTool._tFindClass=null; DebugTool._rSpList=[]; DebugTool._logFun=null; __static(DebugTool, ['text',function(){return this.text=new Stat();},'cmdToTypeO',function(){return this.cmdToTypeO={ };},'counter',function(){return this.counter=new CountTool();},'nameFilter',function(){return this.nameFilter={"name":"name"};} ]); return DebugTool; })() /** *... *@author ww */ //class laya.debug.divui.DivScripts var DivScripts=(function(){ function DivScripts(){} __class(DivScripts,'laya.debug.divui.DivScripts'); DivScripts.init=function(){ var script; script=Base64Tool.decodeToByte(DivScripts.data).readUTFBytes(); Laya._runScript(script); } DivScripts.data="ZnVuY3Rpb24gZGh0bWx4RXZlbnQoZSx0LGkpe2UuYWRkRXZlbnRMaXN0ZW5lcj9lLmFkZEV2ZW50TGlzdGVuZXIodCxpLCExKTplLmF0dGFjaEV2ZW50JiZlLmF0dGFjaEV2ZW50KCJvbiIrdCxpKX1mdW5jdGlvbiBkaHRtbFhUcmVlT2JqZWN0KGUsdCxpLG4pe2lmKGRodG1seEV2ZW50LmluaXRUb3VjaCYmZGh0bWx4RXZlbnQuaW5pdFRvdWNoKCksX2lzSUUpdHJ5e2RvY3VtZW50LmV4ZWNDb21tYW5kKCJCYWNrZ3JvdW5kSW1hZ2VDYWNoZSIsITEsITApfWNhdGNoKG8pe30ib2JqZWN0IiE9dHlwZW9mIGU/dGhpcy5wYXJlbnRPYmplY3Q9ZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoZSk6dGhpcy5wYXJlbnRPYmplY3Q9ZSx0aGlzLnBhcmVudE9iamVjdC5zdHlsZS5vdmVyZmxvdz0iaGlkZGVuIix0aGlzLl9pdGltX2RnPSEwLHRoaXMuZGxtdHI9IiwiLHRoaXMuZHJvcExvd2VyPSExLHRoaXMuZW5hYmxlSUVJbWFnZUZpeCghMCksdGhpcy54bWxzdGF0ZT0wLHRoaXMubXl0eXBlPSJ0cmVlIix0aGlzLnNtY2hlY2s9ITAsdGhpcy53aWR0aD10LHRoaXMuaGVpZ2h0PWksdGhpcy5yb290SWQ9bix0aGlzLmNoaWxkQ2FsYz1udWxsLHRoaXMuZGVmX2ltZ194PSIxOHB4Iix0aGlzLmRlZl9pbWdfeT0iMThweCIsdGhpcy5kZWZfbGluZV9pbWdfeD0iMThweCIsdGhpcy5kZWZfbGluZV9pbWdfeT0iMjRweCIsdGhpcy5fZHJhZ2dlZD1uZXcgQXJyYXksdGhpcy5fc2VsZWN0ZWQ9bmV3IEFycmF5LHRoaXMuc3R5bGVfcG9pbnRlcj0icG9pbnRlciIsdGhpcy5fYWltZ3M9ITAsdGhpcy5odG1sY0E9IiBbIix0aGlzLmh0bWxjQj0iXSIsdGhpcy5sV2luPXdpbmRvdyx0aGlzLmNNZW51PTAsdGhpcy5tbGl0ZW1zPTAsdGhpcy5pY29uVVJMPSIiLHRoaXMuZGFkbW9kZT0wLHRoaXMuc2xvd1BhcnNlPSExLHRoaXMuYXV0b1Njcm9sbD0hMCx0aGlzLmhmTW9kZT0wLHRoaXMubm9kZUN1dD1uZXcgQXJyYXksdGhpcy5YTUxzb3VyY2U9MCx0aGlzLlhNTGxvYWRpbmdXYXJuaW5nPTAsdGhpcy5faWRwdWxsPXt9LHRoaXMuX3B1bGxTaXplPTAsdGhpcy50cmVlTGluZXNPbj0hMCx0aGlzLnRzY2hlY2s9ITEsdGhpcy50aW1nZW49ITAsdGhpcy5kcGNweT0hMSx0aGlzLl9sZF9pZD1udWxsLHRoaXMuX2R5bkRlbGV0ZUJyYW5jaGVzPXt9LHRoaXMuX29pZV9vblhMRT1bXSx0aGlzLmltUGF0aD13aW5kb3cuZGh4X2dsb2JhbEltZ1BhdGh8fCIiLHRoaXMuY2hlY2tBcnJheT1uZXcgQXJyYXkoImljb25VbmNoZWNrQWxsLmdpZiIsImljb25DaGVja0FsbC5naWYiLCJpY29uQ2hlY2tHcmF5LmdpZiIsImljb25VbmNoZWNrRGlzLmdpZiIsImljb25DaGVja0Rpcy5naWYiLCJpY29uQ2hlY2tEaXMuZ2lmIiksdGhpcy5yYWRpb0FycmF5PW5ldyBBcnJheSgicmFkaW9fb2ZmLmdpZiIsInJhZGlvX29uLmdpZiIsInJhZGlvX29uLmdpZiIsInJhZGlvX29mZi5naWYiLCJyYWRpb19vbi5naWYiLCJyYWRpb19vbi5naWYiKSx0aGlzLmxpbmVBcnJheT1uZXcgQXJyYXkoImxpbmUyLmdpZiIsImxpbmUzLmdpZiIsImxpbmU0LmdpZiIsYmxhbmtfYmFzZTY0LGJsYW5rX2Jhc2U2NCwibGluZTEuZ2lmIiksdGhpcy5taW51c0FycmF5PW5ldyBBcnJheSgibWludXMyLmdpZiIsIm1pbnVzMy5naWYiLCJtaW51czQuZ2lmIiwiZGF0YTppbWFnZS9naWY7YmFzZTY0LFIwbEdPRGxoRWdBWUFKRUNBTEd2clo2ZG5mVDA5QUFBQUNINUJBRUFBQUlBTEFBQUFBQVNBQmdBQUFJY2xJK3B5KzBQbzV5MFdoc0NEV0IzbUdYZnd3SG1oYWJxeXJaVEFRQTciLCJtaW51czUuZ2lmIiksdGhpcy5wbHVzQXJyYXk9bmV3IEFycmF5KCJwbHVzMi5naWYiLCJwbHVzMy5naWYiLCJwbHVzNC5naWYiLCJkYXRhOmltYWdlL2dpZjtiYXNlNjQsUjBsR09EbGhFZ0FZQUpFQ0FLR2duN0d2cmZUMDlBQUFBQ0g1QkFFQUFBSUFMQUFBQUFBU0FCZ0FBQUljbEkrcHkrMFBvNXkwVW5CRHlIc0NMUUZmT0U2ZGhhYnF5clpKQVFBNyIsInBsdXM1LmdpZiIpLHRoaXMuaW1hZ2VBcnJheT1uZXcgQXJyYXkoImRhdGE6aW1hZ2UvZ2lmO2Jhc2U2NCxSMGxHT0RsaEVnQVNBS0VDQUplWGw3R3ZyZi8vLy8vLy95SDVCQUVLQUFJQUxBQUFBQUFTQUJJQUFBSXpsSStwQXUyOURBaTAxamlUWFJuTm0zVEhCNDVCYUoyZXVsQm94TENTL0s2d09OODBYcHQ2citCOUhrU2FJSVdFS1EwRkFEcz0iLCJkYXRhOmltYWdlL2dpZjtiYXNlNjQsUjBsR09EbGhFZ0FTQUtFQ0FKZVhsN0d2cmYvLy8vLy8veUg1QkFFS0FBSUFMQUFBQUFBU0FCSUFBQUl6bEkrcHl3Y1BtM21oV2drQ3NqQk92VmtpbUVsRzlabENCbFhkKzJYampMS2c1R3FvZVpYcXZzT1FYSy9palVaVEtWVUZBRHM9IiwiZGF0YTppbWFnZS9naWY7YmFzZTY0LFIwbEdPRGxoRWdBU0FLRUNBSmVYbDdHdnJmLy8vLy8vL3lINUJBRUtBQUlBTEFBQUFBQVNBQklBQUFJd2xJK3B5d2NQbTNtaFdna0NzakJPdlZraW1FbEc5WmxDdVlJWTZUWXMrNmJtSERPNGlnZmREM0dOaGhlVjBWUUFBRHM9IiksdGhpcy5jdXRJbWc9bmV3IEFycmF5KDAsMCwwKSx0aGlzLmN1dEltYWdlPSJidXRfY3V0LmdpZiIsZGh4NC5fZXZlbnRhYmxlKHRoaXMpLHRoaXMuaHRtbE5vZGU9bmV3IGRodG1sWFRyZWVJdGVtT2JqZWN0KHRoaXMucm9vdElkLCIiLDAsdGhpcyksdGhpcy5odG1sTm9kZS5odG1sTm9kZS5jaGlsZE5vZGVzWzBdLmNoaWxkTm9kZXNbMF0uc3R5bGUuZGlzcGxheT0ibm9uZSIsdGhpcy5odG1sTm9kZS5odG1sTm9kZS5jaGlsZE5vZGVzWzBdLmNoaWxkTm9kZXNbMF0uY2hpbGROb2Rlc1swXS5jbGFzc05hbWU9ImhpZGRlblJvdyIsdGhpcy5hbGxUcmVlPXRoaXMuX2NyZWF0ZVNlbGYoKSx0aGlzLmFsbFRyZWUuYXBwZW5kQ2hpbGQodGhpcy5odG1sTm9kZS5odG1sTm9kZSksZGh0bWx4LiRjdXN0b21TY3JvbGwmJmRodG1seC5DdXN0b21TY3JvbGwuZW5hYmxlKHRoaXMpLF9pc0ZGJiYodGhpcy5hbGxUcmVlLmNoaWxkTm9kZXNbMF0ud2lkdGg9IjEwMCUiLHRoaXMuYWxsVHJlZS5jaGlsZE5vZGVzWzBdLnN0eWxlLm92ZXJmbG93PSJoaWRkZW4iKTt2YXIgcj10aGlzO2lmKHRoaXMuYWxsVHJlZS5vbnNlbGVjdHN0YXJ0PW5ldyBGdW5jdGlvbigicmV0dXJuIGZhbHNlOyIpLF9pc01hY09TJiYodGhpcy5hbGxUcmVlLm9uY29udGV4dG1lbnU9ZnVuY3Rpb24oZSl7cmV0dXJuIHIuX2RvQ29udENsaWNrKGV8fHdpbmRvdy5ldmVudCwhMCl9KSx0aGlzLmFsbFRyZWUub25tb3VzZWRvd249ZnVuY3Rpb24oZSl7cmV0dXJuIHIuX2RvQ29udENsaWNrKGV8fHdpbmRvdy5ldmVudCl9LHRoaXMuWE1MTG9hZGVyPXRoaXMuX3BhcnNlWE1MVHJlZSxfaXNJRSYmdGhpcy5wcmV2ZW50SUVDYXNoaW5nKCEwKSx0aGlzLnNlbGVjdGlvbkJhcj1kb2N1bWVudC5jcmVhdGVFbGVtZW50KCJESVYiKSx0aGlzLnNlbGVjdGlvbkJhci5jbGFzc05hbWU9InNlbGVjdGlvbkJhciIsdGhpcy5zZWxlY3Rpb25CYXIuaW5uZXJIVE1MPSImbmJzcDsiLHRoaXMuc2VsZWN0aW9uQmFyLnN0eWxlLmRpc3BsYXk9Im5vbmUiLHRoaXMuYWxsVHJlZS5hcHBlbmRDaGlsZCh0aGlzLnNlbGVjdGlvbkJhciksd2luZG93LmFkZEV2ZW50TGlzdGVuZXImJndpbmRvdy5hZGRFdmVudExpc3RlbmVyKCJ1bmxvYWQiLGZ1bmN0aW9uKCl7dHJ5e3IuZGVzdHJ1Y3RvcigpfWNhdGNoKGUpe319LCExKSx3aW5kb3cuYXR0YWNoRXZlbnQmJndpbmRvdy5hdHRhY2hFdmVudCgib251bmxvYWQiLGZ1bmN0aW9uKCl7dHJ5e3IuZGVzdHJ1Y3RvcigpfWNhdGNoKGUpe319KSx0aGlzLnNldEltYWdlc1BhdGg9dGhpcy5zZXRJbWFnZVBhdGgsdGhpcy5zZXRJY29uc1BhdGg9dGhpcy5zZXRJY29uUGF0aCx0aGlzLnNldFNraW4oIm1hdGVyaWFsIiksZGh0bWx4LmltYWdlX3BhdGgpe3ZhciBsPWRodG1seC5pbWFnZV9wYXRoLHM9dGhpcy5wYXJlbnRPYmplY3QuY2xhc3NOYW1lLm1hdGNoKC9kaHh0cmVlX2RoeF8oW2Etel9dKikvaSk7bnVsbCE9cyYmbnVsbCE9c1sxXSYmKGwrPSJkaHh0cmVlXyIrc1sxXSsiLyIpLHRoaXMuc2V0SW1hZ2VQYXRoKGwpfXJldHVybiB0aGlzfWZ1bmN0aW9uIGNPYmplY3QoKXtyZXR1cm4gdGhpc31mdW5jdGlvbiBkaHRtbFhUcmVlSXRlbU9iamVjdChlLHQsaSxuLG8scil7cmV0dXJuIHRoaXMuaHRtbE5vZGU9IiIsdGhpcy5hY29sb3I9IiIsdGhpcy5zY29sb3I9IiIsdGhpcy50cj0wLHRoaXMuY2hpbGRzQ291bnQ9MCx0aGlzLnRlbXBET01NPTAsdGhpcy50ZW1wRE9NVT0wLHRoaXMuZHJhZ1NwYW49MCx0aGlzLmRyYWdNb3ZlPTAsdGhpcy5zcGFuPTAsdGhpcy5jbG9zZWJsZT0xLHRoaXMuY2hpbGROb2Rlcz1uZXcgQXJyYXksdGhpcy51c2VyRGF0YT1uZXcgY09iamVjdCx0aGlzLmNoZWNrc3RhdGU9MCx0aGlzLnRyZWVOb2Q9bix0aGlzLmxhYmVsPXQsdGhpcy5wYXJlbnRPYmplY3Q9aSx0aGlzLmFjdGlvbkhhbmRsZXI9byx0aGlzLmltYWdlcz1uZXcgQXJyYXkobi5pbWFnZUFycmF5WzBdLG4uaW1hZ2VBcnJheVsxXSxuLmltYWdlQXJyYXlbMl0pLHRoaXMuaWQ9bi5fZ2xvYmFsSWRTdG9yYWdlQWRkKGUsdGhpcyksdGhpcy50cmVlTm9kLmNoZWNrQm94T2ZmP3RoaXMuaHRtbE5vZGU9dGhpcy50cmVlTm9kLl9jcmVhdGVJdGVtKDEsdGhpcyxyKTp0aGlzLmh0bWxOb2RlPXRoaXMudHJlZU5vZC5fY3JlYXRlSXRlbSgwLHRoaXMsciksdGhpcy5odG1sTm9kZS5vYmpCZWxvbmc9dGhpcyx0aGlzfWZ1bmN0aW9uIGpzb25Qb2ludGVyKGUsdCl7dGhpcy5kPWUsdGhpcy5kcD10fWZ1bmN0aW9uIGRoeF9pbml0X3RyZWVzKCl7Zm9yKHZhciBlPWRvY3VtZW50LmdldEVsZW1lbnRzQnlUYWdOYW1lKCJkaXYiKSx0PTA7dDxlLmxlbmd0aDt0KyspImRodG1seFRyZWUiPT1lW3RdLmNsYXNzTmFtZSYmZGh0bWxYVHJlZUZyb21IVE1MKGVbdF0pfXZhciBibGFua19iYXNlNjQ9ImRhdGE6aW1hZ2UvZ2lmO2Jhc2U2NCxSMGxHT0RsaEVnQVNBSUFBQVAvLy8vLy8veUg1QkFVVUFBRUFMQUFBQUFBU0FCSUFBQUlQakkrcHkrMFBvNXkwMm91ejNwd1hBRHM9IjsidW5kZWZpbmVkIj09dHlwZW9mIHdpbmRvdy5kaHgmJih3aW5kb3cuZGh4PXdpbmRvdy5kaHg0PXt2ZXJzaW9uOiI1LjAiLHNraW46bnVsbCxsYXN0SWQ6MSxuZXdJZDpmdW5jdGlvbigpe3JldHVybiB0aGlzLmxhc3RJZCsrfSx6aW06e2RhdGE6e30sc3RlcDo1LGZpcnN0OmZ1bmN0aW9uKCl7cmV0dXJuIDEwMH0sbGFzdDpmdW5jdGlvbigpe3ZhciBlPXRoaXMuZmlyc3QoKTtmb3IodmFyIHQgaW4gdGhpcy5kYXRhKWU9TWF0aC5tYXgoZSx0aGlzLmRhdGFbdF0pO3JldHVybiBlfSxyZXNlcnZlOmZ1bmN0aW9uKGUpe3JldHVybiB0aGlzLmRhdGFbZV09dGhpcy5sYXN0KCkrdGhpcy5zdGVwLHRoaXMuZGF0YVtlXX0sY2xlYXI6ZnVuY3Rpb24oZSl7bnVsbCE9dGhpcy5kYXRhW2VdJiYodGhpcy5kYXRhW2VdPW51bGwsZGVsZXRlIHRoaXMuZGF0YVtlXSl9fSxzMmI6ZnVuY3Rpb24oZSl7cmV0dXJuInN0cmluZyI9PXR5cGVvZiBlJiYoZT1lLnRvTG93ZXJDYXNlKCkpLDE9PWV8fDE9PWV8fCJ0cnVlIj09ZXx8IjEiPT1lfHwieWVzIj09ZXx8InkiPT1lfHwib24iPT1lfSxzMmo6ZnVuY3Rpb24ocyl7dmFyIG9iaj1udWxsO2RoeDQudGVtcD1udWxsO3RyeXtldmFsKCJkaHg0LnRlbXA9IitzKX1jYXRjaChlKXtkaHg0LnRlbXA9bnVsbH1yZXR1cm4gb2JqPWRoeDQudGVtcCxkaHg0LnRlbXA9bnVsbCxvYmp9LGFic0xlZnQ6ZnVuY3Rpb24oZSl7cmV0dXJuInN0cmluZyI9PXR5cGVvZiBlJiYoZT1kb2N1bWVudC5nZXRFbGVtZW50QnlJZChlKSksdGhpcy5nZXRPZmZzZXQoZSkubGVmdH0sYWJzVG9wOmZ1bmN0aW9uKGUpe3JldHVybiJzdHJpbmciPT10eXBlb2YgZSYmKGU9ZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoZSkpLHRoaXMuZ2V0T2Zmc2V0KGUpLnRvcH0sX2FPZnM6ZnVuY3Rpb24oZSl7Zm9yKHZhciB0PTAsaT0wO2U7KXQrPXBhcnNlSW50KGUub2Zmc2V0VG9wKSxpKz1wYXJzZUludChlLm9mZnNldExlZnQpLGU9ZS5vZmZzZXRQYXJlbnQ7cmV0dXJue3RvcDp0LGxlZnQ6aX19LF9hT2ZzUmVjdDpmdW5jdGlvbihlKXt2YXIgdD1lLmdldEJvdW5kaW5nQ2xpZW50UmVjdCgpLGk9ZG9jdW1lbnQuYm9keSxuPWRvY3VtZW50LmRvY3VtZW50RWxlbWVudCxvPXdpbmRvdy5wYWdlWU9mZnNldHx8bi5zY3JvbGxUb3B8fGkuc2Nyb2xsVG9wLHI9d2luZG93LnBhZ2VYT2Zmc2V0fHxuLnNjcm9sbExlZnR8fGkuc2Nyb2xsTGVmdCxsPW4uY2xpZW50VG9wfHxpLmNsaWVudFRvcHx8MCxzPW4uY2xpZW50TGVmdHx8aS5jbGllbnRMZWZ0fHwwLGE9dC50b3Arby1sLGQ9dC5sZWZ0K3ItcztyZXR1cm57dG9wOk1hdGgucm91bmQoYSksbGVmdDpNYXRoLnJvdW5kKGQpfX0sZ2V0T2Zmc2V0OmZ1bmN0aW9uKGUpe3JldHVybiBlLmdldEJvdW5kaW5nQ2xpZW50UmVjdD90aGlzLl9hT2ZzUmVjdChlKTp0aGlzLl9hT2ZzKGUpfSxfaXNPYmo6ZnVuY3Rpb24oZSl7cmV0dXJuIG51bGwhPWUmJiJvYmplY3QiPT10eXBlb2YgZSYmInVuZGVmaW5lZCI9PXR5cGVvZiBlLmxlbmd0aH0sX2NvcHlPYmo6ZnVuY3Rpb24oZSl7aWYodGhpcy5faXNPYmooZSkpe3ZhciB0PXt9O2Zvcih2YXIgaSBpbiBlKSJvYmplY3QiPT10eXBlb2YgZVtpXSYmbnVsbCE9ZVtpXT90W2ldPXRoaXMuX2NvcHlPYmooZVtpXSk6dFtpXT1lW2ldfWVsc2UgZm9yKHZhciB0PVtdLGk9MDtpPGUubGVuZ3RoO2krKykib2JqZWN0Ij09dHlwZW9mIGVbaV0mJm51bGwhPWVbaV0/dFtpXT10aGlzLl9jb3B5T2JqKGVbaV0pOnRbaV09ZVtpXTtyZXR1cm4gdH19LHdpbmRvdy5kaHg0LmlzSUU9bmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJNU0lFIik+PTB8fG5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiVHJpZGVudCIpPj0wLHdpbmRvdy5kaHg0LmlzSUU2PW51bGw9PXdpbmRvdy5YTUxIdHRwUmVxdWVzdCYmbmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJNU0lFIik+PTAsd2luZG93LmRoeDQuaXNJRTc9bmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJNU0lFIDcuMCIpPj0wJiZuYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIlRyaWRlbnQiKTwwLHdpbmRvdy5kaHg0LmlzSUU4PW5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiTVNJRSA4LjAiKT49MCYmbmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJUcmlkZW50Iik+PTAsd2luZG93LmRoeDQuaXNJRTk9bmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJNU0lFIDkuMCIpPj0wJiZuYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIlRyaWRlbnQiKT49MCx3aW5kb3cuZGh4NC5pc0lFMTA9bmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJNU0lFIDEwLjAiKT49MCYmbmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJUcmlkZW50Iik+PTAmJjEhPXdpbmRvdy5uYXZpZ2F0b3IucG9pbnRlckVuYWJsZWQsd2luZG93LmRoeDQuaXNJRTExPW5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiVHJpZGVudCIpPj0wJiYxPT13aW5kb3cubmF2aWdhdG9yLnBvaW50ZXJFbmFibGVkLHdpbmRvdy5kaHg0LmlzRWRnZT1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIkVkZ2UiKT49MCx3aW5kb3cuZGh4NC5pc09wZXJhPW5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiT3BlcmEiKT49MCx3aW5kb3cuZGh4NC5pc0Nocm9tZT1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIkNocm9tZSIpPj0wJiYhd2luZG93LmRoeDQuaXNFZGdlLHdpbmRvdy5kaHg0LmlzS0hUTUw9KG5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiU2FmYXJpIik+PTB8fG5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiS29ucXVlcm9yIik+PTApJiYhd2luZG93LmRoeDQuaXNFZGdlLHdpbmRvdy5kaHg0LmlzRkY9bmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJGaXJlZm94Iik+PTAsd2luZG93LmRoeDQuaXNJUGFkPW5hdmlnYXRvci51c2VyQWdlbnQuc2VhcmNoKC9pUGFkL2dpKT49MCx3aW5kb3cuZGh4NC5kbmQ9e2V2czp7fSxwX2VuOih3aW5kb3cuZGh4NC5pc0lFfHx3aW5kb3cuZGh4NC5pc0VkZ2UpJiYod2luZG93Lm5hdmlnYXRvci5wb2ludGVyRW5hYmxlZHx8d2luZG93Lm5hdmlnYXRvci5tc1BvaW50ZXJFbmFibGVkKSxfbVRvdWNoOmZ1bmN0aW9uKGUpe3JldHVybiB3aW5kb3cuZGh4NC5pc0lFMTAmJmUucG9pbnRlclR5cGU9PWUuTVNQT0lOVEVSX1RZUEVfTU9VU0V8fHdpbmRvdy5kaHg0LmlzSUUxMSYmIm1vdXNlIj09ZS5wb2ludGVyVHlwZXx8d2luZG93LmRoeDQuaXNFZGdlJiYibW91c2UiPT1lLnBvaW50ZXJUeXBlfSxfdG91Y2hPbjpmdW5jdGlvbihlKXtudWxsPT1lJiYoZT1kb2N1bWVudC5ib2R5KSxlLnN0eWxlLnRvdWNoQWN0aW9uPWUuc3R5bGUubXNUb3VjaEFjdGlvbj0iIixlPW51bGx9LF90b3VjaE9mZjpmdW5jdGlvbihlKXtudWxsPT1lJiYoZT1kb2N1bWVudC5ib2R5KSxlLnN0eWxlLnRvdWNoQWN0aW9uPWUuc3R5bGUubXNUb3VjaEFjdGlvbj0ibm9uZSIsZT1udWxsfX0sMT09d2luZG93Lm5hdmlnYXRvci5wb2ludGVyRW5hYmxlZD93aW5kb3cuZGh4NC5kbmQuZXZzPXtzdGFydDoicG9pbnRlcmRvd24iLG1vdmU6InBvaW50ZXJtb3ZlIixlbmQ6InBvaW50ZXJ1cCJ9OjE9PXdpbmRvdy5uYXZpZ2F0b3IubXNQb2ludGVyRW5hYmxlZD93aW5kb3cuZGh4NC5kbmQuZXZzPXtzdGFydDoiTVNQb2ludGVyRG93biIsbW92ZToiTVNQb2ludGVyTW92ZSIsZW5kOiJNU1BvaW50ZXJVcCJ9OiJ1bmRlZmluZWQiIT10eXBlb2Ygd2luZG93LmFkZEV2ZW50TGlzdGVuZXImJih3aW5kb3cuZGh4NC5kbmQuZXZzPXtzdGFydDoidG91Y2hzdGFydCIsbW92ZToidG91Y2htb3ZlIixlbmQ6InRvdWNoZW5kIn0pKSwidW5kZWZpbmVkIj09dHlwZW9mIHdpbmRvdy5kaHg0Ll9ldmVudGFibGUmJih3aW5kb3cuZGh4NC5fZXZlbnRhYmxlPWZ1bmN0aW9uKGUsdCl7cmV0dXJuImNsZWFyIj09dD8oZS5kZXRhY2hBbGxFdmVudHMoKSxlLmRoeGV2cz1udWxsLGUuYXR0YWNoRXZlbnQ9bnVsbCxlLmRldGFjaEV2ZW50PW51bGwsZS5jaGVja0V2ZW50PW51bGwsZS5jYWxsRXZlbnQ9bnVsbCxlLmRldGFjaEFsbEV2ZW50cz1udWxsLHZvaWQoZT1udWxsKSk6KGUuZGh4ZXZzPXtkYXRhOnt9fSxlLmF0dGFjaEV2ZW50PWZ1bmN0aW9uKGUsdCl7ZT1TdHJpbmcoZSkudG9Mb3dlckNhc2UoKSx0aGlzLmRoeGV2cy5kYXRhW2VdfHwodGhpcy5kaHhldnMuZGF0YVtlXT17fSk7dmFyIGk9d2luZG93LmRoeDQubmV3SWQoKTtyZXR1cm4gdGhpcy5kaHhldnMuZGF0YVtlXVtpXT10LGl9LGUuZGV0YWNoRXZlbnQ9ZnVuY3Rpb24oZSl7Zm9yKHZhciB0IGluIHRoaXMuZGh4ZXZzLmRhdGEpe3ZhciBpPTA7Zm9yKHZhciBuIGluIHRoaXMuZGh4ZXZzLmRhdGFbdF0pbj09ZT8odGhpcy5kaHhldnMuZGF0YVt0XVtuXT1udWxsLGRlbGV0ZSB0aGlzLmRoeGV2cy5kYXRhW3RdW25dKTppKys7MD09aSYmKHRoaXMuZGh4ZXZzLmRhdGFbdF09bnVsbCxkZWxldGUgdGhpcy5kaHhldnMuZGF0YVt0XSl9fSxlLmNoZWNrRXZlbnQ9ZnVuY3Rpb24oZSl7cmV0dXJuIGU9U3RyaW5nKGUpLnRvTG93ZXJDYXNlKCksbnVsbCE9dGhpcy5kaHhldnMuZGF0YVtlXX0sZS5jYWxsRXZlbnQ9ZnVuY3Rpb24oZSx0KXtpZihlPVN0cmluZyhlKS50b0xvd2VyQ2FzZSgpLG51bGw9PXRoaXMuZGh4ZXZzLmRhdGFbZV0pcmV0dXJuITA7dmFyIGk9ITA7Zm9yKHZhciBuIGluIHRoaXMuZGh4ZXZzLmRhdGFbZV0paT10aGlzLmRoeGV2cy5kYXRhW2VdW25dLmFwcGx5KHRoaXMsdCkmJmk7cmV0dXJuIGl9LGUuZGV0YWNoQWxsRXZlbnRzPWZ1bmN0aW9uKCl7Zm9yKHZhciBlIGluIHRoaXMuZGh4ZXZzLmRhdGEpe2Zvcih2YXIgdCBpbiB0aGlzLmRoeGV2cy5kYXRhW2VdKXRoaXMuZGh4ZXZzLmRhdGFbZV1bdF09bnVsbCxkZWxldGUgdGhpcy5kaHhldnMuZGF0YVtlXVt0XTt0aGlzLmRoeGV2cy5kYXRhW2VdPW51bGwsZGVsZXRlIHRoaXMuZGh4ZXZzLmRhdGFbZV19fSx2b2lkKGU9bnVsbCkpfSxkaHg0Ll9ldmVudGFibGUoZGh4NCkpLCJ1bmRlZmluZWQiPT10eXBlb2Ygd2luZG93LmRodG1seCYmKHdpbmRvdy5kaHRtbHg9e2V4dGVuZDpmdW5jdGlvbihlLHQpe2Zvcih2YXIgaSBpbiB0KWVbaV18fChlW2ldPXRbaV0pO3JldHVybiBlfSxleHRlbmRfYXBpOmZ1bmN0aW9uKGUsdCxpKXt2YXIgbj13aW5kb3dbZV07biYmKHdpbmRvd1tlXT1mdW5jdGlvbihlKXtpZihlJiYib2JqZWN0Ij09dHlwZW9mIGUmJiFlLnRhZ05hbWUpe3ZhciBpPW4uYXBwbHkodGhpcyx0Ll9pbml0P3QuX2luaXQoZSk6YXJndW1lbnRzKTtmb3IodmFyIG8gaW4gZGh0bWx4KXRbb10mJnRoaXNbdFtvXV0oZGh0bWx4W29dKTtmb3IodmFyIG8gaW4gZSl0W29dP3RoaXNbdFtvXV0oZVtvXSk6MD09PW8uaW5kZXhPZigib24iKSYmdGhpcy5hdHRhY2hFdmVudChvLGVbb10pfWVsc2UgdmFyIGk9bi5hcHBseSh0aGlzLGFyZ3VtZW50cyk7cmV0dXJuIHQuX3BhdGNoJiZ0Ll9wYXRjaCh0aGlzKSxpfHx0aGlzfSx3aW5kb3dbZV0ucHJvdG90eXBlPW4ucHJvdG90eXBlLGkmJmRodG1seC5leHRlbmQod2luZG93W2VdLnByb3RvdHlwZSxpKSl9LHVybDpmdW5jdGlvbihlKXtyZXR1cm4tMSE9ZS5pbmRleE9mKCI/Iik/IiYiOiI/In19KSxfaXNGRj0hMSxfaXNJRT0hMSxfaXNPcGVyYT0hMSxfaXNLSFRNTD0hMSxfaXNNYWNPUz0hMSxfaXNDaHJvbWU9ITEsX0ZGcnY9ITEsX0tIVE1McnY9ITEsX09wZXJhUnY9ITEsLTEhPW5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiTWFjaW50b3NoIikmJihfaXNNYWNPUz0hMCksbmF2aWdhdG9yLnVzZXJBZ2VudC50b0xvd2VyQ2FzZSgpLmluZGV4T2YoImNocm9tZSIpPi0xJiYoX2lzQ2hyb21lPSEwKSwtMSE9bmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJTYWZhcmkiKXx8LTEhPW5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiS29ucXVlcm9yIik/KF9LSFRNTHJ2PXBhcnNlRmxvYXQobmF2aWdhdG9yLnVzZXJBZ2VudC5zdWJzdHIobmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJTYWZhcmkiKSs3LDUpKSxfS0hUTUxydj41MjU/KF9pc0ZGPSEwLF9GRnJ2PTEuOSk6X2lzS0hUTUw9ITApOi0xIT1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIk9wZXJhIik/KF9pc09wZXJhPSEwLF9PcGVyYVJ2PXBhcnNlRmxvYXQobmF2aWdhdG9yLnVzZXJBZ2VudC5zdWJzdHIobmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJPcGVyYSIpKzYsMykpKTotMSE9bmF2aWdhdG9yLmFwcE5hbWUuaW5kZXhPZigiTWljcm9zb2Z0Iik/KF9pc0lFPSEwLCgtMSE9bmF2aWdhdG9yLmFwcFZlcnNpb24uaW5kZXhPZigiTVNJRSA4LjAiKXx8LTEhPW5hdmlnYXRvci5hcHBWZXJzaW9uLmluZGV4T2YoIk1TSUUgOS4wIil8fC0xIT1uYXZpZ2F0b3IuYXBwVmVyc2lvbi5pbmRleE9mKCJNU0lFIDEwLjAiKXx8ZG9jdW1lbnQuZG9jdW1lbnRNb2RlPjcpJiYiQmFja0NvbXBhdCIhPWRvY3VtZW50LmNvbXBhdE1vZGUmJihfaXNJRT04KSk6Ik5ldHNjYXBlIj09bmF2aWdhdG9yLmFwcE5hbWUmJi0xIT1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIlRyaWRlbnQiKT9faXNJRT04OihfaXNGRj0hMCxfRkZydj1wYXJzZUZsb2F0KG5hdmlnYXRvci51c2VyQWdlbnQuc3BsaXQoInJ2OiIpWzFdKSksInVuZGVmaW5lZCI9PXR5cGVvZiB3aW5kb3cuZGh0bWx4RXZlbnQsbnVsbD09ZGh0bWx4RXZlbnQudG91Y2hEZWxheSYmKGRodG1seEV2ZW50LnRvdWNoRGVsYXk9MmUzKSwidW5kZWZpbmVkIj09dHlwZW9mIGRodG1seEV2ZW50LmluaXRUb3VjaCYmKGRodG1seEV2ZW50LmluaXRUb3VjaD1mdW5jdGlvbigpe2Z1bmN0aW9uIGUoKXtpZihpKXt2YXIgZT1kb2N1bWVudC5jcmVhdGVFdmVudCgiSFRNTEV2ZW50cyIpO2UuaW5pdEV2ZW50KCJkYmxjbGljayIsITAsITApLGkuZGlzcGF0Y2hFdmVudChlKSx0PWk9bnVsbH19dmFyIHQsaSxuLG87ZGh0bWx4RXZlbnQoZG9jdW1lbnQuYm9keSwidG91Y2hzdGFydCIsZnVuY3Rpb24ocil7aT1yLnRvdWNoZXNbMF0udGFyZ2V0LG49ci50b3VjaGVzWzBdLmNsaWVudFgsbz1yLnRvdWNoZXNbMF0uY2xpZW50WSx0PXdpbmRvdy5zZXRUaW1lb3V0KGUsZGh0bWx4RXZlbnQudG91Y2hEZWxheSl9KSxkaHRtbHhFdmVudChkb2N1bWVudC5ib2R5LCJ0b3VjaG1vdmUiLGZ1bmN0aW9uKGUpe3QmJihNYXRoLmFicyhlLnRvdWNoZXNbMF0uY2xpZW50WC1uKT41MHx8TWF0aC5hYnMoZS50b3VjaGVzWzBdLmNsaWVudFktbyk+NTApJiYod2luZG93LmNsZWFyVGltZW91dCh0KSx0PWk9ITEpfSksZGh0bWx4RXZlbnQoZG9jdW1lbnQuYm9keSwidG91Y2hlbmQiLGZ1bmN0aW9uKGUpe3QmJih3aW5kb3cuY2xlYXJUaW1lb3V0KHQpLHQ9aT0hMSl9KSxkaHRtbHhFdmVudC5pbml0VG91Y2g9ZnVuY3Rpb24oKXt9fSksZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX2RvQ29udENsaWNrPWZ1bmN0aW9uKGUsdCl7aWYoIXQmJjIhPWUuYnV0dG9uKXJldHVybiB0aGlzLl9hY01lbnUmJih0aGlzLl9hY01lbnUuaGlkZUNvbnRleHRNZW51P3RoaXMuX2FjTWVudS5oaWRlQ29udGV4dE1lbnUoKTp0aGlzLmNNZW51Ll9jb250ZXh0RW5kKCkpLCEwO2Zvcih2YXIgaT1faXNJRT9lLnNyY0VsZW1lbnQ6ZS50YXJnZXQ7aSYmIkJPRFkiIT1pLnRhZ05hbWUmJiFpLnBhcmVudE9iamVjdDspaT1pLnBhcmVudE5vZGU7aWYoIWl8fCFpLnBhcmVudE9iamVjdClyZXR1cm4hMDt2YXIgbj1pLnBhcmVudE9iamVjdDtpZih0aGlzLmNhbGxFdmVudCgib25SaWdodENsaWNrIixbbi5pZCxlXSl8fCgoZS5zcmNFbGVtZW50fHxlLnRhcmdldCkub25jb250ZXh0bWVudT1mdW5jdGlvbihlKXtyZXR1cm4oZXx8ZXZlbnQpLmNhbmNlbEJ1YmJsZT0hMCwhMX0pLHRoaXMuX2FjTWVudT1uLmNNZW51fHx0aGlzLmNNZW51LHRoaXMuX2FjTWVudSl7aWYoIXRoaXMuY2FsbEV2ZW50KCJvbkJlZm9yZUNvbnRleHRNZW51Iixbbi5pZF0pKXJldHVybiEwO2lmKF9pc01hY09TfHwoKGUuc3JjRWxlbWVudHx8ZS50YXJnZXQpLm9uY29udGV4dG1lbnU9ZnVuY3Rpb24oZSl7cmV0dXJuKGV8fGV2ZW50KS5jYW5jZWxCdWJibGU9ITAsITF9KSx0aGlzLl9hY01lbnUuc2hvd0NvbnRleHRNZW51KXt2YXIgbz13aW5kb3cuZG9jdW1lbnQuZG9jdW1lbnRFbGVtZW50LHI9d2luZG93LmRvY3VtZW50LmJvZHksbD1uZXcgQXJyYXkoby5zY3JvbGxMZWZ0fHxyLnNjcm9sbExlZnQsby5zY3JvbGxUb3B8fHIuc2Nyb2xsVG9wKTtpZihfaXNJRSl2YXIgcz1lLmNsaWVudFgrbFswXSxhPWUuY2xpZW50WStsWzFdO2Vsc2UgdmFyIHM9ZS5wYWdlWCxhPWUucGFnZVk7dGhpcy5fYWNNZW51LnNob3dDb250ZXh0TWVudShzLTEsYS0xKSx0aGlzLmNvbnRleHRJRD1uLmlkLGUuY2FuY2VsQnViYmxlPSEwLHRoaXMuX2FjTWVudS5fc2tpcF9oaWRlPSEwfWVsc2UgaS5jb250ZXh0TWVudUlkPW4uaWQsaS5jb250ZXh0TWVudT10aGlzLl9hY01lbnUsaS5hPXRoaXMuX2FjTWVudS5fY29udGV4dFN0YXJ0LGkuYShpLGUpLGkuYT1udWxsO3JldHVybiExfXJldHVybiEwfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5lbmFibGVJRUltYWdlRml4PWZ1bmN0aW9uKGUpe2U/KHRoaXMuX2dldEltZz1mdW5jdGlvbigpe3ZhciBlPWRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoIkRJViIpO3JldHVybiBlLmlubmVySFRNTD0iJm5ic3A7IixlLmNsYXNzTmFtZT0iZGh4X2JnX2ltZ19maXgiLGV9LHRoaXMuX3NldFNyYz1mdW5jdGlvbihlLHQpe2Uuc3R5bGUuYmFja2dyb3VuZEltYWdlPSJ1cmwoIit0KyIpIn0sdGhpcy5fZ2V0U3JjPWZ1bmN0aW9uKGUpe3ZhciB0PWUuc3R5bGUuYmFja2dyb3VuZEltYWdlO3JldHVybiB0LnN1YnN0cig0LHQubGVuZ3RoLTUpLnJlcGxhY2UoLyheIil8KCIkKS9nLCIiKX0pOih0aGlzLl9nZXRJbWc9ZnVuY3Rpb24oZSl7cmV0dXJuIGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoZT09dGhpcy5yb290SWQ/ImRpdiI6ImltZyIpfSx0aGlzLl9zZXRTcmM9ZnVuY3Rpb24oZSx0KXtlLnNyYz10fSx0aGlzLl9nZXRTcmM9ZnVuY3Rpb24oZSl7cmV0dXJuIGUuc3JjfSl9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLmRlc3RydWN0b3I9ZnVuY3Rpb24oKXtmb3IodmFyIGUgaW4gdGhpcy5faWRwdWxsKXt2YXIgdD10aGlzLl9pZHB1bGxbZV07dCYmKHQucGFyZW50T2JqZWN0PW51bGwsdC50cmVlTm9kPW51bGwsdC5jaGlsZE5vZGVzPW51bGwsdC5zcGFuPW51bGwsdC50ci5ub2RlbT1udWxsLHQudHI9bnVsbCx0Lmh0bWxOb2RlLm9iakJlbG9uZz1udWxsLHQuaHRtbE5vZGU9bnVsbCx0aGlzLl9pZHB1bGxbZV09bnVsbCl9dGhpcy5wYXJlbnRPYmplY3QuaW5uZXJIVE1MPSIiLHRoaXMuYWxsVHJlZS5vbnNlbGVjdHN0YXJ0PW51bGwsdGhpcy5hbGxUcmVlLm9uY29udGV4dG1lbnU9bnVsbCx0aGlzLmFsbFRyZWUub25tb3VzZWRvd249bnVsbDtmb3IodmFyIGUgaW4gdGhpcyl0aGlzW2VdPW51bGx9LGNPYmplY3QucHJvdG90eXBlPW5ldyBPYmplY3QsY09iamVjdC5wcm90b3R5cGUuY2xvbmU9ZnVuY3Rpb24oKXtmdW5jdGlvbiBlKCl7fXJldHVybiBlLnByb3RvdHlwZT10aGlzLG5ldyBlfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5fZ2xvYmFsSWRTdG9yYWdlQWRkPWZ1bmN0aW9uKGUsdCl7cmV0dXJuIHRoaXMuX2dsb2JhbElkU3RvcmFnZUZpbmQoZSwxLDEpPyhlPWUrIl8iKyhuZXcgRGF0ZSkudmFsdWVPZigpLHRoaXMuX2dsb2JhbElkU3RvcmFnZUFkZChlLHQpKToodGhpcy5faWRwdWxsW2VdPXQsdGhpcy5fcHVsbFNpemUrKyxlKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX2dsb2JhbElkU3RvcmFnZVN1Yj1mdW5jdGlvbihlKXt0aGlzLl9pZHB1bGxbZV0mJih0aGlzLl91bnNlbGVjdEl0ZW0odGhpcy5faWRwdWxsW2VdKSx0aGlzLl9pZHB1bGxbZV09bnVsbCx0aGlzLl9wdWxsU2l6ZS0tKSx0aGlzLl9sb2NrZXImJnRoaXMuX2xvY2tlcltlXSYmKHRoaXMuX2xvY2tlcltlXT0hMSl9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLl9nbG9iYWxJZFN0b3JhZ2VGaW5kPWZ1bmN0aW9uKGUsdCxpLG4pe3ZhciBvPXRoaXMuX2lkcHVsbFtlXTtpZihvKXtpZihvLnVuUGFyc2VkJiYhaSYmdGhpcy5yZVBhcnNlKG8sMCksdGhpcy5fc3JuZCYmIW8uaHRtbE5vZGUmJnRoaXMuX2J1aWxkU1JORChvLGkpLG4mJnRoaXMuX2Vkc2Jwc0EpZm9yKHZhciByPTA7cjx0aGlzLl9lZHNicHNBLmxlbmd0aDtyKyspaWYodGhpcy5fZWRzYnBzQVtyXVsyXT09ZSlyZXR1cm4gZGh4NC5jYWxsRXZlbnQoIm9uZ2V0SXRlbUVycm9yIixbIlJlcXVlc3RlZCBpdGVtIHN0aWxsIGluIHBhcnNpbmcgcHJvY2Vzcy4iLGVdKSxudWxsO3JldHVybiBvfXJldHVybiB0aGlzLnNsb3dQYXJzZSYmMCE9ZSYmIXQ/dGhpcy5wcmVQYXJzZShlKTpudWxsfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5fZHJhd05ld1RyPWZ1bmN0aW9uKGUsdCl7dmFyIGk9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgidHIiKSxuPWRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoInRkIiksbz1kb2N1bWVudC5jcmVhdGVFbGVtZW50KCJ0ZCIpO3JldHVybiBuLmFwcGVuZENoaWxkKGRvY3VtZW50LmNyZWF0ZVRleHROb2RlKCIgIikpLG8uY29sU3Bhbj0zLG8uYXBwZW5kQ2hpbGQoZSksaS5hcHBlbmRDaGlsZChuKSxpLmFwcGVuZENoaWxkKG8pLGl9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLnBhcnNlPWZ1bmN0aW9uKGUsdCxpKXtpZigic3RyaW5nIj09dHlwZW9mIHQmJihpPXQsdD1udWxsKSwianNvbiI9PT1pKXJldHVybiB0aGlzLl9sb2FkSlNPTk9iamVjdChlLHQpO2lmKCJjc3YiPT09aSlyZXR1cm4gdGhpcy5fbG9hZENTVlN0cmluZyhlLHQpO2lmKCJqc2FycmF5Ij09PWkpcmV0dXJuIHRoaXMuX2xvYWRKU0FycmF5KGUsdCk7dmFyIG49dGhpczt0aGlzLnBhcnNDb3VudHx8dGhpcy5jYWxsRXZlbnQoIm9uWExTIixbbixudWxsXSksdGhpcy54bWxzdGF0ZT0xLHRoaXMuWE1MTG9hZGVyKHtyZXNwb25zZVhNTDpkaHg0LmFqYXgucGFyc2UoZSl9LHQpfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5fYXR0YWNoQ2hpbGROb2RlPWZ1bmN0aW9uKGUsdCxpLG4sbyxyLGwscyxhLGQsaCl7ZCYmZC5wYXJlbnRPYmplY3QmJihlPWQucGFyZW50T2JqZWN0KSwwPT1lLlhNTGxvYWQmJnRoaXMuWE1Mc291cmNlJiYhdGhpcy5YTUxsb2FkaW5nV2FybmluZyYmKGUuWE1MbG9hZD0xLHRoaXMuX2xvYWREeW5YTUwoZS5pZCkpO3ZhciBjPWUuY2hpbGRzQ291bnQsdT1lLmNoaWxkTm9kZXM7aWYoaCYmaC50ci5wcmV2aW91c1NpYmxpbmcmJihoLnRyLnByZXZpb3VzU2libGluZy5wcmV2aW91c1NpYmxpbmc/ZD1oLnRyLnByZXZpb3VzU2libGluZy5ub2RlbTpzPXMucmVwbGFjZSgiVE9QIiwiIikrIixUT1AiKSxkKXt2YXIgcCxfO2ZvcihwPTA7Yz5wO3ArKylpZih1W3BdPT1kKXtmb3IoXz1jO18hPXA7Xy0tKXVbMStfXT11W19dO2JyZWFrfXArKyxjPXB9aWYocylmb3IodmFyIG09cy5zcGxpdCgiLCIpLGc9MDtnPG0ubGVuZ3RoO2crKylzd2l0Y2gobVtnXSl7Y2FzZSJUT1AiOmZvcihlLmNoaWxkc0NvdW50PjAmJihkPW5ldyBPYmplY3QsZC50cj1lLmNoaWxkTm9kZXNbMF0udHIucHJldmlvdXNTaWJsaW5nKSxlLl9oYXNfdG9wPSEwLHA9YztwPjA7cC0tKXVbcF09dVtwLTFdO2M9MH12YXIgZjsoZj10aGlzLl9pZHB1bGxbdF0pJiYtMT09Zi5zcGFufHwoZj11W2NdPW5ldyBkaHRtbFhUcmVlSXRlbU9iamVjdCh0LGksZSx0aGlzLG4sMSksdD11W2NdLmlkLGUuY2hpbGRzQ291bnQrKyksZi5odG1sTm9kZXx8KGYubGFiZWw9aSxmLmh0bWxOb2RlPXRoaXMuX2NyZWF0ZUl0ZW0odGhpcy5jaGVja0JveE9mZj8xOjAsZiksZi5odG1sTm9kZS5vYmpCZWxvbmc9ZiksbyYmKGYuaW1hZ2VzWzBdPW8pLHImJihmLmltYWdlc1sxXT1yKSxsJiYoZi5pbWFnZXNbMl09bCk7dmFyIGI9dGhpcy5fZHJhd05ld1RyKGYuaHRtbE5vZGUpO2lmKCh0aGlzLlhNTGxvYWRpbmdXYXJuaW5nfHx0aGlzLl9oQWRJKSYmKGYuaHRtbE5vZGUucGFyZW50Tm9kZS5wYXJlbnROb2RlLnN0eWxlLmRpc3BsYXk9Im5vbmUiKSxkJiZkLnRyJiZkLnRyLm5leHRTaWJsaW5nP2UuaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5pbnNlcnRCZWZvcmUoYixkLnRyLm5leHRTaWJsaW5nKTp0aGlzLnBhcnNpbmdPbj09ZS5pZD90aGlzLnBhcnNlZEFycmF5W3RoaXMucGFyc2VkQXJyYXkubGVuZ3RoXT1iOmUuaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5hcHBlbmRDaGlsZChiKSxkJiYhZC5zcGFuJiYoZD1udWxsKSx0aGlzLlhNTHNvdXJjZSYmKGEmJjAhPWE/Zi5YTUxsb2FkPTA6Zi5YTUxsb2FkPTEpLGYudHI9YixiLm5vZGVtPWYsMD09ZS5pdGVtSWQmJihiLmNoaWxkTm9kZXNbMF0uY2xhc3NOYW1lPSJoaWRkZW5Sb3ciKSwoZS5fcl9sb2dpY3x8dGhpcy5fZnJidHIpJiZ0aGlzLl9zZXRTcmMoZi5odG1sTm9kZS5jaGlsZE5vZGVzWzBdLmNoaWxkTm9kZXNbMF0uY2hpbGROb2Rlc1sxXS5jaGlsZE5vZGVzWzBdLHRoaXMuaW1QYXRoK3RoaXMucmFkaW9BcnJheVswXSkscylmb3IodmFyIG09cy5zcGxpdCgiLCIpLGc9MDtnPG0ubGVuZ3RoO2crKylzd2l0Y2gobVtnXSl7Y2FzZSJTRUxFQ1QiOnRoaXMuc2VsZWN0SXRlbSh0LCExKTticmVhaztjYXNlIkNBTEwiOnRoaXMuc2VsZWN0SXRlbSh0LCEwKTticmVhaztjYXNlIkNISUxEIjpmLlhNTGxvYWQ9MDticmVhaztjYXNlIkNIRUNLRUQiOnRoaXMuWE1MbG9hZGluZ1dhcm5pbmc/dGhpcy5zZXRDaGVja0xpc3QrPXRoaXMuZGxtdHIrdDp0aGlzLnNldENoZWNrKHQsMSk7YnJlYWs7Y2FzZSJIQ0hFQ0tFRCI6dGhpcy5fc2V0Q2hlY2soZiwidW5zdXJlIik7YnJlYWs7Y2FzZSJPUEVOIjpmLm9wZW5NZT0xfWlmKCF0aGlzLlhNTGxvYWRpbmdXYXJuaW5nJiYodGhpcy5fZ2V0T3BlblN0YXRlKGUpPDAmJiF0aGlzLl9oQWRJJiZ0aGlzLm9wZW5JdGVtKGUuaWQpLGQmJih0aGlzLl9jb3JyZWN0UGx1cyhkKSx0aGlzLl9jb3JyZWN0TGluZShkKSksdGhpcy5fY29ycmVjdFBsdXMoZSksdGhpcy5fY29ycmVjdExpbmUoZSksdGhpcy5fY29ycmVjdFBsdXMoZiksZS5jaGlsZHNDb3VudD49MiYmKHRoaXMuX2NvcnJlY3RQbHVzKHVbZS5jaGlsZHNDb3VudC0yXSksdGhpcy5fY29ycmVjdExpbmUodVtlLmNoaWxkc0NvdW50LTJdKSksMiE9ZS5jaGlsZHNDb3VudCYmdGhpcy5fY29ycmVjdFBsdXModVswXSksdGhpcy50c2NoZWNrJiZ0aGlzLl9jb3JyZWN0Q2hlY2tTdGF0ZXMoZSksdGhpcy5fb25yYWRoKSlpZigxPT10aGlzLnhtbHN0YXRlKXt2YXIgdj10aGlzLm9uWExFO3RoaXMub25YTEU9ZnVuY3Rpb24oZSl7dGhpcy5fb25yYWRoKHQpLHYmJnYoZSl9fWVsc2UgdGhpcy5fb25yYWRoKHQpO3JldHVybiBmfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5fcGFyc2VJdGVtPWZ1bmN0aW9uKGUsdCxpLG4pe3ZhciBvO2lmKHRoaXMuX3NybmQmJighdGhpcy5faWRwdWxsW289ZS5nZXQoImlkIildfHwhdGhpcy5faWRwdWxsW29dLnNwYW4pKXJldHVybiB2b2lkIHRoaXMuX2FkZEl0ZW1TUk5EKHQuaWQsbyxlKTt2YXIgcj1lLmdldF9hbGwoKTtpZigib2JqZWN0Ij09dHlwZW9mIHRoaXMud2FpdFVwZGF0ZVhNTCYmIXRoaXMud2FpdFVwZGF0ZVhNTFtyLmlkXSlyZXR1cm4gdm9pZCB0aGlzLl9wYXJzZShlLHIuaWQsMSk7bnVsbCE9PXIudGV4dCYmInVuZGVmaW5lZCIhPXR5cGVvZiByLnRleHR8fChyLnRleHQ9ZS5zdWIoIml0ZW10ZXh0Iiksci50ZXh0JiYoci50ZXh0PXIudGV4dC5jb250ZW50KCkpKTt2YXIgbD1bXTtpZihyLnNlbGVjdCYmbC5wdXNoKCJTRUxFQ1QiKSxyLnRvcCYmbC5wdXNoKCJUT1AiKSxyLmNhbGwmJih0aGlzLm5vZGVBc2tpbmdDYWxsPXIuaWQpLC0xPT1yLmNoZWNrZWQ/bC5wdXNoKCJIQ0hFQ0tFRCIpOnIuY2hlY2tlZCYmbC5wdXNoKCJDSEVDS0VEIiksci5vcGVuJiZsLnB1c2goIk9QRU4iKSx0aGlzLndhaXRVcGRhdGVYTUwpaWYodGhpcy5fZ2xvYmFsSWRTdG9yYWdlRmluZChyLmlkKSl2YXIgcz10aGlzLnVwZGF0ZUl0ZW0oci5pZCxyLnRleHQsci5pbTAsci5pbTEsci5pbTIsci5jaGVja2VkLHIuY2hpbGQpO2Vsc2V7MD09dGhpcy5ucGw/bC5wdXNoKCJUT1AiKTppPXQuY2hpbGROb2Rlc1t0aGlzLm5wbF07dmFyIHM9dGhpcy5fYXR0YWNoQ2hpbGROb2RlKHQsci5pZCxyLnRleHQsMCxyLmltMCxyLmltMSxyLmltMixsLmpvaW4oIiwiKSxyLmNoaWxkLDAsaSk7ci5pZD1zLmlkLGk9bnVsbH1lbHNlIHZhciBzPXRoaXMuX2F0dGFjaENoaWxkTm9kZSh0LHIuaWQsci50ZXh0LDAsci5pbTAsci5pbTEsci5pbTIsbC5qb2luKCIsIiksci5jaGlsZCxufHwwLGkpO2lmKHIudG9vbHRpcCYmKHMuc3Bhbi5wYXJlbnROb2RlLnBhcmVudE5vZGUudGl0bGU9ci50b29sdGlwKSxyLnN0eWxlJiYocy5zcGFuLnN0eWxlLmNzc1RleHQ/cy5zcGFuLnN0eWxlLmNzc1RleHQrPSI7IityLnN0eWxlOnMuc3Bhbi5zZXRBdHRyaWJ1dGUoInN0eWxlIixzLnNwYW4uZ2V0QXR0cmlidXRlKCJzdHlsZSIpKyI7ICIrci5zdHlsZSkpLHIucmFkaW8mJihzLl9yX2xvZ2ljPSEwKSxyLm5vY2hlY2tib3gpe3ZhciBhPXMuc3Bhbi5wYXJlbnROb2RlLnByZXZpb3VzU2libGluZy5wcmV2aW91c1NpYmxpbmc7YS5zdHlsZS5kaXNwbGF5PSJub25lIixzLm5vY2hlY2tib3g9ITB9ci5kaXNhYmxlZCYmKG51bGwhPXIuY2hlY2tlZCYmdGhpcy5fc2V0Q2hlY2socyxyLmNoZWNrZWQpLHRoaXMuZGlzYWJsZUNoZWNrYm94KHMsMSkpLHMuX2FjYz1yLmNoaWxkfHwwLHRoaXMucGFyc2VyRXh0ZW5zaW9uJiZ0aGlzLnBhcnNlckV4dGVuc2lvbi5fcGFyc2VFeHRlbnNpb24uY2FsbCh0aGlzLGUscix0P3QuaWQ6MCksdGhpcy5zZXRJdGVtQ29sb3IocyxyLmFDb2wsci5zQ29sKSwiMSI9PXIubG9ja2VkJiZ0aGlzLmxvY2tJdGVtKHMuaWQsITAsITApLChyLmltd2lkdGh8fHIuaW1oZWlnaHQpJiZ0aGlzLnNldEljb25TaXplKHIuaW13aWR0aCxyLmltaGVpZ2h0LHMpLCIwIiE9ci5jbG9zZWFibGUmJiIxIiE9ci5jbG9zZWFibGV8fHRoaXMuc2V0SXRlbUNsb3NlYWJsZShzLHIuY2xvc2VhYmxlKTt2YXIgZD0iIjtyLnRvcG9mZnNldCYmdGhpcy5zZXRJdGVtVG9wT2Zmc2V0KHMsci50b3BvZmZzZXQpLHRoaXMuc2xvd1BhcnNlJiYib2JqZWN0IiE9dHlwZW9mIHRoaXMud2FpdFVwZGF0ZVhNTD8oIXMuY2hpbGRzQ291bnQmJmUuc3ViX2V4aXN0cygiaXRlbSIpJiYocy51blBhcnNlZD1lLmNsb25lKCkpLGUuZWFjaCgidXNlcmRhdGEiLGZ1bmN0aW9uKGUpe3RoaXMuc2V0VXNlckRhdGEoci5pZCxlLmdldCgibmFtZSIpLGUuY29udGVudCgpKX0sdGhpcykpOmUuc3ViX2V4aXN0cygiaXRlbSIpJiYoZD10aGlzLl9wYXJzZShlLHIuaWQsMSkpLCIiIT1kJiYodGhpcy5ub2RlQXNraW5nQ2FsbD1kKSxlLmVhY2goInVzZXJkYXRhIixmdW5jdGlvbih0KXt0aGlzLnNldFVzZXJEYXRhKGUuZ2V0KCJpZCIpLHQuZ2V0KCJuYW1lIiksdC5jb250ZW50KCkpfSx0aGlzKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX3BhcnNlPWZ1bmN0aW9uKGUsdCxpLG4pe2lmKHRoaXMuX3NybmQmJiF0aGlzLnBhcmVudE9iamVjdC5vZmZzZXRIZWlnaHQpe3ZhciBvPXRoaXM7cmV0dXJuIHdpbmRvdy5zZXRUaW1lb3V0KGZ1bmN0aW9uKCl7by5fcGFyc2UoZSx0LGksbil9LDEwMCl9aWYoZS5leGlzdHMoKSl7aWYodGhpcy5za2lwTG9jaz0hMCwhdCl7dD1lLmdldCgiaWQiKSx0aGlzLl9keW5EZWxldGVCcmFuY2hlc1t0XSYmKHRoaXMuZGVsZXRlQ2hpbGRJdGVtcyh0KSx0aGlzLl9keW5EZWxldGVCcmFuY2hlc1t0XS0tLHRoaXMuX2R5bkRlbGV0ZUJyYW5jaGVzW3RdfHxkZWxldGUgdGhpcy5fZHluRGVsZXRlQnJhbmNoZXNbdF0pO3ZhciByPWUuZ2V0KCJkaHhfc2VjdXJpdHkiKTtyJiYoZGh0bWx4LnNlY3VyaXR5X2tleT1yKSxlLmdldCgicmFkaW8iKSYmKHRoaXMuaHRtbE5vZGUuX3JfbG9naWM9ITApLHRoaXMucGFyc2luZ09uPXQsdGhpcy5wYXJzZWRBcnJheT1uZXcgQXJyYXksdGhpcy5zZXRDaGVja0xpc3Q9IiIsdGhpcy5ub2RlQXNraW5nQ2FsbD0iIn12YXIgbD10aGlzLl9nbG9iYWxJZFN0b3JhZ2VGaW5kKHQpO2lmKCFsKXJldHVybiBkaHg0LmNhbGxFdmVudCgib25EYXRhU3RydWN0dXJlRXJyb3IiLFsiWE1MIHJlZmVycyB0byBub3QgZXhpc3RpbmcgcGFyZW50Il0pO2lmKHRoaXMucGFyc0NvdW50PXRoaXMucGFyc0NvdW50P3RoaXMucGFyc0NvdW50KzE6MSx0aGlzLlhNTGxvYWRpbmdXYXJuaW5nPTEsIWwuY2hpbGRzQ291bnR8fG58fHRoaXMuX2Vkc2Jwc3x8bC5faGFzX3RvcCl2YXIgcz0wO2Vsc2UgdmFyIHM9MDtpZih0aGlzLm5wbD0wLGUuZWFjaCgiaXRlbSIsZnVuY3Rpb24obixvKXtyZXR1cm4gbC5YTUxsb2FkPTEsdGhpcy5fcGFyc2VJdGVtKG4sbCwwLHMpLHRoaXMuX2Vkc2JwcyYmdGhpcy5ucGw9PXRoaXMuX2Vkc2Jwc0M/KHRoaXMuX2Rpc3RyaWJ1dGVkU3RhcnQoZSxvKzEsdCxpLGwuY2hpbGRzQ291bnQpLC0xKTp2b2lkIHRoaXMubnBsKyt9LHRoaXMsbiksIWkpe2lmKGUuZWFjaCgidXNlcmRhdGEiLGZ1bmN0aW9uKHQpe3RoaXMuc2V0VXNlckRhdGEoZS5nZXQoImlkIiksdC5nZXQoIm5hbWUiKSx0LmNvbnRlbnQoKSl9LHRoaXMpLGwuWE1MbG9hZD0xLHRoaXMud2FpdFVwZGF0ZVhNTCl7dGhpcy53YWl0VXBkYXRlWE1MPSExO2Zvcih2YXIgYT1sLmNoaWxkc0NvdW50LTE7YT49MDthLS0pbC5jaGlsZE5vZGVzW2FdLl9kbWFyayYmdGhpcy5kZWxldGVJdGVtKGwuY2hpbGROb2Rlc1thXS5pZCl9Zm9yKHZhciBhPSh0aGlzLl9nbG9iYWxJZFN0b3JhZ2VGaW5kKHRoaXMucGFyc2luZ09uKSwwKTthPHRoaXMucGFyc2VkQXJyYXkubGVuZ3RoO2ErKylsLmh0bWxOb2RlLmNoaWxkTm9kZXNbMF0uYXBwZW5kQ2hpbGQodGhpcy5wYXJzZWRBcnJheVthXSk7dGhpcy5wYXJzZWRBcnJheT1bXSx0aGlzLmxhc3RMb2FkZWRYTUxJZD10LHRoaXMuWE1MbG9hZGluZ1dhcm5pbmc9MDtmb3IodmFyIGQ9dGhpcy5zZXRDaGVja0xpc3Quc3BsaXQodGhpcy5kbG10ciksaD0wO2g8ZC5sZW5ndGg7aCsrKWRbaF0mJnRoaXMuc2V0Q2hlY2soZFtoXSwxKTt0aGlzLlhNTHNvdXJjZSYmdGhpcy50c2NoZWNrJiZ0aGlzLnNtY2hlY2smJmwuaWQhPXRoaXMucm9vdElkJiYoMD09PWwuY2hlY2tzdGF0ZT90aGlzLl9zZXRTdWJDaGVja2VkKDAsbCk6MT09PWwuY2hlY2tzdGF0ZSYmdGhpcy5fc2V0U3ViQ2hlY2tlZCgxLGwpKSx0aGlzLl9yZWRyYXdGcm9tKHRoaXMsbnVsbCxuKSxlLmdldCgib3JkZXIiKSYmIm5vbmUiIT1lLmdldCgib3JkZXIiKSYmdGhpcy5fcmVvcmRlckJyYW5jaChsLGUuZ2V0KCJvcmRlciIpLCEwKSwiIiE9dGhpcy5ub2RlQXNraW5nQ2FsbCYmdGhpcy5jYWxsRXZlbnQoIm9uQ2xpY2siLFt0aGlzLm5vZGVBc2tpbmdDYWxsLHRoaXMuZ2V0U2VsZWN0ZWRJdGVtSWQoKV0pLHRoaXMuX2JyYW5jaFVwZGF0ZSYmdGhpcy5fYnJhbmNoVXBkYXRlTmV4dChlKX1pZigxPT10aGlzLnBhcnNDb3VudCl7aWYodGhpcy5wYXJzaW5nT249bnVsbCx0aGlzLl9zcm5kJiZsLmlkIT10aGlzLnJvb3RJZCYmKHRoaXMucHJlcGFyZVNSKGwuaWQpLHRoaXMuWE1Mc291cmNlJiZ0aGlzLm9wZW5JdGVtKGwuaWQpKSxlLnRocm91Z2goIml0ZW0iLCJvcGVuIixudWxsLGZ1bmN0aW9uKGUpe3RoaXMub3Blbkl0ZW0oZS5nZXQoImlkIikpfSx0aGlzKSwhdGhpcy5fZWRzYnBzfHwhdGhpcy5fZWRzYnBzQS5sZW5ndGgpe3ZhciBjPXRoaXM7d2luZG93LnNldFRpbWVvdXQoZnVuY3Rpb24oKXtjLmNhbGxFdmVudCgib25YTEUiLFtjLHRdKX0sMSksdGhpcy54bWxzdGF0ZT0wfXRoaXMuc2tpcExvY2s9ITF9dGhpcy5wYXJzQ291bnQtLTt2YXIgYz10aGlzO3JldHVybiB0aGlzLl9lZHNicHMmJndpbmRvdy5zZXRUaW1lb3V0KGZ1bmN0aW9uKCl7Yy5fZGlzdHJpYnV0ZWRTdGVwKHQpfSx0aGlzLl9lZHNicHNEKSwhaSYmdGhpcy5vblhMRSYmdGhpcy5vblhMRSh0aGlzLHQpLHRoaXMubm9kZUFza2luZ0NhbGx9fSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5fcmVkcmF3RnJvbT1mdW5jdGlvbihlLHQsaSxuKXtpZih0KW89dDtlbHNle3ZhciBvPWUuX2dsb2JhbElkU3RvcmFnZUZpbmQoZS5sYXN0TG9hZGVkWE1MSWQpO2lmKGUubGFzdExvYWRlZFhNTElkPS0xLCFvKXJldHVybiAwfWZvcih2YXIgcj0wLGw9aT9pLTE6MDtsPG8uY2hpbGRzQ291bnQ7bCsrKWlmKHRoaXMuX2JyYW5jaFVwZGF0ZSYmMSE9dGhpcy5fZ2V0T3BlblN0YXRlKG8pfHx0JiYxIT1ufHwoby5jaGlsZE5vZGVzW2xdLmh0bWxOb2RlLnBhcmVudE5vZGUucGFyZW50Tm9kZS5zdHlsZS5kaXNwbGF5PSIiKSwxPT1vLmNoaWxkTm9kZXNbbF0ub3Blbk1lJiYodGhpcy5fb3Blbkl0ZW0oby5jaGlsZE5vZGVzW2xdKSxvLmNoaWxkTm9kZXNbbF0ub3Blbk1lPTApLGUuX3JlZHJhd0Zyb20oZSxvLmNoaWxkTm9kZXNbbF0pLG51bGwhPXRoaXMuY2hpbGRDYWxjKXtpZigoby5jaGlsZE5vZGVzW2xdLnVuUGFyc2VkfHwhby5jaGlsZE5vZGVzW2xdLlhNTGxvYWQmJnRoaXMuWE1Mc291cmNlKSYmKG8uY2hpbGROb2Rlc1tsXS5fYWNjP28uY2hpbGROb2Rlc1tsXS5zcGFuLmlubmVySFRNTD1vLmNoaWxkTm9kZXNbbF0ubGFiZWwrdGhpcy5odG1sY0Erby5jaGlsZE5vZGVzW2xdLl9hY2MrdGhpcy5odG1sY0I6by5jaGlsZE5vZGVzW2xdLnNwYW4uaW5uZXJIVE1MPW8uY2hpbGROb2Rlc1tsXS5sYWJlbCksby5jaGlsZE5vZGVzW2xdLmNoaWxkTm9kZXMubGVuZ3RoJiZ0aGlzLmNoaWxkQ2FsYyl7aWYoMT09dGhpcy5jaGlsZENhbGMmJihvLmNoaWxkTm9kZXNbbF0uc3Bhbi5pbm5lckhUTUw9by5jaGlsZE5vZGVzW2xdLmxhYmVsK3RoaXMuaHRtbGNBK28uY2hpbGROb2Rlc1tsXS5jaGlsZHNDb3VudCt0aGlzLmh0bWxjQiksMj09dGhpcy5jaGlsZENhbGMpe3ZhciBzPW8uY2hpbGROb2Rlc1tsXS5jaGlsZHNDb3VudC0oby5jaGlsZE5vZGVzW2xdLnB1cmVDaGlsZHN8fDApO3MmJihvLmNoaWxkTm9kZXNbbF0uc3Bhbi5pbm5lckhUTUw9by5jaGlsZE5vZGVzW2xdLmxhYmVsK3RoaXMuaHRtbGNBK3MrdGhpcy5odG1sY0IpLG8ucHVyZUNoaWxkcz9vLnB1cmVDaGlsZHMrKzpvLnB1cmVDaGlsZHM9MX1pZigzPT10aGlzLmNoaWxkQ2FsYyYmKG8uY2hpbGROb2Rlc1tsXS5zcGFuLmlubmVySFRNTD1vLmNoaWxkTm9kZXNbbF0ubGFiZWwrdGhpcy5odG1sY0Erby5jaGlsZE5vZGVzW2xdLl9hY2MrdGhpcy5odG1sY0IpLDQ9PXRoaXMuY2hpbGRDYWxjKXt2YXIgcz1vLmNoaWxkTm9kZXNbbF0uX2FjYztzJiYoby5jaGlsZE5vZGVzW2xdLnNwYW4uaW5uZXJIVE1MPW8uY2hpbGROb2Rlc1tsXS5sYWJlbCt0aGlzLmh0bWxjQStzK3RoaXMuaHRtbGNCKX19ZWxzZSA0PT10aGlzLmNoaWxkQ2FsYyYmcisrO3IrPW8uY2hpbGROb2Rlc1tsXS5fYWNjLDM9PXRoaXMuY2hpbGRDYWxjJiZyKyt9by51blBhcnNlZHx8IW8uWE1MbG9hZCYmdGhpcy5YTUxzb3VyY2V8fChvLl9hY2M9ciksZS5fY29ycmVjdExpbmUobyksZS5fY29ycmVjdFBsdXMobyksdGhpcy5jaGlsZENhbGMmJiF0JiZlLl9maXhDaGlsZENvdW50TGFiZWwobyl9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLl9jcmVhdGVTZWxmPWZ1bmN0aW9uKCl7dmFyIGU9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgiZGl2Iik7cmV0dXJuIGUuY2xhc3NOYW1lPSJjb250YWluZXJUYWJsZVN0eWxlIixlLnN0eWxlLndpZHRoPXRoaXMud2lkdGgsZS5zdHlsZS5oZWlnaHQ9dGhpcy5oZWlnaHQsdGhpcy5wYXJlbnRPYmplY3QuYXBwZW5kQ2hpbGQoZSksZX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX3hjbG9zZUFsbD1mdW5jdGlvbihlKXtpZighZS51blBhcnNlZCl7aWYodGhpcy5yb290SWQhPWUuaWQpe2lmKCFlLmh0bWxOb2RlKXJldHVybjtmb3IodmFyIHQ9ZS5odG1sTm9kZS5jaGlsZE5vZGVzWzBdLmNoaWxkTm9kZXMsaT10Lmxlbmd0aCxuPTE7aT5uO24rKyl0W25dLnN0eWxlLmRpc3BsYXk9Im5vbmUiO3RoaXMuX2NvcnJlY3RQbHVzKGUpfWZvcih2YXIgbj0wO248ZS5jaGlsZHNDb3VudDtuKyspZS5jaGlsZE5vZGVzW25dLmNoaWxkc0NvdW50JiZ0aGlzLl94Y2xvc2VBbGwoZS5jaGlsZE5vZGVzW25dKX19LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLl94b3BlbkFsbD1mdW5jdGlvbihlKXt0aGlzLl9IaWRlU2hvdyhlLDIpO2Zvcih2YXIgdD0wO3Q8ZS5jaGlsZHNDb3VudDt0KyspdGhpcy5feG9wZW5BbGwoZS5jaGlsZE5vZGVzW3RdKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX2NvcnJlY3RQbHVzPWZ1bmN0aW9uKGUpe2lmKGUuaHRtbE5vZGUpe3ZhciB0PWUuaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5jaGlsZE5vZGVzWzBdLmNoaWxkTm9kZXNbMF0ubGFzdENoaWxkLGk9ZS5odG1sTm9kZS5jaGlsZE5vZGVzWzBdLmNoaWxkTm9kZXNbMF0uY2hpbGROb2Rlc1syXS5jaGlsZE5vZGVzWzBdLG49dGhpcy5saW5lQXJyYXk7aWYodGhpcy5YTUxzb3VyY2UmJiFlLlhNTGxvYWQpe3ZhciBuPXRoaXMucGx1c0FycmF5O2lmKHRoaXMuX3NldFNyYyhpLHRoaXMuaWNvblVSTCtlLmltYWdlc1syXSksdGhpcy5fdHh0aW1nKXJldHVybiB0LmlubmVySFRNTD0iWytdIn1lbHNlIGlmKGUuY2hpbGRzQ291bnR8fGUudW5QYXJzZWQpaWYoZS5odG1sTm9kZS5jaGlsZE5vZGVzWzBdLmNoaWxkTm9kZXNbMV0mJiJub25lIiE9ZS5odG1sTm9kZS5jaGlsZE5vZGVzWzBdLmNoaWxkTm9kZXNbMV0uc3R5bGUuZGlzcGxheSl7aWYoIWUud3NpZ24pdmFyIG49dGhpcy5taW51c0FycmF5O2lmKHRoaXMuX3NldFNyYyhpLHRoaXMuaWNvblVSTCtlLmltYWdlc1sxXSksdGhpcy5fdHh0aW1nKXJldHVybiB0LmlubmVySFRNTD0iWy1dIn1lbHNle2lmKCFlLndzaWduKXZhciBuPXRoaXMucGx1c0FycmF5O2lmKHRoaXMuX3NldFNyYyhpLHRoaXMuaWNvblVSTCtlLmltYWdlc1syXSksdGhpcy5fdHh0aW1nKXJldHVybiB0LmlubmVySFRNTD0iWytdIn1lbHNlIHRoaXMuX3NldFNyYyhpLHRoaXMuaWNvblVSTCtlLmltYWdlc1swXSk7dmFyIG89MjtlLnRyZWVOb2QudHJlZUxpbmVzT24/KGUucGFyZW50T2JqZWN0JiYobz10aGlzLl9nZXRDb3VudFN0YXR1cyhlLmlkLGUucGFyZW50T2JqZWN0KSksdGhpcy5fc2V0U3JjKHQsdGhpcy5pbVBhdGgrbltvXSkpOnRoaXMuX3NldFNyYyh0LHRoaXMuaW1QYXRoK25bM10pfX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX2NvcnJlY3RMaW5lPWZ1bmN0aW9uKGUpe2lmKGUuaHRtbE5vZGUpe3ZhciB0PWUucGFyZW50T2JqZWN0O2lmKHQpaWYoMCE9dGhpcy5fZ2V0TGluZVN0YXR1cyhlLmlkLHQpJiZ0aGlzLnRyZWVMaW5lc09uKWZvcih2YXIgaT0xO2k8PWUuY2hpbGRzQ291bnQmJmUuaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5jaGlsZE5vZGVzW2ldO2krKyllLmh0bWxOb2RlLmNoaWxkTm9kZXNbMF0uY2hpbGROb2Rlc1tpXS5jaGlsZE5vZGVzWzBdLnN0eWxlLmJhY2tncm91bmRJbWFnZT0idXJsKCIrdGhpcy5pbVBhdGgrdGhpcy5saW5lQXJyYXlbNV0rIikiLGUuaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5jaGlsZE5vZGVzW2ldLmNoaWxkTm9kZXNbMF0uc3R5bGUuYmFja2dyb3VuZFJlcGVhdD0icmVwZWF0LXkiO2Vsc2UgZm9yKHZhciBpPTE7aTw9ZS5jaGlsZHNDb3VudCYmZS5odG1sTm9kZS5jaGlsZE5vZGVzWzBdLmNoaWxkTm9kZXNbaV07aSsrKWUuaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5jaGlsZE5vZGVzW2ldLmNoaWxkTm9kZXNbMF0uc3R5bGUuYmFja2dyb3VuZEltYWdlPSIiLGUuaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5jaGlsZE5vZGVzW2ldLmNoaWxkTm9kZXNbMF0uc3R5bGUuYmFja2dyb3VuZFJlcGVhdD0iIn19LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLl9nZXRMaW5lU3RhdHVzPWZ1bmN0aW9uKGUsdCl7cmV0dXJuIHQuY2hpbGROb2Rlc1t0LmNoaWxkc0NvdW50LTFdLmlkPT1lPzA6MX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX0hpZGVTaG93PWZ1bmN0aW9uKGUsdCl7aWYoIXRoaXMuX2xvY2tlcnx8dGhpcy5za2lwTG9ja3x8IXRoaXMuX2xvY2tlcltlLmlkXSl7aWYodGhpcy5YTUxzb3VyY2UmJiFlLlhNTGxvYWQpe2lmKDE9PXQpcmV0dXJuO3JldHVybiBlLlhNTGxvYWQ9MSx2b2lkIHRoaXMuX2xvYWREeW5YTUwoZS5pZCl9ZS51blBhcnNlZCYmdGhpcy5yZVBhcnNlKGUpO3ZhciBpPWUuaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5jaGlsZE5vZGVzLG49aS5sZW5ndGg7aWYobj4xKXsibm9uZSI9PWlbMV0uc3R5bGUuZGlzcGxheSYmMSE9dHx8Mj09dD9ub2Rlc3R5bGU9IiI6KHRoaXMuYWxsVHJlZS5jaGlsZE5vZGVzWzBdLmJvcmRlcj0iMSIsdGhpcy5hbGxUcmVlLmNoaWxkTm9kZXNbMF0uYm9yZGVyPSIwIixub2Rlc3R5bGU9Im5vbmUiKTtmb3IodmFyIG89MTtuPm87bysrKWlbb10uc3R5bGUuZGlzcGxheT1ub2Rlc3R5bGV9dGhpcy5fY29ycmVjdFBsdXMoZSl9fSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5fZ2V0T3BlblN0YXRlPWZ1bmN0aW9uKGUpe2lmKCFlLmh0bWxOb2RlKXJldHVybiAwO3ZhciB0PWUuaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5jaGlsZE5vZGVzO3JldHVybiB0Lmxlbmd0aDw9MT8wOiJub25lIiE9dFsxXS5zdHlsZS5kaXNwbGF5PzE6LTF9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLm9uUm93Q2xpY2syPWZ1bmN0aW9uKCl7dmFyIGU9dGhpcy5wYXJlbnRPYmplY3QudHJlZU5vZDtyZXR1cm4gZS5jYWxsRXZlbnQoIm9uRGJsQ2xpY2siLFt0aGlzLnBhcmVudE9iamVjdC5pZCxlXSk/KHRoaXMucGFyZW50T2JqZWN0LmNsb3NlYmxlJiYiMCIhPXRoaXMucGFyZW50T2JqZWN0LmNsb3NlYmxlP2UuX0hpZGVTaG93KHRoaXMucGFyZW50T2JqZWN0KTplLl9IaWRlU2hvdyh0aGlzLnBhcmVudE9iamVjdCwyKSxlLmNoZWNrRXZlbnQoIm9uT3BlbkVuZCIpJiYoZS54bWxzdGF0ZT8oZS5fb2llX29uWExFLnB1c2goZS5vblhMRSksZS5vblhMRT1lLl9lcG5GSGUpOmUuY2FsbEV2ZW50KCJvbk9wZW5FbmQiLFt0aGlzLnBhcmVudE9iamVjdC5pZCxlLl9nZXRPcGVuU3RhdGUodGhpcy5wYXJlbnRPYmplY3QpXSkpLCExKTohMX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUub25Sb3dDbGljaz1mdW5jdGlvbigpe3ZhciBlPXRoaXMucGFyZW50T2JqZWN0LnRyZWVOb2Q7cmV0dXJuIGUuY2FsbEV2ZW50KCJvbk9wZW5TdGFydCIsW3RoaXMucGFyZW50T2JqZWN0LmlkLGUuX2dldE9wZW5TdGF0ZSh0aGlzLnBhcmVudE9iamVjdCldKT8odGhpcy5wYXJlbnRPYmplY3QuY2xvc2VibGUmJiIwIiE9dGhpcy5wYXJlbnRPYmplY3QuY2xvc2VibGU/ZS5fSGlkZVNob3codGhpcy5wYXJlbnRPYmplY3QpOmUuX0hpZGVTaG93KHRoaXMucGFyZW50T2JqZWN0LDIpLHZvaWQoZS5jaGVja0V2ZW50KCJvbk9wZW5FbmQiKSYmKGUueG1sc3RhdGU/KGUuX29pZV9vblhMRS5wdXNoKGUub25YTEUpLGUub25YTEU9ZS5fZXBuRkhlKTplLmNhbGxFdmVudCgib25PcGVuRW5kIixbdGhpcy5wYXJlbnRPYmplY3QuaWQsZS5fZ2V0T3BlblN0YXRlKHRoaXMucGFyZW50T2JqZWN0KV0pKSkpOjB9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLmdldFNlbGVjdGVkSXRlbUlkPWZ1bmN0aW9uKCl7Zm9yKHZhciBlPW5ldyBBcnJheSx0PTA7dDx0aGlzLl9zZWxlY3RlZC5sZW5ndGg7dCsrKWVbdF09dGhpcy5fc2VsZWN0ZWRbdF0uaWQ7cmV0dXJuIGUuam9pbih0aGlzLmRsbXRyKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX3NlbGVjdEl0ZW09ZnVuY3Rpb24oZSx0KXtpZih0aGlzLmNoZWNrRXZlbnQoIm9uU2VsZWN0IikmJih0aGlzLl9vblNTQ0ZvbGQ9dGhpcy5nZXRTZWxlY3RlZEl0ZW1JZCgpKSx0aGlzLl9hbXNlbCYmdCYmKHQuY3RybEtleXx8dC5tZXRhS2V5fHx0LnNoaWZ0S2V5KXx8dGhpcy5fdW5zZWxlY3RJdGVtcygpLGUuaV9zZWwmJnRoaXMuX2Ftc2VsJiZ0JiYodC5jdHJsS2V5fHx0Lm1ldGFLZXkpKXRoaXMuX3Vuc2VsZWN0SXRlbShlKTtlbHNlIGlmKCEoZS5pX3NlbHx8dGhpcy5fYW1zZWxTJiYwIT10aGlzLl9zZWxlY3RlZC5sZW5ndGgmJnRoaXMuX3NlbGVjdGVkWzBdLnBhcmVudE9iamVjdCE9ZS5wYXJlbnRPYmplY3QpKWlmKHRoaXMuX2Ftc2VsJiZ0JiZ0LnNoaWZ0S2V5JiYwIT10aGlzLl9zZWxlY3RlZC5sZW5ndGgmJnRoaXMuX3NlbGVjdGVkW3RoaXMuX3NlbGVjdGVkLmxlbmd0aC0xXS5wYXJlbnRPYmplY3Q9PWUucGFyZW50T2JqZWN0KXt2YXIgaT10aGlzLl9nZXRJbmRleCh0aGlzLl9zZWxlY3RlZFt0aGlzLl9zZWxlY3RlZC5sZW5ndGgtMV0pLG49dGhpcy5fZ2V0SW5kZXgoZSk7aWYoaT5uKXt2YXIgbz1pO2k9bixuPW99Zm9yKHZhciByPWk7bj49cjtyKyspZS5wYXJlbnRPYmplY3QuY2hpbGROb2Rlc1tyXS5pX3NlbHx8dGhpcy5fbWFya0l0ZW0oZS5wYXJlbnRPYmplY3QuY2hpbGROb2Rlc1tyXSl9ZWxzZSB0aGlzLl9tYXJrSXRlbShlKTtpZih0aGlzLmNoZWNrRXZlbnQoIm9uU2VsZWN0Iikpe3ZhciBsPXRoaXMuZ2V0U2VsZWN0ZWRJdGVtSWQoKTtsIT10aGlzLl9vblNTQ0ZvbGQmJnRoaXMuY2FsbEV2ZW50KCJvblNlbGVjdCIsW2xdKX19LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLl9tYXJrSXRlbT1mdW5jdGlvbihlKXtlLnNjb2xvciYmKGUuc3Bhbi5zdHlsZS5jb2xvcj1lLnNjb2xvciksZS5zcGFuLmNsYXNzTmFtZT0ic2VsZWN0ZWRUcmVlUm93IixlLnNwYW4ucGFyZW50Tm9kZS5wYXJlbnROb2RlLmNsYXNzTmFtZT0ic2VsZWN0ZWRUcmVlUm93RnVsbCIsZS5pX3NlbD0hMCx0aGlzLl9zZWxlY3RlZFt0aGlzLl9zZWxlY3RlZC5sZW5ndGhdPWV9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLmdldEluZGV4QnlJZD1mdW5jdGlvbihlKXt2YXIgdD10aGlzLl9nbG9iYWxJZFN0b3JhZ2VGaW5kKGUpO3JldHVybiB0P3RoaXMuX2dldEluZGV4KHQpOm51bGx9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLl9nZXRJbmRleD1mdW5jdGlvbihlKXtmb3IodmFyIHQ9ZS5wYXJlbnRPYmplY3QsaT0wO2k8dC5jaGlsZHNDb3VudDtpKyspaWYodC5jaGlsZE5vZGVzW2ldPT1lKXJldHVybiBpfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5fdW5zZWxlY3RJdGVtPWZ1bmN0aW9uKGUpe2lmKGUmJmUuaV9zZWwpe2Uuc3Bhbi5jbGFzc05hbWU9InN0YW5kYXJ0VHJlZVJvdyIsZS5zcGFuLnBhcmVudE5vZGUucGFyZW50Tm9kZS5jbGFzc05hbWU9IiIsZS5hY29sb3ImJihlLnNwYW4uc3R5bGUuY29sb3I9ZS5hY29sb3IpLGUuaV9zZWw9ITE7Zm9yKHZhciB0PTA7dDx0aGlzLl9zZWxlY3RlZC5sZW5ndGg7dCsrKWlmKCF0aGlzLl9zZWxlY3RlZFt0XS5pX3NlbCl7dGhpcy5fc2VsZWN0ZWQuc3BsaWNlKHQsMSk7YnJlYWt9fX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX3Vuc2VsZWN0SXRlbXM9ZnVuY3Rpb24oKXtmb3IodmFyIGU9MDtlPHRoaXMuX3NlbGVjdGVkLmxlbmd0aDtlKyspe3ZhciB0PXRoaXMuX3NlbGVjdGVkW2VdO3Quc3Bhbi5jbGFzc05hbWU9InN0YW5kYXJ0VHJlZVJvdyIsdC5zcGFuLnBhcmVudE5vZGUucGFyZW50Tm9kZS5jbGFzc05hbWU9IiIsdC5hY29sb3ImJih0LnNwYW4uc3R5bGUuY29sb3I9dC5hY29sb3IpLHQuaV9zZWw9ITF9dGhpcy5fc2VsZWN0ZWQ9bmV3IEFycmF5fSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5vblJvd1NlbGVjdD1mdW5jdGlvbihlLHQsaSl7ZT1lfHx3aW5kb3cuZXZlbnQ7dmFyIG49dGhpcy5wYXJlbnRPYmplY3Q7dCYmKG49dC5wYXJlbnRPYmplY3QpO3ZhciBvPW4udHJlZU5vZCxyPW8uZ2V0U2VsZWN0ZWRJdGVtSWQoKTtlJiZlLnNraXBVblNlbHx8by5fc2VsZWN0SXRlbShuLGUpLGl8fChuLmFjdGlvbkhhbmRsZXI/bi5hY3Rpb25IYW5kbGVyKG4uaWQscik6by5jYWxsRXZlbnQoIm9uQ2xpY2siLFtuLmlkLHJdKSl9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLl9jcmVhdGVJdGVtPWZ1bmN0aW9uKGUsdCxpKXt2YXIgbj1kb2N1bWVudC5jcmVhdGVFbGVtZW50KCJ0YWJsZSIpO24uY2VsbFNwYWNpbmc9MCxuLmNlbGxQYWRkaW5nPTAsbi5ib3JkZXI9MCx0aGlzLmhmTW9kZSYmKG4uc3R5bGUudGFibGVMYXlvdXQ9ImZpeGVkIiksbi5zdHlsZS5tYXJnaW49MCxuLnN0eWxlLnBhZGRpbmc9MDt2YXIgbz1kb2N1bWVudC5jcmVhdGVFbGVtZW50KCJ0Ym9keSIpLHI9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgidHIiKSxsPWRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoInRkIik7aWYobC5jbGFzc05hbWU9InN0YW5kYXJ0VHJlZUltYWdlIix0aGlzLl90eHRpbWcpe3ZhciBzPWRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoImRpdiIpO2wuYXBwZW5kQ2hpbGQocykscy5jbGFzc05hbWU9ImRoeF90cmVlX3RleHRTaWduIn1lbHNle3ZhciBzPXRoaXMuX2dldEltZyh0LmlkKTtzLmJvcmRlcj0iMCIsIklNRyI9PXMudGFnTmFtZSYmKHMuYWxpZ249ImFic21pZGRsZSIpLGwuYXBwZW5kQ2hpbGQocykscy5zdHlsZS5wYWRkaW5nPTAscy5zdHlsZS5tYXJnaW49MCxzLnN0eWxlLndpZHRoPXRoaXMuZGVmX2xpbmVfaW1nX3h9dmFyIGE9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgidGQiKSxkPXRoaXMuX2dldEltZyh0aGlzLmNCUk9mP3RoaXMucm9vdElkOnQuaWQpO2QuY2hlY2tlZD0wLHRoaXMuX3NldFNyYyhkLHRoaXMuaW1QYXRoK3RoaXMuY2hlY2tBcnJheVswXSksZC5zdHlsZS53aWR0aD0iMThweCIsZC5zdHlsZS5oZWlnaHQ9IjE4cHgiLGV8fChhLnN0eWxlLmRpc3BsYXk9Im5vbmUiKSxhLmFwcGVuZENoaWxkKGQpLHRoaXMuY0JST2Z8fCJJTUciIT1kLnRhZ05hbWV8fChkLmFsaWduPSJhYnNtaWRkbGUiKSxkLm9uY2xpY2s9dGhpcy5vbkNoZWNrQm94Q2xpY2ssZC50cmVlTm9kPXRoaXMsZC5wYXJlbnRPYmplY3Q9dCx3aW5kb3cuX0tIVE1McnY/YS53aWR0aD0iMTZweCI6YS53aWR0aD0iMjBweCI7dmFyIGg9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgidGQiKTtoLmNsYXNzTmFtZT0ic3RhbmRhcnRUcmVlSW1hZ2UiO3ZhciBjPXRoaXMuX2dldEltZyh0aGlzLnRpbWdlbj90LmlkOnRoaXMucm9vdElkKTtjLm9ubW91c2Vkb3duPXRoaXMuX3ByZXZlbnROc0RyYWcsYy5vbmRyYWdzdGFydD10aGlzLl9wcmV2ZW50TnNEcmFnLGMuYm9yZGVyPSIwIix0aGlzLl9haW1ncyYmKGMucGFyZW50T2JqZWN0PXQsCiJJTUciPT1jLnRhZ05hbWUmJihjLmFsaWduPSJhYnNtaWRkbGUiKSxjLm9uY2xpY2s9dGhpcy5vblJvd1NlbGVjdCksaXx8dGhpcy5fc2V0U3JjKGMsdGhpcy5pY29uVVJMK3RoaXMuaW1hZ2VBcnJheVswXSksaC5hcHBlbmRDaGlsZChjKSxjLnN0eWxlLnBhZGRpbmc9MCxjLnN0eWxlLm1hcmdpbj0wLHRoaXMudGltZ2VuPyhoLnN0eWxlLndpZHRoPWMuc3R5bGUud2lkdGg9dGhpcy5kZWZfaW1nX3gsYy5zdHlsZS5oZWlnaHQ9dGhpcy5kZWZfaW1nX3kpOihjLnN0eWxlLndpZHRoPSIwcHgiLGMuc3R5bGUuaGVpZ2h0PSIwcHgiLChfaXNPcGVyYXx8d2luZG93Ll9LSFRNTHJ2KSYmKGguc3R5bGUuZGlzcGxheT0ibm9uZSIpKTt2YXIgdT1kb2N1bWVudC5jcmVhdGVFbGVtZW50KCJ0ZCIpO3JldHVybiB1LmNsYXNzTmFtZT0iZGh4VGV4dENlbGwgc3RhbmRhcnRUcmVlUm93Iix0LnNwYW49ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic3BhbiIpLHQuc3Bhbi5jbGFzc05hbWU9InN0YW5kYXJ0VHJlZVJvdyIsdGhpcy5tbGl0ZW1zPyh0LnNwYW4uc3R5bGUud2lkdGg9dGhpcy5tbGl0ZW1zLHQuc3Bhbi5zdHlsZS5kaXNwbGF5PSJibG9jayIpOnUubm9XcmFwPSEwLGRoeDQuaXNJRTg/dS5zdHlsZS53aWR0aD0iOTk5OTlweCI6d2luZG93Ll9LSFRNTHJ2fHwodS5zdHlsZS53aWR0aD0iMTAwJSIpLHQuc3Bhbi5pbm5lckhUTUw9dC5sYWJlbCx1LmFwcGVuZENoaWxkKHQuc3BhbiksdS5wYXJlbnRPYmplY3Q9dCxsLnBhcmVudE9iamVjdD10LHUub25jbGljaz10aGlzLm9uUm93U2VsZWN0LGwub25jbGljaz10aGlzLm9uUm93Q2xpY2ssdS5vbmRibGNsaWNrPXRoaXMub25Sb3dDbGljazIsdGhpcy5ldHRpcCYmKHIudGl0bGU9dC5sYWJlbCksdGhpcy5kcmFnQW5kRHJvcE9mZiYmKHRoaXMuX2FpbWdzJiYodGhpcy5kcmFnZ2VyLmFkZERyYWdnYWJsZUl0ZW0oaCx0aGlzKSxoLnBhcmVudE9iamVjdD10KSx0aGlzLmRyYWdnZXIuYWRkRHJhZ2dhYmxlSXRlbSh1LHRoaXMpKSx0LnNwYW4uc3R5bGUucGFkZGluZ0xlZnQ9IjVweCIsdC5zcGFuLnN0eWxlLnBhZGRpbmdSaWdodD0iNXB4Iix1LnN0eWxlLnZlcnRpY2FsQWxpZ249IiIsdS5zdHlsZS5mb250U2l6ZT0iMTBwdCIsdS5zdHlsZS5jdXJzb3I9dGhpcy5zdHlsZV9wb2ludGVyLHIuYXBwZW5kQ2hpbGQobCksci5hcHBlbmRDaGlsZChhKSxyLmFwcGVuZENoaWxkKGgpLHIuYXBwZW5kQ2hpbGQodSksby5hcHBlbmRDaGlsZChyKSxuLmFwcGVuZENoaWxkKG8pLCh0aGlzLmVobHR8fHRoaXMuY2hlY2tFdmVudCgib25Nb3VzZUluIil8fHRoaXMuY2hlY2tFdmVudCgib25Nb3VzZU91dCIpKSYmKHIub25tb3VzZW1vdmU9dGhpcy5faXRlbU1vdXNlSW4scltfaXNJRT8ib25tb3VzZWxlYXZlIjoib25tb3VzZW91dCJdPXRoaXMuX2l0ZW1Nb3VzZU91dCksbn0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuc2V0T25SaWdodENsaWNrSGFuZGxlcj1mdW5jdGlvbihlKXt0aGlzLmF0dGFjaEV2ZW50KCJvblJpZ2h0Q2xpY2siLGUpfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5zZXRPbkNsaWNrSGFuZGxlcj1mdW5jdGlvbihlKXt0aGlzLmF0dGFjaEV2ZW50KCJvbkNsaWNrIixlKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuc2V0T25TZWxlY3RTdGF0ZUNoYW5nZT1mdW5jdGlvbihlKXt0aGlzLmF0dGFjaEV2ZW50KCJvblNlbGVjdCIsZSl9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLnNldFhNTEF1dG9Mb2FkaW5nPWZ1bmN0aW9uKGUpe3RoaXMuWE1Mc291cmNlPWV9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLnNldE9uQ2hlY2tIYW5kbGVyPWZ1bmN0aW9uKGUpe3RoaXMuYXR0YWNoRXZlbnQoIm9uQ2hlY2siLGUpfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5zZXRPbk9wZW5IYW5kbGVyPWZ1bmN0aW9uKGUpe3RoaXMuYXR0YWNoRXZlbnQoIm9uT3BlblN0YXJ0IixlKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuc2V0T25PcGVuU3RhcnRIYW5kbGVyPWZ1bmN0aW9uKGUpe3RoaXMuYXR0YWNoRXZlbnQoIm9uT3BlblN0YXJ0IixlKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuc2V0T25PcGVuRW5kSGFuZGxlcj1mdW5jdGlvbihlKXt0aGlzLmF0dGFjaEV2ZW50KCJvbk9wZW5FbmQiLGUpfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5zZXRPbkRibENsaWNrSGFuZGxlcj1mdW5jdGlvbihlKXt0aGlzLmF0dGFjaEV2ZW50KCJvbkRibENsaWNrIixlKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUub3BlbkFsbEl0ZW1zPWZ1bmN0aW9uKGUpe3ZhciB0PXRoaXMuX2dsb2JhbElkU3RvcmFnZUZpbmQoZSk7cmV0dXJuIHQ/dm9pZCB0aGlzLl94b3BlbkFsbCh0KTowfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5nZXRPcGVuU3RhdGU9ZnVuY3Rpb24oZSl7dmFyIHQ9dGhpcy5fZ2xvYmFsSWRTdG9yYWdlRmluZChlKTtyZXR1cm4gdD90aGlzLl9nZXRPcGVuU3RhdGUodCk6IiJ9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLmNsb3NlQWxsSXRlbXM9ZnVuY3Rpb24oZSl7ZT09PXdpbmRvdy51bmRlZmluZWQmJihlPXRoaXMucm9vdElkKTt2YXIgdD10aGlzLl9nbG9iYWxJZFN0b3JhZ2VGaW5kKGUpO3JldHVybiB0Pyh0aGlzLl94Y2xvc2VBbGwodCksdGhpcy5hbGxUcmVlLmNoaWxkTm9kZXNbMF0uYm9yZGVyPSIxIix2b2lkKHRoaXMuYWxsVHJlZS5jaGlsZE5vZGVzWzBdLmJvcmRlcj0iMCIpKTowfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5zZXRVc2VyRGF0YT1mdW5jdGlvbihlLHQsaSl7dmFyIG49dGhpcy5fZ2xvYmFsSWRTdG9yYWdlRmluZChlLDAsITApO24mJigiaGludCI9PXQmJihuLmh0bWxOb2RlLmNoaWxkTm9kZXNbMF0uY2hpbGROb2Rlc1swXS50aXRsZT1pKSwidW5kZWZpbmVkIj09dHlwZW9mIG4udXNlckRhdGFbInRfIit0XSYmKG4uX3VzZXJkYXRhbGlzdD9uLl91c2VyZGF0YWxpc3QrPSIsIit0Om4uX3VzZXJkYXRhbGlzdD10KSxuLnVzZXJEYXRhWyJ0XyIrdF09aSl9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLmdldFVzZXJEYXRhPWZ1bmN0aW9uKGUsdCl7dmFyIGk9dGhpcy5fZ2xvYmFsSWRTdG9yYWdlRmluZChlLDAsITApO2lmKGkpcmV0dXJuIGkudXNlckRhdGFbInRfIit0XX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuZ2V0SXRlbUNvbG9yPWZ1bmN0aW9uKGUpe3ZhciB0PXRoaXMuX2dsb2JhbElkU3RvcmFnZUZpbmQoZSk7aWYoIXQpcmV0dXJuIDA7dmFyIGk9bmV3IE9iamVjdDtyZXR1cm4gdC5hY29sb3ImJihpLmFjb2xvcj10LmFjb2xvciksdC5zY29sb3ImJihpLnNjb2xvcj10LnNjb2xvciksaX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuc2V0SXRlbUNvbG9yPWZ1bmN0aW9uKGUsdCxpKXtpZihlJiZlLnNwYW4pdmFyIG49ZTtlbHNlIHZhciBuPXRoaXMuX2dsb2JhbElkU3RvcmFnZUZpbmQoZSk7cmV0dXJuIG4/KG4uaV9zZWw/KGl8fHQpJiYobi5zcGFuLnN0eWxlLmNvbG9yPWl8fHQpOnQmJihuLnNwYW4uc3R5bGUuY29sb3I9dCksaSYmKG4uc2NvbG9yPWkpLHQmJihuLmFjb2xvcj10KSx2b2lkIDApOjB9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLnNldE9uTW91c2VJbkhhbmRsZXI9ZnVuY3Rpb24oZSl7dGhpcy5laGx0PSEwLHRoaXMuYXR0YWNoRXZlbnQoIm9uTW91c2VJbiIsZSl9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLnNldE9uTW91c2VPdXRIYW5kbGVyPWZ1bmN0aW9uKGUpe3RoaXMuZWhsdD0hMCx0aGlzLmF0dGFjaEV2ZW50KCJvbk1vdXNlT3V0IixlKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuZW5hYmxlVHJlZUxpbmVzPWZ1bmN0aW9uKGUpe3RoaXMudHJlZUxpbmVzT249ZGh4NC5zMmIoZSl9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLm9wZW5JdGVtPWZ1bmN0aW9uKGUpe3RoaXMuc2tpcExvY2s9ITA7dmFyIHQ9dGhpcy5fZ2xvYmFsSWRTdG9yYWdlRmluZChlKTtyZXR1cm4gdD90aGlzLl9vcGVuSXRlbSh0KTowfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5fb3Blbkl0ZW09ZnVuY3Rpb24oZSl7dmFyIHQ9dGhpcy5fZ2V0T3BlblN0YXRlKGUpO2lmKDA+dHx8dGhpcy5YTUxzb3VyY2UmJiFlLlhNTGxvYWQpe2lmKCF0aGlzLmNhbGxFdmVudCgib25PcGVuU3RhcnQiLFtlLmlkLHRdKSlyZXR1cm4gMDt0aGlzLl9IaWRlU2hvdyhlLDIpLHRoaXMuY2hlY2tFdmVudCgib25PcGVuRW5kIikmJih0aGlzLm9uWExFPT10aGlzLl9lcG5GSGUmJnRoaXMuX2VwbkZIZSh0aGlzLGUuaWQsITApLHRoaXMueG1sc3RhdGUmJnRoaXMuWE1Mc291cmNlPyh0aGlzLl9vaWVfb25YTEUucHVzaCh0aGlzLm9uWExFKSx0aGlzLm9uWExFPXRoaXMuX2VwbkZIZSk6dGhpcy5jYWxsRXZlbnQoIm9uT3BlbkVuZCIsW2UuaWQsdGhpcy5fZ2V0T3BlblN0YXRlKGUpXSkpfWVsc2UgdGhpcy5fc3JuZCYmdGhpcy5fSGlkZVNob3coZSwyKTtlLnBhcmVudE9iamVjdCYmIXRoaXMuX3NraXBfb3Blbl9wYXJlbnQmJnRoaXMuX29wZW5JdGVtKGUucGFyZW50T2JqZWN0KX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX2dldEFsbEZhdEl0ZW1zPWZ1bmN0aW9uKGUpe2Zvcih2YXIgdD0iIixpPTA7aTxlLmNoaWxkc0NvdW50O2krKylpZihlLmNoaWxkTm9kZXNbaV0udW5QYXJzZWR8fGUuY2hpbGROb2Rlc1tpXS5jaGlsZHNDb3VudD4wKXtpZih0P3QrPXRoaXMuZGxtdHIrZS5jaGlsZE5vZGVzW2ldLmlkOnQ9IiIrZS5jaGlsZE5vZGVzW2ldLmlkLGUuY2hpbGROb2Rlc1tpXS51blBhcnNlZCl2YXIgbj10aGlzLl9nZXRBbGxGYXRJdGVtc1hNTChlLmNoaWxkTm9kZXNbaV0udW5QYXJzZWQsMSk7ZWxzZSB2YXIgbj10aGlzLl9nZXRBbGxGYXRJdGVtcyhlLmNoaWxkTm9kZXNbaV0pO24mJih0Kz10aGlzLmRsbXRyK24pfXJldHVybiB0fSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5zZWxlY3RJdGVtPWZ1bmN0aW9uKGUsdCxpKXt0PWRoeDQuczJiKHQpO3ZhciBuPXRoaXMuX2dsb2JhbElkU3RvcmFnZUZpbmQoZSk7aWYoIW58fCFuLnBhcmVudE9iamVjdClyZXR1cm4gMDt0aGlzLlhNTGxvYWRpbmdXYXJuaW5nP24ucGFyZW50T2JqZWN0Lm9wZW5NZT0xOnRoaXMuX29wZW5JdGVtKG4ucGFyZW50T2JqZWN0KTt2YXIgbz1udWxsO2kmJihvPW5ldyBPYmplY3Qsby5jdHJsS2V5PSEwLG4uaV9zZWwmJihvLnNraXBVblNlbD0hMCkpLHQ/dGhpcy5vblJvd1NlbGVjdChvLG4uaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5jaGlsZE5vZGVzWzBdLmNoaWxkTm9kZXNbM10sITEpOnRoaXMub25Sb3dTZWxlY3QobyxuLmh0bWxOb2RlLmNoaWxkTm9kZXNbMF0uY2hpbGROb2Rlc1swXS5jaGlsZE5vZGVzWzNdLCEwKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX2NvbXByZXNzQ2hpbGRMaXN0PWZ1bmN0aW9uKGUsdCl7ZS0tO2Zvcih2YXIgaT0wO2U+aTtpKyspMD09dFtpXSYmKHRbaV09dFtpKzFdLHRbaSsxXT0wKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX2RlbGV0ZU5vZGU9ZnVuY3Rpb24oZSx0LGkpe2lmKCF0fHwhdC5wYXJlbnRPYmplY3QpcmV0dXJuIDA7dmFyIG49MCxvPTA7dC50ci5uZXh0U2libGluZyYmKG49dC50ci5uZXh0U2libGluZy5ub2RlbSksdC50ci5wcmV2aW91c1NpYmxpbmcmJihvPXQudHIucHJldmlvdXNTaWJsaW5nLm5vZGVtKTtmb3IodmFyIHI9dC5wYXJlbnRPYmplY3QsbD1yLmNoaWxkc0NvdW50LHM9ci5jaGlsZE5vZGVzLGE9MDtsPmE7YSsrKWlmKHNbYV0uaWQ9PWUpe2l8fHIuaHRtbE5vZGUuY2hpbGROb2Rlc1swXS5yZW1vdmVDaGlsZChzW2FdLnRyKSxzW2FdPTA7YnJlYWt9dGhpcy5fY29tcHJlc3NDaGlsZExpc3QobCxzKSxpfHxyLmNoaWxkc0NvdW50LS0sbiYmKHRoaXMuX2NvcnJlY3RQbHVzKG4pLHRoaXMuX2NvcnJlY3RMaW5lKG4pKSxvJiYodGhpcy5fY29ycmVjdFBsdXMobyksdGhpcy5fY29ycmVjdExpbmUobykpLHRoaXMudHNjaGVjayYmdGhpcy5fY29ycmVjdENoZWNrU3RhdGVzKHIpLGl8fHRoaXMuX2dsb2JhbElkU3RvcmFnZVJlY1N1Yih0KX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuZGVsZXRlQ2hpbGRJdGVtcz1mdW5jdGlvbihlKXt2YXIgdD10aGlzLl9nbG9iYWxJZFN0b3JhZ2VGaW5kKGUpO2lmKHQpZm9yKHZhciBpPXQuY2hpbGRzQ291bnQsbj0wO2k+bjtuKyspdGhpcy5fZGVsZXRlTm9kZSh0LmNoaWxkTm9kZXNbMF0uaWQsdC5jaGlsZE5vZGVzWzBdKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX2dsb2JhbElkU3RvcmFnZVJlY1N1Yj1mdW5jdGlvbihlKXtmb3IodmFyIHQ9MDt0PGUuY2hpbGRzQ291bnQ7dCsrKXRoaXMuX2dsb2JhbElkU3RvcmFnZVJlY1N1YihlLmNoaWxkTm9kZXNbdF0pLHRoaXMuX2dsb2JhbElkU3RvcmFnZVN1YihlLmNoaWxkTm9kZXNbdF0uaWQpO3RoaXMuX2dsb2JhbElkU3RvcmFnZVN1YihlLmlkKTt2YXIgaT1lO2kuc3Bhbj1udWxsLGkudHIubm9kZW09bnVsbCxpLnRyPW51bGwsaS5odG1sTm9kZT1udWxsfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5fYXV0b1Njcm9sbD1mdW5jdGlvbihlLHQsaSl7dGhpcy5hdXRvU2Nyb2xsJiYoZSYmKHQ9ZGh4NC5hYnNUb3AoZSksaT1kaHg0LmFic1RvcCh0aGlzLmFsbFRyZWUpLXRoaXMuYWxsVHJlZS5zY3JvbGxUb3ApLHQtaS1wYXJzZUludCh0aGlzLmFsbFRyZWUuc2Nyb2xsVG9wKT5wYXJzZUludCh0aGlzLmFsbFRyZWUub2Zmc2V0SGVpZ2h0KS01MCYmKHRoaXMuYWxsVHJlZS5zY3JvbGxUb3A9cGFyc2VJbnQodGhpcy5hbGxUcmVlLnNjcm9sbFRvcCkrMjApLHQtaTxwYXJzZUludCh0aGlzLmFsbFRyZWUuc2Nyb2xsVG9wKSszMCYmKHRoaXMuYWxsVHJlZS5zY3JvbGxUb3A9cGFyc2VJbnQodGhpcy5hbGxUcmVlLnNjcm9sbFRvcCktMjApKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuZW5hYmxlVGV4dFNpZ25zPWZ1bmN0aW9uKGUpe3RoaXMuX3R4dGltZz1kaHg0LnMyYihlKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUucHJldmVudElFQ2FjaGluZz1mdW5jdGlvbihlKXtkaHg0LmFqYXguY2FjaGU9IWV9LGRodG1sWFRyZWVPYmplY3QucHJvdG90eXBlLnByZXZlbnRJRUNhc2hpbmc9ZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUucHJldmVudElFQ2FjaGluZyxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5zZXRJY29uU2l6ZT1mdW5jdGlvbihlLHQsaSl7aWYoaSl7aWYoaSYmaS5zcGFuKXZhciBuPWk7ZWxzZSB2YXIgbj10aGlzLl9nbG9iYWxJZFN0b3JhZ2VGaW5kKGkpO2lmKCFuKXJldHVybiAwO3ZhciBvPW4uc3Bhbi5wYXJlbnROb2RlLnByZXZpb3VzU2libGluZy5jaGlsZE5vZGVzWzBdO2UmJihvLnN0eWxlLndpZHRoPWUrInB4Iix3aW5kb3cuX0tIVE1McnYmJihvLnBhcmVudE5vZGUuc3R5bGUud2lkdGg9ZSsicHgiKSksdCYmKG8uc3R5bGUuaGVpZ2h0PXQrInB4Iix3aW5kb3cuX0tIVE1McnYmJihvLnBhcmVudE5vZGUuc3R5bGUuaGVpZ2h0PXQrInB4IikpfWVsc2UgdGhpcy5kZWZfaW1nX3g9ZSsicHgiLHRoaXMuZGVmX2ltZ195PXQrInB4In0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuZW5hYmxlU2luZ2xlUmFkaW9Nb2RlPWZ1bmN0aW9uKGUpe3RoaXMuX2ZyYnRycz1kaHg0LnMyYihlKX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUub3Blbk9uSXRlbUFkZGVkPWZ1bmN0aW9uKGUpe3RoaXMuX2hBZEk9IWRoeDQuczJiKGUpfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5vcGVuT25JdGVtQWRkaW5nPWZ1bmN0aW9uKGUpe3RoaXMuX2hBZEk9IWRoeDQuczJiKGUpfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5nZXRBbGxJdGVtc1dpdGhLaWRzPWZ1bmN0aW9uKCl7cmV0dXJuIHRoaXMuX2dldEFsbEZhdEl0ZW1zKHRoaXMuaHRtbE5vZGUpfSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5zZXRTa2luPWZ1bmN0aW9uKGUpe3ZhciB0PXRoaXMucGFyZW50T2JqZWN0LmNsYXNzTmFtZS5yZXBsYWNlKC9kaHh0cmVlX1teIF0qL2dpLCIiKTt0aGlzLnBhcmVudE9iamVjdC5jbGFzc05hbWU9dCsiIGRoeHRyZWVfIitlLCJkaHhfdGVycmFjZSIhPWUmJiJkaHhfd2ViIiE9ZSYmIm1hdGVyaWFsIiE9ZXx8dGhpcy5lbmFibGVUcmVlTGluZXMoITEpLCJtYXRlcmlhbCI9PWUmJnRoaXMuc2V0SWNvblNpemUoIjI1IiwiMjUiKX0sanNvblBvaW50ZXIucHJvdG90eXBlPXt0ZXh0OmZ1bmN0aW9uKCl7dmFyIGU9ZnVuY3Rpb24oZSl7Zm9yKHZhciBpPVtdLG49MDtuPGUubGVuZ3RoO24rKylpLnB1c2goInsiK3QoZVtuXSkrIn0iKTtyZXR1cm4gaS5qb2luKCIsIil9LHQ9ZnVuY3Rpb24oaSl7dmFyIG49W107Zm9yKHZhciBvIGluIGkpIm9iamVjdCI9PXR5cGVvZiBpW29dP28ubGVuZ3RoP24ucHVzaCgnIicrbysnIjpbJytlKGlbb10pKyJdIik6bi5wdXNoKCciJytvKyciOnsnK3QoaVtvXSkrIn0iKTpuLnB1c2goJyInK28rJyI6IicraVtvXSsnIicpO3JldHVybiBuLmpvaW4oIiwiKX07cmV0dXJuInsiK3QodGhpcy5kKSsifSJ9LGdldDpmdW5jdGlvbihlKXtyZXR1cm4gdGhpcy5kW2VdfSxleGlzdHM6ZnVuY3Rpb24oKXtyZXR1cm4hIXRoaXMuZH0sY29udGVudDpmdW5jdGlvbigpe3JldHVybiB0aGlzLmQuY29udGVudH0sZWFjaDpmdW5jdGlvbihlLHQsaSl7dmFyIG49dGhpcy5kW2VdLG89bmV3IGpzb25Qb2ludGVyO2lmKG4pZm9yKHZhciByPTA7cjxuLmxlbmd0aDtyKyspby5kPW5bcl0sdC5hcHBseShpLFtvLHJdKX0sZ2V0X2FsbDpmdW5jdGlvbigpe3JldHVybiB0aGlzLmR9LHN1YjpmdW5jdGlvbihlKXtyZXR1cm4gbmV3IGpzb25Qb2ludGVyKHRoaXMuZFtlXSx0aGlzLmQpfSxzdWJfZXhpc3RzOmZ1bmN0aW9uKGUpe3JldHVybiEhdGhpcy5kW2VdfSxlYWNoX3g6ZnVuY3Rpb24oZSx0LGksbixvKXt2YXIgcj10aGlzLmRbZV0sbD1uZXcganNvblBvaW50ZXIoMCx0aGlzLmQpO2lmKHIpZm9yKG89b3x8MDtvPHIubGVuZ3RoO28rKylpZihyW29dW3RdJiYobC5kPXJbb10sLTE9PWkuYXBwbHkobixbbCxvXSkpKXJldHVybn0sdXA6ZnVuY3Rpb24oZSl7cmV0dXJuIG5ldyBqc29uUG9pbnRlcih0aGlzLmRwLHRoaXMuZCl9LHNldDpmdW5jdGlvbihlLHQpe3RoaXMuZFtlXT10fSxjbG9uZTpmdW5jdGlvbihlKXtyZXR1cm4gbmV3IGpzb25Qb2ludGVyKHRoaXMuZCx0aGlzLmRwKX0sdGhyb3VnaDpmdW5jdGlvbihlLHQsaSxuLG8pe3ZhciByPXRoaXMuZFtlXTtpZihyLmxlbmd0aClmb3IodmFyIGw9MDtsPHIubGVuZ3RoO2wrKyl7aWYobnVsbCE9cltsXVt0XSYmIiIhPXJbbF1bdF0mJighaXx8cltsXVt0XT09aSkpe3ZhciBzPW5ldyBqc29uUG9pbnRlcihyW2xdLHRoaXMuZCk7bi5hcHBseShvLFtzLGxdKX12YXIgYT10aGlzLmQ7dGhpcy5kPXJbbF0sdGhpcy5zdWJfZXhpc3RzKGUpJiZ0aGlzLnRocm91Z2goZSx0LGksbixvKSx0aGlzLmQ9YX19fSxkaHRtbFhUcmVlT2JqZWN0LnByb3RvdHlwZS5sb2FkSlNPTk9iamVjdD1mdW5jdGlvbihlLHQpe3JldHVybiB3aW5kb3cuY29uc29sZSYmd2luZG93LmNvbnNvbGUuaW5mbyYmd2luZG93LmNvbnNvbGUuaW5mbygibG9hZEpTT05PYmplY3Qgd2FzIGRlcHJlY2F0ZWQiLCJodHRwOi8vZG9jcy5kaHRtbHguY29tL21pZ3JhdGlvbl9faW5kZXguaHRtbCNtaWdyYXRpb25mcm9tNDN0bzQ0IiksdGhpcy5fbG9hZEpTT05PYmplY3QoZSx0KX0sZGh0bWxYVHJlZU9iamVjdC5wcm90b3R5cGUuX2xvYWRKU09OT2JqZWN0PWZ1bmN0aW9uKGUsdCl7dGhpcy5wYXJzQ291bnR8fHRoaXMuY2FsbEV2ZW50KCJvblhMUyIsW3RoaXMsbnVsbF0pLHRoaXMueG1sc3RhdGU9MTt2YXIgaT1uZXcganNvblBvaW50ZXIoZSk7dGhpcy5fcGFyc2UoaSksdGhpcy5fcD1pLHQmJnQoKX0sd2luZG93LmFkZEV2ZW50TGlzdGVuZXI/d2luZG93LmFkZEV2ZW50TGlzdGVuZXIoImxvYWQiLGRoeF9pbml0X3RyZWVzLCExKTp3aW5kb3cuYXR0YWNoRXZlbnQmJndpbmRvdy5hdHRhY2hFdmVudCgib25sb2FkIixkaHhfaW5pdF90cmVlcyk7dmFyIHN0eWxlPWRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoInN0eWxlIik7c3R5bGUuaW5uZXJIVE1MPSdAa2V5ZnJhbWVzIGRoeF9sb2FkZXJfcm90YXRlezEwMCV7dHJhbnNmb3JtOnJvdGF0ZSgzNjBkZWcpO319QGtleWZyYW1lcyBkaHhfbG9hZGVyX2Rhc2h7MCV7c3Ryb2tlLWRhc2hhcnJheToxLDIwMDtzdHJva2UtZGFzaG9mZnNldDowO301MCV7c3Ryb2tlLWRhc2hhcnJheTo4OSwyMDA7c3Ryb2tlLWRhc2hvZmZzZXQ6LTM1cHg7fTEwMCV7c3Ryb2tlLWRhc2hhcnJheTo4OSwyMDA7c3Ryb2tlLWRhc2hvZmZzZXQ6LTEyNHB4O319LmRodG1seE1lbnVfbWF0ZXJpYWxfTWlkZGxle3Bvc2l0aW9uOnJlbGF0aXZlO2hlaWdodDoyOHB4O2xpbmUtaGVpZ2h0OjI4cHg7YmFja2dyb3VuZC1jb2xvcjojZjVmNWY1O292ZXJmbG93OmhpZGRlbjtib3JkZXI6bm9uZTtmb250LXNpemU6MTRweDtmb250LWZhbWlseTpSb2JvdG8sQXJpYWwsSGVsdmV0aWNhO2NvbG9yOiM0MDQwNDA7LXdlYmtpdC11c2VyLXNlbGVjdDpub25lOy1raHRtbC11c2VyLXNlbGVjdDpub25lOy1tb3otdXNlci1zZWxlY3Q6bm9uZTstbXMtdXNlci1zZWxlY3Q6bm9uZTstby11c2VyLXNlbGVjdDpub25lO3VzZXItc2VsZWN0Om5vbmU7fS5kaHRtbHhNZW51X21hdGVyaWFsX01pZGRsZSBkaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9Ub3BMZXZlbF9JdGVtX05vcm1hbCwuZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUgZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfVG9wTGV2ZWxfSXRlbV9EaXNhYmxlZCwuZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUgZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfVG9wTGV2ZWxfSXRlbV9TZWxlY3RlZHtwb3NpdGlvbjpyZWxhdGl2ZTtmbG9hdDpsZWZ0O2ZvbnQ6aW5oZXJpdDtoZWlnaHQ6MjhweDtsaW5lLWhlaWdodDoyOHB4O21hcmdpbjowO3BhZGRpbmc6MCA4cHg7Y3Vyc29yOmRlZmF1bHQ7d2hpdGUtc3BhY2U6bm93cmFwOy13ZWJraXQtdXNlci1zZWxlY3Q6bm9uZTsta2h0bWwtdXNlci1zZWxlY3Q6bm9uZTstbW96LXVzZXItc2VsZWN0Om5vbmU7LW1zLXVzZXItc2VsZWN0Om5vbmU7LW8tdXNlci1zZWxlY3Q6bm9uZTt1c2VyLXNlbGVjdDpub25lO30uZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUgZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfVG9wTGV2ZWxfSXRlbV9Ob3JtYWwgZGl2LnRvcF9sZXZlbF90ZXh0LC5kaHRtbHhNZW51X21hdGVyaWFsX01pZGRsZSBkaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9Ub3BMZXZlbF9JdGVtX0Rpc2FibGVkIGRpdi50b3BfbGV2ZWxfdGV4dCwuZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUgZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfVG9wTGV2ZWxfSXRlbV9TZWxlY3RlZCBkaXYudG9wX2xldmVsX3RleHR7ZmxvYXQ6bGVmdDttYXJnaW46MCAzcHg7fS5kaHRtbHhNZW51X21hdGVyaWFsX01pZGRsZSBkaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9Ub3BMZXZlbF9JdGVtX05vcm1hbCBpLC5kaHRtbHhNZW51X21hdGVyaWFsX01pZGRsZSBkaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9Ub3BMZXZlbF9JdGVtX0Rpc2FibGVkIGksLmRodG1seE1lbnVfbWF0ZXJpYWxfTWlkZGxlIGRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1RvcExldmVsX0l0ZW1fU2VsZWN0ZWQgaXtoZWlnaHQ6aW5oZXJpdDtsaW5lLWhlaWdodDppbmhlcml0O2Zsb2F0OmxlZnQ7Y29sb3I6aW5oZXJpdDttYXJnaW46MCA0cHg7Zm9udC1zaXplOjEuMmVtO30uZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUgZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfVG9wTGV2ZWxfSXRlbV9EaXNhYmxlZHtjb2xvcjojYTZhNmE2O30uZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUgZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfVG9wTGV2ZWxfSXRlbV9TZWxlY3RlZHtiYWNrZ3JvdW5kLWNvbG9yOiNlYmViZWI7fS5kaHRtbHhNZW51X21hdGVyaWFsX01pZGRsZSBpbWcuZGh0bWx4TWVudV9Ub3BMZXZlbF9JdGVtX0ljb257ZmxvYXQ6bGVmdDttYXJnaW46NXB4IDNweCAwIDNweDt3aWR0aDoxOHB4O2hlaWdodDoxOHB4O2N1cnNvcjpkZWZhdWx0O30uZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUgZGl2LnRvcF9zZXB7cG9zaXRpb246cmVsYXRpdmU7ZmxvYXQ6bGVmdDtoZWlnaHQ6MjJweDt3aWR0aDowO2JvcmRlci1sZWZ0OjFweCBzb2xpZCAjZGZkZmRmO21hcmdpbjozcHggOHB4IDAgOHB4O2ZvbnQtc2l6ZToxcHg7b3ZlcmZsb3c6aGlkZGVuO2N1cnNvcjpkZWZhdWx0Oy13ZWJraXQtdXNlci1zZWxlY3Q6bm9uZTsta2h0bWwtdXNlci1zZWxlY3Q6bm9uZTstbW96LXVzZXItc2VsZWN0Om5vbmU7LW1zLXVzZXItc2VsZWN0Om5vbmU7LW8tdXNlci1zZWxlY3Q6bm9uZTt1c2VyLXNlbGVjdDpub25lO30uZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUgZGl2LmRodG1seE1lbnVfVG9wTGV2ZWxfVGV4dF9yaWdodCwuZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUgZGl2LmRodG1seE1lbnVfVG9wTGV2ZWxfVGV4dF9sZWZ0e3Bvc2l0aW9uOmFic29sdXRlO3RvcDowO2hlaWdodDoyOHB4O2xpbmUtaGVpZ2h0OjI4cHg7Y3Vyc29yOmRlZmF1bHQ7Zm9udC1zaXplOjE0cHg7Zm9udC1mYW1pbHk6Um9ib3RvLEFyaWFsLEhlbHZldGljYTtjb2xvcjojNDA0MDQwOy13ZWJraXQtdXNlci1zZWxlY3Q6bm9uZTsta2h0bWwtdXNlci1zZWxlY3Q6bm9uZTstbW96LXVzZXItc2VsZWN0Om5vbmU7LW1zLXVzZXItc2VsZWN0Om5vbmU7LW8tdXNlci1zZWxlY3Q6bm9uZTt1c2VyLXNlbGVjdDpub25lO30uZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUgZGl2LmRodG1seE1lbnVfVG9wTGV2ZWxfVGV4dF9yaWdodHtyaWdodDo2cHg7fS5kaHRtbHhNZW51X21hdGVyaWFsX01pZGRsZSBkaXYuZGh0bWx4TWVudV9Ub3BMZXZlbF9UZXh0X2xlZnR7bGVmdDo2cHg7fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29ue3Bvc2l0aW9uOmFic29sdXRlO3BhZGRpbmc6NXB4IDA7YmFja2dyb3VuZC1jb2xvcjojZmFmYWZhO292ZXJmbG93OmhpZGRlbjtjdXJzb3I6ZGVmYXVsdDtsaW5lLWhlaWdodDpub3JtYWw7b3ZlcmZsb3cteTphdXRvOy13ZWJraXQtb3ZlcmZsb3ctc2Nyb2xsaW5nOnRvdWNoOy13ZWJraXQtdGFwLWhpZ2hsaWdodC1jb2xvcjpyZ2JhKDAsMCwwLDApO2JveC1zaGFkb3c6MCAxcHggM3B4IHJnYmEoMCwwLDAsMC4xMiksMCAxcHggMnB4IHJnYmEoMCwwLDAsMC4yNCk7LXdlYmtpdC11c2VyLXNlbGVjdDpub25lOy1raHRtbC11c2VyLXNlbGVjdDpub25lOy1tb3otdXNlci1zZWxlY3Q6bm9uZTstbXMtdXNlci1zZWxlY3Q6bm9uZTstby11c2VyLXNlbGVjdDpub25lO3VzZXItc2VsZWN0Om5vbmU7fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29uIHRke3BhZGRpbmc6MDttYXJnaW46MDtsaW5lLWhlaWdodDpub3JtYWw7d2hpdGUtc3BhY2U6bm93cmFwO2ZvbnQtc2l6ZToxNHB4O2ZvbnQtZmFtaWx5OlJvYm90byxBcmlhbCxIZWx2ZXRpY2E7Y29sb3I6IzQwNDA0MDt9ZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gdGQuc3ViX2l0ZW1faWNvbnt3aWR0aDoxOHB4O3RleHQtYWxpZ246Y2VudGVyO31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ZC5zdWJfaXRlbV9pY29uIGltZy5zdWJfaWNvbnttYXJnaW46NHB4IDZweCAwIDZweDt3aWR0aDoxOHB4O2hlaWdodDoxOHB4O31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ZC5zdWJfaXRlbV9pY29uIGl7d2lkdGg6MThweDtoZWlnaHQ6MzBweDtsaW5lLWhlaWdodDoyOXB4O21hcmdpbjowIDZweDtmb250LXNpemU6MS4yZW07dGV4dC1hbGlnbjpjZW50ZXI7Y29sb3I6aW5oZXJpdDt9ZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gdGQuc3ViX2l0ZW1faWNvbiBkaXYuc3ViX2ljb257bWFyZ2luOjAgNnB4O3dpZHRoOjE4cHg7aGVpZ2h0OjMwcHg7bGluZS1oZWlnaHQ6MzBweDtiYWNrZ3JvdW5kLXBvc2l0aW9uOjAgNXB4O2JhY2tncm91bmQtcmVwZWF0Om5vLXJlcGVhdDtiYWNrZ3JvdW5kLWltYWdlOnVybCgiaW1ncy9kaHhtZW51X21hdGVyaWFsL2RoeG1lbnVfY2hyZC5wbmciKTt9ZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gdGQuc3ViX2l0ZW1faWNvbiBkaXYuc3ViX2ljb24uY2hieF8we2JhY2tncm91bmQtcG9zaXRpb246MCA1cHg7fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29uIHRkLnN1Yl9pdGVtX2ljb24gZGl2LnN1Yl9pY29uLmNoYnhfMXtiYWNrZ3JvdW5kLXBvc2l0aW9uOi0xOHB4IDVweDt9ZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gdGQuc3ViX2l0ZW1faWNvbiBkaXYuc3ViX2ljb24ucmRidF8we2JhY2tncm91bmQtcG9zaXRpb246LTcycHggNXB4O31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ZC5zdWJfaXRlbV9pY29uIGRpdi5zdWJfaWNvbi5yZGJ0XzF7YmFja2dyb3VuZC1wb3NpdGlvbjotOTBweCA1cHg7fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29uIHRkLnN1Yl9pdGVtX3RleHQgZGl2LnN1Yl9pdGVtX3RleHR7cG9zaXRpb246cmVsYXRpdmU7aGVpZ2h0OjMwcHg7bGluZS1oZWlnaHQ6MzBweDtwYWRkaW5nOjAgMjJweCAwIDFweDtvdmVyZmxvdzpoaWRkZW47fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29uIHRkLnN1Yl9pdGVtX2hre3BhZGRpbmc6MCAxMHB4IDAgOHB4O31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ZC5zdWJfaXRlbV9oayBkaXYuc3ViX2l0ZW1faGt7Y29sb3I6IzhkOGQ4ZDtmb250LXNpemU6MTJweDt0ZXh0LWFsaWduOnJpZ2h0O31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ZCBkaXYuY29tcGxleF9hcnJvd3tmbG9hdDpyaWdodDt3aWR0aDoxMHB4O21hcmdpbjowIDFweCAwIDExcHg7aGVpZ2h0OjMwcHg7bGluZS1oZWlnaHQ6MzBweDtiYWNrZ3JvdW5kLWltYWdlOnVybCgiaW1ncy9kaHhtZW51X21hdGVyaWFsL2RoeG1lbnVfc3ViYXIucG5nIik7YmFja2dyb3VuZC1yZXBlYXQ6bm8tcmVwZWF0O2JhY2tncm91bmQtcG9zaXRpb246MCAxMHB4O292ZXJmbG93OmhpZGRlbjtmb250LXNpemU6MXB4O31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ZCBkaXYuY29tcGxleF9hcnJvd19sb2FkaW5ne3dpZHRoOjE2cHg7aGVpZ2h0OjMwcHg7bGluZS1oZWlnaHQ6MzBweDtiYWNrZ3JvdW5kLXBvc2l0aW9uOmNlbnRlciBjZW50ZXI7YmFja2dyb3VuZC1yZXBlYXQ6bm8tcmVwZWF0O2JhY2tncm91bmQtaW1hZ2U6dXJsKCJpbWdzL2RoeG1lbnVfbWF0ZXJpYWwvZGh4bWVudV9sb2FkZXIuZ2lmIik7ZmxvYXQ6cmlnaHQ7fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29uIHRyLnN1Yl9pdGVtX3NlbGVjdGVkIHRke2JhY2tncm91bmQtY29sb3I6I2ViZWJlYjt9ZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gdHIuc3ViX2l0ZW1fc2VsZWN0ZWQgdGQgZGl2LmNvbXBsZXhfYXJyb3d7YmFja2dyb3VuZC1wb3NpdGlvbjotMTBweCAxMHB4O31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ci5zdWJfaXRlbV9kaXMgdGQuc3ViX2l0ZW1faGsgZGl2LnN1Yl9pdGVtX2hre2NvbG9yOiNjMGMwYzA7fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29uIHRyLnN1Yl9pdGVtX2RpcyB0ZCBkaXYuc3ViX2l0ZW1fdGV4dCxkaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ci5zdWJfaXRlbV9kaXMgdGQgdGQuc3ViX2l0ZW1faWNvbiBpe2NvbG9yOiNhNmE2YTY7fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29uIHRyLnN1Yl9pdGVtX2RpcyB0ZCBkaXYuY29tcGxleF9hcnJvd3tiYWNrZ3JvdW5kLXBvc2l0aW9uOi0yMHB4IDEwcHg7fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29uIHRyLnN1Yl9pdGVtX2RpcyB0ZCBkaXYuc3ViX2ljb24uY2hieF8we2JhY2tncm91bmQtcG9zaXRpb246LTM2cHggNXB4O31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ci5zdWJfaXRlbV9kaXMgdGQgZGl2LnN1Yl9pY29uLmNoYnhfMXtiYWNrZ3JvdW5kLXBvc2l0aW9uOi01NHB4IDVweDt9ZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gdHIuc3ViX2l0ZW1fZGlzIHRkIGRpdi5zdWJfaWNvbi5yZGJ0XzB7YmFja2dyb3VuZC1wb3NpdGlvbjotMTA4cHggNXB4O31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ci5zdWJfaXRlbV9kaXMgdGQgZGl2LnN1Yl9pY29uLnJkYnRfMXtiYWNrZ3JvdW5kLXBvc2l0aW9uOi0xMjZweCA1cHg7fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29uIHRyLnN1Yl9pdGVtX2RpcyB0ZCBpe2NvbG9yOiNhNmE2YTY7fWRpdi5kaHRtbHhNZW51X21hdGVyaWFsX1N1YkxldmVsQXJlYV9Qb2x5Z29uIHRyLnN1Yl9zZXAgdGR7cGFkZGluZzo1cHggM3B4O31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiB0ci5zdWJfc2VwIHRkIGRpdi5zdWJfc2Vwe3Bvc2l0aW9uOnJlbGF0aXZlO2ZvbnQtc2l6ZToxcHg7bGluZS1oZWlnaHQ6MXB4O2hlaWdodDowO3dpZHRoOjEwMCU7Ym9yZGVyLXRvcDoxcHggc29saWQgI2RmZGZkZjt9ZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX0Fycm93VXAsZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX0Fycm93VXBfT3ZlcixkaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiBkaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfQXJyb3dVcF9EaXNhYmxlZHtwb3NpdGlvbjpyZWxhdGl2ZTtmb250LXNpemU6MXB4O2JvcmRlci1ib3R0b206MXB4IHNvbGlkICNkZmRmZGY7YmFja2dyb3VuZC1pbWFnZTp1cmwoImltZ3MvZGh4bWVudV9tYXRlcmlhbC9kaHhtZW51X2Fycm93X3VwLnBuZyIpO2JhY2tncm91bmQtcmVwZWF0Om5vLXJlcGVhdDtiYWNrZ3JvdW5kLXBvc2l0aW9uOmNlbnRlciAycHg7cGFkZGluZzo4cHggMDttYXJnaW4tYm90dG9tOjNweDt9ZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX0Fycm93VXBfRGlzYWJsZWR7YmFja2dyb3VuZC1pbWFnZTp1cmwoImltZ3MvZGh4bWVudV9tYXRlcmlhbC9kaHhtZW51X2Fycm93X3VwX2Rpcy5wbmciKTt9ZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX0Fycm93RG93bixkaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiBkaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfQXJyb3dEb3duX092ZXIsZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX1BvbHlnb24gZGl2LmRodG1seE1lbnVfbWF0ZXJpYWxfU3ViTGV2ZWxBcmVhX0Fycm93RG93bl9EaXNhYmxlZHtwb3NpdGlvbjpyZWxhdGl2ZTtmb250LXNpemU6MXB4O2JvcmRlci10b3A6MXB4IHNvbGlkICNkZmRmZGY7YmFja2dyb3VuZC1pbWFnZTp1cmwoImltZ3MvZGh4bWVudV9tYXRlcmlhbC9kaHhtZW51X2Fycm93X2Rvd24ucG5nIik7YmFja2dyb3VuZC1yZXBlYXQ6bm8tcmVwZWF0O2JhY2tncm91bmQtcG9zaXRpb246Y2VudGVyIDZweDtwYWRkaW5nOjhweCAwO21hcmdpbi10b3A6M3B4O31kaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfUG9seWdvbiBkaXYuZGh0bWx4TWVudV9tYXRlcmlhbF9TdWJMZXZlbEFyZWFfQXJyb3dEb3duX0Rpc2FibGVke2JhY2tncm91bmQtaW1hZ2U6dXJsKCJpbWdzL2RoeG1lbnVfbWF0ZXJpYWwvZGh4bWVudV9hcnJvd19kb3duX2Rpcy5wbmciKTt9aWZyYW1lLmRodG1seE1lbnVfSUU2Q292ZXJGaXhfbWF0ZXJpYWx7cG9zaXRpb246YWJzb2x1dGU7Ym9yZGVyOm5vbmU7YmFja2dyb3VuZDojMDAwO2ZpbHRlcjpwcm9naWQ6RFhJbWFnZVRyYW5zZm9ybS5NaWNyb3NvZnQuQWxwaGEob3BhY2l0eT0xMDApO30uZGh0bWx4TWVudV9tYXRlcmlhbF9NaWRkbGUuZGlyX2xlZnQgZGl2LmFsaWduX2xlZnR7ZmxvYXQ6bGVmdDt9LmRodG1seE1lbnVfbWF0ZXJpYWxfTWlkZGxlLmRpcl9sZWZ0IGRpdi5hbGlnbl9yaWdodHtmbG9hdDpyaWdodDt9LmRoeG1lbnVfc2tpbl9kZXRlY3R7cG9zaXRpb246YWJzb2x1dGU7bGVmdDowO3RvcDotMTAwcHg7bWFyZ2luOjA7cGFkZGluZzowO2JvcmRlcjowIHNvbGlkIHdoaXRlO3dpZHRoOjQwcHg7aGVpZ2h0OjEwcHg7b3ZlcmZsb3c6aGlkZGVuO31Aa2V5ZnJhbWVzIGRoeF9sb2FkZXJfcm90YXRlezEwMCV7dHJhbnNmb3JtOnJvdGF0ZSgzNjBkZWcpO319QGtleWZyYW1lcyBkaHhfbG9hZGVyX2Rhc2h7MCV7c3Ryb2tlLWRhc2hhcnJheToxLDIwMDtzdHJva2UtZGFzaG9mZnNldDowO301MCV7c3Ryb2tlLWRhc2hhcnJheTo4OSwyMDA7c3Ryb2tlLWRhc2hvZmZzZXQ6LTM1cHg7fTEwMCV7c3Ryb2tlLWRhc2hhcnJheTo4OSwyMDA7c3Ryb2tlLWRhc2hvZmZzZXQ6LTEyNHB4O319LmRlZmF1bHRUcmVlVGFibGV7bWFyZ2luOjA7cGFkZGluZzowO2JvcmRlcjowO30uY29udGFpbmVyVGFibGVTdHlsZXtvdmVyZmxvdzphdXRvOy13ZWJraXQtb3ZlcmZsb3ctc2Nyb2xsaW5nOnRvdWNoO3Bvc2l0aW9uOnJlbGF0aXZlO3RvcDowO2ZvbnQtc2l6ZToxMnB4Oy1raHRtbC11c2VyLXNlbGVjdDpub25lO30uY29udGFpbmVyVGFibGVTdHlsZVJUTCBzcGFue2RpcmVjdGlvbjpydGw7dW5pY29kZS1iaWRpOmJpZGktb3ZlcnJpZGU7fS5jb250YWluZXJUYWJsZVN0eWxlUlRMe2RpcmVjdGlvbjpydGw7b3ZlcmZsb3c6YXV0bztwb3NpdGlvbjpyZWxhdGl2ZTt0b3A6MDtmb250LXNpemU6MTJweDt9LnN0YW5kYXJ0VHJlZVJvd3tmb250LWZhbWlseTpSb2JvdG8sQXJpYWwsSGVsdmV0aWNhO2ZvbnQtc2l6ZTo7LW1vei11c2VyLXNlbGVjdDpub25lO2xpbmUtaGVpZ2h0OjI0cHg7fS5zZWxlY3RlZFRyZWVSb3d7Zm9udC1mYW1pbHk6Um9ib3RvLEFyaWFsLEhlbHZldGljYTtmb250LXNpemU6Oy1tb3otdXNlci1zZWxlY3Q6bm9uZTtiYWNrZ3JvdW5kLWNvbG9yOiNlZWU7Y29sb3I6IzM5Yzt9LmRoeHRyZWVfbWF0ZXJpYWwgLnNlbGVjdGVkVHJlZVJvd0Z1bGwgLmRoeFRleHRDZWxse2JhY2tncm91bmQtY29sb3I6I2VlZTtjb2xvcjojMzljO30uZHJhZ0FuZERyb3BSb3d7Y29sb3I6IzM5Yzt9LnN0YW5kYXJ0VHJlZVJvd19sb3J7dGV4dC1kZWNvcmF0aW9uOnVuZGVybGluZTtiYWNrZ3JvdW5kLWNvbG9yOjtmb250LWZhbWlseTpSb2JvdG8sQXJpYWwsSGVsdmV0aWNhO2ZvbnQtc2l6ZTo7LW1vei11c2VyLXNlbGVjdDpub25lO30uc3RhbmRhcnRUcmVlSW1hZ2V7aGVpZ2h0OjI0cHg7b3ZlcmZsb3c6aGlkZGVuO2JvcmRlcjowO3BhZGRpbmc6MDttYXJnaW46MDtmb250LXNpemU6MXB4O30uc3RhbmRhcnRUcmVlSW1hZ2UgaW1ne3dpZHRoOjE4cHg7aGVpZ2h0OjI0cHg7YmFja2dyb3VuZC1wb3NpdGlvbjpjZW50ZXIgY2VudGVyO2JhY2tncm91bmQtcmVwZWF0Om5vLXJlcGVhdDtib3JkZXI6MDtwYWRkaW5nOjA7bWFyZ2luOjA7Zm9udC1zaXplOjFweDstd2Via2l0LXVzZXItc2VsZWN0Om5vbmU7LWtodG1sLXVzZXItc2VsZWN0Om5vbmU7LW1vei11c2VyLXNlbGVjdDpub25lOy1tcy11c2VyLXNlbGVjdDpub25lOy1vLXVzZXItc2VsZWN0Om5vbmU7dXNlci1zZWxlY3Q6bm9uZTt9LmhpZGRlblJvd3t3aWR0aDoxcHg7b3ZlcmZsb3c6aGlkZGVuO30uZHJhZ1NwYW5EaXYsLmRyYWdTcGFuRGl2IHRke2ZvbnQtZmFtaWx5OlJvYm90byxBcmlhbCxIZWx2ZXRpY2E7Zm9udC1zaXplOjtsaW5lLWhlaWdodDo7dmVydGljYWwtYWxpZ246Y2VudGVyO2JhY2tncm91bmQtY29sb3I6d2hpdGU7ei1pbmRleDo5OTk7fS5kcmFnU3BhbkRpdiB0ZHtwYWRkaW5nOjVweDt9LmFfZGh4X2hpZGRlbl9pbnB1dHtwb3NpdGlvbjphYnNvbHV0ZTt0b3A6LTFweDtsZWZ0Oi0xcHg7d2lkdGg6MXB4O2hlaWdodDoxcHg7Ym9yZGVyOm5vbmU7YmFja2dyb3VuZDpub25lO30uYV9kaHhfaGlkZGVuX2lucHV0e3Bvc2l0aW9uOmFic29sdXRlO3RvcDotMXB4O2xlZnQ6LTFweDt3aWR0aDoxcHg7aGVpZ2h0OjFweDtib3JkZXI6bm9uZTtiYWNrZ3JvdW5kOm5vbmU7fS5zZWxlY3Rpb25CYXJ7dG9wOjA7YmFja2dyb3VuZC1jb2xvcjpibGFjaztwb3NpdGlvbjphYnNvbHV0ZTtvdmVyZmxvdzpoaWRkZW47aGVpZ2h0OjJweDt6LWluZGV4OjExO30uaW50cmVlZWRpdFJvd3tmb250LXNpemU6OHB0O2hlaWdodDoxNnB4O2JvcmRlcjoxcHggc29saWQgc2lsdmVyO3BhZGRpbmc6MDttYXJnaW46MDttYXJnaW4tbGVmdDo0cHg7LW1vei11c2VyLXNlbGVjdDp0ZXh0Oy1raHRtbC11c2VyLXNlbGVjdDp0ZXh0O30uZGh4X3RyZWVfdGV4dFNpZ257Zm9udC1zaXplOjhwdDtmb250LWZhbWlseTptb25vc3BhY2U7d2lkdGg6MjFweDtjb2xvcjo7cGFkZGluZzowO21hcmdpbjowO2N1cnNvcjpwb2ludGVyO3RleHQtYWxpZ246Y2VudGVyO30uZGh4X3RyZWVfb3BhY2l0eXtvcGFjaXR5OjA7ZmlsdGVyOnByb2dpZDpEWEltYWdlVHJhbnNmb3JtLk1pY3Jvc29mdC5BbHBoYShvcGFjaXR5PTApOy13ZWJraXQtdXNlci1zZWxlY3Q6bm9uZTsta2h0bWwtdXNlci1zZWxlY3Q6bm9uZTstbW96LXVzZXItc2VsZWN0Om5vbmU7LW1zLXVzZXItc2VsZWN0Om5vbmU7LW8tdXNlci1zZWxlY3Q6bm9uZTt1c2VyLXNlbGVjdDpub25lO30uZGh4X2JnX2ltZ19maXh7d2lkdGg6MThweDtoZWlnaHQ6MjRweDtiYWNrZ3JvdW5kLXJlcGVhdDpuby1yZXBlYXQ7YmFja2dyb3VuZC1wb3NpdGlvbjpjZW50ZXI7YmFja2dyb3VuZC1wb3NpdGlvbi14OmNlbnRlcjtiYWNrZ3JvdW5kLXBvc2l0aW9uLXk6Y2VudGVyO30uZGh4dHJlZV9za2luX2RldGVjdHtwb3NpdGlvbjphYnNvbHV0ZTtsZWZ0OjA7dG9wOi0xMDBweDttYXJnaW46MDtwYWRkaW5nOjA7Ym9yZGVyOjAgc29saWQgd2hpdGU7d2lkdGg6NDBweDtoZWlnaHQ6MTBweDtvdmVyZmxvdzpoaWRkZW47fScsZG9jdW1lbnQuaGVhZC5hcHBlbmRDaGlsZChzdHlsZSk7dmFyIGxheWFhaXJfZGVidWdfdmlldz17fTt3aW5kb3cubGF5YWFpcl9kZWJ1Z192aWV3PWxheWFhaXJfZGVidWdfdmlldyxsYXlhYWlyX2RlYnVnX3ZpZXcuaW5pdExheWFBaXJEZWJ1Z1ZpZXc9ZnVuY3Rpb24oZSl7ZS5zdHlsZS5ib3JkZXI9IjFweCBzb2xpZCBibGFjayI7dmFyIHQ9TWF0aC5taW4oMjUwLC4zKmUub2Zmc2V0V2lkdGgpLGk9JzxkaXYgY2xhc3M9InRvcC1iYW5uZXIiPlxuPC9kaXY+XG48ZGl2PlxuPGRpdiBzdHlsZT0ib3ZlcmZsb3c6aGlkZGVuOyBib3JkZXItYm90dG9tOjFweCBzb2xpZCAjNDQ0OyBwYWRkaW5nOjVweCI+XG48ZGl2IHN0eWxlPSJmbG9hdDpsZWZ0Ij5cbjxidXR0b24gaWQ9Im5vZGVfZnVuY3Rpb25hbGl0eV9jb250cm9sIj7lrqHmn6XlhYPntKA8L2J1dHRvbj5cbjxidXR0b24gaWQ9InJlZnJlc2hfY29udHJvbCI+5Yi35pawPC9idXR0b24+XG48L2Rpdj5cbjxkaXYgc3R5bGU9ImZsb2F0OnJpZ2h0Ij5cbjxpbnB1dCB0eXBlPSJjaGVja2JveCIgaWQ9InNob3dfY3VycmVudF9jYWNoZV9jb250cm9sIj7mmL7npLrlvZPliY1jYWNoZemHjee7mDwvaW5wdXQ+XG48aW5wdXQgdHlwZT0iY2hlY2tib3giIGlkPSJzaG93X2FsbF9jYWNoZV9jb250cm9sIj7mmL7npLrmiYDmnIljYWNoZeWMuuWfnzwvaW5wdXQ+XG48aW5wdXQgdHlwZT0iY2hlY2tib3giIGlkPSJzaG93X2F0bGFzX2NvbnRyb2wiPuaYvuekuuWkp+WbvuWQiOmbhjwvaW5wdXQ+XG48L2Rpdj5cbjwvZGl2PlxuPGRpdiBjbGFzcz0iaGdyb3VwIj5cbjxkaXYgc3R5bGU9ImZsb2F0OmxlZnQ7d2lkdGg6Jyt0KydweDsgYm9yZGVyLXJpZ2h0OjFweCBzb2xpZCBibGFjayIgaWQ9InRyZWVfY29udGFpbmVyIj48L2Rpdj5cbjxkaXYgc3R5bGU9Im92ZXJmbG93OmhpZGRlbiI+XG48ZGl2IGlkPSJjb250ZW50X3Rvb2xiYXIiIHN0eWxlPSJ3aWR0aDoxMDAlO21hcmdpbjoxMHB4Ij48aW5wdXQgdHlwZT0iY2hlY2tib3giIGlkPSJ2aXNpYmlsaXR5X2NvbnRyb2wiPuWPr+ingTwvaW5wdXQ+XG48aW5wdXQgdHlwZT0iY2hlY2tib3giIGlkPSJzaG93X2JvcmRlcl9jb250cm9sIj7mmL7npLrovrnmoYY8L2lucHV0PlxuPGJ1dHRvbiBpZD0ibG9nX2luZm9fY29udHJvbCI+5omT5Y2w5Yiw5o6n5Yi25Y+wPC9idXR0b24+XG48YnV0dG9uIGlkPSJlbmFibGVkX25vZGVfY2hhaW5fY29udHJvbCI+ZW5hYmxl6ZO+PC9idXR0b24+XG48YnV0dG9uIGlkPSJzaXplX2NoYWluX2NvbnRyb2wiPnNpemXpk748L2J1dHRvbj5cbjwvZGl2PjxkaXYgc3R5bGU9Im92ZXJmbG93OmF1dG8iPjx0YWJsZSBpZD0iY29udGVudF90YWJsZSIgc3R5bGU9ImJvcmRlcjoxcHggc29saWQgI2NjY2NjYztib3JkZXItY29sbGFwc2U6Y29sbGFwc2UiPjwvdGFibGU+XG48L2Rpdj48L2Rpdj5cbjwvZGl2PlxuPC9kaXY+JztlLmlubmVySFRNTD1pLHRoaXMuY29udGFpbmVyPWUsdGhpcy50cmVlPW5ldyBkaHRtbFhUcmVlT2JqZWN0KHRyZWVfY29udGFpbmVyLCIxMDAlIiwiMTAwJSIsMCksbm9kZV9mdW5jdGlvbmFsaXR5X2NvbnRyb2wub25jbGljaz1mdW5jdGlvbihlKXtlLnN0b3BQcm9wYWdhdGlvbigpLGxheWFhaXJfZGVidWdfdmlldy5vbl9pbnNwZWN0X2VsZW1lbnRfY2FsbGJhY2soKSxub2RlX2Z1bmN0aW9uYWxpdHlfY29udHJvbC5zdHlsZS5iYWNrZ3JvdW5kQ29sb3I9IiNGRkYiLG5vZGVfZnVuY3Rpb25hbGl0eV9jb250cm9sLnN0eWxlLmNvbG9yPSJyZ2IoMTA3LCAxNjMsIDI1NSkifX0sbGF5YWFpcl9kZWJ1Z192aWV3LnNldFRyZWU9ZnVuY3Rpb24oZSl7Zm9yKHZhciB0PXRoaXMudHJlZS5nZXRBbGxJdGVtc1dpdGhLaWRzKCkuc3BsaXQoIiwiKSxpPVtdLG49MDtuPHQubGVuZ3RoO24rKyl7dmFyIG89dFtuXSxyPXRoaXMudHJlZS5nZXRPcGVuU3RhdGUobyk7MT09ciYmaS5wdXNoKG8pfXRoaXMudHJlZS5kZWxldGVDaGlsZEl0ZW1zKDApLHRoaXMudHJlZS5wYXJzZShlLCJqc29uIik7Zm9yKHZhciBuPTA7bjxpLmxlbmd0aDtuKyspdGhpcy50cmVlLm9wZW5JdGVtKGlbbl0pfSxsYXlhYWlyX2RlYnVnX3ZpZXcucmVzaXplPWZ1bmN0aW9uKGUsdCl7dGhpcy5jb250YWluZXIuc3R5bGUud2lkdGg9ZSsicHgiLHRoaXMuY29udGFpbmVyLnN0eWxlLmhlaWdodD10KyJweCI7dmFyIGk9dGhpcy5jb250YWluZXIub2Zmc2V0SGVpZ2h0LXRyZWVfY29udGFpbmVyLm9mZnNldFRvcDt0cmVlX2NvbnRhaW5lci5zdHlsZS5oZWlnaHQ9aSsicHgiLGNvbnRlbnRfdG9vbGJhci5zdHlsZS53aWR0aD1lLXRyZWVfY29udGFpbmVyLm9mZnNldFdpZHRoKyJweCIsY29udGVudF90YWJsZS5wYXJlbnRFbGVtZW50LnN0eWxlLmhlaWdodD1pLWNvbnRlbnRfdG9vbGJhci5vZmZzZXRIZWlnaHQtMjErInB4Iixjb250ZW50X3RhYmxlLnN0eWxlLndpZHRoPWUtdHJlZV9jb250YWluZXIub2Zmc2V0V2lkdGgtMTYrInB4In0sbGF5YWFpcl9kZWJ1Z192aWV3LmJvdW5jZVVwSW5zcGVjdEJ1dHRvbj1mdW5jdGlvbigpe25vZGVfZnVuY3Rpb25hbGl0eV9jb250cm9sLnN0eWxlLmJhY2tncm91bmRDb2xvcj0iYnV0dG9uZmFjZSIsbm9kZV9mdW5jdGlvbmFsaXR5X2NvbnRyb2wuc3R5bGUuY29sb3I9ImJsYWNrIn0sbGF5YWFpcl9kZWJ1Z192aWV3LnNldFZhbHVlSW5wdXRIYW5kbGVyPWZ1bmN0aW9uKGUpe3RoaXMudmFsdWVfaW5wdXRfY2FsbGJhY2s9ZX0sbGF5YWFpcl9kZWJ1Z192aWV3LnNldFZhbHVlQ2hhbmdlSGFuZGxlcj1mdW5jdGlvbihlKXt0aGlzLnZhbHVlX2NoYW5nZV9jYWxsYmFjaz1lfSxsYXlhYWlyX2RlYnVnX3ZpZXcuYWRkQ29udGVudD1mdW5jdGlvbihlKXt2YXIgdD1kb2N1bWVudC5jcmVhdGVFbGVtZW50KCJ0ciIpO3QuaW5uZXJIVE1MPSc8dGQgc3R5bGU9IndpZHRoOjEwMHB4O2ZvbnQtc2l6ZToxM3B4O2JvcmRlcjoxcHggc29saWQgI0NDQztwYWRkaW5nLWxlZnQ6MTBweCI+JytlLmtleSsnPC90ZD5cbjx0ZCBzdHlsZT0id2lkdGg6MjAwcHg7Ym9yZGVyOjFweCBzb2xpZCAjQ0NDOyI+PGlucHV0IHN0eWxlPSJib3JkZXI6bm9uZTt3aWR0aDoxMDAlO2hlaWdodDoyNXB4O3BhZGRpbmctbGVmdDoxMHB4OyIgdmFsdWU9JytlLnZhbHVlKyI+PC90ZD4iLGNvbnRlbnRfdGFibGUuYXBwZW5kQ2hpbGQodCk7dmFyIGk9dC5sYXN0RWxlbWVudENoaWxkLmxhc3RFbGVtZW50Q2hpbGQ7aS5kYXRhPWUsaS5vbmlucHV0PWZ1bmN0aW9uKGUpe3RoaXMudmFsdWVfaW5wdXRfY2FsbGJhY2smJnRoaXMudmFsdWVfaW5wdXRfY2FsbGJhY2soZS50YXJnZXQuZGF0YSxlLnRhcmdldC52YWx1ZSl9LmJpbmQodGhpcyksaS5vbmNoYW5nZT1mdW5jdGlvbihlKXt0aGlzLnZhbHVlX2NoYW5nZV9jYWxsYmFjayYmdGhpcy52YWx1ZV9jaGFuZ2VfY2FsbGJhY2soZS50YXJnZXQuZGF0YSxlLnRhcmdldC52YWx1ZSl9LmJpbmQodGhpcyl9LGxheWFhaXJfZGVidWdfdmlldy5zZXRDb250ZW50cz1mdW5jdGlvbihlKXtjb250ZW50X3RhYmxlLmlubmVySFRNTD0iIjtmb3IodmFyIHQ9MDt0PGUubGVuZ3RoO3QrKyl7dmFyIGk9ZVt0XTt0aGlzLmFkZENvbnRlbnQoaSl9fSxsYXlhYWlyX2RlYnVnX3ZpZXcuY2hhbmdlVmFsdWVBdD1mdW5jdGlvbihlLHQpe2NvbnRlbnRfdGFibGUuY2hpbGRyZW5bZV0ubGFzdEVsZW1lbnRDaGlsZC5maXJzdEVsZW1lbnRDaGlsZC52YWx1ZT10fSxsYXlhYWlyX2RlYnVnX3ZpZXcuY2hhbmdlVmFsdWVCeUxhYmVsPWZ1bmN0aW9uKGUsdCl7Zm9yKHZhciBpPWNvbnRlbnRfdGFibGUuY2hpbGRyZW4ubGVuZ3RoLTE7aT49MDtpLS0paWYoY29udGVudF90YWJsZS5jaGlsZHJlbltpXS5maXJzdEVsZW1lbnRDaGlsZC5pbm5lclRleHQ9PWUpe2NvbnRlbnRfdGFibGUuY2hpbGRyZW5baV0ubGFzdEVsZW1lbnRDaGlsZC5maXJzdEVsZW1lbnRDaGlsZC52YWx1ZT10O2JyZWFrfX0sbGF5YWFpcl9kZWJ1Z192aWV3LnNldFZpc2liaWxpdHk9ZnVuY3Rpb24oZSl7dmlzaWJpbGl0eV9jb250cm9sLmNoZWNrZWQ9ISFlfSxsYXlhYWlyX2RlYnVnX3ZpZXcuc2V0U2hvd0RlYnVnQm9yZGVyPWZ1bmN0aW9uKGUpe3Nob3dfYm9yZGVyX2NvbnRyb2wuY2hlY2tlZD0hIWV9LGxheWFhaXJfZGVidWdfdmlldy5nZXRWaXNpYmlsaXR5PWZ1bmN0aW9uKCl7cmV0dXJuIHZpc2liaWxpdHlfY29udHJvbC5jaGVja2VkfSxsYXlhYWlyX2RlYnVnX3ZpZXcuZ2V0U2hvd0RlYnVnQm9yZGVyPWZ1bmN0aW9uKCl7cmV0dXJuIHNob3dfYm9yZGVyX2NvbnRyb2wuY2hlY2tlZH0sbGF5YWFpcl9kZWJ1Z192aWV3LmdldFNob3dDdXJyZW50Q2FjaGU9ZnVuY3Rpb24oKXtyZXR1cm4gc2hvd19jdXJyZW50X2NhY2hlX2NvbnRyb2wuY2hlY2tlZH0sbGF5YWFpcl9kZWJ1Z192aWV3LmdldFNob3dBbGxDYWNoZT1mdW5jdGlvbigpe3JldHVybiBzaG93X2FsbF9jYWNoZV9jb250cm9sLmNoZWNrZWR9LGxheWFhaXJfZGVidWdfdmlldy5nZXRTaG93QXRsYXM9ZnVuY3Rpb24oKXtyZXR1cm4gc2hvd19hdGxhc19jb250cm9sLmNoZWNrZWR9LGxheWFhaXJfZGVidWdfdmlldy5vbkluc3BlY3RFbGVtZW50PWZ1bmN0aW9uKGUpe3RoaXMub25faW5zcGVjdF9lbGVtZW50X2NhbGxiYWNrPWV9LGxheWFhaXJfZGVidWdfdmlldy5vbkxvZ0luZm89ZnVuY3Rpb24oZSl7bG9nX2luZm9fY29udHJvbC5vbmNsaWNrPWV9LGxheWFhaXJfZGVidWdfdmlldy5vblJlZnJlc2g9ZnVuY3Rpb24oZSl7cmVmcmVzaF9jb250cm9sLm9uY2xpY2s9ZX0sbGF5YWFpcl9kZWJ1Z192aWV3Lm9uUHJpbnRFbmFibGVkTm9kZUNoYWluPWZ1bmN0aW9uKGUpe2VuYWJsZWRfbm9kZV9jaGFpbl9jb250cm9sLm9uY2xpY2s9ZX0sbGF5YWFpcl9kZWJ1Z192aWV3Lm9uUHJpbnRTaXplQ2hhaW49ZnVuY3Rpb24oZSl7c2l6ZV9jaGFpbl9jb250cm9sLm9uY2xpY2s9ZX0sbGF5YWFpcl9kZWJ1Z192aWV3Lm9uVG9nZ2xlVmlzaWJpbGl0eT1mdW5jdGlvbihlKXt2aXNpYmlsaXR5X2NvbnRyb2wub25jaGFuZ2U9ZX0sbGF5YWFpcl9kZWJ1Z192aWV3Lm9uVG9nZ2xlRGVidWdCb3JkZXI9ZnVuY3Rpb24oZSl7c2hvd19ib3JkZXJfY29udHJvbC5vbmNoYW5nZT1lfSxsYXlhYWlyX2RlYnVnX3ZpZXcub25Ub2dnbGVTaG93Q3VycmVudENhY2hlPWZ1bmN0aW9uKGUpe3Nob3dfY3VycmVudF9jYWNoZV9jb250cm9sLm9uY2hhbmdlPWV9LGxheWFhaXJfZGVidWdfdmlldy5vblRvZ2dsZVNob3dBbGxDYWNoZT1mdW5jdGlvbihlKXtzaG93X2FsbF9jYWNoZV9jb250cm9sLm9uY2hhbmdlPWV9LGxheWFhaXJfZGVidWdfdmlldy5vblRvZ2dsZVNob3dBdGxhcz1mdW5jdGlvbihlKXtzaG93X2F0bGFzX2NvbnRyb2wub25jaGFuZ2U9ZX07"; return DivScripts; })() /** *tianpeng *@author */ //class laya.debug.tools.AtlasTools var AtlasTools=(function(){ function AtlasTools(){ this.mSprite=null; this.mIndex=0; this.mTextureDic={}; } __class(AtlasTools,'laya.debug.tools.AtlasTools'); var __proto=AtlasTools.prototype; __proto.start=function(){ if (!Render.isWebGL)return; if (this.mSprite==null){ this.mSprite=new Sprite(); } Laya.stage.addChild(this.mSprite); this.showNext(); } __proto.end=function(){ if (!Render.isWebGL)return; if (this.mSprite){ Laya.stage.removeChild(this.mSprite); } } __proto.showNext=function(){ if (!Render.isWebGL)return; if (this.mSprite==null){ this.mSprite=new Sprite(); } Laya.stage.addChild(this.mSprite); this.mIndex++; var resManager; /*__JS__ */resManager=laya.webgl.atlas.AtlasResourceManager.instance;; var tCount=resManager.getAtlaserCount(); if (this.mIndex >=tCount){ this.mIndex=0; }; var tTexture; if (this.mTextureDic[this.mIndex]){ tTexture=this.mTextureDic[this.mIndex]; }else { var tAtlaser=resManager.getAtlaserByIndex(this.mIndex); if (tAtlaser && tAtlaser.texture){ tTexture=new Texture(tAtlaser.texture,null); this.mTextureDic[this.mIndex]=tTexture; } } if (tTexture){ this.mSprite.graphics.clear(); this.mSprite.graphics.save(); this.mSprite.graphics.alpha(0.9); this.mSprite.graphics.drawRect(0,0,1024,1024,"#efefefe"); this.mSprite.graphics.restore(); this.mSprite.graphics.drawTexture(tTexture,0,0,1024,1024); this.mSprite.graphics.fillText((this.mIndex+1).toString()+"/"+tCount.toString(),25,100,"40px Arial","#ff0000","left"); } } AtlasTools.getInstance=function(){ return AtlasTools.mInstance=AtlasTools.mInstance|| new AtlasTools(); } AtlasTools.mInstance=null; return AtlasTools; })() /** *... *@author ww */ //class laya.debug.tools.Base64Atlas var Base64Atlas=(function(){ function Base64Atlas(data,idKey){ this.data=null; this.replaceO=null; this.idKey=null; this._loadedHandler=null; this.data=data; if (!idKey)idKey=Math.random()+"key"; this.idKey=idKey; this.init(); } __class(Base64Atlas,'laya.debug.tools.Base64Atlas'); var __proto=Base64Atlas.prototype; //preLoad(); __proto.init=function(){ this.replaceO={}; var key; for (key in this.data){ this.replaceO[key]=this.idKey+"/"+key; } } __proto.getAdptUrl=function(url){ return this.replaceO[url]; } __proto.preLoad=function(completeHandler){ this._loadedHandler=completeHandler; Laya.loader.load(Base64ImageTool.getPreloads(this.data),new Handler(this,this.preloadEnd)); } __proto.preloadEnd=function(){ var key; for (key in this.data){ var tx; tx=Laya.loader.getRes(this.data[key]); Loader.cacheRes(this.replaceO[key],tx); } if (this._loadedHandler){ this._loadedHandler.run(); } } __proto.replaceRes=function(uiObj){ ObjectTools.replaceValue(uiObj,this.replaceO); } return Base64Atlas; })() /** *... *@author ww */ //class laya.debug.tools.Base64ImageTool var Base64ImageTool=(function(){ function Base64ImageTool(){} __class(Base64ImageTool,'laya.debug.tools.Base64ImageTool'); Base64ImageTool.getCanvasPic=function(img){ img=img.bitmap; var canvas=Browser.createElement("canvas"); var ctx=canvas.getContext('2d'); canvas.height=img.height; canvas.width=img.width; ctx.drawImage(img.source,0,0); return canvas; } Base64ImageTool.getBase64Pic=function(img){ return Base64ImageTool.getCanvasPic(img).toDataURL("image/png"); } Base64ImageTool.getPreloads=function(base64Data){ var rst; rst=[]; var key; for (key in base64Data){ rst.push({url:base64Data[key],type:/*laya.net.Loader.IMAGE*/"image" }); } return rst; } return Base64ImageTool; })() /** *base64编码解码类 *@author ww */ //class laya.debug.tools.Base64Tool var Base64Tool=(function(){ function Base64Tool(){} __class(Base64Tool,'laya.debug.tools.Base64Tool'); Base64Tool.init=function(){ if (Base64Tool.lookup) return; Base64Tool.lookup=new Uint8Array(256) for (var i=0;i < Base64Tool.chars.length;i++){ Base64Tool.lookup[Base64Tool.chars.charCodeAt(i)]=i; } } Base64Tool.encode=function(arraybuffer){ var bytes=new Uint8Array(arraybuffer),i=0,len=bytes.length,base64=""; for (i=0;i < len;i+=3){ base64+=Base64Tool.chars[bytes[i] >> 2]; base64+=Base64Tool.chars[((bytes[i] & 3)<< 4)| (bytes[i+1] >> 4)]; base64+=Base64Tool.chars[((bytes[i+1] & 15)<< 2)| (bytes[i+2] >> 6)]; base64+=Base64Tool.chars[bytes[i+2] & 63]; } if ((len % 3)===2){ base64=base64.substring(0,base64.length-1)+"="; } else if (len % 3===1){ base64=base64.substring(0,base64.length-2)+"=="; } return base64; } Base64Tool.encodeStr=function(str){ var byte; byte=new Byte(); byte.writeUTFString(str); return Base64Tool.encodeByte(byte); } Base64Tool.encodeStr2=function(str){ var byte; byte=new Byte(); byte.writeUTFBytes(str); return Base64Tool.encodeByte(byte); } Base64Tool.encodeByte=function(byte,start,end){ (start===void 0)&& (start=0); (end===void 0)&& (end=-1); if (end < 0){ end=byte.length; } return Base64Tool.encode(byte.buffer.slice(start,end)); } Base64Tool.decodeToByte=function(base64){ return new Byte(Base64Tool.decode(base64)); } Base64Tool.decode=function(base64){ Base64Tool.init(); var bufferLength=base64.length *0.75,len=base64.length,i=0,p=0,encoded1=0,encoded2=0,encoded3=0,encoded4=0; if (base64[base64.length-1]==="="){ bufferLength--; if (base64[base64.length-2]==="="){ bufferLength--; } }; var arraybuffer=new ArrayBuffer(bufferLength),bytes=new Uint8Array(arraybuffer); for (i=0;i < len;i+=4){ encoded1=Base64Tool.lookup[base64.charCodeAt(i)]; encoded2=Base64Tool.lookup[base64.charCodeAt(i+1)]; encoded3=Base64Tool.lookup[base64.charCodeAt(i+2)]; encoded4=Base64Tool.lookup[base64.charCodeAt(i+3)]; bytes[p++]=(encoded1 << 2)| (encoded2 >> 4); bytes[p++]=((encoded2 & 15)<< 4)| (encoded3 >> 2); bytes[p++]=((encoded3 & 3)<< 6)| (encoded4 & 63); } return arraybuffer; } Base64Tool.chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; Base64Tool.lookup=null; return Base64Tool; })() /** *... *@author ww */ //class laya.debug.tools.CacheAnalyser var CacheAnalyser=(function(){ function CacheAnalyser(){} __class(CacheAnalyser,'laya.debug.tools.CacheAnalyser'); var __proto=CacheAnalyser.prototype; __proto.renderCanvas=function(sprite,time){ (time===void 0)&& (time=0); if (!CacheAnalyser.showCacheSprite)return; if (DebugInfoLayer.I.isDebugItem(sprite))return; DebugTool.showDisBoundToSprite(sprite,DebugInfoLayer.I.cacheViewLayer,DebugConsts.CANVAS_REC_COLOR,4); } __proto.reCacheCanvas=function(sprite,time){ (time===void 0)&& (time=0); if (!CacheAnalyser.showRecacheSprite)return; if (DebugInfoLayer.I.isDebugItem(sprite))return; var info; info=CacheAnalyser.getNodeInfoByNode(sprite); info.addCount(time); CacheAnalyser.counter.addTime(sprite,time); if (!info.parent){ DebugInfoLayer.I.nodeRecInfoLayer.addChild(info); } } CacheAnalyser.renderLoopBegin=function(){ DebugInfoLayer.I.cacheViewLayer.graphics.clear(); } CacheAnalyser.getNodeInfoByNode=function(node){ IDTools.idObj(node); var key=0; key=IDTools.getObjID(node); if (!CacheAnalyser._nodeInfoDic[key]){ CacheAnalyser._nodeInfoDic[key]=new ReCacheRecInfo(); } (CacheAnalyser._nodeInfoDic [key]).setTarget(node); return CacheAnalyser._nodeInfoDic[key]; } CacheAnalyser._nodeInfoDic={}; CacheAnalyser.showCacheSprite=false; CacheAnalyser.showRecacheSprite=true; __static(CacheAnalyser, ['counter',function(){return this.counter=new ObjTimeCountTool();},'I',function(){return this.I=new CacheAnalyser();} ]); return CacheAnalyser; })() /** * *@author ww *@version 1.0 * *@created 2017-3-2 下午12:11:59 */ //class laya.debug.tools.CallLaterTool var CallLaterTool=(function(){ function CallLaterTool(){ this._getHandler=null; this._indexHandler=null; this._pool=null; this._laters=null; } __class(CallLaterTool,'laya.debug.tools.CallLaterTool'); var __proto=CallLaterTool.prototype; /** *延迟执行。 *@param caller 执行域(this)。 *@param method 定时器回调函数。 *@param args 回调参数。 */ __proto.callLater=function(caller,method,args){ if (this._getHandler(caller,method)==null){ CallLaterTool.oldCallLater.call(this,caller,method,args); if(CallLaterTool._isRecording){ CallLaterTool._recordedCallLaters.push(this._laters[this._laters.length-1]); } } } CallLaterTool.initCallLaterRecorder=function(){ if(CallLaterTool.oldCallLater)return; CallLaterTool.oldCallLater=Laya.timer["callLater"]; Laya.timer["callLater"]=CallLaterTool["prototype"]["callLater"]; } CallLaterTool.beginRecordCallLater=function(){ CallLaterTool.initCallLaterRecorder(); CallLaterTool._isRecording=true; } CallLaterTool.runRecordedCallLaters=function(){ CallLaterTool._isRecording=false; var timer; timer=Laya.timer; var laters=timer["_laters"]; laters=CallLaterTool._recordedCallLaters; for (var i=0,n=laters.length-1;i <=n;i++){ var handler=laters[i]; if(CallLaterTool._recordedCallLaters.indexOf(handler)<0)continue ; handler.method!==null && handler.run(false); timer["_recoverHandler"](handler); laters.splice(i,1); } CallLaterTool._recordedCallLaters.length=0; } CallLaterTool._recordedCallLaters=[]; CallLaterTool._isRecording=false; CallLaterTool.oldCallLater=null; return CallLaterTool; })() /** *... *@author ww */ //class laya.debug.tools.CanvasTools var CanvasTools=(function(){ function CanvasTools(){} __class(CanvasTools,'laya.debug.tools.CanvasTools'); CanvasTools.createCanvas=function(width,height){ var rst=new HTMLCanvas("2D"); rst.getContext('2d'); rst.size(width,height); return rst; } CanvasTools.renderSpriteToCanvas=function(sprite,canvas,offsetX,offsetY){ RenderSprite.renders[sprite._renderType]._fun(sprite,canvas.context,offsetX,offsetY); } CanvasTools.getImageDataFromCanvas=function(canvas,x,y,width,height){ (x===void 0)&& (x=0); (y===void 0)&& (y=0); (width===void 0)&& (width=0); (height===void 0)&& (height=0); if (width <=0) width=canvas.width; if (height <=0) height=canvas.height; var imgdata=canvas.context.getImageData(x,y,width,height); return imgdata; } CanvasTools.getImageDataFromCanvasByRec=function(canvas,rec){ var imgdata=canvas.context.getImageData(rec.x,rec.y,rec.width,rec.height); return imgdata; } CanvasTools.getDifferCount=function(imageData1,imageData2){ var data1=imageData1.data; var data2=imageData2.data; var differCount=0; differCount=0; CanvasTools.walkImageData(imageData1,myWalkFun); return differCount; function myWalkFun (i,j,tarPos,data){ if (!CanvasTools.isPoinSame(tarPos,data1,data2))differCount++; } } CanvasTools.getDifferRate=function(imageData1,imageData2){ return CanvasTools.getDifferCount(imageData1,imageData2)/(imageData1.width *imageData1.height); } CanvasTools.getCanvasDisRec=function(canvas){ var rst; rst=new Rectangle; var imgdata; imgdata=CanvasTools.getImageDataFromCanvas(canvas,0,0); var maxX=0; var minX=0; var maxY=0; var minY=0; maxX=maxY=0; minX=imgdata.width; minY=imgdata.height; var i=0,iLen=0; var j=0,jLen=0; iLen=imgdata.width; jLen=imgdata.height; var data; data=imgdata.data; var tarPos=0; for (j=0;j < jLen;j++){ for (i=0;i < iLen;i++){ if (!CanvasTools.isEmptyPoint(data,tarPos)){ if (minX > i) minX=i; if (maxX < i) maxX=i; if (minY > j) minY=j; if (maxY < j) maxY=j; } tarPos+=4; } } rst.setTo(minX,minY,maxX-minX+1,maxY-minY+1); return rst; } CanvasTools.fillCanvasRec=function(canvas,rec,color){ var ctx=canvas.context; ctx.fillStyle=color; ctx.fillRect(rec.x,rec.y,rec.width,rec.height); } CanvasTools.isEmptyPoint=function(data,pos){ if (data[pos]==0 && data[pos+1]==0 && data[pos+2]==0 && data[pos+3]==0){ return true; } else{ return false; } } CanvasTools.isPoinSame=function(pos,data1,data2){ if (data1[pos]==data2[pos] && data1[pos+1]==data2[pos+1] && data1[pos+2]==data2[pos+2] && data1[pos+3]==data2[pos+3]){ return true; } else{ return false; } } CanvasTools.walkImageData=function(imgdata,walkFun){ var i=0,iLen=0; var j=0,jLen=0; iLen=imgdata.width; jLen=imgdata.height; var tarPos=0; var data=imgdata.data; for (i=0;i < iLen;i++){ for (j=0;j < jLen;j++){ walkFun(i,j,tarPos,data); tarPos+=4; } } } CanvasTools.getSpriteByCanvas=function(canvas){ var rst; rst=new Sprite(); rst.graphics.drawTexture(new Texture(canvas),0,0,canvas.width,canvas.height); return rst; } CanvasTools.renderSpritesToCanvas=function(canvas,sprites,offx,offy,startIndex){ (offx===void 0)&& (offx=0); (offy===void 0)&& (offy=0); (startIndex===void 0)&& (startIndex=0); var i=0,len=0; len=sprites.length; for (i=startIndex;i < len;i++){ CanvasTools.renderSpriteToCanvas(sprites[i],canvas,offx,offy); } } CanvasTools.clearCanvas=function(canvas){ var preWidth=NaN; var preHeight=NaN; preWidth=canvas.width; preHeight=canvas.height; canvas.size(preWidth+1,preHeight); canvas.size(preWidth,preHeight); } CanvasTools.getImagePixels=function(x,y,width,data,colorLen){ (colorLen===void 0)&& (colorLen=4); var pos=0; pos=(x *width+y)*colorLen; var i=0,len=0; var rst; rst=[]; len=colorLen; for (i=0;i < len;i++){ rst.push(data[pos+i]); } return rst; } return CanvasTools; })() /** * *@author ww *@version 1.0 * *@created 2015-10-23 下午2:24:04 */ //class laya.debug.tools.ClassTool var ClassTool=(function(){ function ClassTool(){} __class(ClassTool,'laya.debug.tools.ClassTool'); ClassTool.defineProperty=function(obj,name,des){ /*__JS__ */Object.defineProperty(obj,name,des);; } ClassTool.getOwnPropertyDescriptor=function(obj,name){ var rst; /*__JS__ */rst=Object.getOwnPropertyDescriptor(obj,name);; return rst; } ClassTool.getOwnPropertyDescriptors=function(obj){ var rst; /*__JS__ */rst=Object.getOwnPropertyDescriptors(obj);; return rst; } ClassTool.getOwnPropertyNames=function(obj){ var rst; /*__JS__ */rst=Object.getOwnPropertyNames(obj);; return rst; } ClassTool.getObjectGetSetKeys=function(obj,rst){ if (!rst)rst=[]; var keys; keys=laya.debug.tools.ClassTool.getOwnPropertyNames(obj); var key; for (key in keys){ key=keys[key]; if (key.indexOf("_$get_")>=0){ key=key.replace("_$get_",""); rst.push(key); } } if (obj["__proto__"]){ ClassTool.getObjectGetSetKeys(obj["__proto__"],rst); } return rst; } ClassTool.getObjectDisplayAbleKeys=function(obj,rst){ if (!rst)rst=[]; var key; var tValue; var tType; for (key in obj){ tValue=obj[key]; tType=typeof(tValue); if (key.charAt(0)=="_")continue ; rst.push(key); } ClassTool.getObjectGetSetKeys(obj,rst); rst=ObjectTools.getNoSameArr(rst); return rst; } ClassTool.getClassName=function(tar){ if ((typeof tar=='function'))return tar.name; return tar["constructor"].name; } ClassTool.getNodeClassAndName=function(tar){ if (!tar)return "null"; var rst; if (tar.name){ rst=ClassTool.getClassName(tar)+"("+tar.name+")"; }else{ rst=ClassTool.getClassName(tar); } return rst; } ClassTool.getClassNameByClz=function(clz){ return clz["name"]; } ClassTool.getClassByName=function(className){ var rst; rst=Laya._runScript(className); return rst; } ClassTool.createObjByName=function(className){ var clz; clz=ClassTool.getClassByName(className); return new clz(); } __static(ClassTool, ['displayTypes',function(){return this.displayTypes={"boolean":true,"number":true,"string":true };} ]); return ClassTool; })() /** *... *@author ww */ //class laya.debug.tools.ClickSelectTool var ClickSelectTool=(function(){ function ClickSelectTool(){ this.completeHandler=null; this.tSelectTar=null; this._selectTip=new Sprite(); this._selectTip.setBounds(new Rectangle(0,0,0,0)); Notice.listen(/*laya.debug.tools.DisplayHook.ITEM_CLICKED*/"ItemClicked",this,this.itemClicked); } __class(ClickSelectTool,'laya.debug.tools.ClickSelectTool'); var __proto=ClickSelectTool.prototype; __proto.beginClickSelect=function(complete){ this.completeHandler=complete; ClickSelectTool.isClickSelectState=true; this.clickSelectChange(); } __proto.clickSelectChange=function(){ if (!Browser.onPC)return; this.tSelectTar=null; this.clearSelectTip(); if (ClickSelectTool.isClickSelectState){ Laya.timer.loop(200,this,this.updateSelectTar,null,true); }else{ Laya.timer.clear(this,this.updateSelectTar); } } __proto.clearSelectTip=function(){ this._selectTip.removeSelf(); } __proto.updateSelectTar=function(){ this.clearSelectTip(); this.tSelectTar=DisplayHook.instance.getDisUnderMouse(); if (!this.tSelectTar){ return; } if (DebugInfoLayer.I.isDebugItem(this.tSelectTar))return; var g; g=this._selectTip.graphics; g.clear(); var rec; rec=NodeUtils.getGRec(this.tSelectTar); DebugInfoLayer.I.popLayer.addChild(this._selectTip); g.drawRect(0,0,rec.width,rec.height,null,DebugConsts.CLICK_SELECT_COLOR,2); this._selectTip.pos(rec.x,rec.y); } __proto.itemClicked=function(tar){ if (!ClickSelectTool.isClickSelectState)return; if (ClickSelectTool.ignoreDebugTool){ if (DebugInfoLayer.I.isDebugItem(tar))return; } if ((tar instanceof laya.debug.uicomps.ContextMenuItem )|| (tar.parent instanceof laya.debug.uicomps.ContextMenuItem )){ return; } DebugTool.showDisBound(tar); if (this.completeHandler){ this.completeHandler.runWith(tar); } ClickSelectTool.isClickSelectState=false; this.clickSelectChange(); } __getset(1,ClickSelectTool,'I',function(){ if (!ClickSelectTool._I)ClickSelectTool._I=new ClickSelectTool(); return ClickSelectTool._I; }); ClickSelectTool._I=null; ClickSelectTool.isClickSelectState=false; ClickSelectTool.ignoreDebugTool=false; return ClickSelectTool; })() /** *... *@author ww */ //class laya.debug.tools.ColorTool var ColorTool=(function(){ function ColorTool(){ this.red=NaN; this.green=NaN; this.blue=NaN; } __class(ColorTool,'laya.debug.tools.ColorTool'); ColorTool.toHexColor=function(color){ return Utils.toHexColor(color); } ColorTool.getRGBByRGBStr=function(str){ str.charAt(0)=='#' && (str=str.substr(1)); var color=/*__JS__ */parseInt(str,16); var flag=(str.length==8); var _color; _color=[((0x00FF0000 & color)>> 16),((0x0000FF00 & color)>> 8),(0x000000FF & color)]; return _color; } ColorTool.getColorBit=function(value){ var rst; rst=Math.floor(value).toString(16); rst=rst.length > 1 ? rst :"0"+rst; return rst; } ColorTool.getRGBStr=function(rgb){ return "#"+ColorTool.getColorBit(rgb[0])+ColorTool.getColorBit(rgb[1])+ColorTool.getColorBit(rgb[2]); } ColorTool.traseHSB=function(hsb){ console.log("hsb:",hsb[0],hsb[1],hsb[2]); } ColorTool.rgb2hsb=function(rgbR,rgbG,rgbB){ var rgb=[rgbR,rgbG,rgbB]; rgb.sort(MathTools.sortNumSmallFirst); var max=rgb[2]; var min=rgb[0]; var hsbB=max / 255.0; var hsbS=max==0 ? 0 :(max-min)/ max; var hsbH=0; if(max==min){ hsbH=1; } else if (rgbR==0 && rgbG==0&&rgbB==0){ }else if (max==rgbR && rgbG >=rgbB){ hsbH=(rgbG-rgbB)*60 / (max-min)+0; } else if (max==rgbR && rgbG < rgbB){ hsbH=(rgbG-rgbB)*60 / (max-min)+360; } else if (max==rgbG){ hsbH=(rgbB-rgbR)*60 / (max-min)+120; } else if (max==rgbB){ hsbH=(rgbR-rgbG)*60 / (max-min)+240; } return [hsbH,hsbS,hsbB]; } ColorTool.hsb2rgb=function(h,s,v){ var r=0,g=0,b=0; var i=Math.floor((h / 60)% 6); var f=(h / 60)-i; var p=v *(1-s); var q=v *(1-f *s); var t=v *(1-(1-f)*s); switch (i){ case 0: r=v; g=t; b=p; break ; case 1: r=q; g=v; b=p; break ; case 2: r=p; g=v; b=t; break ; case 3: r=p; g=q; b=v; break ; case 4: r=t; g=p; b=v; break ; case 5: r=v; g=p; b=q; break ; default : break ; } return [Math.floor(r *255.0),Math.floor(g *255.0),Math.floor(b *255.0)]; } return ColorTool; })() /** * *@author ww *@version 1.0 * *@created 2015-9-29 下午12:53:31 */ //class laya.debug.tools.CommonTools var CommonTools=(function(){ function CommonTools(){} __class(CommonTools,'laya.debug.tools.CommonTools'); CommonTools.bind=function(fun,scope){ var rst; /*__JS__ */rst=fun.bind(scope); return rst; } CommonTools.insertP=function(tar,x,y,scaleX,scaleY,rotation){ var nSp; nSp=new Sprite(); tar.parent.addChild(nSp); nSp.x=x; nSp.y=y; nSp.scaleX=scaleX; nSp.scaleY=scaleY; nSp.rotation=rotation; nSp.addChild(tar); CommonTools.count++; nSp.name="insertP:"+CommonTools.count; } CommonTools.insertChild=function(tar,x,y,scaleX,scaleY,rotation,color){ (color===void 0)&& (color="#ff00ff"); var nSp; nSp=new Sprite(); tar.addChild(nSp); nSp.x=x; nSp.y=y; nSp.scaleX=scaleX; nSp.scaleY=scaleY; nSp.rotation=rotation; nSp.graphics.drawRect(0,0,20,20,color); nSp.name="child:"+tar.numChildren; return nSp; } CommonTools.createSprite=function(width,height,color){ (color===void 0)&& (color="#ff0000"); var sp; sp=new Sprite(); sp.graphics.drawRect(0,0,width,height,color); sp.size(width,height); return sp; } CommonTools.createBtn=function(txt,width,height){ (width===void 0)&& (width=100); (height===void 0)&& (height=40); var sp; sp=new Sprite(); sp.size(width,height); sp.graphics.drawRect(0,0,sp.width,sp.height,"#ff0000"); sp.graphics.fillText(txt,sp.width *0.5,sp.height *0.5,null,"#ffff00","center"); return sp; } CommonTools.count=0; return CommonTools; })() /** * *@author ww *@version 1.0 * *@created 2015-9-24 下午6:37:56 */ //class laya.debug.tools.CountTool var CountTool=(function(){ function CountTool(){ this.data={}; this.preO={}; this.changeO={}; this.count=0; } __class(CountTool,'laya.debug.tools.CountTool'); var __proto=CountTool.prototype; __proto.reset=function(){ this.data={}; this.count=0; } __proto.add=function(name,num){ (num===void 0)&& (num=1); this.count++; if(!this.data.hasOwnProperty(name)){ this.data[name]=0; } this.data[name]=this.data[name]+num; } __proto.getKeyCount=function(key){ if(!this.data.hasOwnProperty(key)){ this.data[key]=0; } return this.data[key]; } __proto.getKeyChange=function(key){ if (!this.changeO[key])return 0; return this.changeO[key]; } __proto.record=function(){ var key; for (key in this.changeO){ this.changeO[key]=0; } for (key in this.data){ if (!this.preO[key])this.preO[key]=0; this.changeO[key]=this.data[key]-this.preO[key]; this.preO[key]=this.data[key] } } __proto.getCount=function(dataO){ var rst=0; var key; for (key in dataO){ rst+=dataO[key]; } return rst; } __proto.traceSelf=function(dataO){ if (!dataO)dataO=this.data; var tCount=0; tCount=this.getCount(dataO); console.log("total:"+tCount); return "total:"+tCount+"\n"+TraceTool.traceObj(dataO); } __proto.traceSelfR=function(dataO){ if (!dataO)dataO=this.data; var tCount=0; tCount=this.getCount(dataO); console.log("total:"+tCount); return "total:"+tCount+"\n"+TraceTool.traceObjR(dataO); } return CountTool; })() /** *... *@author ww */ //class laya.debug.tools.DebugConsts var DebugConsts=(function(){ function DebugConsts(){} __class(DebugConsts,'laya.debug.tools.DebugConsts'); DebugConsts.CLICK_SELECT_COLOR="#ff0000"; DebugConsts.CANVAS_REC_COLOR="#FF00FF"; DebugConsts.RECACHE_REC_COLOR="#00ff00"; DebugConsts.SPRITE_REC_COLOR="#ff0000"; DebugConsts.SPRITE_REC_LINEWIDTH=2; return DebugConsts; })() /** * *@author ww *@version 1.0 * *@created 2015-10-31 下午3:35:16 */ //class laya.debug.tools.DebugExport var DebugExport=(function(){ function DebugExport(){} __class(DebugExport,'laya.debug.tools.DebugExport'); DebugExport.export=function(){ var _window; /*__JS__ */_window=window;; var key; for(key in DebugExport._exportsDic){ _window[key]=DebugExport._exportsDic[key]; } } __static(DebugExport, ['_exportsDic',function(){return this._exportsDic={ "DebugTool":DebugTool, "Watcher":Watcher };} ]); return DebugExport; })() /** *... *@author ww */ //class laya.debug.tools.DebugTxt var DebugTxt=(function(){ function DebugTxt(){} __class(DebugTxt,'laya.debug.tools.DebugTxt'); DebugTxt.init=function(){ if (DebugTxt._txt)return; DebugTxt._txt=new Text(); DebugTxt._txt.pos(100,100); DebugTxt._txt.color="#ff00ff"; DebugTxt._txt.zOrder=999; DebugTxt._txt.fontSize=24; DebugTxt._txt.text="debugTxt inited"; Laya.stage.addChild(DebugTxt._txt); } DebugTxt.getArgArr=function(arg){ var rst; rst=[]; var i=0,len=arg.length; for(i=0;i-1;i--){ var child=sprite._childs[i]; if((child instanceof laya.display.Sprite )) DisControlTool.getObjectsUnderPoint(child,x,y,rst,filterFun); } } return rst; } DisControlTool.getObjectsUnderGlobalPoint=function(sprite,filterFun){ var point=new Point(); point.setTo(Laya.stage.mouseX,Laya.stage.mouseY); if(sprite.parent) point=(sprite.parent).globalToLocal(point); return DisControlTool.getObjectsUnderPoint(sprite,point.x,point.y,null,filterFun); } DisControlTool.findFirstObjectsUnderGlobalPoint=function(){ var disList; disList=DisControlTool.getObjectsUnderGlobalPoint(Laya.stage); if (!disList)return null; var i=0,len=0; var tDis; len=disList.length; for (i=len-1;i>=0;i--){ tDis=disList[i]; if (tDis && tDis.numChildren < 1){ return tDis; } } return tDis; } DisControlTool.visibleAndEnableObjFun=function(tar){ return tar.visible&&tar.mouseEnabled; } DisControlTool.visibleObjFun=function(tar){ return tar.visible; } DisControlTool.getMousePoint=function(sprite){ var point=new Point(); point.setTo(Laya.stage.mouseX,Laya.stage.mouseY); point=sprite.globalToLocal(point); return point; } DisControlTool.isChildE=function(parent,child){ if (!parent)return false; while (child){ if (child.parent==parent)return true; child=child.parent; } return false; } DisControlTool.isInTree=function(pNode,child){ return pNode==child || DisControlTool.isChildE(pNode,child); } DisControlTool.setTop=function(tar){ if(tar&&tar.parent){ var tParent; tParent=tar.parent; tParent.setChildIndex(tar,tParent.numChildren-1); } } DisControlTool.clearItemRelativeInfo=function(item){ var Nan="NaN"; item.getLayout().left=Nan; item.getLayout().right=Nan; item.getLayout().top=Nan; item.getLayout().bottom=Nan; } DisControlTool.swap=function(tarA,tarB){ if (tarA==tarB)return; var iA=0; iA=tarA.parent.getChildIndex(tarA); var iB=0; iB=tarB.parent.getChildIndex(tarB); var bP; bP=tarB.parent; tarA.parent.addChildAt(tarB,iA); bP.addChildAt(tarA,iB); } DisControlTool.insertToTarParent=function(tarA,tars,after){ (after===void 0)&& (after=false); var tIndex=0; var parent; if(!tarA)return; parent=tarA.parent; if(!parent)return; tIndex=parent.getChildIndex(tarA); if(after)tIndex++; DisControlTool.insertToParent(parent,tars,tIndex); } DisControlTool.insertToParent=function(parent,tars,index){ (index===void 0)&& (index=-1); if(!parent)return; if(index<0)index=parent.numChildren; var i=0,len=0; len=tars.length; for(i=0;i=tParent.numChildren){ newIndex=tParent.numChildren-1; } console.log("setChildIndex:"+newIndex); tParent.setChildIndex(child,newIndex); } } DisControlTool.downDis=function(child){ if(child&&child.parent){ var tParent; tParent=child.parent; var newIndex=0; newIndex=tParent.getChildIndex(child)-1; if(newIndex<0)newIndex=0; console.log("setChildIndex:"+newIndex); tParent.setChildIndex(child,newIndex); } } DisControlTool.setResizeAbleEx=function(node){ var clickItem; clickItem=node.getChildByName("resizeBtn"); if (clickItem){ SimpleResizer.setResizeAble(clickItem,node); } } DisControlTool.setResizeAble=function(node){ node.on(/*laya.events.Event.CLICK*/"click",null,DisControlTool.resizeHandler,[node]); } DisControlTool.resizeHandler=function(tar){ DisResizer.setUp(tar); } DisControlTool.setDragingItem=function(dragBar,tar){ dragBar.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",null,DisControlTool.dragingHandler,[tar]); tar.on(/*laya.events.Event.DRAG_END*/"dragend",null,DisControlTool.dragingEnd,[tar]); } DisControlTool.dragingHandler=function(tar){ if (tar){ tar.startDrag(); } } DisControlTool.dragingEnd=function(tar){ DisControlTool.intFyDisPos(tar); console.log(tar.x,tar.y); } DisControlTool.showToStage=function(dis,offX,offY){ (offX===void 0)&& (offX=0); (offY===void 0)&& (offY=0); var rec=dis.getBounds(); dis.x=Laya.stage.mouseX+offX; dis.y=Laya.stage.mouseY+offY; if (dis.x+rec.width > Laya.stage.width){ dis.x-=rec.width+offX; } if (dis.y+rec.height > Laya.stage.height){ dis.y-=rec.height+offY; } DisControlTool.intFyDisPos(dis); } DisControlTool.intFyDisPos=function(dis){ if (!dis)return; dis.x=Math.round(dis.x); dis.y=Math.round(dis.y); } DisControlTool.showOnly=function(disList,showItem){ var i=0,len=0; len=disList.length; for (i=0;i < len;i++){ disList[i].visible=disList[i]==showItem; } } DisControlTool.showOnlyByIndex=function(disList,index){ DisControlTool.showOnly(disList,disList[index]); } DisControlTool.addOnly=function(disList,showItem,parent){ var i=0,len=0; len=disList.length; for (i=0;i < len;i++){ if (disList[i] !=showItem){ disList[i].removeSelf(); }else{ parent.addChild(disList[i]); } } } DisControlTool.addOnlyByIndex=function(disList,index,parent){ DisControlTool.addOnly(disList,disList[index],parent); } __static(DisControlTool, ['tempP',function(){return this.tempP=new Point();} ]); return DisControlTool; })() /** * *@author ww *@version 1.0 * *@created 2015-12-24 下午4:20:25 */ //class laya.debug.tools.DisEditor var DisEditor=(function(){ function DisEditor(){ this.tar=null; this.rec=new Sprite(); this.rootContainer=new Sprite(); } __class(DisEditor,'laya.debug.tools.DisEditor'); var __proto=DisEditor.prototype; __proto.setTarget=function(target){ this.tar=target; var g; g=this.rec.graphics; g.clear(); var bounds; bounds=this.tar.getSelfBounds(); g.drawRect(bounds.x,bounds.y,bounds.width,bounds.height,null,"#00ff00"); this.createSameDisChain(); Laya.stage.addChild(this.rootContainer); } __proto.createSameDisChain=function(){ var tParent; var cpParent; var preTar; preTar=this.rec; tParent=this.tar; while(tParent&&tParent!=Laya.stage){ cpParent=new Sprite(); cpParent.addChild(preTar); cpParent.x=tParent.x; cpParent.y=tParent.y; cpParent.scaleX=tParent.scaleX; cpParent.scaleY=tParent.scaleY; cpParent.rotation=tParent.rotation; cpParent.scrollRect=tParent.scrollRect; preTar=cpParent; tParent=tParent.parent; } this.rootContainer.removeChildren(); this.rootContainer.addChild(preTar); } return DisEditor; })() /** *调试拾取显示对象类 *@author ww */ //class laya.debug.tools.DisplayHook var DisplayHook=(function(){ function DisplayHook(){ this.mouseX=NaN; this.mouseY=NaN; this._stage=null; this._target=null; this.isGetting=false; this._matrix=new Matrix(); this._point=new Point(); this._rect=new Rectangle(); this._event=Event.EMPTY; this._stage=Laya.stage; this.init(Render.context.canvas); } __class(DisplayHook,'laya.debug.tools.DisplayHook'); var __proto=DisplayHook.prototype; __proto.init=function(canvas){ var _$this=this; if (Browser.window.navigator.msPointerEnabled){ canvas.style['-ms-content-zooming']='none'; canvas.style['-ms-touch-action']='none'; }; var _this=this; Browser.document.addEventListener('mousedown',function(e){ _$this._event._stoped=false; DisplayHook.isFirst=true; _this.check(_this._stage,e.offsetX,e.offsetY,_this.onMouseDown,true,false); },true); Browser.document.addEventListener('touchstart',function(e){ _$this._event._stoped=false; DisplayHook.isFirst=true; var touches=e.changedTouches; for (var i=0,n=touches.length;i < n;i++){ var touch=touches[i]; initEvent(touch,e); _this.check(_this._stage,_this.mouseX,_this.mouseY,_this.onMouseDown,true,false); } },true); function initEvent (e,event){ _this._event._stoped=false; _this._event.nativeEvent=event || e; _this._target=null; if (e.offsetX){ _this.mouseX=e.offsetX; _this.mouseY=e.offsetY; }else { _this.mouseX=e.clientX-Laya.stage.offset.x; _this.mouseY=e.clientY-Laya.stage.offset.y; } } } __proto.onMouseMove=function(ele,hit){ this.sendEvent(ele,/*laya.events.Event.MOUSE_MOVE*/"mousemove"); return; if (hit && ele !=this._stage && ele!==this._target){ if (this._target){ if (this._target.$_MOUSEOVER){ this._target.$_MOUSEOVER=false; this._target.event(/*laya.events.Event.MOUSE_OUT*/"mouseout"); } } this._target=ele; if (!ele.$_MOUSEOVER){ ele.$_MOUSEOVER=true; this.sendEvent(ele,/*laya.events.Event.MOUSE_OVER*/"mouseover"); } }else if (!hit && this._target && ele===this._target){ this._target=null; if (ele.$_MOUSEOVER){ ele.$_MOUSEOVER=false; this.sendEvent(ele,/*laya.events.Event.MOUSE_OUT*/"mouseout"); } } } __proto.onMouseUp=function(ele,hit){ hit && this.sendEvent(ele,/*laya.events.Event.MOUSE_UP*/"mouseup"); } __proto.onMouseDown=function(ele,hit){ if (hit){ ele.$_MOUSEDOWN=true; this.sendEvent(ele,/*laya.events.Event.MOUSE_DOWN*/"mousedown"); } } __proto.sendEvent=function(ele,type){ if (!this._event._stoped){ ele.event(type,this._event.setTo(type,ele,ele)); if (type===/*laya.events.Event.MOUSE_UP*/"mouseup" && ele.$_MOUSEDOWN){ ele.$_MOUSEDOWN=false; ele.event(/*laya.events.Event.CLICK*/"click",this._event.setTo(/*laya.events.Event.CLICK*/"click",ele,ele)); } } } __proto.selectDisUnderMouse=function(){ DisplayHook.isFirst=true; this.check(Laya.stage,Laya.stage.mouseX,Laya.stage.mouseY,null,true,false); SelectInfosView.I.setSelectTarget(DebugTool.target); } __proto.getDisUnderMouse=function(){ this.isGetting=true; DisplayHook.isFirst=true; DebugTool.target=null; this.check(Laya.stage,Laya.stage.mouseX,Laya.stage.mouseY,null,true,false); this.isGetting=false; return DebugTool.target; } __proto.check=function(sp,mouseX,mouseY,callBack,hitTest,mouseEnable){ if (sp==DebugTool.debugLayer)return false; if (sp==DebugInfoLayer.I)return false; if (this.isGetting && sp==DebugInfoLayer.I)return false; if (!sp.visible || sp.getSelfBounds().width<=0)return false; var isHit=false; mouseEnable=true if (mouseEnable){ var graphicHit=false; if (hitTest){ this._rect=sp.getBounds(); isHit=this._rect.contains(mouseX,mouseY); this._point.setTo(mouseX,mouseY); sp.fromParentPoint(this._point); mouseX=this._point.x; mouseY=this._point.y; } if (isHit){ var flag=false; for (var i=sp._childs.length-1;i >-1;i--){ var child=sp._childs[i]; (flag=this.check(child,mouseX,mouseY,callBack,hitTest,true)); if (flag)break ; } graphicHit=sp.getGraphicBounds().contains(mouseX,mouseY); isHit=flag||graphicHit; if(isHit&&!flag&&DisplayHook.isFirst){ DisplayHook.isFirst=false; if(! ((sp instanceof laya.debug.tools.debugUI.DButton ))){ DebugTool.target=sp; if (!this.isGetting){ DebugTool.autoWork(); Notice.notify("ItemClicked",sp); } } } } } return isHit; } DisplayHook.initMe=function(){ if(!DisplayHook.instance){ DisplayHook.instance=new DisplayHook(); } } DisplayHook.ITEM_CLICKED="ItemClicked"; DisplayHook.instance=null; DisplayHook.isFirst=false; return DisplayHook; })() /** *简单的显示对象对象池 *从父容器上移除时即被视为可被重用 *@author ww *@version 1.0 * *@created 2015-11-13 下午8:05:13 */ //class laya.debug.tools.DisPool var DisPool=(function(){ function DisPool(){} __class(DisPool,'laya.debug.tools.DisPool'); DisPool.getDis=function(clz){ var clzName; clzName=ClassTool.getClassNameByClz(clz); if(!DisPool._objDic[clzName]){ DisPool._objDic[clzName]=[]; }; var disList; disList=DisPool._objDic[clzName]; var i=0,len=0; len=disList.length; for(i=0;i0&& SpriteRenderForVisibleAnalyse.tarRec.height > 0){ SpriteRenderForVisibleAnalyse.isTarRecOK=true; SpriteRenderForVisibleAnalyse.preImageData=CanvasTools.getImageDataFromCanvasByRec(SpriteRenderForVisibleAnalyse.mainCanvas,SpriteRenderForVisibleAnalyse.tarRec); SpriteRenderForVisibleAnalyse.tarImageData=CanvasTools.getImageDataFromCanvasByRec(SpriteRenderForVisibleAnalyse.mainCanvas,SpriteRenderForVisibleAnalyse.tarRec); }else{ console.log("tarRec Not OK:",SpriteRenderForVisibleAnalyse.tarRec); } }else{ if (SpriteRenderForVisibleAnalyse.isTarRecOK){ SpriteRenderForVisibleAnalyse.tImageData=CanvasTools.getImageDataFromCanvasByRec(SpriteRenderForVisibleAnalyse.mainCanvas,SpriteRenderForVisibleAnalyse.tarRec); var dRate=NaN; dRate=CanvasTools.getDifferRate(SpriteRenderForVisibleAnalyse.preImageData,SpriteRenderForVisibleAnalyse.tImageData); SpriteRenderForVisibleAnalyse.preImageData=SpriteRenderForVisibleAnalyse.tImageData; if (dRate > 0){ VisibleAnalyser.addCoverNode(me,dRate); } } } } __proto.analyseNode=function(node){ VisibleAnalyser.resetCoverList(); if (Sprite["prototype"]["render"] !=SpriteRenderForVisibleAnalyse.I.render){ this.preFun=Sprite["prototype"]["render"]; } this.target=node; Sprite["prototype"]["render"]=this.render; if (!SpriteRenderForVisibleAnalyse.tarCanvas) SpriteRenderForVisibleAnalyse.tarCanvas=CanvasTools.createCanvas(Laya.stage.width,Laya.stage.height); if (!SpriteRenderForVisibleAnalyse.mainCanvas) SpriteRenderForVisibleAnalyse.mainCanvas=CanvasTools.createCanvas(Laya.stage.width,Laya.stage.height); this.isTargetRenderd=false; SpriteRenderForVisibleAnalyse.isVisibleTesting=true; SpriteRenderForVisibleAnalyse.allowRendering=false; CanvasTools.clearCanvas(SpriteRenderForVisibleAnalyse.mainCanvas); CanvasTools.clearCanvas(SpriteRenderForVisibleAnalyse.tarCanvas); SpriteRenderForVisibleAnalyse.isTarRecOK=false; var ctx=new RenderContext(SpriteRenderForVisibleAnalyse.mainCanvas.width,SpriteRenderForVisibleAnalyse.mainCanvas.height,SpriteRenderForVisibleAnalyse.mainCanvas); SpriteRenderForVisibleAnalyse.mainCanvas=ctx.canvas; this.render.call(Laya.stage,ctx,0,0); if (!SpriteRenderForVisibleAnalyse.isTarRecOK){ SpriteRenderForVisibleAnalyse.coverRate=0; }else{ SpriteRenderForVisibleAnalyse.coverRate=CanvasTools.getDifferRate(SpriteRenderForVisibleAnalyse.preImageData,SpriteRenderForVisibleAnalyse.tarImageData); } VisibleAnalyser.coverRate=SpriteRenderForVisibleAnalyse.coverRate; VisibleAnalyser.isTarRecOK=SpriteRenderForVisibleAnalyse.isTarRecOK; console.log("coverRate:",SpriteRenderForVisibleAnalyse.coverRate); this.isTargetRenderd=false; SpriteRenderForVisibleAnalyse.isVisibleTesting=false; SpriteRenderForVisibleAnalyse.allowRendering=true; Sprite["prototype"]["render"]=this.preFun; } __proto.noRenderMode=function(){ return; RenderSprite["prototype"]["_graphics"]=this.m_graphics; RenderSprite["prototype"]["_image"]=this.m_image; RenderSprite["prototype"]["_image2"]=this.m_image2; } __proto.normalMode=function(){ RenderSprite["prototype"]["_graphics"]=this.pgraphic; RenderSprite["prototype"]["_image"]=this.pimage; RenderSprite["prototype"]["_image2"]=this.pimage2; } __proto.inits=function(){ this.noRenderMode(); } __proto.m_graphics=function(sprite,context,x,y){ if (laya.debug.tools.enginehook.SpriteRenderForVisibleAnalyse.allowRendering){ var tf=sprite._style._tf; sprite._graphics && sprite._graphics._render(sprite,context,x-tf.translateX,y-tf.translateY); }; var next=this._next; next._fun.call(next,sprite,context,x,y); } __proto.m_image=function(sprite,context,x,y){ if (laya.debug.tools.enginehook.SpriteRenderForVisibleAnalyse.allowRendering){ var style=sprite._style; context.ctx.drawTexture2(x,y,style._tf.translateX,style._tf.translateY,sprite.transform,style.alpha,style.blendMode,sprite._graphics._one); } } __proto.m_image2=function(sprite,context,x,y){ if (laya.debug.tools.enginehook.SpriteRenderForVisibleAnalyse.allowRendering){ var tf=sprite._style._tf; context.ctx.drawTexture2(x,y,tf.translateX,tf.translateY,sprite.transform,1,null,sprite._graphics._one); } } SpriteRenderForVisibleAnalyse.tarCanvas=null; SpriteRenderForVisibleAnalyse.mainCanvas=null; SpriteRenderForVisibleAnalyse.preImageData=null; SpriteRenderForVisibleAnalyse.tImageData=null; SpriteRenderForVisibleAnalyse.tarImageData=null; SpriteRenderForVisibleAnalyse.tarRec=null; SpriteRenderForVisibleAnalyse.isTarRecOK=false; SpriteRenderForVisibleAnalyse.isVisibleTesting=false; SpriteRenderForVisibleAnalyse.allowRendering=true; SpriteRenderForVisibleAnalyse.coverRate=NaN; __static(SpriteRenderForVisibleAnalyse, ['I',function(){return this.I=new SpriteRenderForVisibleAnalyse();} ]); return SpriteRenderForVisibleAnalyse; })() /** *... *@author ww */ //class laya.debug.tools.enginehook.SpriteRenderHook var SpriteRenderHook=(function(){ function SpriteRenderHook(){ /**@private */ this._repaint=1; this._renderType=1; this._x=0; this._y=0; } __class(SpriteRenderHook,'laya.debug.tools.enginehook.SpriteRenderHook'); var __proto=SpriteRenderHook.prototype; /** *更新、呈现显示对象。 *@param context 渲染的上下文引用。 *@param x X轴坐标。 *@param y Y轴坐标。 */ __proto.render=function(context,x,y){ if ((this)==Laya.stage){ CacheAnalyser.renderLoopBegin(); }; var preTime=0; preTime=Browser.now(); Stat.spriteCount++; if (this["ShowBorderSign"]){ DebugTool.showDisBoundToSprite(this,DebugInfoLayer.I.cacheViewLayer,DebugConsts.SPRITE_REC_COLOR,DebugConsts.SPRITE_REC_LINEWIDTH); } RenderSprite.renders[this._renderType]._fun(this,context,x+this._x,y+this._y); this._repaint=0; RenderAnalyser.I.render(this,Browser.now()-preTime); } SpriteRenderHook.init=function(){ if (SpriteRenderHook.I)return; SpriteRenderHook.I=new SpriteRenderHook(); SpriteRenderHook.setRenderHook(); } SpriteRenderHook.setRenderHook=function(){ Sprite["prototype"]["render"]=SpriteRenderHook.I.render; } SpriteRenderHook.showDisplayBorder=function(sprite,ifShowBorder){ (ifShowBorder===void 0)&& (ifShowBorder=true); sprite["ShowBorderSign"]=ifShowBorder; } SpriteRenderHook.isDisplayShowBorder=function(sprite){ return sprite["ShowBorderSign"]; } SpriteRenderHook.I=null; SpriteRenderHook.ShowBorderSign="ShowBorderSign"; return SpriteRenderHook; })() /** *本类调用原生observe接口,仅支持部分浏览器,chrome有效 *变化输出为异步方式,所以无法跟踪到是什么函数导致变化 *@author ww *@version 1.0 * *@created 2015-10-26 上午9:35:45 */ //class laya.debug.tools.exp.Observer var Observer=(function(){ function Observer(){} __class(Observer,'laya.debug.tools.exp.Observer'); Observer.observe=function(obj,callBack){ /*__JS__ */Object.observe(obj,callBack); } Observer.unobserve=function(obj,callBack){ /*__JS__ */Object.unobserve(obj,callBack); } Observer.observeDiffer=function(obj,sign,msg){ (msg===void 0)&& (msg="obDiffer"); var differFun=function (){ DifferTool.differ(sign,obj,msg); } Observer.observe(obj,differFun); } return Observer; })() /** *本类调用原生watch接口,仅火狐有效 *@author ww *@version 1.0 * *@created 2015-10-26 上午9:48:18 */ //class laya.debug.tools.exp.Watch var Watch=(function(){ function Watch(){} __class(Watch,'laya.debug.tools.exp.Watch'); Watch.watch=function(obj,name,callBack){ /*__JS__ */obj.watch(name,callBack); } Watch.unwatch=function(obj,name,callBack){ /*__JS__ */obj.unwatch(name,callBack); } return Watch; })() /** * *@author ww *@version 1.0 * *@created 2015-10-30 下午1:06:56 */ //class laya.debug.tools.FilterTool var FilterTool=(function(){ function FilterTool(){} __class(FilterTool,'laya.debug.tools.FilterTool'); FilterTool.getArrByFilter=function(arr,filterFun){ var i=0,len=arr.length; var rst=[]; for(i=0;i=0;i--){ if (GetSetProfile.noDisplayKeys[arr[i]]){ arr.splice(i,1); } } } GetSetProfile.getClassCount=function(className){ return GetSetProfile.countDic[className]; } GetSetProfile.addClassCount=function(className){ if (!GetSetProfile.countDic[className]){ GetSetProfile.countDic[className]=1; } else { GetSetProfile.countDic[className]=GetSetProfile.countDic[className]+1; } } GetSetProfile.init=function(){ if (GetSetProfile._inited) return; GetSetProfile._inited=true; var createFun=function (sp){ GetSetProfile.classCreated(sp); } FunHook.hook(Node,"call",null,createFun); GetSetProfile.handlerO={}; GetSetProfile.handlerO["get"]=function (target,key,receiver){ console.log("get",target,key,receiver); return /*__JS__ */Reflect.get(target,key,receiver); }; GetSetProfile.handlerO["set"]=function (target,key,value,receiver){ console.log("set",target,key,value,receiver); return /*__JS__ */Reflect.set(target,key,value,receiver); } } GetSetProfile.classCreated=function(obj,oClas){ if (GetSetProfile.fromMe) return; var className; className=ClassTool.getClassName(obj); GetSetProfile.addClassCount(className); GetSetProfile.addClassCount("ALL"); IDTools.idObj(obj); var classDes; classDes=GetSetProfile.hookClassDic[className]; if (!classDes){ GetSetProfile.profileClass(obj["constructor"]); classDes=GetSetProfile.hookClassDic[className]; if (!classDes) return; } GetSetProfile.hookObj2(obj,classDes); } GetSetProfile.hookObj=function(obj,keys){ var handler=GetSetProfile.handlerO; /*__JS__ */new Proxy(obj,handler); } GetSetProfile.hookObj2=function(obj,keys){ var i=0,len=0; len=keys.length; for (i=0;i < len;i++){ GetSetProfile.hookVar(obj,keys[i]); } } GetSetProfile.profileClass=function(clz){ var className; className=ClassTool.getClassName(clz); GetSetProfile.fromMe=true; var tO=new clz(); GetSetProfile.fromMe=false; var keys; keys=ClassTool.getObjectDisplayAbleKeys(tO); keys=ObjectTools.getNoSameArr(keys); var i=0,len=0; len=keys.length; var tV; var key; for (i=len-1;i >=0;i--){ key=keys[i]; tV=tO[key]; if ((typeof tV=='function')){ keys.splice(i,1); } } len=keys.length; GetSetProfile.removeNoDisplayKeys(keys); GetSetProfile.hookClassDic[className]=keys; } GetSetProfile.hookPrototype=function(tO,key){ console.log("hook:",key); try { GetSetProfile.hookVar(tO,key); } catch (e){ console.log("fail",key); } } GetSetProfile.reportCall=function(obj,name,type){ IDTools.idObj(obj); var objID=0; objID=IDTools.getObjID(obj); var className; className=ClassTool.getClassName(obj); GetSetProfile.recordInfo(className,name,type,objID); GetSetProfile.recordInfo("ALL",name,type,objID); } GetSetProfile.recordInfo=function(className,name,type,objID){ var propCallsDic; if (!GetSetProfile.infoDic[className]){ GetSetProfile.infoDic[className]={}; } propCallsDic=GetSetProfile.infoDic[className]; var propCalls; if (!propCallsDic[name]){ propCallsDic[name]={}; } propCalls=propCallsDic[name]; var propCallO; if (!propCalls[type]){ propCalls[type]={}; } propCallO=propCalls[type]; if (!propCallO[objID]){ propCallO[objID]=1; if (!propCallO["objCount"]){ propCallO["objCount"]=1; } else { propCallO["objCount"]=propCallO["objCount"]+1; } } else { propCallO[objID]=propCallO[objID]+1; } if (!propCallO["count"]){ propCallO["count"]=1; } else { propCallO["count"]=propCallO["count"]+1; } } GetSetProfile.showInfo=function(){ var rstO; rstO={}; var rstO1; rstO1={}; var arr; arr=[]; var arr1; arr1=[]; var className; var keyName; var type; for (className in GetSetProfile.infoDic){ var tClassO; var tClassO1; tClassO=GetSetProfile.infoDic[className]; rstO[className]=tClassO1={}; for (keyName in tClassO){ var tKeyO; var tKeyO1; tKeyO=tClassO[keyName]; tClassO1[keyName]=tKeyO1={}; for(type in tKeyO){ var tDataO; var tDataO1; tDataO=tKeyO[type]; tDataO["rate"]=tDataO["objCount"] / GetSetProfile.getClassCount(className); tKeyO1[type]=tDataO["rate"]; var tSKey; tSKey=className+"_"+keyName+"_"+type; rstO1[tSKey]=tDataO["rate"]; if (className=="ALL"){ if (type=="get"){ arr.push([tSKey,tDataO["rate"],tDataO["count"]]); }else{ arr1.push([tSKey,tDataO["rate"],tDataO["count"]]); } } } } } console.log(GetSetProfile.infoDic); console.log(GetSetProfile.countDic); console.log(rstO); console.log(rstO1); console.log("nodeCount:",GetSetProfile.getClassCount("ALL")); console.log("sort by rate"); GetSetProfile.showStaticInfo(arr,arr1,"1"); console.log("sort by count"); GetSetProfile.showStaticInfo(arr,arr1,"2"); } GetSetProfile.showStaticInfo=function(arr,arr1,sortKey){ console.log("get:"); GetSetProfile.showStaticArray(arr,sortKey); console.log("set:"); GetSetProfile.showStaticArray(arr1,sortKey); } GetSetProfile.showStaticArray=function(arr,sortKey){ (sortKey===void 0)&& (sortKey="1"); arr.sort(MathUtil.sortByKey(sortKey,true,true)); var i=0,len=0; len=arr.length; var tArr; for (i=0;i < len;i++){ tArr=arr[i]; console.log(tArr[0],Math.floor(tArr[1]*100),tArr[2]); } } GetSetProfile.hookVar=function(obj,name,setHook,getHook){ if (!setHook) setHook=[]; if (!getHook) getHook=[]; var preO=obj; var preValue; var newKey="___@"+newKey; var des; des=ClassTool.getOwnPropertyDescriptor(obj,name); var ndes={}; var mSet=function (value){ preValue=value; }; var mGet=function (){ return preValue; }; var mSet1=function (value){ var _t=/*__JS__ */this; GetSetProfile.reportCall(_t,name,"set"); }; var mGet1=function (){ var _t=/*__JS__ */this; GetSetProfile.reportCall(_t,name,"get"); return preValue; } getHook.push(mGet1); setHook.push(mSet1); while (!des && obj["__proto__"]){ obj=obj["__proto__"]; des=ClassTool.getOwnPropertyDescriptor(obj,name); } if (des){ ndes.set=des.set ? des.set :mSet; ndes.get=des.get ? des.get :mGet; if (!des.get){ preValue=preO[name]; } ndes.enumerable=des.enumerable; setHook.push(ndes.set); getHook.push(ndes.get); FunHook.hookFuns(ndes,"set",setHook); FunHook.hookFuns(ndes,"get",getHook,getHook.length-1); ClassTool.defineProperty(preO,name,ndes); } if (!des){ ndes.set=mSet; ndes.get=mGet; preValue=preO[name]; setHook.push(ndes.set); getHook.push(ndes.get); FunHook.hookFuns(ndes,"set",setHook); FunHook.hookFuns(ndes,"get",getHook,getHook.length-1); ClassTool.defineProperty(preO,name,ndes); } } GetSetProfile._inited=false; GetSetProfile.handlerO=null; GetSetProfile.ALL="ALL"; GetSetProfile.countDic={}; GetSetProfile.fromMe=false; GetSetProfile.hookClassDic={}; GetSetProfile.infoDic={}; __static(GetSetProfile, ['noDisplayKeys',function(){return this.noDisplayKeys={"conchModel":true};} ]); return GetSetProfile; })() /** *本类用于在对象的函数上挂钩子 *@author ww *@version 1.0 * *@created 2015-10-23 下午1:13:13 */ //class laya.debug.tools.hook.FunHook var FunHook=(function(){ function FunHook(){} __class(FunHook,'laya.debug.tools.hook.FunHook'); FunHook.hook=function(obj,funName,preFun,aftFun){ FunHook.hookFuns(obj,funName,[preFun,obj[funName],aftFun],1); } FunHook.hookAllFun=function(obj){ var key; var arr; arr=ClassTool.getOwnPropertyNames(obj); for(key in arr){ key=arr[key]; if (FunHook.special[key])continue ; console.log("try hook:",key); if((typeof (obj[key])=='function')){ console.log("hook:",key); FunHook.hookFuns(obj,key,[FunHook.getTraceMsg("call:"+key),obj[key]],1); } } if(obj["__proto__"]){ FunHook.hookAllFun(obj["__proto__"]); }else{ console.log("end:",obj); } } FunHook.getTraceMsg=function(msg){ var rst; rst=function (){ console.log(msg); } return rst; } FunHook.hookFuns=function(obj,funName,funList,rstI){ (rstI===void 0)&& (rstI=-1); var _preFun=obj[funName]; var newFun; newFun=function (__args){ var args=arguments; var rst; var i=0; var len=0; len=funList.length; for(i=0;i 0)return JSTools._pixelRatio; var canvas=Browser.createElement("canvas"); var context=canvas.getContext('2d'); var devicePixelRatio=Browser.window.devicePixelRatio || 1; var backingStoreRatio=context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; var ratio=devicePixelRatio / backingStoreRatio; console.log("pixelRatioc:",ratio); JSTools._pixelRatio=ratio; return ratio; } JSTools._pixelRatio=-1; return JSTools; })() /** *布局工具类,目前只支持水平方向布局 *@author ww */ //class laya.debug.tools.layout.Layouter var Layouter=(function(){ function Layouter(){ /** *布局用的数据,与布局方法有关 */ this.data=null; /** *布局涉及的对象 */ this._items=null; /** *布局用的函数 */ this.layoutFun=null; /** *布局起始x */ this._sX=0; /** *布局宽 */ this._width=0; } __class(Layouter,'laya.debug.tools.layout.Layouter'); var __proto=Layouter.prototype; __proto.layout=function(){ this.layoutFun(this._width,this._items,this.data,this._sX); } /** *重新布局 * */ __proto.changed=function(){ Laya.timer.callLater(this,this.layout); } /** *根据当前的对象状态计算位置大小 * */ __proto.calSize=function(){ var i=0,len=0; var tItem; tItem=this.items[0]; this._sX=tItem.x; var maxX=NaN; maxX=this._sX+tItem.width; len=this.items.length; for (i=1;i < len;i++){ tItem=this.items[i]; if (this._sX > tItem.x){ this._sX=tItem.x; } if (maxX < tItem.x+tItem.width){ maxX=tItem.x+tItem.width; } } this._width=maxX-this._sX; } __getset(0,__proto,'width',function(){ return this._width; },function(v){ this._width=v; this.changed(); }); __getset(0,__proto,'x',function(){ return this._sX; },function(v){ this._sX=v; this.changed(); }); __getset(0,__proto,'items',function(){ return this._items; },function(arr){ this._items=arr; this.calSize(); }); return Layouter; })() /** *... *@author ww */ //class laya.debug.tools.layout.LayoutFuns var LayoutFuns=(function(){ function LayoutFuns(){} __class(LayoutFuns,'laya.debug.tools.layout.LayoutFuns'); LayoutFuns.sameWidth=function(totalWidth,items,data,sX){ (sX===void 0)&& (sX=0); var dWidth=0; if (data && data.dWidth) dWidth=data.dWidth; var perWidth=NaN; perWidth=(totalWidth-(items.length-1)*dWidth)/ items.length; var tItem; var i=0,len=0; var tX=NaN; tX=sX; len=items.length; for (i=0;i < len;i++){ tItem=items[i]; tItem.x=tX; tItem.width=perWidth; tX+=dWidth+perWidth; } } LayoutFuns.getSameWidthLayout=function(items,dWidth){ var data; data={}; data.dWidth=dWidth; return LayoutFuns.getLayouter(items,data,laya.debug.tools.layout.LayoutFuns.sameWidth); } LayoutFuns.getLayouter=function(items,data,fun){ var layouter; layouter=new Layouter(); layouter.items=items; layouter.data=data; layouter.layoutFun=fun; return layouter; } LayoutFuns.sameDis=function(totalWidth,items,data,sX){ (sX===void 0)&& (sX=0); var dWidth=NaN; dWidth=totalWidth; var tItem; var i=0,len=0; len=items.length; LayoutFuns.prepareForLayoutWidth(totalWidth,items); for (i=0;i < len;i++){ tItem=items[i]; dWidth-=tItem.width; } if (items.length > 1) dWidth=dWidth / (items.length-1); var tX=NaN; tX=sX; len=items.length; for (i=0;i < len;i++){ tItem=items[i]; tItem.x=tX; tX+=dWidth+tItem.width; } } LayoutFuns.getSameDisLayout=function(items,rateSame){ (rateSame===void 0)&& (rateSame=false); var data; data={}; if (rateSame){ var i=0,len=0; len=items.length; var tItem; var totalWidth=NaN; totalWidth=0; for (i=0;i < len;i++){ tItem=items[i]; totalWidth+=tItem.width; } totalWidth=tItem.x+tItem.width; for (i=0;i < len;i++){ tItem=items[i]; LayoutFuns.setItemRate(tItem,tItem.width / totalWidth); } } return LayoutFuns.getLayouter(items,data,laya.debug.tools.layout.LayoutFuns.sameDis); } LayoutFuns.fullFill=function(totalWidth,items,data,sX){ (sX===void 0)&& (sX=0); var dL=0,dR=0; if (data){ if (data.dL) dL=data.dL; if (data.dR) dR=data.dR; }; var item; var i=0,len=0; len=items.length; for (i=0;i < len;i++){ item=items[i]; item.x=sX+dL; item.width=totalWidth-dL-dR; } } LayoutFuns.getFullFillLayout=function(items,dL,dR){ (dL===void 0)&& (dL=0); (dR===void 0)&& (dR=0); var data; data={}; data.dL=dL; data.dR=dR; return LayoutFuns.getLayouter(items,data,laya.debug.tools.layout.LayoutFuns.fullFill); } LayoutFuns.fixPos=function(totalWidth,items,data,sX){ (sX===void 0)&& (sX=0); var dLen=0; var poss=[]; var isRate=false; if (data){ if (data.dLen) dLen=data.dLen; if (data.poss) poss=data.poss; if (data.isRate) isRate=data.isRate; }; var item; var i=0,len=0; len=poss.length; var tX=NaN; tX=sX; var tValue=NaN; var preItem; preItem=null; for (i=0;i < len;i++){ item=items[i]; tValue=sX+poss[i]; if (isRate){ tValue=sX+poss[i] *totalWidth; } item.x=tValue; if (preItem){ preItem.width=item.x-dLen-preItem.x; } preItem=item; }; var lastItem; lastItem=items[items.length-1]; lastItem.width=sX+totalWidth-dLen-lastItem.x; } LayoutFuns.getFixPos=function(items,dLen,isRate,poss){ (dLen===void 0)&& (dLen=0); (isRate===void 0)&& (isRate=false); var data; data={}; var layout; layout=LayoutFuns.getLayouter(items,data,LayoutFuns.fixPos); var i=0,len=0; var sX=NaN; var totalWidth=NaN; sX=layout.x; totalWidth=layout.width; if (!poss){ poss=[]; len=items.length; var tValue=NaN; for (i=0;i < len;i++){ tValue=items[i].x-sX; if (isRate){ tValue=tValue / totalWidth; } else{ } poss.push(tValue); } } data.dLen=dLen; data.poss=poss; data.isRate=isRate; return layout; } LayoutFuns.clearItemsRelativeInfo=function(items){ var i=0,len=0; len=items.length; for (i=0;i < len;i++){ LayoutFuns.clearItemRelativeInfo(items[i]); } } LayoutFuns.clearItemRelativeInfo=function(item){ var Nan="NaN"; item.getLayout().left=Nan; item.getLayout().right=Nan; } LayoutFuns.prepareForLayoutWidth=function(totalWidth,items){ var i=0,len=0; len=items.length; for (i=0;i < len;i++){ LayoutFuns.prepareItemForLayoutWidth(totalWidth,items[i]); } } LayoutFuns.getSumWidth=function(items){ var sum=NaN; sum=0; var i=0,len=0; len=items.length; for (i=0;i < len;i++){ sum+=items[i].width; } return sum; } LayoutFuns.prepareItemForLayoutWidth=function(totalWidth,item){ if (LayoutFuns.getItemRate(item)> 0){ item.width=totalWidth *LayoutFuns.getItemRate(item); } } LayoutFuns.setItemRate=function(item,rate){ item["layoutRate"]=rate; } LayoutFuns.getItemRate=function(item){ return item["layoutRate"] ? item["layoutRate"] :-1; } LayoutFuns.setItemFreeSize=function(item,free){ (free===void 0)&& (free=true); item["layoutFreeSize"]=free; } LayoutFuns.isItemFreeSize=function(item){ return item["layoutFreeSize"]; } LayoutFuns.lockedDis=function(totalWidth,items,data,sX){ (sX===void 0)&& (sX=0); var dists; dists=data.dists; var sumDis=NaN; sumDis=data.sumDis; var sumWidth=NaN; var i=0,len=0; var tItem; var preItem; LayoutFuns.prepareForLayoutWidth(totalWidth,items); sumWidth=LayoutFuns.getSumWidth(items); var dWidth=NaN; dWidth=totalWidth-sumDis-sumWidth; var freeItem; freeItem=LayoutFuns.getFreeItem(items); if(freeItem){ freeItem.width+=dWidth; } preItem=items[0]; preItem.x=sX; len=items.length; for(i=1;i maxHeight){ maxHeight=tItem.height; } tCount++; if (tCount >=xCount){ tCount=tCount % xCount; tItem.y+=maxHeight+dY; maxHeight=0; }else{ tX+=tItem.width+dx; } } } LayoutTools.layoutToWidth=function(items,width,dX,dY,sx,sy){ var tX=NaN,tY=NaN; var tItem; var i=0,len=0; tX=sx; tY=sy; len=items.length; for(i=0;iwidth){ tX=sx; tY+=dY+tItem.height; }else{ } tItem.x=tX; tItem.y=tY; tX+=dX+tItem.width; } } return LayoutTools; })() /** *... *@author ww */ //class laya.debug.tools.MathTools var MathTools=(function(){ function MathTools(){} __class(MathTools,'laya.debug.tools.MathTools'); MathTools.sortBigFirst=function(a,b){ if (a==b) return 0; return b > a ? 1 :-1; } MathTools.sortSmallFirst=function(a,b){ if (a==b) return 0; return b > a ?-1 :1; } MathTools.sortNumBigFirst=function(a,b){ return parseFloat(b)-parseFloat(a); } MathTools.sortNumSmallFirst=function(a,b){ return parseFloat(a)-parseFloat(b); } MathTools.sortByKey=function(key,bigFirst,forceNum){ (bigFirst===void 0)&& (bigFirst=false); (forceNum===void 0)&& (forceNum=true); var _sortFun; if (bigFirst){ _sortFun=forceNum ? MathTools.sortNumBigFirst :MathTools.sortBigFirst; }else { _sortFun=forceNum ? MathTools.sortNumSmallFirst :MathTools.sortSmallFirst; } return function (a,b){ return _sortFun(a[key],b[key]); }; } return MathTools; })() /** *... *@author ww */ //class laya.debug.tools.MouseEventAnalyser var MouseEventAnalyser=(function(){ function MouseEventAnalyser(){} __class(MouseEventAnalyser,'laya.debug.tools.MouseEventAnalyser'); MouseEventAnalyser.analyseNode=function(node){ DebugTool.showDisBound(node,true); var _node; _node=node; ObjectTools.clearObj(MouseEventAnalyser.infoO); ObjectTools.clearObj(MouseEventAnalyser.nodeO); ObjectTools.clearObj(MouseEventAnalyser.hitO); var nodeList; nodeList=[]; while (node){ IDTools.idObj(node); MouseEventAnalyser.nodeO[IDTools.getObjID(node)]=node; nodeList.push(node); node=node.parent; } MouseEventAnalyser.check(Laya.stage,Laya.stage.mouseX,Laya.stage.mouseY,null); var canStr; if (MouseEventAnalyser.hitO[IDTools.getObjID(_node)]){ console.log("can hit"); canStr="can hit"; } else{ console.log("can't hit"); canStr="can't hit"; }; var i=0,len=0; nodeList=nodeList.reverse(); len=nodeList.length; var rstTxts; rstTxts=["[分析对象]:"+ClassTool.getNodeClassAndName(_node)+":"+canStr]; for (i=0;i < len;i++){ node=nodeList[i]; if (MouseEventAnalyser.hitO[IDTools.getObjID(node)]){ console.log("can hit:",ClassTool.getNodeClassAndName(node)); console.log("原因:",MouseEventAnalyser.infoO[IDTools.getObjID(node)]); rstTxts.push("can hit:"+" "+ClassTool.getNodeClassAndName(node)); rstTxts.push("原因:"+" "+MouseEventAnalyser.infoO[IDTools.getObjID(node)]); } else{ console.log("can't hit:"+ClassTool.getNodeClassAndName(node)); console.log("原因:",MouseEventAnalyser.infoO[IDTools.getObjID(node)] ? MouseEventAnalyser.infoO[IDTools.getObjID(node)] :"鼠标事件在父级已停止派发"); rstTxts.push("can't hit:"+" "+ClassTool.getNodeClassAndName(node)); rstTxts.push("原因:"+" "+(MouseEventAnalyser.infoO[IDTools.getObjID(node)] ? MouseEventAnalyser.infoO[IDTools.getObjID(node)] :"鼠标事件在父级已停止派发")); } }; var rstStr; rstStr=rstTxts.join("\n"); ToolPanel.I.showTxtInfo(rstStr); } MouseEventAnalyser.check=function(sp,mouseX,mouseY,callBack){ IDTools.idObj(sp); var isInAnlyseChain=false; isInAnlyseChain=MouseEventAnalyser.nodeO[IDTools.getObjID(sp)]; MouseEventAnalyser._point.setTo(mouseX,mouseY); sp.fromParentPoint(MouseEventAnalyser._point); mouseX=MouseEventAnalyser._point.x; mouseY=MouseEventAnalyser._point.y; var scrollRect=sp.scrollRect; if (scrollRect){ MouseEventAnalyser._rect.setTo(scrollRect.x,scrollRect.y,scrollRect.width,scrollRect.height); var isHit=MouseEventAnalyser._rect.contains(mouseX,mouseY); if (!isHit){ if (isInAnlyseChain){ MouseEventAnalyser.infoO[IDTools.getObjID(sp)]="scrollRect没有包含鼠标"+MouseEventAnalyser._rect.toString()+":"+mouseX+","+mouseY; } return false; } }; var i=0,len=0; var cList; cList=sp._childs; len=cList.length; var child; var childInChain; childInChain=null; for (i=0;i < len;i++){ child=cList[i]; IDTools.idObj(child); if (MouseEventAnalyser.nodeO[IDTools.getObjID(child)]){ childInChain=child; break ; } }; var coverByOthers=false; coverByOthers=childInChain ? true :false; var flag=false; if (sp.hitTestPrior && !sp.mouseThrough && !MouseEventAnalyser.hitTest(sp,mouseX,mouseY)){ MouseEventAnalyser.infoO[IDTools.getObjID(sp)]="hitTestPrior=true,宽高区域不包含鼠标:"+":"+mouseX+","+mouseY+" size:"+sp.width+","+sp.height; return false; } for (i=sp._childs.length-1;i >-1;i--){ child=sp._childs[i]; if (child==childInChain){ if (!childInChain.mouseEnabled){ MouseEventAnalyser.infoO[IDTools.getObjID(childInChain)]="mouseEnabled=false"; } if (!childInChain.visible){ MouseEventAnalyser.infoO[IDTools.getObjID(childInChain)]="visible=false"; } coverByOthers=false; } if (child.mouseEnabled && child.visible){ flag=MouseEventAnalyser.check(child,mouseX ,mouseY,callBack); if (flag){ MouseEventAnalyser.hitO[IDTools.getObjID(sp)]=true; MouseEventAnalyser.infoO[IDTools.getObjID(sp)]="子对象被击中"; if (child==childInChain){ MouseEventAnalyser.infoO[IDTools.getObjID(sp)]="子对象被击中,"+"击中对象在分析链中"; } else{ MouseEventAnalyser.infoO[IDTools.getObjID(sp)]="子对象被击中,"+"击中对象不在分析链中"; if (coverByOthers){ MouseEventAnalyser.infoO[IDTools.getObjID(childInChain)]="被兄弟节点挡住,兄弟节点信息:"+ClassTool.getNodeClassAndName(child)+","+child.getBounds().toString(); DebugTool.showDisBound(child,false,"#ffff00"); } } return true; } else{ if (child==childInChain){ coverByOthers=false; } } } }; var mHitRect=new Rectangle(); var graphicHit=false; graphicHit=sp.getGraphicBounds().contains(mouseX,mouseY); if (sp.width > 0 && sp.height > 0){ var hitRect=MouseEventAnalyser._rect; if (!sp.mouseThrough){ if (sp.hitArea) hitRect=sp.hitArea; else hitRect.setTo(0,0,sp.width,sp.height); mHitRect.copyFrom(hitRect); isHit=hitRect.contains(mouseX,mouseY); } else{ isHit=graphicHit; mHitRect.copyFrom(sp.getGraphicBounds()); } if (isHit){ MouseEventAnalyser.hitO[IDTools.getObjID(sp)]=true; } }else{ } if (!isHit){ if (graphicHit){ MouseEventAnalyser.infoO[IDTools.getObjID(sp)]="子对象未包含鼠标,实际绘图区域包含鼠标,设置的宽高区域不包含鼠标:"+":"+mouseX+","+mouseY+" hitRec:"+mHitRect.toString()+" graphicBounds:"+sp.getGraphicBounds().toString()+",设置mouseThrough=true或将宽高设置到实际绘图区域可解决问题"; }else{ MouseEventAnalyser.infoO[IDTools.getObjID(sp)]="子对象未包含鼠标,实际绘图区域不包含鼠标,设置的宽高区域不包含鼠标:"+":"+mouseX+","+mouseY+" hitRec:"+mHitRect.toString()+" graphicBounds:"+sp.getGraphicBounds().toString(); } } else{ MouseEventAnalyser.infoO[IDTools.getObjID(sp)]="自身区域被击中"; } return isHit; } MouseEventAnalyser.hitTest=function(sp,mouseX,mouseY){ var isHit=false; if ((sp.hitArea instanceof laya.utils.HitArea )){ return sp.hitArea.isHit(mouseX,mouseY); } if (sp.width > 0 && sp.height > 0 || sp.mouseThrough || sp.hitArea){ var hitRect=MouseEventAnalyser._rect; if (!sp.mouseThrough){ if (sp.hitArea)hitRect=sp.hitArea; else hitRect.setTo(0,0,sp.width,sp.height); isHit=hitRect.contains(mouseX,mouseY); }else { isHit=sp.getGraphicBounds().contains(mouseX,mouseY); } } return isHit; } MouseEventAnalyser.infoO={}; MouseEventAnalyser.nodeO={}; MouseEventAnalyser.hitO={}; __static(MouseEventAnalyser, ['_matrix',function(){return this._matrix=new Matrix();},'_point',function(){return this._point=new Point();},'_rect',function(){return this._rect=new Rectangle();} ]); return MouseEventAnalyser; })() /** *本类提供obj相关的一些操作 *@author ww *@version 1.0 * *@created 2015-10-21 下午2:03:36 */ //class laya.debug.tools.ObjectTools var ObjectTools=(function(){ function ObjectTools(){} __class(ObjectTools,'laya.debug.tools.ObjectTools'); ObjectTools.getFlatKey=function(tKey,aKey){ if(tKey=="")return aKey; return tKey+ObjectTools.sign+aKey; } ObjectTools.flatObj=function(obj,rst,tKey){ (tKey===void 0)&& (tKey=""); rst=rst?rst:{}; var key; var tValue; for(key in obj){ if((typeof (obj[key])=='object')){ ObjectTools.flatObj(obj[key],rst,ObjectTools.getFlatKey(tKey,key)); }else{ tValue=obj[key]; rst[ObjectTools.getFlatKey(tKey,key)]=obj[key]; } } return rst; } ObjectTools.recoverObj=function(obj){ var rst={}; var tKey; for(tKey in obj){ ObjectTools.setKeyValue(rst,tKey,obj[tKey]); } return rst; } ObjectTools.differ=function(objA,objB){ var tKey; var valueA; var valueB; objA=ObjectTools.flatObj(objA); objB=ObjectTools.flatObj(objB); var rst={}; for(tKey in objA){ if(!objB.hasOwnProperty(tKey)){ rst[tKey]="被删除"; } } for(tKey in objB){ if(objB[tKey]!=objA[tKey]){ rst[tKey]={"pre":objA[tKey],"now":objB[tKey]}; } } return rst; } ObjectTools.traceDifferObj=function(obj){ var key; var tO; for(key in obj){ if((typeof (obj[key])=='string')){ console.log(key+":",obj[key]); }else{ tO=obj[key]; console.log(key+":","now:",tO["now"],"pre:",tO["pre"]); } } } ObjectTools.setKeyValue=function(obj,flatKey,value){ if(flatKey.indexOf(ObjectTools.sign)>=0){ var keys=flatKey.split(ObjectTools.sign); var tKey; while(keys.length>1){ tKey=keys.shift(); if(!obj[tKey]){ obj[tKey]={}; console.log("addKeyObj:",tKey); } obj=obj[tKey]; if(!obj){ console.log("wrong flatKey:",flatKey); return; } } obj[keys.shift()]=value; }else{ obj[flatKey]=value; } } ObjectTools.clearObj=function(obj){ var key; for (key in obj){ delete obj[key]; } } ObjectTools.copyObjFast=function(obj){ var jsStr; jsStr=laya.debug.tools.ObjectTools.getJsonString(obj); return laya.debug.tools.ObjectTools.getObj(jsStr); } ObjectTools.copyObj=function(obj){ if((obj instanceof Array))return ObjectTools.copyArr(obj); var rst={}; var key; for(key in obj){ if(obj[key]===null||obj[key]===undefined){ rst[key]=obj[key]; }else if(((obj[key])instanceof Array)){ rst[key]=ObjectTools.copyArr(obj[key]); } else if((typeof (obj[key])=='object')){ rst[key]=ObjectTools.copyObj(obj[key]); }else{ rst[key]=obj[key]; } } return rst; } ObjectTools.copyArr=function(arr){ var rst; rst=[]; var i=0,len=0; len=arr.length; for(i=0;i src.length)pos=src.length; var preLen=src.length; var i=0,len=0; src.length+=insertArr.length; var moveLen=0; moveLen=insertArr.length; for (i=src.length-1;i >=pos;i--){ src[i]=src[i-moveLen]; } len=insertArr.length; for (i=0;i < len;i++){ src[pos+i]=insertArr[i]; } return src; } ObjectTools.clearArr=function(arr){ if (!arr)return arr; arr.length=0; return arr; } ObjectTools.removeFromArr=function(arr,item){ var i=0,len=0; len=arr.length; for(i=0;i minWidth?tWidth:minWidth; tar.height=tHeight>minHeight?tHeight:minHeight; } SimpleResizer.onMouseMoveEnd=function(e){ SimpleResizer.clearEvents(); } SimpleResizer.clearEvents=function(){ Laya.timer.clear(null,SimpleResizer.onMouseMoving); Laya.stage.off(/*laya.events.Event.MOUSE_UP*/"mouseup",null,SimpleResizer.onMouseMoveEnd); } __static(SimpleResizer, ['preMousePoint',function(){return this.preMousePoint=new Point();},'preTarSize',function(){return this.preTarSize=new Point();},'preScale',function(){return this.preScale=new Point();} ]); return SimpleResizer; })() /** *... *@author ww */ //class laya.debug.tools.ResTools var ResTools=(function(){ function ResTools(){} __class(ResTools,'laya.debug.tools.ResTools'); ResTools.getCachedResList=function(){ if (Render.isWebGL){ return ResTools.getWebGlResList(); }else{ return ResTools.getCanvasResList(); } } ResTools.getWebGlResList=function(){ var rst; rst=[]; var tResource; var _resources; _resources=ResourceManager.currentResourceManager["_resources"]; for(var i=0;i <_resources.length;i++){ tResource=_resources[i]; if(ClassTool.getClassName(tResource)=="WebGLImage"){ var url=tResource["src"]; if(url&&url.indexOf("data:image/png;base64")<0) rst.push(url); } } return rst; } ResTools.getCanvasResList=function(){ var picDic; picDic={}; var dataO; dataO=Loader.loadedMap; ResTools.collectPics(dataO,picDic); return ResTools.getArrFromDic(picDic); } ResTools.getArrFromDic=function(dic){ var key; var rst; rst=[]; for (key in dic){ rst.push(key); } return rst; } ResTools.collectPics=function(dataO,picDic){ if (!dataO)return; var key; var tTexture; for (key in dataO){ tTexture=dataO[key]; if (tTexture){ if (tTexture.bitmap&&tTexture.bitmap.src){ var url=tTexture.bitmap.src; if(url.indexOf("data:image/png;base64")<0) picDic[tTexture.bitmap.src]=true; } } } } return ResTools; })() /** *类实例创建分析工具 *@author ww *@version 1.0 * *@created 2015-9-25 下午3:31:46 */ //class laya.debug.tools.RunProfile var RunProfile=(function(){ function RunProfile(){} __class(RunProfile,'laya.debug.tools.RunProfile'); RunProfile.run=function(funName,callLen){ (callLen===void 0)&& (callLen=3); var tCount; if(!RunProfile.infoDic.hasOwnProperty(funName)){ RunProfile.infoDic[funName]=new CountTool(); } tCount=RunProfile.infoDic[funName]; var msg; msg=TraceTool.getCallLoc(callLen)+"\n"+TraceTool.getCallStack(1,callLen-3); tCount.add(msg); if(RunProfile._runShowDic[funName]){ console.log("Create:"+funName); console.log(msg); } } RunProfile.showClassCreate=function(funName){ RunProfile._runShowDic[funName]=true; } RunProfile.hideClassCreate=function(funName){ RunProfile._runShowDic[funName]=false; } RunProfile.getRunInfo=function(funName){ var rst; rst=RunProfile.infoDic[funName]; if(rst){ } return RunProfile.infoDic[funName]; } RunProfile.runTest=function(fun,count,sign){ (sign===void 0)&& (sign="runTest"); DTrace.timeStart(sign); var i=0; for(i=0;i=0){ return StringTool.insert(str,iStr,i+tarStr.length); } return str; } StringTool.insertBefore=function(str,iStr,tarStr,isLast){ (isLast===void 0)&& (isLast=false); var i=0; if(isLast){ i=str.lastIndexOf(tarStr); }else{ i=str.indexOf(tarStr); } if(i>=0){ return StringTool.insert(str,iStr,i); } return str; } StringTool.insertParamToFun=function(funStr,params){ var oldParam; oldParam=StringTool.getParamArr(funStr); var inserStr; inserStr=params.join(","); if(oldParam.length>0){ inserStr=","+inserStr; } return StringTool.insertBefore(funStr,inserStr,")",true); } StringTool.trim=function(str,vList){ if(!vList){ vList=[" ","\r","\n","\t",String.fromCharCode(65279)]; }; var rst; var i=0; var len=0; rst=str; len=vList.length; for(i=0;i=0){ i--; }; var rst; rst=str.substring(0,i) if(i>=0){ return str.substring(0,i+1); } return ""; } StringTool.trimSide=function(str){ var rst; rst=StringTool.trimLeft(str); rst=StringTool.trimRight(rst); return rst; } StringTool.isOkFileName=function(fileName){ if(laya.debug.tools.StringTool.trimSide(fileName)=="")return false; var i=0,len=0; len=fileName.length; for(i=0;i=0;i--){ str=strArr[i]; str=laya.debug.tools.StringTool.trimSide(str); if(StringTool.isEmpty(str)){ strArr.splice(i,1); }else{ strArr[i]=str; } } return strArr; } StringTool.ifNoAddToTail=function(str,sign){ if(str.indexOf(sign)>=0){ return str; } return str+sign; } StringTool.trimEmptyLine=function(str){ var i=0; var len=0; var tLines; var tLine; tLines=str.split("\n"); for(i=tLines.length-1;i>=0;i--){ tLine=tLines[i]; if(StringTool.isEmptyLine(tLine)){ tLines.splice(i,1); } } return tLines.join("\n"); } StringTool.isEmptyLine=function(str){ str=laya.debug.tools.StringTool.trim(str); if(str=="")return true; return false; } StringTool.removeCommentLine=function(lines){ var rst; rst=[]; var i=0; var tLine; var adptLine; i=0; var len=0; var index=0; len=lines.length; while(i=0){ adptLine=tLine.substring(0,index-1); StringTool.addIfNotEmpty(rst,adptLine); while(i=0){ adptLine=tLine.substring(index+2); StringTool.addIfNotEmpty(rst,adptLine); break ; } i++; } }else if(tLine.indexOf("//")>=0){ if(laya.debug.tools.StringTool.trim(tLine).indexOf("//")==0){ }else{ StringTool.addIfNotEmpty(rst,adptLine); } }else{ StringTool.addIfNotEmpty(rst,adptLine); } i++; } return rst; } StringTool.addIfNotEmpty=function(arr,str){ if(!str)return; var tStr; tStr=StringTool.trim(str); if(tStr!=""){ arr.push(str); } } StringTool.trimExt=function(str,vars){ var rst; rst=StringTool.trim(str); var i=0; var len=0; len=vars.length; for(i=0;i0){ if(arr[0]==""){ arr.shift(); }else{ break ; } } } StringTool.getWords=function(line){ var rst=StringTool.getSplitLine(line); StringTool.delelteItem(rst); return rst; } StringTool.getLinesI=function(startLine,endLine,lines){ var i=0; var rst=[]; for(i=startLine;i<=endLine;i++){ rst.push(lines[i]); } return rst; } StringTool.structfy=function(str,inWidth,removeEmpty){ (inWidth===void 0)&& (inWidth=4); (removeEmpty===void 0)&& (removeEmpty=true); if(removeEmpty){ str=laya.debug.tools.StringTool.trimEmptyLine(str); }; var lines; var tIn=0; tIn=0; var tInStr; tInStr=StringTool.getEmptyStr(0); lines=str.split("\n"); var i=0; var len=0; var tLineStr; len=lines.length; for(i=0;i=0){ tInStr=StringTool.getEmptyStr(tIn*inWidth); } tLineStr=tInStr+tLineStr; lines[i]=tLineStr; tInStr=StringTool.getEmptyStr(tIn*inWidth); } return lines.join("\n"); } StringTool.getEmptyStr=function(width){ if(!StringTool.emptyDic.hasOwnProperty(width)){ var i=0; var len=0; len=width; var rst; rst=""; for(i=0;i0||tC=="0"){ rst=10*rst+Number(tC); if(rst>0)isBegin=true; }else{ if(isBegin)return rst; } } return rst; } StringTool.getReplace=function(str,oStr,nStr){ if(!str)return ""; var rst; rst=str.replace(new RegExp(oStr,"g"),nStr); return rst; } StringTool.getWordCount=function(str,findWord){ var rg=new RegExp(findWord,"g") return str.match(rg).length; } StringTool.getResolvePath=function(path,basePath){ if(StringTool.isAbsPath(path)){ return path; }; var tSign; tSign="\\"; if(basePath.indexOf("/")>=0){ tSign="/"; } if(basePath.charAt(basePath.length-1)==tSign){ basePath=basePath.substr(0,basePath.length-1); }; var parentSign; parentSign=".."+tSign; var tISign; tISign="."+tSign; var pCount=0; pCount=StringTool.getWordCount(path,parentSign); path=laya.debug.tools.StringTool.getReplace(path,parentSign,""); path=laya.debug.tools.StringTool.getReplace(path,tISign,""); var i=0; var len=0; len=pCount; var iPos=0; for(i=0;i=0)return true; return false; } StringTool.removeLastSign=function(str,sign){ var iPos=0; iPos=str.lastIndexOf(sign); str=str.substring(0,iPos); return str; } StringTool.getParamArr=function(str){ var paramStr; paramStr=laya.debug.tools.StringTool.getBetween(str,"(",")",true); if(StringTool.trim(paramStr).length<1)return []; return paramStr.split(","); } StringTool.copyStr=function(str){ return str.substring(); } StringTool.ArrayToString=function(arr){ var rst; rst="[{items}]".replace(new RegExp("\\{items\\}","g"),StringTool.getArrayItems(arr)); return rst; } StringTool.getArrayItems=function(arr){ var rst; if(arr.length<1)return ""; rst=StringTool.parseItem(arr[0]); var i=0; var len=0; len=arr.length; for(i=1;i0)debugger; TimeTool._deep++; var timer; timer=Laya.timer; var laters=timer["_laters"]; for (var i=0,n=laters.length-1;i <=n;i++){ var handler=laters[i]; if(handler){ handler.method!==null && handler.run(false); timer["_recoverHandler"](handler); }else{ debugger; } i===n && (n=laters.length-1); } laters.length=0; TimeTool._deep--; } TimeTool.timeDic={}; TimeTool._deep=0; return TimeTool; })() /** *... *@author ww */ //class laya.debug.tools.TouchDebugTools var TouchDebugTools=(function(){ function TouchDebugTools(){} __class(TouchDebugTools,'laya.debug.tools.TouchDebugTools'); TouchDebugTools.getTouchIDs=function(events){ var rst; rst=[]; var i=0,len=0; len=events.length; for (i=0;i < len;i++){ rst.push(events[i].identifier||0); } return rst; } TouchDebugTools.traceTouchIDs=function(msg,events){ DebugTxt.dTrace(msg+":"+TouchDebugTools.getTouchIDs(events).join(",")); } return TouchDebugTools; })() /** * *@author ww *@version 1.0 * *@created 2015-9-25 上午10:48:54 */ //class laya.debug.tools.TraceTool var TraceTool=(function(){ function TraceTool(){} __class(TraceTool,'laya.debug.tools.TraceTool'); TraceTool.closeAllLog=function(){ var logFun; logFun=TraceTool.emptyLog; Browser.window.console.log=logFun; } TraceTool.emptyLog=function(){} TraceTool.traceObj=function(obj){ TraceTool.tempArr.length=0; var key; for(key in obj){ TraceTool.tempArr.push(key+":"+obj[key]); }; var rst; rst=TraceTool.tempArr.join("\n"); console.log(rst); return rst; } TraceTool.traceObjR=function(obj){ TraceTool.tempArr.length=0; var key; for(key in obj){ TraceTool.tempArr.push(obj[key]+":"+key); }; var rst; rst=TraceTool.tempArr.join("\n"); console.log(rst); return rst; } TraceTool.traceSize=function(tar){ DebugTool.dTrace("Size: x:"+tar.x+" y:"+tar.y+" w:"+tar.width+" h:"+tar.height+" scaleX:"+tar.scaleX+" scaleY:"+tar.scaleY); } TraceTool.traceSplit=function(msg){ console.log("---------------------"+msg+"---------------------------"); } TraceTool.group=function(gName){ /*__JS__ */console.group(gName);; } TraceTool.groupEnd=function(){ /*__JS__ */console.groupEnd();; } TraceTool.getCallStack=function(life,s){ (life===void 0)&& (life=1); (s===void 0)&& (s=1); var caller; caller=TraceTool.getCallStack; caller=caller.caller.caller; var msg; msg=""; while(caller&&life>0){ if(s<=0){ msg+=caller+"<-"; life--; }else{ } caller=caller.caller; s--; } return msg; } TraceTool.getCallLoc=function(index){ (index===void 0)&& (index=2); var loc; try { TraceTool.Erroer.i++; }catch (e){ var arr; arr=e.stack.replace(/Error\n/).split(/\n/); if (arr[index]){ loc=arr[index].replace(/^\s+|\s+$/,""); }else{ loc="unknow"; } } return loc; } TraceTool.traceCallStack=function(){ var loc; try { TraceTool.Erroer.i++; }catch (e){ loc=e.stack; } console.log(loc); return loc; } TraceTool.getPlaceHolder=function(len){ if(!TraceTool.holderDic.hasOwnProperty(len)){ var rst; rst=""; var i=0; for(i=0;i 0 && visibleRec.height > 0){ isInVisibleRec=true; } else{ isInVisibleRec=false; }; var gAlpha=NaN; gAlpha=NodeUtils.getGAlpha(node); var gVisible=false; gVisible=NodeUtils.getGVisible(node); var msg; msg=""; msg+="isInstage:"+isInstage+"\n"; msg+="isInVisibleRec:"+isInVisibleRec+"\n"; msg+="gVisible:"+gVisible+"\n"; msg+="gAlpha:"+gAlpha+"\n"; if (isInstage && isInVisibleRec && gVisible && gAlpha > 0){ if (Render.isWebGL){ VisibleAnalyser.anlyseRecVisible(node); }else{ SpriteRenderForVisibleAnalyse.I.analyseNode(node); } msg+="coverRate:"+VisibleAnalyser.coverRate+"\n"; if (VisibleAnalyser._coverList.length > 0){ Laya.timer.once(1000,null,VisibleAnalyser.showListLater); } } console.log(msg); OutPutView.I.showTxt(msg); } VisibleAnalyser.showListLater=function(){ NodeListPanelView.I.showList(VisibleAnalyser._coverList); } VisibleAnalyser.isCoverByBrother=function(node){ var parent=node.parent; if (!parent) return; var _childs; _childs=parent._childs; var index=0; index=_childs.indexOf(node); if (index < 0) return; var i=0,len=0; var canvas; var rec; rec=parent.getSelfBounds(); if (rec.width <=0 || rec.height <=0) return; } VisibleAnalyser.anlyseRecVisible=function(node){ VisibleAnalyser.isNodeWalked=false; VisibleAnalyser._analyseTarget=node; if (!VisibleAnalyser.mainCanvas) VisibleAnalyser.mainCanvas=CanvasTools.createCanvas(Laya.stage.width,Laya.stage.height); CanvasTools.clearCanvas(VisibleAnalyser.mainCanvas); VisibleAnalyser.tColor=1; VisibleAnalyser.resetCoverList(); WalkTools.walkTargetEX(Laya.stage,VisibleAnalyser.recVisibleWalker,null,VisibleAnalyser.filterFun); if (!VisibleAnalyser.isTarRecOK){ VisibleAnalyser.coverRate=0; } else{ VisibleAnalyser.coverRate=CanvasTools.getDifferRate(VisibleAnalyser.preImageData,VisibleAnalyser.tarImageData); } console.log("coverRate:",VisibleAnalyser.coverRate); } VisibleAnalyser.getRecArea=function(rec){ return rec.width *rec.height; } VisibleAnalyser.addCoverNode=function(node,coverRate){ var data; data={}; data.path=node; data.label=ClassTool.getNodeClassAndName(node)+":"+coverRate; data.coverRate=coverRate; VisibleAnalyser._coverList.push(data); console.log("coverByNode:",node,coverRate); } VisibleAnalyser.resetCoverList=function(){ VisibleAnalyser._coverList.length=0; } VisibleAnalyser.recVisibleWalker=function(node){ if (node==VisibleAnalyser._analyseTarget){ VisibleAnalyser.isNodeWalked=true; VisibleAnalyser.tarRec.copyFrom(NodeUtils.getGRec(node)); console.log("tarRec:",VisibleAnalyser.tarRec.toString()); if (VisibleAnalyser.tarRec.width > 0 && VisibleAnalyser.tarRec.height > 0){ VisibleAnalyser.isTarRecOK=true; VisibleAnalyser.tColor++; CanvasTools.fillCanvasRec(VisibleAnalyser.mainCanvas,VisibleAnalyser.tarRec,ColorTool.toHexColor(VisibleAnalyser.tColor)); VisibleAnalyser.preImageData=CanvasTools.getImageDataFromCanvasByRec(VisibleAnalyser.mainCanvas,VisibleAnalyser.tarRec); VisibleAnalyser.tarImageData=CanvasTools.getImageDataFromCanvasByRec(VisibleAnalyser.mainCanvas,VisibleAnalyser.tarRec); } else{ console.log("tarRec Not OK:",VisibleAnalyser.tarRec); } } else{ if (VisibleAnalyser.isTarRecOK){ var tRec; tRec=NodeUtils.getGRec(node); VisibleAnalyser.interRec=VisibleAnalyser.tarRec.intersection(tRec,VisibleAnalyser.interRec); if (VisibleAnalyser.interRec && VisibleAnalyser.interRec.width > 0 && VisibleAnalyser.interRec.height > 0){ VisibleAnalyser.tColor++; CanvasTools.fillCanvasRec(VisibleAnalyser.mainCanvas,tRec,ColorTool.toHexColor(VisibleAnalyser.tColor)); VisibleAnalyser.tImageData=CanvasTools.getImageDataFromCanvasByRec(VisibleAnalyser.mainCanvas,VisibleAnalyser.tarRec); var dRate=NaN; dRate=CanvasTools.getDifferRate(VisibleAnalyser.preImageData,VisibleAnalyser.tImageData); VisibleAnalyser.preImageData=VisibleAnalyser.tImageData; VisibleAnalyser.addCoverNode(node,dRate); } } } } VisibleAnalyser.filterFun=function(node){ if (node.visible==false) return false; if (node.alpha < 0) return false; if (DebugInfoLayer.I.isDebugItem(node))return false; return true; } VisibleAnalyser.isNodeWalked=false; VisibleAnalyser._analyseTarget=null; VisibleAnalyser.isTarRecOK=false; VisibleAnalyser.mainCanvas=null; VisibleAnalyser.preImageData=null; VisibleAnalyser.tImageData=null; VisibleAnalyser.tarImageData=null; VisibleAnalyser.coverRate=NaN; VisibleAnalyser.tColor=0; VisibleAnalyser._coverList=[]; __static(VisibleAnalyser, ['tarRec',function(){return this.tarRec=new Rectangle();},'interRec',function(){return this.interRec=new Rectangle();} ]); return VisibleAnalyser; })() /** * *@author ww *@version 1.0 * *@created 2015-9-24 下午6:15:01 */ //class laya.debug.tools.WalkTools var WalkTools=(function(){ function WalkTools(){} __class(WalkTools,'laya.debug.tools.WalkTools'); WalkTools.walkTarget=function(target,fun,_this){ fun.apply(_this,[target]); var i=0; var len=0; var tChild; len=target.numChildren; for(i=0;i 0; return rst; } NodeUtils.adptShowKeys=function(keys){ var i=0,len=0; len=keys.length; for (i=len-1;i >=0;i--){ keys[i]=StringTool.trimSide(keys[i]); if (keys[i].length < 1){ keys.splice(i,1); } } return keys; } NodeUtils.getNodeTreeData=function(sprite,keys){ NodeUtils.adptShowKeys(keys); var treeO; treeO=NodeUtils.getPropertyDesO(sprite,keys); var treeArr; treeArr=[]; NodeUtils.getTreeArr(treeO,treeArr); return treeArr; } NodeUtils.getTreeArr=function(treeO,arr,add){ (add===void 0)&& (add=true); if (add) arr.push(treeO); var tArr=treeO.childs; var i=0,len=tArr.length; for (i=0;i < len;i++){ if (!add){ tArr[i].nodeParent=null; } else{ tArr[i].nodeParent=treeO; } if (tArr[i].isDirectory){ NodeUtils.getTreeArr(tArr[i],arr); } else{ arr.push(tArr[i]); } } } NodeUtils.traceStage=function(){ console.log(NodeUtils.getFilterdTree(Laya.stage,null)); console.log("treeArr:",NodeUtils.getNodeTreeData(Laya.stage,null)); } NodeUtils.getNodeCount=function(node,visibleRequire){ (visibleRequire===void 0)&& (visibleRequire=false); if (visibleRequire){ if (!node.visible)return 0; }; var rst=0; rst=1; var i=0,len=0; var cList; cList=node._childs; len=cList.length; for (i=0;i < len;i++){ rst+=NodeUtils.getNodeCount(cList[i],visibleRequire); } return rst; } NodeUtils.getGVisible=function(node){ while (node){ if (!node.visible)return false; node=node.parent; } return true; } NodeUtils.getGAlpha=function(node){ var rst=NaN; rst=1; while (node){ rst *=node.alpha; node=node.parent; } return rst; } NodeUtils.getGPos=function(node){ var point; point=new Point(); node.localToGlobal(point); return point; } NodeUtils.getGRec=function(node){ var pointList; pointList=node._getBoundPointsM(true); if (!pointList || pointList.length < 1) return Rectangle.TEMP.setTo(0,0,0,0); pointList=GrahamScan.pListToPointList(pointList,true); WalkTools.walkArr(pointList,node.localToGlobal,node); pointList=GrahamScan.pointListToPlist(pointList); var _disBoundRec; _disBoundRec=Rectangle._getWrapRec(pointList,_disBoundRec); return _disBoundRec; } NodeUtils.getGGraphicRec=function(node){ var pointList; pointList=node.getGraphicBounds()._getBoundPoints(); if (!pointList || pointList.length < 1) return Rectangle.TEMP.setTo(0,0,0,0); pointList=GrahamScan.pListToPointList(pointList,true); WalkTools.walkArr(pointList,node.localToGlobal,node); pointList=GrahamScan.pointListToPlist(pointList); var _disBoundRec; _disBoundRec=Rectangle._getWrapRec(pointList,_disBoundRec); return _disBoundRec; } NodeUtils.getNodeCmdCount=function(node){ var rst=0; if (node.graphics){ if (node.graphics.cmds){ rst=node.graphics.cmds.length; } else{ if (node.graphics._one){ rst=1; } else{ rst=0; } } } else{ rst=0; } return rst; } NodeUtils.getNodeCmdTotalCount=function(node){ var rst=0; var i=0,len=0; var cList; cList=node._childs; len=cList.length; rst=NodeUtils.getNodeCmdCount(node); for (i=0;i < len;i++){ rst+=NodeUtils.getNodeCmdTotalCount(cList[i]); } return rst; } NodeUtils.getRenderNodeCount=function(node){ if (node.cacheAs !="none")return 1; var rst=0; var i=0,len=0; var cList; cList=node._childs; len=cList.length; rst=1; for (i=0;i < len;i++){ rst+=NodeUtils.getRenderNodeCount(cList[i]); } return rst; } NodeUtils.getReFreshRenderNodeCount=function(node){ var rst=0; var i=0,len=0; var cList; cList=node._childs; len=cList.length; rst=1; for (i=0;i < len;i++){ rst+=NodeUtils.getRenderNodeCount(cList[i]); } return rst; } NodeUtils.showCachedSpriteRecs=function(){ NodeUtils.g=DebugInfoLayer.I.graphicLayer.graphics; NodeUtils.g.clear(); WalkTools.walkTarget(Laya.stage,NodeUtils.drawCachedBounds,null); } NodeUtils.drawCachedBounds=function(sprite){ if (sprite.cacheAs=="none")return; if (DebugInfoLayer.I.isDebugItem(sprite))return; var rec; rec=NodeUtils.getGRec(sprite); NodeUtils.g.drawRect(rec.x,rec.y,rec.width,rec.height,null,"#0000ff",2); } NodeUtils.g=null; __static(NodeUtils, ['defaultKeys',function(){return this.defaultKeys=["x","y","width","height"];} ]); return NodeUtils; })() /** *... *@author ww */ //class laya.debug.view.StyleConsts var StyleConsts=(function(){ function StyleConsts(){} __class(StyleConsts,'laya.debug.view.StyleConsts'); StyleConsts.setViewScale=function(view){ view.scaleX=view.scaleY=StyleConsts.PanelScale; } __static(StyleConsts, ['PanelScale',function(){return this.PanelScale=Browser.onPC?1:Browser.pixelRatio;} ]); return StyleConsts; })() /** *本类用于模块间消息传递 *@author ww */ //class laya.debug.tools.Notice extends laya.events.EventDispatcher var Notice=(function(_super){ function Notice(){ Notice.__super.call(this); } __class(Notice,'laya.debug.tools.Notice',_super); Notice.notify=function(type,data){ Notice.I.event(type,data); } Notice.listen=function(type,_scope,fun,args,cancelBefore){ (cancelBefore===void 0)&& (cancelBefore=false); if(cancelBefore)Notice.cancel(type,_scope,fun); Notice.I.on(type,_scope,fun,args); } Notice.cancel=function(type,_scope,fun){ Notice.I.off(type,_scope,fun); } __static(Notice, ['I',function(){return this.I=new Notice();} ]); return Notice; })(EventDispatcher) /** *... *@author ww */ //class laya.debug.tools.enginehook.LoaderHook extends laya.net.LoaderManager var LoaderHook=(function(_super){ function LoaderHook(){ LoaderHook.__super.call(this); } __class(LoaderHook,'laya.debug.tools.enginehook.LoaderHook',_super); var __proto=LoaderHook.prototype; __proto.checkUrls=function(url){ var tarUrl; if ((typeof url=='string')){ tarUrl=url; }else{ tarUrl=url.url; } if (LoaderHook.preFails[tarUrl]){ if (LoaderHook.enableFailDebugger){ debugger; } } } __proto.chekUrlList=function(urls){ var i=0,len=0; len=urls.length; for (i=0;i < len;i++){ this.checkUrls(urls[i]); } } __proto.load=function(url,complete,progress,type,priority,cache,group,ignoreCache){ (priority===void 0)&& (priority=1); (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); if ((url instanceof Array)){ this.chekUrlList(url); }else{ this.checkUrls(url); } return _super.prototype.load.call(this,url,complete,progress,type,priority,cache,group,ignoreCache); } LoaderHook.init=function(){ if (LoaderHook.isInited)return; LoaderHook.isInited=true; Laya.loader=new LoaderHook(); Laya.loader.on(/*laya.events.Event.ERROR*/"error",null,LoaderHook.onFail); LoaderHook.preFails=LocalStorage.getJSON("LoadFailItems"); if (!LoaderHook.preFails)LoaderHook.preFails={}; } LoaderHook.onFail=function(failFile){ OutPutView.I.dTrace("LoadFail:"+failFile); LoaderHook.nowFails[failFile]=true; LocalStorage.setJSON("LoadFailItems",LoaderHook.nowFails); } LoaderHook.resetFails=function(){ LoaderHook.nowFails={}; LocalStorage.setJSON("LoadFailItems",LoaderHook.nowFails); } LoaderHook.preFails={}; LoaderHook.nowFails={}; LoaderHook.enableFailDebugger=true; LoaderHook.FailSign="LoadFailItems"; LoaderHook.isInited=false; return LoaderHook; })(LoaderManager) /** *颜色选取类 *@author ww */ //class laya.debug.tools.ColorSelector extends laya.display.Sprite var ColorSelector=(function(_super){ function ColorSelector(){ this.sideColor=null; this.mainColor=null; this.demoColor=null; this.posSp=null; this.hPos=null; this.container=null; this.isChanging=false; this.tColor=null; this.tH=NaN; ColorSelector.__super.call(this); this.container=this; this.createUI(); } __class(ColorSelector,'laya.debug.tools.ColorSelector',_super); var __proto=ColorSelector.prototype; __proto.createUI=function(){ this.sideColor=new Sprite(); this.container.addChild(this.sideColor); this.posSp=new Sprite(); this.posSp.pos(100,100); this.posSp.graphics.drawCircle(0,0,5,null,"#ff0000"); this.posSp.graphics.drawCircle(0,0,6,null,"#ffff00"); this.posSp.autoSize=true; this.posSp.cacheAsBitmap=true; this.sideColor.addChild(this.posSp); this.sideColor.pos(0,0); this.sideColor.size(150,150); this.sideColor.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.sideColorClick); var i=0; this.mainColor=new Sprite(); var g; g=this.mainColor.graphics; var h=NaN; var s=NaN; var b=NaN; var rgb; for (i=0;i < 150;i++){ rgb=ColorTool.hsb2rgb(i/150*360,1,1); g.drawLine(0,i,20,i,ColorTool.getRGBStr(rgb)); } this.mainColor.pos(150+10,0); this.mainColor.size(20,i); this.mainColor.cacheAsBitmap=true; this.hPos=new Sprite(); this.hPos.graphics.drawPie(0,0,10,-10,10,"#ff0000"); this.hPos.x=this.mainColor.x+22; this.container.addChild(this.hPos); this.container.addChild(this.mainColor); this.mainColor.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.mainColorClick); this.demoColor=new Sprite(); this.demoColor.pos(this.sideColor.x,this.sideColor.y+this.sideColor.height+10); this.demoColor.size(150,20); this.container.addChild(this.demoColor); this.setColorByRGBStr("#099599"); this.posSp.on(/*laya.events.Event.DRAG_MOVE*/"dragmove",this,this.posDraging); } // posSp.on(Event.MOUSE_DOWN,this,posMouseDown); __proto.posMouseDown=function(e){} __proto.posDraging=function(){ this.updatePosSpAndShowColor(); } __proto.posDragEnd=function(){ this.isChanging=false; this.updatePosSpAndShowColor(); } __proto.setColorByRGBStr=function(rgbStr){ var rgb; rgb=ColorTool.getRGBByRGBStr(rgbStr); this.setColor(rgb[0],rgb[1],rgb[2]); } __proto.setColor=function(red,green,blue,notice){ (notice===void 0)&& (notice=true); var hsb; hsb=ColorTool.rgb2hsb(red,green,blue); var tRGB; tRGB=ColorTool.hsb2rgb(hsb[0],hsb[1],hsb[2]); this.setColorByHSB(hsb[0],hsb[1],hsb[2],notice); } __proto.setColorByHSB=function(h,s,b,notice){ (notice===void 0)&& (notice=true); this.hPos.y=this.mainColor.y+h/360*150; this.posSp.x=s *150; this.posSp.y=(1-b)*150; this.updateSideColor(h,notice); } __proto.sideColorClick=function(e){ this.isChanging=true; this.posSp.startDrag(); this.updatePosSpAndShowColor(); Laya.stage.off(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.sideColorMouseUp); Laya.stage.once(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.sideColorMouseUp); } __proto.sideColorMouseUp=function(e){ this.isChanging=false; this.updatePosSpAndShowColor(); } __proto.updatePosSpAndShowColor=function(){ this.posSp.x=this.sideColor.mouseX; this.posSp.y=this.sideColor.mouseY; if(this.posSp.x<0)this.posSp.x=0; if(this.posSp.y<0)this.posSp.y=0; if(this.posSp.x>150)this.posSp.x=150; if(this.posSp.y>150)this.posSp.y=150; this.updateDemoColor(); } __proto.updateDemoColor=function(notice){ (notice===void 0)&& (notice=true); var h=NaN; var s=NaN; var b=NaN; h=this.tH; s=this.posSp.x / 150; b=1-this.posSp.y / 150; this.tColor=ColorTool.hsb2rgb(h,s,b); var g; g=this.demoColor.graphics; g.clear(); g.drawRect(0,0,this.demoColor.width,this.demoColor.height,ColorTool.getRGBStr(this.tColor)); if(this.isChanging)return; if(notice) this.event("ColorChanged",this); } __proto.mainColorClick=function(e){ var yPos=NaN; yPos=this.mainColor.mouseY; this.hPos.y=yPos+this.mainColor.y; var h=NaN; h=yPos / 150 *360; this.updateSideColor(h); } __proto.updateSideColor=function(h,notice){ (notice===void 0)&& (notice=true); this.tH=h; var s=NaN; var b=NaN; var g; g=this.sideColor.graphics; g.clear(); this.sideColor.cacheAsBitmap=false; var rgb; rgb=ColorTool.hsb2rgb(h,1,1); var gradient=Browser.context.createLinearGradient(0,0,80,0); gradient.addColorStop(0,"white"); gradient.addColorStop(1,ColorTool.getRGBStr(rgb)); this.sideColor.graphics.drawRect(0,0,150,150,gradient); this.sideColor.graphics.loadImage("comp/colorpicker_overlay.png",0,0); this.sideColor.size(150,150); this.sideColor.cacheAsBitmap=true; this.updateDemoColor(notice); } ColorSelector.COLOR_CHANGED="ColorChanged"; ColorSelector.COLOR_CLEARED="COLOR_CLEARED"; ColorSelector.RecWidth=150; return ColorSelector; })(Sprite) /** * *@author ww *@version 1.0 * *@created 2015-12-30 下午1:59:34 */ //class laya.debug.tools.comps.Arrow extends laya.display.Sprite var Arrow=(function(_super){ function Arrow(){ Arrow.__super.call(this); this.drawMe(); } __class(Arrow,'laya.debug.tools.comps.Arrow',_super); var __proto=Arrow.prototype; __proto.drawMe=function(){ var g; g=this.graphics; g.clear(); g.drawLine(0,0,-1,-1,"#ff0000"); g.drawLine(0,0,1,-1,"#ff0000"); } return Arrow; })(Sprite) /** * *@author ww *@version 1.0 * *@created 2015-12-30 下午2:03:32 */ //class laya.debug.tools.comps.ArrowLine extends laya.display.Sprite var ArrowLine=(function(_super){ function ArrowLine(sign){ this.lineLen=160; this.arrowLen=10; this.sign="Y"; this._targetChanger=null; this._isMoving=false; this.lenControl=new Rect(); this.rotationControl=new Rect(); this.lenChanger=ValueChanger.create(this,"lineLen"); this.lenControlXChanger=ValueChanger.create(this.lenControl,"x"); (sign===void 0)&& (sign="X"); ArrowLine.__super.call(this); this.sign=sign; this.addChild(this.lenControl); this.addChild(this.rotationControl); this.lenControl.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.controlMouseDown); this.drawMe(); } __class(ArrowLine,'laya.debug.tools.comps.ArrowLine',_super); var __proto=ArrowLine.prototype; __proto.drawMe=function(){ var g; g=this.graphics; g.clear(); g.drawLine(0,0,this.lineLen,0,"#ffff00"); g.drawLine(this.lineLen,0,this.lineLen-this.arrowLen,-this.arrowLen,"#ff0000"); g.drawLine(this.lineLen,0,this.lineLen-this.arrowLen,this.arrowLen,"#ff0000"); g.fillText(this.sign,50,-5,"","#ff0000","left"); if(this._isMoving&&this._targetChanger){ g.fillText(this._targetChanger.key+":"+this._targetChanger.value.toFixed(2),this.lineLen-15,-25,"","#ffff00","center"); } this.lenControl.posTo(this.lineLen-15,0); this.rotationControl.posTo(this.lineLen+10,0); this.size(this.arrowLen,this.lineLen); } __proto.clearMoveEvents=function(){ Laya.stage.off(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.stageMouseMove); Laya.stage.off(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.stageMouseUp); } __proto.controlMouseDown=function(e){ this.clearMoveEvents(); this.lenControlXChanger.record(); this.lenChanger.record(); if(this.targetChanger){ this.targetChanger.record(); } this._isMoving=true; Laya.stage.on(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.stageMouseMove); Laya.stage.on(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.stageMouseUp); } __proto.stageMouseMove=function(e){ this.lenControlXChanger.value=this.mouseX; this.lenChanger.showValueByScale(this.lenControlXChanger.scaleValue); if(this.targetChanger){ this.targetChanger.showValueByScale(this.lenControlXChanger.scaleValue); } this.drawMe(); } __proto.stageMouseUp=function(e){ this._isMoving=false; this.noticeChange(); this.clearMoveEvents(); this.lenControlXChanger.recover(); this.lenChanger.recover(); this.drawMe(); } __proto.noticeChange=function(){ var dLen=NaN; dLen=this.lenChanger.dValue; console.log("lenChange:",dLen); } __getset(0,__proto,'targetChanger',function(){ return this._targetChanger; },function(changer){ if(this._targetChanger){ this._targetChanger.dispose(); } this._targetChanger=changer; }); return ArrowLine; })(Sprite) /** *... *@author ww */ //class laya.debug.tools.comps.AutoSizeRec extends laya.display.Sprite var AutoSizeRec=(function(_super){ function AutoSizeRec(type){ this.type=0; this._color="#ffffff"; this.preX=NaN; this.preY=NaN; AutoSizeRec.__super.call(this); } __class(AutoSizeRec,'laya.debug.tools.comps.AutoSizeRec',_super); var __proto=AutoSizeRec.prototype; __proto.setColor=function(color){ this._color=color; this.reRender(); } __proto.changeSize=function(){ this.reRender(); } __proto.reRender=function(){ var g=this.graphics; g.clear(); g.drawRect(0,0,this.width,this.height,this._color); } __proto.record=function(){ this.preX=this.x; this.preY=this.y; } __proto.getDx=function(){ return this.x-this.preX; } __proto.getDy=function(){ return this.y-this.preY; } __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Sprite,this,'height',value); this.changeSize(); }); __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(Sprite,this,'width',value); this.changeSize(); }); return AutoSizeRec; })(Sprite) /** * *@author ww *@version 1.0 * *@created 2015-12-30 下午2:37:05 */ //class laya.debug.tools.comps.Axis extends laya.display.Sprite var Axis=(function(_super){ function Axis(){ this._target=null; this._lenType= [ ["width","height"], ["scaleX","scaleY"]]; this._type=1; this.xAxis=new ArrowLine("X"); this.yAxis=new ArrowLine("Y"); this.controlBox=new Rect(); this._point=new Point(); this.oPoint=new Point(); this.myRotationChanger=ValueChanger.create(this,"rotation"); this.targetRotationChanger=ValueChanger.create(null,"rotation"); this.stageMouseRotationChanger=new ValueChanger(); Axis.__super.call(this); this.mouseEnabled=true; this.size(1,1); this.initMe(); this.xAxis.rotationControl.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.controlMouseDown); this.yAxis.rotationControl.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.controlMouseDown); this.controlBox.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.controlBoxMouseDown); this.on(/*laya.events.Event.DRAG_MOVE*/"dragmove",this,this.dragging); } __class(Axis,'laya.debug.tools.comps.Axis',_super); var __proto=Axis.prototype; __proto.updateChanges=function(){ if(this._target){ var params; params=this._lenType[this._type]; this.xAxis.targetChanger=ValueChanger.create(this._target,params[0]); this.yAxis.targetChanger=ValueChanger.create(this._target,params[1]); } } __proto.switchType=function(){ this._type++; this._type=this._type%this._lenType.length; this.type=this._type; } __proto.controlBoxMouseDown=function(e){ this.startDrag(); } __proto.dragging=function(){ if (this._target){ this._point.setTo(this.x,this.y); DisControlTool.transPoint(this.parent,this._target.parent,this._point); this._target.pos(this._point.x,this._point.y); } } __proto.initMe=function(){ this.addChild(this.xAxis); this.addChild(this.yAxis); this.yAxis.rotation=90; this.addChild(this.controlBox); this.controlBox.posTo(0,0); } __proto.clearMoveEvents=function(){ Laya.stage.off(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.stageMouseMove); Laya.stage.off(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.stageMouseUp); } __proto.controlMouseDown=function(e){ this.targetRotationChanger.target=this.target; this.clearMoveEvents(); this.oPoint.setTo(0,0); this.myRotationChanger.record(); this.oPoint=this.localToGlobal(this.oPoint); this.stageMouseRotationChanger.value=this.getStageMouseRatation(); this.stageMouseRotationChanger.record(); this.targetRotationChanger.record(); Laya.stage.on(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.stageMouseMove); Laya.stage.on(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.stageMouseUp); } __proto.getStageMouseRatation=function(){ return MathUtil.getRotation(this.oPoint.x,this.oPoint.y,Laya.stage.mouseX,Laya.stage.mouseY); } __proto.stageMouseMove=function(e){ this.stageMouseRotationChanger.value=this.getStageMouseRatation(); var dRotation=NaN; dRotation=-this.stageMouseRotationChanger.dValue; if(this.target){ this.targetRotationChanger.showValueByAdd(dRotation); }else{ this.myRotationChanger.showValueByAdd(dRotation); } } __proto.stageMouseUp=function(e){ this.noticeChange(); this.clearMoveEvents(); } __proto.noticeChange=function(){ console.log("rotate:",-this.stageMouseRotationChanger.dValue); } __getset(0,__proto,'target',function(){ return this._target; },function(tar){ this._target=tar; this.updateChanges(); }); __getset(0,__proto,'type',function(){ return this._type; },function(lenType){ this._type=lenType; this.updateChanges(); }); return Axis; })(Sprite) /** * *@author ww *@version 1.0 * *@created 2015-12-30 下午3:23:06 */ //class laya.debug.tools.comps.Rect extends laya.display.Sprite var Rect=(function(_super){ function Rect(){ this.recWidth=10; Rect.__super.call(this); this.drawMe(); } __class(Rect,'laya.debug.tools.comps.Rect',_super); var __proto=Rect.prototype; __proto.drawMe=function(){ var g; g=this.graphics; g.clear(); g.drawRect(0,0,this.recWidth,this.recWidth,"#22ff22"); this.size(this.recWidth,this.recWidth); } __proto.posTo=function(x,y){ this.x=x-this.recWidth*0.5; this.y=y-this.recWidth*0.5; } return Rect; })(Sprite) //class laya.debug.tools.DragBox extends laya.display.Sprite var DragBox=(function(_super){ function DragBox(type){ this._box=null; this._target=null; this._currDir=null; /**0-无,1-水平,2-垂直,3-全部*/ this._type=0; this.fixScale=NaN; DragBox.__super.call(this); this._left=this.drawBlock(); this._right=this.drawBlock(); this._top=this.drawBlock(); this._bottom=this.drawBlock(); this._topLeft=this.drawBlock(); this._topRight=this.drawBlock(); this._bottomLeft=this.drawBlock(); this._bottomRight=this.drawBlock(); this._lastPoint=new Point(); this._type=type=3; this.addChild(this._box=this.drawBorder(0,0,0xff0000)); if (type==1 || type==3){ this.addChild(this._left); this.addChild(this._right); } if (type==2 || type==3){ this.addChild(this._top); this.addChild(this._bottom); } if (type==3){ this.addChild(this._topLeft); this.addChild(this._topRight); this.addChild(this._bottomLeft); this.addChild(this._bottomRight); } this.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onMouseDown); this.mouseThrough=true; } __class(DragBox,'laya.debug.tools.DragBox',_super); var __proto=DragBox.prototype; __proto.onMouseDown=function(e){ this._currDir=e.target; if(e.nativeEvent.shiftKey){ this.initFixScale(); } if (this._currDir !=this){ this._lastPoint.x=Laya.stage.mouseX; this._lastPoint.y=Laya.stage.mouseY; Laya.stage.on(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.onMouseMove); Laya.stage.on(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.onMouseUp); e.stopPropagation(); } } __proto.onMouseUp=function(e){ Laya.stage.off(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.onMouseMove); Laya.stage.off(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.onMouseUp); } __proto.initFixScale=function(){ this.fixScale=this._target.height / this._target.width; } __proto.onMouseMove=function(e){ var scale=1; var tx=(Laya.stage.mouseX-this._lastPoint.x)/ scale; var ty=(Laya.stage.mouseY-this._lastPoint.y)/ scale; var sameScale=false; var adptX=NaN; var adptY=NaN; if(e.nativeEvent.shiftKey){ if(this.fixScale<0)this.initFixScale(); adptY=tx *this.fixScale; adptX=ty/this.fixScale; sameScale=true; switch(this._currDir){ case this._topLeft: case this._bottomLeft: this._currDir=this._left; break ; case this._topRight: case this._bottomRight: this._currDir=this._right; break ; } } if (tx !=0 || ty !=0){ this._lastPoint.x+=tx *scale; this._lastPoint.y+=ty *scale; var tw=tx / this._target.scaleX; var th=ty / this._target.scaleY; if (this._currDir==this._left){ this._target.x+=tx; this._target.width-=tw; if (sameScale){ this._target.height=this._target.width*this.fixScale; } }else if (this._currDir==this._right){ this._target.width+=tw; if (sameScale){ this._target.height=this._target.width*this.fixScale; } }else if (this._currDir==this._top){ this._target.y+=ty; this._target.height-=th; if (sameScale){ this._target.width=this._target.height/this.fixScale; } }else if (this._currDir==this._bottom){ this._target.height+=th; if (sameScale){ this._target.width=this._target.height/this.fixScale; } }else if (this._currDir==this._topLeft){ this._target.x+=tx; this._target.y+=ty; this._target.width-=tw; this._target.height-=th; }else if (this._currDir==this._topRight){ this._target.y+=ty; this._target.width+=tw; this._target.height-=th; }else if (this._currDir==this._bottomLeft){ this._target.x+=tx; this._target.width-=tw; this._target.height+=th; }else if (this._currDir==this._bottomRight){ this._target.width+=tw; this._target.height+=th; } if (this._target.width < 1){ this._target.width=1; } if (this._target.height < 1){ this._target.height=1; } this._target.width=Math.round(this._target.width); this._target.x=Math.round(this._target.x); this._target.y=Math.round(this._target.y); this._target.height=Math.round(this._target.height); this.refresh(); } } /**画矩形*/ __proto.drawBorder=function(width,height,color,alpha){ (alpha===void 0)&& (alpha=1); var box=new Sprite(); var g=box.graphics; g.clear(); g.drawRect(0,0,width,height,null,"#"+color); return box; } /**画矩形*/ __proto.drawBlock=function(){ var box=new Sprite(); var g=box.graphics; g.clear(); box.width=DragBox.BLOCK_WIDTH; box.height=DragBox.BLOCK_WIDTH; g.drawRect(-DragBox.BLOCK_WIDTH *0.5,-DragBox.BLOCK_WIDTH *0.5,DragBox.BLOCK_WIDTH,DragBox.BLOCK_WIDTH,"#ffffff","#ff0000",1); box.mouseEnabled=true; box.mouseThrough=true; return box; } /**设置对象*/ __proto.setTarget=function(target){ this._target=target; this.refresh(); } __proto.refresh=function(){ this.changePoint(); this.changeSize(); } __proto.changePoint=function(){ var p=this._target.localToGlobal(new Point()); var np=(this.parent).globalToLocal(p); this.x=np.x; this.y=np.y; } /**设置大小*/ __proto.changeSize=function(){ var width=this._target.width *this._target.scaleX; var height=this._target.height *this._target.scaleY; console.log("change size"); this.rotation=this._target.rotation; if (this._box.width !=width || this._box.height !=height){ this._box.graphics.clear(); this._box.graphics.drawRect(0,0,Math.abs(width),Math.abs(height),null,"#ff0000"); this._box.size(width,height); this.size(width,height); this._box.scaleX=Math.abs(this._box.scaleX)*(this._target.scaleX > 0 ? 1 :-1); this._box.scaleY=Math.abs(this._box.scaleY)*(this._target.scaleY > 0 ? 1 :-1); this._left.x=0; this._left.y=height *0.5; this._right.x=width; this._right.y=height *0.5; this._top.x=width *0.5; this._top.y=0; this._bottom.x=width *0.5; this._bottom.y=height; this._topLeft.x=this._topLeft.y=0; this._topRight.x=width; this._topRight.y=0; this._bottomLeft.x=0; this._bottomLeft.y=height; this._bottomRight.x=width; this._bottomRight.y=height; } } DragBox.BLOCK_WIDTH=6; return DragBox; })(Sprite) /** *... *@author ww */ //class laya.debug.view.nodeInfo.DebugInfoLayer extends laya.display.Sprite var DebugInfoLayer=(function(_super){ function DebugInfoLayer(){ this.nodeRecInfoLayer=null; this.lineLayer=null; this.txtLayer=null; this.popLayer=null; this.graphicLayer=null; this.cacheViewLayer=null; DebugInfoLayer.__super.call(this); this.nodeRecInfoLayer=new Sprite(); this.lineLayer=new Sprite(); this.txtLayer=new Sprite(); this.popLayer=new Sprite(); this.graphicLayer=new Sprite(); this.cacheViewLayer=new Sprite(); this.nodeRecInfoLayer.name="nodeRecInfoLayer"; this.lineLayer.name="lineLayer"; this.txtLayer.name="txtLayer"; this.popLayer.name="popLayer"; this.graphicLayer.name="graphicLayer"; this.cacheViewLayer.name="cacheViewLayer"; this.addChild(this.lineLayer); this.addChild(this.cacheViewLayer); this.addChild(this.nodeRecInfoLayer); this.addChild(this.txtLayer); this.addChild(this.popLayer); this.addChild(this.graphicLayer); DebugInfoLayer.I=this; this.zOrder=999; Laya.stage.on(/*laya.events.Event.DOUBLE_CLICK*/"doubleclick",this,this.setTop); } __class(DebugInfoLayer,'laya.debug.view.nodeInfo.DebugInfoLayer',_super); var __proto=DebugInfoLayer.prototype; __proto.setTop=function(){ DisControlTool.setTop(this); } __proto.isDebugItem=function(sprite){ return DisControlTool.isInTree(this,sprite); } DebugInfoLayer.init=function(){ if (!DebugInfoLayer.I){ new DebugInfoLayer(); Laya.stage.addChild(DebugInfoLayer.I); } } DebugInfoLayer.I=null; return DebugInfoLayer; })(Sprite) /** *... *@author ww */ //class laya.debug.view.nodeInfo.NodeInfoPanel extends laya.display.Sprite var NodeInfoPanel=(function(_super){ function NodeInfoPanel(){ this._stateDic={}; this.isWorkState=false; NodeInfoPanel.__super.call(this); } __class(NodeInfoPanel,'laya.debug.view.nodeInfo.NodeInfoPanel',_super); var __proto=NodeInfoPanel.prototype; __proto.showDisInfo=function(node){ this.recoverNodes(); NodeInfosItem.showDisInfos(node); this.showOnly(node); this.isWorkState=true; } __proto.showOnly=function(node){ if (!node) return; this.hideBrothers(node); this.showOnly(node.parent); } __proto.recoverNodes=function(){ NodeInfosItem.hideAllInfos(); var key; var data; var tTar; for (key in this._stateDic){ data=this._stateDic[key]; tTar=data["target"]; if (tTar){ try{ tTar.visible=data.visible; }catch (e){ } } } this.isWorkState=false; } __proto.hideOtherChain=function(node){ if (!node) return; while (node){ this.hideBrothers(node); node=node.parent; } } __proto.hideChilds=function(node){ if (!node) return; var i=0,len=0; var cList; cList=node._childs; len=cList.length; var tChild; for (i=0;i < len;i++){ tChild=cList[i]; if (tChild==NodeInfosItem.NodeInfoContainer)continue ; this.saveNodeInfo(tChild); tChild.visible=false; } } __proto.hideBrothers=function(node){ if (!node) return; var p; p=node.parent; if (!p) return; var i=0,len=0; var cList; cList=p._childs; len=cList.length; var tChild; for (i=0;i < len;i++){ tChild=cList[i]; if (tChild==NodeInfosItem.NodeInfoContainer)continue ; if (tChild !=node){ this.saveNodeInfo(tChild); tChild.visible=false; } } } __proto.saveNodeInfo=function(node){ IDTools.idObj(node); if(this._stateDic.hasOwnProperty(IDTools.getObjID(node)))return; var data; data={}; data.target=node; data.visible=node.visible; this._stateDic[IDTools.getObjID(node)]=data; } __proto.recoverNodeInfo=function(node){ IDTools.idObj(node); if (this._stateDic.hasOwnProperty(IDTools.getObjID(node))){ var data; data=this._stateDic[IDTools.getObjID(node)]; node["visible"]=data.visible; } } NodeInfoPanel.init=function(){ if (!NodeInfoPanel.I){ NodeInfoPanel.I=new NodeInfoPanel(); NodeInfosItem.init(); ToolPanel.init(); } } NodeInfoPanel.I=null; return NodeInfoPanel; })(Sprite) /** *... *@author ww */ //class laya.debug.view.nodeInfo.NodeInfosItem extends laya.display.Sprite var NodeInfosItem=(function(_super){ function NodeInfosItem(){ //addChild(_infoTxt); this._infoTxt=null; this._tar=null; NodeInfosItem.__super.call(this); this._infoTxt=new Text(); this._infoTxt.color="#ff0000"; this._infoTxt.bgColor="#00ff00"; this._infoTxt.fontSize=12; } __class(NodeInfosItem,'laya.debug.view.nodeInfo.NodeInfosItem',_super); var __proto=NodeInfosItem.prototype; __proto.removeSelf=function(){ this._infoTxt.removeSelf(); return laya.display.Node.prototype.removeSelf.call(this); } __proto.showToUI=function(){ NodeInfosItem.NodeInfoContainer.nodeRecInfoLayer.addChild(this); this._infoTxt.removeSelf(); NodeInfosItem.NodeInfoContainer.txtLayer.addChild(this._infoTxt); this.findOkPos(); } __proto.randomAPos=function(r){ this._infoTxt.x=this.x+Laya.stage.width*Math.random(); this._infoTxt.y=this.y+r *Math.random(); } __proto.findOkPos=function(){ var len=0; len=20; this.randomAPos(len); return; var count=0; count=1; while (!this.isPosOk()){ count++; if (count >=500){ len+=10; count=0; } this.randomAPos(len); } } __proto.isPosOk=function(){ var tParent; tParent=NodeInfosItem.NodeInfoContainer.nodeRecInfoLayer; var i=0,len=0; var cList; cList=tParent._childs; len=cList.length; var tChild; var mRec; mRec=this._infoTxt.getBounds(); if (mRec.x < 0)return false; if (mRec.y < 0)return false; if (mRec.right > Laya.stage.width)return false; for (i=0;i < len;i++){ tChild=cList[i]; if (tChild==this._infoTxt)continue ; if (mRec.intersects(tChild.getBounds()))return false; } return true; } __proto.showInfo=function(node){ this._tar=node; if (!node)return; NodeInfosItem._txts.length=0; var i=0,len=0; var tKey; len=NodeInfosItem.showValues.length; if (node.name){ NodeInfosItem._txts.push(ClassTool.getClassName(node)+"("+node.name+")"); }else{ NodeInfosItem._txts.push(ClassTool.getClassName(node)); } for (i=0;i < len;i++){ tKey=NodeInfosItem.showValues[i]; NodeInfosItem._txts.push(tKey+":"+NodeInfosItem.getNodeValue(node,tKey)); } this._infoTxt.text=NodeInfosItem._txts.join("\n"); this.graphics.clear(); var pointList; pointList=node._getBoundPointsM(true); if(!pointList||pointList.length<1)return; pointList=GrahamScan.pListToPointList(pointList,true); WalkTools.walkArr(pointList,node.localToGlobal,node); pointList=GrahamScan.pointListToPlist(pointList); NodeInfosItem._disBoundRec=Rectangle._getWrapRec(pointList,NodeInfosItem._disBoundRec); this.graphics.drawRect(0,0,NodeInfosItem._disBoundRec.width,NodeInfosItem._disBoundRec.height,null,"#00ffff"); this.pos(NodeInfosItem._disBoundRec.x,NodeInfosItem._disBoundRec.y); } __proto.fresh=function(){ this.showInfo(this._tar); } __proto.clearMe=function(){ this._tar=null; } __proto.recover=function(){ Pool.recover("NodeInfosItem",this); } NodeInfosItem.init=function(){ if (!NodeInfosItem.NodeInfoContainer){ DebugInfoLayer.init(); NodeInfosItem.NodeInfoContainer=DebugInfoLayer.I; Laya.stage.addChild(NodeInfosItem.NodeInfoContainer); } } NodeInfosItem.getNodeInfoByNode=function(node){ IDTools.idObj(node); var key=0; key=IDTools.getObjID(node); if (!NodeInfosItem._nodeInfoDic[key]){ NodeInfosItem._nodeInfoDic[key]=new NodeInfosItem(); } return NodeInfosItem._nodeInfoDic[key]; } NodeInfosItem.hideAllInfos=function(){ var key; var tInfo; for (key in NodeInfosItem._nodeInfoDic){ tInfo=NodeInfosItem._nodeInfoDic[key]; tInfo.removeSelf(); } NodeInfosItem.clearRelations(); } NodeInfosItem.showNodeInfo=function(node){ var nodeInfo; nodeInfo=NodeInfosItem.getNodeInfoByNode(node); nodeInfo.showInfo(node); nodeInfo.showToUI(); } NodeInfosItem.showDisInfos=function(node){ var _node; _node=node; if (!node) return; while (node){ NodeInfosItem.showNodeInfo(node); node=node.parent; } DisControlTool.setTop(NodeInfosItem.NodeInfoContainer); NodeInfosItem.apdtTxtInfoPoss(_node); NodeInfosItem.updateRelations(); } NodeInfosItem.apdtTxtInfoPoss=function(node){ var disList; disList=[]; while (node){ disList.push(node); node=node.parent; }; var i=0,len=0; var tInfo; var tTxt; len=disList.length; var xPos=NaN; xPos=Laya.stage.width-150; var heightLen=0; heightLen=100; node=disList[0]; if (node){ tInfo=NodeInfosItem.getNodeInfoByNode(node); if (tInfo){ tTxt=tInfo._infoTxt; xPos=Laya.stage.width-tTxt.width-10; heightLen=tTxt.height+10; } } disList=disList.reverse(); for (i=0;i < len;i++){ node=disList[i]; tInfo=NodeInfosItem.getNodeInfoByNode(node); if (tInfo){ tTxt=tInfo._infoTxt; tTxt.pos(xPos,heightLen *i); } } } NodeInfosItem.clearRelations=function(){ var g; g=NodeInfosItem.NodeInfoContainer.lineLayer.graphics; g.clear(); } NodeInfosItem.updateRelations=function(){ var g; g=NodeInfosItem.NodeInfoContainer.lineLayer.graphics; g.clear(); var key; var tInfo; for (key in NodeInfosItem._nodeInfoDic){ tInfo=NodeInfosItem._nodeInfoDic[key]; if (tInfo.parent){ g.drawLine(tInfo.x,tInfo.y,tInfo._infoTxt.x,tInfo._infoTxt.y,"#0000ff"); } } } NodeInfosItem.getNodeValue=function(node,key){ var rst; NodeInfosItem._nodePoint.setTo(0,0); switch(key){ case "x": rst=node["x"]+" (g:"+node.localToGlobal(NodeInfosItem._nodePoint).x+")" break ; case "y": rst=node["y"]+" (g:"+node.localToGlobal(NodeInfosItem._nodePoint).y+")" break ; default : rst=node[key]; } return rst; } NodeInfosItem.NodeInfoContainer=null; NodeInfosItem._nodeInfoDic={}; NodeInfosItem._txts=[]; __static(NodeInfosItem, ['showValues',function(){return this.showValues=["x","y","scaleX","scaleY","width","height","visible","mouseEnabled"];},'_disBoundRec',function(){return this._disBoundRec=new Rectangle();},'_nodePoint',function(){return this._nodePoint=new Point();} ]); return NodeInfosItem; })(Sprite) /** *... *@author ww */ //class laya.debug.view.nodeInfo.recinfos.NodeRecInfo extends laya.display.Sprite var NodeRecInfo=(function(_super){ function NodeRecInfo(){ this.txt=null; this._tar=null; this.recColor="#00ff00"; NodeRecInfo.__super.call(this); this.txt=new Text(); this.txt.color="#ff0000"; this.txt.bgColor="#00ff00"; this.txt.fontSize=12; this.addChild(this.txt); } __class(NodeRecInfo,'laya.debug.view.nodeInfo.recinfos.NodeRecInfo',_super); var __proto=NodeRecInfo.prototype; __proto.setInfo=function(str){ this.txt.text=str; } __proto.setTarget=function(tar){ this._tar=tar; } __proto.showInfo=function(node){ this._tar=node; if (!node)return; if(!node._$P)return; this.graphics.clear(); var pointList; pointList=node._getBoundPointsM(true); if(!pointList||pointList.length<1)return; pointList=GrahamScan.pListToPointList(pointList,true); WalkTools.walkArr(pointList,node.localToGlobal,node); pointList=GrahamScan.pointListToPlist(pointList); NodeRecInfo._disBoundRec=Rectangle._getWrapRec(pointList,NodeRecInfo._disBoundRec); this.graphics.drawRect(0,0,NodeRecInfo._disBoundRec.width,NodeRecInfo._disBoundRec.height,null,DebugConsts.RECACHE_REC_COLOR,2); this.pos(NodeRecInfo._disBoundRec.x,NodeRecInfo._disBoundRec.y); } __proto.fresh=function(){ this.showInfo(this._tar); } __proto.clearMe=function(){ this._tar=null; } __static(NodeRecInfo, ['_disBoundRec',function(){return this._disBoundRec=new Rectangle();} ]); return NodeRecInfo; })(Sprite) /** *... *@author ww */ //class laya.debug.view.nodeInfo.ToolPanel extends laya.display.Sprite var ToolPanel=(function(_super){ function ToolPanel(){ ToolPanel.__super.call(this); Base64AtlasManager.base64.preLoad(Handler.create(this,this.showToolBar)); ContextMenu.init(); DisResizer.init(); var tipManager; tipManager=new TipManagerForDebug(); } __class(ToolPanel,'laya.debug.view.nodeInfo.ToolPanel',_super); var __proto=ToolPanel.prototype; //Laya.timer.once(1000,this,showToolBar); __proto.showToolBar=function(){ DebugPanelView.I.show(); } __proto.createViews=function(){ ToolPanel.typeClassDic["Find"]=FindView; ToolPanel.typeClassDic["Filter"]=FilterView; ToolPanel.typeClassDic["TxtInfo"]=TxtInfoView; ToolPanel.typeClassDic["Tree"]=NodeTreeView; } __proto.switchShow=function(type){ var view; view=this.getView(type); if (view){ view.switchShow(); } } __proto.getView=function(type){ var view; view=ToolPanel.viewDic[type]; if (!view && ToolPanel.typeClassDic[type]){ view=ToolPanel.viewDic[type]=new ToolPanel.typeClassDic[type](); } return view; } __proto.showTxtInfo=function(txt){ OutPutView.I.showTxt(txt); } __proto.showNodeTree=function(node){ NodeTree.I.setDis(node); DebugPanelView.I.switchToTree(); } __proto.showSelectInStage=function(node){ NodeTree.I.showSelectInStage(node); DebugPanelView.I.switchToTree(); } __proto.showSelectItems=function(selectList){ DebugPanelView.I.swichToSelect(); SelectInfosView.I.setSelectList(selectList); } ToolPanel.init=function(){ if (!ToolPanel.I)ToolPanel.I=new ToolPanel(); } ToolPanel.I=null; ToolPanel.viewDic={}; ToolPanel.Find="Find"; ToolPanel.Filter="Filter"; ToolPanel.TxtInfo="TxtInfo"; ToolPanel.Tree="Tree"; __static(ToolPanel, ['typeClassDic',function(){return this.typeClassDic={ };} ]); return ToolPanel; })(Sprite) /** * *@author ww *@version 1.0 * *@created 2015-9-29 上午11:17:35 */ //class laya.debug.tools.debugUI.DButton extends laya.display.Text var DButton=(function(_super){ function DButton(){ DButton.__super.call(this); this.bgColor="#ffff00"; this.wordWrap=false; this.mouseEnabled=true; } __class(DButton,'laya.debug.tools.debugUI.DButton',_super); return DButton; })(Text) /** *自动根据大小填充自己全部区域的显示对象 *@author ww */ //class laya.debug.tools.resizer.AutoFillRec extends laya.ui.Component var AutoFillRec=(function(_super){ function AutoFillRec(type){ this.type=0; this.preX=NaN; this.preY=NaN; AutoFillRec.__super.call(this); } __class(AutoFillRec,'laya.debug.tools.resizer.AutoFillRec',_super); var __proto=AutoFillRec.prototype; //super(type); __proto.changeSize=function(){ _super.prototype.changeSize.call(this); var g=this.graphics; g.clear(); g.drawRect(0,0,this.width,this.height,"#33c5f5"); } __proto.record=function(){ this.preX=this.x; this.preY=this.y; } __proto.getDx=function(){ return this.x-this.preX; } __proto.getDy=function(){ return this.y-this.preY; } return AutoFillRec; })(Component) /**鼠标提示管理类*/ //class laya.debug.tools.TipManagerForDebug extends laya.ui.Component var TipManagerForDebug=(function(_super){ function TipManagerForDebug(){ this._tipBox=null; this._tipText=null; this._defaultTipHandler=null; TipManagerForDebug.__super.call(this); this._tipBox=new Component(); this._tipBox.addChild(this._tipText=new Text()); this._tipText.x=this._tipText.y=5; this._tipText.color=TipManagerForDebug.tipTextColor; this._defaultTipHandler=this.showDefaultTip; Laya.stage.on(/*laya.ui.UIEvent.SHOW_TIP*/"showtip",this,this.onStageShowTip); Laya.stage.on(/*laya.ui.UIEvent.HIDE_TIP*/"hidetip",this,this.onStageHideTip); } __class(TipManagerForDebug,'laya.debug.tools.TipManagerForDebug',_super); var __proto=TipManagerForDebug.prototype; __proto.onStageHideTip=function(e){ Laya.timer.clear(this,this.showTip); this.closeAll(); this.removeSelf(); } __proto.onStageShowTip=function(data){ Laya.timer.once(TipManagerForDebug.tipDelay,this,this.showTip,[data],true); } __proto.showTip=function(tip){ if ((typeof tip=='string')){ var text=String(tip); if (Boolean(text)){ this._defaultTipHandler(text); } }else if ((tip instanceof laya.utils.Handler )){ (tip).run(); }else if ((typeof tip=='function')){ (tip).apply(); } if (true){ Laya.stage.on(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.onStageMouseMove); Laya.stage.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onStageMouseDown); } this.onStageMouseMove(null); } __proto.onStageMouseDown=function(e){ this.closeAll(); } __proto.onStageMouseMove=function(e){ this.showToStage(this,TipManagerForDebug.offsetX,TipManagerForDebug.offsetY); } __proto.showToStage=function(dis,offX,offY){ (offX===void 0)&& (offX=0); (offY===void 0)&& (offY=0); var rec=dis.getBounds(); dis.x=Laya.stage.mouseX+offX; dis.y=Laya.stage.mouseY+offY; if (dis.x+rec.width > Laya.stage.width){ dis.x-=rec.width+offX; } if (dis.y+rec.height > Laya.stage.height){ dis.y-=rec.height+offY; } } /**关闭所有鼠标提示*/ __proto.closeAll=function(){ Laya.timer.clear(this,this.showTip); Laya.stage.off(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.onStageMouseMove); Laya.stage.off(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onStageMouseDown); this.removeChildren(); } __proto.showDisTip=function(tip){ this.addChild(tip); this.showToStage(this); Laya.stage.addChild(this); } __proto.showDefaultTip=function(text){ this._tipText.text=text; var g=this._tipBox.graphics; g.clear(); g.drawRect(0,0,this._tipText.width+10,this._tipText.height+10,TipManagerForDebug.tipBackColor); this.addChild(this._tipBox); this.showToStage(this); Laya.stage.addChild(this); } /**默认鼠标提示函数*/ __getset(0,__proto,'defaultTipHandler',function(){ return this._defaultTipHandler; },function(value){ this._defaultTipHandler=value; }); TipManagerForDebug.offsetX=10; TipManagerForDebug.offsetY=15; TipManagerForDebug.tipTextColor="#ffffff"; TipManagerForDebug.tipBackColor="#111111"; TipManagerForDebug.tipDelay=200; return TipManagerForDebug; })(Component) /** *... *@author ww */ //class laya.debug.view.nodeInfo.views.UIViewBase extends laya.ui.Component var UIViewBase=(function(_super){ function UIViewBase(){ this.minHandler=null; this.maxHandler=null; this.isFirstShow=true; this.dis=null; UIViewBase.__super.call(this); this.dis=this; this.minHandler=new Handler(this,this.close); this.maxHandler=new Handler(this,this.show); this.createPanel(); if (this.dis){ this.dis.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.bringToTop); this.dis.cacheAsBitmap=true; } } __class(UIViewBase,'laya.debug.view.nodeInfo.views.UIViewBase',_super); var __proto=UIViewBase.prototype; __proto.show=function(){ DebugInfoLayer.I.setTop(); DebugInfoLayer.I.popLayer.addChild(this.dis); if (this.isFirstShow){ this.firstShowFun(); this.isFirstShow=false; } } __proto.firstShowFun=function(){ this.dis.x=(Laya.stage.width-this.dis.width)*0.5; this.dis.y=(Laya.stage.height-this.dis.height)*0.5; DisControlTool.intFyDisPos(this.dis); } __proto.bringToTop=function(){ DisControlTool.setTop(this.dis); } __proto.switchShow=function(){ if (this.dis.parent){ this.close(); }else{ this.show(); } } __proto.close=function(){ this.dis.removeSelf(); } __proto.createPanel=function(){} __proto.getInput=function(){ var input; input=new DInput(); input.size(200,30); input.fontSize=30; return input; } __proto.getButton=function(){ var btn; btn=new DButton(); btn.size(40,30); btn.fontSize=30; return btn; } return UIViewBase; })(Component) /** *... *@author ww */ //class laya.debug.view.nodeInfo.recinfos.ReCacheRecInfo extends laya.debug.view.nodeInfo.recinfos.NodeRecInfo var ReCacheRecInfo=(function(_super){ function ReCacheRecInfo(){ this.isWorking=false; this.count=0; this.mTime=0; ReCacheRecInfo.__super.call(this); this.txt.fontSize=12; } __class(ReCacheRecInfo,'laya.debug.view.nodeInfo.recinfos.ReCacheRecInfo',_super); var __proto=ReCacheRecInfo.prototype; __proto.addCount=function(time){ (time===void 0)&& (time=0); this.count++; this.mTime+=time; if (!this.isWorking){ this.working=true; } } __proto.updates=function(){ if (!this._tar["displayedInStage"]){ this.working=false; this.removeSelf(); } this.txt.text=ClassTool.getNodeClassAndName(this._tar)+"\n"+"reCache:"+this.count+"\ntime:"+this.mTime; if (this.count > 0){ this.fresh(); Laya.timer.clear(this,this.removeSelfLater); }else{ this.working=false; Laya.timer.once(3000,this,this.removeSelfLater); } this.count=0; this.mTime=0; } __proto.removeSelfLater=function(){ this.working=false; this.removeSelf(); } __getset(0,__proto,'working',null,function(v){ this.isWorking=v; if (v){ Laya.timer.loop(1000,this,this.updates); }else{ Laya.timer.clear(this,this.updates); } }); ReCacheRecInfo.showTime=3000; return ReCacheRecInfo; })(NodeRecInfo) /** *... *@author ww */ //class laya.debug.tools.debugUI.DInput extends laya.display.Input var DInput=(function(_super){ function DInput(){ DInput.__super.call(this); this.bgColor="#11ff00"; } __class(DInput,'laya.debug.tools.debugUI.DInput',_super); return DInput; })(Input) /** * *@author ww *@version 1.0 * *@created 2015-10-24 下午2:58:37 */ //class laya.debug.uicomps.ContextMenu extends laya.ui.Box var ContextMenu=(function(_super){ function ContextMenu(){ this._tY=0; ContextMenu.__super.call(this); StyleConsts.setViewScale(this); } __class(ContextMenu,'laya.debug.uicomps.ContextMenu',_super); var __proto=ContextMenu.prototype; __proto.addItem=function(item){ this.addChild(item); item.y=this._tY; this._tY+=item.height; item.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onClick); } __proto.onClick=function(e){ this.event(/*laya.events.Event.SELECT*/"select",e); this.removeSelf(); } __proto.show=function(posX,posY){ (posX===void 0)&& (posX=-999); (posY===void 0)&& (posY=-999); Laya.timer.once(100,this,ContextMenu.showMenu,[this,posX,posY]); } ContextMenu.init=function(){ Laya.stage.on(/*laya.events.Event.CLICK*/"click",null,ContextMenu.cleanMenu); } ContextMenu.cleanMenu=function(e){ var i=0; var len=0; len=ContextMenu._menuList.length; for(i=0;i 0){ tData.label=key+":"+dataO[key]+" +"+tData.add; } else{ tData.label=key+":"+dataO[key]; } count=RunProfile.getRunInfo(key); if (count){ count.record(); } tData.rank=tData.add *1000+tData.count; this.preInfo[key]=dataO[key]; dataList.push(tData); } dataList.sort(MathTools.sortByKey("rank",true,true)); this.view.itemList.array=dataList; } __getset(1,ObjectCreateView,'I',function(){ if (!ObjectCreateView._I) ObjectCreateView._I=new ObjectCreateView(); return ObjectCreateView._I; },laya.debug.view.nodeInfo.views.UIViewBase._$SET_I); ObjectCreateView._I=null; return ObjectCreateView; })(UIViewBase) /** *... *@author ww */ //class laya.debug.view.nodeInfo.views.ObjectInfoView extends laya.debug.view.nodeInfo.views.UIViewBase var ObjectInfoView=(function(_super){ function ObjectInfoView(){ this.view=null; this.showKeys=["x","y","width","height","renderCost"]; this._closeSettingHandler=null; this._tar=null; ObjectInfoView.__super.call(this); } __class(ObjectInfoView,'laya.debug.view.nodeInfo.views.ObjectInfoView',_super); var __proto=ObjectInfoView.prototype; __proto.createPanel=function(){ _super.prototype.createPanel.call(this); this.view=new ObjectInfo(); StyleConsts.setViewScale(this.view); this.addChild(this.view); this.inits(); } __proto.inits=function(){ this.view.closeBtn.on(/*laya.events.Event.CLICK*/"click",this,this.close); this.view.settingBtn.on(/*laya.events.Event.CLICK*/"click",this,this.onSettingBtn); this.view.autoUpdate.on(/*laya.events.Event.CHANGE*/"change",this,this.onAutoUpdateChange); DisControlTool.setDragingItem(this.view.bg,this.view); DisControlTool.setResizeAbleEx(this.view); this._closeSettingHandler=new Handler(this,this.closeSetting); this.dis=this.view; } __proto.onAutoUpdateChange=function(){ this.autoUpdate=this.view.autoUpdate.selected; } __proto.onSettingBtn=function(){ NodeTreeSettingView.I.showSetting(this.showKeys,this._closeSettingHandler,this._tar); } __proto.reset=function(){ this.showKeys=["x","y","width","height","renderCost"]; } __proto.closeSetting=function(newKeys){ this.showKeys=newKeys; this.fresh(); } __proto.showObjectInfo=function(obj){ this._tar=obj; this.fresh(); this.show(); this.onAutoUpdateChange(); } __proto.fresh=function(){ if (!this._tar){ this.view.showTxt.text=""; this.view.title.text="未选中对象"; } else{ this.view.title.text=ClassTool.getNodeClassAndName(this._tar); this.view.showTxt.text=ObjectInfoView.getObjValueStr(this._tar,this.showKeys,false); } } __proto.freshKeyInfos=function(){ this.fresh(); } __proto.close=function(){ _super.prototype.close.call(this); this.autoUpdate=false; Pool.recover("ObjectInfoView",this); } __proto.show=function(){ _super.prototype.show.call(this); } __getset(0,__proto,'autoUpdate',null,function(v){ Laya.timer.clear(this,this.freshKeyInfos); if (v){ Laya.timer.loop(2000,this,this.freshKeyInfos); } }); ObjectInfoView.getObjValueStr=function(obj,keys,withTitle){ (withTitle===void 0)&& (withTitle=true); var i=0,len=0; var tKey; ObjectInfoView._txts.length=0; len=keys.length; if (withTitle){ if (obj.name){ ObjectInfoView._txts.push(ClassTool.getClassName(obj)+"("+obj.name+")"); } else{ ObjectInfoView._txts.push(ClassTool.getClassName(obj)); } } for (i=0;i < len;i++){ tKey=keys[i]; ObjectInfoView._txts.push(tKey+":"+ObjectInfoView.getNodeValue(obj,tKey)); } return ObjectInfoView._txts.join("\n"); } ObjectInfoView.getNodeValue=function(node,key){ var rst; if ((node instanceof laya.display.Sprite )){ var tNode; tNode=node; switch (key){ case "gRec": rst=NodeUtils.getGRec(tNode).toString(); break ; case "gAlpha": rst=NodeUtils.getGAlpha(tNode)+""; break ; case "cmdCount": rst=NodeUtils.getNodeCmdCount(tNode)+""; break ; case "cmdAll": rst=NodeUtils.getNodeCmdTotalCount(tNode)+""; break ; case "nodeAll": rst=""+NodeUtils.getNodeCount(tNode); break ; case "nodeVisible": rst=""+NodeUtils.getNodeCount(tNode,true); break ; case "nodeRender": rst=""+NodeUtils.getRenderNodeCount(tNode); break ; case "nodeReCache": rst=""+NodeUtils.getReFreshRenderNodeCount(tNode); break ; case "renderCost": rst=""+RenderAnalyser.I.getTime(tNode); break ; case "renderCount": rst=""+RenderAnalyser.I.getCount(tNode); break ; default : rst=node[key]+""; } } else{ rst=node[key]+""; } return rst; } ObjectInfoView.showObject=function(obj){ var infoView; infoView=Pool.getItemByClass("ObjectInfoView",ObjectInfoView); infoView.reset(); infoView.showObjectInfo(obj); } ObjectInfoView._txts=[]; return ObjectInfoView; })(UIViewBase) /** *... *@author ww */ //class laya.debug.view.nodeInfo.views.OutPutView extends laya.debug.view.nodeInfo.views.UIViewBase var OutPutView=(function(_super){ function OutPutView(){ this.view=null; OutPutView.__super.call(this); DebugTool._logFun=OutPutView.log; } __class(OutPutView,'laya.debug.view.nodeInfo.views.OutPutView',_super); var __proto=OutPutView.prototype; __proto.createPanel=function(){ this.view=new OutPut(); DisControlTool.setDragingItem(this.view.txt,this.view); DisControlTool.setDragingItem(this.view.bg,this.view); StyleConsts.setViewScale(this.view); this.view.txt.textField.overflow=Text.SCROLL; this.view.txt.textField.wordWrap=true; this.view.on(/*laya.events.Event.MOUSE_WHEEL*/"mousewheel",this,this.mouseWheel); this.view.txt.text=""; DisControlTool.setResizeAbleEx(this.view); this.view.closeBtn.on(/*laya.events.Event.CLICK*/"click",this,this.close); this.view.clearBtn.on(/*laya.events.Event.CLICK*/"click",this,this.onClearBtn); this.dis=this.view; } __proto.onClearBtn=function(){ this.clearText(); } __proto.mouseWheel=function(e){ this.view.txt.textField.scrollY-=e.delta*10; } __proto.showTxt=function(str){ this.view.txt.text=str; this.show(); this.view.txt.textField.scrollY=this.view.txt.textField.maxScrollY; } __proto.clearText=function(){ this.view.txt.text=""; } __proto.dTrace=function(__arg){ var arg=arguments; if (this.view.txt.textField.scrollY > 1000){ this.view.txt.text=""; }; var str; var i=0,len=0; len=arg.length; str=arg[0]; for (i=1;i < len;i++){ str+=" "+arg[i]; } this.addStr(str); } __proto.addStr=function(str){ this.view.txt.text+="\n"+str; this.show(); this.view.txt.textField.scrollY=this.view.txt.textField.maxScrollY; } __getset(1,OutPutView,'I',function(){ if (!OutPutView._I)OutPutView._I=new OutPutView(); return OutPutView._I; },laya.debug.view.nodeInfo.views.UIViewBase._$SET_I); OutPutView.log=function(str){ OutPutView.I.addStr(str); } OutPutView._I=null; return OutPutView; })(UIViewBase) /** *... *@author ww */ //class laya.debug.view.nodeInfo.views.RenderCostRankView extends laya.debug.view.nodeInfo.views.UIViewBase var RenderCostRankView=(function(_super){ function RenderCostRankView(){ this.view=null; RenderCostRankView.__super.call(this); } __class(RenderCostRankView,'laya.debug.view.nodeInfo.views.RenderCostRankView',_super); var __proto=RenderCostRankView.prototype; __proto.createPanel=function(){ this.view=new Rank(); this.view.top=this.view.bottom=this.view.left=this.view.right=0; this.addChild(this.view); NodeMenu.I.setNodeListAction(this.view.itemList); this.view.closeBtn.on(/*laya.events.Event.CLICK*/"click",this,this.close); this.view.freshBtn.on(/*laya.events.Event.CLICK*/"click",this,this.fresh); this.view.itemList.scrollBar.hide=true; this.view.autoUpdate.on(/*laya.events.Event.CHANGE*/"change",this,this.onAutoUpdateChange); this.dis=this; this.view.itemList.array=[]; this.onAutoUpdateChange(); this.fresh(); Laya.timer.once(5000,this,this.fresh); } __proto.onRightClick=function(){ var list; list=this.view.itemList; if (list.selectedItem){ var tarNode; tarNode=list.selectedItem.path; NodeMenu.I.objRightClick(tarNode); } } __proto.onAutoUpdateChange=function(){ this.autoUpdate=this.view.autoUpdate.selected; } __proto.fresh=function(){ this.view.title.text="渲染用时排行("+NodeConsts.RenderCostMaxTime+"ms)"; var nodeDic; nodeDic=RenderAnalyser.I.nodeDic; var key; var tNode; var tData; var dataList; dataList=[]; for (key in nodeDic){ tNode=nodeDic[key]; if (RenderCostRankView.filterDebugNodes && DisControlTool.isInTree(DebugInfoLayer.I,tNode))continue ; if (RenderAnalyser.I.getTime(tNode)<=0)continue ; tData={}; tData.time=RenderAnalyser.I.getTime(tNode); if (RenderCostRankView.filterDebugNodes && tNode==Laya.stage){ tData.time-=RenderAnalyser.I.getTime(DebugInfoLayer.I); } tData.path=tNode; tData.label=ClassTool.getNodeClassAndName(tNode)+":"+tData.time; dataList.push(tData); } dataList.sort(MathTools.sortByKey("time",true,true)); this.view.itemList.array=dataList; } __getset(0,__proto,'autoUpdate',null,function(v){ Laya.timer.clear(this,this.fresh); if (v){ this.fresh(); Laya.timer.loop(NodeConsts.RenderCostMaxTime,this,this.fresh); } }); __getset(1,RenderCostRankView,'I',function(){ if (!RenderCostRankView._I) RenderCostRankView._I=new RenderCostRankView(); return RenderCostRankView._I; },laya.debug.view.nodeInfo.views.UIViewBase._$SET_I); RenderCostRankView._I=null; RenderCostRankView.filterDebugNodes=true; return RenderCostRankView; })(UIViewBase) /** *... *@author ww */ //class laya.debug.view.nodeInfo.views.ResRankView extends laya.debug.view.nodeInfo.views.UIViewBase var ResRankView=(function(_super){ function ResRankView(){ this.view=null; ResRankView.__super.call(this); } __class(ResRankView,'laya.debug.view.nodeInfo.views.ResRankView',_super); var __proto=ResRankView.prototype; __proto.createPanel=function(){ this.view=new Rank(); this.view.top=this.view.bottom=this.view.left=this.view.right=0; this.addChild(this.view); this.view.closeBtn.on(/*laya.events.Event.CLICK*/"click",this,this.close); this.view.freshBtn.on(/*laya.events.Event.CLICK*/"click",this,this.fresh); this.view.itemList.scrollBar.hide=true; this.view.autoUpdate.on(/*laya.events.Event.CHANGE*/"change",this,this.onAutoUpdateChange); this.dis=this; this.view.itemList.array=[]; this.view.itemList.on(/*laya.events.Event.RIGHT_CLICK*/"rightclick",this,this.onRightClick); this.onAutoUpdateChange(); this.fresh(); } __proto.onRightClick=function(){ var list; list=this.view.itemList; if (list.selectedItem){ console.log(list.selectedItem["url"]); } } __proto.onAutoUpdateChange=function(){ this.autoUpdate=this.view.autoUpdate.selected; } __proto.fresh=function(){ this.view.title.text="图片缓存列表"; var resList; resList=ResTools.getCachedResList(); var key; var tNode; var tData; var dataList; dataList=[]; var i=0,len=0; len=resList.length; for (i=0;i < len;i++){ tData={}; var tUrl; tUrl=resList[i]; tUrl=tUrl.replace(URL.rootPath,"") tData.label=tUrl; tData.url=tUrl; dataList.push(tData); } this.view.itemList.array=dataList; } __getset(0,__proto,'autoUpdate',null,function(v){ Laya.timer.clear(this,this.fresh); if (v){ this.fresh(); Laya.timer.loop(NodeConsts.RenderCostMaxTime,this,this.fresh); } }); __getset(1,ResRankView,'I',function(){ if (!ResRankView._I) ResRankView._I=new ResRankView(); return ResRankView._I; },laya.debug.view.nodeInfo.views.UIViewBase._$SET_I); ResRankView._I=null; ResRankView.filterDebugNodes=true; return ResRankView; })(UIViewBase) /** *... *@author ww */ //class laya.debug.view.nodeInfo.views.SelectInfosView extends laya.debug.view.nodeInfo.views.UIViewBase var SelectInfosView=(function(_super){ function SelectInfosView(){ this.showKeys=[]; this.view=null; this.fliterTxt=null; this.itemList=null; SelectInfosView.__super.call(this); SelectInfosView._I=this; this.setSelectList(null); } __class(SelectInfosView,'laya.debug.view.nodeInfo.views.SelectInfosView',_super); var __proto=SelectInfosView.prototype; __proto.createPanel=function(){ this.view=new SelectInfos(); this.addChild(this.view); this.view.top=this.view.bottom=this.view.left=this.view.right=0; NodeMenu.I.setNodeListAction(this.view.selectList); this.view.closeBtn.on(/*laya.events.Event.CLICK*/"click",this,this.close); this.view.selectList.scrollBar.hide=true; this.dis=null; this.view.findBtn.on(/*laya.events.Event.CLICK*/"click",this,this.onFindBtn); this.fliterTxt=this.view.fliterTxt; this.view.fliterTxt.on(/*laya.events.Event.ENTER*/"enter",this,this.onFliterTxtChange); this.view.fliterTxt.on(/*laya.events.Event.BLUR*/"blur",this,this.onFliterTxtChange); } __proto.onFliterTxtChange=function(e){ var key; key=this.fliterTxt.text; if (key==""){ if (this.showKeys.length !=0){ this.showKeys.length=0; this.fresh(); } }else if (key !=this.showKeys.join(",")){ this.showKeys=key.split(","); this.fresh(); } } __proto.onFindBtn=function(){ FindSmallView.I.show(); } __proto.onRightClick=function(){ var list; list=this.view.selectList; if (list.selectedItem){ var tarNode; tarNode=list.selectedItem.path; NodeMenu.I.objRightClick(tarNode); } } //} __proto.setSelectTarget=function(node){ if (!node)return; this.setSelectList([node]); } __proto.setSelectList=function(list){ this.itemList=list; this.fresh(); } //show(); __proto.fresh=function(){ var list; list=this.itemList; if (!list || list.length < 1){ this.view.selectList.array=[]; return; }; var i=0,len=0; var tDis; var tData; len=list.length; var disList; disList=[]; for (i=0;i < len;i++){ tDis=list[i]; tData={}; tData.label=this.getLabelTxt(tDis); tData.path=tDis; disList.push(tData); } this.view.selectList.array=disList; } __proto.getLabelTxt=function(item){ var rst; rst=ClassTool.getNodeClassAndName(item); var i=0,len=0; len=this.showKeys.length; for (i=0;i < len;i++){ rst+=","+ObjectInfoView.getNodeValue(item,this.showKeys[i]); } return rst; } __getset(1,SelectInfosView,'I',function(){ if (!SelectInfosView._I)SelectInfosView._I=new SelectInfosView(); return SelectInfosView._I; },laya.debug.view.nodeInfo.views.UIViewBase._$SET_I); SelectInfosView._I=null; return SelectInfosView; })(UIViewBase) /** *... *@author ww */ //class laya.debug.view.nodeInfo.views.ToolBarView extends laya.debug.view.nodeInfo.views.UIViewBase var ToolBarView=(function(_super){ function ToolBarView(){ this.view=null; ToolBarView.__super.call(this); } __class(ToolBarView,'laya.debug.view.nodeInfo.views.ToolBarView',_super); var __proto=ToolBarView.prototype; __proto.createPanel=function(){ this.view=new ToolBar(); this.addChild(this.view); DisControlTool.setDragingItem(this.view.bg,this.view); this.view.on(/*laya.events.Event.CLICK*/"click",this,this.onBtnClick); this.view.minBtn.minHandler=this.minHandler; this.view.minBtn.maxHandler=this.maxHandler; this.view.minBtn.tar=this.view; this.clickSelectChange(); this.view.selectWhenClick.on(/*laya.events.Event.CHANGE*/"change",this,this.clickSelectChange); Notice.listen(/*laya.debug.tools.DisplayHook.ITEM_CLICKED*/"ItemClicked",this,this.itemClicked); this.dis=this.view; } __proto.itemClicked=function(tar){ if (!ToolBarView.isClickSelectState)return; if (DisControlTool.isInTree(this.view.selectWhenClick,tar))return; if (ToolBarView.ignoreDebugTool){ if (DebugInfoLayer.I.isDebugItem(tar))return; } } __proto.clickSelectChange=function(){ ToolBarView.isClickSelectState=this.view.selectWhenClick.selected; } __proto.firstShowFun=function(){ this.dis.x=Laya.stage.width-this.dis.width-20; this.dis.y=5; } __proto.onBtnClick=function(e){ switch(e.target){ case this.view.treeBtn: ToolPanel.I.switchShow(/*laya.debug.view.nodeInfo.ToolPanel.Tree*/"Tree"); break ; case this.view.findBtn: ToolPanel.I.switchShow(/*laya.debug.view.nodeInfo.ToolPanel.Find*/"Find"); break ; case this.view.clearBtn: DebugTool.clearDebugLayer(); break ; case this.view.rankBtn: RenderCostRankView.I.show(); break ; case this.view.nodeRankBtn: ObjectCreateView.I.show(); break ; case this.view.cacheBtn: NodeUtils.showCachedSpriteRecs(); break ; } } __getset(1,ToolBarView,'I',function(){ if (!ToolBarView._I)ToolBarView._I=new ToolBarView(); return ToolBarView._I; },laya.debug.view.nodeInfo.views.UIViewBase._$SET_I); ToolBarView._I=null; ToolBarView.ignoreDebugTool=true; ToolBarView.isClickSelectState=false; return ToolBarView; })(UIViewBase) /** *... *@author ww */ //class laya.debug.view.nodeInfo.views.TxtInfoView extends laya.debug.view.nodeInfo.views.UIViewBase var TxtInfoView=(function(_super){ function TxtInfoView(){ this.input=null; this.btn=null; TxtInfoView.__super.call(this); } __class(TxtInfoView,'laya.debug.view.nodeInfo.views.TxtInfoView',_super); var __proto=TxtInfoView.prototype; __proto.createPanel=function(){ this.input=new Input(); this.input.size(200,400); this.input.multiline=true; this.input.bgColor="#ff00ff"; this.input.fontSize=12; this.input.wordWrap=true; this.addChild(this.input); this.btn=this.getButton(); this.btn.text="关闭"; this.btn.size(50,20); this.btn.align="center"; this.btn.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onCloseBtn); this.btn.pos(5,this.input.height+5); this.addChild(this.btn); } __proto.showInfo=function(txt){ this.input.text=txt; this.show(); } __proto.show=function(){ DebugInfoLayer.I.setTop(); DebugInfoLayer.I.popLayer.addChild(this); this.x=(Laya.stage.width-this.width); this.y=0; } __proto.onCloseBtn=function(){ this.close(); } return TxtInfoView; })(UIViewBase) //class laya.debug.ui.debugui.CodeUsedResUI extends laya.ui.View var CodeUsedResUI=(function(_super){ function CodeUsedResUI(){ this.tab=null; CodeUsedResUI.__super.call(this); } __class(CodeUsedResUI,'laya.debug.ui.debugui.CodeUsedResUI',_super); var __proto=CodeUsedResUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(CodeUsedResUI.uiView); } __proto.viewMapRegists=function(){} __static(CodeUsedResUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"x":359,"y":91,"skin":"comp/button1.png"},"type":"Image"},{"props":{"x":309,"y":283,"skin":"comp/line2.png"},"type":"Image"},{"type":"Tab","child":[{"props":{"skin":"view/create.png","label":" 对象创建","width":70,"height":17,"name":"item0"},"type":"CheckBox"},{"props":{"x":70,"skin":"view/rendertime.png","label":"渲染用时","width":70,"height":19,"name":"item1"},"type":"CheckBox"},{"props":{"x":140,"skin":"view/cache.png","label":"Cache","width":70,"height":16,"name":"item2"},"type":"CheckBox"}],"props":{"x":76,"y":210,"selectedIndex":0,"var":"tab"}}],"props":{"width":600,"height":400,"base64pic":true}};} ]); return CodeUsedResUI; })(View) //class laya.debug.ui.debugui.comps.ListItemUI extends laya.ui.View var ListItemUI=(function(_super){ function ListItemUI(){ ListItemUI.__super.call(this); } __class(ListItemUI,'laya.debug.ui.debugui.comps.ListItemUI',_super); var __proto=ListItemUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(ListItemUI.uiView); } __proto.viewMapRegists=function(){} __static(ListItemUI, ['uiView',function(){return this.uiView={"type":"View","props":{"base64pic":true,"width":244,"height":19},"child":[{"type":"Clip","props":{"y":-1,"skin":"comp/clip_selectBox.png","clipY":2,"height":19,"name":"selectBox","left":2,"right":2,"x":0}},{"type":"Label","props":{"x":25,"text":"render","color":"#dcea36","width":77,"height":17,"name":"label","y":2,"fontSize":12}},{"type":"Clip","props":{"skin":"comp/clip_tree_arrow.png","clipY":2,"name":"arrow","x":8,"y":4,"mouseEnabled":false}}]};} ]); return ListItemUI; })(View) //class laya.debug.ui.debugui.comps.RankListItemUI extends laya.ui.View var RankListItemUI=(function(_super){ function RankListItemUI(){ RankListItemUI.__super.call(this); } __class(RankListItemUI,'laya.debug.ui.debugui.comps.RankListItemUI',_super); var __proto=RankListItemUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(RankListItemUI.uiView); } __proto.viewMapRegists=function(){} __static(RankListItemUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"y":-1,"skin":"comp/clip_selectBox.png","clipY":2,"height":19,"name":"selectBox","left":0,"right":0,"x":0},"type":"Clip"},{"props":{"text":"render","color":"#a0a0a0","height":15,"name":"label","y":2,"left":11,"right":5,"fontSize":12,"x":11,"width":163},"type":"Label"}],"props":{"width":179,"height":19}};} ]); return RankListItemUI; })(View) //class laya.debug.ui.debugui.DebugPanelUI extends laya.ui.View var DebugPanelUI=(function(_super){ function DebugPanelUI(){ this.bg=null; this.minBtn=null; this.treePanel=null; this.selectWhenClick=null; this.profilePanel=null; this.resizeBtn=null; this.mouseAnalyseBtn=null; this.dragIcon=null; this.clearBtn=null; this.selectPanel=null; this.tab=null; DebugPanelUI.__super.call(this); } __class(DebugPanelUI,'laya.debug.ui.debugui.DebugPanelUI',_super); var __proto=DebugPanelUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(DebugPanelUI.uiView); } __proto.viewMapRegists=function(){ View.regComponent("laya.debug.view.nodeInfo.nodetree.MinBtnComp",MinBtnComp); View.regComponent("laya.debug.view.nodeInfo.views.NodeTreeView",NodeTreeView); View.regComponent("laya.debug.view.nodeInfo.nodetree.Profile",Profile); View.regComponent("laya.debug.view.nodeInfo.views.SelectInfosView",SelectInfosView); } __static(DebugPanelUI, ['uiView',function(){return this.uiView={"type":"View","props":{"base64pic":true,"width":260,"height":400},"child":[{"type":"Image","props":{"x":205,"y":254,"skin":"view/bg_panel.png","left":0,"right":0,"top":0,"bottom":0,"var":"bg","sizeGrid":"5,5,5,5"}},{"type":"Image","props":{"y":0,"skin":"view/bg_top.png","left":0,"right":0}},{"type":"MinBtnComp","props":{"y":-3,"var":"minBtn","runtime":"laya.debug.view.nodeInfo.nodetree.MinBtnComp","right":-3,"x":207}},{"type":"NodeTree","props":{"left":0,"right":0,"top":32,"bottom":0,"name":"节点树","var":"treePanel","runtime":"laya.debug.view.nodeInfo.views.NodeTreeView"}},{"type":"CheckBox","props":{"x":8,"y":9,"skin":"view/clickselect.png","toolTip":"点击选取","var":"selectWhenClick","mouseEnabled":true,"width":14,"height":14}},{"type":"Profile","props":{"name":"性能","top":32,"right":0,"left":0,"bottom":0,"var":"profilePanel","runtime":"laya.debug.view.nodeInfo.nodetree.Profile"}},{"type":"Button","props":{"x":169,"y":247,"skin":"view/resize.png","right":2,"bottom":2,"name":"resizeBtn","var":"resizeBtn","stateNum":3}},{"type":"Clip","props":{"y":9,"skin":"view/clickanalyse.png","var":"mouseAnalyseBtn","toolTip":"拖动选取","left":33,"x":33,"clipY":3}},{"type":"Clip","props":{"y":0,"skin":"view/clickanalyse.png","var":"dragIcon","x":33,"clipY":3}},{"type":"Button","props":{"y":7,"skin":"view/res.png","stateNum":2,"toolTip":"清除边框","var":"clearBtn","right":34,"x":184}},{"type":"SelectInfos","props":{"top":32,"left":0,"right":0,"bottom":0,"name":"选中","var":"selectPanel","runtime":"laya.debug.view.nodeInfo.views.SelectInfosView"}},{"type":"Tab","props":{"x":59,"y":0,"name":"tab","var":"tab","selectedIndex":0},"child":[{"type":"Button","props":{"skin":"view/tab_panel.png","label":"节点","width":42,"height":32,"name":"item0","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":42,"skin":"view/tab_panel.png","label":"查询","width":42,"height":32,"name":"item1","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":84,"skin":"view/tab_panel.png","label":"性能","width":42,"height":32,"name":"item2","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}}]}]};} ]); return DebugPanelUI; })(View) //class laya.debug.ui.debugui.FindNodeSmallUI extends laya.ui.View var FindNodeSmallUI=(function(_super){ function FindNodeSmallUI(){ this.bg=null; this.closeBtn=null; this.title=null; this.typeSelect=null; this.findTxt=null; this.findBtn=null; FindNodeSmallUI.__super.call(this); } __class(FindNodeSmallUI,'laya.debug.ui.debugui.FindNodeSmallUI',_super); var __proto=FindNodeSmallUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(FindNodeSmallUI.uiView); } __proto.viewMapRegists=function(){} __static(FindNodeSmallUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"x":185,"y":234,"skin":"view/bg_tool.png","left":0,"right":0,"top":0,"bottom":0,"var":"bg"},"type":"Image"},{"props":{"x":185,"y":15,"skin":"view/btn_close.png","var":"closeBtn","top":2,"right":2},"type":"Button"},{"props":{"x":6,"y":4,"text":"查找对象","width":67,"height":20,"color":"#288edf","var":"title"},"type":"Label"},{"props":{"x":60,"y":81,"skin":"comp/combobox.png","labels":"name,class","width":63,"height":21,"var":"typeSelect","sizeGrid":"5,35,5,5","labelColors":"#a0a0a0,#fffff,#ffffff#fffff"},"type":"ComboBox"},{"props":{"x":27,"y":83,"text":"类型","width":27,"height":20,"color":"#288edf","align":"right"},"type":"Label"},{"props":{"x":7,"y":40,"text":"包含内容","width":47,"height":20,"color":"#288edf","align":"right"},"type":"Label"},{"props":{"x":60,"y":37,"skin":"comp/textinput.png","text":"Sprite","width":164,"height":22,"var":"findTxt","sizeGrid":"5,5,5,5","color":"#a0a0a0"},"type":"TextInput"},{"props":{"x":158,"y":79,"skin":"comp/button.png","label":"查找","width":65,"height":23,"var":"findBtn","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"},"type":"Button"}],"props":{"base64pic":true,"width":233,"height":120}};} ]); return FindNodeSmallUI; })(View) //class laya.debug.ui.debugui.FindNodeUI extends laya.ui.View var FindNodeUI=(function(_super){ function FindNodeUI(){ this.bg=null; this.closeBtn=null; this.title=null; this.typeSelect=null; this.findTxt=null; this.result=null; this.findBtn=null; FindNodeUI.__super.call(this); } __class(FindNodeUI,'laya.debug.ui.debugui.FindNodeUI',_super); var __proto=FindNodeUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(FindNodeUI.uiView); } __proto.viewMapRegists=function(){ View.regComponent("laya.debug.uicomps.RankListItem",RankListItem); } __static(FindNodeUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"x":185,"y":234,"skin":"view/bg_panel.png","left":0,"right":0,"top":0,"bottom":0,"var":"bg","sizeGrid":"5,5,5,5"},"type":"Image"},{"props":{"x":185,"y":15,"skin":"view/btn_close.png","var":"closeBtn","top":2,"right":2},"type":"Button"},{"props":{"x":6,"y":4,"text":"查找对象","width":67,"height":20,"color":"#88ef19","var":"title"},"type":"Label"},{"props":{"x":52,"y":75,"skin":"comp/combobox.png","labels":"name,class","width":63,"height":21,"var":"typeSelect","sizeGrid":"5,35,5,5","labelColors":"#a0a0a0,#fffff,#ffffff#fffff"},"type":"ComboBox"},{"props":{"x":10,"y":77,"text":"类型","width":27,"height":20,"color":"#88ef19","align":"right"},"type":"Label"},{"props":{"x":7,"y":34,"text":"包含内容","width":47,"height":20,"color":"#88ef19","align":"right"},"type":"Label"},{"props":{"x":59,"y":31,"skin":"comp/textinput.png","text":"Sprite","width":131,"height":22,"var":"findTxt","sizeGrid":"5,5,5,5","color":"#a0a0a0"},"type":"TextInput"},{"type":"List","child":[{"type":"RankListItem","props":{"y":30,"left":5,"right":5,"name":"render","x":30,"runtime":"laya.debug.uicomps.RankListItem"}}],"props":{"x":6,"y":106,"width":188,"height":180,"vScrollBarSkin":"comp/vscroll.png","var":"result"}},{"props":{"x":125,"y":73,"skin":"comp/button.png","label":"查找","width":65,"height":23,"var":"findBtn","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"},"type":"Button"}],"props":{"width":200,"height":300,"base64pic":true}};} ]); return FindNodeUI; })(View) //class laya.debug.ui.debugui.MinBtnCompUI extends laya.ui.View var MinBtnCompUI=(function(_super){ function MinBtnCompUI(){ this.minBtn=null; this.maxUI=null; this.bg=null; this.maxBtn=null; MinBtnCompUI.__super.call(this); } __class(MinBtnCompUI,'laya.debug.ui.debugui.MinBtnCompUI',_super); var __proto=MinBtnCompUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(MinBtnCompUI.uiView); } __proto.viewMapRegists=function(){} __static(MinBtnCompUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"x":7,"y":8,"skin":"comp/minBtn.png","stateNum":"3","var":"minBtn","width":22,"height":20,"toolTip":"最小化"},"type":"Button"},{"type":"Box","child":[{"props":{"x":0,"y":0,"skin":"view/bg_panel.png","var":"bg","width":36,"height":36,"sizeGrid":"5,5,5,5"},"type":"Image"},{"props":{"x":6,"y":8,"skin":"view/zoom_out.png","stateNum":"2","var":"maxBtn"},"type":"Button"}],"props":{"var":"maxUI"}}],"props":{"width":36,"height":36,"base64pic":true}};} ]); return MinBtnCompUI; })(View) //class laya.debug.ui.debugui.NodeListPanelUI extends laya.ui.View var NodeListPanelUI=(function(_super){ function NodeListPanelUI(){ this.bg=null; this.closeBtn=null; this.title=null; this.itemList=null; NodeListPanelUI.__super.call(this); } __class(NodeListPanelUI,'laya.debug.ui.debugui.NodeListPanelUI',_super); var __proto=NodeListPanelUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(NodeListPanelUI.uiView); } __proto.viewMapRegists=function(){ View.regComponent("laya.debug.uicomps.RankListItem",RankListItem); } __static(NodeListPanelUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"x":235,"y":284,"skin":"view/bg_panel.png","left":0,"right":0,"top":0,"bottom":0,"var":"bg","sizeGrid":"5,5,5,5"},"type":"Image"},{"props":{"x":204,"y":32,"skin":"view/btn_close.png","var":"closeBtn","top":2,"right":2,"visible":true},"type":"Button"},{"props":{"x":10,"y":6,"text":"节点信息","width":147,"height":16,"color":"#288edf","var":"title"},"type":"Label"},{"type":"List","child":[{"type":"RankListItem","props":{"left":5,"right":5,"name":"render","runtime":"laya.debug.uicomps.RankListItem"}}],"props":{"vScrollBarSkin":"comp/vscroll.png","var":"itemList","left":2,"right":2,"top":26,"bottom":0,"repeatX":1,"x":20}}],"props":{"width":200,"height":300}};} ]); return NodeListPanelUI; })(View) //class laya.debug.ui.debugui.NodeToolUI extends laya.ui.View var NodeToolUI=(function(_super){ function NodeToolUI(){ this.bg=null; this.closeBtn=null; this.tarTxt=null; this.freshBtn=null; this.mouseAnalyseBtn=null; this.dragIcon=null; NodeToolUI.__super.call(this); } __class(NodeToolUI,'laya.debug.ui.debugui.NodeToolUI',_super); var __proto=NodeToolUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(NodeToolUI.uiView); } __proto.viewMapRegists=function(){} __static(NodeToolUI, ['uiView',function(){return this.uiView={"type":"View","props":{"base64pic":true,"width":200,"height":341},"child":[{"type":"Image","props":{"x":195,"y":244,"skin":"view/bg_panel.png","left":0,"right":0,"top":0,"bottom":0,"var":"bg","sizeGrid":"5,5,5,5"}},{"type":"Label","props":{"x":9,"y":5,"text":"当前选中对象","width":67,"height":16,"color":"#a0a0a0"}},{"type":"Button","props":{"x":195,"y":25,"skin":"view/btn_close.png","var":"closeBtn","top":2,"right":2}},{"type":"Label","props":{"x":10,"y":25,"text":"当前对象","width":67,"height":16,"color":"#a0a0a0","var":"tarTxt"}},{"type":"Button","props":{"x":15,"y":65,"skin":"comp/button.png","label":"父链","width":39,"height":23,"mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":66,"y":65,"skin":"comp/button.png","label":"子","width":35,"height":23,"mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":112,"y":65,"skin":"comp/button.png","label":"兄弟","width":49,"height":23,"mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":13,"y":117,"skin":"comp/button.png","label":"Enable链","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":100,"y":117,"skin":"comp/button.png","label":"Size链","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Label","props":{"x":14,"y":97,"text":"节点链信息","width":67,"height":16,"color":"#a0a0a0"}},{"type":"Label","props":{"x":15,"y":45,"text":"对象选取","width":67,"height":16,"color":"#a0a0a0"}},{"type":"Label","props":{"x":16,"y":145,"text":"节点显示","width":67,"height":16,"color":"#a0a0a0"}},{"type":"Button","props":{"x":13,"y":164,"skin":"comp/button.png","label":"隐藏旁支","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":100,"y":164,"skin":"comp/button.png","label":"隐藏兄弟","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":13,"y":197,"skin":"comp/button.png","label":"隐藏子","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":99,"y":197,"skin":"comp/button.png","label":"恢复","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Label","props":{"x":15,"y":228,"text":"其他","width":67,"height":16,"color":"#a0a0a0"}},{"type":"Button","props":{"x":12,"y":247,"skin":"comp/button.png","label":"节点树定位","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":99,"y":247,"skin":"comp/button.png","label":"显示边框","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Label","props":{"x":12,"y":315,"text":"Alt+A分析鼠标能否够点中对象","width":173,"height":16,"color":"#a0a0a0"}},{"type":"Button","props":{"x":156,"y":1,"skin":"view/refresh2.png","var":"freshBtn","left":156,"toolTip":"recache节点"}},{"type":"Button","props":{"x":12,"y":279,"skin":"comp/button.png","label":"输出到控制台","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Button","props":{"x":99,"y":279,"skin":"comp/button.png","label":"显示切换","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"}},{"type":"Clip","props":{"y":44,"skin":"view/clickanalyse.png","var":"mouseAnalyseBtn","toolTip":"拖动到对象上方判断是否能够点中","left":84,"x":84,"clipY":3}},{"type":"Clip","props":{"y":35,"skin":"view/clickanalyse.png","var":"dragIcon","x":94,"clipY":3}}]};} ]); return NodeToolUI; })(View) //class laya.debug.ui.debugui.NodeTreeSettingUI extends laya.ui.View var NodeTreeSettingUI=(function(_super){ function NodeTreeSettingUI(){ this.bg=null; this.showTxt=null; this.okBtn=null; this.closeBtn=null; NodeTreeSettingUI.__super.call(this); } __class(NodeTreeSettingUI,'laya.debug.ui.debugui.NodeTreeSettingUI',_super); var __proto=NodeTreeSettingUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(NodeTreeSettingUI.uiView); } __proto.viewMapRegists=function(){} __static(NodeTreeSettingUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"x":0,"y":0,"skin":"view/bg_panel.png","left":0,"top":0,"bottom":0,"right":0,"var":"bg","width":200,"height":300,"sizeGrid":"5,5,5,5"},"type":"Image"},{"props":{"x":9,"y":7,"text":"要显示的属性","width":76,"height":16,"color":"#ffffff","align":"left"},"type":"Label"},{"props":{"x":6,"y":29,"skin":"comp/textinput.png","text":"x\\ny\\nwidth\\nheight","width":188,"height":230,"multiline":true,"var":"showTxt","color":"#a0a0a0","sizeGrid":"5,5,5,5"},"type":"TextInput"},{"props":{"x":57,"y":269,"skin":"comp/button.png","label":"确定","var":"okBtn","mouseEnabled":"true","labelColors":"#ffffff,#ffffff,#ffffff,#ffffff"},"type":"Button"},{"props":{"x":175,"y":5,"skin":"view/btn_close.png","var":"closeBtn"},"type":"Button"}],"props":{"base64pic":true,"width":200,"height":300}};} ]); return NodeTreeSettingUI; })(View) //class laya.debug.ui.debugui.NodeTreeUI extends laya.ui.View var NodeTreeUI=(function(_super){ function NodeTreeUI(){ this.nodeTree=null; this.controlBar=null; this.settingBtn=null; this.freshBtn=null; this.fliterTxt=null; this.closeBtn=null; this.ifShowProps=null; NodeTreeUI.__super.call(this); } __class(NodeTreeUI,'laya.debug.ui.debugui.NodeTreeUI',_super); var __proto=NodeTreeUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(NodeTreeUI.uiView); } __proto.viewMapRegists=function(){ View.regComponent("laya.debug.uicomps.TreeListItem",TreeListItem); } __static(NodeTreeUI, ['uiView',function(){return this.uiView={"type":"View","props":{"width":200,"height":260,"base64pic":true},"child":[{"type":"Image","props":{"x":-22,"y":-47,"skin":"view/bg_panel.png","width":211,"height":206,"left":0,"right":0,"top":0,"bottom":0,"sizeGrid":"5,5,5,5"}},{"props":{"y":0,"skin":"view/bg_tool.png","left":0,"right":0},"type":"Image"},{"type":"Tree","props":{"x":0,"scrollBarSkin":"comp/vscroll.png","width":195,"height":229,"var":"nodeTree","left":0,"right":0,"top":38,"bottom":20},"child":[{"type":"ListItem","props":{"y":0,"name":"render","left":0,"right":0,"runtime":"laya.debug.uicomps.TreeListItem"}}]},{"type":"Box","props":{"x":3,"y":5,"var":"controlBar","left":3,"right":3,"top":5,"height":23},"child":[{"type":"Button","props":{"x":6,"skin":"view/setting.png","stateNum":3,"var":"settingBtn","toolTip":"设置显示的属性","y":6}},{"type":"Button","props":{"y":6,"skin":"view/refresh.png","var":"freshBtn","left":30,"toolTip":"刷新数据"}},{"type":"TextInput","props":{"y":0,"skin":"view/bg_top.png","height":22,"var":"fliterTxt","left":53,"right":0,"color":"#a0a0a0"}},{"type":"Button","props":{"x":172,"y":2,"skin":"view/btn_close.png","var":"closeBtn","right":1,"visible":false}}]},{"props":{"y":243,"skin":"comp/checkbox.png","label":"显示属性","var":"ifShowProps","bottom":3,"selected":true,"visible":true,"x":2,"width":70,"height":14,"labelColors":"#a0a0a0,#fffff,#ffffff,#fffff"},"type":"CheckBox"}]};} ]); return NodeTreeUI; })(View) //class laya.debug.ui.debugui.ObjectCreateUI extends laya.ui.View var ObjectCreateUI=(function(_super){ function ObjectCreateUI(){ this.bg=null; this.closeBtn=null; this.itemList=null; this.freshBtn=null; ObjectCreateUI.__super.call(this); } __class(ObjectCreateUI,'laya.debug.ui.debugui.ObjectCreateUI',_super); var __proto=ObjectCreateUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(ObjectCreateUI.uiView); } __proto.viewMapRegists=function(){ View.regComponent("laya.debug.uicomps.RankListItem",RankListItem); } __static(ObjectCreateUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"x":215,"y":264,"skin":"view/bg_panel.png","left":0,"right":0,"top":0,"bottom":0,"var":"bg","sizeGrid":"5,5,5,5"},"type":"Image"},{"props":{"x":184,"y":12,"skin":"view/btn_close.png","var":"closeBtn","top":2,"right":2,"visible":false},"type":"Button"},{"props":{"x":11,"y":5,"text":"对象创建统计","width":83,"height":16,"color":"#288edf"},"type":"Label"},{"type":"List","child":[{"type":"RankListItem","props":{"y":0,"left":5,"right":5,"name":"render","runtime":"laya.debug.uicomps.RankListItem"}}],"props":{"vScrollBarSkin":"comp/vscroll.png","var":"itemList","top":26,"bottom":5,"left":5,"right":5,"repeatX":1}},{"props":{"y":1,"skin":"view/refresh2.png","var":"freshBtn","toolTip":"刷新数据","right":1,"x":178},"type":"Button"}],"props":{"width":200,"height":300,"base64pic":true}};} ]); return ObjectCreateUI; })(View) //class laya.debug.ui.debugui.ObjectInfoUI extends laya.ui.View var ObjectInfoUI=(function(_super){ function ObjectInfoUI(){ this.bg=null; this.title=null; this.showTxt=null; this.closeBtn=null; this.autoUpdate=null; this.settingBtn=null; ObjectInfoUI.__super.call(this); } __class(ObjectInfoUI,'laya.debug.ui.debugui.ObjectInfoUI',_super); var __proto=ObjectInfoUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(ObjectInfoUI.uiView); } __proto.viewMapRegists=function(){} __static(ObjectInfoUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"x":-1,"y":0,"skin":"view/bg_panel.png","left":-1,"right":1,"top":0,"bottom":0,"var":"bg","sizeGrid":"5,5,5,5"},"type":"Image"},{"props":{"x":7,"y":5,"text":"对象类型","width":67,"height":20,"color":"#ffffff","var":"title","left":7,"right":6},"type":"Label"},{"props":{"x":2,"skin":"comp/textinput.png","text":"属性内容","width":196,"height":228,"left":2,"right":2,"var":"showTxt","top":25,"bottom":20,"editable":false,"multiline":true,"sizeGrid":"5,5,5,5","color":"#a0a0a0"},"type":"TextArea"},{"props":{"x":178,"y":4,"skin":"view/btn_close.png","var":"closeBtn","top":4,"right":2},"type":"Button"},{"props":{"skin":"comp/checkbox.png","label":"自动刷新属性","var":"autoUpdate","bottom":2,"x":3,"labelColors":"#a0a0a0,#fffff,#ffffff,#fffff"},"type":"CheckBox"},{"props":{"x":164,"skin":"view/setting.png","stateNum":"3","var":"settingBtn","y":6,"top":6,"right":24,"toolTip":"设置显示属性"},"type":"Button"},{"props":{"x":179,"y":257,"skin":"view/resize.png","right":2,"bottom":2,"name":"resizeBtn","stateNum":3},"type":"Button"}],"props":{"base64pic":true,"width":200,"height":200}};} ]); return ObjectInfoUI; })(View) //class laya.debug.ui.debugui.OutPutUI extends laya.ui.View var OutPutUI=(function(_super){ function OutPutUI(){ this.bg=null; this.txt=null; this.closeBtn=null; this.clearBtn=null; OutPutUI.__super.call(this); } __class(OutPutUI,'laya.debug.ui.debugui.OutPutUI',_super); var __proto=OutPutUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(OutPutUI.uiView); } __proto.viewMapRegists=function(){} __static(OutPutUI, ['uiView',function(){return this.uiView={"type":"View","props":{"width":300,"height":200,"base64pic":true},"child":[{"type":"Image","props":{"x":205,"y":254,"skin":"view/bg_panel.png","left":0,"right":0,"top":0,"bottom":0,"var":"bg","sizeGrid":"5,5,5,5"}},{"type":"Label","props":{"skin":"comp/textarea.png","text":"TextArea","color":"#a0a0a0","var":"txt","left":5,"right":5,"top":22,"bottom":5,"mouseEnabled":true,"sizeGrid":"3,3,3,3"}},{"type":"Button","props":{"x":185,"y":15,"skin":"view/btn_close.png","var":"closeBtn","top":2,"right":2}},{"props":{"x":253,"y":1,"skin":"view/re.png","stateNum":"2","var":"clearBtn","right":25},"type":"Button"},{"props":{"x":169,"y":247,"skin":"view/resize.png","right":2,"bottom":2,"name":"resizeBtn","stateNum":3},"type":"Button"}]};} ]); return OutPutUI; })(View) //class laya.debug.ui.debugui.ProfileUI extends laya.ui.View var ProfileUI=(function(_super){ function ProfileUI(){ this.renderPanel=null; this.createPanel=null; this.cachePanel=null; this.tab=null; this.resPanel=null; ProfileUI.__super.call(this); } __class(ProfileUI,'laya.debug.ui.debugui.ProfileUI',_super); var __proto=ProfileUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(ProfileUI.uiView); } __proto.viewMapRegists=function(){ View.regComponent("laya.debug.view.nodeInfo.views.RenderCostRankView",RenderCostRankView); View.regComponent("laya.debug.view.nodeInfo.views.ObjectCreateView",ObjectCreateView); View.regComponent("laya.debug.view.nodeInfo.views.CacheRankView",CacheRankView); View.regComponent("laya.debug.view.nodeInfo.views.ResRankView",ResRankView); } __static(ProfileUI, ['uiView',function(){return this.uiView={"type":"View","props":{"width":260,"height":329,"base64pic":true},"child":[{"type":"Image","props":{"y":0,"skin":"view/bg_tool.png","right":0,"left":0}},{"type":"Rank","props":{"var":"renderPanel","top":29,"runtime":"laya.debug.view.nodeInfo.views.RenderCostRankView","right":0,"name":"渲染用时","left":0,"bottom":0}},{"type":"ObjectCreate","props":{"var":"createPanel","top":29,"runtime":"laya.debug.view.nodeInfo.views.ObjectCreateView","right":0,"name":"对象创建统计","left":0,"bottom":0}},{"type":"Rank","props":{"x":10,"var":"cachePanel","top":29,"runtime":"laya.debug.view.nodeInfo.views.CacheRankView","right":0,"name":"cache用时","left":0,"bottom":0}},{"type":"Tab","props":{"y":9,"x":7,"width":191,"var":"tab","selectedIndex":0,"height":19},"child":[{"type":"CheckBox","props":{"y":0,"x":0,"width":50,"skin":"view/create.png","name":"item0","labelColors":"#a0a0a0,#ffffff,#ffffff,#ffffff","label":" 对象","height":17}},{"type":"CheckBox","props":{"y":0,"x":55,"width":50,"skin":"view/rendertime.png","name":"item1","labelColors":"#a0a0a0,#ffffff,#ffffff,#ffffff","label":" 渲染","height":19}},{"type":"CheckBox","props":{"y":0,"x":110,"width":50,"skin":"view/cache.png","name":"item2","labelColors":"#a0a0a0,#ffffff,#ffffff,#ffffff","label":" 重绘","height":16}},{"type":"CheckBox","props":{"y":0,"x":165,"width":50,"skin":"view/cache.png","name":"item3","labelColors":"#a0a0a0,#ffffff,#ffffff,#ffffff","label":" 资源","height":16}}]},{"type":"Rank","props":{"y":40,"x":50,"var":"resPanel","top":29,"runtime":"laya.debug.view.nodeInfo.views.ResRankView","right":0,"name":"资源缓存","left":0,"bottom":0}}]};} ]); return ProfileUI; })(View) //class laya.debug.ui.debugui.RankUI extends laya.ui.View var RankUI=(function(_super){ function RankUI(){ this.bg=null; this.closeBtn=null; this.title=null; this.itemList=null; this.autoUpdate=null; this.freshBtn=null; RankUI.__super.call(this); } __class(RankUI,'laya.debug.ui.debugui.RankUI',_super); var __proto=RankUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(RankUI.uiView); } __proto.viewMapRegists=function(){ View.regComponent("laya.debug.uicomps.RankListItem",RankListItem); } __static(RankUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"x":225,"y":274,"skin":"view/bg_panel.png","left":0,"right":0,"top":0,"bottom":0,"var":"bg","sizeGrid":"5,5,5,5"},"type":"Image"},{"props":{"x":194,"y":22,"skin":"view/btn_close.png","var":"closeBtn","top":2,"right":2,"visible":false},"type":"Button"},{"props":{"x":8,"y":5,"text":"渲染用时表(3000ms)","width":109,"height":16,"color":"#288edf","var":"title"},"type":"Label"},{"type":"List","child":[{"type":"RankListItem","props":{"left":5,"right":5,"name":"render","runtime":"laya.debug.uicomps.RankListItem"}}],"props":{"vScrollBarSkin":"comp/vscroll.png","var":"itemList","left":2,"right":2,"top":26,"bottom":25,"repeatX":1,"x":10,"y":10}},{"props":{"skin":"comp/checkbox.png","label":"自动刷新属性","var":"autoUpdate","bottom":3,"selected":false,"visible":true,"left":2,"labelColors":"#a0a0a0,#fffff,#ffffff,#fffff"},"type":"CheckBox"},{"props":{"y":1,"skin":"view/refresh2.png","var":"freshBtn","toolTip":"刷新数据","right":1},"type":"Button"}],"props":{"width":200,"height":300}};} ]); return RankUI; })(View) //class laya.debug.ui.debugui.SelectInfosUI extends laya.ui.View var SelectInfosUI=(function(_super){ function SelectInfosUI(){ this.bg=null; this.closeBtn=null; this.selectList=null; this.findBtn=null; this.fliterTxt=null; SelectInfosUI.__super.call(this); } __class(SelectInfosUI,'laya.debug.ui.debugui.SelectInfosUI',_super); var __proto=SelectInfosUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(SelectInfosUI.uiView); } __proto.viewMapRegists=function(){ View.regComponent("laya.debug.uicomps.RankListItem",RankListItem); } __static(SelectInfosUI, ['uiView',function(){return this.uiView={"type":"View","child":[{"props":{"x":205,"y":254,"skin":"view/bg_panel.png","left":0,"right":0,"top":0,"bottom":0,"var":"bg","sizeGrid":"5,5,5,5"},"type":"Image"},{"props":{"skin":"view/btn_close.png","var":"closeBtn","top":32,"visible":false,"right":2},"type":"Button"},{"props":{"x":7,"y":36,"text":"当前选中列表","width":83,"height":16,"color":"#288edf"},"type":"Label"},{"type":"List","child":[{"type":"RankListItem","props":{"left":5,"right":5,"name":"render","runtime":"laya.debug.uicomps.RankListItem"}}],"props":{"vScrollBarSkin":"comp/vscroll.png","var":"selectList","left":5,"right":5,"top":56,"bottom":25,"repeatX":1,"x":20}},{"props":{"x":6,"text":"Alt+V选取鼠标下的对象","width":189,"height":16,"color":"#a0a0a0","bottom":3},"type":"Label"},{"type":"Image","props":{"y":0,"skin":"view/bg_tool.png","left":0,"right":0}},{"type":"Clip","props":{"y":6,"skin":"view/search.png","clipY":2,"var":"findBtn","right":5,"toolTip":"查找","x":174}},{"type":"TextInput","props":{"y":6,"skin":"view/bg_top.png","height":22,"var":"fliterTxt","left":8,"right":45,"color":"#a0a0a0","x":8,"width":147}}],"props":{"width":200,"height":300,"base64pic":true}};} ]); return SelectInfosUI; })(View) //class laya.debug.ui.debugui.ToolBarUI extends laya.ui.View var ToolBarUI=(function(_super){ function ToolBarUI(){ this.bg=null; this.treeBtn=null; this.findBtn=null; this.minBtn=null; this.selectWhenClick=null; this.clearBtn=null; this.rankBtn=null; this.nodeRankBtn=null; this.cacheBtn=null; ToolBarUI.__super.call(this); } __class(ToolBarUI,'laya.debug.ui.debugui.ToolBarUI',_super); var __proto=ToolBarUI.prototype; __proto.createChildren=function(){ this.viewMapRegists(); laya.ui.Component.prototype.createChildren.call(this); this.createView(ToolBarUI.uiView); } __proto.viewMapRegists=function(){ View.regComponent("laya.debug.view.nodeInfo.nodetree.MinBtnComp",MinBtnComp); } __static(ToolBarUI, ['uiView',function(){return this.uiView={"type":"View","props":{"base64pic":true,"width":250,"height":30},"child":[{"type":"Image","props":{"x":195,"y":244,"skin":"view/bg_panel.png","left":0,"right":0,"top":0,"bottom":0,"var":"bg","sizeGrid":"5,5,5,5"}},{"type":"Button","props":{"x":2,"y":6,"skin":"view/save.png","stateNum":2,"var":"treeBtn","toolTip":"节点树"}},{"type":"Button","props":{"x":25,"y":6,"skin":"view/save.png","stateNum":2,"var":"findBtn","toolTip":"查找面板"}},{"type":"MinBtnComp","props":{"x":218,"y":-3,"var":"minBtn","runtime":"laya.debug.view.nodeInfo.nodetree.MinBtnComp"}},{"type":"CheckBox","props":{"x":124,"y":8,"skin":"comp/checkbox.png","label":"点击选取","var":"selectWhenClick","labelColors":"#a0a0a0,#fffff,#ffffff,#fffff"}},{"type":"Button","props":{"x":193,"y":5,"skin":"view/res.png","stateNum":2,"toolTip":"清除边框","var":"clearBtn"}},{"type":"Button","props":{"x":49,"y":6,"skin":"view/save.png","stateNum":2,"var":"rankBtn","toolTip":"渲染用时排行"}},{"type":"Button","props":{"x":72,"y":6,"skin":"view/save.png","stateNum":2,"var":"nodeRankBtn","toolTip":"创建对象排行"}},{"type":"Button","props":{"x":94,"y":6,"skin":"view/save.png","stateNum":2,"var":"cacheBtn","toolTip":"cache对象"}}]};} ]); return ToolBarUI; })(View) /** * *@author ww *@version 1.0 * *@created 2016-7-6 上午9:42:46 */ //class laya.debug.uicomps.ListBase extends laya.ui.List var ListBase=(function(_super){ function ListBase(){ ListBase.__super.call(this); } __class(ListBase,'laya.debug.uicomps.ListBase',_super); var __proto=ListBase.prototype; __getset(0,__proto,'selectedIndex',_super.prototype._$get_selectedIndex,function(value){ if (this._selectedIndex !=value){ this._selectedIndex=value; this.changeSelectStatus(); this.event(/*laya.events.Event.CHANGE*/"change"); this.selectHandler && this.selectHandler.runWith(value); } if (this.selectEnable && this._scrollBar){ var numX=this._isVertical ? this.repeatX :this.repeatY; if (value < this._startIndex || (value+numX > this._startIndex+this.repeatX *this.repeatY)){ this.scrollTo(value); } } }); return ListBase; })(List) /** * *@author ww *@version 1.0 * *@created 2016-7-6 上午9:49:47 */ //class laya.debug.uicomps.TreeBase extends laya.ui.Tree var TreeBase=(function(_super){ function TreeBase(){ TreeBase.__super.call(this); } __class(TreeBase,'laya.debug.uicomps.TreeBase',_super); var __proto=TreeBase.prototype; /**@inheritDoc */ __proto.createChildren=function(){ this.addChild(this._list=new ListBase()); this._list.renderHandler=Handler.create(this,this.renderItem,null,false); this._list.repeatX=1; this._list.on(/*laya.events.Event.CHANGE*/"change",this,this.onListChange); } return TreeBase; })(Tree) /** *... *@author ww */ //class laya.debug.uicomps.RankListItem extends laya.debug.ui.debugui.comps.RankListItemUI var RankListItem=(function(_super){ function RankListItem(){ RankListItem.__super.call(this); Base64AtlasManager.replaceRes(RankListItemUI.uiView); this.createView(RankListItemUI.uiView); } __class(RankListItem,'laya.debug.uicomps.RankListItem',_super); var __proto=RankListItem.prototype; __proto.createChildren=function(){} return RankListItem; })(RankListItemUI) /** *... *@author ww */ //class laya.debug.uicomps.TreeListItem extends laya.debug.ui.debugui.comps.ListItemUI var TreeListItem=(function(_super){ function TreeListItem(){ TreeListItem.__super.call(this); Base64AtlasManager.replaceRes(ListItemUI.uiView); this.createView(ListItemUI.uiView); } __class(TreeListItem,'laya.debug.uicomps.TreeListItem',_super); var __proto=TreeListItem.prototype; __proto.createChildren=function(){} return TreeListItem; })(ListItemUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.DebugPage extends laya.debug.ui.debugui.DebugPanelUI var DebugPage=(function(_super){ function DebugPage(){ this.views=null; DebugPage.__super.call(this); this.msRec=new Rectangle(); Base64AtlasManager.replaceRes(DebugPanelUI.uiView); this.createView(DebugPanelUI.uiView); DisControlTool.setResizeAbleEx(this); this.views=[this.treePanel,this.selectPanel,this.profilePanel]; this.tab.selectedIndex=0; this.tabChange(); this.tab.on(/*laya.events.Event.CHANGE*/"change",this,this.tabChange); this.changeSize(); } __class(DebugPage,'laya.debug.view.nodeInfo.nodetree.DebugPage',_super); var __proto=DebugPage.prototype; __proto.createChildren=function(){ this.viewMapRegists(); } __proto.tabChange=function(){ DisControlTool.addOnlyByIndex(this.views,this.tab.selectedIndex,this); DisControlTool.setTop(this.resizeBtn); } __proto.changeSize=function(){ if (this.width < 245){ this.width=245; } if (this.height < 100){ this.height=200; } laya.ui.Component.prototype.changeSize.call(this); this.msRec.setTo(0,0,this.width,this.height); this.scrollRect=this.msRec; } return DebugPage; })(DebugPanelUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.FindNode extends laya.debug.ui.debugui.FindNodeUI var FindNode=(function(_super){ function FindNode(){ FindNode.__super.call(this); Base64AtlasManager.replaceRes(FindNodeUI.uiView); this.createView(FindNodeUI.uiView); } __class(FindNode,'laya.debug.view.nodeInfo.nodetree.FindNode',_super); var __proto=FindNode.prototype; __proto.createChildren=function(){ this.viewMapRegists(); } return FindNode; })(FindNodeUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.FindNodeSmall extends laya.debug.ui.debugui.FindNodeSmallUI var FindNodeSmall=(function(_super){ function FindNodeSmall(){ FindNodeSmall.__super.call(this); Base64AtlasManager.replaceRes(FindNodeSmallUI.uiView); this.createView(FindNodeSmallUI.uiView); } __class(FindNodeSmall,'laya.debug.view.nodeInfo.nodetree.FindNodeSmall',_super); var __proto=FindNodeSmall.prototype; __proto.createChildren=function(){} return FindNodeSmall; })(FindNodeSmallUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.MinBtnComp extends laya.debug.ui.debugui.MinBtnCompUI var MinBtnComp=(function(_super){ function MinBtnComp(){ this.tar=null; this.minHandler=null; this.maxHandler=null; this.prePos=new Point(); MinBtnComp.__super.call(this); Base64AtlasManager.replaceRes(MinBtnCompUI.uiView); this.createView(MinBtnCompUI.uiView); this.init(); } __class(MinBtnComp,'laya.debug.view.nodeInfo.nodetree.MinBtnComp',_super); var __proto=MinBtnComp.prototype; __proto.createChildren=function(){} __proto.init=function(){ this.minBtn.on(/*laya.events.Event.CLICK*/"click",this,this.onMinBtn); this.maxBtn.on(/*laya.events.Event.CLICK*/"click",this,this.onMaxBtn); this.minState=false; this.maxUI.removeSelf(); DisControlTool.setDragingItem(this.bg,this.maxUI); } __proto.onMaxBtn=function(){ this.maxUI.removeSelf(); if (this.maxHandler){ this.maxHandler.run(); } if (this.tar){ this.tar.x+=this.maxUI.x-this.prePos.x; this.tar.y+=this.maxUI.y-this.prePos.y; } } __proto.onMinBtn=function(){ if (!this.displayedInStage)return; var tPos; tPos=Point.TEMP; tPos.setTo(0,0); tPos=this.localToGlobal(tPos); tPos=DebugInfoLayer.I.popLayer.globalToLocal(tPos); this.maxUI.pos(tPos.x,tPos.y); DebugInfoLayer.I.popLayer.addChild(this.maxUI); if (this.tar){ this.prePos.setTo(tPos.x,tPos.y); } if (this.minHandler){ this.minHandler.run(); } } __getset(0,__proto,'minState',null,function(v){ }); return MinBtnComp; })(MinBtnCompUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.NodeListPanel extends laya.debug.ui.debugui.NodeListPanelUI var NodeListPanel=(function(_super){ function NodeListPanel(){ NodeListPanel.__super.call(this); Base64AtlasManager.replaceRes(NodeListPanelUI.uiView); this.createView(NodeListPanelUI.uiView); } __class(NodeListPanel,'laya.debug.view.nodeInfo.nodetree.NodeListPanel',_super); var __proto=NodeListPanel.prototype; __proto.createChildren=function(){ this.viewMapRegists(); } return NodeListPanel; })(NodeListPanelUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.NodeTool extends laya.debug.ui.debugui.NodeToolUI var NodeTool=(function(_super){ function NodeTool(){ NodeTool.__super.call(this); Base64AtlasManager.replaceRes(NodeToolUI.uiView); this.createView(NodeToolUI.uiView); } __class(NodeTool,'laya.debug.view.nodeInfo.nodetree.NodeTool',_super); var __proto=NodeTool.prototype; __proto.createChildren=function(){} return NodeTool; })(NodeToolUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.NodeTree extends laya.debug.ui.debugui.NodeTreeUI var NodeTree=(function(_super){ function NodeTree(){ this.showProps=false; this._closeSettingHandler=null; this._tar=null; NodeTree.__super.call(this); Base64AtlasManager.replaceRes(NodeTreeUI.uiView); View.regComponent("Tree",TreeBase); this.createView(NodeTreeUI.uiView); View.regComponent("Tree",Tree); this.inits(); NodeTree.I=this; } __class(NodeTree,'laya.debug.view.nodeInfo.nodetree.NodeTree',_super); var __proto=NodeTree.prototype; __proto.createChildren=function(){ this.viewMapRegists(); } __proto.inits=function(){ this.nodeTree.list.scrollBar.hide=true; this.nodeTree.list.selectEnable=true; this.settingBtn.on(/*laya.events.Event.CLICK*/"click",this,this.onSettingBtn); this.freshBtn.on(/*laya.events.Event.CLICK*/"click",this,this.fresh); this.closeBtn.on(/*laya.events.Event.CLICK*/"click",this,this.onCloseBtn); this.fliterTxt.on(/*laya.events.Event.ENTER*/"enter",this,this.onFliterTxtChange); this.fliterTxt.on(/*laya.events.Event.BLUR*/"blur",this,this.onFliterTxtChange); NodeMenu.I.setNodeListAction(this.nodeTree.list); this.nodeTree.list.on(/*laya.events.Event.CLICK*/"click",this,this.onListClick,[this.nodeTree.list]); this.nodeTree.renderHandler=new Handler(this,this.treeRender); this._closeSettingHandler=new Handler(this,this.closeSetting); this.onIfShowPropsChange(); this.ifShowProps.on(/*laya.events.Event.CHANGE*/"change",this,this.onIfShowPropsChange); } __proto.onIfShowPropsChange=function(){ this.showProps=this.ifShowProps.selected; this.fresh(); } __proto.onListClick=function(list){ if (list.selectedItem){ if (list.selectedItem.isDirectory){ list.selectedItem.isOpen=!list.selectedItem.isOpen; this.nodeTree.fresh(); } } } //} __proto.onFindBtn=function(){ FindSmallView.I.show(); } __proto.onCloseBtn=function(){ this.removeSelf(); } __proto.onTreeDoubleClick=function(e){ if (this.nodeTree.selectedItem){ var tarNode; tarNode=this.nodeTree.selectedItem.path; NodeMenu.I.objRightClick(tarNode); } } //} __proto.onTreeRightMouseDown=function(e){ if (this.nodeTree.selectedItem){ var tarNode; tarNode=this.nodeTree.selectedItem.path; NodeMenu.I.objRightClick(tarNode); } } //} __proto.onSettingBtn=function(){ NodeTreeSettingView.I.showSetting(NodeTree.showKeys,this._closeSettingHandler,this._tar); } __proto.closeSetting=function(newKeys){ NodeTree.showKeys=newKeys; this.fresh(); } __proto.onFliterTxtChange=function(e){ var key; key=this.fliterTxt.text; if (key=="")return; if (key !=NodeTree.showKeys.join(",")){ NodeTree.showKeys=key.split(","); this.fresh(); } return; this.selecteByFile(key); } __proto.selecteByFile=function(key){ var arr; arr=this.nodeTree.source; var rsts; rsts=DebugTool.findNameHas(key,false); if (rsts && rsts.length > 0){ var tar; tar=rsts[0]; this.parseOpen(arr,tar); } } __proto.showSelectInStage=function(node){ this.setDis(Laya.stage); this.selectByNode(node); } __proto.selectByNode=function(node){ if (!node)return; var arr; arr=this.nodeTree.source; this.parseOpen(arr,node); } __proto.showNodeList=function(nodeList){ if (!nodeList)return; var i=0,len=0; len=nodeList.length; var showList; showList=[]; var tData; var tSprite; for (i=0;i < len;i++){ tSprite=nodeList[i]; tData={}; tData.label=ClassTool.getNodeClassAndName(tSprite); tData.path=tSprite; showList.push(tData); } this.nodeTree.array=showList; } __proto.parseOpen=function(tree,node){ if (tree.length < 1)return; if (!node)return; var i=0,len=0; len=tree.length; var tItem; for(i=0;i-1){ item.x=0; result.push(item); } if (item.child && item.child.length > 0){ this.getFilterSource(item.child,result,key); } } } __proto.onControlDown=function(){ this.startDrag(); } __proto.setDis=function(sprite){ this._tar=sprite; this.fresh(); } __proto.fresh=function(){ var preTar; if (this.nodeTree.selectedItem){ var tItem; tItem=this.nodeTree.selectedItem; while (tItem && (! (tItem.path instanceof laya.display.Sprite ))){ tItem=tItem.nodeParent; } if (tItem && tItem.path){ preTar=tItem.path; } } if (!this._tar){ this.nodeTree.array=[]; }else{ this.nodeTree.array=NodeUtils.getNodeTreeData(this._tar,this.showProps?NodeTree.showKeys:NodeTree.emptyShowKey); } if (preTar){ this.selectByNode(preTar); } } __proto.treeRender=function(cell,index){ var item=cell.dataSource; if (item){ var isDirectory=item.child || item.isDirectory; var label=cell.getChildByName("label"); if ((item.path instanceof laya.display.Node )){ label.color="#09a4f6"; }else{ if (item.isChilds){ label.color="#00ff11"; }else{ label.color="#838bc5"; } } } } NodeTree.I=null; NodeTree.emptyShowKey=[]; __static(NodeTree, ['showKeys',function(){return this.showKeys=["x","y","width","height","renderCost"];} ]); return NodeTree; })(NodeTreeUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.NodeTreeSetting extends laya.debug.ui.debugui.NodeTreeSettingUI var NodeTreeSetting=(function(_super){ function NodeTreeSetting(){ NodeTreeSetting.__super.call(this); Base64AtlasManager.replaceRes(NodeTreeSettingUI.uiView); this.createView(NodeTreeSettingUI.uiView); } __class(NodeTreeSetting,'laya.debug.view.nodeInfo.nodetree.NodeTreeSetting',_super); var __proto=NodeTreeSetting.prototype; //inits(); __proto.createChildren=function(){} return NodeTreeSetting; })(NodeTreeSettingUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.ObjectCreate extends laya.debug.ui.debugui.ObjectCreateUI var ObjectCreate=(function(_super){ function ObjectCreate(){ ObjectCreate.__super.call(this); Base64AtlasManager.replaceRes(ObjectCreateUI.uiView); this.createView(ObjectCreateUI.uiView); } __class(ObjectCreate,'laya.debug.view.nodeInfo.nodetree.ObjectCreate',_super); var __proto=ObjectCreate.prototype; __proto.createChildren=function(){ this.viewMapRegists(); } return ObjectCreate; })(ObjectCreateUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.ObjectInfo extends laya.debug.ui.debugui.ObjectInfoUI var ObjectInfo=(function(_super){ function ObjectInfo(){ ObjectInfo.__super.call(this); Base64AtlasManager.replaceRes(ObjectInfoUI.uiView); this.createView(ObjectInfoUI.uiView); } __class(ObjectInfo,'laya.debug.view.nodeInfo.nodetree.ObjectInfo',_super); var __proto=ObjectInfo.prototype; __proto.createChildren=function(){} return ObjectInfo; })(ObjectInfoUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.OutPut extends laya.debug.ui.debugui.OutPutUI var OutPut=(function(_super){ function OutPut(){ OutPut.__super.call(this); Base64AtlasManager.replaceRes(OutPutUI.uiView); this.createView(OutPutUI.uiView); } __class(OutPut,'laya.debug.view.nodeInfo.nodetree.OutPut',_super); var __proto=OutPut.prototype; __proto.createChildren=function(){} return OutPut; })(OutPutUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.Profile extends laya.debug.ui.debugui.ProfileUI var Profile=(function(_super){ function Profile(){ this.views=null; Profile.__super.call(this); Base64AtlasManager.replaceRes(ProfileUI.uiView); this.createView(ProfileUI.uiView); this.views=[this.createPanel,this.renderPanel,this.cachePanel,this.resPanel]; this.tab.selectedIndex=0; this.tabChange(); this.tab.on(/*laya.events.Event.CHANGE*/"change",this,this.tabChange); } __class(Profile,'laya.debug.view.nodeInfo.nodetree.Profile',_super); var __proto=Profile.prototype; __proto.createChildren=function(){ this.viewMapRegists(); } __proto.tabChange=function(){ DisControlTool.addOnlyByIndex(this.views,this.tab.selectedIndex,this); } return Profile; })(ProfileUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.Rank extends laya.debug.ui.debugui.RankUI var Rank=(function(_super){ function Rank(){ Rank.__super.call(this); Base64AtlasManager.replaceRes(RankUI.uiView); this.createView(RankUI.uiView); } __class(Rank,'laya.debug.view.nodeInfo.nodetree.Rank',_super); var __proto=Rank.prototype; __proto.createChildren=function(){ this.viewMapRegists(); } return Rank; })(RankUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.SelectInfos extends laya.debug.ui.debugui.SelectInfosUI var SelectInfos=(function(_super){ function SelectInfos(){ SelectInfos.__super.call(this); Base64AtlasManager.replaceRes(SelectInfosUI.uiView); this.createView(SelectInfosUI.uiView); } __class(SelectInfos,'laya.debug.view.nodeInfo.nodetree.SelectInfos',_super); var __proto=SelectInfos.prototype; __proto.createChildren=function(){ this.viewMapRegists(); } return SelectInfos; })(SelectInfosUI) /** *... *@author ww */ //class laya.debug.view.nodeInfo.nodetree.ToolBar extends laya.debug.ui.debugui.ToolBarUI var ToolBar=(function(_super){ function ToolBar(){ ToolBar.__super.call(this); Base64AtlasManager.replaceRes(ToolBarUI.uiView); this.createView(ToolBarUI.uiView); } __class(ToolBar,'laya.debug.view.nodeInfo.nodetree.ToolBar',_super); var __proto=ToolBar.prototype; __proto.createChildren=function(){} return ToolBar; })(ToolBarUI) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.device.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Bitmap=laya.resource.Bitmap,Browser=laya.utils.Browser,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var Handler=laya.utils.Handler,Rectangle=laya.maths.Rectangle,Render=laya.renders.Render,Sprite=laya.display.Sprite; var Stage=laya.display.Stage,Texture=laya.resource.Texture,Utils=laya.utils.Utils,WebGL=laya.webgl.WebGL; var WebGLContext=laya.webgl.WebGLContext; /** *使用前可用supported查看浏览器支持。 */ //class laya.device.geolocation.Geolocation var Geolocation=(function(){ function Geolocation(){} __class(Geolocation,'laya.device.geolocation.Geolocation'); Geolocation.getCurrentPosition=function(onSuccess,onError){ Geolocation.navigator.geolocation.getCurrentPosition(function(pos){ Geolocation.position.setPosition(pos); onSuccess.runWith(Geolocation.position); }, function(error){ onError.runWith(error); },{ enableHighAccuracy :laya.device.geolocation.Geolocation.enableHighAccuracy, timeout :laya.device.geolocation.Geolocation.timeout, maximumAge :laya.device.geolocation.Geolocation.maximumAge }); } Geolocation.watchPosition=function(onSuccess,onError){ return Geolocation.navigator.geolocation.watchPosition(function(pos){ Geolocation.position.setPosition(pos); onSuccess.runWith(Geolocation.position); }, function(error){ onError.runWith(error); },{ enableHighAccuracy :Geolocation.enableHighAccuracy, timeout :Geolocation.timeout, maximumAge :Geolocation.maximumAge }); } Geolocation.clearWatch=function(id){ Geolocation.navigator.geolocation.clearWatch(id); } Geolocation.PERMISSION_DENIED=1; Geolocation.POSITION_UNAVAILABLE=2; Geolocation.TIMEOUT=3; Geolocation.enableHighAccuracy=false; Geolocation.maximumAge=0; __static(Geolocation, ['navigator',function(){return this.navigator=Browser.window.navigator;},'position',function(){return this.position=new GeolocationInfo();},'supported',function(){return this.supported=!!Geolocation.navigator.geolocation;},'timeout',function(){return this.timeout=1E10;} ]); return Geolocation; })() //class laya.device.geolocation.GeolocationInfo var GeolocationInfo=(function(){ function GeolocationInfo(){ this.pos=null; this.coords=null; } __class(GeolocationInfo,'laya.device.geolocation.GeolocationInfo'); var __proto=GeolocationInfo.prototype; __proto.setPosition=function(pos){ this.pos=pos; this.coords=pos.coords; } __getset(0,__proto,'heading',function(){ return this.coords.heading; }); __getset(0,__proto,'latitude',function(){ return this.coords.latitude; }); __getset(0,__proto,'altitudeAccuracy',function(){ return this.coords.altitudeAccuracy; }); __getset(0,__proto,'longitude',function(){ return this.coords.longitude; }); __getset(0,__proto,'altitude',function(){ return this.coords.altitude; }); __getset(0,__proto,'accuracy',function(){ return this.coords.accuracy; }); __getset(0,__proto,'speed',function(){ return this.coords.speed; }); __getset(0,__proto,'timestamp',function(){ return this.pos.timestamp; }); return GeolocationInfo; })() /** *Media用于捕捉摄像头和麦克风。可以捕捉任意之一,或者同时捕捉两者。getCamera前可以使用supported()检查当前浏览器是否支持。 *NOTE: *

    目前Media在移动平台只支持Android,不支持IOS。只可在FireFox完整地使用,Chrome测试时无法捕捉视频。

    */ //class laya.device.media.Media var Media=(function(){ function Media(){} __class(Media,'laya.device.media.Media'); Media.supported=function(){ return !!Browser.window.navigator.getUserMedia; } Media.getMedia=function(options,onSuccess,onError){ if (Browser.window.navigator.getUserMedia){ Browser.window.navigator.getUserMedia(options,function(stream){ onSuccess.runWith(Browser.window.URL.createObjectURL(stream)); },function(err){ onError.runWith(err); }); } } Media.__init$=function(){ /*__JS__ */navigator.getUserMedia=navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;; } return Media; })() /** *加速度x/y/z的单位均为m/s²。 *在硬件(陀螺仪)不支持的情况下,alpha、beta和gamma值为null。 * *@author Survivor */ //class laya.device.motion.AccelerationInfo var AccelerationInfo=(function(){ function AccelerationInfo(){ /** *x轴上的加速度值。 */ this.x=NaN; /** *y轴上的加速度值。 */ this.y=NaN; /** *z轴上的加速度值。 */ this.z=NaN; } __class(AccelerationInfo,'laya.device.motion.AccelerationInfo'); return AccelerationInfo; })() /** *保存旋转信息的类。请勿修改本类的属性。 *@author Survivor */ //class laya.device.motion.RotationInfo var RotationInfo=(function(){ function RotationInfo(){ /** *

    *指示设备是否可以提供绝对方位数据(指向地球坐标系),或者设备决定的任意坐标系。 *关于坐标系参见https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Orientation_and_motion_data_explained。 *

    *需要注意的是,IOS环境下,该值始终为false。即使如此,你依旧可以从alpha中取得正确的值。 */ this.absolute=false; /** *Z轴旋转角度,其值范围从0至360。 *若absolute为true或者在IOS中,alpha值是从北方到当前设备方向的角度值。 */ this.alpha=NaN; /** *X轴旋转角度,其值范围从-180至180。代表设备从前至后的运动。 */ this.beta=NaN; /** *Y轴旋转角度,其值范围从-90至90。代表设备从左至右的运动。 */ this.gamma=NaN; /** *罗盘数据的精确度(角度)。仅IOS可用。 */ this.compassAccuracy=NaN; } __class(RotationInfo,'laya.device.motion.RotationInfo'); return RotationInfo; })() /** *Accelerator.instance获取唯一的Accelerator引用,请勿调用构造函数。 * *

    *listen()的回调处理器接受四个参数: *

      *
    1. acceleration:表示用户给予设备的加速度。
    2. *
    3. accelerationIncludingGravity:设备受到的总加速度(包含重力)。
    4. *
    5. rotationRate:设备的自转速率。
    6. *
    7. interval:加速度获取的时间间隔(毫秒)。
    8. *
    *

    *

    *NOTE
    *如,rotationRate的alpha在apple和moz文档中都是z轴旋转角度,但是实测是x轴旋转角度。为了使各属性表示的值与文档所述相同,实际值与其他属性进行了对调。 *其中: *

      *
    • alpha使用gamma值。
    • *
    • beta使用alpha值。
    • *
    • gamma使用beta。
    • *
    *目前孰是孰非尚未可知,以此为注。 *

    */ //class laya.device.motion.Accelerator extends laya.events.EventDispatcher var Accelerator=(function(_super){ function Accelerator(singleton){ Accelerator.__super.call(this); /*__JS__ */this.onDeviceOrientationChange=this.onDeviceOrientationChange.bind(this); } __class(Accelerator,'laya.device.motion.Accelerator',_super); var __proto=Accelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); Browser.window.addEventListener('devicemotion',this.onDeviceOrientationChange); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) Browser.window.removeEventListener('devicemotion',this.onDeviceOrientationChange) return _super.prototype.off.call(this,type,caller,listener,onceOnly); } __proto.onDeviceOrientationChange=function(e){ var interval=e.interval; Accelerator.acceleration.x=e.acceleration.x; Accelerator.acceleration.y=e.acceleration.y; Accelerator.acceleration.z=e.acceleration.z; Accelerator.accelerationIncludingGravity.x=e.accelerationIncludingGravity.x; Accelerator.accelerationIncludingGravity.y=e.accelerationIncludingGravity.y; Accelerator.accelerationIncludingGravity.z=e.accelerationIncludingGravity.z; Accelerator.rotationRate.alpha=e.rotationRate.gamma *-1; Accelerator.rotationRate.beta=e.rotationRate.alpha *-1; Accelerator.rotationRate.gamma=e.rotationRate.beta; if (Browser.onAndroid){ if (Accelerator.onChrome){ Accelerator.rotationRate.alpha *=180 / Math.PI; Accelerator.rotationRate.beta *=180 / Math.PI; Accelerator.rotationRate.gamma *=180 / Math.PI; } Accelerator.acceleration.x *=-1; Accelerator.accelerationIncludingGravity.x *=-1; } else if (Browser.onIOS){ Accelerator.acceleration.y *=-1; Accelerator.acceleration.z *=-1; Accelerator.accelerationIncludingGravity.y *=-1; Accelerator.accelerationIncludingGravity.z *=-1; interval *=1000; } this.event(/*laya.events.Event.CHANGE*/"change",[Accelerator.acceleration,Accelerator.accelerationIncludingGravity,Accelerator.rotationRate,interval]); } __getset(1,Accelerator,'instance',function(){Accelerator._instance=Accelerator._instance|| new Accelerator(0) return Accelerator._instance; },laya.events.EventDispatcher._$SET_instance); Accelerator.getTransformedAcceleration=function(acceleration){Accelerator.transformedAcceleration=Accelerator.transformedAcceleration|| new AccelerationInfo(); Accelerator.transformedAcceleration.z=acceleration.z; if (Browser.window.orientation==90){ Accelerator.transformedAcceleration.x=acceleration.y; Accelerator.transformedAcceleration.y=-acceleration.x; } else if (Browser.window.orientation==-90){ Accelerator.transformedAcceleration.x=-acceleration.y; Accelerator.transformedAcceleration.y=acceleration.x; } else if (!Browser.window.orientation){ Accelerator.transformedAcceleration.x=acceleration.x; Accelerator.transformedAcceleration.y=acceleration.y; } else if (Browser.window.orientation==180){ Accelerator.transformedAcceleration.x=-acceleration.x; Accelerator.transformedAcceleration.y=-acceleration.y; }; var tx=NaN; if (Laya.stage.canvasDegree==-90){ tx=Accelerator.transformedAcceleration.x; Accelerator.transformedAcceleration.x=-Accelerator.transformedAcceleration.y; Accelerator.transformedAcceleration.y=tx; } else if (Laya.stage.canvasDegree==90){ tx=Accelerator.transformedAcceleration.x; Accelerator.transformedAcceleration.x=Accelerator.transformedAcceleration.y; Accelerator.transformedAcceleration.y=-tx; } return Accelerator.transformedAcceleration; } Accelerator._instance=null; Accelerator.transformedAcceleration=null; __static(Accelerator, ['acceleration',function(){return this.acceleration=new AccelerationInfo();},'accelerationIncludingGravity',function(){return this.accelerationIncludingGravity=new AccelerationInfo();},'rotationRate',function(){return this.rotationRate=new RotationInfo();},'onChrome',function(){return this.onChrome=(Browser.userAgent.indexOf("Chrome")>-1);} ]); return Accelerator; })(EventDispatcher) /** *使用Gyroscope.instance获取唯一的Gyroscope引用,请勿调用构造函数。 * *

    *listen()的回调处理器接受两个参数: *function onOrientationChange(absolute:Boolean,info:RotationInfo):void *

      *
    1. absolute:指示设备是否可以提供绝对方位数据(指向地球坐标系),或者设备决定的任意坐标系。关于坐标系参见https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Orientation_and_motion_data_explained
    2. *
    3. info:RotationInfo类型参数,保存设备的旋转值。
    4. *
    *

    * *

    *浏览器兼容性参见:http://caniuse.com/#search=deviceorientation *

    */ //class laya.device.motion.Gyroscope extends laya.events.EventDispatcher var Gyroscope=(function(_super){ function Gyroscope(singleton){ Gyroscope.__super.call(this); /*__JS__ */this.onDeviceOrientationChange=this.onDeviceOrientationChange.bind(this); } __class(Gyroscope,'laya.device.motion.Gyroscope',_super); var __proto=Gyroscope.prototype; /** *监视陀螺仪运动。 *@param observer 回调函数接受一个Boolean类型的absoluteGyroscopeInfo类型参数。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); Browser.window.addEventListener('deviceorientation',this.onDeviceOrientationChange); return this; } /** *取消指定处理器对陀螺仪的监视。 *@param observer */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) Browser.window.removeEventListener('deviceorientation',this.onDeviceOrientationChange); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } __proto.onDeviceOrientationChange=function(e){ Gyroscope.info.alpha=e.alpha; Gyroscope.info.beta=e.beta; Gyroscope.info.gamma=e.gamma; if (e.webkitCompassHeading){ Gyroscope.info.alpha=e.webkitCompassHeading *-1; Gyroscope.info.compassAccuracy=e.webkitCompassAccuracy; } this.event(/*laya.events.Event.CHANGE*/"change",[e.absolute,Gyroscope.info]); } __getset(1,Gyroscope,'instance',function(){Gyroscope._instance=Gyroscope._instance|| new Gyroscope(0); return Gyroscope._instance; },laya.events.EventDispatcher._$SET_instance); Gyroscope._instance=null; __static(Gyroscope, ['info',function(){return this.info=new RotationInfo();} ]); return Gyroscope; })(EventDispatcher) /** *Shake只能在支持此操作的设备上有效。 * *@author Survivor */ //class laya.device.Shake extends laya.events.EventDispatcher var Shake=(function(_super){ function Shake(){ this.throushold=0; this.shakeInterval=0; this.callback=null; this.lastX=NaN; this.lastY=NaN; this.lastZ=NaN; this.lastMillSecond=NaN; Shake.__super.call(this); } __class(Shake,'laya.device.Shake',_super); var __proto=Shake.prototype; /** *开始响应设备摇晃。 *@param throushold 响应的瞬时速度阈值,轻度摇晃的值约在5~10间。 *@param timeout 设备摇晃的响应间隔时间。 *@param callback 在设备摇晃触发时调用的处理器。 */ __proto.start=function(throushold,interval){ this.throushold=throushold; this.shakeInterval=interval; this.lastX=this.lastY=this.lastZ=NaN; Accelerator.instance.on(/*laya.events.Event.CHANGE*/"change",this,this.onShake); } /** *停止响应设备摇晃。 */ __proto.stop=function(){ Accelerator.instance.off(/*laya.events.Event.CHANGE*/"change",this,this.onShake); } __proto.onShake=function(acceleration,accelerationIncludingGravity,rotationRate,interval){ if(isNaN(this.lastX)){ this.lastX=accelerationIncludingGravity.x; this.lastY=accelerationIncludingGravity.y; this.lastZ=accelerationIncludingGravity.z; this.lastMillSecond=Browser.now(); return; }; var deltaX=Math.abs(this.lastX-accelerationIncludingGravity.x); var deltaY=Math.abs(this.lastY-accelerationIncludingGravity.y); var deltaZ=Math.abs(this.lastZ-accelerationIncludingGravity.z); if(this.isShaked(deltaX,deltaY,deltaZ)){ var deltaMillSecond=Browser.now()-this.lastMillSecond; if (deltaMillSecond > this.shakeInterval){ this.event(/*laya.events.Event.CHANGE*/"change"); this.lastMillSecond=Browser.now(); } } this.lastX=accelerationIncludingGravity.x; this.lastY=accelerationIncludingGravity.y; this.lastZ=accelerationIncludingGravity.z; } // 通过任意两个分量判断是否满足摇晃设定。 __proto.isShaked=function(deltaX,deltaY,deltaZ){ return (deltaX > this.throushold && deltaY > this.throushold)|| (deltaX > this.throushold && deltaZ > this.throushold)|| (deltaY > this.throushold && deltaZ > this.throushold) } __getset(1,Shake,'instance',function(){Shake._instance=Shake._instance|| new Shake(); return Shake._instance; },laya.events.EventDispatcher._$SET_instance); Shake._instance=null; return Shake; })(EventDispatcher) /** *Video将视频显示到Canvas上。Video可能不会在所有浏览器有效。 *

    关于Video支持的所有事件参见:http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp

    *

    *注意:
    *在PC端可以在任何时机调用play()因此,可以在程序开始运行时就使Video开始播放。但是在移动端,只有在用户第一次触碰屏幕后才可以调用play(),所以移动端不可能在程序开始运行时就自动开始播放Video。 *

    * *

    MDN Video链接: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video

    */ //class laya.device.media.Video extends laya.display.Sprite var Video=(function(_super){ function Video(width,height){ this.htmlVideo=null; this.videoElement=null; this.internalTexture=null; (width===void 0)&& (width=320); (height===void 0)&& (height=240); Video.__super.call(this); if (Render.isWebGL) this.htmlVideo=new WebGLVideo(); else this.htmlVideo=new HtmlVideo(); this.videoElement=this.htmlVideo.getVideo(); this.videoElement.layaTarget=this; this.internalTexture=new Texture(this.htmlVideo); this.videoElement.addEventListener("abort",Video.onAbort); this.videoElement.addEventListener("canplay",Video.onCanplay); this.videoElement.addEventListener("canplaythrough",Video.onCanplaythrough); this.videoElement.addEventListener("durationchange",Video.onDurationchange); this.videoElement.addEventListener("emptied",Video.onEmptied); this.videoElement.addEventListener("error",Video.onError); this.videoElement.addEventListener("loadeddata",Video.onLoadeddata); this.videoElement.addEventListener("loadedmetadata",Video.onLoadedmetadata); this.videoElement.addEventListener("loadstart",Video.onLoadstart); this.videoElement.addEventListener("pause",Video.onPause); this.videoElement.addEventListener("play",Video.onPlay); this.videoElement.addEventListener("playing",Video.onPlaying); this.videoElement.addEventListener("progress",Video.onProgress); this.videoElement.addEventListener("ratechange",Video.onRatechange); this.videoElement.addEventListener("seeked",Video.onSeeked); this.videoElement.addEventListener("seeking",Video.onSeeking); this.videoElement.addEventListener("stalled",Video.onStalled); this.videoElement.addEventListener("suspend",Video.onSuspend); this.videoElement.addEventListener("timeupdate",Video.onTimeupdate); this.videoElement.addEventListener("volumechange",Video.onVolumechange); this.videoElement.addEventListener("waiting",Video.onWaiting); this.videoElement.addEventListener("ended",this.onPlayComplete['bind'](this)); this.size(width,height); if (Browser.onMobile){ /*__JS__ */this.onDocumentClick=this.onDocumentClick.bind(this); Browser.document.addEventListener("touchend",this.onDocumentClick); } } __class(Video,'laya.device.media.Video',_super); var __proto=Video.prototype; __proto.onPlayComplete=function(e){ Laya.timer.clear(this,this.renderCanvas); this.event("ended"); } /** *设置播放源。 *@param url 播放源路径。 */ __proto.load=function(url){ if (url.indexOf("blob:")==0) this.videoElement.src=url; else this.htmlVideo.setSource(url,laya.device.media.Video.MP4); } /** *开始播放视频。 */ __proto.play=function(){ this.videoElement.play(); Laya.timer.frameLoop(1,this,this.renderCanvas); } /** *暂停视频播放。 */ __proto.pause=function(){ this.videoElement.pause(); Laya.timer.clear(this,this.renderCanvas); } /** *重新加载视频。 */ __proto.reload=function(){ this.videoElement.load(); } /** *检测是否支持播放指定格式视频。 *@param type 参数为Video.MP4 / Video.OGG / Video.WEBM之一。 *@return 表示支持的级别。可能的值: *
      *
    • "probably",Video.SUPPORT_PROBABLY-浏览器最可能支持该音频/视频类型
    • *
    • "maybe",Video.SUPPORT_MAYBY-浏览器也许支持该音频/视频类型
    • *
    • "",Video.SUPPORT_NO-(空字符串)浏览器不支持该音频/视频类型
    • *
    */ __proto.canPlayType=function(type){ var typeString; switch (type){ case laya.device.media.Video.MP4: typeString="video/mp4"; break ; case laya.device.media.Video.OGG: typeString="video/ogg"; break ; case laya.device.media.Video.WEBM: typeString="video/webm"; break ; } return this.videoElement.canPlayType(typeString); } __proto.renderCanvas=function(){ if (this.readyState===0) return; if (Render.isWebGL) this.htmlVideo['updateTexture'](); this.graphics.clear(); this.graphics.drawTexture(this.internalTexture,0,0,this.width,this.height); } __proto.onDocumentClick=function(){ this.videoElement.play(); this.videoElement.pause(); Browser.document.removeEventListener("touchend",this.onDocumentClick); } __proto.size=function(width,height){ _super.prototype.size.call(this,width,height) this.videoElement.width=width / Browser.pixelRatio; if (this.paused)this.renderCanvas(); return this; } /** *销毁内部事件绑定。 */ __proto.destroy=function(detroyChildren){ (detroyChildren===void 0)&& (detroyChildren=true); _super.prototype.destroy.call(this,detroyChildren); this.videoElement.removeEventListener("abort",Video.onAbort); this.videoElement.removeEventListener("canplay",Video.onCanplay); this.videoElement.removeEventListener("canplaythrough",Video.onCanplaythrough); this.videoElement.removeEventListener("durationchange",Video.onDurationchange); this.videoElement.removeEventListener("emptied",Video.onEmptied); this.videoElement.removeEventListener("error",Video.onError); this.videoElement.removeEventListener("loadeddata",Video.onLoadeddata); this.videoElement.removeEventListener("loadedmetadata",Video.onLoadedmetadata); this.videoElement.removeEventListener("loadstart",Video.onLoadstart); this.videoElement.removeEventListener("pause",Video.onPause); this.videoElement.removeEventListener("play",Video.onPlay); this.videoElement.removeEventListener("playing",Video.onPlaying); this.videoElement.removeEventListener("progress",Video.onProgress); this.videoElement.removeEventListener("ratechange",Video.onRatechange); this.videoElement.removeEventListener("seeked",Video.onSeeked); this.videoElement.removeEventListener("seeking",Video.onSeeking); this.videoElement.removeEventListener("stalled",Video.onStalled); this.videoElement.removeEventListener("suspend",Video.onSuspend); this.videoElement.removeEventListener("timeupdate",Video.onTimeupdate); this.videoElement.removeEventListener("volumechange",Video.onVolumechange); this.videoElement.removeEventListener("waiting",Video.onWaiting); this.videoElement.removeEventListener("ended",this.onPlayComplete); this.pause(); this.videoElement=null; } __proto.syncVideoPosition=function(){ var stage=Laya.stage; var rec; rec=Utils.getGlobalPosAndScale(this); var a=stage._canvasTransform.a,d=stage._canvasTransform.d; var x=rec.x *stage.clientScaleX *a+stage.offset.x; var y=rec.y *stage.clientScaleY *d+stage.offset.y; this.videoElement.style.left=x+'px';; this.videoElement.style.top=y+'px'; this.videoElement.width=this.width / Browser.pixelRatio; this.videoElement.height=this.height / Browser.pixelRatio; } /** *buffered 属性返回 TimeRanges(JS)对象。TimeRanges 对象表示用户的音视频缓冲范围。缓冲范围指的是已缓冲音视频的时间范围。如果用户在音视频中跳跃播放,会得到多个缓冲范围。 *

    buffered.length返回缓冲范围个数。如获取第一个缓冲范围则是buffered.start(0)和buffered.end(0)。以秒计。

    *@return TimeRanges(JS)对象 */ __getset(0,__proto,'buffered',function(){ return this.videoElement.buffered; }); /** *获取视频源尺寸。ready事件触发后可用。 */ __getset(0,__proto,'videoWidth',function(){ return this.videoElement.videoWidth; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.currentSrc; }); /** *设置和获取当前播放头位置。 */ __getset(0,__proto,'currentTime',function(){ return this.videoElement.currentTime; },function(value){ this.videoElement.currentTime=value; this.renderCanvas(); }); /** *返回音频/视频的播放是否已结束 */ __getset(0,__proto,'ended',function(){ return this.videoElement.ended; }); /** *设置和获取当前音量。 */ __getset(0,__proto,'volume',function(){ return this.videoElement.volume; },function(value){ this.videoElement.volume=value; }); __getset(0,__proto,'videoHeight',function(){ return this.videoElement.videoHeight; }); /** *表示视频元素的就绪状态: *
      *
    • 0=HAVE_NOTHING-没有关于音频/视频是否就绪的信息
    • *
    • 1=HAVE_METADATA-关于音频/视频就绪的元数据
    • *
    • 2=HAVE_CURRENT_DATA-关于当前播放位置的数据是可用的,但没有足够的数据来播放下一帧/毫秒
    • *
    • 3=HAVE_FUTURE_DATA-当前及至少下一帧的数据是可用的
    • *
    • 4=HAVE_ENOUGH_DATA-可用数据足以开始播放
    • *
    */ __getset(0,__proto,'readyState',function(){ return this.videoElement.readyState; }); /** *获取视频长度(秒)。ready事件触发后可用。 */ __getset(0,__proto,'duration',function(){ return this.videoElement.duration; }); /** *返回表示音频/视频错误状态的 MediaError(JS)对象。 */ __getset(0,__proto,'error',function(){ return this.videoElement.error; }); /** *设置或返回音频/视频是否应在结束时重新播放。 */ __getset(0,__proto,'loop',function(){ return this.videoElement.loop; },function(value){ this.videoElement.loop=value; }); /** *playbackRate 属性设置或返回音频/视频的当前播放速度。如: *
      *
    • 1.0 正常速度
    • *
    • 0.5 半速(更慢)
    • *
    • 2.0 倍速(更快)
    • *
    • -1.0 向后,正常速度
    • *
    • -0.5 向后,半速
    • *
    *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ return this.videoElement.playbackRate; },function(value){ this.videoElement.playbackRate=value; }); /** *获取和设置静音状态。 */ __getset(0,__proto,'muted',function(){ return this.videoElement.muted; },function(value){ this.videoElement.muted=value; }); /** *返回视频是否暂停 */ __getset(0,__proto,'paused',function(){ return this.videoElement.paused; }); /** *preload 属性设置或返回是否在页面加载后立即加载视频。可赋值如下: *
      *
    • auto 指示一旦页面加载,则开始加载视频。
    • *
    • metadata 指示当页面加载后仅加载音频/视频的元数据。
    • *
    • none 指示页面加载后不应加载音频/视频。
    • *
    */ __getset(0,__proto,'preload',function(){ return this.videoElement.preload; },function(value){ this.videoElement.preload=value; }); /** *参见 http://www.w3school.com.cn/tags/av_prop_seekable.asp。 */ __getset(0,__proto,'seekable',function(){ return this.videoElement.seekable; }); /** *seeking 属性返回用户目前是否在音频/视频中寻址。 *寻址中(Seeking)指的是用户在音频/视频中移动/跳跃到新的位置。 */ __getset(0,__proto,'seeking',function(){ return this.videoElement.seeking; }); __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Sprite,this,'height',value); if (this.paused)this.renderCanvas(); }); __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ this.videoElement.width=this.width / Browser.pixelRatio; Laya.superSet(Sprite,this,'width',value); if (this.paused)this.renderCanvas(); }); Video.onAbort=function(e){e.target.layaTarget.event("abort")} Video.onCanplay=function(e){e.target.layaTarget.event("canplay")} Video.onCanplaythrough=function(e){e.target.layaTarget.event("canplaythrough")} Video.onDurationchange=function(e){e.target.layaTarget.event("durationchange")} Video.onEmptied=function(e){e.target.layaTarget.event("emptied")} Video.onError=function(e){e.target.layaTarget.event("error")} Video.onLoadeddata=function(e){e.target.layaTarget.event("loadeddata")} Video.onLoadedmetadata=function(e){e.target.layaTarget.event("loadedmetadata")} Video.onLoadstart=function(e){e.target.layaTarget.event("loadstart")} Video.onPause=function(e){e.target.layaTarget.event("pause")} Video.onPlay=function(e){e.target.layaTarget.event("play")} Video.onPlaying=function(e){e.target.layaTarget.event("playing")} Video.onProgress=function(e){e.target.layaTarget.event("progress")} Video.onRatechange=function(e){e.target.layaTarget.event("ratechange")} Video.onSeeked=function(e){e.target.layaTarget.event("seeked")} Video.onSeeking=function(e){e.target.layaTarget.event("seeking")} Video.onStalled=function(e){e.target.layaTarget.event("stalled")} Video.onSuspend=function(e){e.target.layaTarget.event("suspend")} Video.onTimeupdate=function(e){e.target.layaTarget.event("timeupdate")} Video.onVolumechange=function(e){e.target.layaTarget.event("volumechange")} Video.onWaiting=function(e){e.target.layaTarget.event("waiting")} Video.MP4=1; Video.OGG=2; Video.CAMERA=4; Video.WEBM=8; Video.SUPPORT_PROBABLY="probably"; Video.SUPPORT_MAYBY="maybe"; Video.SUPPORT_NO=""; return Video; })(Sprite) /** *@private */ //class laya.device.media.HtmlVideo extends laya.resource.Bitmap var HtmlVideo=(function(_super){ function HtmlVideo(){ this.video=null; HtmlVideo.__super.call(this); this._w=1; this._h=1; this.createDomElement(); } __class(HtmlVideo,'laya.device.media.HtmlVideo',_super); var __proto=HtmlVideo.prototype; __proto.createDomElement=function(){ var _$this=this; this._source=this.video=Browser.createElement("video"); var style=this.video.style; style.position='absolute'; style.top='0px'; style.left='0px'; this.video.addEventListener("loadedmetadata",(function(){ this._w=_$this.video.videoWidth; this._h=_$this.video.videoHeight; })['bind'](this)); } __proto.setSource=function(url,extension){ while(this.video.childElementCount) this.video.firstChild.remove(); if (extension & Video.MP4) this.appendSource(url,"video/mp4"); if (extension & Video.OGG) this.appendSource(url+".ogg","video/ogg"); } __proto.appendSource=function(source,type){ var sourceElement=Browser.createElement("source"); sourceElement.src=source; sourceElement.type=type; this.video.appendChild(sourceElement); } __proto.getVideo=function(){ return this.video; } HtmlVideo.create=function(){ return new HtmlVideo(); } return HtmlVideo; })(Bitmap) /** *@private */ //class laya.device.media.WebGLVideo extends laya.device.media.HtmlVideo var WebGLVideo=(function(_super){ function WebGLVideo(){ this.gl=null; this.preTarget=null; this.preTexture=null; WebGLVideo.__super.call(this); if(Browser.onIPhone) return; this.gl=WebGL.mainContext; this._source=this.gl.createTexture(); this.preTarget=WebGLContext.curBindTexTarget; this.preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(this.gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,this._source); this.gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); this.gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); this.gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,/*laya.webgl.WebGLContext.LINEAR*/0x2601); this.gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,/*laya.webgl.WebGLContext.LINEAR*/0x2601); (this.preTarget && this.preTexture)&& (WebGLContext.bindTexture(this.gl,this.preTarget,this.preTexture)); } __class(WebGLVideo,'laya.device.media.WebGLVideo',_super); var __proto=WebGLVideo.prototype; __proto.updateTexture=function(){ if(Browser.onIPhone) return; WebGLContext.bindTexture(this.gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,this._source); this.gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,/*laya.webgl.WebGLContext.RGB*/0x1907,/*laya.webgl.WebGLContext.RGB*/0x1907,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this.video); } return WebGLVideo; })(HtmlVideo) Laya.__init([Media]); })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.filter.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Color=laya.utils.Color,ColorFilterAction=laya.filters.ColorFilterAction; var ColorFilterActionGL=laya.filters.webgl.ColorFilterActionGL,Filter=laya.filters.Filter,FilterActionGL=laya.filters.webgl.FilterActionGL; var Matrix=laya.maths.Matrix,Rectangle=laya.maths.Rectangle,Render=laya.renders.Render,RenderContext=laya.renders.RenderContext; var RenderTarget2D=laya.webgl.resource.RenderTarget2D,RunDriver=laya.utils.RunDriver,ShaderDefines2D=laya.webgl.shader.d2.ShaderDefines2D; var Sprite=laya.display.Sprite,Texture=laya.resource.Texture,Value2D=laya.webgl.shader.d2.value.Value2D; /** *默认的FILTER,什么都不做 *@private */ //class laya.filters.FilterAction var FilterAction=(function(){ function FilterAction(){ this.data=null; } __class(FilterAction,'laya.filters.FilterAction'); var __proto=FilterAction.prototype; Laya.imps(__proto,{"laya.filters.IFilterAction":true}) __proto.apply=function(data){ return null; } return FilterAction; })() /** *@private */ //class laya.filters.WebGLFilter var WebGLFilter=(function(){ function WebGLFilter(){} __class(WebGLFilter,'laya.filters.WebGLFilter'); WebGLFilter.enable=function(){ if (WebGLFilter.isInit)return; WebGLFilter.isInit=true; if (!Render.isWebGL)return; RunDriver.createFilterAction=function (type){ var action; switch (type){ case /*laya.filters.Filter.COLOR*/0x20: action=new ColorFilterActionGL(); break ; case /*laya.filters.Filter.BLUR*/0x10: action=new BlurFilterActionGL(); break ; case /*laya.filters.Filter.GLOW*/0x08: action=new GlowFilterActionGL(); break ; } return action; } } WebGLFilter.isInit=false; WebGLFilter.__init$=function(){ BlurFilterActionGL; ColorFilterActionGL; GlowFilterActionGL; Render; RunDriver;{ RunDriver.createFilterAction=function (type){ var action; switch (type){ case /*laya.filters.Filter.BLUR*/0x10: action=new FilterAction(); break ; case /*laya.filters.Filter.GLOW*/0x08: action=new FilterAction(); break ; case /*laya.filters.Filter.COLOR*/0x20: action=new ColorFilterAction(); break ; } return action; } } } return WebGLFilter; })() /** *模糊滤镜 */ //class laya.filters.BlurFilter extends laya.filters.Filter var BlurFilter=(function(_super){ function BlurFilter(strength){ /**模糊滤镜的强度(值越大,越不清晰 */ this.strength=NaN; this.strength_sig2_2sig2_gauss1=[]; BlurFilter.__super.call(this); (strength===void 0)&& (strength=4); if (Render.isWebGL)WebGLFilter.enable(); this.strength=strength; this._action=RunDriver.createFilterAction(0x10); this._action.data=this; } __class(BlurFilter,'laya.filters.BlurFilter',_super); var __proto=BlurFilter.prototype; /** *@private 通知微端 */ __proto.callNative=function(sp){ sp.conchModel &&sp.conchModel.blurFilter&&sp.conchModel.blurFilter(this.strength); } /** *@private *当前滤镜对应的操作器 */ __getset(0,__proto,'action',function(){ return this._action; }); /** *@private *当前滤镜的类型 */ __getset(0,__proto,'type',function(){ return 0x10; }); return BlurFilter; })(Filter) /** *发光滤镜(也可以当成阴影滤使用) */ //class laya.filters.GlowFilter extends laya.filters.Filter var GlowFilter=(function(_super){ function GlowFilter(color,blur,offX,offY){ /**滤镜的颜色*/ this._color=null; GlowFilter.__super.call(this); this._elements=new Float32Array(9); (blur===void 0)&& (blur=4); (offX===void 0)&& (offX=6); (offY===void 0)&& (offY=6); if (Render.isWebGL){ WebGLFilter.enable(); } this._color=new Color(color); this.blur=Math.min(blur,20); this.offX=offX; this.offY=offY; this._action=RunDriver.createFilterAction(0x08); this._action.data=this; } __class(GlowFilter,'laya.filters.GlowFilter',_super); var __proto=GlowFilter.prototype; /**@private */ __proto.getColor=function(){ return this._color._color; } /** *@private 通知微端 */ __proto.callNative=function(sp){ sp.conchModel &&sp.conchModel.glowFilter&&sp.conchModel.glowFilter(this._color.strColor,this._elements[4],this._elements[5],this._elements[6]); } /** *@private *滤镜类型 */ __getset(0,__proto,'type',function(){ return 0x08; }); /**@private */ __getset(0,__proto,'action',function(){ return this._action; }); /**@private */ /**@private */ __getset(0,__proto,'offY',function(){ return this._elements[6]; },function(value){ this._elements[6]=value; }); /**@private */ /**@private */ __getset(0,__proto,'offX',function(){ return this._elements[5]; },function(value){ this._elements[5]=value; }); /**@private */ /**@private */ __getset(0,__proto,'blur',function(){ return this._elements[4]; },function(value){ this._elements[4]=value; }); return GlowFilter; })(Filter) /** *@private */ //class laya.filters.webgl.BlurFilterActionGL extends laya.filters.webgl.FilterActionGL var BlurFilterActionGL=(function(_super){ function BlurFilterActionGL(){ this.data=null; BlurFilterActionGL.__super.call(this); } __class(BlurFilterActionGL,'laya.filters.webgl.BlurFilterActionGL',_super); var __proto=BlurFilterActionGL.prototype; __proto.setValueMix=function(shader){ shader.defines.add(this.data.type); var o=shader; } __proto.apply3d=function(scope,sprite,context,x,y){ var b=scope.getValue("bounds"); var shaderValue=Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0); shaderValue.setFilters([this.data]); var tMatrix=Matrix.EMPTY; tMatrix.identity(); context.ctx.drawTarget(scope,0,0,b.width,b.height,Matrix.EMPTY,"src",shaderValue); shaderValue.setFilters(null); } __proto.setValue=function(shader){ shader.strength=this.data.strength; var sigma=this.data.strength/3.0; var sigma2=sigma*sigma; this.data.strength_sig2_2sig2_gauss1[0]=this.data.strength; this.data.strength_sig2_2sig2_gauss1[1]=sigma2; this.data.strength_sig2_2sig2_gauss1[2]=2.0*sigma2; this.data.strength_sig2_2sig2_gauss1[3]=1.0/(2.0*Math.PI*sigma2); shader.strength_sig2_2sig2_gauss1=this.data.strength_sig2_2sig2_gauss1; } __getset(0,__proto,'typeMix',function(){return /*laya.filters.Filter.BLUR*/0x10;}); return BlurFilterActionGL; })(FilterActionGL) /** *@private */ //class laya.filters.webgl.GlowFilterActionGL extends laya.filters.webgl.FilterActionGL var GlowFilterActionGL=(function(_super){ function GlowFilterActionGL(){ this.data=null; this._initKey=false; this._textureWidth=0; this._textureHeight=0; GlowFilterActionGL.__super.call(this); } __class(GlowFilterActionGL,'laya.filters.webgl.GlowFilterActionGL',_super); var __proto=GlowFilterActionGL.prototype; Laya.imps(__proto,{"laya.filters.IFilterActionGL":true}) __proto.setValueMix=function(shader){} __proto.apply3d=function(scope,sprite,context,x,y){ var b=scope.getValue("bounds"); scope.addValue("color",this.data.getColor()); var w=b.width,h=b.height; this._textureWidth=w; this._textureHeight=h; var shaderValue; var mat=Matrix.TEMP; mat.identity(); shaderValue=Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0); shaderValue.setFilters([this.data]); context.ctx.drawTarget(scope,0,0,this._textureWidth,this._textureHeight,mat,"src",shaderValue,null); shaderValue=Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0); context.ctx.drawTarget(scope,0,0,this._textureWidth,this._textureHeight,mat,"src",shaderValue); return null; } __proto.setSpriteWH=function(sprite){ this._textureWidth=sprite.width; this._textureHeight=sprite.height; } __proto.setValue=function(shader){ shader.u_offsetX=this.data.offX; shader.u_offsetY=-this.data.offY; shader.u_strength=1.0; shader.u_blurX=this.data.blur; shader.u_blurY=this.data.blur; shader.u_textW=this._textureWidth; shader.u_textH=this._textureHeight; shader.u_color=this.data.getColor(); } __getset(0,__proto,'typeMix',function(){return /*laya.filters.Filter.GLOW*/0x08;}); GlowFilterActionGL.tmpTarget=function(scope,sprite,context,x,y){ var b=scope.getValue("bounds"); var out=scope.getValue("out"); out.end(); var tmpTarget=RenderTarget2D.create(b.width,b.height); tmpTarget.start(); var color=scope.getValue("color"); if (color){ tmpTarget.clear(color[0],color[1],color[2],0); } scope.addValue("tmpTarget",tmpTarget); } GlowFilterActionGL.startOut=function(scope,sprite,context,x,y){ var tmpTarget=scope.getValue("tmpTarget"); tmpTarget.end(); var out=scope.getValue("out"); out.start(); var color=scope.getValue("color"); if (color){ out.clear(color[0],color[1],color[2],0); } } GlowFilterActionGL.recycleTarget=function(scope,sprite,context,x,y){ var src=scope.getValue("src"); var tmpTarget=scope.getValue("tmpTarget"); tmpTarget.recycle(); } return GlowFilterActionGL; })(FilterActionGL) Laya.__init([WebGLFilter]); })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.html.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,CSSStyle=laya.display.css.CSSStyle,ClassUtils=laya.utils.ClassUtils; var Event=laya.events.Event,HTMLChar=laya.utils.HTMLChar,Loader=laya.net.Loader,Node=laya.display.Node,Rectangle=laya.maths.Rectangle; var Render=laya.renders.Render,RenderContext=laya.renders.RenderContext,RenderSprite=laya.renders.RenderSprite; var Sprite=laya.display.Sprite,Stat=laya.utils.Stat,Text=laya.display.Text,Texture=laya.resource.Texture; var URL=laya.net.URL,Utils=laya.utils.Utils; /** *@private */ //class laya.html.utils.HTMLParse var HTMLParse=(function(){ function HTMLParse(){} __class(HTMLParse,'laya.html.utils.HTMLParse'); HTMLParse.parse=function(ower,xmlString,url){ xmlString=xmlString.replace(/
    /g,"
    "); xmlString=""+xmlString+""; xmlString=xmlString.replace(HTMLParse.spacePattern,HTMLParse.char255); var xml=Utils.parseXMLFromString(xmlString); HTMLParse._parseXML(ower,xml.childNodes[0].childNodes,url); } HTMLParse._parseXML=function(parent,xml,url,href){ var i=0,n=0; if (xml.join || xml.item){ for (i=0,n=xml.length;i < n;++i){ HTMLParse._parseXML(parent,xml[i],url,href); } }else { var node; var nodeName; if (xml.nodeType==3){ var txt; if ((parent instanceof laya.html.dom.HTMLDivElement )){ if (xml.nodeName==null){ xml.nodeName="#text"; } nodeName=xml.nodeName.toLowerCase(); txt=xml.textContent.replace(/^\s+|\s+$/g,''); if (txt.length > 0){ node=ClassUtils.getInstance(nodeName); if (node){ parent.addChild(node); ((node).innerTEXT=txt.replace(HTMLParse.char255AndOneSpacePattern," ")); } } }else { txt=xml.textContent.replace(/^\s+|\s+$/g,''); if (txt.length > 0){ ((parent).innerTEXT=txt.replace(HTMLParse.char255AndOneSpacePattern," ")); } } return; }else { nodeName=xml.nodeName.toLowerCase(); if (nodeName=="#comment")return; node=ClassUtils.getInstance(nodeName); if (node){ node=parent.addChild(node); (node).URI=url; (node).href=href; var attributes=xml.attributes; if (attributes && attributes.length > 0){ for (i=0,n=attributes.length;i < n;++i){ var attribute=attributes[i]; var attrName=attribute.nodeName; var value=attribute.value; node._setAttributes(attrName,value); } } HTMLParse._parseXML(node,xml.childNodes,url,(node).href); }else { HTMLParse._parseXML(parent,xml.childNodes,url,href); } } } } HTMLParse.char255=String.fromCharCode(255); HTMLParse.spacePattern=/ | /g; HTMLParse.char255AndOneSpacePattern=new RegExp(String.fromCharCode(255)+"|(\\s+)","g"); return HTMLParse; })() /** *@private *HTML的布局类 *对HTML的显示对象进行排版 */ //class laya.html.utils.Layout var Layout=(function(){ function Layout(){} __class(Layout,'laya.html.utils.Layout'); Layout.later=function(element){ if (Layout._will==null){ Layout._will=[]; Laya.stage.frameLoop(1,null,function(){ if (Layout._will.length < 1) return; for (var i=0;i < Layout._will.length;i++){ laya.html.utils.Layout.layout(Layout._will[i]); } Layout._will.length=0; }); } Layout._will.push(element); } Layout.layout=function(element){ if (!element || !element._style)return null; if ((element._style._type & /*laya.display.css.CSSStyle.ADDLAYOUTED*/0x200)===0) return null; element.getStyle()._type &=~ /*laya.display.css.CSSStyle.ADDLAYOUTED*/0x200; var arr=Layout._multiLineLayout(element); if (Render.isConchApp&&element["layaoutCallNative"]){ (element).layaoutCallNative(); } return arr; } Layout._multiLineLayout=function(element){ if (Text.RightToLeft)return Layout._multiLineLayout2(element); var elements=new Array; element._addChildsToLayout(elements); var i=0,n=elements.length,j=0; var style=element._getCSSStyle(); var letterSpacing=style.letterSpacing; var leading=style.leading; var lineHeight=style.lineHeight; var widthAuto=style._widthAuto()|| !style.wordWrap; var width=widthAuto ? 999999 :element.width; var height=element.height; var maxWidth=0; var exWidth=style.italic ? style.fontSize / 3 :0; var align=style._getAlign(); var valign=style._getValign(); var endAdjust=valign!==0 || align!==0 || lineHeight !=0; var oneLayout; var x=0; var y=0; var w=0; var h=0; var tBottom=0; var lines=new Array; var curStyle; var curPadding; var curLine=lines[0]=new LayoutLine(); var newLine=false,nextNewline=false; var htmlWord; var sprite; curLine.h=0; if (style.italic) width-=style.fontSize / 3; var tWordWidth=0; var tLineFirstKey=true; function addLine (){ curLine.y=y; y+=curLine.h+leading; if (curLine.h==0)y+=lineHeight; curLine.mWidth=tWordWidth; tWordWidth=0; curLine=new LayoutLine(); lines.push(curLine); curLine.h=0; x=0; tLineFirstKey=true; newLine=false; } for (i=0;i < n;i++){ oneLayout=elements[i]; if (oneLayout==null){ if (!tLineFirstKey){ x+=Layout.DIV_ELEMENT_PADDING; } curLine.wordStartIndex=curLine.elements.length; continue ; } tLineFirstKey=false; if ((oneLayout instanceof laya.html.dom.HTMLBrElement )){ addLine(); curLine.y=y; continue ; }else if (oneLayout._isChar()){ htmlWord=oneLayout; if (!htmlWord.isWord){ if (lines.length > 0 && (x+w)> width && curLine.wordStartIndex > 0){ var tLineWord=0; tLineWord=curLine.elements.length-curLine.wordStartIndex+1; curLine.elements.length=curLine.wordStartIndex; i-=tLineWord; addLine(); continue ; } newLine=false; tWordWidth+=htmlWord.width; }else { newLine=nextNewline || (htmlWord.char==='\n'); curLine.wordStartIndex=curLine.elements.length; } w=htmlWord.width+letterSpacing; h=htmlWord.height; nextNewline=false; newLine=newLine || ((x+w)> width); newLine && addLine(); curLine.minTextHeight=Math.min(curLine.minTextHeight,oneLayout.height); }else { curStyle=oneLayout._getCSSStyle(); sprite=oneLayout; curPadding=curStyle.padding; curStyle._getCssFloat()===0 || (endAdjust=true); newLine=nextNewline || curStyle.lineElement; w=sprite.width *sprite._style._tf.scaleX+curPadding[1]+curPadding[3]+letterSpacing; h=sprite.height *sprite._style._tf.scaleY+curPadding[0]+curPadding[2]; nextNewline=curStyle.lineElement; newLine=newLine || ((x+w)> width && curStyle.wordWrap); newLine && addLine(); } curLine.elements.push(oneLayout); curLine.h=Math.max(curLine.h,h); oneLayout.x=x; oneLayout.y=y; x+=w; curLine.w=x-letterSpacing; curLine.y=y; maxWidth=Math.max(x+exWidth,maxWidth); } y=curLine.y+curLine.h; if (endAdjust){ var tY=0; var tWidth=width; if (widthAuto && element.width > 0){ tWidth=element.width; } for (i=0,n=lines.length;i < n;i++){ lines[i].updatePos(0,tWidth,i,tY,align,valign,lineHeight); tY+=Math.max(lineHeight,lines[i].h+leading); } y=tY; } widthAuto && (element.width=maxWidth); (y > element.height)&& (element.height=y); return [maxWidth,y]; } Layout._multiLineLayout2=function(element){ var elements=new Array; element._addChildsToLayout(elements); var i=0,n=elements.length,j=0; var style=element._getCSSStyle(); var letterSpacing=style.letterSpacing; var leading=style.leading; var lineHeight=style.lineHeight; var widthAuto=style._widthAuto()|| !style.wordWrap; var width=widthAuto ? 999999 :element.width; var height=element.height; var maxWidth=0; var exWidth=style.italic ? style.fontSize / 3 :0; var align=2-style._getAlign(); var valign=style._getValign(); var endAdjust=valign!==0 || align!==0 || lineHeight !=0; var oneLayout; var x=0; var y=0; var w=0; var h=0; var tBottom=0; var lines=new Array; var curStyle; var curPadding; var curLine=lines[0]=new LayoutLine(); var newLine=false,nextNewline=false; var htmlWord; var sprite; curLine.h=0; if (style.italic) width-=style.fontSize / 3; var tWordWidth=0; var tLineFirstKey=true; function addLine (){ curLine.y=y; y+=curLine.h+leading; if (curLine.h==0)y+=lineHeight; curLine.mWidth=tWordWidth; tWordWidth=0; curLine=new LayoutLine(); lines.push(curLine); curLine.h=0; x=0; tLineFirstKey=true; newLine=false; } for (i=0;i < n;i++){ oneLayout=elements[i]; if (oneLayout==null){ if (!tLineFirstKey){ x+=Layout.DIV_ELEMENT_PADDING; } curLine.wordStartIndex=curLine.elements.length; continue ; } tLineFirstKey=false; if ((oneLayout instanceof laya.html.dom.HTMLBrElement )){ addLine(); curLine.y=y; continue ; }else if (oneLayout._isChar()){ htmlWord=oneLayout; if (!htmlWord.isWord){ if (lines.length > 0 && (x+w)> width && curLine.wordStartIndex > 0){ var tLineWord=0; tLineWord=curLine.elements.length-curLine.wordStartIndex+1; curLine.elements.length=curLine.wordStartIndex; i-=tLineWord; addLine(); continue ; } newLine=false; tWordWidth+=htmlWord.width; }else { newLine=nextNewline || (htmlWord.char==='\n'); curLine.wordStartIndex=curLine.elements.length; } w=htmlWord.width+letterSpacing; h=htmlWord.height; nextNewline=false; newLine=newLine || ((x+w)> width); newLine && addLine(); curLine.minTextHeight=Math.min(curLine.minTextHeight,oneLayout.height); }else { curStyle=oneLayout._getCSSStyle(); sprite=oneLayout; curPadding=curStyle.padding; curStyle._getCssFloat()===0 || (endAdjust=true); newLine=nextNewline || curStyle.lineElement; w=sprite.width *sprite._style._tf.scaleX+curPadding[1]+curPadding[3]+letterSpacing; h=sprite.height *sprite._style._tf.scaleY+curPadding[0]+curPadding[2]; nextNewline=curStyle.lineElement; newLine=newLine || ((x+w)> width && curStyle.wordWrap); newLine && addLine(); } curLine.elements.push(oneLayout); curLine.h=Math.max(curLine.h,h); oneLayout.x=x; oneLayout.y=y; x+=w; curLine.w=x-letterSpacing; curLine.y=y; maxWidth=Math.max(x+exWidth,maxWidth); } y=curLine.y+curLine.h; if (endAdjust){ var tY=0; var tWidth=width; for (i=0,n=lines.length;i < n;i++){ lines[i].updatePos(0,tWidth,i,tY,align,valign,lineHeight); tY+=Math.max(lineHeight,lines[i].h+leading); } y=tY; } widthAuto && (element.width=maxWidth); (y > element.height)&& (element.height=y); for (i=0,n=lines.length;i < n;i++){ lines[i].revertOrder(width); } return [maxWidth,y]; } Layout._will=null; Layout.DIV_ELEMENT_PADDING=0; return Layout; })() /** *@private */ //class laya.html.utils.LayoutLine var LayoutLine=(function(){ function LayoutLine(){ this.x=0; this.y=0; this.w=0; this.h=0; this.wordStartIndex=0; this.minTextHeight=99999; this.mWidth=0; this.elements=new Array; } __class(LayoutLine,'laya.html.utils.LayoutLine'); var __proto=LayoutLine.prototype; /** *底对齐(默认) *@param left *@param width *@param dy *@param align 水平 *@param valign 垂直 *@param lineHeight 行高 */ __proto.updatePos=function(left,width,lineNum,dy,align,valign,lineHeight){ var w=0; var one if (this.elements.length > 0){ one=this.elements[this.elements.length-1]; w=one.x+one.width-this.elements[0].x; }; var dx=0,ddy=NaN; align===/*laya.display.css.CSSStyle.ALIGN_CENTER*/1 && (dx=(width-w)/ 2); align===/*laya.display.css.CSSStyle.ALIGN_RIGHT*/2 && (dx=(width-w)); lineHeight===0 || valign !=0 || (valign=1); for (var i=0,n=this.elements.length;i < n;i++){ one=this.elements[i]; var tCSSStyle=one._getCSSStyle(); dx!==0 && (one.x+=dx); switch (tCSSStyle._getValign()){ case 0: one.y=dy; break ; case /*laya.display.css.CSSStyle.VALIGN_MIDDLE*/1:; var tMinTextHeight=0; if (this.minTextHeight !=99999){ tMinTextHeight=this.minTextHeight; }; var tBottomLineY=(tMinTextHeight+lineHeight)/ 2; tBottomLineY=Math.max(tBottomLineY,this.h); if ((one instanceof laya.html.dom.HTMLImageElement )){ ddy=dy+tBottomLineY-one.height; }else { ddy=dy+tBottomLineY-one.height; } one.y=ddy; break ; case /*laya.display.css.CSSStyle.VALIGN_BOTTOM*/2: one.y=dy+(lineHeight-one.height); break ; } } } /** *布局反向,目前用于将ltr模式布局转为rtl模式布局 */ __proto.revertOrder=function(width){ var one if (this.elements.length > 0){ var i=0,len=0; len=this.elements.length; for (i=0;i < len;i++){ one=this.elements[i]; one.x=width-one.x-one.width; } } } return LayoutLine; })() /** *@private */ //class laya.html.dom.HTMLElement extends laya.display.Sprite var HTMLElement=(function(_super){ function HTMLElement(){ this.URI=null; this._href=null; HTMLElement.__super.call(this); this._text=HTMLElement._EMPTYTEXT; this.setStyle(new CSSStyle(this)); this._getCSSStyle().valign="middle"; this.mouseEnabled=true; } __class(HTMLElement,'laya.html.dom.HTMLElement',_super); var __proto=HTMLElement.prototype; /** *@private */ __proto.layaoutCallNative=function(){ var n=0; if (this._childs &&(n=this._childs.length)> 0){ for (var i=0;i < n;i++){ this._childs[i].layaoutCallNative && this._childs[i].layaoutCallNative(); } }; var word=this._getWords(); word ? laya.html.dom.HTMLElement.fillWords(this,word,0,0,this.style.font,this.style.color,this.style.underLine,this.style.stroke,this.style.strokeColor):this.graphics.clear(); } __proto.appendChild=function(c){ return this.addChild(c); } /** *rtl模式的getWords函數 */ __proto._getWords2=function(){ var txt=this._text.text; if (!txt || txt.length===0) return null; var i=0,n=0; var realWords; var drawWords; if (!this._text.drawWords){ realWords=txt.split(" "); n=realWords.length-1; drawWords=[]; for (i=0;i < n;i++){ drawWords.push(realWords[i]," ") } if(n>=0) drawWords.push(realWords[n]); this._text.drawWords=drawWords; }else{ drawWords=this._text.drawWords; }; var words=this._text.words; if (words && words.length===drawWords.length) return words; words===null && (this._text.words=words=[]); words.length=drawWords.length; var size; var style=this.style; var fontStr=style.font; for (i=0,n=drawWords.length;i < n;i++){ size=Utils.measureText(drawWords[i],fontStr); var tHTMLChar=words[i]=new HTMLChar(drawWords[i],size.width,size.height || style.fontSize,style); if (tHTMLChar.char.length > 1){ tHTMLChar.charNum=tHTMLChar.char; } if (this.href){ var tSprite=new Sprite(); this.addChild(tSprite); tHTMLChar.setSprite(tSprite); } } return words; } __proto._getWords=function(){ if (!Text.CharacterCache)return this._getWords2(); var txt=this._text.text; if (!txt || txt.length===0) return null; var words=this._text.words; if (words && words.length===txt.length) return words; words===null && (this._text.words=words=[]); words.length=txt.length; var size; var style=this.style; var fontStr=style.font; var startX=0; for (var i=0,n=txt.length;i < n;i++){ size=Utils.measureText(txt.charAt(i),fontStr); var tHTMLChar=words[i]=new HTMLChar(txt.charAt(i),size.width,size.height||style.fontSize,style); if (this.href){ var tSprite=new Sprite(); this.addChild(tSprite); tHTMLChar.setSprite(tSprite); } } return words; } __proto.showLinkSprite=function(){ var words=this._text.words; if (words){ var tLinkSpriteList=[]; var tSprite; var tHtmlChar; for (var i=0;i < words.length;i++){ tHtmlChar=words[i]; tSprite=new Sprite(); tSprite.graphics.drawRect(0,0,tHtmlChar.width,tHtmlChar.height,"#ff0000"); tSprite.width=tHtmlChar.width; tSprite.height=tHtmlChar.height; this.addChild(tSprite); tLinkSpriteList.push(tSprite); } } } __proto._layoutLater=function(){ var style=this.style; if ((style._type & /*laya.display.css.CSSStyle.ADDLAYOUTED*/0x200))return; if (style.widthed(this)&& (this._childs.length>0 || this._getWords()!=null)&& style.block){ Layout.later(this); style._type |=/*laya.display.css.CSSStyle.ADDLAYOUTED*/0x200; } else{ this.parent && (this.parent)._layoutLater(); } } __proto._setAttributes=function(name,value){ switch (name){ case 'style': this.style.cssText(value); return; case 'class': this.className=value; return; } _super.prototype._setAttributes.call(this,name,value); } __proto.updateHref=function(){ if (this._href !=null){ var words=this._getWords(); if (words){ var tHTMLChar; var tSprite; for (var i=0;i < words.length;i++){ tHTMLChar=words[i]; tSprite=tHTMLChar.getSprite(); if (tSprite){ tSprite.size(tHTMLChar.width,tHTMLChar.height); tSprite.on(/*laya.events.Event.CLICK*/"click",this,this.onLinkHandler); } } } } } __proto.onLinkHandler=function(e){ switch(e.type){ case /*laya.events.Event.CLICK*/"click":; var target=this; while (target){ target.event(/*laya.events.Event.LINK*/"link",[this.href]); target=target.parent; } break ; } } __proto.formatURL=function(url){ if (!this.URI)return url; return URL.formatURL(url,this.URI ? this.URI.path :null); } __getset(0,__proto,'href',function(){ return this._href; },function(url){ this._href=url; if (url !=null){ this._getCSSStyle().underLine=1; this.updateHref(); } }); __getset(0,__proto,'color',null,function(value){ this.style.color=value; }); __getset(0,__proto,'onClick',null,function(value){ var fn; Laya._runScript("fn=function(event){"+value+";}"); this.on(/*laya.events.Event.CLICK*/"click",this,fn); }); __getset(0,__proto,'id',null,function(value){ HTMLDocument.document.setElementById(value,this); }); __getset(0,__proto,'innerTEXT',function(){ return this._text.text; },function(value){ this.text=value; }); __getset(0,__proto,'style',function(){ return this._style; }); __getset(0,__proto,'text',function(){ return this._text.text; },function(value){ if (this._text==HTMLElement._EMPTYTEXT){ this._text={text:value,words:null}; } else{ this._text.text=value; this._text.words && (this._text.words.length=0); } Render.isConchApp && this.layaoutCallNative(); this._renderType |=/*laya.renders.RenderSprite.CHILDS*/0x800; this.repaint(); this.updateHref(); }); __getset(0,__proto,'parent',_super.prototype._$get_parent,function(value){ if ((value instanceof laya.html.dom.HTMLElement )){ var p=value; this.URI || (this.URI=p.URI); this.style.inherit(p.style); } Laya.superSet(Sprite,this,'parent',value); }); __getset(0,__proto,'className',null,function(value){ this.style.attrs(HTMLDocument.document.styleSheets['.'+value]); }); HTMLElement.fillWords=function(ele,words,x,y,font,color,underLine,stroke,strokeColor){ ele.graphics.clear(); for (var i=0,n=words.length;i < n;i++){ var a=words[i]; if (stroke > 0){ ele.graphics.fillBorderText(a.char,a.x+x,a.y+y,font,color,strokeColor,stroke,'left'); } else { ele.graphics.fillText(a.char,a.x+x,a.y+y,font,color,'left',underLine); } } } HTMLElement._EMPTYTEXT={text:null,words:null}; return HTMLElement; })(Sprite) /** *@private */ //class laya.html.dom.HTMLBrElement extends laya.html.dom.HTMLElement var HTMLBrElement=(function(_super){ function HTMLBrElement(){ HTMLBrElement.__super.call(this); this.style.lineElement=true; this.style.block=true; } __class(HTMLBrElement,'laya.html.dom.HTMLBrElement',_super); return HTMLBrElement; })(HTMLElement) /** *DIV标签 */ //class laya.html.dom.HTMLDivElement extends laya.html.dom.HTMLElement var HTMLDivElement=(function(_super){ function HTMLDivElement(){ /**实际内容的高 */ this.contextHeight=NaN; /**实际内容的宽 */ this.contextWidth=NaN; HTMLDivElement.__super.call(this); this.style.block=true; this.style.lineElement=true; this.style.width=200; this.style.height=200; HTMLStyleElement; } __class(HTMLDivElement,'laya.html.dom.HTMLDivElement',_super); var __proto=HTMLDivElement.prototype; /** *追加内容,解析并对显示对象排版 *@param text */ __proto.appendHTML=function(text){ HTMLParse.parse(this,text,this.URI); this.layout(); } /** *@private *@param out *@return */ __proto._addChildsToLayout=function(out){ var words=this._getWords(); if (words==null && this._childs.length==0)return false; words && words.forEach(function(o){ out.push(o); }); var tFirstKey=true; for (var i=0,len=this._childs.length;i < len;i++){ var o=this._childs[i]; if (tFirstKey){ tFirstKey=false; }else { out.push(null); } o._addToLayout(out) } return true; } /** *@private *@param out */ __proto._addToLayout=function(out){ this.layout(); } /** *@private *对显示内容进行排版 */ __proto.layout=function(){ if (!this.style)return; this.style._type |=/*laya.display.css.CSSStyle.ADDLAYOUTED*/0x200; var tArray=Layout.layout(this); if (tArray){ if (!this._$P.mHtmlBounds)this._set$P("mHtmlBounds",new Rectangle()); var tRectangle=this._$P.mHtmlBounds; tRectangle.x=tRectangle.y=0; tRectangle.width=this.contextWidth=tArray[0]; tRectangle.height=this.contextHeight=tArray[1]; this.setBounds(tRectangle); } } /** *获取对象的高 */ __getset(0,__proto,'height',function(){ if (this._height)return this._height; return this.contextHeight; },_super.prototype._$set_height); /** *设置标签内容 */ __getset(0,__proto,'innerHTML',null,function(text){ this.destroyChildren(); this.appendHTML(text); }); /** *获取对象的宽 */ __getset(0,__proto,'width',function(){ if (this._width)return this._width; return this.contextWidth; },function(value){ var changed=false; if (value===0){ changed=value !=this._width; }else{ changed=value !=this.width; } Laya.superSet(HTMLElement,this,'width',value); if(changed) this.layout(); }); return HTMLDivElement; })(HTMLElement) /** *@private */ //class laya.html.dom.HTMLDocument extends laya.html.dom.HTMLElement var HTMLDocument=(function(_super){ function HTMLDocument(){ this.all=new Array; this.styleSheets=CSSStyle.styleSheets; HTMLDocument.__super.call(this); } __class(HTMLDocument,'laya.html.dom.HTMLDocument',_super); var __proto=HTMLDocument.prototype; __proto.getElementById=function(id){ return this.all[id]; } __proto.setElementById=function(id,e){ this.all[id]=e; } __static(HTMLDocument, ['document',function(){return this.document=new HTMLDocument();} ]); return HTMLDocument; })(HTMLElement) /** *@private */ //class laya.html.dom.HTMLImageElement extends laya.html.dom.HTMLElement var HTMLImageElement=(function(_super){ function HTMLImageElement(){ this._tex=null; this._url=null; this._renderArgs=[]; HTMLImageElement.__super.call(this); this.style.block=true; } __class(HTMLImageElement,'laya.html.dom.HTMLImageElement',_super); var __proto=HTMLImageElement.prototype; __proto._addToLayout=function(out){ !this._style.absolute && out.push(this); } __proto.render=function(context,x,y){ if (!this._tex || !this._tex.loaded || !this._tex.loaded || this._width < 1 || this._height < 1)return; Stat.spriteCount++; this._renderArgs[0]=this._tex; this._renderArgs[1]=this.x; this._renderArgs[2]=this.y; this._renderArgs[3]=this.width || this._tex.width; this._renderArgs[4]=this.height || this._tex.height; context.ctx.drawTexture2(x,y,this.style.translateX,this.style.translateY,this.transform,this.style.alpha,this.style.blendMode,this._renderArgs); } /** *@private */ __proto.layaoutCallNative=function(){ var n=0; if (this._childs &&(n=this._childs.length)> 0){ for (var i=0;i < n;i++){ this._childs[i].layaoutCallNative && this._childs[i].layaoutCallNative(); } } } __getset(0,__proto,'src',null,function(url){ var _$this=this; url=this.formatURL(url); if (this._url==url)return; this._url=url; var tex=this._tex=Loader.getRes(url); if (!tex){ this._tex=tex=new Texture(); tex.load(url); Loader.cacheRes(url,tex); } function onloaded (){ if (!_$this._style)return; var style=_$this._style; var w=style.widthed(_$this)?-1:_$this._tex.width; var h=style.heighted(_$this)?-1:_$this._tex.height; if (!style.widthed(_$this)&& _$this._width !=_$this._tex.width){ _$this.width=_$this._tex.width; _$this.parent && (_$this.parent)._layoutLater(); } if (!style.heighted(_$this)&& _$this._height !=_$this._tex.height){ _$this.height=_$this._tex.height; _$this.parent && (_$this.parent)._layoutLater(); } if (Render.isConchApp){ _$this._renderArgs[0]=_$this._tex; _$this._renderArgs[1]=_$this.x; _$this._renderArgs[2]=_$this.y; _$this._renderArgs[3]=_$this.width || _$this._tex.width; _$this._renderArgs[4]=_$this.height || _$this._tex.height; _$this.graphics.drawTexture(_$this._tex,0,0,_$this._renderArgs[3],_$this._renderArgs[4]); } _$this.repaint(); _$this.parentRepaint(); } tex.loaded?onloaded():tex.on(/*laya.events.Event.LOADED*/"loaded",null,onloaded); }); return HTMLImageElement; })(HTMLElement) /** *@private */ //class laya.html.dom.HTMLLinkElement extends laya.html.dom.HTMLElement var HTMLLinkElement=(function(_super){ function HTMLLinkElement(){ this.type=null; HTMLLinkElement.__super.call(this); this.visible=false; } __class(HTMLLinkElement,'laya.html.dom.HTMLLinkElement',_super); var __proto=HTMLLinkElement.prototype; __proto._onload=function(data){ switch(this.type){ case 'text/css': CSSStyle.parseCSS(data,this.URI); break ; } } __getset(0,__proto,'href',_super.prototype._$get_href,function(url){ var _$this=this; url=this.formatURL(url); this.URI=new URL(url); var l=new Loader(); l.once(/*laya.events.Event.COMPLETE*/"complete",null,function(data){ _$this._onload(data); }); l.load(url,/*laya.net.Loader.TEXT*/"text"); }); HTMLLinkElement._cuttingStyle=new RegExp("((@keyframes[\\s\\t]+|)(.+))[\\t\\n\\r\\\s]*{","g"); return HTMLLinkElement; })(HTMLElement) /** *@private */ //class laya.html.dom.HTMLStyleElement extends laya.html.dom.HTMLElement var HTMLStyleElement=(function(_super){ function HTMLStyleElement(){ HTMLStyleElement.__super.call(this); this.visible=false; } __class(HTMLStyleElement,'laya.html.dom.HTMLStyleElement',_super); var __proto=HTMLStyleElement.prototype; /** *解析样式 */ __getset(0,__proto,'text',_super.prototype._$get_text,function(value){ CSSStyle.parseCSS(value,null); }); return HTMLStyleElement; })(HTMLElement) /** *iframe标签类,目前用于加载外并解析数据 */ //class laya.html.dom.HTMLIframeElement extends laya.html.dom.HTMLDivElement var HTMLIframeElement=(function(_super){ function HTMLIframeElement(){ HTMLIframeElement.__super.call(this); this._getCSSStyle().valign="middle"; } __class(HTMLIframeElement,'laya.html.dom.HTMLIframeElement',_super); var __proto=HTMLIframeElement.prototype; /** *加载html文件,并解析数据 *@param url */ __getset(0,__proto,'href',_super.prototype._$get_href,function(url){ var _$this=this; url=this.formatURL(url); var l=new Loader(); l.once(/*laya.events.Event.COMPLETE*/"complete",null,function(data){ var pre=_$this.URI; _$this.URI=new URL(url); _$this.innerHTML=data; !pre || (_$this.URI=pre); }); l.load(url,/*laya.net.Loader.TEXT*/"text"); }); return HTMLIframeElement; })(HTMLDivElement) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.hwmini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Config=Laya.Config,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,RunDriver=laya.utils.RunDriver; var Sound=laya.media.Sound,SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager,TTMiniAdapter=laya.tt.mini.TTMiniAdapter; var URL=laya.net.URL,Utils=laya.utils.Utils; //class laya.hw.mini.HWMiniAdapter var HWMiniAdapter=(function(){ function HWMiniAdapter(){} __class(HWMiniAdapter,'laya.hw.mini.HWMiniAdapter'); HWMiniAdapter.getJson=function(data){ return JSON.parse(data); } HWMiniAdapter.init=function(isPosMsg,isSon){ (isPosMsg===void 0)&& (isPosMsg=false); (isSon===void 0)&& (isSon=false); if (HWMiniAdapter._inited)return; HWMiniAdapter._inited=true; HWMiniAdapter.window=/*__JS__ */window; if(!HWMiniAdapter.window.hasOwnProperty("hbs")) return; HWMiniAdapter.isZiYu=isSon; HWMiniAdapter.isPosMsgYu=isPosMsg; HWMiniAdapter.EnvConfig={}; try{ /*__JS__ */laya.webgl.resource.WebGLCanvas.premulAlpha=true; }catch(e){ } if(!HWMiniAdapter.isZiYu){ MiniFileMgr$9.setNativeFileDir("/layaairGame"); MiniFileMgr$9.existDir(MiniFileMgr$9.fileNativeDir,Handler.create(HWMiniAdapter,HWMiniAdapter.onMkdirCallBack)); } HWMiniAdapter.systemInfo=HWMiniAdapter.window.hbs.getSystemInfoSync(); if (HWMiniAdapter.systemInfo.system.toLowerCase()==='ios 10.1.1'){ try{ /*__JS__ */laya.webgl.resource.WebGLCharImage.canUseCanvas=false; }catch(e){ } } HWMiniAdapter.window.focus=function (){ }; Laya['_getUrlPath']=function (){ }; Laya['getUrlPath']=function (){ }; HWMiniAdapter.window.logtime=function (str){ }; HWMiniAdapter.window.alertTimeLog=function (str){ }; HWMiniAdapter.window.resetShareInfo=function (){ }; HWMiniAdapter._preCreateElement=Browser.createElement; Browser["createElement"]=HWMiniAdapter.createElement; RunDriver.createShaderCondition=HWMiniAdapter.createShaderCondition; Utils['parseXMLFromString']=HWMiniAdapter.parseXMLFromString; Input['_createInputElement']=MiniInput$9['_createInputElement']; HWMiniAdapter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader$9.prototype.load; Loader.prototype._loadImage=MiniImage$9.prototype._loadImage; Config.useRetinalCanvas=true; } HWMiniAdapter.measureText=function(str){ var tempObj=HWMiniAdapter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } HWMiniAdapter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return "binary"; return "utf8"; } HWMiniAdapter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr$9.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr$9.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } HWMiniAdapter.remove=function(fileUrl,callBack){ MiniFileMgr$9.deleteFile("",fileUrl,callBack,"",0); } HWMiniAdapter.removeAll=function(){ MiniFileMgr$9.deleteAll(); } HWMiniAdapter.hasNativeFile=function(fileUrl){ return MiniFileMgr$9.isLocalNativeFile(fileUrl); } HWMiniAdapter.getFileInfo=function(fileUrl){ return MiniFileMgr$9.getFileInfo(fileUrl); } HWMiniAdapter.getFileList=function(){ return MiniFileMgr$9.filesListObj; } HWMiniAdapter.exitMiniProgram=function(){ HWMiniAdapter.window.hbs.exitMiniProgram(); } HWMiniAdapter.onMkdirCallBack=function(errorCode,data){ if (!errorCode){ MiniFileMgr$9.filesListObj=JSON.parse(data.data); MiniFileMgr$9.fakeObj=JSON.parse(data.data)||{}; } } HWMiniAdapter.pixelRatio=function(){ if (!HWMiniAdapter.EnvConfig.pixelRatioInt){ try { HWMiniAdapter.EnvConfig.pixelRatioInt=HWMiniAdapter.systemInfo.pixelRatio; return HWMiniAdapter.systemInfo.pixelRatio; }catch (error){} } return HWMiniAdapter.EnvConfig.pixelRatioInt; } HWMiniAdapter.createElement=function(type){ if (type=="textarea" || type=="input"){ return HWMiniAdapter.onCreateInput(type); }else if (type=="div"){ var node=HWMiniAdapter._preCreateElement(type); node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } else { return HWMiniAdapter._preCreateElement(type); } } HWMiniAdapter.onCreateInput=function(type){ var node=HWMiniAdapter._preCreateElement(type); node.focus=MiniInput$9.inputFocus; node.blur=MiniInput$9.inputblur; node.style={}; node.value=0; node.parentElement={}; node.placeholder={}; node.type={}; node.setColor=function (value){ }; node.setType=function (value){ }; node.setFontFace=function (value){ }; node.addEventListener=function (value){ }; node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } HWMiniAdapter.createShaderCondition=function(conditionScript){ var _$this=this; var func=function (){ var abc=conditionScript; return _$this[conditionScript.replace("this.","")]; } return func; } HWMiniAdapter.sendAtlasToOpenDataContext=function(url){ if(!laya.hw.mini.HWMiniAdapter.isZiYu){ var atlasJson=Loader.getRes(URL.formatURL(url)); if(atlasJson){ var textureArr=(atlasJson.meta.image).split(","); if (atlasJson.meta && atlasJson.meta.image){ var toloadPics=atlasJson.meta.image.split(","); var split=url.indexOf("/")>=0 ? "/" :"\\"; var idx=url.lastIndexOf(split); var folderPath=idx >=0 ? url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[url.replace(".json",".png")]; } for(i=0;i\s+<'); try { /*__JS__ */rst=(new window.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } HWMiniAdapter.idx=1; __static(HWMiniAdapter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir","wxlocal"];} ]); return HWMiniAdapter; })() /**@private **/ //class laya.hw.mini.MiniFileMgr var MiniFileMgr$9=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.hw.mini.MiniFileMgr',null,'MiniFileMgr$9'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=HWMiniAdapter.nativefiles.length;i=totalSize)){ if(data.size > HWMiniAdapter.minClearSize) HWMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > HWMiniAdapter.minClearSize) HWMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=HWMiniAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.hw.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i *
  • 1.0 正常速度
  • *
  • 0.5 半速(更慢)
  • *
  • 2.0 倍速(更快)
  • *
  • -1.0 向后,正常速度
  • *
  • -0.5 向后,半速
  • * *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ if(!this.videoElement) return 0; return this.videoElement.playbackRate; },function(value){ if(!this.videoElement) return; this.videoElement.playbackRate=value; }); __getset(0,__proto,'x',function(){ if(!this.videoElement) return 0; return this.videoElement.x; },function(value){ if(!this.videoElement) return; this.videoElement.x=value; }); __getset(0,__proto,'y',function(){ if(!this.videoElement) return 0; return this.videoElement.y; },function(value){ if(!this.videoElement) return; this.videoElement.y=value; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.src; }); MiniVideo.__init__=function(){ /*__JS__ */laya.device.media.Video=MiniVideo; } return MiniVideo; })() /**@private **/ //class laya.hw.mini.MiniAccelerator extends laya.events.EventDispatcher var MiniAccelerator$9=(function(_super){ function MiniAccelerator(){ MiniAccelerator.__super.call(this); } __class(MiniAccelerator,'laya.hw.mini.MiniAccelerator',_super,'MiniAccelerator$9'); var __proto=MiniAccelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); MiniAccelerator.startListen(this["onDeviceOrientationChange"]); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) MiniAccelerator.stopListen(); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } MiniAccelerator.__init__=function(){ try{ var Acc; Acc=/*__JS__ */laya.device.motion.Accelerator; if (!Acc)return; Acc["prototype"]["on"]=MiniAccelerator["prototype"]["on"]; Acc["prototype"]["off"]=MiniAccelerator["prototype"]["off"]; }catch (e){ } } MiniAccelerator.startListen=function(callBack){ MiniAccelerator._callBack=callBack; if (MiniAccelerator._isListening)return; MiniAccelerator._isListening=true; try{ HWMiniAdapter.window.hbs.onAccelerometerChange(laya.hw.mini.MiniAccelerator.onAccelerometerChange); }catch(e){} } MiniAccelerator.stopListen=function(){ MiniAccelerator._isListening=false; try{ HWMiniAdapter.window.hbs.stopAccelerometer({}); }catch(e){} } MiniAccelerator.onAccelerometerChange=function(res){ var e; e={}; e.acceleration=res; e.accelerationIncludingGravity=res; e.rotationRate={}; if (MiniAccelerator._callBack !=null){ MiniAccelerator._callBack(e); } } MiniAccelerator._isListening=false; MiniAccelerator._callBack=null; return MiniAccelerator; })(EventDispatcher) /**@private **/ //class laya.hw.mini.MiniLoader extends laya.events.EventDispatcher var MiniLoader$9=(function(_super){ function MiniLoader(){ MiniLoader.__super.call(this); } __class(MiniLoader,'laya.hw.mini.MiniLoader',_super,'MiniLoader$9'); var __proto=MiniLoader.prototype; /** *@private *@param url *@param type *@param cache *@param group *@param ignoreCache */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); var thisLoader=this; thisLoader._url=url; if (url.indexOf("data:image")===0)thisLoader._type=type=/*laya.net.Loader.IMAGE*/"image"; else { thisLoader._type=type || (type=thisLoader.getTypeFromUrl(url)); } thisLoader._cache=cache; thisLoader._data=null; if (!ignoreCache && Loader.loadedMap[URL.formatURL(url)]){ thisLoader._data=Loader.loadedMap[URL.formatURL(url)]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",thisLoader._data); return; } if (Loader.parserMap[type] !=null){ thisLoader._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; }; var encoding=HWMiniAdapter.getUrlEncode(url,type); var urlType=Utils.getFileExtension(url); if ((MiniLoader._fileTypeArr.indexOf(urlType)!=-1)|| type==/*laya.net.Loader.IMAGE*/"image"){ HWMiniAdapter.EnvConfig.load.call(this,url,type,cache,group,ignoreCache); }else { if(HWMiniAdapter.isZiYu && !MiniFileMgr$9.ziyuFileData[url]){ url=URL.formatURL(url); } if(HWMiniAdapter.isZiYu && MiniFileMgr$9.ziyuFileData[url]){ var tempData=MiniFileMgr$9.ziyuFileData[url]; thisLoader.onLoaded(tempData); return; } if (!MiniFileMgr$9.getFileInfo(URL.formatURL(url))){ if (MiniFileMgr$9.isLocalNativeFile(url)){ if (HWMiniAdapter.subNativeFiles && HWMiniAdapter.subNativeheads.length==0){ for (var key in HWMiniAdapter.subNativeFiles){ var tempArr=HWMiniAdapter.subNativeFiles[key]; HWMiniAdapter.subNativeheads=HWMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ HWMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(HWMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && HWMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=HWMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } if(type==/*laya.net.Loader.SOUND*/"sound"){ thisLoader._loadSound(url); }else{ MiniFileMgr$9.read(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); } return; }; var tempUrl=url; var tempurl=URL.formatURL(url); if (tempurl.indexOf(HWMiniAdapter.window.hbs.env.USER_DATA_PATH)==-1 &&(url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)&& !HWMiniAdapter.AutoCacheDownFile){ if(type==/*laya.net.Loader.SOUND*/"sound"){ thisLoader._loadSound(url); }else{ HWMiniAdapter.EnvConfig.load.call(thisLoader,tempUrl,type,cache,group,ignoreCache); } }else { fileObj=MiniFileMgr$9.getFileInfo(url); if(fileObj){ fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; MiniFileMgr$9.readFile(fileObj.url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else if (thisLoader.type=="image" || thisLoader.type=="htmlimage"){ HWMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } else{ url=URL.formatURL(url); if(type !=/*laya.net.Loader.IMAGE*/"image" && ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1)|| MiniFileMgr$9.isLocalNativeFile(url))){ MiniFileMgr$9.readFile(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else{ MiniFileMgr$9.downFiles(encodeURI(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url,true); } } } }else { var fileObj=MiniFileMgr$9.getFileInfo(URL.formatURL(url)); fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; var nativepath=MiniFileMgr$9.getFileNativePath(fileObj.md5); MiniFileMgr$9.readFile(nativepath,fileObj.encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),URL.formatURL(url)); } } } /** *private *@param url **/ __proto._loadSound=function(url){ var thisLoader=this; var fileNativeUrl; if (MiniFileMgr$9.isLocalNativeFile(url)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="" && (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)) fileNativeUrl=url.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } laya.hw.mini.MiniLoader.onDownLoadCallBack(url,thisLoader,0); }else{ var tempurl=URL.formatURL(url); if (!MiniFileMgr$9.isLocalNativeFile(url)&& (tempurl.indexOf("http://")==-1 && tempurl.indexOf("https://")==-1)|| (tempurl.indexOf(HWMiniAdapter.window.hbs.env.USER_DATA_PATH)!=-1)){ laya.hw.mini.MiniLoader.onDownLoadCallBack(url,thisLoader,0); }else{ MiniFileMgr$9.downOtherFiles(encodeURI(tempurl),Handler.create(MiniLoader,laya.hw.mini.MiniLoader.onDownLoadCallBack,[tempurl,thisLoader]),tempurl); } } } MiniLoader.onDownLoadCallBack=function(sourceUrl,thisLoader,errorCode,tempFilePath){ if (!errorCode){ var fileNativeUrl; if(HWMiniAdapter.autoCacheFile){ if(!tempFilePath){ if (MiniFileMgr$9.isLocalNativeFile(sourceUrl)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=sourceUrl; if(tempStr !="" && (sourceUrl.indexOf("http://")!=-1 || sourceUrl.indexOf("https://")!=-1)) fileNativeUrl=sourceUrl.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } }else{ var fileObj=MiniFileMgr$9.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$9.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=sourceUrl; } } }else{ fileNativeUrl=tempFilePath; } } sourceUrl=fileNativeUrl; var sound=new SoundManager._soundClass(); sound.load(encodeURI(sourceUrl)); thisLoader.onLoaded(sound); }else{ thisLoader.event(/*laya.events.Event.ERROR*/"error","Load sound failed"); } } MiniLoader.onReadNativeCallBack=function(encoding,url,type,cache,group,ignoreCache,thisLoader,errorCode,data){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); (errorCode===void 0)&& (errorCode=0); if (!errorCode){ var tempData; if (type==/*laya.net.Loader.JSON*/"json" || type==/*laya.net.Loader.ATLAS*/"atlas"){ tempData=HWMiniAdapter.getJson(data.data); }else if (type==/*laya.net.Loader.XML*/"xml"){ tempData=Utils.parseXMLFromString(data.data); }else { tempData=data.data; } if(!HWMiniAdapter.isZiYu &&HWMiniAdapter.isPosMsgYu && type !=/*laya.net.Loader.BUFFER*/"arraybuffer" && HWMiniAdapter.window.hbs){ HWMiniAdapter.window.hbs.postMessage({url:url,data:tempData,isLoad:"filedata"}); } thisLoader.onLoaded(tempData); }else if (errorCode==1){ console.log("-----------本地加载失败,尝试外网加载----url:"+url); HWMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } } __static(MiniLoader, ['_fileTypeArr',function(){return this._fileTypeArr=['png','jpg','bmp','jpeg','gif'];} ]); return MiniLoader; })(EventDispatcher) /**@private **/ //class laya.hw.mini.MiniSound extends laya.events.EventDispatcher var MiniSound$9=(function(_super){ function MiniSound(){ /**@private **/ this._sound=null; /** *@private *声音URL */ this.url=null; /** *@private *是否已加载完成 */ this.loaded=false; /**@private **/ this.readyUrl=null; MiniSound.__super.call(this); } __class(MiniSound,'laya.hw.mini.MiniSound',_super,'MiniSound$9'); var __proto=MiniSound.prototype; /** *@private *加载声音。 *@param url 地址。 * */ __proto.load=function(url){ if (!MiniFileMgr$9.isLocalNativeFile(url)){ url=URL.formatURL(url); }else{ if (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1){ if(MiniFileMgr$9.loadPath !=""){ url=url.split(MiniFileMgr$9.loadPath)[1]; }else{ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; if(tempStr !="") url=url.split(tempStr)[1]; } } } this.url=url; this.readyUrl=url; if (MiniSound._audioCache[this.readyUrl]){ this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if(HWMiniAdapter.autoCacheFile&&MiniFileMgr$9.getFileInfo(url)){ this.onDownLoadCallBack(url,0); }else{ if(!HWMiniAdapter.autoCacheFile){ this.onDownLoadCallBack(url,0); }else{ if (MiniFileMgr$9.isLocalNativeFile(url)){ tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="") url=url.split(tempStr)[1]; if (!url){ url=tempUrl; } if (HWMiniAdapter.subNativeFiles && HWMiniAdapter.subNativeheads.length==0){ for (var key in HWMiniAdapter.subNativeFiles){ var tempArr=HWMiniAdapter.subNativeFiles[key]; HWMiniAdapter.subNativeheads=HWMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ HWMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(HWMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && HWMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=HWMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } this.onDownLoadCallBack(url,0); }else{ MiniFileMgr$9.downOtherFiles(encodeURI(url),Handler.create(this,this.onDownLoadCallBack,[url]),url); } } } } /**@private **/ __proto.onDownLoadCallBack=function(sourceUrl,errorCode){ if (!errorCode){ var fileNativeUrl; if(HWMiniAdapter.autoCacheFile){ if (MiniFileMgr$9.isLocalNativeFile(sourceUrl)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=sourceUrl; if(tempStr !="" && (sourceUrl.indexOf("http://")!=-1 || sourceUrl.indexOf("https://")!=-1)) fileNativeUrl=sourceUrl.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } }else{ var fileObj=MiniFileMgr$9.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$9.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=encodeURI(sourceUrl); } } this._sound=MiniSound._createSound(); this._sound.src=this.url=fileNativeUrl; }else{ this._sound=MiniSound._createSound(); this._sound.src=encodeURI(sourceUrl); } this._sound.onCanplay(MiniSound.bindToThis(this.onCanPlay,this)); this._sound.onError(MiniSound.bindToThis(this.onError,this)); }else{ this.event(/*laya.events.Event.ERROR*/"error"); } } /**@private **/ __proto.onError=function(error){ this.event(/*laya.events.Event.ERROR*/"error"); this._sound.offError(null); } /**@private **/ __proto.onCanPlay=function(){ this.loaded=true; this.event(/*laya.events.Event.COMPLETE*/"complete"); this._sound.offCanplay(null); } /** *@private *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); var tSound; if (this.url==SoundManager._tMusic){ if (!MiniSound._musicAudio)MiniSound._musicAudio=MiniSound._createSound(); tSound=MiniSound._musicAudio; }else { if(MiniSound._audioCache[this.readyUrl]){ tSound=MiniSound._audioCache[this.readyUrl]._sound; }else{ tSound=MiniSound._createSound(); } } if(HWMiniAdapter.autoCacheFile&&MiniFileMgr$9.getFileInfo(this.url)){ var fileNativeUrl; var fileObj=MiniFileMgr$9.getFileInfo(this.url); var fileMd5Name=fileObj.md5; tSound.src=this.url=MiniFileMgr$9.getFileNativePath(fileMd5Name); }else{ tSound.src=encodeURI(this.url); }; var channel=new MiniSoundChannel$9(tSound,this); channel.url=this.url; channel.loops=loops; channel.loop=(loops===0 ? true :false); channel.startTime=startTime; channel.play(); SoundManager.addChannel(channel); return channel; } /** *@private *释放声音资源。 * */ __proto.dispose=function(){ var ad=MiniSound._audioCache[this.readyUrl]; if (ad){ ad.src=""; if(ad._sound){ ad._sound.destroy(); ad._sound=null; ad=null; } delete MiniSound._audioCache[this.readyUrl]; } if(this._sound){ this._sound.destroy(); this._sound=null; } this.url=this.readyUrl=null; } /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ return this._sound.duration; }); MiniSound._createSound=function(){ MiniSound._id++; return HWMiniAdapter.window.hbs.createInnerAudioContext(); } MiniSound.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } MiniSound._musicAudio=null; MiniSound._id=0; MiniSound._audioCache={}; return MiniSound; })(EventDispatcher) /**@private **/ //class laya.hw.mini.MiniSoundChannel extends laya.media.SoundChannel var MiniSoundChannel$9=(function(_super){ function MiniSoundChannel(audio,miniSound){ /**@private **/ this._audio=null; /**@private **/ this._onEnd=null; /**@private **/ this._miniSound=null; MiniSoundChannel.__super.call(this); this._audio=audio; this._miniSound=miniSound; this._onEnd=MiniSoundChannel.bindToThis(this.__onEnd,this); audio.onEnded(this._onEnd); } __class(MiniSoundChannel,'laya.hw.mini.MiniSoundChannel',_super,'MiniSoundChannel$9'); var __proto=MiniSoundChannel.prototype; /**@private **/ __proto.__onEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.stop(); this._audio.offEnded(null); this._audio.destroy(); this._audio=null; this._miniSound=null; this._onEnd=null; } /**@private **/ __proto.pause=function(){ this.isStopped=true; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',null,function(time){ if(this._audio){ this._audio.startTime=time; } }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ return this._audio.autoplay; },function(value){ this._audio.autoplay=value; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ return this._audio.loop; },function(value){ this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.particle.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var BlendMode=laya.webgl.canvas.BlendMode,Event=laya.events.Event,HTMLCanvas=laya.resource.HTMLCanvas; var Handler=laya.utils.Handler,IndexBuffer2D=laya.webgl.utils.IndexBuffer2D,Loader=laya.net.Loader,MathUtil=laya.maths.MathUtil; var Matrix=laya.maths.Matrix,Render=laya.renders.Render,RenderContext=laya.renders.RenderContext,RenderSprite=laya.renders.RenderSprite; var Shader=laya.webgl.shader.Shader,Sprite=laya.display.Sprite,Stat=laya.utils.Stat,Texture=laya.resource.Texture; var Utils=laya.utils.Utils,Value2D=laya.webgl.shader.d2.value.Value2D,VertexBuffer2D=laya.webgl.utils.VertexBuffer2D; var WebGL=laya.webgl.WebGL,WebGLContext=laya.webgl.WebGLContext; /** *EmitterBase 类是粒子发射器类 */ //class laya.particle.emitter.EmitterBase var EmitterBase=(function(){ function EmitterBase(){ /** *积累的帧时间 */ this._frameTime=0; /** *粒子发射速率 */ this._emissionRate=60; /** *当前剩余发射时间 */ this._emissionTime=0; /** *发射粒子最小时间间隔 */ this.minEmissionTime=1 / 60; /**@private */ this._particleTemplate=null; } __class(EmitterBase,'laya.particle.emitter.EmitterBase'); var __proto=EmitterBase.prototype; /** *开始发射粒子 *@param duration 发射持续的时间(秒) */ __proto.start=function(duration){ (duration===void 0)&& (duration=2147483647); if (this._emissionRate !=0) this._emissionTime=duration; } /** *停止发射粒子 *@param clearParticles 是否清理当前的粒子 */ __proto.stop=function(){ this._emissionTime=0; } /** *清理当前的活跃粒子 *@param clearTexture 是否清理贴图数据,若清除贴图数据将无法再播放 */ __proto.clear=function(){ this._emissionTime=0; } /** *发射一个粒子 * */ __proto.emit=function(){} /** *时钟前进 *@param passedTime 前进时间 * */ __proto.advanceTime=function(passedTime){ (passedTime===void 0)&& (passedTime=1); this._emissionTime-=passedTime; if (this._emissionTime < 0)return; this._frameTime+=passedTime; if (this._frameTime < this.minEmissionTime)return; while (this._frameTime > this.minEmissionTime){ this._frameTime-=this.minEmissionTime; this.emit(); } } /** *设置粒子粒子模板 *@param particleTemplate 粒子模板 * */ __getset(0,__proto,'particleTemplate',null,function(particleTemplate){ this._particleTemplate=particleTemplate; }); /** *设置粒子发射速率 *@param emissionRate 粒子发射速率 (个/秒) */ /** *获取粒子发射速率 *@return 发射速率 粒子发射速率 (个/秒) */ __getset(0,__proto,'emissionRate',function(){ return this._emissionRate; },function(_emissionRate){ if (_emissionRate <=0)return; this._emissionRate=_emissionRate; (_emissionRate > 0)&& (this.minEmissionTime=1 / _emissionRate); }); return EmitterBase; })() /** *@private */ //class laya.particle.ParticleData var ParticleData=(function(){ function ParticleData(){ this.position=null; this.velocity=null; this.startColor=null; this.endColor=null; this.sizeRotation=null; this.radius=null; this.radian=null; this.durationAddScale=NaN; this.time=NaN; } __class(ParticleData,'laya.particle.ParticleData'); ParticleData.Create=function(settings,position,velocity,time){ var particleData=new ParticleData(); particleData.position=position; MathUtil.scaleVector3(velocity,settings.emitterVelocitySensitivity,ParticleData._tempVelocity); var horizontalVelocity=MathUtil.lerp(settings.minHorizontalVelocity,settings.maxHorizontalVelocity,Math.random()); var horizontalAngle=Math.random()*Math.PI *2; ParticleData._tempVelocity[0]+=horizontalVelocity *Math.cos(horizontalAngle); ParticleData._tempVelocity[2]+=horizontalVelocity *Math.sin(horizontalAngle); ParticleData._tempVelocity[1]+=MathUtil.lerp(settings.minVerticalVelocity,settings.maxVerticalVelocity,Math.random()); particleData.velocity=ParticleData._tempVelocity; particleData.startColor=ParticleData._tempStartColor; particleData.endColor=ParticleData._tempEndColor; var i=0; if (settings.disableColor){ for (i=0;i < 4;i++){ particleData.startColor[i]=1; particleData.endColor[i]=1; } } else{ if (settings.colorComponentInter){ for (i=0;i < 4;i++){ particleData.startColor[i]=MathUtil.lerp(settings.minStartColor[i],settings.maxStartColor[i],Math.random()); particleData.endColor[i]=MathUtil.lerp(settings.minEndColor[i],settings.maxEndColor[i],Math.random()); } }else { MathUtil.lerpVector4(settings.minStartColor,settings.maxStartColor,Math.random(),particleData.startColor); MathUtil.lerpVector4(settings.minEndColor,settings.maxEndColor,Math.random(),particleData.endColor); } } particleData.sizeRotation=ParticleData._tempSizeRotation; var sizeRandom=Math.random(); particleData.sizeRotation[0]=MathUtil.lerp(settings.minStartSize,settings.maxStartSize,sizeRandom); particleData.sizeRotation[1]=MathUtil.lerp(settings.minEndSize,settings.maxEndSize,sizeRandom); particleData.sizeRotation[2]=MathUtil.lerp(settings.minRotateSpeed,settings.maxRotateSpeed,Math.random()); particleData.radius=ParticleData._tempRadius; var radiusRandom=Math.random(); particleData.radius[0]=MathUtil.lerp(settings.minStartRadius,settings.maxStartRadius,radiusRandom); particleData.radius[1]=MathUtil.lerp(settings.minEndRadius,settings.maxEndRadius,radiusRandom); particleData.radian=ParticleData._tempRadian; particleData.radian[0]=MathUtil.lerp(settings.minHorizontalStartRadian,settings.maxHorizontalStartRadian,Math.random()); particleData.radian[1]=MathUtil.lerp(settings.minVerticalStartRadian,settings.maxVerticalStartRadian,Math.random()); var useEndRadian=settings.useEndRadian; particleData.radian[2]=useEndRadian?MathUtil.lerp(settings.minHorizontalEndRadian,settings.maxHorizontalEndRadian,Math.random()):particleData.radian[0]; particleData.radian[3]=useEndRadian?MathUtil.lerp(settings.minVerticalEndRadian,settings.maxVerticalEndRadian,Math.random()):particleData.radian[1]; particleData.durationAddScale=settings.ageAddScale *Math.random(); particleData.time=time; return particleData; } __static(ParticleData, ['_tempVelocity',function(){return this._tempVelocity=new Float32Array(3);},'_tempStartColor',function(){return this._tempStartColor=new Float32Array(4);},'_tempEndColor',function(){return this._tempEndColor=new Float32Array(4);},'_tempSizeRotation',function(){return this._tempSizeRotation=new Float32Array(3);},'_tempRadius',function(){return this._tempRadius=new Float32Array(2);},'_tempRadian',function(){return this._tempRadian=new Float32Array(4);} ]); return ParticleData; })() /** *@private */ //class laya.particle.ParticleEmitter var ParticleEmitter=(function(){ function ParticleEmitter(templet,particlesPerSecond,initialPosition){ this._templet=null; this._timeBetweenParticles=NaN; this._previousPosition=null; this._timeLeftOver=0; this._tempVelocity=new Float32Array([0,0,0]); this._tempPosition=new Float32Array([0,0,0]); this._templet=templet; this._timeBetweenParticles=1.0 / particlesPerSecond; this._previousPosition=initialPosition; } __class(ParticleEmitter,'laya.particle.ParticleEmitter'); var __proto=ParticleEmitter.prototype; __proto.update=function(elapsedTime,newPosition){ elapsedTime=elapsedTime / 1000; if (elapsedTime > 0){ MathUtil.subtractVector3(newPosition,this._previousPosition,this._tempVelocity); MathUtil.scaleVector3(this._tempVelocity,1 / elapsedTime,this._tempVelocity); var timeToSpend=this._timeLeftOver+elapsedTime; var currentTime=-this._timeLeftOver; while (timeToSpend > this._timeBetweenParticles){ currentTime+=this._timeBetweenParticles; timeToSpend-=this._timeBetweenParticles; MathUtil.lerpVector3(this._previousPosition,newPosition,currentTime / elapsedTime,this._tempPosition); this._templet.addParticleArray(this._tempPosition,this._tempVelocity); } this._timeLeftOver=timeToSpend; } this._previousPosition[0]=newPosition[0]; this._previousPosition[1]=newPosition[1]; this._previousPosition[2]=newPosition[2]; } return ParticleEmitter; })() /** *ParticleSettings 类是粒子配置数据类 */ //class laya.particle.ParticleSetting var ParticleSetting=(function(){ function ParticleSetting(){ /**贴图*/ this.textureName=null; /**贴图个数,默认为1可不设置*/ this.textureCount=1; /**最大同屏粒子个数,最大饱和粒子数为maxPartices-1。注意:WebGL模式下释放粒子时间为最大声明周期,可能会出现释放延迟,实际看到的同屏粒子数小于该数值,如连续喷发出现中断,请调大该数值。*/ this.maxPartices=100; /**粒子持续时间(单位:秒)*/ this.duration=1; /**如果大于0,某些粒子的持续时间会小于其他粒子,并具有随机性(单位:无)*/ this.ageAddScale=0; /**粒子受发射器速度的敏感度(需在自定义发射器中编码设置)*/ this.emitterVelocitySensitivity=1; /**最小开始尺寸(单位:2D像素、3D坐标)*/ this.minStartSize=100; /**最大开始尺寸(单位:2D像素、3D坐标)*/ this.maxStartSize=100; /**最小结束尺寸(单位:2D像素、3D坐标)*/ this.minEndSize=100; /**最大结束尺寸(单位:2D像素、3D坐标)*/ this.maxEndSize=100; /**最小水平速度(单位:2D像素、3D坐标)*/ this.minHorizontalVelocity=0; /**最大水平速度(单位:2D像素、3D坐标)*/ this.maxHorizontalVelocity=0; /**最小垂直速度(单位:2D像素、3D坐标)*/ this.minVerticalVelocity=0; /**最大垂直速度(单位:2D像素、3D坐标)*/ this.maxVerticalVelocity=0; /**等于1时粒子从出生到消亡保持一致的速度,等于0时粒子消亡时速度为0,大于1时粒子会保持加速(单位:无)*/ this.endVelocity=1; /**最小旋转速度(单位:2D弧度/秒、3D弧度/秒)*/ this.minRotateSpeed=0; /**最大旋转速度(单位:2D弧度/秒、3D弧度/秒)*/ this.maxRotateSpeed=0; /**最小开始半径(单位:2D像素、3D坐标)*/ this.minStartRadius=0; /**最大开始半径(单位:2D像素、3D坐标)*/ this.maxStartRadius=0; /**最小结束半径(单位:2D像素、3D坐标)*/ this.minEndRadius=0; /**最大结束半径(单位:2D像素、3D坐标)*/ this.maxEndRadius=0; /**最小水平开始弧度(单位:2D弧度、3D弧度)*/ this.minHorizontalStartRadian=0; /**最大水平开始弧度(单位:2D弧度、3D弧度)*/ this.maxHorizontalStartRadian=0; /**最小垂直开始弧度(单位:2D弧度、3D弧度)*/ this.minVerticalStartRadian=0; /**最大垂直开始弧度(单位:2D弧度、3D弧度)*/ this.maxVerticalStartRadian=0; /**是否使用结束弧度,false为结束时与起始弧度保持一致,true为根据minHorizontalEndRadian、maxHorizontalEndRadian、minVerticalEndRadian、maxVerticalEndRadian计算结束弧度。*/ this.useEndRadian=true; /**最小水平结束弧度(单位:2D弧度、3D弧度)*/ this.minHorizontalEndRadian=0; /**最大水平结束弧度(单位:2D弧度、3D弧度)*/ this.maxHorizontalEndRadian=0; /**最小垂直结束弧度(单位:2D弧度、3D弧度)*/ this.minVerticalEndRadian=0; /**最大垂直结束弧度(单位:2D弧度、3D弧度)*/ this.maxVerticalEndRadian=0; /**false代表RGBA整体插值,true代表RGBA逐分量插值*/ this.colorComponentInter=false; /**false代表使用参数颜色数据,true代表使用原图颜色数据*/ this.disableColor=false; /**混合模式,待调整,引擎中暂无BlendState抽象*/ this.blendState=0; /**发射器类型,"point","box","sphere","ring"*/ this.emitterType="null"; /**发射器发射速率*/ this.emissionRate=0; /**球发射器半径*/ this.sphereEmitterRadius=1; /**球发射器速度*/ this.sphereEmitterVelocity=0; /**球发射器速度随机值*/ this.sphereEmitterVelocityAddVariance=0; /**环发射器半径*/ this.ringEmitterRadius=30; /**环发射器速度*/ this.ringEmitterVelocity=0; /**环发射器速度随机值*/ this.ringEmitterVelocityAddVariance=0; /**环发射器up向量,0代表X轴,1代表Y轴,2代表Z轴*/ this.ringEmitterUp=2; this.gravity=new Float32Array([0,0,0]); this.minStartColor=new Float32Array([1,1,1,1]); this.maxStartColor=new Float32Array([1,1,1,1]); this.minEndColor=new Float32Array([1,1,1,1]); this.maxEndColor=new Float32Array([1,1,1,1]); this.pointEmitterPosition=new Float32Array([0,0,0]); this.pointEmitterPositionVariance=new Float32Array([0,0,0]); this.pointEmitterVelocity=new Float32Array([0,0,0]); this.pointEmitterVelocityAddVariance=new Float32Array([0,0,0]); this.boxEmitterCenterPosition=new Float32Array([0,0,0]); this.boxEmitterSize=new Float32Array([0,0,0]); this.boxEmitterVelocity=new Float32Array([0,0,0]); this.boxEmitterVelocityAddVariance=new Float32Array([0,0,0]); this.sphereEmitterCenterPosition=new Float32Array([0,0,0]); this.ringEmitterCenterPosition=new Float32Array([0,0,0]); this.positionVariance=new Float32Array([0,0,0]); } __class(ParticleSetting,'laya.particle.ParticleSetting'); ParticleSetting.checkSetting=function(setting){ var key; for (key in ParticleSetting._defaultSetting){ if (!setting.hasOwnProperty(key)){ setting[key]=ParticleSetting._defaultSetting[key]; } } setting.endVelocity=+setting.endVelocity; setting.gravity[0]=+setting.gravity[0]; setting.gravity[1]=+setting.gravity[1]; setting.gravity[2]=+setting.gravity[2]; } __static(ParticleSetting, ['_defaultSetting',function(){return this._defaultSetting=new ParticleSetting();} ]); return ParticleSetting; })() /** * *ParticleTemplateBase 类是粒子模板基类 * */ //class laya.particle.ParticleTemplateBase var ParticleTemplateBase=(function(){ function ParticleTemplateBase(){ /** *粒子配置数据 */ this.settings=null; /** *粒子贴图 */ this.texture=null; } __class(ParticleTemplateBase,'laya.particle.ParticleTemplateBase'); var __proto=ParticleTemplateBase.prototype; /** *添加一个粒子 *@param position 粒子位置 *@param velocity 粒子速度 * */ __proto.addParticleArray=function(position,velocity){} return ParticleTemplateBase; })() /** *@private */ //class laya.particle.particleUtils.CanvasShader var CanvasShader=(function(){ function CanvasShader(){ this.u_Duration=NaN; this.u_EndVelocity=NaN; this.u_Gravity=null; this.a_Position=null; this.a_Velocity=null; this.a_StartColor=null; this.a_EndColor=null; this.a_SizeRotation=null; this.a_Radius=null; this.a_Radian=null; this.a_AgeAddScale=NaN; this.gl_Position=null; this.v_Color=null; this.oSize=NaN; this._color=new Float32Array(4); this._position=new Float32Array(3); } __class(CanvasShader,'laya.particle.particleUtils.CanvasShader'); var __proto=CanvasShader.prototype; __proto.getLen=function(position){ return Math.sqrt(position[0] *position[0]+position[1] *position[1]+position[2] *position[2]); } __proto.ComputeParticlePosition=function(position,velocity,age,normalizedAge){ this._position[0]=position[0]; this._position[1]=position[1]; this._position[2]=position[2]; var startVelocity=this.getLen(velocity); var endVelocity=startVelocity *this.u_EndVelocity; var velocityIntegral=startVelocity *normalizedAge+(endVelocity-startVelocity)*normalizedAge *normalizedAge / 2.0; var lenVelocity=NaN; lenVelocity=this.getLen(velocity); var i=0,len=0; len=3; for (i=0;i < len;i++){ this._position[i]=this._position[i]+(velocity[i] / lenVelocity)*velocityIntegral *this.u_Duration; this._position[i]+=this.u_Gravity[i] *age *normalizedAge; }; var radius=MathUtil.lerp(this.a_Radius[0],this.a_Radius[1],normalizedAge); var radianHorizontal=MathUtil.lerp(this.a_Radian[0],this.a_Radian[2],normalizedAge); var radianVertical=MathUtil.lerp(this.a_Radian[1],this.a_Radian[3],normalizedAge); var r=Math.cos(radianVertical)*radius; this._position[1]+=Math.sin(radianVertical)*radius; this._position[0]+=Math.cos(radianHorizontal)*r; this._position[2]+=Math.sin(radianHorizontal)*r; return new Float32Array([this._position[0],this._position[1],0.0,1.0]); } __proto.ComputeParticleSize=function(startSize,endSize,normalizedAge){ var size=MathUtil.lerp(startSize,endSize,normalizedAge); return size; } __proto.ComputeParticleRotation=function(rot,age){ return rot *age; } __proto.ComputeParticleColor=function(startColor,endColor,normalizedAge){ var rst=this._color; MathUtil.lerpVector4(startColor,endColor,normalizedAge,rst); rst[3]=rst[3]*normalizedAge *(1.0-normalizedAge)*(1.0-normalizedAge)*6.7; return rst; } __proto.clamp=function(value,min,max){ if(valuemax)return max; return value; } __proto.getData=function(age){ age *=1.0+this.a_AgeAddScale; var normalizedAge=this.clamp(age / this.u_Duration,0.0,1.0); this.gl_Position=this.ComputeParticlePosition(this.a_Position,this.a_Velocity,age,normalizedAge); var pSize=this.ComputeParticleSize(this.a_SizeRotation[0],this.a_SizeRotation[1],normalizedAge); var rotation=this.ComputeParticleRotation(this.a_SizeRotation[2],age); this.v_Color=this.ComputeParticleColor(this.a_StartColor,this.a_EndColor,normalizedAge); var matric=new Matrix(); var scale=NaN; scale=pSize/this.oSize*2; matric.scale(scale,scale); matric.rotate(rotation); matric.setTranslate(this.gl_Position[0],-this.gl_Position[1]); var alpha=NaN; alpha=this.v_Color[3]; return [this.v_Color,alpha,matric,this.v_Color[0]*alpha,this.v_Color[1]*alpha,this.v_Color[2]*alpha]; } return CanvasShader; })() /** * *@private * *@created 2015-8-25 下午3:41:07 */ //class laya.particle.particleUtils.CMDParticle var CMDParticle=(function(){ function CMDParticle(){ /** *最大帧 */ this.maxIndex=0; /** *帧命令数组 */ this.cmds=null; /** *粒子id */ this.id=0; } __class(CMDParticle,'laya.particle.particleUtils.CMDParticle'); var __proto=CMDParticle.prototype; __proto.setCmds=function(cmds){ this.cmds=cmds; this.maxIndex=cmds.length-1; } return CMDParticle; })() //class laya.particle.particleUtils.PicTool var PicTool=(function(){ function PicTool(){} __class(PicTool,'laya.particle.particleUtils.PicTool'); PicTool.getCanvasPic=function(img,color){ img=img.bitmap; var canvas=new HTMLCanvas("2D"); var ctx=canvas.getContext('2d'); canvas.size(img.width,img.height); var red=(color >> 16 & 0xFF); var green=(color >> 8 & 0xFF); var blue=(color & 0xFF); if(Render.isConchApp){ ctx.setFilter(red/255,green/255,blue/255,0); } ctx.drawImage(img.source,0,0); if (!Render.isConchApp){ var imgdata=ctx.getImageData(0,0,canvas.width,canvas.height); var data=imgdata.data; for (var i=0,n=data.length;i < n;i+=4){ if (data[i+3]==0)continue ; data[i] *=red/255; data[i+1] *=green/255; data[i+2] *=blue/255; } ctx.putImageData(imgdata,0,0); } return canvas; } PicTool.getRGBPic=function(img){ var rst; rst=[new Texture(PicTool.getCanvasPic(img,0xFF0000)),new Texture(PicTool.getCanvasPic(img,0x00FF00)),new Texture(PicTool.getCanvasPic(img,0x0000FF))]; return rst; } return PicTool; })() /** * *@private */ //class laya.particle.emitter.Emitter2D extends laya.particle.emitter.EmitterBase var Emitter2D=(function(_super){ function Emitter2D(_template){ this.setting=null; this._posRange=null; this._canvasTemplate=null; this._emitFun=null; Emitter2D.__super.call(this); this.template=_template; } __class(Emitter2D,'laya.particle.emitter.Emitter2D',_super); var __proto=Emitter2D.prototype; __proto.emit=function(){ _super.prototype.emit.call(this); if(this._emitFun!=null) this._emitFun(); } __proto.getRandom=function(value){ return (Math.random()*2-1)*value; } __proto.webGLEmit=function(){ var pos=new Float32Array(3); pos[0]=this.getRandom(this._posRange[0]); pos[1]=this.getRandom(this._posRange[1]); pos[2]=this.getRandom(this._posRange[2]); var v=new Float32Array(3); v[0]=0; v[1]=0; v[2]=0; this._particleTemplate.addParticleArray(pos,v); } __proto.canvasEmit=function(){ var pos=new Float32Array(3); pos[0]=this.getRandom(this._posRange[0]); pos[1]=this.getRandom(this._posRange[1]); pos[2]=this.getRandom(this._posRange[2]); var v=new Float32Array(3); v[0]=0; v[1]=0; v[2]=0; this._particleTemplate.addParticleArray(pos,v); } __getset(0,__proto,'template',function(){ return this._particleTemplate; },function(template){ this._particleTemplate=template; if (!template){ this._emitFun=null; this.setting=null; this._posRange=null; }; this.setting=template.settings; this._posRange=this.setting.positionVariance; if((this._particleTemplate instanceof laya.particle.ParticleTemplate2D )){ this._emitFun=this.webGLEmit; }else if((this._particleTemplate instanceof laya.particle.ParticleTemplateCanvas )){ this._canvasTemplate=template; this._emitFun=this.canvasEmit; } }); return Emitter2D; })(EmitterBase) /** *@private */ //class laya.particle.ParticleTemplateWebGL extends laya.particle.ParticleTemplateBase var ParticleTemplateWebGL=(function(_super){ function ParticleTemplateWebGL(parSetting){ this._vertices=null; this._vertexBuffer=null; this._indexBuffer=null; this._floatCountPerVertex=29; //0~3为CornerTextureCoordinate,4~6为Position,7~9Velocity,10到13为StartColor,14到17为EndColor,18到20位SizeRotation,21到22位Radius,23到26位Radian,27为DurationAddScaleShaderValue,28为Time this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._currentTime=0; this._drawCounter=0; ParticleTemplateWebGL.__super.call(this); this.settings=parSetting; } __class(ParticleTemplateWebGL,'laya.particle.ParticleTemplateWebGL',_super); var __proto=ParticleTemplateWebGL.prototype; __proto.initialize=function(){ this._vertices=new Float32Array(this.settings.maxPartices *this._floatCountPerVertex *4); var particleOffset=0; for (var i=0;i < this.settings.maxPartices;i++){ var random=Math.random(); var cornerYSegement=this.settings.textureCount ? 1.0 / this.settings.textureCount :1.0; var cornerY=NaN; for (cornerY=0;cornerY < this.settings.textureCount;cornerY+=cornerYSegement){ if (random < cornerY+cornerYSegement) break ; } particleOffset=i *this._floatCountPerVertex *4; this._vertices[particleOffset+this._floatCountPerVertex *0+0]=-1; this._vertices[particleOffset+this._floatCountPerVertex *0+1]=-1; this._vertices[particleOffset+this._floatCountPerVertex *0+2]=0; this._vertices[particleOffset+this._floatCountPerVertex *0+3]=cornerY; this._vertices[particleOffset+this._floatCountPerVertex *1+0]=1; this._vertices[particleOffset+this._floatCountPerVertex *1+1]=-1; this._vertices[particleOffset+this._floatCountPerVertex *1+2]=1; this._vertices[particleOffset+this._floatCountPerVertex *1+3]=cornerY; this._vertices[particleOffset+this._floatCountPerVertex *2+0]=1; this._vertices[particleOffset+this._floatCountPerVertex *2+1]=1; this._vertices[particleOffset+this._floatCountPerVertex *2+2]=1; this._vertices[particleOffset+this._floatCountPerVertex *2+3]=cornerY+cornerYSegement; this._vertices[particleOffset+this._floatCountPerVertex *3+0]=-1; this._vertices[particleOffset+this._floatCountPerVertex *3+1]=1; this._vertices[particleOffset+this._floatCountPerVertex *3+2]=0; this._vertices[particleOffset+this._floatCountPerVertex *3+3]=cornerY+cornerYSegement; } } __proto.loadContent=function(){} __proto.update=function(elapsedTime){ this._currentTime+=elapsedTime / 1000; this.retireActiveParticles(); this.freeRetiredParticles(); if (this._firstActiveElement==this._firstFreeElement) this._currentTime=0; if (this._firstRetiredElement==this._firstActiveElement) this._drawCounter=0; } __proto.retireActiveParticles=function(){ var epsilon=0.0001; var particleDuration=this.settings.duration; while (this._firstActiveElement !=this._firstNewElement){ var offset=this._firstActiveElement *this._floatCountPerVertex *4; var index=offset+28; var particleAge=this._currentTime-this._vertices[index]; particleAge *=(1.0+this._vertices[offset+27]); if (particleAge+epsilon < particleDuration) break ; this._vertices[index]=this._drawCounter; this._firstActiveElement++; if (this._firstActiveElement >=this.settings.maxPartices) this._firstActiveElement=0; } } __proto.freeRetiredParticles=function(){ while (this._firstRetiredElement !=this._firstActiveElement){ var age=this._drawCounter-this._vertices[this._firstRetiredElement *this._floatCountPerVertex *4+28]; if (age < 3) break ; this._firstRetiredElement++; if (this._firstRetiredElement >=this.settings.maxPartices) this._firstRetiredElement=0; } } __proto.addNewParticlesToVertexBuffer=function(){} __proto.addParticleArray=function(position,velocity){ var nextFreeParticle=this._firstFreeElement+1; if (nextFreeParticle >=this.settings.maxPartices) nextFreeParticle=0; if (nextFreeParticle===this._firstRetiredElement) return; var particleData=ParticleData.Create(this.settings,position,velocity,this._currentTime); var startIndex=this._firstFreeElement *this._floatCountPerVertex *4; for (var i=0;i < 4;i++){ var j=0,offset=0; for (j=0,offset=4;j < 3;j++) this._vertices[startIndex+i *this._floatCountPerVertex+offset+j]=particleData.position[j]; for (j=0,offset=7;j < 3;j++) this._vertices[startIndex+i *this._floatCountPerVertex+offset+j]=particleData.velocity[j]; for (j=0,offset=10;j < 4;j++) this._vertices[startIndex+i *this._floatCountPerVertex+offset+j]=particleData.startColor[j]; for (j=0,offset=14;j < 4;j++) this._vertices[startIndex+i *this._floatCountPerVertex+offset+j]=particleData.endColor[j]; for (j=0,offset=18;j < 3;j++) this._vertices[startIndex+i *this._floatCountPerVertex+offset+j]=particleData.sizeRotation[j]; for (j=0,offset=21;j < 2;j++) this._vertices[startIndex+i *this._floatCountPerVertex+offset+j]=particleData.radius[j]; for (j=0,offset=23;j < 4;j++) this._vertices[startIndex+i *this._floatCountPerVertex+offset+j]=particleData.radian[j]; this._vertices[startIndex+i *this._floatCountPerVertex+27]=particleData.durationAddScale; this._vertices[startIndex+i *this._floatCountPerVertex+28]=particleData.time; } this._firstFreeElement=nextFreeParticle; } return ParticleTemplateWebGL; })(ParticleTemplateBase) /** *@private */ //class laya.particle.ParticleTemplateCanvas extends laya.particle.ParticleTemplateBase var ParticleTemplateCanvas=(function(_super){ function ParticleTemplateCanvas(particleSetting){ /** *是否处于可播放状态 */ this._ready=false; /** *贴图列表 */ this.textureList=[]; /** *粒子列表 */ this.particleList=[]; /** *贴图中心偏移x */ this.pX=0; /** *贴图中心偏移y */ this.pY=0; /** *当前活跃的粒子 */ this.activeParticles=[]; /** *粒子pool */ this.deadParticles=[]; /** *粒子播放进度列表 */ this.iList=[]; /** *粒子系统使用的最大粒子数 */ this._maxNumParticles=0; /** *纹理的宽度 */ this.textureWidth=NaN; /** *宽度倒数 */ this.dTextureWidth=NaN; /** *是否支持颜色变化 */ this.colorChange=true; /** *采样步长 */ this.step=1/60; this.canvasShader=new CanvasShader(); ParticleTemplateCanvas.__super.call(this); this.settings=particleSetting; this._maxNumParticles=particleSetting.maxPartices; this.texture=new Texture(); this.texture.on(/*laya.events.Event.LOADED*/"loaded",this,this._textureLoaded); this.texture.load(particleSetting.textureName); } __class(ParticleTemplateCanvas,'laya.particle.ParticleTemplateCanvas',_super); var __proto=ParticleTemplateCanvas.prototype; __proto._textureLoaded=function(e){ this.setTexture(this.texture); this._ready=true; } __proto.clear=function(clearTexture){ (clearTexture===void 0)&& (clearTexture=true); this.deadParticles.length=0; this.activeParticles.length=0; this.textureList.length=0; } /** *设置纹理 *@param texture * */ __proto.setTexture=function(texture){ this.texture=texture; this.textureWidth=texture.width; this.dTextureWidth=1/this.textureWidth; this.pX=-texture.width*0.5; this.pY=-texture.height*0.5; this.textureList=ParticleTemplateCanvas.changeTexture(texture,this.textureList); this.particleList.length=0; this.deadParticles.length=0; this.activeParticles.length=0; } /** *创建一个粒子数据 *@return * */ __proto._createAParticleData=function(position,velocity){ this.canvasShader.u_EndVelocity=this.settings.endVelocity; this.canvasShader.u_Gravity=this.settings.gravity; this.canvasShader.u_Duration=this.settings.duration; var particle; particle=ParticleData.Create(this.settings,position,velocity,0); this.canvasShader.a_Position=particle.position; this.canvasShader.a_Velocity=particle.velocity; this.canvasShader.a_StartColor=particle.startColor; this.canvasShader.a_EndColor=particle.endColor; this.canvasShader.a_SizeRotation=particle.sizeRotation; this.canvasShader.a_Radius=particle.radius; this.canvasShader.a_Radian=particle.radian; this.canvasShader.a_AgeAddScale=particle.durationAddScale; this.canvasShader.oSize=this.textureWidth; var rst=new CMDParticle(); var i=0,len=this.settings.duration/(1+particle.durationAddScale); var params=[]; var mStep=NaN; for(i=0;i0){ tParticle=this.deadParticles.pop(); this.iList[tParticle.id]=0; this.activeParticles.push(tParticle); } } } __proto.advanceTime=function(passedTime){ (passedTime===void 0)&& (passedTime=1); if(!this._ready)return; var particleList=this.activeParticles; var pool=this.deadParticles; var i=0,len=particleList.length; var tcmd; var tI=0; var iList=this.iList; for(i=len-1;i>-1;i--){ tcmd=particleList[i]; tI=iList[tcmd.id]; if(tI>=tcmd.maxIndex){ tI=0; particleList.splice(i,1); pool.push(tcmd); }else{ tI+=1; } iList[tcmd.id]=tI; } } __proto.render=function(context,x,y){ if(!this._ready)return; if(this.activeParticles.length<1)return; if (this.textureList.length < 2)return; if (this.settings.disableColor){ this.noColorRender(context,x,y); }else{ this.canvasRender(context,x,y); } } __proto.noColorRender=function(context,x,y){ var particleList=this.activeParticles; var i=0,len=particleList.length; var tcmd; var tParam; var tAlpha=NaN; var px=this.pX,py=this.pY; var pw=-px*2,ph=-py*2; var tI=0; var textureList=this.textureList; var iList=this.iList; var preAlpha=NaN; context.translate(x,y); preAlpha=context.ctx.globalAlpha; for(i=0;i0.01){ context.setAlpha(preAlpha*tParam[3]); context.drawTexture(textureList[0],px,py,pw,ph); } if(tParam[4]>0.01){ context.setAlpha(preAlpha*tParam[4]); context.drawTexture(textureList[1],px,py,pw,ph); } if(tParam[5]>0.01){ context.setAlpha(preAlpha*tParam[5]); context.drawTexture(textureList[2],px,py,pw,ph); } context.restore(); } context.setAlpha(preAlpha); context.translate(-x,-y); context.blendMode(preB); } ParticleTemplateCanvas.changeTexture=function(texture,rst,settings){ if(!rst)rst=[]; rst.length=0; if (settings&&settings.disableColor){ rst.push(texture,texture,texture); }else{ Utils.copyArray(rst,PicTool.getRGBPic(texture)); } return rst; } return ParticleTemplateCanvas; })(ParticleTemplateBase) /** *@private */ //class laya.particle.ParticleTemplate2D extends laya.particle.ParticleTemplateWebGL var ParticleTemplate2D=(function(_super){ function ParticleTemplate2D(parSetting){ this._vertexBuffer2D=null; this._indexBuffer2D=null; this.x=0; this.y=0; this._blendFn=null; this._startTime=0; this.sv=new ParticleShaderValue(); ParticleTemplate2D.__super.call(this,parSetting); var _this=this; Laya.loader.load(this.settings.textureName,Handler.create(null,function(texture){ (texture.bitmap).enableMerageInAtlas=false; _this.texture=texture; })); this.sv.u_Duration=this.settings.duration; this.sv.u_Gravity=this.settings.gravity; this.sv.u_EndVelocity=this.settings.endVelocity; this._blendFn=BlendMode.fns[parSetting.blendState]; this.initialize(); this._vertexBuffer=this._vertexBuffer2D=VertexBuffer2D.create(-1,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._indexBuffer=this._indexBuffer2D=IndexBuffer2D.create(/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); this.loadContent(); } __class(ParticleTemplate2D,'laya.particle.ParticleTemplate2D',_super); var __proto=ParticleTemplate2D.prototype; Laya.imps(__proto,{"laya.webgl.submit.ISubmit":true}) __proto.getRenderType=function(){return-111} __proto.releaseRender=function(){} __proto.addParticleArray=function(position,velocity){ position[0]+=this.x; position[1]+=this.y; _super.prototype.addParticleArray.call(this,position,velocity); } __proto.loadContent=function(){ var indexes=new Uint16Array(this.settings.maxPartices *6); for (var i=0;i < this.settings.maxPartices;i++){ indexes[i *6+0]=(i *4+0); indexes[i *6+1]=(i *4+1); indexes[i *6+2]=(i *4+2); indexes[i *6+3]=(i *4+0); indexes[i *6+4]=(i *4+2); indexes[i *6+5]=(i *4+3); } this._indexBuffer2D.clear(); this._indexBuffer2D.append(indexes); this._indexBuffer2D.upload(); } __proto.addNewParticlesToVertexBuffer=function(){ this._vertexBuffer2D.clear(); this._vertexBuffer2D.append(this._vertices); var start=0; if (this._firstNewElement < this._firstFreeElement){ start=this._firstNewElement *4 *this._floatCountPerVertex *4; this._vertexBuffer2D.subUpload(start,start,start+(this._firstFreeElement-this._firstNewElement)*4 *this._floatCountPerVertex *4); }else { start=this._firstNewElement *4 *this._floatCountPerVertex *4; this._vertexBuffer2D.subUpload(start,start,start+(this.settings.maxPartices-this._firstNewElement)*4 *this._floatCountPerVertex *4); if (this._firstFreeElement > 0){ this._vertexBuffer2D.setNeedUpload(); this._vertexBuffer2D.subUpload(0,0,this._firstFreeElement *4 *this._floatCountPerVertex *4); } } this._firstNewElement=this._firstFreeElement; } __proto.renderSubmit=function(){ if (this.texture&&this.texture.loaded){ this.update(Laya.timer.delta); this.sv.u_CurrentTime=this._currentTime; if (this._firstNewElement !=this._firstFreeElement){ this.addNewParticlesToVertexBuffer(); } this.blend(); if (this._firstActiveElement !=this._firstFreeElement){ var gl=WebGL.mainContext; this._vertexBuffer2D.bind(this._indexBuffer2D); this.sv.u_texture=this.texture.source; this.sv.upload(); if (this._firstActiveElement < this._firstFreeElement){ WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,(this._firstFreeElement-this._firstActiveElement)*6,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this._firstActiveElement *6 *2); } else{ WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,(this.settings.maxPartices-this._firstActiveElement)*6,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this._firstActiveElement *6 *2); if (this._firstFreeElement > 0) WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._firstFreeElement *6,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); } Stat.drawCall++; } this._drawCounter++; } return 1; } __proto.blend=function(){ if (BlendMode.activeBlendFunction!==this._blendFn){ var gl=WebGL.mainContext; gl.enable(/*laya.webgl.WebGLContext.BLEND*/0x0BE2); this._blendFn(gl); BlendMode.activeBlendFunction=this._blendFn; } } __proto.dispose=function(){ this._vertexBuffer2D.dispose(); this._indexBuffer2D.dispose(); } ParticleTemplate2D.activeBlendType=-1; return ParticleTemplate2D; })(ParticleTemplateWebGL) /** *@private */ //class laya.particle.shader.value.ParticleShaderValue extends laya.webgl.shader.d2.value.Value2D var ParticleShaderValue=(function(_super){ function ParticleShaderValue(){ this.a_CornerTextureCoordinate=[4,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,116,0]; this.a_Position=[3,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,116,16]; this.a_Velocity=[3,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,116,28]; this.a_StartColor=[4,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,116,40]; this.a_EndColor=[4,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,116,56]; this.a_SizeRotation=[3,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,116,72]; this.a_Radius=[2,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,116,84]; this.a_Radian=[4,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,116,92]; this.a_AgeAddScale=[1,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,116,108]; this.a_Time=[1,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,116,112]; this.u_CurrentTime=NaN; this.u_Duration=NaN; this.u_Gravity=null; //v3 this.u_EndVelocity=NaN; this.u_texture=null; ParticleShaderValue.__super.call(this,0,0); } __class(ParticleShaderValue,'laya.particle.shader.value.ParticleShaderValue',_super); var __proto=ParticleShaderValue.prototype; __proto.upload=function(){ this.refresh(); ParticleShaderValue.pShader.upload(this); } __static(ParticleShaderValue, ['pShader',function(){return this.pShader=new ParticleShader();} ]); return ParticleShaderValue; })(Value2D) /** *Particle2D 类是2D粒子播放类 * */ //class laya.particle.Particle2D extends laya.display.Sprite var Particle2D=(function(_super){ function Particle2D(setting){ /**@private */ this._matrix4=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]; /**@private */ this._particleTemplate=null; /**@private */ this._canvasTemplate=null; /**@private */ this._emitter=null; /**是否自动播放*/ this.autoPlay=true; Particle2D.__super.call(this); if (setting)this.setParticleSetting(setting); } __class(Particle2D,'laya.particle.Particle2D',_super); var __proto=Particle2D.prototype; /** *加载粒子文件 *@param url 粒子文件地址 */ __proto.load=function(url){ Laya.loader.load(url,Handler.create(this,this.setParticleSetting),null,/*laya.net.Loader.JSON*/"json"); } /** *设置粒子配置数据 *@param settings 粒子配置数据 */ __proto.setParticleSetting=function(setting){ var _$this=this; if (!setting)return this.stop(); ParticleSetting.checkSetting(setting); if(/*__JS__ */!window.ConchParticleTemplate2D||Render.isWebGL)this.customRenderEnable=true; if (Render.isWebGL){ this._particleTemplate=new ParticleTemplate2D(setting); this.graphics._saveToCmd(Render.context._drawParticle,[this._particleTemplate]); } else if (Render.isConchApp&&/*__JS__ */window.ConchParticleTemplate2D){ this._particleTemplate=/*__JS__ */new ConchParticleTemplate2D(); var _this=this; Laya.loader.load(setting.textureName,Handler.create(null,function(texture){ /*__JS__ */_this._particleTemplate.texture=texture; _this._particleTemplate.settings=setting; if (Render.isConchNode){ /*__JS__ */_this.graphics.drawParticle(_this._particleTemplate); } else{ _this.graphics._saveToCmd(Render.context._drawParticle,[_$this._particleTemplate]); } })); this._emitter={start:function (){}}; /*__JS__ */this.play=this._particleTemplate.play.bind(this._particleTemplate); /*__JS__ */this.stop=this._particleTemplate.stop.bind(this._particleTemplate); if (this.autoPlay)this.play(); return; } else { this._particleTemplate=this._canvasTemplate=new ParticleTemplateCanvas(setting); } if (!this._emitter){ this._emitter=new Emitter2D(this._particleTemplate); }else { (this._emitter).template=this._particleTemplate; } if (this.autoPlay){ this.emitter.start(); this.play(); } } /** *播放 */ __proto.play=function(){ this.timer.frameLoop(1,this,this._loop); } /** *停止 */ __proto.stop=function(){ this.timer.clear(this,this._loop); } /**@private */ __proto._loop=function(){ this.advanceTime(1 / 60); } /** *时钟前进 *@param passedTime 时钟前进时间 */ __proto.advanceTime=function(passedTime){ (passedTime===void 0)&& (passedTime=1); if (this._canvasTemplate){ this._canvasTemplate.advanceTime(passedTime); } if (this._emitter){ this._emitter.advanceTime(passedTime); } } __proto.customRender=function(context,x,y){ if (Render.isWebGL){ this._matrix4[0]=context.ctx._curMat.a; this._matrix4[1]=context.ctx._curMat.b; this._matrix4[4]=context.ctx._curMat.c; this._matrix4[5]=context.ctx._curMat.d; this._matrix4[12]=context.ctx._curMat.tx; this._matrix4[13]=context.ctx._curMat.ty; var sv=(this._particleTemplate).sv; sv.u_mmat=this._matrix4; } if (this._canvasTemplate){ this._canvasTemplate.render(context,x,y); } } __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if ((this._particleTemplate instanceof laya.particle.ParticleTemplate2D )) (this._particleTemplate).dispose(); _super.prototype.destroy.call(this,destroyChild); } /** *设置 粒子文件地址 *@param path 粒子文件地址 */ __getset(0,__proto,'url',null,function(url){ this.load(url); }); /** *获取粒子发射器 */ __getset(0,__proto,'emitter',function(){ return this._emitter; }); return Particle2D; })(Sprite) /** *@private */ //class laya.particle.shader.ParticleShader extends laya.webgl.shader.Shader var ParticleShader=(function(_super){ function ParticleShader(){ ParticleShader.__super.call(this,ParticleShader.vs,ParticleShader.ps,"ParticleShader"); } __class(ParticleShader,'laya.particle.shader.ParticleShader',_super); __static(ParticleShader, ['vs',function(){return this.vs="attribute vec4 a_CornerTextureCoordinate;\nattribute vec3 a_Position;\nattribute vec3 a_Velocity;\nattribute vec4 a_StartColor;\nattribute vec4 a_EndColor;\nattribute vec3 a_SizeRotation;\nattribute vec2 a_Radius;\nattribute vec4 a_Radian;\nattribute float a_AgeAddScale;\nattribute float a_Time;\n\nvarying vec4 v_Color;\nvarying vec2 v_TextureCoordinate;\n\nuniform float u_CurrentTime;\nuniform float u_Duration;\nuniform float u_EndVelocity;\nuniform vec3 u_Gravity;\n\n#ifdef PARTICLE3D\n uniform mat4 u_WorldMat;\n uniform mat4 u_View;\n uniform mat4 u_Projection;\n uniform vec2 u_ViewportScale;\n#else\n uniform vec2 size;\n uniform mat4 mmat;\n uniform mat4 u_mmat;\n#endif\n\nvec4 ComputeParticlePosition(in vec3 position, in vec3 velocity,in float age,in float normalizedAge)\n{\n\n float startVelocity = length(velocity);//起始标量速度\n float endVelocity = startVelocity * u_EndVelocity;//结束标量速度\n\n float velocityIntegral = startVelocity * normalizedAge +(endVelocity - startVelocity) * normalizedAge *normalizedAge/2.0;//计算当前速度的标量(单位空间),vt=v0*t+(1/2)*a*(t^2)\n \n vec3 addPosition = normalize(velocity) * velocityIntegral * u_Duration;//计算受自身速度影响的位置,转换标量到矢量 \n addPosition += u_Gravity * age * normalizedAge;//计算受重力影响的位置\n \n float radius=mix(a_Radius.x, a_Radius.y, normalizedAge); //计算粒子受半径和角度影响(无需计算角度和半径时,可用宏定义优化屏蔽此计算)\n float radianHorizontal =mix(a_Radian.x,a_Radian.z,normalizedAge);\n float radianVertical =mix(a_Radian.y,a_Radian.w,normalizedAge);\n \n float r =cos(radianVertical)* radius;\n addPosition.y += sin(radianVertical) * radius;\n \n addPosition.x += cos(radianHorizontal) *r;\n addPosition.z += sin(radianHorizontal) *r;\n \n #ifdef PARTICLE3D\n position+=addPosition;\n return u_Projection*u_View*u_WorldMat*(vec4(position, 1.0));\n #else\n addPosition.y=-addPosition.y;//2D粒子位置更新需要取负,2D粒子坐标系Y轴正向朝上\n position+=addPosition;\n return vec4(position,1.0);\n #endif\n}\n\nfloat ComputeParticleSize(in float startSize,in float endSize, in float normalizedAge)\n{ \n float size = mix(startSize, endSize, normalizedAge);\n \n #ifdef PARTICLE3D\n //Project the size into screen coordinates.\n return size * u_Projection[1][1];\n #else\n return size;\n #endif\n}\n\nmat2 ComputeParticleRotation(in float rot,in float age)\n{ \n float rotation =rot * age;\n //计算2x2旋转矩阵.\n float c = cos(rotation);\n float s = sin(rotation);\n return mat2(c, -s, s, c);\n}\n\nvec4 ComputeParticleColor(in vec4 startColor,in vec4 endColor,in float normalizedAge)\n{\n vec4 color=mix(startColor,endColor,normalizedAge);\n //硬编码设置,使粒子淡入很快,淡出很慢,6.7的缩放因子把置归一在0到1之间,可以谷歌x*(1-x)*(1-x)*6.7的制图表\n color.a *= normalizedAge * (1.0-normalizedAge) * (1.0-normalizedAge) * 6.7;\n \n return color;\n}\n\nvoid main()\n{\n float age = u_CurrentTime - a_Time;\n age *= 1.0 + a_AgeAddScale;\n float normalizedAge = clamp(age / u_Duration,0.0,1.0);\n gl_Position = ComputeParticlePosition(a_Position, a_Velocity, age, normalizedAge);//计算粒子位置\n float pSize = ComputeParticleSize(a_SizeRotation.x,a_SizeRotation.y, normalizedAge);\n mat2 rotation = ComputeParticleRotation(a_SizeRotation.z, age);\n \n #ifdef PARTICLE3D\n gl_Position.xy += (rotation*a_CornerTextureCoordinate.xy) * pSize * u_ViewportScale;\n #else\n mat4 mat=u_mmat*mmat;\n gl_Position=vec4((mat*gl_Position).xy,0.0,1.0);\n gl_Position.xy += (rotation*a_CornerTextureCoordinate.xy) * pSize*vec2(mat[0][0],mat[1][1]);\n gl_Position=vec4((gl_Position.x/size.x-0.5)*2.0,(0.5-gl_Position.y/size.y)*2.0,0.0,1.0);\n #endif\n \n v_Color = ComputeParticleColor(a_StartColor,a_EndColor, normalizedAge);\n v_TextureCoordinate =a_CornerTextureCoordinate.zw;\n}\n\n";},'ps',function(){return this.ps="#ifdef FSHIGHPRECISION\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nvarying vec4 v_Color;\nvarying vec2 v_TextureCoordinate;\nuniform sampler2D u_texture;\n\nvoid main()\n{ \n gl_FragColor=texture2D(u_texture,v_TextureCoordinate)*v_Color;\n gl_FragColor.xyz *= v_Color.w;\n}";} ]); return ParticleShader; })(Shader) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.pathfinding.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; /** *... *@author dongketao */ //class PathFinding.core.DiagonalMovement var DiagonalMovement=(function(){ function DiagonalMovement(){} __class(DiagonalMovement,'PathFinding.core.DiagonalMovement'); DiagonalMovement.Always=1; DiagonalMovement.Never=2; DiagonalMovement.IfAtMostOneObstacle=3; DiagonalMovement.OnlyWhenNoObstacles=4; return DiagonalMovement; })() /** *... *@author dongketao */ //class PathFinding.core.Grid var Grid=(function(){ function Grid(width_or_matrix,height,matrix){ this.width=0; this.height=0; this.nodes=null; var width=0; if ((typeof width_or_matrix=='number')){ width=width_or_matrix; } else{ height=width_or_matrix.length; width=width_or_matrix[0].length; matrix=width_or_matrix; } this.width=width; this.height=height; this.nodes=this._buildNodes(width,height,matrix); } __class(Grid,'PathFinding.core.Grid'); var __proto=Grid.prototype; /** *Build and return the nodes. *@private *@param {number}width *@param {number}height *@param {Array>}[matrix]-A 0-1 matrix representing *the walkable status of the nodes. *@see Grid */ __proto._buildNodes=function(width,height,matrix){ var i=0,j=0,nodes=[]; for (i=0;i < height;++i){ nodes[i]=[]; for (j=0;j < width;++j){ nodes[i][j]=new Node$1(j,i); } } if (matrix==null){ return nodes; } if (matrix.length !=height || matrix[0].length !=width){ throw new Error('Matrix size does not fit'); } for (i=0;i < height;++i){ for (j=0;j < width;++j){ if (matrix[i][j]){ nodes[i][j].walkable=false; } } } return nodes; } __proto.getNodeAt=function(x,y){ return this.nodes[y][x]; } /** *Determine whether the node at the given position is walkable. *(Also returns false if the position is outside the grid.) *@param {number}x-The x coordinate of the node. *@param {number}y-The y coordinate of the node. *@return {boolean}-The walkability of the node. */ __proto.isWalkableAt=function(x,y){ return this.isInside(x,y)&& this.nodes[y][x].walkable; } /** *Determine whether the position is inside the grid. *XXX:`grid.isInside(x,y)` is wierd to read. *It should be `(x,y)is inside grid`,but I failed to find a better *name for this method. *@param {number}x *@param {number}y *@return {boolean} */ __proto.isInside=function(x,y){ return (x >=0 && x < this.width)&& (y >=0 && y < this.height); } /** *Set whether the node on the given position is walkable. *NOTE:throws exception if the coordinate is not inside the grid. *@param {number}x-The x coordinate of the node. *@param {number}y-The y coordinate of the node. *@param {boolean}walkable-Whether the position is walkable. */ __proto.setWalkableAt=function(x,y,walkable){ this.nodes[y][x].walkable=walkable; } /** *Get the neighbors of the given node. * *offsets diagonalOffsets: *+---+---+---++---+---+---+ *| | 0 | | | 0 | | 1 | *+---+---+---++---+---+---+ *| 3 | | 1 | | | | | *+---+---+---++---+---+---+ *| | 2 | | | 3 | | 2 | *+---+---+---++---+---+---+ * *When allowDiagonal is true,if offsets[i] is valid,then *diagonalOffsets[i] and *diagonalOffsets[(i+1)% 4] is valid. *@param {Node}node *@param {diagonalMovement}diagonalMovement */ __proto.getNeighbors=function(node,diagonalMovement){ var x=node.x,y=node.y,neighbors=[],s0=false,d0=false,s1=false,d1=false,s2=false,d2=false,s3=false,d3=false,nodes=this.nodes; if (this.isWalkableAt(x,y-1)){ neighbors.push(nodes[y-1][x]); s0=true; } if (this.isWalkableAt(x+1,y)){ neighbors.push(nodes[y][x+1]); s1=true; } if (this.isWalkableAt(x,y+1)){ neighbors.push(nodes[y+1][x]); s2=true; } if (this.isWalkableAt(x-1,y)){ neighbors.push(nodes[y][x-1]); s3=true; } if (diagonalMovement==DiagonalMovement.Never){ return neighbors; } if (diagonalMovement==DiagonalMovement.OnlyWhenNoObstacles){ d0=s3 && s0; d1=s0 && s1; d2=s1 && s2; d3=s2 && s3; } else if (diagonalMovement==DiagonalMovement.IfAtMostOneObstacle){ d0=s3 || s0; d1=s0 || s1; d2=s1 || s2; d3=s2 || s3; } else if (diagonalMovement==DiagonalMovement.Always){ d0=true; d1=true; d2=true; d3=true; } else{ throw new Error('Incorrect value of diagonalMovement'); } if (d0 && this.isWalkableAt(x-1,y-1)){ neighbors.push(nodes[y-1][x-1]); } if (d1 && this.isWalkableAt(x+1,y-1)){ neighbors.push(nodes[y-1][x+1]); } if (d2 && this.isWalkableAt(x+1,y+1)){ neighbors.push(nodes[y+1][x+1]); } if (d3 && this.isWalkableAt(x-1,y+1)){ neighbors.push(nodes[y+1][x-1]); } return neighbors; } /** *Get a clone of this grid. *@return {Grid}Cloned grid. */ __proto.clone=function(){ var i=0,j=0, width=this.width,height=this.height,thisNodes=this.nodes, newGrid=new Grid(width,height),newNodes=[]; for (i=0;i < height;++i){ newNodes[i]=[]; for (j=0;j < width;++j){ newNodes[i][j]=new Node$1(j,i,thisNodes[i][j].walkable); } } newGrid.nodes=newNodes; return newGrid; } __proto.reset=function(){ var _node; for (var i=0;i < this.height;++i){ for (var j=0;j < this.width;++j){ _node=this.nodes[i][j]; _node.g=0; _node.f=0; _node.h=0; _node.by=0; _node.parent=null; _node.opened=null; _node.closed=null; _node.tested=null; } } } Grid.createGridFromAStarMap=function(texture){ var textureWidth=texture.width; var textureHeight=texture.height; var pixelsInfo=texture.getPixels(); var aStarArr=[]; var index=0; for (var w=0;w < textureWidth;w++){ var colaStarArr=aStarArr[w]=[]; for (var h=0;h < textureHeight;h++){ var r=pixelsInfo[index++]; var g=pixelsInfo[index++]; var b=pixelsInfo[index++]; var a=pixelsInfo[index++]; if (r==255 && g==255 && b==255 && a==255) colaStarArr[h]=1; else { colaStarArr[h]=0; } } }; var gird=new Grid(textureWidth,textureHeight,aStarArr); return gird; } return Grid; })() /** *... *@author dongketao */ //class PathFinding.core.Heuristic var Heuristic=(function(){ function Heuristic(){} __class(Heuristic,'PathFinding.core.Heuristic'); Heuristic.manhattan=function(dx,dy){ return dx+dy; } Heuristic.euclidean=function(dx,dy){ return Math.sqrt(dx *dx+dy *dy); } Heuristic.octile=function(dx,dy){ var F=Math.SQRT2-1; return (dx < dy)? F *dx+dy :F *dy+dx; } Heuristic.chebyshev=function(dx,dy){ return Math.max(dx,dy); } return Heuristic; })() /** *... *@author dongketao */ //class PathFinding.core.Node var Node$1=(function(){ function Node(x,y,walkable){ this.x=0; this.y=0; this.g=0; this.f=0; this.h=0; this.by=0; this.parent=null; this.opened=null; this.closed=null; this.tested=null; this.retainCount=null; this.walkable=false; (walkable===void 0)&& (walkable=true); this.x=x; this.y=y; this.walkable=walkable; } __class(Node,'PathFinding.core.Node',null,'Node$1'); return Node; })() /** *... *@author dongketao */ //class PathFinding.core.Util var Util=(function(){ function Util(){} __class(Util,'PathFinding.core.Util'); Util.backtrace=function(node){ var path=[[node.x,node.y]]; while (node.parent){ node=node.parent; path.push([node.x,node.y]); } return path.reverse(); } Util.biBacktrace=function(nodeA,nodeB){ var pathA=Util.backtrace(nodeA),pathB=Util.backtrace(nodeB); return pathA.concat(pathB.reverse()); } Util.pathLength=function(path){ var i=0,sum=0,a=0,b=0,dx=0,dy=0; for (i=1;i < path.length;++i){ a=path[i-1]; b=path[i]; dx=a[0]-b[0]; dy=a[1]-b[1]; sum+=Math.sqrt(dx *dx+dy *dy); } return sum; } Util.interpolate=function(x0,y0,x1,y1){ var abs=Math.abs,line=[],sx=0,sy=0,dx=0,dy=0,err=0,e2=0; dx=abs(x1-x0); dy=abs(y1-y0); sx=(x0 < x1)? 1 :-1; sy=(y0 < y1)? 1 :-1; err=dx-dy; while (true){ line.push([x0,y0]); if (x0==x1 && y0==y1){ break ; } e2=2 *err; if (e2 >-dy){ err=err-dy; x0=x0+sx; } if (e2 < dx){ err=err+dx; y0=y0+sy; } } return line; } Util.expandPath=function(path){ var expanded=[],len=path.length,coord0,coord1,interpolated,interpolatedLen=0,i=0,j=0; if (len < 2){ return expanded; } for (i=0;i < len-1;++i){ coord0=path[i]; coord1=path[i+1]; interpolated=Util.interpolate(coord0[0],coord0[1],coord1[0],coord1[1]); interpolatedLen=interpolated.length; for (j=0;j < interpolatedLen-1;++j){ expanded.push(interpolated[j]); } } expanded.push(path[len-1]); return expanded; } Util.smoothenPath=function(grid,path){ var len=path.length,x0=path[0][0], y0=path[0][1], x1=path[len-1][0], y1=path[len-1][1], sx=0,sy=0, ex=0,ey=0, newPath,i=0,j=0,coord,line,testCoord,blocked=false,lastValidCoord; sx=x0; sy=y0; newPath=[[sx,sy]]; for (i=2;i < len;++i){ coord=path[i]; ex=coord[0]; ey=coord[1]; line=Util.interpolate(sx,sy,ex,ey); blocked=false; for (j=1;j < line.length;++j){ testCoord=line[j]; if (!grid.isWalkableAt(testCoord[0],testCoord[1])){ blocked=true; break ; } } if (blocked){ lastValidCoord=path[i-1]; newPath.push(lastValidCoord); sx=lastValidCoord[0]; sy=lastValidCoord[1]; } } newPath.push([x1,y1]); return newPath; } Util.compressPath=function(path){ if (path.length < 3){ return path; }; var compressed=[],sx=path[0][0], sy=path[0][1], px=path[1][0], py=path[1][1], dx=px-sx, dy=py-sy, lx=0,ly=0,ldx=0,ldy=0,sq=NaN,i=0; sq=Math.sqrt(dx *dx+dy *dy); dx /=sq; dy /=sq; compressed.push([sx,sy]); for (i=2;i < path.length;i++){ lx=px; ly=py; ldx=dx; ldy=dy; px=path[i][0]; py=path[i][1]; dx=px-lx; dy=py-ly; sq=Math.sqrt(dx *dx+dy *dy); dx /=sq; dy /=sq; if (dx!==ldx || dy!==ldy){ compressed.push([lx,ly]); } } compressed.push([px,py]); return compressed; } return Util; })() /** *... *@author dongketao */ //class PathFinding.finders.AStarFinder var AStarFinder=(function(){ function AStarFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.heuristic=null; this.weight=0; this.diagonalMovement=0; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.heuristic=opt.heuristic || Heuristic.manhattan; this.weight=opt.weight || 1; this.diagonalMovement=opt.diagonalMovement; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } if (this.diagonalMovement===DiagonalMovement.Never){ this.heuristic=opt.heuristic || Heuristic.manhattan; } else{ this.heuristic=opt.heuristic || Heuristic.octile; } } __class(AStarFinder,'PathFinding.finders.AStarFinder'); var __proto=AStarFinder.prototype; /** *Find and return the the path. *@return {Array>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var openList=new Heap(function(nodeA,nodeB){ return nodeA.f-nodeB.f; }),startNode=grid.getNodeAt(startX,startY),endNode=grid.getNodeAt(endX,endY),heuristic=this.heuristic,diagonalMovement=this.diagonalMovement,weight=this.weight,abs=Math.abs,SQRT2=Math.SQRT2,node,neighbors,neighbor,i=0,l=0,x=0,y=0,ng=0; startNode.g=0; startNode.f=0; openList.push(startNode); startNode.opened=true; while (!openList.empty()){ node=openList.pop(); node.closed=true; if (node===endNode){ return Util.backtrace(endNode); } neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } x=neighbor.x; y=neighbor.y; ng=node.g+((x-node.x===0 || y-node.y===0)? 1 :SQRT2); if (!neighbor.opened || ng < neighbor.g){ neighbor.g=ng; neighbor.h=neighbor.h || weight *heuristic(abs(x-endX),abs(y-endY)); neighbor.f=neighbor.g+neighbor.h; neighbor.parent=node; if (!neighbor.opened){ openList.push(neighbor); neighbor.opened=true; } else{ openList.updateItem(neighbor); } } } } return []; } return AStarFinder; })() /** *... *@author ... */ //class PathFinding.finders.BiAStarFinder var BiAStarFinder=(function(){ function BiAStarFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.diagonalMovement=0; this.heuristic=null; this.weight=0; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.diagonalMovement=opt.diagonalMovement; this.heuristic=opt.heuristic || Heuristic.manhattan; this.weight=opt.weight || 1; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } if (this.diagonalMovement==DiagonalMovement.Never){ this.heuristic=opt.heuristic || Heuristic.manhattan; } else{ this.heuristic=opt.heuristic || Heuristic.octile; } } __class(BiAStarFinder,'PathFinding.finders.BiAStarFinder'); var __proto=BiAStarFinder.prototype; /** *Find and return the the path. *@return {Array>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var cmp=function (nodeA,nodeB){ return nodeA.f-nodeB.f; }; var startOpenList=new Heap(cmp),endOpenList=new Heap(cmp),startNode=grid.getNodeAt(startX,startY),endNode=grid.getNodeAt(endX,endY),heuristic=this.heuristic,diagonalMovement=this.diagonalMovement,weight=this.weight,abs=Math.abs,SQRT2=Math.SQRT2,node,neighbors,neighbor,i=0,l=0,x=0,y=0,ng=0,BY_START=1,BY_END=2; startNode.g=0; startNode.f=0; startOpenList.push(startNode); startNode.opened=BY_START; endNode.g=0; endNode.f=0; endOpenList.push(endNode); endNode.opened=BY_END; while (!startOpenList.empty()&& !endOpenList.empty()){ node=startOpenList.pop(); node.closed=true; neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } if (neighbor.opened===BY_END){ return Util.biBacktrace(node,neighbor); } x=neighbor.x; y=neighbor.y; ng=node.g+((x-node.x===0 || y-node.y===0)? 1 :SQRT2); if (!neighbor.opened || ng < neighbor.g){ neighbor.g=ng; neighbor.h=neighbor.h || weight *heuristic(abs(x-endX),abs(y-endY)); neighbor.f=neighbor.g+neighbor.h; neighbor.parent=node; if (!neighbor.opened){ startOpenList.push(neighbor); neighbor.opened=BY_START; } else{ startOpenList.updateItem(neighbor); } } } node=endOpenList.pop(); node.closed=true; neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } if (neighbor.opened===BY_START){ return Util.biBacktrace(neighbor,node); } x=neighbor.x; y=neighbor.y; ng=node.g+((x-node.x===0 || y-node.y===0)? 1 :SQRT2); if (!neighbor.opened || ng < neighbor.g){ neighbor.g=ng; neighbor.h=neighbor.h || weight *heuristic(abs(x-startX),abs(y-startY)); neighbor.f=neighbor.g+neighbor.h; neighbor.parent=node; if (!neighbor.opened){ endOpenList.push(neighbor); neighbor.opened=BY_END; } else{ endOpenList.updateItem(neighbor); } } } } return []; } return BiAStarFinder; })() /** *... *@author dongketao */ //class PathFinding.finders.BiBreadthFirstFinder var BiBreadthFirstFinder=(function(){ function BiBreadthFirstFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.heuristic=null; this.weight=0; this.diagonalMovement=0; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.diagonalMovement=opt.diagonalMovement; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } } __class(BiBreadthFirstFinder,'PathFinding.finders.BiBreadthFirstFinder'); var __proto=BiBreadthFirstFinder.prototype; /** *Find and return the the path. *@return {Array>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var startNode=grid.getNodeAt(startX,startY),endNode=grid.getNodeAt(endX,endY),startOpenList=[],endOpenList=[],neighbors,neighbor,node,diagonalMovement=this.diagonalMovement,BY_START=0,BY_END=1,i=0,l=0; startOpenList.push(startNode); startNode.opened=true; startNode.by=BY_START; endOpenList.push(endNode); endNode.opened=true; endNode.by=BY_END; while (startOpenList.length && endOpenList.length){ node=startOpenList.shift(); node.closed=true; neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } if (neighbor.opened){ if (neighbor.by===BY_END){ return Util.biBacktrace(node,neighbor); } continue ; } startOpenList.push(neighbor); neighbor.parent=node; neighbor.opened=true; neighbor.by=BY_START; } node=endOpenList.shift(); node.closed=true; neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } if (neighbor.opened){ if (neighbor.by===BY_START){ return Util.biBacktrace(neighbor,node); } continue ; } endOpenList.push(neighbor); neighbor.parent=node; neighbor.opened=true; neighbor.by=BY_END; } } return []; } return BiBreadthFirstFinder; })() /** *... *@author dongketao */ //class PathFinding.finders.BreadthFirstFinder var BreadthFirstFinder=(function(){ function BreadthFirstFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.heuristic=null; this.weight=0; this.diagonalMovement=0; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.diagonalMovement=opt.diagonalMovement; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } } __class(BreadthFirstFinder,'PathFinding.finders.BreadthFirstFinder'); var __proto=BreadthFirstFinder.prototype; /** *Find and return the the path. *@return {Array>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var openList=[],diagonalMovement=this.diagonalMovement,startNode=grid.getNodeAt(startX,startY),endNode=grid.getNodeAt(endX,endY),neighbors,neighbor,node,i=0,l=0; openList.push(startNode); startNode.opened=true; while (openList.length){ node=openList.shift(); node.closed=true; if (node===endNode){ return Util.backtrace(endNode); } neighbors=grid.getNeighbors(node,diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed || neighbor.opened){ continue ; } openList.push(neighbor); neighbor.opened=true; neighbor.parent=node; } } return []; } return BreadthFirstFinder; })() /** *... *@author dongketao */ //class PathFinding.finders.IDAStarFinder var IDAStarFinder=(function(){ function IDAStarFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.heuristic=null; this.weight=0; this.diagonalMovement=0; this.trackRecursion=false; this.timeLimit=NaN; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.diagonalMovement=opt.diagonalMovement; this.heuristic=opt.heuristic || Heuristic.manhattan; this.weight=opt.weight || 1; this.trackRecursion=opt.trackRecursion || false; this.timeLimit=opt.timeLimit || Infinity; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } if (this.diagonalMovement===DiagonalMovement.Never){ this.heuristic=opt.heuristic || Heuristic.manhattan; } else{ this.heuristic=opt.heuristic || Heuristic.octile; } } __class(IDAStarFinder,'PathFinding.finders.IDAStarFinder'); var __proto=IDAStarFinder.prototype; /** *Find and return the the path. When an empty array is returned,either *no path is possible,or the maximum execution time is reached. * *@return {Array>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var _$this=this; var nodesVisited=0; var startTime=new Date().getTime(); var h=function (a,b){ return _$this.heuristic(Math.abs(b.x-a.x),Math.abs(b.y-a.y)); }; var cost=function (a,b){ return (a.x===b.x || a.y===b.y)? 1 :Math.SQRT2; }; var search=function (node,g,cutoff,route,depth){ nodesVisited++; if (_$this.timeLimit > 0 && new Date().getTime()-startTime > _$this.timeLimit *1000){ return Infinity; }; var f=g+h(node,end)*_$this.weight; if (f > cutoff){ return f; } if (node==end){ route[depth]=[node.x,node.y]; return node; }; var min=0,t=0,k=0,neighbour; var neighbours=grid.getNeighbors(node,_$this.diagonalMovement); for (k=0,min=Infinity;neighbour=neighbours[k];++k){ if (_$this.trackRecursion){ neighbour.retainCount=neighbour.retainCount+1 || 1; if (neighbour.tested !=true){ neighbour.tested=true; } } t=search(neighbour,g+cost(node,neighbour),cutoff,route,depth+1); if ((t instanceof PathFinding.core.Node )){ route[depth]=[node.x,node.y]; return t; } if (_$this.trackRecursion && (--neighbour.retainCount)===0){ neighbour.tested=false; } if (t < min){ min=t; } } return min; }; var start=grid.getNodeAt(startX,startY); var end=grid.getNodeAt(endX,endY); var cutOff=h(start,end); var j=0,route,t=0; for (j=0;true;++j){ route=[]; t=search(start,0,cutOff,route,0); if (t==Infinity){ route=[]; break ; } if ((t instanceof PathFinding.core.Node )){ break ; } cutOff=t; } return route; } return IDAStarFinder; })() /** *... *@author ... */ //class PathFinding.finders.JumpPointFinderBase var JumpPointFinderBase=(function(){ function JumpPointFinderBase(opt){ this.grid=null; this.openList=null; this.startNode=null; this.endNode=null; this.heuristic=null; this.trackJumpRecursion=false; opt=opt || {}; this.heuristic=opt.heuristic || Heuristic.manhattan; this.trackJumpRecursion=opt.trackJumpRecursion || false; } __class(JumpPointFinderBase,'PathFinding.finders.JumpPointFinderBase'); var __proto=JumpPointFinderBase.prototype; /** *Find and return the path. *@return {Array>}The path,including both start and *end positions. */ __proto.findPath=function(startX,startY,endX,endY,grid){ var openList=this.openList=new Heap(function(nodeA,nodeB){ return nodeA.f-nodeB.f; }),startNode=this.startNode=grid.getNodeAt(startX,startY),endNode=this.endNode=grid.getNodeAt(endX,endY),node; this.grid=grid; startNode.g=0; startNode.f=0; openList.push(startNode); startNode.opened=true; while (!openList.empty()){ node=openList.pop(); node.closed=true; if (node==endNode){ return Util.expandPath(Util.backtrace(endNode)); } this._identifySuccessors(node); } return []; } /** *Identify successors for the given node. Runs a jump point search in the *direction of each available neighbor,adding any points found to the open *list. *@protected */ __proto._identifySuccessors=function(node){ var grid=this.grid,heuristic=this.heuristic,openList=this.openList,endX=this.endNode.x,endY=this.endNode.y,neighbors,neighbor,jumpPoint,i=0,l=0,x=node.x,y=node.y,jx=0,jy=0,dx=0,dy=0,d=0,ng=0,jumpNode,abs=Math.abs,max=Math.max; neighbors=this._findNeighbors(node); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; jumpPoint=this._jump(neighbor[0],neighbor[1],x,y); if (jumpPoint){ jx=jumpPoint[0]; jy=jumpPoint[1]; jumpNode=grid.getNodeAt(jx,jy); if (jumpNode.closed){ continue ; } d=Heuristic.octile(abs(jx-x),abs(jy-y)); ng=node.g+d; if (!jumpNode.opened || ng < jumpNode.g){ jumpNode.g=ng; jumpNode.h=jumpNode.h || heuristic(abs(jx-endX),abs(jy-endY)); jumpNode.f=jumpNode.g+jumpNode.h; jumpNode.parent=node; if (!jumpNode.opened){ openList.push(jumpNode); jumpNode.opened=true; } else{ openList.updateItem(jumpNode); } } } } } __proto._jump=function(x,y,px,py){ return []; } __proto._findNeighbors=function(node){ return []; } return JumpPointFinderBase; })() /** *... *@author ... */ //class PathFinding.finders.JumpPointFinder var JumpPointFinder=(function(){ /** *Path finder using the Jump Point Search algorithm *@param {Object}opt *@param {function}opt.heuristic Heuristic function to estimate the distance *(defaults to manhattan). *@param {DiagonalMovement}opt.diagonalMovement Condition under which diagonal *movement will be allowed. */ function JumpPointFinder(opt){} __class(JumpPointFinder,'PathFinding.finders.JumpPointFinder'); return JumpPointFinder; })() /** *... *@author dongketao */ //class PathFinding.finders.TraceFinder var TraceFinder=(function(){ function TraceFinder(opt){ this.allowDiagonal=false; this.dontCrossCorners=false; this.diagonalMovement=0; this.heuristic=null; opt=opt || {}; this.allowDiagonal=opt.allowDiagonal; this.dontCrossCorners=opt.dontCrossCorners; this.heuristic=opt.heuristic || Heuristic.manhattan; this.diagonalMovement=opt.diagonalMovement; if (!this.diagonalMovement){ if (!this.allowDiagonal){ this.diagonalMovement=DiagonalMovement.Never; } else{ if (this.dontCrossCorners){ this.diagonalMovement=DiagonalMovement.OnlyWhenNoObstacles; } else{ this.diagonalMovement=DiagonalMovement.IfAtMostOneObstacle; } } } if (this.diagonalMovement==DiagonalMovement.Never){ this.heuristic=opt.heuristic || Heuristic.manhattan; } else{ this.heuristic=opt.heuristic || Heuristic.octile; } } __class(TraceFinder,'PathFinding.finders.TraceFinder'); var __proto=TraceFinder.prototype; __proto.findPath=function(startX,startY,endX,endY,grid){ var openList=new Heap(function(nodeA,nodeB){ return nodeA.f-nodeB.f; }),startNode=grid.getNodeAt(startX,startY),endNode=grid.getNodeAt(endX,endY),heuristic=this.heuristic,allowDiagonal=this.allowDiagonal,dontCrossCorners=this.dontCrossCorners,abs=Math.abs,SQRT2=Math.SQRT2,node,neighbors,neighbor,i=0,l=0,x=0,y=0,ng=0; startNode.g=0; startNode.f=0; openList.push(startNode); startNode.opened=true; while (!openList.empty()){ node=openList.pop(); node.closed=true; if (node===endNode){ return Util.backtrace(endNode); } neighbors=grid.getNeighbors(node,this.diagonalMovement); for (i=0,l=neighbors.length;i < l;++i){ neighbor=neighbors[i]; if (neighbor.closed){ continue ; } x=neighbor.x; y=neighbor.y; ng=node.g+((x-node.x===0 || y-node.y===0)? 1 :SQRT2); if (!neighbor.opened || ng < neighbor.g){ neighbor.g=ng *l / 9; neighbor.h=neighbor.h || heuristic(abs(x-endX),abs(y-endY)); neighbor.f=neighbor.g+neighbor.h; neighbor.parent=node; if (!neighbor.opened){ openList.push(neighbor); neighbor.opened=true; } else{ openList.updateItem(neighbor); } } } } return []; } return TraceFinder; })() /** *... *@author dongketao */ //class PathFinding.libs.Heap var Heap=(function(){ function Heap(cmp){ this.cmp=null; this.nodes=null; this.heapFunction=new HeapFunction(); this.cmp=cmp !=null ? cmp :this.heapFunction.defaultCmp; this.nodes=[]; } __class(Heap,'PathFinding.libs.Heap'); var __proto=Heap.prototype; __proto.push=function(x){ return this.heapFunction.heappush(this.nodes,x,this.cmp); } __proto.pop=function(){ return this.heapFunction.heappop(this.nodes,this.cmp); } __proto.peek=function(){ return this.nodes[0]; } __proto.contains=function(x){ return this.nodes.indexOf(x)!==-1; } __proto.replace=function(x){ return this.heapFunction.heapreplace(this.nodes,x,this.cmp); } __proto.pushpop=function(x){ return this.heapFunction.heappushpop(this.nodes,x,this.cmp); } __proto.heapify=function(){ return this.heapFunction.heapify(this.nodes,this.cmp); } __proto.updateItem=function(x){ return this.heapFunction.updateItem(this.nodes,x,this.cmp); } __proto.clear=function(){ return this.nodes=[]; } __proto.empty=function(){ return this.nodes.length===0; } __proto.size=function(){ return this.nodes.length; } __proto.clone=function(){ var heap=new Heap(); heap.nodes=this.nodes.slice(0); return heap; } __proto.toArray=function(){ return this.nodes.slice(0); } return Heap; })() /** *... *@author dongketao */ //class PathFinding.libs.HeapFunction var HeapFunction=(function(){ function HeapFunction(){ //}; this.defaultCmp=function(x,y){ if (x < y){ return-1; } if (x > y){ return 1; } return 0; } } __class(HeapFunction,'PathFinding.libs.HeapFunction'); var __proto=HeapFunction.prototype; //}; __proto.insort=function(a,x,lo,hi,cmp){ var mid=NaN; if (lo==null){ lo=0; } if (cmp==null){ cmp=this.defaultCmp; } if (lo < 0){ throw new Error('lo must be non-negative'); } if (hi==null){ hi=a.length; } while (lo < hi){ mid=Math.floor((lo+hi)/ 2); if (cmp(x,a[mid])< 0){ hi=mid; } else{ lo=mid+1; } } return ([].splice.apply(a,[lo,lo-lo].concat(x)),x); } //}; __proto.heappush=function(array,item,cmp){ if (cmp==null){ cmp=this.defaultCmp; } array.push(item); return this._siftdown(array,0,array.length-1,cmp); } //}; __proto.heappop=function(array,cmp){ var lastelt,returnitem; if (cmp==null){ cmp=this.defaultCmp; } lastelt=array.pop(); if (array.length){ returnitem=array[0]; array[0]=lastelt; this._siftup(array,0,cmp); } else{ returnitem=lastelt; } return returnitem; } //}; __proto.heapreplace=function(array,item,cmp){ var returnitem; if (cmp==null){ cmp=this.defaultCmp; } returnitem=array[0]; array[0]=item; this._siftup(array,0,cmp); return returnitem; } //}; __proto.heappushpop=function(array,item,cmp){ var _ref; if (cmp==null){ cmp=this.defaultCmp; } if (array.length && cmp(array[0],item)< 0){ _ref=[array[0],item],item=_ref[0],array[0]=_ref[1]; this._siftup(array,0,cmp); } return item; } //}; __proto.heapify=function(array,cmp){ var i=0,_i=0,_j=0,_len=0,_ref,_ref1,_results,_results1; if (cmp==null){ cmp=this.defaultCmp; } _ref1=(function(){ _results1=[]; for (_j=0,_ref=Math.floor(array.length / 2);0 <=_ref ? _j < _ref :_j > _ref;0 <=_ref ? _j++:_j--){ _results1.push(_j); } return _results1; }).apply(this).reverse(); _results=[]; for (_i=0,_len=_ref1.length;_i < _len;_i++){ i=_ref1[_i]; _results.push(this._siftup(array,i,cmp)); } return _results; } //}; __proto.updateItem=function(array,item,cmp){ var pos=0; if (cmp==null){ cmp=this.defaultCmp; } pos=array.indexOf(item); if (pos===-1){ return null; } this._siftdown(array,0,pos,cmp); return this._siftup(array,pos,cmp); } //}; __proto.nlargest=function(array,n,cmp){ var elem,result,_i=0,_len=0,_ref; if (cmp==null){ cmp=this.defaultCmp; } result=array.slice(0,n); if (!result.length){ return result; } this.heapify(result,cmp); _ref=array.slice(n); for (_i=0,_len=_ref.length;_i < _len;_i++){ elem=_ref[_i]; this.heappushpop(result,elem,cmp); } return result.sort(cmp).reverse(); } //}; __proto.nsmallest=function(array,n,cmp){ var elem,i,los,result,_i=0,_j=0,_len,_ref,_ref1,_results; if (cmp==null){ cmp=this.defaultCmp; } if (n *10 <=array.length){ result=array.slice(0,n).sort(cmp); if (!result.length){ return result; } los=result[result.length-1]; _ref=array.slice(n); for (_i=0,_len=_ref.length;_i < _len;_i++){ elem=_ref[_i]; if (cmp(elem,los)< 0){ this.insort(result,elem,0,null,cmp); result.pop(); los=result[result.length-1]; } } return result; } this.heapify(array,cmp); _results=[]; for (i=_j=0,_ref1=Math.min(n,array.length);0 <=_ref1 ? _j < _ref1 :_j > _ref1;i=0 <=_ref1 ?++_j :--_j){ _results.push(this.heappop(array,cmp)); } return _results; } //}; __proto._siftdown=function(array,startpos,pos,cmp){ var newitem,parent,parentpos=0; if (cmp==null){ cmp=this.defaultCmp; } newitem=array[pos]; while (pos > startpos){ parentpos=(pos-1)>> 1; parent=array[parentpos]; if (cmp(newitem,parent)< 0){ array[pos]=parent; pos=parentpos; continue ; } break ; } return array[pos]=newitem; } //}; __proto._siftup=function(array,pos,cmp){ var childpos=0,endpos=0,newitem,rightpos=0,startpos=0; if (cmp==null){ cmp=this.defaultCmp; } endpos=array.length; startpos=pos; newitem=array[pos]; childpos=2 *pos+1; while (childpos < endpos){ rightpos=childpos+1; if (rightpos < endpos && !(cmp(array[childpos],array[rightpos])< 0)){ childpos=rightpos; } array[pos]=array[childpos]; pos=childpos; childpos=2 *pos+1; } array[pos]=newitem; return this._siftdown(array,startpos,pos,cmp); } return HeapFunction; })() /** *... *@author ... */ //class PathFinding.finders.BestFirstFinder extends PathFinding.finders.AStarFinder var BestFirstFinder=(function(_super){ function BestFirstFinder(opt){ BestFirstFinder.__super.call(this,opt); var orig=this.heuristic; this.heuristic=function (dx,dy){ return orig(dx,dy)*1000000; }; } __class(BestFirstFinder,'PathFinding.finders.BestFirstFinder',_super); return BestFirstFinder; })(AStarFinder) /** *... *@author ... */ //class PathFinding.finders.BiBestFirstFinder extends PathFinding.finders.BiAStarFinder var BiBestFirstFinder=(function(_super){ function BiBestFirstFinder(opt){ BiBestFirstFinder.__super.call(this,opt); var orig=this.heuristic; this.heuristic=function (dx,dy){ return orig(dx,dy)*1000000; }; } __class(BiBestFirstFinder,'PathFinding.finders.BiBestFirstFinder',_super); return BiBestFirstFinder; })(BiAStarFinder) /** *... *@author ... */ //class PathFinding.finders.BiDijkstraFinder extends PathFinding.finders.BiAStarFinder var BiDijkstraFinder=(function(_super){ function BiDijkstraFinder(opt){ BiDijkstraFinder.__super.call(this,opt); this.heuristic=function (dx,dy){ return 0; }; } __class(BiDijkstraFinder,'PathFinding.finders.BiDijkstraFinder',_super); return BiDijkstraFinder; })(BiAStarFinder) /** *... *@author ... */ //class PathFinding.finders.DijkstraFinder extends PathFinding.finders.AStarFinder var DijkstraFinder=(function(_super){ function DijkstraFinder(opt){ DijkstraFinder.__super.call(this,opt); this.heuristic=function (dx,dy){ return 0; }; } __class(DijkstraFinder,'PathFinding.finders.DijkstraFinder',_super); return DijkstraFinder; })(AStarFinder) /** *... *@author ... */ //class PathFinding.finders.JPFAlwaysMoveDiagonally extends PathFinding.finders.JumpPointFinderBase var JPFAlwaysMoveDiagonally=(function(_super){ function JPFAlwaysMoveDiagonally(opt){ JPFAlwaysMoveDiagonally.__super.call(this,opt); } __class(JPFAlwaysMoveDiagonally,'PathFinding.finders.JPFAlwaysMoveDiagonally',_super); var __proto=JPFAlwaysMoveDiagonally.prototype; /** *Search recursively in the direction (parent-> child),stopping only when a *jump point is found. *@protected *@return {Array>}The x,y coordinate of the jump point *found,or null if not found */ __proto._jump=function(x,y,px,py){ var grid=this.grid,dx=x-px,dy=y-py; if (!grid.isWalkableAt(x,y)){ return null; } if (this.trackJumpRecursion==true){ grid.getNodeAt(x,y).tested=true; } if (grid.getNodeAt(x,y)==this.endNode){ return [x,y]; } if (dx!==0 && dy!==0){ if ((grid.isWalkableAt(x-dx,y+dy)&& !grid.isWalkableAt(x-dx,y))|| (grid.isWalkableAt(x+dx,y-dy)&& !grid.isWalkableAt(x,y-dy))){ return [x,y]; } if (this._jump(x+dx,y,x,y)|| this._jump(x,y+dy,x,y)){ return [x,y]; } } else{ if (dx!==0){ if ((grid.isWalkableAt(x+dx,y+1)&& !grid.isWalkableAt(x,y+1))|| (grid.isWalkableAt(x+dx,y-1)&& !grid.isWalkableAt(x,y-1))){ return [x,y]; } } else{ if ((grid.isWalkableAt(x+1,y+dy)&& !grid.isWalkableAt(x+1,y))|| (grid.isWalkableAt(x-1,y+dy)&& !grid.isWalkableAt(x-1,y))){ return [x,y]; } } } return this._jump(x+dx,y+dy,x,y); } /** *Find the neighbors for the given node. If the node has a parent, *prune the neighbors based on the jump point search algorithm,otherwise *return all available neighbors. *@return {Array>}The neighbors found. */ __proto._findNeighbors=function(node){ var parent=node.parent,x=node.x,y=node.y,grid=this.grid,px=0,py=0,nx=0,ny=0,dx=0,dy=0,neighbors=[],neighborNodes,neighborNode,i=0,l=0; if (parent){ px=parent.x; py=parent.y; dx=(x-px)/ Math.max(Math.abs(x-px),1); dy=(y-py)/ Math.max(Math.abs(y-py),1); if (dx!==0 && dy!==0){ if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); } if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); } if (grid.isWalkableAt(x+dx,y+dy)){ neighbors.push([x+dx,y+dy]); } if (!grid.isWalkableAt(x-dx,y)){ neighbors.push([x-dx,y+dy]); } if (!grid.isWalkableAt(x,y-dy)){ neighbors.push([x+dx,y-dy]); } } else{ if (dx===0){ if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); } if (!grid.isWalkableAt(x+1,y)){ neighbors.push([x+1,y+dy]); } if (!grid.isWalkableAt(x-1,y)){ neighbors.push([x-1,y+dy]); } } else{ if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); } if (!grid.isWalkableAt(x,y+1)){ neighbors.push([x+dx,y+1]); } if (!grid.isWalkableAt(x,y-1)){ neighbors.push([x+dx,y-1]); } } } } else{ neighborNodes=grid.getNeighbors(node,DiagonalMovement.Always); for (i=0,l=neighborNodes.length;i < l;++i){ neighborNode=neighborNodes[i]; neighbors.push([neighborNode.x,neighborNode.y]); } } return neighbors; } return JPFAlwaysMoveDiagonally; })(JumpPointFinderBase) /** *... *@author ... */ //class PathFinding.finders.JPFMoveDiagonallyIfAtMostOneObstacle extends PathFinding.finders.JumpPointFinderBase var JPFMoveDiagonallyIfAtMostOneObstacle=(function(_super){ function JPFMoveDiagonallyIfAtMostOneObstacle(opt){ JPFMoveDiagonallyIfAtMostOneObstacle.__super.call(this,opt); } __class(JPFMoveDiagonallyIfAtMostOneObstacle,'PathFinding.finders.JPFMoveDiagonallyIfAtMostOneObstacle',_super); var __proto=JPFMoveDiagonallyIfAtMostOneObstacle.prototype; /** *Search recursively in the direction (parent-> child),stopping only when a *jump point is found. *@protected *@return {Array>}The x,y coordinate of the jump point *found,or null if not found */ __proto._jump=function(x,y,px,py){ var grid=this.grid,dx=x-px,dy=y-py; if (!grid.isWalkableAt(x,y)){ return null; } if (this.trackJumpRecursion===true){ grid.getNodeAt(x,y).tested=true; } if (grid.getNodeAt(x,y)==this.endNode){ return [x,y]; } if (dx!==0 && dy!==0){ if ((grid.isWalkableAt(x-dx,y+dy)&& !grid.isWalkableAt(x-dx,y))|| (grid.isWalkableAt(x+dx,y-dy)&& !grid.isWalkableAt(x,y-dy))){ return [x,y]; } if (this._jump(x+dx,y,x,y)|| this._jump(x,y+dy,x,y)){ return [x,y]; } } else{ if (dx!==0){ if ((grid.isWalkableAt(x+dx,y+1)&& !grid.isWalkableAt(x,y+1))|| (grid.isWalkableAt(x+dx,y-1)&& !grid.isWalkableAt(x,y-1))){ return [x,y]; } } else{ if ((grid.isWalkableAt(x+1,y+dy)&& !grid.isWalkableAt(x+1,y))|| (grid.isWalkableAt(x-1,y+dy)&& !grid.isWalkableAt(x-1,y))){ return [x,y]; } } } if (grid.isWalkableAt(x+dx,y)|| grid.isWalkableAt(x,y+dy)){ return this._jump(x+dx,y+dy,x,y); } else{ return null; } } /** *Find the neighbors for the given node. If the node has a parent, *prune the neighbors based on the jump point search algorithm,otherwise *return all available neighbors. *@return {Array>}The neighbors found. */ __proto._findNeighbors=function(node){ var parent=node.parent,x=node.x,y=node.y,grid=this.grid,px=0,py=0,nx=0,ny=0,dx=0,dy=0,neighbors=[],neighborNodes,neighborNode,i=0,l=0; if (parent){ px=parent.x; py=parent.y; dx=(x-px)/ Math.max(Math.abs(x-px),1); dy=(y-py)/ Math.max(Math.abs(y-py),1); if (dx!==0 && dy!==0){ if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); } if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); } if (grid.isWalkableAt(x,y+dy)|| grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y+dy]); } if (!grid.isWalkableAt(x-dx,y)&& grid.isWalkableAt(x,y+dy)){ neighbors.push([x-dx,y+dy]); } if (!grid.isWalkableAt(x,y-dy)&& grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y-dy]); } } else{ if (dx===0){ if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); if (!grid.isWalkableAt(x+1,y)){ neighbors.push([x+1,y+dy]); } if (!grid.isWalkableAt(x-1,y)){ neighbors.push([x-1,y+dy]); } } } else{ if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); if (!grid.isWalkableAt(x,y+1)){ neighbors.push([x+dx,y+1]); } if (!grid.isWalkableAt(x,y-1)){ neighbors.push([x+dx,y-1]); } } } } } else{ neighborNodes=grid.getNeighbors(node,DiagonalMovement.IfAtMostOneObstacle); for (i=0,l=neighborNodes.length;i < l;++i){ neighborNode=neighborNodes[i]; neighbors.push([neighborNode.x,neighborNode.y]); } } return neighbors; } return JPFMoveDiagonallyIfAtMostOneObstacle; })(JumpPointFinderBase) /** *... *@author ... */ //class PathFinding.finders.JPFMoveDiagonallyIfNoObstacles extends PathFinding.finders.JumpPointFinderBase var JPFMoveDiagonallyIfNoObstacles=(function(_super){ function JPFMoveDiagonallyIfNoObstacles(opt){ JPFMoveDiagonallyIfNoObstacles.__super.call(this,opt); } __class(JPFMoveDiagonallyIfNoObstacles,'PathFinding.finders.JPFMoveDiagonallyIfNoObstacles',_super); var __proto=JPFMoveDiagonallyIfNoObstacles.prototype; /** *Search recursively in the direction (parent-> child),stopping only when a *jump point is found. *@protected *@return {Array>}The x,y coordinate of the jump point *found,or null if not found */ __proto._jump=function(x,y,px,py){ var grid=this.grid,dx=x-px,dy=y-py; if (!grid.isWalkableAt(x,y)){ return null; } if (this.trackJumpRecursion===true){ grid.getNodeAt(x,y).tested=true; } if (grid.getNodeAt(x,y)===this.endNode){ return [x,y]; } if (dx!==0 && dy!==0){ if (this._jump(x+dx,y,x,y)|| this._jump(x,y+dy,x,y)){ return [x,y]; } } else{ if (dx!==0){ if ((grid.isWalkableAt(x,y-1)&& !grid.isWalkableAt(x-dx,y-1))|| (grid.isWalkableAt(x,y+1)&& !grid.isWalkableAt(x-dx,y+1))){ return [x,y]; } } else if (dy!==0){ if ((grid.isWalkableAt(x-1,y)&& !grid.isWalkableAt(x-1,y-dy))|| (grid.isWalkableAt(x+1,y)&& !grid.isWalkableAt(x+1,y-dy))){ return [x,y]; } } } if (grid.isWalkableAt(x+dx,y)&& grid.isWalkableAt(x,y+dy)){ return this._jump(x+dx,y+dy,x,y); } else{ return null; } } /** *Find the neighbors for the given node. If the node has a parent, *prune the neighbors based on the jump point search algorithm,otherwise *return all available neighbors. *@return {Array>}The neighbors found. */ __proto._findNeighbors=function(node){ var parent=node.parent,x=node.x,y=node.y,grid=this.grid,px=0,py=0,nx=0,ny=0,dx=0,dy=0,neighbors=[],neighborNodes,neighborNode,i=0,l=0; if (parent){ px=parent.x; py=parent.y; dx=(x-px)/ Math.max(Math.abs(x-px),1); dy=(y-py)/ Math.max(Math.abs(y-py),1); if (dx!==0 && dy!==0){ if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); } if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); } if (grid.isWalkableAt(x,y+dy)&& grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y+dy]); } } else{ var isNextWalkable=false; if (dx!==0){ isNextWalkable=grid.isWalkableAt(x+dx,y); var isTopWalkable=grid.isWalkableAt(x,y+1); var isBottomWalkable=grid.isWalkableAt(x,y-1); if (isNextWalkable){ neighbors.push([x+dx,y]); if (isTopWalkable){ neighbors.push([x+dx,y+1]); } if (isBottomWalkable){ neighbors.push([x+dx,y-1]); } } if (isTopWalkable){ neighbors.push([x,y+1]); } if (isBottomWalkable){ neighbors.push([x,y-1]); } } else if (dy!==0){ isNextWalkable=grid.isWalkableAt(x,y+dy); var isRightWalkable=grid.isWalkableAt(x+1,y); var isLeftWalkable=grid.isWalkableAt(x-1,y); if (isNextWalkable){ neighbors.push([x,y+dy]); if (isRightWalkable){ neighbors.push([x+1,y+dy]); } if (isLeftWalkable){ neighbors.push([x-1,y+dy]); } } if (isRightWalkable){ neighbors.push([x+1,y]); } if (isLeftWalkable){ neighbors.push([x-1,y]); } } } } else{ neighborNodes=grid.getNeighbors(node,DiagonalMovement.OnlyWhenNoObstacles); for (i=0,l=neighborNodes.length;i < l;++i){ neighborNode=neighborNodes[i]; neighbors.push([neighborNode.x,neighborNode.y]); } } return neighbors; } return JPFMoveDiagonallyIfNoObstacles; })(JumpPointFinderBase) /** *... *@author ... */ //class PathFinding.finders.JPFNeverMoveDiagonally extends PathFinding.finders.JumpPointFinderBase var JPFNeverMoveDiagonally=(function(_super){ function JPFNeverMoveDiagonally(opt){ JPFNeverMoveDiagonally.__super.call(this,opt); } __class(JPFNeverMoveDiagonally,'PathFinding.finders.JPFNeverMoveDiagonally',_super); var __proto=JPFNeverMoveDiagonally.prototype; /** *Search recursively in the direction (parent-> child),stopping only when a *jump point is found. *@protected *@return {Array>}The x,y coordinate of the jump point *found,or null if not found */ __proto._jump=function(x,y,px,py){ var grid=this.grid,dx=x-px,dy=y-py; if (!grid.isWalkableAt(x,y)){ return null; } if (this.trackJumpRecursion===true){ grid.getNodeAt(x,y).tested=true; } if (grid.getNodeAt(x,y)==this.endNode){ return [x,y]; } if (dx!==0){ if ((grid.isWalkableAt(x,y-1)&& !grid.isWalkableAt(x-dx,y-1))|| (grid.isWalkableAt(x,y+1)&& !grid.isWalkableAt(x-dx,y+1))){ return [x,y]; } } else if (dy!==0){ if ((grid.isWalkableAt(x-1,y)&& !grid.isWalkableAt(x-1,y-dy))|| (grid.isWalkableAt(x+1,y)&& !grid.isWalkableAt(x+1,y-dy))){ return [x,y]; } if (this._jump(x+1,y,x,y)|| this._jump(x-1,y,x,y)){ return [x,y]; } } else{ throw new Error("Only horizontal and vertical movements are allowed"); } return this._jump(x+dx,y+dy,x,y); } /** *Find the neighbors for the given node. If the node has a parent, *prune the neighbors based on the jump point search algorithm,otherwise *return all available neighbors. *@return {Array>}The neighbors found. */ __proto._findNeighbors=function(node){ var parent=node.parent,x=node.x,y=node.y,grid=this.grid,px=0,py=0,nx=0,ny=0,dx=0,dy=0,neighbors=[],neighborNodes,neighborNode,i=0,l=0; if (parent){ px=parent.x; py=parent.y; dx=(x-px)/ Math.max(Math.abs(x-px),1); dy=(y-py)/ Math.max(Math.abs(y-py),1); if (dx!==0){ if (grid.isWalkableAt(x,y-1)){ neighbors.push([x,y-1]); } if (grid.isWalkableAt(x,y+1)){ neighbors.push([x,y+1]); } if (grid.isWalkableAt(x+dx,y)){ neighbors.push([x+dx,y]); } } else if (dy!==0){ if (grid.isWalkableAt(x-1,y)){ neighbors.push([x-1,y]); } if (grid.isWalkableAt(x+1,y)){ neighbors.push([x+1,y]); } if (grid.isWalkableAt(x,y+dy)){ neighbors.push([x,y+dy]); } } } else{ neighborNodes=grid.getNeighbors(node,DiagonalMovement.Never); for (i=0,l=neighborNodes.length;i < l;++i){ neighborNode=neighborNodes[i]; neighbors.push([neighborNode.x,neighborNode.y]); } } return neighbors; } return JPFNeverMoveDiagonally; })(JumpPointFinderBase) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.qqmini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Config=Laya.Config,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,RunDriver=laya.utils.RunDriver; var SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager,URL=laya.net.URL,Utils=laya.utils.Utils; /**@private **/ //class laya.qq.mini.MiniFileMgr var MiniFileMgr$7=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.qq.mini.MiniFileMgr',null,'MiniFileMgr$7'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=QQMiniAdapter.nativefiles.length;i=totalSize)){ if(data.size > QQMiniAdapter.minClearSize) QQMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > QQMiniAdapter.minClearSize) QQMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=QQMiniAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.qq.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); if (!fileObj){ MiniFileMgr.onSaveFile(readyUrl,"",false,encoding,callBack); return; }; var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i *
  • 1.0 正常速度
  • *
  • 0.5 半速(更慢)
  • *
  • 2.0 倍速(更快)
  • *
  • -1.0 向后,正常速度
  • *
  • -0.5 向后,半速
  • * *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ if(!this.videoElement) return 0; return this.videoElement.playbackRate; },function(value){ if(!this.videoElement) return; this.videoElement.playbackRate=value; }); __getset(0,__proto,'x',function(){ if(!this.videoElement) return 0; return this.videoElement.x; },function(value){ if(!this.videoElement) return; this.videoElement.x=value; }); __getset(0,__proto,'y',function(){ if(!this.videoElement) return 0; return this.videoElement.y; },function(value){ if(!this.videoElement) return; this.videoElement.y=value; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.src; }); MiniVideo.__init__=function(){ /*__JS__ */laya.device.media.Video=MiniVideo; } return MiniVideo; })() //class laya.qq.mini.QQMiniAdapter var QQMiniAdapter=(function(){ function QQMiniAdapter(){} __class(QQMiniAdapter,'laya.qq.mini.QQMiniAdapter'); QQMiniAdapter.getJson=function(data){ return JSON.parse(data); } QQMiniAdapter.init=function(isPosMsg,isSon){ (isPosMsg===void 0)&& (isPosMsg=false); (isSon===void 0)&& (isSon=false); if (QQMiniAdapter._inited)return; QQMiniAdapter._inited=true; QQMiniAdapter.window=/*__JS__ */window; if(!QQMiniAdapter.window.hasOwnProperty("qq")) return; if(QQMiniAdapter.window.navigator.userAgent.indexOf('MiniGame')<0)return; QQMiniAdapter.isZiYu=isSon; QQMiniAdapter.isPosMsgYu=isPosMsg; QQMiniAdapter.EnvConfig={}; try{ /*__JS__ */laya.webgl.resource.WebGLCanvas.premulAlpha=true; }catch(e){ } if(!QQMiniAdapter.isZiYu){ MiniFileMgr$7.setNativeFileDir("/layaairGame"); MiniFileMgr$7.existDir(MiniFileMgr$7.fileNativeDir,Handler.create(QQMiniAdapter,QQMiniAdapter.onMkdirCallBack)); } QQMiniAdapter.systemInfo=QQMiniAdapter.window.qq.getSystemInfoSync(); if (QQMiniAdapter.systemInfo.system.toLowerCase()==='ios 10.1.1'){ try{ /*__JS__ */laya.webgl.resource.WebGLCharImage.canUseCanvas=false; }catch(e){ } } QQMiniAdapter.window.focus=function (){ }; Laya['_getUrlPath']=function (){ }; Laya['getUrlPath']=function (){ }; QQMiniAdapter.window.logtime=function (str){ }; QQMiniAdapter.window.alertTimeLog=function (str){ }; QQMiniAdapter.window.resetShareInfo=function (){ }; QQMiniAdapter.window.CanvasRenderingContext2D=function (){ }; QQMiniAdapter.window.CanvasRenderingContext2D.prototype=QQMiniAdapter.window.qq.createCanvas().getContext('2d').__proto__; QQMiniAdapter.window.document.body.appendChild=function (){ }; QQMiniAdapter.EnvConfig.pixelRatioInt=0; RunDriver.getPixelRatio=QQMiniAdapter.pixelRatio; QQMiniAdapter._preCreateElement=Browser.createElement; Browser["createElement"]=QQMiniAdapter.createElement; RunDriver.createShaderCondition=QQMiniAdapter.createShaderCondition; Utils['parseXMLFromString']=QQMiniAdapter.parseXMLFromString; Input['_createInputElement']=MiniInput$7['_createInputElement']; QQMiniAdapter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader$7.prototype.load; Loader.prototype._loadImage=MiniImage$7.prototype._loadImage; LocalStorage._baseClass=MiniLocalStorage$7; MiniLocalStorage$7.__init__(); QQMiniAdapter.onReciveData(); Config.useRetinalCanvas=true; } QQMiniAdapter.onReciveData=function(){ if(laya.qq.mini.QQMiniAdapter.isZiYu){ QQMiniAdapter.window.qq.onMessage(function(message){ if(message['isLoad']=="opendatacontext"){ if(message.url){ MiniFileMgr$7.ziyuFileData[message.url]=message.atlasdata; MiniFileMgr$7.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }else if(message['isLoad']=="openJsondatacontext"){ if(message.url){ MiniFileMgr$7.ziyuFileData[message.url]=message.atlasdata; } }else if(message['isLoad']=="openJsondatacontextPic"){ MiniFileMgr$7.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }); } } QQMiniAdapter.measureText=function(str){ var tempObj=QQMiniAdapter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } QQMiniAdapter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return ""; return "utf8"; } QQMiniAdapter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr$7.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr$7.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } QQMiniAdapter.remove=function(fileUrl,callBack){ MiniFileMgr$7.deleteFile("",fileUrl,callBack,"",0); } QQMiniAdapter.removeAll=function(){ MiniFileMgr$7.deleteAll(); } QQMiniAdapter.hasNativeFile=function(fileUrl){ return MiniFileMgr$7.isLocalNativeFile(fileUrl); } QQMiniAdapter.getFileInfo=function(fileUrl){ return MiniFileMgr$7.getFileInfo(fileUrl); } QQMiniAdapter.getFileList=function(){ return MiniFileMgr$7.filesListObj; } QQMiniAdapter.exitMiniProgram=function(){ QQMiniAdapter.window.qq.exitMiniProgram(); } QQMiniAdapter.onMkdirCallBack=function(errorCode,data){ if (!errorCode){ MiniFileMgr$7.filesListObj=JSON.parse(data.data); MiniFileMgr$7.fakeObj=JSON.parse(data.data); } } QQMiniAdapter.pixelRatio=function(){ if (!QQMiniAdapter.EnvConfig.pixelRatioInt){ try { QQMiniAdapter.EnvConfig.pixelRatioInt=QQMiniAdapter.systemInfo.pixelRatio; return QQMiniAdapter.systemInfo.pixelRatio; }catch (error){} } return QQMiniAdapter.EnvConfig.pixelRatioInt; } QQMiniAdapter.createElement=function(type){ if (type=="canvas"){ var _source; if (QQMiniAdapter.idx==1){ if(QQMiniAdapter.isZiYu){ _source=QQMiniAdapter.window.sharedCanvas; _source.style={}; }else{ _source=QQMiniAdapter.window.canvas; } }else { _source=QQMiniAdapter.window.qq.createCanvas(); } QQMiniAdapter.idx++; return _source; }else if (type=="textarea" || type=="input"){ return QQMiniAdapter.onCreateInput(type); }else if (type=="div"){ var node=QQMiniAdapter._preCreateElement(type); node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } else { return QQMiniAdapter._preCreateElement(type); } } QQMiniAdapter.onCreateInput=function(type){ var node=QQMiniAdapter._preCreateElement(type); node.focus=MiniInput$7.wxinputFocus; node.blur=MiniInput$7.wxinputblur; node.style={}; node.value=0; node.parentElement={}; node.placeholder={}; node.type={}; node.setColor=function (value){ }; node.setType=function (value){ }; node.setFontFace=function (value){ }; node.addEventListener=function (value){ }; node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } QQMiniAdapter.createShaderCondition=function(conditionScript){ var _$this=this; var func=function (){ var abc=conditionScript; return _$this[conditionScript.replace("this.","")]; } return func; } QQMiniAdapter.sendAtlasToOpenDataContext=function(url){ if(!laya.qq.mini.QQMiniAdapter.isZiYu){ var atlasJson=Loader.getRes(URL.formatURL(url)); if(atlasJson){ var textureArr=(atlasJson.meta.image).split(","); if (atlasJson.meta && atlasJson.meta.image){ var toloadPics=atlasJson.meta.image.split(","); var split=url.indexOf("/")>=0 ? "/" :"\\"; var idx=url.lastIndexOf(split); var folderPath=idx >=0 ? url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[url.replace(".json",".png")]; } for(i=0;i\s+<'); try { /*__JS__ */rst=(new window.Parser.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } QQMiniAdapter.idx=1; __static(QQMiniAdapter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir","wxlocal"];} ]); return QQMiniAdapter; })() /**@private **/ //class laya.qq.mini.MiniAccelerator extends laya.events.EventDispatcher var MiniAccelerator$7=(function(_super){ function MiniAccelerator(){ MiniAccelerator.__super.call(this); } __class(MiniAccelerator,'laya.qq.mini.MiniAccelerator',_super,'MiniAccelerator$7'); var __proto=MiniAccelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); MiniAccelerator.startListen(this["onDeviceOrientationChange"]); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) MiniAccelerator.stopListen(); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } MiniAccelerator.__init__=function(){ try{ var Acc; Acc=/*__JS__ */laya.device.motion.Accelerator; if (!Acc)return; Acc["prototype"]["on"]=MiniAccelerator["prototype"]["on"]; Acc["prototype"]["off"]=MiniAccelerator["prototype"]["off"]; }catch (e){ } } MiniAccelerator.startListen=function(callBack){ MiniAccelerator._callBack=callBack; if (MiniAccelerator._isListening)return; MiniAccelerator._isListening=true; try{ QQMiniAdapter.window.qq.onAccelerometerChange(laya.qq.mini.MiniAccelerator.onAccelerometerChange); }catch(e){} } MiniAccelerator.stopListen=function(){ MiniAccelerator._isListening=false; try{ QQMiniAdapter.window.qq.stopAccelerometer({}); }catch(e){} } MiniAccelerator.onAccelerometerChange=function(res){ var e; e={}; e.acceleration=res; e.accelerationIncludingGravity=res; e.rotationRate={}; if (MiniAccelerator._callBack !=null){ MiniAccelerator._callBack(e); } } MiniAccelerator._isListening=false; MiniAccelerator._callBack=null; return MiniAccelerator; })(EventDispatcher) /**@private **/ //class laya.qq.mini.MiniLoader extends laya.events.EventDispatcher var MiniLoader$7=(function(_super){ function MiniLoader(){ MiniLoader.__super.call(this); } __class(MiniLoader,'laya.qq.mini.MiniLoader',_super,'MiniLoader$7'); var __proto=MiniLoader.prototype; /** *@private *@param url *@param type *@param cache *@param group *@param ignoreCache */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); var thisLoader=this; thisLoader._url=url; if (url.indexOf("data:image")===0)thisLoader._type=type=/*laya.net.Loader.IMAGE*/"image"; else { thisLoader._type=type || (type=thisLoader.getTypeFromUrl(url)); } thisLoader._cache=cache; thisLoader._data=null; if (!ignoreCache && Loader.loadedMap[URL.formatURL(url)]){ thisLoader._data=Loader.loadedMap[URL.formatURL(url)]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",thisLoader._data); return; } if (Loader.parserMap[type] !=null){ thisLoader._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; }; var encoding=QQMiniAdapter.getUrlEncode(url,type); var urlType=Utils.getFileExtension(url); if ((MiniLoader._fileTypeArr.indexOf(urlType)!=-1)|| type==/*laya.net.Loader.IMAGE*/"image"){ QQMiniAdapter.EnvConfig.load.call(this,url,type,cache,group,ignoreCache); }else { if(QQMiniAdapter.isZiYu && !MiniFileMgr$7.ziyuFileData[url]){ url=URL.formatURL(url); } if(QQMiniAdapter.isZiYu && MiniFileMgr$7.ziyuFileData[url]){ var tempData=MiniFileMgr$7.ziyuFileData[url]; thisLoader.onLoaded(tempData); return; } if (!MiniFileMgr$7.getFileInfo(URL.formatURL(url))){ if (MiniFileMgr$7.isLocalNativeFile(url)){ if (QQMiniAdapter.subNativeFiles && QQMiniAdapter.subNativeheads.length==0){ for (var key in QQMiniAdapter.subNativeFiles){ var tempArr=QQMiniAdapter.subNativeFiles[key]; QQMiniAdapter.subNativeheads=QQMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ QQMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(QQMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && QQMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=QQMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } MiniFileMgr$7.read(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); return; }; var tempUrl=url; var tempurl=URL.formatURL(url); if (tempurl.indexOf(QQMiniAdapter.window.qq.env.USER_DATA_PATH)==-1 &&(url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)&& !QQMiniAdapter.AutoCacheDownFile){ QQMiniAdapter.EnvConfig.load.call(thisLoader,tempUrl,type,cache,group,ignoreCache); }else { fileObj=MiniFileMgr$7.getFileInfo(url); if(fileObj){ fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; MiniFileMgr$7.readFile(fileObj.url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else if (thisLoader.type=="image" || thisLoader.type=="htmlimage"){ QQMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } else{ url=URL.formatURL(url); if(type !=/*laya.net.Loader.IMAGE*/"image" && ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1)|| MiniFileMgr$7.isLocalNativeFile(url))){ MiniFileMgr$7.readFile(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else{ MiniFileMgr$7.downFiles(encodeURI(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url,cache); } } } }else { var fileObj=MiniFileMgr$7.getFileInfo(URL.formatURL(url)); fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; var nativepath=MiniFileMgr$7.getFileNativePath(fileObj.md5); MiniFileMgr$7.readFile(nativepath,fileObj.encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),URL.formatURL(url)); } } } MiniLoader.onReadNativeCallBack=function(encoding,url,type,cache,group,ignoreCache,thisLoader,errorCode,data){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); (errorCode===void 0)&& (errorCode=0); if (!errorCode){ var tempData; if (type==/*laya.net.Loader.JSON*/"json" || type==/*laya.net.Loader.ATLAS*/"atlas"){ tempData=QQMiniAdapter.getJson(data.data); }else if (type==/*laya.net.Loader.XML*/"xml"){ tempData=Utils.parseXMLFromString(data.data); }else { tempData=data.data; } if(!QQMiniAdapter.isZiYu &&QQMiniAdapter.isPosMsgYu && type !=/*laya.net.Loader.BUFFER*/"arraybuffer" && QQMiniAdapter.window.qq){ QQMiniAdapter.window.qq.postMessage({url:url,data:tempData,isLoad:"filedata"}); } thisLoader.onLoaded(tempData); }else if (errorCode==1){ console.log("-----------本地加载失败,尝试外网加载----"); QQMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } } __static(MiniLoader, ['_fileTypeArr',function(){return this._fileTypeArr=['png','jpg','bmp','jpeg','gif'];} ]); return MiniLoader; })(EventDispatcher) /**@private **/ //class laya.qq.mini.MiniSound extends laya.events.EventDispatcher var MiniSound$7=(function(_super){ function MiniSound(){ /**@private **/ this._sound=null; /** *@private *声音URL */ this.url=null; /** *@private *是否已加载完成 */ this.loaded=false; /**@private **/ this.readyUrl=null; MiniSound.__super.call(this); } __class(MiniSound,'laya.qq.mini.MiniSound',_super,'MiniSound$7'); var __proto=MiniSound.prototype; /** *@private *加载声音。 *@param url 地址。 * */ __proto.load=function(url){ if (!MiniFileMgr$7.isLocalNativeFile(url)){ url=URL.formatURL(url); }else{ if (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1){ if(MiniFileMgr$7.loadPath !=""){ url=url.split(MiniFileMgr$7.loadPath)[1]; }else{ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; if(tempStr !="") url=url.split(tempStr)[1]; } } } this.url=url; this.readyUrl=url; if (MiniSound._audioCache[this.readyUrl]){ this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if(QQMiniAdapter.autoCacheFile&&MiniFileMgr$7.getFileInfo(url)){ this.onDownLoadCallBack(url,0); }else{ if(!QQMiniAdapter.autoCacheFile){ this.onDownLoadCallBack(url,0); }else{ if (MiniFileMgr$7.isLocalNativeFile(url)){ tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="") url=url.split(tempStr)[1]; if (!url){ url=tempUrl; } if (QQMiniAdapter.subNativeFiles && QQMiniAdapter.subNativeheads.length==0){ for (var key in QQMiniAdapter.subNativeFiles){ var tempArr=QQMiniAdapter.subNativeFiles[key]; QQMiniAdapter.subNativeheads=QQMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ QQMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(QQMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && QQMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=QQMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } this.onDownLoadCallBack(url,0); }else{ MiniFileMgr$7.downOtherFiles(url,Handler.create(this,this.onDownLoadCallBack,[url]),url); } } } } /**@private **/ __proto.onDownLoadCallBack=function(sourceUrl,errorCode){ if (!errorCode){ var fileNativeUrl; if(QQMiniAdapter.autoCacheFile){ var fileObj=MiniFileMgr$7.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$7.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=sourceUrl; } this._sound=MiniSound._createSound(); this._sound.src=this.url=fileNativeUrl; }else{ this._sound=MiniSound._createSound(); this._sound.src=sourceUrl; } this._sound.onCanplay(MiniSound.bindToThis(this.onCanPlay,this)); this._sound.onError(MiniSound.bindToThis(this.onError,this)); }else{ this.event(/*laya.events.Event.ERROR*/"error"); } } /**@private **/ __proto.onError=function(error){ try{ console.log("-----1---------------minisound-----id:"+MiniSound._id); console.log(error); } catch(error){ console.log("-----2---------------minisound-----id:"+MiniSound._id); console.log(error); } this.event(/*laya.events.Event.ERROR*/"error"); this._sound.offError(null); } /**@private **/ __proto.onCanPlay=function(){ this.loaded=true; this.event(/*laya.events.Event.COMPLETE*/"complete"); this._sound.offCanplay(null); } /** *@private *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); var tSound; if (this.url==SoundManager._tMusic){ if (!MiniSound._musicAudio)MiniSound._musicAudio=MiniSound._createSound(); tSound=MiniSound._musicAudio; }else { if(MiniSound._audioCache[this.readyUrl]){ tSound=MiniSound._audioCache[this.readyUrl]._sound; }else{ tSound=MiniSound._createSound(); } } if(QQMiniAdapter.autoCacheFile&&MiniFileMgr$7.getFileInfo(this.url)){ var fileNativeUrl; var fileObj=MiniFileMgr$7.getFileInfo(this.url); var fileMd5Name=fileObj.md5; tSound.src=this.url=MiniFileMgr$7.getFileNativePath(fileMd5Name); }else{ tSound.src=this.url; }; var channel=new MiniSoundChannel$7(tSound,this); channel.url=this.url; channel.loops=loops; channel.loop=(loops===0 ? true :false); channel.startTime=startTime; channel.play(); SoundManager.addChannel(channel); return channel; } /** *@private *释放声音资源。 * */ __proto.dispose=function(){ var ad=MiniSound._audioCache[this.readyUrl]; if (ad){ ad.src=""; if(ad._sound){ ad._sound.destroy(); ad._sound=null; ad=null; } delete MiniSound._audioCache[this.readyUrl]; } } /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ return this._sound.duration; }); MiniSound._createSound=function(){ MiniSound._id++; return QQMiniAdapter.window.qq.createInnerAudioContext(); } MiniSound.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } MiniSound._musicAudio=null; MiniSound._id=0; MiniSound._audioCache={}; return MiniSound; })(EventDispatcher) /**@private **/ //class laya.qq.mini.MiniSoundChannel extends laya.media.SoundChannel var MiniSoundChannel$7=(function(_super){ function MiniSoundChannel(audio,miniSound){ /**@private **/ this._audio=null; /**@private **/ this._onEnd=null; /**@private **/ this._miniSound=null; MiniSoundChannel.__super.call(this); this._audio=audio; this._miniSound=miniSound; this._onEnd=MiniSoundChannel.bindToThis(this.__onEnd,this); audio.onEnded(this._onEnd); } __class(MiniSoundChannel,'laya.qq.mini.MiniSoundChannel',_super,'MiniSoundChannel$7'); var __proto=MiniSoundChannel.prototype; /**@private **/ __proto.__onEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.pause(); this._audio.offEnded(null); this._audio=null; this._miniSound=null; this._onEnd=null; } /**@private **/ __proto.pause=function(){ this.isStopped=true; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',null,function(time){ if(this._audio){ this._audio.startTime=time; } }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ return this._audio.autoplay; },function(value){ this._audio.autoplay=value; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ return this._audio.loop; },function(value){ this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.quickgamemini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Config=Laya.Config,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,RunDriver=laya.utils.RunDriver; var SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager,URL=laya.net.URL,Utils=laya.utils.Utils; /**@private **/ //class laya.qg.mini.MiniFileMgr var MiniFileMgr$3=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.qg.mini.MiniFileMgr',null,'MiniFileMgr$3'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=QGMiniAdapter.nativefiles.length;i=totalSize)){ if(data.size > QGMiniAdapter.minClearSize) QGMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > QGMiniAdapter.minClearSize) QGMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=QGMiniAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.qg.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i *
  • 1.0 正常速度
  • *
  • 0.5 半速(更慢)
  • *
  • 2.0 倍速(更快)
  • *
  • -1.0 向后,正常速度
  • *
  • -0.5 向后,半速
  • * *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ if(!this.videoElement) return 0; return this.videoElement.playbackRate; },function(value){ if(!this.videoElement) return; this.videoElement.playbackRate=value; }); __getset(0,__proto,'x',function(){ if(!this.videoElement) return 0; return this.videoElement.x; },function(value){ if(!this.videoElement) return; this.videoElement.x=value; }); __getset(0,__proto,'y',function(){ if(!this.videoElement) return 0; return this.videoElement.y; },function(value){ if(!this.videoElement) return; this.videoElement.y=value; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.src; }); MiniVideo.__init__=function(){ /*__JS__ */laya.device.media.Video=MiniVideo; } return MiniVideo; })() //class laya.qg.mini.QGMiniAdapter var QGMiniAdapter=(function(){ function QGMiniAdapter(){} __class(QGMiniAdapter,'laya.qg.mini.QGMiniAdapter'); QGMiniAdapter.getJson=function(data){ return JSON.parse(data); } QGMiniAdapter.init=function(isPosMsg,isSon){ (isPosMsg===void 0)&& (isPosMsg=false); (isSon===void 0)&& (isSon=false); if (QGMiniAdapter._inited)return; QGMiniAdapter._inited=true; QGMiniAdapter.window=/*__JS__ */window; if(!QGMiniAdapter.window.hasOwnProperty('qg')) return; if(QGMiniAdapter.window.navigator.userAgent.indexOf('OPPO')<0)return; QGMiniAdapter.isZiYu=isSon; QGMiniAdapter.isPosMsgYu=isPosMsg; QGMiniAdapter.EnvConfig={}; try{ /*__JS__ */laya.webgl.resource.WebGLCanvas.premulAlpha=true; }catch(e){ } if(!QGMiniAdapter.isZiYu){ if(!/*__JS__ */qg){ console.log("======qg null======================"); } if(!/*__JS__ */qg.env){ console.log("======qg.env null======================"); } MiniFileMgr$3.setNativeFileDir("/layaairGame"); MiniFileMgr$3.existDir(MiniFileMgr$3.fileNativeDir,Handler.create(QGMiniAdapter,QGMiniAdapter.onMkdirCallBack)); } QGMiniAdapter.window.qg.getSystemInfo({ success:function (data){ QGMiniAdapter.systemInfo=data; } }); QGMiniAdapter.window.focus=function (){ }; Laya['_getUrlPath']=function (){ }; Laya['getUrlPath']=function (){ }; QGMiniAdapter.window.logtime=function (str){ }; QGMiniAdapter.window.alertTimeLog=function (str){ }; QGMiniAdapter.window.resetShareInfo=function (){ }; QGMiniAdapter.window.document.body.appendChild=function (){ }; QGMiniAdapter.EnvConfig.pixelRatioInt=0; RunDriver.getPixelRatio=QGMiniAdapter.pixelRatio; QGMiniAdapter._preCreateElement=Browser.createElement; Browser["createElement"]=QGMiniAdapter.createElement; RunDriver.createShaderCondition=QGMiniAdapter.createShaderCondition; Utils['parseXMLFromString']=QGMiniAdapter.parseXMLFromString; Input['_createInputElement']=MiniInput$3['_createInputElement']; QGMiniAdapter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader$3.prototype.load; Loader.prototype._loadImage=MiniImage$3.prototype._loadImage; QGMiniAdapter.onReciveData(); Config.useRetinalCanvas=true; } QGMiniAdapter.onReciveData=function(){ if(laya.qg.mini.QGMiniAdapter.isZiYu && QGMiniAdapter.window.qg.onMessage){ QGMiniAdapter.window.qg.onMessage(function(message){ if(message['isLoad']=="opendatacontext"){ if(message.url){ MiniFileMgr$3.ziyuFileData[message.url]=message.atlasdata; MiniFileMgr$3.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }else if(message['isLoad']=="openJsondatacontext"){ if(message.url){ MiniFileMgr$3.ziyuFileData[message.url]=message.atlasdata; } }else if(message['isLoad']=="openJsondatacontextPic"){ MiniFileMgr$3.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }); } } QGMiniAdapter.measureText=function(str){ var tempObj=QGMiniAdapter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } QGMiniAdapter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return ""; return "utf8"; } QGMiniAdapter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr$3.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr$3.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } QGMiniAdapter.remove=function(fileUrl,callBack){ MiniFileMgr$3.deleteFile("",fileUrl,callBack,"",0); } QGMiniAdapter.removeAll=function(){ MiniFileMgr$3.deleteAll(); } QGMiniAdapter.hasNativeFile=function(fileUrl){ return MiniFileMgr$3.isLocalNativeFile(fileUrl); } QGMiniAdapter.getFileInfo=function(fileUrl){ return MiniFileMgr$3.getFileInfo(fileUrl); } QGMiniAdapter.getFileList=function(){ return MiniFileMgr$3.filesListObj; } QGMiniAdapter.exitMiniProgram=function(){ QGMiniAdapter.window.qg.exitMiniProgram(); } QGMiniAdapter.onMkdirCallBack=function(errorCode,data){ if (!errorCode) MiniFileMgr$3.filesListObj=JSON.parse(data.data); } QGMiniAdapter.pixelRatio=function(){ if (!QGMiniAdapter.EnvConfig.pixelRatioInt){ try { QGMiniAdapter.systemInfo.pixelRatio=QGMiniAdapter.window.devicePixelRatio; QGMiniAdapter.EnvConfig.pixelRatioInt=QGMiniAdapter.systemInfo.pixelRatio; return QGMiniAdapter.systemInfo.pixelRatio; }catch (error){} } return QGMiniAdapter.EnvConfig.pixelRatioInt; } QGMiniAdapter.createElement=function(type){ if (type=="canvas"){ var _source; if (QGMiniAdapter.idx==1){ if(QGMiniAdapter.isZiYu){ _source=QGMiniAdapter.window.document.createElement("canvas"); _source.style={}; }else{ _source=QGMiniAdapter.window.__canvas; } }else { _source=QGMiniAdapter.window.document.createElement("canvas"); } QGMiniAdapter.idx++; return _source; }else if (type=="textarea" || type=="input"){ return QGMiniAdapter.onCreateInput(type); }else if (type=="div"){ var node=QGMiniAdapter._preCreateElement(type); node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } else { return QGMiniAdapter._preCreateElement(type); } } QGMiniAdapter.onCreateInput=function(type){ var node=QGMiniAdapter._preCreateElement(type); node.focus=MiniInput$3.wxinputFocus; node.blur=MiniInput$3.wxinputblur; node.style={}; node.value=0; node.parentElement={}; node.placeholder={}; node.type={}; node.setColor=function (value){ }; node.setType=function (value){ }; node.setFontFace=function (value){ }; node.addEventListener=function (value){ }; node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } QGMiniAdapter.createShaderCondition=function(conditionScript){ var _$this=this; var func=function (){ var abc=conditionScript; return _$this[conditionScript.replace("this.","")]; } return func; } QGMiniAdapter.sendAtlasToOpenDataContext=function(url){ if(!laya.qg.mini.QGMiniAdapter.isZiYu){ var atlasJson=Loader.getRes(URL.formatURL(url)); if(atlasJson){ var textureArr=(atlasJson.meta.image).split(","); if (atlasJson.meta && atlasJson.meta.image){ var toloadPics=atlasJson.meta.image.split(","); var split=url.indexOf("/")>=0 ? "/" :"\\"; var idx=url.lastIndexOf(split); var folderPath=idx >=0 ? url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[url.replace(".json",".png")]; } for(i=0;i\s+<'); try { /*__JS__ */rst=(new window.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } QGMiniAdapter.idx=1; __static(QGMiniAdapter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir","qgfile"];} ]); return QGMiniAdapter; })() /**@private **/ //class laya.qg.mini.MiniAccelerator extends laya.events.EventDispatcher var MiniAccelerator$3=(function(_super){ function MiniAccelerator(){ MiniAccelerator.__super.call(this); } __class(MiniAccelerator,'laya.qg.mini.MiniAccelerator',_super,'MiniAccelerator$3'); var __proto=MiniAccelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); MiniAccelerator.startListen(this["onAccelerometerChange"]); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) MiniAccelerator.stopListen(); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } MiniAccelerator.__init__=function(){ try{ var Acc; Acc=/*__JS__ */laya.device.motion.Accelerator; if (!Acc)return; Acc["prototype"]["on"]=MiniAccelerator["prototype"]["on"]; Acc["prototype"]["off"]=MiniAccelerator["prototype"]["off"]; }catch (e){ } } MiniAccelerator.startListen=function(callBack){ MiniAccelerator._callBack=callBack; if (MiniAccelerator._isListening)return; MiniAccelerator._isListening=true; try{ QGMiniAdapter.window.qg.onAccelerometerChange(laya.qg.mini.MiniAccelerator.onAccelerometerChange); }catch(e){} } MiniAccelerator.stopListen=function(){ MiniAccelerator._isListening=false; try{ QGMiniAdapter.window.qg.stopAccelerometer({}); }catch(e){} } MiniAccelerator.onAccelerometerChange=function(res){ var e; e={}; e.acceleration=res; e.accelerationIncludingGravity=res; e.rotationRate={}; if (MiniAccelerator._callBack !=null){ MiniAccelerator._callBack(e); } } MiniAccelerator._isListening=false; MiniAccelerator._callBack=null; return MiniAccelerator; })(EventDispatcher) /**@private **/ //class laya.qg.mini.MiniLoader extends laya.events.EventDispatcher var MiniLoader$3=(function(_super){ function MiniLoader(){ MiniLoader.__super.call(this); } __class(MiniLoader,'laya.qg.mini.MiniLoader',_super,'MiniLoader$3'); var __proto=MiniLoader.prototype; /** *@private *@param url *@param type *@param cache *@param group *@param ignoreCache */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); var thisLoader=this; thisLoader._url=url; if (!url){ thisLoader.onLoaded(null); return; } url=URL.customFormat(url); if (url.indexOf("data:image")===0)thisLoader._type=type=/*laya.net.Loader.IMAGE*/"image"; else { thisLoader._type=type || (type=thisLoader.getTypeFromUrl(thisLoader._url)); } thisLoader._cache=cache; thisLoader._data=null; if (!ignoreCache && Loader.loadedMap[URL.formatURL(url)]){ thisLoader._data=Loader.loadedMap[URL.formatURL(url)]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",thisLoader._data); return; } if (Loader.parserMap[type] !=null){ thisLoader._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; }; var encoding=QGMiniAdapter.getUrlEncode(url,type); var urlType=Utils.getFileExtension(url); if ((MiniLoader._fileTypeArr.indexOf(urlType)!=-1)|| type==/*laya.net.Loader.IMAGE*/"image"){ QGMiniAdapter.EnvConfig.load.call(this,url,type,cache,group,ignoreCache); }else { if(QGMiniAdapter.isZiYu && !MiniFileMgr$3.ziyuFileData[url]){ url=URL.formatURL(url); } if(QGMiniAdapter.isZiYu && MiniFileMgr$3.ziyuFileData[url]){ var tempData=MiniFileMgr$3.ziyuFileData[url]; thisLoader.onLoaded(tempData); return; } if (!MiniFileMgr$3.getFileInfo(URL.formatURL(url))){ if (MiniFileMgr$3.isLocalNativeFile(url)){ if (QGMiniAdapter.subNativeFiles && QGMiniAdapter.subNativeheads.length==0){ for (var key in QGMiniAdapter.subNativeFiles){ var tempArr=QGMiniAdapter.subNativeFiles[key]; QGMiniAdapter.subNativeheads=QGMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ QGMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(QGMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && QGMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=QGMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } MiniFileMgr$3.read(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); return; }; var tempUrl=url; var tempurl=URL.formatURL(url); if (tempurl.indexOf(QGMiniAdapter.window.qg.env.USER_DATA_PATH)==-1 &&(url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)&& !QGMiniAdapter.AutoCacheDownFile){ QGMiniAdapter.EnvConfig.load.call(thisLoader,tempUrl,type,cache,group,ignoreCache); }else { fileObj=MiniFileMgr$3.getFileInfo(url); if(fileObj){ fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; MiniFileMgr$3.readFile(fileObj.url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else if (thisLoader.type=="image" || thisLoader.type=="htmlimage"){ QGMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } else{ url=URL.formatURL(url); if(type !=/*laya.net.Loader.IMAGE*/"image" && ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1)|| MiniFileMgr$3.isLocalNativeFile(url))){ MiniFileMgr$3.readFile(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else{ MiniFileMgr$3.downFiles(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url,cache); } } } }else { var fileObj=MiniFileMgr$3.getFileInfo(URL.formatURL(url)); fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; var nativepath=MiniFileMgr$3.getFileNativePath(fileObj.md5); MiniFileMgr$3.readFile(nativepath,fileObj.encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),URL.formatURL(url)); } } } MiniLoader.onReadNativeCallBack=function(encoding,url,type,cache,group,ignoreCache,thisLoader,errorCode,data){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); (errorCode===void 0)&& (errorCode=0); if (!errorCode){ var tempData; if (type==/*laya.net.Loader.JSON*/"json" || type==/*laya.net.Loader.ATLAS*/"atlas"){ tempData=QGMiniAdapter.getJson(data.data); }else if (type==/*laya.net.Loader.XML*/"xml"){ tempData=Utils.parseXMLFromString(data.data); }else { tempData=data.data; } if(!QGMiniAdapter.isZiYu &&QGMiniAdapter.isPosMsgYu && type !=/*laya.net.Loader.BUFFER*/"arraybuffer"){ QGMiniAdapter.window.qg.postMessage && QGMiniAdapter.window.qg.postMessage({url:url,data:tempData,isLoad:"filedata"}); } thisLoader.onLoaded(tempData); }else if (errorCode==1){ console.log("-----------本地加载失败,尝试外网加载----"); QGMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } } __static(MiniLoader, ['_fileTypeArr',function(){return this._fileTypeArr=['png','jpg','bmp','jpeg','gif'];} ]); return MiniLoader; })(EventDispatcher) /**@private **/ //class laya.qg.mini.MiniSound extends laya.events.EventDispatcher var MiniSound$3=(function(_super){ function MiniSound(){ /**@private **/ this._sound=null; /** *@private *声音URL */ this.url=null; /** *@private *是否已加载完成 */ this.loaded=false; /**@private **/ this.readyUrl=null; MiniSound.__super.call(this); this._sound=MiniSound._createSound(); } __class(MiniSound,'laya.qg.mini.MiniSound',_super,'MiniSound$3'); var __proto=MiniSound.prototype; /** *@private *加载声音。 *@param url 地址。 * */ __proto.load=function(url){ if (!MiniFileMgr$3.isLocalNativeFile(url)){ url=URL.formatURL(url); }else{ if (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1){ if(MiniFileMgr$3.loadPath !=""){ url=url.split(MiniFileMgr$3.loadPath)[1]; }else{ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; if(tempStr !="") url=url.split(tempStr)[1]; } } } this.url=url; this.readyUrl=url; if(QGMiniAdapter.autoCacheFile&&MiniFileMgr$3.getFileInfo(url)){ this.onDownLoadCallBack(url,0); }else{ if(!QGMiniAdapter.autoCacheFile){ this.onDownLoadCallBack(url,0); }else{ if (MiniFileMgr$3.isLocalNativeFile(url)){ tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="") url=url.split(tempStr)[1]; if (!url){ url=tempUrl; } if (QGMiniAdapter.subNativeFiles && QGMiniAdapter.subNativeheads.length==0){ for (var key in QGMiniAdapter.subNativeFiles){ var tempArr=QGMiniAdapter.subNativeFiles[key]; QGMiniAdapter.subNativeheads=QGMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ QGMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(QGMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && QGMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=QGMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } this.onDownLoadCallBack(url,0); }else{ if((url.indexOf("http://")==-1 && url.indexOf("https://")==-1) || url.indexOf(QGMiniAdapter.window.my.env.USER_DATA_PATH)!=-1){ this.onDownLoadCallBack(url,0); }else MiniFileMgr$3.downOtherFiles(url,Handler.create(this,this.onDownLoadCallBack,[url]),url); } } } } /**@private **/ __proto.onDownLoadCallBack=function(sourceUrl,errorCode,tempFilePath){ (tempFilePath===void 0)&& (tempFilePath=""); if (!errorCode){ var fileNativeUrl; if(QGMiniAdapter.autoCacheFile){ if (MiniFileMgr$3.isLocalNativeFile(sourceUrl)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=sourceUrl; if(tempStr !="" && (sourceUrl.indexOf("http://")!=-1 || sourceUrl.indexOf("https://")!=-1)) fileNativeUrl=sourceUrl.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } }else{ var fileObj=MiniFileMgr$3.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$3.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=encodeURI(sourceUrl); } } this._sound.src=this.url=fileNativeUrl; }else{ this._sound.src=sourceUrl; } }else{ this.event(/*laya.events.Event.ERROR*/"error"); } } /** *@private *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); if(!this.url)return null; var channel=new MiniSoundChannel$3(this); channel.url=this.url; channel.loops=loops; channel.loop=(loops===0 ? true :false); channel.startTime=startTime; channel.play(); SoundManager.addChannel(channel); return channel; } /** *@private *释放声音资源。 * */ __proto.dispose=function(){ if (this._sound){ this._sound.destroy(); this._sound=null; this.readyUrl=this.url=null; } } /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ return this._sound.duration; }); MiniSound._createSound=function(){ if(MiniSound._audioCache.length){ return MiniSound._audioCache.pop(); }else{ MiniSound._id++; return QGMiniAdapter.window.qg.createInnerAudioContext(); } } MiniSound._id=0; MiniSound._audioCache=[]; return MiniSound; })(EventDispatcher) /**@private **/ //class laya.qg.mini.MiniSoundChannel extends laya.media.SoundChannel var MiniSoundChannel$3=(function(_super){ function MiniSoundChannel(miniSound){ /**@private **/ this._audio=null; /**@private **/ this._onEnd=null; this._onCanplay=null; this._onError=null; /**@private **/ this._miniSound=null; MiniSoundChannel.__super.call(this); this._audio=miniSound._sound; this._miniSound=miniSound; this._onEnd=MiniSoundChannel.bindToThis(this.__onEnd,this); this._onCanplay=MiniSoundChannel.bindToThis(this.onCanPlay,this); this._onError=MiniSoundChannel.bindToThis(this.onError,this); this.addEventListener(); } __class(MiniSoundChannel,'laya.qg.mini.MiniSoundChannel',_super,'MiniSoundChannel$3'); var __proto=MiniSoundChannel.prototype; __proto.addEventListener=function(){ this._audio.onError(this._onError); this._audio.onCanplay(this._onCanplay); } //_audio.onEnded(_onEnd); __proto.offEventListener=function(){ this._audio.offError(this._onError); this._audio.offCanplay(this._onCanplay); this._audio.offEnded(this._onEnd); } /**@private **/ __proto.onError=function(error){ console.log("-----1---------------minisound-----url:",this.url); this.event(/*laya.events.Event.ERROR*/"error",[error]); if(!this._audio)return; this._miniSound.dispose(); this.offEventListener(); this._audio=this._miniSound=null; } /**@private **/ __proto.onCanPlay=function(){ if(!this._audio)return; this.event(/*laya.events.Event.COMPLETE*/"complete"); this.offEventListener(); this._audio.onEnded(this._onEnd); if (!this.isStopped){ this.play() }else{ this.stop(); } } /**@private **/ __proto.__onEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); if(!this._audio || !this._audio.src)return; this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ _super.prototype.stop.call(this); this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.stop(); if (!this.loop){ this.offEventListener(); this._miniSound.dispose(); this._miniSound=null; this._audio=null; } } /**@private **/ __proto.pause=function(){ this.isStopped=true; if(!this._audio)return; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',function(){ if(!this._audio)return 0; return this._audio.startTime; },function(time){ if(!this._audio)return; this._audio.startTime=time; }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ if(!this._audio)return false; return this._audio.autoplay; },function(value){ if(!this._audio)return; this._audio.autoplay=value; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ if(!this._audio)return false; return this._audio.loop; },function(value){ if(!this._audio)return; this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.tbmini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Config=Laya.Config,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,ResourceVersion=laya.net.ResourceVersion; var RunDriver=laya.utils.RunDriver,SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager; var URL=laya.net.URL,Utils=laya.utils.Utils; /**@private **/ //class laya.tb.mini.MiniFileMgr var MiniFileMgr$10=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.tb.mini.MiniFileMgr',null,'MiniFileMgr$10'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=TBMiniAdapter.nativefiles.length;i=totalSize)){ if(data.size > TBMiniAdapter.minClearSize) TBMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > TBMiniAdapter.minClearSize) TBMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=TBMiniAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.tb.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i *
  • 1.0 正常速度
  • *
  • 0.5 半速(更慢)
  • *
  • 2.0 倍速(更快)
  • *
  • -1.0 向后,正常速度
  • *
  • -0.5 向后,半速
  • * *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ if(!this.videoElement) return 0; return this.videoElement.playbackRate; },function(value){ if(!this.videoElement) return; this.videoElement.playbackRate=value; }); __getset(0,__proto,'x',function(){ if(!this.videoElement) return 0; return this.videoElement.x; },function(value){ if(!this.videoElement) return; this.videoElement.x=value; }); __getset(0,__proto,'y',function(){ if(!this.videoElement) return 0; return this.videoElement.y; },function(value){ if(!this.videoElement) return; this.videoElement.y=value; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.src; }); MiniVideo.__init__=function(){ /*__JS__ */laya.device.media.Video=MiniVideo; } return MiniVideo; })() //class laya.tb.mini.TBMiniAdapter var TBMiniAdapter=(function(){ function TBMiniAdapter(){} __class(TBMiniAdapter,'laya.tb.mini.TBMiniAdapter'); TBMiniAdapter.getJson=function(data){ return JSON.parse(data); } TBMiniAdapter.init=function(){ if (TBMiniAdapter._inited)return; TBMiniAdapter._inited=true; TBMiniAdapter.window=/*__JS__ */window; var u=TBMiniAdapter.window.navigator.userAgent; if(!(u.indexOf('TB')>-1 || u.indexOf('Taobao')>-1 || u.indexOf('TM/')>-1)) return; TBMiniAdapter.EnvConfig={}; MiniFileMgr$10.setNativeFileDir("/layaairGame"); MiniFileMgr$10.existDir(MiniFileMgr$10.fileNativeDir,Handler.create(TBMiniAdapter,TBMiniAdapter.onMkdirCallBack)); TBMiniAdapter.systemInfo=TBMiniAdapter.window.my.getSystemInfoSync(); TBMiniAdapter.window.focus=function (){ }; Laya['_getUrlPath']=function (){ }; Laya['getUrlPath']=function (){ }; TBMiniAdapter.window.logtime=function (str){ }; TBMiniAdapter.window.alertTimeLog=function (str){ }; TBMiniAdapter.window.resetShareInfo=function (){ }; TBMiniAdapter._preCreateElement=Browser.createElement; Browser["createElement"]=TBMiniAdapter.createElement; TBMiniAdapter.window.CanvasRenderingContext2D=function (){}; TBMiniAdapter.window.CanvasRenderingContext2D.prototype=TBMiniAdapter._preCreateElement('canvas').getContext('2d').__proto__; TBMiniAdapter.window.document.body.appendChild=function (){ }; RunDriver.createShaderCondition=TBMiniAdapter.createShaderCondition; Utils['parseXMLFromString']=TBMiniAdapter.parseXMLFromString; Input['_createInputElement']=MiniInput$10['_createInputElement']; TBMiniAdapter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader$10.prototype.load; Loader.prototype._loadImage=MiniImage$10.prototype._loadImage; LocalStorage._baseClass=MiniLocalStorage$9; MiniLocalStorage$9.__init__(); Config.useRetinalCanvas=true; } TBMiniAdapter.measureText=function(str){ var tempObj=TBMiniAdapter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } TBMiniAdapter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return ""; return "utf8"; } TBMiniAdapter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr$10.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr$10.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } TBMiniAdapter.remove=function(fileUrl,callBack){ MiniFileMgr$10.deleteFile("",fileUrl,callBack,"",0); } TBMiniAdapter.removeAll=function(){ MiniFileMgr$10.deleteAll(); } TBMiniAdapter.hasNativeFile=function(fileUrl){ return MiniFileMgr$10.isLocalNativeFile(fileUrl); } TBMiniAdapter.getFileInfo=function(fileUrl){ return MiniFileMgr$10.getFileInfo(fileUrl); } TBMiniAdapter.getFileList=function(){ return MiniFileMgr$10.filesListObj; } TBMiniAdapter.exitMiniProgram=function(){ TBMiniAdapter.window.my.exitMiniProgram(); } TBMiniAdapter.onMkdirCallBack=function(errorCode,data){ if (!errorCode){ MiniFileMgr$10.filesListObj=JSON.parse(data.data); MiniFileMgr$10.fakeObj=JSON.parse(data.data); } } TBMiniAdapter.pixelRatio=function(){ if (!TBMiniAdapter.EnvConfig.pixelRatioInt){ try { TBMiniAdapter.EnvConfig.pixelRatioInt=TBMiniAdapter.systemInfo.pixelRatio; return TBMiniAdapter.systemInfo.pixelRatio; }catch (error){} } return TBMiniAdapter.EnvConfig.pixelRatioInt; } TBMiniAdapter.createElement=function(type){ if (type=="canvas"){ var _source; if (TBMiniAdapter.idx==1){ _source=TBMiniAdapter.window.canvas.getRealCanvas(); }else { _source=TBMiniAdapter._preCreateElement(type); } (!_source.style)&& (_source.style={}); TBMiniAdapter.idx++; return _source; }else if (type=="textarea" || type=="input"){ return TBMiniAdapter.onCreateInput(type); }else if (type=="div"){ var node=TBMiniAdapter._preCreateElement(type); node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } else { return TBMiniAdapter._preCreateElement(type); } } TBMiniAdapter.onCreateInput=function(type){ var node=TBMiniAdapter._preCreateElement(type); node.focus=MiniInput$10.wxinputFocus; node.blur=MiniInput$10.wxinputblur; node.value=0; node.placeholder={}; node.type={}; node.setColor=function (value){ }; node.setType=function (value){ }; node.setFontFace=function (value){ }; node.contains=function (value){ return null }; return node; } TBMiniAdapter.createShaderCondition=function(conditionScript){ var _$this=this; var func=function (){ var abc=conditionScript; return _$this[conditionScript.replace("this.","")]; } return func; } TBMiniAdapter.EnvConfig=null; TBMiniAdapter.window=null; TBMiniAdapter._preCreateElement=null; TBMiniAdapter._inited=false; TBMiniAdapter.systemInfo=null; TBMiniAdapter.isPosMsgYu=false; TBMiniAdapter.autoCacheFile=true; TBMiniAdapter.minClearSize=(5 *1024 *1024); TBMiniAdapter.subNativeFiles={}; TBMiniAdapter.subNativeheads=[]; TBMiniAdapter.subMaps=[]; TBMiniAdapter.AutoCacheDownFile=false; TBMiniAdapter.baseDir="pages/index/"; TBMiniAdapter._measureText=null; TBMiniAdapter.parseXMLFromString=function(value){ var rst; var Parser; value=value.replace(/>\s+<'); try { /*__JS__ */rst=(new window.Parser.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } TBMiniAdapter.idx=1; __static(TBMiniAdapter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir"];} ]); return TBMiniAdapter; })() /**@private **/ //class laya.tb.mini.MiniAccelerator extends laya.events.EventDispatcher var MiniAccelerator$10=(function(_super){ function MiniAccelerator(){ MiniAccelerator.__super.call(this); } __class(MiniAccelerator,'laya.tb.mini.MiniAccelerator',_super,'MiniAccelerator$10'); var __proto=MiniAccelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); MiniAccelerator.startListen(this["onDeviceOrientationChange"]); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) MiniAccelerator.stopListen(); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } MiniAccelerator.__init__=function(){ try{ var Acc; Acc=/*__JS__ */laya.device.motion.Accelerator; if (!Acc)return; Acc["prototype"]["on"]=MiniAccelerator["prototype"]["on"]; Acc["prototype"]["off"]=MiniAccelerator["prototype"]["off"]; }catch (e){ } } MiniAccelerator.startListen=function(callBack){ MiniAccelerator._callBack=callBack; if (MiniAccelerator._isListening)return; MiniAccelerator._isListening=true; try{ TBMiniAdapter.window.my.onAccelerometerChange(laya.tb.mini.MiniAccelerator.onAccelerometerChange); }catch(e){} } MiniAccelerator.stopListen=function(){ MiniAccelerator._isListening=false; try{ TBMiniAdapter.window.my.stopAccelerometer({}); }catch(e){} } MiniAccelerator.onAccelerometerChange=function(res){ var e; e={}; e.acceleration=res; e.accelerationIncludingGravity=res; e.rotationRate={}; if (MiniAccelerator._callBack !=null){ MiniAccelerator._callBack(e); } } MiniAccelerator._isListening=false; MiniAccelerator._callBack=null; return MiniAccelerator; })(EventDispatcher) /**@private **/ //class laya.tb.mini.MiniLoader extends laya.events.EventDispatcher var MiniLoader$10=(function(_super){ function MiniLoader(){ MiniLoader.__super.call(this); } __class(MiniLoader,'laya.tb.mini.MiniLoader',_super,'MiniLoader$10'); var __proto=MiniLoader.prototype; /** *@private *@param url *@param type *@param cache *@param group *@param ignoreCache */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); var thisLoader=this; thisLoader._url=url; if (url.indexOf("data:image")===0)thisLoader._type=type=/*laya.net.Loader.IMAGE*/"image"; else { thisLoader._type=type || (type=thisLoader.getTypeFromUrl(url)); } thisLoader._cache=cache; thisLoader._data=null; if (!ignoreCache && Loader.loadedMap[URL.formatURL(url)]){ thisLoader._data=Loader.loadedMap[URL.formatURL(url)]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",thisLoader._data); return; } if (Loader.parserMap[type] !=null){ thisLoader._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; } if (MiniFileMgr$10.isLocalNativeFile(url)&& !MiniFileMgr$10.getFileInfo(url)){ if (TBMiniAdapter.subNativeFiles && TBMiniAdapter.subNativeheads.length==0){ for (var key in TBMiniAdapter.subNativeFiles){ var tempArr=TBMiniAdapter.subNativeFiles[key]; TBMiniAdapter.subNativeheads=TBMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ TBMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(TBMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && TBMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=TBMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } }; var encoding=TBMiniAdapter.getUrlEncode(url,type); var urlType=Utils.getFileExtension(url); if ((MiniLoader._fileTypeArr.indexOf(urlType)!=-1)|| type==/*laya.net.Loader.IMAGE*/"image"){ TBMiniAdapter.EnvConfig.load.call(this,url,type,cache,group,ignoreCache); }else { if (!MiniFileMgr$10.getFileInfo(url)){ if (MiniFileMgr$10.isLocalNativeFile(url)){ if (MiniFileMgr$10.isSubNativeFile(url)){ MiniFileMgr$10.readFile(ResourceVersion.addVersionPrefix(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); }else MiniFileMgr$10.readFile(TBMiniAdapter.baseDir+ResourceVersion.addVersionPrefix(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); }else{ var tempUrl=url; var tempurl=URL.formatURL(url); fileObj=MiniFileMgr$10.getFileInfo(url); if(fileObj){ fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; MiniFileMgr$10.readFile(fileObj.url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); } else{ url=URL.formatURL(url); if(type !=/*laya.net.Loader.IMAGE*/"image" && ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1))){ MiniFileMgr$10.readFile(TBMiniAdapter.baseDir+url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else{ MiniFileMgr$10.downFiles(encodeURI(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url,TBMiniAdapter.AutoCacheDownFile); } } } }else { var fileObj=MiniFileMgr$10.getFileInfo(URL.formatURL(url)); fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; var nativepath=MiniFileMgr$10.getFileNativePath(fileObj.md5); MiniFileMgr$10.readFile(nativepath,fileObj.encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); } } } MiniLoader.onReadNativeCallBack=function(encoding,url,type,cache,group,ignoreCache,thisLoader,errorCode,data){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); (errorCode===void 0)&& (errorCode=0); if (!errorCode){ var tempData; if (type==/*laya.net.Loader.JSON*/"json" || type==/*laya.net.Loader.ATLAS*/"atlas"){ tempData=TBMiniAdapter.getJson(data.data); }else if (type==/*laya.net.Loader.XML*/"xml"){ tempData=Utils.parseXMLFromString(data.data); }else { tempData=data.data; } thisLoader.onLoaded(tempData); }else if (errorCode==1){ thisLoader.onError && thisLoader.onError(data); } } __static(MiniLoader, ['_fileTypeArr',function(){return this._fileTypeArr=['png','jpg','bmp','jpeg','gif'];} ]); return MiniLoader; })(EventDispatcher) /**@private **/ //class laya.tb.mini.MiniSound extends laya.events.EventDispatcher var MiniSound$10=(function(_super){ function MiniSound(){ /**@private **/ this._sound=null; /** *@private *声音URL */ this.url=null; /** *@private *是否已加载完成 */ this.loaded=false; /**@private **/ this.readyUrl=null; MiniSound.__super.call(this); this._sound=MiniSound._createSound(); } __class(MiniSound,'laya.tb.mini.MiniSound',_super,'MiniSound$10'); var __proto=MiniSound.prototype; /** *@private *加载声音。 *@param url 地址。 * */ __proto.load=function(url){ if (!MiniFileMgr$10.isLocalNativeFile(url)){ url=URL.formatURL(url); }else{ if (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1){ if(MiniFileMgr$10.loadPath !=""){ url=url.split(MiniFileMgr$10.loadPath)[1]; }else{ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; if(tempStr !="") url=url.split(tempStr)[1]; } } } this.url=url; this.readyUrl=url; if(TBMiniAdapter.autoCacheFile&&MiniFileMgr$10.getFileInfo(url)){ this.onDownLoadCallBack(url,0); }else{ if(!TBMiniAdapter.autoCacheFile){ this.onDownLoadCallBack(url,0); }else{ if (MiniFileMgr$10.isLocalNativeFile(url)){ tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="") url=url.split(tempStr)[1]; if (!url){ url=tempUrl; } if (TBMiniAdapter.subNativeFiles && TBMiniAdapter.subNativeheads.length==0){ for (var key in TBMiniAdapter.subNativeFiles){ var tempArr=TBMiniAdapter.subNativeFiles[key]; TBMiniAdapter.subNativeheads=TBMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ TBMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(TBMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && TBMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=TBMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } this.onDownLoadCallBack(url,0); }else{ if ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1) || url.indexOf(TBMiniAdapter.window.my.env.USER_DATA_PATH)!=-1){ this.onDownLoadCallBack(url,0); }else{ MiniFileMgr$10.downOtherFiles(url,Handler.create(this,this.onDownLoadCallBack,[url]),url,TBMiniAdapter.autoCacheFile); } } } } } /**@private **/ __proto.onDownLoadCallBack=function(sourceUrl,errorCode,tempFilePath){ (tempFilePath===void 0)&& (tempFilePath=""); if (!errorCode && this._sound){ var fileNativeUrl; if(TBMiniAdapter.autoCacheFile){ if(tempFilePath==""){ if (MiniFileMgr$10.isLocalNativeFile(sourceUrl)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL._basePath; var tempUrl=sourceUrl; if(tempStr !="" && (sourceUrl.indexOf("http://")!=-1 || sourceUrl.indexOf("https://")!=-1)) fileNativeUrl=sourceUrl.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } if (MiniFileMgr$10.isSubNativeFile(fileNativeUrl)){ fileNativeUrl=fileNativeUrl; }else fileNativeUrl=TBMiniAdapter.baseDir+fileNativeUrl; }else{ var fileObj=MiniFileMgr$10.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$10.getFileNativePath(fileMd5Name); }else{ if (sourceUrl.indexOf("http://")==-1 && sourceUrl.indexOf("https://")==-1 && sourceUrl.indexOf(TBMiniAdapter.window.my.env.USER_DATA_PATH)==-1){ fileNativeUrl=TBMiniAdapter.baseDir+sourceUrl; }else { fileNativeUrl=sourceUrl; } } } }else{ fileNativeUrl=tempFilePath; } this._sound.src=this.url=fileNativeUrl; }else{ if((MiniFileMgr$10.isLocalNativeFile(sourceUrl)&& !MiniFileMgr$10.isSubNativeFile(sourceUrl))|| ( sourceUrl.indexOf("http://")==-1 &&sourceUrl.indexOf("https://")==-1 &&sourceUrl.indexOf(TBMiniAdapter.window.my.env.USER_DATA_PATH)==-1)){ sourceUrl=TBMiniAdapter.baseDir+sourceUrl; } this._sound.src=sourceUrl; } }else{ this.event(/*laya.events.Event.ERROR*/"error"); } } /** *@private *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); if(!this.url)return null; var channel=new MiniSoundChannel$10(this); channel.url=this.url; channel.loops=loops; channel.loop=(loops===0 ? true :false); channel.startTime=startTime; channel.isStopped=false; SoundManager.addChannel(channel); return channel; } /** *@private *释放声音资源。 * */ __proto.dispose=function(){ if (this._sound){ this._sound.src=""; MiniSound._audioCache.push(this._sound); this._sound=null; this.readyUrl=this.url=null; } } /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ return this._sound.duration; }); MiniSound._createSound=function(){ if(MiniSound._audioCache.length){ return MiniSound._audioCache.pop(); }else{ MiniSound._id++; return TBMiniAdapter.window.my.createInnerAudioContext(); } } MiniSound._id=0; MiniSound._audioCache=[]; return MiniSound; })(EventDispatcher) /**@private **/ //class laya.tb.mini.MiniSoundChannel extends laya.media.SoundChannel var MiniSoundChannel$10=(function(_super){ function MiniSoundChannel(miniSound){ /**@private **/ this._audio=null; /**@private **/ this._onEnd=null; this._onCanplay=null; this._onError=null; /**@private **/ this._miniSound=null; MiniSoundChannel.__super.call(this); this._audio=miniSound._sound; this._miniSound=miniSound; this._onEnd=MiniSoundChannel.bindToThis(this.__onEnd,this); this._onCanplay=MiniSoundChannel.bindToThis(this.onCanPlay,this); this._onError=MiniSoundChannel.bindToThis(this.onError,this); this.addEventListener(); } __class(MiniSoundChannel,'laya.tb.mini.MiniSoundChannel',_super,'MiniSoundChannel$10'); var __proto=MiniSoundChannel.prototype; __proto.addEventListener=function(){ this._audio.onError(this._onError); this._audio.onCanplay(this._onCanplay); } //_audio.onEnded(_onEnd); __proto.offEventListener=function(){ this._audio.offError(this._onError); this._audio.offCanplay(this._onCanplay); this._audio.offEnded(this._onEnd); } /**@private **/ __proto.onError=function(error){ console.log("-----1---------------minisound-----url:",this.url); console.log(error); this.event(/*laya.events.Event.ERROR*/"error"); if(!this._audio)return; this._miniSound.dispose(); this.offEventListener(); this._audio=this._miniSound=null; } /**@private **/ __proto.onCanPlay=function(){ if(!this._audio)return; this.event(/*laya.events.Event.COMPLETE*/"complete"); this.offEventListener(); this._audio.onEnded(this._onEnd); if (!this.isStopped){ this.play() }else{ this.stop(); } } /**@private **/ __proto.__onEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); if(!this._audio)return; this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ _super.prototype.stop.call(this); this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.stop(); if (!this.loop){ this.offEventListener(); this._miniSound.dispose(); this._miniSound=null; this._audio=null; } } /**@private **/ __proto.pause=function(){ this.isStopped=true; if(!this._audio)return; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',function(){ if(!this._audio)return 0; return this._audio.startTime; },function(time){ if(!this._audio)return; this._audio.startTime=time; }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ if(!this._audio)return false; return this._audio.autoplay; },function(value){ if(!this._audio)return; this._audio.autoplay=value; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ if(!this._audio)return false; return this._audio.loop; },function(value){ if(!this._audio)return; this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.tbplugin.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Config=Laya.Config,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,ResourceVersion=laya.net.ResourceVersion; var RunDriver=laya.utils.RunDriver,SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager; var URL=laya.net.URL,Utils=laya.utils.Utils; /**@private **/ //class laya.tbplugin.mini.MiniFileMgr var MiniFileMgr$11=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.tbplugin.mini.MiniFileMgr',null,'MiniFileMgr$11'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=TBPluginAdapter.nativefiles.length;i=totalSize)){ if(data.size > TBPluginAdapter.minClearSize) TBPluginAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > TBPluginAdapter.minClearSize) TBPluginAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=TBPluginAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.tbplugin.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i *
  • 1.0 正常速度
  • *
  • 0.5 半速(更慢)
  • *
  • 2.0 倍速(更快)
  • *
  • -1.0 向后,正常速度
  • *
  • -0.5 向后,半速
  • * *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ if(!this.videoElement) return 0; return this.videoElement.playbackRate; },function(value){ if(!this.videoElement) return; this.videoElement.playbackRate=value; }); __getset(0,__proto,'x',function(){ if(!this.videoElement) return 0; return this.videoElement.x; },function(value){ if(!this.videoElement) return; this.videoElement.x=value; }); __getset(0,__proto,'y',function(){ if(!this.videoElement) return 0; return this.videoElement.y; },function(value){ if(!this.videoElement) return; this.videoElement.y=value; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.src; }); MiniVideo.__init__=function(){ /*__JS__ */laya.device.media.Video=MiniVideo; } return MiniVideo; })() //class laya.tbplugin.mini.TBPluginAdapter var TBPluginAdapter=(function(){ function TBPluginAdapter(){} __class(TBPluginAdapter,'laya.tbplugin.mini.TBPluginAdapter'); TBPluginAdapter.getJson=function(data){ return JSON.parse(data); } TBPluginAdapter.init=function(){ if (TBPluginAdapter._inited)return; TBPluginAdapter._inited=true; TBPluginAdapter.window=/*__JS__ */window; var u=TBPluginAdapter.window.navigator.userAgent; if(!(u.indexOf('TB')>-1 || u.indexOf('Taobao')>-1 || u.indexOf('TM/')>-1)) return; TBPluginAdapter.EnvConfig={}; MiniFileMgr$11.setNativeFileDir("/layaairGame"); MiniFileMgr$11.existDir(MiniFileMgr$11.fileNativeDir,Handler.create(TBPluginAdapter,TBPluginAdapter.onMkdirCallBack)); TBPluginAdapter.systemInfo=TBPluginAdapter.window.my.getSystemInfoSync(); TBPluginAdapter.window.focus=function (){ }; Laya['_getUrlPath']=function (){ }; Laya['getUrlPath']=function (){ }; TBPluginAdapter.window.logtime=function (str){ }; TBPluginAdapter.window.alertTimeLog=function (str){ }; TBPluginAdapter.window.resetShareInfo=function (){ }; TBPluginAdapter._preCreateElement=Browser.createElement; Browser["createElement"]=TBPluginAdapter.createElement; TBPluginAdapter.window.CanvasRenderingContext2D=function (){}; TBPluginAdapter.window.CanvasRenderingContext2D.prototype=TBPluginAdapter._preCreateElement('canvas').getContext('2d').__proto__; TBPluginAdapter.window.document.body.appendChild=function (){ }; RunDriver.createShaderCondition=TBPluginAdapter.createShaderCondition; Utils['parseXMLFromString']=TBPluginAdapter.parseXMLFromString; Input['_createInputElement']=MiniInput$11['_createInputElement']; TBPluginAdapter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader$11.prototype.load; Loader.prototype._loadImage=MiniImage$11.prototype._loadImage; LocalStorage._baseClass=MiniLocalStorage$10; MiniLocalStorage$10.__init__(); Config.useRetinalCanvas=true; } TBPluginAdapter.measureText=function(str){ var tempObj=TBPluginAdapter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } TBPluginAdapter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return ""; return "utf8"; } TBPluginAdapter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr$11.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr$11.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } TBPluginAdapter.remove=function(fileUrl,callBack){ MiniFileMgr$11.deleteFile("",fileUrl,callBack,"",0); } TBPluginAdapter.removeAll=function(){ MiniFileMgr$11.deleteAll(); } TBPluginAdapter.hasNativeFile=function(fileUrl){ return MiniFileMgr$11.isLocalNativeFile(fileUrl); } TBPluginAdapter.getFileInfo=function(fileUrl){ return MiniFileMgr$11.getFileInfo(fileUrl); } TBPluginAdapter.getFileList=function(){ return MiniFileMgr$11.filesListObj; } TBPluginAdapter.exitMiniProgram=function(){ TBPluginAdapter.window.my.exitMiniProgram(); } TBPluginAdapter.onMkdirCallBack=function(errorCode,data){ if (!errorCode){ MiniFileMgr$11.filesListObj=JSON.parse(data.data); MiniFileMgr$11.fakeObj=JSON.parse(data.data); } } TBPluginAdapter.pixelRatio=function(){ if (!TBPluginAdapter.EnvConfig.pixelRatioInt){ try { TBPluginAdapter.EnvConfig.pixelRatioInt=TBPluginAdapter.systemInfo.pixelRatio; return TBPluginAdapter.systemInfo.pixelRatio; }catch (error){} } return TBPluginAdapter.EnvConfig.pixelRatioInt; } TBPluginAdapter.createElement=function(type){ if (type=="canvas"){ var _source; if (TBPluginAdapter.idx==1){ _source=TBPluginAdapter.window.canvas.getRealCanvas(); if(!TBPluginAdapter.window.my.isIDE){ var originfun=_source.getContext; _source.getContext=function (type){ var gl=originfun.apply(_source,[type]); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false); return gl; } } }else { _source=TBPluginAdapter._preCreateElement(type); } (!_source.style)&& (_source.style={}); TBPluginAdapter.idx++; return _source; }else if (type=="textarea" || type=="input"){ return TBPluginAdapter.onCreateInput(type); }else if (type=="div"){ var node=TBPluginAdapter._preCreateElement(type); node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } else { return TBPluginAdapter._preCreateElement(type); } } TBPluginAdapter.onCreateInput=function(type){ var node=TBPluginAdapter._preCreateElement(type); node.focus=MiniInput$11.wxinputFocus; node.blur=MiniInput$11.wxinputblur; node.value=0; node.placeholder={}; node.type={}; node.setColor=function (value){ }; node.setType=function (value){ }; node.setFontFace=function (value){ }; node.contains=function (value){ return null }; return node; } TBPluginAdapter.createShaderCondition=function(conditionScript){ var _$this=this; var func=function (){ var abc=conditionScript; return _$this[conditionScript.replace("this.","")]; } return func; } TBPluginAdapter.EnvConfig=null; TBPluginAdapter.window=null; TBPluginAdapter._preCreateElement=null; TBPluginAdapter._inited=false; TBPluginAdapter.systemInfo=null; TBPluginAdapter.isPosMsgYu=false; TBPluginAdapter.autoCacheFile=false; TBPluginAdapter.minClearSize=(5 *1024 *1024); TBPluginAdapter.AutoCacheDownFile=false; TBPluginAdapter.baseDir="component/"; TBPluginAdapter._measureText=null; TBPluginAdapter.parseXMLFromString=function(value){ var rst; var Parser; value=value.replace(/>\s+<'); try { /*__JS__ */rst=(new window.Parser.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } TBPluginAdapter.idx=1; __static(TBPluginAdapter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir"];} ]); return TBPluginAdapter; })() /**@private **/ //class laya.tbplugin.mini.MiniAccelerator extends laya.events.EventDispatcher var MiniAccelerator$11=(function(_super){ function MiniAccelerator(){ MiniAccelerator.__super.call(this); } __class(MiniAccelerator,'laya.tbplugin.mini.MiniAccelerator',_super,'MiniAccelerator$11'); var __proto=MiniAccelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); MiniAccelerator.startListen(this["onDeviceOrientationChange"]); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) MiniAccelerator.stopListen(); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } MiniAccelerator.__init__=function(){ try{ var Acc; Acc=/*__JS__ */laya.device.motion.Accelerator; if (!Acc)return; Acc["prototype"]["on"]=MiniAccelerator["prototype"]["on"]; Acc["prototype"]["off"]=MiniAccelerator["prototype"]["off"]; }catch (e){ } } MiniAccelerator.startListen=function(callBack){ MiniAccelerator._callBack=callBack; if (MiniAccelerator._isListening)return; MiniAccelerator._isListening=true; try{ TBPluginAdapter.window.my.onAccelerometerChange(laya.tbplugin.mini.MiniAccelerator.onAccelerometerChange); }catch(e){} } MiniAccelerator.stopListen=function(){ MiniAccelerator._isListening=false; try{ TBPluginAdapter.window.my.stopAccelerometer({}); }catch(e){} } MiniAccelerator.onAccelerometerChange=function(res){ var e; e={}; e.acceleration=res; e.accelerationIncludingGravity=res; e.rotationRate={}; if (MiniAccelerator._callBack !=null){ MiniAccelerator._callBack(e); } } MiniAccelerator._isListening=false; MiniAccelerator._callBack=null; return MiniAccelerator; })(EventDispatcher) /**@private **/ //class laya.tbplugin.mini.MiniLoader extends laya.events.EventDispatcher var MiniLoader$11=(function(_super){ function MiniLoader(){ MiniLoader.__super.call(this); } __class(MiniLoader,'laya.tbplugin.mini.MiniLoader',_super,'MiniLoader$11'); var __proto=MiniLoader.prototype; /** *@private *@param url *@param type *@param cache *@param group *@param ignoreCache */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); var thisLoader=this; thisLoader._url=url; if (url.indexOf("data:image")===0)thisLoader._type=type=/*laya.net.Loader.IMAGE*/"image"; else { thisLoader._type=type || (type=thisLoader.getTypeFromUrl(url)); } thisLoader._cache=cache; thisLoader._data=null; if (!ignoreCache && Loader.loadedMap[URL.formatURL(url)]){ thisLoader._data=Loader.loadedMap[URL.formatURL(url)]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",thisLoader._data); return; } if (Loader.parserMap[type] !=null){ thisLoader._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; }; var encoding=TBPluginAdapter.getUrlEncode(url,type); var urlType=Utils.getFileExtension(url); if ((MiniLoader._fileTypeArr.indexOf(urlType)!=-1)|| type==/*laya.net.Loader.IMAGE*/"image"){ TBPluginAdapter.EnvConfig.load.call(this,url,type,cache,group,ignoreCache); }else { if (!MiniFileMgr$11.getFileInfo(url)){ if (MiniFileMgr$11.isLocalNativeFile(url)){ if (TBPluginAdapter.subNativeFiles && TBPluginAdapter.subNativeheads.length==0){ for (var key in TBPluginAdapter.subNativeFiles){ var tempArr=TBPluginAdapter.subNativeFiles[key]; TBPluginAdapter.subNativeheads=TBPluginAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ TBPluginAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(TBPluginAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && TBPluginAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=TBPluginAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } MiniFileMgr$11.readFile(TBPluginAdapter.baseDir+ResourceVersion.addVersionPrefix(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); return; }; var tempUrl=url; var tempurl=URL.formatURL(url); fileObj=MiniFileMgr$11.getFileInfo(url); if(fileObj){ fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; MiniFileMgr$11.readFile(fileObj.url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else if (thisLoader.type=="image" || thisLoader.type=="htmlimage"){ TBPluginAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } else{ url=URL.formatURL(url); if(type !=/*laya.net.Loader.IMAGE*/"image" && ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1)|| MiniFileMgr$11.isLocalNativeFile(url))){ MiniFileMgr$11.readFile(TBPluginAdapter.baseDir+url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else{ MiniFileMgr$11.downFiles(encodeURI(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url,TBPluginAdapter.AutoCacheDownFile); } } }else { var fileObj=MiniFileMgr$11.getFileInfo(URL.formatURL(url)); fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; var nativepath=MiniFileMgr$11.getFileNativePath(fileObj.md5); MiniFileMgr$11.readFile(nativepath,fileObj.encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); } } } MiniLoader.onReadNativeCallBack=function(encoding,url,type,cache,group,ignoreCache,thisLoader,errorCode,data){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); (errorCode===void 0)&& (errorCode=0); if (!errorCode){ var tempData; if (type==/*laya.net.Loader.JSON*/"json" || type==/*laya.net.Loader.ATLAS*/"atlas"){ tempData=TBPluginAdapter.getJson(data.data); }else if (type==/*laya.net.Loader.XML*/"xml"){ tempData=Utils.parseXMLFromString(data.data); }else { tempData=data.data; } thisLoader.onLoaded(tempData); }else if (errorCode==1){ thisLoader.onError && thisLoader.onError(data); } } __static(MiniLoader, ['_fileTypeArr',function(){return this._fileTypeArr=['png','jpg','bmp','jpeg','gif'];} ]); return MiniLoader; })(EventDispatcher) /**@private **/ //class laya.tbplugin.mini.MiniSound extends laya.events.EventDispatcher var MiniSound$11=(function(_super){ function MiniSound(){ /**@private **/ this._sound=null; /** *@private *声音URL */ this.url=null; /** *@private *是否已加载完成 */ this.loaded=false; /**@private **/ this.readyUrl=null; MiniSound.__super.call(this); this._sound=MiniSound._createSound(); } __class(MiniSound,'laya.tbplugin.mini.MiniSound',_super,'MiniSound$11'); var __proto=MiniSound.prototype; /** *@private *加载声音。 *@param url 地址。 * */ __proto.load=function(url){ this.event(/*laya.events.Event.ERROR*/"error","Not support play sound"); return; if (!MiniFileMgr$11.isLocalNativeFile(url)){ url=URL.formatURL(url); }else{ if (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1){ if(MiniFileMgr$11.loadPath !=""){ url=url.split(MiniFileMgr$11.loadPath)[1]; }else{ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; if(tempStr !="") url=url.split(tempStr)[1]; } } } this.url=url; this.readyUrl=url; if(TBPluginAdapter.autoCacheFile&&MiniFileMgr$11.getFileInfo(url)){ this.onDownLoadCallBack(url,0); }else{ if(!TBPluginAdapter.autoCacheFile){ this.onDownLoadCallBack(url,0); }else{ if (MiniFileMgr$11.isLocalNativeFile(url)){ tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="") url=url.split(tempStr)[1]; if (!url){ url=tempUrl; } if (TBPluginAdapter.subNativeFiles && TBPluginAdapter.subNativeheads.length==0){ for (var key in TBPluginAdapter.subNativeFiles){ var tempArr=TBPluginAdapter.subNativeFiles[key]; TBPluginAdapter.subNativeheads=TBPluginAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ TBPluginAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(TBPluginAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && TBPluginAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=TBPluginAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } this.onDownLoadCallBack(url,0); }else{ if ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1) || url.indexOf(TBPluginAdapter.window.my.env.USER_DATA_PATH)!=-1){ this.onDownLoadCallBack(url,0); }else{ MiniFileMgr$11.downOtherFiles(url,Handler.create(this,this.onDownLoadCallBack,[url]),url,TBPluginAdapter.autoCacheFile); } } } } } /**@private **/ __proto.onDownLoadCallBack=function(sourceUrl,errorCode,tempFilePath){ (tempFilePath===void 0)&& (tempFilePath=""); if (!errorCode && this._sound){ var fileNativeUrl; if(TBPluginAdapter.autoCacheFile){ if(tempFilePath==""){ if (MiniFileMgr$11.isLocalNativeFile(sourceUrl)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL._basePath; var tempUrl=sourceUrl; if(tempStr !="" && (sourceUrl.indexOf("http://")!=-1 || sourceUrl.indexOf("https://")!=-1)) fileNativeUrl=sourceUrl.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } fileNativeUrl=TBPluginAdapter.baseDir+fileNativeUrl; }else{ var fileObj=MiniFileMgr$11.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$11.getFileNativePath(fileMd5Name); }else{ if (sourceUrl.indexOf("http://")==-1 && sourceUrl.indexOf("https://")==-1 && sourceUrl.indexOf(TBPluginAdapter.window.my.env.USER_DATA_PATH)==-1){ fileNativeUrl=TBPluginAdapter.baseDir+sourceUrl; }else { fileNativeUrl=sourceUrl; } } } }else{ fileNativeUrl=tempFilePath; } this._sound.src=this.url=fileNativeUrl; }else{ if(MiniFileMgr$11.isLocalNativeFile(sourceUrl)|| ( sourceUrl.indexOf("http://")==-1 &&sourceUrl.indexOf("https://")==-1 &&sourceUrl.indexOf(TBPluginAdapter.window.my.env.USER_DATA_PATH)==-1)){ sourceUrl=TBPluginAdapter.baseDir+sourceUrl; } this._sound.src=sourceUrl; } }else{ this.event(/*laya.events.Event.ERROR*/"error"); } } /** *@private *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); return null; var channel=new MiniSoundChannel$11(this); channel.url=this.url; channel.loops=loops; channel.loop=(loops===0 ? true :false); channel.startTime=startTime; channel.isStopped=false; SoundManager.addChannel(channel); return channel; } /** *@private *释放声音资源。 * */ __proto.dispose=function(){ if (this._sound){ this._sound.src=""; MiniSound._audioCache.push(this._sound); this._sound=null; this.readyUrl=this.url=null; } } /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ return this._sound.duration; }); MiniSound._createSound=function(){ return null; } MiniSound._id=0; MiniSound._audioCache=[]; return MiniSound; })(EventDispatcher) /**@private **/ //class laya.tbplugin.mini.MiniSoundChannel extends laya.media.SoundChannel var MiniSoundChannel$11=(function(_super){ function MiniSoundChannel(miniSound){ /**@private **/ this._audio=null; /**@private **/ this._onEnd=null; this._onCanplay=null; this._onError=null; /**@private **/ this._miniSound=null; MiniSoundChannel.__super.call(this); this._audio=miniSound._sound; this._miniSound=miniSound; this._onEnd=MiniSoundChannel.bindToThis(this.__onEnd,this); this._onCanplay=MiniSoundChannel.bindToThis(this.onCanPlay,this); this._onError=MiniSoundChannel.bindToThis(this.onError,this); this.addEventListener(); } __class(MiniSoundChannel,'laya.tbplugin.mini.MiniSoundChannel',_super,'MiniSoundChannel$11'); var __proto=MiniSoundChannel.prototype; __proto.addEventListener=function(){ this._audio.onError(this._onError); this._audio.onCanplay(this._onCanplay); } //_audio.onEnded(_onEnd); __proto.offEventListener=function(){ this._audio.offError(this._onError); this._audio.offCanplay(this._onCanplay); this._audio.offEnded(this._onEnd); } /**@private **/ __proto.onError=function(error){ console.log("-----1---------------minisound-----url:",this.url); console.log(error); this.event(/*laya.events.Event.ERROR*/"error"); if(!this._audio)return; this._miniSound.dispose(); this.offEventListener(); this._audio=this._miniSound=null; } /**@private **/ __proto.onCanPlay=function(){ if(!this._audio)return; this.event(/*laya.events.Event.COMPLETE*/"complete"); this.offEventListener(); this._audio.onEnded(this._onEnd); if (!this.isStopped){ this.play() }else{ this.stop(); } } /**@private **/ __proto.__onEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); if(!this._audio)return; this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ _super.prototype.stop.call(this); this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.stop(); if (!this.loop){ this.offEventListener(); this._miniSound.dispose(); this._miniSound=null; this._audio=null; } } /**@private **/ __proto.pause=function(){ this.isStopped=true; if(!this._audio)return; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',function(){ if(!this._audio)return 0; return this._audio.startTime; },function(time){ if(!this._audio)return; this._audio.startTime=time; }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ if(!this._audio)return false; return this._audio.autoplay; },function(value){ if(!this._audio)return; this._audio.autoplay=value; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ if(!this._audio)return false; return this._audio.loop; },function(value){ if(!this._audio)return; this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.tiledmap.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,HTMLCanvas=laya.resource.HTMLCanvas,Handler=laya.utils.Handler,Loader=laya.net.Loader; var Point=laya.maths.Point,Rectangle=laya.maths.Rectangle,Render=laya.renders.Render,RenderContext=laya.renders.RenderContext; var Sprite=laya.display.Sprite,Texture=laya.resource.Texture; /** *tiledMap是整个地图的核心 *地图以层级来划分地图(例如:地表层,植被层,建筑层) *每层又以分块(GridSprite)来处理显示对象,只显示在视口区域的区 *每块又包括N*N个格子(tile) *格子类型又分为动画格子跟图片格子两种 *@author ... */ //class laya.map.TiledMap var TiledMap=(function(){ var GRect,TileMapAniData,TileSet; function TiledMap(){ //json数据 this._jsonData=null; //存放地图中用到的所有子纹理数据 this._tileTexSetArr=[]; //主纹理数据,主要在释放纹理资源时使用 this._texArray=[]; //地图信息中的一些基本数据 this._x=0; //地图的坐标 this._y=0; //_height=_mapTileH *_mapH this._width=0; //地图的宽度 this._height=0; //地图的高度 this._mapW=0; //地图的横向格子数 this._mapH=0; //地图的竖向格子数 this._mapTileW=0; //tile的宽度 this._mapTileH=0; //地图的显示对象 this._mapSprite=null; //地图的显示对象 this._layerArray=[]; //这里保存所有的MapLayer对象 this._renderLayerArray=[]; //这里保存需要渲染的MapLayer对象 this._gridArray=[]; //地图块相关的 this._showGridKey=false; //是否显示块边界线(用来调试用) this._totalGridNum=0; //一层中的GridSprite的总数 this._gridW=0; //地图的横向块数 this._gridH=0; //地图的坚向块数 this._gridWidth=450; //块的默认宽度 this._gridHeight=450; //块的默认高度 this._jsonLoader=null; //用来加载JSON文件用的LOADER this._loader=null; //用来加载纹理数据用的LOADER this._tileSetArray=[]; //用来存放还需要哪些儿纹理等待加载 this._currTileSet=null; //正在加载的纹理需要的数据源 this._completeHandler=null; //上次视口显示的块范围 this._index=0; this._animationDic={}; //需要创建的动画数据 this._properties=null; //当前地图的自定义属性 this._tileProperties={}; //图块属性 this._tileProperties2={}; //默认的地图类型(具体要看JSON文件) this._orientation="orthogonal"; //默认的tile渲染顺序(具体要看JSON文件) this._renderOrder="right-down"; //调试用的颜色组合 this._colorArray=["FF","00","33","66"]; //缩放相关的操作 this._scale=1; this._pivotScaleX=0.5; this._pivotScaleY=0.5; this._centerX=0; this._centerY=0; /**@private */ this._viewPortX=0; /**@private */ this._viewPortY=0; this._viewPortWidth=0; this._viewPortHeight=0; //是否开启线性取样 this._enableLinear=true; //资源的相对路径 this._resPath=null; this._pathArray=null; //把地图限制在显示区域 this._limitRange=false; /** *快速更新模式是否不可用 */ this._fastDirty=true; /** *是否自动缓存没有动画的地块 */ this.autoCache=true; /** *自动缓存类型,地图较大时建议使用normal */ this.autoCacheType="normal"; /** *是否合并图层,开启合并图层时,图层属性内可添加layer属性,运行时将会将相邻的layer属性相同的图层进行合并以提高性能 */ this.enableMergeLayer=false; /** *是否移除被覆盖的格子,地块可添加type属性,type不为0时表示不透明,被不透明地块遮挡的地块将会被剔除以提高性能 */ this.removeCoveredTile=false; /** *是否显示大格子里显示的贴图数量 */ this.showGridTextureCount=false; /** *是否调整地块边缘消除缩放导致的缝隙 */ this.antiCrack=true; /** *是否在加载完成之后cache所有大格子 */ this.cacheAllAfterInit=false; this._texutreStartDic={}; this._rect=new Rectangle(); this._paddingRect=new Rectangle(); this._mapRect=new GRect(); this._mapLogicRect=new GRect(); this._mapLastRect=new GRect(); this._mapSprite=new Sprite(); } __class(TiledMap,'laya.map.TiledMap'); var __proto=TiledMap.prototype; /** *创建地图 *@param mapName JSON文件名字 *@param viewRect 视口区域 *@param completeHandler 地图创建完成的回调函数 *@param viewRectPadding 视口扩充区域,把视口区域上、下、左、右扩充一下,防止视口移动时的穿帮 *@param gridSize grid大小 *@param enableLinear 是否开启线性取样(为false时,可以解决地图黑线的问题,但画质会锐化) *@param limitRange 把地图限制在显示区域 */ __proto.createMap=function(mapName,viewRect,completeHandler,viewRectPadding,gridSize,enableLinear,limitRange){ (enableLinear===void 0)&& (enableLinear=true); (limitRange===void 0)&& (limitRange=false); this._enableLinear=enableLinear; this._limitRange=limitRange; this._rect.x=viewRect.x; this._rect.y=viewRect.y; this._rect.width=viewRect.width; this._rect.height=viewRect.height; this._viewPortWidth=viewRect.width / this._scale; this._viewPortHeight=viewRect.height / this._scale; this._completeHandler=completeHandler; if (viewRectPadding){ this._paddingRect.copyFrom(viewRectPadding); } else { this._paddingRect.setTo(0,0,0,0); } if (gridSize){ this._gridWidth=gridSize.x; this._gridHeight=gridSize.y; }; var tIndex=mapName.lastIndexOf("/"); if (tIndex >-1){ this._resPath=mapName.substr(0,tIndex); this._pathArray=this._resPath.split("/"); } else { this._resPath=""; this._pathArray=[]; } this._jsonLoader=new Loader(); this._jsonLoader.once("complete",this,this.onJsonComplete); this._jsonLoader.load(mapName,/*laya.net.Loader.JSON*/"json",false); } /** *json文件读取成功后,解析里面的纹理数据,进行加载 *@param e JSON数据 */ __proto.onJsonComplete=function(e){ var tJsonData=this._jsonData=e; this._properties=tJsonData.properties; this._orientation=tJsonData.orientation; this._renderOrder=tJsonData.renderorder; this._mapW=tJsonData.width; this._mapH=tJsonData.height; this._mapTileW=tJsonData.tilewidth; this._mapTileH=tJsonData.tileheight; this._width=this._mapTileW *this._mapW; this._height=this._mapTileH *this._mapH; if (this._orientation=="staggered"){ this._height=(0.5+this._mapH *0.5)*this._mapTileH; } this._mapLastRect.top=this._mapLastRect.bottom=this._mapLastRect.left=this._mapLastRect.right=-1; var tArray=tJsonData.tilesets; var tileset; var tTileSet; var i=0; for (i=0;i < tArray.length;i++){ tileset=tArray[i]; tTileSet=new TileSet(); tTileSet.init(tileset); if (tTileSet.properties && tTileSet.properties.ignore)continue ; this._tileProperties[i]=tTileSet.tileproperties; this.addTileProperties(tTileSet.tileproperties); this._tileSetArray.push(tTileSet); var tTiles=tileset.tiles; if (tTiles){ for (var p in tTiles){ var tAnimation=tTiles[p].animation; if (tAnimation){ var tAniData=new TileMapAniData(); this._animationDic[p]=tAniData; tAniData.image=tileset.image; for (var j=0;j < tAnimation.length;j++){ var tAnimationItem=tAnimation[j]; tAniData.mAniIdArray.push(tAnimationItem.tileid); tAniData.mDurationTimeArray.push(tAnimationItem.duration); } } } } } this._tileTexSetArr.push(null); if (this._tileSetArray.length > 0){ tTileSet=this._currTileSet=this._tileSetArray.shift(); this._loader=new Loader(); this._loader.once("complete",this,this.onTextureComplete); var tPath=this.mergePath(this._resPath,tTileSet.image); this._loader.load(tPath,/*laya.net.Loader.IMAGE*/"image",false); } } /** *合并路径 *@param resPath *@param relativePath *@return */ __proto.mergePath=function(resPath,relativePath){ var tResultPath=""; var tImageArray=relativePath.split("/"); var tParentPathNum=0; var i=0; for (i=tImageArray.length-1;i >=0;i--){ if (tImageArray[i]==".."){ tParentPathNum++; } } if (tParentPathNum==0){ if (this._pathArray.length > 0){ tResultPath=resPath+"/"+relativePath; } else { tResultPath=relativePath; } return tResultPath; }; var tSrcNum=this._pathArray.length-tParentPathNum; if (tSrcNum < 0){ console.log("[error]path does not exist",this._pathArray,tImageArray,resPath,relativePath); } for (i=0;i < tSrcNum;i++){ if (i==0){ tResultPath+=this._pathArray[i]; } else { tResultPath=tResultPath+"/"+this._pathArray[i]; } } for (i=tParentPathNum;i < tImageArray.length;i++){ tResultPath=tResultPath+"/"+tImageArray[i]; } return tResultPath; } /** *纹理加载完成,如果所有的纹理加载,开始初始化地图 *@param e 纹理数据 */ __proto.onTextureComplete=function(e){ var json=this._jsonData; var tTexture=e; if (Render.isWebGL && (!this._enableLinear)){ tTexture.bitmap.minFifter=0x2600; tTexture.bitmap.magFifter=0x2600; tTexture.bitmap.enableMerageInAtlas=false; } this._texArray.push(tTexture); var tSubTexture=null; var tTileSet=this._currTileSet; var tTileTextureW=tTileSet.tilewidth; var tTileTextureH=tTileSet.tileheight; var tImageWidth=tTileSet.imagewidth; var tImageHeight=tTileSet.imageheight; var tFirstgid=tTileSet.firstgid; var tTileWNum=Math.floor((tImageWidth-tTileSet.margin-tTileTextureW)/ (tTileTextureW+tTileSet.spacing))+1; var tTileHNum=Math.floor((tImageHeight-tTileSet.margin-tTileTextureH)/ (tTileTextureH+tTileSet.spacing))+1; var tTileTexSet=null; this._texutreStartDic[tTileSet.image]=this._tileTexSetArr.length; for (var i=0;i < tTileHNum;i++){ for (var j=0;j < tTileWNum;j++){ tTileTexSet=new TileTexSet(); tTileTexSet.offX=tTileSet.titleoffsetX; tTileTexSet.offY=tTileSet.titleoffsetY-(tTileTextureH-this._mapTileH); tTileTexSet.texture=Texture.createFromTexture(tTexture,tTileSet.margin+(tTileTextureW+tTileSet.spacing)*j,tTileSet.margin+(tTileTextureH+tTileSet.spacing)*i,tTileTextureW,tTileTextureH); if(this.antiCrack) this.adptTexture(tTileTexSet.texture); this._tileTexSetArr.push(tTileTexSet); tTileTexSet.gid=this._tileTexSetArr.length; } } if (this._tileSetArray.length > 0){ tTileSet=this._currTileSet=this._tileSetArray.shift(); this._loader.once("complete",this,this.onTextureComplete); var tPath=this.mergePath(this._resPath,tTileSet.image); this._loader.load(tPath,/*laya.net.Loader.IMAGE*/"image",false); } else { this._currTileSet=null; this.initMap(); } } __proto.adptTexture=function(tex){ if (!tex)return; var pX=tex.uv[0]; var pX1=tex.uv[2]; var pY=tex.uv[1]; var pY1=tex.uv[7]; var dW=1 / tex.bitmap.width; var dH=1 / tex.bitmap.height; tex.uv[0]=tex.uv[6]=pX+dW; tex.uv[2]=tex.uv[4]=pX1-dW; tex.uv[1]=tex.uv[3]=pY+dH; tex.uv[5]=tex.uv[7]=pY1-dH; } /** *初始化地图 */ __proto.initMap=function(){ var i=0,n=0; for (var p in this._animationDic){ var tAniData=this._animationDic[p]; var gStart=0; gStart=this._texutreStartDic[tAniData.image]; var tTileTexSet=this.getTexture(parseInt(p)+gStart); if (tAniData.mAniIdArray.length > 0){ tTileTexSet.textureArray=[]; tTileTexSet.durationTimeArray=tAniData.mDurationTimeArray; tTileTexSet.isAnimation=true; tTileTexSet.animationTotalTime=0; for (i=0,n=tTileTexSet.durationTimeArray.length;i < n;i++){ tTileTexSet.animationTotalTime+=tTileTexSet.durationTimeArray[i]; } for (i=0,n=tAniData.mAniIdArray.length;i < n;i++){ var tTexture=this.getTexture(tAniData.mAniIdArray[i]+gStart); tTileTexSet.textureArray.push(tTexture); } } } this._gridWidth=Math.floor(this._gridWidth / this._mapTileW)*this._mapTileW; this._gridHeight=Math.floor(this._gridHeight / this._mapTileH)*this._mapTileH; if (this._gridWidth < this._mapTileW){ this._gridWidth=this._mapTileW; } if (this._gridHeight < this._mapTileH){ this._gridHeight=this._mapTileH; } this._gridW=Math.ceil(this._width / this._gridWidth); this._gridH=Math.ceil(this._height / this._gridHeight); this._totalGridNum=this._gridW *this._gridH; for (i=0;i < this._gridH;i++){ var tGridArray=[]; this._gridArray.push(tGridArray); for (var j=0;j < this._gridW;j++){ tGridArray.push(null); } }; var tLayerArray=this._jsonData.layers; var isFirst=true; var tTarLayerID=1; var tLayerTarLayerName; var preLayerTarName; var preLayer; for (var tLayerLoop=0;tLayerLoop < tLayerArray.length;tLayerLoop++){ var tLayerData=tLayerArray[tLayerLoop]; if (tLayerData.visible==true){ var tMapLayer=new MapLayer(); tMapLayer.init(tLayerData,this); if (!this.enableMergeLayer){ this._mapSprite.addChild(tMapLayer); this._renderLayerArray.push(tMapLayer); }else{ tLayerTarLayerName=tMapLayer.getLayerProperties("layer"); isFirst=isFirst || (!preLayer)|| (tLayerTarLayerName !=preLayerTarName); if (isFirst){ isFirst=false; tMapLayer.tarLayer=tMapLayer; preLayer=tMapLayer; this._mapSprite.addChild(tMapLayer); this._renderLayerArray.push(tMapLayer); }else{ tMapLayer.tarLayer=preLayer; } preLayerTarName=tLayerTarLayerName; } this._layerArray.push(tMapLayer); } } if (this.removeCoveredTile){ this.adptTiledMapData(); } if (this.cacheAllAfterInit){ this.cacheAllGrid(); } this.moveViewPort(this._rect.x,this._rect.y); Laya.stage.addChild(this.mapSprite()); if (this._completeHandler !=null){ this._completeHandler.run(); } } //这里应该发送消息,通知上层,地图创建完成 __proto.addTileProperties=function(tileDataDic){ var key; for (key in tileDataDic){ this._tileProperties2[key]=tileDataDic[key]; } } __proto.getTileUserData=function(id,sign,defaultV){ if (!this._tileProperties2 || !this._tileProperties2[id] || !(sign in this._tileProperties2[id]))return defaultV; return this._tileProperties2[id][sign]; } __proto.adptTiledMapData=function(){ var i=0,len=0; len=this._layerArray.length; var tLayer; var noNeeds={}; var tDatas; for (i=len-1;i >=0;i--){ tLayer=this._layerArray[i]; tDatas=tLayer._mapData; if (!tDatas)continue ; this.removeCoverd(tDatas,noNeeds); this.collectCovers(tDatas,noNeeds,i); } } __proto.removeCoverd=function(datas,noNeeds){ var i=0,len=0; len=datas.length; for (i=0;i < len;i++){ if (noNeeds[i]){ datas[i]=0; } } } __proto.collectCovers=function(datas,noNeeds,layer){ var i=0,len=0; len=datas.length; var tTileData=0; var isCover=0; for (i=0;i < len;i++){ tTileData=datas[i]; if (tTileData > 0){ isCover=this.getTileUserData(tTileData-1,"type",0); if (isCover > 0){ noNeeds[i]=tTileData; } } } } /** *得到一块指定的地图纹理 *@param index 纹理的索引值,默认从1开始 *@return */ __proto.getTexture=function(index){ if (index < this._tileTexSetArr.length){ return this._tileTexSetArr[index]; } return null; } /** *得到地图的自定义属性 *@param name 属性名称 *@return */ __proto.getMapProperties=function(name){ if (this._properties){ return this._properties[name]; } return null; } /** *得到tile自定义属性 *@param index 地图块索引 *@param id 具体的TileSetID *@param name 属性名称 *@return */ __proto.getTileProperties=function(index,id,name){ if (this._tileProperties[index] && this._tileProperties[index][id]){ return this._tileProperties[index][id][name]; } return null; } /** *通过纹理索引,生成一个可控制物件 *@param index 纹理的索引值,默认从1开始 *@return */ __proto.getSprite=function(index,width,height){ if (0 < this._tileTexSetArr.length){ var tGridSprite=new GridSprite(); tGridSprite.initData(this,true); tGridSprite.size(width,height); var tTileTexSet=this._tileTexSetArr[index]; if (tTileTexSet !=null && tTileTexSet.texture !=null){ if (tTileTexSet.isAnimation){ var tAnimationSprite=new TileAniSprite(); this._index++; tAnimationSprite.setTileTextureSet(this._index.toString(),tTileTexSet); tGridSprite.addAniSprite(tAnimationSprite); tGridSprite.addChild(tAnimationSprite); } else { tGridSprite.graphics.drawTexture(tTileTexSet.texture,0,0,width,height); } tGridSprite.drawImageNum++; } return tGridSprite; } return null; } /** *设置视口的缩放中心点(例如:scaleX=scaleY=0.5,就是以视口中心缩放) *@param scaleX *@param scaleY */ __proto.setViewPortPivotByScale=function(scaleX,scaleY){ this._pivotScaleX=scaleX; this._pivotScaleY=scaleY; this._fastDirty=true; } /** *移动视口 *@param moveX 视口的坐标x *@param moveY 视口的坐标y */ __proto.moveViewPort=function(moveX,moveY){ this._x=-moveX; this._y=-moveY; if (this._fastDirty){ this._rect.x=moveX; this._rect.y=moveY; this.updateViewPort(); }else{ var dx=NaN,dy=NaN; dx=moveX-this._rect.x; dy=moveY-this._rect.y; this._rect.x=moveX; this._rect.y=moveY; this.updateViewPortFast(dx,dy); } } /** *改变视口大小 *@param moveX 视口的坐标x *@param moveY 视口的坐标y *@param width 视口的宽 *@param height 视口的高 */ __proto.changeViewPort=function(moveX,moveY,width,height){ if (moveX==this._rect.x && moveY==this._rect.y && width==this._rect.width && height==this._rect.height)return; if (width==this._rect.width && height==this._rect.height){ this.moveViewPort(moveX,moveY); return; } this._fastDirty=true; this._x=-moveX; this._y=-moveY; this._rect.x=moveX; this._rect.y=moveY; this._rect.width=width; this._rect.height=height; this._viewPortWidth=width / this._scale; this._viewPortHeight=height / this._scale; this.updateViewPort(); } /** *在锚点的基础上计算,通过宽和高,重新计算视口 *@param width 新视口宽 *@param height 新视口高 *@param rect 返回的结果 *@return */ __proto.changeViewPortBySize=function(width,height,rect){ if (rect==null){ rect=new Rectangle(); } this._centerX=this._rect.x+this._rect.width *this._pivotScaleX; this._centerY=this._rect.y+this._rect.height *this._pivotScaleY; rect.x=this._centerX-width *this._pivotScaleX; rect.y=this._centerY-height *this._pivotScaleY; rect.width=width; rect.height=height; this.changeViewPort(rect.x,rect.y,rect.width,rect.height); return rect; } /** *快速更新视口 ,只有在视口大小和各种缩放信息没有改变时才可以使用这个函数更新 *@param dx 视口偏移x *@param dy 视口偏移y */ __proto.updateViewPortFast=function(dx,dy){ this._centerX+=dx; this._centerY+=dy; this._viewPortX+=dx; this._viewPortY+=dy; var posChanged=false; var dyG=dy / this._gridHeight; var dxG=dx / this._gridWidth; this._mapLogicRect.top+=dyG; this._mapLogicRect.bottom+=dyG; this._mapLogicRect.left+=dxG; this._mapLogicRect.right+=dxG; this._mapRect.top=0|this._mapLogicRect.top; this._mapRect.bottom=0|this._mapLogicRect.bottom; this._mapRect.left=0|this._mapLogicRect.left; this._mapRect.right=0|this._mapLogicRect.right; if (this._mapRect.top !=this._mapLastRect.top || this._mapRect.bottom !=this._mapLastRect.bottom || this._mapRect.left !=this._mapLastRect.left || this._mapRect.right !=this._mapLastRect.right){ this.clipViewPort(); this._mapLastRect.top=this._mapRect.top; this._mapLastRect.bottom=this._mapRect.bottom; this._mapLastRect.left=this._mapRect.left; this._mapLastRect.right=this._mapRect.right; posChanged=true; };posChanged=posChanged|| (dx !=0 || dy !=0); if (!posChanged)return; this.updateMapLayersPos(); } /** *刷新地图层坐标 */ __proto.updateMapLayersPos=function(){ var tMapLayer; var len=this._renderLayerArray.length; for (var i=0;i < len;i++){ tMapLayer=this._renderLayerArray[i]; if (tMapLayer._gridSpriteArray.length > 0){ tMapLayer.updateAloneObject(); tMapLayer.pos(-this._viewPortX,-this._viewPortY); } } } /** *刷新视口 */ __proto.updateViewPort=function(){ this._fastDirty=false; var dw=this._rect.width *this._pivotScaleX; var dh=this._rect.height *this._pivotScaleY; this._centerX=this._rect.x+dw; this._centerY=this._rect.y+dh; var posChanged=false; var preValue=this._viewPortX; this._viewPortX=this._centerX-dw / this._scale; if (preValue !=this._viewPortX){ posChanged=true; }else { preValue=this._viewPortY; } this._viewPortY=this._centerY-dh/ this._scale; if (!posChanged && preValue !=this._viewPortY){ posChanged=true; } if (this._limitRange){ var tRight=this._viewPortX+this._viewPortWidth; if (tRight > this._width){ this._viewPortX=this._width-this._viewPortWidth; }; var tBottom=this._viewPortY+this._viewPortHeight; if (tBottom > this._height){ this._viewPortY=this._height-this._viewPortHeight; } if (this._viewPortX < 0){ this._viewPortX=0; } if (this._viewPortY < 0){ this._viewPortY=0; } }; var tPaddingRect=this._paddingRect; this._mapLogicRect.top=(this._viewPortY-tPaddingRect.y)/ this._gridHeight; this._mapLogicRect.bottom=(this._viewPortY+this._viewPortHeight+tPaddingRect.height+tPaddingRect.y)/ this._gridHeight; this._mapLogicRect.left=(this._viewPortX-tPaddingRect.x)/ this._gridWidth; this._mapLogicRect.right=(this._viewPortX+this._viewPortWidth+tPaddingRect.width+tPaddingRect.x)/ this._gridWidth; this._mapRect.top=0|this._mapLogicRect.top; this._mapRect.bottom=0|this._mapLogicRect.bottom; this._mapRect.left=0|this._mapLogicRect.left; this._mapRect.right=0|this._mapLogicRect.right; if (this._mapRect.top !=this._mapLastRect.top || this._mapRect.bottom !=this._mapLastRect.bottom || this._mapRect.left !=this._mapLastRect.left || this._mapRect.right !=this._mapLastRect.right){ this.clipViewPort(); this._mapLastRect.top=this._mapRect.top; this._mapLastRect.bottom=this._mapRect.bottom; this._mapLastRect.left=this._mapRect.left; this._mapLastRect.right=this._mapRect.right; posChanged=true; } if (!posChanged)return; this.updateMapLayersPos(); } /** *GRID裁剪 */ __proto.clipViewPort=function(){ var tSpriteNum=0; var tSprite; var tIndex=0; var tSub=0; var tAdd=0; var i=0,j=0; if (this._mapRect.left > this._mapLastRect.left){ tSub=this._mapRect.left-this._mapLastRect.left; if (tSub > 0){ for (j=this._mapLastRect.left;j < this._mapLastRect.left+tSub;j++){ for (i=this._mapLastRect.top;i <=this._mapLastRect.bottom;i++){ this.hideGrid(j,i); } } } } else { tAdd=Math.min(this._mapLastRect.left,this._mapRect.right+1)-this._mapRect.left; if (tAdd > 0){ for (j=this._mapRect.left;j < this._mapRect.left+tAdd;j++){ for (i=this._mapRect.top;i <=this._mapRect.bottom;i++){ this.showGrid(j,i); } } } } if (this._mapRect.right > this._mapLastRect.right){ tAdd=this._mapRect.right-this._mapLastRect.right; if (tAdd > 0){ for (j=Math.max(this._mapLastRect.right+1,this._mapRect.left);j <=this._mapLastRect.right+tAdd;j++){ for (i=this._mapRect.top;i <=this._mapRect.bottom;i++){ this.showGrid(j,i); } } } } else { tSub=this._mapLastRect.right-this._mapRect.right if (tSub > 0){ for (j=this._mapRect.right+1;j <=this._mapRect.right+tSub;j++){ for (i=this._mapLastRect.top;i <=this._mapLastRect.bottom;i++){ this.hideGrid(j,i); } } } } if (this._mapRect.top > this._mapLastRect.top){ tSub=this._mapRect.top-this._mapLastRect.top; if (tSub > 0){ for (i=this._mapLastRect.top;i < this._mapLastRect.top+tSub;i++){ for (j=this._mapLastRect.left;j <=this._mapLastRect.right;j++){ this.hideGrid(j,i); } } } } else { tAdd=Math.min(this._mapLastRect.top,this._mapRect.bottom+1)-this._mapRect.top; if (tAdd > 0){ for (i=this._mapRect.top;i < this._mapRect.top+tAdd;i++){ for (j=this._mapRect.left;j <=this._mapRect.right;j++){ this.showGrid(j,i); } } } } if (this._mapRect.bottom > this._mapLastRect.bottom){ tAdd=this._mapRect.bottom-this._mapLastRect.bottom; if (tAdd > 0){ for (i=Math.max(this._mapLastRect.bottom+1,this._mapRect.top);i <=this._mapLastRect.bottom+tAdd;i++){ for (j=this._mapRect.left;j <=this._mapRect.right;j++){ this.showGrid(j,i); } } } } else { tSub=this._mapLastRect.bottom-this._mapRect.bottom if (tSub > 0){ for (i=this._mapRect.bottom+1;i <=this._mapRect.bottom+tSub;i++){ for (j=this._mapLastRect.left;j <=this._mapLastRect.right;j++){ this.hideGrid(j,i); } } } } } /** *显示指定的GRID *@param gridX *@param gridY */ __proto.showGrid=function(gridX,gridY){ if (gridX < 0 || gridX >=this._gridW || gridY < 0 || gridY >=this._gridH){ return; }; var i=0,j=0; var tGridSprite; var tTempArray=this._gridArray[gridY][gridX]; if (tTempArray==null){ tTempArray=this.getGridArray(gridX,gridY); } else { for (i=0;i < tTempArray.length && i < this._layerArray.length;i++){ var tLayerSprite=this._layerArray[i]; if (tLayerSprite && tTempArray[i]){ tGridSprite=tTempArray[i]; if (tGridSprite.visible==false && tGridSprite.drawImageNum > 0){ tGridSprite.show(); } } } } } __proto.cacheAllGrid=function(){ var i=0,j=0; var tempArr; for (i=0;i < this._gridW;i++){ for (j=0;j < this._gridH;j++){ tempArr=this.getGridArray(i,j); this.cacheGridsArray(tempArr); } } } __proto.cacheGridsArray=function(arr){ var canvas; if (!TiledMap._tempContext){ TiledMap._tempContext=new RenderContext(1,1,HTMLCanvas.create(/*laya.resource.HTMLCanvas.TYPEAUTO*/"AUTO")); } canvas=TiledMap._tempContext.canvas; canvas.context.asBitmap=false; var i=0,len=0; len=arr.length; var tGrid; for (i=0;i < len;i++){ tGrid=arr[i]; canvas.clear(); canvas.size(1,1); tGrid.render(TiledMap._tempContext,0,0); tGrid.hide(); } canvas.clear(); canvas.size(1,1); } __proto.getGridArray=function(gridX,gridY){ var i=0,j=0; var tGridSprite; var tTempArray=this._gridArray[gridY][gridX]; if (tTempArray==null){ tTempArray=this._gridArray[gridY][gridX]=[]; var tLeft=0; var tRight=0; var tTop=0; var tBottom=0; var tGridWidth=this._gridWidth; var tGridHeight=this._gridHeight; switch (this.orientation){ case /*CLASS CONST:laya.map.TiledMap.ORIENTATION_ISOMETRIC*/"isometric": tLeft=Math.floor(gridX *tGridWidth); tRight=Math.floor(gridX *tGridWidth+tGridWidth); tTop=Math.floor(gridY *tGridHeight); tBottom=Math.floor(gridY *tGridHeight+tGridHeight); var tLeft1=0,tRight1=0,tTop1=0,tBottom1=0; break ; case /*CLASS CONST:laya.map.TiledMap.ORIENTATION_STAGGERED*/"staggered": tLeft=Math.floor(gridX *tGridWidth / this._mapTileW); tRight=Math.floor((gridX *tGridWidth+tGridWidth)/ this._mapTileW); tTop=Math.floor(gridY *tGridHeight / (this._mapTileH / 2)); tBottom=Math.floor((gridY *tGridHeight+tGridHeight)/ (this._mapTileH / 2)); break ; case /*CLASS CONST:laya.map.TiledMap.ORIENTATION_ORTHOGONAL*/"orthogonal": tLeft=Math.floor(gridX *tGridWidth / this._mapTileW); tRight=Math.floor((gridX *tGridWidth+tGridWidth)/ this._mapTileW); tTop=Math.floor(gridY *tGridHeight / this._mapTileH); tBottom=Math.floor((gridY *tGridHeight+tGridHeight)/ this._mapTileH); break ; case /*CLASS CONST:laya.map.TiledMap.ORIENTATION_HEXAGONAL*/"hexagonal":; var tHeight=this._mapTileH *2 / 3; tLeft=Math.floor(gridX *tGridWidth / this._mapTileW); tRight=Math.ceil((gridX *tGridWidth+tGridWidth)/ this._mapTileW); tTop=Math.floor(gridY *tGridHeight / tHeight); tBottom=Math.ceil((gridY *tGridHeight+tGridHeight)/ tHeight); break ; }; var tLayer=null; var tTGridSprite; var tDrawMapLayer; for (var z=0;z < this._layerArray.length;z++){ tLayer=this._layerArray[z]; if (this.enableMergeLayer){ if (tLayer.tarLayer !=tDrawMapLayer){ tTGridSprite=null; tDrawMapLayer=tLayer.tarLayer; } if (!tTGridSprite){ tTGridSprite=tDrawMapLayer.getDrawSprite(gridX,gridY); tTempArray.push(tTGridSprite); } tGridSprite=tTGridSprite; } else { tGridSprite=tLayer.getDrawSprite(gridX,gridY); tTempArray.push(tGridSprite); }; var tColorStr; if (this._showGridKey){ tColorStr="#"; tColorStr+=this._colorArray[Math.floor(Math.random()*this._colorArray.length)]; tColorStr+=this._colorArray[Math.floor(Math.random()*this._colorArray.length)]; tColorStr+=this._colorArray[Math.floor(Math.random()*this._colorArray.length)]; } switch (this.orientation){ case /*CLASS CONST:laya.map.TiledMap.ORIENTATION_ISOMETRIC*/"isometric":; var tHalfTileHeight=this.tileHeight / 2; var tHalfTileWidth=this.tileWidth / 2; var tHalfMapWidth=this._width / 2; tTop1=Math.floor(tTop / tHalfTileHeight); tBottom1=Math.floor(tBottom / tHalfTileHeight); tLeft1=this._mapW+Math.floor((tLeft-tHalfMapWidth)/ tHalfTileWidth); tRight1=this._mapW+Math.floor((tRight-tHalfMapWidth)/ tHalfTileWidth); var tMapW=this._mapW *2; var tMapH=this._mapH *2; if (tTop1 < 0){ tTop1=0; } if (tTop1 >=tMapH){ tTop1=tMapH-1; } if (tBottom1 < 0){ tBottom=0; } if (tBottom1 >=tMapH){ tBottom1=tMapH-1; } tGridSprite.zOrder=this._totalGridNum *z+gridY *this._gridW+gridX; for (i=tTop1;i < tBottom1;i++){ for (j=0;j <=i;j++){ var tIndexX=i-j; var tIndexY=j; var tIndexValue=(tIndexX-tIndexY)+this._mapW; if (tIndexValue > tLeft1 && tIndexValue <=tRight1){ if (tLayer.drawTileTexture(tGridSprite,tIndexX,tIndexY)){ tGridSprite.drawImageNum++; } } } } break ; case /*CLASS CONST:laya.map.TiledMap.ORIENTATION_STAGGERED*/"staggered": tGridSprite.zOrder=z *this._totalGridNum+gridY *this._gridW+gridX; for (i=tTop;i < tBottom;i++){ for (j=tLeft;j < tRight;j++){ if (tLayer.drawTileTexture(tGridSprite,j,i)){ tGridSprite.drawImageNum++; } } } break ; case /*CLASS CONST:laya.map.TiledMap.ORIENTATION_ORTHOGONAL*/"orthogonal": case /*CLASS CONST:laya.map.TiledMap.ORIENTATION_HEXAGONAL*/"hexagonal": switch (this._renderOrder){ case "right-down": tGridSprite.zOrder=z *this._totalGridNum+gridY *this._gridW+gridX; for (i=tTop;i < tBottom;i++){ for (j=tLeft;j < tRight;j++){ if (tLayer.drawTileTexture(tGridSprite,j,i)){ tGridSprite.drawImageNum++; } } } break ; case "right-up": tGridSprite.zOrder=z *this._totalGridNum+(this._gridH-1-gridY)*this._gridW+gridX; for (i=tBottom-1;i >=tTop;i--){ for (j=tLeft;j < tRight;j++){ if (tLayer.drawTileTexture(tGridSprite,j,i)){ tGridSprite.drawImageNum++; } } } break ; case "left-down": tGridSprite.zOrder=z *this._totalGridNum+gridY *this._gridW+(this._gridW-1-gridX); for (i=tTop;i < tBottom;i++){ for (j=tRight-1;j >=tLeft;j--){ if (tLayer.drawTileTexture(tGridSprite,j,i)){ tGridSprite.drawImageNum++; } } } break ; case "left-up": tGridSprite.zOrder=z *this._totalGridNum+(this._gridH-1-gridY)*this._gridW+(this._gridW-1-gridX); for (i=tBottom-1;i >=tTop;i--){ for (j=tRight-1;j >=tLeft;j--){ if (tLayer.drawTileTexture(tGridSprite,j,i)){ tGridSprite.drawImageNum++; } } } break ; } break ; } if (!tGridSprite.isHaveAnimation){ tGridSprite.autoSize=true; if (this.autoCache) tGridSprite.cacheAs=this.autoCacheType; tGridSprite.autoSize=false; } if (!this.enableMergeLayer){ if (tGridSprite.drawImageNum > 0){ tLayer.addChild(tGridSprite); tGridSprite.visible=false; tGridSprite.show(); } if (this._showGridKey){ tGridSprite.graphics.drawRect(0,0,tGridWidth,tGridHeight,null,tColorStr); } }else{ if (tTGridSprite && tTGridSprite.drawImageNum > 0&&tDrawMapLayer){ tDrawMapLayer.addChild(tTGridSprite); tTGridSprite.visible=false; tTGridSprite.show(); } } } if (this.enableMergeLayer&&this.showGridTextureCount){ if (tTGridSprite){ tTGridSprite.graphics.fillText(tTGridSprite.drawImageNum+"",20,20,null,"#ff0000","left"); } } } return tTempArray; } /** *隐藏指定的GRID *@param gridX *@param gridY */ __proto.hideGrid=function(gridX,gridY){ if (gridX < 0 || gridX >=this._gridW || gridY < 0 || gridY >=this._gridH){ return; }; var tTempArray=this._gridArray[gridY][gridX]; if (tTempArray){ var tGridSprite; for (var i=0;i < tTempArray.length;i++){ tGridSprite=tTempArray[i]; if (tGridSprite.drawImageNum > 0){ if (tGridSprite !=null){ tGridSprite.hide(); } } } } } /** *得到对象层上的某一个物品 *@param layerName 层的名称 *@param objectName 所找物品的名称 *@return */ __proto.getLayerObject=function(layerName,objectName){ var tLayer=null; for (var i=0;i < this._layerArray.length;i++){ tLayer=this._layerArray[i]; if (tLayer.layerName==layerName){ break ; } } if (tLayer){ return tLayer.getObjectByName(objectName); } return null; } /** *销毁地图 */ __proto.destroy=function(){ this._orientation="orthogonal"; this._jsonData=null; var i=0; var j=0; var z=0; this._gridArray=[]; var tTileTexSet; for (i=0;i < this._tileTexSetArr.length;i++){ tTileTexSet=this._tileTexSetArr[i]; if (tTileTexSet){ tTileTexSet.clearAll(); } } this._tileTexSetArr=[]; var tTexture; for (i=0;i < this._texArray.length;i++){ tTexture=this._texArray[i]; tTexture.destroy(); } this._texArray=[]; this._width=0; this._height=0; this._mapW=0; this._mapH=0; this._mapTileW=0; this._mapTileH=0; this._rect.setTo(0,0,0,0); var tLayer; for (i=0;i < this._layerArray.length;i++){ tLayer=this._layerArray[i]; tLayer.clearAll(); } this._layerArray=[]; this._renderLayerArray=[]; if (this._mapSprite){ this._mapSprite.destroy(); this._mapSprite=null; } this._jsonLoader=null; this._loader=null; var tDic=this._animationDic; for (var p in tDic){ delete tDic[p]; } this._properties=null; tDic=this._tileProperties; for (p in tDic){ delete tDic[p]; } this._currTileSet=null; this._completeHandler=null; this._mapRect.clearAll(); this._mapLastRect.clearAll(); this._tileSetArray=[]; this._gridWidth=450; this._gridHeight=450; this._gridW=0; this._gridH=0; this._x=0; this._y=0; this._index=0; this._enableLinear=true; this._resPath=null; this._pathArray=null; } /** *整个地图的显示容器 *@return 地图的显示容器 */ __proto.mapSprite=function(){ return this._mapSprite; } /** *得到指定的MapLayer *@param layerName 要找的层名称 *@return */ __proto.getLayerByName=function(layerName){ var tMapLayer; for (var i=0;i < this._layerArray.length;i++){ tMapLayer=this._layerArray[i]; if (layerName==tMapLayer.layerName){ return tMapLayer; } } return null; } /** *通过索引得MapLayer *@param index 要找的层索引 *@return */ __proto.getLayerByIndex=function(index){ if (index < this._layerArray.length){ return this._layerArray[index]; } return null; } /** *当前地图类型 */ __getset(0,__proto,'orientation',function(){ return this._orientation; }); /** *@private *视口x坐标 */ __getset(0,__proto,'viewPortX',function(){ return-this._viewPortX; }); /** *设置地图缩放 *@param scale */ /** *得到当前地图的缩放 */ __getset(0,__proto,'scale',function(){ return this._scale; },function(scale){ if (scale <=0) return; this._scale=scale; this._viewPortWidth=this._rect.width / scale; this._viewPortHeight=this._rect.height / scale; this._mapSprite.scale(this._scale,this._scale); this.updateViewPort(); }); /** *格子的宽度 */ __getset(0,__proto,'tileWidth',function(){ return this._mapTileW; }); /** *@private *视口的y坐标 */ __getset(0,__proto,'viewPortY',function(){ return-this._viewPortY; }); /** *格子的高度 */ __getset(0,__proto,'tileHeight',function(){ return this._mapTileH; }); /** *地图的宽度 */ __getset(0,__proto,'width',function(){ return this._width; }); /** *地图竖向的格子数 */ __getset(0,__proto,'numRowsTile',function(){ return this._mapH; }); /** *地图横向的格子数 */ __getset(0,__proto,'numColumnsTile',function(){ return this._mapW; }); /** *地图的高度 */ __getset(0,__proto,'height',function(){ return this._height; }); /** *@private *视口的宽度 */ __getset(0,__proto,'viewPortWidth',function(){ return this._viewPortWidth; }); /** *@private *视口的高度 */ __getset(0,__proto,'viewPortHeight',function(){ return this._viewPortHeight; }); /** *地图的x坐标 */ __getset(0,__proto,'x',function(){ return this._x; }); /** *地图的y坐标 */ __getset(0,__proto,'y',function(){ return this._y; }); /** *块的宽度 */ __getset(0,__proto,'gridWidth',function(){ return this._gridWidth; }); /** *块的高度 */ __getset(0,__proto,'gridHeight',function(){ return this._gridHeight; }); /** *地图的横向块数 */ __getset(0,__proto,'numColumnsGrid',function(){ return this._gridW; }); /** *地图的坚向块数 */ __getset(0,__proto,'numRowsGrid',function(){ return this._gridH; }); /** *tile渲染顺序 */ __getset(0,__proto,'renderOrder',function(){ return this._renderOrder; }); TiledMap.ORIENTATION_ORTHOGONAL="orthogonal"; TiledMap.ORIENTATION_ISOMETRIC="isometric"; TiledMap.ORIENTATION_STAGGERED="staggered"; TiledMap.ORIENTATION_HEXAGONAL="hexagonal"; TiledMap.RENDERORDER_RIGHTDOWN="right-down"; TiledMap.RENDERORDER_RIGHTUP="right-up"; TiledMap.RENDERORDER_LEFTDOWN="left-down"; TiledMap.RENDERORDER_LEFTUP="left-up"; TiledMap._tempContext=null; TiledMap.__init$=function(){ //class GRect GRect=(function(){ function GRect(){ this.left=0; this.top=0; this.right=0; this.bottom=0; } __class(GRect,''); var __proto=GRect.prototype; __proto.clearAll=function(){ this.left=this.top=this.right=this.bottom=0; } return GRect; })() //class TileMapAniData TileMapAniData=(function(){ function TileMapAniData(){ this.mAniIdArray=[]; this.mDurationTimeArray=[]; this.mTileTexSetArr=[]; this.image=null; } __class(TileMapAniData,''); return TileMapAniData; })() //class TileSet TileSet=(function(){ function TileSet(){ this.firstgid=0; this.image=""; this.imageheight=0; this.imagewidth=0; this.margin=0; this.name=0; this.properties=null; this.spacing=0; this.tileheight=0; this.tilewidth=0; this.titleoffsetX=0; this.titleoffsetY=0; this.tileproperties=null; } __class(TileSet,''); var __proto=TileSet.prototype; __proto.init=function(data){ this.firstgid=data.firstgid; this.image=data.image; this.imageheight=data.imageheight; this.imagewidth=data.imagewidth; this.margin=data.margin; this.name=data.name; this.properties=data.properties; this.spacing=data.spacing; this.tileheight=data.tileheight; this.tilewidth=data.tilewidth; this.tileproperties=data.tileproperties; var tTileoffset=data.tileoffset; if (tTileoffset){ this.titleoffsetX=tTileoffset.x; this.titleoffsetY=tTileoffset.y; } } return TileSet; })() } return TiledMap; })() /** *此类是子纹理类,也包括同类动画的管理 *TiledMap会把纹理分割成无数子纹理,也可以把其中的某块子纹理替换成一个动画序列 *本类的实现就是如果发现子纹理被替换成一个动画序列,animationKey会被设为true *即animationKey为true,就使用TileAniSprite来做显示,把动画序列根据时间画到TileAniSprite上 *@author ... */ //class laya.map.TileTexSet var TileTexSet=(function(){ function TileTexSet(){ /**唯一标识*/ this.gid=-1; /**子纹理的引用*/ this.texture=null; /**纹理显示时的坐标偏移X*/ this.offX=0; /**纹理显示时的坐标偏移Y*/ this.offY=0; /**当前要播放动画的纹理序列*/ this.textureArray=null; /**当前动画每帧的时间间隔*/ this.durationTimeArray=null; /**动画播放的总时间 */ this.animationTotalTime=0; /**true表示当前纹理,是一组动画,false表示当前只有一个纹理*/ this.isAnimation=false; this._spriteNum=0; //当前动画有多少个显示对象 this._aniDic=null; //通过显示对象的唯一名字,去保存显示显示对象 this._frameIndex=0; //当前动画播放到第几帧 this._time=0; //距离上次动画刷新,过了多少长时间 this._interval=0; //每帧刷新的时间间隔 this._preFrameTime=0; } __class(TileTexSet,'laya.map.TileTexSet'); var __proto=TileTexSet.prototype; /** *加入一个动画显示对象到此动画中 *@param aniName //显示对象的名字 *@param sprite //显示对象 */ __proto.addAniSprite=function(aniName,sprite){ if (this.animationTotalTime==0){ return; } if (this._aniDic==null){ this._aniDic={}; } if (this._spriteNum==0){ Laya.timer.frameLoop(3,this,this.animate); this._preFrameTime=Browser.now(); this._frameIndex=0; this._time=0; this._interval=0; } this._spriteNum++; this._aniDic[aniName]=sprite; if (this.textureArray && this._frameIndex < this.textureArray.length){ var tTileTextureSet=this.textureArray[this._frameIndex]; this.drawTexture(sprite,tTileTextureSet); } } /** *把动画画到所有注册的SPRITE上 */ __proto.animate=function(){ if (this.textureArray && this.textureArray.length > 0 && this.durationTimeArray && this.durationTimeArray.length > 0){ var tNow=Browser.now(); this._interval=tNow-this._preFrameTime; this._preFrameTime=tNow; if (this._interval > this.animationTotalTime){ this._interval=this._interval % this.animationTotalTime; } this._time+=this._interval; var tTime=this.durationTimeArray[this._frameIndex]; while (this._time > tTime){ this._time-=tTime; this._frameIndex++; if (this._frameIndex >=this.durationTimeArray.length || this._frameIndex >=this.textureArray.length){ this._frameIndex=0; }; var tTileTextureSet=this.textureArray[this._frameIndex]; var tSprite; for (var p in this._aniDic){ tSprite=this._aniDic[p]; this.drawTexture(tSprite,tTileTextureSet); } tTime=this.durationTimeArray[this._frameIndex]; } } } __proto.drawTexture=function(sprite,tileTextSet){ sprite.graphics.clear(); sprite.graphics.drawTexture(tileTextSet.texture,tileTextSet.offX,tileTextSet.offY); } /** *移除不需要更新的SPRITE *@param _name */ __proto.removeAniSprite=function(_name){ if (this._aniDic && this._aniDic[_name]){ delete this._aniDic[_name]; this._spriteNum-- if (this._spriteNum==0){ Laya.timer.clear(this,this.animate); } } } /** *显示当前动画的使用情况 */ __proto.showDebugInfo=function(){ var tInfo=null; if (this._spriteNum > 0){ tInfo="TileTextureSet::gid:"+this.gid.toString()+" 动画数:"+this._spriteNum.toString(); } return tInfo; } /** *清理 */ __proto.clearAll=function(){ this.gid=-1; if (this.texture){ this.texture.destroy(); this.texture=null; } this.offX=0; this.offY=0; this.textureArray=null; this.durationTimeArray=null; this.isAnimation=false; this._spriteNum=0; this._aniDic=null; this._frameIndex=0; this._preFrameTime=0; this._time=0; this._interval=0; } return TileTexSet; })() /** *地图的每层都会分块渲染处理 *本类就是地图的块数据 *@author ... */ //class laya.map.GridSprite extends laya.display.Sprite var GridSprite=(function(_super){ function GridSprite(){ /**相对于地图X轴的坐标*/ this.relativeX=0; /**相对于地图Y轴的坐标*/ this.relativeY=0; /**是否用于对象层的独立物件*/ this.isAloneObject=false; /**当前GRID中是否有动画*/ this.isHaveAnimation=false; /**当前GRID包含的动画*/ this.aniSpriteArray=null; /**当前GRID包含多少个TILE(包含动画)*/ this.drawImageNum=0; this._map=null; GridSprite.__super.call(this); } __class(GridSprite,'laya.map.GridSprite',_super); var __proto=GridSprite.prototype; /** *传入必要的参数,用于裁剪,跟确认此对象类型 *@param map 把地图的引用传进来,参与一些裁剪计算 *@param objectKey true:表示当前GridSprite是个活动对象,可以控制,false:地图层的组成块 */ __proto.initData=function(map,objectKey){ (objectKey===void 0)&& (objectKey=false); this._map=map; this.isAloneObject=objectKey; } /**@private */ __proto._setDisplay=function(value){ if (!value){ var cc=this._$P.cacheCanvas; if (cc && cc.ctx){ cc.ctx.canvas.destroy(); cc.ctx=null; }; var fc=this._$P._filterCache; if (fc){ fc.destroy(); fc.recycle(); this._set$P('_filterCache',null); } this._$P._isHaveGlowFilter && this._set$P('_isHaveGlowFilter',false); } _super.prototype._setDisplay.call(this,value); } /** *把一个动画对象绑定到当前GridSprite *@param sprite 动画的显示对象 */ __proto.addAniSprite=function(sprite){ if (this.aniSpriteArray==null){ this.aniSpriteArray=[]; } this.aniSpriteArray.push(sprite); } /** *显示当前GridSprite,并把上面的动画全部显示 */ __proto.show=function(){ if (!this.visible){ this.visible=true; if (!this.isAloneObject){ var tParent; tParent=this.parent; if (tParent){ tParent.showGridSprite(this); } } if (!Render.isWebGL&&this._map.autoCache){ this.cacheAs=this._map.autoCacheType; } if (this.aniSpriteArray==null){ return; }; var tAniSprite; for (var i=0;i < this.aniSpriteArray.length;i++){ tAniSprite=this.aniSpriteArray[i]; tAniSprite.show(); } } } /** *隐藏当前GridSprite,并把上面绑定的动画全部移除 */ __proto.hide=function(){ if (this.visible){ this.visible=false; if (!this.isAloneObject){ var tParent; tParent=this.parent; if (tParent){ tParent.hideGridSprite(this); } } if (!Render.isWebGL&&this._map.autoCache){ this.cacheAs="none"; } if (this.aniSpriteArray==null){ return; }; var tAniSprite; for (var i=0;i < this.aniSpriteArray.length;i++){ tAniSprite=this.aniSpriteArray[i]; tAniSprite.hide(); } } } /** *刷新坐标,当我们自己控制一个GridSprite移动时,需要调用此函数,手动刷新 */ __proto.updatePos=function(){ if (this.isAloneObject){ if (this._map){ this.x=this.relativeX; this.y=this.relativeY; } if (this.x < 0 || this.x > this._map.viewPortWidth || this.y < 0 || this.y > this._map.viewPortHeight){ this.hide(); }else { this.show(); } }else { if (this._map){ this.x=this.relativeX; this.y=this.relativeY; } } } /** *重置当前对象的所有属性 */ __proto.clearAll=function(){ if (this._map){ this._map=null; } this.visible=false; var tAniSprite; if (this.aniSpriteArray !=null){ for (var i=0;i < this.aniSpriteArray.length;i++){ tAniSprite=this.aniSpriteArray[i]; tAniSprite.clearAll(); } } this.destroy(); this.relativeX=0; this.relativeY=0; this.isHaveAnimation=false; this.aniSpriteArray=null; this.drawImageNum=0; } return GridSprite; })(Sprite) /** *地图支持多层渲染(例如,地表层,植被层,建筑层等) *本类就是层级类 *@author ... */ //class laya.map.MapLayer extends laya.display.Sprite var MapLayer=(function(_super){ function MapLayer(){ this._map=null; this._mapData=null; this._tileWidthHalf=0; this._tileHeightHalf=0; this._mapWidthHalf=0; this._mapHeightHalf=0; /** *@private */ this._gridSpriteArray=[]; this._objDic=null; //用来做字典,方便查询 this._dataDic=null; //临时变量 this._properties=null; /**被合到的层*/ this.tarLayer=null; /**当前Layer的名称*/ this.layerName=null; /** *当前需要更新的gridSprite列表 */ this._showGridList=[]; /** *活动对象列表,活动对象不管是否显示都需要更新 */ this._aloneObjs=[]; MapLayer.__super.call(this); this._tempMapPos=new Point(); } __class(MapLayer,'laya.map.MapLayer',_super); var __proto=MapLayer.prototype; /** *解析LAYER数据,以及初始化一些数据 *@param layerData 地图数据中,layer数据的引用 *@param map 地图的引用 */ __proto.init=function(layerData,map){ this._map=map; this._mapData=layerData.data; var tHeight=layerData.height; var tWidth=layerData.width; var tTileW=map.tileWidth; var tTileH=map.tileHeight; this.layerName=layerData.name; this._properties=layerData.properties; this.alpha=layerData.opacity; this._tileWidthHalf=tTileW / 2; this._tileHeightHalf=tTileH / 2; this._mapWidthHalf=this._map.width / 2-this._tileWidthHalf; this._mapHeightHalf=this._map.height / 2; switch (layerData.type){ case "tilelayer": break ; case "objectgroup":; var tObjectGid=0; var tArray=layerData.objects; if (tArray.length > 0){ this._objDic={}; this._dataDic={}; }; var tObjectData; var tObjWidth=NaN; var tObjHeight=NaN; for (var i=0;i < tArray.length;i++){ tObjectData=tArray[i]; this._dataDic[tObjectData.name]=tObjectData; if (tObjectData.visible==true){ tObjWidth=tObjectData.width; tObjHeight=tObjectData.height; var tSprite=map.getSprite(tObjectData.gid,tObjWidth,tObjHeight); if (tSprite !=null){ switch (this._map.orientation){ case /*laya.map.TiledMap.ORIENTATION_ISOMETRIC*/"isometric": this.getScreenPositionByTilePos(tObjectData.x / tTileH,tObjectData.y / tTileH,Point.TEMP); tSprite.pivot(tObjWidth / 2,tObjHeight / 2); tSprite.rotation=tObjectData.rotation; tSprite.x=tSprite.relativeX=Point.TEMP.x+this._map.viewPortX; tSprite.y=tSprite.relativeY=Point.TEMP.y+this._map.viewPortY-tObjHeight / 2; break ; case /*laya.map.TiledMap.ORIENTATION_STAGGERED*/"staggered": tSprite.pivot(tObjWidth / 2,tObjHeight / 2); tSprite.rotation=tObjectData.rotation; tSprite.x=tSprite.relativeX=tObjectData.x+tObjWidth / 2; tSprite.y=tSprite.relativeY=tObjectData.y-tObjHeight / 2; break ; case /*laya.map.TiledMap.ORIENTATION_ORTHOGONAL*/"orthogonal": tSprite.pivot(tObjWidth / 2,tObjHeight / 2); tSprite.rotation=tObjectData.rotation; tSprite.x=tSprite.relativeX=tObjectData.x+tObjWidth / 2; tSprite.y=tSprite.relativeY=tObjectData.y-tObjHeight / 2; break ; case /*laya.map.TiledMap.ORIENTATION_HEXAGONAL*/"hexagonal": tSprite.x=tSprite.relativeX=tObjectData.x; tSprite.y=tSprite.relativeY=tObjectData.y; break ; } this.addChild(tSprite); this._gridSpriteArray.push(tSprite); if (tSprite.isAloneObject){ this._showGridList.push(tSprite); this._aloneObjs.push(tSprite); } this._objDic[tObjectData.name]=tSprite; } } } break ; } } /** *通过名字获取控制对象,如果找不到返回为null *@param objName 所要获取对象的名字 *@return */ __proto.getObjectByName=function(objName){ if (this._objDic){ return this._objDic[objName]; } return null; } /** *通过名字获取数据,如果找不到返回为null *@param objName 所要获取对象的名字 *@return */ __proto.getObjectDataByName=function(objName){ if (this._dataDic){ return this._dataDic[objName]; } return null; } /** *得到地图层的自定义属性 *@param name *@return */ __proto.getLayerProperties=function(name){ if (this._properties){ return this._properties[name]; } return null; } /** *得到指定格子的数据 *@param tileX 格子坐标X *@param tileY 格子坐标Y *@return */ __proto.getTileData=function(tileX,tileY){ if (tileY >=0 && tileY < this._map.numRowsTile && tileX >=0 && tileX < this._map.numColumnsTile){ var tIndex=tileY *this._map.numColumnsTile+tileX; var tMapData=this._mapData; if (tMapData !=null && tIndex < tMapData.length){ return tMapData[tIndex]; } } return 0; } /** *通过地图坐标得到屏幕坐标 *@param tileX 格子坐标X *@param tileY 格子坐标Y *@param screenPos 把计算好的屏幕坐标数据,放到此对象中 */ __proto.getScreenPositionByTilePos=function(tileX,tileY,screenPos){ if (screenPos){ switch (this._map.orientation){ case /*laya.map.TiledMap.ORIENTATION_ISOMETRIC*/"isometric": screenPos.x=this._map.width / 2-(tileY-tileX)*this._tileWidthHalf; screenPos.y=(tileY+tileX)*this._tileHeightHalf; break ; case /*laya.map.TiledMap.ORIENTATION_STAGGERED*/"staggered": tileX=Math.floor(tileX); tileY=Math.floor(tileY); screenPos.x=tileX *this._map.tileWidth+(tileY & 1)*this._tileWidthHalf; screenPos.y=tileY *this._tileHeightHalf; break ; case /*laya.map.TiledMap.ORIENTATION_ORTHOGONAL*/"orthogonal": screenPos.x=tileX *this._map.tileWidth; screenPos.y=tileY *this._map.tileHeight; break ; case /*laya.map.TiledMap.ORIENTATION_HEXAGONAL*/"hexagonal": tileX=Math.floor(tileX); tileY=Math.floor(tileY); var tTileHeight=this._map.tileHeight *2 / 3; screenPos.x=(tileX *this._map.tileWidth+tileY % 2 *this._tileWidthHalf)% this._map.gridWidth; screenPos.y=(tileY *tTileHeight)% this._map.gridHeight; break ; } screenPos.x=(screenPos.x+this._map.viewPortX)*this._map.scale; screenPos.y=(screenPos.y+this._map.viewPortY)*this._map.scale; } } /** *通过屏幕坐标来获取选中格子的数据 *@param screenX 屏幕坐标x *@param screenY 屏幕坐标y *@return */ __proto.getTileDataByScreenPos=function(screenX,screenY){ var tData=0; if (this.getTilePositionByScreenPos(screenX,screenY,this._tempMapPos)){ tData=this.getTileData(Math.floor(this._tempMapPos.x),Math.floor(this._tempMapPos.y)); } return tData; } /** *通过屏幕坐标来获取选中格子的索引 *@param screenX 屏幕坐标x *@param screenY 屏幕坐标y *@param result 把计算好的格子坐标,放到此对象中 *@return */ __proto.getTilePositionByScreenPos=function(screenX,screenY,result){ screenX=screenX/this._map.scale-this._map.viewPortX; screenY=screenY/this._map.scale-this._map.viewPortY; var tTileW=this._map.tileWidth; var tTileH=this._map.tileHeight; var tV=0; var tU=0; switch (this._map.orientation){ case /*laya.map.TiledMap.ORIENTATION_ISOMETRIC*/"isometric":; var tDirX=screenX-this._map.width / 2; var tDirY=screenY; tV=-(tDirX / tTileW-tDirY / tTileH); tU=tDirX / tTileW+tDirY / tTileH; if (result){ result.x=tU; result.y=tV; } return true; break ; case /*laya.map.TiledMap.ORIENTATION_STAGGERED*/"staggered": if (result){ var cx=0,cy=0,rx=0,ry=0; cx=Math.floor(screenX / tTileW)*tTileW+tTileW / 2; cy=Math.floor(screenY / tTileH)*tTileH+tTileH / 2; rx=(screenX-cx)*tTileH / 2; ry=(screenY-cy)*tTileW / 2; if (Math.abs(rx)+Math.abs(ry)<=tTileW *tTileH / 4){ tU=Math.floor(screenX / tTileW); tV=Math.floor(screenY / tTileH)*2; }else { screenX=screenX-tTileW / 2; tU=Math.floor(screenX / tTileW)+1; screenY=screenY-tTileH / 2; tV=Math.floor(screenY / tTileH)*2+1; } result.x=tU-(tV & 1); result.y=tV; } return true; break ; case /*laya.map.TiledMap.ORIENTATION_ORTHOGONAL*/"orthogonal": tU=screenX / tTileW; tV=screenY / tTileH; if (result){ result.x=tU; result.y=tV; } return true; break ; case /*laya.map.TiledMap.ORIENTATION_HEXAGONAL*/"hexagonal":; var tTileHeight=tTileH *2 / 3; tV=screenY / tTileHeight; tU=(screenX-tV % 2 *this._tileWidthHalf)/ tTileW; if (result){ result.x=tU; result.y=tV; } break ; } return false; } /** *得到一个GridSprite *@param gridX 当前Grid的X轴索引 *@param gridY 当前Grid的Y轴索引 *@return 一个GridSprite对象 */ __proto.getDrawSprite=function(gridX,gridY){ var tSprite=new GridSprite(); tSprite.relativeX=gridX *this._map.gridWidth; tSprite.relativeY=gridY *this._map.gridHeight; tSprite.initData(this._map); tSprite.updatePos(); this._gridSpriteArray.push(tSprite); return tSprite; } /** *将gridSprite设为显示状态 *@param gridSprite */ __proto.showGridSprite=function(gridSprite){ var gridList=this._showGridList; var i=0,len=0; len=gridList.length; var ok_i=-1; var tGridSprite; for (i=0;i < len;i++){ tGridSprite=gridList[i]; if (tGridSprite==gridSprite)return; if (!tGridSprite.isAloneObject && !tGridSprite.visible){ ok_i=i; } } if (ok_i >=0){ gridList[ok_i]=gridSprite; }else{ gridList.push(gridSprite); } } /** *将gridSprite设为隐藏状态 *@param gridSprite * */ __proto.hideGridSprite=function(gridSprite){ gridSprite.visible=false; } /** *更新此层中块的坐标 *手动刷新的目的是,保持层级的宽和高保持最小,加快渲染 */ __proto.updateGridPos=function(){ var tSprite; var tList; tList=this._showGridList; var len=0; len=tList.length; for (var i=0;i < len;i++){ tSprite=tList[i]; if ((tSprite._style.visible || tSprite.isAloneObject)&& tSprite.drawImageNum > 0){ tSprite.updatePos(); } } } /** *更新此层中的活动对象 */ __proto.updateAloneObject=function(){ var tSprite; var tList; tList=this._aloneObjs; var len=0; len=tList.length; for (var i=0;i < len;i++){ tSprite=tList[i]; if (tSprite.drawImageNum > 0){ tSprite.updatePos(); } } } /** *渲染时使用需要更新的列表进行渲染,减少遍历 *@param context *@param x *@param y * */ __proto.render=function(context,x,y){ var childs=this._childs; this._childs=this._showGridList; _super.prototype.render.call(this,context,x,y); this._childs=childs; } /** *@private *把tile画到指定的显示对象上 *@param gridSprite 被指定显示的目标 *@param tileX 格子的X轴坐标 *@param tileY 格子的Y轴坐标 *@return */ __proto.drawTileTexture=function(gridSprite,tileX,tileY){ if (tileY >=0 && tileY < this._map.numRowsTile && tileX >=0 && tileX < this._map.numColumnsTile){ var tIndex=tileY *this._map.numColumnsTile+tileX; var tMapData=this._mapData; if (tMapData !=null && tIndex < tMapData.length){ if (tMapData[tIndex] !=0){ var tTileTexSet=this._map.getTexture(tMapData[tIndex]); if (tTileTexSet){ var tX=0; var tY=0; var tTexture=tTileTexSet.texture; switch (this._map.orientation){ case /*laya.map.TiledMap.ORIENTATION_STAGGERED*/"staggered": tX=tileX *this._map.tileWidth % this._map.gridWidth+(tileY & 1)*this._tileWidthHalf; tY=tileY *this._tileHeightHalf % this._map.gridHeight; break ; case /*laya.map.TiledMap.ORIENTATION_ORTHOGONAL*/"orthogonal": tX=tileX *this._map.tileWidth % this._map.gridWidth; tY=tileY *this._map.tileHeight % this._map.gridHeight; break ; case /*laya.map.TiledMap.ORIENTATION_ISOMETRIC*/"isometric": tX=(this._mapWidthHalf+(tileX-tileY)*this._tileWidthHalf)% this._map.gridWidth; tY=((tileX+tileY)*this._tileHeightHalf)% this._map.gridHeight; break ; case /*laya.map.TiledMap.ORIENTATION_HEXAGONAL*/"hexagonal":; var tTileHeight=this._map.tileHeight *2 / 3; tX=(tileX *this._map.tileWidth+tileY % 2 *this._tileWidthHalf)% this._map.gridWidth; tY=(tileY *tTileHeight)% this._map.gridHeight; break ; } if (tTileTexSet.isAnimation){ var tAnimationSprite=new TileAniSprite(); tAnimationSprite.x=tX; tAnimationSprite.y=tY; tAnimationSprite.setTileTextureSet(tIndex.toString(),tTileTexSet); gridSprite.addAniSprite(tAnimationSprite); gridSprite.addChild(tAnimationSprite); gridSprite.isHaveAnimation=true; }else { gridSprite.graphics.drawTexture(tTileTexSet.texture,tX+tTileTexSet.offX,tY+tTileTexSet.offY); } return true; } } } } return false; } /** *@private *清理当前对象 */ __proto.clearAll=function(){ this._map=null; this._mapData=null; this._tileWidthHalf=0; this._tileHeightHalf=0; this._mapWidthHalf=0; this._mapHeightHalf=0; this.layerName=null; var i=0; if (this._objDic){ for (var p in this._objDic){ delete this._objDic[p]; } this._objDic=null; } if (this._dataDic){ for (p in this._dataDic){ delete this._dataDic[p]; } this._dataDic=null; }; var tGridSprite; for (i=0;i < this._gridSpriteArray.length;i++){ tGridSprite=this._gridSpriteArray[i]; tGridSprite.clearAll(); } this._properties=null; this._tempMapPos=null; this.tarLayer=null; } return MapLayer; })(Sprite) /** *TildMap的动画显示对象(一个动画(TileTexSet),可以绑定多个动画显示对象(TileAniSprite)) *@author ... */ //class laya.map.TileAniSprite extends laya.display.Sprite var TileAniSprite=(function(_super){ function TileAniSprite(){ this._tileTextureSet=null; //动画的引用 this._aniName=null; TileAniSprite.__super.call(this); } __class(TileAniSprite,'laya.map.TileAniSprite',_super); var __proto=TileAniSprite.prototype; /** *确定当前显示对象的名称以及属于哪个动画 *@param aniName 当前动画显示对象的名字,名字唯一 *@param tileTextureSet 当前显示对象属于哪个动画(一个动画,可以绑定多个同类显示对象) */ __proto.setTileTextureSet=function(aniName,tileTextureSet){ this._aniName=aniName; this._tileTextureSet=tileTextureSet; tileTextureSet.addAniSprite(this._aniName,this); } /** *把当前动画加入到对应的动画刷新列表中 */ __proto.show=function(){ this._tileTextureSet.addAniSprite(this._aniName,this); } /** *把当前动画从对应的动画刷新列表中移除 */ __proto.hide=function(){ this._tileTextureSet.removeAniSprite(this._aniName); } /** *清理 */ __proto.clearAll=function(){ this._tileTextureSet.removeAniSprite(this._aniName); this.destroy(); this._tileTextureSet=null; this._aniName=null; } return TileAniSprite; })(Sprite) Laya.__init([TiledMap]); })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.ttmini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Config=Laya.Config,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,RunDriver=laya.utils.RunDriver; var Sound=laya.media.Sound,SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager,URL=laya.net.URL; var Utils=laya.utils.Utils; /**@private **/ //class laya.tt.mini.MiniFileMgr var MiniFileMgr$8=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.tt.mini.MiniFileMgr',null,'MiniFileMgr$8'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=TTMiniAdapter.nativefiles.length;i=totalSize)){ if(data.size > TTMiniAdapter.minClearSize) TTMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > TTMiniAdapter.minClearSize) TTMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=TTMiniAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.tt.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i=0 ? "/" :"\\"; var idx=url.lastIndexOf(split); var folderPath=idx >=0 ? url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[url.replace(".json",".png")]; } for(i=0;i\s+<'); try { /*__JS__ */rst=(new window.Parser.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } TTMiniAdapter.idx=1; __static(TTMiniAdapter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir","wxlocal"];} ]); return TTMiniAdapter; })() /**@private **/ //class laya.tt.mini.MiniAccelerator extends laya.events.EventDispatcher var MiniAccelerator$8=(function(_super){ function MiniAccelerator(){ MiniAccelerator.__super.call(this); } __class(MiniAccelerator,'laya.tt.mini.MiniAccelerator',_super,'MiniAccelerator$8'); var __proto=MiniAccelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); MiniAccelerator.startListen(this["onDeviceOrientationChange"]); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) MiniAccelerator.stopListen(); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } MiniAccelerator.__init__=function(){ try{ var Acc; Acc=/*__JS__ */laya.device.motion.Accelerator; if (!Acc)return; Acc["prototype"]["on"]=MiniAccelerator["prototype"]["on"]; Acc["prototype"]["off"]=MiniAccelerator["prototype"]["off"]; }catch (e){ } } MiniAccelerator.startListen=function(callBack){ MiniAccelerator._callBack=callBack; if (MiniAccelerator._isListening)return; MiniAccelerator._isListening=true; try{ TTMiniAdapter.window.wx.onAccelerometerChange(laya.tt.mini.MiniAccelerator.onAccelerometerChange); }catch(e){} } MiniAccelerator.stopListen=function(){ MiniAccelerator._isListening=false; try{ TTMiniAdapter.window.wx.stopAccelerometer({}); }catch(e){} } MiniAccelerator.onAccelerometerChange=function(res){ var e; e={}; e.acceleration=res; e.accelerationIncludingGravity=res; e.rotationRate={}; if (MiniAccelerator._callBack !=null){ MiniAccelerator._callBack(e); } } MiniAccelerator._isListening=false; MiniAccelerator._callBack=null; return MiniAccelerator; })(EventDispatcher) /**@private **/ //class laya.tt.mini.MiniLoader extends laya.events.EventDispatcher var MiniLoader$8=(function(_super){ function MiniLoader(){ MiniLoader.__super.call(this); } __class(MiniLoader,'laya.tt.mini.MiniLoader',_super,'MiniLoader$8'); var __proto=MiniLoader.prototype; /** *@private *@param url *@param type *@param cache *@param group *@param ignoreCache */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); var thisLoader=this; thisLoader._url=url; if (url.indexOf("data:image")===0)thisLoader._type=type=/*laya.net.Loader.IMAGE*/"image"; else { thisLoader._type=type || (type=thisLoader.getTypeFromUrl(url)); } thisLoader._cache=cache; thisLoader._data=null; if (!ignoreCache && Loader.loadedMap[URL.formatURL(url)]){ thisLoader._data=Loader.loadedMap[URL.formatURL(url)]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",thisLoader._data); return; } if (Loader.parserMap[type] !=null){ thisLoader._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; }; var encoding=TTMiniAdapter.getUrlEncode(url,type); var urlType=Utils.getFileExtension(url); if ((MiniLoader._fileTypeArr.indexOf(urlType)!=-1)|| type==/*laya.net.Loader.IMAGE*/"image"){ TTMiniAdapter.EnvConfig.load.call(this,url,type,cache,group,ignoreCache); }else { if(TTMiniAdapter.isZiYu && !MiniFileMgr$8.ziyuFileData[url]){ url=URL.formatURL(url); } if(TTMiniAdapter.isZiYu && MiniFileMgr$8.ziyuFileData[url]){ var tempData=MiniFileMgr$8.ziyuFileData[url]; thisLoader.onLoaded(tempData); return; } if (!MiniFileMgr$8.getFileInfo(URL.formatURL(url))){ if (MiniFileMgr$8.isLocalNativeFile(url)){ if (TTMiniAdapter.subNativeFiles && TTMiniAdapter.subNativeheads.length==0){ for (var key in TTMiniAdapter.subNativeFiles){ var tempArr=TTMiniAdapter.subNativeFiles[key]; TTMiniAdapter.subNativeheads=TTMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ TTMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(TTMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && TTMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=TTMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } if(type==/*laya.net.Loader.SOUND*/"sound"){ thisLoader._loadSound(url); }else{ MiniFileMgr$8.read(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); } return; }; var tempUrl=url; var tempurl=URL.formatURL(url); if (tempurl.indexOf(TTMiniAdapter.window.tt.env.USER_DATA_PATH)==-1 &&(url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)&& !TTMiniAdapter.AutoCacheDownFile){ if(type==/*laya.net.Loader.SOUND*/"sound"){ thisLoader._loadSound(url); }else{ TTMiniAdapter.EnvConfig.load.call(thisLoader,tempUrl,type,cache,group,ignoreCache); } }else { fileObj=MiniFileMgr$8.getFileInfo(url); if(fileObj){ fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; MiniFileMgr$8.readFile(fileObj.url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else if (thisLoader.type=="image" || thisLoader.type=="htmlimage"){ TTMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } else{ url=URL.formatURL(url); if(type !=/*laya.net.Loader.IMAGE*/"image" && ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1)|| MiniFileMgr$8.isLocalNativeFile(url))){ MiniFileMgr$8.readFile(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else{ MiniFileMgr$8.downFiles(encodeURI(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url,true); } } } }else { var fileObj=MiniFileMgr$8.getFileInfo(URL.formatURL(url)); fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; var nativepath=MiniFileMgr$8.getFileNativePath(fileObj.md5); MiniFileMgr$8.readFile(nativepath,fileObj.encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),URL.formatURL(url)); } } } /** *private *@param url **/ __proto._loadSound=function(url){ var thisLoader=this; var fileNativeUrl; if (MiniFileMgr$8.isLocalNativeFile(url)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="" && (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)) fileNativeUrl=url.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } laya.tt.mini.MiniLoader.onDownLoadCallBack(url,thisLoader,0); }else{ var tempurl=URL.formatURL(url); if (!MiniFileMgr$8.isLocalNativeFile(url)&& (tempurl.indexOf("http://")==-1 && tempurl.indexOf("https://")==-1)|| (tempurl.indexOf(TTMiniAdapter.window.tt.env.USER_DATA_PATH)!=-1)){ laya.tt.mini.MiniLoader.onDownLoadCallBack(url,thisLoader,0); }else{ MiniFileMgr$8.downOtherFiles(encodeURI(tempurl),Handler.create(MiniLoader,laya.tt.mini.MiniLoader.onDownLoadCallBack,[tempurl,thisLoader]),tempurl); } } } MiniLoader.onDownLoadCallBack=function(sourceUrl,thisLoader,errorCode,tempFilePath){ if (!errorCode){ var fileNativeUrl; if(TTMiniAdapter.autoCacheFile){ if(!tempFilePath){ if (MiniFileMgr$8.isLocalNativeFile(sourceUrl)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=sourceUrl; if(tempStr !="" && (sourceUrl.indexOf("http://")!=-1 || sourceUrl.indexOf("https://")!=-1)) fileNativeUrl=sourceUrl.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } }else{ var fileObj=MiniFileMgr$8.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$8.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=sourceUrl; } } }else{ fileNativeUrl=tempFilePath; } } sourceUrl=fileNativeUrl; var sound=new SoundManager._soundClass(); sound.load(encodeURI(sourceUrl)); thisLoader.onLoaded(sound); }else{ thisLoader.event(/*laya.events.Event.ERROR*/"error","Load sound failed"); } } MiniLoader.onReadNativeCallBack=function(encoding,url,type,cache,group,ignoreCache,thisLoader,errorCode,data){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); (errorCode===void 0)&& (errorCode=0); if (!errorCode){ var tempData; if (type==/*laya.net.Loader.JSON*/"json" || type==/*laya.net.Loader.ATLAS*/"atlas"){ tempData=TTMiniAdapter.getJson(data.data); }else if (type==/*laya.net.Loader.XML*/"xml"){ tempData=Utils.parseXMLFromString(data.data); }else { tempData=data.data; } if(!TTMiniAdapter.isZiYu &&TTMiniAdapter.isPosMsgYu && type !=/*laya.net.Loader.BUFFER*/"arraybuffer" && TTMiniAdapter.window.tt){ TTMiniAdapter.window.tt.postMessage({url:url,data:tempData,isLoad:"filedata"}); } thisLoader.onLoaded(tempData); }else if (errorCode==1){ console.log("-----------本地加载失败,尝试外网加载----url:"+url); TTMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } } __static(MiniLoader, ['_fileTypeArr',function(){return this._fileTypeArr=['png','jpg','bmp','jpeg','gif'];} ]); return MiniLoader; })(EventDispatcher) /**@private **/ //class laya.tt.mini.MiniSound extends laya.events.EventDispatcher var MiniSound$8=(function(_super){ function MiniSound(){ /**@private **/ this._sound=null; /** *@private *声音URL */ this.url=null; /** *@private *是否已加载完成 */ this.loaded=false; /**@private **/ this.readyUrl=null; MiniSound.__super.call(this); } __class(MiniSound,'laya.tt.mini.MiniSound',_super,'MiniSound$8'); var __proto=MiniSound.prototype; /** *@private *加载声音。 *@param url 地址。 * */ __proto.load=function(url){ if (!MiniFileMgr$8.isLocalNativeFile(url)){ url=URL.formatURL(url); }else{ if (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1){ if(MiniFileMgr$8.loadPath !=""){ url=url.split(MiniFileMgr$8.loadPath)[1]; }else{ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; if(tempStr !="") url=url.split(tempStr)[1]; } } } this.url=url; this.readyUrl=url; if (MiniSound._audioCache[this.readyUrl]){ this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if(TTMiniAdapter.autoCacheFile&&MiniFileMgr$8.getFileInfo(url)){ this.onDownLoadCallBack(url,0); }else{ if(!TTMiniAdapter.autoCacheFile){ this.onDownLoadCallBack(url,0); }else{ if (MiniFileMgr$8.isLocalNativeFile(url)){ tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="") url=url.split(tempStr)[1]; if (!url){ url=tempUrl; } if (TTMiniAdapter.subNativeFiles && TTMiniAdapter.subNativeheads.length==0){ for (var key in TTMiniAdapter.subNativeFiles){ var tempArr=TTMiniAdapter.subNativeFiles[key]; TTMiniAdapter.subNativeheads=TTMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ TTMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(TTMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && TTMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=TTMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } this.onDownLoadCallBack(url,0); }else{ MiniFileMgr$8.downOtherFiles(encodeURI(url),Handler.create(this,this.onDownLoadCallBack,[url]),url); } } } } /**@private **/ __proto.onDownLoadCallBack=function(sourceUrl,errorCode){ if (!errorCode){ var fileNativeUrl; if(TTMiniAdapter.autoCacheFile){ if (MiniFileMgr$8.isLocalNativeFile(sourceUrl)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=sourceUrl; if(tempStr !="" && (sourceUrl.indexOf("http://")!=-1 || sourceUrl.indexOf("https://")!=-1)) fileNativeUrl=sourceUrl.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } }else{ var fileObj=MiniFileMgr$8.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$8.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=encodeURI(sourceUrl); } } this._sound=MiniSound._createSound(); this._sound.src=this.url=fileNativeUrl; }else{ this._sound=MiniSound._createSound(); this._sound.src=encodeURI(sourceUrl); } this._sound.onCanplay(MiniSound.bindToThis(this.onCanPlay,this)); this._sound.onError(MiniSound.bindToThis(this.onError,this)); }else{ this.event(/*laya.events.Event.ERROR*/"error"); } } /**@private **/ __proto.onError=function(error){ this.event(/*laya.events.Event.ERROR*/"error"); this._sound.offError(null); } /**@private **/ __proto.onCanPlay=function(){ this.loaded=true; this.event(/*laya.events.Event.COMPLETE*/"complete"); this._sound.offCanplay(null); } /** *@private *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); var tSound; if (this.url==SoundManager._tMusic){ if (!MiniSound._musicAudio)MiniSound._musicAudio=MiniSound._createSound(); tSound=MiniSound._musicAudio; }else { if(MiniSound._audioCache[this.readyUrl]){ tSound=MiniSound._audioCache[this.readyUrl]._sound; }else{ tSound=MiniSound._createSound(); } } if(TTMiniAdapter.autoCacheFile&&MiniFileMgr$8.getFileInfo(this.url)){ var fileNativeUrl; var fileObj=MiniFileMgr$8.getFileInfo(this.url); var fileMd5Name=fileObj.md5; tSound.src=this.url=MiniFileMgr$8.getFileNativePath(fileMd5Name); }else{ tSound.src=encodeURI(this.url); }; var channel=new MiniSoundChannel$8(tSound,this); channel.url=this.url; channel.loops=loops; channel.loop=(loops===0 ? true :false); channel.startTime=startTime; channel.play(); SoundManager.addChannel(channel); return channel; } /** *@private *释放声音资源。 * */ __proto.dispose=function(){ var ad=MiniSound._audioCache[this.readyUrl]; if (ad){ ad.src=""; if(ad._sound){ ad._sound.destroy(); ad._sound=null; ad=null; } delete MiniSound._audioCache[this.readyUrl]; } if(this._sound){ this._sound.destroy(); this._sound=null; } this.url=this.readyUrl=null; } /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ return this._sound.duration; }); MiniSound._createSound=function(){ MiniSound._id++; return TTMiniAdapter.window.tt.createInnerAudioContext(); } MiniSound.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } MiniSound._musicAudio=null; MiniSound._id=0; MiniSound._audioCache={}; return MiniSound; })(EventDispatcher) /**@private **/ //class laya.tt.mini.MiniSoundChannel extends laya.media.SoundChannel var MiniSoundChannel$8=(function(_super){ function MiniSoundChannel(audio,miniSound){ /**@private **/ this._audio=null; /**@private **/ this._onEnd=null; /**@private **/ this._miniSound=null; MiniSoundChannel.__super.call(this); this._audio=audio; this._miniSound=miniSound; this._onEnd=MiniSoundChannel.bindToThis(this.__onEnd,this); audio.onEnded(this._onEnd); } __class(MiniSoundChannel,'laya.tt.mini.MiniSoundChannel',_super,'MiniSoundChannel$8'); var __proto=MiniSoundChannel.prototype; /**@private **/ __proto.__onEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.stop(); this._audio.offEnded(null); this._audio.destroy(); this._audio=null; this._miniSound=null; this._onEnd=null; } /**@private **/ __proto.pause=function(){ this.isStopped=true; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',null,function(time){ if(this._audio){ this._audio.startTime=time; } }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ return this._audio.autoplay; },function(value){ this._audio.autoplay=value; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ return this._audio.loop; },function(value){ this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) /** *视频类 *@author xiaosong *@date-2019-04-22 */ //class laya.tt.mini.MiniVideo var MiniVideo$6=(function(){ function MiniVideo(width,height){ /**视频是否播放结束**/ this.videoend=false; this.videourl=""; this.videoElement=null; this.onPlayFunc=null; this.onEndedFunC=null; /**视频的总时⻓长,单位为秒**/ this._duration=NaN; /**视频播放的当前位置**/ this.position=NaN; (width===void 0)&& (width=320); (height===void 0)&& (height=240); this.videoElement=TTMiniAdapter.window.tt.createVideo({width:width,height:height,autoplay:true}); } __class(MiniVideo,'laya.tt.mini.MiniVideo',null,'MiniVideo$6'); var __proto=MiniVideo.prototype; __proto.on=function(eventType,ths,callBack){ if(eventType=="loadedmetadata"){ this.onPlayFunc=callBack.bind(ths); this.videoElement.onPlay=this.onPlayFunction.bind(this); }else if(eventType=="ended"){ this.onEndedFunC=callBack.bind(ths); this.videoElement.onEnded=this.onEndedFunction.bind(this); } this.videoElement.onTimeUpdate=this.onTimeUpdateFunc.bind(this); } __proto.onTimeUpdateFunc=function(data){ this.position=data.position; this._duration=data.duration; } __proto.onPlayFunction=function(){ if(this.videoElement) this.videoElement.readyState=200; console.log("=====视频加载完成========"); this.onPlayFunc !=null && this.onPlayFunc(); } __proto.onEndedFunction=function(){ if(!this.videoElement) return; this.videoend=true; console.log("=====视频播放完毕========"); this.onEndedFunC !=null && this.onEndedFunC(); } __proto.off=function(eventType,ths,callBack){ if(eventType=="loadedmetadata"){ this.onPlayFunc=callBack.bind(ths); this.videoElement.offPlay=this.onPlayFunction.bind(this); }else if(eventType=="ended"){ this.onEndedFunC=callBack.bind(ths); this.videoElement.offEnded=this.onEndedFunction.bind(this); } } /** *设置播放源。 *@param url 播放源路径。 */ __proto.load=function(url){ if(!this.videoElement) return; this.videoElement.src=url; } /** *开始播放视频。 */ __proto.play=function(){ if(!this.videoElement) return; this.videoend=false; this.videoElement.play(); } /** *暂停视频播放。 */ __proto.pause=function(){ if(!this.videoElement) return; this.videoend=true; this.videoElement.pause(); } /** *设置大小 *@param width *@param height */ __proto.size=function(width,height){ if(!this.videoElement) return; this.videoElement.width=width; this.videoElement.height=height; } __proto.destroy=function(){ if(this.videoElement) this.videoElement.destroy(); this.videoElement=null; this.onEndedFunC=null; this.onPlayFunc=null; this.videoend=false; this.videourl=null; } /** *重新加载视频。 */ __proto.reload=function(){ if(!this.videoElement) return; this.videoElement.src=this.videourl; } /** *获取视频长度(秒)。ready事件触发后可用。 */ __getset(0,__proto,'duration',function(){ return this._duration; }); /** *返回视频是否暂停 */ __getset(0,__proto,'paused',function(){ if(!this.videoElement) return false; return this.videoElement.paused; }); /** *设置或返回音频/视频是否应在结束时重新播放。 */ __getset(0,__proto,'loop',function(){ if(!this.videoElement) return false; return this.videoElement.loop; },function(value){ if(!this.videoElement) return; this.videoElement.loop=value; }); /** *设置和获取当前播放头位置。 */ __getset(0,__proto,'currentTime',function(){ if(!this.videoElement) return 0; return this.videoElement.initialTime; },function(value){ if(!this.videoElement) return; this.videoElement.initialTime=value; }); /** *返回音频/视频的播放是否已结束 */ __getset(0,__proto,'ended',function(){ return this.videoend; }); /** *获取和设置静音状态。 */ __getset(0,__proto,'muted',function(){ if(!this.videoElement) return false; return this.videoElement.muted; },function(value){ if(!this.videoElement) return; this.videoElement.muted=value; }); /** *获取视频源尺寸。ready事件触发后可用。 */ __getset(0,__proto,'videoWidth',function(){ if(!this.videoElement) return 0; return this.videoElement.width; }); __getset(0,__proto,'videoHeight',function(){ if(!this.videoElement) return 0; return this.videoElement.height; }); /** *playbackRate 属性设置或返回音频/视频的当前播放速度。如: *
      *
    • 1.0 正常速度
    • *
    • 0.5 半速(更慢)
    • *
    • 2.0 倍速(更快)
    • *
    • -1.0 向后,正常速度
    • *
    • -0.5 向后,半速
    • *
    *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ if(!this.videoElement) return 0; return this.videoElement.playbackRate; },function(value){ if(!this.videoElement) return; this.videoElement.playbackRate=value; }); __getset(0,__proto,'x',function(){ if(!this.videoElement) return 0; return this.videoElement.x; },function(value){ if(!this.videoElement) return; this.videoElement.x=value; }); __getset(0,__proto,'y',function(){ if(!this.videoElement) return 0; return this.videoElement.y; },function(value){ if(!this.videoElement) return; this.videoElement.y=value; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.src; }); MiniVideo.__init__=function(){ /*__JS__ */laya.device.media.Video=MiniVideo; } return MiniVideo; })() })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.ui.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Animation=laya.display.Animation,Browser=laya.utils.Browser,ClassUtils=laya.utils.ClassUtils,ColorFilter=laya.filters.ColorFilter; var Ease=laya.utils.Ease,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher,Font=laya.display.css.Font; var FrameAnimation=laya.display.FrameAnimation,Graphics=laya.display.Graphics,Handler=laya.utils.Handler; var HttpRequest=laya.net.HttpRequest,Input=laya.display.Input,Loader=laya.net.Loader,LocalStorage=laya.net.LocalStorage; var Node=laya.display.Node,Point=laya.maths.Point,Rectangle=laya.maths.Rectangle,Render=laya.renders.Render; var Sprite=laya.display.Sprite,Stage=laya.display.Stage,Text=laya.display.Text,Texture=laya.resource.Texture; var TimeLine=laya.utils.TimeLine,Tween=laya.utils.Tween,Utils=laya.utils.Utils,WeakObject=laya.utils.WeakObject; Laya.interface('laya.ui.IItem'); Laya.interface('laya.ui.ISelect'); Laya.interface('laya.ui.IRender'); Laya.interface('laya.ui.IComponent'); Laya.interface('laya.ui.IBox','IComponent'); /** *LayoutStyle 是一个布局样式类。 */ //class laya.ui.LayoutStyle var LayoutStyle=(function(){ function LayoutStyle(){ /**一个布尔值,表示是否有效。*/ this.enable=false; this.top=NaN; this.bottom=NaN; this.left=NaN; this.right=NaN; this.centerX=NaN; this.centerY=NaN; this.anchorX=NaN; this.anchorY=NaN; } __class(LayoutStyle,'laya.ui.LayoutStyle'); __static(LayoutStyle, ['EMPTY',function(){return this.EMPTY=new LayoutStyle();} ]); return LayoutStyle; })() /** *Styles 定义了组件常用的样式属性。 */ //class laya.ui.Styles var Styles=(function(){ function Styles(){} __class(Styles,'laya.ui.Styles'); Styles.labelColor="#000000"; Styles.buttonStateNum=3; Styles.scrollBarMinNum=15; Styles.scrollBarDelayTime=500; __static(Styles, ['defaultSizeGrid',function(){return this.defaultSizeGrid=[4,4,4,4,0];},'labelPadding',function(){return this.labelPadding=[2,2,2,2];},'inputLabelPadding',function(){return this.inputLabelPadding=[1,1,1,3];},'buttonLabelColors',function(){return this.buttonLabelColors=["#32556b","#32cc6b","#ff0000","#C0C0C0"];},'comboBoxItemColors',function(){return this.comboBoxItemColors=["#5e95b6","#ffffff","#000000","#8fa4b1","#ffffff"];} ]); return Styles; })() /** *UIUtils 是文本工具集。 */ //class laya.ui.UIUtils var UIUtils=(function(){ function UIUtils(){} __class(UIUtils,'laya.ui.UIUtils'); UIUtils.fillArray=function(arr,str,type){ var temp=arr.concat(); if (str){ var a=str.split(","); for (var i=0,n=Math.min(temp.length,a.length);i < n;i++){ var value=a[i]; temp[i]=(value=="true" ? true :(value=="false" ? false :value)); if (type !=null)temp[i]=type(value); } } return temp; } UIUtils.toColor=function(color){ return Utils.toHexColor(color); } UIUtils.gray=function(traget,isGray){ (isGray===void 0)&& (isGray=true); if (isGray){ UIUtils.addFilter(traget,UIUtils.grayFilter); }else { UIUtils.clearFilter(traget,ColorFilter); } } UIUtils.addFilter=function(target,filter){ var filters=target.filters || []; filters.push(filter); target.filters=filters; } UIUtils.clearFilter=function(target,filterType){ var filters=target.filters; if (filters !=null && filters.length > 0){ for (var i=filters.length-1;i >-1;i--){ var filter=filters[i]; if (Laya.__typeof(filter,filterType))filters.splice(i,1); } target.filters=filters; } } UIUtils._getReplaceStr=function(word){ return UIUtils.escapeSequence[word]; } UIUtils.adptString=function(str){ return str.replace(/\\(\w)/g,UIUtils._getReplaceStr); } UIUtils.getBindFun=function(value){ var fun=UIUtils._funMap.get(value); if (fun==null){ var temp="\""+value+"\""; temp=temp.replace(/^"\${|}"$/g,"").replace(/\${/g,"\"+").replace(/}/g,"+\""); var str="(function(data){if(data==null)return;with(data){try{\nreturn "+temp+"\n}catch(e){}}})"; fun=Laya._runScript(str); UIUtils._funMap.set(value,fun); } return fun; } __static(UIUtils, ['grayFilter',function(){return this.grayFilter=new ColorFilter([0.3086,0.6094,0.082,0,0,0.3086,0.6094,0.082,0,0,0.3086,0.6094,0.082,0,0,0,0,0,1,0]);},'escapeSequence',function(){return this.escapeSequence={"\\n":"\n","\\t":"\t"};},'_funMap',function(){return this._funMap=new WeakObject();} ]); return UIUtils; })() /**全局配置*/ //class UIConfig var UIConfig=(function(){ function UIConfig(){} __class(UIConfig,'UIConfig'); UIConfig.touchScrollEnable=true; UIConfig.mouseWheelEnable=true; UIConfig.showButtons=true; UIConfig.popupBgColor="#000000"; UIConfig.popupBgAlpha=0.5; UIConfig.closeDialogOnSide=true; return UIConfig; })() /** *AutoBitmap 类是用于表示位图图像或绘制图形的显示对象。 *

    封装了位置,宽高及九宫格的处理,供UI组件使用。

    */ //class laya.ui.AutoBitmap extends laya.display.Graphics var AutoBitmap=(function(_super){ function AutoBitmap(){ /**@private 是否自动缓存命令*/ this.autoCacheCmd=true; /**@private 宽度*/ this._width=0; /**@private 高度*/ this._height=0; /**@private 源数据*/ this._source=null; /**@private 网格数据*/ this._sizeGrid=null; /**@private */ this._isChanged=false; /**@private */ this._offset=null; AutoBitmap.__super.call(this); } __class(AutoBitmap,'laya.ui.AutoBitmap',_super); var __proto=AutoBitmap.prototype; /**@inheritDoc */ __proto.destroy=function(){ _super.prototype.destroy.call(this); this._source=null; this._sizeGrid=null; this._offset=null; } /**@private */ __proto._setChanged=function(){ if (!this._isChanged){ this._isChanged=true; Laya.timer.callLater(this,this.changeSource); } } /** *@private *修改纹理资源。 */ __proto.changeSource=function(){ this._isChanged=false; var source=this._source; if (!source || !source.bitmap)return; var width=this.width; var height=this.height; var sizeGrid=this._sizeGrid; var sw=source.sourceWidth; var sh=source.sourceHeight; if (!sizeGrid || (sw===width && sh===height)){ this.clear(); this.drawTexture(source,this._offset ? this._offset[0] :0,this._offset ? this._offset[1] :0,width,height); }else { source.$_GID || (source.$_GID=Utils.getGID()); var key=source.$_GID+"."+width+"."+height+"."+sizeGrid.join("."); if (Utils.isOKCmdList(WeakObject.I.get(key))){ this.cmds=WeakObject.I.get(key); return; } this.clear(); var top=sizeGrid[0]; var right=sizeGrid[1]; var bottom=sizeGrid[2]; var left=sizeGrid[3]; var repeat=sizeGrid[4]; var needClip=false; if (width==sw){ left=right=0; } if (height==sh){ top=bottom=0; } if (left+right > width){ var clipWidth=width; needClip=true; width=left+right; this.save(); this.clipRect(0,0,clipWidth,height); } left && top && this.drawTexture(AutoBitmap.getTexture(source,0,0,left,top),0,0,left,top); right && top && this.drawTexture(AutoBitmap.getTexture(source,sw-right,0,right,top),width-right,0,right,top); left && bottom && this.drawTexture(AutoBitmap.getTexture(source,0,sh-bottom,left,bottom),0,height-bottom,left,bottom); right && bottom && this.drawTexture(AutoBitmap.getTexture(source,sw-right,sh-bottom,right,bottom),width-right,height-bottom,right,bottom); top && this.drawBitmap(repeat,AutoBitmap.getTexture(source,left,0,sw-left-right,top),left,0,width-left-right,top); bottom && this.drawBitmap(repeat,AutoBitmap.getTexture(source,left,sh-bottom,sw-left-right,bottom),left,height-bottom,width-left-right,bottom); left && this.drawBitmap(repeat,AutoBitmap.getTexture(source,0,top,left,sh-top-bottom),0,top,left,height-top-bottom); right && this.drawBitmap(repeat,AutoBitmap.getTexture(source,sw-right,top,right,sh-top-bottom),width-right,top,right,height-top-bottom); this.drawBitmap(repeat,AutoBitmap.getTexture(source,left,top,sw-left-right,sh-top-bottom),left,top,width-left-right,height-top-bottom); if (needClip)this.restore(); if (this.autoCacheCmd && !Render.isConchApp)WeakObject.I.set(key,this.cmds); } this._repaint(); } __proto.drawBitmap=function(repeat,tex,x,y,width,height){ (width===void 0)&& (width=0); (height===void 0)&& (height=0); if (width < 0.1 || height < 0.1)return; if (repeat && (tex.width !=width || tex.height !=height))this.fillTexture(tex,x,y,width,height); else this.drawTexture(tex,x,y,width,height); } __proto.clear=function(recoverCmds){ (recoverCmds===void 0)&& (recoverCmds=true); _super.prototype.clear.call(this,false); } /** *当前实例的有效缩放网格数据。 *

    如果设置为null,则在应用任何缩放转换时,将正常缩放整个显示对象。

    *

    数据格式:[上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)]。 *

    • 例如:[4,4,4,4,1]

    *

    sizeGrid 的值如下所示: *

      *
    1. 上边距
    2. *
    3. 右边距
    4. *
    5. 下边距
    6. *
    7. 左边距
    8. *
    9. 是否重复填充(值为0:不重复填充,1:重复填充)
    10. *

    *

    当定义 sizeGrid 属性时,该显示对象被分割到以 sizeGrid 数据中的"上边距,右边距,下边距,左边距" 组成的矩形为基础的具有九个区域的网格中,该矩形定义网格的中心区域。网格的其它八个区域如下所示: *

      *
    • 矩形上方的区域
    • *
    • 矩形外的右上角
    • *
    • 矩形左侧的区域
    • *
    • 矩形右侧的区域
    • *
    • 矩形外的左下角
    • *
    • 矩形下方的区域
    • *
    • 矩形外的右下角
    • *
    • 矩形外的左上角
    • *
    *同时也支持3宫格,比如0,4,0,4,1为水平3宫格,4,0,4,0,1为垂直3宫格,3宫格性能比9宫格高。 *

    */ __getset(0,__proto,'sizeGrid',function(){ return this._sizeGrid; },function(value){ this._sizeGrid=value; this._setChanged(); }); /** *表示显示对象的宽度,以像素为单位。 */ __getset(0,__proto,'width',function(){ if (this._width)return this._width; if (this._source)return this._source.sourceWidth; return 0; },function(value){ if (this._width !=value){ this._width=value; this._setChanged(); } }); /** *表示显示对象的高度,以像素为单位。 */ __getset(0,__proto,'height',function(){ if (this._height)return this._height; if (this._source)return this._source.sourceHeight; return 0; },function(value){ if (this._height !=value){ this._height=value; this._setChanged(); } }); /** *对象的纹理资源。 *@see laya.resource.Texture */ __getset(0,__proto,'source',function(){ return this._source; },function(value){ if (value){ this._source=value this._setChanged(); }else { this._source=null; this.clear(); } }); AutoBitmap.getTexture=function(tex,x,y,width,height){ if (width <=0)width=1; if (height <=0)height=1; tex.$_GID || (tex.$_GID=Utils.getGID()) var key=tex.$_GID+"."+x+"."+y+"."+width+"."+height; var texture=WeakObject.I.get(key); if (!texture || !texture.source){ texture=Texture.createFromTexture(tex,x,y,width,height); WeakObject.I.set(key,texture); } return texture; } return AutoBitmap; })(Graphics) /** *UIEvent 类用来定义UI组件类的事件类型。 */ //class laya.ui.UIEvent extends laya.events.Event var UIEvent=(function(_super){ function UIEvent(){ UIEvent.__super.call(this);; } __class(UIEvent,'laya.ui.UIEvent',_super); UIEvent.SHOW_TIP="showtip"; UIEvent.HIDE_TIP="hidetip"; return UIEvent; })(Event) /** *Component 是ui控件类的基类。 *

    生命周期:preinitialize > createChildren > initialize > 组件构造函数

    */ //class laya.ui.Component extends laya.display.Sprite var Component=(function(_super){ function Component(){ this._comXml=null; /**@private 控件的元数据。 */ this._dataSource=null; /**@private 鼠标悬停提示 */ this._toolTip=null; /**@private 标签 */ this._tag=null; /**@private 禁用 */ this._disabled=false; /**@private 变灰*/ this._gray=false; /** *是否启用相对布局 */ this.layoutEnabled=true; Component.__super.call(this); this._layout=LayoutStyle.EMPTY; this.preinitialize(); this.createChildren(); this.initialize(); } __class(Component,'laya.ui.Component',_super); var __proto=Component.prototype; Laya.imps(__proto,{"laya.ui.IComponent":true}) /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._dataSource=this._layout=null; this._tag=null; this._toolTip=null; } /** *

    预初始化。

    *@internal 子类可在此函数内设置、修改属性默认值 */ __proto.preinitialize=function(){} /** *

    创建并添加控件子节点。

    *@internal 子类可在此函数内创建并添加子节点。 */ __proto.createChildren=function(){} /** *

    控件初始化。

    *@internal 在此子对象已被创建,可以对子对象进行修改。 */ __proto.initialize=function(){} /** *

    延迟运行指定的函数。

    *

    在控件被显示在屏幕之前调用,一般用于延迟计算数据。

    *@param method 要执行的函数的名称。例如,functionName。 *@param args 传递给 method 函数的可选参数列表。 * *@see #runCallLater() */ __proto.callLater=function(method,args){ Laya.timer.callLater(this,method,args); } /** *

    如果有需要延迟调用的函数(通过 callLater 函数设置),则立即执行延迟调用函数。

    *@param method 要执行的函数名称。例如,functionName。 *@see #callLater() */ __proto.runCallLater=function(method){ Laya.timer.runCallLater(this,method); } /** *

    立即执行影响宽高度量的延迟调用函数。

    *@internal

    使用 runCallLater 函数,立即执行影响宽高度量的延迟运行函数(使用 callLater 设置延迟执行函数)。

    *@see #callLater() *@see #runCallLater() */ __proto.commitMeasure=function(){} /** *

    重新调整对象的大小。

    */ __proto.changeSize=function(){ this.event(/*laya.events.Event.RESIZE*/"resize"); if (this._layout.enable){ this.resetLayoutX(); this.resetLayoutY(); } } /** *@private *

    获取对象的布局样式。

    */ __proto.getLayout=function(){ this._layout===LayoutStyle.EMPTY && (this._layout=new LayoutStyle()); return this._layout; } /** *@private *

    指定对象是否可使用布局。

    *

    如果值为true,则此对象可以使用布局样式,否则不使用布局样式。

    *@param value 一个 Boolean 值,指定对象是否可使用布局。 */ __proto._setLayoutEnabled=function(value){ if (this._layout && this._layout.enable !=value){ this._layout.enable=value; this.on(/*laya.events.Event.ADDED*/"added",this,this.onAdded); this.on(/*laya.events.Event.REMOVED*/"removed",this,this.onRemoved); if (this.parent){ this.onAdded(); } } } /** *对象从显示列表移除的事件侦听处理函数。 */ __proto.onRemoved=function(){ this.parent.off(/*laya.events.Event.RESIZE*/"resize",this,this.onCompResize); } /** *对象被添加到显示列表的事件侦听处理函数。 */ __proto.onAdded=function(){ this.parent.on(/*laya.events.Event.RESIZE*/"resize",this,this.onCompResize); this.resetLayoutX(); this.resetLayoutY(); } /** *父容器的 Event.RESIZE 事件侦听处理函数。 */ __proto.onCompResize=function(){ if (this._layout && this._layout.enable){ this.resetLayoutX(); this.resetLayoutY(); } } /** *

    重置对象的 X 轴(水平方向)布局。

    */ __proto.resetLayoutX=function(){ var layout=this._layout; if (!isNaN(layout.anchorX))this.pivotX=layout.anchorX *this.width; if (!this.layoutEnabled)return; var parent=this.parent; if (parent){ if (!isNaN(layout.centerX)){ this.x=Math.round((parent.width-this.displayWidth)*0.5+layout.centerX+this.pivotX *this.scaleX); }else if (!isNaN(layout.left)){ this.x=Math.round(layout.left+this.pivotX *this.scaleX); if (!isNaN(layout.right)){ this.width=(parent._width-layout.left-layout.right)/ (this.scaleX || 0.01); } }else if (!isNaN(layout.right)){ this.x=Math.round(parent.width-this.displayWidth-layout.right+this.pivotX *this.scaleX); } } } /** *

    重置对象的 Y 轴(垂直方向)布局。

    */ __proto.resetLayoutY=function(){ var layout=this._layout; if (!isNaN(layout.anchorY))this.pivotY=layout.anchorY *this.height; if (!this.layoutEnabled)return; var parent=this.parent; if (parent){ if (!isNaN(layout.centerY)){ this.y=Math.round((parent.height-this.displayHeight)*0.5+layout.centerY+this.pivotY *this.scaleY); }else if (!isNaN(layout.top)){ this.y=Math.round(layout.top+this.pivotY *this.scaleY); if (!isNaN(layout.bottom)){ this.height=(parent._height-layout.top-layout.bottom)/ (this.scaleY || 0.01); } }else if (!isNaN(layout.bottom)){ this.y=Math.round(parent.height-this.displayHeight-layout.bottom+this.pivotY *this.scaleY); } } } /** *对象的 Event.MOUSE_OVER 事件侦听处理函数。 */ __proto.onMouseOver=function(e){ Laya.stage.event(/*laya.ui.UIEvent.SHOW_TIP*/"showtip",this._toolTip); } /** *对象的 Event.MOUSE_OUT 事件侦听处理函数。 */ __proto.onMouseOut=function(e){ Laya.stage.event(/*laya.ui.UIEvent.HIDE_TIP*/"hidetip",this._toolTip); } __proto._childChanged=function(child){ this.callLater(this.changeSize); _super.prototype._childChanged.call(this,child); } /** *

    对象的显示宽度(以像素为单位)。

    */ __getset(0,__proto,'displayWidth',function(){ return this.width *this.scaleX; }); /** *

    表示显示对象的宽度,以像素为单位。

    *

    注:当值为0时,宽度为自适应大小。

    */ __getset(0,__proto,'width',function(){ if (this._width)return this._width; return this.measureWidth; },function(value){ if (this._width !=value){ this._width=value; this.conchModel && this.conchModel.size(this._width,this._height); this.callLater(this.changeSize); if (this._layout.enable && (!isNaN(this._layout.centerX)|| !isNaN(this._layout.right)|| !isNaN(this._layout.anchorX)))this.resetLayoutX(); } }); /** *

    显示对象的实际显示区域宽度(以像素为单位)。

    */ __getset(0,__proto,'measureWidth',function(){ var max=0; this.commitMeasure(); for (var i=this.numChildren-1;i >-1;i--){ var comp=this.getChildAt(i); if (comp.visible){ max=Math.max(comp.x+comp.width *comp.scaleX,max); } } return max; }); /** *

    对象的显示高度(以像素为单位)。

    */ __getset(0,__proto,'displayHeight',function(){ return this.height *this.scaleY; }); /** *

    表示显示对象的高度,以像素为单位。

    *

    注:当值为0时,高度为自适应大小。

    */ __getset(0,__proto,'height',function(){ if (this._height)return this._height; return this.measureHeight; },function(value){ if (this._height !=value){ this._height=value; this.conchModel && this.conchModel.size(this._width,this._height); this.callLater(this.changeSize); if (this._layout.enable && (!isNaN(this._layout.centerY)|| !isNaN(this._layout.bottom)|| !isNaN(this._layout.anchorY)))this.resetLayoutY(); } }); /** *

    数据赋值,通过对UI赋值来控制UI显示逻辑。

    *

    简单赋值会更改组件的默认属性,使用大括号可以指定组件的任意属性进行赋值。

    *@example //默认属性赋值 dataSource={label1:"改变了label",checkbox1:true};//(更改了label1的text属性值,更改checkbox1的selected属性)。 //任意属性赋值 dataSource={label2:{text:"改变了label",size:14},checkbox2:{selected:true,x:10}}; */ __getset(0,__proto,'dataSource',function(){ return this._dataSource; },function(value){ this._dataSource=value; for (var prop in this._dataSource){ if (this.hasOwnProperty(prop)&& !((typeof (this[prop])=='function'))){ this[prop]=this._dataSource[prop]; } } }); /**@inheritDoc */ __getset(0,__proto,'scaleY',_super.prototype._$get_scaleY,function(value){ if (Laya.superGet(Sprite,this,'scaleY')!=value){ Laya.superSet(Sprite,this,'scaleY',value); this.callLater(this.changeSize); this._layout.enable && this.resetLayoutY(); } }); /** *

    显示对象的实际显示区域高度(以像素为单位)。

    */ __getset(0,__proto,'measureHeight',function(){ var max=0; this.commitMeasure(); for (var i=this.numChildren-1;i >-1;i--){ var comp=this.getChildAt(i); if (comp.visible){ max=Math.max(comp.y+comp.height *comp.scaleY,max); } } return max; }); /**@inheritDoc */ __getset(0,__proto,'scaleX',_super.prototype._$get_scaleX,function(value){ if (Laya.superGet(Sprite,this,'scaleX')!=value){ Laya.superSet(Sprite,this,'scaleX',value); this.callLater(this.changeSize); this._layout.enable && this.resetLayoutX(); } }); /** *

    从组件顶边到其内容区域顶边之间的垂直距离(以像素为单位)。

    */ __getset(0,__proto,'top',function(){ return this._layout.top; },function(value){ if (value !=this._layout.top){ this.getLayout().top=value; this._setLayoutEnabled(true); } this.resetLayoutY(); }); /** *

    从组件底边到其内容区域底边之间的垂直距离(以像素为单位)。

    */ __getset(0,__proto,'bottom',function(){ return this._layout.bottom; },function(value){ if (value !=this._layout.bottom){ this.getLayout().bottom=value; this._setLayoutEnabled(true); } this.resetLayoutY(); }); /** *

    从组件左边到其内容区域左边之间的水平距离(以像素为单位)。

    */ __getset(0,__proto,'left',function(){ return this._layout.left; },function(value){ if (value !=this._layout.left){ this.getLayout().left=value; this._setLayoutEnabled(true); } this.resetLayoutX(); }); /** *

    从组件右边到其内容区域右边之间的水平距离(以像素为单位)。

    */ __getset(0,__proto,'right',function(){ return this._layout.right; },function(value){ if (value !=this._layout.right){ this.getLayout().right=value; this._setLayoutEnabled(true); } this.resetLayoutX(); }); /** *

    在父容器中,此对象的水平方向中轴线与父容器的水平方向中心线的距离(以像素为单位)。

    */ __getset(0,__proto,'centerX',function(){ return this._layout.centerX; },function(value){ if (value !=this._layout.centerX){ this.getLayout().centerX=value; this._setLayoutEnabled(true); } this.resetLayoutX(); }); /** *

    在父容器中,此对象的垂直方向中轴线与父容器的垂直方向中心线的距离(以像素为单位)。

    */ __getset(0,__proto,'centerY',function(){ return this._layout.centerY; },function(value){ if (value !=this._layout.centerY){ this.getLayout().centerY=value; this._setLayoutEnabled(true); } this.resetLayoutY(); }); /**X轴锚点,值为0-1*/ __getset(0,__proto,'anchorX',function(){ return this._layout.anchorX; },function(value){ if (value !=this._layout.anchorX){ this.getLayout().anchorX=value; this._setLayoutEnabled(true); } this.resetLayoutX(); }); /**Y轴锚点,值为0-1*/ __getset(0,__proto,'anchorY',function(){ return this._layout.anchorY; },function(value){ if (value !=this._layout.anchorY){ this.getLayout().anchorY=value; this._setLayoutEnabled(true); } this.resetLayoutY(); }); /** *

    对象的标签。

    *@internal 冗余字段,可以用来储存数据。 */ __getset(0,__proto,'tag',function(){ return this._tag; },function(value){ this._tag=value; }); /** *

    鼠标悬停提示。

    *

    可以赋值为文本 String 或函数 Handler ,用来实现自定义样式的鼠标提示和参数携带等。

    *@example *private var _testTips:TestTipsUI=new TestTipsUI(); *private function testTips():void { //简单鼠标提示 *btn2.toolTip="这里是鼠标提示<b>粗体</b><br>换行"; //自定义的鼠标提示 *btn1.toolTip=showTips1; //带参数的自定义鼠标提示 *clip.toolTip=new Handler(this,showTips2,["clip"]); *} *private function showTips1():void { *_testTips.label.text="这里是按钮["+btn1.label+"]"; *tip.addChild(_testTips); *} *private function showTips2(name:String):void { *_testTips.label.text="这里是"+name; *tip.addChild(_testTips); *} */ __getset(0,__proto,'toolTip',function(){ return this._toolTip; },function(value){ if (this._toolTip !=value){ this._toolTip=value; if (value !=null){ this.on(/*laya.events.Event.MOUSE_OVER*/"mouseover",this,this.onMouseOver); this.on(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.onMouseOut); }else { this.off(/*laya.events.Event.MOUSE_OVER*/"mouseover",this,this.onMouseOver); this.off(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.onMouseOut); } } }); /** *XML 数据。 */ __getset(0,__proto,'comXml',function(){ return this._comXml; },function(value){ this._comXml=value; }); /**是否变灰。*/ __getset(0,__proto,'gray',function(){ return this._gray; },function(value){ if (value!==this._gray){ this._gray=value; UIUtils.gray(this,value); } }); /**是否禁用页面,设置为true后,会变灰并且禁用鼠标。*/ __getset(0,__proto,'disabled',function(){ return this._disabled; },function(value){ if (value!==this._disabled){ this.gray=this._disabled=value; this.mouseEnabled=!value; } }); return Component; })(Sprite) /** *DialogManager 对话框管理容器,所有的对话框都在该容器内,并且受管理器管理。 *任意对话框打开和关闭,都会出发管理类的open和close事件 *可以通过UIConfig设置弹出框背景透明度,模式窗口点击边缘是否关闭,点击窗口是否切换层次等 *通过设置对话框的zOrder属性,可以更改弹出的层次 */ //class laya.ui.DialogManager extends laya.display.Sprite var DialogManager=(function(_super){ function DialogManager(){ /**锁屏层*/ this.lockLayer=null; /**@private 全局默认弹出对话框效果,可以设置一个效果代替默认的弹出效果,如果不想有任何效果,可以赋值为null*/ this.popupEffect=function(dialog){ dialog.scale(1,1); Tween.from(dialog,{x:Laya.stage.width / 2,y:Laya.stage.height / 2,scaleX:0,scaleY:0},300,Ease.backOut,Handler.create(this,this.doOpen,[dialog])); } /**@private 全局默认关闭对话框效果,可以设置一个效果代替默认的关闭效果,如果不想有任何效果,可以赋值为null*/ this.closeEffect=function(dialog,type){ Tween.to(dialog,{x:Laya.stage.width / 2,y:Laya.stage.height / 2,scaleX:0,scaleY:0},300,Ease.strongOut,Handler.create(this,this.doClose,[dialog,type])); } DialogManager.__super.call(this); this.maskLayer=new Sprite(); this.popupEffectHandler=new Handler(this,this.popupEffect); this.closeEffectHandler=new Handler(this,this.closeEffect); this.mouseEnabled=this.maskLayer.mouseEnabled=true; this.zOrder=1000; Laya.stage.addChild(this); Laya.stage.on(/*laya.events.Event.RESIZE*/"resize",this,this._onResize); if (UIConfig.closeDialogOnSide)this.maskLayer.on("click",this,this._closeOnSide); this._onResize(null); } __class(DialogManager,'laya.ui.DialogManager',_super); var __proto=DialogManager.prototype; __proto._closeOnSide=function(){ var dialog=this.getChildAt(this.numChildren-1); if ((dialog instanceof laya.ui.Dialog ))dialog.close("side"); } /**设置锁定界面,如果为空则什么都不显示*/ __proto.setLockView=function(value){ if (!this.lockLayer){ this.lockLayer=new Box(); this.lockLayer.mouseEnabled=true; this.lockLayer.size(Laya.stage.width,Laya.stage.height); } this.lockLayer.removeChildren(); if (value){ value.centerX=value.centerY=0; this.lockLayer.addChild(value); } } /**@private */ __proto._onResize=function(e){ var width=this.maskLayer.width=Laya.stage.width; var height=this.maskLayer.height=Laya.stage.height; if (this.lockLayer)this.lockLayer.size(width,height); this.maskLayer.graphics.clear(); this.maskLayer.graphics.drawRect(0,0,width,height,UIConfig.popupBgColor); this.maskLayer.alpha=UIConfig.popupBgAlpha; for (var i=this.numChildren-1;i >-1;i--){ var item=this.getChildAt(i); if (item.popupCenter)this._centerDialog(item); } } __proto._centerDialog=function(dialog){ dialog.x=Math.round(((Laya.stage.width-dialog.width)>> 1)+dialog.pivotX); dialog.y=Math.round(((Laya.stage.height-dialog.height)>> 1)+dialog.pivotY); } /** *显示对话框(非模式窗口类型)。 *@param dialog 需要显示的对象框 Dialog 实例。 *@param closeOther 是否关闭其它对话框,若值为ture,则关闭其它的对话框。 *@param showEffect 是否显示弹出效果 */ __proto.open=function(dialog,closeOther,showEffect){ (closeOther===void 0)&& (closeOther=false); (showEffect===void 0)&& (showEffect=false); if (closeOther)this._closeAll(); if (dialog.popupCenter)this._centerDialog(dialog); this.addChild(dialog); if (dialog.isModal || this._$P["hasZorder"])this.timer.callLater(this,this._checkMask); if (showEffect && dialog.popupEffect !=null)dialog.popupEffect.runWith(dialog); else this.doOpen(dialog); this.event(/*laya.events.Event.OPEN*/"open"); } /** *执行打开对话框。 *@param dialog 需要关闭的对象框 Dialog 实例。 *@param type 关闭的类型,默认为空 */ __proto.doOpen=function(dialog){ dialog.onOpened(); } /** *锁定所有层,显示加载条信息,防止双击 */ __proto.lock=function(value){ if (this.lockLayer){ if (value)this.addChild(this.lockLayer); else this.lockLayer.removeSelf(); } } /** *关闭对话框。 *@param dialog 需要关闭的对象框 Dialog 实例。 *@param type 关闭的类型,默认为空 *@param showEffect 是否显示弹出效果 */ __proto.close=function(dialog,type,showEffect){ (showEffect===void 0)&& (showEffect=false); if (showEffect && dialog.closeEffect !=null)dialog.closeEffect.runWith([dialog,type]); else this.doClose(dialog,type); this.event(/*laya.events.Event.CLOSE*/"close"); } /** *执行关闭对话框。 *@param dialog 需要关闭的对象框 Dialog 实例。 *@param type 关闭的类型,默认为空 */ __proto.doClose=function(dialog,type){ dialog.removeSelf(); dialog.isModal && this._checkMask(); dialog.closeHandler && dialog.closeHandler.runWith(type); dialog.onClosed(type); } /** *关闭所有的对话框。 */ __proto.closeAll=function(){ this._closeAll(); this.event(/*laya.events.Event.CLOSE*/"close"); } /**@private */ __proto._closeAll=function(){ for (var i=this.numChildren-1;i >-1;i--){ var item=this.getChildAt(i); if (item && item.close !=null){ this.doClose(item); } } } /** *根据组获取所有对话框 *@param group 组名称 *@return 对话框数组 */ __proto.getDialogsByGroup=function(group){ var arr=[]; for (var i=this.numChildren-1;i >-1;i--){ var item=this.getChildAt(i); if (item && item.group===group){ arr.push(item); } } return arr; } /** *根据组关闭所有弹出框 *@param group 需要关闭的组名称 *@return 需要关闭的对话框数组 */ __proto.closeByGroup=function(group){ var arr=[]; for (var i=this.numChildren-1;i >-1;i--){ var item=this.getChildAt(i); if (item && item.group===group){ item.close(); arr.push(item); } } return arr; } /**@private 发生层次改变后,重新检查遮罩层是否正确*/ __proto._checkMask=function(){ this.maskLayer.removeSelf(); for (var i=this.numChildren-1;i >-1;i--){ var dialog=this.getChildAt(i); if (dialog && dialog.isModal){ this.addChildAt(this.maskLayer,i); return; } } } return DialogManager; })(Sprite) /** *Image 类是用于表示位图图像或绘制图形的显示对象。 *Image和Clip组件是唯一支持异步加载的两个组件,比如img.skin="abc/xxx.png",其他UI组件均不支持异步加载。 * *@example 以下示例代码,创建了一个新的 Image 实例,设置了它的皮肤、位置信息,并添加到舞台上。 *package *{ *import laya.ui.Image; *public class Image_Example *{ *public function Image_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *onInit(); *} *private function onInit():void *{ *var bg:Image=new Image("resource/ui/bg.png");//创建一个 Image 类的实例对象 bg ,并传入它的皮肤。 *bg.x=100;//设置 bg 对象的属性 x 的值,用于控制 bg 对象的显示位置。 *bg.y=100;//设置 bg 对象的属性 y 的值,用于控制 bg 对象的显示位置。 *bg.sizeGrid="40,10,5,10";//设置 bg 对象的网格信息。 *bg.width=150;//设置 bg 对象的宽度。 *bg.height=250;//设置 bg 对象的高度。 *Laya.stage.addChild(bg);//将此 bg 对象添加到显示列表。 *var image:Image=new Image("resource/ui/image.png");//创建一个 Image 类的实例对象 image ,并传入它的皮肤。 *image.x=100;//设置 image 对象的属性 x 的值,用于控制 image 对象的显示位置。 *image.y=100;//设置 image 对象的属性 y 的值,用于控制 image 对象的显示位置。 *Laya.stage.addChild(image);//将此 image 对象添加到显示列表。 *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *onInit(); *function onInit(){ *var bg=new laya.ui.Image("resource/ui/bg.png");//创建一个 Image 类的实例对象 bg ,并传入它的皮肤。 *bg.x=100;//设置 bg 对象的属性 x 的值,用于控制 bg 对象的显示位置。 *bg.y=100;//设置 bg 对象的属性 y 的值,用于控制 bg 对象的显示位置。 *bg.sizeGrid="40,10,5,10";//设置 bg 对象的网格信息。 *bg.width=150;//设置 bg 对象的宽度。 *bg.height=250;//设置 bg 对象的高度。 *Laya.stage.addChild(bg);//将此 bg 对象添加到显示列表。 *var image=new laya.ui.Image("resource/ui/image.png");//创建一个 Image 类的实例对象 image ,并传入它的皮肤。 *image.x=100;//设置 image 对象的属性 x 的值,用于控制 image 对象的显示位置。 *image.y=100;//设置 image 对象的属性 y 的值,用于控制 image 对象的显示位置。 *Laya.stage.addChild(image);//将此 image 对象添加到显示列表。 *} *@example *class Image_Example { *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *this.onInit(); *} *private onInit():void { *var bg:laya.ui.Image=new laya.ui.Image("resource/ui/bg.png");//创建一个 Image 类的实例对象 bg ,并传入它的皮肤。 *bg.x=100;//设置 bg 对象的属性 x 的值,用于控制 bg 对象的显示位置。 *bg.y=100;//设置 bg 对象的属性 y 的值,用于控制 bg 对象的显示位置。 *bg.sizeGrid="40,10,5,10";//设置 bg 对象的网格信息。 *bg.width=150;//设置 bg 对象的宽度。 *bg.height=250;//设置 bg 对象的高度。 *Laya.stage.addChild(bg);//将此 bg 对象添加到显示列表。 *var image:laya.ui.Image=new laya.ui.Image("resource/ui/image.png");//创建一个 Image 类的实例对象 image ,并传入它的皮肤。 *image.x=100;//设置 image 对象的属性 x 的值,用于控制 image 对象的显示位置。 *image.y=100;//设置 image 对象的属性 y 的值,用于控制 image 对象的显示位置。 *Laya.stage.addChild(image);//将此 image 对象添加到显示列表。 *} *} *@see laya.ui.AutoBitmap */ //class laya.ui.Image extends laya.ui.Component var Image=(function(_super){ function Image(skin){ /**@private */ this._bitmap=null; /**@private */ this._skin=null; /**@private */ this._group=null; Image.__super.call(this); this.skin=skin; } __class(Image,'laya.ui.Image',_super); var __proto=Image.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,true); this._bitmap && this._bitmap.destroy(); this._bitmap=null; } /** *销毁对象并释放加载的皮肤资源。 */ __proto.dispose=function(){ this.destroy(true); Laya.loader.clearRes(this._skin); } /**@inheritDoc */ __proto.createChildren=function(){ this.graphics=this._bitmap=new AutoBitmap(); this._bitmap.autoCacheCmd=false; } /** *@private *设置皮肤资源。 */ __proto.setSource=function(url,img){ if (url===this._skin && img){ this.source=img this.onCompResize(); } } /** *@copy laya.ui.AutoBitmap#source */ __getset(0,__proto,'source',function(){ return this._bitmap.source; },function(value){ if (!this._bitmap)return; this._bitmap.source=value; this.event(/*laya.events.Event.LOADED*/"loaded"); this.repaint(); }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if ((typeof value=='string'))this.skin=value; else Laya.superSet(Component,this,'dataSource',value); }); /**@inheritDoc */ __getset(0,__proto,'measureHeight',function(){ return this._bitmap.height; }); /** *

    对象的皮肤地址,以字符串表示。

    *

    如果资源未加载,则先加载资源,加载完成后应用于此对象。

    *注意:资源加载完成后,会自动缓存至资源库中。 */ __getset(0,__proto,'skin',function(){ return this._skin; },function(value){ if (this._skin !=value){ this._skin=value; if (value){ var source=Loader.getRes(value); if (source){ this.source=source; this.onCompResize(); }else Laya.loader.load(this._skin,Handler.create(this,this.setSource,[this._skin]),null,/*laya.net.Loader.IMAGE*/"image",1,true,this._group); }else { this.source=null; } } }); /** *资源分组。 */ __getset(0,__proto,'group',function(){ return this._group; },function(value){ if (value && this._skin)Loader.setGroup(this._skin,value); this._group=value; }); /** *

    当前实例的位图 AutoImage 实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"。

    *@see laya.ui.AutoBitmap#sizeGrid */ __getset(0,__proto,'sizeGrid',function(){ if (this._bitmap.sizeGrid)return this._bitmap.sizeGrid.join(","); return null; },function(value){ this._bitmap.sizeGrid=UIUtils.fillArray(Styles.defaultSizeGrid,value,Number); }); /**@inheritDoc */ __getset(0,__proto,'measureWidth',function(){ return this._bitmap.width; }); /**@inheritDoc */ __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(Component,this,'width',value); this._bitmap.width=value==0 ? 0.0000001 :value; }); /**@inheritDoc */ __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Component,this,'height',value); this._bitmap.height=value==0 ? 0.0000001 :value; }); return Image; })(Component) /** *Box 类是一个控件容器类。 */ //class laya.ui.Box extends laya.ui.Component var Box=(function(_super){ function Box(){ Box.__super.call(this);; } __class(Box,'laya.ui.Box',_super); var __proto=Box.prototype; Laya.imps(__proto,{"laya.ui.IBox":true}) /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; for (var name in value){ var comp=this.getChildByName(name); if (comp)comp.dataSource=value[name]; else if (this.hasOwnProperty(name)&& !((typeof (this[name])=='function')))this[name]=value[name]; } }); return Box; })(Component) /** *Button 组件用来表示常用的多态按钮。 Button 组件可显示文本标签、图标或同时显示两者。 * *

    可以是单态,两态和三态,默认三态(up,over,down)。

    * *@example 以下示例代码,创建了一个 Button 实例。 *package *{ *import laya.ui.Button; *import laya.utils.Handler; *public class Button_Example *{ *public function Button_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/button.png",Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *trace("资源加载完成!"); *var button:Button=new Button("resource/ui/button.png","label");//创建一个 Button 类的实例对象 button ,并传入它的皮肤。 *button.x=100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 *button.y=100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 *button.clickHandler=new Handler(this,onClickButton,[button]);//设置 button 的点击事件处理器。 *Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 *} *private function onClickButton(button:Button):void *{ *trace("按钮button被点击了!"); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/button.png",laya.utils.Handler.create(this,loadComplete));//加载资源 *function loadComplete() *{ *console.log("资源加载完成!"); *var button=new laya.ui.Button("resource/ui/button.png","label");//创建一个 Button 类的实例对象 button ,传入它的皮肤skin和标签label。 *button.x=100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 *button.y=100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 *button.clickHandler=laya.utils.Handler.create(this,onClickButton,[button],false);//设置 button 的点击事件处理函数。 *Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 *} *function onClickButton(button) *{ *console.log("按钮被点击了。",button); *} *@example *import Button=laya.ui.Button; *import Handler=laya.utils.Handler; *class Button_Example{ *constructor() *{ *Laya.init(640,800); *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/button.png",laya.utils.Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete() *{ *var button:Button=new Button("resource/ui/button.png","label");//创建一个 Button 类的实例对象 button ,并传入它的皮肤。 *button.x=100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 *button.y=100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 *button.clickHandler=new Handler(this,this.onClickButton,[button]);//设置 button 的点击事件处理器。 *Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 *} *private onClickButton(button:Button):void *{ *console.log("按钮button被点击了!") *} *} */ //class laya.ui.Button extends laya.ui.Component var Button=(function(_super){ function Button(skin,label){ /** *指定按钮按下时是否是切换按钮的显示状态。 * *@example 以下示例代码,创建了一个 Button 实例,并设置为切换按钮。 *@example *package *{ *import laya.ui.Button; *import laya.utils.Handler; *public class Button_toggle *{ *public function Button_toggle() *{ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/button.png",Handler.create(this,onLoadComplete)); *} *private function onLoadComplete():void *{ *trace("资源加载完成!"); *var button:Button=new Button("resource/ui/button.png","label");//创建一个 Button 实例对象 button ,传入它的皮肤skin和标签label。 *button.x=100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 *button.y=100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 *button.toggle=true;//设置 button 对象为切换按钮。 *button.clickHandler=new Handler(this,onClickButton,[button]);//设置 button 的点击事件处理器。 *Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 *} *private function onClickButton(button:Button):void *{ *trace("button.selected = "+button.selected); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/button.png",laya.utils.Handler.create(this,loadComplete));//加载资源 *function loadComplete() *{ *console.log("资源加载完成!"); *var button=new laya.ui.Button("resource/ui/button.png","label");//创建一个 Button 类的实例对象 button ,传入它的皮肤skin和标签label。 *button.x=100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 *button.y=100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 *button.toggle=true;//设置 button 对象为切换按钮。 *button.clickHandler=laya.utils.Handler.create(this,onClickButton,[button],false);//设置 button 的点击事件处理器。 *Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 *} *function onClickButton(button) *{ *console.log("button.selected = ",button.selected); *} *@example *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("button.png",null,null,null,null,null);//加载资源 *function loadComplete(){ *console.log("资源加载完成!"); *var button:laya.ui.Button=new laya.ui.Button("button.png","label");//创建一个 Button 类的实例对象 button ,传入它的皮肤skin和标签label。 *button.x=100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 *button.y=100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 *button.toggle=true;//设置 button 对象为切换按钮。 *button.clickHandler=laya.utils.Handler.create(this,onClickButton,[button],false);//设置 button 的点击事件处理器。 *Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 *} *function onClickButton(button){ *console.log("button.selected = ",button.selected); *} */ this.toggle=false; /** *@private */ this._bitmap=null; /** *@private *按钮上的文本。 */ this._text=null; /** *@private *按钮文本标签描边的颜色值。 */ this._strokeColors=null; /** *@private *按钮的状态值。 */ this._state=0; /** *@private *表示按钮的选中状态。 */ this._selected=false; /** *@private *按钮的皮肤资源。 */ this._skin=null; /** *@private *指定此显示对象是否自动计算并改变大小等属性。 */ this._autoSize=true; /** *@private *源数据。 */ this._sources=null; /** *@private *按钮的点击事件函数。 */ this._clickHandler=null; /** *@private */ this._stateChanged=false; Button.__super.call(this); this._labelColors=Styles.buttonLabelColors; this._stateNum=Styles.buttonStateNum; (label===void 0)&& (label=""); this.skin=skin; this.label=label; } __class(Button,'laya.ui.Button',_super); var __proto=Button.prototype; Laya.imps(__proto,{"laya.ui.ISelect":true}) /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._bitmap && this._bitmap.destroy(); this._text && this._text.destroy(destroyChild); this._bitmap=null; this._text=null; this._clickHandler=null; this._labelColors=this._sources=this._strokeColors=null; } /**@inheritDoc */ __proto.createChildren=function(){ this.graphics=this._bitmap=new AutoBitmap(); } /**@private */ __proto.createText=function(){ if (!this._text){ this._text=new Text(); this._text.overflow=Text.HIDDEN; this._text.align="center"; this._text.valign="middle"; this._text.width=this._width; this._text.height=this._height; } } /**@inheritDoc */ __proto.initialize=function(){ if (this._mouseEnableState!==1){ this.mouseEnabled=true; this._setBit(/*laya.display.Node.MOUSEENABLE*/0x2,true); } this._createListener(/*laya.events.Event.MOUSE_OVER*/"mouseover",this,this.onMouse,null,false,false); this._createListener(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.onMouse,null,false,false); this._createListener(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onMouse,null,false,false); this._createListener(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.onMouse,null,false,false); this._createListener(/*laya.events.Event.CLICK*/"click",this,this.onMouse,null,false,false); } /** *对象的 Event.MOUSE_OVER、Event.MOUSE_OUT、Event.MOUSE_DOWN、Event.MOUSE_UP、Event.CLICK 事件侦听处理函数。 *@param e Event 对象。 */ __proto.onMouse=function(e){ if (this.toggle===false && this._selected)return; if (e.type===/*laya.events.Event.CLICK*/"click"){ this.toggle && (this.selected=!this._selected); this._clickHandler && this._clickHandler.run(); return; } !this._selected && (this.state=Button.stateMap[e.type]); } /** *@private *对象的资源切片发生改变。 */ __proto.changeClips=function(){ var img=Loader.getRes(this._skin); if (!img){ console.log("lose skin",this._skin); return; }; var width=img.sourceWidth; var height=img.sourceHeight / this._stateNum; img.$_GID || (img.$_GID=Utils.getGID()); var key=img.$_GID+"-"+this._stateNum; var clips=WeakObject.I.get(key); if (!Utils.isOkTextureList(clips)){ clips=null; } if (clips)this._sources=clips; else { this._sources=[]; if (this._stateNum===1){ this._sources.push(img); }else { for (var i=0;i < this._stateNum;i++){ this._sources.push(Texture.createFromTexture(img,0,height *i,width,height)); } } WeakObject.I.set(key,this._sources); } if (this._autoSize){ this._bitmap.width=this._width || width; this._bitmap.height=this._height || height; if (this._text){ this._text.width=this._bitmap.width; this._text.height=this._bitmap.height; } }else { this._text && (this._text.x=width); } } /** *@private *改变对象的状态。 */ __proto.changeState=function(){ this._stateChanged=false; this.runCallLater(this.changeClips); var index=this._state < this._stateNum ? this._state :this._stateNum-1; this._sources && (this._bitmap.source=this._sources[index]); if (this.label){ this._text.color=this._labelColors[index]; if (this._strokeColors)this._text.strokeColor=this._strokeColors[index]; } } /**@private */ __proto._setStateChanged=function(){ if (!this._stateChanged){ this._stateChanged=true; this.callLater(this.changeState); } } /** *

    描边颜色,以字符串表示。

    *默认值为 "#000000"(黑色); *@see laya.display.Text.strokeColor() */ __getset(0,__proto,'labelStrokeColor',function(){ this.createText(); return this._text.strokeColor; },function(value){ this.createText(); this._text.strokeColor=value }); /** *@inheritDoc */ __getset(0,__proto,'measureHeight',function(){ this.runCallLater(this.changeClips); return this._text ? Math.max(this._bitmap.height,this._text.height):this._bitmap.height; }); /** *

    对象的皮肤资源地址。

    *支持单态,两态和三态,用 stateNum 属性设置 *

    对象的皮肤地址,以字符串表示。

    *@see #stateNum */ __getset(0,__proto,'skin',function(){ return this._skin; },function(value){ if (this._skin !=value){ this._skin=value; this.callLater(this.changeClips); this._setStateChanged(); } }); /** *对象的状态值。 *@see #stateMap */ __getset(0,__proto,'state',function(){ return this._state; },function(value){ if (this._state !=value){ this._state=value; this._setStateChanged(); } }); /** *按钮文本标签 Text 控件。 */ __getset(0,__proto,'text',function(){ this.createText(); return this._text; }); /** *

    指定对象的状态值,以数字表示。

    *

    默认值为3。此值决定皮肤资源图片的切割方式。

    *

    取值: *

  • 1:单态。图片不做切割,按钮的皮肤状态只有一种。
  • *
  • 2:两态。图片将以竖直方向被等比切割为2部分,从上向下,依次为 *弹起状态皮肤、 *按下和经过及选中状态皮肤。
  • *
  • 3:三态。图片将以竖直方向被等比切割为3部分,从上向下,依次为 *弹起状态皮肤、 *经过状态皮肤、 *按下和选中状态皮肤
  • *

    */ __getset(0,__proto,'stateNum',function(){ return this._stateNum; },function(value){ if ((typeof value=='string')){ value=parseInt(value); } if (this._stateNum !=value){ this._stateNum=value < 1 ? 1 :value > 3 ? 3 :value; this.callLater(this.changeClips); } }); /** *表示按钮各个状态下的描边颜色。 *

    格式: "upColor,overColor,downColor,disableColor"。

    */ __getset(0,__proto,'strokeColors',function(){ return this._strokeColors ? this._strokeColors.join(","):""; },function(value){ this._strokeColors=UIUtils.fillArray(Styles.buttonLabelColors,value,String); this._setStateChanged(); }); /** *表示按钮各个状态下的文本颜色。 *

    格式: "upColor,overColor,downColor,disableColor"。

    */ __getset(0,__proto,'labelColors',function(){ return this._labelColors.join(","); },function(value){ this._labelColors=UIUtils.fillArray(Styles.buttonLabelColors,value,String); this._setStateChanged(); }); /** *@inheritDoc */ __getset(0,__proto,'measureWidth',function(){ this.runCallLater(this.changeClips); if (this._autoSize)return this._bitmap.width; this.runCallLater(this.changeState); return this._bitmap.width+(this._text ? this._text.width :0); }); /** *按钮的文本内容。 */ __getset(0,__proto,'label',function(){ return this._text ? this._text.text :null; },function(value){ if (!this._text && !value)return; this.createText(); if (this._text.text !=value){ value && !this._text.parent && this.addChild(this._text); this._text.text=(value+"").replace(/\\n/g,"\n"); this._setStateChanged(); } }); /** *表示按钮的选中状态。 *

    如果值为true,表示该对象处于选中状态。否则该对象处于未选中状态。

    */ __getset(0,__proto,'selected',function(){ return this._selected; },function(value){ if (this._selected !=value){ this._selected=value; this.state=this._selected ? 2 :0; this.event(/*laya.events.Event.CHANGE*/"change"); } }); /** *表示按钮文本标签的边距。 *

    格式:"上边距,右边距,下边距,左边距"。

    */ __getset(0,__proto,'labelPadding',function(){ this.createText(); return this._text.padding.join(","); },function(value){ this.createText(); this._text.padding=UIUtils.fillArray(Styles.labelPadding,value,Number); }); /** *表示按钮文本标签的字体大小。 *@see laya.display.Text.fontSize() */ __getset(0,__proto,'labelSize',function(){ this.createText(); return this._text.fontSize; },function(value){ this.createText(); this._text.fontSize=value }); /** *

    描边宽度(以像素为单位)。

    *默认值0,表示不描边。 *@see laya.display.Text.stroke() */ __getset(0,__proto,'labelStroke',function(){ this.createText(); return this._text.stroke; },function(value){ this.createText(); this._text.stroke=value }); /** *表示按钮文本标签是否为粗体字。 *@see laya.display.Text.bold() */ __getset(0,__proto,'labelBold',function(){ this.createText(); return this._text.bold; },function(value){ this.createText(); this._text.bold=value; }); /** *表示按钮文本标签的字体名称,以字符串形式表示。 *@see laya.display.Text.font() */ __getset(0,__proto,'labelFont',function(){ this.createText(); return this._text.font; },function(value){ this.createText(); this._text.font=value; }); /**标签对齐模式,默认为居中对齐。*/ __getset(0,__proto,'labelAlign',function(){ this.createText() return this._text.align; },function(value){ this.createText() this._text.align=value; }); /** *对象的点击事件处理器函数(无默认参数)。 */ __getset(0,__proto,'clickHandler',function(){ return this._clickHandler; },function(value){ this._clickHandler=value; }); /** *

    当前实例的位图 AutoImage 实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    *@see laya.ui.AutoBitmap.sizeGrid */ __getset(0,__proto,'sizeGrid',function(){ if (this._bitmap.sizeGrid)return this._bitmap.sizeGrid.join(","); return null; },function(value){ this._bitmap.sizeGrid=UIUtils.fillArray(Styles.defaultSizeGrid,value,Number); }); /**@inheritDoc */ __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(Component,this,'width',value); if (this._autoSize){ this._bitmap.width=value; this._text && (this._text.width=value); } }); /**@inheritDoc */ __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Component,this,'height',value); if (this._autoSize){ this._bitmap.height=value; this._text && (this._text.height=value); } }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if ((typeof value=='number')|| (typeof value=='string'))this.label=value+""; else Laya.superSet(Component,this,'dataSource',value); }); /**图标x,y偏移,格式:100,100*/ __getset(0,__proto,'iconOffset',function(){ return this._bitmap._offset ? this._bitmap._offset.join(","):null; },function(value){ if (value)this._bitmap._offset=UIUtils.fillArray([1,1],value,Number); else this._bitmap._offset=[]; }); __static(Button, ['stateMap',function(){return this.stateMap={"mouseup":0,"mouseover":1,"mousedown":2,"mouseout":0};} ]); return Button; })(Component) /** *

    Clip 类是位图切片动画。

    *

    Clip 可将一张图片,按横向分割数量 clipX 、竖向分割数量 clipY , *或横向分割每个切片的宽度 clipWidth 、竖向分割每个切片的高度 clipHeight , *从左向右,从上到下,分割组合为一个切片动画。

    *Image和Clip组件是唯一支持异步加载的两个组件,比如clip.skin="abc/xxx.png",其他UI组件均不支持异步加载。 * *@example 以下示例代码,创建了一个 Clip 实例。 *package *{ *import laya.ui.Clip; *public class Clip_Example *{ *private var clip:Clip; *public function Clip_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *onInit(); *} *private function onInit():void *{ *clip=new Clip("resource/ui/clip_num.png",10,1);//创建一个 Clip 类的实例对象 clip ,传入它的皮肤skin和横向分割数量、竖向分割数量。 *clip.autoPlay=true;//设置 clip 动画自动播放。 *clip.interval=100;//设置 clip 动画的播放时间间隔。 *clip.x=100;//设置 clip 对象的属性 x 的值,用于控制 clip 对象的显示位置。 *clip.y=100;//设置 clip 对象的属性 y 的值,用于控制 clip 对象的显示位置。 *clip.on(Event.CLICK,this,onClick);//给 clip 添加点击事件函数侦听。 *Laya.stage.addChild(clip);//将此 clip 对象添加到显示列表。 *} *private function onClick():void *{ *trace("clip 的点击事件侦听处理函数。clip.total="+clip.total); *if (clip.isPlaying==true) *{ *clip.stop();//停止动画。 *}else { *clip.play();//播放动画。 *} *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *var clip; *Laya.loader.load("resource/ui/clip_num.png",laya.utils.Handler.create(this,loadComplete));//加载资源 *function loadComplete(){ *console.log("资源加载完成!"); *clip=new laya.ui.Clip("resource/ui/clip_num.png",10,1);//创建一个 Clip 类的实例对象 clip ,传入它的皮肤skin和横向分割数量、竖向分割数量。 *clip.autoPlay=true;//设置 clip 动画自动播放。 *clip.interval=100;//设置 clip 动画的播放时间间隔。 *clip.x=100;//设置 clip 对象的属性 x 的值,用于控制 clip 对象的显示位置。 *clip.y=100;//设置 clip 对象的属性 y 的值,用于控制 clip 对象的显示位置。 *clip.on(Event.CLICK,this,onClick);//给 clip 添加点击事件函数侦听。 *Laya.stage.addChild(clip);//将此 clip 对象添加到显示列表。 *} *function onClick() *{ *console.log("clip 的点击事件侦听处理函数。"); *if(clip.isPlaying==true) *{ *clip.stop(); *}else { *clip.play(); *} *} *@example *import Clip=laya.ui.Clip; *import Handler=laya.utils.Handler; *class Clip_Example { *private clip:Clip; *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *this.onInit(); *} *private onInit():void { *this.clip=new Clip("resource/ui/clip_num.png",10,1);//创建一个 Clip 类的实例对象 clip ,传入它的皮肤skin和横向分割数量、竖向分割数量。 *this.clip.autoPlay=true;//设置 clip 动画自动播放。 *this.clip.interval=100;//设置 clip 动画的播放时间间隔。 *this.clip.x=100;//设置 clip 对象的属性 x 的值,用于控制 clip 对象的显示位置。 *this.clip.y=100;//设置 clip 对象的属性 y 的值,用于控制 clip 对象的显示位置。 *this.clip.on(laya.events.Event.CLICK,this,this.onClick);//给 clip 添加点击事件函数侦听。 *Laya.stage.addChild(this.clip);//将此 clip 对象添加到显示列表。 *} *private onClick():void { *console.log("clip 的点击事件侦听处理函数。clip.total="+this.clip.total); *if (this.clip.isPlaying==true){ *this.clip.stop();//停止动画。 *}else { *this.clip.play();//播放动画。 *} *} *} * */ //class laya.ui.Clip extends laya.ui.Component var Clip=(function(_super){ function Clip(url,clipX,clipY){ /**@private */ this._sources=null; /**@private */ this._bitmap=null; /**@private */ this._skin=null; /**@private */ this._clipX=1; /**@private */ this._clipY=1; /**@private */ this._clipWidth=0; /**@private */ this._clipHeight=0; /**@private */ this._autoPlay=false; /**@private */ this._interval=50; /**@private */ this._complete=null; /**@private */ this._isPlaying=false; /**@private */ this._index=0; /**@private */ this._clipChanged=false; /**@private */ this._group=null; /**@private */ this._toIndex=-1; Clip.__super.call(this); (clipX===void 0)&& (clipX=1); (clipY===void 0)&& (clipY=1); this._clipX=clipX; this._clipY=clipY; this.skin=url; } __class(Clip,'laya.ui.Clip',_super); var __proto=Clip.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,true); this._bitmap && this._bitmap.destroy(); this._bitmap=null; this._sources=null; } /** *销毁对象并释放加载的皮肤资源。 */ __proto.dispose=function(){ this.destroy(true); Laya.loader.clearRes(this._skin); } /**@inheritDoc */ __proto.createChildren=function(){ this.graphics=this._bitmap=new AutoBitmap(); } /**@private */ __proto._onDisplay=function(e){ if (this._isPlaying){ if (this._displayedInStage)this.play(); else this.stop(); }else if (this._autoPlay){ this.play(); } } /** *@private *改变切片的资源、切片的大小。 */ __proto.changeClip=function(){ this._clipChanged=false; if (!this._skin)return; var img=Loader.getRes(this._skin); if (img){ this.loadComplete(this._skin,img); }else { Laya.loader.load(this._skin,Handler.create(this,this.loadComplete,[this._skin])); } } /** *@private *加载切片图片资源完成函数。 *@param url 资源地址。 *@param img 纹理。 */ __proto.loadComplete=function(url,img){ if (url===this._skin && img){ var w=this._clipWidth || Math.ceil(img.sourceWidth / this._clipX); var h=this._clipHeight || Math.ceil(img.sourceHeight / this._clipY); var key=this._skin+w+h; var clips=WeakObject.I.get(key); if (!Utils.isOkTextureList(clips)){ clips=null; } if (clips)this._sources=clips; else { this._sources=[]; for (var i=0;i < this._clipY;i++){ for (var j=0;j < this._clipX;j++){ this._sources.push(Texture.createFromTexture(img,w *j,h *i,w,h)); } } WeakObject.I.set(key,this._sources); } this.index=this._index; this.event(/*laya.events.Event.LOADED*/"loaded"); this.onCompResize(); } } /** *播放动画。 *@param from 开始索引 *@param to 结束索引,-1为不限制 */ __proto.play=function(from,to){ (from===void 0)&& (from=0); (to===void 0)&& (to=-1); this._isPlaying=true; this.index=from; this._toIndex=to; this._index++; Laya.timer.loop(this.interval,this,this._loop); this.on(/*laya.events.Event.DISPLAY*/"display",this,this._onDisplay); this.on(/*laya.events.Event.UNDISPLAY*/"undisplay",this,this._onDisplay); } /** *@private */ __proto._loop=function(){ if (this._style.visible && this._sources){ this._index++; if (this._toIndex >-1 && this._index >=this._toIndex)this.stop(); else if (this._index >=this._sources.length)this._index=0; this.index=this._index; } } /** *停止动画。 */ __proto.stop=function(){ this._isPlaying=false; Laya.timer.clear(this,this._loop); this.event(/*laya.events.Event.COMPLETE*/"complete"); } /**@private */ __proto._setClipChanged=function(){ if (!this._clipChanged){ this._clipChanged=true; this.callLater(this.changeClip); } } /** *表示动画播放间隔时间(以毫秒为单位)。 */ __getset(0,__proto,'interval',function(){ return this._interval; },function(value){ if (this._interval !=value){ this._interval=value; if (this._isPlaying)this.play(); } }); /** *@copy laya.ui.Image#skin */ __getset(0,__proto,'skin',function(){ return this._skin; },function(value){ if (this._skin !=value){ this._skin=value; if (value){ this._setClipChanged() }else { this._bitmap.source=null; } } }); /** *源数据。 */ __getset(0,__proto,'sources',function(){ return this._sources; },function(value){ this._sources=value; this.index=this._index; this.event(/*laya.events.Event.LOADED*/"loaded"); }); /**X轴(横向)切片数量。*/ __getset(0,__proto,'clipX',function(){ return this._clipX; },function(value){ this._clipX=value || 1; this._setClipChanged() }); /**Y轴(竖向)切片数量。*/ __getset(0,__proto,'clipY',function(){ return this._clipY; },function(value){ this._clipY=value || 1; this._setClipChanged() }); /** *切片动画的总帧数。 */ __getset(0,__proto,'total',function(){ this.runCallLater(this.changeClip); return this._sources ? this._sources.length :0; }); /** *横向分割时每个切片的宽度,与 clipX 同时设置时优先级高于 clipX 。 */ __getset(0,__proto,'clipWidth',function(){ return this._clipWidth; },function(value){ this._clipWidth=value; this._setClipChanged() }); /** *

    当前实例的位图 AutoImage 实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    *@see laya.ui.AutoBitmap.sizeGrid */ __getset(0,__proto,'sizeGrid',function(){ if (this._bitmap.sizeGrid)return this._bitmap.sizeGrid.join(","); return null; },function(value){ this._bitmap.sizeGrid=UIUtils.fillArray(Styles.defaultSizeGrid,value,Number); }); /** *资源分组。 */ __getset(0,__proto,'group',function(){ return this._group; },function(value){ if (value && this._skin)Loader.setGroup(this._skin,value); this._group=value; }); /** *竖向分割时每个切片的高度,与 clipY 同时设置时优先级高于 clipY 。 */ __getset(0,__proto,'clipHeight',function(){ return this._clipHeight; },function(value){ this._clipHeight=value; this._setClipChanged() }); /**@inheritDoc */ __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(Component,this,'width',value); this._bitmap.width=value; }); /**@inheritDoc */ __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Component,this,'height',value); this._bitmap.height=value; }); /**@inheritDoc */ __getset(0,__proto,'measureWidth',function(){ this.runCallLater(this.changeClip); return this._bitmap.width; }); /**@inheritDoc */ __getset(0,__proto,'measureHeight',function(){ this.runCallLater(this.changeClip); return this._bitmap.height; }); /** *当前帧索引。 */ __getset(0,__proto,'index',function(){ return this._index; },function(value){ this._index=value; this._bitmap && this._sources && (this._bitmap.source=this._sources[value]); this.event(/*laya.events.Event.CHANGE*/"change"); }); /** *表示是否自动播放动画,若自动播放值为true,否则值为false; *

    可控制切片动画的播放、停止。

    */ __getset(0,__proto,'autoPlay',function(){ return this._autoPlay; },function(value){ if (this._autoPlay !=value){ this._autoPlay=value; value ? this.play():this.stop(); } }); /** *表示动画的当前播放状态。 *如果动画正在播放中,则为true,否则为flash。 */ __getset(0,__proto,'isPlaying',function(){ return this._isPlaying; },function(value){ this._isPlaying=value; }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if (((typeof value=='number')&& Math.floor(value)==value)|| (typeof value=='string'))this.index=parseInt(value); else Laya.superSet(Component,this,'dataSource',value); }); /** *AutoBitmap 位图实例。 */ __getset(0,__proto,'bitmap',function(){ return this._bitmap; }); return Clip; })(Component) /** *ColorPicker 组件将显示包含多个颜色样本的列表,用户可以从中选择颜色。 * *@example 以下示例代码,创建了一个 ColorPicker 实例。 *package *{ *import laya.ui.ColorPicker; *import laya.utils.Handler; *public class ColorPicker_Example *{ *public function ColorPicker_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/color.png",Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *trace("资源加载完成!"); *var colorPicket:ColorPicker=new ColorPicker();//创建一个 ColorPicker 类的实例对象 colorPicket 。 *colorPicket.skin="resource/ui/color.png";//设置 colorPicket 的皮肤。 *colorPicket.x=100;//设置 colorPicket 对象的属性 x 的值,用于控制 colorPicket 对象的显示位置。 *colorPicket.y=100;//设置 colorPicket 对象的属性 y 的值,用于控制 colorPicket 对象的显示位置。 *colorPicket.changeHandler=new Handler(this,onChangeColor,[colorPicket]);//设置 colorPicket 的颜色改变回调函数。 *Laya.stage.addChild(colorPicket);//将此 colorPicket 对象添加到显示列表。 *} *private function onChangeColor(colorPicket:ColorPicker):void *{ *trace("当前选择的颜色: "+colorPicket.selectedColor); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *Laya.loader.load("resource/ui/color.png",laya.utils.Handler.create(this,loadComplete));//加载资源 *function loadComplete() *{ *console.log("资源加载完成!"); *var colorPicket=new laya.ui.ColorPicker();//创建一个 ColorPicker 类的实例对象 colorPicket 。 *colorPicket.skin="resource/ui/color.png";//设置 colorPicket 的皮肤。 *colorPicket.x=100;//设置 colorPicket 对象的属性 x 的值,用于控制 colorPicket 对象的显示位置。 *colorPicket.y=100;//设置 colorPicket 对象的属性 y 的值,用于控制 colorPicket 对象的显示位置。 *colorPicket.changeHandler=laya.utils.Handler.create(this,onChangeColor,[colorPicket],false);//设置 colorPicket 的颜色改变回调函数。 *Laya.stage.addChild(colorPicket);//将此 colorPicket 对象添加到显示列表。 *} *function onChangeColor(colorPicket) *{ *console.log("当前选择的颜色: "+colorPicket.selectedColor); *} *@example *import ColorPicker=laya.ui.ColorPicker; *import Handler=laya.utils.Handler; *class ColorPicker_Example { *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/color.png",Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *console.log("资源加载完成!"); *var colorPicket:ColorPicker=new ColorPicker();//创建一个 ColorPicker 类的实例对象 colorPicket 。 *colorPicket.skin="resource/ui/color.png";//设置 colorPicket 的皮肤。 *colorPicket.x=100;//设置 colorPicket 对象的属性 x 的值,用于控制 colorPicket 对象的显示位置。 *colorPicket.y=100;//设置 colorPicket 对象的属性 y 的值,用于控制 colorPicket 对象的显示位置。 *colorPicket.changeHandler=new Handler(this,this.onChangeColor,[colorPicket]);//设置 colorPicket 的颜色改变回调函数。 *Laya.stage.addChild(colorPicket);//将此 colorPicket 对象添加到显示列表。 *} *private onChangeColor(colorPicket:ColorPicker):void { *console.log("当前选择的颜色: "+colorPicket.selectedColor); *} *} */ //class laya.ui.ColorPicker extends laya.ui.Component var ColorPicker=(function(_super){ function ColorPicker(){ /** *当颜色发生改变时执行的函数处理器。 *默认返回参数color:颜色值字符串。 */ this.changeHandler=null; /** *@private *指定每个正方形的颜色小格子的宽高(以像素为单位)。 */ this._gridSize=11; /** *@private *表示颜色样本列表面板的背景颜色值。 */ this._bgColor="#ffffff"; /** *@private *表示颜色样本列表面板的边框颜色值。 */ this._borderColor="#000000"; /** *@private *表示颜色样本列表面板选择或输入的颜色值。 */ this._inputColor="#000000"; /** *@private *表示颜色输入框的背景颜色值。 */ this._inputBgColor="#efefef"; /** *@private *表示颜色样本列表面板。 */ this._colorPanel=null; /** *@private *表示颜色网格。 */ this._colorTiles=null; /** *@private *表示颜色块显示对象。 */ this._colorBlock=null; /** *@private *表示颜色输入框控件 Input 。 */ this._colorInput=null; /** *@private *表示点击后显示颜色样本列表面板的按钮控件 Button 。 */ this._colorButton=null; /** *@private *表示颜色值列表。 */ this._colors=[]; /** *@private *表示选择的颜色值。 */ this._selectedColor="#000000"; /**@private */ this._panelChanged=false; ColorPicker.__super.call(this); } __class(ColorPicker,'laya.ui.ColorPicker',_super); var __proto=ColorPicker.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._colorPanel && this._colorPanel.destroy(destroyChild); this._colorButton && this._colorButton.destroy(destroyChild); this._colorPanel=null; this._colorTiles=null; this._colorBlock=null; this._colorInput=null; this._colorButton=null; this._colors=null; this.changeHandler=null; } /**@inheritDoc */ __proto.createChildren=function(){ this.addChild(this._colorButton=new Button()); this._colorPanel=new Box(); this._colorPanel.size(230,166); this._colorPanel.addChild(this._colorTiles=new Sprite()); this._colorPanel.addChild(this._colorBlock=new Sprite()); this._colorPanel.addChild(this._colorInput=new Input()); } /**@inheritDoc */ __proto.initialize=function(){ this._colorButton.on(/*laya.events.Event.CLICK*/"click",this,this.onColorButtonClick); this._colorBlock.pos(5,5); this._colorInput.pos(60,5); this._colorInput.size(60,20); this._colorInput.on(/*laya.events.Event.CHANGE*/"change",this,this.onColorInputChange); this._colorInput.on(/*laya.events.Event.KEY_DOWN*/"keydown",this,this.onColorFieldKeyDown); this._colorTiles.pos(5,30); this._colorTiles.on(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.onColorTilesMouseMove); this._colorTiles.on(/*laya.events.Event.CLICK*/"click",this,this.onColorTilesClick); this._colorTiles.size(20 *this._gridSize,12 *this._gridSize); this._colorPanel.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onPanelMouseDown); this.bgColor=this._bgColor; } __proto.onPanelMouseDown=function(e){ e.stopPropagation(); } /** *改变颜色样本列表面板。 */ __proto.changePanel=function(){ this._panelChanged=false; var g=this._colorPanel.graphics; g.clear(); g.drawRect(0,0,230,166,this._bgColor,this._borderColor); this.drawBlock(this._selectedColor); this._colorInput.borderColor=this._borderColor; this._colorInput.bgColor=this._inputBgColor; this._colorInput.color=this._inputColor; g=this._colorTiles.graphics; g.clear(); var mainColors=[0x000000,0x333333,0x666666,0x999999,0xCCCCCC,0xFFFFFF,0xFF0000,0x00FF00,0x0000FF,0xFFFF00,0x00FFFF,0xFF00FF]; for (var i=0;i < 12;i++){ for (var j=0;j < 20;j++){ var color=0; if (j===0)color=mainColors[i]; else if (j===1)color=0x000000; else color=(((i *3+j / 6)% 3 << 0)+((i / 6)<< 0)*3)*0x33 << 16 | j % 6 *0x33 << 8 | (i << 0)% 6 *0x33; var strColor=UIUtils.toColor(color); this._colors.push(strColor); var x=j *this._gridSize; var y=i *this._gridSize; g.drawRect(x,y,this._gridSize,this._gridSize,strColor,"#000000"); } } } /** *颜色样本列表面板的显示按钮的 Event.MOUSE_DOWN 事件侦听处理函数。 */ __proto.onColorButtonClick=function(e){ if (this._colorPanel.parent)this.close(); else this.open(); } /** *打开颜色样本列表面板。 */ __proto.open=function(){ var p=this.localToGlobal(new Point()); var px=p.x+this._colorPanel.width <=Laya.stage.width ? p.x :Laya.stage.width-this._colorPanel.width; var py=p.y+this._colorButton.height; py=py+this._colorPanel.height <=Laya.stage.height ? py :p.y-this._colorPanel.height; this._colorPanel.pos(px,py); this._colorPanel.zOrder=1001; Laya._currentStage.addChild(this._colorPanel); Laya.stage.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.removeColorBox); } /** *关闭颜色样本列表面板。 */ __proto.close=function(){ Laya.stage.off(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.removeColorBox); this._colorPanel.removeSelf(); } /** *舞台的 Event.MOUSE_DOWN 事件侦听处理函数。 */ __proto.removeColorBox=function(e){ this.close(); } /** *小格子色块的 Event.KEY_DOWN 事件侦听处理函数。 */ __proto.onColorFieldKeyDown=function(e){ if (e.keyCode==13){ if (this._colorInput.text)this.selectedColor=this._colorInput.text; else this.selectedColor=null; this.close(); e.stopPropagation(); } } /** *颜色值输入框 Event.CHANGE 事件侦听处理函数。 */ __proto.onColorInputChange=function(e){ if (this._colorInput.text)this.drawBlock(this._colorInput.text); else this.drawBlock("#FFFFFF"); } /** *小格子色块的 Event.CLICK 事件侦听处理函数。 */ __proto.onColorTilesClick=function(e){ this.selectedColor=this.getColorByMouse(); this.close(); } /** *@private *小格子色块的 Event.MOUSE_MOVE 事件侦听处理函数。 */ __proto.onColorTilesMouseMove=function(e){ this._colorInput.focus=false; var color=this.getColorByMouse(); this._colorInput.text=color; this.drawBlock(color); } /** *通过鼠标位置取对应的颜色块的颜色值。 */ __proto.getColorByMouse=function(){ var point=this._colorTiles.getMousePoint(); var x=Math.floor(point.x / this._gridSize); var y=Math.floor(point.y / this._gridSize); return this._colors[y *20+x]; } /** *绘制颜色块。 *@param color 需要绘制的颜色块的颜色值。 */ __proto.drawBlock=function(color){ var g=this._colorBlock.graphics; g.clear(); var showColor=color ? color :"#ffffff"; g.drawRect(0,0,50,20,showColor,this._borderColor); color || g.drawLine(0,0,50,20,"#ff0000"); } /** *改变颜色。 */ __proto.changeColor=function(){ var g=this.graphics; g.clear(); var showColor=this._selectedColor || "#000000"; g.drawRect(0,0,this._colorButton.width,this._colorButton.height,showColor); } /**@private */ __proto._setPanelChanged=function(){ if (!this._panelChanged){ this._panelChanged=true; this.callLater(this.changePanel); } } /** *表示颜色输入框的背景颜色值。 */ __getset(0,__proto,'inputBgColor',function(){ return this._inputBgColor; },function(value){ this._inputBgColor=value; this._setPanelChanged(); }); /** *表示选择的颜色值。 */ __getset(0,__proto,'selectedColor',function(){ return this._selectedColor; },function(value){ if (this._selectedColor !=value){ this._selectedColor=this._colorInput.text=value; this.drawBlock(value); this.changeColor(); this.changeHandler && this.changeHandler.runWith(this._selectedColor); this.event(/*laya.events.Event.CHANGE*/"change",Event.EMPTY.setTo(/*laya.events.Event.CHANGE*/"change",this,this)); } }); /** *@copy laya.ui.Button#skin */ __getset(0,__proto,'skin',function(){ return this._colorButton.skin; },function(value){ this._colorButton.skin=value; this.changeColor(); }); /** *表示颜色样本列表面板的背景颜色值。 */ __getset(0,__proto,'bgColor',function(){ return this._bgColor; },function(value){ this._bgColor=value; this._setPanelChanged(); }); /** *表示颜色样本列表面板的边框颜色值。 */ __getset(0,__proto,'borderColor',function(){ return this._borderColor; },function(value){ this._borderColor=value; this._setPanelChanged(); }); /** *表示颜色样本列表面板选择或输入的颜色值。 */ __getset(0,__proto,'inputColor',function(){ return this._inputColor; },function(value){ this._inputColor=value; this._setPanelChanged(); }); return ColorPicker; })(Component) /** *ComboBox 组件包含一个下拉列表,用户可以从该列表中选择单个值。 * *@example 以下示例代码,创建了一个 ComboBox 实例。 *package *{ *import laya.ui.ComboBox; *import laya.utils.Handler; *public class ComboBox_Example *{ *public function ComboBox_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/button.png",Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *trace("资源加载完成!"); *var comboBox:ComboBox=new ComboBox("resource/ui/button.png","item0,item1,item2,item3,item4,item5");//创建一个 ComboBox 类的实例对象 comboBox ,传入它的皮肤和标签集。 *comboBox.x=100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 *comboBox.y=100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 *comboBox.selectHandler=new Handler(this,onSelect);//设置 comboBox 选择项改变时执行的处理器。 *Laya.stage.addChild(comboBox);//将此 comboBox 对象添加到显示列表。 *} *private function onSelect(index:int):void *{ *trace("当前选中的项对象索引: ",index); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/button.png",laya.utils.Handler.create(this,loadComplete));//加载资源 *function loadComplete(){ *console.log("资源加载完成!"); *var comboBox=new laya.ui.ComboBox("resource/ui/button.png","item0,item1,item2,item3,item4,item5");//创建一个 ComboBox 类的实例对象 comboBox ,传入它的皮肤和标签集。 *comboBox.x=100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 *comboBox.y=100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 *comboBox.selectHandler=new laya.utils.Handler(this,onSelect);//设置 comboBox 选择项改变时执行的处理器。 *Laya.stage.addChild(comboBox);//将此 comboBox 对象添加到显示列表。 *} *function onSelect(index) *{ *console.log("当前选中的项对象索引: ",index); *} *@example *import ComboBox=laya.ui.ComboBox; *import Handler=laya.utils.Handler; *class ComboBox_Example { *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/button.png",Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *console.log("资源加载完成!"); *var comboBox:ComboBox=new ComboBox("resource/ui/button.png","item0,item1,item2,item3,item4,item5");//创建一个 ComboBox 类的实例对象 comboBox ,传入它的皮肤和标签集。 *comboBox.x=100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 *comboBox.y=100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 *comboBox.selectHandler=new Handler(this,this.onSelect);//设置 comboBox 选择项改变时执行的处理器。 *Laya.stage.addChild(comboBox);//将此 comboBox 对象添加到显示列表。 *} *private onSelect(index:number):void { *console.log("当前选中的项对象索引: ",index); *} *} * */ //class laya.ui.ComboBox extends laya.ui.Component var ComboBox=(function(_super){ function ComboBox(skin,labels){ /**@private */ this._visibleNum=6; /** *@private */ this._button=null; /** *@private */ this._list=null; /** *@private */ this._isOpen=false; /** *@private */ this._itemSize=12; /** *@private */ this._labels=[]; /** *@private */ this._selectedIndex=-1; /** *@private */ this._selectHandler=null; /** *@private */ this._itemHeight=NaN; /** *@private */ this._listHeight=NaN; /** *@private */ this._listChanged=false; /** *@private */ this._itemChanged=false; /** *@private */ this._scrollBarSkin=null; /** *@private */ this._isCustomList=false; /** *渲染项,用来显示下拉列表展示对象 */ this.itemRender=null; ComboBox.__super.call(this); this._itemColors=Styles.comboBoxItemColors; this.skin=skin; this.labels=labels; } __class(ComboBox,'laya.ui.ComboBox',_super); var __proto=ComboBox.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._button && this._button.destroy(destroyChild); this._list && this._list.destroy(destroyChild); this._button=null; this._list=null; this._itemColors=null; this._labels=null; this._selectHandler=null; } /**@inheritDoc */ __proto.createChildren=function(){ this.addChild(this._button=new Button()); this._button.text.align="left"; this._button.labelPadding="0,0,0,5"; this._button.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onButtonMouseDown); } __proto._createList=function(){ this._list=new List(); if (this._scrollBarSkin)this._list.vScrollBarSkin=this._scrollBarSkin; this._setListEvent(this._list); } __proto._setListEvent=function(list){ this._list.selectEnable=true; this._list.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onListDown); this._list.mouseHandler=Handler.create(this,this.onlistItemMouse,null,false); if (this._list.scrollBar)this._list.scrollBar.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onScrollBarDown); } /** *@private */ __proto.onListDown=function(e){ e.stopPropagation(); } __proto.onScrollBarDown=function(e){ e.stopPropagation(); } __proto.onButtonMouseDown=function(e){ this.callLater(this.switchTo,[!this._isOpen]); } /** *@private */ __proto.changeList=function(){ this._listChanged=false; var labelWidth=this.width-2; var labelColor=this._itemColors[2]; this._itemHeight=this._itemSize+6; this._list.itemRender=this.itemRender || {type:"Box",child:[{type:"Label",props:{name:"label",x:1,padding:"3,3,3,3",width:labelWidth,height:this._itemHeight,fontSize:this._itemSize,color:labelColor}}]}; this._list.repeatY=this._visibleNum; this._list.refresh(); } /** *@private *下拉列表的鼠标事件响应函数。 */ __proto.onlistItemMouse=function(e,index){ var type=e.type; if (type===/*laya.events.Event.MOUSE_OVER*/"mouseover" || type===/*laya.events.Event.MOUSE_OUT*/"mouseout"){ if (this._isCustomList)return; var box=this._list.getCell(index); if (!box)return; var label=box.getChildByName("label"); if (label){ if (type===/*laya.events.Event.ROLL_OVER*/"mouseover"){ label.bgColor=this._itemColors[0]; label.color=this._itemColors[1]; }else { label.bgColor=null; label.color=this._itemColors[2]; } } }else if (type===/*laya.events.Event.CLICK*/"click"){ this.selectedIndex=index; this.isOpen=false; } } /** *@private */ __proto.switchTo=function(value){ this.isOpen=value; } /** *更改下拉列表的打开状态。 */ __proto.changeOpen=function(){ this.isOpen=!this._isOpen; } /** *更改下拉列表。 */ __proto.changeItem=function(){ this._itemChanged=false; this._listHeight=this._labels.length > 0 ? Math.min(this._visibleNum,this._labels.length)*this._itemHeight :this._itemHeight; if (!this._isCustomList){ var g=this._list.graphics; g.clear(); g.drawRect(0,0,this.width-1,this._listHeight,this._itemColors[4],this._itemColors[3]); }; var a=this._list.array || []; a.length=0; for (var i=0,n=this._labels.length;i < n;i++){ a.push({label:this._labels[i]}); } this._list.height=this._listHeight; this._list.array=a; } __proto.changeSelected=function(){ this._button.label=this.selectedLabel; } __proto._onStageMouseWheel=function(e){ if(!this._list||this._list.contains(e.target))return; this.removeList(null); } /** *关闭下拉列表。 */ __proto.removeList=function(e){ Laya.stage.off(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.removeList); Laya.stage.off(/*laya.events.Event.MOUSE_WHEEL*/"mousewheel",this,this._onStageMouseWheel); this.isOpen=false; } /** *表示选择的下拉列表项的索引。 */ __getset(0,__proto,'selectedIndex',function(){ return this._selectedIndex; },function(value){ if (this._selectedIndex !=value){ this._selectedIndex=value; if (this._labels.length > 0)this.changeSelected(); else this.callLater(this.changeSelected); this.event(/*laya.events.Event.CHANGE*/"change",[Event.EMPTY.setTo(/*laya.events.Event.CHANGE*/"change",this,this)]); this._selectHandler && this._selectHandler.runWith(this._selectedIndex); } }); /**@inheritDoc */ __getset(0,__proto,'measureHeight',function(){ return this._button.height; }); /** *@copy laya.ui.Button#skin */ __getset(0,__proto,'skin',function(){ return this._button.skin; },function(value){ if (this._button.skin !=value){ this._button.skin=value; this._listChanged=true; } }); /**@inheritDoc */ __getset(0,__proto,'measureWidth',function(){ return this._button.width; }); /**@inheritDoc */ __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(Component,this,'width',value); this._button.width=this._width; this._itemChanged=true; this._listChanged=true; }); /** *表示选择的下拉列表项的的标签。 */ __getset(0,__proto,'selectedLabel',function(){ return this._selectedIndex >-1 && this._selectedIndex < this._labels.length ? this._labels[this._selectedIndex] :null; },function(value){ this.selectedIndex=this._labels.indexOf(value); }); /** *标签集合字符串。 */ __getset(0,__proto,'labels',function(){ return this._labels.join(","); },function(value){ if (this._labels.length > 0)this.selectedIndex=-1; if (value)this._labels=value.split(","); else this._labels.length=0; this._itemChanged=true; }); /**@inheritDoc */ __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Component,this,'height',value); this._button.height=this._height; }); /** *改变下拉列表的选择项时执行的处理器(默认返回参数index:int)。 */ __getset(0,__proto,'selectHandler',function(){ return this._selectHandler; },function(value){ this._selectHandler=value; }); /** *获取或设置没有滚动条的下拉列表中可显示的最大行数。 */ __getset(0,__proto,'visibleNum',function(){ return this._visibleNum; },function(value){ this._visibleNum=value; this._listChanged=true; }); /** *表示按钮文本标签是否为粗体字。 *@see laya.display.Text#bold */ __getset(0,__proto,'labelBold',function(){ return this._button.text.bold; },function(value){ this._button.text.bold=value }); /** *下拉列表项颜色。 *

    格式:"悬停或被选中时背景颜色,悬停或被选中时标签颜色,标签颜色,边框颜色,背景颜色"

    */ __getset(0,__proto,'itemColors',function(){ return String(this._itemColors) },function(value){ this._itemColors=UIUtils.fillArray(this._itemColors,value,String); this._listChanged=true; }); /** *下拉列表项标签的字体大小。 */ __getset(0,__proto,'itemSize',function(){ return this._itemSize; },function(value){ this._itemSize=value; this._listChanged=true; }); /** *获取对 ComboBox 组件所包含的 VScrollBar 滚动条组件的引用。 */ __getset(0,__proto,'scrollBar',function(){ return this.list.scrollBar; }); /** *表示下拉列表的打开状态。 */ __getset(0,__proto,'isOpen',function(){ return this._isOpen; },function(value){ if (this._isOpen !=value){ this._isOpen=value; this._button.selected=this._isOpen; if (this._isOpen){ this._list || this._createList(); this._listChanged && !this._isCustomList && this.changeList(); this._itemChanged && this.changeItem(); var p=this.localToGlobal(Point.TEMP.setTo(0,0)); var py=p.y+this._button.height; py=py+this._listHeight <=Laya.stage.height ? py :p.y-this._listHeight; this._list.pos(p.x,py); this._list.zOrder=1001; Laya._currentStage.addChild(this._list); Laya.stage.once(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.removeList); Laya.stage.on(/*laya.events.Event.MOUSE_WHEEL*/"mousewheel",this,this._onStageMouseWheel); this._list.selectedIndex=this._selectedIndex; }else { this._list && this._list.removeSelf(); } } }); /** *滚动条皮肤。 */ __getset(0,__proto,'scrollBarSkin',function(){ return this._scrollBarSkin; },function(value){ this._scrollBarSkin=value; }); /** *

    当前实例的位图 AutoImage 实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    *@see laya.ui.AutoBitmap.sizeGrid */ __getset(0,__proto,'sizeGrid',function(){ return this._button.sizeGrid; },function(value){ this._button.sizeGrid=value; }); /** *获取对 ComboBox 组件所包含的 Button 组件的引用。 */ __getset(0,__proto,'button',function(){ return this._button; }); /** *获取对 ComboBox 组件所包含的 List 列表组件的引用。 */ __getset(0,__proto,'list',function(){ this._list || this._createList(); return this._list; },function(value){ if (value){ value.removeSelf(); this._isCustomList=true; this._list=value; this._setListEvent(value); this._itemHeight=value.getCell(0).height+value.spaceY; } }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if (((typeof value=='number')&& Math.floor(value)==value)|| (typeof value=='string'))this.selectedIndex=parseInt(value); else if ((value instanceof Array))this.labels=(value).join(","); else Laya.superSet(Component,this,'dataSource',value); }); /** *获取或设置对 ComboBox 组件所包含的 Button 组件的文本标签颜色。 *

    格式:upColor,overColor,downColor,disableColor

    */ __getset(0,__proto,'labelColors',function(){ return this._button.labelColors; },function(value){ if (this._button.labelColors !=value){ this._button.labelColors=value; } }); /** *获取或设置对 ComboBox 组件所包含的 Button 组件的文本边距。 *

    格式:上边距,右边距,下边距,左边距

    */ __getset(0,__proto,'labelPadding',function(){ return this._button.text.padding.join(","); },function(value){ this._button.text.padding=UIUtils.fillArray(Styles.labelPadding,value,Number); }); /** *获取或设置对 ComboBox 组件所包含的 Button 组件的标签字体大小。 */ __getset(0,__proto,'labelSize',function(){ return this._button.text.fontSize; },function(value){ this._button.text.fontSize=value }); /** *表示按钮文本标签的字体名称,以字符串形式表示。 *@see laya.display.Text#font */ __getset(0,__proto,'labelFont',function(){ return this._button.text.font; },function(value){ this._button.text.font=value }); /** *表示按钮的状态值。 *@see laya.ui.Button#stateNum */ __getset(0,__proto,'stateNum',function(){ return this._button.stateNum; },function(value){ this._button.stateNum=value }); return ComboBox; })(Component) /** *ScrollBar 组件是一个滚动条组件。 *

    当数据太多以至于显示区域无法容纳时,最终用户可以使用 ScrollBar 组件控制所显示的数据部分。

    *

    滚动条由四部分组成:两个箭头按钮、一个轨道和一个滑块。

    * * *@see laya.ui.VScrollBar *@see laya.ui.HScrollBar */ //class laya.ui.ScrollBar extends laya.ui.Component var ScrollBar=(function(_super){ function ScrollBar(skin){ /**滚动衰减系数*/ this.rollRatio=0.95; /**滚动变化时回调,回传value参数。*/ this.changeHandler=null; /**是否缩放滑动条,默认值为true。 */ this.scaleBar=true; /**一个布尔值,指定是否自动隐藏滚动条(无需滚动时),默认值为false。*/ this.autoHide=false; /**橡皮筋效果极限距离,0为没有橡皮筋效果。*/ this.elasticDistance=0; /**橡皮筋回弹时间,单位为毫秒。*/ this.elasticBackTime=500; /**上按钮 */ this.upButton=null; /**下按钮 */ this.downButton=null; /**滑条 */ this.slider=null; /**@private */ this._scrollSize=1; /**@private */ this._skin=null; /**@private */ this._thumbPercent=1; /**@private */ this._target=null; /**@private */ this._lastPoint=null; /**@private */ this._lastOffset=0; /**@private */ this._checkElastic=false; /**@private */ this._isElastic=false; /**@private */ this._value=NaN; /**@private */ this._hide=false; /**@private */ this._clickOnly=true; /**@private */ this._offsets=null; ScrollBar.__super.call(this); this._showButtons=UIConfig.showButtons; this._touchScrollEnable=UIConfig.touchScrollEnable; this._mouseWheelEnable=UIConfig.mouseWheelEnable; this.skin=skin; this.max=1; } __class(ScrollBar,'laya.ui.ScrollBar',_super); var __proto=ScrollBar.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); this.stopScroll(); this.target=null; _super.prototype.destroy.call(this,destroyChild); this.upButton && this.upButton.destroy(destroyChild); this.downButton && this.downButton.destroy(destroyChild); this.slider && this.slider.destroy(destroyChild); this.upButton=this.downButton=null; this.slider=null; this.changeHandler=null; this._offsets=null; } /**@inheritDoc */ __proto.createChildren=function(){ this.addChild(this.slider=new Slider()); this.addChild(this.upButton=new Button()); this.addChild(this.downButton=new Button()); } /**@inheritDoc */ __proto.initialize=function(){ this.slider.showLabel=false; this.slider.on(/*laya.events.Event.CHANGE*/"change",this,this.onSliderChange); this.slider.setSlider(0,0,0); this.upButton.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onButtonMouseDown); this.downButton.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onButtonMouseDown); } /** *@private *滑块位置发生改变的处理函数。 */ __proto.onSliderChange=function(){ if(this._value !=this.slider.value)this.value=this.slider.value; } /** *@private *向上和向下按钮的 Event.MOUSE_DOWN 事件侦听处理函数。 */ __proto.onButtonMouseDown=function(e){ var isUp=e.currentTarget===this.upButton; this.slide(isUp); Laya.timer.once(Styles.scrollBarDelayTime,this,this.startLoop,[isUp]); Laya.stage.once(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.onStageMouseUp); } /**@private */ __proto.startLoop=function(isUp){ Laya.timer.frameLoop(1,this,this.slide,[isUp]); } /**@private */ __proto.slide=function(isUp){ if (isUp)this.value-=this._scrollSize; else this.value+=this._scrollSize; } /** *@private *舞台的 Event.MOUSE_DOWN 事件侦听处理函数。 */ __proto.onStageMouseUp=function(e){ Laya.timer.clear(this,this.startLoop); Laya.timer.clear(this,this.slide); } /** *@private *更改对象的皮肤及位置。 */ __proto.changeScrollBar=function(){ this.upButton.visible=this._showButtons; this.downButton.visible=this._showButtons; if (this._showButtons){ this.upButton.skin=this._skin.replace(".png","$up.png"); this.downButton.skin=this._skin.replace(".png","$down.png"); } if (this.slider.isVertical)this.slider.y=this._showButtons ? this.upButton.height :0; else this.slider.x=this._showButtons ? this.upButton.width :0; this.resetPositions(); this.repaint(); } /**@inheritDoc */ __proto.changeSize=function(){ _super.prototype.changeSize.call(this); this.repaint(); this.resetPositions(); this.event(/*laya.events.Event.CHANGE*/"change"); this.changeHandler && this.changeHandler.runWith(this.value); } /**@private */ __proto.resetPositions=function(){ if (this.slider.isVertical)this.slider.height=this.height-(this._showButtons ? (this.upButton.height+this.downButton.height):0); else this.slider.width=this.width-(this._showButtons ? (this.upButton.width+this.downButton.width):0); this.resetButtonPosition(); } /**@private */ __proto.resetButtonPosition=function(){ if (this.slider.isVertical)this.downButton.y=this.slider.y+this.slider.height; else this.downButton.x=this.slider.x+this.slider.width; } /** *设置滚动条信息。 *@param min 滚动条最小位置值。 *@param max 滚动条最大位置值。 *@param value 滚动条当前位置值。 */ __proto.setScroll=function(min,max,value){ this.runCallLater(this.changeSize); this.slider.setSlider(min,max,value); this.slider.bar.visible=max > 0; if (!this._hide && this.autoHide)this.visible=false; } /**@private */ __proto.onTargetMouseWheel=function(e){ this.value-=e.delta *this._scrollSize; this.target=this._target; } /**@private */ __proto.onTargetMouseDown=function(e){ this._clickOnly=true; this._lastOffset=0; this._checkElastic=false; this._lastPoint || (this._lastPoint=new Point()); this._lastPoint.setTo(Laya.stage.mouseX,Laya.stage.mouseY); Laya.timer.clear(this,this.tweenMove); Tween.clearTween(this); Laya.stage.once(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.onStageMouseUp2); Laya.stage.once(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.onStageMouseUp2); Laya.timer.frameLoop(1,this,this.loop); } /**@private */ __proto.loop=function(){ var mouseY=Laya.stage.mouseY; var mouseX=Laya.stage.mouseX; this._lastOffset=this.isVertical ? (mouseY-this._lastPoint.y):(mouseX-this._lastPoint.x); if (this._clickOnly){ if (Math.abs(this._lastOffset *(this.isVertical ? Laya.stage._canvasTransform.getScaleY():Laya.stage._canvasTransform.getScaleX()))> 1){ this._clickOnly=false; this._offsets || (this._offsets=[]); this._offsets.length=0; this._target.mouseEnabled=false; if (!this.hide && this.autoHide){ this.alpha=1; this.visible=true; } this.event(/*laya.events.Event.START*/"start"); }else return; } this._offsets.push(this._lastOffset); this._lastPoint.x=mouseX; this._lastPoint.y=mouseY; if (this._lastOffset===0)return; if (!this._checkElastic){ if (this.elasticDistance > 0){ if (!this._checkElastic && this._lastOffset !=0){ if ((this._lastOffset > 0 && this._value <=this.min)|| (this._lastOffset < 0 && this._value >=this.max)){ this._isElastic=true; this._checkElastic=true; }else { this._isElastic=false; } } }else { this._checkElastic=true; } } if (this._isElastic){ if (this._value <=this.min){ this.value-=this._lastOffset *Math.max(0,(1-((this.min-this._value)/ this.elasticDistance))); }else if (this._value >=this.max){ this.value-=this._lastOffset *Math.max(0,(1-((this._value-this.max)/ this.elasticDistance))); } }else { this.value-=this._lastOffset; } } /**@private */ __proto.onStageMouseUp2=function(e){ Laya.stage.off(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.onStageMouseUp2); Laya.stage.off(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.onStageMouseUp2); Laya.timer.clear(this,this.loop); if (this._clickOnly){ if(this._value>=this.min&&this._value<=this.max) return; } this._target.mouseEnabled=true; if (this._isElastic){ if (this._value < this.min){ Tween.to(this,{value:this.min},this.elasticBackTime,Ease.sineOut,Handler.create(this,this.elasticOver)); }else if (this._value > this.max){ Tween.to(this,{value:this.max},this.elasticBackTime,Ease.sineOut,Handler.create(this,this.elasticOver)); } }else { if (!this._offsets)return; if (this._offsets.length < 1){ this._offsets[0]=this.isVertical ? Laya.stage.mouseY-this._lastPoint.y :Laya.stage.mouseX-this._lastPoint.x; }; var offset=0; var n=Math.min(this._offsets.length,3); for (var i=0;i < n;i++){ offset+=this._offsets[this._offsets.length-1-i]; } this._lastOffset=offset / n; offset=Math.abs(this._lastOffset); if (offset < 2){ this.event(/*laya.events.Event.END*/"end"); return; } if (offset > 60)this._lastOffset=this._lastOffset > 0 ? 60 :-60; var dis=Math.round(Math.abs(this.elasticDistance *(this._lastOffset / 240))); Laya.timer.frameLoop(1,this,this.tweenMove,[dis]); } } /**@private */ __proto.elasticOver=function(){ this._isElastic=false; if (!this.hide && this.autoHide){ Tween.to(this,{alpha:0},500); } this.event(/*laya.events.Event.END*/"end"); } /**@private */ __proto.tweenMove=function(maxDistance){ this._lastOffset *=this.rollRatio; var tarSpeed=NaN; if (maxDistance > 0){ if (this._lastOffset > 0 && this.value <=this.min){ this._isElastic=true; tarSpeed=-(this.min-maxDistance-this.value)*0.5; if (this._lastOffset > tarSpeed)this._lastOffset=tarSpeed; }else if (this._lastOffset < 0 && this.value >=this.max){ this._isElastic=true; tarSpeed=-(this.max+maxDistance-this.value)*0.5; if (this._lastOffset < tarSpeed)this._lastOffset=tarSpeed; } } this.value-=this._lastOffset; if (Math.abs(this._lastOffset)< 1){ Laya.timer.clear(this,this.tweenMove); if (this._isElastic){ if (this._value < this.min){ Tween.to(this,{value:this.min},this.elasticBackTime,Ease.sineOut,Handler.create(this,this.elasticOver)); }else if (this._value > this.max){ Tween.to(this,{value:this.max},this.elasticBackTime,Ease.sineOut,Handler.create(this,this.elasticOver)); }else { this.elasticOver(); } return; } this.event(/*laya.events.Event.END*/"end"); if (!this.hide && this.autoHide){ Tween.to(this,{alpha:0},500); } } } /** *停止滑动。 */ __proto.stopScroll=function(){ this.onStageMouseUp2(null); Laya.timer.clear(this,this.tweenMove); Tween.clearTween(this); } /**@inheritDoc */ __getset(0,__proto,'measureHeight',function(){ if (this.slider.isVertical)return 100; return this.slider.height; }); /** *@copy laya.ui.Image#skin */ __getset(0,__proto,'skin',function(){ return this._skin; },function(value){ if (this._skin !=value){ this._skin=value; this.slider.skin=this._skin; this.callLater(this.changeScrollBar); } }); /** *获取或设置表示最高滚动位置的数字。 */ __getset(0,__proto,'max',function(){ return this.slider.max; },function(value){ this.slider.max=value; }); /**一个布尔值,指定是否显示向上、向下按钮,默认值为true。*/ __getset(0,__proto,'showButtons',function(){ return this._showButtons; },function(value){ this._showButtons=value; this.callLater(this.changeScrollBar); }); /**@inheritDoc */ __getset(0,__proto,'measureWidth',function(){ if (this.slider.isVertical)return this.slider.width; return 100; }); /** *获取或设置表示最低滚动位置的数字。 */ __getset(0,__proto,'min',function(){ return this.slider.min; },function(value){ this.slider.min=value; }); /** *获取或设置表示当前滚动位置的数字。 */ __getset(0,__proto,'value',function(){ return this._value; },function(v){ if (v!==this._value){ this._value=v; if (!this._isElastic){ if (this.slider._value !=v){ this.slider._value=v; this.slider.changeValue(); } this._value=this.slider._value; } this.event(/*laya.events.Event.CHANGE*/"change"); this.changeHandler && this.changeHandler.runWith(this._value); } }); /** *一个布尔值,指示滚动条是否为垂直滚动。如果值为true,则为垂直滚动,否则为水平滚动。 *

    默认值为:true。

    */ __getset(0,__proto,'isVertical',function(){ return this.slider.isVertical; },function(value){ this.slider.isVertical=value; }); /** *

    当前实例的 Slider 实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    *@see laya.ui.AutoBitmap.sizeGrid */ __getset(0,__proto,'sizeGrid',function(){ return this.slider.sizeGrid; },function(value){ this.slider.sizeGrid=value; }); /**获取或设置一个值,该值表示按下滚动条轨道时页面滚动的增量。 */ __getset(0,__proto,'scrollSize',function(){ return this._scrollSize; },function(value){ this._scrollSize=value; }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if ((typeof value=='number')|| (typeof value=='string'))this.value=Number(value); else Laya.superSet(Component,this,'dataSource',value); }); /**获取或设置一个值,该值表示滑条长度比例,值为:(0-1)。 */ __getset(0,__proto,'thumbPercent',function(){ return this._thumbPercent; },function(value){ this.runCallLater(this.changeScrollBar); this.runCallLater(this.changeSize); value=value >=1 ? 0.99 :value; this._thumbPercent=value; if (this.scaleBar){ if (this.slider.isVertical)this.slider.bar.height=Math.max(this.slider.height *value,Styles.scrollBarMinNum); else this.slider.bar.width=Math.max(this.slider.width *value,Styles.scrollBarMinNum); } }); /** *设置滚动对象。 *@see laya.ui.TouchScroll#target */ __getset(0,__proto,'target',function(){ return this._target; },function(value){ if (this._target){ this._target.off(/*laya.events.Event.MOUSE_WHEEL*/"mousewheel",this,this.onTargetMouseWheel); this._target.off(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onTargetMouseDown); } this._target=value; if (value){ this._mouseWheelEnable && this._target.on(/*laya.events.Event.MOUSE_WHEEL*/"mousewheel",this,this.onTargetMouseWheel); this._touchScrollEnable && this._target.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onTargetMouseDown); } }); /**是否隐藏滚动条,不显示滚动条,但是可以正常滚动,默认为false。*/ __getset(0,__proto,'hide',function(){ return this._hide; },function(value){ this._hide=value; this.visible=!value; }); /**一个布尔值,指定是否开启触摸,默认值为true。*/ __getset(0,__proto,'touchScrollEnable',function(){ return this._touchScrollEnable; },function(value){ this._touchScrollEnable=value; this.target=this._target; }); /**一个布尔值,指定是否滑轮滚动,默认值为true。*/ __getset(0,__proto,'mouseWheelEnable',function(){ return this._mouseWheelEnable; },function(value){ this._mouseWheelEnable=value; this.target=this._target; }); /** *滚动的刻度值,滑动数值为tick的整数倍。默认值为1。 */ __getset(0,__proto,'tick',function(){ return this.slider.tick; },function(value){ this.slider.tick=value; }); return ScrollBar; })(Component) /** *使用 Slider 控件,用户可以通过在滑块轨道的终点之间移动滑块来选择值。 *

    滑块的当前值由滑块端点(对应于滑块的最小值和最大值)之间滑块的相对位置确定。

    *

    滑块允许最小值和最大值之间特定间隔内的值。滑块还可以使用数据提示显示其当前值。

    * *@see laya.ui.HSlider *@see laya.ui.VSlider */ //class laya.ui.Slider extends laya.ui.Component var Slider=(function(_super){ function Slider(skin){ /** *数据变化处理器。 *

    默认回调参数为滑块位置属性 value属性值:Number 。

    */ this.changeHandler=null; /** *一个布尔值,指示是否为垂直滚动。如果值为true,则为垂直方向,否则为水平方向。 *

    默认值为:true。

    *@default true */ this.isVertical=true; /** *一个布尔值,指示是否显示标签。 *@default true */ this.showLabel=true; /**@private */ this._allowClickBack=false; /**@private */ this._max=100; /**@private */ this._min=0; /**@private */ this._tick=1; /**@private */ this._value=0; /**@private */ this._skin=null; /**@private */ this._bg=null; /**@private */ this._progress=null; /**@private */ this._bar=null; /**@private */ this._tx=NaN; /**@private */ this._ty=NaN; /**@private */ this._maxMove=NaN; /**@private */ this._globalSacle=null; Slider.__super.call(this); this.skin=skin; } __class(Slider,'laya.ui.Slider',_super); var __proto=Slider.prototype; /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._bg && this._bg.destroy(destroyChild); this._bar && this._bar.destroy(destroyChild); this._progress && this._progress.destroy(destroyChild); this._bg=null; this._bar=null; this._progress=null; this.changeHandler=null; } /**@inheritDoc */ __proto.createChildren=function(){ this.addChild(this._bg=new Image()); this.addChild(this._bar=new Button()); } /**@inheritDoc */ __proto.initialize=function(){ this._bar.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onBarMouseDown); this._bg.sizeGrid=this._bar.sizeGrid="4,4,4,4,0"; if (this._progress)this._progress.sizeGrid=this._bar.sizeGrid; this.allowClickBack=true; } /** *@private *滑块的的 Event.MOUSE_DOWN 事件侦听处理函数。 */ __proto.onBarMouseDown=function(e){ this._globalSacle || (this._globalSacle=new Point()); this._globalSacle.setTo(this.globalScaleX || 0.01,this.globalScaleY || 0.01); this._maxMove=this.isVertical ? (this.height-this._bar.height):(this.width-this._bar.width); this._tx=Laya.stage.mouseX; this._ty=Laya.stage.mouseY; Laya.stage.on(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.mouseMove); Laya.stage.once(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.mouseUp); Laya.stage.once(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.mouseUp); this.showValueText(); } /** *@private *显示标签。 */ __proto.showValueText=function(){ if (this.showLabel){ var label=laya.ui.Slider.label; this.addChild(label); label.textField.changeText(this._value+""); if (this.isVertical){ label.x=this._bar.x+20; label.y=(this._bar.height-label.height)*0.5+this._bar.y; }else { label.y=this._bar.y-20; label.x=(this._bar.width-label.width)*0.5+this._bar.x; } } } /** *@private *隐藏标签。 */ __proto.hideValueText=function(){ laya.ui.Slider.label && laya.ui.Slider.label.removeSelf(); } /** *@private */ __proto.mouseUp=function(e){ Laya.stage.off(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this.mouseMove); Laya.stage.off(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.mouseUp); Laya.stage.off(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.mouseUp); this.sendChangeEvent(/*laya.events.Event.CHANGED*/"changed"); this.hideValueText(); } /** *@private */ __proto.mouseMove=function(e){ var oldValue=this._value; if (this.isVertical){ this._bar.y+=(Laya.stage.mouseY-this._ty)/ this._globalSacle.y; if (this._bar.y > this._maxMove)this._bar.y=this._maxMove; else if (this._bar.y < 0)this._bar.y=0; this._value=this._bar.y / this._maxMove *(this._max-this._min)+this._min; if(this._progress)this._progress.height=this._bar.y+0.5*this._bar.height; }else { this._bar.x+=(Laya.stage.mouseX-this._tx)/ this._globalSacle.x; if (this._bar.x > this._maxMove)this._bar.x=this._maxMove; else if (this._bar.x < 0)this._bar.x=0; this._value=this._bar.x / this._maxMove *(this._max-this._min)+this._min; if(this._progress)this._progress.width=this._bar.x+0.5*this._bar.width; } this._tx=Laya.stage.mouseX; this._ty=Laya.stage.mouseY; var pow=Math.pow(10,(this._tick+"").length-1); this._value=Math.round(Math.round(this._value / this._tick)*this._tick *pow)/ pow; if (this._value !=oldValue){ this.sendChangeEvent(); } this.showValueText(); } /** *@private */ __proto.sendChangeEvent=function(type){ (type===void 0)&& (type=/*laya.events.Event.CHANGE*/"change"); this.event(type); this.changeHandler && this.changeHandler.runWith(this._value); } /** *@private *设置滑块的位置信息。 */ __proto.setBarPoint=function(){ if (this.isVertical)this._bar.x=Math.round((this._bg.width-this._bar.width)*0.5); else this._bar.y=Math.round((this._bg.height-this._bar.height)*0.5); } /**@inheritDoc */ __proto.changeSize=function(){ _super.prototype.changeSize.call(this); if (this.isVertical)this._bg.height=this.height; else this._bg.width=this.width; this.setBarPoint(); this.changeValue(); } /** *设置滑动条的信息。 *@param min 滑块的最小值。 *@param max 滑块的最小值。 *@param value 滑块的当前值。 */ __proto.setSlider=function(min,max,value){ this._value=-1; this._min=min; this._max=max > min ? max :min; this.value=value < min ? min :value > max ? max :value; } /** *@private *改变滑块的位置值。 */ __proto.changeValue=function(){ var pow=Math.pow(10,(this._tick+"").length-1); this._value=Math.round(Math.round(this._value / this._tick)*this._tick *pow)/ pow; this._value=this._value > this._max ? this._max :this._value < this._min ? this._min :this._value; var num=this._max-this._min; if (num===0)num=1; if (this.isVertical){ this._bar.y=(this._value-this._min)/ num *(this.height-this._bar.height); if(this._progress)this._progress.height=this._bar.y+0.5*this._bar.height; } else{ this._bar.x=(this._value-this._min)/ num *(this.width-this._bar.width); if(this._progress)this._progress.width=this._bar.x+0.5*this._bar.width; } } /** *@private *滑动条的 Event.MOUSE_DOWN 事件侦听处理函数。 */ __proto.onBgMouseDown=function(e){ var point=this._bg.getMousePoint(); if (this.isVertical)this.value=point.y / (this.height-this._bar.height)*(this._max-this._min)+this._min; else this.value=point.x / (this.width-this._bar.width)*(this._max-this._min)+this._min; } /**@inheritDoc */ __getset(0,__proto,'measureHeight',function(){ return Math.max(this._bg.height,this._bar.height); }); /** *@copy laya.ui.Image#skin */ __getset(0,__proto,'skin',function(){ return this._skin; },function(value){ if (this._skin !=value){ this._skin=value; this._bg.skin=this._skin; this._bar.skin=this._skin.replace(".png","$bar.png"); var progressSkin=this._skin.replace(".png","$progress.png"); if (Loader.getRes(progressSkin)){ if (!this._progress){ this.addChild(this._progress=new Image()); this._progress.sizeGrid=this._bar.sizeGrid; this.setChildIndex(this._progress,1); } this._progress.skin=progressSkin; } this.setBarPoint(); this.callLater(this.changeValue); } }); /** *一个布尔值,指定是否允许通过点击滑动条改变 Slidervalue 属性值。 */ __getset(0,__proto,'allowClickBack',function(){ return this._allowClickBack; },function(value){ if (this._allowClickBack !=value){ this._allowClickBack=value; if (value)this._bg.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onBgMouseDown); else this._bg.off(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onBgMouseDown); } }); /** *获取或设置表示最高位置的数字。 默认值为100。 */ __getset(0,__proto,'max',function(){ return this._max; },function(value){ if (this._max !=value){ this._max=value; this.callLater(this.changeValue); } }); /**@inheritDoc */ __getset(0,__proto,'measureWidth',function(){ return Math.max(this._bg.width,this._bar.width); }); /** *滑动的刻度值,滑动数值为tick的整数倍。默认值为1。 */ __getset(0,__proto,'tick',function(){ return this._tick; },function(value){ if (this._tick !=value){ this._tick=value; this.callLater(this.changeValue); } }); /** *

    当前实例的背景图( Image )和滑块按钮( Button )实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    *@see laya.ui.AutoBitmap.sizeGrid */ __getset(0,__proto,'sizeGrid',function(){ return this._bg.sizeGrid; },function(value){ this._bg.sizeGrid=value; this._bar.sizeGrid=value; if (this._progress)this._progress.sizeGrid=this._bar.sizeGrid; }); /** *获取或设置表示最低位置的数字。 默认值为0。 */ __getset(0,__proto,'min',function(){ return this._min; },function(value){ if (this._min !=value){ this._min=value; this.callLater(this.changeValue); } }); /** *获取或设置表示当前滑块位置的数字。 */ __getset(0,__proto,'value',function(){ return this._value; },function(num){ if (this._value !=num){ var oldValue=this._value; this._value=num; this.changeValue(); if (this._value !=oldValue){ this.sendChangeEvent(); } } }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if ((typeof value=='number')|| (typeof value=='string'))this.value=Number(value); else Laya.superSet(Component,this,'dataSource',value); }); /** *表示滑块按钮的引用。 */ __getset(0,__proto,'bar',function(){ return this._bar; }); __static(Slider, ['label',function(){return this.label=new Label();} ]); return Slider; })(Component) /** *

    Label 类用于创建显示对象以显示文本。

    * *@example 以下示例代码,创建了一个 Label 实例。 *package *{ *import laya.ui.Label; *public class Label_Example *{ *public function Label_Example() *{ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *onInit(); *} *private function onInit():void *{ *var label:Label=new Label();//创建一个 Label 类的实例对象 label 。 *label.font="Arial";//设置 label 的字体。 *label.bold=true;//设置 label 显示为粗体。 *label.leading=4;//设置 label 的行间距。 *label.wordWrap=true;//设置 label 自动换行。 *label.padding="10,10,10,10";//设置 label 的边距。 *label.color="#ff00ff";//设置 label 的颜色。 *label.text="Hello everyone,我是一个可爱的文本!";//设置 label 的文本内容。 *label.x=100;//设置 label 对象的属性 x 的值,用于控制 label 对象的显示位置。 *label.y=100;//设置 label 对象的属性 y 的值,用于控制 label 对象的显示位置。 *label.width=300;//设置 label 的宽度。 *label.height=200;//设置 label 的高度。 *Laya.stage.addChild(label);//将 label 添加到显示列表。 *var passwordLabel:Label=new Label("请原谅我,我不想被人看到我心里话。");//创建一个 Label 类的实例对象 passwordLabel 。 *passwordLabel.asPassword=true;//设置 passwordLabel 的显示反式为密码显示。 *passwordLabel.x=100;//设置 passwordLabel 对象的属性 x 的值,用于控制 passwordLabel 对象的显示位置。 *passwordLabel.y=350;//设置 passwordLabel 对象的属性 y 的值,用于控制 passwordLabel 对象的显示位置。 *passwordLabel.width=300;//设置 passwordLabel 的宽度。 *passwordLabel.color="#000000";//设置 passwordLabel 的文本颜色。 *passwordLabel.bgColor="#ccffff";//设置 passwordLabel 的背景颜色。 *passwordLabel.fontSize=20;//设置 passwordLabel 的文本字体大小。 *Laya.stage.addChild(passwordLabel);//将 passwordLabel 添加到显示列表。 *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *onInit(); *function onInit(){ *var label=new laya.ui.Label();//创建一个 Label 类的实例对象 label 。 *label.font="Arial";//设置 label 的字体。 *label.bold=true;//设置 label 显示为粗体。 *label.leading=4;//设置 label 的行间距。 *label.wordWrap=true;//设置 label 自动换行。 *label.padding="10,10,10,10";//设置 label 的边距。 *label.color="#ff00ff";//设置 label 的颜色。 *label.text="Hello everyone,我是一个可爱的文本!";//设置 label 的文本内容。 *label.x=100;//设置 label 对象的属性 x 的值,用于控制 label 对象的显示位置。 *label.y=100;//设置 label 对象的属性 y 的值,用于控制 label 对象的显示位置。 *label.width=300;//设置 label 的宽度。 *label.height=200;//设置 label 的高度。 *Laya.stage.addChild(label);//将 label 添加到显示列表。 *var passwordLabel=new laya.ui.Label("请原谅我,我不想被人看到我心里话。");//创建一个 Label 类的实例对象 passwordLabel 。 *passwordLabel.asPassword=true;//设置 passwordLabel 的显示反式为密码显示。 *passwordLabel.x=100;//设置 passwordLabel 对象的属性 x 的值,用于控制 passwordLabel 对象的显示位置。 *passwordLabel.y=350;//设置 passwordLabel 对象的属性 y 的值,用于控制 passwordLabel 对象的显示位置。 *passwordLabel.width=300;//设置 passwordLabel 的宽度。 *passwordLabel.color="#000000";//设置 passwordLabel 的文本颜色。 *passwordLabel.bgColor="#ccffff";//设置 passwordLabel 的背景颜色。 *passwordLabel.fontSize=20;//设置 passwordLabel 的文本字体大小。 *Laya.stage.addChild(passwordLabel);//将 passwordLabel 添加到显示列表。 *} *@example *import Label=laya.ui.Label; *class Label_Example { *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *this.onInit(); *} *private onInit():void { *var label:Label=new Label();//创建一个 Label 类的实例对象 label 。 *label.font="Arial";//设置 label 的字体。 *label.bold=true;//设置 label 显示为粗体。 *label.leading=4;//设置 label 的行间距。 *label.wordWrap=true;//设置 label 自动换行。 *label.padding="10,10,10,10";//设置 label 的边距。 *label.color="#ff00ff";//设置 label 的颜色。 *label.text="Hello everyone,我是一个可爱的文本!";//设置 label 的文本内容。 *label.x=100;//设置 label 对象的属性 x 的值,用于控制 label 对象的显示位置。 *label.y=100;//设置 label 对象的属性 y 的值,用于控制 label 对象的显示位置。 *label.width=300;//设置 label 的宽度。 *label.height=200;//设置 label 的高度。 *Laya.stage.addChild(label);//将 label 添加到显示列表。 *var passwordLabel:Label=new Label("请原谅我,我不想被人看到我心里话。");//创建一个 Label 类的实例对象 passwordLabel 。 *passwordLabel.asPassword=true;//设置 passwordLabel 的显示反式为密码显示。 *passwordLabel.x=100;//设置 passwordLabel 对象的属性 x 的值,用于控制 passwordLabel 对象的显示位置。 *passwordLabel.y=350;//设置 passwordLabel 对象的属性 y 的值,用于控制 passwordLabel 对象的显示位置。 *passwordLabel.width=300;//设置 passwordLabel 的宽度。 *passwordLabel.color="#000000";//设置 passwordLabel 的文本颜色。 *passwordLabel.bgColor="#ccffff";//设置 passwordLabel 的背景颜色。 *passwordLabel.fontSize=20;//设置 passwordLabel 的文本字体大小。 *Laya.stage.addChild(passwordLabel);//将 passwordLabel 添加到显示列表。 *} *} *@see laya.display.Text */ //class laya.ui.Label extends laya.ui.Component var Label=(function(_super){ function Label(text){ /** *@private *文本 Text 实例。 */ this._tf=null; Label.__super.call(this); (text===void 0)&& (text=""); Font.defaultColor=Styles.labelColor; this.text=text; } __class(Label,'laya.ui.Label',_super); var __proto=Label.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._tf=null; } /**@inheritDoc */ __proto.createChildren=function(){ this.addChild(this._tf=new Text()); } /**@copy laya.display.Text#changeText() **/ __proto.changeText=function(text){ this._tf.changeText(text); } /** *

    边距信息

    *

    "上边距,右边距,下边距 , 左边距(边距以像素为单位)"

    *@see laya.display.Text.padding */ __getset(0,__proto,'padding',function(){ return this._tf.padding.join(","); },function(value){ this._tf.padding=UIUtils.fillArray(Styles.labelPadding,value,Number); }); /** *@copy laya.display.Text#bold */ __getset(0,__proto,'bold',function(){ return this._tf.bold; },function(value){ this._tf.bold=value; }); /** *@copy laya.display.Text#align */ __getset(0,__proto,'align',function(){ return this._tf.align; },function(value){ this._tf.align=value; }); /** *当前文本内容字符串。 *@see laya.display.Text.text */ __getset(0,__proto,'text',function(){ return this._tf.text; },function(value){ if (this._tf.text !=value){ if(value) value=UIUtils.adptString(value+""); this._tf.text=value; this.event(/*laya.events.Event.CHANGE*/"change"); if (!this._width || !this._height)this.onCompResize(); } }); /** *@copy laya.display.Text#italic */ __getset(0,__proto,'italic',function(){ return this._tf.italic; },function(value){ this._tf.italic=value; }); /** *@copy laya.display.Text#wordWrap */ /** *@copy laya.display.Text#wordWrap */ __getset(0,__proto,'wordWrap',function(){ return this._tf.wordWrap; },function(value){ this._tf.wordWrap=value; }); /** *@copy laya.display.Text#font */ __getset(0,__proto,'font',function(){ return this._tf.font; },function(value){ this._tf.font=value; }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if ((typeof value=='number')|| (typeof value=='string'))this.text=value+""; else Laya.superSet(Component,this,'dataSource',value); }); /** *@copy laya.display.Text#color */ __getset(0,__proto,'color',function(){ return this._tf.color; },function(value){ this._tf.color=value; }); /** *@copy laya.display.Text#valign */ __getset(0,__proto,'valign',function(){ return this._tf.valign; },function(value){ this._tf.valign=value; }); /** *@copy laya.display.Text#leading */ __getset(0,__proto,'leading',function(){ return this._tf.leading; },function(value){ this._tf.leading=value; }); /** *@copy laya.display.Text#fontSize */ __getset(0,__proto,'fontSize',function(){ return this._tf.fontSize; },function(value){ this._tf.fontSize=value; }); /** *@copy laya.display.Text#bgColor */ __getset(0,__proto,'bgColor',function(){ return this._tf.bgColor },function(value){ this._tf.bgColor=value; }); /** *@copy laya.display.Text#borderColor */ __getset(0,__proto,'borderColor',function(){ return this._tf.borderColor },function(value){ this._tf.borderColor=value; }); /** *@copy laya.display.Text#stroke */ __getset(0,__proto,'stroke',function(){ return this._tf.stroke; },function(value){ this._tf.stroke=value; }); /** *@copy laya.display.Text#strokeColor */ __getset(0,__proto,'strokeColor',function(){ return this._tf.strokeColor; },function(value){ this._tf.strokeColor=value; }); /** *文本控件实体 Text 实例。 */ __getset(0,__proto,'textField',function(){ return this._tf; }); /** *@inheritDoc */ __getset(0,__proto,'measureWidth',function(){ return this._tf.width; }); /** *@inheritDoc */ __getset(0,__proto,'measureHeight',function(){ return this._tf.height; }); /** *@inheritDoc */ /** *@inheritDoc */ __getset(0,__proto,'width',function(){ if (this._width || this._tf.text)return Laya.superGet(Component,this,'width'); return 0; },function(value){ Laya.superSet(Component,this,'width',value); this._tf.width=value; }); /** *@inheritDoc */ /** *@inheritDoc */ __getset(0,__proto,'height',function(){ if (this._height || this._tf.text)return Laya.superGet(Component,this,'height'); return 0; },function(value){ Laya.superSet(Component,this,'height',value); this._tf.height=value; }); /** *@copy laya.display.Text#overflow */ /** *@copy laya.display.Text#overflow */ __getset(0,__proto,'overflow',function(){ return this._tf.overflow; },function(value){ this._tf.overflow=value; }); /** *@copy laya.display.Text#underline */ /** *@copy laya.display.Text#underline */ __getset(0,__proto,'underline',function(){ return this._tf.underline; },function(value){ this._tf.underline=value; }); /** *@copy laya.display.Text#underlineColor */ /** *@copy laya.display.Text#underlineColor */ __getset(0,__proto,'underlineColor',function(){ return this._tf.underlineColor; },function(value){ this._tf.underlineColor=value; }); return Label; })(Component) /** *ProgressBar 组件显示内容的加载进度。 *@example 以下示例代码,创建了一个新的 ProgressBar 实例,设置了它的皮肤、位置、宽高、网格等信息,并添加到舞台上。 *package *{ *import laya.ui.ProgressBar; *import laya.utils.Handler; *public class ProgressBar_Example *{ *private var progressBar:ProgressBar; *public function ProgressBar_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/progress.png","resource/ui/progress$bar.png"],Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *progressBar=new ProgressBar("resource/ui/progress.png");//创建一个 ProgressBar 类的实例对象 progressBar 。 *progressBar.x=100;//设置 progressBar 对象的属性 x 的值,用于控制 progressBar 对象的显示位置。 *progressBar.y=100;//设置 progressBar 对象的属性 y 的值,用于控制 progressBar 对象的显示位置。 *progressBar.value=0.3;//设置 progressBar 的进度值。 *progressBar.width=200;//设置 progressBar 的宽度。 *progressBar.height=50;//设置 progressBar 的高度。 *progressBar.sizeGrid="5,10,5,10";//设置 progressBar 的网格信息。 *progressBar.changeHandler=new Handler(this,onChange);//设置 progressBar 的value值改变时执行的处理器。 *Laya.stage.addChild(progressBar);//将 progressBar 添加到显示列表。 *Laya.timer.once(3000,this,changeValue);//设定 3000ms(毫秒)后,执行函数changeValue。 *} *private function changeValue():void *{ *trace("改变进度条的进度值。"); *progressBar.value=0.6; *} *private function onChange(value:Number):void *{ *trace("进度发生改变: value=" ,value); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *var res=["resource/ui/progress.png","resource/ui/progress$bar.png"]; *Laya.loader.load(res,laya.utils.Handler.create(this,onLoadComplete));//加载资源。 *function onLoadComplete() *{ *progressBar=new laya.ui.ProgressBar("resource/ui/progress.png");//创建一个 ProgressBar 类的实例对象 progressBar 。 *progressBar.x=100;//设置 progressBar 对象的属性 x 的值,用于控制 progressBar 对象的显示位置。 *progressBar.y=100;//设置 progressBar 对象的属性 y 的值,用于控制 progressBar 对象的显示位置。 *progressBar.value=0.3;//设置 progressBar 的进度值。 *progressBar.width=200;//设置 progressBar 的宽度。 *progressBar.height=50;//设置 progressBar 的高度。 *progressBar.sizeGrid="10,5,10,5";//设置 progressBar 的网格信息。 *progressBar.changeHandler=new laya.utils.Handler(this,onChange);//设置 progressBar 的value值改变时执行的处理器。 *Laya.stage.addChild(progressBar);//将 progressBar 添加到显示列表。 *Laya.timer.once(3000,this,changeValue);//设定 3000ms(毫秒)后,执行函数changeValue。 *} *function changeValue() *{ *console.log("改变进度条的进度值。"); *progressBar.value=0.6; *} *function onChange(value) *{ *console.log("进度发生改变: value=" ,value); *} *@example *import ProgressBar=laya.ui.ProgressBar; *import Handler=laya.utils.Handler; *class ProgressBar_Example { *private progressBar:ProgressBar; *public ProgressBar_Example(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/progress.png","resource/ui/progress$bar.png"],Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *this.progressBar=new ProgressBar("resource/ui/progress.png");//创建一个 ProgressBar 类的实例对象 progressBar 。 *this.progressBar.x=100;//设置 progressBar 对象的属性 x 的值,用于控制 progressBar 对象的显示位置。 *this.progressBar.y=100;//设置 progressBar 对象的属性 y 的值,用于控制 progressBar 对象的显示位置。 *this.progressBar.value=0.3;//设置 progressBar 的进度值。 *this.progressBar.width=200;//设置 progressBar 的宽度。 *this.progressBar.height=50;//设置 progressBar 的高度。 *this.progressBar.sizeGrid="5,10,5,10";//设置 progressBar 的网格信息。 *this.progressBar.changeHandler=new Handler(this,this.onChange);//设置 progressBar 的value值改变时执行的处理器。 *Laya.stage.addChild(this.progressBar);//将 progressBar 添加到显示列表。 *Laya.timer.once(3000,this,this.changeValue);//设定 3000ms(毫秒)后,执行函数changeValue。 *} *private changeValue():void { *console.log("改变进度条的进度值。"); *this.progressBar.value=0.6; *} *private onChange(value:number):void { *console.log("进度发生改变: value=",value); *} *} */ //class laya.ui.ProgressBar extends laya.ui.Component var ProgressBar=(function(_super){ function ProgressBar(skin){ /** *当 ProgressBar 实例的 value 属性发生变化时的函数处理器。 *

    默认返回参数value 属性(进度值)。

    */ this.changeHandler=null; /**@private */ this._bg=null; /**@private */ this._bar=null; /**@private */ this._skin=null; /**@private */ this._value=0.5; ProgressBar.__super.call(this); this.skin=skin; } __class(ProgressBar,'laya.ui.ProgressBar',_super); var __proto=ProgressBar.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._bg && this._bg.destroy(destroyChild); this._bar && this._bar.destroy(destroyChild); this._bg=this._bar=null; this.changeHandler=null; } /**@inheritDoc */ __proto.createChildren=function(){ this.addChild(this._bg=new Image()); this.addChild(this._bar=new Image()); this._bar._bitmap.autoCacheCmd=false; } /** *@private *更改进度值的显示。 */ __proto.changeValue=function(){ if (this.sizeGrid){ var grid=this.sizeGrid.split(","); var left=Number(grid[3]); var right=Number(grid[1]); var max=this.width-left-right; var sw=max *this._value; this._bar.width=left+right+sw; this._bar.visible=this._bar.width > left+right; }else { this._bar.width=this.width *this._value; } } /**@inheritDoc */ __getset(0,__proto,'measureHeight',function(){ return this._bg.height; }); /** *@copy laya.ui.Image#skin */ __getset(0,__proto,'skin',function(){ return this._skin; },function(value){ if (this._skin !=value){ this._skin=value; this._bg.skin=this._skin; this._bar.skin=this._skin.replace(".png","$bar.png"); this.callLater(this.changeValue); } }); /**@inheritDoc */ __getset(0,__proto,'measureWidth',function(){ return this._bg.width; }); /**@inheritDoc */ __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Component,this,'height',value); this._bg.height=this._height; this._bar.height=this._height; }); /** *获取进度条对象。 */ __getset(0,__proto,'bar',function(){ return this._bar; }); /** *当前的进度量。 *

    取值:介于0和1之间。

    */ __getset(0,__proto,'value',function(){ return this._value; },function(num){ if (this._value !=num){ num=num > 1 ? 1 :num < 0 ? 0 :num; this._value=num; this.callLater(this.changeValue); this.event(/*laya.events.Event.CHANGE*/"change"); this.changeHandler && this.changeHandler.runWith(num); } }); /** *获取背景条对象。 */ __getset(0,__proto,'bg',function(){ return this._bg; }); /** *

    当前 ProgressBar 实例的进度条背景位图( Image 实例)的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    *@see laya.ui.AutoBitmap.sizeGrid */ __getset(0,__proto,'sizeGrid',function(){ return this._bg.sizeGrid; },function(value){ this._bg.sizeGrid=this._bar.sizeGrid=value; }); /**@inheritDoc */ __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(Component,this,'width',value); this._bg.width=this._width; this.callLater(this.changeValue); }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if ((typeof value=='number')|| (typeof value=='string'))this.value=Number(value); else Laya.superSet(Component,this,'dataSource',value); }); return ProgressBar; })(Component) /**鼠标提示管理类*/ //class laya.ui.TipManager extends laya.ui.Component var TipManager=(function(_super){ function TipManager(){ this._tipBox=null; this._tipText=null; this._defaultTipHandler=null; TipManager.__super.call(this); this._tipBox=new Component(); this._tipBox.addChild(this._tipText=new Text()); this._tipText.x=this._tipText.y=5; this._tipText.color=TipManager.tipTextColor; this._defaultTipHandler=this._showDefaultTip; Laya.stage.on(/*laya.ui.UIEvent.SHOW_TIP*/"showtip",this,this._onStageShowTip); Laya.stage.on(/*laya.ui.UIEvent.HIDE_TIP*/"hidetip",this,this._onStageHideTip); this.zOrder=1100 } __class(TipManager,'laya.ui.TipManager',_super); var __proto=TipManager.prototype; /** *@private */ __proto._onStageHideTip=function(e){ Laya.timer.clear(this,this._showTip); this.closeAll(); this.removeSelf(); } /** *@private */ __proto._onStageShowTip=function(data){ Laya.timer.once(TipManager.tipDelay,this,this._showTip,[data],true); } /** *@private */ __proto._showTip=function(tip){ if ((typeof tip=='string')){ var text=String(tip); if (Boolean(text)){ this._defaultTipHandler(text); } }else if ((tip instanceof laya.utils.Handler )){ (tip).run(); }else if ((typeof tip=='function')){ (tip).apply(); } if (true){ Laya.stage.on(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this._onStageMouseMove); Laya.stage.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this._onStageMouseDown); } this._onStageMouseMove(null); } /** *@private */ __proto._onStageMouseDown=function(e){ this.closeAll(); } /** *@private */ __proto._onStageMouseMove=function(e){ this._showToStage(this,TipManager.offsetX,TipManager.offsetY); } /** *@private */ __proto._showToStage=function(dis,offX,offY){ (offX===void 0)&& (offX=0); (offY===void 0)&& (offY=0); var rec=dis.getBounds(); dis.x=Laya.stage.mouseX+offX; dis.y=Laya.stage.mouseY+offY; if (dis.x+rec.width > Laya.stage.width){ dis.x-=rec.width+offX; } if (dis.y+rec.height > Laya.stage.height){ dis.y-=rec.height+offY; } } /**关闭所有鼠标提示*/ __proto.closeAll=function(){ Laya.timer.clear(this,this._showTip); Laya.stage.off(/*laya.events.Event.MOUSE_MOVE*/"mousemove",this,this._onStageMouseMove); Laya.stage.off(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this._onStageMouseDown); this.removeChildren(); } /** *显示显示对象类型的tip */ __proto.showDislayTip=function(tip){ this.addChild(tip); this._showToStage(this); Laya._currentStage.addChild(this); } /** *@private */ __proto._showDefaultTip=function(text){ this._tipText.text=text; var g=this._tipBox.graphics; g.clear(); g.drawRect(0,0,this._tipText.width+10,this._tipText.height+10,TipManager.tipBackColor); this.addChild(this._tipBox); this._showToStage(this); Laya._currentStage.addChild(this); } /**默认鼠标提示函数*/ __getset(0,__proto,'defaultTipHandler',function(){ return this._defaultTipHandler; },function(value){ this._defaultTipHandler=value; }); TipManager.offsetX=10; TipManager.offsetY=15; TipManager.tipTextColor="#ffffff"; TipManager.tipBackColor="#111111"; TipManager.tipDelay=200; return TipManager; })(Component) /** *广告插件 *@author 小松 *@date-2018-09-19 */ //class laya.ui.AdvImage extends laya.ui.Image var AdvImage=(function(_super){ function AdvImage(skin){ /**广告列表数据**/ this.advsListArr=[]; /**资源列表请求地址**/ this.resUrl="https://unioncdn.layabox.com/config/iconlist.json"; /**广告列表信息**/ this._data=[]; /**每6分钟重新请求一次新广告列表**/ this._resquestTime=360000; /**微信跳转appid**/ this._appid=null; /**二维码图片地址**/ this._appCodeImgStr=null; /**播放索引**/ this._playIndex=0; /**轮播间隔时间**/ this._lunboTime=5000; AdvImage.__super.call(this); this._http=new Browser.window.XMLHttpRequest(); this.skin=skin; this.init(); this.size(120,120); } __class(AdvImage,'laya.ui.AdvImage',_super); var __proto=AdvImage.prototype; __proto.init=function(){ if(Browser.onMiniGame && this.isSupportJump){ Laya.timer.loop(this._resquestTime,this,this.onGetAdvsListData); this.onGetAdvsListData(); this.initEvent(); }else{ this.visible=false; } } __proto.initEvent=function(){ this.on(/*laya.events.Event.CLICK*/"click",this,this.onAdvsImgClick); } __proto.onAdvsImgClick=function(){ var currentJumpUrl=this.getCurrentAppidObj(); if(currentJumpUrl) this.jumptoGame(); } __proto.revertAdvsData=function(){ if(this.advsListArr[this._playIndex]){ this.visible=true; this.skin=this.advsListArr[this._playIndex]; } } /** *跳转游戏 *@param callBack Function 回调参数说明:type 0 跳转成功;1跳转失败;2跳转接口调用成功 */ __proto.jumptoGame=function(){ var _$this=this; if(!Browser.onMiniGame) return; if(this.isSupportJump){ /*__JS__ */wx.navigateToMiniProgram({ appId:this._appid, path:"", extraData:"", envVersion:"release", success:function success (){ console.log("-------------跳转成功--------------"); }, fail:function fail (){ console.log("-------------跳转失败--------------"); }, complete:function complete (){ console.log("-------------跳转接口调用成功--------------"); _$this.updateAdvsInfo(); }.bind(this) }); } } __proto.updateAdvsInfo=function(){ this.visible=false; this.onLunbo(); Laya.timer.loop(this._lunboTime,this,this.onLunbo); } __proto.onLunbo=function(){ if(this._playIndex >=this.advsListArr.length-1) this._playIndex=0; else this._playIndex+=1; this.visible=true; this.revertAdvsData(); } /**获取轮播数据**/ __proto.getCurrentAppidObj=function(){ return this.advsListArr[this._playIndex]; } /** *获取广告列表数据信息 */ __proto.onGetAdvsListData=function(){ var _this=this; var random=this.randRange(10000,1000000); var url=this.resUrl+"?"+random; this._http.open("get",url,true); this._http.setRequestHeader("Content-Type","application/x-www-form-urlencoded") this._http.responseType="text"; this._http.onerror=function (e){ _this._onError(e); } this._http.onload=function (e){ _this._onLoad(e); } this._http.send(null); } /** *生成指定范围的随机数 *@param minNum 最小值 *@param maxNum 最大值 */ __proto.randRange=function(minNum,maxNum){ return (Math.floor(Math.random()*(maxNum-minNum+1))+minNum); } /** *@private *请求出错侦的听处理函数。 *@param e 事件对象。 */ __proto._onError=function(e){ this.error("Request failed Status:"+this._http.status+" text:"+this._http.statusText); } /** *@private *请求消息返回的侦听处理函数。 *@param e 事件对象。 */ __proto._onLoad=function(e){ var http=this._http; var status=http.status!==undefined ? http.status :200; if (status===200 || status===204 || status===0){ this.complete(); }else { this.error("["+http.status+"]"+http.statusText+":"+http.responseURL); } } /** *@private *请求错误的处理函数。 *@param message 错误信息。 */ __proto.error=function(message){ this.event(/*laya.events.Event.ERROR*/"error",message); } /** *@private *请求成功完成的处理函数。 */ __proto.complete=function(){ var flag=true; try { this._data=this._http.response || this._http.responseText; this._data=JSON.parse(this._data); this.advsListArr=this._data.list; this._appid=this._data.appid; this._appCodeImgStr=this._data.qrcode; this.updateAdvsInfo(); this.revertAdvsData(); }catch (e){ flag=false; this.error(e.message); } } /** *@private *清除当前请求。 */ __proto.clear=function(){ var http=this._http; http.onerror=http.onabort=http.onprogress=http.onload=null; } __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,true); Laya.timer.clear(this,this.onLunbo); Laya.timer.clear(this,this.onGetAdvsListData); this.clear(); } /**当前小游戏环境是否支持游戏跳转功能**/ __getset(0,__proto,'isSupportJump',function(){ if(Browser.onMiniGame){ var isSupperJump=(typeof /*__JS__ */wx.navigateToMiniProgram=='function'); return isSupperJump; } return false; }); return AdvImage; })(Image) /** *View 是一个视图类。 *@internal

    View

    */ //class laya.ui.View extends laya.ui.Box var View=(function(_super){ var DataWatcher; function View(){ /**@private */ this._idMap=null; /**@private */ this._aniList=null; /**@private */ this._watchMap={}; View.__super.call(this); } __class(View,'laya.ui.View',_super); var __proto=View.prototype; /** *@private *通过视图数据创建视图。 *@param uiView 视图数据信息。 */ __proto.createView=function(uiView){ if (uiView.animations && !this._idMap)this._idMap={}; View.createComp(uiView,this,this); if (uiView.animations){ var anilist=[]; var animations=uiView.animations; var i=0,len=animations.length; var tAni; var tAniO; for (i=0;i < len;i++){ tAni=new FrameAnimation(); tAniO=animations[i]; tAni._setUp(this._idMap,tAniO); this[tAniO.name]=tAni; tAni._setControlNode(this); switch (tAniO.action){ case 1: tAni.play(0,false); break ; case 2: tAni.play(0,true); break ; } anilist.push(tAni); } this._aniList=anilist; } if (this._width > 0 && uiView.props.hitTestPrior==null && !this.mouseThrough)this.hitTestPrior=true; } __proto.onEvent=function(type,event){} /** *@private *装载UI视图。用于加载模式。 *@param path UI资源地址。 */ __proto.loadUI=function(path){ var uiView=View.uiMap[path]; uiView && this.createView(uiView); } /** *

    销毁此对象。

    *@param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this._aniList)this._aniList.length=0; this._idMap=null; this._aniList=null; this._watchMap=null; laya.ui.Component.prototype.destroy.call(this,destroyChild); } /**@private */ __proto.changeData=function(key){ var arr=this._watchMap[key]; if (!arr)return; console.log("change",key); for (var i=0,n=arr.length;i < n;i++){ var watcher=arr[i]; watcher.exe(this); } } View._regs=function(){ for (var key in View.uiClassMap){ ClassUtils.regClass(key,View.uiClassMap[key]); } } View.createComp=function(uiView,comp,view,dataMap){ comp=comp || View.getCompInstance(uiView); if (!comp){ console.warn("can not create:"+uiView.type); return null; }; var child=uiView.child; if (child){ var isList=(comp instanceof laya.ui.List ); for (var i=0,n=child.length;i < n;i++){ var node=child[i]; if (comp.hasOwnProperty("itemRender")&& (node.props.name=="render" || node.props.renderType==="render")){ (comp).itemRender=node; }else if (node.type=="Graphic"){ ClassUtils.addGraphicsToSprite(node,comp); }else if (ClassUtils.isDrawType(node.type)){ ClassUtils.addGraphicToSprite(node,comp,true); }else { if (isList){ var arr=[]; var tChild=View.createComp(node,null,view,arr); if (arr.length)tChild["_$bindData"]=arr; }else { tChild=View.createComp(node,null,view,dataMap); } if (node.type=="Script"){ if ("owner" in tChild){ tChild["owner"]=comp; }else if ("target" in tChild){ tChild["target"]=comp; } }else if (node.props.renderType=="mask" || node.props.name=="mask"){ comp.mask=tChild; }else {( tChild instanceof laya.display.Sprite )&& comp.addChild(tChild); } } } }; var props=uiView.props; for (var prop in props){ var value=props[prop]; if (View.eventDic[prop]){ if (value&&view){ (comp).on(prop,view,view.onEvent,[value]); } }else View.setCompValue(comp,prop,value,view,dataMap); } if (Laya.__typeof(comp,'laya.ui.IItem'))(comp).initItems(); if (uiView.compId && view && view._idMap){ view._idMap[uiView.compId]=comp; } return comp; } View.setCompValue=function(comp,prop,value,view,dataMap){ if ((typeof value=='string')&& value.indexOf("${")>-1){ View._sheet || (View._sheet=ClassUtils.getClass("laya.data.Table")); if (!View._sheet){ console.warn("Can not find class Sheet"); return; } if (dataMap){ dataMap.push(comp,prop,value); }else if (view){ if (value.indexOf("].")==-1){ value=value.replace(".","[0]."); }; var watcher=new DataWatcher(comp,prop,value); watcher.exe(view); var one,temp; var str=value.replace(/\[.*?\]\./g,"."); while ((one=View._parseWatchData.exec(str))!=null){ var key1=one[1]; while ((temp=View._parseKeyWord.exec(key1))!=null){ var key2=temp[0]; var arr=(view._watchMap[key2] || (view._watchMap[key2]=[])); arr.push(watcher); View._sheet.I.notifer.on(key2,view,view.changeData,[key2]); } arr=(view._watchMap[key1] || (view._watchMap[key1]=[])); arr.push(watcher); View._sheet.I.notifer.on(key1,view,view.changeData,[key1]); } } return; } if (prop==="var" && view){ view[value]=comp; }else if (prop=="onClick"){ var fun=Laya._runScript("(function(){"+value+"})"); comp.on(/*laya.events.Event.CLICK*/"click",view,fun); }else { comp[prop]=(value==="true" ? true :(value==="false" ? false :value)); } } View.getCompInstance=function(json){ var runtime=json.props ? json.props.runtime :null; var compClass; compClass=runtime ? (View.viewClassMap[runtime] || View.uiClassMap[runtime]|| Laya["__classmap"][runtime]):View.uiClassMap[json.type]; if (json.props && json.props.hasOwnProperty("renderType")&& json.props["renderType"]=="instance")return compClass["instance"]; return compClass ? new compClass():null; } View.regComponent=function(key,compClass){ View.uiClassMap[key]=compClass; ClassUtils.regClass(key,compClass); } View.regViewRuntime=function(key,compClass){ View.viewClassMap[key]=compClass; } View.uiMap={}; View.viewClassMap={}; View._sheet=null; __static(View, ['uiClassMap',function(){return this.uiClassMap={"ViewStack":ViewStack,"LinkButton":Button,"TextArea":TextArea,"ColorPicker":ColorPicker,"Box":Box,"Button":Button,"CheckBox":CheckBox,"Clip":Clip,"ComboBox":ComboBox,"Component":Component,"HScrollBar":HScrollBar,"HSlider":HSlider,"Image":Image,"Label":Label,"List":List,"Panel":Panel,"ProgressBar":ProgressBar,"Radio":Radio,"RadioGroup":RadioGroup,"ScrollBar":ScrollBar,"Slider":Slider,"Tab":Tab,"TextInput":TextInput,"View":View,"VScrollBar":VScrollBar,"VSlider":VSlider,"Tree":Tree,"HBox":HBox,"VBox":VBox,"Sprite":Sprite,"Animation":Animation,"Text":Text,"FontClip":FontClip};},'eventDic',function(){return this.eventDic={"mousedown":true,"mouseup":true,"mousemove":true,"mouseover":true,"mouseout":true,"click":true,"doubleclick":true,"rightmousedown":true,"rightmouseup":true,"rightclick":true };},'_parseWatchData',function(){return this._parseWatchData=/\${(.*?)}/g;},'_parseKeyWord',function(){return this._parseKeyWord=/[a-zA-Z_][a-zA-Z0-9_]*(?:(?:\.[a-zA-Z_][a-zA-Z0-9_]*)+)/g;} ]); View.__init$=function(){ View._regs() //class DataWatcher DataWatcher=(function(){ function DataWatcher(comp,prop,value){ this.comp=null; this.prop=null; this.value=null; this.comp=comp; this.prop=prop; this.value=value; } __class(DataWatcher,''); var __proto=DataWatcher.prototype; __proto.exe=function(view){ var fun=UIUtils.getBindFun(this.value); this.comp[this.prop]=fun.call(this,view); } return DataWatcher; })() } return View; })(Box) /** *CheckBox 组件显示一个小方框,该方框内可以有选中标记。 *CheckBox 组件还可以显示可选的文本标签,默认该标签位于 CheckBox 右侧。 *

    CheckBox 使用 dataSource赋值时的的默认属性是:selected

    * *@example 以下示例代码,创建了一个 CheckBox 实例。 *package *{ *import laya.ui.CheckBox; *import laya.utils.Handler; *public class CheckBox_Example *{ *public function CheckBox_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/check.png",Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *trace("资源加载完成!"); *var checkBox:CheckBox=new CheckBox("resource/ui/check.png","这个是一个CheckBox组件。");//创建一个 CheckBox 类的实例对象 checkBox ,传入它的皮肤skin和标签label。 *checkBox.x=100;//设置 checkBox 对象的属性 x 的值,用于控制 checkBox 对象的显示位置。 *checkBox.y=100;//设置 checkBox 对象的属性 y 的值,用于控制 checkBox 对象的显示位置。 *checkBox.clickHandler=new Handler(this,onClick,[checkBox]);//设置 checkBox 的点击事件处理器。 *Laya.stage.addChild(checkBox);//将此 checkBox 对象添加到显示列表。 *} *private function onClick(checkBox:CheckBox):void *{ *trace("输出选中状态: checkBox.selected = "+checkBox.selected); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *Laya.loader.load("resource/ui/check.png",laya.utils.Handler.create(this,loadComplete));//加载资源 *function loadComplete() *{ *console.log("资源加载完成!"); *var checkBox:laya.ui.CheckBox=new laya.ui.CheckBox("resource/ui/check.png","这个是一个CheckBox组件。");//创建一个 CheckBox 类的类的实例对象 checkBox ,传入它的皮肤skin和标签label。 *checkBox.x=100;//设置 checkBox 对象的属性 x 的值,用于控制 checkBox 对象的显示位置。 *checkBox.y=100;//设置 checkBox 对象的属性 y 的值,用于控制 checkBox 对象的显示位置。 *checkBox.clickHandler=new laya.utils.Handler(this,this.onClick,[checkBox],false);//设置 checkBox 的点击事件处理器。 *Laya.stage.addChild(checkBox);//将此 checkBox 对象添加到显示列表。 *} *function onClick(checkBox) *{ *console.log("checkBox.selected = ",checkBox.selected); *} *@example *import CheckBox=laya.ui.CheckBox; *import Handler=laya.utils.Handler; *class CheckBox_Example{ *constructor() *{ *Laya.init(640,800); *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/check.png",Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete() *{ *var checkBox:CheckBox=new CheckBox("resource/ui/check.png","这个是一个CheckBox组件。");//创建一个 CheckBox 类的实例对象 checkBox ,传入它的皮肤skin和标签label。 *checkBox.x=100;//设置 checkBox 对象的属性 x 的值,用于控制 checkBox 对象的显示位置。 *checkBox.y=100;//设置 checkBox 对象的属性 y 的值,用于控制 checkBox 对象的显示位置。 *checkBox.clickHandler=new Handler(this,this.onClick,[checkBox]);//设置 checkBox 的点击事件处理器。 *Laya.stage.addChild(checkBox);//将此 checkBox 对象添加到显示列表。 *} *private onClick(checkBox:CheckBox):void *{ *console.log("输出选中状态: checkBox.selected = "+checkBox.selected); *} *} */ //class laya.ui.CheckBox extends laya.ui.Button var CheckBox=(function(_super){ /** *创建一个新的 CheckBox 组件实例。 *@param skin 皮肤资源地址。 *@param label 文本标签的内容。 */ function CheckBox(skin,label){ (label===void 0)&& (label=""); CheckBox.__super.call(this,skin,label); } __class(CheckBox,'laya.ui.CheckBox',_super); var __proto=CheckBox.prototype; /**@inheritDoc */ __proto.preinitialize=function(){ laya.ui.Component.prototype.preinitialize.call(this); this.toggle=true; this._autoSize=false; } /**@inheritDoc */ __proto.initialize=function(){ _super.prototype.initialize.call(this); this.createText(); this._text.align="left"; this._text.valign="top"; this._text.width=0; } /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if ((typeof value=='boolean'))this.selected=value; else if ((typeof value=='string'))this.selected=value==="true"; else Laya.superSet(Button,this,'dataSource',value); }); return CheckBox; })(Button) /** *LayoutBox 是一个布局容器类。 */ //class laya.ui.LayoutBox extends laya.ui.Box var LayoutBox=(function(_super){ function LayoutBox(){ /**@private */ this._space=0; /**@private */ this._align="none"; /**@private */ this._itemChanged=false; LayoutBox.__super.call(this); } __class(LayoutBox,'laya.ui.LayoutBox',_super); var __proto=LayoutBox.prototype; /**@inheritDoc */ __proto.addChild=function(child){ child.on(/*laya.events.Event.RESIZE*/"resize",this,this.onResize); this._setItemChanged(); return laya.display.Node.prototype.addChild.call(this,child); } __proto.onResize=function(e){ this._setItemChanged(); } /**@inheritDoc */ __proto.addChildAt=function(child,index){ child.on(/*laya.events.Event.RESIZE*/"resize",this,this.onResize); this._setItemChanged(); return laya.display.Node.prototype.addChildAt.call(this,child,index); } /**@inheritDoc */ __proto.removeChildAt=function(index){ this.getChildAt(index).off(/*laya.events.Event.RESIZE*/"resize",this,this.onResize); this._setItemChanged(); return laya.display.Node.prototype.removeChildAt.call(this,index); } /**刷新。*/ __proto.refresh=function(){ this._setItemChanged(); } /** *改变子对象的布局。 */ __proto.changeItems=function(){ this._itemChanged=false; } /** *排序项目列表。可通过重写改变默认排序规则。 *@param items 项目列表。 */ __proto.sortItem=function(items){ if (items)items.sort(function(a,b){return a.y-b.y;}); } __proto._setItemChanged=function(){ if (!this._itemChanged){ this._itemChanged=true; this.callLater(this.changeItems); } } /**子对象的间隔。*/ __getset(0,__proto,'space',function(){ return this._space; },function(value){ this._space=value; this._setItemChanged(); }); /**子对象对齐方式。*/ __getset(0,__proto,'align',function(){ return this._align; },function(value){ this._align=value; this._setItemChanged(); }); return LayoutBox; })(Box) /** *字体切片,简化版的位图字体,只需设置一个切片图片和文字内容即可使用,效果同位图字体 *使用方式:设置位图字体皮肤skin,设置皮肤对应的字体内容sheet(如果多行,可以使用空格换行),示例: *fontClip.skin="font1.png";//设置皮肤 *fontClip.sheet="abc123 456";//设置皮肤对应的内容,空格换行。此皮肤为2行5列(显示时skin会被等分为2行5列),第一行对应的文字为"abc123",第二行为"456" *fontClip.value="a1326";//显示"a1326"文字 */ //class laya.ui.FontClip extends laya.ui.Clip var FontClip=(function(_super){ function FontClip(skin,sheet){ /**数值*/ this._valueArr=null; /**文字内容数组**/ this._indexMap=null; /**位图字体内容**/ this._sheet=null; /**@private */ this._direction="horizontal"; /**X方向间隙*/ this._spaceX=0; /**Y方向间隙*/ this._spaceY=0; /**@private 水平对齐方式*/ this._align="left"; /**@private 显示文字宽*/ this._wordsW=0; /**@private 显示文字高*/ this._wordsH=0; FontClip.__super.call(this); if (skin)this.skin=skin; if (sheet)this.sheet=sheet; } __class(FontClip,'laya.ui.FontClip',_super); var __proto=FontClip.prototype; __proto.createChildren=function(){ this._bitmap=new AutoBitmap(); this.on(/*laya.events.Event.LOADED*/"loaded",this,this._onClipLoaded); } /** *资源加载完毕 */ __proto._onClipLoaded=function(){ this.callLater(this.changeValue); } /**渲染数值*/ __proto.changeValue=function(){ if (!this._sources)return; if (!this._valueArr)return; this.graphics.clear(true); var texture; texture=this._sources[0]; if (!texture)return; var isHorizontal=(this._direction==="horizontal"); if (isHorizontal){ this._wordsW=this._valueArr.length *(texture.sourceWidth+this.spaceX); this._wordsH=texture.sourceHeight; }else{ this._wordsW=texture.sourceWidth; this._wordsH=(texture.sourceHeight+this.spaceY)*this._valueArr.length; }; var dX=0; if (this._width){ switch(this._align){ case "center": dX=0.5 *(this._width-this._wordsW); break ; case "right": dX=this._width-this._wordsW; break ; default : dX=0; } } for (var i=0,sz=this._valueArr.length;i < sz;i++){ var index=this._indexMap[this._valueArr.charAt(i)]; if (!this.sources[index])continue ; texture=this.sources[index]; if (isHorizontal)this.graphics.drawTexture(texture,dX+i *(texture.sourceWidth+this.spaceX),0,texture.sourceWidth,texture.sourceHeight); else this.graphics.drawTexture(texture,0+dX,i *(texture.sourceHeight+this.spaceY),texture.sourceWidth,texture.sourceHeight); } if (!this._width){ this.resetLayoutX(); this.callLater(this.changeSize); } if (!this._height){ this.resetLayoutY(); this.callLater(this.changeSize); } } __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); this._valueArr=null; this._indexMap=null; this.graphics.clear(true); this.removeSelf(); this.off(/*laya.events.Event.LOADED*/"loaded",this,this._onClipLoaded); _super.prototype.destroy.call(this,destroyChild); } /** *设置位图字体内容,空格代表换行。比如"abc123 456",代表第一行对应的文字为"abc123",第二行为"456" */ __getset(0,__proto,'sheet',function(){ return this._sheet; },function(value){ value+=""; this._sheet=value; var arr=value.split(" "); this._clipX=String(arr[0]).length; this.clipY=arr.length; this._indexMap={}; for (var i=0;i < this._clipY;i++){ var line=arr[i].split(""); for (var j=0,n=line.length;j < n;j++){ this._indexMap[line[j]]=i *this._clipX+j; } } }); __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Clip,this,'height',value); this.callLater(this.changeValue); }); /** *布局方向。 *

    默认值为"horizontal"。

    *

    取值: *

  • "horizontal":表示水平布局。
  • *
  • "vertical":表示垂直布局。
  • *

    */ __getset(0,__proto,'direction',function(){ return this._direction; },function(value){ this._direction=value; this.callLater(this.changeValue); }); /** *设置位图字体的显示内容 */ __getset(0,__proto,'value',function(){ if (!this._valueArr)return ""; return this._valueArr; },function(value){ value+=""; this._valueArr=value; this.callLater(this.changeValue); }); __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(Clip,this,'width',value); this.callLater(this.changeValue); }); /**X方向文字间隙*/ __getset(0,__proto,'spaceX',function(){ return this._spaceX; },function(value){ this._spaceX=value; if (this._direction==="horizontal")this.callLater(this.changeValue); }); /**Y方向文字间隙*/ __getset(0,__proto,'spaceY',function(){ return this._spaceY; },function(value){ this._spaceY=value; if (!(this._direction==="horizontal"))this.callLater(this.changeValue); }); /**水平对齐方式*/ __getset(0,__proto,'align',function(){ return this._align; },function(v){ this._align=v; this.callLater(this.changeValue); }); __getset(0,__proto,'measureWidth',function(){ return this._wordsW; }); __getset(0,__proto,'measureHeight',function(){ return this._wordsH; }); return FontClip; })(Clip) /** *List 控件可显示项目列表。默认为垂直方向列表。可通过UI编辑器自定义列表。 * *@example 以下示例代码,创建了一个 List 实例。 *package *{ *import laya.ui.List; *import laya.utils.Handler; *public class List_Example *{ *public function List_Example() *{ *Laya.init(640,800,"false");//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/vscroll.png","resource/ui/vscroll$bar.png","resource/ui/vscroll$down.png","resource/ui/vscroll$up.png"],Handler.create(this,onLoadComplete)); *} *private function onLoadComplete():void *{ *var arr:Array=[];//创建一个数组,用于存贮列表的数据信息。 *for (var i:int=0;i <20;i++) *{ *arr.push({label:"item"+i}); *} *var list:List=new List();//创建一个 List 类的实例对象 list 。 *list.itemRender=Item;//设置 list 的单元格渲染器。 *list.repeatX=1;//设置 list 的水平方向单元格数量。 *list.repeatY=10;//设置 list 的垂直方向单元格数量。 *list.vScrollBarSkin="resource/ui/vscroll.png";//设置 list 的垂直方向滚动条皮肤。 *list.array=arr;//设置 list 的列表数据源。 *list.pos(100,100);//设置 list 的位置。 *list.selectEnable=true;//设置 list 可选。 *list.selectHandler=new Handler(this,onSelect);//设置 list 改变选择项执行的处理器。 *Laya.stage.addChild(list);//将 list 添加到显示列表。 *} *private function onSelect(index:int):void *{ *trace("当前选择的项目索引: index= ",index); *} *} *} *import laya.ui.Box; *import laya.ui.Label; *class Item extends Box *{ *public function Item() *{ *graphics.drawRect(0,0,100,20,null,"#ff0000"); *var label:Label=new Label(); *label.text="100000"; *label.name="label";//设置 label 的name属性值。 *label.size(100,20); *addChild(label); *} *} *@example *(function (_super){ *function Item(){ *Item.__super.call(this);//初始化父类 *this.graphics.drawRect(0,0,100,20,"#ff0000"); *var label=new laya.ui.Label();//创建一个 Label 类的实例对象 label 。 *label.text="100000";//设置 label 的文本内容。 *label.name="label";//设置 label 的name属性值。 *label.size(100,20);//设置 label 的宽度、高度。 *this.addChild(label);//将 label 添加到显示列表。 *}; *Laya.class(Item,"mypackage.listExample.Item",_super);//注册类 Item 。 *})(laya.ui.Box); *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *var res=["resource/ui/vscroll.png","resource/ui/vscroll$bar.png","resource/ui/vscroll$down.png","resource/ui/vscroll$up.png"]; *Laya.loader.load(res,new laya.utils.Handler(this,onLoadComplete));//加载资源。 *function onLoadComplete(){ *var arr=[];//创建一个数组,用于存贮列表的数据信息。 *for (var i=0;i <20;i++){ *arr.push({label:"item"+i}); *} *var list=new laya.ui.List();//创建一个 List 类的实例对象 list 。 *list.itemRender=mypackage.listExample.Item;//设置 list 的单元格渲染器。 *list.repeatX=1;//设置 list 的水平方向单元格数量。 *list.repeatY=10;//设置 list 的垂直方向单元格数量。 *list.vScrollBarSkin="resource/ui/vscroll.png";//设置 list 的垂直方向滚动条皮肤。 *list.array=arr;//设置 list 的列表数据源。 *list.pos(100,100);//设置 list 的位置。 *list.selectEnable=true;//设置 list 可选。 *list.selectHandler=new laya.utils.Handler(this,onSelect);//设置 list 改变选择项执行的处理器。 *Laya.stage.addChild(list);//将 list 添加到显示列表。 *} *function onSelect(index) *{ *console.log("当前选择的项目索引: index= ",index); *} * *@example *import List=laya.ui.List; *import Handler=laya.utils.Handler; *public class List_Example { *public List_Example(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/vscroll.png","resource/ui/vscroll$bar.png","resource/ui/vscroll$down.png","resource/ui/vscroll$up.png"],Handler.create(this,this.onLoadComplete)); *} *private onLoadComplete():void { *var arr=[];//创建一个数组,用于存贮列表的数据信息。 *for (var i:number=0;i <20;i++) *{ *arr.push({label:"item"+i }); *} *var list:List=new List();//创建一个 List 类的实例对象 list 。 *list.itemRender=Item;//设置 list 的单元格渲染器。 *list.repeatX=1;//设置 list 的水平方向单元格数量。 *list.repeatY=10;//设置 list 的垂直方向单元格数量。 *list.vScrollBarSkin="resource/ui/vscroll.png";//设置 list 的垂直方向滚动条皮肤。 *list.array=arr;//设置 list 的列表数据源。 *list.pos(100,100);//设置 list 的位置。 *list.selectEnable=true;//设置 list 可选。 *list.selectHandler=new Handler(this,this.onSelect);//设置 list 改变选择项执行的处理器。 *Laya.stage.addChild(list);//将 list 添加到显示列表。 *} *private onSelect(index:number):void { *console.log("当前选择的项目索引: index= ",index); *} *} *import Box=laya.ui.Box; *import Label=laya.ui.Label; *class Item extends Box { *constructor(){ *this.graphics.drawRect(0,0,100,20,null,"#ff0000"); *var label:Label=new Label(); *label.text="100000"; *label.name="label";//设置 label 的name属性值。 *label.size(100,20); *this.addChild(label); *} *} */ //class laya.ui.List extends laya.ui.Box var List=(function(_super){ function List(){ /**改变 List 的选择项时执行的处理器,(默认返回参数: 项索引(index:int))。*/ this.selectHandler=null; /**单元格渲染处理器(默认返回参数cell:Box,index:int)。*/ this.renderHandler=null; /**单元格鼠标事件处理器(默认返回参数e:Event,index:int)。*/ this.mouseHandler=null; /**指定是否可以选择,若值为true则可以选择,否则不可以选择。 @default false*/ this.selectEnable=false; /**最大分页数。*/ this.totalPage=0; /**@private */ this._content=null; /**@private */ this._scrollBar=null; /**@private */ this._itemRender=null; /**@private */ this._repeatX=0; /**@private */ this._repeatY=0; /**@private */ this._repeatX2=0; /**@private */ this._repeatY2=0; /**@private */ this._spaceX=0; /**@private */ this._spaceY=0; /**@private */ this._array=null; /**@private */ this._startIndex=0; /**@private */ this._selectedIndex=-1; /**@private */ this._page=0; /**@private */ this._isVertical=true; /**@private */ this._cellSize=20; /**@private */ this._cellOffset=0; /**@private */ this._isMoved=false; /**是否缓存内容,如果数据源较少,并且list内无动画,设置此属性为true能大大提高性能 */ this.cacheContent=false; /**@private */ this._createdLine=0; /**@private */ this._cellChanged=false; this._cells=[]; this._offset=new Point(); List.__super.call(this); } __class(List,'laya.ui.List',_super); var __proto=List.prototype; Laya.imps(__proto,{"laya.ui.IRender":true,"laya.ui.IItem":true}) /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); this._content && this._content.destroy(destroyChild); this._scrollBar && this._scrollBar.destroy(destroyChild); laya.ui.Component.prototype.destroy.call(this,destroyChild); this._content=null; this._scrollBar=null; this._itemRender=null; this._cells=null; this._array=null; this.selectHandler=this.renderHandler=this.mouseHandler=null; } /**@inheritDoc */ __proto.createChildren=function(){ this.addChild(this._content=new Box()); } __proto.onScrollStart=function(){ this._$P.cacheAs || (this._$P.cacheAs=Laya.superGet(Box,this,'cacheAs')); Laya.superSet(Box,this,'cacheAs',"none"); this._scrollBar.once(/*laya.events.Event.END*/"end",this,this.onScrollEnd); } __proto.onScrollEnd=function(){ Laya.superSet(Box,this,'cacheAs',this._$P.cacheAs); } __proto._removePreScrollBar=function(){ var preNode=this.removeChildByName("scrollBar"); if (preNode)preNode.destroy(true); } /** *@private *更改单元格的信息。 *@internal 在此销毁、创建单元格,并设置单元格的位置等属性。相当于此列表内容发送改变时调用此函数。 */ __proto.changeCells=function(){ this._cellChanged=false; if (this._itemRender){ this.scrollBar=this.getChildByName("scrollBar"); var cell=this._getOneCell(); var cellWidth=(cell.width+this._spaceX)|| 1; var cellHeight=(cell.height+this._spaceY)|| 1; if (this._width > 0)this._repeatX2=this._isVertical ? Math.round(this._width / cellWidth):Math.ceil(this._width / cellWidth); if (this._height > 0)this._repeatY2=this._isVertical ? Math.ceil(this._height / cellHeight):Math.round(this._height / cellHeight); var listWidth=this._width ? this._width :(cellWidth *this.repeatX-this._spaceX); var listHeight=this._height ? this._height :(cellHeight *this.repeatY-this._spaceY); this._cellSize=this._isVertical ? cellHeight :cellWidth; this._cellOffset=this._isVertical ? (cellHeight *Math.max(this._repeatY2,this._repeatY)-listHeight-this._spaceY):(cellWidth *Math.max(this._repeatX2,this._repeatX)-listWidth-this._spaceX); if (this._isVertical && this._scrollBar)this._scrollBar.height=listHeight; else if (!this._isVertical && this._scrollBar)this._scrollBar.width=listWidth; this.setContentSize(listWidth,listHeight); var numX=this._isVertical ? this.repeatX :this.repeatY; var numY=(this._isVertical ? this.repeatY :this.repeatX)+(this._scrollBar ? 1 :0); this._createItems(0,numX,numY); this._createdLine=numY; if (this._array){ this.array=this._array; this.runCallLater(this.renderItems); } } } __proto._getOneCell=function(){ if (this._cells.length===0){ var item=this.createItem(); this._offset.setTo(item.x,item.y); if (this.cacheContent)return item; this._cells.push(item); } return this._cells[0]; } __proto._createItems=function(startY,numX,numY){ var box=this._content; var cell=this._getOneCell(); var cellWidth=cell.width+this._spaceX; var cellHeight=cell.height+this._spaceY; if (this.cacheContent){ var cacheBox=new Box(); cacheBox.cacheAsBitmap=true; cacheBox.pos((this._isVertical ? 0 :startY)*cellWidth,(this._isVertical ? startY :0)*cellHeight); this._content.addChild(cacheBox); this._content.optimizeScrollRect=true; box=cacheBox; }else { var arr=[]; for (var i=this._cells.length-1;i >-1;i--){ var item=this._cells[i]; item.removeSelf(); arr.push(item); } this._cells.length=0; } for (var k=startY;k < numY;k++){ for (var l=0;l < numX;l++){ if (arr && arr.length){ cell=arr.pop(); }else { cell=this.createItem(); } cell.x=(this._isVertical ? l :k)*cellWidth-box.x; cell.y=(this._isVertical ? k :l)*cellHeight-box.y; cell.name="item"+(k *numX+l); box.addChild(cell); this.addCell(cell); } } } __proto.createItem=function(){ var arr=[]; if ((typeof this._itemRender=='function')){ var box=new this._itemRender(); }else { box=View.createComp(this._itemRender,null,null,arr) } if (arr.length==0 && box._watchMap){ var watchMap=box._watchMap; for (var name in watchMap){ var a=watchMap[name]; for (var i=0;i < a.length;i++){ var watcher=a[i]; arr.push(watcher.comp,watcher.prop,watcher.value) } } } if (arr.length)box["_$bindData"]=arr; return box; } /** *@private *添加单元格。 *@param cell 需要添加的单元格对象。 */ __proto.addCell=function(cell){ cell.on(/*laya.events.Event.CLICK*/"click",this,this.onCellMouse); cell.on(/*laya.events.Event.RIGHT_CLICK*/"rightclick",this,this.onCellMouse); cell.on(/*laya.events.Event.MOUSE_OVER*/"mouseover",this,this.onCellMouse); cell.on(/*laya.events.Event.MOUSE_OUT*/"mouseout",this,this.onCellMouse); cell.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this.onCellMouse); cell.on(/*laya.events.Event.MOUSE_UP*/"mouseup",this,this.onCellMouse); this._cells.push(cell); } /** *初始化单元格信息。 */ __proto.initItems=function(){ if (!this._itemRender && this.getChildByName("item0")!=null){ this.repeatX=1; var count=0; count=0; for (var i=0;i < 10000;i++){ var cell=this.getChildByName("item"+i); if (cell){ this.addCell(cell); count++; continue ; } break ; } this.repeatY=count; } } /** *设置可视区域大小。 *

    以(0,0,width参数,height参数)组成的矩形区域为可视区域。

    *@param width 可视区域宽度。 *@param height 可视区域高度。 */ __proto.setContentSize=function(width,height){ this._content.width=width; this._content.height=height; if (this._scrollBar || this._offset.x !=0 || this._offset.y !=0){ this._content.scrollRect || (this._content.scrollRect=new Rectangle()); this._content.scrollRect.setTo(-this._offset.x,-this._offset.y,width,height); this._content.scrollRect=this._content.scrollRect; } this.event(/*laya.events.Event.RESIZE*/"resize"); } /** *@private *单元格的鼠标事件侦听处理函数。 */ __proto.onCellMouse=function(e){ if (e.type===/*laya.events.Event.MOUSE_DOWN*/"mousedown")this._isMoved=false; var cell=e.currentTarget; var index=this._startIndex+this._cells.indexOf(cell); if (index < 0)return; if (e.type===/*laya.events.Event.CLICK*/"click" || e.type===/*laya.events.Event.RIGHT_CLICK*/"rightclick"){ if (this.selectEnable && !this._isMoved)this.selectedIndex=index; else this.changeCellState(cell,true,0); }else if ((e.type===/*laya.events.Event.MOUSE_OVER*/"mouseover" || e.type===/*laya.events.Event.MOUSE_OUT*/"mouseout")&& this._selectedIndex!==index){ this.changeCellState(cell,e.type===/*laya.events.Event.MOUSE_OVER*/"mouseover",0); } this.mouseHandler && this.mouseHandler.runWith([e,index]); } /** *@private *改变单元格的可视状态。 *@param cell 单元格对象。 *@param visable 是否显示。 *@param index 单元格的属性 index 值。 */ __proto.changeCellState=function(cell,visable,index){ var selectBox=cell.getChildByName("selectBox"); if (selectBox){ this.selectEnable=true; selectBox.visible=visable; selectBox.index=index; } } /**@inheritDoc */ __proto.changeSize=function(){ laya.ui.Component.prototype.changeSize.call(this); this.setContentSize(this.width,this.height); if (this._scrollBar)this.callLater(this.onScrollBarChange); } /** *@private *滚动条的 Event.CHANGE 事件侦听处理函数。 */ __proto.onScrollBarChange=function(e){ this.runCallLater(this.changeCells); var scrollValue=this._scrollBar.value; var lineX=(this._isVertical ? this.repeatX :this.repeatY); var lineY=(this._isVertical ? this.repeatY :this.repeatX); var scrollLine=Math.floor(scrollValue / this._cellSize); if (!this.cacheContent){ var index=scrollLine *lineX; var num=0; if (index > this._startIndex){ num=index-this._startIndex; var down=true; var toIndex=this._startIndex+lineX *(lineY+1); this._isMoved=true; }else if (index < this._startIndex){ num=this._startIndex-index; down=false; toIndex=this._startIndex-1; this._isMoved=true; } for (var i=0;i < num;i++){ if (down){ var cell=this._cells.shift(); this._cells[this._cells.length]=cell; var cellIndex=toIndex+i; }else { cell=this._cells.pop(); this._cells.unshift(cell); cellIndex=toIndex-i; }; var pos=Math.floor(cellIndex / lineX)*this._cellSize; this._isVertical ? cell.y=pos :cell.x=pos; this.renderItem(cell,cellIndex); } this._startIndex=index; this.changeSelectStatus(); }else { num=(lineY+1); if (this._createdLine-scrollLine < num){ this._createItems(this._createdLine,lineX,this._createdLine+num); this.renderItems(this._createdLine *lineX,0); this._createdLine+=num; } }; var r=this._content.scrollRect; if (this._isVertical){ r.y=scrollValue-this._offset.y; r.x=-this._offset.x; }else { r.y=-this._offset.y; r.x=scrollValue-this._offset.x; } this._content.scrollRect=r; } __proto.posCell=function(cell,cellIndex){ if (!this._scrollBar)return; var lineX=(this._isVertical ? this.repeatX :this.repeatY); var lineY=(this._isVertical ? this.repeatY :this.repeatX); var pos=Math.floor(cellIndex / lineX)*this._cellSize; this._isVertical ? cell.y=pos :cell.x=pos; } /** *@private *改变单元格的选择状态。 */ __proto.changeSelectStatus=function(){ for (var i=0,n=this._cells.length;i < n;i++){ this.changeCellState(this._cells[i],this._selectedIndex===this._startIndex+i,1); } } /** *@private *渲染单元格列表。 */ __proto.renderItems=function(from,to){ (from===void 0)&& (from=0); (to===void 0)&& (to=0); for (var i=from,n=to || this._cells.length;i < n;i++){ this.renderItem(this._cells[i],this._startIndex+i); } this.changeSelectStatus(); } /** *渲染一个单元格。 *@param cell 需要渲染的单元格对象。 *@param index 单元格索引。 */ __proto.renderItem=function(cell,index){ if (this._array && index >=0 && index < this._array.length){ cell.visible=true; if (cell._$bindData){ cell._dataSource=this._array[index]; this._bindData(cell,this._array[index]); }else cell.dataSource=this._array[index]; if (!this.cacheContent){ this.posCell(cell,index); } if (this.hasListener(/*laya.events.Event.RENDER*/"render"))this.event(/*laya.events.Event.RENDER*/"render",[cell,index]); if (this.renderHandler)this.renderHandler.runWith([cell,index]); }else { cell.visible=false; cell.dataSource=null; } } __proto._bindData=function(cell,data){ var arr=cell._$bindData; for (var i=0,n=arr.length;i < n;i++){ var ele=arr[i++]; var prop=arr[i++]; var value=arr[i]; var fun=UIUtils.getBindFun(value); ele[prop]=fun.call(this,data); } } /** *刷新列表数据源。 */ __proto.refresh=function(){ this.array=this._array; } /** *获取单元格数据源。 *@param index 单元格索引。 */ __proto.getItem=function(index){ if (index >-1 && index < this._array.length){ return this._array[index]; } return null; } /** *修改单元格数据源。 *@param index 单元格索引。 *@param source 单元格数据源。 */ __proto.changeItem=function(index,source){ if (index >-1 && index < this._array.length){ this._array[index]=source; if (index >=this._startIndex && index < this._startIndex+this._cells.length){ this.renderItem(this.getCell(index),index); } } } /** *设置单元格数据源。 *@param index 单元格索引。 *@param source 单元格数据源。 */ __proto.setItem=function(index,source){ this.changeItem(index,source); } /** *添加单元格数据源。 *@param souce 数据源。 */ __proto.addItem=function(souce){ this._array.push(souce); this.array=this._array; } /** *添加单元格数据源到对应的数据索引处。 *@param souce 单元格数据源。 *@param index 索引。 */ __proto.addItemAt=function(souce,index){ this._array.splice(index,0,souce); this.array=this._array; } /** *通过数据源索引删除单元格数据源。 *@param index 需要删除的数据源索引值。 */ __proto.deleteItem=function(index){ this._array.splice(index,1); this.array=this._array; } /** *通过可视单元格索引,获取单元格。 *@param index 可视单元格索引。 *@return 单元格对象。 */ __proto.getCell=function(index){ this.runCallLater(this.changeCells); if (index >-1 && this._cells){ return this._cells[(index-this._startIndex)% this._cells.length]; } return null; } /** *

    滚动列表,以设定的数据索引对应的单元格为当前可视列表的第一项。

    *@param index 单元格在数据列表中的索引。 */ __proto.scrollTo=function(index){ if (this._scrollBar){ var numX=this._isVertical ? this.repeatX :this.repeatY; this._scrollBar.value=Math.floor(index / numX)*this._cellSize; }else { this.startIndex=index; } } /** *

    缓动滚动列表,以设定的数据索引对应的单元格为当前可视列表的第一项。

    *@param index 单元格在数据列表中的索引。 *@param time 缓动时间。 *@param complete 缓动结束回掉 */ __proto.tweenTo=function(index,time,complete){ (time===void 0)&& (time=200); if (this._scrollBar){ var numX=this._isVertical ? this.repeatX :this.repeatY; Tween.to(this._scrollBar,{value:Math.floor(index / numX)*this._cellSize},time,null,complete,0,true); }else { this.startIndex=index; if (complete)complete.run(); } } /**@private */ __proto._setCellChanged=function(){ if (!this._cellChanged){ this._cellChanged=true; this.callLater(this.changeCells); } } __proto.commitMeasure=function(){ this.runCallLater(this.changeCells); } /**@inheritDoc */ __getset(0,__proto,'cacheAs',_super.prototype._$get_cacheAs,function(value){ Laya.superSet(Box,this,'cacheAs',value); if (this._scrollBar){ this._$P.cacheAs=null; if (value!=="none")this._scrollBar.on(/*laya.events.Event.START*/"start",this,this.onScrollStart); else this._scrollBar.off(/*laya.events.Event.START*/"start",this,this.onScrollStart); } }); /** *获取对 List 组件所包含的内容容器 Box 组件的引用。 */ __getset(0,__proto,'content',function(){ return this._content; }); /**@inheritDoc */ __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ if (value !=this._height){ Laya.superSet(Box,this,'height',value); this._setCellChanged(); } }); /** *单元格渲染器。 *

    取值: *

      *
    1. 单元格类对象。
    2. *
    3. UI 的 JSON 描述。
    4. *

    */ __getset(0,__proto,'itemRender',function(){ return this._itemRender; },function(value){ if (this._itemRender !=value){ this._itemRender=value; for (var i=this._cells.length-1;i >-1;i--){ this._cells[i].destroy(); } this._cells.length=0; this._setCellChanged(); } }); /** *垂直方向滚动条皮肤。 */ __getset(0,__proto,'vScrollBarSkin',function(){ return this._scrollBar ? this._scrollBar.skin :null; },function(value){ this._removePreScrollBar(); var scrollBar=new VScrollBar(); scrollBar.name="scrollBar"; scrollBar.right=0; if (value && value !=" ") scrollBar.skin=value; this.scrollBar=scrollBar; this.addChild(scrollBar); this._setCellChanged(); }); /** *列表的当前页码。 */ __getset(0,__proto,'page',function(){ return this._page; },function(value){ this._page=value if (this._array){ this._page=value > 0 ? value :0; this._page=this._page < this.totalPage ? this._page :this.totalPage-1; this.startIndex=this._page *this.repeatX *this.repeatY; } }); /** *水平方向滚动条皮肤。 */ __getset(0,__proto,'hScrollBarSkin',function(){ return this._scrollBar ? this._scrollBar.skin :null; },function(value){ this._removePreScrollBar(); var scrollBar=new HScrollBar(); scrollBar.name="scrollBar"; scrollBar.bottom=0; if (value && value !=" ") scrollBar.skin=value; this.scrollBar=scrollBar; this.addChild(scrollBar); this._setCellChanged(); }); /** *水平方向显示的单元格数量。 */ __getset(0,__proto,'repeatX',function(){ return this._repeatX > 0 ? this._repeatX :this._repeatX2 > 0 ? this._repeatX2 :1; },function(value){ this._repeatX=value; this._setCellChanged(); }); /** *获取对 List 组件所包含的滚动条 ScrollBar 组件的引用。 */ __getset(0,__proto,'scrollBar',function(){ return this._scrollBar; },function(value){ if (this._scrollBar !=value){ this._scrollBar=value; if (value){ this._isVertical=this._scrollBar.isVertical; this.addChild(this._scrollBar); this._scrollBar.on(/*laya.events.Event.CHANGE*/"change",this,this.onScrollBarChange); } } }); /**@inheritDoc */ __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ if (value !=this._width){ Laya.superSet(Box,this,'width',value); this._setCellChanged(); } }); /** *垂直方向显示的单元格数量。 */ __getset(0,__proto,'repeatY',function(){ return this._repeatY > 0 ? this._repeatY :this._repeatY2 > 0 ? this._repeatY2 :1; },function(value){ this._repeatY=value; this._setCellChanged(); }); /** *水平方向显示的单元格之间的间距(以像素为单位)。 */ __getset(0,__proto,'spaceX',function(){ return this._spaceX; },function(value){ this._spaceX=value; this._setCellChanged(); }); /** *垂直方向显示的单元格之间的间距(以像素为单位)。 */ __getset(0,__proto,'spaceY',function(){ return this._spaceY; },function(value){ this._spaceY=value; this._setCellChanged(); }); /** *表示当前选择的项索引。selectedIndex值更改会引起list重新渲染 */ __getset(0,__proto,'selectedIndex',function(){ return this._selectedIndex; },function(value){ if (this._selectedIndex !=value){ this._selectedIndex=value; this.changeSelectStatus(); this.event(/*laya.events.Event.CHANGE*/"change"); this.selectHandler && this.selectHandler.runWith(value); this.startIndex=this._startIndex; } }); /** *当前选中的单元格数据源。 */ __getset(0,__proto,'selectedItem',function(){ return this._selectedIndex !=-1 ? this._array[this._selectedIndex] :null; },function(value){ this.selectedIndex=this._array.indexOf(value); }); /** *列表的数据总个数。 */ __getset(0,__proto,'length',function(){ return this._array ? this._array.length :0; }); /** *获取或设置当前选择的单元格对象。 */ __getset(0,__proto,'selection',function(){ return this.getCell(this._selectedIndex); },function(value){ this.selectedIndex=this._startIndex+this._cells.indexOf(value); }); /** *当前显示的单元格列表的开始索引。 */ __getset(0,__proto,'startIndex',function(){ return this._startIndex; },function(value){ this._startIndex=value > 0 ? value :0; this.callLater(this.renderItems); }); /** *列表数据源。 */ __getset(0,__proto,'array',function(){ return this._array; },function(value){ this.runCallLater(this.changeCells); this._array=value || []; var length=this._array.length; this.totalPage=Math.ceil(length / (this.repeatX *this.repeatY)); this._selectedIndex=this._selectedIndex < length ? this._selectedIndex :length-1; this.startIndex=this._startIndex; if (this._scrollBar){ this._scrollBar.stopScroll(); var numX=this._isVertical ? this.repeatX :this.repeatY; var numY=this._isVertical ? this.repeatY :this.repeatX; var lineCount=Math.ceil(length / numX); var total=this._cellOffset > 0 ? this.totalPage+1 :this.totalPage; if (total > 1){ this._scrollBar.scrollSize=this._cellSize; this._scrollBar.thumbPercent=numY / lineCount; this._scrollBar.setScroll(0,(lineCount-numY)*this._cellSize+this._cellOffset,this._scrollBar.value); this._scrollBar.target=this._content; }else { this._scrollBar.setScroll(0,0,0); this._scrollBar.target=this._content; } } }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if (((typeof value=='number')&& Math.floor(value)==value)|| (typeof value=='string'))this.selectedIndex=parseInt(value); else if ((value instanceof Array))this.array=value else Laya.superSet(Box,this,'dataSource',value); }); /** *单元格集合。 */ __getset(0,__proto,'cells',function(){ this.runCallLater(this.changeCells); return this._cells; }); return List; })(Box) /** *使用 HScrollBar (水平 ScrollBar )控件,可以在因数据太多而不能在显示区域完全显示时控制显示的数据部分。 *@example 以下示例代码,创建了一个 HScrollBar 实例。 *package *{ *import laya.ui.HScrollBar; *import laya.utils.Handler; *public class HScrollBar_Example *{ *private var hScrollBar:HScrollBar; *public function HScrollBar_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/hscroll.png","resource/ui/hscroll$bar.png","resource/ui/hscroll$down.png","resource/ui/hscroll$up.png"],Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *hScrollBar=new HScrollBar();//创建一个 HScrollBar 类的实例对象 hScrollBar 。 *hScrollBar.skin="resource/ui/hscroll.png";//设置 hScrollBar 的皮肤。 *hScrollBar.x=100;//设置 hScrollBar 对象的属性 x 的值,用于控制 hScrollBar 对象的显示位置。 *hScrollBar.y=100;//设置 hScrollBar 对象的属性 y 的值,用于控制 hScrollBar 对象的显示位置。 *hScrollBar.changeHandler=new Handler(this,onChange);//设置 hScrollBar 的滚动变化处理器。 *Laya.stage.addChild(hScrollBar);//将此 hScrollBar 对象添加到显示列表。 *} *private function onChange(value:Number):void *{ *trace("滚动条的位置: value="+value); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *var hScrollBar; *var res=["resource/ui/hscroll.png","resource/ui/hscroll$bar.png","resource/ui/hscroll$down.png","resource/ui/hscroll$up.png"]; *Laya.loader.load(res,laya.utils.Handler.create(this,onLoadComplete));//加载资源。 *function onLoadComplete(){ *console.log("资源加载完成!"); *hScrollBar=new laya.ui.HScrollBar();//创建一个 HScrollBar 类的实例对象 hScrollBar 。 *hScrollBar.skin="resource/ui/hscroll.png";//设置 hScrollBar 的皮肤。 *hScrollBar.x=100;//设置 hScrollBar 对象的属性 x 的值,用于控制 hScrollBar 对象的显示位置。 *hScrollBar.y=100;//设置 hScrollBar 对象的属性 y 的值,用于控制 hScrollBar 对象的显示位置。 *hScrollBar.changeHandler=new laya.utils.Handler(this,onChange);//设置 hScrollBar 的滚动变化处理器。 *Laya.stage.addChild(hScrollBar);//将此 hScrollBar 对象添加到显示列表。 *} *function onChange(value) *{ *console.log("滚动条的位置: value="+value); *} *@example *import HScrollBar=laya.ui.HScrollBar; *import Handler=laya.utils.Handler; *class HScrollBar_Example { *private hScrollBar:HScrollBar; *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/hscroll.png","resource/ui/hscroll$bar.png","resource/ui/hscroll$down.png","resource/ui/hscroll$up.png"],Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *this.hScrollBar=new HScrollBar();//创建一个 HScrollBar 类的实例对象 hScrollBar 。 *this.hScrollBar.skin="resource/ui/hscroll.png";//设置 hScrollBar 的皮肤。 *this.hScrollBar.x=100;//设置 hScrollBar 对象的属性 x 的值,用于控制 hScrollBar 对象的显示位置。 *this.hScrollBar.y=100;//设置 hScrollBar 对象的属性 y 的值,用于控制 hScrollBar 对象的显示位置。 *this.hScrollBar.changeHandler=new Handler(this,this.onChange);//设置 hScrollBar 的滚动变化处理器。 *Laya.stage.addChild(this.hScrollBar);//将此 hScrollBar 对象添加到显示列表。 *} *private onChange(value:number):void { *console.log("滚动条的位置: value="+value); *} *} */ //class laya.ui.HScrollBar extends laya.ui.ScrollBar var HScrollBar=(function(_super){ function HScrollBar(){ HScrollBar.__super.call(this);; } __class(HScrollBar,'laya.ui.HScrollBar',_super); var __proto=HScrollBar.prototype; /**@inheritDoc */ __proto.initialize=function(){ _super.prototype.initialize.call(this); this.slider.isVertical=false; } return HScrollBar; })(ScrollBar) /** *Panel 是一个面板容器类。 */ //class laya.ui.Panel extends laya.ui.Box var Panel=(function(_super){ function Panel(){ /**@private */ this._content=null; /**@private */ this._vScrollBar=null; /**@private */ this._hScrollBar=null; /**@private */ this._scrollChanged=false; Panel.__super.call(this); this.width=this.height=100; } __class(Panel,'laya.ui.Panel',_super); var __proto=Panel.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); laya.ui.Component.prototype.destroy.call(this,destroyChild); this._content && this._content.destroy(destroyChild); this._vScrollBar && this._vScrollBar.destroy(destroyChild); this._hScrollBar && this._hScrollBar.destroy(destroyChild); this._vScrollBar=null; this._hScrollBar=null; this._content=null; } /**@inheritDoc */ __proto.destroyChildren=function(){ this._content.destroyChildren(); } /**@inheritDoc */ __proto.createChildren=function(){ laya.display.Node.prototype.addChild.call(this,this._content=new Box()); } /**@inheritDoc */ __proto.addChild=function(child){ child.on(/*laya.events.Event.RESIZE*/"resize",this,this.onResize); this._setScrollChanged(); return this._content.addChild(child); } /** *@private *子对象的 Event.RESIZE 事件侦听处理函数。 */ __proto.onResize=function(){ this._setScrollChanged(); } /**@inheritDoc */ __proto.addChildAt=function(child,index){ child.on(/*laya.events.Event.RESIZE*/"resize",this,this.onResize); this._setScrollChanged(); return this._content.addChildAt(child,index); } /**@inheritDoc */ __proto.removeChild=function(child){ child.off(/*laya.events.Event.RESIZE*/"resize",this,this.onResize); this._setScrollChanged(); return this._content.removeChild(child); } /**@inheritDoc */ __proto.removeChildAt=function(index){ this.getChildAt(index).off(/*laya.events.Event.RESIZE*/"resize",this,this.onResize); this._setScrollChanged(); return this._content.removeChildAt(index); } /**@inheritDoc */ __proto.removeChildren=function(beginIndex,endIndex){ (beginIndex===void 0)&& (beginIndex=0); (endIndex===void 0)&& (endIndex=0x7fffffff); this._content.removeChildren(beginIndex,endIndex); this._setScrollChanged(); return this; } /**@inheritDoc */ __proto.getChildAt=function(index){ return this._content.getChildAt(index); } /**@inheritDoc */ __proto.getChildByName=function(name){ return this._content.getChildByName(name); } /**@inheritDoc */ __proto.getChildIndex=function(child){ return this._content.getChildIndex(child); } /**@private */ __proto.changeScroll=function(){ this._scrollChanged=false; var contentW=this.contentWidth || 1; var contentH=this.contentHeight || 1; var vscroll=this._vScrollBar; var hscroll=this._hScrollBar; var vShow=vscroll && contentH > this._height; var hShow=hscroll && contentW > this._width; var showWidth=vShow ? this._width-vscroll.width :this._width; var showHeight=hShow ? this._height-hscroll.height :this._height; if (vscroll){ vscroll.x=this._width-vscroll.width; vscroll.y=0; vscroll.height=this._height-(hShow ? hscroll.height :0); vscroll.scrollSize=Math.max(this._height *0.033,1); vscroll.thumbPercent=showHeight / contentH; vscroll.setScroll(0,contentH-showHeight,vscroll.value); } if (hscroll){ hscroll.x=0; hscroll.y=this._height-hscroll.height; hscroll.width=this._width-(vShow ? vscroll.width :0); hscroll.scrollSize=Math.max(this._width *0.033,1); hscroll.thumbPercent=showWidth / contentW; hscroll.setScroll(0,contentW-showWidth,hscroll.value); } } /**@inheritDoc */ __proto.changeSize=function(){ laya.ui.Component.prototype.changeSize.call(this); this.setContentSize(this._width,this._height); } /** *@private *设置内容的宽度、高度(以像素为单位)。 *@param width 宽度。 *@param height 高度。 */ __proto.setContentSize=function(width,height){ var content=this._content; content.width=width; content.height=height; content.scrollRect || (content.scrollRect=new Rectangle()); content.scrollRect.setTo(0,0,width,height); content.scrollRect=content.scrollRect; } /** *@private *滚动条的Event.MOUSE_DOWN事件侦听处理函数。事件侦听处理函数。 *@param scrollBar 滚动条对象。 *@param e Event 对象。 */ __proto.onScrollBarChange=function(scrollBar){ var rect=this._content.scrollRect; if (rect){ var start=Math.round(scrollBar.value); scrollBar.isVertical ? rect.y=start :rect.x=start; this._content.scrollRect=rect; } } /** *

    滚动内容容器至设定的垂直、水平方向滚动条位置。

    *@param x 水平方向滚动条属性value值。滚动条位置数字。 *@param y 垂直方向滚动条属性value值。滚动条位置数字。 */ __proto.scrollTo=function(x,y){ (x===void 0)&& (x=0); (y===void 0)&& (y=0); if (this.vScrollBar)this.vScrollBar.value=y; if (this.hScrollBar)this.hScrollBar.value=x; } /** *刷新滚动内容。 */ __proto.refresh=function(){ this.changeScroll(); } __proto.onScrollStart=function(){ this._$P.cacheAs || (this._$P.cacheAs=Laya.superGet(Box,this,'cacheAs')); Laya.superSet(Box,this,'cacheAs',"none"); this._hScrollBar && this._hScrollBar.once(/*laya.events.Event.END*/"end",this,this.onScrollEnd); this._vScrollBar && this._vScrollBar.once(/*laya.events.Event.END*/"end",this,this.onScrollEnd); } __proto.onScrollEnd=function(){ Laya.superSet(Box,this,'cacheAs',this._$P.cacheAs); } /**@private */ __proto._setScrollChanged=function(){ if (!this._scrollChanged){ this._scrollChanged=true; this.callLater(this.changeScroll); } } /**@inheritDoc */ __getset(0,__proto,'numChildren',function(){ return this._content.numChildren; }); /** *水平方向滚动条皮肤。 */ __getset(0,__proto,'hScrollBarSkin',function(){ return this._hScrollBar ? this._hScrollBar.skin :null; },function(value){ if (this._hScrollBar==null){ laya.display.Node.prototype.addChild.call(this,this._hScrollBar=new HScrollBar()); this._hScrollBar.on(/*laya.events.Event.CHANGE*/"change",this,this.onScrollBarChange,[this._hScrollBar]); this._hScrollBar.target=this._content; this._setScrollChanged(); } this._hScrollBar.skin=value; }); /** *@private *获取内容宽度(以像素为单位)。 */ __getset(0,__proto,'contentWidth',function(){ var max=0; for (var i=this._content.numChildren-1;i >-1;i--){ var comp=this._content.getChildAt(i); max=Math.max(comp.x+comp.width *comp.scaleX,max); } return max; }); /** *@private *获取内容高度(以像素为单位)。 */ __getset(0,__proto,'contentHeight',function(){ var max=0; for (var i=this._content.numChildren-1;i >-1;i--){ var comp=this._content.getChildAt(i); max=Math.max(comp.y+comp.height *comp.scaleY,max); } return max; }); /** *@inheritDoc */ __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(Box,this,'width',value); this._setScrollChanged(); }); /** *水平方向滚动条对象。 */ __getset(0,__proto,'hScrollBar',function(){ return this._hScrollBar; }); /** *获取内容容器对象。 */ __getset(0,__proto,'content',function(){ return this._content; }); /**@inheritDoc */ __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Box,this,'height',value); this._setScrollChanged(); }); /** *垂直方向滚动条皮肤。 */ __getset(0,__proto,'vScrollBarSkin',function(){ return this._vScrollBar ? this._vScrollBar.skin :null; },function(value){ if (this._vScrollBar==null){ laya.display.Node.prototype.addChild.call(this,this._vScrollBar=new VScrollBar()); this._vScrollBar.on(/*laya.events.Event.CHANGE*/"change",this,this.onScrollBarChange,[this._vScrollBar]); this._vScrollBar.target=this._content; this._setScrollChanged(); } this._vScrollBar.skin=value; }); /** *垂直方向滚动条对象。 */ __getset(0,__proto,'vScrollBar',function(){ return this._vScrollBar; }); /**@inheritDoc */ __getset(0,__proto,'cacheAs',_super.prototype._$get_cacheAs,function(value){ Laya.superSet(Box,this,'cacheAs',value); this._$P.cacheAs=null; if (value!=="none"){ this._hScrollBar && this._hScrollBar.on(/*laya.events.Event.START*/"start",this,this.onScrollStart); this._vScrollBar && this._vScrollBar.on(/*laya.events.Event.START*/"start",this,this.onScrollStart); }else { this._hScrollBar && this._hScrollBar.off(/*laya.events.Event.START*/"start",this,this.onScrollStart); this._vScrollBar && this._vScrollBar.off(/*laya.events.Event.START*/"start",this,this.onScrollStart); } }); return Panel; })(Box) /** *使用 HSlider 控件,用户可以通过在滑块轨道的终点之间移动滑块来选择值。 *

    HSlider 控件采用水平方向。滑块轨道从左向右扩展,而标签位于轨道的顶部或底部。

    * *@example 以下示例代码,创建了一个 HSlider 实例。 *package *{ *import laya.ui.HSlider; *import laya.utils.Handler; *public class HSlider_Example *{ *private var hSlider:HSlider; *public function HSlider_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/hslider.png","resource/ui/hslider$bar.png"],Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *hSlider=new HSlider();//创建一个 HSlider 类的实例对象 hSlider 。 *hSlider.skin="resource/ui/hslider.png";//设置 hSlider 的皮肤。 *hSlider.min=0;//设置 hSlider 最低位置值。 *hSlider.max=10;//设置 hSlider 最高位置值。 *hSlider.value=2;//设置 hSlider 当前位置值。 *hSlider.tick=1;//设置 hSlider 刻度值。 *hSlider.x=100;//设置 hSlider 对象的属性 x 的值,用于控制 hSlider 对象的显示位置。 *hSlider.y=100;//设置 hSlider 对象的属性 y 的值,用于控制 hSlider 对象的显示位置。 *hSlider.changeHandler=new Handler(this,onChange);//设置 hSlider 位置变化处理器。 *Laya.stage.addChild(hSlider);//把 hSlider 添加到显示列表。 *} *private function onChange(value:Number):void *{ *trace("滑块的位置: value="+value); *} *} *} *@example *Laya.init(640,800,"canvas");//设置游戏画布宽高、渲染模式 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *var hSlider; *var res=["resource/ui/hslider.png","resource/ui/hslider$bar.png"]; *Laya.loader.load(res,laya.utils.Handler.create(this,onLoadComplete)); *function onLoadComplete(){ *console.log("资源加载完成!"); *hSlider=new laya.ui.HSlider();//创建一个 HSlider 类的实例对象 hSlider 。 *hSlider.skin="resource/ui/hslider.png";//设置 hSlider 的皮肤。 *hSlider.min=0;//设置 hSlider 最低位置值。 *hSlider.max=10;//设置 hSlider 最高位置值。 *hSlider.value=2;//设置 hSlider 当前位置值。 *hSlider.tick=1;//设置 hSlider 刻度值。 *hSlider.x=100;//设置 hSlider 对象的属性 x 的值,用于控制 hSlider 对象的显示位置。 *hSlider.y=100;//设置 hSlider 对象的属性 y 的值,用于控制 hSlider 对象的显示位置。 *hSlider.changeHandler=new laya.utils.Handler(this,onChange);//设置 hSlider 位置变化处理器。 *Laya.stage.addChild(hSlider);//把 hSlider 添加到显示列表。 *} *function onChange(value) *{ *console.log("滑块的位置: value="+value); *} *@example *import Handler=laya.utils.Handler; *import HSlider=laya.ui.HSlider; *class HSlider_Example { *private hSlider:HSlider; *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/hslider.png","resource/ui/hslider$bar.png"],Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *this.hSlider=new HSlider();//创建一个 HSlider 类的实例对象 hSlider 。 *this.hSlider.skin="resource/ui/hslider.png";//设置 hSlider 的皮肤。 *this.hSlider.min=0;//设置 hSlider 最低位置值。 *this.hSlider.max=10;//设置 hSlider 最高位置值。 *this.hSlider.value=2;//设置 hSlider 当前位置值。 *this.hSlider.tick=1;//设置 hSlider 刻度值。 *this.hSlider.x=100;//设置 hSlider 对象的属性 x 的值,用于控制 hSlider 对象的显示位置。 *this.hSlider.y=100;//设置 hSlider 对象的属性 y 的值,用于控制 hSlider 对象的显示位置。 *this.hSlider.changeHandler=new Handler(this,this.onChange);//设置 hSlider 位置变化处理器。 *Laya.stage.addChild(this.hSlider);//把 hSlider 添加到显示列表。 *} *private onChange(value:number):void { *console.log("滑块的位置: value="+value); *} *} * *@see laya.ui.Slider */ //class laya.ui.HSlider extends laya.ui.Slider var HSlider=(function(_super){ /** *创建一个 HSlider 类实例。 *@param skin 皮肤。 */ function HSlider(skin){ HSlider.__super.call(this,skin); this.isVertical=false; } __class(HSlider,'laya.ui.HSlider',_super); return HSlider; })(Slider) /** *Group 是一个可以自动布局的项集合控件。 *

    Group 的默认项对象为 Button 类实例。 *GroupTabRadioGroup 的基类。

    */ //class laya.ui.UIGroup extends laya.ui.Box var UIGroup=(function(_super){ function UIGroup(labels,skin){ /** *改变 Group 的选择项时执行的处理器,(默认返回参数: 项索引(index:int))。 */ this.selectHandler=null; /**@private */ this._items=null; /**@private */ this._selectedIndex=-1; /**@private */ this._skin=null; /**@private */ this._direction="horizontal"; /**@private */ this._space=0; /**@private */ this._labels=null; /**@private */ this._labelColors=null; /**@private */ this._labelFont=null; /**@private */ this._labelStrokeColor=null; /**@private */ this._strokeColors=null; /**@private */ this._labelStroke=NaN; /**@private */ this._labelSize=0; /**@private */ this._labelBold=false; /**@private */ this._labelPadding=null; /**@private */ this._labelAlign=null; /**@private */ this._stateNum=0; /**@private */ this._labelChanged=false; UIGroup.__super.call(this); this.skin=skin; this.labels=labels; } __class(UIGroup,'laya.ui.UIGroup',_super); var __proto=UIGroup.prototype; Laya.imps(__proto,{"laya.ui.IItem":true}) /**@inheritDoc */ __proto.preinitialize=function(){ this.mouseEnabled=true; } /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); laya.ui.Component.prototype.destroy.call(this,destroyChild); this._items && (this._items.length=0); this._items=null; this.selectHandler=null; } /** *添加一个项对象,返回此项对象的索引id。 * *@param item 需要添加的项对象。 *@param autoLayOut 是否自动布局,如果为true,会根据 directionspace 属性计算item的位置。 *@return */ __proto.addItem=function(item,autoLayOut){ (autoLayOut===void 0)&& (autoLayOut=true); var display=item; var index=this._items.length; display.name="item"+index; this.addChild(display); this.initItems(); if (autoLayOut && index > 0){ var preItem=this._items [index-1]; if (this._direction=="horizontal"){ display.x=preItem.x+preItem.width+this._space; }else { display.y=preItem.y+preItem.height+this._space; } }else { if (autoLayOut){ display.x=0; display.y=0; } } return index; } /** *删除一个项对象。 *@param item 需要删除的项对象。 *@param autoLayOut 是否自动布局,如果为true,会根据 directionspace 属性计算item的位置。 */ __proto.delItem=function(item,autoLayOut){ (autoLayOut===void 0)&& (autoLayOut=true); var index=this._items.indexOf(item); if (index !=-1){ var display=item; this.removeChild(display); for (var i=index+1,n=this._items.length;i < n;i++){ var child=this._items [i]; child.name="item"+(i-1); if (autoLayOut){ if (this._direction=="horizontal"){ child.x-=display.width+this._space; }else { child.y-=display.height+this._space; } } } this.initItems(); if (this._selectedIndex >-1){ var newIndex=0; newIndex=this._selectedIndex < this._items.length ? this._selectedIndex :(this._selectedIndex-1); this._selectedIndex=-1; this.selectedIndex=newIndex; } } } /** *初始化项对象们。 */ __proto.initItems=function(){ this._items || (this._items=[]); this._items.length=0; for (var i=0;i < 10000;i++){ var item=this.getChildByName("item"+i); if (item==null)break ; this._items.push(item); item.selected=(i===this._selectedIndex); item.clickHandler=Handler.create(this,this.itemClick,[i],false); } } /** *@private *项对象的点击事件侦听处理函数。 *@param index 项索引。 */ __proto.itemClick=function(index){ this.selectedIndex=index; } /** *@private *通过对象的索引设置项对象的 selected 属性值。 *@param index 需要设置的项对象的索引。 *@param selected 表示项对象的选中状态。 */ __proto.setSelect=function(index,selected){ if (this._items && index >-1 && index < this._items.length)this._items[index].selected=selected; } /** *@private *创建一个项显示对象。 *@param skin 项对象的皮肤。 *@param label 项对象标签。 */ __proto.createItem=function(skin,label){ return null; } /** *@private *更改项对象的属性值。 */ __proto.changeLabels=function(){ this._labelChanged=false; if (this._items){ var left=0 for (var i=0,n=this._items.length;i < n;i++){ var btn=this._items [i]; this._skin && (btn.skin=this._skin); this._labelColors && (btn.labelColors=this._labelColors); this._labelSize && (btn.labelSize=this._labelSize); this._labelStroke && (btn.labelStroke=this._labelStroke); this._labelStrokeColor && (btn.labelStrokeColor=this._labelStrokeColor); this._strokeColors && (btn.strokeColors=this._strokeColors); this._labelBold && (btn.labelBold=this._labelBold); this._labelPadding && (btn.labelPadding=this._labelPadding); this._labelAlign && (btn.labelAlign=this._labelAlign); this._stateNum && (btn.stateNum=this._stateNum); this._labelFont && (btn.labelFont=this._labelFont); if (this._direction==="horizontal"){ btn.y=0; btn.x=left; left+=btn.width+this._space; }else { btn.x=0; btn.y=left; left+=btn.height+this._space; } } } this.changeSize(); } /**@inheritDoc */ __proto.commitMeasure=function(){ this.runCallLater(this.changeLabels); } /**@private */ __proto._setLabelChanged=function(){ if (!this._labelChanged){ this._labelChanged=true; this.callLater(this.changeLabels); } } /** *

    描边颜色,以字符串表示。

    *默认值为 "#000000"(黑色); *@see laya.display.Text.strokeColor() */ __getset(0,__proto,'labelStrokeColor',function(){ return this._labelStrokeColor; },function(value){ if (this._labelStrokeColor !=value){ this._labelStrokeColor=value; this._setLabelChanged(); } }); /** *@copy laya.ui.Image#skin */ __getset(0,__proto,'skin',function(){ return this._skin; },function(value){ if (this._skin !=value){ this._skin=value; this._setLabelChanged(); } }); /** *表示当前选择的项索引。默认值为-1。 */ __getset(0,__proto,'selectedIndex',function(){ return this._selectedIndex; },function(value){ if (this._selectedIndex !=value){ this.setSelect(this._selectedIndex,false); this._selectedIndex=value; this.setSelect(value,true); this.event(/*laya.events.Event.CHANGE*/"change"); this.selectHandler && this.selectHandler.runWith(this._selectedIndex); } }); /** *标签集合字符串。以逗号做分割,如"item0,item1,item2,item3,item4,item5"。 */ __getset(0,__proto,'labels',function(){ return this._labels; },function(value){ if (this._labels !=value){ this._labels=value; this.removeChildren(); this._setLabelChanged(); if (this._labels){ var a=this._labels.split(","); for (var i=0,n=a.length;i < n;i++){ var item=this.createItem(this._skin,a[i]); item.name="item"+i; this.addChild(item); } } this.initItems(); } }); /** *

    表示各个状态下的描边颜色。

    *@see laya.display.Text.strokeColor() */ __getset(0,__proto,'strokeColors',function(){ return this._strokeColors; },function(value){ if (this._strokeColors !=value){ this._strokeColors=value; this._setLabelChanged(); } }); /** *@copy laya.ui.Button#labelColors() */ __getset(0,__proto,'labelColors',function(){ return this._labelColors; },function(value){ if (this._labelColors !=value){ this._labelColors=value; this._setLabelChanged(); } }); /** *

    描边宽度(以像素为单位)。

    *默认值0,表示不描边。 *@see laya.display.Text.stroke() */ __getset(0,__proto,'labelStroke',function(){ return this._labelStroke; },function(value){ if (this._labelStroke !=value){ this._labelStroke=value; this._setLabelChanged(); } }); /** *表示按钮文本标签的字体大小。 */ __getset(0,__proto,'labelSize',function(){ return this._labelSize; },function(value){ if (this._labelSize !=value){ this._labelSize=value; this._setLabelChanged(); } }); /** *表示按钮的状态值,以数字表示,默认为3态。 *@see laya.ui.Button#stateNum */ __getset(0,__proto,'stateNum',function(){ return this._stateNum; },function(value){ if (this._stateNum !=value){ this._stateNum=value; this._setLabelChanged(); } }); /** *表示按钮文本标签是否为粗体字。 */ __getset(0,__proto,'labelBold',function(){ return this._labelBold; },function(value){ if (this._labelBold !=value){ this._labelBold=value; this._setLabelChanged(); } }); /** *表示按钮文本标签的字体名称,以字符串形式表示。 *@see laya.display.Text.font() */ __getset(0,__proto,'labelFont',function(){ return this._labelFont; },function(value){ if (this._labelFont !=value){ this._labelFont=value; this._setLabelChanged(); } }); /** *表示按钮文本标签的边距。 *

    格式:"上边距,右边距,下边距,左边距"。

    */ __getset(0,__proto,'labelPadding',function(){ return this._labelPadding; },function(value){ if (this._labelPadding !=value){ this._labelPadding=value; this._setLabelChanged(); } }); /** *布局方向。 *

    默认值为"horizontal"。

    *

    取值: *

  • "horizontal":表示水平布局。
  • *
  • "vertical":表示垂直布局。
  • *

    */ __getset(0,__proto,'direction',function(){ return this._direction; },function(value){ this._direction=value; this._setLabelChanged(); }); /** *项对象们之间的间隔(以像素为单位)。 */ __getset(0,__proto,'space',function(){ return this._space; },function(value){ this._space=value; this._setLabelChanged(); }); /** *项对象们的存放数组。 */ __getset(0,__proto,'items',function(){ return this._items; }); /** *获取或设置当前选择的项对象。 */ __getset(0,__proto,'selection',function(){ return this._selectedIndex >-1 && this._selectedIndex < this._items.length ? this._items[this._selectedIndex] :null; },function(value){ this.selectedIndex=this._items.indexOf(value); }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if (((typeof value=='number')&& Math.floor(value)==value)|| (typeof value=='string'))this.selectedIndex=parseInt(value); else if ((value instanceof Array))this.labels=(value).join(","); else Laya.superSet(Box,this,'dataSource',value); }); return UIGroup; })(Box) /** *Radio 控件使用户可在一组互相排斥的选择中做出一种选择。 *用户一次只能选择 Radio 组中的一个成员。选择未选中的组成员将取消选择该组中当前所选的 Radio 控件。 *@see laya.ui.RadioGroup */ //class laya.ui.Radio extends laya.ui.Button var Radio=(function(_super){ function Radio(skin,label){ /**@private */ this._value=null; (label===void 0)&& (label=""); Radio.__super.call(this,skin,label); } __class(Radio,'laya.ui.Radio',_super); var __proto=Radio.prototype; /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._value=null; } /**@inheritDoc */ __proto.preinitialize=function(){ laya.ui.Component.prototype.preinitialize.call(this); this.toggle=false; this._autoSize=false; } /**@inheritDoc */ __proto.initialize=function(){ _super.prototype.initialize.call(this); this.createText(); this._text.align="left"; this._text.valign="top"; this._text.width=0; this.on(/*laya.events.Event.CLICK*/"click",this,this.onClick); } /** *@private *对象的Event.CLICK事件侦听处理函数。 */ __proto.onClick=function(e){ this.selected=true; } /** *获取或设置 Radio 关联的可选用户定义值。 */ __getset(0,__proto,'value',function(){ return this._value !=null ? this._value :this.label; },function(obj){ this._value=obj; }); return Radio; })(Button) /** *Tree 控件使用户可以查看排列为可扩展树的层次结构数据。 * *@example *package *{ *import laya.ui.Tree; *import laya.utils.Browser; *import laya.utils.Handler; *public class Tree_Example *{ *public function Tree_Example() *{ *Laya.init(640,800); *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/vscroll.png","resource/ui/vscroll$bar.png","resource/ui/vscroll$down.png","resource/ui/vscroll$up.png","resource/ui/clip_selectBox.png","resource/ui/clip_tree_folder.png","resource/ui/clip_tree_arrow.png"],Handler.create(this,onLoadComplete)); *} *private function onLoadComplete():void *{ *var xmlString:String;//创建一个xml字符串,用于存储树结构数据。 *xmlString="<root><item label='box1'><abc label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/><abc label='child5'/></item><item label='box2'><abc label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/></item></root>"; *var domParser:*=new Browser.window.DOMParser();//创建一个DOMParser实例domParser。 *var xml:*=domParser.parseFromString(xmlString,"text/xml");//解析xml字符。 *var tree:Tree=new Tree();//创建一个 Tree 类的实例对象 tree 。 *tree.scrollBarSkin="resource/ui/vscroll.png";//设置 tree 的皮肤。 *tree.itemRender=Item;//设置 tree 的项渲染器。 *tree.xml=xml;//设置 tree 的树结构数据。 *tree.x=100;//设置 tree 对象的属性 x 的值,用于控制 tree 对象的显示位置。 *tree.y=100;//设置 tree 对象的属性 y 的值,用于控制 tree 对象的显示位置。 *tree.width=200;//设置 tree 的宽度。 *tree.height=100;//设置 tree 的高度。 *Laya.stage.addChild(tree);//将 tree 添加到显示列表。 *} *} *} *import laya.ui.Box; *import laya.ui.Clip; *import laya.ui.Label; *class Item extends Box *{ *public function Item() *{ *this.name="render"; *this.right=0; *this.left=0; *var selectBox:Clip=new Clip("resource/ui/clip_selectBox.png",1,2); *selectBox.name="selectBox"; *selectBox.height=24; *selectBox.x=13; *selectBox.y=0; *selectBox.left=12; *addChild(selectBox); *var folder:Clip=new Clip("resource/ui/clip_tree_folder.png",1,3); *folder.name="folder"; *folder.x=14; *folder.y=4; *addChild(folder); *var label:Label=new Label("treeItem"); *label.name="label"; *label.color="#ffff00"; *label.width=150; *label.height=22; *label.x=33; *label.y=1; *label.left=33; *label.right=0; *addChild(label); *var arrow:Clip=new Clip("resource/ui/clip_tree_arrow.png",1,2); *arrow.name="arrow"; *arrow.x=0; *arrow.y=5; *addChild(arrow); *} *} *@example *Laya.init(640,800);//设置游戏画布宽高、渲染模式 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *var res=["resource/ui/vscroll.png","resource/ui/vscroll$bar.png","resource/ui/vscroll$down.png","resource/ui/vscroll$up.png","resource/ui/clip_selectBox.png","resource/ui/clip_tree_folder.png","resource/ui/clip_tree_arrow.png"]; *Laya.loader.load(res,new laya.utils.Handler(this,onLoadComplete)); *function onLoadComplete(){ *var xmlString;//创建一个xml字符串,用于存储树结构数据。 *xmlString="<root><item label='box1'><abc label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/><abc label='child5'/></item><item label='box2'><abc label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/></item></root>"; *var domParser=new laya.utils.Browser.window.DOMParser();//创建一个DOMParser实例domParser。 *var xml=domParser.parseFromString(xmlString,"text/xml");//解析xml字符。 *var tree=new laya.ui.Tree();//创建一个 Tree 类的实例对象 tree 。 *tree.scrollBarSkin="resource/ui/vscroll.png";//设置 tree 的皮肤。 *tree.itemRender=mypackage.treeExample.Item;//设置 tree 的项渲染器。 *tree.xml=xml;//设置 tree 的树结构数据。 *tree.x=100;//设置 tree 对象的属性 x 的值,用于控制 tree 对象的显示位置。 *tree.y=100;//设置 tree 对象的属性 y 的值,用于控制 tree 对象的显示位置。 *tree.width=200;//设置 tree 的宽度。 *tree.height=100;//设置 tree 的高度。 *Laya.stage.addChild(tree);//将 tree 添加到显示列表。 *} *(function (_super){ *function Item(){ *Item.__super.call(this);//初始化父类。 *this.right=0; *this.left=0; *var selectBox=new laya.ui.Clip("resource/ui/clip_selectBox.png",1,2); *selectBox.name="selectBox";//设置 selectBox 的name 为“selectBox”时,将被识别为树结构的项的背景。2帧:悬停时背景、选中时背景。 *selectBox.height=24; *selectBox.x=13; *selectBox.y=0; *selectBox.left=12; *this.addChild(selectBox);//需要使用this.访问父类的属性或方法。 *var folder=new laya.ui.Clip("resource/ui/clip_tree_folder.png",1,3); *folder.name="folder";//设置 folder 的name 为“folder”时,将被识别为树结构的文件夹开启状态图表。2帧:折叠状态、打开状态。 *folder.x=14; *folder.y=4; *this.addChild(folder); *var label=new laya.ui.Label("treeItem"); *label.name="label";//设置 label 的name 为“label”时,此值将用于树结构数据赋值。 *label.color="#ffff00"; *label.width=150; *label.height=22; *label.x=33; *label.y=1; *label.left=33; *label.right=0; *this.addChild(label); *var arrow=new laya.ui.Clip("resource/ui/clip_tree_arrow.png",1,2); *arrow.name="arrow";//设置 arrow 的name 为“arrow”时,将被识别为树结构的文件夹开启状态图表。2帧:折叠状态、打开状态。 *arrow.x=0; *arrow.y=5; *this.addChild(arrow); *}; *Laya.class(Item,"mypackage.treeExample.Item",_super);//注册类 Item 。 *})(laya.ui.Box); *@example *import Tree=laya.ui.Tree; *import Browser=laya.utils.Browser; *import Handler=laya.utils.Handler; *class Tree_Example { *constructor(){ *Laya.init(640,800); *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/vscroll.png","resource/ui/vscroll$bar.png","resource/ui/vscroll$down.png","resource/ui/vscroll$up.png","resource/ui/vscroll$up.png","resource/ui/clip_selectBox.png","resource/ui/clip_tree_folder * . * png","resource/ui/clip_tree_arrow.png"],Handler.create(this,this.onLoadComplete)); *} *private onLoadComplete():void { *var xmlString:String;//创建一个xml字符串,用于存储树结构数据。 *xmlString="<root><item label='box1'><abc label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/><abc label='child5'/></item><item label='box2'><abc * label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/></item></root>"; *var domParser:any=new Browser.window.DOMParser();//创建一个DOMParser实例domParser。 *var xml:any=domParser.parseFromString(xmlString,"text/xml");//解析xml字符。 *var tree:Tree=new Tree();//创建一个 Tree 类的实例对象 tree 。 *tree.scrollBarSkin="resource/ui/vscroll.png";//设置 tree 的皮肤。 *tree.itemRender=Item;//设置 tree 的项渲染器。 *tree.xml=xml;//设置 tree 的树结构数据。 *tree.x=100;//设置 tree 对象的属性 x 的值,用于控制 tree 对象的显示位置。 *tree.y=100;//设置 tree 对象的属性 y 的值,用于控制 tree 对象的显示位置。 *tree.width=200;//设置 tree 的宽度。 *tree.height=100;//设置 tree 的高度。 *Laya.stage.addChild(tree);//将 tree 添加到显示列表。 *} *} *import Box=laya.ui.Box; *import Clip=laya.ui.Clip; *import Label=laya.ui.Label; *class Item extends Box { *constructor(){ *super(); *this.name="render"; *this.right=0; *this.left=0; *var selectBox:Clip=new Clip("resource/ui/clip_selectBox.png",1,2); *selectBox.name="selectBox"; *selectBox.height=24; *selectBox.x=13; *selectBox.y=0; *selectBox.left=12; *this.addChild(selectBox); *var folder:Clip=new Clip("resource/ui/clip_tree_folder.png",1,3); *folder.name="folder"; *folder.x=14; *folder.y=4; *this.addChild(folder); *var label:Label=new Label("treeItem"); *label.name="label"; *label.color="#ffff00"; *label.width=150; *label.height=22; *label.x=33; *label.y=1; *label.left=33; *label.right=0; *this.addChild(label); *var arrow:Clip=new Clip("resource/ui/clip_tree_arrow.png",1,2); *arrow.name="arrow"; *arrow.x=0; *arrow.y=5; *this.addChild(arrow); *} *} */ //class laya.ui.Tree extends laya.ui.Box var Tree=(function(_super){ function Tree(){ /**@private */ this._list=null; /**@private */ this._source=null; /**@private */ this._renderHandler=null; /**@private */ this._spaceLeft=10; /**@private */ this._spaceBottom=0; /**@private */ this._keepStatus=true; Tree.__super.call(this); this.width=this.height=200; } __class(Tree,'laya.ui.Tree',_super); var __proto=Tree.prototype; Laya.imps(__proto,{"laya.ui.IRender":true}) /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); laya.ui.Component.prototype.destroy.call(this,destroyChild); this._list && this._list.destroy(destroyChild); this._list=null; this._source=null; this._renderHandler=null; } /**@inheritDoc */ __proto.createChildren=function(){ this.addChild(this._list=new List()); this._list.renderHandler=Handler.create(this,this.renderItem,null,false); this._list.repeatX=1; this._list.on(/*laya.events.Event.CHANGE*/"change",this,this.onListChange); } /** *@private *此对象包含的List实例的Event.CHANGE事件侦听处理函数。 */ __proto.onListChange=function(e){ this.event(/*laya.events.Event.CHANGE*/"change"); } /** *@private *获取数据源集合。 */ __proto.getArray=function(){ var arr=[]; var item; /*for each*/for(var $each_item in this._source){ item=this._source[$each_item]; if (this.getParentOpenStatus(item)){ item.x=this._spaceLeft *this.getDepth(item); arr.push(item); } } return arr; } /** *@private *获取项对象的深度。 */ __proto.getDepth=function(item,num){ (num===void 0)&& (num=0); if (item.nodeParent==null)return num; else return this.getDepth(item.nodeParent,num+1); } /** *@private *获取项对象的上一级的打开状态。 */ __proto.getParentOpenStatus=function(item){ var parent=item.nodeParent; if (parent==null){ return true; }else { if (parent.isOpen){ if (parent.nodeParent !=null)return this.getParentOpenStatus(parent); else return true; }else { return false; } } } /** *@private *渲染一个项对象。 *@param cell 一个项对象。 *@param index 项的索引。 */ __proto.renderItem=function(cell,index){ var item=cell.dataSource; if (item){ cell.left=item.x; var arrow=cell.getChildByName("arrow"); if (arrow){ if (item.hasChild){ arrow.visible=true; arrow.index=item.isOpen ? 1 :0; arrow.tag=index; arrow.off(/*laya.events.Event.CLICK*/"click",this,this.onArrowClick); arrow.on(/*laya.events.Event.CLICK*/"click",this,this.onArrowClick); }else { arrow.visible=false; } }; var folder=cell.getChildByName("folder"); if (folder){ if (folder.clipY==2){ folder.index=item.isDirectory ? 0 :1; }else { folder.index=item.isDirectory ? item.isOpen ? 1 :0 :2; } } this._renderHandler && this._renderHandler.runWith([cell,index]); } } /** *@private */ __proto.onArrowClick=function(e){ var arrow=e.currentTarget; var index=arrow.tag; this._list.array[index].isOpen=!this._list.array[index].isOpen; this.event(/*laya.events.Event.OPEN*/"open"); this._list.array=this.getArray(); } /** *设置指定项索引的项对象的打开状态。 *@param index 项索引。 *@param isOpen 是否处于打开状态。 */ __proto.setItemState=function(index,isOpen){ if (!this._list.array[index])return; this._list.array[index].isOpen=isOpen; this._list.array=this.getArray(); } /** *刷新项列表。 */ __proto.fresh=function(){ this._list.array=this.getArray(); this.repaint(); } /** *@private *解析并处理XML类型的数据源。 */ __proto.parseXml=function(xml,source,nodeParent,isRoot){ var obj; var list=xml.childNodes; var childCount=list.length; if (!isRoot){ obj={}; var list2=xml.attributes; var attrs; /*for each*/for(var $each_attrs in list2){ attrs=list2[$each_attrs]; var prop=attrs.nodeName; var value=attrs.nodeValue; obj[prop]=value=="true" ? true :value=="false" ? false :value; } obj.nodeParent=nodeParent; if (childCount > 0)obj.isDirectory=true; obj.hasChild=childCount > 0; source.push(obj); } for (var i=0;i < childCount;i++){ var node=list[i]; this.parseXml(node,source,obj,false); } } /** *@private *处理数据项的打开状态。 */ __proto.parseOpenStatus=function(oldSource,newSource){ for (var i=0,n=newSource.length;i < n;i++){ var newItem=newSource[i]; if (newItem.isDirectory){ for (var j=0,m=oldSource.length;j < m;j++){ var oldItem=oldSource[j]; if (oldItem.isDirectory && this.isSameParent(oldItem,newItem)&& newItem.label==oldItem.label){ newItem.isOpen=oldItem.isOpen; break ; } } } } } /** *@private *判断两个项对象在树结构中的父节点是否相同。 *@param item1 项对象。 *@param item2 项对象。 *@return 如果父节点相同值为true,否则值为false。 */ __proto.isSameParent=function(item1,item2){ if (item1.nodeParent==null && item2.nodeParent==null)return true; else if (item1.nodeParent==null || item2.nodeParent==null)return false else { if (item1.nodeParent.label==item2.nodeParent.label)return this.isSameParent(item1.nodeParent,item2.nodeParent); else return false; } } /** *更新项列表,显示指定键名的数据项。 *@param key 键名。 */ __proto.filter=function(key){ if (Boolean(key)){ var result=[]; this.getFilterSource(this._source,result,key); this._list.array=result; }else { this._list.array=this.getArray(); } } /** *@private *获取数据源中指定键名的值。 */ __proto.getFilterSource=function(array,result,key){ key=key.toLocaleLowerCase(); var item; /*for each*/for(var $each_item in array){ item=array[$each_item]; if (!item.isDirectory && String(item.label).toLowerCase().indexOf(key)>-1){ item.x=0; result.push(item); } if (item.child && item.child.length > 0){ this.getFilterSource(item.child,result,key); } } } /** *每一项之间的间隔距离(以像素为单位)。 */ __getset(0,__proto,'spaceBottom',function(){ return this._list.spaceY; },function(value){ this._list.spaceY=value; }); /** *数据源发生变化后,是否保持之前打开状态,默认为true。 *

    取值: *

  • true:保持之前打开状态。
  • *
  • false:不保持之前打开状态。
  • *

    */ __getset(0,__proto,'keepStatus',function(){ return this._keepStatus; },function(value){ this._keepStatus=value; }); /** *此对象包含的List实例的单元格渲染器。 *

    取值: *

      *
    1. 单元格类对象。
    2. *
    3. UI 的 JSON 描述。
    4. *

    */ __getset(0,__proto,'itemRender',function(){ return this._list.itemRender; },function(value){ this._list.itemRender=value; }); /** *列表数据源,只包含当前可视节点数据。 */ __getset(0,__proto,'array',function(){ return this._list.array; },function(value){ if (this._keepStatus && this._list.array && value){ this.parseOpenStatus(this._list.array,value); } this._source=value; this._list.array=this.getArray(); }); /** *单元格鼠标事件处理器。 *

    默认返回参数(e:Event,index:int)。

    */ __getset(0,__proto,'mouseHandler',function(){ return this._list.mouseHandler; },function(value){ this._list.mouseHandler=value; }); /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; Laya.superSet(Box,this,'dataSource',value); }); /** *数据源,全部节点数据。 */ __getset(0,__proto,'source',function(){ return this._source; }); /**滚动条*/ __getset(0,__proto,'scrollBar',function(){ return this._list.scrollBar; }); /** *此对象包含的List实例对象。 */ __getset(0,__proto,'list',function(){ return this._list; }); /** *滚动条皮肤。 */ __getset(0,__proto,'scrollBarSkin',function(){ return this._list.vScrollBarSkin; },function(value){ this._list.vScrollBarSkin=value; }); /** *Tree 实例的渲染处理器。 */ __getset(0,__proto,'renderHandler',function(){ return this._renderHandler; },function(value){ this._renderHandler=value; }); /** *表示当前选择的项索引。 */ __getset(0,__proto,'selectedIndex',function(){ return this._list.selectedIndex; },function(value){ this._list.selectedIndex=value; }); /** *左侧缩进距离(以像素为单位)。 */ __getset(0,__proto,'spaceLeft',function(){ return this._spaceLeft; },function(value){ this._spaceLeft=value; }); /** *当前选中的项对象的数据源。 */ __getset(0,__proto,'selectedItem',function(){ return this._list.selectedItem; },function(value){ this._list.selectedItem=value; }); /** *@inheritDoc */ __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(Box,this,'width',value); this._list.width=value; }); /**@inheritDoc */ __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Box,this,'height',value); this._list.height=value; }); /** *xml结构的数据源。 */ __getset(0,__proto,'xml',null,function(value){ var arr=[]; this.parseXml(value.childNodes[0],arr,null,true); this.array=arr; }); /** *表示选择的树节点项的path属性值。 */ __getset(0,__proto,'selectedPath',function(){ if (this._list.selectedItem){ return this._list.selectedItem.path; } return null; }); return Tree; })(Box) /** *ViewStack 类用于视图堆栈类,用于视图的显示等设置处理。 */ //class laya.ui.ViewStack extends laya.ui.Box var ViewStack=(function(_super){ function ViewStack(){ /**@private */ this._items=null; /**@private */ this._selectedIndex=0; ViewStack.__super.call(this); this._setIndexHandler=Handler.create(this,this.setIndex,null,false); } __class(ViewStack,'laya.ui.ViewStack',_super); var __proto=ViewStack.prototype; Laya.imps(__proto,{"laya.ui.IItem":true}) /** *批量设置视图对象。 *@param views 视图对象数组。 */ __proto.setItems=function(views){ this.removeChildren(); var index=0; for (var i=0,n=views.length;i < n;i++){ var item=views[i]; if (item){ item.name="item"+index; this.addChild(item); index++; } } this.initItems(); } /** *添加视图。 *@internal 添加视图对象,并设置此视图对象的name 属性。 *@param view 需要添加的视图对象。 */ __proto.addItem=function(view){ view.name="item"+this._items.length; this.addChild(view); this.initItems(); } /** *初始化视图对象集合。 */ __proto.initItems=function(){ this._items=[]; for (var i=0;i < 10000;i++){ var item=this.getChildByName("item"+i); if (item==null){ break ; } this._items.push(item); item.visible=(i==this._selectedIndex); } } /** *@private *通过对象的索引设置项对象的 selected 属性值。 *@param index 需要设置的对象的索引。 *@param selected 表示对象的选中状态。 */ __proto.setSelect=function(index,selected){ if (this._items && index >-1 && index < this._items.length){ this._items[index].visible=selected; } } /** *@private *设置属性selectedIndex的值。 *@param index 选中项索引值。 */ __proto.setIndex=function(index){ this.selectedIndex=index; } /**@inheritDoc */ __getset(0,__proto,'dataSource',_super.prototype._$get_dataSource,function(value){ this._dataSource=value; if (((typeof value=='number')&& Math.floor(value)==value)|| (typeof value=='string')){ this.selectedIndex=parseInt(value); }else { for (var prop in this._dataSource){ if (this.hasOwnProperty(prop)){ this[prop]=this._dataSource[prop]; } } } }); /** *表示当前视图索引。 */ __getset(0,__proto,'selectedIndex',function(){ return this._selectedIndex; },function(value){ if (this._selectedIndex !=value){ this.setSelect(this._selectedIndex,false); this._selectedIndex=value; this.setSelect(this._selectedIndex,true); } }); /** *获取或设置当前选择的项对象。 */ __getset(0,__proto,'selection',function(){ return this._selectedIndex >-1 && this._selectedIndex < this._items.length ? this._items[this._selectedIndex] :null; },function(value){ this.selectedIndex=this._items.indexOf(value); }); /** *视图集合数组。 */ __getset(0,__proto,'items',function(){ return this._items; }); /** *索引设置处理器。 *

    默认回调参数:index:int

    */ __getset(0,__proto,'setIndexHandler',function(){ return this._setIndexHandler; },function(value){ this._setIndexHandler=value; }); return ViewStack; })(Box) /** * *使用 VScrollBar (垂直 ScrollBar )控件,可以在因数据太多而不能在显示区域完全显示时控制显示的数据部分。 * *@example 以下示例代码,创建了一个 VScrollBar 实例。 *package *{ *import laya.ui.vScrollBar; *import laya.ui.VScrollBar; *import laya.utils.Handler; *public class VScrollBar_Example *{ *private var vScrollBar:VScrollBar; *public function VScrollBar_Example() *{ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/vscroll.png","resource/ui/vscroll$bar.png","resource/ui/vscroll$down.png","resource/ui/vscroll$up.png"],Handler.create(this,onLoadComplete)); *} *private function onLoadComplete():void *{ *vScrollBar=new VScrollBar();//创建一个 vScrollBar 类的实例对象 hScrollBar 。 *vScrollBar.skin="resource/ui/vscroll.png";//设置 vScrollBar 的皮肤。 *vScrollBar.x=100;//设置 vScrollBar 对象的属性 x 的值,用于控制 vScrollBar 对象的显示位置。 *vScrollBar.y=100;//设置 vScrollBar 对象的属性 y 的值,用于控制 vScrollBar 对象的显示位置。 *vScrollBar.changeHandler=new Handler(this,onChange);//设置 vScrollBar 的滚动变化处理器。 *Laya.stage.addChild(vScrollBar);//将此 vScrollBar 对象添加到显示列表。 *} *private function onChange(value:Number):void *{ *trace("滚动条的位置: value="+value); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *var vScrollBar; *var res=["resource/ui/vscroll.png","resource/ui/vscroll$bar.png","resource/ui/vscroll$down.png","resource/ui/vscroll$up.png"]; *Laya.loader.load(res,laya.utils.Handler.create(this,onLoadComplete));//加载资源。 *function onLoadComplete(){ *vScrollBar=new laya.ui.VScrollBar();//创建一个 vScrollBar 类的实例对象 hScrollBar 。 *vScrollBar.skin="resource/ui/vscroll.png";//设置 vScrollBar 的皮肤。 *vScrollBar.x=100;//设置 vScrollBar 对象的属性 x 的值,用于控制 vScrollBar 对象的显示位置。 *vScrollBar.y=100;//设置 vScrollBar 对象的属性 y 的值,用于控制 vScrollBar 对象的显示位置。 *vScrollBar.changeHandler=new laya.utils.Handler(this,onChange);//设置 vScrollBar 的滚动变化处理器。 *Laya.stage.addChild(vScrollBar);//将此 vScrollBar 对象添加到显示列表。 *} *function onChange(value){ *console.log("滚动条的位置: value="+value); *} *@example *import VScrollBar=laya.ui.VScrollBar; *import Handler=laya.utils.Handler; *class VScrollBar_Example { *private vScrollBar:VScrollBar; *constructor(){ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/vscroll.png","resource/ui/vscroll$bar.png","resource/ui/vscroll$down.png","resource/ui/vscroll$up.png"],Handler.create(this,this.onLoadComplete)); *} *private onLoadComplete():void { *this.vScrollBar=new VScrollBar();//创建一个 vScrollBar 类的实例对象 hScrollBar 。 *this.vScrollBar.skin="resource/ui/vscroll.png";//设置 vScrollBar 的皮肤。 *this.vScrollBar.x=100;//设置 vScrollBar 对象的属性 x 的值,用于控制 vScrollBar 对象的显示位置。 *this.vScrollBar.y=100;//设置 vScrollBar 对象的属性 y 的值,用于控制 vScrollBar 对象的显示位置。 *this.vScrollBar.changeHandler=new Handler(this,this.onChange);//设置 vScrollBar 的滚动变化处理器。 *Laya.stage.addChild(this.vScrollBar);//将此 vScrollBar 对象添加到显示列表。 *} *private onChange(value:number):void { *console.log("滚动条的位置: value="+value); *} *} */ //class laya.ui.VScrollBar extends laya.ui.ScrollBar var VScrollBar=(function(_super){ function VScrollBar(){ VScrollBar.__super.call(this);; } __class(VScrollBar,'laya.ui.VScrollBar',_super); return VScrollBar; })(ScrollBar) /** *TextInput 类用于创建显示对象以显示和输入文本。 * *@example 以下示例代码,创建了一个 TextInput 实例。 *package *{ *import laya.display.Stage; *import laya.ui.TextInput; *import laya.utils.Handler; *public class TextInput_Example *{ *public function TextInput_Example() *{ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/input.png"],Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *var textInput:TextInput=new TextInput("这是一个TextInput实例。");//创建一个 TextInput 类的实例对象 textInput 。 *textInput.skin="resource/ui/input.png";//设置 textInput 的皮肤。 *textInput.sizeGrid="4,4,4,4";//设置 textInput 的网格信息。 *textInput.color="#008fff";//设置 textInput 的文本颜色。 *textInput.font="Arial";//设置 textInput 的文本字体。 *textInput.bold=true;//设置 textInput 的文本显示为粗体。 *textInput.fontSize=30;//设置 textInput 的字体大小。 *textInput.wordWrap=true;//设置 textInput 的文本自动换行。 *textInput.x=100;//设置 textInput 对象的属性 x 的值,用于控制 textInput 对象的显示位置。 *textInput.y=100;//设置 textInput 对象的属性 y 的值,用于控制 textInput 对象的显示位置。 *textInput.width=300;//设置 textInput 的宽度。 *textInput.height=200;//设置 textInput 的高度。 *Laya.stage.addChild(textInput);//将 textInput 添加到显示列表。 *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *Laya.loader.load(["resource/ui/input.png"],laya.utils.Handler.create(this,onLoadComplete));//加载资源。 *function onLoadComplete(){ *var textInput=new laya.ui.TextInput("这是一个TextInput实例。");//创建一个 TextInput 类的实例对象 textInput 。 *textInput.skin="resource/ui/input.png";//设置 textInput 的皮肤。 *textInput.sizeGrid="4,4,4,4";//设置 textInput 的网格信息。 *textInput.color="#008fff";//设置 textInput 的文本颜色。 *textInput.font="Arial";//设置 textInput 的文本字体。 *textInput.bold=true;//设置 textInput 的文本显示为粗体。 *textInput.fontSize=30;//设置 textInput 的字体大小。 *textInput.wordWrap=true;//设置 textInput 的文本自动换行。 *textInput.x=100;//设置 textInput 对象的属性 x 的值,用于控制 textInput 对象的显示位置。 *textInput.y=100;//设置 textInput 对象的属性 y 的值,用于控制 textInput 对象的显示位置。 *textInput.width=300;//设置 textInput 的宽度。 *textInput.height=200;//设置 textInput 的高度。 *Laya.stage.addChild(textInput);//将 textInput 添加到显示列表。 *} *@example *import Stage=laya.display.Stage; *import TextInput=laya.ui.TextInput; *import Handler=laya.utils.Handler; *class TextInput_Example { *constructor(){ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/input.png"],Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *var textInput:TextInput=new TextInput("这是一个TextInput实例。");//创建一个 TextInput 类的实例对象 textInput 。 *textInput.skin="resource/ui/input.png";//设置 textInput 的皮肤。 *textInput.sizeGrid="4,4,4,4";//设置 textInput 的网格信息。 *textInput.color="#008fff";//设置 textInput 的文本颜色。 *textInput.font="Arial";//设置 textInput 的文本字体。 *textInput.bold=true;//设置 textInput 的文本显示为粗体。 *textInput.fontSize=30;//设置 textInput 的字体大小。 *textInput.wordWrap=true;//设置 textInput 的文本自动换行。 *textInput.x=100;//设置 textInput 对象的属性 x 的值,用于控制 textInput 对象的显示位置。 *textInput.y=100;//设置 textInput 对象的属性 y 的值,用于控制 textInput 对象的显示位置。 *textInput.width=300;//设置 textInput 的宽度。 *textInput.height=200;//设置 textInput 的高度。 *Laya.stage.addChild(textInput);//将 textInput 添加到显示列表。 *} *} */ //class laya.ui.TextInput extends laya.ui.Label var TextInput=(function(_super){ function TextInput(text){ /**@private */ this._bg=null; /**@private */ this._skin=null; TextInput.__super.call(this); (text===void 0)&& (text=""); this.text=text; this.skin=this.skin; } __class(TextInput,'laya.ui.TextInput',_super); var __proto=TextInput.prototype; /**@inheritDoc */ __proto.preinitialize=function(){ this.mouseEnabled=true; } /**@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._bg && this._bg.destroy(); this._bg=null; } /**@inheritDoc */ __proto.createChildren=function(){ this.addChild(this._tf=new Input()); this._tf.padding=Styles.inputLabelPadding; this._tf.on(/*laya.events.Event.INPUT*/"input",this,this._onInput); this._tf.on(/*laya.events.Event.ENTER*/"enter",this,this._onEnter); this._tf.on(/*laya.events.Event.BLUR*/"blur",this,this._onBlur); this._tf.on(/*laya.events.Event.FOCUS*/"focus",this,this._onFocus); } /** *@private */ __proto._onFocus=function(){ this.event(/*laya.events.Event.FOCUS*/"focus",this); } /** *@private */ __proto._onBlur=function(){ this.event(/*laya.events.Event.BLUR*/"blur",this); } /** *@private */ __proto._onInput=function(){ this.event(/*laya.events.Event.INPUT*/"input",this); } /** *@private */ __proto._onEnter=function(){ this.event(/*laya.events.Event.ENTER*/"enter",this); } /**@inheritDoc */ __proto.initialize=function(){ this.width=128; this.height=22; } /**选中输入框内的文本。*/ __proto.select=function(){ (this._tf).select(); } __proto.setSelection=function(startIndex,endIndex){ (this._tf).setSelection(startIndex,endIndex); } /** *当前文本内容字符串。 *@see laya.display.Text.text */ __getset(0,__proto,'text',_super.prototype._$get_text,function(value){ if (this._tf.text !=value){ value=value+""; this._tf.text=value; this.event(/*laya.events.Event.CHANGE*/"change"); } }); /** *表示此对象包含的文本背景 AutoBitmap 组件实例。 */ __getset(0,__proto,'bg',function(){ return this._bg; },function(value){ this.graphics=this._bg=value; }); /** *设置原生input输入框的y坐标偏移。 */ __getset(0,__proto,'inputElementYAdjuster',function(){ return (this._tf).inputElementYAdjuster; },function(value){ (this._tf).inputElementYAdjuster=value; }); /** *

    指示当前是否是文本域。

    *值为true表示当前是文本域,否则不是文本域。 */ __getset(0,__proto,'multiline',function(){ return (this._tf).multiline; },function(value){ (this._tf).multiline=value; }); /** *@copy laya.ui.Image#skin */ __getset(0,__proto,'skin',function(){ return this._skin; },function(value){ if (this._skin !=value){ this._skin=value; this._bg || (this.graphics=this._bg=new AutoBitmap()); this._bg.source=Loader.getRes(this._skin); this._width && (this._bg.width=this._width); this._height && (this._bg.height=this._height); } }); /** *

    当前实例的背景图( AutoBitmap )实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    *@see laya.ui.AutoBitmap.sizeGrid */ __getset(0,__proto,'sizeGrid',function(){ return this._bg && this._bg.sizeGrid ? this._bg.sizeGrid.join(","):null; },function(value){ this._bg || (this.graphics=this._bg=new AutoBitmap()); this._bg.sizeGrid=UIUtils.fillArray(Styles.defaultSizeGrid,value,Number); }); /** *设置原生input输入框的x坐标偏移。 */ __getset(0,__proto,'inputElementXAdjuster',function(){ return (this._tf).inputElementXAdjuster; },function(value){ (this._tf).inputElementXAdjuster=value; }); /**@inheritDoc */ __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(Label,this,'width',value); this._bg && (this._bg.width=value); }); /**@inheritDoc */ __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(Label,this,'height',value); this._bg && (this._bg.height=value); }); /** *设置可编辑状态。 */ __getset(0,__proto,'editable',function(){ return (this._tf).editable; },function(value){ (this._tf).editable=value; }); /**限制输入的字符。*/ __getset(0,__proto,'restrict',function(){ return (this._tf).restrict; },function(pattern){ (this._tf).restrict=pattern; }); /** *@copy laya.display.Input#prompt */ __getset(0,__proto,'prompt',function(){ return (this._tf).prompt; },function(value){ (this._tf).prompt=value; }); /** *@copy laya.display.Input#promptColor */ __getset(0,__proto,'promptColor',function(){ return (this._tf).promptColor; },function(value){ (this._tf).promptColor=value; }); /** *@copy laya.display.Input#maxChars */ __getset(0,__proto,'maxChars',function(){ return (this._tf).maxChars; },function(value){ (this._tf).maxChars=value; }); /** *@copy laya.display.Input#focus */ __getset(0,__proto,'focus',function(){ return (this._tf).focus; },function(value){ (this._tf).focus=value; }); /** *@copy laya.display.Input#type */ __getset(0,__proto,'type',function(){ return (this._tf).type; },function(value){ (this._tf).type=value; }); /** *@copy laya.display.Input#asPassword */ __getset(0,__proto,'asPassword',function(){ return (this._tf).asPassword; },function(value){ (this._tf).asPassword=value; }); return TextInput; })(Label) /** *使用 VSlider 控件,用户可以通过在滑块轨道的终点之间移动滑块来选择值。 *

    VSlider 控件采用垂直方向。滑块轨道从下往上扩展,而标签位于轨道的左右两侧。

    * *@example 以下示例代码,创建了一个 VSlider 实例。 *package *{ *import laya.ui.HSlider; *import laya.ui.VSlider; *import laya.utils.Handler; *public class VSlider_Example *{ *private var vSlider:VSlider; *public function VSlider_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/vslider.png","resource/ui/vslider$bar.png"],Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *vSlider=new VSlider();//创建一个 VSlider 类的实例对象 vSlider 。 *vSlider.skin="resource/ui/vslider.png";//设置 vSlider 的皮肤。 *vSlider.min=0;//设置 vSlider 最低位置值。 *vSlider.max=10;//设置 vSlider 最高位置值。 *vSlider.value=2;//设置 vSlider 当前位置值。 *vSlider.tick=1;//设置 vSlider 刻度值。 *vSlider.x=100;//设置 vSlider 对象的属性 x 的值,用于控制 vSlider 对象的显示位置。 *vSlider.y=100;//设置 vSlider 对象的属性 y 的值,用于控制 vSlider 对象的显示位置。 *vSlider.changeHandler=new Handler(this,onChange);//设置 vSlider 位置变化处理器。 *Laya.stage.addChild(vSlider);//把 vSlider 添加到显示列表。 *} *private function onChange(value:Number):void *{ *trace("滑块的位置: value="+value); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *var vSlider; *Laya.loader.load(["resource/ui/vslider.png","resource/ui/vslider$bar.png"],laya.utils.Handler.create(this,onLoadComplete));//加载资源。 *function onLoadComplete(){ *vSlider=new laya.ui.VSlider();//创建一个 VSlider 类的实例对象 vSlider 。 *vSlider.skin="resource/ui/vslider.png";//设置 vSlider 的皮肤。 *vSlider.min=0;//设置 vSlider 最低位置值。 *vSlider.max=10;//设置 vSlider 最高位置值。 *vSlider.value=2;//设置 vSlider 当前位置值。 *vSlider.tick=1;//设置 vSlider 刻度值。 *vSlider.x=100;//设置 vSlider 对象的属性 x 的值,用于控制 vSlider 对象的显示位置。 *vSlider.y=100;//设置 vSlider 对象的属性 y 的值,用于控制 vSlider 对象的显示位置。 *vSlider.changeHandler=new laya.utils.Handler(this,onChange);//设置 vSlider 位置变化处理器。 *Laya.stage.addChild(vSlider);//把 vSlider 添加到显示列表。 *} *function onChange(value){ *console.log("滑块的位置: value="+value); *} *@example *import HSlider=laya.ui.HSlider; *import VSlider=laya.ui.VSlider; *import Handler=laya.utils.Handler; *class VSlider_Example { *private vSlider:VSlider; *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/vslider.png","resource/ui/vslider$bar.png"],Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *this.vSlider=new VSlider();//创建一个 VSlider 类的实例对象 vSlider 。 *this.vSlider.skin="resource/ui/vslider.png";//设置 vSlider 的皮肤。 *this.vSlider.min=0;//设置 vSlider 最低位置值。 *this.vSlider.max=10;//设置 vSlider 最高位置值。 *this.vSlider.value=2;//设置 vSlider 当前位置值。 *this.vSlider.tick=1;//设置 vSlider 刻度值。 *this.vSlider.x=100;//设置 vSlider 对象的属性 x 的值,用于控制 vSlider 对象的显示位置。 *this.vSlider.y=100;//设置 vSlider 对象的属性 y 的值,用于控制 vSlider 对象的显示位置。 *this.vSlider.changeHandler=new Handler(this,this.onChange);//设置 vSlider 位置变化处理器。 *Laya.stage.addChild(this.vSlider);//把 vSlider 添加到显示列表。 *} *private onChange(value:number):void { *console.log("滑块的位置: value="+value); *} *} *@see laya.ui.Slider */ //class laya.ui.VSlider extends laya.ui.Slider var VSlider=(function(_super){ function VSlider(){ VSlider.__super.call(this);; } __class(VSlider,'laya.ui.VSlider',_super); return VSlider; })(Slider) /** *Dialog 组件是一个弹出对话框,实现对话框弹出,拖动,模式窗口功能。 *可以通过UIConfig设置弹出框背景透明度,模式窗口点击边缘是否关闭等 *通过设置zOrder属性,可以更改弹出的层次 *通过设置popupEffect和closeEffect可以设置弹出效果和关闭效果,如果不想有任何弹出关闭效果,可以设置前述属性为空 * *@example 以下示例代码,创建了一个 Dialog 实例。 *package *{ *import laya.ui.Dialog; *import laya.utils.Handler; *public class Dialog_Example *{ *private var dialog:Dialog_Instance; *public function Dialog_Example() *{ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/btn_close.png",Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *dialog=new Dialog_Instance();//创建一个 Dialog_Instance 类的实例对象 dialog。 *dialog.dragArea="0,0,150,50";//设置 dialog 的拖拽区域。 *dialog.show();//显示 dialog。 *dialog.closeHandler=new Handler(this,onClose);//设置 dialog 的关闭函数处理器。 *} *private function onClose(name:String):void *{ *if (name==Dialog.CLOSE) *{ *trace("通过点击 name 为"+name+"的组件,关闭了dialog。"); *} *} *} *} *import laya.ui.Button; *import laya.ui.Dialog; *import laya.ui.Image; *class Dialog_Instance extends Dialog *{ *function Dialog_Instance():void *{ *var bg:Image=new Image("resource/ui/bg.png"); *bg.sizeGrid="40,10,5,10"; *bg.width=150; *bg.height=250; *addChild(bg); *var image:Image=new Image("resource/ui/image.png"); *addChild(image); *var button:Button=new Button("resource/ui/btn_close.png"); *button.name=Dialog.CLOSE;//设置button的name属性值。 *button.x=0; *button.y=0; *addChild(button); *} *} *@example *Laya.init(640,800);//设置游戏画布宽高、渲染模式 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *var dialog; *Laya.loader.load("resource/ui/btn_close.png",laya.utils.Handler.create(this,loadComplete));//加载资源 *(function (_super){//新建一个类Dialog_Instance继承自laya.ui.Dialog。 *function Dialog_Instance(){ *Dialog_Instance.__super.call(this);//初始化父类 *var bg=new laya.ui.Image("resource/ui/bg.png");//新建一个 Image 类的实例 bg 。 *bg.sizeGrid="10,40,10,5";//设置 bg 的网格信息。 *bg.width=150;//设置 bg 的宽度。 *bg.height=250;//设置 bg 的高度。 *this.addChild(bg);//将 bg 添加到显示列表。 *var image=new laya.ui.Image("resource/ui/image.png");//新建一个 Image 类的实例 image 。 *this.addChild(image);//将 image 添加到显示列表。 *var button=new laya.ui.Button("resource/ui/btn_close.png");//新建一个 Button 类的实例 bg 。 *button.name=laya.ui.Dialog.CLOSE;//设置 button 的 name 属性值。 *button.x=0;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 *button.y=0;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 *this.addChild(button);//将 button 添加到显示列表。 *}; *Laya.class(Dialog_Instance,"mypackage.dialogExample.Dialog_Instance",_super);//注册类Dialog_Instance。 *})(laya.ui.Dialog); *function loadComplete(){ *console.log("资源加载完成!"); *dialog=new mypackage.dialogExample.Dialog_Instance();//创建一个 Dialog_Instance 类的实例对象 dialog。 *dialog.dragArea="0,0,150,50";//设置 dialog 的拖拽区域。 *dialog.show();//显示 dialog。 *dialog.closeHandler=new laya.utils.Handler(this,onClose);//设置 dialog 的关闭函数处理器。 *} *function onClose(name){ *if (name==laya.ui.Dialog.CLOSE){ *console.log("通过点击 name 为"+name+"的组件,关闭了dialog。"); *} *} *@example *import Dialog=laya.ui.Dialog; *import Handler=laya.utils.Handler; *class Dialog_Example { *private dialog:Dialog_Instance; *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load("resource/ui/btn_close.png",Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *this.dialog=new Dialog_Instance();//创建一个 Dialog_Instance 类的实例对象 dialog。 *this.dialog.dragArea="0,0,150,50";//设置 dialog 的拖拽区域。 *this.dialog.show();//显示 dialog。 *this.dialog.closeHandler=new Handler(this,this.onClose);//设置 dialog 的关闭函数处理器。 *} *private onClose(name:string):void { *if (name==Dialog.CLOSE){ *console.log("通过点击 name 为"+name+"的组件,关闭了dialog。"); *} *} *} *import Button=laya.ui.Button; *class Dialog_Instance extends Dialog { *Dialog_Instance():void { *var bg:laya.ui.Image=new laya.ui.Image("resource/ui/bg.png"); *bg.sizeGrid="40,10,5,10"; *bg.width=150; *bg.height=250; *this.addChild(bg); *var image:laya.ui.Image=new laya.ui.Image("resource/ui/image.png"); *this.addChild(image); *var button:Button=new Button("resource/ui/btn_close.png"); *button.name=Dialog.CLOSE;//设置button的name属性值。 *button.x=0; *button.y=0; *this.addChild(button); *} *} */ //class laya.ui.Dialog extends laya.ui.View var Dialog=(function(_super){ function Dialog(){ /** *一个布尔值,指定对话框是否居中弹。 *

    如果值为true,则居中弹出,否则,则根据对象坐标显示,默认为true。

    */ this.popupCenter=true; /** *对话框被关闭时会触发的回调函数处理器。 *

    回调函数参数为用户点击的按钮名字name:String。

    */ this.closeHandler=null; /** *弹出对话框效果,可以设置一个效果代替默认的弹出效果,如果不想有任何效果,可以赋值为null *全局默认弹出效果可以通过manager.popupEffect修改 */ this.popupEffect=null; /** *关闭对话框效果,可以设置一个效果代替默认的关闭效果,如果不想有任何效果,可以赋值为null *全局默认关闭效果可以通过manager.closeEffect修改 */ this.closeEffect=null; /**组名称*/ this.group=null; /**是否是模式窗口*/ this.isModal=false; /**@private */ this._dragArea=null; Dialog.__super.call(this); } __class(Dialog,'laya.ui.Dialog',_super); var __proto=Dialog.prototype; /**@inheritDoc */ __proto.initialize=function(){ this.popupEffect=Dialog.manager.popupEffectHandler; this.closeEffect=Dialog.manager.closeEffectHandler; this._dealDragArea(); this.on(/*laya.events.Event.CLICK*/"click",this,this._onClick); } /**@private */ __proto._dealDragArea=function(){ var dragTarget=this.getChildByName("drag"); if (dragTarget){ this.dragArea=dragTarget.x+","+dragTarget.y+","+dragTarget.width+","+dragTarget.height; dragTarget.removeSelf(); } } /** *@private (protected) *对象的 Event.CLICK 点击事件侦听处理函数。 */ __proto._onClick=function(e){ var btn=e.target; if (btn){ switch (btn.name){ case "close": case "cancel": case "sure": case "no": case "ok": case "yes": this.close(btn.name); break ; } } } /** *显示对话框(以非模式窗口方式显示)。 *@param closeOther 是否关闭其它的对话框。若值为true则关闭其它对话框。 *@param showEffect 是否显示弹出效果 */ __proto.show=function(closeOther,showEffect){ (closeOther===void 0)&& (closeOther=false); (showEffect===void 0)&& (showEffect=true); this._open(false,closeOther,showEffect); } /** *显示对话框(以模式窗口方式显示)。 *@param closeOther 是否关闭其它的对话框。若值为true则关闭其它对话框。 *@param showEffect 是否显示弹出效果 */ __proto.popup=function(closeOther,showEffect){ (closeOther===void 0)&& (closeOther=false); (showEffect===void 0)&& (showEffect=true); this._open(true,closeOther,showEffect); } /**@private */ __proto._open=function(modal,closeOther,showEffect){ Dialog.manager.lock(false); this.isModal=modal; Dialog.manager.open(this,closeOther,showEffect); } /**打开完成后,调用此方法(如果有弹出动画,则在动画完成后执行)*/ __proto.onOpened=function(){} /** *关闭对话框。 *@param type 如果是点击默认关闭按钮触发,则传入关闭按钮的名字(name),否则为null。 *@param showEffect 是否显示关闭效果 */ __proto.close=function(type,showEffect){ (showEffect===void 0)&& (showEffect=true); Dialog.manager.close(this,type,showEffect); } /**关闭完成后,调用此方法(如果有关闭动画,则在动画完成后执行) *@param type 如果是点击默认关闭按钮触发,则传入关闭按钮的名字(name),否则为null。 */ __proto.onClosed=function(type){} /**@private */ __proto._onMouseDown=function(e){ var point=this.getMousePoint(); if (this._dragArea.contains(point.x,point.y))this.startDrag(); else this.stopDrag(); } /** *用来指定对话框的拖拽区域。默认值为"0,0,0,0"。 *

    格式:构成一个矩形所需的 x,y,width,heith 值,用逗号连接为字符串。 *例如:"0,0,100,200"。 *

    * *@see #includeExamplesSummary 请参考示例 */ __getset(0,__proto,'dragArea',function(){ if (this._dragArea)return this._dragArea.toString(); return null; },function(value){ if (value){ var a=UIUtils.fillArray([0,0,0,0],value,Number); this._dragArea=new Rectangle(a[0],a[1],a[2],a[3]); this.on(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this._onMouseDown); }else { this._dragArea=null; this.off(/*laya.events.Event.MOUSE_DOWN*/"mousedown",this,this._onMouseDown); } }); /** *弹出框的显示状态;如果弹框处于显示中,则为true,否则为false; */ __getset(0,__proto,'isPopup',function(){ return this.parent !=null; }); __getset(0,__proto,'zOrder',_super.prototype._$get_zOrder,function(value){ Laya.superSet(View,this,'zOrder',value); Dialog.manager._checkMask(); }); /**对话框管理容器,所有的对话框都在该容器内,并且受管理器管,可以自定义自己的管理器,来更改窗口管理的流程。 *任意对话框打开和关闭,都会触发管理类的open和close事件*/ __getset(1,Dialog,'manager',function(){ return Dialog._manager=Dialog._manager|| new DialogManager(); },function(value){ Dialog._manager=value; }); Dialog.setLockView=function(view){ Dialog.manager.setLockView(view); } Dialog.lock=function(value){ Dialog.manager.lock(value); } Dialog.closeAll=function(){ Dialog.manager.closeAll(); } Dialog.getDialogsByGroup=function(group){ return Dialog.manager.getDialogsByGroup(group); } Dialog.closeByGroup=function(group){ return Dialog.manager.closeByGroup(group); } Dialog.CLOSE="close"; Dialog.CANCEL="cancel"; Dialog.SURE="sure"; Dialog.NO="no"; Dialog.OK="ok"; Dialog.YES="yes"; Dialog._manager=null; return Dialog; })(View) /** *HBox 是一个水平布局容器类。 */ //class laya.ui.HBox extends laya.ui.LayoutBox var HBox=(function(_super){ function HBox(){ HBox.__super.call(this);; } __class(HBox,'laya.ui.HBox',_super); var __proto=HBox.prototype; /**@inheritDoc */ __proto.sortItem=function(items){ if (items)items.sort(function(a,b){return a.x-b.x;}); } /**@inheritDoc */ __proto.changeItems=function(){ this._itemChanged=false; var items=[]; var maxHeight=0; for (var i=0,n=this.numChildren;i < n;i++){ var item=this.getChildAt(i); if (item&&item.layoutEnabled){ items.push(item); maxHeight=this._height?this._height:Math.max(maxHeight,item.height *item.scaleY); } } this.sortItem(items); var left=0; for (i=0,n=items.length;i < n;i++){ item=items[i]; item.x=left; left+=item.width *item.scaleX+this._space; if (this._align=="top"){ item.y=0; }else if (this._align=="middle"){ item.y=(maxHeight-item.height *item.scaleY)*0.5; }else if (this._align=="bottom"){ item.y=maxHeight-item.height *item.scaleY; } } this.changeSize(); } __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ if (this._height !=value){ Laya.superSet(LayoutBox,this,'height',value); this.callLater(this.changeItems); } }); HBox.NONE="none"; HBox.TOP="top"; HBox.MIDDLE="middle"; HBox.BOTTOM="bottom"; return HBox; })(LayoutBox) /** *游戏中心插件 *@author xiaosong *@date 2018-12-26 */ //class laya.ui.MoreGame extends laya.ui.View var MoreGame=(function(_super){ var GameBox,GameItem; function MoreGame(type){ /**是否停止缓动,默认晃动**/ this.gameStopHD=false; /**icon动画**/ this.iconImgTl=null; /**iconImage**/ this._iconImage=null; /**更多游戏容器**/ this._moreBox=null; /**游戏内盒子容器**/ this._gameBox=null; /**屏幕方向,默认0 横屏,1竖屏**/ this.screenType=0; /**更多游戏配置数据**/ this._moreGameDataUrl="https://abc.layabox.com/public/more/gamelist2.json"; /**图片尺寸设置信息**/ this._iconImageObj=null; /**图标点击回调**/ this.clickCallBack=null; /**关闭盒子回调**/ this.closeCallBack=null; /**是否在显示中**/ this.isShow=false; /**系统信息**/ this.dinfo=null; /**统计数据地址**/ this.ErrorUrlHttps="https://elastic.layabox.com/"; /**统计类型**/ this.tongjiType="bdm"; (type===void 0)&& (type=0); MoreGame.__super.call(this); this.screenType=type; this.init(); } __class(MoreGame,'laya.ui.MoreGame',_super); var __proto=MoreGame.prototype; /** *获取字符串时间戳,例如:2018-7-6 *@param _timestamp *@return * */ __proto.getLocalDateString=function(_timestamp){ (_timestamp===void 0)&& (_timestamp=0); var timeStr=this.getDateByTimestamp(_timestamp).toLocaleDateString(); if(Browser.onLimixiu || Browser.onMiniGame){ var date=new Date(); timeStr=MoreGame.toLocaleDateString(date.getTime()); }; var reg=new RegExp("/","g"); timeStr=timeStr.replace(reg,"-"); return timeStr; } __proto.getDateByTimestamp=function(_timestamp){ (_timestamp===void 0)&& (_timestamp=0); if (!_timestamp || _timestamp=="")return /*__JS__ */new Date(); return /*__JS__ */new Date(_timestamp); } /** *发送统计信息 *@param etype 统计数据类型 *@param errorInfo 报错信息 *@param pro 统计扩展数据 */ __proto.reportError=function(etype,errorInfo,pro){ (errorInfo===void 0)&& (errorInfo=""); pro=pro || {}; var now=/*__JS__ */Date.now(); var date=new Date(now+0); pro.date=date.toLocaleString(); pro.etype=etype; if (etype !="error"){ if (etype !="statistics"){ etype="statistics"; } } pro.version="V0.0.1"; pro.gameId=10100; pro.dinfo=this.dinfo; pro.channel=-1000; pro.msg=errorInfo; pro["@timestamp"]=/*__JS__ */date.toISOString(); pro.user=this.getUserId(); pro.openid=this.getOpenId(); var rdate=MoreGame.getDay(date); pro.rdate=rdate; pro.day=date.getDate()+""; pro.hour=date.getHours()+""; pro.minute=date.getMinutes()+""; pro.gameurl=/*__JS__ */document.baseURI; pro.regTime=0; if (etype=="error"){ this.sendLog(pro,this.tongjiType+"error-"+rdate.substring(0,6)+"/"+etype+"/",etype); }else{ this.sendLog(pro,this.tongjiType+"-"+rdate.substring(0,6)+"/"+etype+"/",etype); } } /**获取用户userid**/ __proto.getUserId=function(){ var userid=parseInt(LocalStorage.getItem("layauserid")+"")||-1; if(userid==-1){ userid=this.randRange(0,1000000000); LocalStorage.setItem("layauserid",userid+""); } return userid; } /**获取用户的openid**/ __proto.getOpenId=function(){ var str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var openId=LocalStorage.getItem("openid"); if(openId==null || openId==""){ openId=""; for(var i=0,sz=32;i gameList.length-1) return; var gameObj=gameList[index]; item.init(gameObj,this.screenType,new Handler(this,this.onItemClickCallBack)); } /** *单元点击回调 *@param itemData */ __proto.onItemClickCallBack=function(itemData){ var _$this=this; if(!/*__JS__ */swan.navigateToMiniProgram) return; var appKey=itemData.appKey; var path=itemData.path; var extendInfo=itemData.extendInfo; /*__JS__ */swan.navigateToMiniProgram({ appKey:appKey, path:path, extraData:extendInfo, success:function success (e){ }, fail:function fail (e){ }, complete:function complete (e){ _$this.reportError(itemData.statid); }.bind(this) }); } /**更多游戏返回按钮点击**/ __proto.onJiantouImgClick=function(type){ this.isShow=false; if(this._moreBox){ this._moreBox.visible=false; } this.closeCallBack !=null && this.closeCallBack.run(); } /** *创建文本 *@param str *@param parent *@param width *@param height *@param size *@param color *@param wordwarp *@param align *@param leading *@return */ __proto.onCreateLabel=function(str,parent,size,color,wordwarp,align,leading){ (size===void 0)&& (size=24); (color===void 0)&& (color="#000000"); (wordwarp===void 0)&& (wordwarp=false); (align===void 0)&& (align="center"); (leading===void 0)&& (leading=10); var label=new Label(); label.text=str; label.font="Microsoft YaHei"; label.fontSize=size; label.color=color; label.bold=true; label.leading=leading; label.valign="middle"; label.align=align; label.wordWrap=wordwarp; parent.addChild(label); return label; } /** *创建图片 *@param url *@param parent 图片的父容器 *@return */ __proto.onCreateImage=function(url,parent){ var image=new Image(); image.skin=url; parent.addChild(image); return image; } /**初始化判断当前是否显示插件**/ __proto.init=function(){ var userAgent=Browser.window.navigator.userAgent; var onBDMiniGame=userAgent.indexOf('SwanGame')>-1; this.visible=false; if(onBDMiniGame){ this.dinfo=JSON.stringify(/*__JS__ */laya.bd.mini.BMiniAdapter.systemInfo); this.onGetAdvsListData(); } } /** *生成指定范围的随机数 *@param minNum 最小值 *@param maxNum 最大值 */ __proto.randRange=function(minNum,maxNum){ return (Math.floor(Math.random()*(maxNum-minNum+1))+minNum); } /** *获取广告列表数据信息 */ __proto.onGetAdvsListData=function(){ var _this=this; var random=this.randRange(10000,1000000); var url=this._moreGameDataUrl+"?"+random; MoreGame._http.open("get",url,true); MoreGame._http.setRequestHeader("Content-Type","application/x-www-form-urlencoded") MoreGame._http.responseType="text"; MoreGame._http.onerror=function (e){ _this._onError(e); } MoreGame._http.onload=function (e){ _this._onLoad(e); } MoreGame._http.send(null); } /** *@private *请求出错侦的听处理函数。 *@param e 事件对象。 */ __proto._onError=function(e){ this.error("Request failed Status:"+MoreGame._http.status+" text:"+MoreGame._http.statusText); } /** *@private *请求消息返回的侦听处理函数。 *@param e 事件对象。 */ __proto._onLoad=function(e){ var http=MoreGame._http; var status=http.status!==undefined ? http.status :200; if (status===200 || status===204 || status===0){ this.complete(); }else { this.error("["+http.status+"]"+http.statusText+":"+http.responseURL); } } /** *@private *请求错误的处理函数。 *@param message 错误信息。 */ __proto.error=function(message){ this.event(/*laya.events.Event.ERROR*/"error",message); } /** *@private *请求成功完成的处理函数。 */ __proto.complete=function(){ var flag=true; try { var tempData=MoreGame._http.response || MoreGame._http.responseText; MoreGame._moreGameData=JSON.parse(tempData); this.initUI(); }catch (e){ flag=false; this.error(e.message); } } /**初始化UI显示**/ __proto.initUI=function(){ if(MoreGame._moreGameData.isOpen && this.screenType){ if(!this._iconImage){ this._iconImage=new Image(); this.addChild(this._iconImage); } this._iconImage.skin=MoreGame.onGetImgSkinUrl(MoreGame._moreGameData.icon); if(this._iconImageObj){ this._iconImage.size(this._iconImageObj.width,this._iconImageObj.height); this._iconImage.pivot(this._iconImageObj.width/2,this._iconImageObj.height/2); this._iconImage.pos(this._iconImageObj.width/2,this._iconImageObj.height/2); } this.visible=true; this.initEvent(); this.gameStopHD=false; this.checkIconImgHD(); }else{ this.visible=false; } } /** *设置icon的宽高尺寸 *@param width *@param height */ __proto.setIconSize=function(w,h){ if(this._iconImage){ this._iconImage.size(w,h); this._iconImage.pivot(w/2,h/2); this._iconImage.pos(w/2,h/2); } this._iconImageObj={width:w,height:h}; } MoreGame.toLocaleDateString=function(dateNum){ return MoreGame.getDateFormatStr(dateNum,"/"); } MoreGame.getDateFormatStr=function(stamp,formatStr){ (formatStr===void 0)&& (formatStr="yynndd"); var date=new Date(stamp); var yy=date.getFullYear(); var nn=date.getMonth()+1; var dd=date.getDate(); var hh=date.getHours(); var mm=date.getMinutes(); var ss=date.getSeconds(); switch(formatStr){ case "yynndd": return yy.toString()+"年"+nn.toString()+"月"+dd.toString()+"日"; break ; case "/": return yy.toString()+"/"+nn.toString()+"/"+dd.toString(); break ; } return yy.toString()+"年"+nn.toString()+"月"+dd.toString()+"日"+hh.toString()+"时"+mm.toString()+"分"+ss.toString()+"秒"; } MoreGame.getDay=function(sdate){ var month=sdate.getMonth()+1; var day=sdate.getDate(); var result=sdate.getFullYear()+""+(month < 10?"0"+month:month)+""+(day < 10?"0"+day:day); return result; } MoreGame.onGetAtlasDanImgUrl=function(url){ return MoreGame._moreGameData.imgPath+MoreGame._moreGameData.atlas+url+".png"; } MoreGame.onGetImgSkinUrl=function(resUrl){ return MoreGame._moreGameData.imgPath+resUrl; } MoreGame.onGetIconImgSkinUrl=function(resUrl){ return MoreGame._moreGameData.iconPath+resUrl; } MoreGame._moreGameData=null; __static(MoreGame, ['_http',function(){return this._http=new Browser.window.XMLHttpRequest();} ]); MoreGame.__init$=function(){ /** *有渲染游戏单元 *@author xiaosong *@date-2019-03-26 */ //class GameBox extends laya.ui.Box GameBox=(function(_super){ function GameBox(){ /**游戏类型**/ this.titleLabel=null; /**游戏列表容器**/ this.gameListBox=null; GameBox.__super.call(this); } __class(GameBox,'',_super); var __proto=GameBox.prototype; /** *初始化列表数据 *@param data */ __proto.init=function(data,screenType,callBack){ if(!this.titleLabel){ this.titleLabel=this.onCreateLabel(data.title,this,32,"#3d3939"); this.titleLabel.pos(8,0); this.titleLabel.size(162,50); }else{ this.titleLabel.text=data.title; } if(!this.gameListBox){ this.gameListBox=new Box(); this.addChild(this.gameListBox); var tempX=0; var tempY=65; var tempWidth=175; for(var i=0,sz=data.gameList.length;iVBox 是一个垂直布局容器类。 */ //class laya.ui.VBox extends laya.ui.LayoutBox var VBox=(function(_super){ function VBox(){ VBox.__super.call(this);; } __class(VBox,'laya.ui.VBox',_super); var __proto=VBox.prototype; /**@inheritDoc */ __proto.changeItems=function(){ this._itemChanged=false; var items=[]; var maxWidth=0; for (var i=0,n=this.numChildren;i < n;i++){ var item=this.getChildAt(i); if (item&&item.layoutEnabled){ items.push(item); maxWidth=this._width?this._width:Math.max(maxWidth,item.width *item.scaleX); } } this.sortItem(items); var top=0; for (i=0,n=items.length;i < n;i++){ item=items[i]; item.y=top; top+=item.height *item.scaleY+this._space; if (this._align=="left"){ item.x=0; }else if (this._align=="center"){ item.x=(maxWidth-item.width *item.scaleX)*0.5; }else if (this._align=="right"){ item.x=maxWidth-item.width *item.scaleX; } } this.changeSize(); } __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ if (this._width !=value){ Laya.superSet(LayoutBox,this,'width',value); this.callLater(this.changeItems); } }); VBox.NONE="none"; VBox.LEFT="left"; VBox.CENTER="center"; VBox.RIGHT="right"; return VBox; })(LayoutBox) /** *RadioGroup 控件定义一组 Radio 控件,这些控件相互排斥; *因此,用户每次只能选择一个 Radio 控件。 * *@example 以下示例代码,创建了一个 RadioGroup 实例。 *package *{ *import laya.ui.Radio; *import laya.ui.RadioGroup; *import laya.utils.Handler; *public class RadioGroup_Example *{ *public function RadioGroup_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/radio.png"],Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *var radioGroup:RadioGroup=new RadioGroup();//创建一个 RadioGroup 类的实例对象 radioGroup 。 *radioGroup.pos(100,100);//设置 radioGroup 的位置信息。 *radioGroup.labels="item0,item1,item2";//设置 radioGroup 的标签集。 *radioGroup.skin="resource/ui/radio.png";//设置 radioGroup 的皮肤。 *radioGroup.space=10;//设置 radioGroup 的项间隔距离。 *radioGroup.selectHandler=new Handler(this,onSelect);//设置 radioGroup 的选择项发生改变时执行的处理器。 *Laya.stage.addChild(radioGroup);//将 radioGroup 添加到显示列表。 *} *private function onSelect(index:int):void *{ *trace("当前选择的单选按钮索引: index= ",index); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高、渲染模式 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *Laya.loader.load(["resource/ui/radio.png"],laya.utils.Handler.create(this,onLoadComplete)); *function onLoadComplete(){ *var radioGroup=new laya.ui.RadioGroup();//创建一个 RadioGroup 类的实例对象 radioGroup 。 *radioGroup.pos(100,100);//设置 radioGroup 的位置信息。 *radioGroup.labels="item0,item1,item2";//设置 radioGroup 的标签集。 *radioGroup.skin="resource/ui/radio.png";//设置 radioGroup 的皮肤。 *radioGroup.space=10;//设置 radioGroup 的项间隔距离。 *radioGroup.selectHandler=new laya.utils.Handler(this,onSelect);//设置 radioGroup 的选择项发生改变时执行的处理器。 *Laya.stage.addChild(radioGroup);//将 radioGroup 添加到显示列表。 *} *function onSelect(index){ *console.log("当前选择的单选按钮索引: index= ",index); *} *@example *import Radio=laya.ui.Radio; *import RadioGroup=laya.ui.RadioGroup; *import Handler=laya.utils.Handler; *class RadioGroup_Example { *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/radio.png"],Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *var radioGroup:RadioGroup=new RadioGroup();//创建一个 RadioGroup 类的实例对象 radioGroup 。 *radioGroup.pos(100,100);//设置 radioGroup 的位置信息。 *radioGroup.labels="item0,item1,item2";//设置 radioGroup 的标签集。 *radioGroup.skin="resource/ui/radio.png";//设置 radioGroup 的皮肤。 *radioGroup.space=10;//设置 radioGroup 的项间隔距离。 *radioGroup.selectHandler=new Handler(this,this.onSelect);//设置 radioGroup 的选择项发生改变时执行的处理器。 *Laya.stage.addChild(radioGroup);//将 radioGroup 添加到显示列表。 *} *private onSelect(index:number):void { *console.log("当前选择的单选按钮索引: index= ",index); *} *} */ //class laya.ui.RadioGroup extends laya.ui.UIGroup var RadioGroup=(function(_super){ function RadioGroup(){ RadioGroup.__super.call(this);; } __class(RadioGroup,'laya.ui.RadioGroup',_super); var __proto=RadioGroup.prototype; /**@inheritDoc */ __proto.createItem=function(skin,label){ return new Radio(skin,label); } return RadioGroup; })(UIGroup) /** *Tab 组件用来定义选项卡按钮组。 * *@internal

    属性:selectedIndex 的默认值为-1。

    * *@example 以下示例代码,创建了一个 Tab 实例。 *package *{ *import laya.ui.Tab; *import laya.utils.Handler; *public class Tab_Example *{ *public function Tab_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/tab.png"],Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *var tab:Tab=new Tab();//创建一个 Tab 类的实例对象 tab 。 *tab.skin="resource/ui/tab.png";//设置 tab 的皮肤。 *tab.labels="item0,item1,item2";//设置 tab 的标签集。 *tab.x=100;//设置 tab 对象的属性 x 的值,用于控制 tab 对象的显示位置。 *tab.y=100;//设置 tab 对象的属性 y 的值,用于控制 tab 对象的显示位置。 *tab.selectHandler=new Handler(this,onSelect);//设置 tab 的选择项发生改变时执行的处理器。 *Laya.stage.addChild(tab);//将 tab 添到显示列表。 *} *private function onSelect(index:int):void *{ *trace("当前选择的表情页索引: index= ",index); *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *Laya.loader.load(["resource/ui/tab.png"],laya.utils.Handler.create(this,onLoadComplete)); *function onLoadComplete(){ *var tab=new laya.ui.Tab();//创建一个 Tab 类的实例对象 tab 。 *tab.skin="resource/ui/tab.png";//设置 tab 的皮肤。 *tab.labels="item0,item1,item2";//设置 tab 的标签集。 *tab.x=100;//设置 tab 对象的属性 x 的值,用于控制 tab 对象的显示位置。 *tab.y=100;//设置 tab 对象的属性 y 的值,用于控制 tab 对象的显示位置。 *tab.selectHandler=new laya.utils.Handler(this,onSelect);//设置 tab 的选择项发生改变时执行的处理器。 *Laya.stage.addChild(tab);//将 tab 添到显示列表。 *} *function onSelect(index){ *console.log("当前选择的标签页索引: index= ",index); *} *@example *import Tab=laya.ui.Tab; *import Handler=laya.utils.Handler; *class Tab_Example { *constructor(){ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/tab.png"],Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *var tab:Tab=new Tab();//创建一个 Tab 类的实例对象 tab 。 *tab.skin="resource/ui/tab.png";//设置 tab 的皮肤。 *tab.labels="item0,item1,item2";//设置 tab 的标签集。 *tab.x=100;//设置 tab 对象的属性 x 的值,用于控制 tab 对象的显示位置。 *tab.y=100;//设置 tab 对象的属性 y 的值,用于控制 tab 对象的显示位置。 *tab.selectHandler=new Handler(this,this.onSelect);//设置 tab 的选择项发生改变时执行的处理器。 *Laya.stage.addChild(tab);//将 tab 添到显示列表。 *} *private onSelect(index:number):void { *console.log("当前选择的表情页索引: index= ",index); *} *} */ //class laya.ui.Tab extends laya.ui.UIGroup var Tab=(function(_super){ function Tab(){ Tab.__super.call(this);; } __class(Tab,'laya.ui.Tab',_super); var __proto=Tab.prototype; /** *@private *@inheritDoc */ __proto.createItem=function(skin,label){ return new Button(skin,label); } return Tab; })(UIGroup) /** *TextArea 类用于创建显示对象以显示和输入文本。 *@example 以下示例代码,创建了一个 TextArea 实例。 *package *{ *import laya.ui.TextArea; *import laya.utils.Handler; *public class TextArea_Example *{ *public function TextArea_Example() *{ *Laya.init(640,800);//设置游戏画布宽高。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/input.png"],Handler.create(this,onLoadComplete));//加载资源。 *} *private function onLoadComplete():void *{ *var textArea:TextArea=new TextArea("这个一个TextArea实例。");//创建一个 TextArea 类的实例对象 textArea 。 *textArea.skin="resource/ui/input.png";//设置 textArea 的皮肤。 *textArea.sizeGrid="4,4,4,4";//设置 textArea 的网格信息。 *textArea.color="#008fff";//设置 textArea 的文本颜色。 *textArea.font="Arial";//设置 textArea 的字体。 *textArea.bold=true;//设置 textArea 的文本显示为粗体。 *textArea.fontSize=20;//设置 textArea 的文本字体大小。 *textArea.wordWrap=true;//设置 textArea 的文本自动换行。 *textArea.x=100;//设置 textArea 对象的属性 x 的值,用于控制 textArea 对象的显示位置。 *textArea.y=100;//设置 textArea 对象的属性 y 的值,用于控制 textArea 对象的显示位置。 *textArea.width=300;//设置 textArea 的宽度。 *textArea.height=200;//设置 textArea 的高度。 *Laya.stage.addChild(textArea);//将 textArea 添加到显示列表。 *} *} *} *@example *Laya.init(640,800);//设置游戏画布宽高、渲染模式 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色 *Laya.loader.load(["resource/ui/input.png"],laya.utils.Handler.create(this,onLoadComplete));//加载资源。 *function onLoadComplete(){ *var textArea=new laya.ui.TextArea("这个一个TextArea实例。");//创建一个 TextArea 类的实例对象 textArea 。 *textArea.skin="resource/ui/input.png";//设置 textArea 的皮肤。 *textArea.sizeGrid="4,4,4,4";//设置 textArea 的网格信息。 *textArea.color="#008fff";//设置 textArea 的文本颜色。 *textArea.font="Arial";//设置 textArea 的字体。 *textArea.bold=true;//设置 textArea 的文本显示为粗体。 *textArea.fontSize=20;//设置 textArea 的文本字体大小。 *textArea.wordWrap=true;//设置 textArea 的文本自动换行。 *textArea.x=100;//设置 textArea 对象的属性 x 的值,用于控制 textArea 对象的显示位置。 *textArea.y=100;//设置 textArea 对象的属性 y 的值,用于控制 textArea 对象的显示位置。 *textArea.width=300;//设置 textArea 的宽度。 *textArea.height=200;//设置 textArea 的高度。 *Laya.stage.addChild(textArea);//将 textArea 添加到显示列表。 *} *@example *import TextArea=laya.ui.TextArea; *import Handler=laya.utils.Handler; *class TextArea_Example { *constructor(){ *Laya.init(640,800);//设置游戏画布宽高、渲染模式。 *Laya.stage.bgColor="#efefef";//设置画布的背景颜色。 *Laya.loader.load(["resource/ui/input.png"],Handler.create(this,this.onLoadComplete));//加载资源。 *} *private onLoadComplete():void { *var textArea:TextArea=new TextArea("这个一个TextArea实例。");//创建一个 TextArea 类的实例对象 textArea 。 *textArea.skin="resource/ui/input.png";//设置 textArea 的皮肤。 *textArea.sizeGrid="4,4,4,4";//设置 textArea 的网格信息。 *textArea.color="#008fff";//设置 textArea 的文本颜色。 *textArea.font="Arial";//设置 textArea 的字体。 *textArea.bold=true;//设置 textArea 的文本显示为粗体。 *textArea.fontSize=20;//设置 textArea 的文本字体大小。 *textArea.wordWrap=true;//设置 textArea 的文本自动换行。 *textArea.x=100;//设置 textArea 对象的属性 x 的值,用于控制 textArea 对象的显示位置。 *textArea.y=100;//设置 textArea 对象的属性 y 的值,用于控制 textArea 对象的显示位置。 *textArea.width=300;//设置 textArea 的宽度。 *textArea.height=200;//设置 textArea 的高度。 *Laya.stage.addChild(textArea);//将 textArea 添加到显示列表。 *} *} */ //class laya.ui.TextArea extends laya.ui.TextInput var TextArea=(function(_super){ function TextArea(text){ /**@private */ this._vScrollBar=null; /**@private */ this._hScrollBar=null; (text===void 0)&& (text=""); TextArea.__super.call(this,text); } __class(TextArea,'laya.ui.TextArea',_super); var __proto=TextArea.prototype; __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._vScrollBar && this._vScrollBar.destroy(); this._hScrollBar && this._hScrollBar.destroy(); this._vScrollBar=null; this._hScrollBar=null; } __proto.initialize=function(){ this.width=180; this.height=150; this._tf.wordWrap=true; this.multiline=true; } __proto.onVBarChanged=function(e){ if (this._tf.scrollY !=this._vScrollBar.value){ this._tf.scrollY=this._vScrollBar.value; } } __proto.onHBarChanged=function(e){ if (this._tf.scrollX !=this._hScrollBar.value){ this._tf.scrollX=this._hScrollBar.value; } } __proto.changeScroll=function(){ var vShow=this._vScrollBar && this._tf.maxScrollY > 0; var hShow=this._hScrollBar && this._tf.maxScrollX > 0; var showWidth=vShow ? this._width-this._vScrollBar.width :this._width; var showHeight=hShow ? this._height-this._hScrollBar.height :this._height; var padding=this._tf.padding || Styles.labelPadding; this._tf.width=showWidth; this._tf.height=showHeight; if (this._vScrollBar){ this._vScrollBar.x=this._width-this._vScrollBar.width-padding[2]; this._vScrollBar.y=padding[1]; this._vScrollBar.height=this._height-(hShow ? this._hScrollBar.height :0)-padding[1]-padding[3]; this._vScrollBar.scrollSize=1; this._vScrollBar.thumbPercent=showHeight / Math.max(this._tf.textHeight,showHeight); this._vScrollBar.setScroll(1,this._tf.maxScrollY,this._tf.scrollY); this._vScrollBar.visible=vShow; } if (this._hScrollBar){ this._hScrollBar.x=padding[0]; this._hScrollBar.y=this._height-this._hScrollBar.height-padding[3]; this._hScrollBar.width=this._width-(vShow ? this._vScrollBar.width :0)-padding[0]-padding[2]; this._hScrollBar.scrollSize=Math.max(showWidth *0.033,1); this._hScrollBar.thumbPercent=showWidth / Math.max(this._tf.textWidth,showWidth); this._hScrollBar.setScroll(0,this.maxScrollX,this.scrollX); this._hScrollBar.visible=hShow; } } /**滚动到某个位置*/ __proto.scrollTo=function(y){ this.commitMeasure(); this._tf.scrollY=y; } /**垂直滚动值*/ __getset(0,__proto,'scrollY',function(){ return this._tf.scrollY; }); __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ Laya.superSet(TextInput,this,'width',value); this.callLater(this.changeScroll); }); /**水平滚动条实体*/ __getset(0,__proto,'hScrollBar',function(){ return this._hScrollBar; }); __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ Laya.superSet(TextInput,this,'height',value); this.callLater(this.changeScroll); }); /**水平滚动最大值*/ __getset(0,__proto,'maxScrollX',function(){ return this._tf.maxScrollX; }); /**垂直滚动条皮肤*/ __getset(0,__proto,'vScrollBarSkin',function(){ return this._vScrollBar ? this._vScrollBar.skin :null; },function(value){ if (this._vScrollBar==null){ this.addChild(this._vScrollBar=new VScrollBar()); this._vScrollBar.on(/*laya.events.Event.CHANGE*/"change",this,this.onVBarChanged); this._vScrollBar.target=this._tf; this.callLater(this.changeScroll); } this._vScrollBar.skin=value; }); /**水平滚动条皮肤*/ __getset(0,__proto,'hScrollBarSkin',function(){ return this._hScrollBar ? this._hScrollBar.skin :null; },function(value){ if (this._hScrollBar==null){ this.addChild(this._hScrollBar=new HScrollBar()); this._hScrollBar.on(/*laya.events.Event.CHANGE*/"change",this,this.onHBarChanged); this._hScrollBar.mouseWheelEnable=false; this._hScrollBar.target=this._tf; this.callLater(this.changeScroll); } this._hScrollBar.skin=value; }); /**垂直滚动条实体*/ __getset(0,__proto,'vScrollBar',function(){ return this._vScrollBar; }); /**垂直滚动最大值*/ __getset(0,__proto,'maxScrollY',function(){ return this._tf.maxScrollY; }); /**水平滚动值*/ __getset(0,__proto,'scrollX',function(){ return this._tf.scrollX; }); return TextArea; })(TextInput) /** *异步Dialog的生命周期:show或者popup > onCreate(如果没有创建过)> onOpen > onClose > onDestroy(如果销毁) *onCreate在页面未创建时执行一次,再次打开页面不会再执行,适合写一些只执行一次的逻辑,比如资源加载,节点事件监听 *onOpen在页面每次打开都会执行,适合做一些每次都需要处理的事情,比如消息请求,根据数据初始化页面 *onClose在每次关闭的时候调用,适合关闭时停止动画,网络消息监听等逻辑 *onDestroy在页面被销毁的时候调用,适合置空引用对象 */ //class laya.ui.AsynDialog extends laya.ui.Dialog var AsynDialog=(function(_super){ function AsynDialog(){ /**@private */ this._uiView=null; /**打开时是否关闭其他页面*/ this.isCloseOther=false; AsynDialog.__super.call(this); } __class(AsynDialog,'laya.ui.AsynDialog',_super); var __proto=AsynDialog.prototype; /**@private */ __proto.createView=function(uiView){ this._uiView=uiView; } __proto._open=function(modal,closeOther,showEffect){ this.isModal=modal; this.isCloseOther=closeOther; Dialog.manager.lock(true); if (this._uiView)this.onCreated(); else this.onOpen(); } /** *在页面未创建时执行一次,再次打开页面不会再执行,适合写一些只执行一次的逻辑,比如资源加载,节点事件监听 */ __proto.onCreated=function(){ this.createUI(); this.onOpen(); } /**根据节点数据创建UI*/ __proto.createUI=function(){ laya.ui.View.prototype.createView.call(this,this._uiView); this._uiView=null; this._dealDragArea(); } /** *在页面每次打开都会执行,适合做一些每次都需要处理的事情,比如消息请求,根据数据初始化页面 */ __proto.onOpen=function(){ Dialog.manager.open(this,this.isCloseOther); Dialog.manager.lock(false); } __proto.close=function(type,showEffect){ (showEffect===void 0)&& (showEffect=true); Dialog.manager.close(this); this.onClose(); } /** *在每次关闭的时候调用,适合关闭时停止动画,网络消息监听等逻辑 */ __proto.onClose=function(){} __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); laya.ui.View.prototype.destroy.call(this,destroyChild); this._uiView=null; this.onDestroy(); } /** *在页面被销毁的时候调用,适合置空引用对象 */ __proto.onDestroy=function(){} return AsynDialog; })(Dialog) Laya.__init([View,MoreGame]); })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.vvmini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Config=Laya.Config,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,RunDriver=laya.utils.RunDriver; var SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager,URL=laya.net.URL,Utils=laya.utils.Utils; /**@private **/ //class laya.vv.mini.MiniFileMgr var MiniFileMgr$4=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.vv.mini.MiniFileMgr',null,'MiniFileMgr$4'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=VVMiniAdapter.nativefiles.length;i=totalSize)){ if(data.size > VVMiniAdapter.minClearSize) VVMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if(data.length) data.size=data.length; if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > VVMiniAdapter.minClearSize) VVMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=VVMiniAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.vv.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i *
  • 1.0 正常速度
  • *
  • 0.5 半速(更慢)
  • *
  • 2.0 倍速(更快)
  • *
  • -1.0 向后,正常速度
  • *
  • -0.5 向后,半速
  • * *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ if(!this.videoElement) return 0; return this.videoElement.playbackRate; },function(value){ if(!this.videoElement) return; this.videoElement.playbackRate=value; }); __getset(0,__proto,'x',function(){ if(!this.videoElement) return 0; return this.videoElement.x; },function(value){ if(!this.videoElement) return; this.videoElement.x=value; }); __getset(0,__proto,'y',function(){ if(!this.videoElement) return 0; return this.videoElement.y; },function(value){ if(!this.videoElement) return; this.videoElement.y=value; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.src; }); MiniVideo.__init__=function(){ /*__JS__ */laya.device.media.Video=MiniVideo; } return MiniVideo; })() //class laya.vv.mini.VVMiniAdapter var VVMiniAdapter=(function(){ function VVMiniAdapter(){} __class(VVMiniAdapter,'laya.vv.mini.VVMiniAdapter'); VVMiniAdapter.getJson=function(data){ return JSON.parse(data); } VVMiniAdapter.init=function(isPosMsg,isSon){ (isPosMsg===void 0)&& (isPosMsg=false); (isSon===void 0)&& (isSon=false); if (VVMiniAdapter._inited)return; VVMiniAdapter._inited=true; VVMiniAdapter.window=/*__JS__ */window; if(!VVMiniAdapter.window.hasOwnProperty("qg")) return; if(VVMiniAdapter.window.navigator.userAgent.indexOf('VVGame')<0)return; VVMiniAdapter.isZiYu=isSon; VVMiniAdapter.isPosMsgYu=isPosMsg; VVMiniAdapter.EnvConfig={}; try{ /*__JS__ */laya.webgl.resource.WebGLCanvas.premulAlpha=true; }catch(e){ } if(!laya.vv.mini.VVMiniAdapter.window.qg.env){ laya.vv.mini.VVMiniAdapter.window.qg.env={}; laya.vv.mini.VVMiniAdapter.window.qg.env.USER_DATA_PATH="internal://files"; } if(!VVMiniAdapter.isZiYu){ MiniFileMgr$4.setNativeFileDir("/layaairGame"); MiniFileMgr$4.existDir(MiniFileMgr$4.fileNativeDir,Handler.create(VVMiniAdapter,VVMiniAdapter.onMkdirCallBack)); } VVMiniAdapter.systemInfo=VVMiniAdapter.window.qg.getSystemInfoSync(); VVMiniAdapter.window.focus=function (){ }; Laya['_getUrlPath']=function (){ }; Laya['getUrlPath']=function (){ }; VVMiniAdapter.window.logtime=function (str){ }; VVMiniAdapter.window.alertTimeLog=function (str){ }; VVMiniAdapter.window.resetShareInfo=function (){ }; VVMiniAdapter.window.CanvasRenderingContext2D=function (){ }; VVMiniAdapter.window.CanvasRenderingContext2D.prototype=VVMiniAdapter.window.qg.createCanvas().getContext('2d').__proto__; VVMiniAdapter.window.document.body.appendChild=function (){ }; VVMiniAdapter.EnvConfig.pixelRatioInt=0; RunDriver.getPixelRatio=VVMiniAdapter.pixelRatio; VVMiniAdapter._preCreateElement=Browser.createElement; Browser["createElement"]=VVMiniAdapter.createElement; RunDriver.createShaderCondition=VVMiniAdapter.createShaderCondition; Utils['parseXMLFromString']=VVMiniAdapter.parseXMLFromString; Input['_createInputElement']=MiniInput$4['_createInputElement']; VVMiniAdapter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader$4.prototype.load; Loader.prototype._loadImage=MiniImage$4.prototype._loadImage; VVMiniAdapter.onReciveData(); Config.useRetinalCanvas=true; Config.CborderSize=0; } VVMiniAdapter.onReciveData=function(){ if(laya.vv.mini.VVMiniAdapter.isZiYu && VVMiniAdapter.window.qg.onMessage){ VVMiniAdapter.window.qg.onMessage(function(message){ if(message['isLoad']=="opendatacontext"){ if(message.url){ MiniFileMgr$4.ziyuFileData[message.url]=message.atlasdata; MiniFileMgr$4.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }else if(message['isLoad']=="openJsondatacontext"){ if(message.url){ MiniFileMgr$4.ziyuFileData[message.url]=message.atlasdata; } }else if(message['isLoad']=="openJsondatacontextPic"){ MiniFileMgr$4.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }); } } VVMiniAdapter.measureText=function(str){ var tempObj=VVMiniAdapter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } VVMiniAdapter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return "binary"; return "utf8"; } VVMiniAdapter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr$4.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr$4.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } VVMiniAdapter.remove=function(fileUrl,callBack){ MiniFileMgr$4.deleteFile("",fileUrl,callBack,"",0); } VVMiniAdapter.removeAll=function(){ MiniFileMgr$4.deleteAll(); } VVMiniAdapter.hasNativeFile=function(fileUrl){ return MiniFileMgr$4.isLocalNativeFile(fileUrl); } VVMiniAdapter.getFileInfo=function(fileUrl){ return MiniFileMgr$4.getFileInfo(fileUrl); } VVMiniAdapter.getFileList=function(){ return MiniFileMgr$4.filesListObj; } VVMiniAdapter.exitMiniProgram=function(){ VVMiniAdapter.window.qg.exitMiniProgram(); } VVMiniAdapter.onMkdirCallBack=function(errorCode,data){ if (!errorCode) MiniFileMgr$4.filesListObj=JSON.parse(data.data); } VVMiniAdapter.pixelRatio=function(){ if (!VVMiniAdapter.EnvConfig.pixelRatioInt){ try { VVMiniAdapter.systemInfo.pixelRatio=VVMiniAdapter.window.devicePixelRatio; VVMiniAdapter.EnvConfig.pixelRatioInt=VVMiniAdapter.systemInfo.pixelRatio; return VVMiniAdapter.systemInfo.pixelRatio; }catch (error){} } return VVMiniAdapter.EnvConfig.pixelRatioInt; } VVMiniAdapter.createElement=function(type){ if (type=="canvas"){ var _source; if (VVMiniAdapter.idx==1){ if(VVMiniAdapter.isZiYu){ _source={}; _source.style={}; }else{ _source=/*__JS__ */document.getElementById("canvas"); } }else { _source=VVMiniAdapter.window.qg.createCanvas(); } VVMiniAdapter.idx++; return _source; }else if (type=="textarea" || type=="input"){ return VVMiniAdapter.onCreateInput(type); }else if (type=="div"){ var node=VVMiniAdapter._preCreateElement(type); node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } else { return VVMiniAdapter._preCreateElement(type); } } VVMiniAdapter.onCreateInput=function(type){ var node=VVMiniAdapter._preCreateElement(type); node.focus=MiniInput$4.wxinputFocus; node.blur=MiniInput$4.wxinputblur; node.style={}; node.value=0; node.parentElement={}; node.placeholder={}; node.type={}; node.setColor=function (value){ }; node.setType=function (value){ }; node.setFontFace=function (value){ }; node.addEventListener=function (value){ }; node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } VVMiniAdapter.createShaderCondition=function(conditionScript){ var _$this=this; var func=function (){ var abc=conditionScript; return _$this[conditionScript.replace("this.","")]; } return func; } VVMiniAdapter.sendAtlasToOpenDataContext=function(url){ if(!laya.vv.mini.VVMiniAdapter.isZiYu){ var atlasJson=Loader.getRes(URL.formatURL(url)); if(atlasJson){ var textureArr=(atlasJson.meta.image).split(","); if (atlasJson.meta && atlasJson.meta.image){ var toloadPics=atlasJson.meta.image.split(","); var split=url.indexOf("/")>=0 ? "/" :"\\"; var idx=url.lastIndexOf(split); var folderPath=idx >=0 ? url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[url.replace(".json",".png")]; } for(i=0;i\s+<'); try { /*__JS__ */rst=(new window.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } VVMiniAdapter.idx=1; __static(VVMiniAdapter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir","files"];} ]); return VVMiniAdapter; })() /**@private **/ //class laya.vv.mini.MiniAccelerator extends laya.events.EventDispatcher var MiniAccelerator$4=(function(_super){ function MiniAccelerator(){ MiniAccelerator.__super.call(this); } __class(MiniAccelerator,'laya.vv.mini.MiniAccelerator',_super,'MiniAccelerator$4'); var __proto=MiniAccelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); MiniAccelerator.startListen(this["onAccelerometerChange"]); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) MiniAccelerator.stopListen(); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } MiniAccelerator.__init__=function(){ try{ var Acc; Acc=/*__JS__ */laya.device.motion.Accelerator; if (!Acc)return; Acc["prototype"]["on"]=MiniAccelerator["prototype"]["on"]; Acc["prototype"]["off"]=MiniAccelerator["prototype"]["off"]; }catch (e){ } } MiniAccelerator.startListen=function(callBack){ MiniAccelerator._callBack=callBack; if (MiniAccelerator._isListening)return; MiniAccelerator._isListening=true; try{ VVMiniAdapter.window.qg.subscribeAccelerometer(laya.vv.mini.MiniAccelerator.onAccelerometerChange); }catch(e){} } MiniAccelerator.stopListen=function(){ MiniAccelerator._isListening=false; try{ VVMiniAdapter.window.qg.unsubscribeAccelerometer(); }catch(e){} } MiniAccelerator.onAccelerometerChange=function(res){ var e; e={}; e.acceleration=res; e.accelerationIncludingGravity=res; e.rotationRate={}; if (MiniAccelerator._callBack !=null){ MiniAccelerator._callBack(e); } } MiniAccelerator._isListening=false; MiniAccelerator._callBack=null; return MiniAccelerator; })(EventDispatcher) /**@private **/ //class laya.vv.mini.MiniLoader extends laya.events.EventDispatcher var MiniLoader$4=(function(_super){ function MiniLoader(){ MiniLoader.__super.call(this); } __class(MiniLoader,'laya.vv.mini.MiniLoader',_super,'MiniLoader$4'); var __proto=MiniLoader.prototype; /** *@private *@param url *@param type *@param cache *@param group *@param ignoreCache */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); var thisLoader=this; thisLoader._url=url; if (url.indexOf("data:image")===0)thisLoader._type=type=/*laya.net.Loader.IMAGE*/"image"; else { thisLoader._type=type || (type=thisLoader.getTypeFromUrl(url)); } thisLoader._cache=cache; thisLoader._data=null; if (!ignoreCache && Loader.loadedMap[URL.formatURL(url)]){ thisLoader._data=Loader.loadedMap[URL.formatURL(url)]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",thisLoader._data); return; } if (Loader.parserMap[type] !=null){ thisLoader._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; }; var encoding=VVMiniAdapter.getUrlEncode(url,type); var urlType=Utils.getFileExtension(url); if ((MiniLoader._fileTypeArr.indexOf(urlType)!=-1)|| type==/*laya.net.Loader.IMAGE*/"image"){ VVMiniAdapter.EnvConfig.load.call(this,url,type,cache,group,ignoreCache); }else { if(VVMiniAdapter.isZiYu && !MiniFileMgr$4.ziyuFileData[url]){ url=URL.formatURL(url); } if(VVMiniAdapter.isZiYu && MiniFileMgr$4.ziyuFileData[url]){ var tempData=MiniFileMgr$4.ziyuFileData[url]; thisLoader.onLoaded(tempData); return; } if (!MiniFileMgr$4.getFileInfo(URL.formatURL(url))){ if (MiniFileMgr$4.isLocalNativeFile(url)){ if (VVMiniAdapter.subNativeFiles && VVMiniAdapter.subNativeheads.length==0){ for (var key in VVMiniAdapter.subNativeFiles){ var tempArr=VVMiniAdapter.subNativeFiles[key]; VVMiniAdapter.subNativeheads=VVMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ VVMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(VVMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && VVMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=VVMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } MiniFileMgr$4.read(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); return; }; var tempUrl=url; var tempurl=URL.formatURL(url); if (tempurl.indexOf(VVMiniAdapter.window.qg.env.USER_DATA_PATH)==-1 &&(url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)&& !VVMiniAdapter.AutoCacheDownFile){ VVMiniAdapter.EnvConfig.load.call(thisLoader,tempUrl,type,cache,group,ignoreCache); }else { fileObj=MiniFileMgr$4.getFileInfo(url); if(fileObj){ fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; MiniFileMgr$4.readFile(fileObj.url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else if (thisLoader.type=="image" || thisLoader.type=="htmlimage"){ VVMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } else{ url=URL.formatURL(url); if(type !=/*laya.net.Loader.IMAGE*/"image" && ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1)|| MiniFileMgr$4.isLocalNativeFile(url))){ MiniFileMgr$4.readFile(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else{ MiniFileMgr$4.downFiles(encodeURI(url),encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url,true); } } } }else { var fileObj=MiniFileMgr$4.getFileInfo(URL.formatURL(url)); fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; var nativepath=MiniFileMgr$4.getFileNativePath(fileObj.md5); MiniFileMgr$4.readFile(nativepath,fileObj.encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),URL.formatURL(url)); } } } MiniLoader.onReadNativeCallBack=function(encoding,url,type,cache,group,ignoreCache,thisLoader,errorCode,data){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); (errorCode===void 0)&& (errorCode=0); if (!errorCode){ var tempData; if (type==/*laya.net.Loader.JSON*/"json" || type==/*laya.net.Loader.ATLAS*/"atlas"){ tempData=VVMiniAdapter.getJson(data.data); }else if (type==/*laya.net.Loader.XML*/"xml"){ tempData=Utils.parseXMLFromString(data.data); }else { tempData=data.data; } if(!VVMiniAdapter.isZiYu &&VVMiniAdapter.isPosMsgYu && type !=/*laya.net.Loader.BUFFER*/"arraybuffer" && VVMiniAdapter.window.qg.postMessage){ VVMiniAdapter.window.qg.postMessage({url:url,data:tempData,isLoad:"filedata"}); } thisLoader.onLoaded(tempData); }else if (errorCode==1){ console.log("-----------本地加载失败,尝试外网加载----"); VVMiniAdapter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } } __static(MiniLoader, ['_fileTypeArr',function(){return this._fileTypeArr=['png','jpg','bmp','jpeg','gif'];} ]); return MiniLoader; })(EventDispatcher) /**@private **/ //class laya.vv.mini.MiniSound extends laya.events.EventDispatcher var MiniSound$4=(function(_super){ function MiniSound(){ /**@private **/ this._sound=null; /** *@private *声音URL */ this.url=null; /** *@private *是否已加载完成 */ this.loaded=false; /**@private **/ this.readyUrl=null; MiniSound.__super.call(this); } __class(MiniSound,'laya.vv.mini.MiniSound',_super,'MiniSound$4'); var __proto=MiniSound.prototype; /** *@private *加载声音。 *@param url 地址。 * */ __proto.load=function(url){ if (!MiniFileMgr$4.isLocalNativeFile(url)){ url=URL.formatURL(url); }else{ if (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1){ if(MiniFileMgr$4.loadPath !=""){ url=url.split(MiniFileMgr$4.loadPath)[1]; }else{ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; if(tempStr !="") url=url.split(tempStr)[1]; } } } this.url=url; this.readyUrl=url; if (MiniSound._audioCache[this.readyUrl]){ this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if(VVMiniAdapter.autoCacheFile&&MiniFileMgr$4.getFileInfo(url)){ this.onDownLoadCallBack(url,0); }else{ if(!VVMiniAdapter.autoCacheFile){ this.onDownLoadCallBack(url,0); }else{ if (MiniFileMgr$4.isLocalNativeFile(url)){ tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="") url=url.split(tempStr)[1]; if (!url){ url=tempUrl; } if (VVMiniAdapter.subNativeFiles && VVMiniAdapter.subNativeheads.length==0){ for (var key in VVMiniAdapter.subNativeFiles){ var tempArr=VVMiniAdapter.subNativeFiles[key]; VVMiniAdapter.subNativeheads=VVMiniAdapter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ VVMiniAdapter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(VVMiniAdapter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && VVMiniAdapter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=VVMiniAdapter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } this.onDownLoadCallBack(url,0); }else{ if (!MiniFileMgr$4.isLocalNativeFile(url)&& (url.indexOf("http://")==-1 && url.indexOf("https://")==-1)|| (url.indexOf("http://usr/")!=-1)){ this.onDownLoadCallBack(url,0); }else{ MiniFileMgr$4.downOtherFiles(encodeURI(url),Handler.create(this,this.onDownLoadCallBack,[url]),url); } } } } } /**@private **/ __proto.onDownLoadCallBack=function(sourceUrl,errorCode,tempFilePath){ if (!errorCode){ var fileNativeUrl; if(VVMiniAdapter.autoCacheFile){ if(!tempFilePath){ if (MiniFileMgr$4.isLocalNativeFile(sourceUrl)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL._basePath; var tempUrl=sourceUrl; if(tempStr !="" && (sourceUrl.indexOf("http://")!=-1 || sourceUrl.indexOf("https://")!=-1)) fileNativeUrl=sourceUrl.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } }else{ var fileObj=MiniFileMgr$4.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr$4.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=sourceUrl; } } }else{ fileNativeUrl=tempFilePath; } this._sound=MiniSound._createSound(); this._sound.src=this.url=fileNativeUrl; }else{ this._sound=MiniSound._createSound(); this._sound.src=sourceUrl; } if(this._sound.onCanplay){ this._sound.onCanplay(MiniSound.bindToThis(this.onCanPlay,this)); this._sound.onError(MiniSound.bindToThis(this.onError,this)); }else{ Laya.timer.clear(this,this.onCheckComplete); Laya.timer.frameLoop(2,this,this.onCheckComplete); } }else{ this.event(/*laya.events.Event.ERROR*/"error"); } } __proto.onCheckComplete=function(){ if(this._sound && this._sound.duration > 0){ this.onCanPlay(); } Laya.timer.clear(this,this.onCheckComplete); } /**@private **/ __proto.onError=function(error){ try{ console.log("-----1---------------minisound-----id:"+MiniSound._id); console.log(error); } catch(error){ console.log("-----2---------------minisound-----id:"+MiniSound._id); console.log(error); } this.event(/*laya.events.Event.ERROR*/"error"); if(this._sound.offError){ this._sound.offError(null); } } /**@private **/ __proto.onCanPlay=function(){ this.loaded=true; this.event(/*laya.events.Event.COMPLETE*/"complete"); if(this._sound.offCanplay){ this._sound.offCanplay(null); } } /** *@private *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); var tSound; if (this.url==SoundManager._tMusic){ if (!MiniSound._musicAudio)MiniSound._musicAudio=MiniSound._createSound(); tSound=MiniSound._musicAudio; }else { if(MiniSound._audioCache[this.readyUrl]){ tSound=MiniSound._audioCache[this.readyUrl]._sound; }else{ tSound=MiniSound._createSound(); } } if(VVMiniAdapter.autoCacheFile&&MiniFileMgr$4.getFileInfo(this.url)){ var fileNativeUrl; var fileObj=MiniFileMgr$4.getFileInfo(this.url); var fileMd5Name=fileObj.md5; tSound.src=this.url=MiniFileMgr$4.getFileNativePath(fileMd5Name); }else{ tSound.src=this.url; }; var channel=new MiniSoundChannel$4(tSound,this); channel.url=this.url; channel.loops=loops; channel.loop=(loops===0 ? true :false); channel.startTime=startTime; channel.play(); SoundManager.addChannel(channel); return channel; } /** *@private *释放声音资源。 * */ __proto.dispose=function(){ var ad=MiniSound._audioCache[this.readyUrl]; if (ad){ ad.src=""; if(ad._sound){ ad._sound.destroy(); ad._sound=null; ad=null; } delete MiniSound._audioCache[this.readyUrl]; } } /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ return this._sound.duration; }); MiniSound._createSound=function(){ MiniSound._id++; return VVMiniAdapter.window.qg.createInnerAudioContext(); } MiniSound.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } MiniSound._musicAudio=null; MiniSound._id=0; MiniSound._audioCache={}; return MiniSound; })(EventDispatcher) /**@private **/ //class laya.vv.mini.MiniSoundChannel extends laya.media.SoundChannel var MiniSoundChannel$4=(function(_super){ function MiniSoundChannel(audio,miniSound){ /**@private **/ this._audio=null; /**@private **/ this._onEnd=null; /**@private **/ this._miniSound=null; MiniSoundChannel.__super.call(this); this._audio=audio; this._miniSound=miniSound; this._onEnd=MiniSoundChannel.bindToThis(this.__onEnd,this); audio.onEnded(this._onEnd); } __class(MiniSoundChannel,'laya.vv.mini.MiniSoundChannel',_super,'MiniSoundChannel$4'); var __proto=MiniSoundChannel.prototype; /**@private **/ __proto.__onEnd=function(){ MiniSound$4._audioCache[this.url]=this._miniSound; if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.stop(); this._audio.offEnded(null); this._miniSound.dispose(); this._audio=null; this._miniSound=null; this._onEnd=null; } /**@private **/ __proto.pause=function(){ this.isStopped=true; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',null,function(time){ if(this._audio){ this._audio.startTime=time; } }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ return this._audio.autoplay; },function(value){ this._audio.autoplay=value; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ return this._audio.loop; },function(value){ this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.webgl.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Arith=laya.maths.Arith,Bezier=laya.maths.Bezier,Bitmap=laya.resource.Bitmap,Browser=laya.utils.Browser; var Byte=laya.utils.Byte,Color=laya.utils.Color,ColorFilter=laya.filters.ColorFilter,Config=Laya.Config,Context=laya.resource.Context; var Event=laya.events.Event,Filter=laya.filters.Filter,Graphics=laya.display.Graphics,HTMLCanvas=laya.resource.HTMLCanvas; var HTMLChar=laya.utils.HTMLChar,HTMLImage=laya.resource.HTMLImage,HTMLSubImage=laya.resource.HTMLSubImage; var Handler=laya.utils.Handler,Loader=laya.net.Loader,Matrix=laya.maths.Matrix,Point=laya.maths.Point,Rectangle=laya.maths.Rectangle; var Render=laya.renders.Render,RenderContext=laya.renders.RenderContext,RenderSprite=laya.renders.RenderSprite; var Resource=laya.resource.Resource,ResourceManager=laya.resource.ResourceManager,RunDriver=laya.utils.RunDriver; var Sprite=laya.display.Sprite,Stage=laya.display.Stage,Stat=laya.utils.Stat,StringKey=laya.utils.StringKey; var Style=laya.display.css.Style,System=laya.system.System,Text=laya.display.Text,Texture=laya.resource.Texture; var TransformInfo=laya.display.css.TransformInfo,URL=laya.net.URL,Utils=laya.utils.Utils,VectorGraphManager=laya.utils.VectorGraphManager; var WordText=laya.utils.WordText; Laya.interface('laya.webgl.shapes.IShape'); Laya.interface('laya.webgl.submit.ISubmit'); Laya.interface('laya.webgl.text.ICharSegment'); Laya.interface('laya.webgl.canvas.save.ISaveData'); Laya.interface('laya.webgl.resource.IMergeAtlasBitmap'); Laya.interface('laya.filters.IFilterActionGL','laya.filters.IFilterAction'); //class laya.filters.webgl.FilterActionGL var FilterActionGL=(function(){ function FilterActionGL(){} __class(FilterActionGL,'laya.filters.webgl.FilterActionGL'); var __proto=FilterActionGL.prototype; Laya.imps(__proto,{"laya.filters.IFilterActionGL":true}) __proto.setValue=function(shader){} __proto.setValueMix=function(shader){} __proto.apply3d=function(scope,sprite,context,x,y){return null;} __proto.apply=function(srcCanvas){return null;} __getset(0,__proto,'typeMix',function(){ return 0; }); return FilterActionGL; })() //class laya.webgl.shader.ShaderValue var ShaderValue=(function(){ function ShaderValue(){} __class(ShaderValue,'laya.webgl.shader.ShaderValue'); return ShaderValue; })() //class laya.webgl.atlas.AtlasGrid var AtlasGrid=(function(){ var TexRowInfo,TexMergeTexSize; function AtlasGrid(width,height,atlasID){ this._atlasID=0; this._width=0; this._height=0; this._texCount=0; this._rowInfo=null; this._cells=null; this._failSize=new TexMergeTexSize(); (width===void 0)&& (width=0); (height===void 0)&& (height=0); (atlasID===void 0)&& (atlasID=0); this._cells=null; this._rowInfo=null; this._init(width,height); this._atlasID=atlasID; } __class(AtlasGrid,'laya.webgl.atlas.AtlasGrid'); var __proto=AtlasGrid.prototype; //------------------------------------------------------------------------------ __proto.getAltasID=function(){ return this._atlasID; } //------------------------------------------------------------------------------ __proto.setAltasID=function(atlasID){ if (atlasID >=0){ this._atlasID=atlasID; } } //------------------------------------------------------------------ __proto.addTex=function(type,width,height){ var result=this._get(width,height); if (result.ret==false){ return result; } this._fill(result.x,result.y,width,height,type); this._texCount++; return result; } //------------------------------------------------------------------------------ __proto._release=function(){ if (this._cells !=null){ this._cells.length=0; this._cells=null; } if (this._rowInfo){ this._rowInfo.length=0; this._rowInfo=null; } } //------------------------------------------------------------------------------ __proto._init=function(width,height){ this._width=width; this._height=height; this._release(); if (this._width==0)return false; this._cells=new Uint8Array(this._width *this._height*3); this._rowInfo=__newvec(this._height); for (var i=0;i < this._height;i++){ this._rowInfo[i]=new TexRowInfo(); } this._clear(); return true; } //------------------------------------------------------------------ __proto._get=function(width,height){ var pFillInfo=new MergeFillInfo(); if (width >=this._failSize.width && height >=this._failSize.height){ return pFillInfo; }; var rx=-1; var ry=-1; var nWidth=this._width; var nHeight=this._height; var pCellBox=this._cells; for (var y=0;y < nHeight;y++){ if (this._rowInfo[y].spaceCount < width)continue ; for (var x=0;x < nWidth;){ var tm=(y *nWidth+x)*3; if (pCellBox[tm] !=0 || pCellBox[tm+1] < width || pCellBox[tm+2] < height){ x+=pCellBox[tm+1]; continue ; } rx=x; ry=y; for (var xx=0;xx < width;xx++){ if (pCellBox[3*xx+tm+2] < height){ rx=-1; break ; } } if (rx < 0){ x+=pCellBox[tm+1]; continue ; } pFillInfo.ret=true; pFillInfo.x=rx; pFillInfo.y=ry; return pFillInfo; } } return pFillInfo; } //------------------------------------------------------------------ __proto._fill=function(x,y,w,h,type){ var nWidth=this._width; var nHeghit=this._height; this._check((x+w)<=nWidth && (y+h)<=nHeghit); for (var yy=y;yy < (h+y);++yy){ this._check(this._rowInfo[yy].spaceCount >=w); this._rowInfo[yy].spaceCount-=w; for (var xx=0;xx < w;xx++){ var tm=(x+yy *nWidth+xx)*3; this._check(this._cells[tm]==0); this._cells[tm]=type; this._cells[tm+1]=w; this._cells[tm+2]=h; } } if (x > 0){ for (yy=0;yy < h;++yy){ var s=0; for (xx=x-1;xx >=0;--xx,++s){ if (this._cells[((y+yy)*nWidth+xx)*3] !=0)break ; } for (xx=s;xx > 0;--xx){ this._cells[((y+yy)*nWidth+x-xx)*3+1]=xx; this._check(xx > 0); } } } if (y > 0){ for (xx=x;xx < (x+w);++xx){ s=0; for (yy=y-1;yy >=0;--yy,s++){ if (this._cells[(xx+yy *nWidth)*3] !=0)break ; } for (yy=s;yy > 0;--yy){ this._cells[(xx+(y-yy)*nWidth)*3+2]=yy; this._check(yy > 0); } } } } __proto._check=function(ret){ if (ret==false){ console.log("xtexMerger 错误啦"); } } //------------------------------------------------------------------ __proto._clear=function(){ this._texCount=0; for (var y=0;y < this._height;y++){ this._rowInfo[y].spaceCount=this._width; } for (var i=0;i < this._height;i++){ for (var j=0;j < this._width;j++){ var tm=(i *this._width+j)*3; this._cells[tm]=0; this._cells[tm+1]=this._width-j; this._cells[tm+2]=this._width-i; } } this._failSize.width=this._width+1; this._failSize.height=this._height+1; } AtlasGrid.__init$=function(){ //------------------------------------------------------------------------------ //class TexRowInfo TexRowInfo=(function(){ function TexRowInfo(){ this.spaceCount=0; } __class(TexRowInfo,''); return TexRowInfo; })() //------------------------------------------------------------------------------ //class TexMergeTexSize TexMergeTexSize=(function(){ function TexMergeTexSize(){ this.width=0; this.height=0; } __class(TexMergeTexSize,''); return TexMergeTexSize; })() } return AtlasGrid; })() //class laya.webgl.atlas.AtlasResourceManager var AtlasResourceManager=(function(){ function AtlasResourceManager(width,height,gridSize,maxTexNum){ this._currentAtlasCount=0; this._maxAtlaserCount=0; this._width=0; this._height=0; this._gridSize=0; this._gridNumX=0; this._gridNumY=0; this._init=false; this._curAtlasIndex=0; this._setAtlasParam=false; this._atlaserArray=null; this._needGC=false; this._setAtlasParam=true; this._width=width; this._height=height; this._gridSize=gridSize; this._maxAtlaserCount=maxTexNum; this._gridNumX=width / gridSize; this._gridNumY=height / gridSize; this._curAtlasIndex=0; this._atlaserArray=[]; } __class(AtlasResourceManager,'laya.webgl.atlas.AtlasResourceManager'); var __proto=AtlasResourceManager.prototype; __proto.setAtlasParam=function(width,height,gridSize,maxTexNum){ if (this._setAtlasParam==true){ AtlasResourceManager._sid_=0; this._width=width; this._height=height; this._gridSize=gridSize; this._maxAtlaserCount=maxTexNum; this._gridNumX=width / gridSize; this._gridNumY=height / gridSize; this._curAtlasIndex=0; this.freeAll(); return true; }else { console.log("设置大图合集参数错误,只能在开始页面设置各种参数"); throw-1; return false; } return false; } //添加 图片到大图集 __proto.pushData=function(texture){ var bitmap=texture.bitmap; var nWebGLImageIndex=-1; var curAtlas=null; var i=0,n=0,altasIndex=0; for (i=0,n=this._atlaserArray.length;i < n;i++){ altasIndex=(this._curAtlasIndex+i)% n; curAtlas=this._atlaserArray[altasIndex]; nWebGLImageIndex=curAtlas.findBitmapIsExist(bitmap); if (nWebGLImageIndex !=-1){ break ; } } if (nWebGLImageIndex !=-1){ var offset=curAtlas.InAtlasWebGLImagesOffsetValue[nWebGLImageIndex]; offsetX=offset[0]; offsetY=offset[1]; curAtlas.addToAtlas(texture,offsetX,offsetY); return true; }else { var tex=texture; this._setAtlasParam=false; var bFound=false; var nImageGridX=(Math.ceil((texture.bitmap.width+2)/ this._gridSize)); var nImageGridY=(Math.ceil((texture.bitmap.height+2)/ this._gridSize)); var bSuccess=false; for (var k=0;k < 2;k++){ var maxAtlaserCount=this._maxAtlaserCount; for (i=0;i < maxAtlaserCount;i++){ altasIndex=(this._curAtlasIndex+i)% maxAtlaserCount; (this._atlaserArray.length-1 >=altasIndex)|| (this._atlaserArray.push(new Atlaser(this._gridNumX,this._gridNumY,this._width,this._height,AtlasResourceManager._sid_++))); var atlas=this._atlaserArray[altasIndex]; var offsetX=0,offsetY=0; var fillInfo=atlas.addTex(1,nImageGridX,nImageGridY); if (fillInfo.ret){ offsetX=fillInfo.x *this._gridSize+1; offsetY=fillInfo.y *this._gridSize+1; bitmap.lock=true; atlas.addToAtlasTexture((bitmap),offsetX,offsetY); atlas.addToAtlas(texture,offsetX,offsetY); bSuccess=true; this._curAtlasIndex=altasIndex; break ; } } if (bSuccess) break ; this._atlaserArray.push(new Atlaser(this._gridNumX,this._gridNumY,this._width,this._height,AtlasResourceManager._sid_++)); this._needGC=true; this.garbageCollection(); this._curAtlasIndex=this._atlaserArray.length-1; } if (!bSuccess){ console.log(">>>AtlasManager pushData error"); } return bSuccess; } } __proto.addToAtlas=function(tex){ laya.webgl.atlas.AtlasResourceManager.instance.pushData(tex); } /** *回收大图合集,不建议手动调用 *@return */ __proto.garbageCollection=function(){ if (this._needGC===true){ var n=this._atlaserArray.length-this._maxAtlaserCount; for (var i=0;i < n;i++){ this._atlaserArray[i].dispose(); console.log("AtlasResourceManager:Dispose the inner Atlas。"); } console.log(">>>>altas garbageCollection ="+n); this._atlaserArray.splice(0,n); this._needGC=false; } return true; } __proto.freeAll=function(){ for (var i=0,n=this._atlaserArray.length;i < n;i++){ this._atlaserArray[i].dispose(); } this._atlaserArray.length=0; this._curAtlasIndex=0; } __proto.getAtlaserCount=function(){ return this._atlaserArray.length; } __proto.getAtlaserByIndex=function(index){ return this._atlaserArray[index]; } __getset(1,AtlasResourceManager,'instance',function(){ if (!AtlasResourceManager._Instance){ AtlasResourceManager._Instance=new AtlasResourceManager(laya.webgl.atlas.AtlasResourceManager.atlasTextureWidth,laya.webgl.atlas.AtlasResourceManager.atlasTextureHeight,/*CLASS CONST:laya.webgl.atlas.AtlasResourceManager.gridSize*/16,laya.webgl.atlas.AtlasResourceManager.maxTextureCount); } return AtlasResourceManager._Instance; }); __getset(1,AtlasResourceManager,'enabled',function(){ return Config.atlasEnable; }); __getset(1,AtlasResourceManager,'atlasLimitWidth',function(){ return AtlasResourceManager._atlasLimitWidth; },function(value){ AtlasResourceManager._atlasLimitWidth=value; }); __getset(1,AtlasResourceManager,'atlasLimitHeight',function(){ return AtlasResourceManager._atlasLimitHeight; },function(value){ AtlasResourceManager._atlasLimitHeight=value; }); AtlasResourceManager._enable=function(){ Config.atlasEnable=true; } AtlasResourceManager._disable=function(){ Config.atlasEnable=false; } AtlasResourceManager.__init__=function(){ AtlasResourceManager.atlasTextureWidth=2048; AtlasResourceManager.atlasTextureHeight=2048; AtlasResourceManager.maxTextureCount=6; AtlasResourceManager.atlasLimitWidth=512; AtlasResourceManager.atlasLimitHeight=512; } AtlasResourceManager._atlasLimitWidth=0; AtlasResourceManager._atlasLimitHeight=0; AtlasResourceManager.gridSize=16; AtlasResourceManager.atlasTextureWidth=0; AtlasResourceManager.atlasTextureHeight=0; AtlasResourceManager.maxTextureCount=0; AtlasResourceManager._atlasRestore=0; AtlasResourceManager.BOARDER_TYPE_NO=0; AtlasResourceManager.BOARDER_TYPE_RIGHT=1; AtlasResourceManager.BOARDER_TYPE_LEFT=2; AtlasResourceManager.BOARDER_TYPE_BOTTOM=4; AtlasResourceManager.BOARDER_TYPE_TOP=8; AtlasResourceManager.BOARDER_TYPE_ALL=15; AtlasResourceManager._sid_=0; AtlasResourceManager._Instance=null; return AtlasResourceManager; })() //class laya.webgl.atlas.MergeFillInfo var MergeFillInfo=(function(){ function MergeFillInfo(){ this.x=0; this.y=0; this.ret=false; this.ret=false; this.x=0; this.y=0; } __class(MergeFillInfo,'laya.webgl.atlas.MergeFillInfo'); return MergeFillInfo; })() ; //class laya.webgl.canvas.BlendMode var BlendMode=(function(){ function BlendMode(){} __class(BlendMode,'laya.webgl.canvas.BlendMode'); BlendMode._init_=function(gl){ BlendMode.fns=[BlendMode.BlendNormal,BlendMode.BlendAdd,BlendMode.BlendMultiply,BlendMode.BlendScreen,BlendMode.BlendOverlay,BlendMode.BlendLight,BlendMode.BlendMask,BlendMode.BlendDestinationOut]; BlendMode.targetFns=[BlendMode.BlendNormalTarget,BlendMode.BlendAddTarget,BlendMode.BlendMultiplyTarget,BlendMode.BlendScreenTarget,BlendMode.BlendOverlayTarget,BlendMode.BlendLightTarget,BlendMode.BlendMask,BlendMode.BlendDestinationOut]; } BlendMode.BlendNormal=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.ONE_MINUS_SRC_ALPHA*/0x0303); } BlendMode.BlendAdd=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.DST_ALPHA*/0x0304); } BlendMode.BlendMultiply=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.DST_COLOR*/0x0306,/*laya.webgl.WebGLContext.ONE_MINUS_SRC_ALPHA*/0x0303); } BlendMode.BlendScreen=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.ONE*/1); } BlendMode.BlendOverlay=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.ONE_MINUS_SRC_COLOR*/0x0301); } BlendMode.BlendLight=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.ONE*/1); } BlendMode.BlendNormalTarget=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.ONE_MINUS_SRC_ALPHA*/0x0303); } BlendMode.BlendAddTarget=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.DST_ALPHA*/0x0304); } BlendMode.BlendMultiplyTarget=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.DST_COLOR*/0x0306,/*laya.webgl.WebGLContext.ONE_MINUS_SRC_ALPHA*/0x0303); } BlendMode.BlendScreenTarget=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.ONE*/1); } BlendMode.BlendOverlayTarget=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.ONE_MINUS_SRC_COLOR*/0x0301); } BlendMode.BlendLightTarget=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.ONE*/1); } BlendMode.BlendMask=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ZERO*/0,/*laya.webgl.WebGLContext.SRC_ALPHA*/0x0302); } BlendMode.BlendDestinationOut=function(gl){ gl.blendFunc(/*laya.webgl.WebGLContext.ZERO*/0,/*laya.webgl.WebGLContext.ZERO*/0); } BlendMode.activeBlendFunction=null; BlendMode.NAMES=["normal","add","multiply","screen","overlay","light","mask","destination-out"]; BlendMode.TOINT={"normal":0,"add":1,"multiply":2,"screen":3 ,"lighter":1,"overlay":4,"light":5,"mask":6,"destination-out":7}; BlendMode.NORMAL="normal"; BlendMode.ADD="add"; BlendMode.MULTIPLY="multiply"; BlendMode.SCREEN="screen"; BlendMode.LIGHT="light"; BlendMode.OVERLAY="overlay"; BlendMode.DESTINATIONOUT="destination-out"; BlendMode.fns=[]; BlendMode.targetFns=[]; return BlendMode; })() //class laya.webgl.canvas.DrawStyle var DrawStyle=(function(){ function DrawStyle(value){ this._color=Color.create("black"); this.setValue(value); } __class(DrawStyle,'laya.webgl.canvas.DrawStyle'); var __proto=DrawStyle.prototype; __proto.setValue=function(value){ if (value){ if ((typeof value=='string')){ this._color=Color.create(value); return; } if ((value instanceof laya.utils.Color )){ this._color=value; return; } } } __proto.reset=function(){ this._color=Color.create("black"); } __proto.equal=function(value){ if ((typeof value=='string'))return this._color.strColor===value; if ((value instanceof laya.utils.Color ))return this._color.numColor===(value).numColor; return false; } __proto.toColorStr=function(){ return this._color.strColor; } DrawStyle.create=function(value){ if (value){ var color; if ((typeof value=='string'))color=Color.create(value); else if ((value instanceof laya.utils.Color ))color=value; if (color){ return color._drawStyle || (color._drawStyle=new DrawStyle(value)); } } return laya.webgl.canvas.DrawStyle.DEFAULT; } __static(DrawStyle, ['DEFAULT',function(){return this.DEFAULT=new DrawStyle("#000000");} ]); return DrawStyle; })() //class laya.webgl.canvas.Path var Path=(function(){ function Path(){ this._x=0; this._y=0; //this._rect=null; //this.ib=null; //this.vb=null; this.dirty=false; //this.geomatrys=null; //this._curGeomatry=null; this.offset=0; this.count=0; this.geoStart=0; this.tempArray=[]; this.closePath=false; this.geomatrys=[]; var gl=WebGL.mainContext; this.ib=IndexBuffer2D.create(/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this.vb=VertexBuffer2D.create(5); } __class(Path,'laya.webgl.canvas.Path'); var __proto=Path.prototype; __proto.addPoint=function(pointX,pointY){ this.tempArray.push(pointX,pointY); } __proto.getEndPointX=function(){ return this.tempArray[this.tempArray.length-2]; } __proto.getEndPointY=function(){ return this.tempArray[this.tempArray.length-1]; } __proto.polygon=function(x,y,points,color,borderWidth,borderColor){ var geo; this.geomatrys.push(this._curGeomatry=geo=new Polygon(x,y,points,color,borderWidth,borderColor)); if (!color)geo.fill=false; if (borderColor==undefined)geo.borderWidth=0; return geo; } __proto.setGeomtry=function(shape){ this.geomatrys.push(this._curGeomatry=shape); } __proto.drawLine=function(x,y,points,width,color){ var geo; if (this.closePath){ this.geomatrys.push(this._curGeomatry=geo=new LoopLine(x,y,points,width,color)); }else { this.geomatrys.push(this._curGeomatry=geo=new Line(x,y,points,width,color)); } geo.fill=false; return geo; } __proto.update=function(){ var si=this.ib._byteLength; var len=this.geomatrys.length; this.offset=si; for (var i=this.geoStart;i < len;i++){ this.geomatrys[i].getData(this.ib,this.vb,this.vb._byteLength / 20); } this.geoStart=len; this.count=(this.ib._byteLength-si)/ CONST3D2D.BYTES_PIDX; } __proto.reset=function(){ this.vb.clear(); this.ib.clear(); this.offset=this.count=this.geoStart=0; this.geomatrys.length=0; } __proto.recover=function(){ this._curGeomatry=null; this.vb.destory(); this.vb=null; this.ib.destory(); this.ib=null; } return Path; })() //class laya.webgl.canvas.save.SaveBase var SaveBase=(function(){ function SaveBase(){ //this._valueName=null; //this._value=null; //this._dataObj=null; //this._newSubmit=false; } __class(SaveBase,'laya.webgl.canvas.save.SaveBase'); var __proto=SaveBase.prototype; Laya.imps(__proto,{"laya.webgl.canvas.save.ISaveData":true}) __proto.isSaveMark=function(){return false;} __proto.restore=function(context){ this._dataObj[this._valueName]=this._value; SaveBase._cache[SaveBase._cache._length++]=this; this._newSubmit && (context._curSubmit=Submit.RENDERBASE,context._renderKey=0); } SaveBase._createArray=function(){ var value=[]; value._length=0; return value; } SaveBase._init=function(){ var namemap=SaveBase._namemap={}; namemap[0x1]="ALPHA"; namemap[0x2]="fillStyle"; namemap[0x8]="font"; namemap[0x100]="lineWidth"; namemap[0x200]="strokeStyle"; namemap[0x2000]="_mergeID"; namemap[0x400]=namemap[0x800]=namemap[0x1000]=[]; namemap[0x4000]="textBaseline"; namemap[0x8000]="textAlign"; namemap[0x10000]="_nBlendType"; namemap[0x100000]="shader"; namemap[0x200000]="filters"; return namemap; } SaveBase.save=function(context,type,dataObj,newSubmit){ if ((context._saveMark._saveuse & type)!==type){ context._saveMark._saveuse |=type; var cache=SaveBase._cache; var o=cache._length > 0 ? cache[--cache._length] :(new SaveBase()); o._value=dataObj[o._valueName=SaveBase._namemap[type]]; o._dataObj=dataObj; o._newSubmit=newSubmit; var _save=context._save; _save[_save._length++]=o; } } SaveBase._cache=laya.webgl.canvas.save.SaveBase._createArray(); SaveBase._namemap=SaveBase._init(); return SaveBase; })() //class laya.webgl.canvas.save.SaveClipRect var SaveClipRect=(function(){ function SaveClipRect(){ //this._clipSaveRect=null; //this._submitScissor=null; this._clipRect=new Rectangle(); } __class(SaveClipRect,'laya.webgl.canvas.save.SaveClipRect'); var __proto=SaveClipRect.prototype; Laya.imps(__proto,{"laya.webgl.canvas.save.ISaveData":true}) __proto.isSaveMark=function(){return false;} __proto.restore=function(context){ context._clipRect=this._clipSaveRect; SaveClipRect._cache[SaveClipRect._cache._length++]=this; this._submitScissor.submitLength=context._submits._length-this._submitScissor.submitIndex; context._curSubmit=Submit.RENDERBASE; context._renderKey=0; } SaveClipRect.save=function(context,submitScissor){ if ((context._saveMark._saveuse & /*laya.webgl.canvas.save.SaveBase.TYPE_CLIPRECT*/0x20000)==/*laya.webgl.canvas.save.SaveBase.TYPE_CLIPRECT*/0x20000)return; context._saveMark._saveuse |=/*laya.webgl.canvas.save.SaveBase.TYPE_CLIPRECT*/0x20000; var cache=SaveClipRect._cache; var o=cache._length > 0 ? cache[--cache._length] :(new SaveClipRect()); o._clipSaveRect=context._clipRect; context._clipRect=o._clipRect.copyFrom(context._clipRect); o._submitScissor=submitScissor; var _save=context._save; _save[_save._length++]=o; } __static(SaveClipRect, ['_cache',function(){return this._cache=SaveBase._createArray();} ]); return SaveClipRect; })() //class laya.webgl.canvas.save.SaveClipRectStencil var SaveClipRectStencil=(function(){ function SaveClipRectStencil(){ //this._clipSaveRect=null; //this._saveMatrix=null; this._contextX=0; this._contextY=0; //this._submitStencil=null; this._clipRect=new Rectangle(); this._rect=new Rectangle(); this._matrix=new Matrix(); } __class(SaveClipRectStencil,'laya.webgl.canvas.save.SaveClipRectStencil'); var __proto=SaveClipRectStencil.prototype; Laya.imps(__proto,{"laya.webgl.canvas.save.ISaveData":true}) __proto.isSaveMark=function(){return false;} __proto.restore=function(context){ SubmitStencil.restore(context,this._rect,this._saveMatrix,this._contextX,this._contextY); context._clipRect=this._clipSaveRect; context._curMat=this._saveMatrix; context._x=this._contextX; context._y=this._contextY; SaveClipRectStencil._cache[SaveClipRectStencil._cache._length++]=this; context._curSubmit=Submit.RENDERBASE; } SaveClipRectStencil.save=function(context,submitStencil,x,y,width,height,clipX,clipY,clipWidth,clipHeight){ if ((context._saveMark._saveuse & /*laya.webgl.canvas.save.SaveBase.TYPE_CLIPRECT_STENCIL*/0x40000)==/*laya.webgl.canvas.save.SaveBase.TYPE_CLIPRECT_STENCIL*/0x40000)return; context._saveMark._saveuse |=/*laya.webgl.canvas.save.SaveBase.TYPE_CLIPRECT_STENCIL*/0x40000; var cache=SaveClipRectStencil._cache; var o=cache._length > 0 ? cache[--cache._length] :(new SaveClipRectStencil()); o._clipSaveRect=context._clipRect; o._clipRect.setTo(clipX,clipY,clipWidth,clipHeight); context._clipRect=o._clipRect; o._rect.x=x; o._rect.y=y; o._rect.width=width; o._rect.height=height; o._contextX=context._x; o._contextY=context._y; o._saveMatrix=context._curMat; context._curMat.copyTo(o._matrix); context._curMat=o._matrix; o._submitStencil=submitStencil; var _save=context._save; _save[_save._length++]=o; } __static(SaveClipRectStencil, ['_cache',function(){return this._cache=SaveBase._createArray();} ]); return SaveClipRectStencil; })() //class laya.webgl.canvas.save.SaveMark var SaveMark=(function(){ function SaveMark(){ this._saveuse=0; //this._preSaveMark=null; ; } __class(SaveMark,'laya.webgl.canvas.save.SaveMark'); var __proto=SaveMark.prototype; Laya.imps(__proto,{"laya.webgl.canvas.save.ISaveData":true}) __proto.isSaveMark=function(){ return true; } __proto.restore=function(context){ context._saveMark=this._preSaveMark; SaveMark._no[SaveMark._no._length++]=this; } SaveMark.Create=function(context){ var no=SaveMark._no; var o=no._length > 0 ? no[--no._length] :(new SaveMark()); o._saveuse=0; o._preSaveMark=context._saveMark; context._saveMark=o; return o; } __static(SaveMark, ['_no',function(){return this._no=SaveBase._createArray();} ]); return SaveMark; })() //class laya.webgl.canvas.save.SaveTransform var SaveTransform=(function(){ function SaveTransform(){ //this._savematrix=null; this._matrix=new Matrix(); } __class(SaveTransform,'laya.webgl.canvas.save.SaveTransform'); var __proto=SaveTransform.prototype; Laya.imps(__proto,{"laya.webgl.canvas.save.ISaveData":true}) __proto.isSaveMark=function(){return false;} __proto.restore=function(context){ context._curMat=this._savematrix; SaveTransform._no[SaveTransform._no._length++]=this; } SaveTransform.save=function(context){ var _saveMark=context._saveMark; if ((_saveMark._saveuse & /*laya.webgl.canvas.save.SaveBase.TYPE_TRANSFORM*/0x800)===/*laya.webgl.canvas.save.SaveBase.TYPE_TRANSFORM*/0x800)return; _saveMark._saveuse |=/*laya.webgl.canvas.save.SaveBase.TYPE_TRANSFORM*/0x800; var no=SaveTransform._no; var o=no._length > 0 ? no[--no._length] :(new SaveTransform()); o._savematrix=context._curMat; context._curMat=context._curMat.copyTo(o._matrix); var _save=context._save; _save[_save._length++]=o; } __static(SaveTransform, ['_no',function(){return this._no=SaveBase._createArray();} ]); return SaveTransform; })() //class laya.webgl.canvas.save.SaveTranslate var SaveTranslate=(function(){ function SaveTranslate(){ //this._x=NaN; //this._y=NaN; } __class(SaveTranslate,'laya.webgl.canvas.save.SaveTranslate'); var __proto=SaveTranslate.prototype; Laya.imps(__proto,{"laya.webgl.canvas.save.ISaveData":true}) __proto.isSaveMark=function(){return false;} __proto.restore=function(context){ var mat=context._curMat; context._x=this._x; context._y=this._y; SaveTranslate._no[SaveTranslate._no._length++]=this; } SaveTranslate.save=function(context){ var no=SaveTranslate._no; var o=no._length > 0 ? no[--no._length] :(new SaveTranslate()); o._x=context._x; o._y=context._y; var _save=context._save; _save[_save._length++]=o; } __static(SaveTranslate, ['_no',function(){return this._no=SaveBase._createArray();} ]); return SaveTranslate; })() //class laya.webgl.resource.RenderTargetMAX var RenderTargetMAX=(function(){ function RenderTargetMAX(){ //public var targets:Vector.;//没用到 this.target=null; this.repaint=false; this._width=NaN; this._height=NaN; this._sp=null; this._clipRect=new Rectangle(); } __class(RenderTargetMAX,'laya.webgl.resource.RenderTargetMAX'); var __proto=RenderTargetMAX.prototype; __proto.setSP=function(sp){ this._sp=sp; } __proto.size=function(w,h){ var _$this=this; if (this._width===w && this._height===h){ this.target.size(w,h); return; } this.repaint=true; this._width=w; this._height=h; if (!this.target) this.target=RenderTarget2D.create(w,h); else this.target.size(w,h); if (!this.target.hasListener(/*laya.events.Event.RECOVERED*/"recovered")){ this.target.on(/*laya.events.Event.RECOVERED*/"recovered",this,function(e){ Laya.timer.callLater(_$this._sp,_$this._sp.repaint); }); } } __proto._flushToTarget=function(context,target){ if (target._destroy)return; var worldScissorTest=RenderState2D.worldScissorTest; var preworldClipRect=RenderState2D.worldClipRect; RenderState2D.worldClipRect=this._clipRect; this._clipRect.x=this._clipRect.y=0; this._clipRect.width=this._width; this._clipRect.height=this._height; RenderState2D.worldScissorTest=false; WebGL.mainContext.disable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); var preAlpha=RenderState2D.worldAlpha; var preMatrix4=RenderState2D.worldMatrix4; var preMatrix=RenderState2D.worldMatrix; var preFilters=RenderState2D.worldFilters; var preShaderDefines=RenderState2D.worldShaderDefines; RenderState2D.worldMatrix=Matrix.EMPTY; RenderState2D.restoreTempArray(); RenderState2D.worldMatrix4=RenderState2D.TEMPMAT4_ARRAY; RenderState2D.worldAlpha=1; RenderState2D.worldFilters=null; RenderState2D.worldShaderDefines=null; BaseShader.activeShader=null; target.start(); Config.showCanvasMark ? target.clear(0,1,0,0.3):target.clear(0,0,0,0); context.flush(); target.end(); BaseShader.activeShader=null; RenderState2D.worldAlpha=preAlpha; RenderState2D.worldMatrix4=preMatrix4; RenderState2D.worldMatrix=preMatrix; RenderState2D.worldFilters=preFilters; RenderState2D.worldShaderDefines=preShaderDefines; RenderState2D.worldScissorTest=worldScissorTest if (worldScissorTest){ var y=RenderState2D.height-preworldClipRect.y-preworldClipRect.height; WebGL.mainContext.scissor(preworldClipRect.x,y,preworldClipRect.width,preworldClipRect.height); WebGL.mainContext.enable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); } RenderState2D.worldClipRect=preworldClipRect; } __proto.flush=function(context){ if (this.repaint){ this._flushToTarget(context,this.target); this.repaint=false; } } __proto.drawTo=function(context,x,y,width,height){ context.drawTexture(this.target.getTexture(),x,y,width,height,0,0); } __proto.destroy=function(){ if (this.target){ this.target.destroy(); this.target=null; this._sp=null; } } return RenderTargetMAX; })() //class laya.webgl.shader.d2.Shader2D var Shader2D=(function(){ function Shader2D(){ this.ALPHA=1; //this.glTexture=null; //this.shader=null; //this.filters=null; this.shaderType=0; //this.colorAdd=null; //this.strokeStyle=null; //this.fillStyle=null; this.defines=new ShaderDefines2D(); } __class(Shader2D,'laya.webgl.shader.d2.Shader2D'); var __proto=Shader2D.prototype; __proto.destroy=function(){ this.defines=null; this.filters=null; this.glTexture=null; this.strokeStyle=null; this.fillStyle=null; } Shader2D.__init__=function(){ Shader.addInclude("parts/ColorFilter_ps_uniform.glsl","uniform vec4 colorAlpha;\nuniform mat4 colorMat;"); Shader.addInclude("parts/ColorFilter_ps_logic.glsl","mat4 alphaMat =colorMat;\n\nalphaMat[0][3] *= gl_FragColor.a;\nalphaMat[1][3] *= gl_FragColor.a;\nalphaMat[2][3] *= gl_FragColor.a;\n\ngl_FragColor = gl_FragColor * alphaMat;\ngl_FragColor += colorAlpha/255.0*gl_FragColor.a;\n"); Shader.addInclude("parts/GlowFilter_ps_uniform.glsl","uniform vec4 u_color;\nuniform float u_strength;\nuniform float u_blurX;\nuniform float u_blurY;\nuniform float u_offsetX;\nuniform float u_offsetY;\nuniform float u_textW;\nuniform float u_textH;"); Shader.addInclude("parts/GlowFilter_ps_logic.glsl","const float c_IterationTime = 10.0;\nfloat floatIterationTotalTime = c_IterationTime * c_IterationTime;\nvec4 vec4Color = vec4(0.0,0.0,0.0,0.0);\nvec2 vec2FilterDir = vec2(-(u_offsetX)/u_textW,-(u_offsetY)/u_textH);\nvec2 vec2FilterOff = vec2(u_blurX/u_textW/c_IterationTime * 2.0,u_blurY/u_textH/c_IterationTime * 2.0);\nfloat maxNum = u_blurX * u_blurY;\nvec2 vec2Off = vec2(0.0,0.0);\nfloat floatOff = c_IterationTime/2.0;\nfor(float i = 0.0;i<=c_IterationTime; ++i){\n for(float j = 0.0;j<=c_IterationTime; ++j){\n vec2Off = vec2(vec2FilterOff.x * (i - floatOff),vec2FilterOff.y * (j - floatOff));\n vec4Color += texture2D(texture, v_texcoord + vec2FilterDir + vec2Off)/floatIterationTotalTime;\n }\n}\ngl_FragColor = vec4(u_color.rgb,vec4Color.a * u_strength);\ngl_FragColor.rgb *= gl_FragColor.a;"); Shader.addInclude("parts/BlurFilter_ps_logic.glsl","gl_FragColor = blur();\ngl_FragColor.w*=alpha;"); Shader.addInclude("parts/BlurFilter_ps_uniform.glsl","uniform vec4 strength_sig2_2sig2_gauss1;\nuniform vec2 blurInfo;\n\n#define PI 3.141593\n\n//float sigma=strength/3.0;//3σ以外影响很小。即当σ=1的时候,半径为3\n//float sig2 = sigma*sigma;\n//float _2sig2 = 2.0*sig2;\n//return 1.0/(2*PI*sig2)*exp(-(x*x+y*y)/_2sig2)\n//float gauss1 = 1.0/(2.0*PI*sig2);\n\nfloat getGaussian(float x, float y){\n return strength_sig2_2sig2_gauss1.w*exp(-(x*x+y*y)/strength_sig2_2sig2_gauss1.z);\n}\n\nvec4 blur(){\n const float blurw = 9.0;\n vec4 vec4Color = vec4(0.0,0.0,0.0,0.0);\n vec2 halfsz=vec2(blurw,blurw)/2.0/blurInfo; \n vec2 startpos=v_texcoord-halfsz;\n vec2 ctexcoord = startpos;\n vec2 step = 1.0/blurInfo; //每个像素 \n \n for(float y = 0.0;y<=blurw; ++y){\n ctexcoord.x=startpos.x;\n for(float x = 0.0;x<=blurw; ++x){\n //TODO 纹理坐标的固定偏移应该在vs中处理\n vec4Color += texture2D(texture, ctexcoord)*getGaussian(x-blurw/2.0,y-blurw/2.0);\n ctexcoord.x+=step.x;\n }\n ctexcoord.y+=step.y;\n }\n return vec4Color;\n}"); Shader.addInclude("parts/ColorAdd_ps_uniform.glsl","uniform vec4 colorAdd;\n"); Shader.addInclude("parts/ColorAdd_ps_logic.glsl","gl_FragColor = vec4(colorAdd.rgb,colorAdd.a*gl_FragColor.a);\ngl_FragColor.xyz *= colorAdd.a;"); var vs,ps; vs="attribute vec4 position;\nattribute vec2 texcoord;\nuniform vec2 size;\n\n#ifdef WORLDMAT\nuniform mat4 mmat;\n#endif\nvarying vec2 v_texcoord;\nvoid main() {\n #ifdef WORLDMAT\n vec4 pos=mmat*position;\n gl_Position =vec4((pos.x/size.x-0.5)*2.0,(0.5-pos.y/size.y)*2.0,pos.z,1.0);\n #else\n gl_Position =vec4((position.x/size.x-0.5)*2.0,(0.5-position.y/size.y)*2.0,position.z,1.0);\n #endif\n \n v_texcoord = texcoord;\n}"; ps="precision mediump float;\n//precision highp float;\nvarying vec2 v_texcoord;\nuniform sampler2D texture;\nuniform float alpha;\n#include?BLUR_FILTER \"parts/BlurFilter_ps_uniform.glsl\";\n#include?COLOR_FILTER \"parts/ColorFilter_ps_uniform.glsl\";\n#include?GLOW_FILTER \"parts/GlowFilter_ps_uniform.glsl\";\n#include?COLOR_ADD \"parts/ColorAdd_ps_uniform.glsl\";\n\nvoid main() {\n vec4 color= texture2D(texture, v_texcoord);\n color.a*=alpha;\n color.rgb*=alpha;\n gl_FragColor=color;\n #include?COLOR_ADD \"parts/ColorAdd_ps_logic.glsl\"; \n #include?BLUR_FILTER \"parts/BlurFilter_ps_logic.glsl\";\n #include?COLOR_FILTER \"parts/ColorFilter_ps_logic.glsl\";\n #include?GLOW_FILTER \"parts/GlowFilter_ps_logic.glsl\";\n}"; Shader.preCompile2D(0,/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,vs,ps,null); vs="attribute vec4 position;\nuniform vec2 size;\nuniform mat4 mmat;\nvoid main() {\n vec4 pos=mmat*position;\n gl_Position =vec4((pos.x/size.x-0.5)*2.0,(0.5-pos.y/size.y)*2.0,pos.z,1.0);\n}"; ps="precision mediump float;\nuniform vec4 color;\nuniform float alpha;\n#include?COLOR_FILTER \"parts/ColorFilter_ps_uniform.glsl\";\nvoid main() {\n vec4 a = vec4(color.r, color.g, color.b, color.a);\n a.w = alpha;\n a.xyz *= alpha;\n gl_FragColor = a;\n #include?COLOR_FILTER \"parts/ColorFilter_ps_logic.glsl\";\n}"; Shader.preCompile2D(0,/*laya.webgl.shader.d2.ShaderDefines2D.COLOR2D*/0x02,vs,ps,null); vs="attribute vec4 position;\nattribute vec3 a_color;\nuniform mat4 mmat;\nuniform mat4 u_mmat2;\nuniform vec2 u_pos;\nuniform vec2 size;\nvarying vec3 color;\nvoid main(){\n vec4 tPos = vec4(position.x + u_pos.x,position.y + u_pos.y,position.z,position.w);\n vec4 pos=mmat*u_mmat2*tPos;\n gl_Position =vec4((pos.x/size.x-0.5)*2.0,(0.5-pos.y/size.y)*2.0,pos.z,1.0);\n color=a_color;\n}"; ps="precision mediump float;\n//precision mediump float;\nvarying vec3 color;\nuniform float alpha;\nvoid main(){\n //vec4 a=vec4(color.r, color.g, color.b, 1);\n //a.a*=alpha;\n gl_FragColor=vec4(color.r, color.g, color.b, alpha);\n gl_FragColor.rgb*=alpha;\n}"; Shader.preCompile2D(0,/*laya.webgl.shader.d2.ShaderDefines2D.PRIMITIVE*/0x04,vs,ps,null); vs="attribute vec4 position;\nattribute vec2 texcoord;\nuniform vec2 size;\n\n#ifdef WORLDMAT\nuniform mat4 mmat;\n#endif\nvarying vec2 v_texcoord;\nvoid main() {\n #ifdef WORLDMAT\n vec4 pos=mmat*position;\n gl_Position =vec4((pos.x/size.x-0.5)*2.0,(0.5-pos.y/size.y)*2.0,pos.z,1.0);\n #else\n gl_Position =vec4((position.x/size.x-0.5)*2.0,(0.5-position.y/size.y)*2.0,position.z,1.0);\n #endif\n \n v_texcoord = texcoord;\n}"; ps="#ifdef FSHIGHPRECISION\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n//precision highp float;\nvarying vec2 v_texcoord;\nuniform sampler2D texture;\nuniform float alpha;\nuniform vec4 u_TexRange;\nuniform vec2 u_offset;\n#include?BLUR_FILTER \"parts/BlurFilter_ps_uniform.glsl\";\n#include?COLOR_FILTER \"parts/ColorFilter_ps_uniform.glsl\";\n#include?GLOW_FILTER \"parts/GlowFilter_ps_uniform.glsl\";\n#include?COLOR_ADD \"parts/ColorAdd_ps_uniform.glsl\";\n\nvoid main() {\n vec2 newTexCoord;\n newTexCoord.x = mod(u_offset.x + v_texcoord.x,u_TexRange.y) + u_TexRange.x;\n newTexCoord.y = mod(u_offset.y + v_texcoord.y,u_TexRange.w) + u_TexRange.z;\n vec4 color= texture2D(texture, newTexCoord);\n color.a*=alpha;\n gl_FragColor=color;\n #include?COLOR_ADD \"parts/ColorAdd_ps_logic.glsl\"; \n #include?BLUR_FILTER \"parts/BlurFilter_ps_logic.glsl\";\n #include?COLOR_FILTER \"parts/ColorFilter_ps_logic.glsl\";\n #include?GLOW_FILTER \"parts/GlowFilter_ps_logic.glsl\";\n}"; Shader.preCompile2D(0,/*laya.webgl.shader.d2.ShaderDefines2D.FILLTEXTURE*/0x100,vs,ps,null); vs="attribute vec2 position;\nattribute vec2 texcoord;\nattribute vec4 color;\nuniform vec2 size;\nuniform float offsetX;\nuniform float offsetY;\nuniform mat4 mmat;\nuniform mat4 u_mmat2;\nvarying vec2 v_texcoord;\nvarying vec4 v_color;\nvoid main() {\n vec4 pos=mmat*u_mmat2*vec4(offsetX+position.x,offsetY+position.y,0,1 );\n gl_Position = vec4((pos.x/size.x-0.5)*2.0,(0.5-pos.y/size.y)*2.0,pos.z,1.0);\n v_color = color;\n v_color.rgb *= v_color.a;\n v_texcoord = texcoord; \n}"; ps="precision mediump float;\nvarying vec2 v_texcoord;\nvarying vec4 v_color;\nuniform sampler2D texture;\nuniform float alpha;\nvoid main() {\n vec4 t_color = texture2D(texture, v_texcoord);\n gl_FragColor = t_color.rgba * v_color;\n gl_FragColor *= alpha;\n}"; Shader.preCompile2D(0,/*laya.webgl.shader.d2.ShaderDefines2D.SKINMESH*/0x200,vs,ps,null); } return Shader2D; })() //class laya.webgl.shader.ShaderDefines var ShaderDefines=(function(){ function ShaderDefines(name2int,int2name,int2nameMap){ this._value=0; //this._name2int=null; //this._int2name=null; //this._int2nameMap=null; this._name2int=name2int; this._int2name=int2name; this._int2nameMap=int2nameMap; } __class(ShaderDefines,'laya.webgl.shader.ShaderDefines'); var __proto=ShaderDefines.prototype; __proto.add=function(value){ if ((typeof value=='string'))value=this._name2int[value]; this._value |=value; return this._value; } __proto.addInt=function(value){ this._value |=value; return this._value; } __proto.remove=function(value){ if ((typeof value=='string'))value=this._name2int[value]; this._value &=(~value); return this._value; } __proto.isDefine=function(def){ return (this._value & def)===def; } __proto.getValue=function(){ return this._value; } __proto.setValue=function(value){ this._value=value; } __proto.toNameDic=function(){ var r=this._int2nameMap[this._value]; return r ? r :ShaderDefines._toText(this._value,this._int2name,this._int2nameMap); } ShaderDefines._reg=function(name,value,_name2int,_int2name){ _name2int[name]=value; _int2name[value]=name; } ShaderDefines._toText=function(value,_int2name,_int2nameMap){ var r=_int2nameMap[value]; if (r)return r; var o={}; var d=1; for (var i=0;i < 32;i++){ d=1 << i; if (d > value)break ; if (value & d){ var name=_int2name[d]; name && (o[name]=""); } } _int2nameMap[value]=o; return o; } ShaderDefines._toInt=function(names,_name2int){ var words=names.split('.'); var num=0; for (var i=0,n=words.length;i < n;i++){ var value=_name2int[words[i]]; if (!value)throw new Error("Defines to int err:"+names+"/"+words[i]); num |=value; } return num; } return ShaderDefines; })() /** *这里销毁的问题,后面待确认 */ //class laya.webgl.shader.d2.skinAnishader.SkinMesh var SkinMesh=(function(){ function SkinMesh(){ this.mVBBuffer=null; this.mIBBuffer=null; this.mVBData=null; this.mIBData=null; this.mEleNum=0; this.mTexture=null; this.transform=null; this._vs=null; this._ps=null; this._indexStart=-1; this._verticles=null; this._uvs=null; this._tempMatrix=new Matrix(); } __class(SkinMesh,'laya.webgl.shader.d2.skinAnishader.SkinMesh'); var __proto=SkinMesh.prototype; __proto.init=function(texture,vs,ps){ if (vs){ this._vs=vs; }else { this._vs=[]; var tWidth=texture.width; var tHeight=texture.height; var tRed=1; var tGreed=1; var tBlue=1; var tAlpha=1; this._vs.push(0,0,0,0,tRed,tGreed,tBlue,tAlpha); this._vs.push(tWidth,0,1,0,tRed,tGreed,tBlue,tAlpha); this._vs.push(tWidth,tHeight,1,1,tRed,tGreed,tBlue,tAlpha); this._vs.push(0,tHeight,0,1,tRed,tGreed,tBlue,tAlpha); } if (ps){ this._ps=ps; }else { if (!SkinMesh._defaultPS){ SkinMesh._defaultPS=[]; SkinMesh._defaultPS.push(0,1,3,3,1,2); } this._ps=SkinMesh._defaultPS; } this.mVBData=new Float32Array(this._vs); this.mIBData=new Uint16Array(this._ps.length); this.mIBData["start"]=-1; this.mEleNum=this._ps.length; this.mTexture=texture; } __proto.init2=function(texture,vs,ps,verticles,uvs){ if (this.transform)this.transform=null; if (ps){ this._ps=ps; }else { this._ps=[]; this._ps.push(0,1,3,3,1,2); } this._verticles=verticles; this._uvs=uvs; this.mEleNum=this._ps.length; this.mTexture=texture; if (Render.isConchNode || Render.isConchApp){ this._initMyData(); this.mVBData=new Float32Array(this._vs); } } __proto._initMyData=function(){ var vsI=0; var vI=0; var vLen=this._verticles.length; var tempVLen=vLen *4; this._vs=SkinMesh._tempVS; var insertNew=false; if (Render.isConchNode || Render.isConchApp){ this._vs.length=tempVLen; insertNew=true; }else{ if (this._vs.length < tempVLen){ this._vs.length=tempVLen; insertNew=true; } } SkinMesh._tVSLen=tempVLen; if (insertNew){ while (vsI < tempVLen){ this._vs[vsI]=this._verticles[vI]; this._vs[vsI+1]=this._verticles[vI+1]; this._vs[vsI+2]=this._uvs[vI]; this._vs[vsI+3]=this._uvs[vI+1]; this._vs[vsI+4]=1; this._vs[vsI+5]=1; this._vs[vsI+6]=1; this._vs[vsI+7]=1; vsI+=8; vI+=2; } }else{ while (vsI < tempVLen){ this._vs[vsI]=this._verticles[vI]; this._vs[vsI+1]=this._verticles[vI+1]; this._vs[vsI+2]=this._uvs[vI]; this._vs[vsI+3]=this._uvs[vI+1]; vsI+=8; vI+=2; } } } __proto.getData2=function(vb,ib,start){ this.mVBBuffer=vb; this.mIBBuffer=ib; this._initMyData(); vb.appendEx2(this._vs,Float32Array,SkinMesh._tVSLen,4); this._indexStart=ib._byteLength; var tIB; tIB=SkinMesh._tempIB; if (tIB.length < this._ps.length){ tIB.length=this._ps.length; } for (var i=0,n=this._ps.length;i < n;i++){ tIB[i]=this._ps[i]+start; } ib.appendEx2(tIB,Uint16Array,this._ps.length,2); } __proto.getData=function(vb,ib,start){ this.mVBBuffer=vb; this.mIBBuffer=ib; vb.append(this.mVBData); this._indexStart=ib._byteLength; if (this.mIBData["start"] !=start){ for (var i=0,n=this._ps.length;i < n;i++){ this.mIBData[i]=this._ps[i]+start; } this.mIBData["start"]=start; } ib.append(this.mIBData); } __proto.render=function(context,x,y){ if (Render.isWebGL && this.mTexture){ context._renderKey=0; context._shader2D.glTexture=null; SkinMeshBuffer.getInstance().addSkinMesh(this); var tempSubmit=Submit.createShape(context,this.mIBBuffer,this.mVBBuffer,this.mEleNum,this._indexStart,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.SKINMESH*/0x200,0)); this.transform || (this.transform=Matrix.EMPTY); this.transform.translate(x,y); Matrix.mul(this.transform,context._curMat,this._tempMatrix); this.transform.translate(-x,-y); var tShaderValue=tempSubmit.shaderValue; var tArray=tShaderValue.u_mmat2||RenderState2D.getMatrArray(); RenderState2D.mat2MatArray(this._tempMatrix,tArray); tShaderValue.textureHost=this.mTexture; tShaderValue.offsetX=0; tShaderValue.offsetY=0; tShaderValue.u_mmat2=tArray; tShaderValue.ALPHA=context._shader2D.ALPHA; context._submits[context._submits._length++]=tempSubmit; } else if (Render.isConchApp&&this.mTexture){ this.transform || (this.transform=Matrix.EMPTY); context.setSkinMesh&&context.setSkinMesh(x,y,this._ps,this.mVBData,this.mEleNum,0,this.mTexture,this.transform); } } SkinMesh._tempVS=[]; SkinMesh._tempIB=[]; SkinMesh._defaultPS=null; SkinMesh._tVSLen=0; return SkinMesh; })() //class laya.webgl.shader.d2.skinAnishader.SkinMeshBuffer var SkinMeshBuffer=(function(){ function SkinMeshBuffer(){ this.ib=null; this.vb=null; var gl=WebGL.mainContext; this.ib=IndexBuffer2D.create(/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this.vb=VertexBuffer2D.create(8); } __class(SkinMeshBuffer,'laya.webgl.shader.d2.skinAnishader.SkinMeshBuffer'); var __proto=SkinMeshBuffer.prototype; __proto.addSkinMesh=function(skinMesh){ skinMesh.getData2(this.vb,this.ib,this.vb._byteLength / 32); } __proto.reset=function(){ this.vb.clear(); this.ib.clear(); } SkinMeshBuffer.getInstance=function(){ return SkinMeshBuffer.instance=SkinMeshBuffer.instance|| new SkinMeshBuffer(); } SkinMeshBuffer.instance=null; return SkinMeshBuffer; })() //此类可以减少代码 //class laya.webgl.shapes.BasePoly var BasePoly=(function(){ function BasePoly(x,y,width,height,edges,color,borderWidth,borderColor,round){ //this.x=NaN; //this.y=NaN; //this.r=NaN; //this.width=NaN; //this.height=NaN; //this.edges=NaN; this.r0=0 //this.color=0; //this.borderColor=NaN; //this.borderWidth=NaN; //this.round=0; this.fill=true; //this.mUint16Array=null; //this.mFloat32Array=null; this.r1=Math.PI / 2; (round===void 0)&& (round=0); this.x=x; this.y=y; this.width=width; this.height=height; this.edges=edges; this.color=color; this.borderWidth=borderWidth; this.borderColor=borderColor; } __class(BasePoly,'laya.webgl.shapes.BasePoly'); var __proto=BasePoly.prototype; Laya.imps(__proto,{"laya.webgl.shapes.IShape":true}) __proto.getData=function(ib,vb,start){} __proto.rebuild=function(points){} __proto.setMatrix=function(mat){} __proto.needUpdate=function(mat){ return true; } __proto.sector=function(outVert,outIndex,start){ var x=this.x,y=this.y,edges=this.edges,seg=(this.r1-this.r0)/ edges; var w=this.width,h=this.height,color=this.color; var r=((color >> 16)& 0x0000ff)/ 255,g=((color >> 8)& 0xff)/ 255,b=(color & 0x0000ff)/ 255; outVert.push(x,y,r,g,b); for (var i=0;i < edges+1;i++){ outVert.push(x+Math.sin(seg *i+this.r0)*w,y+Math.cos(seg *i+this.r0)*h); outVert.push(r,g,b); } for (i=0;i < edges;i++){ outIndex.push(start,start+i+1,start+i+2); } } //用于画线 __proto.createLine2=function(p,indices,lineWidth,len,outVertex,indexCount){ var points=p.concat(); var result=outVertex; var color=this.borderColor; var r=((color >> 16)& 0x0000ff)/ 255,g=((color >> 8)& 0xff)/ 255,b=(color & 0x0000ff)/ 255; var length=points.length / 2; var iStart=len,w=lineWidth / 2; var px,py,p1x,p1y,p2x,p2y,p3x,p3y; var perpx,perpy,perp2x,perp2y,perp3x,perp3y; var a1,b1,c1,a2,b2,c2; var denom,pdist,dist; p1x=points[0]; p1y=points[1]; p2x=points[2]; p2y=points[3]; perpx=-(p1y-p2y); perpy=p1x-p2x; dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx=perpx / dist *w; perpy=perpy / dist *w; result.push(p1x-perpx+this.x,p1y-perpy+this.y,r,g,b,p1x+perpx+this.x,p1y+perpy+this.y,r,g,b); for (var i=1;i < length-1;i++){ p1x=points[(i-1)*2]; p1y=points[(i-1)*2+1]; p2x=points[(i)*2]; p2y=points[(i)*2+1]; p3x=points[(i+1)*2]; p3y=points[(i+1)*2+1]; perpx=-(p1y-p2y); perpy=p1x-p2x; dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx=perpx / dist *w; perpy=perpy / dist *w; perp2x=-(p2y-p3y); perp2y=p2x-p3x; dist=Math.sqrt(perp2x *perp2x+perp2y *perp2y); perp2x=perp2x / dist *w; perp2y=perp2y / dist *w; a1=(-perpy+p1y)-(-perpy+p2y); b1=(-perpx+p2x)-(-perpx+p1x); c1=(-perpx+p1x)*(-perpy+p2y)-(-perpx+p2x)*(-perpy+p1y); a2=(-perp2y+p3y)-(-perp2y+p2y); b2=(-perp2x+p2x)-(-perp2x+p3x); c2=(-perp2x+p3x)*(-perp2y+p2y)-(-perp2x+p2x)*(-perp2y+p3y); denom=a1 *b2-a2 *b1; if (Math.abs(denom)< 0.1){ denom+=10.1; result.push(p2x-perpx+this.x,p2y-perpy+this.y,r,g,b,p2x+perpx+this.x,p2y+perpy+this.y,r,g,b); continue ; } px=(b1 *c2-b2 *c1)/ denom; py=(a2 *c1-a1 *c2)/ denom; pdist=(px-p2x)*(px-p2x)+(py-p2y)+(py-p2y); result.push(px+this.x,py+this.y,r,g,b,p2x-(px-p2x)+this.x,p2y-(py-p2y)+this.y,r,g,b); } p1x=points[points.length-4]; p1y=points[points.length-3]; p2x=points[points.length-2]; p2y=points[points.length-1]; perpx=-(p1y-p2y); perpy=p1x-p2x; dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx=perpx / dist *w; perpy=perpy / dist *w; result.push(p2x-perpx+this.x,p2y-perpy+this.y,r,g,b,p2x+perpx+this.x,p2y+perpy+this.y,r,g,b); var groupLen=indexCount; for (i=1;i < groupLen;i++){ indices.push(iStart+(i-1)*2,iStart+(i-1)*2+1,iStart+i *2+1,iStart+i *2+1,iStart+i *2,iStart+(i-1)*2); } return result; } // /*,outVertex:Array,outIndex:Array*/ __proto.createLine=function(p,indices,lineWidth,len){ var points=p.concat(); var result=p; var color=this.borderColor; var r=((color >> 16)& 0x0000ff)/ 255,g=((color >> 8)& 0xff)/ 255,b=(color & 0x0000ff)/ 255; points.splice(0,5); var length=points.length / 5; var iStart=len,w=lineWidth / 2; var px,py,p1x,p1y,p2x,p2y,p3x,p3y; var perpx,perpy,perp2x,perp2y,perp3x,perp3y; var a1,b1,c1,a2,b2,c2; var denom,pdist,dist; p1x=points[0]; p1y=points[1]; p2x=points[5]; p2y=points[6]; perpx=-(p1y-p2y); perpy=p1x-p2x; dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx=perpx / dist *w; perpy=perpy / dist *w; result.push(p1x-perpx,p1y-perpy,r,g,b,p1x+perpx,p1y+perpy,r,g,b); for (var i=1;i < length-1;i++){ p1x=points[(i-1)*5]; p1y=points[(i-1)*5+1]; p2x=points[(i)*5]; p2y=points[(i)*5+1]; p3x=points[(i+1)*5]; p3y=points[(i+1)*5+1]; perpx=-(p1y-p2y); perpy=p1x-p2x; dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx=perpx / dist *w; perpy=perpy / dist *w; perp2x=-(p2y-p3y); perp2y=p2x-p3x; dist=Math.sqrt(perp2x *perp2x+perp2y *perp2y); perp2x=perp2x / dist *w; perp2y=perp2y / dist *w; a1=(-perpy+p1y)-(-perpy+p2y); b1=(-perpx+p2x)-(-perpx+p1x); c1=(-perpx+p1x)*(-perpy+p2y)-(-perpx+p2x)*(-perpy+p1y); a2=(-perp2y+p3y)-(-perp2y+p2y); b2=(-perp2x+p2x)-(-perp2x+p3x); c2=(-perp2x+p3x)*(-perp2y+p2y)-(-perp2x+p2x)*(-perp2y+p3y); denom=a1 *b2-a2 *b1; if (Math.abs(denom)< 0.1){ denom+=10.1; result.push(p2x-perpx,p2y-perpy,r,g,b,p2x+perpx,p2y+perpy,r,g,b); continue ; } px=(b1 *c2-b2 *c1)/ denom; py=(a2 *c1-a1 *c2)/ denom; pdist=(px-p2x)*(px-p2x)+(py-p2y)+(py-p2y); result.push(px,py,r,g,b,p2x-(px-p2x),p2y-(py-p2y),r,g,b); } p1x=points[points.length-10]; p1y=points[points.length-9]; p2x=points[points.length-5]; p2y=points[points.length-4]; perpx=-(p1y-p2y); perpy=p1x-p2x; dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx=perpx / dist *w; perpy=perpy / dist *w; result.push(p2x-perpx,p2y-perpy,r,g,b,p2x+perpx,p2y+perpy,r,g,b); var groupLen=this.edges+1; for (i=1;i < groupLen;i++){ indices.push(iStart+(i-1)*2,iStart+(i-1)*2+1,iStart+i *2+1,iStart+i *2+1,iStart+i *2,iStart+(i-1)*2); } return result; } //闭合路径 __proto.createLoopLine=function(p,indices,lineWidth,len,outVertex,outIndex){ var points=p.concat(); var result=outVertex ? outVertex :p; var color=this.borderColor; var r=((color >> 16)& 0x0000ff)/ 255,g=((color >> 8)& 0xff)/ 255,b=(color & 0x0000ff)/ 255; points.splice(0,5); var firstPoint=[points[0],points[1]]; var lastPoint=[points[points.length-5],points[points.length-4]]; var midPointX=lastPoint[0]+(firstPoint[0]-lastPoint[0])*0.5; var midPointY=lastPoint[1]+(firstPoint[1]-lastPoint[1])*0.5; points.unshift(midPointX,midPointY,0,0,0); points.push(midPointX,midPointY,0,0,0); var length=points.length / 5; var iStart=len,w=lineWidth / 2; var px,py,p1x,p1y,p2x,p2y,p3x,p3y; var perpx,perpy,perp2x,perp2y,perp3x,perp3y; var a1,b1,c1,a2,b2,c2; var denom,pdist,dist; p1x=points[0]; p1y=points[1]; p2x=points[5]; p2y=points[6]; perpx=-(p1y-p2y); perpy=p1x-p2x; dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx=perpx / dist *w; perpy=perpy / dist *w; result.push(p1x-perpx,p1y-perpy,r,g,b,p1x+perpx,p1y+perpy,r,g,b); for (var i=1;i < length-1;i++){ p1x=points[(i-1)*5]; p1y=points[(i-1)*5+1]; p2x=points[(i)*5]; p2y=points[(i)*5+1]; p3x=points[(i+1)*5]; p3y=points[(i+1)*5+1]; perpx=-(p1y-p2y); perpy=p1x-p2x; dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx=perpx / dist *w; perpy=perpy / dist *w; perp2x=-(p2y-p3y); perp2y=p2x-p3x; dist=Math.sqrt(perp2x *perp2x+perp2y *perp2y); perp2x=perp2x / dist *w; perp2y=perp2y / dist *w; a1=(-perpy+p1y)-(-perpy+p2y); b1=(-perpx+p2x)-(-perpx+p1x); c1=(-perpx+p1x)*(-perpy+p2y)-(-perpx+p2x)*(-perpy+p1y); a2=(-perp2y+p3y)-(-perp2y+p2y); b2=(-perp2x+p2x)-(-perp2x+p3x); c2=(-perp2x+p3x)*(-perp2y+p2y)-(-perp2x+p2x)*(-perp2y+p3y); denom=a1 *b2-a2 *b1; if (Math.abs(denom)< 0.1){ denom+=10.1; result.push(p2x-perpx,p2y-perpy,r,g,b,p2x+perpx,p2y+perpy,r,g,b); continue ; } px=(b1 *c2-b2 *c1)/ denom; py=(a2 *c1-a1 *c2)/ denom; pdist=(px-p2x)*(px-p2x)+(py-p2y)+(py-p2y); result.push(px,py,r,g,b,p2x-(px-p2x),p2y-(py-p2y),r,g,b); } if (outIndex){ indices=outIndex; }; var groupLen=this.edges+1; for (i=1;i < groupLen;i++){ indices.push(iStart+(i-1)*2,iStart+(i-1)*2+1,iStart+i *2+1,iStart+i *2+1,iStart+i *2,iStart+(i-1)*2); } indices.push(iStart+(i-1)*2,iStart+(i-1)*2+1,iStart+1,iStart+1,iStart,iStart+(i-1)*2); return result; } return BasePoly; })() //class laya.webgl.shapes.Earcut var Earcut=(function(){ function Earcut(){} __class(Earcut,'laya.webgl.shapes.Earcut'); Earcut.earcut=function(data,holeIndices,dim){ dim=dim || 2; var hasHoles=holeIndices && holeIndices.length, outerLen=hasHoles ? holeIndices[0] *dim :data.length, outerNode=Earcut.linkedList(data,0,outerLen,dim,true), triangles=[]; if (!outerNode)return triangles; var minX,minY,maxX,maxY,x,y,invSize; if (hasHoles)outerNode=Earcut.eliminateHoles(data,holeIndices,outerNode,dim); if (data.length > 80 *dim){ minX=maxX=data[0]; minY=maxY=data[1]; for (var i=dim;i < outerLen;i+=dim){ x=data[i]; y=data[i+1]; if (x < minX)minX=x; if (y < minY)minY=y; if (x > maxX)maxX=x; if (y > maxY)maxY=y; } invSize=Math.max(maxX-minX,maxY-minY); invSize=invSize!==0 ? 1 / invSize :0; } Earcut.earcutLinked(outerNode,triangles,dim,minX,minY,invSize); return triangles; } Earcut.linkedList=function(data,start,end,dim,clockwise){ var i,last; if (clockwise===(Earcut.signedArea(data,start,end,dim)> 0)){ for (i=start;i < end;i+=dim)last=Earcut.insertNode(i,data[i],data[i+1],last); }else { for (i=end-dim;i >=start;i-=dim)last=Earcut.insertNode(i,data[i],data[i+1],last); } if (last && Earcut.equals(last,last.next)){ Earcut.removeNode(last); last=last.next; } return last; } Earcut.filterPoints=function(start,end){ if (!start)return start; if (!end)end=start; var p=start, again; do { again=false; if (!p.steiner && (Earcut.equals(p,p.next)|| Earcut.area(p.prev,p,p.next)===0)){ Earcut.removeNode(p); p=end=p.prev; if (p===p.next)break ; again=true; }else { p=p.next; } }while (again || p!==end); return end; } Earcut.earcutLinked=function(ear,triangles,dim,minX,minY,invSize,pass){ if (!ear)return; if (!pass && invSize)Earcut.indexCurve(ear,minX,minY,invSize); var stop=ear, prev,next; while (ear.prev!==ear.next){ prev=ear.prev; next=ear.next; if (invSize ? Earcut.isEarHashed(ear,minX,minY,invSize):Earcut.isEar(ear)){ triangles.push(prev.i / dim); triangles.push(ear.i / dim); triangles.push(next.i / dim); Earcut.removeNode(ear); ear=next.next; stop=next.next; continue ; } ear=next; if (ear===stop){ if (!pass){ Earcut.earcutLinked(Earcut.filterPoints(ear,null),triangles,dim,minX,minY,invSize,1); }else if (pass===1){ ear=Earcut.cureLocalIntersections(ear,triangles,dim); Earcut.earcutLinked(ear,triangles,dim,minX,minY,invSize,2); }else if (pass===2){ Earcut.splitEarcut(ear,triangles,dim,minX,minY,invSize); } break ; } } } Earcut.isEar=function(ear){ var a=ear.prev, b=ear, c=ear.next; if (Earcut.area(a,b,c)>=0)return false; var p=ear.next.next; while (p!==ear.prev){ if (Earcut.pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&& Earcut.area(p.prev,p,p.next)>=0)return false; p=p.next; } return true; } Earcut.isEarHashed=function(ear,minX,minY,invSize){ var a=ear.prev, b=ear, c=ear.next; if (Earcut.area(a,b,c)>=0)return false; var minTX=a.x < b.x ? (a.x < c.x ? a.x :c.x):(b.x < c.x ? b.x :c.x), minTY=a.y < b.y ? (a.y < c.y ? a.y :c.y):(b.y < c.y ? b.y :c.y), maxTX=a.x > b.x ? (a.x > c.x ? a.x :c.x):(b.x > c.x ? b.x :c.x), maxTY=a.y > b.y ? (a.y > c.y ? a.y :c.y):(b.y > c.y ? b.y :c.y); var minZ=Earcut.zOrder(minTX,minTY,minX,minY,invSize), maxZ=Earcut.zOrder(maxTX,maxTY,minX,minY,invSize); var p=ear.nextZ; while (p && p.z <=maxZ){ if (p!==ear.prev && p!==ear.next && Earcut.pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&& Earcut.area(p.prev,p,p.next)>=0)return false; p=p.nextZ; } p=ear.prevZ; while (p && p.z >=minZ){ if (p!==ear.prev && p!==ear.next && Earcut.pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&& Earcut.area(p.prev,p,p.next)>=0)return false; p=p.prevZ; } return true; } Earcut.cureLocalIntersections=function(start,triangles,dim){ var p=start; do { var a=p.prev, b=p.next.next; if (!Earcut.equals(a,b)&& Earcut.intersects(a,p,p.next,b)&& Earcut.locallyInside(a,b)&& Earcut.locallyInside(b,a)){ triangles.push(a.i / dim); triangles.push(p.i / dim); triangles.push(b.i / dim); Earcut.removeNode(p); Earcut.removeNode(p.next); p=start=b; } p=p.next; }while (p!==start); return p; } Earcut.splitEarcut=function(start,triangles,dim,minX,minY,invSize){ var a=start; do { var b=a.next.next; while (b!==a.prev){ if (a.i!==b.i && Earcut.isValidDiagonal(a,b)){ var c=Earcut.splitPolygon(a,b); a=Earcut.filterPoints(a,a.next); c=Earcut.filterPoints(c,c.next); Earcut.earcutLinked(a,triangles,dim,minX,minY,invSize); Earcut.earcutLinked(c,triangles,dim,minX,minY,invSize); return; } b=b.next; } a=a.next; }while (a!==start); } Earcut.eliminateHoles=function(data,holeIndices,outerNode,dim){ var queue=[], i,len,start,end,list; for (i=0,len=holeIndices.length;i < len;i++){ start=holeIndices[i] *dim; end=i < len-1 ? holeIndices[i+1] *dim :data.length; list=Earcut.linkedList(data,start,end,dim,false); if (list===list.next)list.steiner=true; queue.push(Earcut.getLeftmost(list)); } queue.sort(Earcut.compareX); for (i=0;i < queue.length;i++){ Earcut.eliminateHole(queue[i],outerNode); outerNode=Earcut.filterPoints(outerNode,outerNode.next); } return outerNode; } Earcut.compareX=function(a,b){ return a.x-b.x; } Earcut.eliminateHole=function(hole,outerNode){ outerNode=Earcut.findHoleBridge(hole,outerNode); if (outerNode){ var b=Earcut.splitPolygon(outerNode,hole); Earcut.filterPoints(b,b.next); } } Earcut.findHoleBridge=function(hole,outerNode){ var p=outerNode, hx=hole.x, hy=hole.y, qx=-Infinity, m; do { if (hy <=p.y && hy >=p.next.y && p.next.y!==p.y){ var x=p.x+(hy-p.y)*(p.next.x-p.x)/ (p.next.y-p.y); if (x <=hx && x > qx){ qx=x; if (x===hx){ if (hy===p.y)return p; if (hy===p.next.y)return p.next; } m=p.x < p.next.x ? p :p.next; } } p=p.next; }while (p!==outerNode); if (!m)return null; if (hx===qx)return m.prev; var stop=m, mx=m.x, my=m.y, tanMin=Infinity, tan; p=m.next; while (p!==stop){ if (hx >=p.x && p.x >=mx && hx!==p.x && Earcut.pointInTriangle(hy < my ? hx :qx,hy,mx,my,hy < my ? qx :hx,hy,p.x,p.y)){ tan=Math.abs(hy-p.y)/ (hx-p.x); if ((tan < tanMin || (tan===tanMin && p.x > m.x))&& Earcut.locallyInside(p,hole)){ m=p; tanMin=tan; } } p=p.next; } return m; } Earcut.indexCurve=function(start,minX,minY,invSize){ var p=start; do { if (p.z===null)p.z=Earcut.zOrder(p.x,p.y,minX,minY,invSize); p.prevZ=p.prev; p.nextZ=p.next; p=p.next; }while (p!==start); p.prevZ.nextZ=null; p.prevZ=null; Earcut.sortLinked(p); } Earcut.sortLinked=function(list){ var i,p,q,e,tail,numMerges,pSize,qSize, inSize=1; do { p=list; list=null; tail=null; numMerges=0; while (p){ numMerges++; q=p; pSize=0; for (i=0;i < inSize;i++){ pSize++; q=q.nextZ; if (!q)break ; } qSize=inSize; while (pSize > 0 || (qSize > 0 && q)){ if (pSize!==0 && (qSize===0 || !q || p.z <=q.z)){ e=p; p=p.nextZ; pSize--; }else { e=q; q=q.nextZ; qSize--; } if (tail)tail.nextZ=e; else list=e; e.prevZ=tail; tail=e; } p=q; } tail.nextZ=null; inSize *=2; }while (numMerges > 1); return list; } Earcut.zOrder=function(x,y,minX,minY,invSize){ x=32767 *(x-minX)*invSize; y=32767 *(y-minY)*invSize; x=(x | (x << 8))& 0x00FF00FF; x=(x | (x << 4))& 0x0F0F0F0F; x=(x | (x << 2))& 0x33333333; x=(x | (x << 1))& 0x55555555; y=(y | (y << 8))& 0x00FF00FF; y=(y | (y << 4))& 0x0F0F0F0F; y=(y | (y << 2))& 0x33333333; y=(y | (y << 1))& 0x55555555; return x | (y << 1); } Earcut.getLeftmost=function(start){ var p=start, leftmost=start; do { if (p.x < leftmost.x)leftmost=p; p=p.next; }while (p!==start); return leftmost; } Earcut.pointInTriangle=function(ax,ay,bx,by,cx,cy,px,py){ return (cx-px)*(ay-py)-(ax-px)*(cy-py)>=0 && (ax-px)*(by-py)-(bx-px)*(ay-py)>=0 && (bx-px)*(cy-py)-(cx-px)*(by-py)>=0; } Earcut.isValidDiagonal=function(a,b){ return a.next.i!==b.i && a.prev.i!==b.i && !Earcut.intersectsPolygon(a,b)&& Earcut.locallyInside(a,b)&& Earcut.locallyInside(b,a)&& Earcut.middleInside(a,b); } Earcut.area=function(p,q,r){ return (q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y); } Earcut.equals=function(p1,p2){ return p1.x===p2.x && p1.y===p2.y; } Earcut.intersects=function(p1,q1,p2,q2){ if ((Earcut.equals(p1,q1)&& Earcut.equals(p2,q2))|| (Earcut.equals(p1,q2)&& Earcut.equals(p2,q1)))return true; return Earcut.area(p1,q1,p2)> 0!==Earcut.area(p1,q1,q2)> 0 && Earcut.area(p2,q2,p1)> 0!==Earcut.area(p2,q2,q1)> 0; } Earcut.intersectsPolygon=function(a,b){ var p=a; do { if (p.i!==a.i && p.next.i!==a.i && p.i!==b.i && p.next.i!==b.i && Earcut.intersects(p,p.next,a,b))return true; p=p.next; }while (p!==a); return false; } Earcut.locallyInside=function(a,b){ return Earcut.area(a.prev,a,a.next)< 0 ? Earcut.area(a,b,a.next)>=0 && Earcut.area(a,a.prev,b)>=0 : Earcut.area(a,b,a.prev)< 0 || Earcut.area(a,a.next,b)< 0; } Earcut.middleInside=function(a,b){ var p=a, inside=false, px=(a.x+b.x)/ 2, py=(a.y+b.y)/ 2; do { if (((p.y > py)!==(p.next.y > py))&& p.next.y!==p.y && (px < (p.next.x-p.x)*(py-p.y)/ (p.next.y-p.y)+p.x)) inside=!inside; p=p.next; }while (p!==a); return inside; } Earcut.splitPolygon=function(a,b){ var a2=new EarcutNode(a.i,a.x,a.y), b2=new EarcutNode(b.i,b.x,b.y), an=a.next, bp=b.prev; a.next=b; b.prev=a; a2.next=an; an.prev=a2; b2.next=a2; a2.prev=b2; bp.next=b2; b2.prev=bp; return b2; } Earcut.insertNode=function(i,x,y,last){ var p=new EarcutNode(i,x,y); if (!last){ p.prev=p; p.next=p; }else { p.next=last.next; p.prev=last; last.next.prev=p; last.next=p; } return p; } Earcut.removeNode=function(p){ p.next.prev=p.prev; p.prev.next=p.next; if (p.prevZ)p.prevZ.nextZ=p.nextZ; if (p.nextZ)p.nextZ.prevZ=p.prevZ; } Earcut.signedArea=function(data,start,end,dim){ var sum=0; for (var i=start,j=end-dim;i < end;i+=dim){ sum+=(data[j]-data[i])*(data[i+1]+data[j+1]); j=i; } return sum; } return Earcut; })() //class laya.webgl.shapes.EarcutNode var EarcutNode=(function(){ function EarcutNode(i,x,y){ this.i=null; this.x=null; this.y=null; this.prev=null; this.next=null; this.z=null; this.prevZ=null; this.nextZ=null; this.steiner=null; this.i=i; this.x=x; this.y=y; this.prev=null; this.next=null; this.z=null; this.prevZ=null; this.nextZ=null; this.steiner=false; } __class(EarcutNode,'laya.webgl.shapes.EarcutNode'); return EarcutNode; })() //class laya.webgl.shapes.GeometryData var GeometryData=(function(){ function GeometryData(lineWidth,lineColor,lineAlpha,fillColor,fillAlpha,fill,shape){ //this.lineWidth=NaN; //this.lineColor=NaN; //this.lineAlpha=NaN; //this.fillColor=NaN; //this.fillAlpha=NaN; //this.shape=null; //this.fill=false; this.lineWidth=lineWidth; this.lineColor=lineColor; this.lineAlpha=lineAlpha; this.fillColor=fillColor; this.fillAlpha=fillAlpha; this.shape=shape; this.fill=fill; } __class(GeometryData,'laya.webgl.shapes.GeometryData'); var __proto=GeometryData.prototype; __proto.clone=function(){ return new GeometryData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape); } __proto.getIndexData=function(){ return null; } __proto.getVertexData=function(){ return null; } __proto.destroy=function(){ this.shape=null; } return GeometryData; })() //class laya.webgl.shapes.Vertex var Vertex=(function(){ function Vertex(p){ //this.points=null; if((p instanceof Float32Array)) this.points=p; else if((p instanceof Array)){ var len=p.length; this.points=new Float32Array(p); } } __class(Vertex,'laya.webgl.shapes.Vertex'); var __proto=Vertex.prototype; Laya.imps(__proto,{"laya.webgl.shapes.IShape":true}) __proto.getData=function(ib,vb,start){} __proto.needUpdate=function(mat){ return false; } __proto.rebuild=function(points){} // TODO Auto Generated method stub __proto.setMatrix=function(mat){} return Vertex; })() //class laya.webgl.submit.Submit var Submit=(function(){ function Submit(renderType){ //this._selfVb=null; //this._ib=null; //this._blendFn=null; //this._renderType=0; //this._vb=null; // 从VB中什么地方开始画,画到哪 //this._startIdx=0; //this._numEle=0; //this.shaderValue=null; (renderType===void 0)&& (renderType=10000); this._renderType=renderType; } __class(Submit,'laya.webgl.submit.Submit'); var __proto=Submit.prototype; Laya.imps(__proto,{"laya.webgl.submit.ISubmit":true}) __proto.releaseRender=function(){ var cache=Submit._cache; cache[cache._length++]=this; this.shaderValue.release(); this._vb=null; } __proto.getRenderType=function(){ return this._renderType; } __proto.renderSubmit=function(){ if (this._numEle===0)return 1; var _tex=this.shaderValue.textureHost; if (_tex){ var source=_tex.source; if (!_tex.bitmap || !source) return 1; this.shaderValue.texture=source; } this._vb.bind_upload(this._ib); var gl=WebGL.mainContext; this.shaderValue.upload(); if (BlendMode.activeBlendFunction!==this._blendFn){ gl.enable(/*laya.webgl.WebGLContext.BLEND*/0x0BE2); this._blendFn(gl); BlendMode.activeBlendFunction=this._blendFn; } Stat.drawCall++; Stat.trianglesFaces+=this._numEle / 3; gl.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._numEle,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this._startIdx); return 1; } Submit.__init__=function(){ var s=Submit.RENDERBASE=new Submit(-1); s.shaderValue=new Value2D(0,0); s.shaderValue.ALPHA=-1234; } Submit.createSubmit=function(context,ib,vb,pos,sv){ var o=Submit._cache._length ? Submit._cache[--Submit._cache._length] :new Submit(); if (vb==null){ vb=o._selfVb || (o._selfVb=VertexBuffer2D.create(-1)); vb.clear(); pos=0; } o._ib=ib; o._vb=vb; o._startIdx=pos *CONST3D2D.BYTES_PIDX; o._numEle=0; var blendType=context._nBlendType; o._blendFn=context._targets ? BlendMode.targetFns[blendType] :BlendMode.fns[blendType]; o.shaderValue=sv; o.shaderValue.setValue(context._shader2D); var filters=context._shader2D.filters; filters && o.shaderValue.setFilters(filters); return o; } Submit.createShape=function(ctx,ib,vb,numEle,offset,sv){ var o=(!Submit._cache._length)? (new Submit()):Submit._cache[--Submit._cache._length]; o._ib=ib; o._vb=vb; o._numEle=numEle; o._startIdx=offset; o.shaderValue=sv; o.shaderValue.setValue(ctx._shader2D); var blendType=ctx._nBlendType; o._blendFn=ctx._targets ? BlendMode.targetFns[blendType] :BlendMode.fns[blendType]; return o; } Submit.TYPE_2D=10000; Submit.TYPE_CANVAS=10003; Submit.TYPE_CMDSETRT=10004; Submit.TYPE_CUSTOM=10005; Submit.TYPE_BLURRT=10006; Submit.TYPE_CMDDESTORYPRERT=10007; Submit.TYPE_DISABLESTENCIL=10008; Submit.TYPE_OTHERIBVB=10009; Submit.TYPE_PRIMITIVE=10010; Submit.TYPE_RT=10011; Submit.TYPE_BLUR_RT=10012; Submit.TYPE_TARGET=10013; Submit.TYPE_CHANGE_VALUE=10014; Submit.TYPE_SHAPE=10015; Submit.TYPE_TEXTURE=10016; Submit.TYPE_FILLTEXTURE=10017; Submit.RENDERBASE=null; Submit._cache=(Submit._cache=[],Submit._cache._length=0,Submit._cache); return Submit; })() //class laya.webgl.submit.SubmitCMD var SubmitCMD=(function(){ function SubmitCMD(){ this.fun=null; this.args=null; } __class(SubmitCMD,'laya.webgl.submit.SubmitCMD'); var __proto=SubmitCMD.prototype; Laya.imps(__proto,{"laya.webgl.submit.ISubmit":true}) __proto.renderSubmit=function(){ this.fun.apply(null,this.args); return 1; } __proto.getRenderType=function(){ return 0; } __proto.releaseRender=function(){ var cache=SubmitCMD._cache; cache[cache._length++]=this; } SubmitCMD.create=function(args,fun){ var o=SubmitCMD._cache._length?SubmitCMD._cache[--SubmitCMD._cache._length]:new SubmitCMD(); o.fun=fun; o.args=args; return o; } SubmitCMD._cache=(SubmitCMD._cache=[],SubmitCMD._cache._length=0,SubmitCMD._cache); return SubmitCMD; })() //class laya.webgl.submit.SubmitCMDScope var SubmitCMDScope=(function(){ function SubmitCMDScope(){ this.variables={}; } __class(SubmitCMDScope,'laya.webgl.submit.SubmitCMDScope'); var __proto=SubmitCMDScope.prototype; __proto.getValue=function(name){ return this.variables[name]; } __proto.addValue=function(name,value){ return this.variables[name]=value; } __proto.setValue=function(name,value){ if(this.variables.hasOwnProperty(name)){ return this.variables[name]=value; } return null; } __proto.clear=function(){ for(var key in this.variables){ delete this.variables[key]; } } __proto.recycle=function(){ this.clear(); SubmitCMDScope.POOL.push(this); } SubmitCMDScope.create=function(){ var scope=SubmitCMDScope.POOL.pop(); scope||(scope=new SubmitCMDScope()); return scope; } SubmitCMDScope.POOL=[]; return SubmitCMDScope; })() //class laya.webgl.submit.SubmitOtherIBVB var SubmitOtherIBVB=(function(){ function SubmitOtherIBVB(){ this.offset=0; //this._vb=null; //this._ib=null; //this._blendFn=null; //this._mat=null; //this._shader=null; //this._shaderValue=null; //this._numEle=0; this.startIndex=0; ; this._mat=Matrix.create(); } __class(SubmitOtherIBVB,'laya.webgl.submit.SubmitOtherIBVB'); var __proto=SubmitOtherIBVB.prototype; Laya.imps(__proto,{"laya.webgl.submit.ISubmit":true}) __proto.releaseRender=function(){ var cache=SubmitOtherIBVB._cache; cache[cache._length++]=this; } __proto.getRenderType=function(){ return /*laya.webgl.submit.Submit.TYPE_OTHERIBVB*/10009; } __proto.renderSubmit=function(){ var _tex=this._shaderValue.textureHost; if (_tex){ var source=_tex.source; if (!_tex.bitmap || !source) return 1; this._shaderValue.texture=source; } this._vb.bind_upload(this._ib); var w=RenderState2D.worldMatrix4; var wmat=Matrix.TEMP; Matrix.mulPre(this._mat,w[0],w[1],w[4],w[5],w[12],w[13],wmat); var tmp=RenderState2D.worldMatrix4=SubmitOtherIBVB.tempMatrix4; tmp[0]=wmat.a; tmp[1]=wmat.b; tmp[4]=wmat.c; tmp[5]=wmat.d; tmp[12]=wmat.tx; tmp[13]=wmat.ty; this._shader._offset=this.offset; this._shaderValue.refresh(); this._shader.upload(this._shaderValue); this._shader._offset=0; var gl=WebGL.mainContext; if (BlendMode.activeBlendFunction!==this._blendFn){ gl.enable(/*laya.webgl.WebGLContext.BLEND*/0x0BE2); this._blendFn(gl); BlendMode.activeBlendFunction=this._blendFn; } Stat.drawCall++; Stat.trianglesFaces+=this._numEle / 3; gl.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._numEle,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this.startIndex); RenderState2D.worldMatrix4=w; BaseShader.activeShader=null; return 1; } SubmitOtherIBVB.create=function(context,vb,ib,numElement,shader,shaderValue,startIndex,offset,type){ (type===void 0)&& (type=0); var o=(!SubmitOtherIBVB._cache._length)? (new SubmitOtherIBVB()):SubmitOtherIBVB._cache[--SubmitOtherIBVB._cache._length]; o._ib=ib; o._vb=vb; o._numEle=numElement; o._shader=shader; o._shaderValue=shaderValue; var blendType=context._nBlendType; o._blendFn=context._targets ? BlendMode.targetFns[blendType] :BlendMode.fns[blendType]; switch(type){ case 0: o.offset=0; o.startIndex=offset / (CONST3D2D.BYTES_PE *vb.vertexStride)*1.5; o.startIndex *=CONST3D2D.BYTES_PIDX; break ; case 1: o.startIndex=startIndex; o.offset=offset; break ; } return o; } SubmitOtherIBVB._cache=(SubmitOtherIBVB._cache=[],SubmitOtherIBVB._cache._length=0,SubmitOtherIBVB._cache); SubmitOtherIBVB.tempMatrix4=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,]; return SubmitOtherIBVB; })() //class laya.webgl.submit.SubmitScissor var SubmitScissor=(function(){ function SubmitScissor(){ this.submitIndex=0; this.submitLength=0; this.context=null; this.clipRect=new Rectangle(); this.screenRect=new Rectangle(); } __class(SubmitScissor,'laya.webgl.submit.SubmitScissor'); var __proto=SubmitScissor.prototype; Laya.imps(__proto,{"laya.webgl.submit.ISubmit":true}) __proto._scissor=function(x,y,w,h){ var m=RenderState2D.worldMatrix4; var a=m[0],d=m[5],tx=m[12],ty=m[13]; x=x *a+tx; y=y *d+ty; w *=a; h *=d; if (w < 1 || h < 1){ return false; }; var r=x+w; var b=y+h; x < 0 && (x=0,w=r-x); y < 0 && (y=0,h=b-y); var screen=RenderState2D.worldClipRect; x=Math.max(x,screen.x); y=Math.max(y,screen.y); w=Math.min(r,screen.right)-x; h=Math.min(b,screen.bottom)-y; if (w < 1 || h < 1){ return false; }; var worldScissorTest=RenderState2D.worldScissorTest; this.screenRect.copyFrom(screen); screen.x=x; screen.y=y; screen.width=w; screen.height=h; RenderState2D.worldScissorTest=true; y=RenderState2D.height-y-h; WebGL.mainContext.scissor(x,y,w,h); WebGL.mainContext.enable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); this.context.submitElement(this.submitIndex,this.submitIndex+this.submitLength); if (worldScissorTest){ y=RenderState2D.height-this.screenRect.y-this.screenRect.height; WebGL.mainContext.scissor(this.screenRect.x,y,this.screenRect.width,this.screenRect.height); WebGL.mainContext.enable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); } else{ WebGL.mainContext.disable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); RenderState2D.worldScissorTest=false; } screen.copyFrom(this.screenRect); return true; } __proto._scissorWithTagart=function(x,y,w,h){ if (w < 1 || h < 1){ return false; }; var r=x+w; var b=y+h; x < 0 && (x=0,w=r-x); y < 0 && (y=0,h=b-y); var screen=RenderState2D.worldClipRect; x=Math.max(x,screen.x); y=Math.max(y,screen.y); w=Math.min(r,screen.right)-x; h=Math.min(b,screen.bottom)-y; if (w < 1 || h < 1){ return false; }; var worldScissorTest=RenderState2D.worldScissorTest; this.screenRect.copyFrom(screen); RenderState2D.worldScissorTest=true; screen.x=x; screen.y=y; screen.width=w; screen.height=h; y=RenderState2D.height-y-h; WebGL.mainContext.scissor(x,y,w,h); WebGL.mainContext.enable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); this.context.submitElement(this.submitIndex,this.submitIndex+this.submitLength); if (worldScissorTest){ y=RenderState2D.height-this.screenRect.y-this.screenRect.height; WebGL.mainContext.scissor(this.screenRect.x,y,this.screenRect.width,this.screenRect.height); WebGL.mainContext.enable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); } else{ WebGL.mainContext.disable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); RenderState2D.worldScissorTest=false; } screen.copyFrom(this.screenRect); return true; } __proto.renderSubmit=function(){ this.submitLength=Math.min(this.context._submits._length-1,this.submitLength); if (this.submitLength < 1 || this.clipRect.width < 1 || this.clipRect.height < 1) return this.submitLength+1; if (this.context._targets) this._scissorWithTagart(this.clipRect.x,this.clipRect.y,this.clipRect.width,this.clipRect.height); else this._scissor(this.clipRect.x,this.clipRect.y,this.clipRect.width,this.clipRect.height); return this.submitLength+1; } __proto.getRenderType=function(){ return 0; } __proto.releaseRender=function(){ var cache=SubmitScissor._cache; cache[cache._length++]=this; this.context=null; } SubmitScissor.create=function(context){ var o=SubmitScissor._cache._length?SubmitScissor._cache[--SubmitScissor._cache._length]:new SubmitScissor(); o.context=context; return o; } SubmitScissor._cache=(SubmitScissor._cache=[],SubmitScissor._cache._length=0,SubmitScissor._cache); return SubmitScissor; })() //class laya.webgl.submit.SubmitStencil var SubmitStencil=(function(){ function SubmitStencil(){ this.step=0; this.blendMode=null; this.level=0; } __class(SubmitStencil,'laya.webgl.submit.SubmitStencil'); var __proto=SubmitStencil.prototype; Laya.imps(__proto,{"laya.webgl.submit.ISubmit":true}) __proto.renderSubmit=function(){ switch(this.step){ case 1: this.do1(); break ; case 2: this.do2(); break ; case 3: this.do3(); break ; case 4: this.do4(); break ; case 5: this.do5(); break ; case 6: this.do6(); break ; case 7: this.do7(); break ; case 8: this.do8(); break ; } return 1; } __proto.getRenderType=function(){ return 0; } __proto.releaseRender=function(){ var cache=SubmitStencil._cache; cache[cache._length++]=this; } __proto.do1=function(){ var gl=WebGL.mainContext; gl.enable(/*laya.webgl.WebGLContext.STENCIL_TEST*/0x0B90); gl.clear(/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400); gl.colorMask(false,false,false,false); gl.stencilFunc(/*laya.webgl.WebGLContext.EQUAL*/0x0202,this.level,0xFF); gl.stencilOp(/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.INCR*/0x1E02); } //gl.stencilOp(WebGLContext.KEEP,WebGLContext.KEEP,WebGLContext.INVERT);//测试通过给模版缓冲 写入值 一开始是0 现在是 0xFF (模版缓冲中不知道是多少位的数据) __proto.do2=function(){ var gl=WebGL.mainContext; gl.stencilFunc(/*laya.webgl.WebGLContext.EQUAL*/0x0202,this.level+1,0xFF); gl.colorMask(true,true,true,true); gl.stencilOp(/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00); } __proto.do3=function(){ var gl=WebGL.mainContext; gl.colorMask(true,true,true,true); gl.stencilOp(/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00); gl.clear(/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400); gl.disable(/*laya.webgl.WebGLContext.STENCIL_TEST*/0x0B90); } __proto.do4=function(){ var gl=WebGL.mainContext; if (this.level==0){ gl.enable(/*laya.webgl.WebGLContext.STENCIL_TEST*/0x0B90); gl.clear(/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400); } gl.colorMask(false,false,false,false); gl.stencilFunc(/*laya.webgl.WebGLContext.ALWAYS*/0x0207,0,0xFF); gl.stencilOp(/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.INCR*/0x1E02); } __proto.do5=function(){ var gl=WebGL.mainContext; gl.stencilFunc(/*laya.webgl.WebGLContext.EQUAL*/0x0202,this.level,0xFF); gl.colorMask(true,true,true,true); gl.stencilOp(/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00); } __proto.do6=function(){ var gl=WebGL.mainContext; BlendMode.targetFns[BlendMode.TOINT[this.blendMode]](gl); } __proto.do7=function(){ var gl=WebGL.mainContext; gl.colorMask(false,false,false,false); gl.stencilOp(/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.DECR*/0x1E03); } __proto.do8=function(){ var gl=WebGL.mainContext; gl.colorMask(true,true,true,true); gl.stencilFunc(/*laya.webgl.WebGLContext.EQUAL*/0x0202,this.level,0xFF); gl.stencilOp(/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00,/*laya.webgl.WebGLContext.KEEP*/0x1E00); } SubmitStencil.restore=function(context,clip,m,_x,_y){ var submitStencil; context._renderKey=0; if (SubmitStencil._mask > 0){ SubmitStencil._mask--; } if (SubmitStencil._mask==0){ submitStencil=laya.webgl.submit.SubmitStencil.create(3); context.addRenderObject(submitStencil); context._curSubmit=Submit.RENDERBASE; } else{ submitStencil=laya.webgl.submit.SubmitStencil.create(7); context.addRenderObject(submitStencil); var vb=context._vb; var nPos=(vb._byteLength >> 2); if (GlUtils.fillRectImgVb(vb,null,clip.x,clip.y,clip.width,clip.height,Texture.DEF_UV,m,_x,_y,0,0)){ var shader=context._shader2D; shader.glTexture=null; var submit=context._curSubmit=Submit.createSubmit(context,context._ib,vb,((vb._byteLength-/*laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16 */*laya.webgl.utils.Buffer2D.FLOAT32*/4)/ 32)*3,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.COLOR2D*/0x02,0)); submit.shaderValue.ALPHA=1.0; context._submits[context._submits._length++]=submit; context._curSubmit._numEle+=6; context._curSubmit=Submit.RENDERBASE; }else { alert("clipRect calc stencil rect error"); } submitStencil=laya.webgl.submit.SubmitStencil.create(8); context.addRenderObject(submitStencil); } } SubmitStencil.restore2=function(context,submit){ var submitStencil; context._renderKey=0; if (SubmitStencil._mask > 0){ SubmitStencil._mask--; } if (SubmitStencil._mask==0){ submitStencil=laya.webgl.submit.SubmitStencil.create(3); context.addRenderObject(submitStencil); context._curSubmit=Submit.RENDERBASE; } else{ submitStencil=laya.webgl.submit.SubmitStencil.create(7); context.addRenderObject(submitStencil); context._submits[context._submits._length++]=submit; submitStencil=laya.webgl.submit.SubmitStencil.create(8); context.addRenderObject(submitStencil); } } SubmitStencil.create=function(step){ var o=SubmitStencil._cache._length?SubmitStencil._cache[--SubmitStencil._cache._length]:new SubmitStencil(); o.step=step; if (step==5) ++SubmitStencil._mask; o.level=SubmitStencil._mask; return o; } SubmitStencil._cache=(SubmitStencil._cache=[],SubmitStencil._cache._length=0,SubmitStencil._cache); SubmitStencil._mask=0; return SubmitStencil; })() //class laya.webgl.submit.SubmitTarget var SubmitTarget=(function(){ function SubmitTarget(){ this._renderType=0; this._vb=null; this._ib=null; this._startIdx=0; this._numEle=0; this.shaderValue=null; this.blendType=0; this.proName=null; this.scope=null; } __class(SubmitTarget,'laya.webgl.submit.SubmitTarget'); var __proto=SubmitTarget.prototype; Laya.imps(__proto,{"laya.webgl.submit.ISubmit":true}) __proto.renderSubmit=function(){ this._vb.bind_upload(this._ib); var target=this.scope.getValue(this.proName); if (target){ this.shaderValue.texture=target.source; if (this.shaderValue["strength"] && !this.shaderValue["blurInfo"]){ this.shaderValue["blurInfo"]=[target.width,target.height]; } this.shaderValue.upload(); this.blend(); Stat.drawCall++; Stat.trianglesFaces+=this._numEle/3; WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._numEle,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this._startIdx); } return 1; } __proto.blend=function(){ if (BlendMode.activeBlendFunction!==BlendMode.fns[this.blendType]){ var gl=WebGL.mainContext; gl.enable(/*laya.webgl.WebGLContext.BLEND*/0x0BE2); BlendMode.fns[this.blendType](gl); BlendMode.activeBlendFunction=BlendMode.fns[this.blendType]; } } __proto.getRenderType=function(){ return 0; } __proto.releaseRender=function(){ var cache=SubmitTarget._cache; cache[cache._length++]=this; } SubmitTarget.create=function(context,ib,vb,pos,sv,proName){ var o=SubmitTarget._cache._length?SubmitTarget._cache[--SubmitTarget._cache._length]:new SubmitTarget(); o._ib=ib; o._vb=vb; o.proName=proName; o._startIdx=pos *CONST3D2D.BYTES_PIDX; o._numEle=0; o.blendType=context._nBlendType; o.shaderValue=sv; o.shaderValue.setValue(context._shader2D); return o; } SubmitTarget._cache=(SubmitTarget._cache=[],SubmitTarget._cache._length=0,SubmitTarget._cache); return SubmitTarget; })() /** *...特殊的字符,如泰文,必须重新实现这个类 */ //class laya.webgl.text.CharSegment var CharSegment=(function(){ function CharSegment(){ this._sourceStr=null; } __class(CharSegment,'laya.webgl.text.CharSegment'); var __proto=CharSegment.prototype; Laya.imps(__proto,{"laya.webgl.text.ICharSegment":true}) __proto.textToSpit=function(str){ this._sourceStr=str; } __proto.getChar=function(i){ return this._sourceStr.charAt(i); } __proto.getCharCode=function(i){ return this._sourceStr.charCodeAt(i); } __proto.length=function(){ return this._sourceStr.length; } return CharSegment; })() //class laya.webgl.text.DrawText var DrawText=(function(){ var CharValue; function DrawText(){} __class(DrawText,'laya.webgl.text.DrawText'); DrawText.__init__=function(){ DrawText._charsTemp=new Array; DrawText._drawValue=new CharValue(); DrawText._charSeg=new CharSegment(); } DrawText.customCharSeg=function(charseg){ DrawText._charSeg=charseg; } DrawText.getChar=function(char,id,drawValue){ var result=WebGLCharImage.createOneChar(char,drawValue); if(id!=-1) DrawText._charsCache[id]=result; return result; } DrawText._drawSlow=function(save,ctx,txt,words,curMat,font,textAlign,fillColor,borderColor,lineWidth,x,y,sx,sy,underLine){ var drawValue=DrawText._drawValue.value(font,fillColor,borderColor,lineWidth,sx,sy,underLine); var i=0,n=0; var chars=DrawText._charsTemp; var width=0,oneChar,htmlWord,id=NaN; if (words){ chars.length=words.length; for (i=0,n=words.length;i < n;i++){ htmlWord=words[i]; id=htmlWord.charNum+drawValue.txtID; chars[i]=oneChar=DrawText._charsCache[id] || DrawText.getChar(htmlWord.char,id,drawValue); oneChar.active(); } }else { var text=((txt instanceof laya.utils.WordText ))? txt.toString():txt; if (Text.CharacterCache){ DrawText._charSeg.textToSpit(text); var len=/*if err,please use iflash.method.xmlLength()*/DrawText._charSeg.length(); chars.length=len; for (i=0,n=len;i < n;i++){ id=DrawText._charSeg.getCharCode(i)+drawValue.txtID; chars[i]=oneChar=DrawText._charsCache[id] || DrawText.getChar(DrawText._charSeg.getChar(i),id,drawValue); oneChar.active(); width+=oneChar.cw; } } else { chars.length=0; oneChar=DrawText.getChar(text,-1,drawValue); oneChar.active(); width+=oneChar.cw; chars[0]=oneChar; } }; var dx=0; if (textAlign!==null && textAlign!=="left") dx=-(textAlign=="center" ? (width / 2):width); var uv,bdSz=NaN,texture,value,saveLength=0; if (words){ for (i=0,n=chars.length;i < n;i++){ oneChar=chars[i]; if (!oneChar.isSpace){ htmlWord=words[i]; bdSz=oneChar.borderSize; texture=oneChar.texture; ctx._drawText(texture,x+dx+htmlWord.x *sx-bdSz,y+htmlWord.y *sy-bdSz,texture.width,texture.height,curMat,0,0,0,0); } } }else { for (i=0,n=chars.length;i < n;i++){ oneChar=chars[i]; if (!oneChar.isSpace){ bdSz=oneChar.borderSize; texture=oneChar.texture; ctx._drawText(texture,x+dx-bdSz,y-bdSz,texture.width,texture.height,curMat,0,0,0,0); save && (value=save[saveLength++],value || (value=save[saveLength-1]=[]),value[0]=texture,value[1]=dx-bdSz,value[2]=-bdSz); } dx+=oneChar.cw; } save && (save.length=saveLength); } } DrawText._drawFast=function(save,ctx,curMat,x,y){ var texture,value; for (var i=0,n=save.length;i < n;i++){ value=save[i]; texture=value[0]; texture.active(); ctx._drawText(texture,x+value[1],y+value[2],texture.width,texture.height,curMat,0,0,0,0); } } DrawText.drawText=function(ctx,txt,words,curMat,font,textAlign,fillColor,borderColor,lineWidth,x,y,underLine){ (underLine===void 0)&& (underLine=0); if ((txt && txt.length===0)|| (words && words.length===0)) return; var sx=curMat.a,sy=curMat.d; (curMat.b!==0 || curMat.c!==0)&& (sx=sy=1); var scale=sx!==1 || sy!==1; if (scale && Laya.stage.transform){ var t=Laya.stage.transform; scale=t.a===sx && t.d===sy; }else scale=false; if (scale){ curMat=curMat.copyTo(WebGLContext2D._tmpMatrix); var tempTx=curMat.tx; var tempTy=curMat.ty; curMat.scale(1 / sx,1 / sy); curMat._checkTransform(); x *=sx; y *=sy; x+=tempTx-curMat.tx; y+=tempTy-curMat.ty; }else sx=sy=1; if (words){ DrawText._drawSlow(null,ctx,txt,words,curMat,font,textAlign,fillColor,borderColor,lineWidth,x,y,sx,sy,underLine); }else { if (txt.toUpperCase===null){ var idNum=sx+sy *100000; var myCache=txt; if (!myCache.changed && myCache.id===idNum){ DrawText._drawFast(myCache.save,ctx,curMat,x,y); }else { myCache.id=idNum; myCache.changed=false; DrawText._drawSlow(myCache.save,ctx,txt,words,curMat,font,textAlign,fillColor,borderColor,lineWidth,x,y,sx,sy,underLine); } return; }; var id=txt+font.toString()+fillColor+borderColor+lineWidth+sx+sy+textAlign; var cache=DrawText._textsCache[id]; if (Text.CharacterCache){ if (cache){ DrawText._drawFast(cache,ctx,curMat,x,y); }else { DrawText._textsCache.__length || (DrawText._textsCache.__length=0); if (DrawText._textsCache.__length > Config.WebGLTextCacheCount){ DrawText._textsCache={}; DrawText._textsCache.__length=0; DrawText._curPoolIndex=0; } DrawText._textCachesPool[DrawText._curPoolIndex] ? (cache=DrawText._textsCache[id]=DrawText._textCachesPool[DrawText._curPoolIndex],cache.length=0):(DrawText._textCachesPool[DrawText._curPoolIndex]=cache=DrawText._textsCache[id]=[]); DrawText._textsCache.__length++ DrawText._curPoolIndex++; DrawText._drawSlow(cache,ctx,txt,words,curMat,font,textAlign,fillColor,borderColor,lineWidth,x,y,sx,sy,underLine); } } else{ DrawText._drawSlow(cache,ctx,txt,words,curMat,font,textAlign,fillColor,borderColor,lineWidth,x,y,sx,sy,underLine); } } } DrawText._charsTemp=null; DrawText._textCachesPool=[]; DrawText._curPoolIndex=0; DrawText._charsCache={}; DrawText._textsCache={}; DrawText._drawValue=null; DrawText.d=[]; DrawText._charSeg=null; DrawText.__init$=function(){ //class CharValue CharValue=(function(){ function CharValue(){ //this.txtID=NaN; //this.font=null; //this.fillColor=null; //this.borderColor=null; //this.lineWidth=0; //this.scaleX=NaN; //this.scaleY=NaN; //this.underLine=0; } __class(CharValue,''); var __proto=CharValue.prototype; __proto.value=function(font,fillColor,borderColor,lineWidth,scaleX,scaleY,underLine){ this.font=font; this.fillColor=fillColor; this.borderColor=borderColor; this.lineWidth=lineWidth; this.scaleX=scaleX; this.scaleY=scaleY; this.underLine=underLine; var key=font.toString()+scaleX+scaleY+lineWidth+fillColor+borderColor+underLine; this.txtID=CharValue._keymap[key]; if (!this.txtID){ this.txtID=(++CharValue._keymapCount)*0.0000001; CharValue._keymap[key]=this.txtID; } return this; } CharValue.clear=function(){ CharValue._keymap={}; CharValue._keymapCount=1; } CharValue._keymap={}; CharValue._keymapCount=1; return CharValue; })() } return DrawText; })() //class laya.webgl.text.FontInContext var FontInContext=(function(){ function FontInContext(font){ //this._text=null; //this._words=null; this._index=0; this._size=14; this._italic=-2; FontInContext._cache2=FontInContext._cache2|| []; this.setFont(font || "14px Arial"); } __class(FontInContext,'laya.webgl.text.FontInContext'); var __proto=FontInContext.prototype; __proto.setFont=function(value){ var arr=FontInContext._cache2[value]; if (!arr){ this._words=value.split(' '); for (var i=0,n=this._words.length;i < n;i++){ if (this._words[i].indexOf('px')> 0){ this._index=i; break ; } } this._size=parseInt(this._words[this._index]); FontInContext._cache2[value]=[this._words,this._size]; }else { this._words=arr[0]; this._size=arr[1]; } this._text=null; this._italic=-2; } __proto.getItalic=function(){ this._italic===-2 && (this._italic=this.hasType("italic")); return this._italic; } __proto.hasType=function(name){ for (var i=0,n=this._words.length;i < n;i++) if (this._words[i]===name)return i; return-1; } __proto.removeType=function(name){ for (var i=0,n=this._words.length;i < n;i++) if (this._words[i]===name){ this._words.splice(i,1); if (this._index > i)this._index--; break ; } this._text=null; this._italic=-2; } __proto.copyTo=function(dec){ dec._text=this._text; dec._size=this._size; dec._index=this._index; dec._words=this._words.slice(); dec._italic=-2; return dec; } __proto.toString=function(){ return this._text ? this._text :(this._text=this._words.join(' ')); } __getset(0,__proto,'size',function(){ return this._size; },function(value){ this._size=value; this._words[this._index]=value+"px"; this._text=null; }); FontInContext.create=function(font){ var r=FontInContext._cache[font]; if (r)return r; r=FontInContext._cache[font]=new FontInContext(font); return r; } FontInContext.EMPTY=new FontInContext(); FontInContext._cache={}; FontInContext._cache2=null; return FontInContext; })() //class laya.webgl.utils.CONST3D2D var CONST3D2D=(function(){ function CONST3D2D(){} __class(CONST3D2D,'laya.webgl.utils.CONST3D2D'); CONST3D2D.defaultMatrix4=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]; CONST3D2D.defaultMinusYMatrix4=[1,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,1]; CONST3D2D.uniformMatrix3=[1,0,0,0,0,1,0,0,0,0,1,0]; CONST3D2D._TMPARRAY=[]; CONST3D2D._OFFSETX=0; CONST3D2D._OFFSETY=0; __static(CONST3D2D, ['BYTES_PE',function(){return this.BYTES_PE=/*__JS__ */Float32Array.BYTES_PER_ELEMENT;},'BYTES_PIDX',function(){return this.BYTES_PIDX=/*__JS__ */Uint16Array.BYTES_PER_ELEMENT;} ]); return CONST3D2D; })() //class laya.webgl.utils.GlUtils var GlUtils=(function(){ function GlUtils(){} __class(GlUtils,'laya.webgl.utils.GlUtils'); GlUtils.make2DProjection=function(width,height,depth){ return [2.0 / width,0,0,0,0,-2.0 / height,0,0,0,0,2.0 / depth,0,-1,1,0,1,]; } GlUtils.fillIBQuadrangle=function(buffer,count){ if (count > 65535 / 4){ throw Error("IBQuadrangle count:"+count+" must<:"+Math.floor(65535 / 4)); return false; } count=Math.floor(count); buffer._resizeBuffer((count+1)*6 */*laya.webgl.utils.Buffer2D.SHORT*/2,false); buffer.byteLength=buffer.bufferLength; var bufferData=buffer.getUint16Array(); var idx=0; for (var i=0;i < count;i++){ bufferData[idx++]=i *4; bufferData[idx++]=i *4+2; bufferData[idx++]=i *4+1; bufferData[idx++]=i *4; bufferData[idx++]=i *4+3; bufferData[idx++]=i *4+2; } buffer.setNeedUpload(); return true; } GlUtils.expandIBQuadrangle=function(buffer,count){ buffer.bufferLength >=(count *6 */*laya.webgl.utils.Buffer2D.SHORT*/2)|| GlUtils.fillIBQuadrangle(buffer,count); } GlUtils.mathCeilPowerOfTwo=function(value){ value--; value |=value >> 1; value |=value >> 2; value |=value >> 4; value |=value >> 8; value |=value >> 16; value++; return value; } GlUtils.fillQuadrangleImgVb=function(vb,x,y,point4,uv,m,_x,_y){ var vpos=(vb._byteLength >> 2)+/*laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16; vb.byteLength=(vpos << 2); var vbdata=vb.getFloat32Array(); vpos-=/*laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16; vbdata[vpos+2]=uv[0]; vbdata[vpos+3]=uv[1]; vbdata[vpos+6]=uv[2]; vbdata[vpos+7]=uv[3]; vbdata[vpos+10]=uv[4]; vbdata[vpos+11]=uv[5]; vbdata[vpos+14]=uv[6]; vbdata[vpos+15]=uv[7]; var a=m.a,b=m.b,c=m.c,d=m.d; if (a!==1 || b!==0 || c!==0 || d!==1){ m.bTransform=true; var tx=m.tx+_x,ty=m.ty+_y; vbdata[vpos]=(point4[0]+x)*a+(point4[1]+y)*c+tx; vbdata[vpos+1]=(point4[0]+x)*b+(point4[1]+y)*d+ty; vbdata[vpos+4]=(point4[2]+x)*a+(point4[3]+y)*c+tx; vbdata[vpos+5]=(point4[2]+x)*b+(point4[3]+y)*d+ty; vbdata[vpos+8]=(point4[4]+x)*a+(point4[5]+y)*c+tx; vbdata[vpos+9]=(point4[4]+x)*b+(point4[5]+y)*d+ty; vbdata[vpos+12]=(point4[6]+x)*a+(point4[7]+y)*c+tx; vbdata[vpos+13]=(point4[6]+x)*b+(point4[7]+y)*d+ty; }else { m.bTransform=false; x+=m.tx+_x; y+=m.ty+_y; vbdata[vpos]=x+point4[0]; vbdata[vpos+1]=y+point4[1]; vbdata[vpos+4]=x+point4[2]; vbdata[vpos+5]=y+point4[3]; vbdata[vpos+8]=x+point4[4]; vbdata[vpos+9]=y+point4[5]; vbdata[vpos+12]=x+point4[6]; vbdata[vpos+13]=y+point4[7]; } vb._upload=true; return true; } GlUtils.fillTranglesVB=function(vb,x,y,points,m,_x,_y){ var vpos=(vb._byteLength >> 2)+points.length; vb.byteLength=(vpos << 2); var vbdata=vb.getFloat32Array(); vpos-=points.length; var len=points.length; var a=m.a,b=m.b,c=m.c,d=m.d; for (var i=0;i < len;i+=4){ vbdata[vpos+i+2]=points[i+2]; vbdata[vpos+i+3]=points[i+3]; if (a!==1 || b!==0 || c!==0 || d!==1){ m.bTransform=true; var tx=m.tx+_x,ty=m.ty+_y; vbdata[vpos+i]=(points[i]+x)*a+(points[i+1]+y)*c+tx; vbdata[vpos+i+1]=(points[i]+x)*b+(points[i+1]+y)*d+ty; }else { m.bTransform=false; x+=m.tx+_x; y+=m.ty+_y; vbdata[vpos+i]=x+points[i]; vbdata[vpos+i+1]=y+points[i+1]; } } vb._upload=true; return true; } GlUtils.copyPreImgVb=function(vb,dx,dy){ var vpos=(vb._byteLength >> 2); vb.byteLength=((vpos+/*laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16)<< 2); var vbdata=vb.getFloat32Array(); for (var i=0,ci=vpos-16;i < 4;i++){ vbdata[vpos]=vbdata[ci]+dx; ++vpos; ++ci; vbdata[vpos]=vbdata[ci]+dy; ++vpos; ++ci; vbdata[vpos]=vbdata[ci]; ++vpos; ++ci; vbdata[vpos]=vbdata[ci]; ++vpos; ++ci; } vb._upload=true; } GlUtils.fillRectImgVb=function(vb,clip,x,y,width,height,uv,m,_x,_y,dx,dy,round){ (round===void 0)&& (round=false); var mType=1; var toBx,toBy,toEx,toEy; var cBx,cBy,cEx,cEy; var w0,h0,tx,ty; var finalX,finalY,offsetX,offsetY; var a=m.a,b=m.b,c=m.c,d=m.d; var useClip=clip && clip.width < /*laya.webgl.canvas.WebGLContext2D._MAXSIZE*/99999999; if (a!==1 || b!==0 || c!==0 || d!==1){ m.bTransform=true; if (b===0 && c===0){ mType=23; w0=width+x,h0=height+y; tx=m.tx+_x,ty=m.ty+_y; toBx=a *x+tx; toEx=a *w0+tx; toBy=d *y+ty; toEy=d *h0+ty; } }else { mType=23; m.bTransform=false; toBx=x+m.tx+_x; toEx=toBx+width; toBy=y+m.ty+_y; toEy=toBy+height; } if (useClip){ cBx=clip.x,cBy=clip.y,cEx=clip.width+cBx,cEy=clip.height+cBy; } if (mType!==1){ if (Math.min(toBx,toEx)>=cEx)return false; if (Math.min(toBy,toEy)>=cEy)return false; if (Math.max(toEx,toBx)<=cBx)return false; if (Math.max(toEy,toBy)<=cBy)return false; }; var vpos=(vb._byteLength >> 2); vb.byteLength=((vpos+/*laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16)<< 2); var vbdata=vb.getFloat32Array(); vbdata[vpos+2]=uv[0]; vbdata[vpos+3]=uv[1]; vbdata[vpos+6]=uv[2]; vbdata[vpos+7]=uv[3]; vbdata[vpos+10]=uv[4]; vbdata[vpos+11]=uv[5]; vbdata[vpos+14]=uv[6]; vbdata[vpos+15]=uv[7]; switch (mType){ case 1: tx=m.tx+_x,ty=m.ty+_y; w0=width+x,h0=height+y; var w1=x,h1=y; var aw1=a *w1,ch1=c *h1,dh1=d *h1,bw1=b *w1; var aw0=a *w0,ch0=c *h0,dh0=d *h0,bw0=b *w0; if (round){ finalX=aw1+ch1+tx; offsetX=Math.round(finalX)-finalX; finalY=dh1+bw1+ty; offsetY=Math.round(finalY)-finalY; vbdata[vpos]=finalX+offsetX; vbdata[vpos+1]=finalY+offsetY; vbdata[vpos+4]=aw0+ch1+tx+offsetX; vbdata[vpos+5]=dh1+bw0+ty+offsetY; vbdata[vpos+8]=aw0+ch0+tx+offsetX; vbdata[vpos+9]=dh0+bw0+ty+offsetY; vbdata[vpos+12]=aw1+ch0+tx+offsetX; vbdata[vpos+13]=dh0+bw1+ty+offsetY; }else { vbdata[vpos]=aw1+ch1+tx; vbdata[vpos+1]=dh1+bw1+ty; vbdata[vpos+4]=aw0+ch1+tx; vbdata[vpos+5]=dh1+bw0+ty; vbdata[vpos+8]=aw0+ch0+tx; vbdata[vpos+9]=dh0+bw0+ty; vbdata[vpos+12]=aw1+ch0+tx; vbdata[vpos+13]=dh0+bw1+ty; } break ; case 23: if (round){ finalX=toBx+dx; offsetX=Math.round(finalX)-finalX; finalY=toBy; offsetY=Math.round(finalY)-finalY; vbdata[vpos]=finalX+offsetX; vbdata[vpos+1]=finalY+offsetY; vbdata[vpos+4]=toEx+dx+offsetX; vbdata[vpos+5]=toBy+offsetY; vbdata[vpos+8]=toEx+offsetX; vbdata[vpos+9]=toEy+offsetY; vbdata[vpos+12]=toBx+offsetX; vbdata[vpos+13]=toEy+offsetY; }else { vbdata[vpos]=toBx+dx; vbdata[vpos+1]=toBy; vbdata[vpos+4]=toEx+dx; vbdata[vpos+5]=toBy; vbdata[vpos+8]=toEx; vbdata[vpos+9]=toEy; vbdata[vpos+12]=toBx; vbdata[vpos+13]=toEy; } break ; } vb._upload=true; return true; } GlUtils.fillLineVb=function(vb,clip,fx,fy,tx,ty,width,mat){ var linew=width *.5; var data=GlUtils._fillLineArray; var perpx=-(fy-ty),perpy=fx-tx; var dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx /=dist,perpy /=dist,perpx *=linew,perpy *=linew; data[0]=fx-perpx,data[1]=fy-perpy,data[4]=fx+perpx,data[5]=fy+perpy,data[8]=tx+perpx,data[9]=ty+perpy,data[12]=tx-perpx,data[13]=ty-perpy; mat && mat.transformPointArray(data,data); var vpos=(vb._byteLength >> 2)+/*laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16; vb.byteLength=(vpos << 2); vb.insertData(data,vpos-/*laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16); return true; } GlUtils._fillLineArray=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; return GlUtils; })() //class laya.webgl.utils.MatirxArray var MatirxArray=(function(){ function MatirxArray(){} __class(MatirxArray,'laya.webgl.utils.MatirxArray'); MatirxArray.ArrayMul=function(a,b,o){ if (!a){ MatirxArray.copyArray(b,o); return; } if (!b){ MatirxArray.copyArray(a,o); return; }; var ai0=NaN,ai1=NaN,ai2=NaN,ai3=NaN; for (var i=0;i < 4;i++){ ai0=a[i]; ai1=a[i+4]; ai2=a[i+8]; ai3=a[i+12]; o[i]=ai0 *b[0]+ai1 *b[1]+ai2 *b[2]+ai3 *b[3]; o[i+4]=ai0 *b[4]+ai1 *b[5]+ai2 *b[6]+ai3 *b[7]; o[i+8]=ai0 *b[8]+ai1 *b[9]+ai2 *b[10]+ai3 *b[11]; o[i+12]=ai0 *b[12]+ai1 *b[13]+ai2 *b[14]+ai3 *b[15]; } } MatirxArray.copyArray=function(f,t){ if (!f)return; if (!t)return; for (var i=0;i < f.length;i++){ t[i]=f[i]; } } return MatirxArray; })() /** *Mesh2d只是保存数据。描述attribute用的。本身不具有渲染功能。 */ //class laya.webgl.utils.Mesh2D var Mesh2D=(function(){ function Mesh2D(stride,vballoc,iballoc){ this._stride=0; //顶点结构大小。每个mesh的顶点结构是固定的。 this.vertNum=0; //当前的顶点的个数 this.indexNum=0; //实际index 个数。例如一个三角形是3个。由于ib本身可能超过实际使用的数量,所以需要一个indexNum this._applied=false; //是否已经设置给webgl了 this._vb=null; //vb和ib都可能需要在外部修改,所以public this._ib=null; this._vao=null; this._attribInfo=null; //保存起来的属性定义数组。 this._quadNum=0; //public static var meshlist:Array=[];//活着的mesh对象列表。 this.canReuse=false; this._stride=stride; this._vb=new VertexBuffer2D(stride,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); if (vballoc){ this._vb._resizeBuffer(vballoc,false); }else{} this._ib=new IndexBuffer2D(); if (iballoc){ this._ib._resizeBuffer(iballoc,false); } } __class(Mesh2D,'laya.webgl.utils.Mesh2D'); var __proto=Mesh2D.prototype; /** *重新创建一个mesh。复用这个对象的vertex结构,ib对象和attribinfo对象 */ __proto.cloneWithNewVB=function(){ var mesh=new Mesh2D(this._stride,0,0); mesh._ib=this._ib; mesh._quadNum=this._quadNum; mesh._attribInfo=this._attribInfo; return mesh; } /** *创建一个mesh,使用当前对象的vertex结构。vb和ib自己提供。 *@return */ __proto.cloneWithNewVBIB=function(){ var mesh=new Mesh2D(this._stride,0,0); mesh._attribInfo=this._attribInfo; return mesh; } /** *获得一个可以写的vb对象 */ __proto.getVBW=function(){ this._vb.setNeedUpload(); return this._vb; } /** *获得一个只读vb */ __proto.getVBR=function(){ return this._vb; } __proto.getIBR=function(){ return this._ib; } /** *获得一个可写的ib */ __proto.getIBW=function(){ this._ib.setNeedUpload(); return this._ib; } /** *直接创建一个固定的ib。按照固定四边形的索引。 *@param var QuadNum */ __proto.createQuadIB=function(QuadNum){ this._quadNum=QuadNum; this._ib._resizeBuffer(QuadNum *6 *2,false); this._ib.byteLength=this._ib.bufferLength; var bd=this._ib.getUint16Array(); var idx=0; var curvert=0; for (var i=0;i < QuadNum;i++){ bd[idx++]=curvert; bd[idx++]=curvert+2; bd[idx++]=curvert+1; bd[idx++]=curvert; bd[idx++]=curvert+3; bd[idx++]=curvert+2; curvert+=4; } this._ib.setNeedUpload(); } /** *设置mesh的属性。每3个一组,对应的location分别是0,1,2... *含义是:type,size,offset *不允许多流。因此stride是固定的,offset只是在一个vertex之内。 *@param attribs */ __proto.setAttributes=function(attribs){ this._attribInfo=attribs; if (this._attribInfo.length % 3 !=0){ throw 'Mesh2D setAttributes error!'; } } __proto.getEleNum=function(){ return this._ib.getBuffer().byteLength / 2; } /** *子类实现。用来把自己放到对应的回收池中,以便复用。 */ __proto.releaseMesh=function(){} /** *释放资源。 */ __proto.destroy=function(){} /** *清理vb数据 */ __proto.clearVB=function(){ this._vb.clear(); } Mesh2D._gvaoid=0; return Mesh2D; })() //class laya.webgl.utils.RenderState2D var RenderState2D=(function(){ function RenderState2D(){} __class(RenderState2D,'laya.webgl.utils.RenderState2D'); RenderState2D.getMatrArray=function(){ return [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]; } RenderState2D.mat2MatArray=function(mat,matArray){ var m=mat; var m4=matArray; m4[0]=m.a; m4[1]=m.b; m4[2]=RenderState2D.EMPTYMAT4_ARRAY[2]; m4[3]=RenderState2D.EMPTYMAT4_ARRAY[3]; m4[4]=m.c; m4[5]=m.d; m4[6]=RenderState2D.EMPTYMAT4_ARRAY[6]; m4[7]=RenderState2D.EMPTYMAT4_ARRAY[7]; m4[8]=RenderState2D.EMPTYMAT4_ARRAY[8]; m4[9]=RenderState2D.EMPTYMAT4_ARRAY[9]; m4[10]=RenderState2D.EMPTYMAT4_ARRAY[10]; m4[11]=RenderState2D.EMPTYMAT4_ARRAY[11]; m4[12]=m.tx; m4[13]=m.ty; m4[14]=RenderState2D.EMPTYMAT4_ARRAY[14]; m4[15]=RenderState2D.EMPTYMAT4_ARRAY[15]; return matArray; } RenderState2D.restoreTempArray=function(){ RenderState2D.TEMPMAT4_ARRAY[0]=1; RenderState2D.TEMPMAT4_ARRAY[1]=0; RenderState2D.TEMPMAT4_ARRAY[4]=0; RenderState2D.TEMPMAT4_ARRAY[5]=1; RenderState2D.TEMPMAT4_ARRAY[12]=0; RenderState2D.TEMPMAT4_ARRAY[13]=0; } RenderState2D.clear=function(){ RenderState2D.worldScissorTest=false; RenderState2D.worldShaderDefines=null; RenderState2D.worldFilters=null; RenderState2D.worldAlpha=1; RenderState2D.worldClipRect.x=RenderState2D.worldClipRect.y=0; RenderState2D.worldClipRect.width=RenderState2D.width; RenderState2D.worldClipRect.height=RenderState2D.height; RenderState2D.curRenderTarget=null; } RenderState2D._MAXSIZE=99999999; RenderState2D.EMPTYMAT4_ARRAY=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]; RenderState2D.TEMPMAT4_ARRAY=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]; RenderState2D.worldMatrix4=RenderState2D.TEMPMAT4_ARRAY; RenderState2D.worldAlpha=1.0; RenderState2D.worldScissorTest=false; RenderState2D.worldFilters=null; RenderState2D.worldShaderDefines=null; RenderState2D.curRenderTarget=null; RenderState2D.width=0; RenderState2D.height=0; __static(RenderState2D, ['worldMatrix',function(){return this.worldMatrix=new Matrix();},'worldClipRect',function(){return this.worldClipRect=new Rectangle(0,0,99999999,99999999);} ]); return RenderState2D; })() /** *@private *ShaderCompile 类用于实现Shader编译。 */ //class laya.webgl.utils.ShaderCompile var ShaderCompile=(function(){ var ShaderNode,InlcudeFile; function ShaderCompile(name,vs,ps,nameMap,defs){ //this._nameMap=null; //this._VS=null; //this._PS=null; var _$this=this; function _compile (script){ var includefiles=[]; var top=new ShaderNode(includefiles); _$this._compileToTree(top,script.split('\n'),0,includefiles,defs); return top; }; var startTime=Browser.now(); this._VS=_compile(vs); this._PS=_compile(ps); this._nameMap=nameMap; if ((Browser.now()-startTime)> 2) console.log("ShaderCompile use time:"+(Browser.now()-startTime)+" size:"+vs.length+"/"+ps.length); } __class(ShaderCompile,'laya.webgl.utils.ShaderCompile'); var __proto=ShaderCompile.prototype; __proto._compileToTree=function(parent,lines,start,includefiles,defs){ var node,preNode; var text,name,fname; var ofs=0,words,noUseNode; var i=0,n=0,j=0; for (i=start;i < lines.length;i++){ text=lines[i]; if (text.length < 1)continue ; ofs=text.indexOf("//"); if (ofs===0)continue ; if (ofs >=0)text=text.substr(0,ofs); node=noUseNode || new ShaderNode(includefiles); noUseNode=null; node.text=text; node.noCompile=true; if ((ofs=text.indexOf("#"))>=0){ name="#"; for (j=ofs+1,n=text.length;j < n;j++){ var c=text.charAt(j); if (c===' ' || c==='\t' || c==='?')break ; name+=c; } node.name=name; switch (name){ case "#ifdef": case "#ifndef": node.src=text; node.noCompile=text.match(/[!&|()=<>]/)!=null; if (!node.noCompile){ words=text.replace(/^\s*/,'').split(/\s+/); node.setCondition(words[1],name==="#ifdef" ? 1 :2); node.text="//"+node.text; }else { console.log("function():Boolean{return "+text.substr(ofs+node.name.length)+"}"); } node.setParent(parent); parent=node; if (defs){ words=text.substr(j).split(ShaderCompile._splitToWordExps3); for (j=0;j < words.length;j++){ text=words[j]; text.length && (defs[ text]=true); } } continue ; case "#if": node.src=text; node.noCompile=true; node.setParent(parent); parent=node; if (defs){ words=text.substr(j).split(ShaderCompile._splitToWordExps3); for (j=0;j < words.length;j++){ text=words[j]; text.length && text!="defined" && (defs[ text]=true); } } continue ; case "#else": node.src=text; parent=parent.parent; preNode=parent.childs[parent.childs.length-1]; node.noCompile=preNode.noCompile if (!(node.noCompile)){ node.condition=preNode.condition; node.conditionType=preNode.conditionType==1 ? 2 :1; node.text="//"+node.text+" "+preNode.text+" "+node.conditionType; } node.setParent(parent); parent=node; continue ; case "#endif": parent=parent.parent; preNode=parent.childs[parent.childs.length-1]; node.noCompile=preNode.noCompile; if (!(node.noCompile)){ node.text="//"+node.text; } node.setParent(parent); continue ; case "#include": words=ShaderCompile.splitToWords(text,null); var inlcudeFile=ShaderCompile.includes[words[1]]; if (!inlcudeFile){ throw "ShaderCompile error no this include file:"+words[1]; return; } if ((ofs=words[0].indexOf("?"))< 0){ node.setParent(parent); text=inlcudeFile.getWith(words[2]=='with' ? words[3] :null); this._compileToTree(node,text.split('\n'),0,includefiles,defs); node.text=""; continue ; } node.setCondition(words[0].substr(ofs+1),1); node.text=inlcudeFile.getWith(words[2]=='with' ? words[3] :null); break ; case "#import": words=ShaderCompile.splitToWords(text,null); fname=words[1]; includefiles.push({node:node,file:ShaderCompile.includes[fname],ofs:node.text.length}); continue ; } }else { preNode=parent.childs[parent.childs.length-1]; if (preNode && !preNode.name){ includefiles.length > 0 && ShaderCompile.splitToWords(text,preNode); noUseNode=node; preNode.text+="\n"+text; continue ; } includefiles.length > 0 && ShaderCompile.splitToWords(text,node); } node.setParent(parent); } } __proto.createShader=function(define,shaderName,createShader){ var defMap={}; var defineStr=""; if (define){ for (var i in define){ defineStr+="#define "+i+"\n"; defMap[i]=true; } }; var vs=this._VS.toscript(defMap,[]); var ps=this._PS.toscript(defMap,[]); return (createShader || Shader.create)(defineStr+vs.join('\n'),defineStr+ps.join('\n'),shaderName,this._nameMap); } ShaderCompile._parseOne=function(attributes,uniforms,words,i,word,b){ var one={type:ShaderCompile.shaderParamsMap[words[i+1]],name:words[i+2],size:isNaN(parseInt(words[i+3]))? 1 :parseInt(words[i+3])}; if (b){ if (word=="attribute"){ attributes.push(one); }else { uniforms.push(one); } } if (words[i+3]==':'){ one.type=words[i+4]; i+=2; } i+=2; return i; } ShaderCompile.addInclude=function(fileName,txt){ if (!txt || txt.length===0) throw new Error("add shader include file err:"+fileName); if (ShaderCompile.includes[fileName]) throw new Error("add shader include file err, has add:"+fileName); ShaderCompile.includes[fileName]=new InlcudeFile(txt); } ShaderCompile.preGetParams=function(vs,ps){ var text=[vs,ps]; var result={}; var attributes=[]; var uniforms=[]; var definesInfo={}; var definesName=[]; result.attributes=attributes; result.uniforms=uniforms; result.defines=definesInfo; var i=0,n=0,one; for (var s=0;s < 2;s++){ text[s]=text[s].replace(ShaderCompile._removeAnnotation,""); var words=text[s].match(ShaderCompile._reg); var tempelse; for (i=0,n=words.length;i < n;i++){ var word=words[i]; if (word !="attribute" && word !="uniform"){ if (word=="#define"){ word=words[++i]; definesName[word]=1; continue ; }else if (word=="#ifdef"){ tempelse=words[++i]; var def=definesInfo[tempelse]=definesInfo[tempelse] || []; for (i++;i < n;i++){ word=words[i]; if (word !="attribute" && word !="uniform"){ if (word=="#else"){ for (i++;i < n;i++){ word=words[i]; if (word !="attribute" && word !="uniform"){ if (word=="#endif"){ break ; } continue ; } i=ShaderCompile._parseOne(attributes,uniforms,words,i,word,!definesName[tempelse]); } } continue ; } i=ShaderCompile._parseOne(attributes,uniforms,words,i,word,definesName[tempelse]); } } continue ; } i=ShaderCompile._parseOne(attributes,uniforms,words,i,word,true); } } return result; } ShaderCompile.splitToWords=function(str,block){ var out=[]; var c; var ofs=-1; var word; for (var i=0,n=str.length;i < n;i++){ c=str.charAt(i); if (" \t=+-*/&%!<>()'\",;".indexOf(c)>=0){ if (ofs >=0 && (i-ofs)> 1){ word=str.substr(ofs,i-ofs); out.push(word); } if (c=='"' || c=="'"){ var ofs2=str.indexOf(c,i+1); if (ofs2 < 0){ throw "Sharder err:"+str; } out.push(str.substr(i+1,ofs2-i-1)); i=ofs2; ofs=-1; continue ; } if (c=='(' && block && out.length > 0){ word=out[out.length-1]+";"; if ("vec4;main;".indexOf(word)< 0) block.useFuns+=word; } ofs=-1; continue ; } if (ofs < 0)ofs=i; } if (ofs < n && (n-ofs)> 1){ word=str.substr(ofs,n-ofs); out.push(word); } return out; } ShaderCompile.IFDEF_NO=0; ShaderCompile.IFDEF_YES=1; ShaderCompile.IFDEF_ELSE=2; ShaderCompile.IFDEF_PARENT=3; ShaderCompile._removeAnnotation=new RegExp("(/\\*([^*]|[\\r\\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/)|(//.*)","g"); ShaderCompile._reg=new RegExp("(\".*\")|('.*')|([#\\w\\*-\\.+/()=<>{}\\\\]+)|([,;:\\\\])","g"); ShaderCompile._splitToWordExps=new RegExp("[(\".*\")]+|[('.*')]+|([ \\t=\\+\\-*/&%!<>!%\(\),;])","g"); ShaderCompile.includes={}; __static(ShaderCompile, ['shaderParamsMap',function(){return this.shaderParamsMap={"float":/*laya.webgl.WebGLContext.FLOAT*/0x1406,"int":/*laya.webgl.WebGLContext.INT*/0x1404,"bool":/*laya.webgl.WebGLContext.BOOL*/0x8B56,"vec2":/*laya.webgl.WebGLContext.FLOAT_VEC2*/0x8B50,"vec3":/*laya.webgl.WebGLContext.FLOAT_VEC3*/0x8B51,"vec4":/*laya.webgl.WebGLContext.FLOAT_VEC4*/0x8B52,"ivec2":/*laya.webgl.WebGLContext.INT_VEC2*/0x8B53,"ivec3":/*laya.webgl.WebGLContext.INT_VEC3*/0x8B54,"ivec4":/*laya.webgl.WebGLContext.INT_VEC4*/0x8B55,"bvec2":/*laya.webgl.WebGLContext.BOOL_VEC2*/0x8B57,"bvec3":/*laya.webgl.WebGLContext.BOOL_VEC3*/0x8B58,"bvec4":/*laya.webgl.WebGLContext.BOOL_VEC4*/0x8B59,"mat2":/*laya.webgl.WebGLContext.FLOAT_MAT2*/0x8B5A,"mat3":/*laya.webgl.WebGLContext.FLOAT_MAT3*/0x8B5B,"mat4":/*laya.webgl.WebGLContext.FLOAT_MAT4*/0x8B5C,"sampler2D":/*laya.webgl.WebGLContext.SAMPLER_2D*/0x8B5E,"samplerCube":/*laya.webgl.WebGLContext.SAMPLER_CUBE*/0x8B60};},'_splitToWordExps3',function(){return this._splitToWordExps3=new RegExp("[ \\t=\\+\\-*/&%!<>!%\(\),;\\|]","g");} ]); ShaderCompile.__init$=function(){ //class ShaderNode ShaderNode=(function(){ function ShaderNode(includefiles){ this.childs=[]; this.text=""; this.parent=null; this.name=null; this.noCompile=false; this.includefiles=null; this.condition=null; this.conditionType=0; this.useFuns=""; this.z=0; this.src=null; this.includefiles=includefiles; } __class(ShaderNode,''); var __proto=ShaderNode.prototype; __proto.setParent=function(parent){ parent.childs.push(this); this.z=parent.z+1; this.parent=parent; } __proto.setCondition=function(condition,type){ if (condition){ this.conditionType=type; condition=condition.replace(/(\s*$)/g,""); this.condition=function (){ return this[condition]; } this.condition.__condition=condition; } } __proto.toscript=function(def,out){ return this._toscript(def,out,++ShaderNode.__id); } __proto._toscript=function(def,out,id){ if (this.childs.length < 1 && !this.text)return out; var outIndex=out.length; if (this.condition){ var ifdef=!!this.condition.call(def); this.conditionType===/*laya.webgl.utils.ShaderCompile.IFDEF_ELSE*/2 && (ifdef=!ifdef); if (!ifdef)return out; } this.text && out.push(this.text); this.childs.length > 0 && this.childs.forEach(function(o,index,arr){ o._toscript(def,out,id); }); if (this.includefiles.length > 0 && this.useFuns.length > 0){ var funsCode; for (var i=0,n=this.includefiles.length;i < n;i++){ if (this.includefiles[i].curUseID==id){ continue ; } funsCode=this.includefiles[i].file.getFunsScript(this.useFuns); if (funsCode.length > 0){ this.includefiles[i].curUseID=id; out[0]=funsCode+out[0]; } } } return out; } ShaderNode.__id=1; return ShaderNode; })() //class InlcudeFile InlcudeFile=(function(){ function InlcudeFile(txt){ this.script=null; this.codes={}; this.funs={}; this.curUseID=-1; this.funnames=""; this.script=txt; var begin=0,ofs=0,end=0; while (true){ begin=txt.indexOf("#begin",begin); if (begin < 0)break ; end=begin+5; while (true){ end=txt.indexOf("#end",end); if (end < 0)break ; if (txt.charAt(end+4)==='i') end+=5; else break ; } if (end < 0){ throw "add include err,no #end:"+txt; return; } ofs=txt.indexOf('\n',begin); var words=ShaderCompile.splitToWords(txt.substr(begin,ofs-begin),null); if (words[1]=='code'){ this.codes[words[2]]=txt.substr(ofs+1,end-ofs-1); }else if (words[1]=='function'){ ofs=txt.indexOf("function",begin); ofs+="function".length; this.funs[words[3]]=txt.substr(ofs+1,end-ofs-1); this.funnames+=words[3]+";"; } begin=end+1; } } __class(InlcudeFile,''); var __proto=InlcudeFile.prototype; __proto.getWith=function(name){ var r=name ? this.codes[name] :this.script; if (!r){ throw "get with error:"+name; } return r; } __proto.getFunsScript=function(funsdef){ var r=""; for (var i in this.funs){ if (funsdef.indexOf(i+";")>=0){ r+=this.funs[i]; } } return r; } return InlcudeFile; })() } return ShaderCompile; })() /** *@private */ //class laya.webgl.WebGL var WebGL=(function(){ function WebGL(){} __class(WebGL,'laya.webgl.WebGL'); WebGL._uint8ArraySlice=function(){ var _this=/*__JS__ */this; var sz=_this.length; var dec=new Uint8Array(_this.length); for (var i=0;i < sz;i++)dec[i]=_this[i]; return dec; } WebGL._float32ArraySlice=function(){ var _this=/*__JS__ */this; var sz=_this.length; var dec=new Float32Array(_this.length); for (var i=0;i < sz;i++)dec[i]=_this[i]; return dec; } WebGL._uint16ArraySlice=function(__arg){ var arg=arguments; var _this=/*__JS__ */this; var sz=0; var dec; var i=0; if (arg.length===0){ sz=_this.length; dec=new Uint16Array(sz); for (i=0;i < sz;i++) dec[i]=_this[i]; }else if (arg.length===2){ var start=arg[0]; var end=arg[1]; if (end > start){ sz=end-start; dec=new Uint16Array(sz); for (i=start;i < end;i++) dec[i-start]=_this[i]; }else { dec=new Uint16Array(0); } } return dec; } WebGL.expandContext=function(){ var from=Context.prototype; var to=/*__JS__ */CanvasRenderingContext2D.prototype; to.fillTrangles=from.fillTrangles; Buffer2D.__int__(null); to.setIBVB=function (x,y,ib,vb,numElement,mat,shader,shaderValues,startIndex,offset){ (startIndex===void 0)&& (startIndex=0); (offset===void 0)&& (offset=0); if (ib===null){ this._ib=this._ib || IndexBuffer2D.QuadrangleIB; ib=this._ib; GlUtils.expandIBQuadrangle(ib,(vb._byteLength / (4 *16)+8)); } this._setIBVB(x,y,ib,vb,numElement,mat,shader,shaderValues,startIndex,offset); }; to.fillTrangles=function (tex,x,y,points,m){ this._curMat=this._curMat || Matrix.create(); this._vb=this._vb || VertexBuffer2D.create(); if (!this._ib){ this._ib=IndexBuffer2D.create(); GlUtils.fillIBQuadrangle(this._ib,length / 4); }; var vb=this._vb; var length=points.length >> 4; GlUtils.fillTranglesVB(vb,x,y,points,m || this._curMat,0,0); GlUtils.expandIBQuadrangle(this._ib,(vb._byteLength / (4 *16)+8)); var shaderValues=new Value2D(0x01,0); shaderValues.textureHost=tex; var sd=new Shader2X("attribute vec2 position; attribute vec2 texcoord; uniform vec2 size; uniform mat4 mmat; varying vec2 v_texcoord; void main() { vec4 p=vec4(position.xy,0.0,1.0);vec4 pos=mmat*p; gl_Position =vec4((pos.x/size.x-0.5)*2.0,(0.5-pos.y/size.y)*2.0,pos.z,1.0); v_texcoord = texcoord; }","precision mediump float; varying vec2 v_texcoord; uniform sampler2D texture; void main() {vec4 color= texture2D(texture, v_texcoord); color.a*=1.0; gl_FragColor= color;}"); /*__JS__ */vb._vertType=3; this._setIBVB(x,y,this._ib,vb,length *6,m,sd,shaderValues,0,0); } } WebGL.enable=function(){ Browser.__init__(); if (Render.isConchApp){ if (!Render.isConchWebGL){ RunDriver.skinAniSprite=function (){ var tSkinSprite=new SkinMesh() return tSkinSprite; } WebGL.expandContext(); return false; } } RunDriver.getWebGLContext=function getWebGLContext (canvas){ var gl; var names=["webgl","experimental-webgl","webkit-3d","moz-webgl"]; for (var i=0;i < names.length;i++){ try { gl=canvas.getContext(names[i],{stencil:Config.isStencil,alpha:Config.isAlpha,antialias:Config.isAntialias,premultipliedAlpha:Config.premultipliedAlpha,preserveDrawingBuffer:Config.preserveDrawingBuffer}); }catch (e){} if (gl) return gl; } return null; } WebGL.mainContext=RunDriver.getWebGLContext(Render._mainCanvas); if (WebGL.mainContext==null) return false; if (Render.isWebGL)return true; HTMLImage.create=function (src,def){ return new WebGLImage(src,def); } HTMLSubImage.create=function (canvas,offsetX,offsetY,width,height,atlasImage,src){ return new WebGLSubImage(canvas,offsetX,offsetY,width,height,atlasImage,src); } Render.WebGL=WebGL; Render.isWebGL=true; DrawText.__init__(); RunDriver.createRenderSprite=function (type,next){ return new RenderSprite3D(type,next); } RunDriver.createWebGLContext2D=function (c){ return new WebGLContext2D(c); } RunDriver.changeWebGLSize=function (width,height){ laya.webgl.WebGL.onStageResize(width,height); } RunDriver.createGraphics=function (){ return new GraphicsGL(); }; var action=RunDriver.createFilterAction; RunDriver.createFilterAction=action ? action :function (type){ return new ColorFilterActionGL() } RunDriver.clear=function (color){ RenderState2D.worldScissorTest && laya.webgl.WebGL.mainContext.disable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); var ctx=Render.context.ctx; var c=color && (ctx._submits._length==0 || Config.preserveDrawingBuffer)? Color.create(color)._color :Stage._wgColor; if (c)ctx.clearBG(c[0],c[1],c[2],c[3]); else ctx.clearBG(0,0,0,0); RenderState2D.clear(); } RunDriver.addToAtlas=function (texture,force){ (force===void 0)&& (force=false); var bitmap=texture.bitmap; if (!Render.optimizeTextureMemory(texture.url,texture)){ (bitmap).enableMerageInAtlas=false; return; } if ((Laya.__typeof(bitmap,'laya.webgl.resource.IMergeAtlasBitmap'))&& ((bitmap).allowMerageInAtlas)){ bitmap.on(/*laya.events.Event.RECOVERED*/"recovered",texture,texture.addTextureToAtlas); } } RunDriver.isAtlas=function (bitmap){ return (bitmap instanceof laya.webgl.atlas.AtlasWebGLCanvas ); } AtlasResourceManager._enable(); RunDriver.beginFlush=function (){ var atlasResourceManager=AtlasResourceManager.instance; var count=atlasResourceManager.getAtlaserCount(); for (var i=0;i < count;i++){ var atlerCanvas=atlasResourceManager.getAtlaserByIndex(i).texture; (atlerCanvas._flashCacheImageNeedFlush)&& (RunDriver.flashFlushImage(atlerCanvas)); } } RunDriver.drawToCanvas=function (sprite,_renderType,canvasWidth,canvasHeight,offsetX,offsetY){ if (canvasWidth <=0 || canvasHeight <=0){ console.log("[error] canvasWidth and canvasHeight should greater than zero"); } canvasWidth |=0;canvasHeight |=0;offsetX |=0;offsetY |=0; var renderTarget=RenderTarget2D.create(canvasWidth,canvasHeight,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,0,false); renderTarget.start(); renderTarget.clear(0,0,0,0); Render.context.clear(); RenderSprite.renders[_renderType]._fun(sprite,Render.context,offsetX,RenderState2D.height-canvasHeight+offsetY); Render.context.flush(); renderTarget.end(); var pixels=renderTarget.getData(0,0,canvasWidth,canvasHeight); renderTarget.recycle(); if (pixels.byteLength !=canvasWidth *canvasHeight *4){ console.log('drawToCanvas error: w:'+canvasWidth+',h:'+canvasHeight+',datalen:'+pixels.byteLength); return; }; var htmlCanvas=new WebGLCanvas(); htmlCanvas._canvas=Browser.createElement("canvas"); htmlCanvas.size(canvasWidth,canvasHeight); var context=htmlCanvas._canvas.getContext('2d'); Browser.canvas.size(canvasWidth,canvasHeight); var tempContext=Browser.context; var imgData=tempContext.createImageData(canvasWidth,canvasHeight); imgData.data.set(/*__JS__ */new Uint8ClampedArray(pixels.buffer)); htmlCanvas._imgData=imgData; tempContext.putImageData(imgData,0,0); context.save(); context.translate(0,canvasHeight); context.scale(1,-1); context.drawImage(Browser.canvas.source,0,0); context.restore(); return htmlCanvas; } RunDriver.createFilterAction=function (type){ var action; switch (type){ case /*laya.filters.Filter.COLOR*/0x20: action=new ColorFilterActionGL(); break ; } return action; } RunDriver.addTextureToAtlas=function (texture){ texture._uvID++; AtlasResourceManager._atlasRestore++; ((texture.bitmap).enableMerageInAtlas)&& (AtlasResourceManager.instance.addToAtlas(texture)); } RunDriver.getTexturePixels=function (value,x,y,width,height){ (Render.context.ctx).clear(); var tSprite=new Sprite(); tSprite.graphics.drawTexture(value,-x,-y); var tRenderTarget=RenderTarget2D.create(width,height); tRenderTarget.start(); tRenderTarget.clear(0,0,0,0); tSprite.render(Render.context,0,0); (Render.context.ctx).flush(); tRenderTarget.end(); var tUint8Array=tRenderTarget.getData(0,0,width,height); var tArray=[]; var tIndex=0; for (var i=height-1;i >=0;i--){ for (var j=0;j < width;j++){ tIndex=(i *width+j)*4; tArray.push(tUint8Array[tIndex]); tArray.push(tUint8Array[tIndex+1]); tArray.push(tUint8Array[tIndex+2]); tArray.push(tUint8Array[tIndex+3]); } } return tArray; } RunDriver.skinAniSprite=function (){ var tSkinSprite=new SkinMesh() return tSkinSprite; } HTMLCanvas.create=function (type,canvas){ var ret=new WebGLCanvas(); ret._imgData=canvas; ret.flipY=false; return ret; } Filter._filterStart=function (scope,sprite,context,x,y){ var b=scope.getValue("bounds"); var source=RenderTarget2D.create(b.width,b.height); source.start(); source.clear(0,0,0,0); scope.addValue("src",source); scope.addValue("ScissorTest",RenderState2D.worldScissorTest); if (RenderState2D.worldScissorTest){ var tClilpRect=new Rectangle(); tClilpRect.copyFrom((context.ctx)._clipRect) scope.addValue("clipRect",tClilpRect); RenderState2D.worldScissorTest=false; laya.webgl.WebGL.mainContext.disable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); } } Filter._filterEnd=function (scope,sprite,context,x,y){ var b=scope.getValue("bounds"); var source=scope.getValue("src"); source.end(); var out=RenderTarget2D.create(b.width,b.height); out.start(); out.clear(0,0,0,0); scope.addValue("out",out); sprite._set$P('_filterCache',out); sprite._set$P('_isHaveGlowFilter',scope.getValue("_isHaveGlowFilter")); } Filter._EndTarget=function (scope,context){ var source=scope.getValue("src"); source.recycle(); var out=scope.getValue("out"); out.end(); var b=scope.getValue("ScissorTest"); if (b){ RenderState2D.worldScissorTest=true; laya.webgl.WebGL.mainContext.enable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); context.ctx.save(); var tClipRect=scope.getValue("clipRect"); (context.ctx).clipRect(tClipRect.x,tClipRect.y,tClipRect.width,tClipRect.height); } } Filter._useSrc=function (scope){ var source=scope.getValue("out"); source.end(); source=scope.getValue("src"); source.start(); source.clear(0,0,0,0); } Filter._endSrc=function (scope){ var source=scope.getValue("src"); source.end(); } Filter._useOut=function (scope){ var source=scope.getValue("src"); source.end(); source=scope.getValue("out"); source.start(); source.clear(0,0,0,0); } Filter._endOut=function (scope){ var source=scope.getValue("out"); source.end(); } Filter._recycleScope=function (scope){ scope.recycle(); } Filter._filter=function (sprite,context,x,y){ var next=this._next; if (next){ var filters=sprite.filters,len=filters.length; if (len==1 && (filters[0].type==/*laya.filters.Filter.COLOR*/0x20)){ context.ctx.save(); context.ctx.setFilters([filters[0]]); next._fun.call(next,sprite,context,x,y); context.ctx.restore(); return; }; var shaderValue; var b; var scope=SubmitCMDScope.create(); var p=Point.TEMP; var tMatrix=context.ctx._getTransformMatrix(); var mat=Matrix.create(); tMatrix.copyTo(mat); var tPadding=0; var tHalfPadding=0; var tIsHaveGlowFilter=false; var out=sprite._$P._filterCache ? sprite._$P._filterCache :null; if (!out || sprite._repaint){ tIsHaveGlowFilter=sprite._isHaveGlowFilter(); scope.addValue("_isHaveGlowFilter",tIsHaveGlowFilter); if (tIsHaveGlowFilter){ tPadding=50; tHalfPadding=25; } b=new Rectangle(); b.copyFrom((sprite).getSelfBounds()); b.x+=(sprite).x; b.y+=(sprite).y; b.x-=(sprite).pivotX+4; b.y-=(sprite).pivotY+4; var tSX=b.x; var tSY=b.y; b.width+=(tPadding+8); b.height+=(tPadding+8); p.x=b.x *mat.a+b.y *mat.c; p.y=b.y *mat.d+b.x *mat.b; b.x=p.x; b.y=p.y; p.x=b.width *mat.a+b.height *mat.c; p.y=b.height *mat.d+b.width *mat.b; b.width=p.x; b.height=p.y; if (b.width <=0 || b.height <=0){ return; } out && out.recycle(); scope.addValue("bounds",b); var submit=SubmitCMD.create([scope,sprite,context,0,0],Filter._filterStart); context.addRenderObject(submit); (context.ctx)._renderKey=0; (context.ctx)._shader2D.glTexture=null; var tX=sprite.x-tSX+tHalfPadding; var tY=sprite.y-tSY+tHalfPadding; next._fun.call(next,sprite,context,tX,tY); submit=SubmitCMD.create([scope,sprite,context,0,0],Filter._filterEnd); context.addRenderObject(submit); for (var i=0;i < len;i++){ if (i !=0){ submit=SubmitCMD.create([scope],Filter._useSrc); context.addRenderObject(submit); shaderValue=Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0); Matrix.TEMP.identity(); context.ctx.drawTarget(scope,0,0,b.width,b.height,Matrix.TEMP,"out",shaderValue,null,BlendMode.TOINT.overlay); submit=SubmitCMD.create([scope],Filter._useOut); context.addRenderObject(submit); }; var fil=filters[i]; fil.action.apply3d(scope,sprite,context,0,0); } submit=SubmitCMD.create([scope,context],Filter._EndTarget); context.addRenderObject(submit); }else { tIsHaveGlowFilter=sprite._$P._isHaveGlowFilter ? sprite._$P._isHaveGlowFilter :false; if (tIsHaveGlowFilter){ tPadding=50; tHalfPadding=25; } b=sprite.getBounds(); if (b.width <=0 || b.height <=0){ return; } b.width+=tPadding; b.height+=tPadding; p.x=b.x *mat.a+b.y *mat.c; p.y=b.y *mat.d+b.x *mat.b; b.x=p.x; b.y=p.y; p.x=b.width *mat.a+b.height *mat.c; p.y=b.height *mat.d+b.width *mat.b; b.width=p.x; b.height=p.y; scope.addValue("out",out); } x=x-tHalfPadding-sprite.x; y=y-tHalfPadding-sprite.y; p.setTo(x,y); mat.transformPoint(p); x=p.x+b.x; y=p.y+b.y; shaderValue=Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0); Matrix.TEMP.identity(); (context.ctx).drawTarget(scope,x,y,b.width,b.height,Matrix.TEMP,"out",shaderValue,null,BlendMode.TOINT.overlay); submit=SubmitCMD.create([scope],Filter._recycleScope); context.addRenderObject(submit); mat.destroy(); } } Float32Array.prototype.slice || (Float32Array.prototype.slice=WebGL._float32ArraySlice); Uint16Array.prototype.slice || (Uint16Array.prototype.slice=WebGL._uint16ArraySlice); Uint8Array.prototype.slice || (Uint8Array.prototype.slice=WebGL._uint8ArraySlice); return true; } WebGL.onStageResize=function(width,height){ if (WebGL.mainContext==null)return; WebGL.mainContext.viewport(0,0,width,height); RenderState2D.width=width; RenderState2D.height=height; } WebGL.onInvalidGLRes=function(){ AtlasResourceManager.instance.freeAll(); ResourceManager.releaseContentManagers(true); WebGL.doNodeRepaint(Laya.stage); WebGL.mainContext.viewport(0,0,RenderState2D.width,RenderState2D.height); Laya.stage.event(/*laya.events.Event.DEVICE_LOST*/"devicelost"); } WebGL.doNodeRepaint=function(sprite){ (sprite.numChildren==0)&& (sprite.repaint()); for (var i=0;i < sprite.numChildren;i++) WebGL.doNodeRepaint(sprite.getChildAt(i)); } WebGL.init=function(canvas,width,height){ WebGL.mainCanvas=canvas; HTMLCanvas._createContext=function (canvas){ return new WebGLContext2D(canvas); } WebGLCanvas._createContext=function (canvas){ return new WebGLContext2D(canvas); }; var gl=laya.webgl.WebGL.mainContext; if (gl.getShaderPrecisionFormat !=null){ var vertexPrecisionFormat=gl.getShaderPrecisionFormat(/*laya.webgl.WebGLContext.VERTEX_SHADER*/0x8B31,/*laya.webgl.WebGLContext.HIGH_FLOAT*/0x8DF2); var framePrecisionFormat=gl.getShaderPrecisionFormat(/*laya.webgl.WebGLContext.FRAGMENT_SHADER*/0x8B30,/*laya.webgl.WebGLContext.HIGH_FLOAT*/0x8DF2); WebGL.shaderHighPrecision=(vertexPrecisionFormat.precision&&framePrecisionFormat.precision)? true :false; }else { WebGL.shaderHighPrecision=false; } WebGL.compressAstc=gl.getExtension("WEBGL_compressed_texture_astc"); WebGL.compressAtc=gl.getExtension("WEBGL_compressed_texture_atc"); WebGL.compressEtc=gl.getExtension("WEBGL_compressed_texture_etc"); WebGL.compressEtc1=gl.getExtension("WEBGL_compressed_texture_etc1"); WebGL.compressPvrtc=gl.getExtension("WEBGL_compressed_texture_pvrtc"); WebGL.compressS3tc=gl.getExtension("WEBGL_compressed_texture_s3tc"); WebGL.compressS3tc_srgb=gl.getExtension("WEBGL_compressed_texture_s3tc_srgb"); gl.deleteTexture1=gl.deleteTexture; gl.deleteTexture=function (t){ if (t==WebGLContext.curBindTexValue){ WebGLContext.curBindTexValue=null; } gl.deleteTexture1(t); } WebGL.onStageResize(width,height); if (WebGL.mainContext==null) throw new Error("webGL getContext err!"); System.__init__(); AtlasResourceManager.__init__(); ShaderDefines2D.__init__(); Submit.__init__(); WebGLContext2D.__init__(); Value2D.__init__(); Shader2D.__init__(); Buffer2D.__int__(gl); BlendMode._init_(gl); if (Render.isConchApp){ /*__JS__ */conch.setOnInvalidGLRes(WebGL.onInvalidGLRes); } } WebGL.compressAstc=null; WebGL.compressAtc=null; WebGL.compressEtc=null; WebGL.compressEtc1=null; WebGL.compressPvrtc=null; WebGL.compressS3tc=null; WebGL.compressS3tc_srgb=null; WebGL.mainCanvas=null; WebGL.mainContext=null; WebGL.antialias=true; WebGL.shaderHighPrecision=false; WebGL._bg_null=[0,0,0,0]; return WebGL; })() //class laya.webgl.WebGLContext var WebGLContext=(function(){ function WebGLContext(){} __class(WebGLContext,'laya.webgl.WebGLContext'); WebGLContext.UseProgram=function(program){ if (WebGLContext._useProgram===program)return false; WebGL.mainContext.useProgram(program); WebGLContext._useProgram=program; return true; } WebGLContext.setDepthTest=function(gl,value){ value!==WebGLContext._depthTest && (WebGLContext._depthTest=value,value?gl.enable(/*CLASS CONST:laya.webgl.WebGLContext.DEPTH_TEST*/0x0B71):gl.disable(/*CLASS CONST:laya.webgl.WebGLContext.DEPTH_TEST*/0x0B71)); } WebGLContext.setDepthMask=function(gl,value){ value!==WebGLContext._depthMask && (WebGLContext._depthMask=value,gl.depthMask(value)); } WebGLContext.setDepthFunc=function(gl,value){ value!==WebGLContext._depthFunc && (WebGLContext._depthFunc=value,gl.depthFunc(value)); } WebGLContext.setBlend=function(gl,value){ value!==WebGLContext._blend && (WebGLContext._blend=value,value?gl.enable(/*CLASS CONST:laya.webgl.WebGLContext.BLEND*/0x0BE2):gl.disable(/*CLASS CONST:laya.webgl.WebGLContext.BLEND*/0x0BE2)); } WebGLContext.setBlendFunc=function(gl,sFactor,dFactor){ (sFactor!==WebGLContext._sFactor||dFactor!==WebGLContext._dFactor)&& (WebGLContext._sFactor=sFactor,WebGLContext._dFactor=dFactor,gl.blendFunc(sFactor,dFactor)); } WebGLContext.setCullFace=function(gl,value){ value!==WebGLContext._cullFace && (WebGLContext._cullFace=value,value?gl.enable(/*CLASS CONST:laya.webgl.WebGLContext.CULL_FACE*/0x0B44):gl.disable(/*CLASS CONST:laya.webgl.WebGLContext.CULL_FACE*/0x0B44)); } WebGLContext.setFrontFace=function(gl,value){ value!==WebGLContext._frontFace && (WebGLContext._frontFace=value,gl.frontFace(value)); } WebGLContext.bindTexture=function(gl,target,texture){ gl.bindTexture(target,texture); WebGLContext.curBindTexTarget=target; WebGLContext.curBindTexValue=texture; } WebGLContext.DEPTH_BUFFER_BIT=0x00000100; WebGLContext.STENCIL_BUFFER_BIT=0x00000400; WebGLContext.COLOR_BUFFER_BIT=0x00004000; WebGLContext.POINTS=0x0000; WebGLContext.LINES=0x0001; WebGLContext.LINE_LOOP=0x0002; WebGLContext.LINE_STRIP=0x0003; WebGLContext.TRIANGLES=0x0004; WebGLContext.TRIANGLE_STRIP=0x0005; WebGLContext.TRIANGLE_FAN=0x0006; WebGLContext.ZERO=0; WebGLContext.ONE=1; WebGLContext.SRC_COLOR=0x0300; WebGLContext.ONE_MINUS_SRC_COLOR=0x0301; WebGLContext.SRC_ALPHA=0x0302; WebGLContext.ONE_MINUS_SRC_ALPHA=0x0303; WebGLContext.DST_ALPHA=0x0304; WebGLContext.ONE_MINUS_DST_ALPHA=0x0305; WebGLContext.DST_COLOR=0x0306; WebGLContext.ONE_MINUS_DST_COLOR=0x0307; WebGLContext.SRC_ALPHA_SATURATE=0x0308; WebGLContext.FUNC_ADD=0x8006; WebGLContext.BLEND_EQUATION=0x8009; WebGLContext.BLEND_EQUATION_RGB=0x8009; WebGLContext.BLEND_EQUATION_ALPHA=0x883D; WebGLContext.FUNC_SUBTRACT=0x800A; WebGLContext.FUNC_REVERSE_SUBTRACT=0x800B; WebGLContext.BLEND_DST_RGB=0x80C8; WebGLContext.BLEND_SRC_RGB=0x80C9; WebGLContext.BLEND_DST_ALPHA=0x80CA; WebGLContext.BLEND_SRC_ALPHA=0x80CB; WebGLContext.CONSTANT_COLOR=0x8001; WebGLContext.ONE_MINUS_CONSTANT_COLOR=0x8002; WebGLContext.CONSTANT_ALPHA=0x8003; WebGLContext.ONE_MINUS_CONSTANT_ALPHA=0x8004; WebGLContext.BLEND_COLOR=0x8005; WebGLContext.ARRAY_BUFFER=0x8892; WebGLContext.ELEMENT_ARRAY_BUFFER=0x8893; WebGLContext.ARRAY_BUFFER_BINDING=0x8894; WebGLContext.ELEMENT_ARRAY_BUFFER_BINDING=0x8895; WebGLContext.STREAM_DRAW=0x88E0; WebGLContext.STATIC_DRAW=0x88E4; WebGLContext.DYNAMIC_DRAW=0x88E8; WebGLContext.BUFFER_SIZE=0x8764; WebGLContext.BUFFER_USAGE=0x8765; WebGLContext.CURRENT_VERTEX_ATTRIB=0x8626; WebGLContext.FRONT=0x0404; WebGLContext.BACK=0x0405; WebGLContext.CULL_FACE=0x0B44; WebGLContext.FRONT_AND_BACK=0x0408; WebGLContext.BLEND=0x0BE2; WebGLContext.DITHER=0x0BD0; WebGLContext.STENCIL_TEST=0x0B90; WebGLContext.DEPTH_TEST=0x0B71; WebGLContext.SCISSOR_TEST=0x0C11; WebGLContext.POLYGON_OFFSET_FILL=0x8037; WebGLContext.SAMPLE_ALPHA_TO_COVERAGE=0x809E; WebGLContext.SAMPLE_COVERAGE=0x80A0; WebGLContext.NO_ERROR=0; WebGLContext.INVALID_ENUM=0x0500; WebGLContext.INVALID_VALUE=0x0501; WebGLContext.INVALID_OPERATION=0x0502; WebGLContext.OUT_OF_MEMORY=0x0505; WebGLContext.CW=0x0900; WebGLContext.CCW=0x0901; WebGLContext.LINE_WIDTH=0x0B21; WebGLContext.ALIASED_POINT_SIZE_RANGE=0x846D; WebGLContext.ALIASED_LINE_WIDTH_RANGE=0x846E; WebGLContext.CULL_FACE_MODE=0x0B45; WebGLContext.FRONT_FACE=0x0B46; WebGLContext.DEPTH_RANGE=0x0B70; WebGLContext.DEPTH_WRITEMASK=0x0B72; WebGLContext.DEPTH_CLEAR_VALUE=0x0B73; WebGLContext.DEPTH_FUNC=0x0B74; WebGLContext.STENCIL_CLEAR_VALUE=0x0B91; WebGLContext.STENCIL_FUNC=0x0B92; WebGLContext.STENCIL_FAIL=0x0B94; WebGLContext.STENCIL_PASS_DEPTH_FAIL=0x0B95; WebGLContext.STENCIL_PASS_DEPTH_PASS=0x0B96; WebGLContext.STENCIL_REF=0x0B97; WebGLContext.STENCIL_VALUE_MASK=0x0B93; WebGLContext.STENCIL_WRITEMASK=0x0B98; WebGLContext.STENCIL_BACK_FUNC=0x8800; WebGLContext.STENCIL_BACK_FAIL=0x8801; WebGLContext.STENCIL_BACK_PASS_DEPTH_FAIL=0x8802; WebGLContext.STENCIL_BACK_PASS_DEPTH_PASS=0x8803; WebGLContext.STENCIL_BACK_REF=0x8CA3; WebGLContext.STENCIL_BACK_VALUE_MASK=0x8CA4; WebGLContext.STENCIL_BACK_WRITEMASK=0x8CA5; WebGLContext.VIEWPORT=0x0BA2; WebGLContext.SCISSOR_BOX=0x0C10; WebGLContext.COLOR_CLEAR_VALUE=0x0C22; WebGLContext.COLOR_WRITEMASK=0x0C23; WebGLContext.UNPACK_ALIGNMENT=0x0CF5; WebGLContext.PACK_ALIGNMENT=0x0D05; WebGLContext.MAX_TEXTURE_SIZE=0x0D33; WebGLContext.MAX_VIEWPORT_DIMS=0x0D3A; WebGLContext.SUBPIXEL_BITS=0x0D50; WebGLContext.RED_BITS=0x0D52; WebGLContext.GREEN_BITS=0x0D53; WebGLContext.BLUE_BITS=0x0D54; WebGLContext.ALPHA_BITS=0x0D55; WebGLContext.DEPTH_BITS=0x0D56; WebGLContext.STENCIL_BITS=0x0D57; WebGLContext.POLYGON_OFFSET_UNITS=0x2A00; WebGLContext.POLYGON_OFFSET_FACTOR=0x8038; WebGLContext.TEXTURE_BINDING_2D=0x8069; WebGLContext.SAMPLE_BUFFERS=0x80A8; WebGLContext.SAMPLES=0x80A9; WebGLContext.SAMPLE_COVERAGE_VALUE=0x80AA; WebGLContext.SAMPLE_COVERAGE_INVERT=0x80AB; WebGLContext.NUM_COMPRESSED_TEXTURE_FORMATS=0x86A2; WebGLContext.COMPRESSED_TEXTURE_FORMATS=0x86A3; WebGLContext.DONT_CARE=0x1100; WebGLContext.FASTEST=0x1101; WebGLContext.NICEST=0x1102; WebGLContext.GENERATE_MIPMAP_HINT=0x8192; WebGLContext.BYTE=0x1400; WebGLContext.UNSIGNED_BYTE=0x1401; WebGLContext.SHORT=0x1402; WebGLContext.UNSIGNED_SHORT=0x1403; WebGLContext.INT=0x1404; WebGLContext.UNSIGNED_INT=0x1405; WebGLContext.FLOAT=0x1406; WebGLContext.DEPTH_COMPONENT=0x1902; WebGLContext.ALPHA=0x1906; WebGLContext.RGB=0x1907; WebGLContext.RGBA=0x1908; WebGLContext.LUMINANCE=0x1909; WebGLContext.LUMINANCE_ALPHA=0x190A; WebGLContext.UNSIGNED_SHORT_4_4_4_4=0x8033; WebGLContext.UNSIGNED_SHORT_5_5_5_1=0x8034; WebGLContext.UNSIGNED_SHORT_5_6_5=0x8363; WebGLContext.FRAGMENT_SHADER=0x8B30; WebGLContext.VERTEX_SHADER=0x8B31; WebGLContext.MAX_VERTEX_ATTRIBS=0x8869; WebGLContext.MAX_VERTEX_UNIFORM_VECTORS=0x8DFB; WebGLContext.MAX_VARYING_VECTORS=0x8DFC; WebGLContext.MAX_COMBINED_TEXTURE_IMAGE_UNITS=0x8B4D; WebGLContext.MAX_VERTEX_TEXTURE_IMAGE_UNITS=0x8B4C; WebGLContext.MAX_TEXTURE_IMAGE_UNITS=0x8872; WebGLContext.MAX_FRAGMENT_UNIFORM_VECTORS=0x8DFD; WebGLContext.SHADER_TYPE=0x8B4F; WebGLContext.DELETE_STATUS=0x8B80; WebGLContext.LINK_STATUS=0x8B82; WebGLContext.VALIDATE_STATUS=0x8B83; WebGLContext.ATTACHED_SHADERS=0x8B85; WebGLContext.ACTIVE_UNIFORMS=0x8B86; WebGLContext.ACTIVE_ATTRIBUTES=0x8B89; WebGLContext.SHADING_LANGUAGE_VERSION=0x8B8C; WebGLContext.CURRENT_PROGRAM=0x8B8D; WebGLContext.NEVER=0x0200; WebGLContext.LESS=0x0201; WebGLContext.EQUAL=0x0202; WebGLContext.LEQUAL=0x0203; WebGLContext.GREATER=0x0204; WebGLContext.NOTEQUAL=0x0205; WebGLContext.GEQUAL=0x0206; WebGLContext.ALWAYS=0x0207; WebGLContext.KEEP=0x1E00; WebGLContext.REPLACE=0x1E01; WebGLContext.INCR=0x1E02; WebGLContext.DECR=0x1E03; WebGLContext.INVERT=0x150A; WebGLContext.INCR_WRAP=0x8507; WebGLContext.DECR_WRAP=0x8508; WebGLContext.VENDOR=0x1F00; WebGLContext.RENDERER=0x1F01; WebGLContext.VERSION=0x1F02; WebGLContext.NEAREST=0x2600; WebGLContext.LINEAR=0x2601; WebGLContext.NEAREST_MIPMAP_NEAREST=0x2700; WebGLContext.LINEAR_MIPMAP_NEAREST=0x2701; WebGLContext.NEAREST_MIPMAP_LINEAR=0x2702; WebGLContext.LINEAR_MIPMAP_LINEAR=0x2703; WebGLContext.TEXTURE_MAG_FILTER=0x2800; WebGLContext.TEXTURE_MIN_FILTER=0x2801; WebGLContext.TEXTURE_WRAP_S=0x2802; WebGLContext.TEXTURE_WRAP_T=0x2803; WebGLContext.TEXTURE_2D=0x0DE1; WebGLContext.TEXTURE=0x1702; WebGLContext.TEXTURE_CUBE_MAP=0x8513; WebGLContext.TEXTURE_BINDING_CUBE_MAP=0x8514; WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_X=0x8515; WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_X=0x8516; WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_Y=0x8517; WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_Y=0x8518; WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_Z=0x8519; WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_Z=0x851A; WebGLContext.MAX_CUBE_MAP_TEXTURE_SIZE=0x851C; WebGLContext.TEXTURE0=0x84C0; WebGLContext.TEXTURE1=0x84C1; WebGLContext.TEXTURE2=0x84C2; WebGLContext.TEXTURE3=0x84C3; WebGLContext.TEXTURE4=0x84C4; WebGLContext.TEXTURE5=0x84C5; WebGLContext.TEXTURE6=0x84C6; WebGLContext.TEXTURE7=0x84C7; WebGLContext.TEXTURE8=0x84C8; WebGLContext.TEXTURE9=0x84C9; WebGLContext.TEXTURE10=0x84CA; WebGLContext.TEXTURE11=0x84CB; WebGLContext.TEXTURE12=0x84CC; WebGLContext.TEXTURE13=0x84CD; WebGLContext.TEXTURE14=0x84CE; WebGLContext.TEXTURE15=0x84CF; WebGLContext.TEXTURE16=0x84D0; WebGLContext.TEXTURE17=0x84D1; WebGLContext.TEXTURE18=0x84D2; WebGLContext.TEXTURE19=0x84D3; WebGLContext.TEXTURE20=0x84D4; WebGLContext.TEXTURE21=0x84D5; WebGLContext.TEXTURE22=0x84D6; WebGLContext.TEXTURE23=0x84D7; WebGLContext.TEXTURE24=0x84D8; WebGLContext.TEXTURE25=0x84D9; WebGLContext.TEXTURE26=0x84DA; WebGLContext.TEXTURE27=0x84DB; WebGLContext.TEXTURE28=0x84DC; WebGLContext.TEXTURE29=0x84DD; WebGLContext.TEXTURE30=0x84DE; WebGLContext.TEXTURE31=0x84DF; WebGLContext.ACTIVE_TEXTURE=0x84E0; WebGLContext.REPEAT=0x2901; WebGLContext.CLAMP_TO_EDGE=0x812F; WebGLContext.MIRRORED_REPEAT=0x8370; WebGLContext.FLOAT_VEC2=0x8B50; WebGLContext.FLOAT_VEC3=0x8B51; WebGLContext.FLOAT_VEC4=0x8B52; WebGLContext.INT_VEC2=0x8B53; WebGLContext.INT_VEC3=0x8B54; WebGLContext.INT_VEC4=0x8B55; WebGLContext.BOOL=0x8B56; WebGLContext.BOOL_VEC2=0x8B57; WebGLContext.BOOL_VEC3=0x8B58; WebGLContext.BOOL_VEC4=0x8B59; WebGLContext.FLOAT_MAT2=0x8B5A; WebGLContext.FLOAT_MAT3=0x8B5B; WebGLContext.FLOAT_MAT4=0x8B5C; WebGLContext.SAMPLER_2D=0x8B5E; WebGLContext.SAMPLER_CUBE=0x8B60; WebGLContext.VERTEX_ATTRIB_ARRAY_ENABLED=0x8622; WebGLContext.VERTEX_ATTRIB_ARRAY_SIZE=0x8623; WebGLContext.VERTEX_ATTRIB_ARRAY_STRIDE=0x8624; WebGLContext.VERTEX_ATTRIB_ARRAY_TYPE=0x8625; WebGLContext.VERTEX_ATTRIB_ARRAY_NORMALIZED=0x886A; WebGLContext.VERTEX_ATTRIB_ARRAY_POINTER=0x8645; WebGLContext.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING=0x889F; WebGLContext.COMPILE_STATUS=0x8B81; WebGLContext.LOW_FLOAT=0x8DF0; WebGLContext.MEDIUM_FLOAT=0x8DF1; WebGLContext.HIGH_FLOAT=0x8DF2; WebGLContext.LOW_INT=0x8DF3; WebGLContext.MEDIUM_INT=0x8DF4; WebGLContext.HIGH_INT=0x8DF5; WebGLContext.FRAMEBUFFER=0x8D40; WebGLContext.RENDERBUFFER=0x8D41; WebGLContext.RGBA4=0x8056; WebGLContext.RGB5_A1=0x8057; WebGLContext.RGB565=0x8D62; WebGLContext.DEPTH_COMPONENT16=0x81A5; WebGLContext.STENCIL_INDEX=0x1901; WebGLContext.STENCIL_INDEX8=0x8D48; WebGLContext.DEPTH_STENCIL=0x84F9; WebGLContext.RENDERBUFFER_WIDTH=0x8D42; WebGLContext.RENDERBUFFER_HEIGHT=0x8D43; WebGLContext.RENDERBUFFER_INTERNAL_FORMAT=0x8D44; WebGLContext.RENDERBUFFER_RED_SIZE=0x8D50; WebGLContext.RENDERBUFFER_GREEN_SIZE=0x8D51; WebGLContext.RENDERBUFFER_BLUE_SIZE=0x8D52; WebGLContext.RENDERBUFFER_ALPHA_SIZE=0x8D53; WebGLContext.RENDERBUFFER_DEPTH_SIZE=0x8D54; WebGLContext.RENDERBUFFER_STENCIL_SIZE=0x8D55; WebGLContext.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE=0x8CD0; WebGLContext.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME=0x8CD1; WebGLContext.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL=0x8CD2; WebGLContext.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE=0x8CD3; WebGLContext.COLOR_ATTACHMENT0=0x8CE0; WebGLContext.DEPTH_ATTACHMENT=0x8D00; WebGLContext.STENCIL_ATTACHMENT=0x8D20; WebGLContext.DEPTH_STENCIL_ATTACHMENT=0x821A; WebGLContext.NONE=0; WebGLContext.FRAMEBUFFER_COMPLETE=0x8CD5; WebGLContext.FRAMEBUFFER_INCOMPLETE_ATTACHMENT=0x8CD6; WebGLContext.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT=0x8CD7; WebGLContext.FRAMEBUFFER_INCOMPLETE_DIMENSIONS=0x8CD9; WebGLContext.FRAMEBUFFER_UNSUPPORTED=0x8CDD; WebGLContext.FRAMEBUFFER_BINDING=0x8CA6; WebGLContext.RENDERBUFFER_BINDING=0x8CA7; WebGLContext.MAX_RENDERBUFFER_SIZE=0x84E8; WebGLContext.INVALID_FRAMEBUFFER_OPERATION=0x0506; WebGLContext.UNPACK_FLIP_Y_WEBGL=0x9240; WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL=0x9241; WebGLContext.CONTEXT_LOST_WEBGL=0x9242; WebGLContext.UNPACK_COLORSPACE_CONVERSION_WEBGL=0x9243; WebGLContext.BROWSER_DEFAULT_WEBGL=0x9244; WebGLContext._useProgram=null; WebGLContext._depthTest=true; WebGLContext._depthMask=true; WebGLContext._blend=false; WebGLContext._cullFace=false; WebGLContext.curBindTexTarget=null; WebGLContext.curBindTexValue=null; __static(WebGLContext, ['_depthFunc',function(){return this._depthFunc=/*CLASS CONST:laya.webgl.WebGLContext.LESS*/0x0201;},'_sFactor',function(){return this._sFactor=/*CLASS CONST:laya.webgl.WebGLContext.ONE*/1;},'_dFactor',function(){return this._dFactor=/*CLASS CONST:laya.webgl.WebGLContext.ZERO*/0;},'_frontFace',function(){return this._frontFace=/*CLASS CONST:laya.webgl.WebGLContext.CCW*/0x0901;} ]); return WebGLContext; })() //class laya.webgl.display.GraphicsGL extends laya.display.Graphics var GraphicsGL=(function(_super){ function GraphicsGL(){ GraphicsGL.__super.call(this); } __class(GraphicsGL,'laya.webgl.display.GraphicsGL',_super); var __proto=GraphicsGL.prototype; __proto.setShader=function(shader){ this._saveToCmd(Render.context._setShader,[shader]); } __proto.setIBVB=function(x,y,ib,vb,numElement,shader){ this._saveToCmd(Render.context._setIBVB,[x,y,ib,vb,numElement,shader]); } __proto.drawParticle=function(x,y,ps){ var pt=RunDriver.createParticleTemplate2D(ps); pt.x=x; pt.y=y; this._saveToCmd(Render.context._drawParticle,[pt]); } return GraphicsGL; })(Graphics) //class laya.webgl.canvas.WebGLContext2D extends laya.resource.Context var WebGLContext2D=(function(_super){ var ContextParams; function WebGLContext2D(c){ this._x=0; this._y=0; this._id=++WebGLContext2D._COUNT; //this._other=null; this._path=null; //this._primitiveValue2D=null; this._drawCount=1; this._maxNumEle=0; this._clear=false; this._isMain=false; this._atlasResourceChange=0; this._submits=null; this._curSubmit=null; this._ib=null; this._vb=null; //this._curMat=null; this._nBlendType=0; //this._save=null; //this._targets=null; //this._renderKey=NaN; this._saveMark=null; this._shader2D=null; //this._triangleMesh=null; //drawTriangles专用mesh。由于ib不固定,所以不能与_mesh通用 this.meshlist=[]; /**所cacheAs精灵*/ //this.sprite=null; /*******************************************start矢量绘制***************************************************/ this.mId=-1; this.mHaveKey=false; this.mHaveLineKey=false; this.mX=0; this.mY=0; WebGLContext2D.__super.call(this); this._width=99999999; this._height=99999999; this._clipRect=WebGLContext2D.MAXCLIPRECT; this.mOutPoint this._canvas=c; WebGLContext2D._contextcount++; if (Render.isFlash){ this._ib=IndexBuffer2D.create(/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); GlUtils.fillIBQuadrangle(this._ib,16); }else this._ib=IndexBuffer2D.QuadrangleIB; this.clear(); } __class(WebGLContext2D,'laya.webgl.canvas.WebGLContext2D',_super); var __proto=WebGLContext2D.prototype; __proto.setIsMainContext=function(){ this._isMain=true; } __proto.clearBG=function(r,g,b,a){ var gl=WebGL.mainContext; gl.clearColor(r,g,b,a); gl.clear(/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000); } __proto._getSubmits=function(){ return this._submits; } __proto._releaseMem=function(){ if (!this._submits) return; this._curMat.destroy(); this._curMat=null; this._shader2D.destroy(); this._shader2D=null; for (var i=0,n=this._submits._length;i < n;i++) this._submits[i].releaseRender(); this._submits.length=0; this._submits._length=0; this._submits=null; this._curSubmit=null; this._path && this._path.recover(); this._path=null; this._other && (this._other.font=null); this._save=null; if (this._vb){ this._vb.releaseResource(); this._vb.destroy(); this._vb.destory(); this._vb=null; } } __proto.destroy=function(){ --WebGLContext2D._contextcount; this.sprite=null; this._releaseMem(); this._targets && this._targets.destroy(); this._targets=null; this._canvas=null; this._ib && (this._ib !=IndexBuffer2D.QuadrangleIB)&& this._ib.releaseResource(); } __proto.clear=function(){ if (!this._submits){ this._other=ContextParams.DEFAULT; this._curMat=Matrix.create(); this._vb=VertexBuffer2D.create(-1); this._submits=[]; this._save=[SaveMark.Create(this)]; this._save.length=10; this._shader2D=new Shader2D(); this._triangleMesh=MeshTexture.getAMesh(); } this._vb.clear(); this._targets && (this._targets.repaint=true); this._other=ContextParams.DEFAULT; this._clear=true; this._repaint=false; this._drawCount=1; this._renderKey=0; this._other.lineWidth=this._shader2D.ALPHA=1.0; this._nBlendType=0; this._clipRect=WebGLContext2D.MAXCLIPRECT; this._curSubmit=Submit.RENDERBASE; this._shader2D.glTexture=null; this._shader2D.fillStyle=this._shader2D.strokeStyle=DrawStyle.DEFAULT; for (var i=0,n=this._submits._length;i < n;i++) this._submits[i].releaseRender(); this._submits._length=0; this._curMat.identity(); this._other.clear(); this._saveMark=this._save[0]; this._save._length=1; } __proto.size=function(w,h){ if (this._width !=w || this._height !=h){ if (w==0 || h==0){ if (this._vb._byteLength !=0){ this._width=w; this._height=h; this._vb.clear(); this._vb.upload(); } for (var i=0,n=this._submits._length;i < n;i++) this._submits[i].releaseRender(); this._submits.length=0; this._submits._length=0; this._curSubmit=null; this._path && this._path.recover(); this._path=null; this.sprite=null; this._targets && (this._targets.destroy()); this._targets=null; }else { this._width=w; this._height=h; this._targets && (this._targets.size(w,h)); this._canvas.memorySize-=this._canvas.memorySize; } } if (w===0 && h===0)this._releaseMem(); } __proto._getTransformMatrix=function(){ return this._curMat; } __proto.translate=function(x,y){ if (x!==0 || y!==0){ SaveTranslate.save(this); if (this._curMat.bTransform){ SaveTransform.save(this); this._curMat.transformPointN(Point.TEMP.setTo(x,y)); x=Point.TEMP.x; y=Point.TEMP.y; } this._x+=x; this._y+=y; } } __proto.save=function(){ this._save[this._save._length++]=SaveMark.Create(this); } __proto.restore=function(){ var sz=this._save._length; if (sz < 1) return; for (var i=sz-1;i >=0;i--){ var o=this._save[i]; o.restore(this); if (o.isSaveMark()){ this._save._length=i; return; } } } __proto._fillText=function(txt,words,x,y,fontStr,color,strokeColor,lineWidth,textAlign,underLine){ (underLine===void 0)&& (underLine=0); var shader=this._shader2D; var curShader=this._curSubmit.shaderValue; var font=fontStr ? FontInContext.create(fontStr):this._other.font; if (AtlasResourceManager.enabled){ if (shader.ALPHA!==curShader.ALPHA) shader.glTexture=null; DrawText.drawText(this,txt,words,this._curMat,font,textAlign || this._other.textAlign,color,strokeColor,lineWidth,x,y,underLine); }else { var preDef=this._shader2D.defines.getValue(); var colorAdd=color ? Color.create(color)._color :shader.colorAdd; if (shader.ALPHA!==curShader.ALPHA || colorAdd!==shader.colorAdd || curShader.colorAdd!==shader.colorAdd){ shader.glTexture=null; shader.colorAdd=colorAdd; } DrawText.drawText(this,txt,words,this._curMat,font,textAlign || this._other.textAlign,color,strokeColor,lineWidth,x,y,underLine); } } //TODO:实现下划线 __proto.fillWords=function(words,x,y,fontStr,color,underLine){ this._fillText(null,words,x,y,fontStr,color,null,-1,null,underLine); } __proto.fillBorderWords=function(words,x,y,font,color,borderColor,lineWidth){ this._fillBorderText(null,words,x,y,font,color,borderColor,lineWidth,null); } __proto.fillText=function(txt,x,y,fontStr,color,textAlign){ this._fillText(txt,null,x,y,fontStr,color,null,-1,textAlign); } __proto.strokeText=function(txt,x,y,fontStr,color,lineWidth,textAlign){ this._fillText(txt,null,x,y,fontStr,null,color,lineWidth || 1,textAlign); } __proto.fillBorderText=function(txt,x,y,fontStr,fillColor,borderColor,lineWidth,textAlign){ this._fillBorderText(txt,null,x,y,fontStr,fillColor,borderColor,lineWidth,textAlign); } __proto._fillBorderText=function(txt,words,x,y,fontStr,fillColor,borderColor,lineWidth,textAlign){ if (!AtlasResourceManager.enabled){ this._fillText(txt,words,x,y,fontStr,null,borderColor,lineWidth || 1,textAlign); this._fillText(txt,words,x,y,fontStr,fillColor,null,-1,textAlign); return; }; var shader=this._shader2D; var curShader=this._curSubmit.shaderValue; if (shader.ALPHA!==curShader.ALPHA) shader.glTexture=null; var font=fontStr ? (WebGLContext2D._fontTemp.setFont(fontStr),WebGLContext2D._fontTemp):this._other.font; DrawText.drawText(this,txt,words,this._curMat,font,textAlign || this._other.textAlign,fillColor,borderColor,lineWidth || 1,x,y,0); } __proto.fillRect=function(x,y,width,height,fillStyle){ var vb=this._vb; if (GlUtils.fillRectImgVb(vb,this._clipRect,x,y,width,height,Texture.DEF_UV,this._curMat,this._x,this._y,0,0)){ this._renderKey=0; var pre=this._shader2D.fillStyle; fillStyle && (this._shader2D.fillStyle=DrawStyle.create(fillStyle)); var shader=this._shader2D; var curShader=this._curSubmit.shaderValue; if (shader.fillStyle!==curShader.fillStyle || shader.ALPHA!==curShader.ALPHA){ shader.glTexture=null; var submit=this._curSubmit=Submit.createSubmit(this,this._ib,vb,((vb._byteLength-16 */*laya.webgl.utils.Buffer2D.FLOAT32*/4)/ 32)*3,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.COLOR2D*/0x02,0)); submit.shaderValue.color=shader.fillStyle._color._color; submit.shaderValue.ALPHA=shader.ALPHA; this._submits[this._submits._length++]=submit; } this._curSubmit._numEle+=6; this._shader2D.fillStyle=pre; } } __proto.fillTexture=function(texture,x,y,width,height,type,offset,other){ if (!(texture.loaded && texture.bitmap && texture.source)){ if (this.sprite){ Laya.timer.callLater(this,this._repaintSprite); } return; }; var vb=this._vb; var w=texture.bitmap.width,h=texture.bitmap.height,uv=texture.uv; var ox=offset.x % texture.width,oy=offset.y % texture.height; if (w !=other.w || h !=other.h){ if (!other.w && !other.h){ other.oy=other.ox=0; switch (type){ case "repeat": other.width=width; other.height=height; break ; case "repeat-x": other.width=width; if (oy < 0){ if (texture.height+oy > height){ other.height=height; }else { other.height=texture.height+oy; } }else { other.oy=oy; if (texture.height+oy > height){ other.height=height-oy; }else { other.height=texture.height; } } break ; case "repeat-y": if (ox < 0){ if (texture.width+ox > width){ other.width=width; }else { other.width=texture.width+ox; } }else { other.ox=ox; if (texture.width+ox > width){ other.width=width-ox; }else { other.width=texture.width; } } other.height=height; break ; case "no-repeat": if (ox < 0){ if (texture.width+ox > width){ other.width=width; }else { other.width=texture.width+ox; } }else { other.ox=ox; if (texture.width+ox > width){ other.width=width-ox; }else { other.width=texture.width; } } if (oy < 0){ if (texture.height+oy > height){ other.height=height; }else { other.height=texture.height+oy; } }else { other.oy=oy; if (texture.height+oy > height){ other.height=height-oy; }else { other.height=texture.height; } } break ; default : other.width=width; other.height=height; break ; } } other.w=w; other.h=h; other.uv=[0,0,other.width / w,0,other.width / w,other.height / h,0,other.height / h]; } x+=other.ox; y+=other.oy; ox-=other.ox; oy-=other.oy; if (GlUtils.fillRectImgVb(vb,this._clipRect,x,y,other.width,other.height,other.uv,this._curMat,this._x,this._y,0,0)){ this._renderKey=0; var submit=SubmitTexture.create(this,this._ib,vb,((vb._byteLength-16 */*laya.webgl.utils.Buffer2D.FLOAT32*/4)/ 32)*3,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.FILLTEXTURE*/0x100,0)); this._submits[this._submits._length++]=submit; var shaderValue=submit.shaderValue; shaderValue.textureHost=texture; var tTextureX=uv[0] *w; var tTextureY=uv[1] *h; var tTextureW=(uv[2]-uv[0])*w; var tTextureH=(uv[5]-uv[3])*h; var tx=-ox / w; var ty=-oy / h; shaderValue.u_TexRange[0]=tTextureX / w; shaderValue.u_TexRange[1]=tTextureW / w; shaderValue.u_TexRange[2]=tTextureY / h; shaderValue.u_TexRange[3]=tTextureH / h; shaderValue.u_offset[0]=tx; shaderValue.u_offset[1]=ty; if (AtlasResourceManager.enabled && !this._isMain) submit.addTexture(texture,(vb._byteLength >> 2)-/*CLASS CONST:laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16); this._curSubmit=submit; submit._renderType=/*laya.webgl.submit.Submit.TYPE_FILLTEXTURE*/10017; submit._numEle+=6; } } __proto.setShader=function(shader){ SaveBase.save(this,/*laya.webgl.canvas.save.SaveBase.TYPE_SHADER*/0x100000,this._shader2D,true); this._shader2D.shader=shader; } __proto.setFilters=function(value){ SaveBase.save(this,/*laya.webgl.canvas.save.SaveBase.TYPE_FILTERS*/0x200000,this._shader2D,true); this._shader2D.filters=value; this._curSubmit=Submit.RENDERBASE; this._renderKey=0; this._drawCount++; } __proto.drawTexture=function(tex,x,y,width,height,tx,ty){ this._drawTextureM(tex,x,y,width,height,tx,ty,null,1); } __proto.addTextureVb=function(invb,x,y){ var finalVB=this._curSubmit._vb || this._vb; var vpos=(finalVB._byteLength >> 2); finalVB.byteLength=((vpos+/*CLASS CONST:laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16)<< 2); var vbdata=finalVB.getFloat32Array(); for (var i=0,ci=0;i < 16;i+=4){ vbdata[vpos++]=invb[i]+x; vbdata[vpos++]=invb[i+1]+y; vbdata[vpos++]=invb[i+2]; vbdata[vpos++]=invb[i+3]; } this._curSubmit._numEle+=6; this._maxNumEle=Math.max(this._maxNumEle,this._curSubmit._numEle); finalVB._upload=true; } __proto.willDrawTexture=function(tex,alpha){ if (!(tex.loaded && tex.bitmap && tex.source)){ if (this.sprite){ Laya.timer.callLater(this,this._repaintSprite); } return 0; }; var webGLImg=tex.bitmap; var rid=webGLImg.id+this._shader2D.ALPHA *alpha+/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016; if (rid==this._renderKey)return rid; var shader=this._shader2D; var preAlpha=shader.ALPHA; var curShader=this._curSubmit.shaderValue; shader.ALPHA *=alpha; this._renderKey=rid; this._drawCount++; shader.glTexture=webGLImg; var vb=this._vb; var submit=null; var vbSize=(vb._byteLength / 32)*3; submit=SubmitTexture.create(this,this._ib,vb,vbSize,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0)); this._submits[this._submits._length++]=submit; submit.shaderValue.textureHost=tex; submit._renderType=/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016; submit._preIsSameTextureShader=this._curSubmit._renderType===/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016 && shader.ALPHA===curShader.ALPHA; this._curSubmit=submit; shader.ALPHA=preAlpha; return rid; } __proto.drawTextures=function(tex,pos,tx,ty){ if (!(tex.loaded && tex.bitmap && tex.source)){ this.sprite && Laya.timer.callLater(this,this._repaintSprite); return; }; var pre=this._clipRect; this._clipRect=WebGLContext2D.MAXCLIPRECT; if (!this._drawTextureM(tex,pos[0],pos[1],tex.width,tex.height,tx,ty,null,1)){ alert("drawTextures err"); return; } this._clipRect=pre; Stat.drawCall++; if (pos.length < 4) return; var finalVB=this._curSubmit._vb || this._vb; var sx=this._curMat.a,sy=this._curMat.d; for (var i=2,sz=pos.length;i < sz;i+=2){ GlUtils.copyPreImgVb(finalVB,(pos[i]-pos[i-2])*sx,(pos[i+1]-pos[i-1])*sy); this._curSubmit._numEle+=6; } this._maxNumEle=Math.max(this._maxNumEle,this._curSubmit._numEle); } __proto._drawTextureM=function(tex,x,y,width,height,tx,ty,m,alpha){ if (!(tex.loaded && tex.source)){ if (this.sprite){ Laya.timer.callLater(this,this._repaintSprite); } return false; }; var finalVB=this._curSubmit._vb || this._vb; var webGLImg=tex.bitmap; x+=tx; y+=ty; this._drawCount++; var rid=webGLImg.id+this._shader2D.ALPHA *alpha+/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016; if (rid !=this._renderKey){ this._renderKey=rid; var curShader=this._curSubmit.shaderValue; var shader=this._shader2D; var alphaBack=shader.ALPHA; shader.ALPHA *=alpha; shader.glTexture=webGLImg; var vb=this._vb; var submit=null; var vbSize=(vb._byteLength / 32)*3; submit=SubmitTexture.create(this,this._ib,vb,vbSize,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0)); this._submits[this._submits._length++]=submit; submit.shaderValue.textureHost=tex; submit._renderType=/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016; submit._preIsSameTextureShader=this._curSubmit._renderType===/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016 && shader.ALPHA===curShader.ALPHA; this._curSubmit=submit; finalVB=this._curSubmit._vb || this._vb; shader.ALPHA=alphaBack; } if (GlUtils.fillRectImgVb(finalVB,this._clipRect,x,y,width || tex.width,height || tex.height,tex.uv,m || this._curMat,this._x,this._y,0,0)){ if (AtlasResourceManager.enabled && !this._isMain) (this._curSubmit).addTexture(tex,(finalVB._byteLength >> 2)-/*CLASS CONST:laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16); this._curSubmit._numEle+=6; this._maxNumEle=Math.max(this._maxNumEle,this._curSubmit._numEle); return true; } return false; } __proto._repaintSprite=function(){ if(this.sprite) this.sprite.repaint(); } //} __proto._drawText=function(tex,x,y,width,height,m,tx,ty,dx,dy){ var webGLImg=tex.bitmap; this._drawCount++; var rid=webGLImg.id+this._shader2D.ALPHA+/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016; if (rid !=this._renderKey){ this._renderKey=rid; var curShader=this._curSubmit.shaderValue; var shader=this._shader2D; shader.glTexture=webGLImg; var vb=this._vb; var submit=null; var submitID=NaN; var vbSize=(vb._byteLength / 32)*3; if (AtlasResourceManager.enabled){ submit=SubmitTexture.create(this,this._ib,vb,vbSize,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0)); }else { submit=SubmitTexture.create(this,this._ib,vb,vbSize,TextSV.create()); } submit._preIsSameTextureShader=this._curSubmit._renderType===/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016 && shader.ALPHA===curShader.ALPHA; this._submits[this._submits._length++]=submit; submit.shaderValue.textureHost=tex; submit._renderType=/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016; this._curSubmit=submit; } tex.active(); var finalVB=this._curSubmit._vb || this._vb; if (GlUtils.fillRectImgVb(finalVB,this._clipRect,x+tx,y+ty,width || tex.width,height || tex.height,tex.uv,m || this._curMat,this._x,this._y,dx,dy,true)){ if (AtlasResourceManager.enabled && !this._isMain){ (this._curSubmit).addTexture(tex,(finalVB._byteLength >> 2)-/*CLASS CONST:laya.webgl.canvas.WebGLContext2D._RECTVBSIZE*/16); } this._curSubmit._numEle+=6; this._maxNumEle=Math.max(this._maxNumEle,this._curSubmit._numEle); } } __proto.drawTextureWithTransform=function(tex,x,y,width,height,transform,tx,ty,alpha){ if (!transform){ this._drawTextureM(tex,x,y,width,height,tx,ty,null,alpha); return; }; var curMat=this._curMat; var prex=this._x; var prey=this._y; (tx!==0 || ty!==0)&& (this._x=tx *curMat.a+ty *curMat.c,this._y=ty *curMat.d+tx *curMat.b); if (transform && curMat.bTransform){ Matrix.mul(transform,curMat,WebGLContext2D._tmpMatrix); transform=WebGLContext2D._tmpMatrix; transform._checkTransform(); }else { this._x+=curMat.tx; this._y+=curMat.ty; } this._drawTextureM(tex,x,y,width,height,0,0,transform,alpha); this._x=prex; this._y=prey; } __proto.fillQuadrangle=function(tex,x,y,point4,m){ var submit=this._curSubmit; var vb=this._vb; var shader=this._shader2D; var curShader=submit.shaderValue; this._renderKey=0; if (tex.bitmap){ var t_tex=tex.bitmap; if (shader.glTexture !=t_tex || shader.ALPHA!==curShader.ALPHA){ shader.glTexture=t_tex; submit=this._curSubmit=Submit.createSubmit(this,this._ib,vb,((vb._byteLength)/ 32)*3,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0)); submit.shaderValue.glTexture=t_tex; this._submits[this._submits._length++]=submit; } GlUtils.fillQuadrangleImgVb(vb,x,y,point4,tex.uv,m || this._curMat,this._x,this._y); }else { if (!submit.shaderValue.fillStyle || !submit.shaderValue.fillStyle.equal(tex)|| shader.ALPHA!==curShader.ALPHA){ shader.glTexture=null; submit=this._curSubmit=Submit.createSubmit(this,this._ib,vb,((vb._byteLength)/ 32)*3,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.COLOR2D*/0x02,0)); submit.shaderValue.defines.add(/*laya.webgl.shader.d2.ShaderDefines2D.COLOR2D*/0x02); submit.shaderValue.fillStyle=DrawStyle.create(tex); this._submits[this._submits._length++]=submit; } GlUtils.fillQuadrangleImgVb(vb,x,y,point4,Texture.DEF_UV,m || this._curMat,this._x,this._y); } submit._numEle+=6; } __proto.drawTexture2=function(x,y,pivotX,pivotY,transform,alpha,blendMode,args){ if (alpha==0)return; var curMat=this._curMat; this._x=x *curMat.a+y *curMat.c; this._y=y *curMat.d+x *curMat.b; if (transform){ if (curMat.bTransform || transform.bTransform){ Matrix.mul(transform,curMat,WebGLContext2D._tmpMatrix); transform=WebGLContext2D._tmpMatrix; }else { this._x+=transform.tx+curMat.tx; this._y+=transform.ty+curMat.ty; transform=Matrix.EMPTY; } } if (alpha===1 && !blendMode) this._drawTextureM(args[0],args[1]-pivotX,args[2]-pivotY,args[3],args[4],0,0,transform,1); else { var preAlpha=this._shader2D.ALPHA; var preblendType=this._nBlendType; this._shader2D.ALPHA=alpha; blendMode && (this._nBlendType=BlendMode.TOINT(blendMode)); this._drawTextureM(args[0],args[1]-pivotX,args[2]-pivotY,args[3],args[4],0,0,transform,1); this._shader2D.ALPHA=preAlpha; this._nBlendType=preblendType; } this._x=this._y=0; } __proto.drawCanvas=function(canvas,x,y,width,height){ var src=canvas.context; this._renderKey=0; if (src._targets){ this._submits[this._submits._length++]=SubmitCanvas.create(src,0,null); this._curSubmit=Submit.RENDERBASE; src._targets.drawTo(this,x,y,width,height); }else { var submit=this._submits[this._submits._length++]=SubmitCanvas.create(src,this._shader2D.ALPHA,this._shader2D.filters); var sx=width / canvas.width; var sy=height / canvas.height; var mat=submit._matrix; this._curMat.copyTo(mat); sx !=1 && sy !=1 && mat.scale(sx,sy); var tx=mat.tx,ty=mat.ty; mat.tx=mat.ty=0; mat.transformPoint(Point.TEMP.setTo(x,y)); mat.translate(Point.TEMP.x+tx,Point.TEMP.y+ty); this._curSubmit=Submit.RENDERBASE; } if (Config.showCanvasMark){ this.save(); this.lineWidth=4; this.strokeStyle=src._targets ? "yellow" :"green"; this.strokeRect(x-1,y-1,width+2,height+2,1); this.strokeRect(x,y,width,height,1); this.restore(); } } __proto.drawTarget=function(scope,x,y,width,height,m,proName,shaderValue,uv,blend){ (blend===void 0)&& (blend=-1); var vb=this._vb; if (GlUtils.fillRectImgVb(vb,this._clipRect,x,y,width,height,uv || Texture.DEF_UV,m || this._curMat,this._x,this._y,0,0)){ this._renderKey=0; var shader=this._shader2D; shader.glTexture=null; var curShader=this._curSubmit.shaderValue; var submit=this._curSubmit=SubmitTarget.create(this,this._ib,vb,((vb._byteLength-16 */*laya.webgl.utils.Buffer2D.FLOAT32*/4)/ 32)*3,shaderValue,proName); if (blend==-1){ submit.blendType=this._nBlendType; }else { submit.blendType=blend; } submit.scope=scope; this._submits[this._submits._length++]=submit; this._curSubmit._numEle+=6; } } /** *把颜色跟当前设置的alpha混合 *@return */ __proto.mixRGBandAlpha=function(color){ return this._mixRGBandAlpha(color,this._shader2D.ALPHA); } __proto._mixRGBandAlpha=function(color,alpha){ var a=((color & 0xff000000)>>> 24); if (a !=0){ a*=alpha; }else { a=alpha*255; } return (color & 0x00ffffff)| (a << 24); } __proto.drawTriangles=function(tex,x,y,vertices,uvs,indices,matrix,alpha,color,blendMode){ if (!(tex.loaded && tex.source)){ if (this.sprite){ Laya.timer.callLater(this,this._repaintSprite); } return false; } this._drawCount++; var webGLImg=tex.bitmap; var rgba=this._mixRGBandAlpha(0xffffffff,alpha); var vertNum=vertices.length / 2; var eleNum=indices.length; this._renderKey=-1; var submit=this._curSubmit=SubmitTexture.create(this,this._triangleMesh.getIBR(),this._triangleMesh.getVBR(),this._triangleMesh.indexNum,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0)); submit.shaderValue.textureHost=tex; submit._renderType=/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016; this._submits[this._submits._length++]=submit; if(matrix){ WebGLContext2D._tmpMatrix.a=matrix.a;WebGLContext2D._tmpMatrix.b=matrix.b;WebGLContext2D._tmpMatrix.c=matrix.c;WebGLContext2D._tmpMatrix.d=matrix.d;WebGLContext2D._tmpMatrix.tx=matrix.tx+x;WebGLContext2D._tmpMatrix.ty=matrix.ty+y; Matrix.mul(WebGLContext2D._tmpMatrix,this._curMat,WebGLContext2D._tmpMatrix); }else { WebGLContext2D._tmpMatrix.a=this._curMat.a;WebGLContext2D._tmpMatrix.b=this._curMat.b;WebGLContext2D._tmpMatrix.c=this._curMat.c;WebGLContext2D._tmpMatrix.d=this._curMat.d;WebGLContext2D._tmpMatrix.tx=this._curMat.tx+x;WebGLContext2D._tmpMatrix.ty=this._curMat.ty+y; } this._triangleMesh.addData(vertices,uvs,indices,WebGLContext2D._tmpMatrix,rgba,this); this._curSubmit._numEle+=eleNum; this._maxNumEle=Math.max(this._maxNumEle,this._curSubmit._numEle); return true; } __proto.transform=function(a,b,c,d,tx,ty){ SaveTransform.save(this); Matrix.mul(Matrix.TEMP.setTo(a,b,c,d,tx,ty),this._curMat,this._curMat); this._curMat._checkTransform(); } __proto.setTransformByMatrix=function(value){ value.copyTo(this._curMat); } __proto.transformByMatrix=function(value){ SaveTransform.save(this); Matrix.mul(value,this._curMat,this._curMat); this._curMat._checkTransform(); } __proto.rotate=function(angle){ SaveTransform.save(this); this._curMat.rotateEx(angle); } __proto.scale=function(scaleX,scaleY){ SaveTransform.save(this); this._curMat.scaleEx(scaleX,scaleY); } __proto.clipRect=function(x,y,width,height){ if (this._curMat.b !=0 || this._curMat.c !=0){ this._renderKey=0; var submitStencil0=SubmitStencil.create(4); this.addRenderObject(submitStencil0); var vb=this._vb; var nPos=(vb._byteLength >> 2); if (GlUtils.fillRectImgVb(vb,null,x,y,width,height,Texture.DEF_UV,this._curMat,this._x,this._y,0,0)){ var shader=this._shader2D; shader.glTexture=null; var submit=this._curSubmit=Submit.createSubmit(this,this._ib,vb,((vb._byteLength-16 */*laya.webgl.utils.Buffer2D.FLOAT32*/4)/ 32)*3,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.COLOR2D*/0x02,0)); submit.shaderValue.ALPHA=1.0; this._submits[this._submits._length++]=submit; this._curSubmit._numEle+=6; }else { alert("clipRect calc stencil rect error"); }; var submitStencil1=SubmitStencil.create(5); this.addRenderObject(submitStencil1); var vbdata=vb.getFloat32Array(); var minx=Math.min(Math.min(Math.min(vbdata[nPos+0],vbdata[nPos+4]),vbdata[nPos+8]),vbdata[nPos+12]); var maxx=Math.max(Math.max(Math.max(vbdata[nPos+0],vbdata[nPos+4]),vbdata[nPos+8]),vbdata[nPos+12]); var miny=Math.min(Math.min(Math.min(vbdata[nPos+1],vbdata[nPos+5]),vbdata[nPos+9]),vbdata[nPos+13]); var maxy=Math.max(Math.max(Math.max(vbdata[nPos+1],vbdata[nPos+5]),vbdata[nPos+9]),vbdata[nPos+13]); SaveClipRectStencil.save(this,submitStencil1,x,y,width,height,minx,miny,maxx-minx,maxy-miny); this._curSubmit=Submit.RENDERBASE; }else { width *=this._curMat.a; height *=this._curMat.d; var p=Point.TEMP; this._curMat.transformPoint(p.setTo(x,y)); if (width < 0){ p.x=p.x+width; width=-width; } if (height < 0){ p.y=p.y+height; height=-height; } this._renderKey=0; var submitSc=this._curSubmit=SubmitScissor.create(this); this._submits[this._submits._length++]=submitSc; submitSc.submitIndex=this._submits._length; submitSc.submitLength=9999999; SaveClipRect.save(this,submitSc); var clip=this._clipRect; var x1=clip.x,y1=clip.y; var r=p.x+width,b=p.y+height; x1 < p.x && (clip.x=p.x); y1 < p.y && (clip.y=p.y); clip.width=Math.min(r,x1+clip.width)-clip.x; clip.height=Math.min(b,y1+clip.height)-clip.y; this._shader2D.glTexture=null; submitSc.clipRect.copyFrom(clip); this._curSubmit=Submit.RENDERBASE; } } __proto.setIBVB=function(x,y,ib,vb,numElement,mat,shader,shaderValues,startIndex,offset,type){ (startIndex===void 0)&& (startIndex=0); (offset===void 0)&& (offset=0); (type===void 0)&& (type=0); if (ib===null){ if (!Render.isFlash){ ib=this._ib; }else { var falshVB=vb; (falshVB._selfIB)|| (falshVB._selfIB=IndexBuffer2D.create(/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4)); falshVB._selfIB.clear(); ib=falshVB._selfIB; } GlUtils.expandIBQuadrangle(ib,(vb._byteLength / (/*laya.webgl.utils.Buffer2D.FLOAT32*/4 *vb.vertexStride *4))); } if (!shaderValues || !shader) throw Error("setIBVB must input:shader shaderValues"); var submit=SubmitOtherIBVB.create(this,vb,ib,numElement,shader,shaderValues,startIndex,offset,type); mat || (mat=Matrix.EMPTY); mat.translate(x,y); Matrix.mul(mat,this._curMat,submit._mat); mat.translate(-x,-y); this._submits[this._submits._length++]=submit; this._curSubmit=Submit.RENDERBASE; this._renderKey=0; } __proto.addRenderObject=function(o){ this._submits[this._submits._length++]=o; } __proto.fillTrangles=function(tex,x,y,points,m){ var submit=this._curSubmit; var vb=this._vb; var shader=this._shader2D; var curShader=submit.shaderValue; var length=points.length >> 4; var t_tex=tex.bitmap; this._renderKey=0; if (shader.glTexture !=t_tex || shader.ALPHA!==curShader.ALPHA){ submit=this._curSubmit=Submit.createSubmit(this,this._ib,vb,((vb._byteLength)/ 32)*3,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0)); submit.shaderValue.textureHost=tex; this._submits[this._submits._length++]=submit; } GlUtils.fillTranglesVB(vb,x,y,points,m || this._curMat,this._x,this._y); submit._numEle+=length *6; } __proto.submitElement=function(start,end){ var renderList=this._submits; end < 0 && (end=renderList._length); while (start < end){ start+=renderList[start].renderSubmit(); } } __proto.finish=function(){ WebGL.mainContext.finish(); } __proto.flush=function(){ var maxNum=Math.max(this._vb._byteLength / (/*laya.webgl.utils.Buffer2D.FLOAT32*/4 *16),this._maxNumEle / 6)+8; if (maxNum > (this._ib.bufferLength / (6 */*laya.webgl.utils.Buffer2D.SHORT*/2))){ GlUtils.expandIBQuadrangle(this._ib,maxNum); } if (!this._isMain && AtlasResourceManager.enabled && AtlasResourceManager._atlasRestore > this._atlasResourceChange){ this._atlasResourceChange=AtlasResourceManager._atlasRestore; var renderList=this._submits; for (var i=0,s=renderList._length;i < s;i++){ var submit=renderList [i]; if (submit.getRenderType()===/*laya.webgl.submit.Submit.TYPE_TEXTURE*/10016) (submit).checkTexture(); } } this.submitElement(0,this._submits._length); this._path && this._path.reset(); SkinMeshBuffer.instance && SkinMeshBuffer.getInstance().reset(); var sz=0; for (i=0,sz=this.meshlist.length;i < sz;i++){ var curm=this.meshlist[i]; curm.canReuse?(curm.releaseMesh()):(curm.destroy()); } this.meshlist.length=0; this._curSubmit=Submit.RENDERBASE; this._renderKey=0; this._triangleMesh=MeshTexture.getAMesh(); this.meshlist.push(this._triangleMesh); return this._submits._length; } __proto.setPathId=function(id){ this.mId=id; if (this.mId !=-1){ this.mHaveKey=false; var tVGM=VectorGraphManager.getInstance(); if (tVGM.shapeDic[this.mId]){ this.mHaveKey=true; } this.mHaveLineKey=false; if (tVGM.shapeLineDic[this.mId]){ this.mHaveLineKey=true; } } } __proto.movePath=function(x,y){ var _x1=x,_y1=y; x=this._curMat.a *_x1+this._curMat.c *_y1+this._curMat.tx; y=this._curMat.b *_x1+this._curMat.d *_y1+this._curMat.ty; this.mX+=x; this.mY+=y; } __proto.beginPath=function(){ var tPath=this._getPath(); tPath.tempArray.length=0; tPath.closePath=false; this.mX=0; this.mY=0; } __proto.closePath=function(){ this._path.closePath=true; } __proto.fill=function(isConvexPolygon){ (isConvexPolygon===void 0)&& (isConvexPolygon=false); var tPath=this._getPath(); this.drawPoly(0,0,tPath.tempArray,this.fillStyle._color.numColor,0,0,isConvexPolygon); } __proto.stroke=function(){ var tPath=this._getPath(); if (this.lineWidth > 0){ if (this.mId==-1){ tPath.drawLine(0,0,tPath.tempArray,this.lineWidth,this.strokeStyle._color.numColor); }else { if (this.mHaveLineKey){ var tShapeLine=VectorGraphManager.getInstance().shapeLineDic[this.mId]; tShapeLine.rebuild(tPath.tempArray); tPath.setGeomtry(tShapeLine); }else { VectorGraphManager.getInstance().addLine(this.mId,tPath.drawLine(0,0,tPath.tempArray,this.lineWidth,this.strokeStyle._color.numColor)); } } tPath.update(); var tPosArray=[this.mX,this.mY]; var tempSubmit=Submit.createShape(this,tPath.ib,tPath.vb,tPath.count,tPath.offset,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.PRIMITIVE*/0x04,0)); tempSubmit.shaderValue.ALPHA=this._shader2D.ALPHA; (tempSubmit.shaderValue).u_pos=tPosArray; tempSubmit.shaderValue.u_mmat2=RenderState2D.TEMPMAT4_ARRAY; this._submits[this._submits._length++]=tempSubmit; this._renderKey=-1; } } __proto.line=function(fromX,fromY,toX,toY,lineWidth,mat){ var submit=this._curSubmit; var vb=this._vb; if (GlUtils.fillLineVb(vb,this._clipRect,fromX,fromY,toX,toY,lineWidth,mat)){ this._renderKey=0; var shader=this._shader2D; var curShader=submit.shaderValue; if (shader.strokeStyle!==curShader.strokeStyle || shader.ALPHA!==curShader.ALPHA){ shader.glTexture=null; submit=this._curSubmit=Submit.createSubmit(this,this._ib,vb,((vb._byteLength-16 */*laya.webgl.utils.Buffer2D.FLOAT32*/4)/ 32)*3,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.COLOR2D*/0x02,0)); submit.shaderValue.strokeStyle=shader.strokeStyle; submit.shaderValue.mainID=/*laya.webgl.shader.d2.ShaderDefines2D.COLOR2D*/0x02; submit.shaderValue.ALPHA=shader.ALPHA; this._submits[this._submits._length++]=submit; } submit._numEle+=6; } } __proto.moveTo=function(x,y,b){ (b===void 0)&& (b=true); var tPath=this._getPath(); if (b){ var _x1=x,_y1=y; x=this._curMat.a *_x1+this._curMat.c *_y1; y=this._curMat.b *_x1+this._curMat.d *_y1; } tPath.addPoint(x,y); } __proto.lineTo=function(x,y,b){ (b===void 0)&& (b=true); var tPath=this._getPath(); if (b){ var _x1=x,_y1=y; x=this._curMat.a *_x1+this._curMat.c *_y1; y=this._curMat.b *_x1+this._curMat.d *_y1; } tPath.addPoint(x,y); } __proto.drawCurves=function(x,y,args){ this.setPathId(-1); this.beginPath(); this.strokeStyle=args[3]; this.lineWidth=args[4]; var points=args[2]; x+=args[0],y+=args[1]; this.movePath(x,y); this.moveTo(points[0],points[1]); var i=2,n=points.length; while (i < n){ this.quadraticCurveTo(points[i++],points[i++],points[i++],points[i++]); } this.stroke(); } __proto.arcTo=function(x1,y1,x2,y2,r){ if (this.mId !=-1){ if (this.mHaveKey){ return; } }; var i=0; var x=0,y=0; var tPath=this._getPath(); this._curMat.copyTo(WebGLContext2D._tmpMatrix); WebGLContext2D._tmpMatrix.tx=WebGLContext2D._tmpMatrix.ty=0; WebGLContext2D._tempPoint.setTo(tPath.getEndPointX(),tPath.getEndPointY()); WebGLContext2D._tmpMatrix.invertTransformPoint(WebGLContext2D._tempPoint); var dx=WebGLContext2D._tempPoint.x-x1; var dy=WebGLContext2D._tempPoint.y-y1; var len1=Math.sqrt(dx*dx+dy*dy); if (len1 <=0.000001){ return; }; var ndx=dx / len1; var ndy=dy / len1; var dx2=x2-x1; var dy2=y2-y1; var len22=dx2*dx2+dy2*dy2; var len2=Math.sqrt(len22); if (len2 <=0.000001){ return; }; var ndx2=dx2 / len2; var ndy2=dy2 / len2; var odx=ndx+ndx2; var ody=ndy+ndy2; var olen=Math.sqrt(odx*odx+ody*ody); if (olen <=0.000001){ return; }; var nOdx=odx / olen; var nOdy=ody / olen; var alpha=Math.acos(nOdx*ndx+nOdy*ndy); var halfAng=Math.PI / 2-alpha; len1=r / Math.tan(halfAng); var ptx1=len1*ndx+x1; var pty1=len1*ndy+y1; var orilen=Math.sqrt(len1*len1+r*r); var orix=x1+nOdx*orilen; var oriy=y1+nOdy*orilen; var ptx2=len1*ndx2+x1; var pty2=len1*ndy2+y1; var dir=ndx *ndy2-ndy *ndx2; var fChgAng=0; var sinx=0.0; var cosx=0.0; if (dir >=0){ fChgAng=halfAng *2; var fda=fChgAng / WebGLContext2D.SEGNUM; sinx=Math.sin(fda); cosx=Math.cos(fda); } else { fChgAng=-halfAng *2; fda=fChgAng / WebGLContext2D.SEGNUM; sinx=Math.sin(fda); cosx=Math.cos(fda); } x=this._curMat.a *ptx1+this._curMat.c *pty1; y=this._curMat.b *ptx1+this._curMat.d *pty1; if (x !=this._path.getEndPointX()|| y !=this._path.getEndPointY()){ tPath.addPoint(x,y); }; var cvx=ptx1-orix; var cvy=pty1-oriy; var tx=0.0; var ty=0.0; for (i=0;i < WebGLContext2D.SEGNUM;i++){ var cx=cvx*cosx+cvy*sinx; var cy=-cvx*sinx+cvy*cosx; x=cx+orix; y=cy+oriy; x1=this._curMat.a *x+this._curMat.c *y; y1=this._curMat.b *x+this._curMat.d *y; x=x1; y=y1; if (x !=this._path.getEndPointX()|| y !=this._path.getEndPointY()){ tPath.addPoint(x,y); } cvx=cx; cvy=cy; } } __proto.arc=function(cx,cy,r,startAngle,endAngle,counterclockwise,b){ (counterclockwise===void 0)&& (counterclockwise=false); (b===void 0)&& (b=true); if (this.mId !=-1){ var tShape=VectorGraphManager.getInstance().shapeDic[this.mId]; if (tShape){ if (this.mHaveKey && !tShape.needUpdate(this._curMat)) return; } cx=0; cy=0; }; var a=0,da=0,hda=0,kappa=0; var dx=0,dy=0,x=0,y=0,tanx=0,tany=0; var px=0,py=0,ptanx=0,ptany=0; var i=0,ndivs=0,nvals=0; da=endAngle-startAngle; if (!counterclockwise){ if (Math.abs(da)>=Math.PI *2){ da=Math.PI *2; }else { while (da < 0.0){ da+=Math.PI *2; } } }else { if (Math.abs(da)>=Math.PI *2){ da=-Math.PI *2; }else { while (da > 0.0){ da-=Math.PI *2; } } } if (r < 101){ ndivs=Math.max(10,da *r / 5); }else if (r < 201){ ndivs=Math.max(10,da *r / 20); }else { ndivs=Math.max(10,da *r / 40); } hda=(da / ndivs)/ 2.0; kappa=Math.abs(4 / 3 *(1-Math.cos(hda))/ Math.sin(hda)); if (counterclockwise) kappa=-kappa; nvals=0; var tPath=this._getPath(); var _x1=NaN,_y1=NaN; for (i=0;i <=ndivs;i++){ a=startAngle+da *(i / ndivs); dx=Math.cos(a); dy=Math.sin(a); x=cx+dx *r; y=cy+dy *r; if (b){ _x1=x,_y1=y; x=this._curMat.a *_x1+this._curMat.c *_y1; y=this._curMat.b *_x1+this._curMat.d *_y1; } if (x !=this._path.getEndPointX()|| y !=this._path.getEndPointY()){ tPath.addPoint(x,y); } } dx=Math.cos(endAngle); dy=Math.sin(endAngle); x=cx+dx *r; y=cy+dy *r; if (b){ _x1=x,_y1=y; x=this._curMat.a *_x1+this._curMat.c *_y1; y=this._curMat.b *_x1+this._curMat.d *_y1; } if (x !=this._path.getEndPointX()|| y !=this._path.getEndPointY()){ tPath.addPoint(x,y); } } __proto.quadraticCurveTo=function(cpx,cpy,x,y){ var tBezier=Bezier.I; var tResultArray=[]; var _x1=x,_y1=y; x=this._curMat.a *_x1+this._curMat.c *_y1; y=this._curMat.b *_x1+this._curMat.d *_y1; _x1=cpx,_y1=cpy; cpx=this._curMat.a *_x1+this._curMat.c *_y1; cpy=this._curMat.b *_x1+this._curMat.d *_y1; var tArray=tBezier.getBezierPoints([this._path.getEndPointX(),this._path.getEndPointY(),cpx,cpy,x,y],30,2); for (var i=0,n=tArray.length / 2;i < n;i++){ this.lineTo(tArray[i *2],tArray[i *2+1],false); } this.lineTo(x,y,false); } __proto.rect=function(x,y,width,height){ this._other=this._other.make(); this._other.path || (this._other.path=new Path()); this._other.path.rect(x,y,width,height); } __proto.strokeRect=function(x,y,width,height,parameterLineWidth){ var tW=parameterLineWidth *0.5; this.line(x-tW,y,x+width+tW,y,parameterLineWidth,this._curMat); this.line(x+width,y,x+width,y+height,parameterLineWidth,this._curMat); this.line(x,y,x,y+height,parameterLineWidth,this._curMat); this.line(x-tW,y+height,x+width+tW,y+height,parameterLineWidth,this._curMat); } __proto.clip=function(){} /** *画多边形(用) *@param x *@param y *@param points */ __proto.drawPoly=function(x,y,points,color,lineWidth,boderColor,isConvexPolygon){ (isConvexPolygon===void 0)&& (isConvexPolygon=false); this._renderKey=0; this._shader2D.glTexture=null; var tPath=this._getPath(); if (this.mId==-1){ tPath.polygon(x,y,points,color,lineWidth ? lineWidth :1,boderColor) }else { if (this.mHaveKey){ var tShape=VectorGraphManager.getInstance().shapeDic[this.mId]; tShape.setMatrix(this._curMat); tShape.rebuild(tPath.tempArray); tPath.setGeomtry(tShape); }else { var t=tPath.polygon(x,y,points,color,lineWidth ? lineWidth :1,boderColor); VectorGraphManager.getInstance().addShape(this.mId,t); t.setMatrix(this._curMat); } } tPath.update(); var tPosArray=[this.mX,this.mY]; var tempSubmit; tempSubmit=Submit.createShape(this,tPath.ib,tPath.vb,tPath.count,tPath.offset,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.PRIMITIVE*/0x04,0)); tempSubmit.shaderValue.ALPHA=this._shader2D.ALPHA; (tempSubmit.shaderValue).u_pos=tPosArray; tempSubmit.shaderValue.u_mmat2=RenderState2D.EMPTYMAT4_ARRAY; this._submits[this._submits._length++]=tempSubmit; if (lineWidth > 0){ if (this.mHaveLineKey){ var tShapeLine=VectorGraphManager.getInstance().shapeLineDic[this.mId]; tShapeLine.rebuild(tPath.tempArray); tPath.setGeomtry(tShapeLine); }else { VectorGraphManager.getInstance().addShape(this.mId,tPath.drawLine(x,y,points,lineWidth,boderColor)); } tPath.update(); tempSubmit=Submit.createShape(this,tPath.ib,tPath.vb,tPath.count,tPath.offset,Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.PRIMITIVE*/0x04,0)); tempSubmit.shaderValue.ALPHA=this._shader2D.ALPHA; tempSubmit.shaderValue.u_mmat2=RenderState2D.EMPTYMAT4_ARRAY; this._submits[this._submits._length++]=tempSubmit; } } /*******************************************end矢量绘制***************************************************/ __proto.drawParticle=function(x,y,pt){ pt.x=x; pt.y=y; this._submits[this._submits._length++]=pt; } __proto._getPath=function(){ return this._path || (this._path=new Path()); } /*,_shader2D.ALPHA=1*/ __getset(0,__proto,'globalCompositeOperation',function(){ return BlendMode.NAMES[this._nBlendType]; },function(value){ var n=BlendMode.TOINT[value]; n==null || (this._nBlendType===n)|| (SaveBase.save(this,/*laya.webgl.canvas.save.SaveBase.TYPE_GLOBALCOMPOSITEOPERATION*/0x10000,this,true),this._curSubmit=Submit.RENDERBASE,this._renderKey=0,this._nBlendType=n); }); __getset(0,__proto,'strokeStyle',function(){ return this._shader2D.strokeStyle; },function(value){ this._shader2D.strokeStyle.equal(value)|| (SaveBase.save(this,/*laya.webgl.canvas.save.SaveBase.TYPE_STROKESTYLE*/0x200,this._shader2D,false),this._shader2D.strokeStyle=DrawStyle.create(value)); }); __getset(0,__proto,'globalAlpha',function(){ return this._shader2D.ALPHA; },function(value){ value=Math.floor(value *1000)/ 1000; if (value !=this._shader2D.ALPHA){ SaveBase.save(this,/*laya.webgl.canvas.save.SaveBase.TYPE_ALPHA*/0x1,this._shader2D,true); this._shader2D.ALPHA=value; } }); __getset(0,__proto,'asBitmap',null,function(value){ if (value){ this._targets || (this._targets=new RenderTargetMAX()); this._targets.repaint=true; if (!this._width || !this._height) throw Error("asBitmap no size!"); this._targets.setSP(this.sprite); this._targets.size(this._width,this._height); }else this._targets=null; }); __getset(0,__proto,'fillStyle',function(){ return this._shader2D.fillStyle; },function(value){ this._shader2D.fillStyle.equal(value)|| (SaveBase.save(this,/*laya.webgl.canvas.save.SaveBase.TYPE_FILESTYLE*/0x2,this._shader2D,false),this._shader2D.fillStyle=DrawStyle.create(value)); }); __getset(0,__proto,'textAlign',function(){ return this._other.textAlign; },function(value){ (this._other.textAlign===value)|| (this._other=this._other.make(),SaveBase.save(this,/*laya.webgl.canvas.save.SaveBase.TYPE_TEXTALIGN*/0x8000,this._other,false),this._other.textAlign=value); }); __getset(0,__proto,'lineWidth',function(){ return this._other.lineWidth; },function(value){ (this._other.lineWidth===value)|| (this._other=this._other.make(),SaveBase.save(this,/*laya.webgl.canvas.save.SaveBase.TYPE_LINEWIDTH*/0x100,this._other,false),this._other.lineWidth=value); }); __getset(0,__proto,'textBaseline',function(){ return this._other.textBaseline; },function(value){ (this._other.textBaseline===value)|| (this._other=this._other.make(),SaveBase.save(this,/*laya.webgl.canvas.save.SaveBase.TYPE_TEXTBASELINE*/0x4000,this._other,false),this._other.textBaseline=value); }); __getset(0,__proto,'font',null,function(str){ if (str==this._other.font.toString()) return; this._other=this._other.make(); SaveBase.save(this,/*laya.webgl.canvas.save.SaveBase.TYPE_FONT*/0x8,this._other,false); this._other.font===FontInContext.EMPTY ? (this._other.font=new FontInContext(str)):(this._other.font.setFont(str)); }); WebGLContext2D.__init__=function(){ ContextParams.DEFAULT=new ContextParams(); } WebGLContext2D._tempPoint=new Point(); WebGLContext2D._SUBMITVBSIZE=32000; WebGLContext2D._MAXSIZE=99999999; WebGLContext2D._RECTVBSIZE=16; WebGLContext2D.MAXCLIPRECT=new Rectangle(0,0,99999999,99999999); WebGLContext2D._COUNT=0; WebGLContext2D._tmpMatrix=new Matrix(); WebGLContext2D.SEGNUM=32; WebGLContext2D._contextcount=0; __static(WebGLContext2D, ['_fontTemp',function(){return this._fontTemp=new FontInContext();},'_drawStyleTemp',function(){return this._drawStyleTemp=new DrawStyle(null);} ]); WebGLContext2D.__init$=function(){ //class ContextParams ContextParams=(function(){ function ContextParams(){ this.lineWidth=1; this.path=null; this.textAlign=null; this.textBaseline=null; this.font=FontInContext.EMPTY; } __class(ContextParams,''); var __proto=ContextParams.prototype; __proto.clear=function(){ this.lineWidth=1; this.path && this.path.clear(); this.textAlign=this.textBaseline=null; this.font=FontInContext.EMPTY; } __proto.make=function(){ return this===ContextParams.DEFAULT ? new ContextParams():this; } ContextParams.DEFAULT=null; return ContextParams; })() } return WebGLContext2D; })(Context) //class laya.webgl.shader.d2.value.Value2D extends laya.webgl.shader.ShaderValue var Value2D=(function(_super){ function Value2D(mainID,subID){ this.size=[0,0]; this.alpha=1.0; //this.mmat=null; this.ALPHA=1.0; //this.shader=null; //this.mainID=0; this.subID=0; //this.filters=null; //this.textureHost=null; //this.texture=null; //this.fillStyle=null; //this.color=null; //this.strokeStyle=null; //this.colorAdd=null; //this.glTexture=null; //this.u_mmat2=null; //this._inClassCache=null; this._cacheID=0; Value2D.__super.call(this); this.defines=new ShaderDefines2D(); this.position=Value2D._POSITION; this.mainID=mainID; this.subID=subID; this.textureHost=null; this.texture=null; this.fillStyle=null; this.color=null; this.strokeStyle=null; this.colorAdd=null; this.glTexture=null; this.u_mmat2=null; this._cacheID=mainID|subID; this._inClassCache=Value2D._cache[this._cacheID]; if (mainID>0 && !this._inClassCache){ this._inClassCache=Value2D._cache[this._cacheID]=[]; this._inClassCache._length=0; } this.clear(); } __class(Value2D,'laya.webgl.shader.d2.value.Value2D',_super); var __proto=Value2D.prototype; __proto.setValue=function(value){} //throw new Error("todo in subclass"); __proto.refresh=function(){ var size=this.size; size[0]=RenderState2D.width; size[1]=RenderState2D.height; this.alpha=this.ALPHA *RenderState2D.worldAlpha; this.mmat=RenderState2D.worldMatrix4; return this; } __proto._ShaderWithCompile=function(){ return Shader.withCompile2D(0,this.mainID,this.defines.toNameDic(),this.mainID | this.defines._value,Shader2X.create); } __proto._withWorldShaderDefines=function(){ var defs=RenderState2D.worldShaderDefines; var sd=Shader.sharders [this.mainID | this.defines._value | defs.getValue()]; if (!sd){ var def={}; var dic; var name; dic=this.defines.toNameDic();for (name in dic)def[name]=""; dic=defs.toNameDic();for (name in dic)def[name]=""; sd=Shader.withCompile2D(0,this.mainID,def,this.mainID | this.defines._value| defs.getValue(),Shader2X.create); }; var worldFilters=RenderState2D.worldFilters; if (!worldFilters)return sd; var n=worldFilters.length,f; for (var i=0;i < n;i++){ ((f=worldFilters[i]))&& f.action.setValue(this); } return sd; } __proto.upload=function(){ var renderstate2d=RenderState2D; this.alpha=this.ALPHA *renderstate2d.worldAlpha; if (RenderState2D.worldMatrix4!==RenderState2D.TEMPMAT4_ARRAY)this.defines.add(/*laya.webgl.shader.d2.ShaderDefines2D.WORLDMAT*/0x80); (WebGL.shaderHighPrecision)&& (this.defines.add(/*laya.webgl.shader.d2.ShaderDefines2D.SHADERDEFINE_FSHIGHPRECISION*/0x400)); var sd=renderstate2d.worldShaderDefines?this._withWorldShaderDefines():(Shader.sharders [this.mainID | this.defines._value] || this._ShaderWithCompile()); var params; this.size[0]=renderstate2d.width,this.size[1]=renderstate2d.height; this.mmat=renderstate2d.worldMatrix4; if (BaseShader.activeShader!==sd){ if (sd._shaderValueWidth!==renderstate2d.width || sd._shaderValueHeight!==renderstate2d.height){ sd._shaderValueWidth=renderstate2d.width; sd._shaderValueHeight=renderstate2d.height; } else{ params=sd._params2dQuick2 || sd._make2dQuick2(); } sd.upload(this,params); } else{ if (sd._shaderValueWidth!==renderstate2d.width || sd._shaderValueHeight!==renderstate2d.height){ sd._shaderValueWidth=renderstate2d.width; sd._shaderValueHeight=renderstate2d.height; } else{ params=(sd._params2dQuick1)|| sd._make2dQuick1(); } sd.upload(this,params); } } __proto.setFilters=function(value){ this.filters=value; if (!value) return; var n=value.length,f; for (var i=0;i < n;i++){ f=value[i]; if (f){ this.defines.add(f.type); f.action.setValue(this); } } } __proto.clear=function(){ this.defines.setValue(this.subID); } __proto.release=function(){ this._inClassCache[this._inClassCache._length++]=this; this.fillStyle=null; this.strokeStyle=null; this.clear(); } Value2D._initone=function(type,classT){ Value2D._typeClass[type]=classT; Value2D._cache[type]=[]; Value2D._cache[type]._length=0; } Value2D.__init__=function(){ Value2D._POSITION=[2,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,4 *CONST3D2D.BYTES_PE,0]; Value2D._TEXCOORD=[2,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,4 *CONST3D2D.BYTES_PE,2 *CONST3D2D.BYTES_PE]; Value2D._initone(/*laya.webgl.shader.d2.ShaderDefines2D.COLOR2D*/0x02,Color2dSV); Value2D._initone(/*laya.webgl.shader.d2.ShaderDefines2D.PRIMITIVE*/0x04,PrimitiveSV); Value2D._initone(/*laya.webgl.shader.d2.ShaderDefines2D.FILLTEXTURE*/0x100,FillTextureSV); Value2D._initone(/*laya.webgl.shader.d2.ShaderDefines2D.SKINMESH*/0x200,SkinSV); Value2D._initone(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,TextureSV); Value2D._initone(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01 | /*laya.webgl.shader.d2.ShaderDefines2D.COLORADD*/0x40,TextSV); Value2D._initone(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01 | /*laya.webgl.shader.d2.ShaderDefines2D.FILTERGLOW*/0x08,TextureSV); } Value2D.create=function(mainType,subType){ var types=Value2D._cache[mainType|subType]; if (types._length) return types[--types._length]; else return new Value2D._typeClass[mainType|subType](subType); } Value2D._POSITION=null; Value2D._TEXCOORD=null; Value2D._cache=[]; Value2D._typeClass=[]; Value2D.TEMPMAT4_ARRAY=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]; return Value2D; })(ShaderValue) //class laya.webgl.utils.RenderSprite3D extends laya.renders.RenderSprite var RenderSprite3D=(function(_super){ function RenderSprite3D(type,next){ RenderSprite3D.__super.call(this,type,next); } __class(RenderSprite3D,'laya.webgl.utils.RenderSprite3D',_super); var __proto=RenderSprite3D.prototype; __proto.onCreate=function(type){ switch (type){ case 0x08: this._fun=this._blend; return; case 0x04: this._fun=this._transform; return; } } __proto._mask=function(sprite,context,x,y){ var next=this._next; var mask=sprite.mask; var submitCMD; var submitStencil; if (mask){ context.ctx.save(); var preBlendMode=(context.ctx).globalCompositeOperation; var tRect=new Rectangle(); tRect.copyFrom(mask.getBounds()); tRect.width=Math.round(tRect.width); tRect.height=Math.round(tRect.height); tRect.x=Math.round(tRect.x); tRect.y=Math.round(tRect.y); if (tRect.width > 0 && tRect.height > 0){ var tf=sprite._style._tf; var scope=SubmitCMDScope.create(); scope.addValue("bounds",tRect); submitCMD=SubmitCMD.create([scope,context],laya.webgl.utils.RenderSprite3D.tmpTarget); context.addRenderObject(submitCMD); mask.render(context,-tRect.x,-tRect.y); submitCMD=SubmitCMD.create([scope],laya.webgl.utils.RenderSprite3D.endTmpTarget); context.addRenderObject(submitCMD); context.ctx.save(); context.clipRect(x-tf.translateX+tRect.x,y-tf.translateY+tRect.y,tRect.width,tRect.height); next._fun.call(next,sprite,context,x,y); context.ctx.restore(); submitStencil=SubmitStencil.create(6); preBlendMode=(context.ctx).globalCompositeOperation; submitStencil.blendMode="mask"; context.addRenderObject(submitStencil); Matrix.TEMP.identity(); var shaderValue=Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0); var uv=Texture.INV_UV; var w=tRect.width; var h=tRect.height; var tempLimit=32; if (tRect.width < tempLimit || tRect.height < tempLimit){ uv=RenderSprite3D.tempUV; uv[0]=0; uv[1]=0; uv[2]=(tRect.width >=32)? 1 :tRect.width/tempLimit; uv[3]=0 uv[4]=(tRect.width >=32)? 1 :tRect.width/tempLimit; uv[5]=(tRect.height >=32)? 1 :tRect.height/tempLimit; uv[6]=0; uv[7]=(tRect.height >=32)? 1 :tRect.height/tempLimit; tRect.width=(tRect.width >=32)? tRect.width :tempLimit; tRect.height=(tRect.height >=32)? tRect.height :tempLimit; uv[1] *=-1;uv[3] *=-1;uv[5] *=-1;uv[7] *=-1; uv[1]+=1;uv[3]+=1;uv[5]+=1;uv[7]+=1; } (context.ctx).drawTarget(scope,x+tRect.x-tf.translateX,y+tRect.y-tf.translateY,w,h,Matrix.TEMP,"tmpTarget",shaderValue,uv,6); submitCMD=SubmitCMD.create([scope],laya.webgl.utils.RenderSprite3D.recycleTarget); context.addRenderObject(submitCMD); submitStencil=SubmitStencil.create(6); submitStencil.blendMode=preBlendMode; context.addRenderObject(submitStencil); } context.ctx.restore(); } else{ next._fun.call(next,sprite,context,x,y); } } __proto._blend=function(sprite,context,x,y){ var style=sprite._style; var next=this._next; if (style.blendMode){ context.ctx.save(); context.ctx.globalCompositeOperation=style.blendMode; next._fun.call(next,sprite,context,x,y); context.ctx.restore(); } else{ next._fun.call(next,sprite,context,x,y); } } __proto._transform=function(sprite,context,x,y){ var transform=sprite.transform,_next=this._next; if (transform && _next !=RenderSprite.NORENDER){ var ctx=context.ctx; var style=sprite._style; transform.tx=x; transform.ty=y; var m2=ctx._getTransformMatrix(); var m1=m2.clone(); Matrix.mul(transform,m2,m2); m2._checkTransform(); transform.tx=transform.ty=0; _next._fun.call(_next,sprite,context,0,0); m1.copyTo(m2); m1.destroy(); }else { _next._fun.call(_next,sprite,context,x,y); } } RenderSprite3D.tmpTarget=function(scope,context){ var b=scope.getValue("bounds"); var tmpTarget=RenderTarget2D.create(b.width,b.height); tmpTarget.start(); tmpTarget.clear(0,0,0,0); scope.addValue("tmpTarget",tmpTarget); } RenderSprite3D.endTmpTarget=function(scope){ var tmpTarget=scope.getValue("tmpTarget"); tmpTarget.end(); } RenderSprite3D.recycleTarget=function(scope){ var tmpTarget=scope.getValue("tmpTarget"); tmpTarget.recycle(); scope.recycle(); } __static(RenderSprite3D, ['tempUV',function(){return this.tempUV=new Array(8);} ]); return RenderSprite3D; })(RenderSprite) //class laya.filters.webgl.ColorFilterActionGL extends laya.filters.webgl.FilterActionGL var ColorFilterActionGL=(function(_super){ function ColorFilterActionGL(){ this.data=null; ColorFilterActionGL.__super.call(this); } __class(ColorFilterActionGL,'laya.filters.webgl.ColorFilterActionGL',_super); var __proto=ColorFilterActionGL.prototype; Laya.imps(__proto,{"laya.filters.IFilterActionGL":true}) __proto.setValue=function(shader){ shader.colorMat=this.data._mat; shader.colorAlpha=this.data._alpha; } __proto.apply3d=function(scope,sprite,context,x,y){ var b=scope.getValue("bounds"); var shaderValue=Value2D.create(/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,0); shaderValue.setFilters([this.data]); var tMatrix=Matrix.TEMP; tMatrix.identity(); context.ctx.drawTarget(scope,0,0,b.width,b.height,tMatrix,"src",shaderValue); } return ColorFilterActionGL; })(FilterActionGL) //class laya.webgl.atlas.Atlaser extends laya.webgl.atlas.AtlasGrid var Atlaser=(function(_super){ function Atlaser(gridNumX,gridNumY,width,height,atlasID){ this._atlasCanvas=null; this._inAtlasTextureKey=null; this._inAtlasTextureBitmapValue=null; this._inAtlasTextureOriUVValue=null; this._InAtlasWebGLImagesKey=null; this._InAtlasWebGLImagesOffsetValue=null; Atlaser.__super.call(this,gridNumX,gridNumY,atlasID); this._inAtlasTextureKey=[]; this._inAtlasTextureBitmapValue=[]; this._inAtlasTextureOriUVValue=[]; this._InAtlasWebGLImagesKey={}; this._InAtlasWebGLImagesOffsetValue=[]; this._atlasCanvas=new AtlasWebGLCanvas(); this._atlasCanvas._atlaser=this; this._atlasCanvas.width=width; this._atlasCanvas.height=height; this._atlasCanvas.activeResource(); this._atlasCanvas.lock=true; } __class(Atlaser,'laya.webgl.atlas.Atlaser',_super); var __proto=Atlaser.prototype; __proto.computeUVinAtlasTexture=function(texture,oriUV,offsetX,offsetY){ var tex=texture; var _width=AtlasResourceManager.atlasTextureWidth; var _height=AtlasResourceManager.atlasTextureHeight; var u1=offsetX / _width,v1=offsetY / _height,u2=(offsetX+texture.bitmap.width)/ _width,v2=(offsetY+texture.bitmap.height)/ _height; var inAltasUVWidth=texture.bitmap.width / _width,inAltasUVHeight=texture.bitmap.height / _height; texture.uv=[u1+oriUV[0] *inAltasUVWidth,v1+oriUV[1] *inAltasUVHeight,u2-(1-oriUV[2])*inAltasUVWidth,v1+oriUV[3] *inAltasUVHeight,u2-(1-oriUV[4])*inAltasUVWidth,v2-(1-oriUV[5])*inAltasUVHeight,u1+oriUV[6] *inAltasUVWidth,v2-(1-oriUV[7])*inAltasUVHeight]; } __proto.findBitmapIsExist=function(bitmap){ if ((bitmap instanceof laya.webgl.resource.WebGLImage )){ var webImage=bitmap; var sUrl=webImage.url; var object=this._InAtlasWebGLImagesKey[sUrl?sUrl:webImage.id] if (object){ return object.offsetInfoID; } } return-1; } /** * *@param inAtlasRes *@return 是否已经存在队列中 */ __proto.addToAtlasTexture=function(mergeAtlasBitmap,offsetX,offsetY){ if ((mergeAtlasBitmap instanceof laya.webgl.resource.WebGLImage )){ var webImage=mergeAtlasBitmap; var sUrl=webImage.url; this._InAtlasWebGLImagesKey[sUrl?sUrl:webImage.id]={bitmap:mergeAtlasBitmap,offsetInfoID:this._InAtlasWebGLImagesOffsetValue.length}; this._InAtlasWebGLImagesOffsetValue.push([offsetX,offsetY]); } this._atlasCanvas.texSubImage2D(offsetX,offsetY,/*__JS__ */mergeAtlasBitmap.atlasImgData || mergeAtlasBitmap.atlasSource); mergeAtlasBitmap.clearAtlasSource(); } __proto.addToAtlas=function(texture,offsetX,offsetY){ texture._atlasID=this._inAtlasTextureKey.length; var oriUV=texture.uv.slice(); var oriBitmap=texture.bitmap; this._inAtlasTextureKey.push(texture); this._inAtlasTextureOriUVValue.push(oriUV); this._inAtlasTextureBitmapValue.push(oriBitmap); this.computeUVinAtlasTexture(texture,oriUV,offsetX,offsetY); texture.bitmap=this._atlasCanvas; } __proto.clear=function(){ for (var i=0,n=this._inAtlasTextureKey.length;i < n;i++){ this._inAtlasTextureKey[i].bitmap=this._inAtlasTextureBitmapValue[i]; this._inAtlasTextureKey[i].uv=this._inAtlasTextureOriUVValue[i]; this._inAtlasTextureKey[i]._atlasID=-1; this._inAtlasTextureKey[i].bitmap.lock=false; this._inAtlasTextureKey[i].bitmap.releaseResource(); } this._inAtlasTextureKey.length=0; this._inAtlasTextureBitmapValue.length=0; this._inAtlasTextureOriUVValue.length=0; this._InAtlasWebGLImagesKey=null; this._InAtlasWebGLImagesOffsetValue.length=0; } __proto.dispose=function(){ this.clear(); this._atlasCanvas.destroy(); } __getset(0,__proto,'InAtlasWebGLImagesOffsetValue',function(){ return this._InAtlasWebGLImagesOffsetValue; }); __getset(0,__proto,'texture',function(){ return this._atlasCanvas; }); __getset(0,__proto,'inAtlasWebGLImagesKey',function(){ return this._InAtlasWebGLImagesKey; }); return Atlaser; })(AtlasGrid) //class laya.webgl.shader.d2.ShaderDefines2D extends laya.webgl.shader.ShaderDefines var ShaderDefines2D=(function(_super){ function ShaderDefines2D(){ ShaderDefines2D.__super.call(this,ShaderDefines2D.__name2int,ShaderDefines2D.__int2name,ShaderDefines2D.__int2nameMap); } __class(ShaderDefines2D,'laya.webgl.shader.d2.ShaderDefines2D',_super); ShaderDefines2D.__init__=function(){ ShaderDefines2D.reg("TEXTURE2D",0x01); ShaderDefines2D.reg("COLOR2D",0x02); ShaderDefines2D.reg("PRIMITIVE",0x04); ShaderDefines2D.reg("GLOW_FILTER",0x08); ShaderDefines2D.reg("BLUR_FILTER",0x10); ShaderDefines2D.reg("COLOR_FILTER",0x20); ShaderDefines2D.reg("COLOR_ADD",0x40); ShaderDefines2D.reg("WORLDMAT",0x80); ShaderDefines2D.reg("FILLTEXTURE",0x100); ShaderDefines2D.reg("FSHIGHPRECISION",0x400); } ShaderDefines2D.reg=function(name,value){ ShaderDefines._reg(name,value,ShaderDefines2D.__name2int,ShaderDefines2D.__int2name); } ShaderDefines2D.toText=function(value,int2name,int2nameMap){ return ShaderDefines._toText(value,int2name,int2nameMap); } ShaderDefines2D.toInt=function(names){ return ShaderDefines._toInt(names,ShaderDefines2D.__name2int); } ShaderDefines2D.TEXTURE2D=0x01; ShaderDefines2D.COLOR2D=0x02; ShaderDefines2D.PRIMITIVE=0x04; ShaderDefines2D.FILTERGLOW=0x08; ShaderDefines2D.FILTERBLUR=0x10; ShaderDefines2D.FILTERCOLOR=0x20; ShaderDefines2D.COLORADD=0x40; ShaderDefines2D.WORLDMAT=0x80; ShaderDefines2D.FILLTEXTURE=0x100; ShaderDefines2D.SKINMESH=0x200; ShaderDefines2D.SHADERDEFINE_FSHIGHPRECISION=0x400; ShaderDefines2D.__name2int={}; ShaderDefines2D.__int2name=[]; ShaderDefines2D.__int2nameMap=[]; return ShaderDefines2D; })(ShaderDefines) //class laya.webgl.shapes.Ellipse extends laya.webgl.shapes.BasePoly var Ellipse=(function(_super){ function Ellipse(x,y,width,height,color,borderWidth,borderColor){ Ellipse.__super.call(this,x,y,width,height,40,color,borderWidth,borderColor); } __class(Ellipse,'laya.webgl.shapes.Ellipse',_super); return Ellipse; })(BasePoly) //class laya.webgl.shapes.Line extends laya.webgl.shapes.BasePoly var Line=(function(_super){ function Line(x,y,points,borderWidth,color){ this._points=[]; this.rebuild(points); Line.__super.call(this,x,y,0,0,0,color,borderWidth,color,0); } __class(Line,'laya.webgl.shapes.Line',_super); var __proto=Line.prototype; __proto.rebuild=function(points){ var len=points.length; var preLen=this._points.length; if (len !=preLen){ this.mUint16Array=new Uint16Array((len/2-1)*6); this.mFloat32Array=new Float32Array(len*5); } this._points.length=0; var tCurrX=NaN; var tCurrY=NaN; var tLastX=-1; var tLastY=-1; var tLen=points.length / 2; for (var i=0;i < tLen;i++){ tCurrX=points[i *2]; tCurrY=points[i *2+1]; if (Math.abs(tLastX-tCurrX)> 0.01 || Math.abs(tLastY-tCurrY)>0.01){ this._points.push(tCurrX,tCurrY); } tLastX=tCurrX; tLastY=tCurrY; } } __proto.getData=function(ib,vb,start){ var indices=[]; var verts=[]; (this.borderWidth > 0)&& this.createLine2(this._points,indices,this.borderWidth,start,verts,this._points.length / 2); this.mUint16Array.set(indices,0); this.mFloat32Array.set(verts,0); ib.append(this.mUint16Array); vb.append(this.mFloat32Array); } return Line; })(BasePoly) //class laya.webgl.shapes.LoopLine extends laya.webgl.shapes.BasePoly var LoopLine=(function(_super){ function LoopLine(x,y,points,width,color){ this._points=[]; var tCurrX=NaN; var tCurrY=NaN; var tLastX=-1; var tLastY=-1; var tLen=points.length / 2-1; for (var i=0;i < tLen;i++){ tCurrX=points[i *2]; tCurrY=points[i *2+1]; if (Math.abs(tLastX-tCurrX)> 0.01 || Math.abs(tLastY-tCurrY)> 0.01){ this._points.push(tCurrX,tCurrY); } tLastX=tCurrX; tLastY=tCurrY; } tCurrX=points[tLen *2]; tCurrY=points[tLen *2+1]; tLastX=this._points[0]; tLastY=this._points[1]; if (Math.abs(tLastX-tCurrX)> 0.01 || Math.abs(tLastY-tCurrY)> 0.01){ this._points.push(tCurrX,tCurrY); } LoopLine.__super.call(this,x,y,0,0,this._points.length / 2,0,width,color); } __class(LoopLine,'laya.webgl.shapes.LoopLine',_super); var __proto=LoopLine.prototype; __proto.getData=function(ib,vb,start){ if (this.borderWidth > 0){ var color=this.color; var r=((color >> 16)& 0x0000ff)/ 255,g=((color >> 8)& 0xff)/ 255,b=(color & 0x0000ff)/ 255; var verts=[]; var tLastX=-1,tLastY=-1; var tCurrX=0,tCurrY=0; var indices=[]; var tLen=Math.floor(this._points.length / 2); for (var i=0;i < tLen;i++){ tCurrX=this._points[i *2]; tCurrY=this._points[i *2+1]; verts.push(this.x+tCurrX,this.y+tCurrY,r,g,b); } this.createLoopLine(verts,indices,this.borderWidth,start+verts.length / 5); ib.append(new Uint16Array(indices)); vb.append(new Float32Array(verts)); } } __proto.createLoopLine=function(p,indices,lineWidth,len,outVertex,outIndex){ var tLen=p.length / 5; var points=p.concat(); var result=outVertex ? outVertex :p; var color=this.borderColor; var r=((color >> 16)& 0x0000ff)/ 255,g=((color >> 8)& 0xff)/ 255,b=(color & 0x0000ff)/ 255; var firstPoint=[points[0],points[1]]; var lastPoint=[points[points.length-5],points[points.length-4]]; var midPointX=lastPoint[0]+(firstPoint[0]-lastPoint[0])*0.5; var midPointY=lastPoint[1]+(firstPoint[1]-lastPoint[1])*0.5; points.unshift(midPointX,midPointY,0,0,0); points.push(midPointX,midPointY,0,0,0); var length=points.length / 5; var iStart=len,w=lineWidth / 2; var px,py,p1x,p1y,p2x,p2y,p3x,p3y; var perpx,perpy,perp2x,perp2y,perp3x,perp3y; var a1,b1,c1,a2,b2,c2; var denom,pdist,dist; p1x=points[0]; p1y=points[1]; p2x=points[5]; p2y=points[6]; perpx=-(p1y-p2y); perpy=p1x-p2x; dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx=perpx / dist *w; perpy=perpy / dist *w; result.push(p1x-perpx,p1y-perpy,r,g,b,p1x+perpx,p1y+perpy,r,g,b); for (var i=1;i < length-1;i++){ p1x=points[(i-1)*5]; p1y=points[(i-1)*5+1]; p2x=points[(i)*5]; p2y=points[(i)*5+1]; p3x=points[(i+1)*5]; p3y=points[(i+1)*5+1]; perpx=-(p1y-p2y); perpy=p1x-p2x; dist=Math.sqrt(perpx *perpx+perpy *perpy); perpx=perpx / dist *w; perpy=perpy / dist *w; perp2x=-(p2y-p3y); perp2y=p2x-p3x; dist=Math.sqrt(perp2x *perp2x+perp2y *perp2y); perp2x=perp2x / dist *w; perp2y=perp2y / dist *w; a1=(-perpy+p1y)-(-perpy+p2y); b1=(-perpx+p2x)-(-perpx+p1x); c1=(-perpx+p1x)*(-perpy+p2y)-(-perpx+p2x)*(-perpy+p1y); a2=(-perp2y+p3y)-(-perp2y+p2y); b2=(-perp2x+p2x)-(-perp2x+p3x); c2=(-perp2x+p3x)*(-perp2y+p2y)-(-perp2x+p2x)*(-perp2y+p3y); denom=a1 *b2-a2 *b1; if (Math.abs(denom)< 0.1){ denom+=10.1; result.push(p2x-perpx,p2y-perpy,r,g,b,p2x+perpx,p2y+perpy,r,g,b); continue ; } px=(b1 *c2-b2 *c1)/ denom; py=(a2 *c1-a1 *c2)/ denom; pdist=(px-p2x)*(px-p2x)+(py-p2y)+(py-p2y); result.push(px,py,r,g,b,p2x-(px-p2x),p2y-(py-p2y),r,g,b); } if (outIndex){ indices=outIndex; }; var groupLen=this.edges+1; for (i=1;i < groupLen;i++){ indices.push(iStart+(i-1)*2,iStart+(i-1)*2+1,iStart+i *2+1,iStart+i *2+1,iStart+i *2,iStart+(i-1)*2); } indices.push(iStart+(i-1)*2,iStart+(i-1)*2+1,iStart+1,iStart+1,iStart,iStart+(i-1)*2); return result; } return LoopLine; })(BasePoly) //class laya.webgl.shapes.Polygon extends laya.webgl.shapes.BasePoly var Polygon=(function(_super){ function Polygon(x,y,points,color,borderWidth,borderColor){ this._points=null; this._start=-1; this._repaint=false; this.earcutTriangles=null; this._mat=Matrix.create(); this._points=points.slice(0,points.length); Polygon.__super.call(this,x,y,0,0,this._points.length / 2,color,borderWidth,borderColor); } __class(Polygon,'laya.webgl.shapes.Polygon',_super); var __proto=Polygon.prototype; __proto.rebuild=function(point){ if (!this._repaint){ this._points.length=0; this._points=this._points.concat(point); } } __proto.setMatrix=function(mat){ mat.copyTo(this._mat); } __proto.needUpdate=function(mat){ this._repaint=(this._mat.a==mat.a && this._mat.b==mat.b && this._mat.c==mat.c && this._mat.d==mat.d && this._mat.tx==mat.tx && this._mat.ty==mat.ty); return !this._repaint; } __proto.getData=function(ib,vb,start){ var indices,i=0; var tArray=this._points; var tLen=0; if (this.mUint16Array && this.mFloat32Array&&this._repaint){ if (this._start !=start){ this._start=start; indices=[]; tLen=this.earcutTriangles.length; for (i=0;i < tLen;i++){ indices.push(this.earcutTriangles[i]+start); } this.mUint16Array=new Uint16Array(indices); } } else { this._start=start; indices=[]; var verts=[]; var vertsEarcut=[]; var color=this.color; var r=((color >> 16)& 0x0000ff)/ 255,g=((color >> 8)& 0xff)/ 255,b=(color & 0x0000ff)/ 255; tLen=Math.floor(tArray.length / 2); for (i=0;i < tLen;i++){ verts.push(this.x+tArray[i *2],this.y+tArray[i *2+1],r,g,b); vertsEarcut.push(this.x+tArray[i *2],this.y+tArray[i *2+1]); } this.earcutTriangles=Earcut.earcut(vertsEarcut,null,2); tLen=this.earcutTriangles.length; for (i=0;i < tLen;i++){ indices.push(this.earcutTriangles[i]+start); } this.mUint16Array=new Uint16Array(indices); this.mFloat32Array=new Float32Array(verts); } ib.append(this.mUint16Array); vb.append(this.mFloat32Array); } return Polygon; })(BasePoly) //class laya.webgl.submit.SubmitCanvas extends laya.webgl.submit.Submit var SubmitCanvas=(function(_super){ function SubmitCanvas(){ //this._ctx_src=null; this._matrix=new Matrix(); this._matrix4=CONST3D2D.defaultMatrix4.concat(); SubmitCanvas.__super.call(this,/*laya.webgl.submit.Submit.TYPE_2D*/10000); this.shaderValue=new Value2D(0,0); } __class(SubmitCanvas,'laya.webgl.submit.SubmitCanvas',_super); var __proto=SubmitCanvas.prototype; __proto.renderSubmit=function(){ if (this._ctx_src._targets){ this._ctx_src._targets.flush(this._ctx_src); return 1; }; var preAlpha=RenderState2D.worldAlpha; var preMatrix4=RenderState2D.worldMatrix4; var preMatrix=RenderState2D.worldMatrix; var preFilters=RenderState2D.worldFilters; var preWorldShaderDefines=RenderState2D.worldShaderDefines; var v=this.shaderValue; var m=this._matrix; var m4=this._matrix4; var mout=Matrix.TEMP; Matrix.mul(m,preMatrix,mout); m4[0]=mout.a; m4[1]=mout.b; m4[4]=mout.c; m4[5]=mout.d; m4[12]=mout.tx; m4[13]=mout.ty; RenderState2D.worldMatrix=mout.clone(); RenderState2D.worldMatrix4=m4; RenderState2D.worldAlpha=RenderState2D.worldAlpha *v.alpha; if (v.filters && v.filters.length){ RenderState2D.worldFilters=v.filters; RenderState2D.worldShaderDefines=v.defines; } this._ctx_src.flush(); RenderState2D.worldAlpha=preAlpha; RenderState2D.worldMatrix4=preMatrix4; RenderState2D.worldMatrix.destroy(); RenderState2D.worldMatrix=preMatrix; RenderState2D.worldFilters=preFilters; RenderState2D.worldShaderDefines=preWorldShaderDefines; return 1; } __proto.releaseRender=function(){ var cache=SubmitCanvas._cache; this._ctx_src=null; cache[cache._length++]=this; } __proto.getRenderType=function(){ return /*laya.webgl.submit.Submit.TYPE_CANVAS*/10003; } SubmitCanvas.create=function(ctx_src,alpha,filters){ var o=(!SubmitCanvas._cache._length)? (new SubmitCanvas()):SubmitCanvas._cache[--SubmitCanvas._cache._length]; o._ctx_src=ctx_src; var v=o.shaderValue; v.alpha=alpha; v.defines.setValue(0); filters && filters.length && v.setFilters(filters); return o; } SubmitCanvas._cache=(SubmitCanvas._cache=[],SubmitCanvas._cache._length=0,SubmitCanvas._cache); return SubmitCanvas; })(Submit) //class laya.webgl.submit.SubmitTexture extends laya.webgl.submit.Submit var SubmitTexture=(function(_super){ function SubmitTexture(renderType){ this._preIsSameTextureShader=false; this._isSameTexture=true; this._texs=new Array; this._texsID=new Array; this._vbPos=new Array; (renderType===void 0)&& (renderType=10000); SubmitTexture.__super.call(this,renderType); } __class(SubmitTexture,'laya.webgl.submit.SubmitTexture',_super); var __proto=SubmitTexture.prototype; __proto.releaseRender=function(){ var cache=SubmitTexture._cache; cache[cache._length++]=this; this.shaderValue.release(); this._preIsSameTextureShader=false; this._vb=null; this._texs.length=0; this._vbPos.length=0; this._isSameTexture=true; } __proto.addTexture=function(tex,vbpos){ this._texsID[this._texs.length]=tex._uvID; this._texs.push(tex); this._vbPos.push(vbpos); } //检查材质是否修改,修改UV,设置是否是同一材质 __proto.checkTexture=function(){ if (this._texs.length < 1){ this._isSameTexture=true; return; }; var _tex=this.shaderValue.textureHost; var webGLImg=_tex.bitmap; if (webGLImg===null)return; var vbdata=this._vb.getFloat32Array(); for (var i=0,s=this._texs.length;i < s;i++){ var tex=this._texs[i]; tex.active(); var newUV=tex.uv; if (this._texsID[i]!==tex._uvID){ this._texsID[i]=tex._uvID; var vbPos=this._vbPos[i]; vbdata[vbPos+2]=newUV[0]; vbdata[vbPos+3]=newUV[1]; vbdata[vbPos+6]=newUV[2]; vbdata[vbPos+7]=newUV[3]; vbdata[vbPos+10]=newUV[4]; vbdata[vbPos+11]=newUV[5]; vbdata[vbPos+14]=newUV[6]; vbdata[vbPos+15]=newUV[7]; this._vb.setNeedUpload(); } if (tex.bitmap!==webGLImg){ this._isSameTexture=false; } } } __proto.renderSubmit=function(){ if (this._numEle===0){ SubmitTexture._shaderSet=false; return 1; }; var _tex=this.shaderValue.textureHost; if (_tex){ var source=_tex.source; if (!_tex.bitmap || !source){ SubmitTexture._shaderSet=false; return 1; } this.shaderValue.texture=source; } this._vb.bind_upload(this._ib); var gl=WebGL.mainContext; if (BlendMode.activeBlendFunction!==this._blendFn){ gl.enable(/*laya.webgl.WebGLContext.BLEND*/0x0BE2); this._blendFn(gl); BlendMode.activeBlendFunction=this._blendFn; } Stat.drawCall++; Stat.trianglesFaces+=this._numEle / 3; if (this._preIsSameTextureShader && BaseShader.activeShader && SubmitTexture._shaderSet) (BaseShader.activeShader).uploadTexture2D(this.shaderValue.texture); else this.shaderValue.upload(); SubmitTexture._shaderSet=true; if (this._texs.length > 1 && !this._isSameTexture){ var webGLImg=_tex.bitmap; var index=0; var shader=BaseShader.activeShader; for (var i=0,s=this._texs.length;i < s;i++){ var tex2=this._texs[i]; if (tex2.bitmap!==webGLImg || (i+1)===s){ shader.uploadTexture2D(tex2.source); gl.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,(i-index+1)*6,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this._startIdx+index *6 *CONST3D2D.BYTES_PIDX); webGLImg=tex2.bitmap; index=i; } } }else { gl.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._numEle,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this._startIdx); } return 1; } SubmitTexture.create=function(context,ib,vb,pos,sv){ var o=SubmitTexture._cache._length ? SubmitTexture._cache[--SubmitTexture._cache._length] :new SubmitTexture(); if (vb==null){ vb=o._selfVb || (o._selfVb=VertexBuffer2D.create(-1)); vb.clear(); pos=0; } o._ib=ib; o._vb=vb; o._startIdx=pos *CONST3D2D.BYTES_PIDX; o._numEle=0; var blendType=context._nBlendType; o._blendFn=context._targets ? BlendMode.targetFns[blendType] :BlendMode.fns[blendType]; o.shaderValue=sv; o.shaderValue.setValue(context._shader2D); var filters=context._shader2D.filters; filters && o.shaderValue.setFilters(filters); return o; } SubmitTexture._cache=(SubmitTexture._cache=[],SubmitTexture._cache._length=0,SubmitTexture._cache); SubmitTexture._shaderSet=true; return SubmitTexture; })(Submit) /** *与MeshQuadTexture基本相同。不过index不是固定的 */ //class laya.webgl.utils.MeshTexture extends laya.webgl.utils.Mesh2D var MeshTexture=(function(_super){ function MeshTexture(){ MeshTexture.__super.call(this,laya.webgl.utils.MeshTexture.const_stride,0,0); this.canReuse=true; this.setAttributes(laya.webgl.utils.MeshTexture._fixattriInfo); } __class(MeshTexture,'laya.webgl.utils.MeshTexture',_super); var __proto=MeshTexture.prototype; __proto.addData=function(vertices,uvs,idx,matrix,rgba,ctx){ var vertsz=vertices.length / 2; var startpos=this._vb.needSize(vertsz *MeshTexture.const_stride); var f32pos=startpos >> 2; var vbdata=this._vb.getFloat32Array(); var ci=0; for (var i=0;i < vertsz;i++){ var x=vertices[ci],y=vertices[ci+1]; var x1=x *matrix.a+y *matrix.c+matrix.tx; var y1=x *matrix.b+y *matrix.d+matrix.ty; vbdata[f32pos++]=x1;vbdata[f32pos++]=y1; vbdata[f32pos++]=uvs[ci];vbdata[f32pos++]=uvs[ci+1]; ci+=2; } this._vb.setNeedUpload(); var vertN=this.vertNum; if (vertN > 0){ var sz=idx.length; if (sz > MeshTexture.tmpIdx.length)MeshTexture.tmpIdx=new Uint16Array(sz); for (var ii=0;ii < sz;ii++){ MeshTexture.tmpIdx[ii]=idx[ii]+vertN; } this._ib.appendU16Array(MeshTexture.tmpIdx,idx.length); }else { this._ib.append(idx); } this._ib.setNeedUpload(); this.vertNum+=vertsz; this.indexNum+=idx.length; } /** *把本对象放到回收池中,以便getMesh能用。 */ __proto.releaseMesh=function(){ this._vb._byteLength=0; this._ib._byteLength=0; this.vertNum=0; this.indexNum=0; laya.webgl.utils.MeshTexture._POOL.push(this); } __proto.destroy=function(){ this._ib.destroy(); this._vb.destroy(); } MeshTexture.getAMesh=function(){ if (laya.webgl.utils.MeshTexture._POOL.length){ return laya.webgl.utils.MeshTexture._POOL.pop(); } return new MeshTexture(); } MeshTexture.const_stride=16; MeshTexture._POOL=[]; __static(MeshTexture, ['_fixattriInfo',function(){return this._fixattriInfo=[ /*laya.webgl.WebGLContext.FLOAT*/0x1406,2,0, /*laya.webgl.WebGLContext.FLOAT*/0x1406,2,8];},'tmpIdx',function(){return this.tmpIdx=new Uint16Array(4);} ]); return MeshTexture; })(Mesh2D) /** *... *@author ... */ //class laya.webgl.shader.BaseShader extends laya.resource.Resource var BaseShader=(function(_super){ function BaseShader(){ BaseShader.__super.call(this); this.lock=true; } __class(BaseShader,'laya.webgl.shader.BaseShader',_super); BaseShader.activeShader=null; BaseShader.bindShader=null; return BaseShader; })(Resource) //class laya.webgl.resource.RenderTarget2D extends laya.resource.Texture var RenderTarget2D=(function(_super){ function RenderTarget2D(width,height,surfaceFormat,surfaceType,depthStencilFormat,mipMap,repeat,minFifter,magFifter){ this._type=0; this._svWidth=NaN; this._svHeight=NaN; this._preRenderTarget=null; //TODO:......................................................... this._alreadyResolved=false; this._looked=false; this._surfaceFormat=0; this._surfaceType=0; this._depthStencilFormat=0; this._mipMap=false; this._repeat=false; this._minFifter=0; this._magFifter=0; this._destroy=false; (surfaceFormat===void 0)&& (surfaceFormat=/*laya.webgl.WebGLContext.RGBA*/0x1908); (surfaceType===void 0)&& (surfaceType=/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401); (depthStencilFormat===void 0)&& (depthStencilFormat=/*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9); (mipMap===void 0)&& (mipMap=false); (repeat===void 0)&& (repeat=false); (minFifter===void 0)&& (minFifter=-1); (magFifter===void 0)&& (magFifter=-1); this._type=1; this._w=width; this._h=height; this._surfaceFormat=surfaceFormat; this._surfaceType=surfaceType; this._depthStencilFormat=depthStencilFormat; if (Render.isConchWebGL && this._depthStencilFormat===/*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9){ this._depthStencilFormat=/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5; } this._mipMap=mipMap; this._repeat=repeat; this._minFifter=minFifter; this._magFifter=magFifter; this._createWebGLRenderTarget(); this.bitmap.lock=true; RenderTarget2D.__super.call(this,this.bitmap,Texture.INV_UV); } __class(RenderTarget2D,'laya.webgl.resource.RenderTarget2D',_super); var __proto=RenderTarget2D.prototype; Laya.imps(__proto,{"laya.resource.IDispose":true}) //TODO:临时...................................................... __proto.getType=function(){ return this._type; } //*/ __proto.getTexture=function(){ return this; } __proto.size=function(w,h){ if (this._w==w && this._h==h)return; this._w=w; this._h=h; this.release(); if (this._w !=0 && this._h !=0)this._createWebGLRenderTarget(); } __proto.release=function(){ this.destroy(); } __proto.recycle=function(){ RenderTarget2D.POOL.push(this); } __proto.start=function(){ var gl=WebGL.mainContext; this._preRenderTarget=RenderState2D.curRenderTarget; RenderState2D.curRenderTarget=this; gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,this.bitmap.frameBuffer); this._alreadyResolved=false; if (this._type==1){ gl.viewport(0,0,this._w,this._h); this._svWidth=RenderState2D.width; this._svHeight=RenderState2D.height; RenderState2D.width=this._w; RenderState2D.height=this._h; BaseShader.activeShader=null; } return this; } __proto.clear=function(r,g,b,a){ (r===void 0)&& (r=0.0); (g===void 0)&& (g=0.0); (b===void 0)&& (b=0.0); (a===void 0)&& (a=1.0); var gl=WebGL.mainContext; gl.clearColor(r,g,b,a); var clearFlag=/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000; switch (this._depthStencilFormat){ case /*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5: clearFlag |=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; break ; case /*laya.webgl.WebGLContext.STENCIL_INDEX8*/0x8D48: clearFlag |=/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400; break ; case /*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9: clearFlag |=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; clearFlag |=/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400 break ; } gl.clear(clearFlag); } __proto.end=function(){ var gl=WebGL.mainContext; gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,this._preRenderTarget ? this._preRenderTarget.bitmap.frameBuffer :null); this._alreadyResolved=true; RenderState2D.curRenderTarget=this._preRenderTarget; if (this._type==1){ gl.viewport(0,0,this._svWidth,this._svHeight); RenderState2D.width=this._svWidth; RenderState2D.height=this._svHeight; BaseShader.activeShader=null; }else gl.viewport(0,0,Laya.stage.width,Laya.stage.height); } __proto.getData=function(x,y,width,height){ var gl=WebGL.mainContext; gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,(this.bitmap).frameBuffer); var canRead=(gl.checkFramebufferStatus(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40)===/*laya.webgl.WebGLContext.FRAMEBUFFER_COMPLETE*/0x8CD5); if (!canRead){ gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); return null; }; var pixels=new Uint8Array(this._w *this._h *4); gl.readPixels(x,y,width,height,this._surfaceFormat,this._surfaceType,pixels); gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); return pixels; } /**彻底清理资源,注意会强制解锁清理*/ __proto.destroy=function(foreDiposeTexture){ (foreDiposeTexture===void 0)&& (foreDiposeTexture=false); if (!this._destroy){ this._loaded=false; this.bitmap.offAll(); this.bitmap.disposeResource(); this.bitmap.dispose(); this.offAll(); this.bitmap=null; this._alreadyResolved=false; this._destroy=true; _super.prototype.destroy.call(this); } } //待测试 __proto.dispose=function(){} __proto._createWebGLRenderTarget=function(){ this.bitmap=new WebGLRenderTarget(this.width,this.height,this._surfaceFormat,this._surfaceType,this._depthStencilFormat,this._mipMap,this._repeat,this._minFifter,this._magFifter); this.bitmap.activeResource(); this._alreadyResolved=true; this._destroy=false; this._loaded=true; this.bitmap.on(/*laya.events.Event.RECOVERED*/"recovered",this,function(e){ this.event(/*laya.events.Event.RECOVERED*/"recovered"); }) } __getset(0,__proto,'surfaceFormat',function(){ return this._surfaceFormat; }); __getset(0,__proto,'magFifter',function(){ return this._magFifter; }); __getset(0,__proto,'surfaceType',function(){ return this._surfaceType; }); __getset(0,__proto,'mipMap',function(){ return this._mipMap; }); __getset(0,__proto,'depthStencilFormat',function(){ return this._depthStencilFormat; }); //} __getset(0,__proto,'minFifter',function(){ return this._minFifter; }); /**返回RenderTarget的Texture*/ __getset(0,__proto,'source',function(){ if (this._alreadyResolved) return Laya.superGet(Texture,this,'source'); return null; }); RenderTarget2D.create=function(w,h,surfaceFormat,surfaceType,depthStencilFormat,mipMap,repeat,minFifter,magFifter){ (surfaceFormat===void 0)&& (surfaceFormat=/*laya.webgl.WebGLContext.RGBA*/0x1908); (surfaceType===void 0)&& (surfaceType=/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401); (depthStencilFormat===void 0)&& (depthStencilFormat=/*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9); (mipMap===void 0)&& (mipMap=false); (repeat===void 0)&& (repeat=false); (minFifter===void 0)&& (minFifter=-1); (magFifter===void 0)&& (magFifter=-1); var t=RenderTarget2D.POOL.pop(); t || (t=new RenderTarget2D(w,h)); if (!t.bitmap || t._w !=w || t._h !=h || t._surfaceFormat !=surfaceFormat || t._surfaceType !=surfaceType || t._depthStencilFormat !=depthStencilFormat || t._mipMap !=mipMap || t._repeat !=repeat || t._minFifter !=minFifter || t._magFifter !=magFifter){ t._w=w; t._h=h; t._surfaceFormat=surfaceFormat; t._surfaceType=surfaceType; t._depthStencilFormat=depthStencilFormat; if (Render.isConchWebGL && t._depthStencilFormat===/*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9){ t._depthStencilFormat=/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5; } t._mipMap=mipMap; t._repeat=repeat; t._minFifter=minFifter; t._magFifter=magFifter; t.release(); t._createWebGLRenderTarget(); } return t; } RenderTarget2D.TYPE2D=1; RenderTarget2D.TYPE3D=2; RenderTarget2D.POOL=[]; return RenderTarget2D; })(Texture) //class laya.webgl.utils.Buffer extends laya.resource.Resource var Buffer=(function(_super){ function Buffer(){ this._glBuffer=null; this._buffer=null; //可能为Float32Array、Uint16Array、Uint8Array、ArrayBuffer等。 this._bufferType=0; this._bufferUsage=0; this._byteLength=0; Buffer.__super.call(this); Buffer._gl=WebGL.mainContext; } __class(Buffer,'laya.webgl.utils.Buffer',_super); var __proto=Buffer.prototype; __proto._bind=function(){ this.activeResource(); if (Buffer._bindActive[this._bufferType]!==this._glBuffer){ (this._bufferType===/*laya.webgl.WebGLContext.ARRAY_BUFFER*/0x8892)&& (Buffer._bindVertexBuffer=this._glBuffer); Buffer._gl.bindBuffer(this._bufferType,Buffer._bindActive[this._bufferType]=this._glBuffer); BaseShader.activeShader=null; } } __proto.recreateResource=function(){ this._glBuffer || (this._glBuffer=Buffer._gl.createBuffer()); this.completeCreate(); } __proto.disposeResource=function(){ if (this._glBuffer){ WebGL.mainContext.deleteBuffer(this._glBuffer); this._glBuffer=null; } this.memorySize=0; } __getset(0,__proto,'bufferUsage',function(){ return this._bufferUsage; }); Buffer._gl=null; Buffer._bindActive={}; Buffer._bindVertexBuffer=null; Buffer._enableAtributes=[]; return Buffer; })(Resource) //class laya.webgl.shader.d2.skinAnishader.SkinSV extends laya.webgl.shader.d2.value.Value2D var SkinSV=(function(_super){ function SkinSV(type){ this.texcoord=null; this.offsetX=300; this.offsetY=0; SkinSV.__super.call(this,/*laya.webgl.shader.d2.ShaderDefines2D.SKINMESH*/0x200,0); var _vlen=8 *CONST3D2D.BYTES_PE; this.position=[2,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,_vlen,0]; this.texcoord=[2,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,_vlen,2 *CONST3D2D.BYTES_PE]; this.color=[4,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,_vlen,4 *CONST3D2D.BYTES_PE]; } __class(SkinSV,'laya.webgl.shader.d2.skinAnishader.SkinSV',_super); return SkinSV; })(Value2D) //class laya.webgl.shader.d2.value.Color2dSV extends laya.webgl.shader.d2.value.Value2D var Color2dSV=(function(_super){ function Color2dSV(args){ Color2dSV.__super.call(this,/*laya.webgl.shader.d2.ShaderDefines2D.COLOR2D*/0x02,0); this.color=[]; } __class(Color2dSV,'laya.webgl.shader.d2.value.Color2dSV',_super); var __proto=Color2dSV.prototype; __proto.setValue=function(value){ value.fillStyle&&(this.color=value.fillStyle._color._color); value.strokeStyle&&(this.color=value.strokeStyle._color._color); } return Color2dSV; })(Value2D) //class laya.webgl.shader.d2.value.FillTextureSV extends laya.webgl.shader.d2.value.Value2D var FillTextureSV=(function(_super){ function FillTextureSV(type){ this.u_colorMatrix=null; this.strength=0; this.colorMat=null; this.colorAlpha=null; this.u_TexRange=[0,1,0,1]; this.u_offset=[0,0]; this.texcoord=Value2D._TEXCOORD; FillTextureSV.__super.call(this,/*laya.webgl.shader.d2.ShaderDefines2D.FILLTEXTURE*/0x100,0); } __class(FillTextureSV,'laya.webgl.shader.d2.value.FillTextureSV',_super); var __proto=FillTextureSV.prototype; //this.color=[4,WebGLContext.FLOAT,false,_vlen,4 *CONST3D2D.BYTES_PE]; __proto.setValue=function(vo){ this.ALPHA=vo.ALPHA; vo.filters && this.setFilters(vo.filters); } __proto.clear=function(){ this.texture=null; this.shader=null; this.defines.setValue(0); } return FillTextureSV; })(Value2D) //class laya.webgl.shader.d2.value.TextureSV extends laya.webgl.shader.d2.value.Value2D var TextureSV=(function(_super){ function TextureSV(subID){ this.u_colorMatrix=null; this.strength=0; this.blurInfo=null; this.colorMat=null; this.colorAlpha=null; this.texcoord=Value2D._TEXCOORD; (subID===void 0)&& (subID=0); TextureSV.__super.call(this,/*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01,subID); } __class(TextureSV,'laya.webgl.shader.d2.value.TextureSV',_super); var __proto=TextureSV.prototype; __proto.setValue=function(vo){ this.ALPHA=vo.ALPHA; vo.filters && this.setFilters(vo.filters); } __proto.clear=function(){ this.texture=null; this.shader=null; this.defines.setValue(0); } return TextureSV; })(Value2D) //class laya.webgl.shader.d2.value.PrimitiveSV extends laya.webgl.shader.d2.value.Value2D var PrimitiveSV=(function(_super){ function PrimitiveSV(args){ this.a_color=null; this.u_pos=[0,0]; PrimitiveSV.__super.call(this,/*laya.webgl.shader.d2.ShaderDefines2D.PRIMITIVE*/0x04,0); this.position=[2,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,5 *CONST3D2D.BYTES_PE,0]; this.a_color=[3,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,5 *CONST3D2D.BYTES_PE,2 *CONST3D2D.BYTES_PE]; } __class(PrimitiveSV,'laya.webgl.shader.d2.value.PrimitiveSV',_super); return PrimitiveSV; })(Value2D) //class laya.webgl.atlas.AtlasWebGLCanvas extends laya.resource.Bitmap var AtlasWebGLCanvas=(function(_super){ function AtlasWebGLCanvas(){ this._atlaser=null; /**兼容Stage3D使用*/ this._flashCacheImage=null; this._flashCacheImageNeedFlush=false; AtlasWebGLCanvas.__super.call(this); } __class(AtlasWebGLCanvas,'laya.webgl.atlas.AtlasWebGLCanvas',_super); var __proto=AtlasWebGLCanvas.prototype; /***重新创建资源*/ __proto.recreateResource=function(){ var gl=WebGL.mainContext; var glTex=this._source=gl.createTexture(); var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,glTex); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,this._w,this._h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,null); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); this.memorySize=this._w *this._h *4; this.completeCreate(); } /***销毁资源*/ __proto.disposeResource=function(){ if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this.memorySize=0; } } /**采样image到WebGLTexture的一部分*/ __proto.texSubImage2D=function(xoffset,yoffset,bitmap){ if (!Render.isFlash){ var gl=WebGL.mainContext; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,this._source); if (Render.isConchWebGL){ if (/*__JS__ */bitmap !==ConchTextCanvas){ (xoffset-1 >=0)&& (gl.texSubImage2DEx(true,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset-1,yoffset,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,bitmap)); (xoffset+1 <=this._w)&& (gl.texSubImage2DEx(true,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset+1,yoffset,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,bitmap)); (yoffset-1 >=0)&& (gl.texSubImage2DEx(true,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset,yoffset-1,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,bitmap)); (yoffset+1 <=this._h)&& (gl.texSubImage2DEx(true,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset,yoffset+1,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,bitmap)); } gl.texSubImage2DEx(true,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset,yoffset,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,bitmap); } else { gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,true); (xoffset-1 >=0)&& (gl.texSubImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset-1,yoffset,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,bitmap)); (xoffset+1 <=this._w)&& (gl.texSubImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset+1,yoffset,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,bitmap)); (yoffset-1 >=0)&& (gl.texSubImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset,yoffset-1,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,bitmap)); (yoffset+1 <=this._h)&& (gl.texSubImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset,yoffset+1,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,bitmap)); gl.texSubImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset,yoffset,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,bitmap); gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,false); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); }else { if (!this._flashCacheImage){ this._flashCacheImage=HTMLImage.create(""); this._flashCacheImage._image.createCanvas(this._w,this._h); }; var bmData=bitmap.bitmapdata; this._flashCacheImage._image.copyPixels(bmData,0,0,bmData.width,bmData.height,xoffset,yoffset); (this._flashCacheImageNeedFlush)|| (this._flashCacheImageNeedFlush=true); } } /**采样image到WebGLTexture的一部分*/ __proto.texSubImage2DPixel=function(xoffset,yoffset,width,height,pixel){ var gl=WebGL.mainContext; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,this._source); var pixels=new Uint8Array(pixel.data); if (Render.isConchWebGL){ gl.texSubImage2DEx(true,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset,yoffset,width,height,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,pixels); } else { gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,true); gl.texSubImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset,yoffset,width,height,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,pixels); gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,false); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); } /*** *设置图片宽度 *@param value 图片宽度 */ __getset(0,__proto,'width',_super.prototype._$get_width,function(value){ this._w=value; }); /*** *设置图片高度 *@param value 图片高度 */ __getset(0,__proto,'height',_super.prototype._$get_height,function(value){ this._h=value; }); return AtlasWebGLCanvas; })(Bitmap) /**@private */ //class laya.webgl.resource.WebGLCanvas extends laya.resource.Bitmap var WebGLCanvas=(function(_super){ function WebGLCanvas(){ this.flipY=true; //上传的时候是否预乘alpha //this._ctx=null; /**HTML Canvas*/ //this._canvas=null; //this._imgData=null; //} //this.iscpuSource=false; this.alwaysChange=false; WebGLCanvas.__super.call(this); } __class(WebGLCanvas,'laya.webgl.resource.WebGLCanvas',_super); var __proto=WebGLCanvas.prototype; //} __proto.getCanvas=function(){ return this._canvas; } __proto.clear=function(){ this._ctx && this._ctx.clear(); } __proto.destroy=function(){ this._ctx && this._ctx.destroy(); this._ctx=null; laya.resource.Resource.prototype.destroy.call(this); } __proto._setContext=function(context){ this._ctx=context; } __proto.getContext=function(contextID,other){ return this._ctx ? this._ctx :(this._ctx=WebGLCanvas._createContext(this)); } /*override public function copyTo(dec:Bitmap):void { super.copyTo(dec); (dec as WebGLCanvas)._ctx=_ctx; }*/ __proto.size=function(w,h){ if (this._w !=w || this._h !=h){ this._w=w; this._h=h; this._ctx && this._ctx.size(w,h); this._canvas && (this._canvas.height=h,this._canvas.width=w); } } __proto.activeResource=function(force){ (force===void 0)&& (force=false); if (!this._source){ this.recreateResource(); } } __proto.recreateResource=function(){ this.createWebGlTexture(); this.completeCreate(); } __proto.disposeResource=function(){ if (this._source && !this.iscpuSource){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this.memorySize=0; } } __proto.createWebGlTexture=function(){ var gl=WebGL.mainContext; if (!this._canvas){ }; var glTex=this._source=gl.createTexture(); this.iscpuSource=false; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,glTex); gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_FLIP_Y_WEBGL*/0x9240,this.flipY?1:0); if (Render.isConchWebGL){ gl.texImage2DEx(WebGLCanvas.premulAlpha,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._imgData); } else { WebGLCanvas.premulAlpha&&gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,true); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._imgData); WebGLCanvas.premulAlpha && gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,false); } gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_FLIP_Y_WEBGL*/0x9240,0); this.memorySize=this._w *this._h *4; (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); } //_canvas=null; __proto.reloadCanvasData=function(){ var gl=WebGL.mainContext; if (!this._source){ throw "reloadCanvasData error, gl texture not created!"; }; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,this._source); if (Render.isConchWebGL){ gl.texImage2DEx(WebGLCanvas.premulAlpha,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._imgData); } else { WebGLCanvas.premulAlpha&&gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,true); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._imgData); WebGLCanvas.premulAlpha && gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,false); } gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_FLIP_Y_WEBGL*/0x9240,0); (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); } //_canvas=null; __proto.texSubImage2D=function(webglCanvas,xoffset,yoffset){ var gl=WebGL.mainContext; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,this._source); if (Render.isConchWebGL){ gl.texSubImage2DEx(true,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset,yoffset,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,webglCanvas._source); } else { gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,true); gl.texSubImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,xoffset,yoffset,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,webglCanvas._source); gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,false); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); } __proto.toBase64=function(type,encoderOptions,callBack){ var base64Data=null; if (this._canvas){ base64Data=this._canvas.toDataURL(type,encoderOptions); } callBack.call(this,base64Data); } //由于resource的dispose被郭磊改成了destroy,这里会重载父类的destroy,所以必须调用这个,否则会有泄露。 __getset(0,__proto,'context',function(){ return this._ctx; }); __getset(0,__proto,'source',function(){ if (this.alwaysChange)this.reloadCanvasData(); return this._source; }); __getset(0,__proto,'asBitmap',null,function(value){ this._ctx && (this._ctx.asBitmap=value); }); WebGLCanvas._createContext=null; WebGLCanvas.premulAlpha=false; return WebGLCanvas; })(Bitmap) //class laya.webgl.resource.WebGLCharImage extends laya.resource.Bitmap var WebGLCharImage=(function(_super){ function WebGLCharImage(content,drawValue){ // public static var Config.CborderSize:int=12; //this._ctx=null; /***是否创建私有Source*/ //this._allowMerageInAtlas=false; /**是否允许加入大图合集*/ //this._enableMerageInAtlas=false; /**HTML Canvas,绘制字符载体,非私有数据载体*/ //this.canvas=null; /**********************************************************************************/ //this.cw=NaN; //this.ch=NaN; //this.xs=NaN; //this.ys=NaN; //this.char=null; //this.fillColor=null; //this.borderColor=null; //this.borderSize=0; //this.font=null; //this.fontSize=0; //this.texture=null; //this.lineWidth=0; //this.UV=null; //this.isSpace=false; //this.underLine=0; WebGLCharImage.__super.call(this); this.char=content; this.isSpace=content===' '; this.xs=drawValue.scaleX; this.ys=drawValue.scaleY; this.font=drawValue.font.toString(); this.fontSize=drawValue.font.size; this.fillColor=drawValue.fillColor; this.borderColor=drawValue.borderColor; this.lineWidth=drawValue.lineWidth; this.underLine=drawValue.underLine; var bIsConchApp=Render.isConchApp; var pCanvas; if (bIsConchApp){ /*__JS__ */pCanvas=ConchTextCanvas; /*__JS__ */pCanvas._source=ConchTextCanvas; /*__JS__ */pCanvas._source.canvas=ConchTextCanvas; }else { pCanvas=Browser.canvas.source; } this.canvas=pCanvas; this._enableMerageInAtlas=true; if (bIsConchApp){ /*__JS__ */this._ctx=pCanvas; }else { this._ctx=this.canvas.getContext('2d',undefined); }; var t=Utils.measureText(this.char,this.font); this.cw=t.width *this.xs; this.ch=(t.height || this.fontSize)*this.ys; this.onresize(this.cw+Config.CborderSize *2,this.ch+Config.CborderSize *2); this.texture=new Texture(this); } __class(WebGLCharImage,'laya.webgl.resource.WebGLCharImage',_super); var __proto=WebGLCharImage.prototype; Laya.imps(__proto,{"laya.webgl.resource.IMergeAtlasBitmap":true}) __proto.active=function(){ this.texture.active(); } __proto.recreateResource=function(){ var bIsConchApp=Render.isConchApp; this.onresize(this.cw+Config.CborderSize *2,this.ch+Config.CborderSize *2); this.canvas && (this.canvas.height=this._h,this.canvas.width=this._w); if (bIsConchApp){ var nFontSize=this.fontSize; if (this.xs !=1 || this.ys !=1){ nFontSize=parseInt(nFontSize *((this.xs > this.ys)? this.xs :this.ys)+""); }; var sFont="normal 100 "+this.font; sFont=sFont.replace(WebGLCharImage._fontSizeReg,nFontSize); if (this.borderColor){ sFont+=" 1 "+this.borderColor; } this._ctx.font=sFont; this._ctx.textBaseline="top"; this._ctx.fillStyle=this.fillColor; this._ctx.fillText(this.char,Config.CborderSize,Config.CborderSize,null,null,null); }else { this._ctx.save(); this._ctx.lineJoin="round"; (this._ctx).clearRect(0,0,this.cw+Config.CborderSize *2,this.ch+Config.CborderSize *2); this._ctx.font=this.font; if (Text.RightToLeft){ this._ctx.textAlign="end"; } this._ctx.textBaseline="top"; if (this.xs !=1 || this.ys !=1){ this._ctx.setTransform(this.xs,0,0,this.ys,Config.CborderSize,Config.CborderSize); }else { this._ctx.setTransform(1,0,0,1,Config.CborderSize,Config.CborderSize); } if (this.fillColor && this.borderColor){ this._ctx.strokeStyle=this.borderColor; this._ctx.lineWidth=this.lineWidth; this._ctx.strokeText(this.char,0,0,null,null,0,null); this._ctx.fillStyle=this.fillColor; this._ctx.fillText(this.char,0,0); }else { if (this.lineWidth===-1){ this._ctx.fillStyle=this.fillColor ? this.fillColor :"white"; this._ctx.fillText(this.char,0,0); }else { this._ctx.strokeStyle=this.borderColor?this.borderColor:'white'; this._ctx.lineWidth=this.lineWidth; this._ctx.strokeText(this.char,0,0,null,null,0,null); } } if (this.underLine){ this._ctx.lineWidth=1; this._ctx.strokeStyle=this.fillColor; this._ctx.beginPath(); this._ctx.moveTo(0,this.fontSize+1); var nW=this._ctx.measureText(this.char).width+1; this._ctx.lineTo(nW,this.fontSize+1); this._ctx.stroke(); } this._ctx.restore(); } this.borderSize=Config.CborderSize; this.completeCreate(); } __proto.onresize=function(w,h){ this._w=w; this._h=h; this._allowMerageInAtlas=true; } __proto.clearAtlasSource=function(){} /** *是否创建私有Source *@return 是否创建 */ __getset(0,__proto,'allowMerageInAtlas',function(){ return this._allowMerageInAtlas; }); __getset(0,__proto,'atlasSource',function(){ return this.canvas; }); __getset(0,__proto,'atlasImgData',function(){ if (!WebGLCharImage.canUseCanvas){ if(this._ctx.getImageData) return this._ctx.getImageData(0,0,this._w,this._h); } return null; }); /** *是否创建私有Source,通常禁止修改 *@param value 是否创建 */ /** *是否创建私有Source *@return 是否创建 */ __getset(0,__proto,'enableMerageInAtlas',function(){ return this._enableMerageInAtlas; },function(value){ this._enableMerageInAtlas=value; }); WebGLCharImage.createOneChar=function(content,drawValue){ var char=new WebGLCharImage(content,drawValue); return char; } WebGLCharImage.canUseCanvas=true; WebGLCharImage._fontSizeReg=new RegExp("\\d+(?=px)","g"); return WebGLCharImage; })(Bitmap) //class laya.webgl.resource.WebGLRenderTarget extends laya.resource.Bitmap var WebGLRenderTarget=(function(_super){ function WebGLRenderTarget(width,height,surfaceFormat,surfaceType,depthStencilFormat,mipMap,repeat,minFifter,magFifter){ //this._frameBuffer=null; //this._depthStencilBuffer=null; //this._surfaceFormat=0; //this._surfaceType=0; //this._depthStencilFormat=0; //this._mipMap=false; //this._repeat=false; //this._minFifter=0; //this._magFifter=0; (surfaceFormat===void 0)&& (surfaceFormat=/*laya.webgl.WebGLContext.RGBA*/0x1908); (surfaceType===void 0)&& (surfaceType=/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401); (depthStencilFormat===void 0)&& (depthStencilFormat=/*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9); (mipMap===void 0)&& (mipMap=false); (repeat===void 0)&& (repeat=false); (minFifter===void 0)&& (minFifter=-1); (magFifter===void 0)&& (magFifter=1); WebGLRenderTarget.__super.call(this); this._w=width; this._h=height; this._surfaceFormat=surfaceFormat; this._surfaceType=surfaceType; this._depthStencilFormat=depthStencilFormat; if (Render.isConchWebGL && this._depthStencilFormat===/*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9){ this._depthStencilFormat=/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5; } this._mipMap=mipMap; this._repeat=repeat; this._minFifter=minFifter; this._magFifter=magFifter; } __class(WebGLRenderTarget,'laya.webgl.resource.WebGLRenderTarget',_super); var __proto=WebGLRenderTarget.prototype; __proto.recreateResource=function(){ var gl=WebGL.mainContext; this._frameBuffer || (this._frameBuffer=gl.createFramebuffer()); this._source || (this._source=gl.createTexture()); var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,this._source); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,this._w,this._h,0,this._surfaceFormat,this._surfaceType,null); var minFifter=this._minFifter; var magFifter=this._magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPot=Arith.isPOT(this._w,this._h); if (isPot){ if (this._mipMap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this._mipMap && gl.generateMipmap(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,this._frameBuffer); gl.framebufferTexture2D(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.COLOR_ATTACHMENT0*/0x8CE0,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,this._source,0); if (this._depthStencilFormat){ this._depthStencilBuffer || (this._depthStencilBuffer=gl.createRenderbuffer()); gl.bindRenderbuffer(/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); gl.renderbufferStorage(/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilFormat,this._w,this._h); switch (this._depthStencilFormat){ case /*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5: gl.framebufferRenderbuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.DEPTH_ATTACHMENT*/0x8D00,/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); break ; case /*laya.webgl.WebGLContext.STENCIL_INDEX8*/0x8D48: gl.framebufferRenderbuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.STENCIL_ATTACHMENT*/0x8D20,/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); break ; case /*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9: gl.framebufferRenderbuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.DEPTH_STENCIL_ATTACHMENT*/0x821A,/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); break ; } } gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); gl.bindRenderbuffer(/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,null); if (isPot && this._mipMap) this.memorySize=this._w *this._h *4 *(1+1 / 3); else this.memorySize=this._w *this._h *4; this.completeCreate(); } __proto.disposeResource=function(){ if (this._frameBuffer){ WebGL.mainContext.deleteTexture(this._source); WebGL.mainContext.deleteFramebuffer(this._frameBuffer); WebGL.mainContext.deleteRenderbuffer(this._depthStencilBuffer); this._source=null; this._frameBuffer=null; this._depthStencilBuffer=null; this.memorySize=0; } } __getset(0,__proto,'depthStencilBuffer',function(){ return this._depthStencilBuffer; }); __getset(0,__proto,'frameBuffer',function(){ return this._frameBuffer; }); return WebGLRenderTarget; })(Bitmap) //class laya.webgl.resource.WebGLSubImage extends laya.resource.Bitmap var WebGLSubImage=(function(_super){ function WebGLSubImage(canvas,offsetX,offsetY,width,height,atlasImage,src){ /**HTML Context*/ //this._ctx=null; /***是否创建私有Source,值为false时不根据src创建私有WebGLTexture,同时销毁时也只清空source=null,不调用WebGL.mainContext.deleteTexture类似函数,调用资源激活前有效*/ //this._allowMerageInAtlas=false; /**是否允许加入大图合集*/ //this._enableMerageInAtlas=false; /**HTML Canvas,绘制子图载体,非私有数据载体*/ //this.canvas=null; /**是否使用重复模式纹理寻址*/ //this.repeat=false; /**是否使用mipLevel*/ //this.mipmap=false; /**缩小过滤器*/ //this.minFifter=0; /**放大过滤器*/ //this.magFifter=0; //动态默认值,判断是否可生成miplevel //this.atlasImage=null; this.offsetX=0; this.offsetY=0; //this.src=null; WebGLSubImage.__super.call(this); this.repeat=true; this.mipmap=false; this.minFifter=-1; this.magFifter=-1; this.atlasImage=atlasImage; this.canvas=canvas; this._ctx=canvas.getContext('2d',undefined); this._w=width; this._h=height; this.offsetX=offsetX; this.offsetY=offsetY; this.src=src; this._enableMerageInAtlas=true; (AtlasResourceManager.enabled)&& (this._w < AtlasResourceManager.atlasLimitWidth && this._h < AtlasResourceManager.atlasLimitHeight)? this._allowMerageInAtlas=true :this._allowMerageInAtlas=false; } __class(WebGLSubImage,'laya.webgl.resource.WebGLSubImage',_super); var __proto=WebGLSubImage.prototype; Laya.imps(__proto,{"laya.webgl.resource.IMergeAtlasBitmap":true}) /*override public function copyTo(dec:Bitmap):void { var d:WebGLSubImage=dec as WebGLSubImage; super.copyTo(dec); d._ctx=_ctx; }*/ __proto.size=function(w,h){ this._w=w; this._h=h; this._ctx && this._ctx.size(w,h); this.canvas && (this.canvas.height=h,this.canvas.width=w); } __proto.recreateResource=function(){ this.size(this._w,this._h); this._ctx.drawImage(this.atlasImage,this.offsetX,this.offsetY,this._w,this._h,0,0,this._w,this._h); (!(this._allowMerageInAtlas && this._enableMerageInAtlas))? (this.createWebGlTexture()):(this.memorySize=0); this.completeCreate(); } __proto.createWebGlTexture=function(){ var gl=WebGL.mainContext; if (!this.canvas){ throw "create GLTextur err:no data:"+this.canvas; }; var glTex=this._source=gl.createTexture(); var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,glTex); if (Render.isConchWebGL){ gl.texImage2DEx(true,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this.canvas); } else { gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,true); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this.canvas); gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,false); }; var minFifter=this.minFifter; var magFifter=this.magFifter; var repeat=this.repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPOT=Arith.isPOT(this.width,this.height); if (isPOT){ if (this.mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this.mipmap && gl.generateMipmap(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); this.canvas=null; if (isPOT && this.mipmap) this.memorySize=this._w *this._h *4 *(1+1 / 3); else this.memorySize=this._w *this._h *4; } __proto.disposeResource=function(){ if (!(AtlasResourceManager.enabled && this._allowMerageInAtlas)&& this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this.memorySize=0; } } //} __proto.clearAtlasSource=function(){} /** *是否创建私有Source *@return 是否创建 */ __getset(0,__proto,'allowMerageInAtlas',function(){ return this._allowMerageInAtlas; }); //public var createFromPixel:Boolean=true; __getset(0,__proto,'atlasSource',function(){ return this.canvas; }); /** *是否创建私有Source,通常禁止修改 *@param value 是否创建 */ /** *是否创建私有Source *@return 是否创建 */ __getset(0,__proto,'enableMerageInAtlas',function(){ return this._allowMerageInAtlas; },function(value){ this._allowMerageInAtlas=value; }); return WebGLSubImage; })(Bitmap) //class laya.webgl.shader.Shader extends laya.webgl.shader.BaseShader var Shader=(function(_super){ function Shader(vs,ps,saveName,nameMap){ //this._nameMap=null; //shader参数别名,语义 //this._vs=null; //this._ps=null; this._curActTexIndex=0; //this._reCompile=false; //存储一些私有变量 this.tag={}; //this._vshader=null; //this._pshader=null; this._program=null; this._params=null; this._paramsMap={}; this._offset=0; //this._id=0; Shader.__super.call(this); if ((!vs)|| (!ps))throw "Shader Error"; this._id=++Shader._count; this._vs=vs; this._ps=ps; this._nameMap=nameMap ? nameMap :{}; saveName !=null && (Shader.sharders[saveName]=this); } __class(Shader,'laya.webgl.shader.Shader',_super); var __proto=Shader.prototype; __proto.recreateResource=function(){ this._compile(); this.completeCreate(); this.memorySize=0; } //忽略尺寸尺寸 __proto.disposeResource=function(){ WebGL.mainContext.deleteShader(this._vshader); WebGL.mainContext.deleteShader(this._pshader); WebGL.mainContext.deleteProgram(this._program); this._vshader=this._pshader=this._program=null; this._params=null; this._paramsMap={}; this.memorySize=0; this._curActTexIndex=0; } __proto._compile=function(){ if (!this._vs || !this._ps || this._params) return; this._reCompile=true; this._params=[]; var text=[this._vs,this._ps]; var result; var gl=WebGL.mainContext; this._program=gl.createProgram(); this._vshader=Shader._createShader(gl,text[0],/*laya.webgl.WebGLContext.VERTEX_SHADER*/0x8B31); this._pshader=Shader._createShader(gl,text[1],/*laya.webgl.WebGLContext.FRAGMENT_SHADER*/0x8B30); gl.attachShader(this._program,this._vshader); gl.attachShader(this._program,this._pshader); gl.linkProgram(this._program); if (!Render.isConchApp && !gl.getProgramParameter(this._program,/*laya.webgl.WebGLContext.LINK_STATUS*/0x8B82)){ throw gl.getProgramInfoLog(this._program); }; var one,i=0,j=0,n=0,location; var attribNum=0; if (Render.isConchApp){ attribNum=gl.getProgramParameterEx(this._vs,this._ps,"",/*laya.webgl.WebGLContext.ACTIVE_ATTRIBUTES*/0x8B89); } else{ attribNum=gl.getProgramParameter(this._program,/*laya.webgl.WebGLContext.ACTIVE_ATTRIBUTES*/0x8B89); } for (i=0;i < attribNum;i++){ var attrib=null; if (Render.isConchApp){ attrib=gl.getActiveAttribEx(this._vs,this._ps,"",i); } else{ attrib=gl.getActiveAttrib(this._program,i); } location=gl.getAttribLocation(this._program,attrib.name); one={vartype:"attribute",glfun:null,ivartype:0,attrib:attrib,location:location,name:attrib.name,type:attrib.type,isArray:false,isSame:false,preValue:null,indexOfParams:0}; this._params.push(one); }; var nUniformNum=0; if (Render.isConchApp){ nUniformNum=gl.getProgramParameterEx(this._vs,this._ps,"",/*laya.webgl.WebGLContext.ACTIVE_UNIFORMS*/0x8B86); } else{ nUniformNum=gl.getProgramParameter(this._program,/*laya.webgl.WebGLContext.ACTIVE_UNIFORMS*/0x8B86); } for (i=0;i < nUniformNum;i++){ var uniform=null; if (Render.isConchApp){ uniform=gl.getActiveUniformEx(this._vs,this._ps,"",i); } else{ uniform=gl.getActiveUniform(this._program,i); } location=gl.getUniformLocation(this._program,uniform.name); one={vartype:"uniform",glfun:null,ivartype:1,attrib:attrib,location:location,name:uniform.name,type:uniform.type,isArray:false,isSame:false,preValue:null,indexOfParams:0}; if (one.name.indexOf('[0]')> 0){ one.name=one.name.substr(0,one.name.length-3); one.isArray=true; one.location=gl.getUniformLocation(this._program,one.name); } this._params.push(one); } for (i=0,n=this._params.length;i < n;i++){ one=this._params[i]; one.indexOfParams=i; one.index=1; one.value=[one.location,null]; one.codename=one.name; one.name=this._nameMap[one.codename] ? this._nameMap[one.codename] :one.codename; this._paramsMap[one.name]=one; one._this=this; one.uploadedValue=[]; if (one.vartype==="attribute"){ one.fun=this._attribute; continue ; } switch (one.type){ case /*laya.webgl.WebGLContext.INT*/0x1404: one.fun=one.isArray ? this._uniform1iv :this._uniform1i; break ; case /*laya.webgl.WebGLContext.FLOAT*/0x1406: one.fun=one.isArray ? this._uniform1fv :this._uniform1f; break ; case /*laya.webgl.WebGLContext.FLOAT_VEC2*/0x8B50: one.fun=one.isArray ? this._uniform_vec2v:this._uniform_vec2; break ; case /*laya.webgl.WebGLContext.FLOAT_VEC3*/0x8B51: one.fun=one.isArray ? this._uniform_vec3v:this._uniform_vec3; break ; case /*laya.webgl.WebGLContext.FLOAT_VEC4*/0x8B52: one.fun=one.isArray ? this._uniform_vec4v:this._uniform_vec4; break ; case /*laya.webgl.WebGLContext.SAMPLER_2D*/0x8B5E: one.fun=this._uniform_sampler2D; break ; case /*laya.webgl.WebGLContext.SAMPLER_CUBE*/0x8B60: one.fun=this._uniform_samplerCube; break ; case /*laya.webgl.WebGLContext.FLOAT_MAT4*/0x8B5C: one.glfun=gl.uniformMatrix4fv; one.fun=this._uniformMatrix4fv; break ; case /*laya.webgl.WebGLContext.BOOL*/0x8B56: one.fun=this._uniform1i; break ; case /*laya.webgl.WebGLContext.FLOAT_MAT2*/0x8B5A: case /*laya.webgl.WebGLContext.FLOAT_MAT3*/0x8B5B: throw new Error("compile shader err!"); break ; default : throw new Error("compile shader err!"); break ; } } } /** *根据变量名字获得 *@param name *@return */ __proto.getUniform=function(name){ return this._paramsMap[name]; } __proto._attribute=function(one,value){ var gl=WebGL.mainContext; var enableAtributes=Buffer._enableAtributes; var location=one.location; (enableAtributes[location])||(gl.enableVertexAttribArray(location)); gl.vertexAttribPointer(location,value[0],value[1],value[2],value[3],value[4]+this._offset); enableAtributes[location]=Buffer._bindVertexBuffer; return 1; } __proto._uniform1f=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value){ WebGL.mainContext.uniform1f(one.location,uploadedValue[0]=value); return 1; } return 0; } __proto._uniform1fv=function(one,value){ if (value.length < 4){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform1fv(one.location,value); uploadedValue[0]=value[0]; uploadedValue[1]=value[1]; uploadedValue[2]=value[2]; uploadedValue[3]=value[3]; return 1; } return 0; }else { WebGL.mainContext.uniform1fv(one.location,value); return 1; } } __proto._uniform_vec2=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1]){ WebGL.mainContext.uniform2f(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1]); return 1; } return 0; } __proto._uniform_vec2v=function(one,value){ if (value.length < 2){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform2fv(one.location,value); uploadedValue[0]=value[0]; uploadedValue[1]=value[1]; uploadedValue[2]=value[2]; uploadedValue[3]=value[3]; return 1; } return 0; }else { WebGL.mainContext.uniform2fv(one.location,value); return 1; } } __proto._uniform_vec3=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2]){ WebGL.mainContext.uniform3f(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2]); return 1; } return 0; } __proto._uniform_vec3v=function(one,value){ WebGL.mainContext.uniform3fv(one.location,value); return 1; } __proto._uniform_vec4=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform4f(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2],uploadedValue[3]=value[3]); return 1; } return 0; } __proto._uniform_vec4v=function(one,value){ WebGL.mainContext.uniform4fv(one.location,value); return 1; } __proto._uniformMatrix2fv=function(one,value){ WebGL.mainContext.uniformMatrix2fv(one.location,false,value); return 1; } __proto._uniformMatrix3fv=function(one,value){ WebGL.mainContext.uniformMatrix3fv(one.location,false,value); return 1; } __proto._uniformMatrix4fv=function(one,value){ WebGL.mainContext.uniformMatrix4fv(one.location,false,value); return 1; } __proto._uniform1i=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value){ WebGL.mainContext.uniform1i(one.location,uploadedValue[0]=value); return 1; } return 0; } __proto._uniform1iv=function(one,value){ WebGL.mainContext.uniform1iv(one.location,value); return 1; } __proto._uniform_ivec2=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1]){ WebGL.mainContext.uniform2i(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1]); return 1; } return 0; } __proto._uniform_ivec2v=function(one,value){ WebGL.mainContext.uniform2iv(one.location,value); return 1; } __proto._uniform_vec3i=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2]){ WebGL.mainContext.uniform3i(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2]); return 1; } return 0; } __proto._uniform_vec3vi=function(one,value){ WebGL.mainContext.uniform3iv(one.location,value); return 1; } __proto._uniform_vec4i=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform4i(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2],uploadedValue[3]=value[3]); return 1; } return 0; } __proto._uniform_vec4vi=function(one,value){ WebGL.mainContext.uniform4iv(one.location,value); return 1; } __proto._uniform_sampler2D=function(one,value){ var gl=WebGL.mainContext; var uploadedValue=one.uploadedValue; if (uploadedValue[0]==null){ uploadedValue[0]=this._curActTexIndex; gl.uniform1i(one.location,this._curActTexIndex); gl.activeTexture(Shader._TEXTURES[this._curActTexIndex]); WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,value); this._curActTexIndex++; return 1; }else { gl.activeTexture(Shader._TEXTURES[uploadedValue[0]]); WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,value); return 0; } } __proto._uniform_samplerCube=function(one,value){ var gl=WebGL.mainContext; var uploadedValue=one.uploadedValue; if (uploadedValue[0]==null){ uploadedValue[0]=this._curActTexIndex; gl.uniform1i(one.location,this._curActTexIndex); gl.activeTexture(Shader._TEXTURES[this._curActTexIndex]); WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513,value); this._curActTexIndex++; return 1; }else { gl.activeTexture(Shader._TEXTURES[uploadedValue[0]]); WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513,value); return 0; } } __proto._noSetValue=function(one){ console.log("no....:"+one.name); } //throw new Error("upload shader err,must set value:"+one.name); __proto.uploadOne=function(name,value){ this.activeResource(); WebGLContext.UseProgram(this._program); var one=this._paramsMap[name]; one.fun.call(this,one,value); } __proto.uploadTexture2D=function(value){ Stat.shaderCall++; var gl=WebGL.mainContext; gl.activeTexture(/*laya.webgl.WebGLContext.TEXTURE0*/0x84C0); WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,value); } /** *提交shader到GPU *@param shaderValue */ __proto.upload=function(shaderValue,params){ BaseShader.activeShader=BaseShader.bindShader=this; this._lastUseFrameCount===Stat.loopCount || this.activeResource(); WebGLContext.UseProgram(this._program); if (this._reCompile){ params=this._params; this._reCompile=false; }else { params=params || this._params; }; var gl=WebGL.mainContext; var one,value,n=params.length,shaderCall=0; for (var i=0;i < n;i++){ one=params[i]; if ((value=shaderValue[one.name])!==null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadArray=function(shaderValue,length,_bufferUsage){ BaseShader.activeShader=this; BaseShader.bindShader=this; this.activeResource(); WebGLContext.UseProgram(this._program); var params=this._params,value; var one,shaderCall=0; for (var i=length-2;i >=0;i-=2){ one=this._paramsMap[shaderValue[i]]; if (!one) continue ; value=shaderValue[i+1]; if (value !=null){ _bufferUsage && _bufferUsage[one.name] && _bufferUsage[one.name].bind(); shaderCall+=one.fun.call(this,one,value); } } Stat.shaderCall+=shaderCall; } /** *得到编译后的变量及相关预定义 *@return */ __proto.getParams=function(){ return this._params; } Shader.getShader=function(name){ return Shader.sharders[name]; } Shader.create=function(vs,ps,saveName,nameMap){ return new Shader(vs,ps,saveName,nameMap); } Shader.withCompile=function(nameID,define,shaderName,createShader){ if (shaderName && Shader.sharders[shaderName]) return Shader.sharders[shaderName]; var pre=Shader._preCompileShader[0.0002 *nameID]; if (!pre) throw new Error("withCompile shader err!"+nameID); return pre.createShader(define,shaderName,createShader); } Shader.withCompile2D=function(nameID,mainID,define,shaderName,createShader){ if (shaderName && Shader.sharders[shaderName]) return Shader.sharders[shaderName]; var pre=Shader._preCompileShader[0.0002 *nameID+mainID]; if (!pre) throw new Error("withCompile shader err!"+nameID+" "+mainID); return pre.createShader(define,shaderName,createShader); } Shader.addInclude=function(fileName,txt){ ShaderCompile.addInclude(fileName,txt); } Shader.preCompile=function(nameID,vs,ps,nameMap){ var id=0.0002 *nameID; Shader._preCompileShader[id]=new ShaderCompile(id,vs,ps,nameMap); } Shader.preCompile2D=function(nameID,mainID,vs,ps,nameMap){ var id=0.0002 *nameID+mainID; Shader._preCompileShader[id]=new ShaderCompile(id,vs,ps,nameMap); } Shader._createShader=function(gl,str,type){ var shader=gl.createShader(type); gl.shaderSource(shader,str); gl.compileShader(shader); return shader; } Shader._TEXTURES=[ /*laya.webgl.WebGLContext.TEXTURE0*/0x84C0,/*laya.webgl.WebGLContext.TEXTURE1*/0x84C1,/*laya.webgl.WebGLContext.TEXTURE2*/0x84C2,/*laya.webgl.WebGLContext.TEXTURE3*/0x84C3,/*laya.webgl.WebGLContext.TEXTURE4*/0x84C4,/*laya.webgl.WebGLContext.TEXTURE5*/0x84C5,/*laya.webgl.WebGLContext.TEXTURE6*/0x84C6,,/*laya.webgl.WebGLContext.TEXTURE7*/0x84C7,/*laya.webgl.WebGLContext.TEXTURE8*/0x84C8]; Shader._count=0; Shader._preCompileShader={}; Shader.SHADERNAME2ID=0.0002; Shader.sharders=(Shader.sharders=[],Shader.sharders.length=0x20,Shader.sharders); __static(Shader, ['nameKey',function(){return this.nameKey=new StringKey();} ]); return Shader; })(BaseShader) //class laya.webgl.utils.Buffer2D extends laya.webgl.utils.Buffer var Buffer2D=(function(_super){ function Buffer2D(){ this._maxsize=0; this._upload=true; this._uploadSize=0; Buffer2D.__super.call(this); this.lock=true; } __class(Buffer2D,'laya.webgl.utils.Buffer2D',_super); var __proto=Buffer2D.prototype; /** *在当前的基础上需要多大空间,单位是byte *@param sz *@return 增加大小之前的写位置。单位是byte */ __proto.needSize=function(sz){ var old=this._byteLength; if (sz){ var needsz=this._byteLength+sz; needsz <=this._buffer.byteLength || (this._resizeBuffer(needsz << 1,true)); this._byteLength=needsz; } return old; } __proto._bufferData=function(){ this._maxsize=Math.max(this._maxsize,this._byteLength); if (Stat.loopCount % 30==0){ if (this._buffer.byteLength > (this._maxsize+64)){ this.memorySize=this._buffer.byteLength; this._buffer=this._buffer.slice(0,this._maxsize+64); this._checkArrayUse(); } this._maxsize=this._byteLength; } if (this._uploadSize < this._buffer.byteLength){ this._uploadSize=this._buffer.byteLength; Buffer._gl.bufferData(this._bufferType,this._uploadSize,this._bufferUsage); this.memorySize=this._uploadSize; } Buffer._gl.bufferSubData(this._bufferType,0,this._buffer); } __proto._bufferSubData=function(offset,dataStart,dataLength){ (offset===void 0)&& (offset=0); (dataStart===void 0)&& (dataStart=0); (dataLength===void 0)&& (dataLength=0); this._maxsize=Math.max(this._maxsize,this._byteLength); if (Stat.loopCount % 30==0){ if (this._buffer.byteLength > (this._maxsize+64)){ this.memorySize=this._buffer.byteLength; this._buffer=this._buffer.slice(0,this._maxsize+64); this._checkArrayUse(); } this._maxsize=this._byteLength; } if (this._uploadSize < this._buffer.byteLength){ this._uploadSize=this._buffer.byteLength; Buffer._gl.bufferData(this._bufferType,this._uploadSize,this._bufferUsage); this.memorySize=this._uploadSize; } if (dataStart || dataLength){ var subBuffer=this._buffer.slice(dataStart,dataLength); Buffer._gl.bufferSubData(this._bufferType,offset,subBuffer); }else { Buffer._gl.bufferSubData(this._bufferType,offset,this._buffer); } } __proto._checkArrayUse=function(){} __proto._bind_upload=function(){ if (!this._upload) return false; this._upload=false; this._bind(); this._bufferData(); return true; } __proto._bind_subUpload=function(offset,dataStart,dataLength){ (offset===void 0)&& (offset=0); (dataStart===void 0)&& (dataStart=0); (dataLength===void 0)&& (dataLength=0); if (!this._upload) return false; this._upload=false; this._bind(); this._bufferSubData(offset,dataStart,dataLength); return true; } __proto._resizeBuffer=function(nsz,copy){ if (nsz < this._buffer.byteLength) return this; this.memorySize=nsz; if (copy && this._buffer && this._buffer.byteLength > 0){ var newbuffer=new ArrayBuffer(nsz); var n=new Uint8Array(newbuffer); n.set(new Uint8Array(this._buffer),0); this._buffer=newbuffer; }else this._buffer=new ArrayBuffer(nsz); this._checkArrayUse(); this._upload=true; return this; } __proto.append=function(data){ this._upload=true; var byteLen=0,n; byteLen=data.byteLength; if ((data instanceof Uint8Array)){ this._resizeBuffer(this._byteLength+byteLen,true); n=new Uint8Array(this._buffer,this._byteLength); }else if ((data instanceof Uint16Array)){ this._resizeBuffer(this._byteLength+byteLen,true); n=new Uint16Array(this._buffer,this._byteLength); }else if ((data instanceof Float32Array)){ this._resizeBuffer(this._byteLength+byteLen,true); n=new Float32Array(this._buffer,this._byteLength); } n.set(data,0); this._byteLength+=byteLen; this._checkArrayUse(); } /** *附加Uint16Array的数据。数据长度是len。byte的话要*2 *@param data *@param len */ __proto.appendU16Array=function(data,len){ this._resizeBuffer(this._byteLength+len*2,true); var u=new Uint16Array(this._buffer,this._byteLength,len); for (var i=0;i < len;i++){ u[i]=data[i]; } this._byteLength+=len *2; this._checkArrayUse(); } __proto.appendEx=function(data,type){ this._upload=true; var byteLen=0,n; byteLen=data.byteLength; this._resizeBuffer(this._byteLength+byteLen,true); n=new type(this._buffer,this._byteLength); n.set(data,0); this._byteLength+=byteLen; this._checkArrayUse(); } __proto.appendEx2=function(data,type,dataLen,perDataLen){ (perDataLen===void 0)&& (perDataLen=1); this._upload=true; var byteLen=0,n; byteLen=dataLen*perDataLen; this._resizeBuffer(this._byteLength+byteLen,true); n=new type(this._buffer,this._byteLength); var i=0; for (i=0;i < dataLen;i++){ n[i]=data[i]; } this._byteLength+=byteLen; this._checkArrayUse(); } __proto.getBuffer=function(){ return this._buffer; } __proto.setNeedUpload=function(){ this._upload=true; } __proto.getNeedUpload=function(){ return this._upload; } __proto.upload=function(){ var scuess=this._bind_upload(); Buffer._gl.bindBuffer(this._bufferType,null); Buffer._bindActive[this._bufferType]=null; BaseShader.activeShader=null return scuess; } __proto.subUpload=function(offset,dataStart,dataLength){ (offset===void 0)&& (offset=0); (dataStart===void 0)&& (dataStart=0); (dataLength===void 0)&& (dataLength=0); var scuess=this._bind_subUpload(); Buffer._gl.bindBuffer(this._bufferType,null); Buffer._bindActive[this._bufferType]=null; BaseShader.activeShader=null return scuess; } __proto.disposeResource=function(){ _super.prototype.disposeResource.call(this); this._upload=true; this._uploadSize=0; } __proto.clear=function(){ this._byteLength=0; this._upload=true; } __getset(0,__proto,'bufferLength',function(){ return this._buffer.byteLength; }); __getset(0,__proto,'byteLength',null,function(value){ if (this._byteLength===value) return; value <=this._buffer.byteLength || (this._resizeBuffer(value *2+256,true)); this._byteLength=value; }); Buffer2D.__int__=function(gl){ IndexBuffer2D.QuadrangleIB=IndexBuffer2D.create(/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); GlUtils.fillIBQuadrangle(IndexBuffer2D.QuadrangleIB,16); } Buffer2D.FLOAT32=4; Buffer2D.SHORT=2; return Buffer2D; })(Buffer) //class laya.webgl.shader.d2.value.GlowSV extends laya.webgl.shader.d2.value.TextureSV var GlowSV=(function(_super){ function GlowSV(args){ this.u_blurX=false; this.u_color=null; this.u_offset=null; this.u_strength=NaN; this.u_texW=0; this.u_texH=0; GlowSV.__super.call(this,/*laya.webgl.shader.d2.ShaderDefines2D.FILTERGLOW*/0x08| /*laya.webgl.shader.d2.ShaderDefines2D.TEXTURE2D*/0x01); } __class(GlowSV,'laya.webgl.shader.d2.value.GlowSV',_super); var __proto=GlowSV.prototype; __proto.setValue=function(vo){ _super.prototype.setValue.call(this,vo); } __proto.clear=function(){ _super.prototype.clear.call(this); } return GlowSV; })(TextureSV) //class laya.webgl.shader.d2.value.TextSV extends laya.webgl.shader.d2.value.TextureSV var TextSV=(function(_super){ function TextSV(args){ TextSV.__super.call(this,/*laya.webgl.shader.d2.ShaderDefines2D.COLORADD*/0x40); this.defines.add(/*laya.webgl.shader.d2.ShaderDefines2D.COLORADD*/0x40); } __class(TextSV,'laya.webgl.shader.d2.value.TextSV',_super); var __proto=TextSV.prototype; __proto.release=function(){ TextSV.pool[TextSV._length++]=this; this.clear(); } __proto.clear=function(){ _super.prototype.clear.call(this); } TextSV.create=function(){ if (TextSV._length)return TextSV.pool[--TextSV._length]; else return new TextSV(null); } TextSV.pool=[]; TextSV._length=0; return TextSV; })(TextureSV) //class laya.webgl.shader.d2.Shader2X extends laya.webgl.shader.Shader var Shader2X=(function(_super){ function Shader2X(vs,ps,saveName,nameMap){ this._params2dQuick1=null; this._params2dQuick2=null; this._shaderValueWidth=NaN; this._shaderValueHeight=NaN; Shader2X.__super.call(this,vs,ps,saveName,nameMap); } __class(Shader2X,'laya.webgl.shader.d2.Shader2X',_super); var __proto=Shader2X.prototype; __proto.upload2dQuick1=function(shaderValue){ this.upload(shaderValue,this._params2dQuick1 || this._make2dQuick1()); } __proto._make2dQuick1=function(){ if (!this._params2dQuick1){ this.activeResource(); this._params2dQuick1=[]; var params=this._params,one; for (var i=0,n=params.length;i < n;i++){ one=params[i]; if (!Render.isFlash && (one.name==="size" || one.name==="position" || one.name==="texcoord"))continue ; this._params2dQuick1.push(one); } } return this._params2dQuick1; } __proto.disposeResource=function(){ _super.prototype.disposeResource.call(this); this._params2dQuick1=null; this._params2dQuick2=null; } __proto.upload2dQuick2=function(shaderValue){ this.upload(shaderValue,this._params2dQuick2 || this._make2dQuick2()); } __proto._make2dQuick2=function(){ if (!this._params2dQuick2){ this.activeResource(); this._params2dQuick2=[]; var params=this._params,one; for (var i=0,n=params.length;i < n;i++){ one=params[i]; if (!Render.isFlash && (one.name==="size"))continue ; this._params2dQuick2.push(one); } } return this._params2dQuick2; } Shader2X.create=function(vs,ps,saveName,nameMap){ return new Shader2X(vs,ps,saveName,nameMap); } return Shader2X; })(Shader) //class laya.webgl.utils.IndexBuffer2D extends laya.webgl.utils.Buffer2D var IndexBuffer2D=(function(_super){ function IndexBuffer2D(bufferUsage){ this._uint8Array=null; this._uint16Array=null; (bufferUsage===void 0)&& (bufferUsage=/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); IndexBuffer2D.__super.call(this); this._bufferUsage=bufferUsage; this._bufferType=/*laya.webgl.WebGLContext.ELEMENT_ARRAY_BUFFER*/0x8893; Render.isFlash || (this._buffer=new ArrayBuffer(8)); } __class(IndexBuffer2D,'laya.webgl.utils.IndexBuffer2D',_super); var __proto=IndexBuffer2D.prototype; __proto._checkArrayUse=function(){ this._uint8Array && (this._uint8Array=new Uint8Array(this._buffer)); this._uint16Array && (this._uint16Array=new Uint16Array(this._buffer)); } __proto.getUint8Array=function(){ return this._uint8Array || (this._uint8Array=new Uint8Array(this._buffer)); } __proto.getUint16Array=function(){ return this._uint16Array || (this._uint16Array=new Uint16Array(this._buffer)); } __proto.destory=function(){ this._uint16Array=null; this._uint8Array=null; this._buffer=null; } IndexBuffer2D.QuadrangleIB=null; IndexBuffer2D.create=function(bufferUsage){ (bufferUsage===void 0)&& (bufferUsage=/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); return new IndexBuffer2D(bufferUsage); } return IndexBuffer2D; })(Buffer2D) //class laya.webgl.utils.VertexBuffer2D extends laya.webgl.utils.Buffer2D var VertexBuffer2D=(function(_super){ function VertexBuffer2D(vertexStride,bufferUsage){ this._floatArray32=null; this._vertexStride=0; VertexBuffer2D.__super.call(this); this._vertexStride=vertexStride; this._bufferUsage=bufferUsage; this._bufferType=/*laya.webgl.WebGLContext.ARRAY_BUFFER*/0x8892; Render.isFlash || (this._buffer=new ArrayBuffer(8)); this.getFloat32Array(); } __class(VertexBuffer2D,'laya.webgl.utils.VertexBuffer2D',_super); var __proto=VertexBuffer2D.prototype; __proto.getFloat32Array=function(){ return this._floatArray32 || (this._floatArray32=new Float32Array(this._buffer)); } __proto.bind=function(ibBuffer){ (ibBuffer)&& (ibBuffer._bind()); this._bind(); } __proto.insertData=function(data,pos){ var vbdata=this.getFloat32Array(); vbdata.set(data,pos); this._upload=true; } __proto.bind_upload=function(ibBuffer){ (ibBuffer._bind_upload())|| (ibBuffer._bind()); (this._bind_upload())|| (this._bind()); } __proto._checkArrayUse=function(){ this._floatArray32 && (this._floatArray32=new Float32Array(this._buffer)); } __proto.disposeResource=function(){ _super.prototype.disposeResource.call(this); return; var enableAtributes=Buffer._enableAtributes; if (!Render.isConchWebGL){ for (var i=0;i < 10;i++){ WebGL.mainContext.disableVertexAttribArray(i); enableAtributes[i]=null; } } } //} __proto.destory=function(){ this._byteLength=0; this._upload=true; this._buffer=null; this._floatArray32=null; } __getset(0,__proto,'vertexStride',function(){ return this._vertexStride; }); VertexBuffer2D.create=function(vertexStride,bufferUsage){ (bufferUsage===void 0)&& (bufferUsage=/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); return new VertexBuffer2D(vertexStride,bufferUsage); } return VertexBuffer2D; })(Buffer2D) //class laya.webgl.resource.WebGLImage extends laya.resource.HTMLImage var WebGLImage=(function(_super){ function WebGLImage(data,def,format,mipmap){ /**@private */ this._format=0; /**@private */ this._mipmap=false; /***是否创建私有Source,值为false时不根据src创建私有WebGLTexture,同时销毁时也只清空source=null,不调用WebGL.mainContext.deleteTexture类似函数,调用资源激活前有效*/ this._allowMerageInAtlas=false; /**是否允许加入大图合集*/ this._enableMerageInAtlas=false; /**是否使用重复模式纹理寻址*/ this.repeat=false; /**@private */ this._image=null; /**缩小过滤器*/ this.minFifter=0; /**放大过滤器*/ this.magFifter=0; (format===void 0)&& (format=/*laya.webgl.WebGLContext.RGBA*/0x1908); (mipmap===void 0)&& (mipmap=true); WebGLImage.__super.call(this,data,def); this._format=format; this._mipmap=mipmap; this.repeat=false; this.minFifter=-1; this.magFifter=-1; if ((typeof data=='string')){ this._url=data; this._src=data; this._image=new Browser.window.Image(); if (def){ def.onload && (this.onload=def.onload); def.onerror && (this.onerror=def.onerror); def.onCreate && def.onCreate(this); } this._image.crossOrigin=(data && (data.indexOf("data:")==0))? null :""; (data)&& (this._image.src=data); }else if ((data instanceof ArrayBuffer)){ this._src=def; this._url=this._src; var readData=new Byte(data); var magicNumber=readData.readUTFBytes(4); var version=readData.readUTFBytes(2); var dataType=readData.getInt16(); readData.endian=/*laya.utils.Byte.BIG_ENDIAN*/"bigEndian"; this._w=readData.getInt16(); this._h=readData.getInt16(); var originalWidth=readData.getInt16(); var originalHeight=readData.getInt16(); this._image=new Uint8Array(data,readData.pos); this._format=WebGL.compressEtc1.COMPRESSED_RGB_ETC1_WEBGL; (AtlasResourceManager.enabled)&& (this._w < AtlasResourceManager.atlasLimitWidth && this._h < AtlasResourceManager.atlasLimitHeight)? this._allowMerageInAtlas=true :this._allowMerageInAtlas=false; }else { this._src=def; this._url=this._src; this._image=data["source"] || data; this.onresize(); } this._$5__enableMerageInAtlas=true; } __class(WebGLImage,'laya.webgl.resource.WebGLImage',_super); var __proto=WebGLImage.prototype; Laya.imps(__proto,{"laya.webgl.resource.IMergeAtlasBitmap":true}) __proto._init_=function(src,def){} __proto._createWebGlTexture=function(){ if (!this._image){ throw "create GLTextur err:no data:"+this._image; }; var gl=WebGL.mainContext; var glTex=this._source=gl.createTexture(); var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,glTex); if (Render.isConchWebGL){ switch (this._format){ case /*laya.webgl.WebGLContext.RGBA*/0x1908: gl.texImage2DEx(true,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,this._format,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._image); break ; case WebGL.compressEtc1.COMPRESSED_RGB_ETC1_WEBGL: gl.compressedTexImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,this._format,this._w,this._h,0,this._image); break ; } } else { gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,true); switch (this._format){ case /*laya.webgl.WebGLContext.RGBA*/0x1908: gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,this._format,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._image); break ; case WebGL.compressEtc1.COMPRESSED_RGB_ETC1_WEBGL: gl.compressedTexImage2D(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,0,this._format,this._w,this._h,0,this._image); break ; } gl.pixelStorei(/*laya.webgl.WebGLContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL*/0x9241,false); }; var minFifter=this.minFifter; var magFifter=this.magFifter; var repeat=this.repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPot=Arith.isPOT(this._w,this._h); if (isPot){ if (this.mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this.mipmap && gl.generateMipmap(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); this._image.onload=null; this._image=null; if (isPot && this.mipmap) this.memorySize=this._w *this._h *4 *(1+1 / 3); else this.memorySize=this._w *this._h *4; this._recreateLock=false; } /***重新创建资源,如果异步创建中被强制释放再创建,则需等待释放完成后再重新加载创建。*/ __proto.recreateResource=function(){ var _$this=this; if (this._src==null || this._src==="") return; this._needReleaseAgain=false; if (!this._image){ this._recreateLock=true; var _this=this; this._image=new Browser.window.Image(); this._image.crossOrigin=this._src.indexOf("data:")==0 ? null :""; this._image.onload=function (){ if (_this._needReleaseAgain){ _this._needReleaseAgain=false; _this._image.onload=null; _this._image=null; return; } (!(_this._allowMerageInAtlas && _this._enableMerageInAtlas))? (_this._createWebGlTexture()):(_$this.memorySize=0,_$this._recreateLock=false); _this.completeCreate(); }; this._image.src=this._src; }else { if (this._recreateLock){ return; } (!(this._allowMerageInAtlas && this._$5__enableMerageInAtlas))? (this._createWebGlTexture()):(this.memorySize=0,this._recreateLock=false); this.completeCreate(); } } /***销毁资源*/ __proto.disposeResource=function(){ if (this._recreateLock){ this._needReleaseAgain=true; } if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this._image=null; this.memorySize=0; } } /***调整尺寸*/ __proto.onresize=function(){ this._w=this._image.width; this._h=this._image.height; (AtlasResourceManager.enabled)&& (this._w < AtlasResourceManager.atlasLimitWidth && this._h < AtlasResourceManager.atlasLimitHeight)? this._allowMerageInAtlas=true :this._allowMerageInAtlas=false; } __proto.clearAtlasSource=function(){ this._image=null; } /** *获取纹理格式。 */ __getset(0,__proto,'format',function(){ return this._format; }); /** *是否创建私有Source,通常禁止修改 *@param value 是否创建 */ /** *是否创建私有Source *@return 是否创建 */ __getset(0,__proto,'enableMerageInAtlas',function(){ return this._$5__enableMerageInAtlas; },function(value){ this._$5__enableMerageInAtlas=value; }); /** *获取是否具有mipmap。 */ __getset(0,__proto,'mipmap',function(){ return this._mipmap; }); /** *是否创建私有Source *@return 是否创建 */ __getset(0,__proto,'allowMerageInAtlas',function(){ return this._allowMerageInAtlas; }); __getset(0,__proto,'atlasSource',function(){ return this._image; }); /*** *设置onload函数 *@param value onload函数 */ __getset(0,__proto,'onload',null,function(value){ var _$this=this; this._onload=value; this._image && (this._image.onload=this._onload !=null ? (function(){ _$this.onresize(); _$this._onload(); }):null); }); /*** *设置onerror函数 *@param value onerror函数 */ __getset(0,__proto,'onerror',null,function(value){ var _$this=this; this._onerror=value; this._image && (this._image.onerror=this._onerror !=null ? (function(){ _$this._onerror() }):null); }); return WebGLImage; })(HTMLImage) Laya.__init([DrawText,AtlasGrid,WebGLContext2D,ShaderCompile]); })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.wxmini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,RunDriver=laya.utils.RunDriver; var Sound=laya.media.Sound,SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager,URL=laya.net.URL; var Utils=laya.utils.Utils; //class laya.wx.mini.MiniAdpter var MiniAdpter=(function(){ function MiniAdpter(){} __class(MiniAdpter,'laya.wx.mini.MiniAdpter'); MiniAdpter.getJson=function(data){ return JSON.parse(data); } MiniAdpter.init=function(isPosMsg,isSon){ (isPosMsg===void 0)&& (isPosMsg=false); (isSon===void 0)&& (isSon=false); if (MiniAdpter._inited)return; MiniAdpter._inited=true; MiniAdpter.window=/*__JS__ */window; if(!MiniAdpter.window.hasOwnProperty("wx")) return; if(MiniAdpter.window.navigator.userAgent.indexOf('MiniGame')<0)return; MiniAdpter.isZiYu=isSon; MiniAdpter.isPosMsgYu=isPosMsg; MiniAdpter.EnvConfig={}; try{ /*__JS__ */laya.webgl.resource.WebGLCanvas.premulAlpha=true; }catch(e){ } if(!MiniAdpter.isZiYu){ MiniFileMgr.setNativeFileDir("/layaairGame"); MiniFileMgr.existDir(MiniFileMgr.fileNativeDir,Handler.create(MiniAdpter,MiniAdpter.onMkdirCallBack)); } MiniAdpter.systemInfo=MiniAdpter.window.wx.getSystemInfoSync(); if (MiniAdpter.systemInfo.system.toLowerCase()==='ios 10.1.1'){ try{ /*__JS__ */laya.webgl.resource.WebGLCharImage.canUseCanvas=false; }catch(e){ } } MiniAdpter.window.focus=function (){ }; Laya['_getUrlPath']=function (){ }; Laya['getUrlPath']=function (){ }; MiniAdpter.window.logtime=function (str){ }; MiniAdpter.window.alertTimeLog=function (str){ }; MiniAdpter.window.resetShareInfo=function (){ }; MiniAdpter.window.CanvasRenderingContext2D=function (){ }; MiniAdpter.window.CanvasRenderingContext2D.prototype=MiniAdpter.window.wx.createCanvas().getContext('2d').__proto__; MiniAdpter.window.document.body.appendChild=function (){ }; MiniAdpter.EnvConfig.pixelRatioInt=0; RunDriver.getPixelRatio=MiniAdpter.pixelRatio; MiniAdpter._preCreateElement=Browser.createElement; Browser["createElement"]=MiniAdpter.createElement; RunDriver.createShaderCondition=MiniAdpter.createShaderCondition; Utils['parseXMLFromString']=MiniAdpter.parseXMLFromString; Input['_createInputElement']=MiniInput['_createInputElement']; MiniAdpter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader.prototype.load; Loader.prototype._loadImage=MiniImage.prototype._loadImage; LocalStorage._baseClass=MiniLocalStorage; MiniLocalStorage.__init__(); MiniAdpter.onReciveData(); } MiniAdpter.onReciveData=function(){ if(laya.wx.mini.MiniAdpter.isZiYu){ MiniAdpter.window.wx.onMessage(function(message){ if(message['isLoad']=="opendatacontext"){ if(message.url){ MiniFileMgr.ziyuFileData[message.url]=message.atlasdata; MiniFileMgr.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }else if(message['isLoad']=="openJsondatacontext"){ if(message.url){ MiniFileMgr.ziyuFileData[message.url]=message.atlasdata; } }else if(message['isLoad']=="openJsondatacontextPic"){ MiniFileMgr.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }); } } MiniAdpter.measureText=function(str){ var tempObj=MiniAdpter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } MiniAdpter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return ""; return "utf8"; } MiniAdpter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } MiniAdpter.remove=function(fileUrl,callBack){ MiniFileMgr.deleteFile("",fileUrl,callBack,"",0); } MiniAdpter.removeAll=function(){ MiniFileMgr.deleteAll(); } MiniAdpter.hasNativeFile=function(fileUrl){ return MiniFileMgr.isLocalNativeFile(fileUrl); } MiniAdpter.getFileInfo=function(fileUrl){ return MiniFileMgr.getFileInfo(fileUrl); } MiniAdpter.getFileList=function(){ return MiniFileMgr.filesListObj; } MiniAdpter.exitMiniProgram=function(){ MiniAdpter.window.wx.exitMiniProgram(); } MiniAdpter.onMkdirCallBack=function(errorCode,data){ if (!errorCode){ MiniFileMgr.filesListObj=JSON.parse(data.data); MiniFileMgr.fakeObj=JSON.parse(data.data); } } MiniAdpter.pixelRatio=function(){ if (!MiniAdpter.EnvConfig.pixelRatioInt){ try { MiniAdpter.EnvConfig.pixelRatioInt=MiniAdpter.systemInfo.pixelRatio; return MiniAdpter.systemInfo.pixelRatio; }catch (error){} } return MiniAdpter.EnvConfig.pixelRatioInt; } MiniAdpter.createElement=function(type){ if (type=="canvas"){ var _source; if (MiniAdpter.idx==1){ if(MiniAdpter.isZiYu){ _source=MiniAdpter.window.sharedCanvas; _source.style={}; }else{ _source=MiniAdpter.window.canvas; } }else { _source=MiniAdpter.window.wx.createCanvas(); } MiniAdpter.idx++; return _source; }else if (type=="textarea" || type=="input"){ return MiniAdpter.onCreateInput(type); }else if (type=="div"){ var node=MiniAdpter._preCreateElement(type); node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } else { return MiniAdpter._preCreateElement(type); } } MiniAdpter.onCreateInput=function(type){ var node=MiniAdpter._preCreateElement(type); node.focus=MiniInput.wxinputFocus; node.blur=MiniInput.wxinputblur; node.style={}; node.value=0; node.parentElement={}; node.placeholder={}; node.type={}; node.setColor=function (value){ }; node.setType=function (value){ }; node.setFontFace=function (value){ }; node.addEventListener=function (value){ }; node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } MiniAdpter.createShaderCondition=function(conditionScript){ var _$this=this; var func=function (){ var abc=conditionScript; return _$this[conditionScript.replace("this.","")]; } return func; } MiniAdpter.sendAtlasToOpenDataContext=function(url){ if(!laya.wx.mini.MiniAdpter.isZiYu){ var atlasJson=Loader.getRes(URL.formatURL(url)); if(atlasJson){ var textureArr=(atlasJson.meta.image).split(","); if (atlasJson.meta && atlasJson.meta.image){ var toloadPics=atlasJson.meta.image.split(","); var split=url.indexOf("/")>=0 ? "/" :"\\"; var idx=url.lastIndexOf(split); var folderPath=idx >=0 ? url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[url.replace(".json",".png")]; } for(i=0;i\s+<'); try { /*__JS__ */rst=(new window.Parser.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } MiniAdpter.idx=1; __static(MiniAdpter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir","wxlocal"];} ]); return MiniAdpter; })() /**@private **/ //class laya.wx.mini.MiniFileMgr var MiniFileMgr=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.wx.mini.MiniFileMgr'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=MiniAdpter.nativefiles.length;i=totalSize)){ if(data.size > MiniAdpter.minClearSize) MiniAdpter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > MiniAdpter.minClearSize) MiniAdpter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=MiniAdpter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.wx.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i *
  • 1.0 正常速度
  • *
  • 0.5 半速(更慢)
  • *
  • 2.0 倍速(更快)
  • *
  • -1.0 向后,正常速度
  • *
  • -0.5 向后,半速
  • * *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ __getset(0,__proto,'playbackRate',function(){ if(!this.videoElement) return 0; return this.videoElement.playbackRate; },function(value){ if(!this.videoElement) return; this.videoElement.playbackRate=value; }); __getset(0,__proto,'x',function(){ if(!this.videoElement) return 0; return this.videoElement.x; },function(value){ if(!this.videoElement) return; this.videoElement.x=value; }); __getset(0,__proto,'y',function(){ if(!this.videoElement) return 0; return this.videoElement.y; },function(value){ if(!this.videoElement) return; this.videoElement.y=value; }); /** *获取当前播放源路径。 */ __getset(0,__proto,'currentSrc',function(){ return this.videoElement.src; }); MiniVideo.__init__=function(){ /*__JS__ */laya.device.media.Video=MiniVideo; } return MiniVideo; })() /**@private **/ //class laya.wx.mini.MiniAccelerator extends laya.events.EventDispatcher var MiniAccelerator=(function(_super){ function MiniAccelerator(){ MiniAccelerator.__super.call(this); } __class(MiniAccelerator,'laya.wx.mini.MiniAccelerator',_super); var __proto=MiniAccelerator.prototype; /** *侦听加速器运动。 *@param observer 回调函数接受4个参数,见类说明。 */ __proto.on=function(type,caller,listener,args){ _super.prototype.on.call(this,type,caller,listener,args); MiniAccelerator.startListen(this["onDeviceOrientationChange"]); return this; } /** *取消侦听加速器。 *@param handle 侦听加速器所用处理器。 */ __proto.off=function(type,caller,listener,onceOnly){ (onceOnly===void 0)&& (onceOnly=false); if (!this.hasListener(type)) MiniAccelerator.stopListen(); return _super.prototype.off.call(this,type,caller,listener,onceOnly); } MiniAccelerator.__init__=function(){ try{ var Acc; Acc=/*__JS__ */laya.device.motion.Accelerator; if (!Acc)return; Acc["prototype"]["on"]=MiniAccelerator["prototype"]["on"]; Acc["prototype"]["off"]=MiniAccelerator["prototype"]["off"]; }catch (e){ } } MiniAccelerator.startListen=function(callBack){ MiniAccelerator._callBack=callBack; if (MiniAccelerator._isListening)return; MiniAccelerator._isListening=true; try{ MiniAdpter.window.wx.onAccelerometerChange(laya.wx.mini.MiniAccelerator.onAccelerometerChange); }catch(e){} } MiniAccelerator.stopListen=function(){ MiniAccelerator._isListening=false; try{ MiniAdpter.window.wx.stopAccelerometer({}); }catch(e){} } MiniAccelerator.onAccelerometerChange=function(res){ var e; e={}; e.acceleration=res; e.accelerationIncludingGravity=res; e.rotationRate={}; if (MiniAccelerator._callBack !=null){ MiniAccelerator._callBack(e); } } MiniAccelerator._isListening=false; MiniAccelerator._callBack=null; return MiniAccelerator; })(EventDispatcher) /**@private **/ //class laya.wx.mini.MiniLoader extends laya.events.EventDispatcher var MiniLoader=(function(_super){ function MiniLoader(){ MiniLoader.__super.call(this); } __class(MiniLoader,'laya.wx.mini.MiniLoader',_super); var __proto=MiniLoader.prototype; /** *@private *@param url *@param type *@param cache *@param group *@param ignoreCache */ __proto.load=function(url,type,cache,group,ignoreCache){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); var thisLoader=this; thisLoader._url=url; if (url.indexOf("data:image")===0)thisLoader._type=type=/*laya.net.Loader.IMAGE*/"image"; else { thisLoader._type=type || (type=thisLoader.getTypeFromUrl(url)); } thisLoader._cache=cache; thisLoader._data=null; if (!ignoreCache && Loader.loadedMap[URL.formatURL(url)]){ thisLoader._data=Loader.loadedMap[URL.formatURL(url)]; this.event(/*laya.events.Event.PROGRESS*/"progress",1); this.event(/*laya.events.Event.COMPLETE*/"complete",thisLoader._data); return; } if (Loader.parserMap[type] !=null){ thisLoader._customParse=true; if (((Loader.parserMap[type])instanceof laya.utils.Handler ))Loader.parserMap[type].runWith(this); else Loader.parserMap[type].call(null,this); return; }; var encoding=MiniAdpter.getUrlEncode(url,type); var urlType=Utils.getFileExtension(url); if ((MiniLoader._fileTypeArr.indexOf(urlType)!=-1)|| type==/*laya.net.Loader.IMAGE*/"image"){ MiniAdpter.EnvConfig.load.call(this,url,type,cache,group,ignoreCache); }else { if(MiniAdpter.isZiYu && !MiniFileMgr.ziyuFileData[url]){ url=URL.formatURL(url); } if(MiniAdpter.isZiYu && MiniFileMgr.ziyuFileData[url]){ var tempData=MiniFileMgr.ziyuFileData[url]; thisLoader.onLoaded(tempData); return; } if (!MiniFileMgr.getFileInfo(URL.formatURL(url))){ if (MiniFileMgr.isLocalNativeFile(url)){ if (MiniAdpter.subNativeFiles && MiniAdpter.subNativeheads.length==0){ for (var key in MiniAdpter.subNativeFiles){ var tempArr=MiniAdpter.subNativeFiles[key]; MiniAdpter.subNativeheads=MiniAdpter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ MiniAdpter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(MiniAdpter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && MiniAdpter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=MiniAdpter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } if(type==/*laya.net.Loader.SOUND*/"sound"){ thisLoader._loadSound(url); }else{ MiniFileMgr.read(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader])); } return; }; var tempUrl=url; var tempurl=URL.formatURL(url); if (tempurl.indexOf(MiniAdpter.window.wx.env.USER_DATA_PATH)==-1 &&(url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)&& !MiniAdpter.AutoCacheDownFile){ if(type==/*laya.net.Loader.SOUND*/"sound"){ thisLoader._loadSound(url); }else{ MiniAdpter.EnvConfig.load.call(thisLoader,tempUrl,type,cache,group,ignoreCache); } }else { fileObj=MiniFileMgr.getFileInfo(url); if(fileObj){ fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; MiniFileMgr.readFile(fileObj.url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else if (thisLoader.type=="image" || thisLoader.type=="htmlimage"){ MiniAdpter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } else{ url=URL.formatURL(url); if(type !=/*laya.net.Loader.IMAGE*/"image" && ((url.indexOf("http://")==-1 && url.indexOf("https://")==-1)|| MiniFileMgr.isLocalNativeFile(url))){ MiniFileMgr.readFile(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url); }else{ MiniFileMgr.downFiles(url,encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),url,true); } } } }else { var fileObj=MiniFileMgr.getFileInfo(URL.formatURL(url)); fileObj.encoding=fileObj.encoding==null ? "utf8" :fileObj.encoding; var nativepath=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.readFile(nativepath,fileObj.encoding,new Handler(MiniLoader,MiniLoader.onReadNativeCallBack,[encoding,url,type,cache,group,ignoreCache,thisLoader]),URL.formatURL(url)); } } } /** *private *@param url **/ __proto._loadSound=function(url){ var thisLoader=this; var fileNativeUrl; if (MiniFileMgr.isLocalNativeFile(url)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="" && (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1)) fileNativeUrl=url.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } laya.wx.mini.MiniLoader.onDownLoadCallBack(url,thisLoader,0); }else{ var tempurl=URL.formatURL(url); if (!MiniFileMgr.isLocalNativeFile(url)&& (tempurl.indexOf("http://")==-1 && tempurl.indexOf("https://")==-1)|| (tempurl.indexOf(MiniAdpter.window.wx.env.USER_DATA_PATH)!=-1)){ laya.wx.mini.MiniLoader.onDownLoadCallBack(url,thisLoader,0); }else{ MiniFileMgr.downOtherFiles(encodeURI(tempurl),Handler.create(MiniLoader,laya.wx.mini.MiniLoader.onDownLoadCallBack,[tempurl,thisLoader]),tempurl); } } } MiniLoader.onDownLoadCallBack=function(sourceUrl,thisLoader,errorCode,tempFilePath){ if (!errorCode){ var fileNativeUrl; if(MiniAdpter.autoCacheFile){ if(!tempFilePath){ if (MiniFileMgr.isLocalNativeFile(sourceUrl)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=sourceUrl; if(tempStr !="" && (sourceUrl.indexOf("http://")!=-1 || sourceUrl.indexOf("https://")!=-1)) fileNativeUrl=sourceUrl.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } }else{ var fileObj=MiniFileMgr.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=sourceUrl; } } }else{ fileNativeUrl=tempFilePath; } } sourceUrl=fileNativeUrl; var sound=new SoundManager._soundClass(); sound.load(encodeURI(sourceUrl)); thisLoader.onLoaded(sound); }else{ thisLoader.event(/*laya.events.Event.ERROR*/"error","Load sound failed"); } } MiniLoader.onReadNativeCallBack=function(encoding,url,type,cache,group,ignoreCache,thisLoader,errorCode,data){ (cache===void 0)&& (cache=true); (ignoreCache===void 0)&& (ignoreCache=false); (errorCode===void 0)&& (errorCode=0); if (!errorCode){ var tempData; if (type==/*laya.net.Loader.JSON*/"json" || type==/*laya.net.Loader.ATLAS*/"atlas"){ tempData=MiniAdpter.getJson(data.data); }else if (type==/*laya.net.Loader.XML*/"xml"){ tempData=Utils.parseXMLFromString(data.data); }else { tempData=data.data; } if(!MiniAdpter.isZiYu &&MiniAdpter.isPosMsgYu && type !=/*laya.net.Loader.BUFFER*/"arraybuffer" && MiniAdpter.window.wx){ MiniAdpter.window.wx.postMessage({url:url,data:tempData,isLoad:"filedata"}); } thisLoader.onLoaded(tempData); }else if (errorCode==1){ console.log("-----------本地加载失败,尝试外网加载----url:"+url); MiniAdpter.EnvConfig.load.call(thisLoader,url,type,cache,group,ignoreCache); } } __static(MiniLoader, ['_fileTypeArr',function(){return this._fileTypeArr=['png','jpg','bmp','jpeg','gif'];} ]); return MiniLoader; })(EventDispatcher) /**@private **/ //class laya.wx.mini.MiniSound extends laya.events.EventDispatcher var MiniSound=(function(_super){ function MiniSound(){ /**@private **/ this._sound=null; /** *@private *声音URL */ this.url=null; /** *@private *是否已加载完成 */ this.loaded=false; /**@private **/ this.readyUrl=null; MiniSound.__super.call(this); } __class(MiniSound,'laya.wx.mini.MiniSound',_super); var __proto=MiniSound.prototype; /** *@private *加载声音。 *@param url 地址。 * */ __proto.load=function(url){ if (!MiniFileMgr.isLocalNativeFile(url)){ url=URL.formatURL(url); }else{ if (url.indexOf("http://")!=-1 || url.indexOf("https://")!=-1){ if(MiniFileMgr.loadPath !=""){ url=url.split(MiniFileMgr.loadPath)[1]; }else{ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; if(tempStr !="") url=url.split(tempStr)[1]; } } } this.url=url; this.readyUrl=url; if (MiniSound._audioCache[this.readyUrl]){ this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if(MiniAdpter.autoCacheFile&&MiniFileMgr.getFileInfo(url)){ this.onDownLoadCallBack(url,0); }else{ if(!MiniAdpter.autoCacheFile){ this.onDownLoadCallBack(url,0); }else{ if (MiniFileMgr.isLocalNativeFile(url)){ tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=url; if(tempStr !="") url=url.split(tempStr)[1]; if (!url){ url=tempUrl; } if (MiniAdpter.subNativeFiles && MiniAdpter.subNativeheads.length==0){ for (var key in MiniAdpter.subNativeFiles){ var tempArr=MiniAdpter.subNativeFiles[key]; MiniAdpter.subNativeheads=MiniAdpter.subNativeheads.concat(tempArr); for (var aa=0;aa < tempArr.length;aa++){ MiniAdpter.subMaps[tempArr[aa]]=key+"/"+tempArr[aa]; } } } if(MiniAdpter.subNativeFiles && url.indexOf("/")!=-1){ var curfileHead=url.split("/")[0]+"/"; if(curfileHead && MiniAdpter.subNativeheads.indexOf(curfileHead)!=-1){ var newfileHead=MiniAdpter.subMaps[curfileHead]; url=url.replace(curfileHead,newfileHead); } } this.onDownLoadCallBack(url,0); }else{ MiniFileMgr.downOtherFiles(encodeURI(url),Handler.create(this,this.onDownLoadCallBack,[url]),url); } } } } /**@private **/ __proto.onDownLoadCallBack=function(sourceUrl,errorCode){ if (!errorCode){ var fileNativeUrl; if(MiniAdpter.autoCacheFile){ if (MiniFileMgr.isLocalNativeFile(sourceUrl)){ var tempStr=URL.rootPath !="" ? URL.rootPath :URL.basePath; var tempUrl=sourceUrl; if(tempStr !="" && (sourceUrl.indexOf("http://")!=-1 || sourceUrl.indexOf("https://")!=-1)) fileNativeUrl=sourceUrl.split(tempStr)[1]; if(!fileNativeUrl){ fileNativeUrl=tempUrl; } }else{ var fileObj=MiniFileMgr.getFileInfo(sourceUrl); if(fileObj && fileObj.md5){ var fileMd5Name=fileObj.md5; fileNativeUrl=MiniFileMgr.getFileNativePath(fileMd5Name); }else{ fileNativeUrl=encodeURI(sourceUrl); } } this._sound=MiniSound._createSound(); this._sound.src=this.url=fileNativeUrl; }else{ this._sound=MiniSound._createSound(); this._sound.src=encodeURI(sourceUrl); } this._sound.onCanplay(MiniSound.bindToThis(this.onCanPlay,this)); this._sound.onError(MiniSound.bindToThis(this.onError,this)); }else{ this.event(/*laya.events.Event.ERROR*/"error"); } } /**@private **/ __proto.onError=function(error){ this.event(/*laya.events.Event.ERROR*/"error"); this._sound.offError(null); } /**@private **/ __proto.onCanPlay=function(){ this.loaded=true; this.event(/*laya.events.Event.COMPLETE*/"complete"); this._sound.offCanplay(null); } /** *@private *播放声音。 *@param startTime 开始时间,单位秒 *@param loops 循环次数,0表示一直循环 *@return 声道 SoundChannel 对象。 * */ __proto.play=function(startTime,loops){ (startTime===void 0)&& (startTime=0); (loops===void 0)&& (loops=0); var tSound; if (this.url==SoundManager._tMusic){ if (!MiniSound._musicAudio)MiniSound._musicAudio=MiniSound._createSound(); tSound=MiniSound._musicAudio; }else { if(MiniSound._audioCache[this.readyUrl]){ tSound=MiniSound._audioCache[this.readyUrl]._sound; }else{ tSound=MiniSound._createSound(); } } if(MiniAdpter.autoCacheFile&&MiniFileMgr.getFileInfo(this.url)){ var fileNativeUrl; var fileObj=MiniFileMgr.getFileInfo(this.url); var fileMd5Name=fileObj.md5; tSound.src=this.url=MiniFileMgr.getFileNativePath(fileMd5Name); }else{ tSound.src=encodeURI(this.url); }; var channel=new MiniSoundChannel(tSound,this); channel.url=this.url; channel.loops=loops; channel.loop=(loops===0 ? true :false); channel.startTime=startTime; channel.play(); SoundManager.addChannel(channel); return channel; } /** *@private *释放声音资源。 * */ __proto.dispose=function(){ var ad=MiniSound._audioCache[this.readyUrl]; if (ad){ ad.src=""; if(ad._sound){ ad._sound.destroy(); ad._sound=null; ad=null; } delete MiniSound._audioCache[this.readyUrl]; } if(this._sound){ this._sound.destroy(); this._sound=null; } this.url=this.readyUrl=null; } /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ return this._sound.duration; }); MiniSound._createSound=function(){ MiniSound._id++; return MiniAdpter.window.wx.createInnerAudioContext(); } MiniSound.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } MiniSound._musicAudio=null; MiniSound._id=0; MiniSound._audioCache={}; return MiniSound; })(EventDispatcher) /**@private **/ //class laya.wx.mini.MiniSoundChannel extends laya.media.SoundChannel var MiniSoundChannel=(function(_super){ function MiniSoundChannel(audio,miniSound){ /**@private **/ this._audio=null; /**@private **/ this._onEnd=null; /**@private **/ this._miniSound=null; MiniSoundChannel.__super.call(this); this._audio=audio; this._miniSound=miniSound; this._onEnd=MiniSoundChannel.bindToThis(this.__onEnd,this); audio.onEnded(this._onEnd); } __class(MiniSoundChannel,'laya.wx.mini.MiniSoundChannel',_super); var __proto=MiniSoundChannel.prototype; /**@private **/ __proto.__onEnd=function(){ if (this.loops==1){ if (this.completeHandler){ Laya.timer.once(10,this,this.__runComplete,[this.completeHandler],false); this.completeHandler=null; } this.stop(); this.event(/*laya.events.Event.COMPLETE*/"complete"); return; } if (this.loops > 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.stop(); this._audio.offEnded(null); this._audio.destroy(); this._audio=null; this._miniSound=null; this._onEnd=null; } /**@private **/ __proto.pause=function(){ this.isStopped=true; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',null,function(time){ if(this._audio){ this._audio.startTime=time; } }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ return this._audio.autoplay; },function(value){ this._audio.autoplay=value; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ return this._audio.loop; },function(value){ this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/laya.xmmini.js ================================================ (function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var Browser=laya.utils.Browser,Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher; var HTMLImage=laya.resource.HTMLImage,Handler=laya.utils.Handler,Input=laya.display.Input,Loader=laya.net.Loader; var LocalStorage=laya.net.LocalStorage,Matrix=laya.maths.Matrix,Render=laya.renders.Render,RunDriver=laya.utils.RunDriver; var SoundChannel=laya.media.SoundChannel,SoundManager=laya.media.SoundManager,URL=laya.net.URL,Utils=laya.utils.Utils; //class laya.mi.mini.KGMiniAdapter var KGMiniAdapter=(function(){ function KGMiniAdapter(){} __class(KGMiniAdapter,'laya.mi.mini.KGMiniAdapter'); KGMiniAdapter.getJson=function(data){ return JSON.parse(data); } KGMiniAdapter.init=function(isPosMsg,isSon){ (isPosMsg===void 0)&& (isPosMsg=false); (isSon===void 0)&& (isSon=false); if (KGMiniAdapter._inited)return; KGMiniAdapter._inited=true; KGMiniAdapter.window=/*__JS__ */window; if(KGMiniAdapter.window.navigator.userAgent.indexOf('QuickGame')<0)return; KGMiniAdapter.isZiYu=isSon; KGMiniAdapter.isPosMsgYu=isPosMsg; KGMiniAdapter.EnvConfig={}; if(!KGMiniAdapter.isZiYu){ MiniFileMgr$2.setNativeFileDir("/layaairGame"); MiniFileMgr$2.existDir(MiniFileMgr$2.fileNativeDir,Handler.create(KGMiniAdapter,KGMiniAdapter.onMkdirCallBack)); } if(!KGMiniAdapter.isZiYu){ KGMiniAdapter.systemInfo=laya.mi.mini.KGMiniAdapter.window.qg.getSystemInfoSync(); } KGMiniAdapter.window.focus=function (){ }; Laya['getUrlPath']=function (){ }; Laya['_getUrlPath']=function (){ }; KGMiniAdapter.window.logtime=function (str){ }; KGMiniAdapter.window.alertTimeLog=function (str){ }; KGMiniAdapter.window.resetShareInfo=function (){ }; KGMiniAdapter.EnvConfig.pixelRatioInt=0; RunDriver.getPixelRatio=KGMiniAdapter.pixelRatio; KGMiniAdapter._preCreateElement=Browser.createElement; Browser["createElement"]=KGMiniAdapter.createElement; RunDriver.createShaderCondition=KGMiniAdapter.createShaderCondition; Utils['parseXMLFromString']=KGMiniAdapter.parseXMLFromString; Input['_createInputElement']=MiniInput$2['_createInputElement']; KGMiniAdapter.EnvConfig.load=Loader.prototype.load; Loader.prototype.load=MiniLoader$2.prototype.load; Loader.prototype._loadImage=MiniImage$2.prototype._loadImage; KGMiniAdapter.onReciveData(); } KGMiniAdapter.onReciveData=function(){ if(laya.mi.mini.KGMiniAdapter.isZiYu && laya.mi.mini.KGMiniAdapter.window.qg.onMessage){ laya.mi.mini.KGMiniAdapter.window.qg.onMessage(function(message){ if(message['isLoad']=="opendatacontext"){ if(message.url){ MiniFileMgr$2.ziyuFileData[message.url]=message.atlasdata; MiniFileMgr$2.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }else if(message['isLoad']=="openJsondatacontext"){ if(message.url){ MiniFileMgr$2.ziyuFileData[message.url]=message.atlasdata; } }else if(message['isLoad']=="openJsondatacontextPic"){ MiniFileMgr$2.ziyuFileTextureData[message.imgReadyUrl]=message.imgNativeUrl; } }); } } KGMiniAdapter.measureText=function(str){ var tempObj=KGMiniAdapter._measureText(str); if(!tempObj){ tempObj={width:16}; console.warn("-------微信获取文字宽度失败----等待修复---------"); } return tempObj; } KGMiniAdapter.getUrlEncode=function(url,type){ if(type=="arraybuffer") return ""; return "utf8"; } KGMiniAdapter.downLoadFile=function(fileUrl,fileType,callBack,encoding){ (fileType===void 0)&& (fileType=""); (encoding===void 0)&& (encoding="utf8"); var fileObj=MiniFileMgr$2.getFileInfo(fileUrl); if(!fileObj) MiniFileMgr$2.downLoadFile(fileUrl,fileType,callBack,encoding); else{ callBack !=null && callBack.runWith([0]); } } KGMiniAdapter.remove=function(fileUrl,callBack){ MiniFileMgr$2.deleteFile("",fileUrl,callBack,"",0); } KGMiniAdapter.removeAll=function(){ MiniFileMgr$2.deleteAll(); } KGMiniAdapter.hasNativeFile=function(fileUrl){ return MiniFileMgr$2.isLocalNativeFile(fileUrl); } KGMiniAdapter.getFileInfo=function(fileUrl){ return MiniFileMgr$2.getFileInfo(fileUrl); } KGMiniAdapter.getFileList=function(){ return MiniFileMgr$2.filesListObj; } KGMiniAdapter.exitMiniProgram=function(){ laya.mi.mini.KGMiniAdapter.window.qg.exitMiniProgram(); } KGMiniAdapter.onMkdirCallBack=function(errorCode,data){ if (!errorCode) MiniFileMgr$2.filesListObj=JSON.parse(data.data); } KGMiniAdapter.pixelRatio=function(){ if (!KGMiniAdapter.EnvConfig.pixelRatioInt){ try { KGMiniAdapter.EnvConfig.pixelRatioInt=KGMiniAdapter.systemInfo.pixelRatio; return KGMiniAdapter.systemInfo.pixelRatio; }catch (error){} } return KGMiniAdapter.EnvConfig.pixelRatioInt; } KGMiniAdapter.createElement=function(type){ if (type=="canvas"){ var _source; if (KGMiniAdapter.idx==1){ if(KGMiniAdapter.isZiYu){ _source=KGMiniAdapter.window.document.createElement("canvas"); _source.style={}; }else{ _source=KGMiniAdapter.window.document.getElementById("canvas"); _source.style={ width:_source.width+"px", height:_source.height+"px" }; } }else { _source=KGMiniAdapter.window.document.createElement("canvas"); } KGMiniAdapter.idx++; return _source; }else if (type=="textarea" || type=="input"){ return KGMiniAdapter.onCreateInput(type); }else if (type=="div"){ var node=KGMiniAdapter._preCreateElement(type); node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; }else { return KGMiniAdapter._preCreateElement(type); } } KGMiniAdapter.onCreateInput=function(type){ var node=KGMiniAdapter._preCreateElement(type); node.focus=MiniInput$2.wxinputFocus; node.blur=MiniInput$2.wxinputblur; node.style={}; node.value=0; node.placeholder={}; node.setColor=function (value){ }; node.setType=function (value){ }; node.setFontFace=function (value){ }; node.addEventListener=function (value){ }; node.contains=function (value){ return null }; node.removeChild=function (value){ }; return node; } KGMiniAdapter.createShaderCondition=function(conditionScript){ var _$this=this; var func=function (){ var abc=conditionScript; return _$this[conditionScript.replace("this.","")]; } return func; } KGMiniAdapter.sendAtlasToOpenDataContext=function(url){ if(!laya.mi.mini.KGMiniAdapter.isZiYu){ var atlasJson=Loader.getRes(URL.formatURL(url)); if(atlasJson){ var textureArr=(atlasJson.meta.image).split(","); if (atlasJson.meta && atlasJson.meta.image){ var toloadPics=atlasJson.meta.image.split(","); var split=url.indexOf("/")>=0 ? "/" :"\\"; var idx=url.lastIndexOf(split); var folderPath=idx >=0 ? url.substr(0,idx+1):""; for (var i=0,len=toloadPics.length;i < len;i++){ toloadPics[i]=folderPath+toloadPics[i]; } }else { toloadPics=[url.replace(".json",".png")]; } for(i=0;i\s+<'); try { /*__JS__ */rst=(new window.Parser.DOMParser()).parseFromString(value,'text/xml'); }catch (error){ throw "需要引入xml解析库文件"; } return rst; } KGMiniAdapter.idx=1; __static(KGMiniAdapter, ['nativefiles',function(){return this.nativefiles=["layaNativeDir","wxlocal"];} ]); return KGMiniAdapter; })() /**@private **/ //class laya.mi.mini.MiniFileMgr var MiniFileMgr$2=(function(){ function MiniFileMgr(){} __class(MiniFileMgr,'laya.mi.mini.MiniFileMgr',null,'MiniFileMgr$2'); MiniFileMgr.isLocalNativeFile=function(url){ for(var i=0,sz=KGMiniAdapter.nativefiles.length;i=totalSize)){ if(data.size > KGMiniAdapter.minClearSize) KGMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } MiniFileMgr.deleteFile(tempFilePath,readyUrl,callBack,encoding,data.size); }, fail:function (data){ console.log("=1==getFileInfo fail data:"+JSON.stringify(data)); callBack !=null && callBack.runWith([1,data]); } }); } else callBack !=null && callBack.runWith([0]); }else{ MiniFileMgr.fs.getFileInfo({ filePath:tempFilePath, success:function (data){ if((isAutoClear && (fileUseSize+chaSize+data.size)>=totalSize)){ if(data.size > KGMiniAdapter.minClearSize) KGMiniAdapter.minClearSize=data.size; MiniFileMgr.onClearCacheRes(); } console.log("=====tempFilePath:"+tempFilePath+"===saveFilePath:"+saveFilePath); MiniFileMgr.fs.copyFile({srcPath:tempFilePath,destPath:saveFilePath,success:function (data2){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,true,encoding,callBack,data.size); },fail:function (data){ console.log("===copyFile fail data:"+JSON.stringify(data)); callBack !=null && callBack.runWith([1,data]); }}); }, fail:function (data){ console.log("=2==getFileInfo fail data:"+JSON.stringify(data)); callBack !=null && callBack.runWith([1,data]); } }); } } MiniFileMgr.onClearCacheRes=function(){ var memSize=KGMiniAdapter.minClearSize; var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } MiniFileMgr.sortOn(tempFileListArr,"times",16); var clearSize=0; for(var i=1,sz=tempFileListArr.length;i=memSize) break ; clearSize+=fileObj.size; MiniFileMgr.deleteFile("",fileObj.readyUrl); } } MiniFileMgr.sortOn=function(array,name,options){ (options===void 0)&& (options=0); if (options==16)return array.sort(function(a,b){return a[name]-b[name];}); if (options==(16 | 2))return array.sort(function(a,b){return b[name]-a[name];}); return array.sort(function(a,b){return a[name]-b[name] }); } MiniFileMgr.getFileNativePath=function(fileName){ return laya.mi.mini.MiniFileMgr.fileNativeDir+"/"+fileName; } MiniFileMgr.deleteFile=function(tempFileName,readyUrl,callBack,encoding,fileSize){ (readyUrl===void 0)&& (readyUrl=""); (encoding===void 0)&& (encoding=""); (fileSize===void 0)&& (fileSize=0); var fileObj=MiniFileMgr.getFileInfo(readyUrl); var deleteFileUrl=MiniFileMgr.getFileNativePath(fileObj.md5); MiniFileMgr.fs.unlink({filePath:deleteFileUrl,success:function (data){ var isAdd=tempFileName !="" ? true :false; if(tempFileName !=""){ var saveFilePath=MiniFileMgr.getFileNativePath(tempFileName); MiniFileMgr.fs.copyFile({srcPath:tempFileName,destPath:saveFilePath,success:function (data){ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,data.size); },fail:function (data){ callBack !=null && callBack.runWith([1,data]); }}); }else{ MiniFileMgr.onSaveFile(readyUrl,tempFileName,isAdd,encoding,callBack,fileSize); } },fail:function (data){ }}); } MiniFileMgr.deleteAll=function(){ var tempFileListArr=[]; for(var key in MiniFileMgr.filesListObj){ if(key!="fileUsedSize") tempFileListArr.push(MiniFileMgr.filesListObj[key]); } for(var i=1,sz=tempFileListArr.length;i 0){ this.loops--; } this.startTime=0; this.play(); } /** *@private *播放 */ __proto.play=function(){ this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *@private *停止播放 * */ __proto.stop=function(){ this.isStopped=true; SoundManager.removeChannel(this); this.completeHandler=null; if (!this._audio) return; this._audio.stop(); this._audio.offended && this._audio.offended(null); this._miniSound.dispose(); this._audio=null; this._miniSound=null; this._onEnd=null; } /**@private **/ __proto.pause=function(){ this.isStopped=true; this._audio.pause(); } /**@private **/ __proto.resume=function(){ if (!this._audio) return; this.isStopped=false; SoundManager.addChannel(this); this._audio.play(); } /** *设置开始时间 *@param time */ __getset(0,__proto,'startTime',null,function(time){ if(this._audio){ this._audio.startTime=time; } }); /**@private **/ /** *@private *自动播放 *@param value */ __getset(0,__proto,'autoplay',function(){ return this._audio.autoplay; },function(value){ this._audio.autoplay=value; }); /** *@private *当前播放到的位置 *@return * */ __getset(0,__proto,'position',function(){ if (!this._audio) return 0; return this._audio.currentTime; }); /** *@private *获取总时间。 */ __getset(0,__proto,'duration',function(){ if (!this._audio) return 0; return this._audio.duration; }); /**@private **/ /**@private **/ __getset(0,__proto,'loop',function(){ return this._audio.loop; },function(value){ this._audio.loop=value; }); /** *@private *设置音量 *@param v * */ /** *@private *获取音量 *@return */ __getset(0,__proto,'volume',function(){ if (!this._audio)return 1; return this._audio.volume; },function(v){ if (!this._audio)return; this._audio.volume=v; }); MiniSoundChannel.bindToThis=function(fun,scope){ var rst=fun; /*__JS__ */rst=fun.bind(scope);; return rst; } return MiniSoundChannel; })(SoundChannel) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); } ================================================ FILE: public/libs/laya/matter-RenderLaya.js ================================================ var Browser = laya.utils.Browser; var Composite = Matter.Composite; var Events = Matter.Events; var Bounds = Matter.Bounds; var Common = Matter.Common; var Vertices = Matter.Vertices; var Vector = Matter.Vector; var Sleeping = Matter.Sleeping; var Axes = Matter.Axes; var Body = Matter.Body; var SAT = Matter.SAT; var Contact = Matter.Contact; var Pair = Matter.Pair; var Detector = Matter.Detector; var Grid = Matter.Grid; var LayaRender = {}; (function() { var graphics, spriteCon, graphicsCon; LayaRender.create = function(options) { var defaults = { controller: LayaRender, element: null, canvas: null, mouse: null, options: { width: 800, height: 600, pixelRatio: 1, background: '#fafafa', wireframeBackground: '#222', hasBounds: !!options.bounds, enabled: true, wireframes: true, showSleeping: true, showDebug: false, showBroadphase: false, showBounds: false, showVelocity: false, showCollisions: false, showSeparations: false, showAxes: false, showPositions: false, showAngleIndicator: false, showIds: false, showShadows: false, showVertexNumbers: false, showConvexHulls: false, showInternalEdges: false, showMousePosition: false } }; var render = Common.extend(defaults, options); render.canvas = laya.renders.Render.canvas; render.context = laya.renders.Render.context.ctx; render.textures = {}; render.bounds = render.bounds || { min: { x: 0, y: 0 }, max: { x: Laya.stage.width, y: Laya.stage.height } }; createContainer(render); setBackground(render); setPixelRatio(); return render; }; function createContainer(render) { var con = render.container; spriteCon = new Laya.Sprite(); graphicsCon = new Laya.Sprite(); render.spriteContainer = spriteCon; render.graphicsContainer = graphicsCon; con.addChild(spriteCon); con.addChild(graphicsCon); graphics = graphicsCon.graphics; } // 设置背景 function setBackground(render) { var bg = render.options.background; // 纯色背景 if (bg.length == 7 && bg[0] == '#') { spriteCon.graphics.drawRect( 0, 0, render.options.width, render.options.height, bg); } // 图片背景 else { spriteCon.loadImage(bg); } } function setPixelRatio() { var pixelRatio; pixelRatio = 1; Laya.Render.canvas.setAttribute('data-pixel-ratio', pixelRatio); } /** * Renders the given `engine`'s `Matter.World` object. * This is the entry point for all rendering and should be called every time the scene changes. * @method world * @param {engine} engine */ LayaRender.world = function(engine) { var render = engine.render, world = engine.world, options = render.options, allConstraints = Composite.allConstraints(world), bodies = Composite.allBodies(world), constraints = [], i; // handle bounds if (options.hasBounds) { var boundsWidth = render.bounds.max.x - render.bounds.min.x, boundsHeight = render.bounds.max.y - render.bounds.min.y, boundsScaleX = boundsWidth / options.width, boundsScaleY = boundsHeight / options.height; // filter out bodies that are not in view for (i = 0; i < bodies.length; i++) { var body = bodies[i]; body.render.sprite.visible = Bounds.overlaps(body.bounds, render.bounds); } // filter out constraints that are not in view for (i = 0; i < allConstraints.length; i++) { var constraint = allConstraints[i], bodyA = constraint.bodyA, bodyB = constraint.bodyB, pointAWorld = constraint.pointA, pointBWorld = constraint.pointB; if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA); if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB); if (!pointAWorld || !pointBWorld) continue; if (Bounds.contains(render.bounds, pointAWorld) || Bounds.contains(render.bounds, pointBWorld)) constraints.push(constraint); } // transform the view // context.scale(1 / boundsScaleX, 1 / boundsScaleY); // context.translate(-render.bounds.min.x, -render.bounds.min.y); } else { constraints = allConstraints; } graphics.clear(); for (i = 0; i < bodies.length; i++) LayaRender.body(engine, bodies[i]); for (i = 0; i < constraints.length; i++) LayaRender.constraint(engine, constraints[i]); }; LayaRender.body = function(engine, body) { var render = engine.render, bodyRender = body.render; if (!bodyRender.visible) { return; } var spInfo = bodyRender.sprite; var sp = body.sprite; if (bodyRender.sprite && bodyRender.sprite.texture) { // initialize body sprite if not existing if (!sp) { sp = body.sprite = createBodySprite(spInfo.xOffset, spInfo.yOffset); sp.loadImage(spInfo.texture); } sp.scale(spInfo.xScale, spInfo.yScale); sp.pos(body.position.x, body.position.y); sp.rotation = body.angle * 180 / Math.PI; } else { var options = render.options; // handle compound parts for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) { part = body.parts[k]; if (!part.render.visible) continue; var fillStyle = options.wireframes ? null : part.render.fillStyle; var lineWidth = part.render.lineWidth; var strokeStyle = part.render.strokeStyle; // part polygon if (part.circleRadius) { graphics.drawCircle(part.position.x, part.position.y, part.circleRadius, fillStyle, strokeStyle, lineWidth); } else { var path = []; path.push(part.vertices[0].x, part.vertices[0].y); for (var j = 1; j < part.vertices.length; j++) { if (!part.vertices[j - 1].isInternal || showInternalEdges) { path.push(part.vertices[j].x, part.vertices[j].y); } else { path.push(part.vertices[j].x, part.vertices[j].y); } if (part.vertices[j].isInternal && !showInternalEdges) { path.push(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y); } } graphics.drawPoly(0, 0, path, fillStyle, strokeStyle, lineWidth); } } } }; LayaRender.constraint = function(engine, constraint) { var sx, sy, ex, ey; if (!constraint.render.visible || !constraint.pointA || !constraint.pointB) { return; } var bodyA = constraint.bodyA, bodyB = constraint.bodyB; if (bodyA) { sx = bodyA.position.x + constraint.pointA.x; sy = bodyA.position.y + constraint.pointA.y; } else { sx = constraint.pointA.x; sy = constraint.pointA.y; } if (bodyB) { ex = bodyB.position.x + constraint.pointB.x; ey = bodyB.position.y + constraint.pointB.y; } else { ex = constraint.pointB.x; ey = constraint.pointB.y; } graphics.drawLine( sx, sy, ex, ey, constraint.render.strokeStyle, constraint.render.lineWidth); }; function createBodySprite(xOffset, yOffset) { var sp = new Laya.Sprite(); sp.pivot(xOffset, yOffset); sp.pos(-9999, -9999); spriteCon.addChild(sp); return sp; } })(); ================================================ FILE: public/libs/laya/matter.js ================================================ /** * matter-js 0.10.0 by @liabru 2016-05-01 * http://brm.io/matter-js/ * License MIT */ /** * The MIT License (MIT) * * Copyright (c) 2014 Liam Brummitt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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. */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Matter = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { Vector.rotateAbout(part.position, delta, body.position, part.position); } } }; /** * Sets the linear velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. * @method setVelocity * @param {body} body * @param {vector} velocity */ Body.setVelocity = function(body, velocity) { body.positionPrev.x = body.position.x - velocity.x; body.positionPrev.y = body.position.y - velocity.y; body.velocity.x = velocity.x; body.velocity.y = velocity.y; body.speed = Vector.magnitude(body.velocity); }; /** * Sets the angular velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`. * @method setAngularVelocity * @param {body} body * @param {number} velocity */ Body.setAngularVelocity = function(body, velocity) { body.anglePrev = body.angle - velocity; body.angularVelocity = velocity; body.angularSpeed = Math.abs(body.angularVelocity); }; /** * Moves a body by a given vector relative to its current position, without imparting any velocity. * @method translate * @param {body} body * @param {vector} translation */ Body.translate = function(body, translation) { Body.setPosition(body, Vector.add(body.position, translation)); }; /** * Rotates a body by a given angle relative to its current angle, without imparting any angular velocity. * @method rotate * @param {body} body * @param {number} rotation */ Body.rotate = function(body, rotation) { Body.setAngle(body, body.angle + rotation); }; /** * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre). * @method scale * @param {body} body * @param {number} scaleX * @param {number} scaleY * @param {vector} [point] */ Body.scale = function(body, scaleX, scaleY, point) { for (var i = 0; i < body.parts.length; i++) { var part = body.parts[i]; // scale vertices Vertices.scale(part.vertices, scaleX, scaleY, body.position); // update properties part.axes = Axes.fromVertices(part.vertices); if (!body.isStatic) { part.area = Vertices.area(part.vertices); Body.setMass(part, body.density * part.area); // update inertia (requires vertices to be at origin) Vertices.translate(part.vertices, { x: -part.position.x, y: -part.position.y }); Body.setInertia(part, Vertices.inertia(part.vertices, part.mass)); Vertices.translate(part.vertices, { x: part.position.x, y: part.position.y }); } // update bounds Bounds.update(part.bounds, part.vertices, body.velocity); } // handle circles if (body.circleRadius) { if (scaleX === scaleY) { body.circleRadius *= scaleX; } else { // body is no longer a circle body.circleRadius = null; } } if (!body.isStatic) { var total = _totalProperties(body); body.area = total.area; Body.setMass(body, total.mass); Body.setInertia(body, total.inertia); } }; /** * Performs a simulation step for the given `body`, including updating position and angle using Verlet integration. * @method update * @param {body} body * @param {number} deltaTime * @param {number} timeScale * @param {number} correction */ Body.update = function(body, deltaTime, timeScale, correction) { var deltaTimeSquared = Math.pow(deltaTime * timeScale * body.timeScale, 2); // from the previous step var frictionAir = 1 - body.frictionAir * timeScale * body.timeScale, velocityPrevX = body.position.x - body.positionPrev.x, velocityPrevY = body.position.y - body.positionPrev.y; // update velocity with Verlet integration body.velocity.x = (velocityPrevX * frictionAir * correction) + (body.force.x / body.mass) * deltaTimeSquared; body.velocity.y = (velocityPrevY * frictionAir * correction) + (body.force.y / body.mass) * deltaTimeSquared; body.positionPrev.x = body.position.x; body.positionPrev.y = body.position.y; body.position.x += body.velocity.x; body.position.y += body.velocity.y; // update angular velocity with Verlet integration body.angularVelocity = ((body.angle - body.anglePrev) * frictionAir * correction) + (body.torque / body.inertia) * deltaTimeSquared; body.anglePrev = body.angle; body.angle += body.angularVelocity; // track speed and acceleration body.speed = Vector.magnitude(body.velocity); body.angularSpeed = Math.abs(body.angularVelocity); // transform the body geometry for (var i = 0; i < body.parts.length; i++) { var part = body.parts[i]; Vertices.translate(part.vertices, body.velocity); if (i > 0) { part.position.x += body.velocity.x; part.position.y += body.velocity.y; } if (body.angularVelocity !== 0) { Vertices.rotate(part.vertices, body.angularVelocity, body.position); Axes.rotate(part.axes, body.angularVelocity); if (i > 0) { Vector.rotateAbout(part.position, body.angularVelocity, body.position, part.position); } } Bounds.update(part.bounds, part.vertices, body.velocity); } }; /** * Applies a force to a body from a given world-space position, including resulting torque. * @method applyForce * @param {body} body * @param {vector} position * @param {vector} force */ Body.applyForce = function(body, position, force) { body.force.x += force.x; body.force.y += force.y; var offset = { x: position.x - body.position.x, y: position.y - body.position.y }; body.torque += offset.x * force.y - offset.y * force.x; }; /** * Returns the sums of the properties of all compound parts of the parent body. * @method _totalProperties * @private * @param {body} body * @return {} */ var _totalProperties = function(body) { // https://ecourses.ou.edu/cgi-bin/ebook.cgi?doc=&topic=st&chap_sec=07.2&page=theory // http://output.to/sideway/default.asp?qno=121100087 var properties = { mass: 0, area: 0, inertia: 0, centre: { x: 0, y: 0 } }; // sum the properties of all compound parts of the parent body for (var i = body.parts.length === 1 ? 0 : 1; i < body.parts.length; i++) { var part = body.parts[i]; properties.mass += part.mass; properties.area += part.area; properties.inertia += part.inertia; properties.centre = Vector.add(properties.centre, Vector.mult(part.position, part.mass !== Infinity ? part.mass : 1)); } properties.centre = Vector.div(properties.centre, properties.mass !== Infinity ? properties.mass : body.parts.length); return properties; }; /* * * Events Documentation * */ /** * Fired when a body starts sleeping (where `this` is the body). * * @event sleepStart * @this {body} The body that has started sleeping * @param {} event An event object * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired when a body ends sleeping (where `this` is the body). * * @event sleepEnd * @this {body} The body that has ended sleeping * @param {} event An event object * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /* * * Properties Documentation * */ /** * An integer `Number` uniquely identifying number generated in `Body.create` by `Common.nextId`. * * @property id * @type number */ /** * A `String` denoting the type of object. * * @property type * @type string * @default "body" * @readOnly */ /** * An arbitrary `String` name to help the user identify and manage bodies. * * @property label * @type string * @default "Body" */ /** * An array of bodies that make up this body. * The first body in the array must always be a self reference to the current body instance. * All bodies in the `parts` array together form a single rigid compound body. * Parts are allowed to overlap, have gaps or holes or even form concave bodies. * Parts themselves should never be added to a `World`, only the parent body should be. * Use `Body.setParts` when setting parts to ensure correct updates of all properties. * * @property parts * @type body[] */ /** * A self reference if the body is _not_ a part of another body. * Otherwise this is a reference to the body that this is a part of. * See `body.parts`. * * @property parent * @type body */ /** * A `Number` specifying the angle of the body, in radians. * * @property angle * @type number * @default 0 */ /** * An array of `Vector` objects that specify the convex hull of the rigid body. * These should be provided about the origin `(0, 0)`. E.g. * * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] * * When passed via `Body.create`, the vertices are translated relative to `body.position` (i.e. world-space, and constantly updated by `Body.update` during simulation). * The `Vector` objects are also augmented with additional properties required for efficient collision detection. * * Other properties such as `inertia` and `bounds` are automatically calculated from the passed vertices (unless provided via `options`). * Concave hulls are not currently supported. The module `Matter.Vertices` contains useful methods for working with vertices. * * @property vertices * @type vector[] */ /** * A `Vector` that specifies the current world-space position of the body. * * @property position * @type vector * @default { x: 0, y: 0 } */ /** * A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`. * * @property force * @type vector * @default { x: 0, y: 0 } */ /** * A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`. * * @property torque * @type number * @default 0 */ /** * A `Number` that _measures_ the current speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.velocity`). * * @readOnly * @property speed * @type number * @default 0 */ /** * A `Number` that _measures_ the current angular speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.angularVelocity`). * * @readOnly * @property angularSpeed * @type number * @default 0 */ /** * A `Vector` that _measures_ the current velocity of the body after the last `Body.update`. It is read-only. * If you need to modify a body's velocity directly, you should either apply a force or simply change the body's `position` (as the engine uses position-Verlet integration). * * @readOnly * @property velocity * @type vector * @default { x: 0, y: 0 } */ /** * A `Number` that _measures_ the current angular velocity of the body after the last `Body.update`. It is read-only. * If you need to modify a body's angular velocity directly, you should apply a torque or simply change the body's `angle` (as the engine uses position-Verlet integration). * * @readOnly * @property angularVelocity * @type number * @default 0 */ /** * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. * If you need to set a body as static after its creation, you should use `Body.setStatic` as this requires more than just setting this flag. * * @property isStatic * @type boolean * @default false */ /** * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. * * @property isSensor * @type boolean * @default false */ /** * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken. * If you need to set a body as sleeping, you should use `Sleeping.set` as this requires more than just setting this flag. * * @property isSleeping * @type boolean * @default false */ /** * A `Number` that _measures_ the amount of movement a body currently has (a combination of `speed` and `angularSpeed`). It is read-only and always positive. * It is used and updated by the `Matter.Sleeping` module during simulation to decide if a body has come to rest. * * @readOnly * @property motion * @type number * @default 0 */ /** * A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine). * * @property sleepThreshold * @type number * @default 60 */ /** * A `Number` that defines the density of the body, that is its mass per unit area. * If you pass the density via `Body.create` the `mass` property is automatically calculated for you based on the size (area) of the object. * This is generally preferable to simply setting mass and allows for more intuitive definition of materials (e.g. rock has a higher density than wood). * * @property density * @type number * @default 0.001 */ /** * A `Number` that defines the mass of the body, although it may be more appropriate to specify the `density` property instead. * If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`). * * @property mass * @type number */ /** * A `Number` that defines the inverse mass of the body (`1 / mass`). * If you modify this value, you must also modify the `body.mass` property. * * @property inverseMass * @type number */ /** * A `Number` that defines the moment of inertia (i.e. second moment of area) of the body. * It is automatically calculated from the given convex hull (`vertices` array) and density in `Body.create`. * If you modify this value, you must also modify the `body.inverseInertia` property (`1 / inertia`). * * @property inertia * @type number */ /** * A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`). * If you modify this value, you must also modify the `body.inertia` property. * * @property inverseInertia * @type number */ /** * A `Number` that defines the restitution (elasticity) of the body. The value is always positive and is in the range `(0, 1)`. * A value of `0` means collisions may be perfectly inelastic and no bouncing may occur. * A value of `0.8` means the body may bounce back with approximately 80% of its kinetic energy. * Note that collision response is based on _pairs_ of bodies, and that `restitution` values are _combined_ with the following formula: * * Math.max(bodyA.restitution, bodyB.restitution) * * @property restitution * @type number * @default 0 */ /** * A `Number` that defines the friction of the body. The value is always positive and is in the range `(0, 1)`. * A value of `0` means that the body may slide indefinitely. * A value of `1` means the body may come to a stop almost instantly after a force is applied. * * The effects of the value may be non-linear. * High values may be unstable depending on the body. * The engine uses a Coulomb friction model including static and kinetic friction. * Note that collision response is based on _pairs_ of bodies, and that `friction` values are _combined_ with the following formula: * * Math.min(bodyA.friction, bodyB.friction) * * @property friction * @type number * @default 0.1 */ /** * A `Number` that defines the static friction of the body (in the Coulomb friction model). * A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used. * The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary. * This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction. * * @property frictionStatic * @type number * @default 0.5 */ /** * A `Number` that defines the air friction of the body (air resistance). * A value of `0` means the body will never slow as it moves through space. * The higher the value, the faster a body slows when moving through space. * The effects of the value are non-linear. * * @property frictionAir * @type number * @default 0.01 */ /** * An `Object` that specifies the collision filtering properties of this body. * * Collisions between two bodies will obey the following rules: * - If the two bodies have the same non-zero value of `collisionFilter.group`, * they will always collide if the value is positive, and they will never collide * if the value is negative. * - If the two bodies have different values of `collisionFilter.group` or if one * (or both) of the bodies has a value of 0, then the category/mask rules apply as follows: * * Each body belongs to a collision category, given by `collisionFilter.category`. This * value is used as a bit field and the category should have only one bit set, meaning that * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 * different collision categories available. * * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies * the categories it collides with (the value is the bitwise AND value of all these categories). * * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0` * are both true. * * @property collisionFilter * @type object */ /** * An Integer `Number`, that specifies the collision group this body belongs to. * See `body.collisionFilter` for more information. * * @property collisionFilter.group * @type object * @default 0 */ /** * A bit field that specifies the collision category this body belongs to. * The category value should have only one bit set, for example `0x0001`. * This means there are up to 32 unique collision categories available. * See `body.collisionFilter` for more information. * * @property collisionFilter.category * @type object * @default 1 */ /** * A bit mask that specifies the collision categories this body may collide with. * See `body.collisionFilter` for more information. * * @property collisionFilter.mask * @type object * @default -1 */ /** * A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies. * Avoid changing this value unless you understand the purpose of `slop` in physics engines. * The default should generally suffice, although very large bodies may require larger values for stable stacking. * * @property slop * @type number * @default 0.05 */ /** * A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. * * @property timeScale * @type number * @default 1 */ /** * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. * * @property render * @type object */ /** * A flag that indicates if the body should be rendered. * * @property render.visible * @type boolean * @default true */ /** * Sets the opacity to use when rendering. * * @property render.opacity * @type number * @default 1 */ /** * An `Object` that defines the sprite properties to use when rendering, if any. * * @property render.sprite * @type object */ /** * An `String` that defines the path to the image to use as the sprite texture, if any. * * @property render.sprite.texture * @type string */ /** * A `Number` that defines the scaling in the x-axis for the sprite, if any. * * @property render.sprite.xScale * @type number * @default 1 */ /** * A `Number` that defines the scaling in the y-axis for the sprite, if any. * * @property render.sprite.yScale * @type number * @default 1 */ /** * A `Number` that defines the offset in the x-axis for the sprite (normalised by texture width). * * @property render.sprite.xOffset * @type number * @default 0 */ /** * A `Number` that defines the offset in the y-axis for the sprite (normalised by texture height). * * @property render.sprite.yOffset * @type number * @default 0 */ /** * A `Number` that defines the line width to use when rendering the body outline (if a sprite is not defined). * A value of `0` means no outline will be rendered. * * @property render.lineWidth * @type number * @default 1.5 */ /** * A `String` that defines the fill style to use when rendering the body (if a sprite is not defined). * It is the same as when using a canvas, so it accepts CSS style property values. * * @property render.fillStyle * @type string * @default a random colour */ /** * A `String` that defines the stroke style to use when rendering the body outline (if a sprite is not defined). * It is the same as when using a canvas, so it accepts CSS style property values. * * @property render.strokeStyle * @type string * @default a random colour */ /** * An array of unique axis vectors (edge normals) used for collision detection. * These are automatically calculated from the given convex hull (`vertices` array) in `Body.create`. * They are constantly updated by `Body.update` during the simulation. * * @property axes * @type vector[] */ /** * A `Number` that _measures_ the area of the body's convex hull, calculated at creation by `Body.create`. * * @property area * @type string * @default */ /** * A `Bounds` object that defines the AABB region for the body. * It is automatically calculated from the given convex hull (`vertices` array) in `Body.create` and constantly updated by `Body.update` during simulation. * * @property bounds * @type bounds */ })(); },{"../core/Common":14,"../core/Sleeping":20,"../geometry/Axes":23,"../geometry/Bounds":24,"../geometry/Vector":26,"../geometry/Vertices":27,"../render/Render":29}],2:[function(require,module,exports){ /** * The `Matter.Composite` module contains methods for creating and manipulating composite bodies. * A composite body is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`, therefore composites form a tree structure. * It is important to use the functions in this module to modify composites, rather than directly modifying their properties. * Note that the `Matter.World` object is also a type of `Matter.Composite` and as such all composite methods here can also operate on a `Matter.World`. * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Composite */ var Composite = {}; module.exports = Composite; var Events = require('../core/Events'); var Common = require('../core/Common'); var Body = require('./Body'); (function() { /** * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults. * See the properites section below for detailed information on what you can pass via the `options` object. * @method create * @param {} [options] * @return {composite} A new composite */ Composite.create = function(options) { return Common.extend({ id: Common.nextId(), type: 'composite', parent: null, isModified: false, bodies: [], constraints: [], composites: [], label: 'Composite' }, options); }; /** * Sets the composite's `isModified` flag. * If `updateParents` is true, all parents will be set (default: false). * If `updateChildren` is true, all children will be set (default: false). * @method setModified * @param {composite} composite * @param {boolean} isModified * @param {boolean} [updateParents=false] * @param {boolean} [updateChildren=false] */ Composite.setModified = function(composite, isModified, updateParents, updateChildren) { composite.isModified = isModified; if (updateParents && composite.parent) { Composite.setModified(composite.parent, isModified, updateParents, updateChildren); } if (updateChildren) { for(var i = 0; i < composite.composites.length; i++) { var childComposite = composite.composites[i]; Composite.setModified(childComposite, isModified, updateParents, updateChildren); } } }; /** * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite. * Triggers `beforeAdd` and `afterAdd` events on the `composite`. * @method add * @param {composite} composite * @param {} object * @return {composite} The original composite with the objects added */ Composite.add = function(composite, object) { var objects = [].concat(object); Events.trigger(composite, 'beforeAdd', { object: object }); for (var i = 0; i < objects.length; i++) { var obj = objects[i]; switch (obj.type) { case 'body': // skip adding compound parts if (obj.parent !== obj) { Common.log('Composite.add: skipped adding a compound body part (you must add its parent instead)', 'warn'); break; } Composite.addBody(composite, obj); break; case 'constraint': Composite.addConstraint(composite, obj); break; case 'composite': Composite.addComposite(composite, obj); break; case 'mouseConstraint': Composite.addConstraint(composite, obj.constraint); break; } } Events.trigger(composite, 'afterAdd', { object: object }); return composite; }; /** * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite. * Optionally searching its children recursively. * Triggers `beforeRemove` and `afterRemove` events on the `composite`. * @method remove * @param {composite} composite * @param {} object * @param {boolean} [deep=false] * @return {composite} The original composite with the objects removed */ Composite.remove = function(composite, object, deep) { var objects = [].concat(object); Events.trigger(composite, 'beforeRemove', { object: object }); for (var i = 0; i < objects.length; i++) { var obj = objects[i]; switch (obj.type) { case 'body': Composite.removeBody(composite, obj, deep); break; case 'constraint': Composite.removeConstraint(composite, obj, deep); break; case 'composite': Composite.removeComposite(composite, obj, deep); break; case 'mouseConstraint': Composite.removeConstraint(composite, obj.constraint); break; } } Events.trigger(composite, 'afterRemove', { object: object }); return composite; }; /** * Adds a composite to the given composite. * @private * @method addComposite * @param {composite} compositeA * @param {composite} compositeB * @return {composite} The original compositeA with the objects from compositeB added */ Composite.addComposite = function(compositeA, compositeB) { compositeA.composites.push(compositeB); compositeB.parent = compositeA; Composite.setModified(compositeA, true, true, false); return compositeA; }; /** * Removes a composite from the given composite, and optionally searching its children recursively. * @private * @method removeComposite * @param {composite} compositeA * @param {composite} compositeB * @param {boolean} [deep=false] * @return {composite} The original compositeA with the composite removed */ Composite.removeComposite = function(compositeA, compositeB, deep) { var position = Common.indexOf(compositeA.composites, compositeB); if (position !== -1) { Composite.removeCompositeAt(compositeA, position); Composite.setModified(compositeA, true, true, false); } if (deep) { for (var i = 0; i < compositeA.composites.length; i++){ Composite.removeComposite(compositeA.composites[i], compositeB, true); } } return compositeA; }; /** * Removes a composite from the given composite. * @private * @method removeCompositeAt * @param {composite} composite * @param {number} position * @return {composite} The original composite with the composite removed */ Composite.removeCompositeAt = function(composite, position) { composite.composites.splice(position, 1); Composite.setModified(composite, true, true, false); return composite; }; /** * Adds a body to the given composite. * @private * @method addBody * @param {composite} composite * @param {body} body * @return {composite} The original composite with the body added */ Composite.addBody = function(composite, body) { composite.bodies.push(body); Composite.setModified(composite, true, true, false); return composite; }; /** * Removes a body from the given composite, and optionally searching its children recursively. * @private * @method removeBody * @param {composite} composite * @param {body} body * @param {boolean} [deep=false] * @return {composite} The original composite with the body removed */ Composite.removeBody = function(composite, body, deep) { var position = Common.indexOf(composite.bodies, body); if (position !== -1) { Composite.removeBodyAt(composite, position); Composite.setModified(composite, true, true, false); } if (deep) { for (var i = 0; i < composite.composites.length; i++){ Composite.removeBody(composite.composites[i], body, true); } } return composite; }; /** * Removes a body from the given composite. * @private * @method removeBodyAt * @param {composite} composite * @param {number} position * @return {composite} The original composite with the body removed */ Composite.removeBodyAt = function(composite, position) { composite.bodies.splice(position, 1); Composite.setModified(composite, true, true, false); return composite; }; /** * Adds a constraint to the given composite. * @private * @method addConstraint * @param {composite} composite * @param {constraint} constraint * @return {composite} The original composite with the constraint added */ Composite.addConstraint = function(composite, constraint) { composite.constraints.push(constraint); Composite.setModified(composite, true, true, false); return composite; }; /** * Removes a constraint from the given composite, and optionally searching its children recursively. * @private * @method removeConstraint * @param {composite} composite * @param {constraint} constraint * @param {boolean} [deep=false] * @return {composite} The original composite with the constraint removed */ Composite.removeConstraint = function(composite, constraint, deep) { var position = Common.indexOf(composite.constraints, constraint); if (position !== -1) { Composite.removeConstraintAt(composite, position); } if (deep) { for (var i = 0; i < composite.composites.length; i++){ Composite.removeConstraint(composite.composites[i], constraint, true); } } return composite; }; /** * Removes a body from the given composite. * @private * @method removeConstraintAt * @param {composite} composite * @param {number} position * @return {composite} The original composite with the constraint removed */ Composite.removeConstraintAt = function(composite, position) { composite.constraints.splice(position, 1); Composite.setModified(composite, true, true, false); return composite; }; /** * Removes all bodies, constraints and composites from the given composite. * Optionally clearing its children recursively. * @method clear * @param {composite} composite * @param {boolean} keepStatic * @param {boolean} [deep=false] */ Composite.clear = function(composite, keepStatic, deep) { if (deep) { for (var i = 0; i < composite.composites.length; i++){ Composite.clear(composite.composites[i], keepStatic, true); } } if (keepStatic) { composite.bodies = composite.bodies.filter(function(body) { return body.isStatic; }); } else { composite.bodies.length = 0; } composite.constraints.length = 0; composite.composites.length = 0; Composite.setModified(composite, true, true, false); return composite; }; /** * Returns all bodies in the given composite, including all bodies in its children, recursively. * @method allBodies * @param {composite} composite * @return {body[]} All the bodies */ Composite.allBodies = function(composite) { var bodies = [].concat(composite.bodies); for (var i = 0; i < composite.composites.length; i++) bodies = bodies.concat(Composite.allBodies(composite.composites[i])); return bodies; }; /** * Returns all constraints in the given composite, including all constraints in its children, recursively. * @method allConstraints * @param {composite} composite * @return {constraint[]} All the constraints */ Composite.allConstraints = function(composite) { var constraints = [].concat(composite.constraints); for (var i = 0; i < composite.composites.length; i++) constraints = constraints.concat(Composite.allConstraints(composite.composites[i])); return constraints; }; /** * Returns all composites in the given composite, including all composites in its children, recursively. * @method allComposites * @param {composite} composite * @return {composite[]} All the composites */ Composite.allComposites = function(composite) { var composites = [].concat(composite.composites); for (var i = 0; i < composite.composites.length; i++) composites = composites.concat(Composite.allComposites(composite.composites[i])); return composites; }; /** * Searches the composite recursively for an object matching the type and id supplied, null if not found. * @method get * @param {composite} composite * @param {number} id * @param {string} type * @return {object} The requested object, if found */ Composite.get = function(composite, id, type) { var objects, object; switch (type) { case 'body': objects = Composite.allBodies(composite); break; case 'constraint': objects = Composite.allConstraints(composite); break; case 'composite': objects = Composite.allComposites(composite).concat(composite); break; } if (!objects) return null; object = objects.filter(function(object) { return object.id.toString() === id.toString(); }); return object.length === 0 ? null : object[0]; }; /** * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add). * @method move * @param {compositeA} compositeA * @param {object[]} objects * @param {compositeB} compositeB * @return {composite} Returns compositeA */ Composite.move = function(compositeA, objects, compositeB) { Composite.remove(compositeA, objects); Composite.add(compositeB, objects); return compositeA; }; /** * Assigns new ids for all objects in the composite, recursively. * @method rebase * @param {composite} composite * @return {composite} Returns composite */ Composite.rebase = function(composite) { var objects = Composite.allBodies(composite) .concat(Composite.allConstraints(composite)) .concat(Composite.allComposites(composite)); for (var i = 0; i < objects.length; i++) { objects[i].id = Common.nextId(); } Composite.setModified(composite, true, true, false); return composite; }; /** * Translates all children in the composite by a given vector relative to their current positions, * without imparting any velocity. * @method translate * @param {composite} composite * @param {vector} translation * @param {bool} [recursive=true] */ Composite.translate = function(composite, translation, recursive) { var bodies = recursive ? Composite.allBodies(composite) : composite.bodies; for (var i = 0; i < bodies.length; i++) { Body.translate(bodies[i], translation); } Composite.setModified(composite, true, true, false); return composite; }; /** * Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity. * @method rotate * @param {composite} composite * @param {number} rotation * @param {vector} point * @param {bool} [recursive=true] */ Composite.rotate = function(composite, rotation, point, recursive) { var cos = Math.cos(rotation), sin = Math.sin(rotation), bodies = recursive ? Composite.allBodies(composite) : composite.bodies; for (var i = 0; i < bodies.length; i++) { var body = bodies[i], dx = body.position.x - point.x, dy = body.position.y - point.y; Body.setPosition(body, { x: point.x + (dx * cos - dy * sin), y: point.y + (dx * sin + dy * cos) }); Body.rotate(body, rotation); } Composite.setModified(composite, true, true, false); return composite; }; /** * Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point. * @method scale * @param {composite} composite * @param {number} scaleX * @param {number} scaleY * @param {vector} point * @param {bool} [recursive=true] */ Composite.scale = function(composite, scaleX, scaleY, point, recursive) { var bodies = recursive ? Composite.allBodies(composite) : composite.bodies; for (var i = 0; i < bodies.length; i++) { var body = bodies[i], dx = body.position.x - point.x, dy = body.position.y - point.y; Body.setPosition(body, { x: point.x + dx * scaleX, y: point.y + dy * scaleY }); Body.scale(body, scaleX, scaleY); } Composite.setModified(composite, true, true, false); return composite; }; /* * * Events Documentation * */ /** * Fired when a call to `Composite.add` is made, before objects have been added. * * @event beforeAdd * @param {} event An event object * @param {} event.object The object(s) to be added (may be a single body, constraint, composite or a mixed array of these) * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired when a call to `Composite.add` is made, after objects have been added. * * @event afterAdd * @param {} event An event object * @param {} event.object The object(s) that have been added (may be a single body, constraint, composite or a mixed array of these) * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired when a call to `Composite.remove` is made, before objects have been removed. * * @event beforeRemove * @param {} event An event object * @param {} event.object The object(s) to be removed (may be a single body, constraint, composite or a mixed array of these) * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired when a call to `Composite.remove` is made, after objects have been removed. * * @event afterRemove * @param {} event An event object * @param {} event.object The object(s) that have been removed (may be a single body, constraint, composite or a mixed array of these) * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /* * * Properties Documentation * */ /** * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. * * @property id * @type number */ /** * A `String` denoting the type of object. * * @property type * @type string * @default "composite" * @readOnly */ /** * An arbitrary `String` name to help the user identify and manage composites. * * @property label * @type string * @default "Composite" */ /** * A flag that specifies whether the composite has been modified during the current step. * Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled. * If you need to change it manually, you should use the `Composite.setModified` method. * * @property isModified * @type boolean * @default false */ /** * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods. * * @property parent * @type composite * @default null */ /** * An array of `Body` that are _direct_ children of this composite. * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method. * * @property bodies * @type body[] * @default [] */ /** * An array of `Constraint` that are _direct_ children of this composite. * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method. * * @property constraints * @type constraint[] * @default [] */ /** * An array of `Composite` that are _direct_ children of this composite. * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property. * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method. * * @property composites * @type composite[] * @default [] */ })(); },{"../core/Common":14,"../core/Events":16,"./Body":1}],3:[function(require,module,exports){ /** * The `Matter.World` module contains methods for creating and manipulating the world composite. * A `Matter.World` is a `Matter.Composite` body, which is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`. * A `Matter.World` has a few additional properties including `gravity` and `bounds`. * It is important to use the functions in the `Matter.Composite` module to modify the world composite, rather than directly modifying its properties. * There are also a few methods here that alias those in `Matter.Composite` for easier readability. * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class World * @extends Composite */ var World = {}; module.exports = World; var Composite = require('./Composite'); var Constraint = require('../constraint/Constraint'); var Common = require('../core/Common'); (function() { /** * Creates a new world composite. The options parameter is an object that specifies any properties you wish to override the defaults. * See the properties section below for detailed information on what you can pass via the `options` object. * @method create * @constructor * @param {} options * @return {world} A new world */ World.create = function(options) { var composite = Composite.create(); var defaults = { label: 'World', gravity: { x: 0, y: 1, scale: 0.001 }, bounds: { min: { x: -Infinity, y: -Infinity }, max: { x: Infinity, y: Infinity } } }; return Common.extend(composite, defaults, options); }; /* * * Properties Documentation * */ /** * The gravity to apply on the world. * * @property gravity * @type object */ /** * The gravity x component. * * @property gravity.x * @type object * @default 0 */ /** * The gravity y component. * * @property gravity.y * @type object * @default 1 */ /** * The gravity scale factor. * * @property gravity.scale * @type object * @default 0.001 */ /** * A `Bounds` object that defines the world bounds for collision detection. * * @property bounds * @type bounds * @default { min: { x: -Infinity, y: -Infinity }, max: { x: Infinity, y: Infinity } } */ // World is a Composite body // see src/module/Outro.js for these aliases: /** * An alias for Composite.clear * @method clear * @param {world} world * @param {boolean} keepStatic */ /** * An alias for Composite.add * @method addComposite * @param {world} world * @param {composite} composite * @return {world} The original world with the objects from composite added */ /** * An alias for Composite.addBody * @method addBody * @param {world} world * @param {body} body * @return {world} The original world with the body added */ /** * An alias for Composite.addConstraint * @method addConstraint * @param {world} world * @param {constraint} constraint * @return {world} The original world with the constraint added */ })(); },{"../constraint/Constraint":12,"../core/Common":14,"./Composite":2}],4:[function(require,module,exports){ /** * The `Matter.Contact` module contains methods for creating and manipulating collision contacts. * * @class Contact */ var Contact = {}; module.exports = Contact; (function() { /** * Creates a new contact. * @method create * @param {vertex} vertex * @return {contact} A new contact */ Contact.create = function(vertex) { return { id: Contact.id(vertex), vertex: vertex, normalImpulse: 0, tangentImpulse: 0 }; }; /** * Generates a contact id. * @method id * @param {vertex} vertex * @return {string} Unique contactID */ Contact.id = function(vertex) { return vertex.body.id + '_' + vertex.index; }; })(); },{}],5:[function(require,module,exports){ /** * The `Matter.Detector` module contains methods for detecting collisions given a set of pairs. * * @class Detector */ // TODO: speculative contacts var Detector = {}; module.exports = Detector; var SAT = require('./SAT'); var Pair = require('./Pair'); var Bounds = require('../geometry/Bounds'); (function() { /** * Finds all collisions given a list of pairs. * @method collisions * @param {pair[]} broadphasePairs * @param {engine} engine * @return {array} collisions */ Detector.collisions = function(broadphasePairs, engine) { var collisions = [], pairsTable = engine.pairs.table; for (var i = 0; i < broadphasePairs.length; i++) { var bodyA = broadphasePairs[i][0], bodyB = broadphasePairs[i][1]; if ((bodyA.isStatic || bodyA.isSleeping) && (bodyB.isStatic || bodyB.isSleeping)) continue; if (!Detector.canCollide(bodyA.collisionFilter, bodyB.collisionFilter)) continue; // mid phase if (Bounds.overlaps(bodyA.bounds, bodyB.bounds)) { for (var j = bodyA.parts.length > 1 ? 1 : 0; j < bodyA.parts.length; j++) { var partA = bodyA.parts[j]; for (var k = bodyB.parts.length > 1 ? 1 : 0; k < bodyB.parts.length; k++) { var partB = bodyB.parts[k]; if ((partA === bodyA && partB === bodyB) || Bounds.overlaps(partA.bounds, partB.bounds)) { // find a previous collision we could reuse var pairId = Pair.id(partA, partB), pair = pairsTable[pairId], previousCollision; if (pair && pair.isActive) { previousCollision = pair.collision; } else { previousCollision = null; } // narrow phase var collision = SAT.collides(partA, partB, previousCollision); if (collision.collided) { collisions.push(collision); } } } } } } return collisions; }; /** * Returns `true` if both supplied collision filters will allow a collision to occur. * See `body.collisionFilter` for more information. * @method canCollide * @param {} filterA * @param {} filterB * @return {bool} `true` if collision can occur */ Detector.canCollide = function(filterA, filterB) { if (filterA.group === filterB.group && filterA.group !== 0) return filterA.group > 0; return (filterA.mask & filterB.category) !== 0 && (filterB.mask & filterA.category) !== 0; }; })(); },{"../geometry/Bounds":24,"./Pair":7,"./SAT":11}],6:[function(require,module,exports){ /** * The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures. * * @class Grid */ var Grid = {}; module.exports = Grid; var Pair = require('./Pair'); var Detector = require('./Detector'); var Common = require('../core/Common'); (function() { /** * Creates a new grid. * @method create * @param {} options * @return {grid} A new grid */ Grid.create = function(options) { var defaults = { controller: Grid, detector: Detector.collisions, buckets: {}, pairs: {}, pairsList: [], bucketWidth: 48, bucketHeight: 48 }; return Common.extend(defaults, options); }; /** * The width of a single grid bucket. * * @property bucketWidth * @type number * @default 48 */ /** * The height of a single grid bucket. * * @property bucketHeight * @type number * @default 48 */ /** * Updates the grid. * @method update * @param {grid} grid * @param {body[]} bodies * @param {engine} engine * @param {boolean} forceUpdate */ Grid.update = function(grid, bodies, engine, forceUpdate) { var i, col, row, world = engine.world, buckets = grid.buckets, bucket, bucketId, gridChanged = false; for (i = 0; i < bodies.length; i++) { var body = bodies[i]; if (body.isSleeping && !forceUpdate) continue; // don't update out of world bodies if (body.bounds.max.x < world.bounds.min.x || body.bounds.min.x > world.bounds.max.x || body.bounds.max.y < world.bounds.min.y || body.bounds.min.y > world.bounds.max.y) continue; var newRegion = _getRegion(grid, body); // if the body has changed grid region if (!body.region || newRegion.id !== body.region.id || forceUpdate) { if (!body.region || forceUpdate) body.region = newRegion; var union = _regionUnion(newRegion, body.region); // update grid buckets affected by region change // iterate over the union of both regions for (col = union.startCol; col <= union.endCol; col++) { for (row = union.startRow; row <= union.endRow; row++) { bucketId = _getBucketId(col, row); bucket = buckets[bucketId]; var isInsideNewRegion = (col >= newRegion.startCol && col <= newRegion.endCol && row >= newRegion.startRow && row <= newRegion.endRow); var isInsideOldRegion = (col >= body.region.startCol && col <= body.region.endCol && row >= body.region.startRow && row <= body.region.endRow); // remove from old region buckets if (!isInsideNewRegion && isInsideOldRegion) { if (isInsideOldRegion) { if (bucket) _bucketRemoveBody(grid, bucket, body); } } // add to new region buckets if (body.region === newRegion || (isInsideNewRegion && !isInsideOldRegion) || forceUpdate) { if (!bucket) bucket = _createBucket(buckets, bucketId); _bucketAddBody(grid, bucket, body); } } } // set the new region body.region = newRegion; // flag changes so we can update pairs gridChanged = true; } } // update pairs list only if pairs changed (i.e. a body changed region) if (gridChanged) grid.pairsList = _createActivePairsList(grid); }; /** * Clears the grid. * @method clear * @param {grid} grid */ Grid.clear = function(grid) { grid.buckets = {}; grid.pairs = {}; grid.pairsList = []; }; /** * Finds the union of two regions. * @method _regionUnion * @private * @param {} regionA * @param {} regionB * @return {} region */ var _regionUnion = function(regionA, regionB) { var startCol = Math.min(regionA.startCol, regionB.startCol), endCol = Math.max(regionA.endCol, regionB.endCol), startRow = Math.min(regionA.startRow, regionB.startRow), endRow = Math.max(regionA.endRow, regionB.endRow); return _createRegion(startCol, endCol, startRow, endRow); }; /** * Gets the region a given body falls in for a given grid. * @method _getRegion * @private * @param {} grid * @param {} body * @return {} region */ var _getRegion = function(grid, body) { var bounds = body.bounds, startCol = Math.floor(bounds.min.x / grid.bucketWidth), endCol = Math.floor(bounds.max.x / grid.bucketWidth), startRow = Math.floor(bounds.min.y / grid.bucketHeight), endRow = Math.floor(bounds.max.y / grid.bucketHeight); return _createRegion(startCol, endCol, startRow, endRow); }; /** * Creates a region. * @method _createRegion * @private * @param {} startCol * @param {} endCol * @param {} startRow * @param {} endRow * @return {} region */ var _createRegion = function(startCol, endCol, startRow, endRow) { return { id: startCol + ',' + endCol + ',' + startRow + ',' + endRow, startCol: startCol, endCol: endCol, startRow: startRow, endRow: endRow }; }; /** * Gets the bucket id at the given position. * @method _getBucketId * @private * @param {} column * @param {} row * @return {string} bucket id */ var _getBucketId = function(column, row) { return column + ',' + row; }; /** * Creates a bucket. * @method _createBucket * @private * @param {} buckets * @param {} bucketId * @return {} bucket */ var _createBucket = function(buckets, bucketId) { var bucket = buckets[bucketId] = []; return bucket; }; /** * Adds a body to a bucket. * @method _bucketAddBody * @private * @param {} grid * @param {} bucket * @param {} body */ var _bucketAddBody = function(grid, bucket, body) { // add new pairs for (var i = 0; i < bucket.length; i++) { var bodyB = bucket[i]; if (body.id === bodyB.id || (body.isStatic && bodyB.isStatic)) continue; // keep track of the number of buckets the pair exists in // important for Grid.update to work var pairId = Pair.id(body, bodyB), pair = grid.pairs[pairId]; if (pair) { pair[2] += 1; } else { grid.pairs[pairId] = [body, bodyB, 1]; } } // add to bodies (after pairs, otherwise pairs with self) bucket.push(body); }; /** * Removes a body from a bucket. * @method _bucketRemoveBody * @private * @param {} grid * @param {} bucket * @param {} body */ var _bucketRemoveBody = function(grid, bucket, body) { // remove from bucket bucket.splice(Common.indexOf(bucket, body), 1); // update pair counts for (var i = 0; i < bucket.length; i++) { // keep track of the number of buckets the pair exists in // important for _createActivePairsList to work var bodyB = bucket[i], pairId = Pair.id(body, bodyB), pair = grid.pairs[pairId]; if (pair) pair[2] -= 1; } }; /** * Generates a list of the active pairs in the grid. * @method _createActivePairsList * @private * @param {} grid * @return [] pairs */ var _createActivePairsList = function(grid) { var pairKeys, pair, pairs = []; // grid.pairs is used as a hashmap pairKeys = Common.keys(grid.pairs); // iterate over grid.pairs for (var k = 0; k < pairKeys.length; k++) { pair = grid.pairs[pairKeys[k]]; // if pair exists in at least one bucket // it is a pair that needs further collision testing so push it if (pair[2] > 0) { pairs.push(pair); } else { delete grid.pairs[pairKeys[k]]; } } return pairs; }; })(); },{"../core/Common":14,"./Detector":5,"./Pair":7}],7:[function(require,module,exports){ /** * The `Matter.Pair` module contains methods for creating and manipulating collision pairs. * * @class Pair */ var Pair = {}; module.exports = Pair; var Contact = require('./Contact'); (function() { /** * Creates a pair. * @method create * @param {collision} collision * @param {number} timestamp * @return {pair} A new pair */ Pair.create = function(collision, timestamp) { var bodyA = collision.bodyA, bodyB = collision.bodyB, parentA = collision.parentA, parentB = collision.parentB; var pair = { id: Pair.id(bodyA, bodyB), bodyA: bodyA, bodyB: bodyB, contacts: {}, activeContacts: [], separation: 0, isActive: true, isSensor: bodyA.isSensor || bodyB.isSensor, timeCreated: timestamp, timeUpdated: timestamp, inverseMass: parentA.inverseMass + parentB.inverseMass, friction: Math.min(parentA.friction, parentB.friction), frictionStatic: Math.max(parentA.frictionStatic, parentB.frictionStatic), restitution: Math.max(parentA.restitution, parentB.restitution), slop: Math.max(parentA.slop, parentB.slop) }; Pair.update(pair, collision, timestamp); return pair; }; /** * Updates a pair given a collision. * @method update * @param {pair} pair * @param {collision} collision * @param {number} timestamp */ Pair.update = function(pair, collision, timestamp) { var contacts = pair.contacts, supports = collision.supports, activeContacts = pair.activeContacts, parentA = collision.parentA, parentB = collision.parentB; pair.collision = collision; pair.inverseMass = parentA.inverseMass + parentB.inverseMass; pair.friction = Math.min(parentA.friction, parentB.friction); pair.frictionStatic = Math.max(parentA.frictionStatic, parentB.frictionStatic); pair.restitution = Math.max(parentA.restitution, parentB.restitution); pair.slop = Math.max(parentA.slop, parentB.slop); activeContacts.length = 0; if (collision.collided) { for (var i = 0; i < supports.length; i++) { var support = supports[i], contactId = Contact.id(support), contact = contacts[contactId]; if (contact) { activeContacts.push(contact); } else { activeContacts.push(contacts[contactId] = Contact.create(support)); } } pair.separation = collision.depth; Pair.setActive(pair, true, timestamp); } else { if (pair.isActive === true) Pair.setActive(pair, false, timestamp); } }; /** * Set a pair as active or inactive. * @method setActive * @param {pair} pair * @param {bool} isActive * @param {number} timestamp */ Pair.setActive = function(pair, isActive, timestamp) { if (isActive) { pair.isActive = true; pair.timeUpdated = timestamp; } else { pair.isActive = false; pair.activeContacts.length = 0; } }; /** * Get the id for the given pair. * @method id * @param {body} bodyA * @param {body} bodyB * @return {string} Unique pairId */ Pair.id = function(bodyA, bodyB) { if (bodyA.id < bodyB.id) { return bodyA.id + '_' + bodyB.id; } else { return bodyB.id + '_' + bodyA.id; } }; })(); },{"./Contact":4}],8:[function(require,module,exports){ /** * The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. * * @class Pairs */ var Pairs = {}; module.exports = Pairs; var Pair = require('./Pair'); var Common = require('../core/Common'); (function() { var _pairMaxIdleLife = 1000; /** * Creates a new pairs structure. * @method create * @param {object} options * @return {pairs} A new pairs structure */ Pairs.create = function(options) { return Common.extend({ table: {}, list: [], collisionStart: [], collisionActive: [], collisionEnd: [] }, options); }; /** * Updates pairs given a list of collisions. * @method update * @param {object} pairs * @param {collision[]} collisions * @param {number} timestamp */ Pairs.update = function(pairs, collisions, timestamp) { var pairsList = pairs.list, pairsTable = pairs.table, collisionStart = pairs.collisionStart, collisionEnd = pairs.collisionEnd, collisionActive = pairs.collisionActive, activePairIds = [], collision, pairId, pair, i; // clear collision state arrays, but maintain old reference collisionStart.length = 0; collisionEnd.length = 0; collisionActive.length = 0; for (i = 0; i < collisions.length; i++) { collision = collisions[i]; if (collision.collided) { pairId = Pair.id(collision.bodyA, collision.bodyB); activePairIds.push(pairId); pair = pairsTable[pairId]; if (pair) { // pair already exists (but may or may not be active) if (pair.isActive) { // pair exists and is active collisionActive.push(pair); } else { // pair exists but was inactive, so a collision has just started again collisionStart.push(pair); } // update the pair Pair.update(pair, collision, timestamp); } else { // pair did not exist, create a new pair pair = Pair.create(collision, timestamp); pairsTable[pairId] = pair; // push the new pair collisionStart.push(pair); pairsList.push(pair); } } } // deactivate previously active pairs that are now inactive for (i = 0; i < pairsList.length; i++) { pair = pairsList[i]; if (pair.isActive && Common.indexOf(activePairIds, pair.id) === -1) { Pair.setActive(pair, false, timestamp); collisionEnd.push(pair); } } }; /** * Finds and removes pairs that have been inactive for a set amount of time. * @method removeOld * @param {object} pairs * @param {number} timestamp */ Pairs.removeOld = function(pairs, timestamp) { var pairsList = pairs.list, pairsTable = pairs.table, indexesToRemove = [], pair, collision, pairIndex, i; for (i = 0; i < pairsList.length; i++) { pair = pairsList[i]; collision = pair.collision; // never remove sleeping pairs if (collision.bodyA.isSleeping || collision.bodyB.isSleeping) { pair.timeUpdated = timestamp; continue; } // if pair is inactive for too long, mark it to be removed if (timestamp - pair.timeUpdated > _pairMaxIdleLife) { indexesToRemove.push(i); } } // remove marked pairs for (i = 0; i < indexesToRemove.length; i++) { pairIndex = indexesToRemove[i] - i; pair = pairsList[pairIndex]; delete pairsTable[pair.id]; pairsList.splice(pairIndex, 1); } }; /** * Clears the given pairs structure. * @method clear * @param {pairs} pairs * @return {pairs} pairs */ Pairs.clear = function(pairs) { pairs.table = {}; pairs.list.length = 0; pairs.collisionStart.length = 0; pairs.collisionActive.length = 0; pairs.collisionEnd.length = 0; return pairs; }; })(); },{"../core/Common":14,"./Pair":7}],9:[function(require,module,exports){ /** * The `Matter.Query` module contains methods for performing collision queries. * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Query */ var Query = {}; module.exports = Query; var Vector = require('../geometry/Vector'); var SAT = require('./SAT'); var Bounds = require('../geometry/Bounds'); var Bodies = require('../factory/Bodies'); var Vertices = require('../geometry/Vertices'); (function() { /** * Casts a ray segment against a set of bodies and returns all collisions, ray width is optional. Intersection points are not provided. * @method ray * @param {body[]} bodies * @param {vector} startPoint * @param {vector} endPoint * @param {number} [rayWidth] * @return {object[]} Collisions */ Query.ray = function(bodies, startPoint, endPoint, rayWidth) { rayWidth = rayWidth || 1e-100; var rayAngle = Vector.angle(startPoint, endPoint), rayLength = Vector.magnitude(Vector.sub(startPoint, endPoint)), rayX = (endPoint.x + startPoint.x) * 0.5, rayY = (endPoint.y + startPoint.y) * 0.5, ray = Bodies.rectangle(rayX, rayY, rayLength, rayWidth, { angle: rayAngle }), collisions = []; for (var i = 0; i < bodies.length; i++) { var bodyA = bodies[i]; if (Bounds.overlaps(bodyA.bounds, ray.bounds)) { for (var j = bodyA.parts.length === 1 ? 0 : 1; j < bodyA.parts.length; j++) { var part = bodyA.parts[j]; if (Bounds.overlaps(part.bounds, ray.bounds)) { var collision = SAT.collides(part, ray); if (collision.collided) { collision.body = collision.bodyA = collision.bodyB = bodyA; collisions.push(collision); break; } } } } } return collisions; }; /** * Returns all bodies whose bounds are inside (or outside if set) the given set of bounds, from the given set of bodies. * @method region * @param {body[]} bodies * @param {bounds} bounds * @param {bool} [outside=false] * @return {body[]} The bodies matching the query */ Query.region = function(bodies, bounds, outside) { var result = []; for (var i = 0; i < bodies.length; i++) { var body = bodies[i], overlaps = Bounds.overlaps(body.bounds, bounds); if ((overlaps && !outside) || (!overlaps && outside)) result.push(body); } return result; }; /** * Returns all bodies whose vertices contain the given point, from the given set of bodies. * @method point * @param {body[]} bodies * @param {vector} point * @return {body[]} The bodies matching the query */ Query.point = function(bodies, point) { var result = []; for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (Bounds.contains(body.bounds, point)) { for (var j = body.parts.length === 1 ? 0 : 1; j < body.parts.length; j++) { var part = body.parts[j]; if (Bounds.contains(part.bounds, point) && Vertices.contains(part.vertices, point)) { result.push(body); break; } } } } return result; }; })(); },{"../factory/Bodies":21,"../geometry/Bounds":24,"../geometry/Vector":26,"../geometry/Vertices":27,"./SAT":11}],10:[function(require,module,exports){ /** * The `Matter.Resolver` module contains methods for resolving collision pairs. * * @class Resolver */ var Resolver = {}; module.exports = Resolver; var Vertices = require('../geometry/Vertices'); var Vector = require('../geometry/Vector'); var Common = require('../core/Common'); var Bounds = require('../geometry/Bounds'); (function() { Resolver._restingThresh = 4; Resolver._restingThreshTangent = 6; Resolver._positionDampen = 0.9; Resolver._positionWarming = 0.8; Resolver._frictionNormalMultiplier = 5; /** * Prepare pairs for position solving. * @method preSolvePosition * @param {pair[]} pairs */ Resolver.preSolvePosition = function(pairs) { var i, pair, activeCount; // find total contacts on each body for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive) continue; activeCount = pair.activeContacts.length; pair.collision.parentA.totalContacts += activeCount; pair.collision.parentB.totalContacts += activeCount; } }; /** * Find a solution for pair positions. * @method solvePosition * @param {pair[]} pairs * @param {number} timeScale */ Resolver.solvePosition = function(pairs, timeScale) { var i, pair, collision, bodyA, bodyB, normal, bodyBtoA, contactShare, positionImpulse, contactCount = {}, tempA = Vector._temp[0], tempB = Vector._temp[1], tempC = Vector._temp[2], tempD = Vector._temp[3]; // find impulses required to resolve penetration for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive || pair.isSensor) continue; collision = pair.collision; bodyA = collision.parentA; bodyB = collision.parentB; normal = collision.normal; // get current separation between body edges involved in collision bodyBtoA = Vector.sub(Vector.add(bodyB.positionImpulse, bodyB.position, tempA), Vector.add(bodyA.positionImpulse, Vector.sub(bodyB.position, collision.penetration, tempB), tempC), tempD); pair.separation = Vector.dot(normal, bodyBtoA); } for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive || pair.isSensor || pair.separation < 0) continue; collision = pair.collision; bodyA = collision.parentA; bodyB = collision.parentB; normal = collision.normal; positionImpulse = (pair.separation - pair.slop) * timeScale; if (bodyA.isStatic || bodyB.isStatic) positionImpulse *= 2; if (!(bodyA.isStatic || bodyA.isSleeping)) { contactShare = Resolver._positionDampen / bodyA.totalContacts; bodyA.positionImpulse.x += normal.x * positionImpulse * contactShare; bodyA.positionImpulse.y += normal.y * positionImpulse * contactShare; } if (!(bodyB.isStatic || bodyB.isSleeping)) { contactShare = Resolver._positionDampen / bodyB.totalContacts; bodyB.positionImpulse.x -= normal.x * positionImpulse * contactShare; bodyB.positionImpulse.y -= normal.y * positionImpulse * contactShare; } } }; /** * Apply position resolution. * @method postSolvePosition * @param {body[]} bodies */ Resolver.postSolvePosition = function(bodies) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; // reset contact count body.totalContacts = 0; if (body.positionImpulse.x !== 0 || body.positionImpulse.y !== 0) { // update body geometry for (var j = 0; j < body.parts.length; j++) { var part = body.parts[j]; Vertices.translate(part.vertices, body.positionImpulse); Bounds.update(part.bounds, part.vertices, body.velocity); part.position.x += body.positionImpulse.x; part.position.y += body.positionImpulse.y; } // move the body without changing velocity body.positionPrev.x += body.positionImpulse.x; body.positionPrev.y += body.positionImpulse.y; if (Vector.dot(body.positionImpulse, body.velocity) < 0) { // reset cached impulse if the body has velocity along it body.positionImpulse.x = 0; body.positionImpulse.y = 0; } else { // warm the next iteration body.positionImpulse.x *= Resolver._positionWarming; body.positionImpulse.y *= Resolver._positionWarming; } } } }; /** * Prepare pairs for velocity solving. * @method preSolveVelocity * @param {pair[]} pairs */ Resolver.preSolveVelocity = function(pairs) { var i, j, pair, contacts, collision, bodyA, bodyB, normal, tangent, contact, contactVertex, normalImpulse, tangentImpulse, offset, impulse = Vector._temp[0], tempA = Vector._temp[1]; for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive || pair.isSensor) continue; contacts = pair.activeContacts; collision = pair.collision; bodyA = collision.parentA; bodyB = collision.parentB; normal = collision.normal; tangent = collision.tangent; // resolve each contact for (j = 0; j < contacts.length; j++) { contact = contacts[j]; contactVertex = contact.vertex; normalImpulse = contact.normalImpulse; tangentImpulse = contact.tangentImpulse; if (normalImpulse !== 0 || tangentImpulse !== 0) { // total impulse from contact impulse.x = (normal.x * normalImpulse) + (tangent.x * tangentImpulse); impulse.y = (normal.y * normalImpulse) + (tangent.y * tangentImpulse); // apply impulse from contact if (!(bodyA.isStatic || bodyA.isSleeping)) { offset = Vector.sub(contactVertex, bodyA.position, tempA); bodyA.positionPrev.x += impulse.x * bodyA.inverseMass; bodyA.positionPrev.y += impulse.y * bodyA.inverseMass; bodyA.anglePrev += Vector.cross(offset, impulse) * bodyA.inverseInertia; } if (!(bodyB.isStatic || bodyB.isSleeping)) { offset = Vector.sub(contactVertex, bodyB.position, tempA); bodyB.positionPrev.x -= impulse.x * bodyB.inverseMass; bodyB.positionPrev.y -= impulse.y * bodyB.inverseMass; bodyB.anglePrev -= Vector.cross(offset, impulse) * bodyB.inverseInertia; } } } } }; /** * Find a solution for pair velocities. * @method solveVelocity * @param {pair[]} pairs * @param {number} timeScale */ Resolver.solveVelocity = function(pairs, timeScale) { var timeScaleSquared = timeScale * timeScale, impulse = Vector._temp[0], tempA = Vector._temp[1], tempB = Vector._temp[2], tempC = Vector._temp[3], tempD = Vector._temp[4], tempE = Vector._temp[5]; for (var i = 0; i < pairs.length; i++) { var pair = pairs[i]; if (!pair.isActive || pair.isSensor) continue; var collision = pair.collision, bodyA = collision.parentA, bodyB = collision.parentB, normal = collision.normal, tangent = collision.tangent, contacts = pair.activeContacts, contactShare = 1 / contacts.length; // update body velocities bodyA.velocity.x = bodyA.position.x - bodyA.positionPrev.x; bodyA.velocity.y = bodyA.position.y - bodyA.positionPrev.y; bodyB.velocity.x = bodyB.position.x - bodyB.positionPrev.x; bodyB.velocity.y = bodyB.position.y - bodyB.positionPrev.y; bodyA.angularVelocity = bodyA.angle - bodyA.anglePrev; bodyB.angularVelocity = bodyB.angle - bodyB.anglePrev; // resolve each contact for (var j = 0; j < contacts.length; j++) { var contact = contacts[j], contactVertex = contact.vertex, offsetA = Vector.sub(contactVertex, bodyA.position, tempA), offsetB = Vector.sub(contactVertex, bodyB.position, tempB), velocityPointA = Vector.add(bodyA.velocity, Vector.mult(Vector.perp(offsetA), bodyA.angularVelocity), tempC), velocityPointB = Vector.add(bodyB.velocity, Vector.mult(Vector.perp(offsetB), bodyB.angularVelocity), tempD), relativeVelocity = Vector.sub(velocityPointA, velocityPointB, tempE), normalVelocity = Vector.dot(normal, relativeVelocity); var tangentVelocity = Vector.dot(tangent, relativeVelocity), tangentSpeed = Math.abs(tangentVelocity), tangentVelocityDirection = Common.sign(tangentVelocity); // raw impulses var normalImpulse = (1 + pair.restitution) * normalVelocity, normalForce = Common.clamp(pair.separation + normalVelocity, 0, 1) * Resolver._frictionNormalMultiplier; // coulomb friction var tangentImpulse = tangentVelocity, maxFriction = Infinity; if (tangentSpeed > pair.friction * pair.frictionStatic * normalForce * timeScaleSquared) { maxFriction = tangentSpeed; tangentImpulse = Common.clamp( pair.friction * tangentVelocityDirection * timeScaleSquared, -maxFriction, maxFriction ); } // modify impulses accounting for mass, inertia and offset var oAcN = Vector.cross(offsetA, normal), oBcN = Vector.cross(offsetB, normal), share = contactShare / (bodyA.inverseMass + bodyB.inverseMass + bodyA.inverseInertia * oAcN * oAcN + bodyB.inverseInertia * oBcN * oBcN); normalImpulse *= share; tangentImpulse *= share; // handle high velocity and resting collisions separately if (normalVelocity < 0 && normalVelocity * normalVelocity > Resolver._restingThresh * timeScaleSquared) { // high normal velocity so clear cached contact normal impulse contact.normalImpulse = 0; } else { // solve resting collision constraints using Erin Catto's method (GDC08) // impulse constraint tends to 0 var contactNormalImpulse = contact.normalImpulse; contact.normalImpulse = Math.min(contact.normalImpulse + normalImpulse, 0); normalImpulse = contact.normalImpulse - contactNormalImpulse; } // handle high velocity and resting collisions separately if (tangentVelocity * tangentVelocity > Resolver._restingThreshTangent * timeScaleSquared) { // high tangent velocity so clear cached contact tangent impulse contact.tangentImpulse = 0; } else { // solve resting collision constraints using Erin Catto's method (GDC08) // tangent impulse tends to -tangentSpeed or +tangentSpeed var contactTangentImpulse = contact.tangentImpulse; contact.tangentImpulse = Common.clamp(contact.tangentImpulse + tangentImpulse, -maxFriction, maxFriction); tangentImpulse = contact.tangentImpulse - contactTangentImpulse; } // total impulse from contact impulse.x = (normal.x * normalImpulse) + (tangent.x * tangentImpulse); impulse.y = (normal.y * normalImpulse) + (tangent.y * tangentImpulse); // apply impulse from contact if (!(bodyA.isStatic || bodyA.isSleeping)) { bodyA.positionPrev.x += impulse.x * bodyA.inverseMass; bodyA.positionPrev.y += impulse.y * bodyA.inverseMass; bodyA.anglePrev += Vector.cross(offsetA, impulse) * bodyA.inverseInertia; } if (!(bodyB.isStatic || bodyB.isSleeping)) { bodyB.positionPrev.x -= impulse.x * bodyB.inverseMass; bodyB.positionPrev.y -= impulse.y * bodyB.inverseMass; bodyB.anglePrev -= Vector.cross(offsetB, impulse) * bodyB.inverseInertia; } } } }; })(); },{"../core/Common":14,"../geometry/Bounds":24,"../geometry/Vector":26,"../geometry/Vertices":27}],11:[function(require,module,exports){ /** * The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem. * * @class SAT */ // TODO: true circles and curves var SAT = {}; module.exports = SAT; var Vertices = require('../geometry/Vertices'); var Vector = require('../geometry/Vector'); (function() { /** * Detect collision between two bodies using the Separating Axis Theorem. * @method collides * @param {body} bodyA * @param {body} bodyB * @param {collision} previousCollision * @return {collision} collision */ SAT.collides = function(bodyA, bodyB, previousCollision) { var overlapAB, overlapBA, minOverlap, collision, prevCol = previousCollision, canReusePrevCol = false; if (prevCol) { // estimate total motion var parentA = bodyA.parent, parentB = bodyB.parent, motion = parentA.speed * parentA.speed + parentA.angularSpeed * parentA.angularSpeed + parentB.speed * parentB.speed + parentB.angularSpeed * parentB.angularSpeed; // we may be able to (partially) reuse collision result // but only safe if collision was resting canReusePrevCol = prevCol && prevCol.collided && motion < 0.2; // reuse collision object collision = prevCol; } else { collision = { collided: false, bodyA: bodyA, bodyB: bodyB }; } if (prevCol && canReusePrevCol) { // if we can reuse the collision result // we only need to test the previously found axis var axisBodyA = collision.axisBody, axisBodyB = axisBodyA === bodyA ? bodyB : bodyA, axes = [axisBodyA.axes[prevCol.axisNumber]]; minOverlap = _overlapAxes(axisBodyA.vertices, axisBodyB.vertices, axes); collision.reused = true; if (minOverlap.overlap <= 0) { collision.collided = false; return collision; } } else { // if we can't reuse a result, perform a full SAT test overlapAB = _overlapAxes(bodyA.vertices, bodyB.vertices, bodyA.axes); if (overlapAB.overlap <= 0) { collision.collided = false; return collision; } overlapBA = _overlapAxes(bodyB.vertices, bodyA.vertices, bodyB.axes); if (overlapBA.overlap <= 0) { collision.collided = false; return collision; } if (overlapAB.overlap < overlapBA.overlap) { minOverlap = overlapAB; collision.axisBody = bodyA; } else { minOverlap = overlapBA; collision.axisBody = bodyB; } // important for reuse later collision.axisNumber = minOverlap.axisNumber; } collision.bodyA = bodyA.id < bodyB.id ? bodyA : bodyB; collision.bodyB = bodyA.id < bodyB.id ? bodyB : bodyA; collision.collided = true; collision.normal = minOverlap.axis; collision.depth = minOverlap.overlap; collision.parentA = collision.bodyA.parent; collision.parentB = collision.bodyB.parent; bodyA = collision.bodyA; bodyB = collision.bodyB; // ensure normal is facing away from bodyA if (Vector.dot(collision.normal, Vector.sub(bodyB.position, bodyA.position)) > 0) collision.normal = Vector.neg(collision.normal); collision.tangent = Vector.perp(collision.normal); collision.penetration = { x: collision.normal.x * collision.depth, y: collision.normal.y * collision.depth }; // find support points, there is always either exactly one or two var verticesB = _findSupports(bodyA, bodyB, collision.normal), supports = collision.supports || []; supports.length = 0; // find the supports from bodyB that are inside bodyA if (Vertices.contains(bodyA.vertices, verticesB[0])) supports.push(verticesB[0]); if (Vertices.contains(bodyA.vertices, verticesB[1])) supports.push(verticesB[1]); // find the supports from bodyA that are inside bodyB if (supports.length < 2) { var verticesA = _findSupports(bodyB, bodyA, Vector.neg(collision.normal)); if (Vertices.contains(bodyB.vertices, verticesA[0])) supports.push(verticesA[0]); if (supports.length < 2 && Vertices.contains(bodyB.vertices, verticesA[1])) supports.push(verticesA[1]); } // account for the edge case of overlapping but no vertex containment if (supports.length < 1) supports = [verticesB[0]]; collision.supports = supports; return collision; }; /** * Find the overlap between two sets of vertices. * @method _overlapAxes * @private * @param {} verticesA * @param {} verticesB * @param {} axes * @return result */ var _overlapAxes = function(verticesA, verticesB, axes) { var projectionA = Vector._temp[0], projectionB = Vector._temp[1], result = { overlap: Number.MAX_VALUE }, overlap, axis; for (var i = 0; i < axes.length; i++) { axis = axes[i]; _projectToAxis(projectionA, verticesA, axis); _projectToAxis(projectionB, verticesB, axis); overlap = Math.min(projectionA.max - projectionB.min, projectionB.max - projectionA.min); if (overlap <= 0) { result.overlap = overlap; return result; } if (overlap < result.overlap) { result.overlap = overlap; result.axis = axis; result.axisNumber = i; } } return result; }; /** * Projects vertices on an axis and returns an interval. * @method _projectToAxis * @private * @param {} projection * @param {} vertices * @param {} axis */ var _projectToAxis = function(projection, vertices, axis) { var min = Vector.dot(vertices[0], axis), max = min; for (var i = 1; i < vertices.length; i += 1) { var dot = Vector.dot(vertices[i], axis); if (dot > max) { max = dot; } else if (dot < min) { min = dot; } } projection.min = min; projection.max = max; }; /** * Finds supporting vertices given two bodies along a given direction using hill-climbing. * @method _findSupports * @private * @param {} bodyA * @param {} bodyB * @param {} normal * @return [vector] */ var _findSupports = function(bodyA, bodyB, normal) { var nearestDistance = Number.MAX_VALUE, vertexToBody = Vector._temp[0], vertices = bodyB.vertices, bodyAPosition = bodyA.position, distance, vertex, vertexA, vertexB; // find closest vertex on bodyB for (var i = 0; i < vertices.length; i++) { vertex = vertices[i]; vertexToBody.x = vertex.x - bodyAPosition.x; vertexToBody.y = vertex.y - bodyAPosition.y; distance = -Vector.dot(normal, vertexToBody); if (distance < nearestDistance) { nearestDistance = distance; vertexA = vertex; } } // find next closest vertex using the two connected to it var prevIndex = vertexA.index - 1 >= 0 ? vertexA.index - 1 : vertices.length - 1; vertex = vertices[prevIndex]; vertexToBody.x = vertex.x - bodyAPosition.x; vertexToBody.y = vertex.y - bodyAPosition.y; nearestDistance = -Vector.dot(normal, vertexToBody); vertexB = vertex; var nextIndex = (vertexA.index + 1) % vertices.length; vertex = vertices[nextIndex]; vertexToBody.x = vertex.x - bodyAPosition.x; vertexToBody.y = vertex.y - bodyAPosition.y; distance = -Vector.dot(normal, vertexToBody); if (distance < nearestDistance) { vertexB = vertex; } return [vertexA, vertexB]; }; })(); },{"../geometry/Vector":26,"../geometry/Vertices":27}],12:[function(require,module,exports){ /** * The `Matter.Constraint` module contains methods for creating and manipulating constraints. * Constraints are used for specifying that a fixed distance must be maintained between two bodies (or a body and a fixed world-space position). * The stiffness of constraints can be modified to create springs or elastic. * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Constraint */ // TODO: fix instability issues with torque // TODO: linked constraints // TODO: breakable constraints // TODO: collision constraints // TODO: allow constrained bodies to sleep // TODO: handle 0 length constraints properly // TODO: impulse caching and warming var Constraint = {}; module.exports = Constraint; var Vertices = require('../geometry/Vertices'); var Vector = require('../geometry/Vector'); var Sleeping = require('../core/Sleeping'); var Bounds = require('../geometry/Bounds'); var Axes = require('../geometry/Axes'); var Common = require('../core/Common'); (function() { var _minLength = 0.000001, _minDifference = 0.001; /** * Creates a new constraint. * All properties have default values, and many are pre-calculated automatically based on other properties. * See the properties section below for detailed information on what you can pass via the `options` object. * @method create * @param {} options * @return {constraint} constraint */ Constraint.create = function(options) { var constraint = options; // if bodies defined but no points, use body centre if (constraint.bodyA && !constraint.pointA) constraint.pointA = { x: 0, y: 0 }; if (constraint.bodyB && !constraint.pointB) constraint.pointB = { x: 0, y: 0 }; // calculate static length using initial world space points var initialPointA = constraint.bodyA ? Vector.add(constraint.bodyA.position, constraint.pointA) : constraint.pointA, initialPointB = constraint.bodyB ? Vector.add(constraint.bodyB.position, constraint.pointB) : constraint.pointB, length = Vector.magnitude(Vector.sub(initialPointA, initialPointB)); constraint.length = constraint.length || length || _minLength; // render var render = { visible: true, lineWidth: 2, strokeStyle: '#666' }; constraint.render = Common.extend(render, constraint.render); // option defaults constraint.id = constraint.id || Common.nextId(); constraint.label = constraint.label || 'Constraint'; constraint.type = 'constraint'; constraint.stiffness = constraint.stiffness || 1; constraint.angularStiffness = constraint.angularStiffness || 0; constraint.angleA = constraint.bodyA ? constraint.bodyA.angle : constraint.angleA; constraint.angleB = constraint.bodyB ? constraint.bodyB.angle : constraint.angleB; return constraint; }; /** * Solves all constraints in a list of collisions. * @private * @method solveAll * @param {constraint[]} constraints * @param {number} timeScale */ Constraint.solveAll = function(constraints, timeScale) { for (var i = 0; i < constraints.length; i++) { Constraint.solve(constraints[i], timeScale); } }; /** * Solves a distance constraint with Gauss-Siedel method. * @private * @method solve * @param {constraint} constraint * @param {number} timeScale */ Constraint.solve = function(constraint, timeScale) { var bodyA = constraint.bodyA, bodyB = constraint.bodyB, pointA = constraint.pointA, pointB = constraint.pointB; // update reference angle if (bodyA && !bodyA.isStatic) { constraint.pointA = Vector.rotate(pointA, bodyA.angle - constraint.angleA); constraint.angleA = bodyA.angle; } // update reference angle if (bodyB && !bodyB.isStatic) { constraint.pointB = Vector.rotate(pointB, bodyB.angle - constraint.angleB); constraint.angleB = bodyB.angle; } var pointAWorld = pointA, pointBWorld = pointB; if (bodyA) pointAWorld = Vector.add(bodyA.position, pointA); if (bodyB) pointBWorld = Vector.add(bodyB.position, pointB); if (!pointAWorld || !pointBWorld) return; var delta = Vector.sub(pointAWorld, pointBWorld), currentLength = Vector.magnitude(delta); // prevent singularity if (currentLength === 0) currentLength = _minLength; // solve distance constraint with Gauss-Siedel method var difference = (currentLength - constraint.length) / currentLength, normal = Vector.div(delta, currentLength), force = Vector.mult(delta, difference * 0.5 * constraint.stiffness * timeScale * timeScale); // if difference is very small, we can skip if (Math.abs(1 - (currentLength / constraint.length)) < _minDifference * timeScale) return; var velocityPointA, velocityPointB, offsetA, offsetB, oAn, oBn, bodyADenom, bodyBDenom; if (bodyA && !bodyA.isStatic) { // point body offset offsetA = { x: pointAWorld.x - bodyA.position.x + force.x, y: pointAWorld.y - bodyA.position.y + force.y }; // update velocity bodyA.velocity.x = bodyA.position.x - bodyA.positionPrev.x; bodyA.velocity.y = bodyA.position.y - bodyA.positionPrev.y; bodyA.angularVelocity = bodyA.angle - bodyA.anglePrev; // find point velocity and body mass velocityPointA = Vector.add(bodyA.velocity, Vector.mult(Vector.perp(offsetA), bodyA.angularVelocity)); oAn = Vector.dot(offsetA, normal); bodyADenom = bodyA.inverseMass + bodyA.inverseInertia * oAn * oAn; } else { velocityPointA = { x: 0, y: 0 }; bodyADenom = bodyA ? bodyA.inverseMass : 0; } if (bodyB && !bodyB.isStatic) { // point body offset offsetB = { x: pointBWorld.x - bodyB.position.x - force.x, y: pointBWorld.y - bodyB.position.y - force.y }; // update velocity bodyB.velocity.x = bodyB.position.x - bodyB.positionPrev.x; bodyB.velocity.y = bodyB.position.y - bodyB.positionPrev.y; bodyB.angularVelocity = bodyB.angle - bodyB.anglePrev; // find point velocity and body mass velocityPointB = Vector.add(bodyB.velocity, Vector.mult(Vector.perp(offsetB), bodyB.angularVelocity)); oBn = Vector.dot(offsetB, normal); bodyBDenom = bodyB.inverseMass + bodyB.inverseInertia * oBn * oBn; } else { velocityPointB = { x: 0, y: 0 }; bodyBDenom = bodyB ? bodyB.inverseMass : 0; } var relativeVelocity = Vector.sub(velocityPointB, velocityPointA), normalImpulse = Vector.dot(normal, relativeVelocity) / (bodyADenom + bodyBDenom); if (normalImpulse > 0) normalImpulse = 0; var normalVelocity = { x: normal.x * normalImpulse, y: normal.y * normalImpulse }; var torque; if (bodyA && !bodyA.isStatic) { torque = Vector.cross(offsetA, normalVelocity) * bodyA.inverseInertia * (1 - constraint.angularStiffness); // keep track of applied impulses for post solving bodyA.constraintImpulse.x -= force.x; bodyA.constraintImpulse.y -= force.y; bodyA.constraintImpulse.angle += torque; // apply forces bodyA.position.x -= force.x; bodyA.position.y -= force.y; bodyA.angle += torque; } if (bodyB && !bodyB.isStatic) { torque = Vector.cross(offsetB, normalVelocity) * bodyB.inverseInertia * (1 - constraint.angularStiffness); // keep track of applied impulses for post solving bodyB.constraintImpulse.x += force.x; bodyB.constraintImpulse.y += force.y; bodyB.constraintImpulse.angle -= torque; // apply forces bodyB.position.x += force.x; bodyB.position.y += force.y; bodyB.angle -= torque; } }; /** * Performs body updates required after solving constraints. * @private * @method postSolveAll * @param {body[]} bodies */ Constraint.postSolveAll = function(bodies) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i], impulse = body.constraintImpulse; if (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0) { continue; } Sleeping.set(body, false); // update geometry and reset for (var j = 0; j < body.parts.length; j++) { var part = body.parts[j]; Vertices.translate(part.vertices, impulse); if (j > 0) { part.position.x += impulse.x; part.position.y += impulse.y; } if (impulse.angle !== 0) { Vertices.rotate(part.vertices, impulse.angle, body.position); Axes.rotate(part.axes, impulse.angle); if (j > 0) { Vector.rotateAbout(part.position, impulse.angle, body.position, part.position); } } Bounds.update(part.bounds, part.vertices, body.velocity); } impulse.angle = 0; impulse.x = 0; impulse.y = 0; } }; /* * * Properties Documentation * */ /** * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. * * @property id * @type number */ /** * A `String` denoting the type of object. * * @property type * @type string * @default "constraint" * @readOnly */ /** * An arbitrary `String` name to help the user identify and manage bodies. * * @property label * @type string * @default "Constraint" */ /** * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. * * @property render * @type object */ /** * A flag that indicates if the constraint should be rendered. * * @property render.visible * @type boolean * @default true */ /** * A `Number` that defines the line width to use when rendering the constraint outline. * A value of `0` means no outline will be rendered. * * @property render.lineWidth * @type number * @default 2 */ /** * A `String` that defines the stroke style to use when rendering the constraint outline. * It is the same as when using a canvas, so it accepts CSS style property values. * * @property render.strokeStyle * @type string * @default a random colour */ /** * The first possible `Body` that this constraint is attached to. * * @property bodyA * @type body * @default null */ /** * The second possible `Body` that this constraint is attached to. * * @property bodyB * @type body * @default null */ /** * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. * * @property pointA * @type vector * @default { x: 0, y: 0 } */ /** * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. * * @property pointB * @type vector * @default { x: 0, y: 0 } */ /** * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. * A value of `1` means the constraint should be very stiff. * A value of `0.2` means the constraint acts like a soft spring. * * @property stiffness * @type number * @default 1 */ /** * A `Number` that specifies the target resting length of the constraint. * It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. * * @property length * @type number */ })(); },{"../core/Common":14,"../core/Sleeping":20,"../geometry/Axes":23,"../geometry/Bounds":24,"../geometry/Vector":26,"../geometry/Vertices":27}],13:[function(require,module,exports){ /** * The `Matter.MouseConstraint` module contains methods for creating mouse constraints. * Mouse constraints are used for allowing user interaction, providing the ability to move bodies via the mouse or touch. * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class MouseConstraint */ var MouseConstraint = {}; module.exports = MouseConstraint; var Vertices = require('../geometry/Vertices'); var Sleeping = require('../core/Sleeping'); var Mouse = require('../core/Mouse'); var Events = require('../core/Events'); var Detector = require('../collision/Detector'); var Constraint = require('./Constraint'); var Composite = require('../body/Composite'); var Common = require('../core/Common'); var Bounds = require('../geometry/Bounds'); (function() { /** * Creates a new mouse constraint. * All properties have default values, and many are pre-calculated automatically based on other properties. * See the properties section below for detailed information on what you can pass via the `options` object. * @method create * @param {engine} engine * @param {} options * @return {MouseConstraint} A new MouseConstraint */ MouseConstraint.create = function(engine, options) { var mouse = (engine ? engine.mouse : null) || (options ? options.mouse : null); if (!mouse) { if (engine && engine.render && engine.render.canvas) { mouse = Mouse.create(engine.render.canvas); } else if (options && options.element) { mouse = Mouse.create(options.element); } else { mouse = Mouse.create(); Common.log('MouseConstraint.create: options.mouse was undefined, options.element was undefined, may not function as expected', 'warn'); } } var constraint = Constraint.create({ label: 'Mouse Constraint', pointA: mouse.position, pointB: { x: 0, y: 0 }, length: 0.01, stiffness: 0.1, angularStiffness: 1, render: { strokeStyle: '#90EE90', lineWidth: 3 } }); var defaults = { type: 'mouseConstraint', mouse: mouse, element: null, body: null, constraint: constraint, collisionFilter: { category: 0x0001, mask: 0xFFFFFFFF, group: 0 } }; var mouseConstraint = Common.extend(defaults, options); Events.on(engine, 'tick', function() { var allBodies = Composite.allBodies(engine.world); MouseConstraint.update(mouseConstraint, allBodies); _triggerEvents(mouseConstraint); }); return mouseConstraint; }; /** * Updates the given mouse constraint. * @private * @method update * @param {MouseConstraint} mouseConstraint * @param {body[]} bodies */ MouseConstraint.update = function(mouseConstraint, bodies) { var mouse = mouseConstraint.mouse, constraint = mouseConstraint.constraint, body = mouseConstraint.body; if (mouse.button === 0) { if (!constraint.bodyB) { for (var i = 0; i < bodies.length; i++) { body = bodies[i]; if (Bounds.contains(body.bounds, mouse.position) && Detector.canCollide(body.collisionFilter, mouseConstraint.collisionFilter)) { for (var j = body.parts.length > 1 ? 1 : 0; j < body.parts.length; j++) { var part = body.parts[j]; if (Vertices.contains(part.vertices, mouse.position)) { constraint.pointA = mouse.position; constraint.bodyB = mouseConstraint.body = body; constraint.pointB = { x: mouse.position.x - body.position.x, y: mouse.position.y - body.position.y }; constraint.angleB = body.angle; Sleeping.set(body, false); Events.trigger(mouseConstraint, 'startdrag', { mouse: mouse, body: body }); break; } } } } } else { Sleeping.set(constraint.bodyB, false); constraint.pointA = mouse.position; } } else { constraint.bodyB = mouseConstraint.body = null; constraint.pointB = null; if (body) Events.trigger(mouseConstraint, 'enddrag', { mouse: mouse, body: body }); } }; /** * Triggers mouse constraint events. * @method _triggerEvents * @private * @param {mouse} mouseConstraint */ var _triggerEvents = function(mouseConstraint) { var mouse = mouseConstraint.mouse, mouseEvents = mouse.sourceEvents; if (mouseEvents.mousemove) Events.trigger(mouseConstraint, 'mousemove', { mouse: mouse }); if (mouseEvents.mousedown) Events.trigger(mouseConstraint, 'mousedown', { mouse: mouse }); if (mouseEvents.mouseup) Events.trigger(mouseConstraint, 'mouseup', { mouse: mouse }); // reset the mouse state ready for the next step Mouse.clearSourceEvents(mouse); }; /* * * Events Documentation * */ /** * Fired when the mouse has moved (or a touch moves) during the last step * * @event mousemove * @param {} event An event object * @param {mouse} event.mouse The engine's mouse instance * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired when the mouse is down (or a touch has started) during the last step * * @event mousedown * @param {} event An event object * @param {mouse} event.mouse The engine's mouse instance * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired when the mouse is up (or a touch has ended) during the last step * * @event mouseup * @param {} event An event object * @param {mouse} event.mouse The engine's mouse instance * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired when the user starts dragging a body * * @event startdrag * @param {} event An event object * @param {mouse} event.mouse The engine's mouse instance * @param {body} event.body The body being dragged * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired when the user ends dragging a body * * @event enddrag * @param {} event An event object * @param {mouse} event.mouse The engine's mouse instance * @param {body} event.body The body that has stopped being dragged * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /* * * Properties Documentation * */ /** * A `String` denoting the type of object. * * @property type * @type string * @default "constraint" * @readOnly */ /** * The `Mouse` instance in use. If not supplied in `MouseConstraint.create`, one will be created. * * @property mouse * @type mouse * @default mouse */ /** * The `Body` that is currently being moved by the user, or `null` if no body. * * @property body * @type body * @default null */ /** * The `Constraint` object that is used to move the body during interaction. * * @property constraint * @type constraint */ /** * An `Object` that specifies the collision filter properties. * The collision filter allows the user to define which types of body this mouse constraint can interact with. * See `body.collisionFilter` for more information. * * @property collisionFilter * @type object */ })(); },{"../body/Composite":2,"../collision/Detector":5,"../core/Common":14,"../core/Events":16,"../core/Mouse":18,"../core/Sleeping":20,"../geometry/Bounds":24,"../geometry/Vertices":27,"./Constraint":12}],14:[function(require,module,exports){ /** * The `Matter.Common` module contains utility functions that are common to all modules. * * @class Common */ var Common = {}; module.exports = Common; (function() { Common._nextId = 0; Common._seed = 0; /** * Extends the object in the first argument using the object in the second argument. * @method extend * @param {} obj * @param {boolean} deep * @return {} obj extended */ Common.extend = function(obj, deep) { var argsStart, args, deepClone; if (typeof deep === 'boolean') { argsStart = 2; deepClone = deep; } else { argsStart = 1; deepClone = true; } args = Array.prototype.slice.call(arguments, argsStart); for (var i = 0; i < args.length; i++) { var source = args[i]; if (source) { for (var prop in source) { if (deepClone && source[prop] && source[prop].constructor === Object) { if (!obj[prop] || obj[prop].constructor === Object) { obj[prop] = obj[prop] || {}; Common.extend(obj[prop], deepClone, source[prop]); } else { obj[prop] = source[prop]; } } else { obj[prop] = source[prop]; } } } } return obj; }; /** * Creates a new clone of the object, if deep is true references will also be cloned. * @method clone * @param {} obj * @param {bool} deep * @return {} obj cloned */ Common.clone = function(obj, deep) { return Common.extend({}, deep, obj); }; /** * Returns the list of keys for the given object. * @method keys * @param {} obj * @return {string[]} keys */ Common.keys = function(obj) { if (Object.keys) return Object.keys(obj); // avoid hasOwnProperty for performance var keys = []; for (var key in obj) keys.push(key); return keys; }; /** * Returns the list of values for the given object. * @method values * @param {} obj * @return {array} Array of the objects property values */ Common.values = function(obj) { var values = []; if (Object.keys) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { values.push(obj[keys[i]]); } return values; } // avoid hasOwnProperty for performance for (var key in obj) values.push(obj[key]); return values; }; /** * Returns a hex colour string made by lightening or darkening color by percent. * @method shadeColor * @param {string} color * @param {number} percent * @return {string} A hex colour */ Common.shadeColor = function(color, percent) { // http://stackoverflow.com/questions/5560248/programmatically-lighten-or-darken-a-hex-color var colorInteger = parseInt(color.slice(1),16), amount = Math.round(2.55 * percent), R = (colorInteger >> 16) + amount, B = (colorInteger >> 8 & 0x00FF) + amount, G = (colorInteger & 0x0000FF) + amount; return "#" + (0x1000000 + (R < 255 ? R < 1 ? 0 : R :255) * 0x10000 + (B < 255 ? B < 1 ? 0 : B : 255) * 0x100 + (G < 255 ? G < 1 ? 0 : G : 255)).toString(16).slice(1); }; /** * Shuffles the given array in-place. * The function uses a seeded random generator. * @method shuffle * @param {array} array * @return {array} array shuffled randomly */ Common.shuffle = function(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Common.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; }; /** * Randomly chooses a value from a list with equal probability. * The function uses a seeded random generator. * @method choose * @param {array} choices * @return {object} A random choice object from the array */ Common.choose = function(choices) { return choices[Math.floor(Common.random() * choices.length)]; }; /** * Returns true if the object is a HTMLElement, otherwise false. * @method isElement * @param {object} obj * @return {boolean} True if the object is a HTMLElement, otherwise false */ Common.isElement = function(obj) { // http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object try { return obj instanceof HTMLElement; } catch(e){ return (typeof obj==="object") && (obj.nodeType===1) && (typeof obj.style === "object") && (typeof obj.ownerDocument ==="object"); } }; /** * Returns true if the object is an array. * @method isArray * @param {object} obj * @return {boolean} True if the object is an array, otherwise false */ Common.isArray = function(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; /** * Returns the given value clamped between a minimum and maximum value. * @method clamp * @param {number} value * @param {number} min * @param {number} max * @return {number} The value clamped between min and max inclusive */ Common.clamp = function(value, min, max) { if (value < min) return min; if (value > max) return max; return value; }; /** * Returns the sign of the given value. * @method sign * @param {number} value * @return {number} -1 if negative, +1 if 0 or positive */ Common.sign = function(value) { return value < 0 ? -1 : 1; }; /** * Returns the current timestamp (high-res if available). * @method now * @return {number} the current timestamp (high-res if available) */ Common.now = function() { // http://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript // https://gist.github.com/davidwaterston/2982531 var performance = window.performance || {}; performance.now = (function() { return performance.now || performance.webkitNow || performance.msNow || performance.oNow || performance.mozNow || function() { return +(new Date()); }; })(); return performance.now(); }; /** * Returns a random value between a minimum and a maximum value inclusive. * The function uses a seeded random generator. * @method random * @param {number} min * @param {number} max * @return {number} A random number between min and max inclusive */ Common.random = function(min, max) { min = (typeof min !== "undefined") ? min : 0; max = (typeof max !== "undefined") ? max : 1; return min + _seededRandom() * (max - min); }; /** * Converts a CSS hex colour string into an integer. * @method colorToNumber * @param {string} colorString * @return {number} An integer representing the CSS hex string */ Common.colorToNumber = function(colorString) { colorString = colorString.replace('#',''); if (colorString.length == 3) { colorString = colorString.charAt(0) + colorString.charAt(0) + colorString.charAt(1) + colorString.charAt(1) + colorString.charAt(2) + colorString.charAt(2); } return parseInt(colorString, 16); }; /** * A wrapper for console.log, for providing errors and warnings. * @method log * @param {string} message * @param {string} type */ Common.log = function(message, type) { if (!console || !console.log || !console.warn) return; switch (type) { case 'warn': console.warn('Matter.js:', message); break; case 'error': console.log('Matter.js:', message); break; } }; /** * Returns the next unique sequential ID. * @method nextId * @return {Number} Unique sequential ID */ Common.nextId = function() { return Common._nextId++; }; /** * A cross browser compatible indexOf implementation. * @method indexOf * @param {array} haystack * @param {object} needle */ Common.indexOf = function(haystack, needle) { if (haystack.indexOf) return haystack.indexOf(needle); for (var i = 0; i < haystack.length; i++) { if (haystack[i] === needle) return i; } return -1; }; var _seededRandom = function() { // https://gist.github.com/ngryman/3830489 Common._seed = (Common._seed * 9301 + 49297) % 233280; return Common._seed / 233280; }; })(); },{}],15:[function(require,module,exports){ /** * The `Matter.Engine` module contains methods for creating and manipulating engines. * An engine is a controller that manages updating the simulation of the world. * See `Matter.Runner` for an optional game loop utility. * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Engine */ var Engine = {}; module.exports = Engine; var World = require('../body/World'); var Sleeping = require('./Sleeping'); var Resolver = require('../collision/Resolver'); var Render = require('../render/Render'); var Pairs = require('../collision/Pairs'); var Metrics = require('./Metrics'); var Grid = require('../collision/Grid'); var Events = require('./Events'); var Composite = require('../body/Composite'); var Constraint = require('../constraint/Constraint'); var Common = require('./Common'); var Body = require('../body/Body'); (function() { /** * Creates a new engine. The options parameter is an object that specifies any properties you wish to override the defaults. * All properties have default values, and many are pre-calculated automatically based on other properties. * See the properties section below for detailed information on what you can pass via the `options` object. * @method create * @param {object} [options] * @return {engine} engine */ Engine.create = function(element, options) { // options may be passed as the first (and only) argument options = Common.isElement(element) ? options : element; element = Common.isElement(element) ? element : null; options = options || {}; if (element || options.render) { Common.log('Engine.create: engine.render is deprecated (see docs)', 'warn'); } var defaults = { positionIterations: 6, velocityIterations: 4, constraintIterations: 2, enableSleeping: false, events: [], timing: { timestamp: 0, timeScale: 1 }, broadphase: { controller: Grid } }; var engine = Common.extend(defaults, options); // @deprecated if (element || engine.render) { var renderDefaults = { element: element, controller: Render }; engine.render = Common.extend(renderDefaults, engine.render); } // @deprecated if (engine.render && engine.render.controller) { engine.render = engine.render.controller.create(engine.render); } // @deprecated if (engine.render) { engine.render.engine = engine; } engine.world = options.world || World.create(engine.world); engine.pairs = Pairs.create(); engine.broadphase = engine.broadphase.controller.create(engine.broadphase); engine.metrics = engine.metrics || { extended: false }; return engine; }; /** * Moves the simulation forward in time by `delta` ms. * The `correction` argument is an optional `Number` that specifies the time correction factor to apply to the update. * This can help improve the accuracy of the simulation in cases where `delta` is changing between updates. * The value of `correction` is defined as `delta / lastDelta`, i.e. the percentage change of `delta` over the last step. * Therefore the value is always `1` (no correction) when `delta` constant (or when no correction is desired, which is the default). * See the paper on Time Corrected Verlet for more information. * * Triggers `beforeUpdate` and `afterUpdate` events. * Triggers `collisionStart`, `collisionActive` and `collisionEnd` events. * @method update * @param {engine} engine * @param {number} [delta=16.666] * @param {number} [correction=1] */ Engine.update = function(engine, delta, correction) { delta = delta || 1000 / 60; correction = correction || 1; var world = engine.world, timing = engine.timing, broadphase = engine.broadphase, broadphasePairs = [], i; // increment timestamp timing.timestamp += delta * timing.timeScale; // create an event object var event = { timestamp: timing.timestamp }; Events.trigger(engine, 'beforeUpdate', event); // get lists of all bodies and constraints, no matter what composites they are in var allBodies = Composite.allBodies(world), allConstraints = Composite.allConstraints(world); // if sleeping enabled, call the sleeping controller if (engine.enableSleeping) Sleeping.update(allBodies, timing.timeScale); // applies gravity to all bodies _bodiesApplyGravity(allBodies, world.gravity); // update all body position and rotation by integration _bodiesUpdate(allBodies, delta, timing.timeScale, correction, world.bounds); // update all constraints for (i = 0; i < engine.constraintIterations; i++) { Constraint.solveAll(allConstraints, timing.timeScale); } Constraint.postSolveAll(allBodies); // broadphase pass: find potential collision pairs if (broadphase.controller) { // if world is dirty, we must flush the whole grid if (world.isModified) broadphase.controller.clear(broadphase); // update the grid buckets based on current bodies broadphase.controller.update(broadphase, allBodies, engine, world.isModified); broadphasePairs = broadphase.pairsList; } else { // if no broadphase set, we just pass all bodies broadphasePairs = allBodies; } // clear all composite modified flags if (world.isModified) { Composite.setModified(world, false, false, true); } // narrowphase pass: find actual collisions, then create or update collision pairs var collisions = broadphase.detector(broadphasePairs, engine); // update collision pairs var pairs = engine.pairs, timestamp = timing.timestamp; Pairs.update(pairs, collisions, timestamp); Pairs.removeOld(pairs, timestamp); // wake up bodies involved in collisions if (engine.enableSleeping) Sleeping.afterCollisions(pairs.list, timing.timeScale); // trigger collision events if (pairs.collisionStart.length > 0) Events.trigger(engine, 'collisionStart', { pairs: pairs.collisionStart }); // iteratively resolve position between collisions Resolver.preSolvePosition(pairs.list); for (i = 0; i < engine.positionIterations; i++) { Resolver.solvePosition(pairs.list, timing.timeScale); } Resolver.postSolvePosition(allBodies); // iteratively resolve velocity between collisions Resolver.preSolveVelocity(pairs.list); for (i = 0; i < engine.velocityIterations; i++) { Resolver.solveVelocity(pairs.list, timing.timeScale); } // trigger collision events if (pairs.collisionActive.length > 0) Events.trigger(engine, 'collisionActive', { pairs: pairs.collisionActive }); if (pairs.collisionEnd.length > 0) Events.trigger(engine, 'collisionEnd', { pairs: pairs.collisionEnd }); // clear force buffers _bodiesClearForces(allBodies); Events.trigger(engine, 'afterUpdate', event); return engine; }; /** * Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`. * @method merge * @param {engine} engineA * @param {engine} engineB */ Engine.merge = function(engineA, engineB) { Common.extend(engineA, engineB); if (engineB.world) { engineA.world = engineB.world; Engine.clear(engineA); var bodies = Composite.allBodies(engineA.world); for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; Sleeping.set(body, false); body.id = Common.nextId(); } } }; /** * Clears the engine including the world, pairs and broadphase. * @method clear * @param {engine} engine */ Engine.clear = function(engine) { var world = engine.world; Pairs.clear(engine.pairs); var broadphase = engine.broadphase; if (broadphase.controller) { var bodies = Composite.allBodies(world); broadphase.controller.clear(broadphase); broadphase.controller.update(broadphase, bodies, engine, true); } }; /** * Zeroes the `body.force` and `body.torque` force buffers. * @method bodiesClearForces * @private * @param {body[]} bodies */ var _bodiesClearForces = function(bodies) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; // reset force buffers body.force.x = 0; body.force.y = 0; body.torque = 0; } }; /** * Applys a mass dependant force to all given bodies. * @method bodiesApplyGravity * @private * @param {body[]} bodies * @param {vector} gravity */ var _bodiesApplyGravity = function(bodies, gravity) { var gravityScale = typeof gravity.scale !== 'undefined' ? gravity.scale : 0.001; if ((gravity.x === 0 && gravity.y === 0) || gravityScale === 0) { return; } for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (body.isStatic || body.isSleeping) continue; // apply gravity body.force.y += body.mass * gravity.y * gravityScale; body.force.x += body.mass * gravity.x * gravityScale; } }; /** * Applys `Body.update` to all given `bodies`. * @method updateAll * @private * @param {body[]} bodies * @param {number} deltaTime * The amount of time elapsed between updates * @param {number} timeScale * @param {number} correction * The Verlet correction factor (deltaTime / lastDeltaTime) * @param {bounds} worldBounds */ var _bodiesUpdate = function(bodies, deltaTime, timeScale, correction, worldBounds) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (body.isStatic || body.isSleeping) continue; Body.update(body, deltaTime, timeScale, correction); } }; /** * An alias for `Runner.run`, see `Matter.Runner` for more information. * @method run * @param {engine} engine */ /** * Fired just before an update * * @event beforeUpdate * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after engine update and all collision events * * @event afterUpdate * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any) * * @event collisionStart * @param {} event An event object * @param {} event.pairs List of affected pairs * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any) * * @event collisionActive * @param {} event An event object * @param {} event.pairs List of affected pairs * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any) * * @event collisionEnd * @param {} event An event object * @param {} event.pairs List of affected pairs * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /* * * Properties Documentation * */ /** * An integer `Number` that specifies the number of position iterations to perform each update. * The higher the value, the higher quality the simulation will be at the expense of performance. * * @property positionIterations * @type number * @default 6 */ /** * An integer `Number` that specifies the number of velocity iterations to perform each update. * The higher the value, the higher quality the simulation will be at the expense of performance. * * @property velocityIterations * @type number * @default 4 */ /** * An integer `Number` that specifies the number of constraint iterations to perform each update. * The higher the value, the higher quality the simulation will be at the expense of performance. * The default value of `2` is usually very adequate. * * @property constraintIterations * @type number * @default 2 */ /** * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. * Sleeping can improve stability and performance, but often at the expense of accuracy. * * @property enableSleeping * @type boolean * @default false */ /** * An `Object` containing properties regarding the timing systems of the engine. * * @property timing * @type object */ /** * A `Number` that specifies the global scaling factor of time for all bodies. * A value of `0` freezes the simulation. * A value of `0.1` gives a slow-motion effect. * A value of `1.2` gives a speed-up effect. * * @property timing.timeScale * @type number * @default 1 */ /** * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. * It is incremented on every `Engine.update` by the given `delta` argument. * * @property timing.timestamp * @type number * @default 0 */ /** * An instance of a `Render` controller. The default value is a `Matter.Render` instance created by `Engine.create`. * One may also develop a custom renderer module based on `Matter.Render` and pass an instance of it to `Engine.create` via `options.render`. * * A minimal custom renderer object must define at least three functions: `create`, `clear` and `world` (see `Matter.Render`). * It is also possible to instead pass the _module_ reference via `options.render.controller` and `Engine.create` will instantiate one for you. * * @property render * @type render * @deprecated see Demo.js for an example of creating a renderer * @default a Matter.Render instance */ /** * An instance of a broadphase controller. The default value is a `Matter.Grid` instance created by `Engine.create`. * * @property broadphase * @type grid * @default a Matter.Grid instance */ /** * A `World` composite object that will contain all simulated bodies and constraints. * * @property world * @type world * @default a Matter.World instance */ })(); },{"../body/Body":1,"../body/Composite":2,"../body/World":3,"../collision/Grid":6,"../collision/Pairs":8,"../collision/Resolver":10,"../constraint/Constraint":12,"../render/Render":29,"./Common":14,"./Events":16,"./Metrics":17,"./Sleeping":20}],16:[function(require,module,exports){ /** * The `Matter.Events` module contains methods to fire and listen to events on other objects. * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Events */ var Events = {}; module.exports = Events; var Common = require('./Common'); (function() { /** * Subscribes a callback function to the given object's `eventName`. * @method on * @param {} object * @param {string} eventNames * @param {function} callback */ Events.on = function(object, eventNames, callback) { var names = eventNames.split(' '), name; for (var i = 0; i < names.length; i++) { name = names[i]; object.events = object.events || {}; object.events[name] = object.events[name] || []; object.events[name].push(callback); } return callback; }; /** * Removes the given event callback. If no callback, clears all callbacks in `eventNames`. If no `eventNames`, clears all events. * @method off * @param {} object * @param {string} eventNames * @param {function} callback */ Events.off = function(object, eventNames, callback) { if (!eventNames) { object.events = {}; return; } // handle Events.off(object, callback) if (typeof eventNames === 'function') { callback = eventNames; eventNames = Common.keys(object.events).join(' '); } var names = eventNames.split(' '); for (var i = 0; i < names.length; i++) { var callbacks = object.events[names[i]], newCallbacks = []; if (callback && callbacks) { for (var j = 0; j < callbacks.length; j++) { if (callbacks[j] !== callback) newCallbacks.push(callbacks[j]); } } object.events[names[i]] = newCallbacks; } }; /** * Fires all the callbacks subscribed to the given object's `eventName`, in the order they subscribed, if any. * @method trigger * @param {} object * @param {string} eventNames * @param {} event */ Events.trigger = function(object, eventNames, event) { var names, name, callbacks, eventClone; if (object.events) { if (!event) event = {}; names = eventNames.split(' '); for (var i = 0; i < names.length; i++) { name = names[i]; callbacks = object.events[name]; if (callbacks) { eventClone = Common.clone(event, false); eventClone.name = name; eventClone.source = object; for (var j = 0; j < callbacks.length; j++) { callbacks[j].apply(object, [eventClone]); } } } } }; })(); },{"./Common":14}],17:[function(require,module,exports){ },{"../body/Composite":2,"./Common":14}],18:[function(require,module,exports){ /** * The `Matter.Mouse` module contains methods for creating and manipulating mouse inputs. * * @class Mouse */ var Mouse = {}; module.exports = Mouse; var Common = require('../core/Common'); (function() { /** * Creates a mouse input. * @method create * @param {HTMLElement} element * @return {mouse} A new mouse */ Mouse.create = function(element) { var mouse = {}; if (!element) { Common.log('Mouse.create: element was undefined, defaulting to document.body', 'warn'); } mouse.element = element || document.body; mouse.absolute = { x: 0, y: 0 }; mouse.position = { x: 0, y: 0 }; mouse.mousedownPosition = { x: 0, y: 0 }; mouse.mouseupPosition = { x: 0, y: 0 }; mouse.offset = { x: 0, y: 0 }; mouse.scale = { x: 1, y: 1 }; mouse.wheelDelta = 0; mouse.button = -1; mouse.pixelRatio = mouse.element.getAttribute('data-pixel-ratio') || 1; mouse.sourceEvents = { mousemove: null, mousedown: null, mouseup: null, mousewheel: null }; mouse.mousemove = function(event) { var position = _getRelativeMousePosition(event, mouse.element, mouse.pixelRatio), touches = event.changedTouches; if (touches) { mouse.button = 0; event.preventDefault(); } mouse.absolute.x = position.x; mouse.absolute.y = position.y; mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x; mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y; mouse.sourceEvents.mousemove = event; }; mouse.mousedown = function(event) { var position = _getRelativeMousePosition(event, mouse.element, mouse.pixelRatio), touches = event.changedTouches; if (touches) { mouse.button = 0; event.preventDefault(); } else { mouse.button = event.button; } mouse.absolute.x = position.x; mouse.absolute.y = position.y; mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x; mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y; mouse.mousedownPosition.x = mouse.position.x; mouse.mousedownPosition.y = mouse.position.y; mouse.sourceEvents.mousedown = event; }; mouse.mouseup = function(event) { var position = _getRelativeMousePosition(event, mouse.element, mouse.pixelRatio), touches = event.changedTouches; if (touches) { event.preventDefault(); } mouse.button = -1; mouse.absolute.x = position.x; mouse.absolute.y = position.y; mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x; mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y; mouse.mouseupPosition.x = mouse.position.x; mouse.mouseupPosition.y = mouse.position.y; mouse.sourceEvents.mouseup = event; }; mouse.mousewheel = function(event) { mouse.wheelDelta = Math.max(-1, Math.min(1, event.wheelDelta || -event.detail)); event.preventDefault(); }; Mouse.setElement(mouse, mouse.element); return mouse; }; /** * Sets the element the mouse is bound to (and relative to). * @method setElement * @param {mouse} mouse * @param {HTMLElement} element */ Mouse.setElement = function(mouse, element) { mouse.element = element; element.addEventListener('mousemove', mouse.mousemove); element.addEventListener('mousedown', mouse.mousedown); element.addEventListener('mouseup', mouse.mouseup); element.addEventListener('mousewheel', mouse.mousewheel); element.addEventListener('DOMMouseScroll', mouse.mousewheel); element.addEventListener('touchmove', mouse.mousemove); element.addEventListener('touchstart', mouse.mousedown); element.addEventListener('touchend', mouse.mouseup); }; /** * Clears all captured source events. * @method clearSourceEvents * @param {mouse} mouse */ Mouse.clearSourceEvents = function(mouse) { mouse.sourceEvents.mousemove = null; mouse.sourceEvents.mousedown = null; mouse.sourceEvents.mouseup = null; mouse.sourceEvents.mousewheel = null; mouse.wheelDelta = 0; }; /** * Sets the mouse position offset. * @method setOffset * @param {mouse} mouse * @param {vector} offset */ Mouse.setOffset = function(mouse, offset) { mouse.offset.x = offset.x; mouse.offset.y = offset.y; mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x; mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y; }; /** * Sets the mouse position scale. * @method setScale * @param {mouse} mouse * @param {vector} scale */ Mouse.setScale = function(mouse, scale) { mouse.scale.x = scale.x; mouse.scale.y = scale.y; mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x; mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y; }; /** * Gets the mouse position relative to an element given a screen pixel ratio. * @method _getRelativeMousePosition * @private * @param {} event * @param {} element * @param {number} pixelRatio * @return {} */ var _getRelativeMousePosition = function(event, element, pixelRatio) { var elementBounds = element.getBoundingClientRect(), rootNode = (document.documentElement || document.body.parentNode || document.body), scrollX = (window.pageXOffset !== undefined) ? window.pageXOffset : rootNode.scrollLeft, scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset : rootNode.scrollTop, touches = event.changedTouches, x, y; if (touches) { x = touches[0].pageX - elementBounds.left - scrollX; y = touches[0].pageY - elementBounds.top - scrollY; } else { x = event.pageX - elementBounds.left - scrollX; y = event.pageY - elementBounds.top - scrollY; } return { x: x / (element.clientWidth / element.width * pixelRatio), y: y / (element.clientHeight / element.height * pixelRatio) }; }; })(); },{"../core/Common":14}],19:[function(require,module,exports){ /** * The `Matter.Runner` module is an optional utility which provides a game loop, * that handles continuously updating a `Matter.Engine` for you within a browser. * It is intended for development and debugging purposes, but may also be suitable for simple games. * If you are using your own game loop instead, then you do not need the `Matter.Runner` module. * Instead just call `Engine.update(engine, delta)` in your own loop. * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Runner */ var Runner = {}; module.exports = Runner; var Events = require('./Events'); var Engine = require('./Engine'); var Common = require('./Common'); (function() { var _requestAnimationFrame, _cancelAnimationFrame; if (typeof window !== 'undefined') { _requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function(callback){ window.setTimeout(function() { callback(Common.now()); }, 1000 / 60); }; _cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.msCancelAnimationFrame; } /** * Creates a new Runner. The options parameter is an object that specifies any properties you wish to override the defaults. * @method create * @param {} options */ Runner.create = function(options) { var defaults = { fps: 60, correction: 1, deltaSampleSize: 60, counterTimestamp: 0, frameCounter: 0, deltaHistory: [], timePrev: null, timeScalePrev: 1, frameRequestId: null, isFixed: false, enabled: true }; var runner = Common.extend(defaults, options); runner.delta = runner.delta || 1000 / runner.fps; runner.deltaMin = runner.deltaMin || 1000 / runner.fps; runner.deltaMax = runner.deltaMax || 1000 / (runner.fps * 0.5); runner.fps = 1000 / runner.delta; return runner; }; /** * Continuously ticks a `Matter.Engine` by calling `Runner.tick` on the `requestAnimationFrame` event. * @method run * @param {engine} engine */ Runner.run = function(runner, engine) { // create runner if engine is first argument if (typeof runner.positionIterations !== 'undefined') { engine = runner; runner = Runner.create(); } (function render(time){ runner.frameRequestId = _requestAnimationFrame(render); if (time && runner.enabled) { Runner.tick(runner, engine, time); } })(); return runner; }; /** * A game loop utility that updates the engine and renderer by one step (a 'tick'). * Features delta smoothing, time correction and fixed or dynamic timing. * Triggers `beforeTick`, `tick` and `afterTick` events on the engine. * Consider just `Engine.update(engine, delta)` if you're using your own loop. * @method tick * @param {runner} runner * @param {engine} engine * @param {number} time */ Runner.tick = function(runner, engine, time) { var timing = engine.timing, correction = 1, delta; // create an event object var event = { timestamp: timing.timestamp }; Events.trigger(runner, 'beforeTick', event); Events.trigger(engine, 'beforeTick', event); // @deprecated if (runner.isFixed) { // fixed timestep delta = runner.delta; } else { // dynamic timestep based on wall clock between calls delta = (time - runner.timePrev) || runner.delta; runner.timePrev = time; // optimistically filter delta over a few frames, to improve stability runner.deltaHistory.push(delta); runner.deltaHistory = runner.deltaHistory.slice(-runner.deltaSampleSize); delta = Math.min.apply(null, runner.deltaHistory); // limit delta delta = delta < runner.deltaMin ? runner.deltaMin : delta; delta = delta > runner.deltaMax ? runner.deltaMax : delta; // correction for delta correction = delta / runner.delta; // update engine timing object runner.delta = delta; } // time correction for time scaling if (runner.timeScalePrev !== 0) correction *= timing.timeScale / runner.timeScalePrev; if (timing.timeScale === 0) correction = 0; runner.timeScalePrev = timing.timeScale; runner.correction = correction; // fps counter runner.frameCounter += 1; if (time - runner.counterTimestamp >= 1000) { runner.fps = runner.frameCounter * ((time - runner.counterTimestamp) / 1000); runner.counterTimestamp = time; runner.frameCounter = 0; } Events.trigger(runner, 'tick', event); Events.trigger(engine, 'tick', event); // @deprecated // if world has been modified, clear the render scene graph if (engine.world.isModified && engine.render && engine.render.controller && engine.render.controller.clear) { engine.render.controller.clear(engine.render); } // update Events.trigger(runner, 'beforeUpdate', event); Engine.update(engine, delta, correction); Events.trigger(runner, 'afterUpdate', event); // render // @deprecated if (engine.render && engine.render.controller) { Events.trigger(runner, 'beforeRender', event); Events.trigger(engine, 'beforeRender', event); // @deprecated engine.render.controller.world(engine.render); Events.trigger(runner, 'afterRender', event); Events.trigger(engine, 'afterRender', event); // @deprecated } Events.trigger(runner, 'afterTick', event); Events.trigger(engine, 'afterTick', event); // @deprecated }; /** * Ends execution of `Runner.run` on the given `runner`, by canceling the animation frame request event loop. * If you wish to only temporarily pause the engine, see `engine.enabled` instead. * @method stop * @param {runner} runner */ Runner.stop = function(runner) { _cancelAnimationFrame(runner.frameRequestId); }; /** * Alias for `Runner.run`. * @method start * @param {runner} runner * @param {engine} engine */ Runner.start = function(runner, engine) { Runner.run(runner, engine); }; /* * * Events Documentation * */ /** * Fired at the start of a tick, before any updates to the engine or timing * * @event beforeTick * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after engine timing updated, but just before update * * @event tick * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired at the end of a tick, after engine update and after rendering * * @event afterTick * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired before update * * @event beforeUpdate * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after update * * @event afterUpdate * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired before rendering * * @event beforeRender * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event * @deprecated */ /** * Fired after rendering * * @event afterRender * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event * @deprecated */ /* * * Properties Documentation * */ /** * A flag that specifies whether the runner is running or not. * * @property enabled * @type boolean * @default true */ /** * A `Boolean` that specifies if the runner should use a fixed timestep (otherwise it is variable). * If timing is fixed, then the apparent simulation speed will change depending on the frame rate (but behaviour will be deterministic). * If the timing is variable, then the apparent simulation speed will be constant (approximately, but at the cost of determininism). * * @property isFixed * @type boolean * @default false */ /** * A `Number` that specifies the time step between updates in milliseconds. * If `engine.timing.isFixed` is set to `true`, then `delta` is fixed. * If it is `false`, then `delta` can dynamically change to maintain the correct apparent simulation speed. * * @property delta * @type number * @default 1000 / 60 */ })(); },{"./Common":14,"./Engine":15,"./Events":16}],20:[function(require,module,exports){ /** * The `Matter.Sleeping` module contains methods to manage the sleeping state of bodies. * * @class Sleeping */ var Sleeping = {}; module.exports = Sleeping; var Events = require('./Events'); (function() { Sleeping._motionWakeThreshold = 0.18; Sleeping._motionSleepThreshold = 0.08; Sleeping._minBias = 0.9; /** * Puts bodies to sleep or wakes them up depending on their motion. * @method update * @param {body[]} bodies * @param {number} timeScale */ Sleeping.update = function(bodies, timeScale) { var timeFactor = timeScale * timeScale * timeScale; // update bodies sleeping status for (var i = 0; i < bodies.length; i++) { var body = bodies[i], motion = body.speed * body.speed + body.angularSpeed * body.angularSpeed; // wake up bodies if they have a force applied if (body.force.x !== 0 || body.force.y !== 0) { Sleeping.set(body, false); continue; } var minMotion = Math.min(body.motion, motion), maxMotion = Math.max(body.motion, motion); // biased average motion estimation between frames body.motion = Sleeping._minBias * minMotion + (1 - Sleeping._minBias) * maxMotion; if (body.sleepThreshold > 0 && body.motion < Sleeping._motionSleepThreshold * timeFactor) { body.sleepCounter += 1; if (body.sleepCounter >= body.sleepThreshold) Sleeping.set(body, true); } else if (body.sleepCounter > 0) { body.sleepCounter -= 1; } } }; /** * Given a set of colliding pairs, wakes the sleeping bodies involved. * @method afterCollisions * @param {pair[]} pairs * @param {number} timeScale */ Sleeping.afterCollisions = function(pairs, timeScale) { var timeFactor = timeScale * timeScale * timeScale; // wake up bodies involved in collisions for (var i = 0; i < pairs.length; i++) { var pair = pairs[i]; // don't wake inactive pairs if (!pair.isActive) continue; var collision = pair.collision, bodyA = collision.bodyA.parent, bodyB = collision.bodyB.parent; // don't wake if at least one body is static if ((bodyA.isSleeping && bodyB.isSleeping) || bodyA.isStatic || bodyB.isStatic) continue; if (bodyA.isSleeping || bodyB.isSleeping) { var sleepingBody = (bodyA.isSleeping && !bodyA.isStatic) ? bodyA : bodyB, movingBody = sleepingBody === bodyA ? bodyB : bodyA; if (!sleepingBody.isStatic && movingBody.motion > Sleeping._motionWakeThreshold * timeFactor) { Sleeping.set(sleepingBody, false); } } } }; /** * Set a body as sleeping or awake. * @method set * @param {body} body * @param {boolean} isSleeping */ Sleeping.set = function(body, isSleeping) { var wasSleeping = body.isSleeping; if (isSleeping) { body.isSleeping = true; body.sleepCounter = body.sleepThreshold; body.positionImpulse.x = 0; body.positionImpulse.y = 0; body.positionPrev.x = body.position.x; body.positionPrev.y = body.position.y; body.anglePrev = body.angle; body.speed = 0; body.angularSpeed = 0; body.motion = 0; if (!wasSleeping) { Events.trigger(body, 'sleepStart'); } } else { body.isSleeping = false; body.sleepCounter = 0; if (wasSleeping) { Events.trigger(body, 'sleepEnd'); } } }; })(); },{"./Events":16}],21:[function(require,module,exports){ /** * The `Matter.Bodies` module contains factory methods for creating rigid body models * with commonly used body configurations (such as rectangles, circles and other polygons). * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Bodies */ // TODO: true circle bodies var Bodies = {}; module.exports = Bodies; var Vertices = require('../geometry/Vertices'); var Common = require('../core/Common'); var Body = require('../body/Body'); var Bounds = require('../geometry/Bounds'); var Vector = require('../geometry/Vector'); (function() { /** * Creates a new rigid body model with a rectangle hull. * The options parameter is an object that specifies any properties you wish to override the defaults. * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object. * @method rectangle * @param {number} x * @param {number} y * @param {number} width * @param {number} height * @param {object} [options] * @return {body} A new rectangle body */ Bodies.rectangle = function(x, y, width, height, options) { options = options || {}; var rectangle = { label: 'Rectangle Body', position: { x: x, y: y }, vertices: Vertices.fromPath('L 0 0 L ' + width + ' 0 L ' + width + ' ' + height + ' L 0 ' + height) }; if (options.chamfer) { var chamfer = options.chamfer; rectangle.vertices = Vertices.chamfer(rectangle.vertices, chamfer.radius, chamfer.quality, chamfer.qualityMin, chamfer.qualityMax); delete options.chamfer; } return Body.create(Common.extend({}, rectangle, options)); }; /** * Creates a new rigid body model with a trapezoid hull. * The options parameter is an object that specifies any properties you wish to override the defaults. * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object. * @method trapezoid * @param {number} x * @param {number} y * @param {number} width * @param {number} height * @param {number} slope * @param {object} [options] * @return {body} A new trapezoid body */ Bodies.trapezoid = function(x, y, width, height, slope, options) { options = options || {}; slope *= 0.5; var roof = (1 - (slope * 2)) * width; var x1 = width * slope, x2 = x1 + roof, x3 = x2 + x1, verticesPath; if (slope < 0.5) { verticesPath = 'L 0 0 L ' + x1 + ' ' + (-height) + ' L ' + x2 + ' ' + (-height) + ' L ' + x3 + ' 0'; } else { verticesPath = 'L 0 0 L ' + x2 + ' ' + (-height) + ' L ' + x3 + ' 0'; } var trapezoid = { label: 'Trapezoid Body', position: { x: x, y: y }, vertices: Vertices.fromPath(verticesPath) }; if (options.chamfer) { var chamfer = options.chamfer; trapezoid.vertices = Vertices.chamfer(trapezoid.vertices, chamfer.radius, chamfer.quality, chamfer.qualityMin, chamfer.qualityMax); delete options.chamfer; } return Body.create(Common.extend({}, trapezoid, options)); }; /** * Creates a new rigid body model with a circle hull. * The options parameter is an object that specifies any properties you wish to override the defaults. * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object. * @method circle * @param {number} x * @param {number} y * @param {number} radius * @param {object} [options] * @param {number} [maxSides] * @return {body} A new circle body */ Bodies.circle = function(x, y, radius, options, maxSides) { options = options || {}; var circle = { label: 'Circle Body', circleRadius: radius }; // approximate circles with polygons until true circles implemented in SAT maxSides = maxSides || 25; var sides = Math.ceil(Math.max(10, Math.min(maxSides, radius))); // optimisation: always use even number of sides (half the number of unique axes) if (sides % 2 === 1) sides += 1; return Bodies.polygon(x, y, sides, radius, Common.extend({}, circle, options)); }; /** * Creates a new rigid body model with a regular polygon hull with the given number of sides. * The options parameter is an object that specifies any properties you wish to override the defaults. * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object. * @method polygon * @param {number} x * @param {number} y * @param {number} sides * @param {number} radius * @param {object} [options] * @return {body} A new regular polygon body */ Bodies.polygon = function(x, y, sides, radius, options) { options = options || {}; if (sides < 3) return Bodies.circle(x, y, radius, options); var theta = 2 * Math.PI / sides, path = '', offset = theta * 0.5; for (var i = 0; i < sides; i += 1) { var angle = offset + (i * theta), xx = Math.cos(angle) * radius, yy = Math.sin(angle) * radius; path += 'L ' + xx.toFixed(3) + ' ' + yy.toFixed(3) + ' '; } var polygon = { label: 'Polygon Body', position: { x: x, y: y }, vertices: Vertices.fromPath(path) }; if (options.chamfer) { var chamfer = options.chamfer; polygon.vertices = Vertices.chamfer(polygon.vertices, chamfer.radius, chamfer.quality, chamfer.qualityMin, chamfer.qualityMax); delete options.chamfer; } return Body.create(Common.extend({}, polygon, options)); }; /** * Creates a body using the supplied vertices (or an array containing multiple sets of vertices). * If the vertices are convex, they will pass through as supplied. * Otherwise if the vertices are concave, they will be decomposed if [poly-decomp.js](https://github.com/schteppe/poly-decomp.js) is available. * Note that this process is not guaranteed to support complex sets of vertices (e.g. those with holes may fail). * By default the decomposition will discard collinear edges (to improve performance). * It can also optionally discard any parts that have an area less than `minimumArea`. * If the vertices can not be decomposed, the result will fall back to using the convex hull. * The options parameter is an object that specifies any `Matter.Body` properties you wish to override the defaults. * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object. * @method fromVertices * @param {number} x * @param {number} y * @param [[vector]] vertexSets * @param {object} [options] * @param {bool} [flagInternal=false] * @param {number} [removeCollinear=0.01] * @param {number} [minimumArea=10] * @return {body} */ Bodies.fromVertices = function(x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea) { var body, parts, isConvex, vertices, i, j, k, v, z; options = options || {}; parts = []; flagInternal = typeof flagInternal !== 'undefined' ? flagInternal : false; removeCollinear = typeof removeCollinear !== 'undefined' ? removeCollinear : 0.01; minimumArea = typeof minimumArea !== 'undefined' ? minimumArea : 10; if (!window.decomp) { Common.log('Bodies.fromVertices: poly-decomp.js required. Could not decompose vertices. Fallback to convex hull.', 'warn'); } // ensure vertexSets is an array of arrays if (!Common.isArray(vertexSets[0])) { vertexSets = [vertexSets]; } for (v = 0; v < vertexSets.length; v += 1) { vertices = vertexSets[v]; isConvex = Vertices.isConvex(vertices); if (isConvex || !window.decomp) { if (isConvex) { vertices = Vertices.clockwiseSort(vertices); } else { // fallback to convex hull when decomposition is not possible vertices = Vertices.hull(vertices); } parts.push({ position: { x: x, y: y }, vertices: vertices }); } else { // initialise a decomposition var concave = new decomp.Polygon(); for (i = 0; i < vertices.length; i++) { concave.vertices.push([vertices[i].x, vertices[i].y]); } // vertices are concave and simple, we can decompose into parts concave.makeCCW(); if (removeCollinear !== false) concave.removeCollinearPoints(removeCollinear); // use the quick decomposition algorithm (Bayazit) var decomposed = concave.quickDecomp(); // for each decomposed chunk for (i = 0; i < decomposed.length; i++) { var chunk = decomposed[i], chunkVertices = []; // convert vertices into the correct structure for (j = 0; j < chunk.vertices.length; j++) { chunkVertices.push({ x: chunk.vertices[j][0], y: chunk.vertices[j][1] }); } // skip small chunks if (minimumArea > 0 && Vertices.area(chunkVertices) < minimumArea) continue; // create a compound part parts.push({ position: Vertices.centre(chunkVertices), vertices: chunkVertices }); } } } // create body parts for (i = 0; i < parts.length; i++) { parts[i] = Body.create(Common.extend(parts[i], options)); } // flag internal edges (coincident part edges) if (flagInternal) { var coincident_max_dist = 5; for (i = 0; i < parts.length; i++) { var partA = parts[i]; for (j = i + 1; j < parts.length; j++) { var partB = parts[j]; if (Bounds.overlaps(partA.bounds, partB.bounds)) { var pav = partA.vertices, pbv = partB.vertices; // iterate vertices of both parts for (k = 0; k < partA.vertices.length; k++) { for (z = 0; z < partB.vertices.length; z++) { // find distances between the vertices var da = Vector.magnitudeSquared(Vector.sub(pav[(k + 1) % pav.length], pbv[z])), db = Vector.magnitudeSquared(Vector.sub(pav[k], pbv[(z + 1) % pbv.length])); // if both vertices are very close, consider the edge concident (internal) if (da < coincident_max_dist && db < coincident_max_dist) { pav[k].isInternal = true; pbv[z].isInternal = true; } } } } } } } if (parts.length > 1) { // create the parent body to be returned, that contains generated compound parts body = Body.create(Common.extend({ parts: parts.slice(0) }, options)); Body.setPosition(body, { x: x, y: y }); return body; } else { return parts[0]; } }; })(); },{"../body/Body":1,"../core/Common":14,"../geometry/Bounds":24,"../geometry/Vector":26,"../geometry/Vertices":27}],22:[function(require,module,exports){ /** * The `Matter.Composites` module contains factory methods for creating composite bodies * with commonly used configurations (such as stacks and chains). * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Composites */ var Composites = {}; module.exports = Composites; var Composite = require('../body/Composite'); var Constraint = require('../constraint/Constraint'); var Common = require('../core/Common'); var Body = require('../body/Body'); var Bodies = require('./Bodies'); (function() { /** * Create a new composite containing bodies created in the callback in a grid arrangement. * This function uses the body's bounds to prevent overlaps. * @method stack * @param {number} xx * @param {number} yy * @param {number} columns * @param {number} rows * @param {number} columnGap * @param {number} rowGap * @param {function} callback * @return {composite} A new composite containing objects created in the callback */ Composites.stack = function(xx, yy, columns, rows, columnGap, rowGap, callback) { var stack = Composite.create({ label: 'Stack' }), x = xx, y = yy, lastBody, i = 0; for (var row = 0; row < rows; row++) { var maxHeight = 0; for (var column = 0; column < columns; column++) { var body = callback(x, y, column, row, lastBody, i); if (body) { var bodyHeight = body.bounds.max.y - body.bounds.min.y, bodyWidth = body.bounds.max.x - body.bounds.min.x; if (bodyHeight > maxHeight) maxHeight = bodyHeight; Body.translate(body, { x: bodyWidth * 0.5, y: bodyHeight * 0.5 }); x = body.bounds.max.x + columnGap; Composite.addBody(stack, body); lastBody = body; i += 1; } else { x += columnGap; } } y += maxHeight + rowGap; x = xx; } return stack; }; /** * Chains all bodies in the given composite together using constraints. * @method chain * @param {composite} composite * @param {number} xOffsetA * @param {number} yOffsetA * @param {number} xOffsetB * @param {number} yOffsetB * @param {object} options * @return {composite} A new composite containing objects chained together with constraints */ Composites.chain = function(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) { var bodies = composite.bodies; for (var i = 1; i < bodies.length; i++) { var bodyA = bodies[i - 1], bodyB = bodies[i], bodyAHeight = bodyA.bounds.max.y - bodyA.bounds.min.y, bodyAWidth = bodyA.bounds.max.x - bodyA.bounds.min.x, bodyBHeight = bodyB.bounds.max.y - bodyB.bounds.min.y, bodyBWidth = bodyB.bounds.max.x - bodyB.bounds.min.x; var defaults = { bodyA: bodyA, pointA: { x: bodyAWidth * xOffsetA, y: bodyAHeight * yOffsetA }, bodyB: bodyB, pointB: { x: bodyBWidth * xOffsetB, y: bodyBHeight * yOffsetB } }; var constraint = Common.extend(defaults, options); Composite.addConstraint(composite, Constraint.create(constraint)); } composite.label += ' Chain'; return composite; }; /** * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces. * @method mesh * @param {composite} composite * @param {number} columns * @param {number} rows * @param {boolean} crossBrace * @param {object} options * @return {composite} The composite containing objects meshed together with constraints */ Composites.mesh = function(composite, columns, rows, crossBrace, options) { var bodies = composite.bodies, row, col, bodyA, bodyB, bodyC; for (row = 0; row < rows; row++) { for (col = 1; col < columns; col++) { bodyA = bodies[(col - 1) + (row * columns)]; bodyB = bodies[col + (row * columns)]; Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyA, bodyB: bodyB }, options))); } if (row > 0) { for (col = 0; col < columns; col++) { bodyA = bodies[col + ((row - 1) * columns)]; bodyB = bodies[col + (row * columns)]; Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyA, bodyB: bodyB }, options))); if (crossBrace && col > 0) { bodyC = bodies[(col - 1) + ((row - 1) * columns)]; Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyC, bodyB: bodyB }, options))); } if (crossBrace && col < columns - 1) { bodyC = bodies[(col + 1) + ((row - 1) * columns)]; Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyC, bodyB: bodyB }, options))); } } } } composite.label += ' Mesh'; return composite; }; /** * Create a new composite containing bodies created in the callback in a pyramid arrangement. * This function uses the body's bounds to prevent overlaps. * @method pyramid * @param {number} xx * @param {number} yy * @param {number} columns * @param {number} rows * @param {number} columnGap * @param {number} rowGap * @param {function} callback * @return {composite} A new composite containing objects created in the callback */ Composites.pyramid = function(xx, yy, columns, rows, columnGap, rowGap, callback) { return Composites.stack(xx, yy, columns, rows, columnGap, rowGap, function(x, y, column, row, lastBody, i) { var actualRows = Math.min(rows, Math.ceil(columns / 2)), lastBodyWidth = lastBody ? lastBody.bounds.max.x - lastBody.bounds.min.x : 0; if (row > actualRows) return; // reverse row order row = actualRows - row; var start = row, end = columns - 1 - row; if (column < start || column > end) return; // retroactively fix the first body's position, since width was unknown if (i === 1) { Body.translate(lastBody, { x: (column + (columns % 2 === 1 ? 1 : -1)) * lastBodyWidth, y: 0 }); } var xOffset = lastBody ? column * lastBodyWidth : 0; return callback(xx + xOffset + column * columnGap, y, column, row, lastBody, i); }); }; /** * Creates a composite with a Newton's Cradle setup of bodies and constraints. * @method newtonsCradle * @param {number} xx * @param {number} yy * @param {number} number * @param {number} size * @param {number} length * @return {composite} A new composite newtonsCradle body */ Composites.newtonsCradle = function(xx, yy, number, size, length) { var newtonsCradle = Composite.create({ label: 'Newtons Cradle' }); for (var i = 0; i < number; i++) { var separation = 1.9, circle = Bodies.circle(xx + i * (size * separation), yy + length, size, { inertia: Infinity, restitution: 1, friction: 0, frictionAir: 0.0001, slop: 1 }), constraint = Constraint.create({ pointA: { x: xx + i * (size * separation), y: yy }, bodyB: circle }); Composite.addBody(newtonsCradle, circle); Composite.addConstraint(newtonsCradle, constraint); } return newtonsCradle; }; /** * Creates a composite with simple car setup of bodies and constraints. * @method car * @param {number} xx * @param {number} yy * @param {number} width * @param {number} height * @param {number} wheelSize * @return {composite} A new composite car body */ Composites.car = function(xx, yy, width, height, wheelSize) { var group = Body.nextGroup(true), wheelBase = -20, wheelAOffset = -width * 0.5 + wheelBase, wheelBOffset = width * 0.5 - wheelBase, wheelYOffset = 0; var car = Composite.create({ label: 'Car' }), body = Bodies.trapezoid(xx, yy, width, height, 0.3, { collisionFilter: { group: group }, friction: 0.01, chamfer: { radius: 10 } }); var wheelA = Bodies.circle(xx + wheelAOffset, yy + wheelYOffset, wheelSize, { collisionFilter: { group: group }, friction: 0.8, density: 0.01 }); var wheelB = Bodies.circle(xx + wheelBOffset, yy + wheelYOffset, wheelSize, { collisionFilter: { group: group }, friction: 0.8, density: 0.01 }); var axelA = Constraint.create({ bodyA: body, pointA: { x: wheelAOffset, y: wheelYOffset }, bodyB: wheelA, stiffness: 0.2 }); var axelB = Constraint.create({ bodyA: body, pointA: { x: wheelBOffset, y: wheelYOffset }, bodyB: wheelB, stiffness: 0.2 }); Composite.addBody(car, body); Composite.addBody(car, wheelA); Composite.addBody(car, wheelB); Composite.addConstraint(car, axelA); Composite.addConstraint(car, axelB); return car; }; /** * Creates a simple soft body like object. * @method softBody * @param {number} xx * @param {number} yy * @param {number} columns * @param {number} rows * @param {number} columnGap * @param {number} rowGap * @param {boolean} crossBrace * @param {number} particleRadius * @param {} particleOptions * @param {} constraintOptions * @return {composite} A new composite softBody */ Composites.softBody = function(xx, yy, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) { particleOptions = Common.extend({ inertia: Infinity }, particleOptions); constraintOptions = Common.extend({ stiffness: 0.4 }, constraintOptions); var softBody = Composites.stack(xx, yy, columns, rows, columnGap, rowGap, function(x, y) { return Bodies.circle(x, y, particleRadius, particleOptions); }); Composites.mesh(softBody, columns, rows, crossBrace, constraintOptions); softBody.label = 'Soft Body'; return softBody; }; })(); },{"../body/Body":1,"../body/Composite":2,"../constraint/Constraint":12,"../core/Common":14,"./Bodies":21}],23:[function(require,module,exports){ /** * The `Matter.Axes` module contains methods for creating and manipulating sets of axes. * * @class Axes */ var Axes = {}; module.exports = Axes; var Vector = require('../geometry/Vector'); var Common = require('../core/Common'); (function() { /** * Creates a new set of axes from the given vertices. * @method fromVertices * @param {vertices} vertices * @return {axes} A new axes from the given vertices */ Axes.fromVertices = function(vertices) { var axes = {}; // find the unique axes, using edge normal gradients for (var i = 0; i < vertices.length; i++) { var j = (i + 1) % vertices.length, normal = Vector.normalise({ x: vertices[j].y - vertices[i].y, y: vertices[i].x - vertices[j].x }), gradient = (normal.y === 0) ? Infinity : (normal.x / normal.y); // limit precision gradient = gradient.toFixed(3).toString(); axes[gradient] = normal; } return Common.values(axes); }; /** * Rotates a set of axes by the given angle. * @method rotate * @param {axes} axes * @param {number} angle */ Axes.rotate = function(axes, angle) { if (angle === 0) return; var cos = Math.cos(angle), sin = Math.sin(angle); for (var i = 0; i < axes.length; i++) { var axis = axes[i], xx; xx = axis.x * cos - axis.y * sin; axis.y = axis.x * sin + axis.y * cos; axis.x = xx; } }; })(); },{"../core/Common":14,"../geometry/Vector":26}],24:[function(require,module,exports){ /** * The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB). * * @class Bounds */ var Bounds = {}; module.exports = Bounds; (function() { /** * Creates a new axis-aligned bounding box (AABB) for the given vertices. * @method create * @param {vertices} vertices * @return {bounds} A new bounds object */ Bounds.create = function(vertices) { var bounds = { min: { x: 0, y: 0 }, max: { x: 0, y: 0 } }; if (vertices) Bounds.update(bounds, vertices); return bounds; }; /** * Updates bounds using the given vertices and extends the bounds given a velocity. * @method update * @param {bounds} bounds * @param {vertices} vertices * @param {vector} velocity */ Bounds.update = function(bounds, vertices, velocity) { bounds.min.x = Infinity; bounds.max.x = -Infinity; bounds.min.y = Infinity; bounds.max.y = -Infinity; for (var i = 0; i < vertices.length; i++) { var vertex = vertices[i]; if (vertex.x > bounds.max.x) bounds.max.x = vertex.x; if (vertex.x < bounds.min.x) bounds.min.x = vertex.x; if (vertex.y > bounds.max.y) bounds.max.y = vertex.y; if (vertex.y < bounds.min.y) bounds.min.y = vertex.y; } if (velocity) { if (velocity.x > 0) { bounds.max.x += velocity.x; } else { bounds.min.x += velocity.x; } if (velocity.y > 0) { bounds.max.y += velocity.y; } else { bounds.min.y += velocity.y; } } }; /** * Returns true if the bounds contains the given point. * @method contains * @param {bounds} bounds * @param {vector} point * @return {boolean} True if the bounds contain the point, otherwise false */ Bounds.contains = function(bounds, point) { return point.x >= bounds.min.x && point.x <= bounds.max.x && point.y >= bounds.min.y && point.y <= bounds.max.y; }; /** * Returns true if the two bounds intersect. * @method overlaps * @param {bounds} boundsA * @param {bounds} boundsB * @return {boolean} True if the bounds overlap, otherwise false */ Bounds.overlaps = function(boundsA, boundsB) { return (boundsA.min.x <= boundsB.max.x && boundsA.max.x >= boundsB.min.x && boundsA.max.y >= boundsB.min.y && boundsA.min.y <= boundsB.max.y); }; /** * Translates the bounds by the given vector. * @method translate * @param {bounds} bounds * @param {vector} vector */ Bounds.translate = function(bounds, vector) { bounds.min.x += vector.x; bounds.max.x += vector.x; bounds.min.y += vector.y; bounds.max.y += vector.y; }; /** * Shifts the bounds to the given position. * @method shift * @param {bounds} bounds * @param {vector} position */ Bounds.shift = function(bounds, position) { var deltaX = bounds.max.x - bounds.min.x, deltaY = bounds.max.y - bounds.min.y; bounds.min.x = position.x; bounds.max.x = position.x + deltaX; bounds.min.y = position.y; bounds.max.y = position.y + deltaY; }; })(); },{}],25:[function(require,module,exports){ /** * The `Matter.Svg` module contains methods for converting SVG images into an array of vector points. * * To use this module you also need the SVGPathSeg polyfill: https://github.com/progers/pathseg * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Svg */ var Svg = {}; module.exports = Svg; var Bounds = require('../geometry/Bounds'); (function() { /** * Converts an SVG path into an array of vector points. * If the input path forms a concave shape, you must decompose the result into convex parts before use. * See `Bodies.fromVertices` which provides support for this. * Note that this function is not guaranteed to support complex paths (such as those with holes). * @method pathToVertices * @param {SVGPathElement} path * @param {Number} [sampleLength=15] * @return {Vector[]} points */ Svg.pathToVertices = function(path, sampleLength) { // https://github.com/wout/svg.topoly.js/blob/master/svg.topoly.js var i, il, total, point, segment, segments, segmentsQueue, lastSegment, lastPoint, segmentIndex, points = [], lx, ly, length = 0, x = 0, y = 0; sampleLength = sampleLength || 15; var addPoint = function(px, py, pathSegType) { // all odd-numbered path types are relative except PATHSEG_CLOSEPATH (1) var isRelative = pathSegType % 2 === 1 && pathSegType > 1; // when the last point doesn't equal the current point add the current point if (!lastPoint || px != lastPoint.x || py != lastPoint.y) { if (lastPoint && isRelative) { lx = lastPoint.x; ly = lastPoint.y; } else { lx = 0; ly = 0; } var point = { x: lx + px, y: ly + py }; // set last point if (isRelative || !lastPoint) { lastPoint = point; } points.push(point); x = lx + px; y = ly + py; } }; var addSegmentPoint = function(segment) { var segType = segment.pathSegTypeAsLetter.toUpperCase(); // skip path ends if (segType === 'Z') return; // map segment to x and y switch (segType) { case 'M': case 'L': case 'T': case 'C': case 'S': case 'Q': x = segment.x; y = segment.y; break; case 'H': x = segment.x; break; case 'V': y = segment.y; break; } addPoint(x, y, segment.pathSegType); }; // ensure path is absolute _svgPathToAbsolute(path); // get total length total = path.getTotalLength(); // queue segments segments = []; for (i = 0; i < path.pathSegList.numberOfItems; i += 1) segments.push(path.pathSegList.getItem(i)); segmentsQueue = segments.concat(); // sample through path while (length < total) { // get segment at position segmentIndex = path.getPathSegAtLength(length); segment = segments[segmentIndex]; // new segment if (segment != lastSegment) { while (segmentsQueue.length && segmentsQueue[0] != segment) addSegmentPoint(segmentsQueue.shift()); lastSegment = segment; } // add points in between when curving // TODO: adaptive sampling switch (segment.pathSegTypeAsLetter.toUpperCase()) { case 'C': case 'T': case 'S': case 'Q': case 'A': point = path.getPointAtLength(length); addPoint(point.x, point.y, 0); break; } // increment by sample value length += sampleLength; } // add remaining segments not passed by sampling for (i = 0, il = segmentsQueue.length; i < il; ++i) addSegmentPoint(segmentsQueue[i]); return points; }; var _svgPathToAbsolute = function(path) { // http://phrogz.net/convert-svg-path-to-all-absolute-commands var x0, y0, x1, y1, x2, y2, segs = path.pathSegList, x = 0, y = 0, len = segs.numberOfItems; for (var i = 0; i < len; ++i) { var seg = segs.getItem(i), segType = seg.pathSegTypeAsLetter; if (/[MLHVCSQTA]/.test(segType)) { if ('x' in seg) x = seg.x; if ('y' in seg) y = seg.y; } else { if ('x1' in seg) x1 = x + seg.x1; if ('x2' in seg) x2 = x + seg.x2; if ('y1' in seg) y1 = y + seg.y1; if ('y2' in seg) y2 = y + seg.y2; if ('x' in seg) x += seg.x; if ('y' in seg) y += seg.y; switch (segType) { case 'm': segs.replaceItem(path.createSVGPathSegMovetoAbs(x, y), i); break; case 'l': segs.replaceItem(path.createSVGPathSegLinetoAbs(x, y), i); break; case 'h': segs.replaceItem(path.createSVGPathSegLinetoHorizontalAbs(x), i); break; case 'v': segs.replaceItem(path.createSVGPathSegLinetoVerticalAbs(y), i); break; case 'c': segs.replaceItem(path.createSVGPathSegCurvetoCubicAbs(x, y, x1, y1, x2, y2), i); break; case 's': segs.replaceItem(path.createSVGPathSegCurvetoCubicSmoothAbs(x, y, x2, y2), i); break; case 'q': segs.replaceItem(path.createSVGPathSegCurvetoQuadraticAbs(x, y, x1, y1), i); break; case 't': segs.replaceItem(path.createSVGPathSegCurvetoQuadraticSmoothAbs(x, y), i); break; case 'a': segs.replaceItem(path.createSVGPathSegArcAbs(x, y, seg.r1, seg.r2, seg.angle, seg.largeArcFlag, seg.sweepFlag), i); break; case 'z': case 'Z': x = x0; y = y0; break; } } if (segType == 'M' || segType == 'm') { x0 = x; y0 = y; } } }; })(); },{"../geometry/Bounds":24}],26:[function(require,module,exports){ /** * The `Matter.Vector` module contains methods for creating and manipulating vectors. * Vectors are the basis of all the geometry related operations in the engine. * A `Matter.Vector` object is of the form `{ x: 0, y: 0 }`. * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Vector */ // TODO: consider params for reusing vector objects var Vector = {}; module.exports = Vector; (function() { /** * Creates a new vector. * @method create * @param {number} x * @param {number} y * @return {vector} A new vector */ Vector.create = function(x, y) { return { x: x || 0, y: y || 0 }; }; /** * Returns a new vector with `x` and `y` copied from the given `vector`. * @method clone * @param {vector} vector * @return {vector} A new cloned vector */ Vector.clone = function(vector) { return { x: vector.x, y: vector.y }; }; /** * Returns the magnitude (length) of a vector. * @method magnitude * @param {vector} vector * @return {number} The magnitude of the vector */ Vector.magnitude = function(vector) { return Math.sqrt((vector.x * vector.x) + (vector.y * vector.y)); }; /** * Returns the magnitude (length) of a vector (therefore saving a `sqrt` operation). * @method magnitudeSquared * @param {vector} vector * @return {number} The squared magnitude of the vector */ Vector.magnitudeSquared = function(vector) { return (vector.x * vector.x) + (vector.y * vector.y); }; /** * Rotates the vector about (0, 0) by specified angle. * @method rotate * @param {vector} vector * @param {number} angle * @return {vector} A new vector rotated about (0, 0) */ Vector.rotate = function(vector, angle) { var cos = Math.cos(angle), sin = Math.sin(angle); return { x: vector.x * cos - vector.y * sin, y: vector.x * sin + vector.y * cos }; }; /** * Rotates the vector about a specified point by specified angle. * @method rotateAbout * @param {vector} vector * @param {number} angle * @param {vector} point * @param {vector} [output] * @return {vector} A new vector rotated about the point */ Vector.rotateAbout = function(vector, angle, point, output) { var cos = Math.cos(angle), sin = Math.sin(angle); if (!output) output = {}; var x = point.x + ((vector.x - point.x) * cos - (vector.y - point.y) * sin); output.y = point.y + ((vector.x - point.x) * sin + (vector.y - point.y) * cos); output.x = x; return output; }; /** * Normalises a vector (such that its magnitude is `1`). * @method normalise * @param {vector} vector * @return {vector} A new vector normalised */ Vector.normalise = function(vector) { var magnitude = Vector.magnitude(vector); if (magnitude === 0) return { x: 0, y: 0 }; return { x: vector.x / magnitude, y: vector.y / magnitude }; }; /** * Returns the dot-product of two vectors. * @method dot * @param {vector} vectorA * @param {vector} vectorB * @return {number} The dot product of the two vectors */ Vector.dot = function(vectorA, vectorB) { return (vectorA.x * vectorB.x) + (vectorA.y * vectorB.y); }; /** * Returns the cross-product of two vectors. * @method cross * @param {vector} vectorA * @param {vector} vectorB * @return {number} The cross product of the two vectors */ Vector.cross = function(vectorA, vectorB) { return (vectorA.x * vectorB.y) - (vectorA.y * vectorB.x); }; /** * Returns the cross-product of three vectors. * @method cross3 * @param {vector} vectorA * @param {vector} vectorB * @param {vector} vectorC * @return {number} The cross product of the three vectors */ Vector.cross3 = function(vectorA, vectorB, vectorC) { return (vectorB.x - vectorA.x) * (vectorC.y - vectorA.y) - (vectorB.y - vectorA.y) * (vectorC.x - vectorA.x); }; /** * Adds the two vectors. * @method add * @param {vector} vectorA * @param {vector} vectorB * @param {vector} [output] * @return {vector} A new vector of vectorA and vectorB added */ Vector.add = function(vectorA, vectorB, output) { if (!output) output = {}; output.x = vectorA.x + vectorB.x; output.y = vectorA.y + vectorB.y; return output; }; /** * Subtracts the two vectors. * @method sub * @param {vector} vectorA * @param {vector} vectorB * @param {vector} [output] * @return {vector} A new vector of vectorA and vectorB subtracted */ Vector.sub = function(vectorA, vectorB, output) { if (!output) output = {}; output.x = vectorA.x - vectorB.x; output.y = vectorA.y - vectorB.y; return output; }; /** * Multiplies a vector and a scalar. * @method mult * @param {vector} vector * @param {number} scalar * @return {vector} A new vector multiplied by scalar */ Vector.mult = function(vector, scalar) { return { x: vector.x * scalar, y: vector.y * scalar }; }; /** * Divides a vector and a scalar. * @method div * @param {vector} vector * @param {number} scalar * @return {vector} A new vector divided by scalar */ Vector.div = function(vector, scalar) { return { x: vector.x / scalar, y: vector.y / scalar }; }; /** * Returns the perpendicular vector. Set `negate` to true for the perpendicular in the opposite direction. * @method perp * @param {vector} vector * @param {bool} [negate=false] * @return {vector} The perpendicular vector */ Vector.perp = function(vector, negate) { negate = negate === true ? -1 : 1; return { x: negate * -vector.y, y: negate * vector.x }; }; /** * Negates both components of a vector such that it points in the opposite direction. * @method neg * @param {vector} vector * @return {vector} The negated vector */ Vector.neg = function(vector) { return { x: -vector.x, y: -vector.y }; }; /** * Returns the angle in radians between the two vectors relative to the x-axis. * @method angle * @param {vector} vectorA * @param {vector} vectorB * @return {number} The angle in radians */ Vector.angle = function(vectorA, vectorB) { return Math.atan2(vectorB.y - vectorA.y, vectorB.x - vectorA.x); }; /** * Temporary vector pool (not thread-safe). * @property _temp * @type {vector[]} * @private */ Vector._temp = [Vector.create(), Vector.create(), Vector.create(), Vector.create(), Vector.create(), Vector.create()]; })(); },{}],27:[function(require,module,exports){ /** * The `Matter.Vertices` module contains methods for creating and manipulating sets of vertices. * A set of vertices is an array of `Matter.Vector` with additional indexing properties inserted by `Vertices.create`. * A `Matter.Body` maintains a set of vertices to represent the shape of the object (its convex hull). * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Vertices */ var Vertices = {}; module.exports = Vertices; var Vector = require('../geometry/Vector'); var Common = require('../core/Common'); (function() { /** * Creates a new set of `Matter.Body` compatible vertices. * The `points` argument accepts an array of `Matter.Vector` points orientated around the origin `(0, 0)`, for example: * * [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] * * The `Vertices.create` method returns a new array of vertices, which are similar to Matter.Vector objects, * but with some additional references required for efficient collision detection routines. * * Note that the `body` argument is not optional, a `Matter.Body` reference must be provided. * * @method create * @param {vector[]} points * @param {body} body */ Vertices.create = function(points, body) { var vertices = []; for (var i = 0; i < points.length; i++) { var point = points[i], vertex = { x: point.x, y: point.y, index: i, body: body, isInternal: false }; vertices.push(vertex); } return vertices; }; /** * Parses a string containing ordered x y pairs separated by spaces (and optionally commas), * into a `Matter.Vertices` object for the given `Matter.Body`. * For parsing SVG paths, see `Svg.pathToVertices`. * @method fromPath * @param {string} path * @param {body} body * @return {vertices} vertices */ Vertices.fromPath = function(path, body) { var pathPattern = /L?\s*([\-\d\.e]+)[\s,]*([\-\d\.e]+)*/ig, points = []; path.replace(pathPattern, function(match, x, y) { points.push({ x: parseFloat(x), y: parseFloat(y) }); }); return Vertices.create(points, body); }; /** * Returns the centre (centroid) of the set of vertices. * @method centre * @param {vertices} vertices * @return {vector} The centre point */ Vertices.centre = function(vertices) { var area = Vertices.area(vertices, true), centre = { x: 0, y: 0 }, cross, temp, j; for (var i = 0; i < vertices.length; i++) { j = (i + 1) % vertices.length; cross = Vector.cross(vertices[i], vertices[j]); temp = Vector.mult(Vector.add(vertices[i], vertices[j]), cross); centre = Vector.add(centre, temp); } return Vector.div(centre, 6 * area); }; /** * Returns the average (mean) of the set of vertices. * @method mean * @param {vertices} vertices * @return {vector} The average point */ Vertices.mean = function(vertices) { var average = { x: 0, y: 0 }; for (var i = 0; i < vertices.length; i++) { average.x += vertices[i].x; average.y += vertices[i].y; } return Vector.div(average, vertices.length); }; /** * Returns the area of the set of vertices. * @method area * @param {vertices} vertices * @param {bool} signed * @return {number} The area */ Vertices.area = function(vertices, signed) { var area = 0, j = vertices.length - 1; for (var i = 0; i < vertices.length; i++) { area += (vertices[j].x - vertices[i].x) * (vertices[j].y + vertices[i].y); j = i; } if (signed) return area / 2; return Math.abs(area) / 2; }; /** * Returns the moment of inertia (second moment of area) of the set of vertices given the total mass. * @method inertia * @param {vertices} vertices * @param {number} mass * @return {number} The polygon's moment of inertia */ Vertices.inertia = function(vertices, mass) { var numerator = 0, denominator = 0, v = vertices, cross, j; // find the polygon's moment of inertia, using second moment of area // http://www.physicsforums.com/showthread.php?t=25293 for (var n = 0; n < v.length; n++) { j = (n + 1) % v.length; cross = Math.abs(Vector.cross(v[j], v[n])); numerator += cross * (Vector.dot(v[j], v[j]) + Vector.dot(v[j], v[n]) + Vector.dot(v[n], v[n])); denominator += cross; } return (mass / 6) * (numerator / denominator); }; /** * Translates the set of vertices in-place. * @method translate * @param {vertices} vertices * @param {vector} vector * @param {number} scalar */ Vertices.translate = function(vertices, vector, scalar) { var i; if (scalar) { for (i = 0; i < vertices.length; i++) { vertices[i].x += vector.x * scalar; vertices[i].y += vector.y * scalar; } } else { for (i = 0; i < vertices.length; i++) { vertices[i].x += vector.x; vertices[i].y += vector.y; } } return vertices; }; /** * Rotates the set of vertices in-place. * @method rotate * @param {vertices} vertices * @param {number} angle * @param {vector} point */ Vertices.rotate = function(vertices, angle, point) { if (angle === 0) return; var cos = Math.cos(angle), sin = Math.sin(angle); for (var i = 0; i < vertices.length; i++) { var vertice = vertices[i], dx = vertice.x - point.x, dy = vertice.y - point.y; vertice.x = point.x + (dx * cos - dy * sin); vertice.y = point.y + (dx * sin + dy * cos); } return vertices; }; /** * Returns `true` if the `point` is inside the set of `vertices`. * @method contains * @param {vertices} vertices * @param {vector} point * @return {boolean} True if the vertices contains point, otherwise false */ Vertices.contains = function(vertices, point) { for (var i = 0; i < vertices.length; i++) { var vertice = vertices[i], nextVertice = vertices[(i + 1) % vertices.length]; if ((point.x - vertice.x) * (nextVertice.y - vertice.y) + (point.y - vertice.y) * (vertice.x - nextVertice.x) > 0) { return false; } } return true; }; /** * Scales the vertices from a point (default is centre) in-place. * @method scale * @param {vertices} vertices * @param {number} scaleX * @param {number} scaleY * @param {vector} point */ Vertices.scale = function(vertices, scaleX, scaleY, point) { if (scaleX === 1 && scaleY === 1) return vertices; point = point || Vertices.centre(vertices); var vertex, delta; for (var i = 0; i < vertices.length; i++) { vertex = vertices[i]; delta = Vector.sub(vertex, point); vertices[i].x = point.x + delta.x * scaleX; vertices[i].y = point.y + delta.y * scaleY; } return vertices; }; /** * Chamfers a set of vertices by giving them rounded corners, returns a new set of vertices. * The radius parameter is a single number or an array to specify the radius for each vertex. * @method chamfer * @param {vertices} vertices * @param {number[]} radius * @param {number} quality * @param {number} qualityMin * @param {number} qualityMax */ Vertices.chamfer = function(vertices, radius, quality, qualityMin, qualityMax) { radius = radius || [8]; if (!radius.length) radius = [radius]; // quality defaults to -1, which is auto quality = (typeof quality !== 'undefined') ? quality : -1; qualityMin = qualityMin || 2; qualityMax = qualityMax || 14; var newVertices = []; for (var i = 0; i < vertices.length; i++) { var prevVertex = vertices[i - 1 >= 0 ? i - 1 : vertices.length - 1], vertex = vertices[i], nextVertex = vertices[(i + 1) % vertices.length], currentRadius = radius[i < radius.length ? i : radius.length - 1]; if (currentRadius === 0) { newVertices.push(vertex); continue; } var prevNormal = Vector.normalise({ x: vertex.y - prevVertex.y, y: prevVertex.x - vertex.x }); var nextNormal = Vector.normalise({ x: nextVertex.y - vertex.y, y: vertex.x - nextVertex.x }); var diagonalRadius = Math.sqrt(2 * Math.pow(currentRadius, 2)), radiusVector = Vector.mult(Common.clone(prevNormal), currentRadius), midNormal = Vector.normalise(Vector.mult(Vector.add(prevNormal, nextNormal), 0.5)), scaledVertex = Vector.sub(vertex, Vector.mult(midNormal, diagonalRadius)); var precision = quality; if (quality === -1) { // automatically decide precision precision = Math.pow(currentRadius, 0.32) * 1.75; } precision = Common.clamp(precision, qualityMin, qualityMax); // use an even value for precision, more likely to reduce axes by using symmetry if (precision % 2 === 1) precision += 1; var alpha = Math.acos(Vector.dot(prevNormal, nextNormal)), theta = alpha / precision; for (var j = 0; j < precision; j++) { newVertices.push(Vector.add(Vector.rotate(radiusVector, theta * j), scaledVertex)); } } return newVertices; }; /** * Sorts the input vertices into clockwise order in place. * @method clockwiseSort * @param {vertices} vertices * @return {vertices} vertices */ Vertices.clockwiseSort = function(vertices) { var centre = Vertices.mean(vertices); vertices.sort(function(vertexA, vertexB) { return Vector.angle(centre, vertexA) - Vector.angle(centre, vertexB); }); return vertices; }; /** * Returns true if the vertices form a convex shape (vertices must be in clockwise order). * @method isConvex * @param {vertices} vertices * @return {bool} `true` if the `vertices` are convex, `false` if not (or `null` if not computable). */ Vertices.isConvex = function(vertices) { // http://paulbourke.net/geometry/polygonmesh/ var flag = 0, n = vertices.length, i, j, k, z; if (n < 3) return null; for (i = 0; i < n; i++) { j = (i + 1) % n; k = (i + 2) % n; z = (vertices[j].x - vertices[i].x) * (vertices[k].y - vertices[j].y); z -= (vertices[j].y - vertices[i].y) * (vertices[k].x - vertices[j].x); if (z < 0) { flag |= 1; } else if (z > 0) { flag |= 2; } if (flag === 3) { return false; } } if (flag !== 0){ return true; } else { return null; } }; /** * Returns the convex hull of the input vertices as a new array of points. * @method hull * @param {vertices} vertices * @return [vertex] vertices */ Vertices.hull = function(vertices) { // http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain var upper = [], lower = [], vertex, i; // sort vertices on x-axis (y-axis for ties) vertices = vertices.slice(0); vertices.sort(function(vertexA, vertexB) { var dx = vertexA.x - vertexB.x; return dx !== 0 ? dx : vertexA.y - vertexB.y; }); // build lower hull for (i = 0; i < vertices.length; i++) { vertex = vertices[i]; while (lower.length >= 2 && Vector.cross3(lower[lower.length - 2], lower[lower.length - 1], vertex) <= 0) { lower.pop(); } lower.push(vertex); } // build upper hull for (i = vertices.length - 1; i >= 0; i--) { vertex = vertices[i]; while (upper.length >= 2 && Vector.cross3(upper[upper.length - 2], upper[upper.length - 1], vertex) <= 0) { upper.pop(); } upper.push(vertex); } // concatenation of the lower and upper hulls gives the convex hull // omit last points because they are repeated at the beginning of the other list upper.pop(); lower.pop(); return upper.concat(lower); }; })(); },{"../core/Common":14,"../geometry/Vector":26}],28:[function(require,module,exports){ var Matter = module.exports = {}; window.Matter = Matter; Matter.version = 'master'; Matter.Body = require('../body/Body'); Matter.Composite = require('../body/Composite'); Matter.World = require('../body/World'); Matter.Contact = require('../collision/Contact'); Matter.Detector = require('../collision/Detector'); Matter.Grid = require('../collision/Grid'); Matter.Pairs = require('../collision/Pairs'); Matter.Pair = require('../collision/Pair'); Matter.Query = require('../collision/Query'); Matter.Resolver = require('../collision/Resolver'); Matter.SAT = require('../collision/SAT'); Matter.Constraint = require('../constraint/Constraint'); Matter.MouseConstraint = require('../constraint/MouseConstraint'); Matter.Common = require('../core/Common'); Matter.Engine = require('../core/Engine'); Matter.Events = require('../core/Events'); Matter.Mouse = require('../core/Mouse'); Matter.Runner = require('../core/Runner'); Matter.Sleeping = require('../core/Sleeping'); Matter.Bodies = require('../factory/Bodies'); Matter.Composites = require('../factory/Composites'); Matter.Axes = require('../geometry/Axes'); Matter.Bounds = require('../geometry/Bounds'); Matter.Svg = require('../geometry/Svg'); Matter.Vector = require('../geometry/Vector'); Matter.Vertices = require('../geometry/Vertices'); Matter.Render = require('../render/Render'); Matter.RenderPixi = require('../render/RenderPixi'); // aliases Matter.World.add = Matter.Composite.add; Matter.World.remove = Matter.Composite.remove; Matter.World.addComposite = Matter.Composite.addComposite; Matter.World.addBody = Matter.Composite.addBody; Matter.World.addConstraint = Matter.Composite.addConstraint; Matter.World.clear = Matter.Composite.clear; Matter.Engine.run = Matter.Runner.run; },{"../body/Body":1,"../body/Composite":2,"../body/World":3,"../collision/Contact":4,"../collision/Detector":5,"../collision/Grid":6,"../collision/Pair":7,"../collision/Pairs":8,"../collision/Query":9,"../collision/Resolver":10,"../collision/SAT":11,"../constraint/Constraint":12,"../constraint/MouseConstraint":13,"../core/Common":14,"../core/Engine":15,"../core/Events":16,"../core/Metrics":17,"../core/Mouse":18,"../core/Runner":19,"../core/Sleeping":20,"../factory/Bodies":21,"../factory/Composites":22,"../geometry/Axes":23,"../geometry/Bounds":24,"../geometry/Svg":25,"../geometry/Vector":26,"../geometry/Vertices":27,"../render/Render":29,"../render/RenderPixi":30}],29:[function(require,module,exports){ /** * The `Matter.Render` module is a simple HTML5 canvas based renderer for visualising instances of `Matter.Engine`. * It is intended for development and debugging purposes, but may also be suitable for simple games. * It includes a number of drawing options including wireframe, vector with support for sprites and viewports. * * @class Render */ var Render = {}; module.exports = Render; var Common = require('../core/Common'); var Composite = require('../body/Composite'); var Bounds = require('../geometry/Bounds'); var Events = require('../core/Events'); var Grid = require('../collision/Grid'); var Vector = require('../geometry/Vector'); (function() { var _requestAnimationFrame, _cancelAnimationFrame; if (typeof window !== 'undefined') { _requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function(callback){ window.setTimeout(function() { callback(Common.now()); }, 1000 / 60); }; _cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.msCancelAnimationFrame; } /** * Creates a new renderer. The options parameter is an object that specifies any properties you wish to override the defaults. * All properties have default values, and many are pre-calculated automatically based on other properties. * See the properties section below for detailed information on what you can pass via the `options` object. * @method create * @param {object} [options] * @return {render} A new renderer */ Render.create = function(options) { var defaults = { controller: Render, engine: null, element: null, canvas: null, mouse: null, frameRequestId: null, options: { width: 800, height: 600, pixelRatio: 1, background: '#fafafa', wireframeBackground: '#222', hasBounds: !!options.bounds, enabled: true, wireframes: true, showSleeping: true, showDebug: false, showBroadphase: false, showBounds: false, showVelocity: false, showCollisions: false, showSeparations: false, showAxes: false, showPositions: false, showAngleIndicator: false, showIds: false, showShadows: false, showVertexNumbers: false, showConvexHulls: false, showInternalEdges: false, showMousePosition: false } }; var render = Common.extend(defaults, options); if (render.canvas) { render.canvas.width = render.options.width || render.canvas.width; render.canvas.height = render.options.height || render.canvas.height; } render.mouse = options.mouse; render.engine = options.engine; render.canvas = render.canvas || _createCanvas(render.options.width, render.options.height); render.context = render.canvas.getContext('2d'); render.textures = {}; render.bounds = render.bounds || { min: { x: 0, y: 0 }, max: { x: render.canvas.width, y: render.canvas.height } }; if (render.options.pixelRatio !== 1) { Render.setPixelRatio(render, render.options.pixelRatio); } if (Common.isElement(render.element)) { render.element.appendChild(render.canvas); } else { Common.log('Render.create: options.element was undefined, render.canvas was created but not appended', 'warn'); } return render; }; /** * Continuously updates the render canvas on the `requestAnimationFrame` event. * @method run * @param {render} render */ Render.run = function(render) { (function loop(time){ render.frameRequestId = _requestAnimationFrame(loop); Render.world(render); })(); }; /** * Ends execution of `Render.run` on the given `render`, by canceling the animation frame request event loop. * @method stop * @param {render} render */ Render.stop = function(render) { _cancelAnimationFrame(render.frameRequestId); }; /** * Sets the pixel ratio of the renderer and updates the canvas. * To automatically detect the correct ratio, pass the string `'auto'` for `pixelRatio`. * @method setPixelRatio * @param {render} render * @param {number} pixelRatio */ Render.setPixelRatio = function(render, pixelRatio) { var options = render.options, canvas = render.canvas; if (pixelRatio === 'auto') { pixelRatio = _getPixelRatio(canvas); } options.pixelRatio = pixelRatio; canvas.setAttribute('data-pixel-ratio', pixelRatio); canvas.width = options.width * pixelRatio; canvas.height = options.height * pixelRatio; canvas.style.width = options.width + 'px'; canvas.style.height = options.height + 'px'; render.context.scale(pixelRatio, pixelRatio); }; /** * Renders the given `engine`'s `Matter.World` object. * This is the entry point for all rendering and should be called every time the scene changes. * @method world * @param {render} render */ Render.world = function(render) { var engine = render.engine, world = engine.world, canvas = render.canvas, context = render.context, options = render.options, allBodies = Composite.allBodies(world), allConstraints = Composite.allConstraints(world), background = options.wireframes ? options.wireframeBackground : options.background, bodies = [], constraints = [], i; var event = { timestamp: engine.timing.timestamp }; Events.trigger(render, 'beforeRender', event); // apply background if it has changed if (render.currentBackground !== background) _applyBackground(render, background); // clear the canvas with a transparent fill, to allow the canvas background to show context.globalCompositeOperation = 'source-in'; context.fillStyle = "transparent"; context.fillRect(0, 0, canvas.width, canvas.height); context.globalCompositeOperation = 'source-over'; // handle bounds if (options.hasBounds) { var boundsWidth = render.bounds.max.x - render.bounds.min.x, boundsHeight = render.bounds.max.y - render.bounds.min.y, boundsScaleX = boundsWidth / options.width, boundsScaleY = boundsHeight / options.height; // filter out bodies that are not in view for (i = 0; i < allBodies.length; i++) { var body = allBodies[i]; if (Bounds.overlaps(body.bounds, render.bounds)) bodies.push(body); } // filter out constraints that are not in view for (i = 0; i < allConstraints.length; i++) { var constraint = allConstraints[i], bodyA = constraint.bodyA, bodyB = constraint.bodyB, pointAWorld = constraint.pointA, pointBWorld = constraint.pointB; if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA); if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB); if (!pointAWorld || !pointBWorld) continue; if (Bounds.contains(render.bounds, pointAWorld) || Bounds.contains(render.bounds, pointBWorld)) constraints.push(constraint); } // transform the view context.scale(1 / boundsScaleX, 1 / boundsScaleY); context.translate(-render.bounds.min.x, -render.bounds.min.y); } else { constraints = allConstraints; bodies = allBodies; } if (!options.wireframes || (engine.enableSleeping && options.showSleeping)) { // fully featured rendering of bodies Render.bodies(render, bodies, context); } else { if (options.showConvexHulls) Render.bodyConvexHulls(render, bodies, context); // optimised method for wireframes only Render.bodyWireframes(render, bodies, context); } if (options.showBounds) Render.bodyBounds(render, bodies, context); if (options.showAxes || options.showAngleIndicator) Render.bodyAxes(render, bodies, context); if (options.showPositions) Render.bodyPositions(render, bodies, context); if (options.showVelocity) Render.bodyVelocity(render, bodies, context); if (options.showIds) Render.bodyIds(render, bodies, context); if (options.showSeparations) Render.separations(render, engine.pairs.list, context); if (options.showCollisions) Render.collisions(render, engine.pairs.list, context); if (options.showVertexNumbers) Render.vertexNumbers(render, bodies, context); if (options.showMousePosition) Render.mousePosition(render, render.mouse, context); Render.constraints(constraints, context); if (options.showBroadphase && engine.broadphase.controller === Grid) Render.grid(render, engine.broadphase, context); if (options.showDebug) Render.debug(render, context); if (options.hasBounds) { // revert view transforms context.setTransform(options.pixelRatio, 0, 0, options.pixelRatio, 0, 0); } Events.trigger(render, 'afterRender', event); }; /** * Description * @private * @method debug * @param {render} render * @param {RenderingContext} context */ Render.debug = function(render, context) { var c = context, engine = render.engine, world = engine.world, metrics = engine.metrics, options = render.options, bodies = Composite.allBodies(world), space = " "; if (engine.timing.timestamp - (render.debugTimestamp || 0) >= 500) { var text = ""; if (metrics.timing) { text += "fps: " + Math.round(metrics.timing.fps) + space; } render.debugString = text; render.debugTimestamp = engine.timing.timestamp; } if (render.debugString) { c.font = "12px Arial"; if (options.wireframes) { c.fillStyle = 'rgba(255,255,255,0.5)'; } else { c.fillStyle = 'rgba(0,0,0,0.5)'; } var split = render.debugString.split('\n'); for (var i = 0; i < split.length; i++) { c.fillText(split[i], 50, 50 + i * 18); } } }; /** * Description * @private * @method constraints * @param {constraint[]} constraints * @param {RenderingContext} context */ Render.constraints = function(constraints, context) { var c = context; for (var i = 0; i < constraints.length; i++) { var constraint = constraints[i]; if (!constraint.render.visible || !constraint.pointA || !constraint.pointB) continue; var bodyA = constraint.bodyA, bodyB = constraint.bodyB; if (bodyA) { c.beginPath(); c.moveTo(bodyA.position.x + constraint.pointA.x, bodyA.position.y + constraint.pointA.y); } else { c.beginPath(); c.moveTo(constraint.pointA.x, constraint.pointA.y); } if (bodyB) { c.lineTo(bodyB.position.x + constraint.pointB.x, bodyB.position.y + constraint.pointB.y); } else { c.lineTo(constraint.pointB.x, constraint.pointB.y); } c.lineWidth = constraint.render.lineWidth; c.strokeStyle = constraint.render.strokeStyle; c.stroke(); } }; /** * Description * @private * @method bodyShadows * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ Render.bodyShadows = function(render, bodies, context) { var c = context, engine = render.engine; for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (!body.render.visible) continue; if (body.circleRadius) { c.beginPath(); c.arc(body.position.x, body.position.y, body.circleRadius, 0, 2 * Math.PI); c.closePath(); } else { c.beginPath(); c.moveTo(body.vertices[0].x, body.vertices[0].y); for (var j = 1; j < body.vertices.length; j++) { c.lineTo(body.vertices[j].x, body.vertices[j].y); } c.closePath(); } var distanceX = body.position.x - render.options.width * 0.5, distanceY = body.position.y - render.options.height * 0.2, distance = Math.abs(distanceX) + Math.abs(distanceY); c.shadowColor = 'rgba(0,0,0,0.15)'; c.shadowOffsetX = 0.05 * distanceX; c.shadowOffsetY = 0.05 * distanceY; c.shadowBlur = 1 + 12 * Math.min(1, distance / 1000); c.fill(); c.shadowColor = null; c.shadowOffsetX = null; c.shadowOffsetY = null; c.shadowBlur = null; } }; /** * Description * @private * @method bodies * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ Render.bodies = function(render, bodies, context) { var c = context, engine = render.engine, options = render.options, showInternalEdges = options.showInternalEdges || !options.wireframes, body, part, i, k; for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (!body.render.visible) continue; // handle compound parts for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) { part = body.parts[k]; if (!part.render.visible) continue; if (options.showSleeping && body.isSleeping) { c.globalAlpha = 0.5 * part.render.opacity; } else if (part.render.opacity !== 1) { c.globalAlpha = part.render.opacity; } if (part.render.sprite && part.render.sprite.texture && !options.wireframes) { // part sprite var sprite = part.render.sprite, texture = _getTexture(render, sprite.texture); c.translate(part.position.x, part.position.y); c.rotate(part.angle); c.drawImage( texture, texture.width * -sprite.xOffset * sprite.xScale, texture.height * -sprite.yOffset * sprite.yScale, texture.width * sprite.xScale, texture.height * sprite.yScale ); // revert translation, hopefully faster than save / restore c.rotate(-part.angle); c.translate(-part.position.x, -part.position.y); } else { // part polygon if (part.circleRadius) { c.beginPath(); c.arc(part.position.x, part.position.y, part.circleRadius, 0, 2 * Math.PI); } else { c.beginPath(); c.moveTo(part.vertices[0].x, part.vertices[0].y); for (var j = 1; j < part.vertices.length; j++) { if (!part.vertices[j - 1].isInternal || showInternalEdges) { c.lineTo(part.vertices[j].x, part.vertices[j].y); } else { c.moveTo(part.vertices[j].x, part.vertices[j].y); } if (part.vertices[j].isInternal && !showInternalEdges) { c.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y); } } c.lineTo(part.vertices[0].x, part.vertices[0].y); c.closePath(); } if (!options.wireframes) { c.fillStyle = part.render.fillStyle; c.lineWidth = part.render.lineWidth; c.strokeStyle = part.render.strokeStyle; c.fill(); } else { c.lineWidth = 1; c.strokeStyle = '#bbb'; } c.stroke(); } c.globalAlpha = 1; } } }; /** * Optimised method for drawing body wireframes in one pass * @private * @method bodyWireframes * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ Render.bodyWireframes = function(render, bodies, context) { var c = context, showInternalEdges = render.options.showInternalEdges, body, part, i, j, k; c.beginPath(); // render all bodies for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (!body.render.visible) continue; // handle compound parts for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) { part = body.parts[k]; c.moveTo(part.vertices[0].x, part.vertices[0].y); for (j = 1; j < part.vertices.length; j++) { if (!part.vertices[j - 1].isInternal || showInternalEdges) { c.lineTo(part.vertices[j].x, part.vertices[j].y); } else { c.moveTo(part.vertices[j].x, part.vertices[j].y); } if (part.vertices[j].isInternal && !showInternalEdges) { c.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y); } } c.lineTo(part.vertices[0].x, part.vertices[0].y); } } c.lineWidth = 1; c.strokeStyle = '#bbb'; c.stroke(); }; /** * Optimised method for drawing body convex hull wireframes in one pass * @private * @method bodyConvexHulls * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ Render.bodyConvexHulls = function(render, bodies, context) { var c = context, body, part, i, j, k; c.beginPath(); // render convex hulls for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (!body.render.visible || body.parts.length === 1) continue; c.moveTo(body.vertices[0].x, body.vertices[0].y); for (j = 1; j < body.vertices.length; j++) { c.lineTo(body.vertices[j].x, body.vertices[j].y); } c.lineTo(body.vertices[0].x, body.vertices[0].y); } c.lineWidth = 1; c.strokeStyle = 'rgba(255,255,255,0.2)'; c.stroke(); }; /** * Renders body vertex numbers. * @private * @method vertexNumbers * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ Render.vertexNumbers = function(render, bodies, context) { var c = context, i, j, k; for (i = 0; i < bodies.length; i++) { var parts = bodies[i].parts; for (k = parts.length > 1 ? 1 : 0; k < parts.length; k++) { var part = parts[k]; for (j = 0; j < part.vertices.length; j++) { c.fillStyle = 'rgba(255,255,255,0.2)'; c.fillText(i + '_' + j, part.position.x + (part.vertices[j].x - part.position.x) * 0.8, part.position.y + (part.vertices[j].y - part.position.y) * 0.8); } } } }; /** * Renders mouse position. * @private * @method mousePosition * @param {render} render * @param {mouse} mouse * @param {RenderingContext} context */ Render.mousePosition = function(render, mouse, context) { var c = context; c.fillStyle = 'rgba(255,255,255,0.8)'; c.fillText(mouse.position.x + ' ' + mouse.position.y, mouse.position.x + 5, mouse.position.y - 5); }; /** * Draws body bounds * @private * @method bodyBounds * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ Render.bodyBounds = function(render, bodies, context) { var c = context, engine = render.engine, options = render.options; c.beginPath(); for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (body.render.visible) { var parts = bodies[i].parts; for (var j = parts.length > 1 ? 1 : 0; j < parts.length; j++) { var part = parts[j]; c.rect(part.bounds.min.x, part.bounds.min.y, part.bounds.max.x - part.bounds.min.x, part.bounds.max.y - part.bounds.min.y); } } } if (options.wireframes) { c.strokeStyle = 'rgba(255,255,255,0.08)'; } else { c.strokeStyle = 'rgba(0,0,0,0.1)'; } c.lineWidth = 1; c.stroke(); }; /** * Draws body angle indicators and axes * @private * @method bodyAxes * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ Render.bodyAxes = function(render, bodies, context) { var c = context, engine = render.engine, options = render.options, part, i, j, k; c.beginPath(); for (i = 0; i < bodies.length; i++) { var body = bodies[i], parts = body.parts; if (!body.render.visible) continue; if (options.showAxes) { // render all axes for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) { part = parts[j]; for (k = 0; k < part.axes.length; k++) { var axis = part.axes[k]; c.moveTo(part.position.x, part.position.y); c.lineTo(part.position.x + axis.x * 20, part.position.y + axis.y * 20); } } } else { for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) { part = parts[j]; for (k = 0; k < part.axes.length; k++) { // render a single axis indicator c.moveTo(part.position.x, part.position.y); c.lineTo((part.vertices[0].x + part.vertices[part.vertices.length-1].x) / 2, (part.vertices[0].y + part.vertices[part.vertices.length-1].y) / 2); } } } } if (options.wireframes) { c.strokeStyle = 'indianred'; } else { c.strokeStyle = 'rgba(0,0,0,0.8)'; c.globalCompositeOperation = 'overlay'; } c.lineWidth = 1; c.stroke(); c.globalCompositeOperation = 'source-over'; }; /** * Draws body positions * @private * @method bodyPositions * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ Render.bodyPositions = function(render, bodies, context) { var c = context, engine = render.engine, options = render.options, body, part, i, k; c.beginPath(); // render current positions for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (!body.render.visible) continue; // handle compound parts for (k = 0; k < body.parts.length; k++) { part = body.parts[k]; c.arc(part.position.x, part.position.y, 3, 0, 2 * Math.PI, false); c.closePath(); } } if (options.wireframes) { c.fillStyle = 'indianred'; } else { c.fillStyle = 'rgba(0,0,0,0.5)'; } c.fill(); c.beginPath(); // render previous positions for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (body.render.visible) { c.arc(body.positionPrev.x, body.positionPrev.y, 2, 0, 2 * Math.PI, false); c.closePath(); } } c.fillStyle = 'rgba(255,165,0,0.8)'; c.fill(); }; /** * Draws body velocity * @private * @method bodyVelocity * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ Render.bodyVelocity = function(render, bodies, context) { var c = context; c.beginPath(); for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (!body.render.visible) continue; c.moveTo(body.position.x, body.position.y); c.lineTo(body.position.x + (body.position.x - body.positionPrev.x) * 2, body.position.y + (body.position.y - body.positionPrev.y) * 2); } c.lineWidth = 3; c.strokeStyle = 'cornflowerblue'; c.stroke(); }; /** * Draws body ids * @private * @method bodyIds * @param {render} render * @param {body[]} bodies * @param {RenderingContext} context */ Render.bodyIds = function(render, bodies, context) { var c = context, i, j; for (i = 0; i < bodies.length; i++) { if (!bodies[i].render.visible) continue; var parts = bodies[i].parts; for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) { var part = parts[j]; c.font = "12px Arial"; c.fillStyle = 'rgba(255,255,255,0.5)'; c.fillText(part.id, part.position.x + 10, part.position.y - 10); } } }; /** * Description * @private * @method collisions * @param {render} render * @param {pair[]} pairs * @param {RenderingContext} context */ Render.collisions = function(render, pairs, context) { var c = context, options = render.options, pair, collision, corrected, bodyA, bodyB, i, j; c.beginPath(); // render collision positions for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive) continue; collision = pair.collision; for (j = 0; j < pair.activeContacts.length; j++) { var contact = pair.activeContacts[j], vertex = contact.vertex; c.rect(vertex.x - 1.5, vertex.y - 1.5, 3.5, 3.5); } } if (options.wireframes) { c.fillStyle = 'rgba(255,255,255,0.7)'; } else { c.fillStyle = 'orange'; } c.fill(); c.beginPath(); // render collision normals for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive) continue; collision = pair.collision; if (pair.activeContacts.length > 0) { var normalPosX = pair.activeContacts[0].vertex.x, normalPosY = pair.activeContacts[0].vertex.y; if (pair.activeContacts.length === 2) { normalPosX = (pair.activeContacts[0].vertex.x + pair.activeContacts[1].vertex.x) / 2; normalPosY = (pair.activeContacts[0].vertex.y + pair.activeContacts[1].vertex.y) / 2; } if (collision.bodyB === collision.supports[0].body || collision.bodyA.isStatic === true) { c.moveTo(normalPosX - collision.normal.x * 8, normalPosY - collision.normal.y * 8); } else { c.moveTo(normalPosX + collision.normal.x * 8, normalPosY + collision.normal.y * 8); } c.lineTo(normalPosX, normalPosY); } } if (options.wireframes) { c.strokeStyle = 'rgba(255,165,0,0.7)'; } else { c.strokeStyle = 'orange'; } c.lineWidth = 1; c.stroke(); }; /** * Description * @private * @method separations * @param {render} render * @param {pair[]} pairs * @param {RenderingContext} context */ Render.separations = function(render, pairs, context) { var c = context, options = render.options, pair, collision, corrected, bodyA, bodyB, i, j; c.beginPath(); // render separations for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive) continue; collision = pair.collision; bodyA = collision.bodyA; bodyB = collision.bodyB; var k = 1; if (!bodyB.isStatic && !bodyA.isStatic) k = 0.5; if (bodyB.isStatic) k = 0; c.moveTo(bodyB.position.x, bodyB.position.y); c.lineTo(bodyB.position.x - collision.penetration.x * k, bodyB.position.y - collision.penetration.y * k); k = 1; if (!bodyB.isStatic && !bodyA.isStatic) k = 0.5; if (bodyA.isStatic) k = 0; c.moveTo(bodyA.position.x, bodyA.position.y); c.lineTo(bodyA.position.x + collision.penetration.x * k, bodyA.position.y + collision.penetration.y * k); } if (options.wireframes) { c.strokeStyle = 'rgba(255,165,0,0.5)'; } else { c.strokeStyle = 'orange'; } c.stroke(); }; /** * Description * @private * @method grid * @param {render} render * @param {grid} grid * @param {RenderingContext} context */ Render.grid = function(render, grid, context) { var c = context, options = render.options; if (options.wireframes) { c.strokeStyle = 'rgba(255,180,0,0.1)'; } else { c.strokeStyle = 'rgba(255,180,0,0.5)'; } c.beginPath(); var bucketKeys = Common.keys(grid.buckets); for (var i = 0; i < bucketKeys.length; i++) { var bucketId = bucketKeys[i]; if (grid.buckets[bucketId].length < 2) continue; var region = bucketId.split(','); c.rect(0.5 + parseInt(region[0], 10) * grid.bucketWidth, 0.5 + parseInt(region[1], 10) * grid.bucketHeight, grid.bucketWidth, grid.bucketHeight); } c.lineWidth = 1; c.stroke(); }; /** * Description * @private * @method inspector * @param {inspector} inspector * @param {RenderingContext} context */ Render.inspector = function(inspector, context) { var engine = inspector.engine, selected = inspector.selected, render = inspector.render, options = render.options, bounds; if (options.hasBounds) { var boundsWidth = render.bounds.max.x - render.bounds.min.x, boundsHeight = render.bounds.max.y - render.bounds.min.y, boundsScaleX = boundsWidth / render.options.width, boundsScaleY = boundsHeight / render.options.height; context.scale(1 / boundsScaleX, 1 / boundsScaleY); context.translate(-render.bounds.min.x, -render.bounds.min.y); } for (var i = 0; i < selected.length; i++) { var item = selected[i].data; context.translate(0.5, 0.5); context.lineWidth = 1; context.strokeStyle = 'rgba(255,165,0,0.9)'; context.setLineDash([1,2]); switch (item.type) { case 'body': // render body selections bounds = item.bounds; context.beginPath(); context.rect(Math.floor(bounds.min.x - 3), Math.floor(bounds.min.y - 3), Math.floor(bounds.max.x - bounds.min.x + 6), Math.floor(bounds.max.y - bounds.min.y + 6)); context.closePath(); context.stroke(); break; case 'constraint': // render constraint selections var point = item.pointA; if (item.bodyA) point = item.pointB; context.beginPath(); context.arc(point.x, point.y, 10, 0, 2 * Math.PI); context.closePath(); context.stroke(); break; } context.setLineDash([]); context.translate(-0.5, -0.5); } // render selection region if (inspector.selectStart !== null) { context.translate(0.5, 0.5); context.lineWidth = 1; context.strokeStyle = 'rgba(255,165,0,0.6)'; context.fillStyle = 'rgba(255,165,0,0.1)'; bounds = inspector.selectBounds; context.beginPath(); context.rect(Math.floor(bounds.min.x), Math.floor(bounds.min.y), Math.floor(bounds.max.x - bounds.min.x), Math.floor(bounds.max.y - bounds.min.y)); context.closePath(); context.stroke(); context.fill(); context.translate(-0.5, -0.5); } if (options.hasBounds) context.setTransform(1, 0, 0, 1, 0, 0); }; /** * Description * @method _createCanvas * @private * @param {} width * @param {} height * @return canvas */ var _createCanvas = function(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; canvas.oncontextmenu = function() { return false; }; canvas.onselectstart = function() { return false; }; return canvas; }; /** * Gets the pixel ratio of the canvas. * @method _getPixelRatio * @private * @param {HTMLElement} canvas * @return {Number} pixel ratio */ var _getPixelRatio = function(canvas) { var context = canvas.getContext('2d'), devicePixelRatio = window.devicePixelRatio || 1, backingStorePixelRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; return devicePixelRatio / backingStorePixelRatio; }; /** * Gets the requested texture (an Image) via its path * @method _getTexture * @private * @param {render} render * @param {string} imagePath * @return {Image} texture */ var _getTexture = function(render, imagePath) { var image = render.textures[imagePath]; if (image) return image; image = render.textures[imagePath] = new Image(); image.src = imagePath; return image; }; /** * Applies the background to the canvas using CSS. * @method applyBackground * @private * @param {render} render * @param {string} background */ var _applyBackground = function(render, background) { var cssBackground = background; if (/(jpg|gif|png)$/.test(background)) cssBackground = 'url(' + background + ')'; render.canvas.style.background = cssBackground; render.canvas.style.backgroundSize = "contain"; render.currentBackground = background; }; /* * * Events Documentation * */ /** * Fired before rendering * * @event beforeRender * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after rendering * * @event afterRender * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /* * * Properties Documentation * */ /** * A back-reference to the `Matter.Render` module. * * @property controller * @type render */ /** * A reference to the `Matter.Engine` instance to be used. * * @property engine * @type engine */ /** * A reference to the element where the canvas is to be inserted (if `render.canvas` has not been specified) * * @property element * @type HTMLElement * @default null */ /** * The canvas element to render to. If not specified, one will be created if `render.element` has been specified. * * @property canvas * @type HTMLCanvasElement * @default null */ /** * The configuration options of the renderer. * * @property options * @type {} */ /** * The target width in pixels of the `render.canvas` to be created. * * @property options.width * @type number * @default 800 */ /** * The target height in pixels of the `render.canvas` to be created. * * @property options.height * @type number * @default 600 */ /** * A flag that specifies if `render.bounds` should be used when rendering. * * @property options.hasBounds * @type boolean * @default false */ /** * A `Bounds` object that specifies the drawing view region. * Rendering will be automatically transformed and scaled to fit within the canvas size (`render.options.width` and `render.options.height`). * This allows for creating views that can pan or zoom around the scene. * You must also set `render.options.hasBounds` to `true` to enable bounded rendering. * * @property bounds * @type bounds */ /** * The 2d rendering context from the `render.canvas` element. * * @property context * @type CanvasRenderingContext2D */ /** * The sprite texture cache. * * @property textures * @type {} */ })(); },{"../body/Composite":2,"../collision/Grid":6,"../core/Common":14,"../core/Events":16,"../geometry/Bounds":24,"../geometry/Vector":26}],30:[function(require,module,exports){ /** * The `Matter.RenderPixi` module is an example renderer using pixi.js. * See also `Matter.Render` for a canvas based renderer. * * @class RenderPixi * @deprecated the Matter.RenderPixi module will soon be removed from the Matter.js core. * It will likely be moved to its own repository (but maintenance will be limited). */ var RenderPixi = {}; module.exports = RenderPixi; var Composite = require('../body/Composite'); var Common = require('../core/Common'); (function() { var _requestAnimationFrame, _cancelAnimationFrame; if (typeof window !== 'undefined') { _requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function(callback){ window.setTimeout(function() { callback(Common.now()); }, 1000 / 60); }; _cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.msCancelAnimationFrame; } /** * Creates a new Pixi.js WebGL renderer * @method create * @param {object} options * @return {RenderPixi} A new renderer * @deprecated */ RenderPixi.create = function(options) { Common.log('RenderPixi.create: Matter.RenderPixi is deprecated (see docs)', 'warn'); var defaults = { controller: RenderPixi, engine: null, element: null, frameRequestId: null, canvas: null, renderer: null, container: null, spriteContainer: null, pixiOptions: null, options: { width: 800, height: 600, background: '#fafafa', wireframeBackground: '#222', hasBounds: false, enabled: true, wireframes: true, showSleeping: true, showDebug: false, showBroadphase: false, showBounds: false, showVelocity: false, showCollisions: false, showAxes: false, showPositions: false, showAngleIndicator: false, showIds: false, showShadows: false } }; var render = Common.extend(defaults, options), transparent = !render.options.wireframes && render.options.background === 'transparent'; // init pixi render.pixiOptions = render.pixiOptions || { view: render.canvas, transparent: transparent, antialias: true, backgroundColor: options.background }; render.mouse = options.mouse; render.engine = options.engine; render.renderer = render.renderer || new PIXI.WebGLRenderer(render.options.width, render.options.height, render.pixiOptions); render.container = render.container || new PIXI.Container(); render.spriteContainer = render.spriteContainer || new PIXI.Container(); render.canvas = render.canvas || render.renderer.view; render.bounds = render.bounds || { min: { x: 0, y: 0 }, max: { x: render.options.width, y: render.options.height } }; // caches render.textures = {}; render.sprites = {}; render.primitives = {}; // use a sprite batch for performance render.container.addChild(render.spriteContainer); // insert canvas if (Common.isElement(render.element)) { render.element.appendChild(render.canvas); } else { Common.log('No "render.element" passed, "render.canvas" was not inserted into document.', 'warn'); } // prevent menus on canvas render.canvas.oncontextmenu = function() { return false; }; render.canvas.onselectstart = function() { return false; }; return render; }; /** * Continuously updates the render canvas on the `requestAnimationFrame` event. * @method run * @param {render} render * @deprecated */ RenderPixi.run = function(render) { (function loop(time){ render.frameRequestId = _requestAnimationFrame(loop); RenderPixi.world(render); })(); }; /** * Ends execution of `Render.run` on the given `render`, by canceling the animation frame request event loop. * @method stop * @param {render} render * @deprecated */ RenderPixi.stop = function(render) { _cancelAnimationFrame(render.frameRequestId); }; /** * Clears the scene graph * @method clear * @param {RenderPixi} render * @deprecated */ RenderPixi.clear = function(render) { var container = render.container, spriteContainer = render.spriteContainer; // clear stage container while (container.children[0]) { container.removeChild(container.children[0]); } // clear sprite batch while (spriteContainer.children[0]) { spriteContainer.removeChild(spriteContainer.children[0]); } var bgSprite = render.sprites['bg-0']; // clear caches render.textures = {}; render.sprites = {}; render.primitives = {}; // set background sprite render.sprites['bg-0'] = bgSprite; if (bgSprite) container.addChildAt(bgSprite, 0); // add sprite batch back into container render.container.addChild(render.spriteContainer); // reset background state render.currentBackground = null; // reset bounds transforms container.scale.set(1, 1); container.position.set(0, 0); }; /** * Sets the background of the canvas * @method setBackground * @param {RenderPixi} render * @param {string} background * @deprecated */ RenderPixi.setBackground = function(render, background) { if (render.currentBackground !== background) { var isColor = background.indexOf && background.indexOf('#') !== -1, bgSprite = render.sprites['bg-0']; if (isColor) { // if solid background color var color = Common.colorToNumber(background); render.renderer.backgroundColor = color; // remove background sprite if existing if (bgSprite) render.container.removeChild(bgSprite); } else { // initialise background sprite if needed if (!bgSprite) { var texture = _getTexture(render, background); bgSprite = render.sprites['bg-0'] = new PIXI.Sprite(texture); bgSprite.position.x = 0; bgSprite.position.y = 0; render.container.addChildAt(bgSprite, 0); } } render.currentBackground = background; } }; /** * Description * @method world * @param {engine} engine * @deprecated */ RenderPixi.world = function(render) { var engine = render.engine, world = engine.world, renderer = render.renderer, container = render.container, options = render.options, bodies = Composite.allBodies(world), allConstraints = Composite.allConstraints(world), constraints = [], i; if (options.wireframes) { RenderPixi.setBackground(render, options.wireframeBackground); } else { RenderPixi.setBackground(render, options.background); } // handle bounds var boundsWidth = render.bounds.max.x - render.bounds.min.x, boundsHeight = render.bounds.max.y - render.bounds.min.y, boundsScaleX = boundsWidth / render.options.width, boundsScaleY = boundsHeight / render.options.height; if (options.hasBounds) { // Hide bodies that are not in view for (i = 0; i < bodies.length; i++) { var body = bodies[i]; body.render.sprite.visible = Bounds.overlaps(body.bounds, render.bounds); } // filter out constraints that are not in view for (i = 0; i < allConstraints.length; i++) { var constraint = allConstraints[i], bodyA = constraint.bodyA, bodyB = constraint.bodyB, pointAWorld = constraint.pointA, pointBWorld = constraint.pointB; if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA); if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB); if (!pointAWorld || !pointBWorld) continue; if (Bounds.contains(render.bounds, pointAWorld) || Bounds.contains(render.bounds, pointBWorld)) constraints.push(constraint); } // transform the view container.scale.set(1 / boundsScaleX, 1 / boundsScaleY); container.position.set(-render.bounds.min.x * (1 / boundsScaleX), -render.bounds.min.y * (1 / boundsScaleY)); } else { constraints = allConstraints; } for (i = 0; i < bodies.length; i++) RenderPixi.body(render, bodies[i]); for (i = 0; i < constraints.length; i++) RenderPixi.constraint(render, constraints[i]); renderer.render(container); }; /** * Description * @method constraint * @param {engine} engine * @param {constraint} constraint * @deprecated */ RenderPixi.constraint = function(render, constraint) { var engine = render.engine, bodyA = constraint.bodyA, bodyB = constraint.bodyB, pointA = constraint.pointA, pointB = constraint.pointB, container = render.container, constraintRender = constraint.render, primitiveId = 'c-' + constraint.id, primitive = render.primitives[primitiveId]; // initialise constraint primitive if not existing if (!primitive) primitive = render.primitives[primitiveId] = new PIXI.Graphics(); // don't render if constraint does not have two end points if (!constraintRender.visible || !constraint.pointA || !constraint.pointB) { primitive.clear(); return; } // add to scene graph if not already there if (Common.indexOf(container.children, primitive) === -1) container.addChild(primitive); // render the constraint on every update, since they can change dynamically primitive.clear(); primitive.beginFill(0, 0); primitive.lineStyle(constraintRender.lineWidth, Common.colorToNumber(constraintRender.strokeStyle), 1); if (bodyA) { primitive.moveTo(bodyA.position.x + pointA.x, bodyA.position.y + pointA.y); } else { primitive.moveTo(pointA.x, pointA.y); } if (bodyB) { primitive.lineTo(bodyB.position.x + pointB.x, bodyB.position.y + pointB.y); } else { primitive.lineTo(pointB.x, pointB.y); } primitive.endFill(); }; /** * Description * @method body * @param {engine} engine * @param {body} body * @deprecated */ RenderPixi.body = function(render, body) { var engine = render.engine, bodyRender = body.render; if (!bodyRender.visible) return; if (bodyRender.sprite && bodyRender.sprite.texture) { var spriteId = 'b-' + body.id, sprite = render.sprites[spriteId], spriteContainer = render.spriteContainer; // initialise body sprite if not existing if (!sprite) sprite = render.sprites[spriteId] = _createBodySprite(render, body); // add to scene graph if not already there if (Common.indexOf(spriteContainer.children, sprite) === -1) spriteContainer.addChild(sprite); // update body sprite sprite.position.x = body.position.x; sprite.position.y = body.position.y; sprite.rotation = body.angle; sprite.scale.x = bodyRender.sprite.xScale || 1; sprite.scale.y = bodyRender.sprite.yScale || 1; } else { var primitiveId = 'b-' + body.id, primitive = render.primitives[primitiveId], container = render.container; // initialise body primitive if not existing if (!primitive) { primitive = render.primitives[primitiveId] = _createBodyPrimitive(render, body); primitive.initialAngle = body.angle; } // add to scene graph if not already there if (Common.indexOf(container.children, primitive) === -1) container.addChild(primitive); // update body primitive primitive.position.x = body.position.x; primitive.position.y = body.position.y; primitive.rotation = body.angle - primitive.initialAngle; } }; /** * Creates a body sprite * @method _createBodySprite * @private * @param {RenderPixi} render * @param {body} body * @return {PIXI.Sprite} sprite * @deprecated */ var _createBodySprite = function(render, body) { var bodyRender = body.render, texturePath = bodyRender.sprite.texture, texture = _getTexture(render, texturePath), sprite = new PIXI.Sprite(texture); sprite.anchor.x = body.render.sprite.xOffset; sprite.anchor.y = body.render.sprite.yOffset; return sprite; }; /** * Creates a body primitive * @method _createBodyPrimitive * @private * @param {RenderPixi} render * @param {body} body * @return {PIXI.Graphics} graphics * @deprecated */ var _createBodyPrimitive = function(render, body) { var bodyRender = body.render, options = render.options, primitive = new PIXI.Graphics(), fillStyle = Common.colorToNumber(bodyRender.fillStyle), strokeStyle = Common.colorToNumber(bodyRender.strokeStyle), strokeStyleIndicator = Common.colorToNumber(bodyRender.strokeStyle), strokeStyleWireframe = Common.colorToNumber('#bbb'), strokeStyleWireframeIndicator = Common.colorToNumber('#CD5C5C'), part; primitive.clear(); // handle compound parts for (var k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) { part = body.parts[k]; if (!options.wireframes) { primitive.beginFill(fillStyle, 1); primitive.lineStyle(bodyRender.lineWidth, strokeStyle, 1); } else { primitive.beginFill(0, 0); primitive.lineStyle(1, strokeStyleWireframe, 1); } primitive.moveTo(part.vertices[0].x - body.position.x, part.vertices[0].y - body.position.y); for (var j = 1; j < part.vertices.length; j++) { primitive.lineTo(part.vertices[j].x - body.position.x, part.vertices[j].y - body.position.y); } primitive.lineTo(part.vertices[0].x - body.position.x, part.vertices[0].y - body.position.y); primitive.endFill(); // angle indicator if (options.showAngleIndicator || options.showAxes) { primitive.beginFill(0, 0); if (options.wireframes) { primitive.lineStyle(1, strokeStyleWireframeIndicator, 1); } else { primitive.lineStyle(1, strokeStyleIndicator); } primitive.moveTo(part.position.x - body.position.x, part.position.y - body.position.y); primitive.lineTo(((part.vertices[0].x + part.vertices[part.vertices.length-1].x) / 2 - body.position.x), ((part.vertices[0].y + part.vertices[part.vertices.length-1].y) / 2 - body.position.y)); primitive.endFill(); } } return primitive; }; /** * Gets the requested texture (a PIXI.Texture) via its path * @method _getTexture * @private * @param {RenderPixi} render * @param {string} imagePath * @return {PIXI.Texture} texture * @deprecated */ var _getTexture = function(render, imagePath) { var texture = render.textures[imagePath]; if (!texture) texture = render.textures[imagePath] = PIXI.Texture.fromImage(imagePath); return texture; }; })(); },{"../body/Composite":2,"../core/Common":14}]},{},[28])(28) }); ================================================ FILE: public/libs/laya/protobuf.js ================================================ /*! * protobuf.js v6.7.0 (c) 2016, Daniel Wirtz * Compiled Sun, 12 Mar 2017 21:09:56 UTC * Licensed under the BSD-3-Clause License * see: https://github.com/dcodeIO/protobuf.js for details */ (function(global,undefined){"use strict";(function prelude(modules, cache, entries) { // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS // sources through a conflict-free require shim and is again wrapped within an iife that // provides a unified `global` and a minification-friendly `undefined` var plus a global // "use strict" directive so that minification can remove the directives of each module. function $require(name) { var $module = cache[name]; if (!$module) modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports); return $module.exports; } // Expose globally var protobuf = global.protobuf = $require(entries[0]); // Be nice to AMD if (typeof define === "function" && define.amd) define(["long"], function(Long) { protobuf.util.Long = Long; protobuf.configure(); return protobuf; }); // Be nice to CommonJS if (typeof module === "object" && module && module.exports) module.exports = protobuf; })/* end of prelude */({1:[function(require,module,exports){ "use strict"; module.exports = asPromise; /** * Returns a promise from a node-style callback function. * @memberof util * @param {function(?Error, ...*)} fn Function to call * @param {*} ctx Function context * @param {...*} params Function arguments * @returns {Promise<*>} Promisified function */ function asPromise(fn, ctx/*, varargs */) { var params = []; for (var i = 2; i < arguments.length;) params.push(arguments[i++]); var pending = true; return new Promise(function asPromiseExecutor(resolve, reject) { params.push(function asPromiseCallback(err/*, varargs */) { if (pending) { pending = false; if (err) reject(err); else { var args = []; for (var i = 1; i < arguments.length;) args.push(arguments[i++]); resolve.apply(null, args); } } }); try { fn.apply(ctx || this, params); // eslint-disable-line no-invalid-this } catch (err) { if (pending) { pending = false; reject(err); } } }); } },{}],2:[function(require,module,exports){ "use strict"; /** * A minimal base64 implementation for number arrays. * @memberof util * @namespace */ var base64 = exports; /** * Calculates the byte length of a base64 encoded string. * @param {string} string Base64 encoded string * @returns {number} Byte length */ base64.length = function length(string) { var p = string.length; if (!p) return 0; var n = 0; while (--p % 4 > 1 && string.charAt(p) === "=") ++n; return Math.ceil(string.length * 3) / 4 - n; }; // Base64 encoding table var b64 = new Array(64); // Base64 decoding table var s64 = new Array(123); // 65..90, 97..122, 48..57, 43, 47 for (var i = 0; i < 64;) s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; /** * Encodes a buffer to a base64 encoded string. * @param {Uint8Array} buffer Source buffer * @param {number} start Source start * @param {number} end Source end * @returns {string} Base64 encoded string */ base64.encode = function encode(buffer, start, end) { var string = []; // alt: new Array(Math.ceil((end - start) / 3) * 4); var i = 0, // output index j = 0, // goto index t; // temporary while (start < end) { var b = buffer[start++]; switch (j) { case 0: string[i++] = b64[b >> 2]; t = (b & 3) << 4; j = 1; break; case 1: string[i++] = b64[t | b >> 4]; t = (b & 15) << 2; j = 2; break; case 2: string[i++] = b64[t | b >> 6]; string[i++] = b64[b & 63]; j = 0; break; } } if (j) { string[i++] = b64[t]; string[i ] = 61; if (j === 1) string[i + 1] = 61; } return String.fromCharCode.apply(String, string); }; var invalidEncoding = "invalid encoding"; /** * Decodes a base64 encoded string to a buffer. * @param {string} string Source string * @param {Uint8Array} buffer Destination buffer * @param {number} offset Destination offset * @returns {number} Number of bytes written * @throws {Error} If encoding is invalid */ base64.decode = function decode(string, buffer, offset) { var start = offset; var j = 0, // goto index t; // temporary for (var i = 0; i < string.length;) { var c = string.charCodeAt(i++); if (c === 61 && j > 1) break; if ((c = s64[c]) === undefined) throw Error(invalidEncoding); switch (j) { case 0: t = c; j = 1; break; case 1: buffer[offset++] = t << 2 | (c & 48) >> 4; t = c; j = 2; break; case 2: buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; t = c; j = 3; break; case 3: buffer[offset++] = (t & 3) << 6 | c; j = 0; break; } } if (j === 1) throw Error(invalidEncoding); return offset - start; }; /** * Tests if the specified string appears to be base64 encoded. * @param {string} string String to test * @returns {boolean} `true` if probably base64 encoded, otherwise false */ base64.test = function test(string) { return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); }; },{}],3:[function(require,module,exports){ "use strict"; module.exports = codegen; var blockOpenRe = /[{[]$/, blockCloseRe = /^[}\]]/, casingRe = /:$/, branchRe = /^\s*(?:if|}?else if|while|for)\b|\b(?:else)\s*$/, breakRe = /\b(?:break|continue)(?: \w+)?;?$|^\s*return\b/; /** * A closure for generating functions programmatically. * @memberof util * @namespace * @function * @param {...string} params Function parameter names * @returns {Codegen} Codegen instance * @property {boolean} supported Whether code generation is supported by the environment. * @property {boolean} verbose=false When set to true, codegen will log generated code to console. Useful for debugging. * @property {function(string, ...*):string} sprintf Underlying sprintf implementation */ function codegen() { var params = [], src = [], indent = 1, inCase = false; for (var i = 0; i < arguments.length;) params.push(arguments[i++]); /** * A codegen instance as returned by {@link codegen}, that also is a sprintf-like appender function. * @typedef Codegen * @type {function} * @param {string} format Format string * @param {...*} args Replacements * @returns {Codegen} Itself * @property {function(string=):string} str Stringifies the so far generated function source. * @property {function(string=, Object=):function} eof Ends generation and builds the function whilst applying a scope. */ /**/ function gen() { var args = [], i = 0; for (; i < arguments.length;) args.push(arguments[i++]); var line = sprintf.apply(null, args); var level = indent; if (src.length) { var prev = src[src.length - 1]; // block open or one time branch if (blockOpenRe.test(prev)) level = ++indent; // keep else if (branchRe.test(prev)) ++level; // once // casing if (casingRe.test(prev) && !casingRe.test(line)) { level = ++indent; inCase = true; } else if (inCase && breakRe.test(prev)) { level = --indent; inCase = false; } // block close if (blockCloseRe.test(line)) level = --indent; } for (i = 0; i < level; ++i) line = "\t" + line; src.push(line); return gen; } /** * Stringifies the so far generated function source. * @param {string} [name] Function name, defaults to generate an anonymous function * @returns {string} Function source using tabs for indentation * @inner */ function str(name) { return "function" + (name ? " " + name.replace(/[^\w_$]/g, "_") : "") + "(" + params.join(",") + ") {\n" + src.join("\n") + "\n}"; } gen.str = str; /** * Ends generation and builds the function whilst applying a scope. * @param {string} [name] Function name, defaults to generate an anonymous function * @param {Object.} [scope] Function scope * @returns {function} The generated function, with scope applied if specified * @inner */ function eof(name, scope) { if (typeof name === "object") { scope = name; name = undefined; } var source = gen.str(name); if (codegen.verbose) console.log("--- codegen ---\n" + source.replace(/^/mg, "> ").replace(/\t/g, " ")); // eslint-disable-line no-console var keys = Object.keys(scope || (scope = {})); return Function.apply(null, keys.concat("return " + source)).apply(null, keys.map(function(key) { return scope[key]; })); // eslint-disable-line no-new-func // ^ Creates a wrapper function with the scoped variable names as its parameters, // calls it with the respective scoped variable values ^ // and returns our brand-new properly scoped function. // // This works because "Invoking the Function constructor as a function (without using the // new operator) has the same effect as invoking it as a constructor." // https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Function } gen.eof = eof; return gen; } function sprintf(format) { var args = [], i = 1; for (; i < arguments.length;) args.push(arguments[i++]); i = 0; format = format.replace(/%([dfjs])/g, function($0, $1) { switch ($1) { case "d": return Math.floor(args[i++]); case "f": return Number(args[i++]); case "j": return JSON.stringify(args[i++]); default: return args[i++]; } }); if (i !== args.length) throw Error("argument count mismatch"); return format; } codegen.sprintf = sprintf; codegen.supported = false; try { codegen.supported = codegen("a","b")("return a-b").eof()(2,1) === 1; } catch (e) {} // eslint-disable-line no-empty codegen.verbose = false; },{}],4:[function(require,module,exports){ "use strict"; module.exports = EventEmitter; /** * Constructs a new event emitter instance. * @classdesc A minimal event emitter. * @memberof util * @constructor */ function EventEmitter() { /** * Registered listeners. * @type {Object.} * @private */ this._listeners = {}; } /** * Registers an event listener. * @param {string} evt Event name * @param {function} fn Listener * @param {*} [ctx] Listener context * @returns {util.EventEmitter} `this` */ EventEmitter.prototype.on = function on(evt, fn, ctx) { (this._listeners[evt] || (this._listeners[evt] = [])).push({ fn : fn, ctx : ctx || this }); return this; }; /** * Removes an event listener or any matching listeners if arguments are omitted. * @param {string} [evt] Event name. Removes all listeners if omitted. * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. * @returns {util.EventEmitter} `this` */ EventEmitter.prototype.off = function off(evt, fn) { if (evt === undefined) this._listeners = {}; else { if (fn === undefined) this._listeners[evt] = []; else { var listeners = this._listeners[evt]; for (var i = 0; i < listeners.length;) if (listeners[i].fn === fn) listeners.splice(i, 1); else ++i; } } return this; }; /** * Emits an event by calling its listeners with the specified arguments. * @param {string} evt Event name * @param {...*} args Arguments * @returns {util.EventEmitter} `this` */ EventEmitter.prototype.emit = function emit(evt) { var listeners = this._listeners[evt]; if (listeners) { var args = [], i = 1; for (; i < arguments.length;) args.push(arguments[i++]); for (i = 0; i < listeners.length;) listeners[i].fn.apply(listeners[i++].ctx, args); } return this; }; },{}],5:[function(require,module,exports){ "use strict"; module.exports = fetch; var asPromise = require(1), inquire = require(6); var fs = inquire("fs"); /** * Node-style callback as used by {@link util.fetch}. * @typedef FetchCallback * @type {function} * @param {?Error} error Error, if any, otherwise `null` * @param {string} [contents] File contents, if there hasn't been an error * @returns {undefined} */ /** * Options as used by {@link util.fetch}. * @typedef FetchOptions * @type {Object} * @property {boolean} [binary=false] Whether expecting a binary response * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest */ /** * Fetches the contents of a file. * @memberof util * @param {string} filename File path or url * @param {FetchOptions} options Fetch options * @param {FetchCallback} callback Callback function * @returns {undefined} */ function fetch(filename, options, callback) { if (typeof options === "function") { callback = options; options = {}; } else if (!options) options = {}; if (!callback) return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. if (!options.xhr && fs && fs.readFile) return fs.readFile(filename, function fetchReadFileCallback(err, contents) { return err && typeof XMLHttpRequest !== "undefined" ? fetch.xhr(filename, options, callback) : err ? callback(err) : callback(null, options.binary ? contents : contents.toString("utf8")); }); // use the XHR version otherwise. return fetch.xhr(filename, options, callback); } /** * Fetches the contents of a file. * @name util.fetch * @function * @param {string} path File path or url * @param {FetchCallback} callback Callback function * @returns {undefined} * @variation 2 */ /** * Fetches the contents of a file. * @name util.fetch * @function * @param {string} path File path or url * @param {FetchOptions} [options] Fetch options * @returns {Promise} Promise * @variation 3 */ /**/ fetch.xhr = function fetch_xhr(filename, options, callback) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { if (xhr.readyState !== 4) return undefined; // local cors security errors return status 0 / empty string, too. afaik this cannot be // reliably distinguished from an actually empty file for security reasons. feel free // to send a pull request if you are aware of a solution. if (xhr.status !== 0 && xhr.status !== 200) return callback(Error("status " + xhr.status)); // if binary data is expected, make sure that some sort of array is returned, even if // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. if (options.binary) { var buffer = xhr.response; if (!buffer) { buffer = []; for (var i = 0; i < xhr.responseText.length; ++i) buffer.push(xhr.responseText.charCodeAt(i) & 255); } return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); } return callback(null, xhr.responseText); }; if (options.binary) { // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers if ("overrideMimeType" in xhr) xhr.overrideMimeType("text/plain; charset=x-user-defined"); xhr.responseType = "arraybuffer"; } xhr.open("GET", filename); xhr.send(); }; },{"1":1,"6":6}],6:[function(require,module,exports){ "use strict"; module.exports = inquire; /** * Requires a module only if available. * @memberof util * @param {string} moduleName Module to require * @returns {?Object} Required module if available and not empty, otherwise `null` */ function inquire(moduleName) { try { var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval if (mod && (mod.length || Object.keys(mod).length)) return mod; } catch (e) {} // eslint-disable-line no-empty return null; } },{}],7:[function(require,module,exports){ "use strict"; /** * A minimal path module to resolve Unix, Windows and URL paths alike. * @memberof util * @namespace */ var path = exports; var isAbsolute = /** * Tests if the specified path is absolute. * @param {string} path Path to test * @returns {boolean} `true` if path is absolute */ path.isAbsolute = function isAbsolute(path) { return /^(?:\/|\w+:)/.test(path); }; var normalize = /** * Normalizes the specified path. * @param {string} path Path to normalize * @returns {string} Normalized path */ path.normalize = function normalize(path) { path = path.replace(/\\/g, "/") .replace(/\/{2,}/g, "/"); var parts = path.split("/"), absolute = isAbsolute(path), prefix = ""; if (absolute) prefix = parts.shift() + "/"; for (var i = 0; i < parts.length;) { if (parts[i] === "..") { if (i > 0 && parts[i - 1] !== "..") parts.splice(--i, 2); else if (absolute) parts.splice(i, 1); else ++i; } else if (parts[i] === ".") parts.splice(i, 1); else ++i; } return prefix + parts.join("/"); }; /** * Resolves the specified include path against the specified origin path. * @param {string} originPath Path to the origin file * @param {string} includePath Include path relative to origin path * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized * @returns {string} Path to the include file */ path.resolve = function resolve(originPath, includePath, alreadyNormalized) { if (!alreadyNormalized) includePath = normalize(includePath); if (isAbsolute(includePath)) return includePath; if (!alreadyNormalized) originPath = normalize(originPath); return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; }; },{}],8:[function(require,module,exports){ "use strict"; module.exports = pool; /** * An allocator as used by {@link util.pool}. * @typedef PoolAllocator * @type {function} * @param {number} size Buffer size * @returns {Uint8Array} Buffer */ /** * A slicer as used by {@link util.pool}. * @typedef PoolSlicer * @type {function} * @param {number} start Start offset * @param {number} end End offset * @returns {Uint8Array} Buffer slice * @this {Uint8Array} */ /** * A general purpose buffer pool. * @memberof util * @function * @param {PoolAllocator} alloc Allocator * @param {PoolSlicer} slice Slicer * @param {number} [size=8192] Slab size * @returns {PoolAllocator} Pooled allocator */ function pool(alloc, slice, size) { var SIZE = size || 8192; var MAX = SIZE >>> 1; var slab = null; var offset = SIZE; return function pool_alloc(size) { if (size < 1 || size > MAX) return alloc(size); if (offset + size > SIZE) { slab = alloc(SIZE); offset = 0; } var buf = slice.call(slab, offset, offset += size); if (offset & 7) // align to 32 bit offset = (offset | 7) + 1; return buf; }; } },{}],9:[function(require,module,exports){ "use strict"; /** * A minimal UTF8 implementation for number arrays. * @memberof util * @namespace */ var utf8 = exports; /** * Calculates the UTF8 byte length of a string. * @param {string} string String * @returns {number} Byte length */ utf8.length = function utf8_length(string) { var len = 0, c = 0; for (var i = 0; i < string.length; ++i) { c = string.charCodeAt(i); if (c < 128) len += 1; else if (c < 2048) len += 2; else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { ++i; len += 4; } else len += 3; } return len; }; /** * Reads UTF8 bytes as a string. * @param {Uint8Array} buffer Source buffer * @param {number} start Source start * @param {number} end Source end * @returns {string} String read */ utf8.read = function utf8_read(buffer, start, end) { var len = end - start; if (len < 1) return ""; var parts = null, chunk = [], i = 0, // char offset t; // temporary while (start < end) { t = buffer[start++]; if (t < 128) chunk[i++] = t; else if (t > 191 && t < 224) chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; else if (t > 239 && t < 365) { t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; chunk[i++] = 0xD800 + (t >> 10); chunk[i++] = 0xDC00 + (t & 1023); } else chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; if (i > 8191) { (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); i = 0; } } if (parts) { if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); return parts.join(""); } return String.fromCharCode.apply(String, chunk.slice(0, i)); }; /** * Writes a string as UTF8 bytes. * @param {string} string Source string * @param {Uint8Array} buffer Destination buffer * @param {number} offset Destination offset * @returns {number} Bytes written */ utf8.write = function utf8_write(string, buffer, offset) { var start = offset, c1, // character 1 c2; // character 2 for (var i = 0; i < string.length; ++i) { c1 = string.charCodeAt(i); if (c1 < 128) { buffer[offset++] = c1; } else if (c1 < 2048) { buffer[offset++] = c1 >> 6 | 192; buffer[offset++] = c1 & 63 | 128; } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); ++i; buffer[offset++] = c1 >> 18 | 240; buffer[offset++] = c1 >> 12 & 63 | 128; buffer[offset++] = c1 >> 6 & 63 | 128; buffer[offset++] = c1 & 63 | 128; } else { buffer[offset++] = c1 >> 12 | 224; buffer[offset++] = c1 >> 6 & 63 | 128; buffer[offset++] = c1 & 63 | 128; } } return offset - start; }; },{}],10:[function(require,module,exports){ "use strict"; module.exports = Class; var Message = require(21), util = require(36); var Type; // cyclic /** * Constructs a new message prototype for the specified reflected type and sets up its constructor. * @classdesc Runtime class providing the tools to create your own custom classes. * @constructor * @param {Type} type Reflected message type * @param {*} [ctor] Custom constructor to set up, defaults to create a generic one if omitted * @returns {Message} Message prototype */ function Class(type, ctor) { if (!Type) Type = require(34); if (!(type instanceof Type)) throw TypeError("type must be a Type"); if (ctor) { if (typeof ctor !== "function") throw TypeError("ctor must be a function"); } else ctor = Class.generate(type).eof(type.name); // named constructor function (codegen is required anyway) // Let's pretend... ctor.constructor = Class; // new Class() -> Message.prototype (ctor.prototype = new Message()).constructor = ctor; // Static methods on Message are instance methods on Class and vice versa util.merge(ctor, Message, true); // Classes and messages reference their reflected type ctor.$type = type; ctor.prototype.$type = type; // Messages have non-enumerable default values on their prototype var i = 0; for (; i < /* initializes */ type.fieldsArray.length; ++i) { // objects on the prototype must be immmutable. users must assign a new object instance and // cannot use Array#push on empty arrays on the prototype for example, as this would modify // the value on the prototype for ALL messages of this type. Hence, these objects are frozen. ctor.prototype[type._fieldsArray[i].name] = Array.isArray(type._fieldsArray[i].resolve().defaultValue) ? util.emptyArray : util.isObject(type._fieldsArray[i].defaultValue) && !type._fieldsArray[i].long ? util.emptyObject : type._fieldsArray[i].defaultValue; // if a long, it is frozen when initialized } // Messages have non-enumerable getters and setters for each virtual oneof field var ctorProperties = {}; for (i = 0; i < /* initializes */ type.oneofsArray.length; ++i) ctorProperties[type._oneofsArray[i].resolve().name] = { get: util.oneOfGetter(type._oneofsArray[i].oneof), set: util.oneOfSetter(type._oneofsArray[i].oneof) }; if (i) Object.defineProperties(ctor.prototype, ctorProperties); // Register type.ctor = ctor; return ctor.prototype; } /** * Generates a constructor function for the specified type. * @param {Type} type Type to use * @returns {Codegen} Codegen instance */ Class.generate = function generate(type) { // eslint-disable-line no-unused-vars /* eslint-disable no-unexpected-multiline */ var gen = util.codegen("p"); // see issue #700 /* for (var i = 0, field; i < type.fieldsArray.length; ++i) if ((field = type._fieldsArray[i]).map) gen ("this%s={}", util.safeProp(field.name)); else if (field.repeated) gen ("this%s=[]", util.safeProp(field.name)); */ return gen ("if(p){") ("for(var ks=Object.keys(p),i=0;i} object Plain object * @returns {Message} Message instance */ /** * Creates a new message of this type from a plain object. Also converts values to their respective internal types. * This is an alias of {@link Class#fromObject}. * @name Class#from * @function * @param {Object.} object Plain object * @returns {Message} Message instance */ /** * Creates a plain object from a message of this type. Also converts values to other types if specified. * @name Class#toObject * @function * @param {Message} message Message instance * @param {ConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ /** * Encodes a message of this type. * @name Class#encode * @function * @param {Message|Object} message Message to encode * @param {Writer} [writer] Writer to use * @returns {Writer} Writer */ /** * Encodes a message of this type preceeded by its length as a varint. * @name Class#encodeDelimited * @function * @param {Message|Object} message Message to encode * @param {Writer} [writer] Writer to use * @returns {Writer} Writer */ /** * Decodes a message of this type. * @name Class#decode * @function * @param {Reader|Uint8Array} reader Reader or buffer to decode * @returns {Message} Decoded message */ /** * Decodes a message of this type preceeded by its length as a varint. * @name Class#decodeDelimited * @function * @param {Reader|Uint8Array} reader Reader or buffer to decode * @returns {Message} Decoded message */ /** * Verifies a message of this type. * @name Class#verify * @function * @param {Message|Object} message Message or plain object to verify * @returns {?string} `null` if valid, otherwise the reason why it is not */ },{"21":21,"34":34,"36":36}],11:[function(require,module,exports){ "use strict"; module.exports = common; /** * Provides common type definitions. * Can also be used to provide additional google types or your own custom types. * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition * @returns {undefined} * @property {Object.} google/protobuf/any.proto Any * @property {Object.} google/protobuf/duration.proto Duration * @property {Object.} google/protobuf/empty.proto Empty * @property {Object.} google/protobuf/struct.proto Struct, Value, NullValue and ListValue * @property {Object.} google/protobuf/timestamp.proto Timestamp * @property {Object.} google/protobuf/wrappers.proto Wrappers * @example * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension) * protobuf.common("descriptor", descriptorJson); * * // manually provides a custom definition (uses my.foo namespace) * protobuf.common("my/foo/bar.proto", myFooBarJson); */ function common(name, json) { if (!commonRe.test(name)) { name = "google/protobuf/" + name + ".proto"; json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; } common[name] = json; } var commonRe = /\/|\./; // Not provided because of limited use (feel free to discuss or to provide yourself): // // google/protobuf/descriptor.proto // google/protobuf/field_mask.proto // google/protobuf/source_context.proto // google/protobuf/type.proto // // Stripped and pre-parsed versions of these non-bundled files are instead available as part of // the repository or package within the google/protobuf directory. common("any", { Any: { fields: { type_url: { type: "string", id: 1 }, value: { type: "bytes", id: 2 } } } }); var timeType; common("duration", { Duration: timeType = { fields: { seconds: { type: "int64", id: 1 }, nanos: { type: "int32", id: 2 } } } }); common("timestamp", { Timestamp: timeType }); common("empty", { Empty: { fields: {} } }); common("struct", { Struct: { fields: { fields: { keyType: "string", type: "Value", id: 1 } } }, Value: { oneofs: { kind: { oneof: [ "nullValue", "numberValue", "stringValue", "boolValue", "structValue", "listValue" ] } }, fields: { nullValue: { type: "NullValue", id: 1 }, numberValue: { type: "double", id: 2 }, stringValue: { type: "string", id: 3 }, boolValue: { type: "bool", id: 4 }, structValue: { type: "Struct", id: 5 }, listValue: { type: "ListValue", id: 6 } } }, NullValue: { values: { NULL_VALUE: 0 } }, ListValue: { fields: { values: { rule: "repeated", type: "Value", id: 1 } } } }); common("wrappers", { DoubleValue: { fields: { value: { type: "double", id: 1 } } }, FloatValue: { fields: { value: { type: "float", id: 1 } } }, Int64Value: { fields: { value: { type: "int64", id: 1 } } }, UInt64Value: { fields: { value: { type: "uint64", id: 1 } } }, Int32Value: { fields: { value: { type: "int32", id: 1 } } }, UInt32Value: { fields: { value: { type: "uint32", id: 1 } } }, BoolValue: { fields: { value: { type: "bool", id: 1 } } }, StringValue: { fields: { value: { type: "string", id: 1 } } }, BytesValue: { fields: { value: { type: "bytes", id: 1 } } } }); },{}],12:[function(require,module,exports){ "use strict"; /** * Runtime message from/to plain object converters. * @namespace */ var converter = exports; var Enum = require(15), util = require(36); /** * Generates a partial value fromObject conveter. * @param {Codegen} gen Codegen instance * @param {Field} field Reflected field * @param {number} fieldIndex Field index * @param {string} prop Property reference * @returns {Codegen} Codegen instance * @ignore */ function genValuePartial_fromObject(gen, field, fieldIndex, prop) { /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ if (field.resolvedType) { if (field.resolvedType instanceof Enum) { gen ("switch(d%s){", prop); for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { if (field.repeated && values[keys[i]] === field.typeDefault) gen ("default:"); gen ("case%j:", keys[i]) ("case %j:", values[keys[i]]) ("m%s=%j", prop, values[keys[i]]) ("break"); } gen ("}"); } else gen ("if(typeof d%s!==\"object\")", prop) ("throw TypeError(%j)", field.fullName + ": object expected") ("m%s=types[%d].fromObject(d%s)", prop, fieldIndex, prop); } else { var isUnsigned = false; switch (field.type) { case "double": case "float":gen ("m%s=Number(d%s)", prop, prop); break; case "uint32": case "fixed32": gen ("m%s=d%s>>>0", prop, prop); break; case "int32": case "sint32": case "sfixed32": gen ("m%s=d%s|0", prop, prop); break; case "uint64": isUnsigned = true; // eslint-disable-line no-fallthrough case "int64": case "sint64": case "fixed64": case "sfixed64": gen ("if(util.Long)") ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned) ("else if(typeof d%s===\"string\")", prop) ("m%s=parseInt(d%s,10)", prop, prop) ("else if(typeof d%s===\"number\")", prop) ("m%s=d%s", prop, prop) ("else if(typeof d%s===\"object\")", prop) ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); break; case "bytes": gen ("if(typeof d%s===\"string\")", prop) ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop) ("else if(d%s.length)", prop) ("m%s=d%s", prop, prop); break; case "string": gen ("m%s=String(d%s)", prop, prop); break; case "bool": gen ("m%s=Boolean(d%s)", prop, prop); break; /* default: gen ("m%s=d%s", prop, prop); break; */ } } return gen; /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ } /** * Generates a plain object to runtime message converter specific to the specified message type. * @param {Type} mtype Message type * @returns {Codegen} Codegen instance */ converter.fromObject = function fromObject(mtype) { /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ var fields = mtype.fieldsArray; var gen = util.codegen("d") ("if(d instanceof this.ctor)") ("return d"); if (!fields.length) return gen ("return new this.ctor"); gen ("var m=new this.ctor"); for (var i = 0; i < fields.length; ++i) { var field = fields[i].resolve(), prop = util.safeProp(field.name); // Map fields if (field.map) { gen ("if(d%s){", prop) ("if(typeof d%s!==\"object\")", prop) ("throw TypeError(%j)", field.fullName + ": object expected") ("m%s={}", prop) ("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop); break; case "bytes": gen ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); break; default: gen ("d%s=m%s", prop, prop); break; } } return gen; /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ } /** * Generates a runtime message to plain object converter specific to the specified message type. * @param {Type} mtype Message type * @returns {Codegen} Codegen instance */ converter.toObject = function toObject(mtype) { /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ var fields = mtype.fieldsArray; if (!fields.length) return util.codegen()("return {}"); var gen = util.codegen("m", "o") ("if(!o)") ("o={}") ("var d={}"); var repeatedFields = [], mapFields = [], otherFields = [], i = 0; for (; i < fields.length; ++i) if (fields[i].resolve().repeated) repeatedFields.push(fields[i]); else if (fields[i].map) mapFields.push(fields[i]); else otherFields.push(fields[i]); if (repeatedFields.length) { gen ("if(o.arrays||o.defaults){"); for (i = 0; i < repeatedFields.length; ++i) gen ("d%s=[]", util.safeProp(repeatedFields[i].name)); gen ("}"); } if (mapFields.length) { gen ("if(o.objects||o.defaults){"); for (i = 0; i < mapFields.length; ++i) gen ("d%s={}", util.safeProp(mapFields[i].name)); gen ("}"); } if (otherFields.length) { gen ("if(o.defaults){"); for (i = 0, field; i < otherFields.length; ++i) { var field = otherFields[i], prop = util.safeProp(field.name); if (field.resolvedType instanceof Enum) gen ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); else if (field.long) gen ("if(util.Long){") ("var n=new util.Long(%d,%d,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop) ("}else") ("d%s=o.longs===String?%j:%d", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); else if (field.bytes) gen ("d%s=o.bytes===String?%j:%s", prop, String.fromCharCode.apply(String, field.typeDefault), "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]"); else gen ("d%s=%j", prop, field.typeDefault); // also messages (=null) } gen ("}"); } for (i = 0, field; i < fields.length; ++i) { var field = fields[i], prop = util.safeProp(field.name); gen ("if(m%s!==undefined&&m%s!==null&&m.hasOwnProperty(%j)){", prop, prop, field.name); if (field.map) { gen ("d%s={}", prop) ("for(var ks2=Object.keys(m%s),j=0;j>>3){"); var i = 0; for (; i < /* initializes */ mtype.fieldsArray.length; ++i) { var field = mtype._fieldsArray[i].resolve(), type = field.resolvedType instanceof Enum ? "uint32" : field.type, ref = "m" + util.safeProp(field.name); gen ("case %d:", field.id); // Map fields if (field.map) { gen ("r.skip().pos++") // assumes id 1 + key wireType ("if(%s===util.emptyObject)", ref) ("%s={}", ref) ("var k=r.%s()", field.keyType) ("r.pos++"); // assumes id 2 + value wireType if (types.basic[type] === undefined) gen ("%s[typeof k===\"object\"?util.longToHash(k):k]=types[%d].decode(r,r.uint32())", ref, i); // can't be groups else gen ("%s[typeof k===\"object\"?util.longToHash(k):k]=r.%s()", ref, type); // Repeated fields } else if (field.repeated) { gen ("if(!(%s&&%s.length))", ref, ref) ("%s=[]", ref); // Packable (always check for forward and backward compatiblity) if ((decoder.compat || field.packed) && types.packed[type] !== undefined) gen ("if((t&7)===2){") ("var c2=r.uint32()+r.pos") ("while(r.pos>> 0, (field.id << 3 | 4) >>> 0) : gen("types[%d].encode(%s,w.uint32(%d).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); } /** * Compares reflected fields by id. * @param {Field} a First field * @param {Field} b Second field * @returns {number} Comparison value * @ignore */ function compareFieldsById(a, b) { return a.id - b.id; } /** * Generates an encoder specific to the specified message type. * @param {Type} mtype Message type * @returns {Codegen} Codegen instance * @property {boolean} compat=true Generates encoders serializing in ascending field order */ function encoder(mtype) { /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ var gen = util.codegen("m", "w") ("if(!w)") ("w=Writer.create()"); var i, ref; // "when a message is serialized its known fields should be written sequentially by field number" var fields = /* initializes */ mtype.fieldsArray; /* istanbul ignore else */ if (encoder.compat) fields = fields.slice().sort(compareFieldsById); for (var i = 0; i < fields.length; ++i) { var field = fields[i].resolve(), index = encoder.compat ? mtype._fieldsArray.indexOf(field) : /* istanbul ignore next */ i; if (field.partOf) // see below for oneofs continue; var type = field.resolvedType instanceof Enum ? "uint32" : field.type, wireType = types.basic[type]; ref = "m" + util.safeProp(field.name); // Map fields if (field.map) { gen ("if(%s&&m.hasOwnProperty(%j)){", ref, field.name) ("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); if (wireType === undefined) gen ("types[%d].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups else gen (".uint32(%d).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); gen ("}") ("}"); // Repeated fields } else if (field.repeated) { // Packed repeated if (field.packed && types.packed[type] !== undefined) { gen ("if(%s&&%s.length&&m.hasOwnProperty(%j)){", ref, ref, field.name) ("w.uint32(%d).fork()", (field.id << 3 | 2) >>> 0) ("for(var i=0;i<%s.length;++i)", ref) ("w.%s(%s[i])", type, ref) ("w.ldelim()") ("}"); // Non-packed } else { gen ("if(%s!==undefined&&m.hasOwnProperty(%j)){", ref, field.name) ("for(var i=0;i<%s.length;++i)", ref); if (wireType === undefined) genTypePartial(gen, field, index, ref + "[i]"); else gen ("w.uint32(%d).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); gen ("}"); } // Non-repeated } else { if (!field.required) { if (field.long) gen ("if(%s!==undefined&&%s!==null&&m.hasOwnProperty(%j))", ref, ref, field.name); else if (field.bytes || field.resolvedType && !(field.resolvedType instanceof Enum)) gen ("if(%s&&m.hasOwnProperty(%j))", ref, field.name); else gen ("if(%s!==undefined&&m.hasOwnProperty(%j))", ref, field.name); } if (wireType === undefined) genTypePartial(gen, field, index, ref); else gen ("w.uint32(%d).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); } } // oneofs for (var i = 0; i < /* initializes */ mtype.oneofsArray.length; ++i) { var oneof = mtype._oneofsArray[i]; gen ("switch(%s){", "m" + util.safeProp(oneof.name)); for (var j = 0; j < /* direct */ oneof.fieldsArray.length; ++j) { var field = oneof.fieldsArray[j], type = field.resolvedType instanceof Enum ? "uint32" : field.type, wireType = types.basic[type]; ref = "m" + util.safeProp(field.name); gen ("case%j:", field.name); if (wireType === undefined) genTypePartial(gen, field, mtype._fieldsArray.indexOf(field), ref); else gen ("w.uint32(%d).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); gen ("break"); } gen ("}"); } return gen ("return w"); /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ } },{"15":15,"35":35,"36":36}],15:[function(require,module,exports){ "use strict"; module.exports = Enum; // extends ReflectionObject var ReflectionObject = require(24); ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; var util = require(36); /** * Constructs a new enum instance. * @classdesc Reflected enum. * @extends ReflectionObject * @constructor * @param {string} name Unique name within its namespace * @param {Object.} [values] Enum values as an object, by name * @param {Object.} [options] Declared options */ function Enum(name, values, options) { ReflectionObject.call(this, name, options); if (values && typeof values !== "object") throw TypeError("values must be an object"); /** * Enum values by id. * @type {Object.} */ this.valuesById = {}; /** * Enum values by name. * @type {Object.} */ this.values = Object.create(this.valuesById); // toJSON, marker /** * Value comment texts, if any. * @type {Object.} */ this.comments = {}; // Note that values inherit valuesById on their prototype which makes them a TypeScript- // compatible enum. This is used by pbts to write actual enum definitions that work for // static and reflection code alike instead of emitting generic object definitions. if (values) for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i]; } /** * Creates an enum from JSON. * @param {string} name Enum name * @param {Object.} json JSON object * @returns {Enum} Created enum * @throws {TypeError} If arguments are invalid */ Enum.fromJSON = function fromJSON(name, json) { return new Enum(name, json.values, json.options); }; /** * @override */ Enum.prototype.toJSON = function toJSON() { return { options : this.options, values : this.values }; }; /** * Adds a value to this enum. * @param {string} name Value name * @param {number} id Value id * @param {?string} comment Comment, if any * @returns {Enum} `this` * @throws {TypeError} If arguments are invalid * @throws {Error} If there is already a value with this name or id */ Enum.prototype.add = function(name, id, comment) { // utilized by the parser but not by .fromJSON if (!util.isString(name)) throw TypeError("name must be a string"); if (!util.isInteger(id)) throw TypeError("id must be an integer"); if (this.values[name] !== undefined) throw Error("duplicate name"); if (this.valuesById[id] !== undefined) { if (!(this.options && this.options.allow_alias)) throw Error("duplicate id"); this.values[name] = id; } else this.valuesById[this.values[name] = id] = name; this.comments[name] = comment || null; return this; }; /** * Removes a value from this enum * @param {string} name Value name * @returns {Enum} `this` * @throws {TypeError} If arguments are invalid * @throws {Error} If `name` is not a name of this enum */ Enum.prototype.remove = function(name) { if (!util.isString(name)) throw TypeError("name must be a string"); var val = this.values[name]; if (val === undefined) throw Error("name does not exist"); delete this.valuesById[val]; delete this.values[name]; delete this.comments[name]; return this; }; },{"24":24,"36":36}],16:[function(require,module,exports){ "use strict"; module.exports = Field; // extends ReflectionObject var ReflectionObject = require(24); ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; var Enum = require(15), types = require(35), util = require(36); var Type; // cyclic var ruleRe = /^required|optional|repeated$/; /** * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. * @classdesc Reflected message field. * @extends ReflectionObject * @constructor * @param {string} name Unique name within its namespace * @param {number} id Unique id within its namespace * @param {string} type Value type * @param {string|Object.} [rule="optional"] Field rule * @param {string|Object.} [extend] Extended type if different from parent * @param {Object.} [options] Declared options */ function Field(name, id, type, rule, extend, options) { if (util.isObject(rule)) { options = rule; rule = extend = undefined; } else if (util.isObject(extend)) { options = extend; extend = undefined; } ReflectionObject.call(this, name, options); if (!util.isInteger(id) || id < 0) throw TypeError("id must be a non-negative integer"); if (!util.isString(type)) throw TypeError("type must be a string"); if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) throw TypeError("rule must be a string rule"); if (extend !== undefined && !util.isString(extend)) throw TypeError("extend must be a string"); /** * Field rule, if any. * @type {string|undefined} */ this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON /** * Field type. * @type {string} */ this.type = type; // toJSON /** * Unique field id. * @type {number} */ this.id = id; // toJSON, marker /** * Extended type if different from parent. * @type {string|undefined} */ this.extend = extend || undefined; // toJSON /** * Whether this field is required. * @type {boolean} */ this.required = rule === "required"; /** * Whether this field is optional. * @type {boolean} */ this.optional = !this.required; /** * Whether this field is repeated. * @type {boolean} */ this.repeated = rule === "repeated"; /** * Whether this field is a map or not. * @type {boolean} */ this.map = false; /** * Message this field belongs to. * @type {?Type} */ this.message = null; /** * OneOf this field belongs to, if any, * @type {?OneOf} */ this.partOf = null; /** * The field type's default value. * @type {*} */ this.typeDefault = null; /** * The field's default value on prototypes. * @type {*} */ this.defaultValue = null; /** * Whether this field's value should be treated as a long. * @type {boolean} */ this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; /** * Whether this field's value is a buffer. * @type {boolean} */ this.bytes = type === "bytes"; /** * Resolved type if not a basic type. * @type {?(Type|Enum)} */ this.resolvedType = null; /** * Sister-field within the extended type if a declaring extension field. * @type {?Field} */ this.extensionField = null; /** * Sister-field within the declaring namespace if an extended field. * @type {?Field} */ this.declaringField = null; /** * Internally remembers whether this field is packed. * @type {?boolean} * @private */ this._packed = null; } /** * Determines whether this field is packed. Only relevant when repeated and working with proto2. * @name Field#packed * @type {boolean} * @readonly */ Object.defineProperty(Field.prototype, "packed", { get: function() { // defaults to packed=true if not explicity set to false if (this._packed === null) this._packed = this.getOption("packed") !== false; return this._packed; } }); /** * @override */ Field.prototype.setOption = function setOption(name, value, ifNotSet) { if (name === "packed") // clear cached before setting this._packed = null; return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); }; /** * Constructs a field from JSON. * @param {string} name Field name * @param {Object.} json JSON object * @returns {Field} Created field * @throws {TypeError} If arguments are invalid */ Field.fromJSON = function fromJSON(name, json) { return new Field(name, json.id, json.type, json.rule, json.extend, json.options); }; /** * @override */ Field.prototype.toJSON = function toJSON() { return { rule : this.rule !== "optional" && this.rule || undefined, type : this.type, id : this.id, extend : this.extend, options : this.options }; }; /** * Resolves this field's type references. * @returns {Field} `this` * @throws {Error} If any reference cannot be resolved */ Field.prototype.resolve = function resolve() { if (this.resolved) return this; if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it /* istanbul ignore if */ if (!Type) Type = require(34); var scope = this.declaringField ? this.declaringField.parent : this.parent; if (this.resolvedType = scope.lookup(this.type, Type)) this.typeDefault = null; else if (this.resolvedType = scope.lookup(this.type, Enum)) this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined else throw Error("unresolvable field type: " + this.type + " in " + scope); } // use explicitly set default value if present if (this.options && this.options["default"] !== undefined) { this.typeDefault = this.options["default"]; if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") this.typeDefault = this.resolvedType.values[this.typeDefault]; } // remove unnecessary packed option (parser adds this) if not referencing an enum if (this.options && this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) delete this.options.packed; // convert to internal data type if necesssary if (this.long) { this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); /* istanbul ignore else */ if (Object.freeze) Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) } else if (this.bytes && typeof this.typeDefault === "string") { var buf; if (util.base64.test(this.typeDefault)) util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); else util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); this.typeDefault = buf; } // take special care of maps and repeated fields if (this.map) this.defaultValue = util.emptyObject; else if (this.repeated) this.defaultValue = util.emptyArray; else this.defaultValue = this.typeDefault; return ReflectionObject.prototype.resolve.call(this); }; },{"15":15,"24":24,"34":34,"35":35,"36":36}],17:[function(require,module,exports){ "use strict"; var protobuf = module.exports = require(18); protobuf.build = "light"; /** * A node-style callback as used by {@link load} and {@link Root#load}. * @typedef LoadCallback * @type {function} * @param {?Error} error Error, if any, otherwise `null` * @param {Root} [root] Root, if there hasn't been an error * @returns {undefined} */ /** * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. * @param {string|string[]} filename One or multiple files to load * @param {Root} root Root namespace, defaults to create a new one if omitted. * @param {LoadCallback} callback Callback function * @returns {undefined} * @see {@link Root#load} */ function load(filename, root, callback) { if (typeof root === "function") { callback = root; root = new protobuf.Root(); } else if (!root) root = new protobuf.Root(); return root.load(filename, callback); } /** * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. * @name load * @function * @param {string|string[]} filename One or multiple files to load * @param {LoadCallback} callback Callback function * @returns {undefined} * @see {@link Root#load} * @variation 2 */ // function load(filename:string, callback:LoadCallback):undefined /** * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. * @name load * @function * @param {string|string[]} filename One or multiple files to load * @param {Root} [root] Root namespace, defaults to create a new one if omitted. * @returns {Promise} Promise * @see {@link Root#load} * @variation 3 */ // function load(filename:string, [root:Root]):Promise protobuf.load = load; /** * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). * @param {string|string[]} filename One or multiple files to load * @param {Root} [root] Root namespace, defaults to create a new one if omitted. * @returns {Root} Root namespace * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid * @see {@link Root#loadSync} */ function loadSync(filename, root) { if (!root) root = new protobuf.Root(); return root.loadSync(filename); } protobuf.loadSync = loadSync; // Serialization protobuf.encoder = require(14); protobuf.decoder = require(13); protobuf.verifier = require(39); protobuf.converter = require(12); // Reflection protobuf.ReflectionObject = require(24); protobuf.Namespace = require(23); protobuf.Root = require(29); protobuf.Enum = require(15); protobuf.Type = require(34); protobuf.Field = require(16); protobuf.OneOf = require(25); protobuf.MapField = require(20); protobuf.Service = require(32); protobuf.Method = require(22); // Runtime protobuf.Class = require(10); protobuf.Message = require(21); // Utility protobuf.types = require(35); protobuf.util = require(36); // Configure reflection protobuf.ReflectionObject._configure(protobuf.Root); protobuf.Namespace._configure(protobuf.Type, protobuf.Service); protobuf.Root._configure(protobuf.Type); },{"10":10,"12":12,"13":13,"14":14,"15":15,"16":16,"18":18,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"29":29,"32":32,"34":34,"35":35,"36":36,"39":39}],18:[function(require,module,exports){ "use strict"; var protobuf = exports; /** * Build type, one of `"full"`, `"light"` or `"minimal"`. * @name build * @type {string} * @const */ protobuf.build = "minimal"; /** * Named roots. * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). * Can also be used manually to make roots available accross modules. * @name roots * @type {Object.} * @example * // pbjs -r myroot -o compiled.js ... * * // in another module: * require("./compiled.js"); * * // in any subsequent module: * var root = protobuf.roots["myroot"]; */ protobuf.roots = {}; // Serialization protobuf.Writer = require(40); protobuf.BufferWriter = require(41); protobuf.Reader = require(27); protobuf.BufferReader = require(28); // Utility protobuf.util = require(38); protobuf.rpc = require(30); protobuf.configure = configure; /* istanbul ignore next */ /** * Reconfigures the library according to the environment. * @returns {undefined} */ function configure() { protobuf.Reader._configure(protobuf.BufferReader); protobuf.util._configure(); } // Configure serialization protobuf.Writer._configure(protobuf.BufferWriter); configure(); },{"27":27,"28":28,"30":30,"38":38,"40":40,"41":41}],19:[function(require,module,exports){ "use strict"; var protobuf = module.exports = require(17); protobuf.build = "full"; // Parser protobuf.tokenize = require(33); protobuf.parse = require(26); protobuf.common = require(11); // Configure parser protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); },{"11":11,"17":17,"26":26,"33":33}],20:[function(require,module,exports){ "use strict"; module.exports = MapField; // extends Field var Field = require(16); ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; var types = require(35), util = require(36); /** * Constructs a new map field instance. * @classdesc Reflected map field. * @extends Field * @constructor * @param {string} name Unique name within its namespace * @param {number} id Unique id within its namespace * @param {string} keyType Key type * @param {string} type Value type * @param {Object.} [options] Declared options */ function MapField(name, id, keyType, type, options) { Field.call(this, name, id, type, options); /* istanbul ignore next */ if (!util.isString(keyType)) throw TypeError("keyType must be a string"); /** * Key type. * @type {string} */ this.keyType = keyType; // toJSON, marker /** * Resolved key type if not a basic type. * @type {?ReflectionObject} */ this.resolvedKeyType = null; // Overrides Field#map this.map = true; } /** * Constructs a map field from JSON. * @param {string} name Field name * @param {Object.} json JSON object * @returns {MapField} Created map field * @throws {TypeError} If arguments are invalid */ MapField.fromJSON = function fromJSON(name, json) { return new MapField(name, json.id, json.keyType, json.type, json.options); }; /** * @override */ MapField.prototype.toJSON = function toJSON() { return { keyType : this.keyType, type : this.type, id : this.id, extend : this.extend, options : this.options }; }; /** * @override */ MapField.prototype.resolve = function resolve() { if (this.resolved) return this; // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" if (types.mapKey[this.keyType] === undefined) throw Error("invalid key type: " + this.keyType); return Field.prototype.resolve.call(this); }; },{"16":16,"35":35,"36":36}],21:[function(require,module,exports){ "use strict"; module.exports = Message; var util = require(36); /** * Constructs a new message instance. * * This function should also be called from your custom constructors, i.e. `Message.call(this, properties)`. * @classdesc Abstract runtime message. * @constructor * @param {Object.} [properties] Properties to set * @see {@link Class.create} */ function Message(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) this[keys[i]] = properties[keys[i]]; } /** * Reference to the reflected type. * @name Message.$type * @type {Type} * @readonly */ /** * Reference to the reflected type. * @name Message#$type * @type {Type} * @readonly */ /** * Encodes a message of this type. * @param {Message|Object} message Message to encode * @param {Writer} [writer] Writer to use * @returns {Writer} Writer */ Message.encode = function encode(message, writer) { return this.$type.encode(message, writer); }; /** * Encodes a message of this type preceeded by its length as a varint. * @param {Message|Object} message Message to encode * @param {Writer} [writer] Writer to use * @returns {Writer} Writer */ Message.encodeDelimited = function encodeDelimited(message, writer) { return this.$type.encodeDelimited(message, writer); }; /** * Decodes a message of this type. * @name Message.decode * @function * @param {Reader|Uint8Array} reader Reader or buffer to decode * @returns {Message} Decoded message */ Message.decode = function decode(reader) { return this.$type.decode(reader); }; /** * Decodes a message of this type preceeded by its length as a varint. * @name Message.decodeDelimited * @function * @param {Reader|Uint8Array} reader Reader or buffer to decode * @returns {Message} Decoded message */ Message.decodeDelimited = function decodeDelimited(reader) { return this.$type.decodeDelimited(reader); }; /** * Verifies a message of this type. * @name Message.verify * @function * @param {Message|Object} message Message or plain object to verify * @returns {?string} `null` if valid, otherwise the reason why it is not */ Message.verify = function verify(message) { return this.$type.verify(message); }; /** * Creates a new message of this type from a plain object. Also converts values to their respective internal types. * @param {Object.} object Plain object * @returns {Message} Message instance */ Message.fromObject = function fromObject(object) { return this.$type.fromObject(object); }; /** * Creates a new message of this type from a plain object. Also converts values to their respective internal types. * This is an alias of {@link Message.fromObject}. * @function * @param {Object.} object Plain object * @returns {Message} Message instance */ Message.from = Message.fromObject; /** * Creates a plain object from a message of this type. Also converts values to other types if specified. * @param {Message} message Message instance * @param {ConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ Message.toObject = function toObject(message, options) { return this.$type.toObject(message, options); }; /** * Creates a plain object from this message. Also converts values to other types if specified. * @param {ConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ Message.prototype.toObject = function toObject(options) { return this.$type.toObject(this, options); }; /** * Converts this message to JSON. * @returns {Object.} JSON object */ Message.prototype.toJSON = function toJSON() { return this.$type.toObject(this, util.toJSONOptions); }; },{"36":36}],22:[function(require,module,exports){ "use strict"; module.exports = Method; // extends ReflectionObject var ReflectionObject = require(24); ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; var util = require(36); /** * Constructs a new service method instance. * @classdesc Reflected service method. * @extends ReflectionObject * @constructor * @param {string} name Method name * @param {string|undefined} type Method type, usually `"rpc"` * @param {string} requestType Request message type * @param {string} responseType Response message type * @param {boolean|Object.} [requestStream] Whether the request is streamed * @param {boolean|Object.} [responseStream] Whether the response is streamed * @param {Object.} [options] Declared options */ function Method(name, type, requestType, responseType, requestStream, responseStream, options) { /* istanbul ignore next */ if (util.isObject(requestStream)) { options = requestStream; requestStream = responseStream = undefined; /* istanbul ignore next */ } else if (util.isObject(responseStream)) { options = responseStream; responseStream = undefined; } /* istanbul ignore next */ if (!(type === undefined || util.isString(type))) throw TypeError("type must be a string"); /* istanbul ignore next */ if (!util.isString(requestType)) throw TypeError("requestType must be a string"); /* istanbul ignore next */ if (!util.isString(responseType)) throw TypeError("responseType must be a string"); ReflectionObject.call(this, name, options); /** * Method type. * @type {string} */ this.type = type || "rpc"; // toJSON /** * Request type. * @type {string} */ this.requestType = requestType; // toJSON, marker /** * Whether requests are streamed or not. * @type {boolean|undefined} */ this.requestStream = requestStream ? true : undefined; // toJSON /** * Response type. * @type {string} */ this.responseType = responseType; // toJSON /** * Whether responses are streamed or not. * @type {boolean|undefined} */ this.responseStream = responseStream ? true : undefined; // toJSON /** * Resolved request type. * @type {?Type} */ this.resolvedRequestType = null; /** * Resolved response type. * @type {?Type} */ this.resolvedResponseType = null; } /** * Constructs a service method from JSON. * @param {string} name Method name * @param {Object.} json JSON object * @returns {Method} Created method * @throws {TypeError} If arguments are invalid */ Method.fromJSON = function fromJSON(name, json) { return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options); }; /** * @override */ Method.prototype.toJSON = function toJSON() { return { type : this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, requestType : this.requestType, requestStream : this.requestStream, responseType : this.responseType, responseStream : this.responseStream, options : this.options }; }; /** * @override */ Method.prototype.resolve = function resolve() { /* istanbul ignore if */ if (this.resolved) return this; this.resolvedRequestType = this.parent.lookupType(this.requestType); this.resolvedResponseType = this.parent.lookupType(this.responseType); return ReflectionObject.prototype.resolve.call(this); }; },{"24":24,"36":36}],23:[function(require,module,exports){ "use strict"; module.exports = Namespace; // extends ReflectionObject var ReflectionObject = require(24); ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; var Enum = require(15), Field = require(16), util = require(36); var Type, // cyclic Service; // " /** * Constructs a new namespace instance. * @name Namespace * @classdesc Reflected namespace. * @extends NamespaceBase * @constructor * @param {string} name Namespace name * @param {Object.} [options] Declared options */ /** * Constructs a namespace from JSON. * @memberof Namespace * @function * @param {string} name Namespace name * @param {Object.} json JSON object * @returns {Namespace} Created namespace * @throws {TypeError} If arguments are invalid */ Namespace.fromJSON = function fromJSON(name, json) { return new Namespace(name, json.options).addJSON(json.nested); }; /** * Converts an array of reflection objects to JSON. * @memberof Namespace * @param {ReflectionObject[]} array Object array * @returns {Object.|undefined} JSON object or `undefined` when array is empty */ function arrayToJSON(array) { if (!(array && array.length)) return undefined; var obj = {}; for (var i = 0; i < array.length; ++i) obj[array[i].name] = array[i].toJSON(); return obj; } Namespace.arrayToJSON = arrayToJSON; /** * Not an actual constructor. Use {@link Namespace} instead. * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. * @exports NamespaceBase * @extends ReflectionObject * @abstract * @constructor * @param {string} name Namespace name * @param {Object.} [options] Declared options * @see {@link Namespace} */ function Namespace(name, options) { ReflectionObject.call(this, name, options); /** * Nested objects by name. * @type {Object.|undefined} */ this.nested = undefined; // toJSON /** * Cached nested objects as an array. * @type {?ReflectionObject[]} * @private */ this._nestedArray = null; } function clearCache(namespace) { namespace._nestedArray = null; return namespace; } /** * Nested objects of this namespace as an array for iteration. * @name NamespaceBase#nestedArray * @type {ReflectionObject[]} * @readonly */ Object.defineProperty(Namespace.prototype, "nestedArray", { get: function() { return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); } }); /** * @override */ Namespace.prototype.toJSON = function toJSON() { return { options : this.options, nested : arrayToJSON(this.nestedArray) }; }; /** * Adds nested elements to this namespace from JSON. * @param {Object.} nestedJson Nested JSON * @returns {Namespace} `this` */ Namespace.prototype.addJSON = function addJSON(nestedJson) { var ns = this; /* istanbul ignore else */ if (nestedJson) { for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { nested = nestedJson[names[i]]; ns.add( // most to least likely ( nested.fields !== undefined ? Type.fromJSON : nested.values !== undefined ? Enum.fromJSON : nested.methods !== undefined ? Service.fromJSON : nested.id !== undefined ? Field.fromJSON : Namespace.fromJSON )(names[i], nested) ); } } return this; }; /** * Gets the nested object of the specified name. * @param {string} name Nested object name * @returns {?ReflectionObject} The reflection object or `null` if it doesn't exist */ Namespace.prototype.get = function get(name) { return this.nested && this.nested[name] || null; }; /** * Gets the values of the nested {@link Enum|enum} of the specified name. * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. * @param {string} name Nested enum name * @returns {Object.} Enum values * @throws {Error} If there is no such enum */ Namespace.prototype.getEnum = function getEnum(name) { if (this.nested && this.nested[name] instanceof Enum) return this.nested[name].values; throw Error("no such enum"); }; /** * Adds a nested object to this namespace. * @param {ReflectionObject} object Nested object to add * @returns {Namespace} `this` * @throws {TypeError} If arguments are invalid * @throws {Error} If there is already a nested object with this name */ Namespace.prototype.add = function add(object) { if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof Enum || object instanceof Service || object instanceof Namespace)) throw TypeError("object must be a valid nested object"); if (!this.nested) this.nested = {}; else { var prev = this.get(object.name); if (prev) { if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { // replace plain namespace but keep existing nested elements and options var nested = prev.nestedArray; for (var i = 0; i < nested.length; ++i) object.add(nested[i]); this.remove(prev); if (!this.nested) this.nested = {}; object.setOptions(prev.options, true); } else throw Error("duplicate name '" + object.name + "' in " + this); } } this.nested[object.name] = object; object.onAdd(this); return clearCache(this); }; /** * Removes a nested object from this namespace. * @param {ReflectionObject} object Nested object to remove * @returns {Namespace} `this` * @throws {TypeError} If arguments are invalid * @throws {Error} If `object` is not a member of this namespace */ Namespace.prototype.remove = function remove(object) { if (!(object instanceof ReflectionObject)) throw TypeError("object must be a ReflectionObject"); if (object.parent !== this) throw Error(object + " is not a member of " + this); delete this.nested[object.name]; if (!Object.keys(this.nested).length) this.nested = undefined; object.onRemove(this); return clearCache(this); }; /** * Defines additial namespaces within this one if not yet existing. * @param {string|string[]} path Path to create * @param {*} [json] Nested types to create from JSON * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty */ Namespace.prototype.define = function define(path, json) { if (util.isString(path)) path = path.split("."); else if (!Array.isArray(path)) throw TypeError("illegal path"); if (path && path.length && path[0] === "") throw Error("path must be relative"); var ptr = this; while (path.length > 0) { var part = path.shift(); if (ptr.nested && ptr.nested[part]) { ptr = ptr.nested[part]; if (!(ptr instanceof Namespace)) throw Error("path conflicts with non-namespace objects"); } else ptr.add(ptr = new Namespace(part)); } if (json) ptr.addJSON(json); return ptr; }; /** * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. * @returns {Namespace} `this` */ Namespace.prototype.resolveAll = function resolveAll() { var nested = this.nestedArray, i = 0; while (i < nested.length) if (nested[i] instanceof Namespace) nested[i++].resolveAll(); else nested[i++].resolve(); return this.resolve(); }; /** * Looks up the reflection object at the specified path, relative to this namespace. * @param {string|string[]} path Path to look up * @param {function(new: ReflectionObject)} filterType Filter type, one of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked * @returns {?ReflectionObject} Looked up object or `null` if none could be found */ Namespace.prototype.lookup = function lookup(path, filterType, parentAlreadyChecked) { /* istanbul ignore next */ if (typeof filterType === "boolean") { parentAlreadyChecked = filterType; filterType = undefined; } if (util.isString(path) && path.length) { if (path === ".") return this.root; path = path.split("."); } else if (!path.length) return this; // Start at root if path is absolute if (path[0] === "") return this.root.lookup(path.slice(1), filterType); // Test if the first part matches any nested object, and if so, traverse if path contains more var found = this.get(path[0]); if (found) { if (path.length === 1) { if (!filterType || found instanceof filterType) return found; } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterType, true))) return found; } // If there hasn't been a match, try again at the parent if (this.parent === null || parentAlreadyChecked) return null; return this.parent.lookup(path, filterType); }; /** * Looks up the reflection object at the specified path, relative to this namespace. * @name NamespaceBase#lookup * @function * @param {string|string[]} path Path to look up * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked * @returns {?ReflectionObject} Looked up object or `null` if none could be found * @variation 2 */ // lookup(path: string, [parentAlreadyChecked: boolean]) /** * Looks up the {@link Type|type} at the specified path, relative to this namespace. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. * @param {string|string[]} path Path to look up * @returns {Type} Looked up type * @throws {Error} If `path` does not point to a type */ Namespace.prototype.lookupType = function lookupType(path) { var found = this.lookup(path, Type); if (!found) throw Error("no such type"); return found; }; /** * Looks up the {@link Service|service} at the specified path, relative to this namespace. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. * @param {string|string[]} path Path to look up * @returns {Service} Looked up service * @throws {Error} If `path` does not point to a service */ Namespace.prototype.lookupService = function lookupService(path) { var found = this.lookup(path, Service); if (!found) throw Error("no such service"); return found; }; /** * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it returns the enum's values directly and throws instead of returning `null`. * @param {string|string[]} path Path to look up * @returns {Object.} Enum values * @throws {Error} If `path` does not point to an enum */ Namespace.prototype.lookupEnum = function lookupEnum(path) { var found = this.lookup(path, Enum); if (!found) throw Error("no such enum"); return found.values; }; Namespace._configure = function(Type_, Service_) { Type = Type_; Service = Service_; }; },{"15":15,"16":16,"24":24,"36":36}],24:[function(require,module,exports){ "use strict"; module.exports = ReflectionObject; ReflectionObject.className = "ReflectionObject"; var util = require(36); var Root; // cyclic /** * Constructs a new reflection object instance. * @classdesc Base class of all reflection objects. * @constructor * @param {string} name Object name * @param {Object.} [options] Declared options * @abstract */ function ReflectionObject(name, options) { if (!util.isString(name)) throw TypeError("name must be a string"); if (options && !util.isObject(options)) throw TypeError("options must be an object"); /** * Options. * @type {Object.|undefined} */ this.options = options; // toJSON /** * Unique name within its namespace. * @type {string} */ this.name = name; /** * Parent namespace. * @type {?Namespace} */ this.parent = null; /** * Whether already resolved or not. * @type {boolean} */ this.resolved = false; /** * Comment text, if any. * @type {?string} */ this.comment = null; /** * Defining file name. * @type {?string} */ this.filename = null; } Object.defineProperties(ReflectionObject.prototype, { /** * Reference to the root namespace. * @name ReflectionObject#root * @type {Root} * @readonly */ root: { get: function() { var ptr = this; while (ptr.parent !== null) ptr = ptr.parent; return ptr; } }, /** * Full name including leading dot. * @name ReflectionObject#fullName * @type {string} * @readonly */ fullName: { get: function() { var path = [ this.name ], ptr = this.parent; while (ptr) { path.unshift(ptr.name); ptr = ptr.parent; } return path.join("."); } } }); /** * Converts this reflection object to its JSON representation. * @returns {Object.} JSON object * @abstract */ ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { throw Error(); // not implemented, shouldn't happen }; /** * Called when this object is added to a parent. * @param {ReflectionObject} parent Parent added to * @returns {undefined} */ ReflectionObject.prototype.onAdd = function onAdd(parent) { if (this.parent && this.parent !== parent) this.parent.remove(this); this.parent = parent; this.resolved = false; var root = parent.root; if (root instanceof Root) root._handleAdd(this); }; /** * Called when this object is removed from a parent. * @param {ReflectionObject} parent Parent removed from * @returns {undefined} */ ReflectionObject.prototype.onRemove = function onRemove(parent) { var root = parent.root; if (root instanceof Root) root._handleRemove(this); this.parent = null; this.resolved = false; }; /** * Resolves this objects type references. * @returns {ReflectionObject} `this` */ ReflectionObject.prototype.resolve = function resolve() { if (this.resolved) return this; if (this.root instanceof Root) this.resolved = true; // only if part of a root return this; }; /** * Gets an option value. * @param {string} name Option name * @returns {*} Option value or `undefined` if not set */ ReflectionObject.prototype.getOption = function getOption(name) { if (this.options) return this.options[name]; return undefined; }; /** * Sets an option. * @param {string} name Option name * @param {*} value Option value * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set * @returns {ReflectionObject} `this` */ ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { if (!ifNotSet || !this.options || this.options[name] === undefined) (this.options || (this.options = {}))[name] = value; return this; }; /** * Sets multiple options. * @param {Object.} options Options to set * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set * @returns {ReflectionObject} `this` */ ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { if (options) for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) this.setOption(keys[i], options[keys[i]], ifNotSet); return this; }; /** * Converts this instance to its string representation. * @returns {string} Class name[, space, full name] */ ReflectionObject.prototype.toString = function toString() { var className = this.constructor.className, fullName = this.fullName; if (fullName.length) return className + " " + fullName; return className; }; ReflectionObject._configure = function(Root_) { Root = Root_; }; },{"36":36}],25:[function(require,module,exports){ "use strict"; module.exports = OneOf; // extends ReflectionObject var ReflectionObject = require(24); ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; var Field = require(16); /** * Constructs a new oneof instance. * @classdesc Reflected oneof. * @extends ReflectionObject * @constructor * @param {string} name Oneof name * @param {string[]|Object} [fieldNames] Field names * @param {Object.} [options] Declared options */ function OneOf(name, fieldNames, options) { if (!Array.isArray(fieldNames)) { options = fieldNames; fieldNames = undefined; } ReflectionObject.call(this, name, options); /* istanbul ignore next */ if (!(fieldNames === undefined || Array.isArray(fieldNames))) throw TypeError("fieldNames must be an Array"); /** * Field names that belong to this oneof. * @type {string[]} */ this.oneof = fieldNames || []; // toJSON, marker /** * Fields that belong to this oneof as an array for iteration. * @type {Field[]} * @readonly */ this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent } /** * Constructs a oneof from JSON. * @param {string} name Oneof name * @param {Object.} json JSON object * @returns {MapField} Created oneof * @throws {TypeError} If arguments are invalid */ OneOf.fromJSON = function fromJSON(name, json) { return new OneOf(name, json.oneof, json.options); }; /** * @override */ OneOf.prototype.toJSON = function toJSON() { return { oneof : this.oneof, options : this.options }; }; /** * Adds the fields of the specified oneof to the parent if not already done so. * @param {OneOf} oneof The oneof * @returns {undefined} * @inner * @ignore */ function addFieldsToParent(oneof) { if (oneof.parent) for (var i = 0; i < oneof.fieldsArray.length; ++i) if (!oneof.fieldsArray[i].parent) oneof.parent.add(oneof.fieldsArray[i]); } /** * Adds a field to this oneof and removes it from its current parent, if any. * @param {Field} field Field to add * @returns {OneOf} `this` */ OneOf.prototype.add = function add(field) { /* istanbul ignore next */ if (!(field instanceof Field)) throw TypeError("field must be a Field"); if (field.parent && field.parent !== this.parent) field.parent.remove(field); this.oneof.push(field.name); this.fieldsArray.push(field); field.partOf = this; // field.parent remains null addFieldsToParent(this); return this; }; /** * Removes a field from this oneof and puts it back to the oneof's parent. * @param {Field} field Field to remove * @returns {OneOf} `this` */ OneOf.prototype.remove = function remove(field) { /* istanbul ignore next */ if (!(field instanceof Field)) throw TypeError("field must be a Field"); var index = this.fieldsArray.indexOf(field); /* istanbul ignore next */ if (index < 0) throw Error(field + " is not a member of " + this); this.fieldsArray.splice(index, 1); index = this.oneof.indexOf(field.name); /* istanbul ignore else */ if (index > -1) // theoretical this.oneof.splice(index, 1); field.partOf = null; return this; }; /** * @override */ OneOf.prototype.onAdd = function onAdd(parent) { ReflectionObject.prototype.onAdd.call(this, parent); var self = this; // Collect present fields for (var i = 0; i < this.oneof.length; ++i) { var field = parent.get(this.oneof[i]); if (field && !field.partOf) { field.partOf = self; self.fieldsArray.push(field); } } // Add not yet present fields addFieldsToParent(this); }; /** * @override */ OneOf.prototype.onRemove = function onRemove(parent) { for (var i = 0, field; i < this.fieldsArray.length; ++i) if ((field = this.fieldsArray[i]).parent) field.parent.remove(field); ReflectionObject.prototype.onRemove.call(this, parent); }; },{"16":16,"24":24}],26:[function(require,module,exports){ "use strict"; module.exports = parse; parse.filename = null; parse.defaults = { keepCase: false }; var tokenize = require(33), Root = require(29), Type = require(34), Field = require(16), MapField = require(20), OneOf = require(25), Enum = require(15), Service = require(32), Method = require(22), types = require(35), util = require(36); var base10Re = /^[1-9][0-9]*$/, base10NegRe = /^-?[1-9][0-9]*$/, base16Re = /^0[x][0-9a-f]+$/, base16NegRe = /^-?0[x][0-9a-f]+$/, base8Re = /^0[0-7]+$/, base8NegRe = /^-?0[0-7]+$/, numberRe = /^(?!e)[0-9]*(?:\.[0-9]*)?(?:[e][+-]?[0-9]+)?$/, nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/, typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/, fqTypeRefRe = /^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/; function lower(token) { return token === null ? null : token.toLowerCase(); } var camelCaseRe = /_([a-z])(?=[a-z]|$)/g; function camelCase(str) { return str.substring(0,1) + str.substring(1) .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); }); } /** * Result object returned from {@link parse}. * @typedef ParserResult * @type {Object.} * @property {string|undefined} package Package name, if declared * @property {string[]|undefined} imports Imports, if any * @property {string[]|undefined} weakImports Weak imports, if any * @property {string|undefined} syntax Syntax, if specified (either `"proto2"` or `"proto3"`) * @property {Root} root Populated root instance */ /** * Options modifying the behavior of {@link parse}. * @typedef ParseOptions * @type {Object.} * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case */ /** * Parses the given .proto source and returns an object with the parsed contents. * @function * @param {string} source Source contents * @param {Root} root Root to populate * @param {ParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. * @returns {ParserResult} Parser result * @property {string} filename=null Currently processing file name for error reporting, if known * @property {ParseOptions} defaults Default {@link ParseOptions} */ function parse(source, root, options) { /* eslint-disable callback-return */ if (!(root instanceof Root)) { options = root; root = new Root(); } if (!options) options = parse.defaults; var tn = tokenize(source), next = tn.next, push = tn.push, peek = tn.peek, skip = tn.skip, cmnt = tn.cmnt; var head = true, pkg, imports, weakImports, syntax, isProto3 = false; var ptr = root; var applyCase = options.keepCase ? function(name) { return name; } : camelCase; /* istanbul ignore next */ function illegal(token, name, insideTryCatch) { var filename = parse.filename; if (!insideTryCatch) parse.filename = null; return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line() + ")"); } function readString() { var values = [], token; /* istanbul ignore next */ do { if ((token = next()) !== "\"" && token !== "'") throw illegal(token); values.push(next()); skip(token); token = peek(); } while (token === "\"" || token === "'"); return values.join(""); } function readValue(acceptTypeRef) { var token = next(); switch (lower(token)) { case "'": case "\"": push(token); return readString(); case "true": return true; case "false": return false; } try { return parseNumber(token, /* insideTryCatch */ true); } catch (e) { /* istanbul ignore else */ if (acceptTypeRef && typeRefRe.test(token)) return token; /* istanbul ignore next */ throw illegal(token, "value"); } } function readRanges(target, acceptStrings) { var token, start; do { if (acceptStrings && ((token = peek()) === "\"" || token === "'")) target.push(readString()); else target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]); } while (skip(",", true)); skip(";"); } function parseNumber(token, insideTryCatch) { var sign = 1; if (token.charAt(0) === "-") { sign = -1; token = token.substring(1); } var tokenLower = lower(token); switch (tokenLower) { case "inf": return sign * Infinity; case "nan": return NaN; case "0": return 0; } if (base10Re.test(token)) return sign * parseInt(token, 10); if (base16Re.test(tokenLower)) return sign * parseInt(token, 16); if (base8Re.test(token)) return sign * parseInt(token, 8); if (numberRe.test(tokenLower)) return sign * parseFloat(token); /* istanbul ignore next */ throw illegal(token, "number", insideTryCatch); } function parseId(token, acceptNegative) { var tokenLower = lower(token); switch (tokenLower) { case "max": return 536870911; case "0": return 0; } /* istanbul ignore next */ if (token.charAt(0) === "-" && !acceptNegative) throw illegal(token, "id"); if (base10NegRe.test(token)) return parseInt(token, 10); if (base16NegRe.test(tokenLower)) return parseInt(token, 16); /* istanbul ignore else */ if (base8NegRe.test(token)) return parseInt(token, 8); /* istanbul ignore next */ throw illegal(token, "id"); } function parsePackage() { /* istanbul ignore next */ if (pkg !== undefined) throw illegal("package"); pkg = next(); /* istanbul ignore next */ if (!typeRefRe.test(pkg)) throw illegal(pkg, "name"); ptr = ptr.define(pkg); skip(";"); } function parseImport() { var token = peek(); var whichImports; switch (token) { case "weak": whichImports = weakImports || (weakImports = []); next(); break; case "public": next(); // eslint-disable-line no-fallthrough default: whichImports = imports || (imports = []); break; } token = readString(); skip(";"); whichImports.push(token); } function parseSyntax() { skip("="); syntax = lower(readString()); isProto3 = syntax === "proto3"; /* istanbul ignore next */ if (!isProto3 && syntax !== "proto2") throw illegal(syntax, "syntax"); skip(";"); } function parseCommon(parent, token) { switch (token) { case "option": parseOption(parent, token); skip(";"); return true; case "message": parseType(parent, token); return true; case "enum": parseEnum(parent, token); return true; case "service": parseService(parent, token); return true; case "extend": parseExtension(parent, token); return true; } return false; } function parseType(parent, token) { var name = next(); /* istanbul ignore next */ if (!nameRe.test(name)) throw illegal(name, "type name"); var type = new Type(name); type.comment = cmnt(); type.filename = parse.filename; if (skip("{", true)) { while ((token = next()) !== "}") { var tokenLower = lower(token); if (parseCommon(type, token)) continue; switch (tokenLower) { case "map": parseMapField(type, tokenLower); break; case "required": case "optional": case "repeated": parseField(type, tokenLower); break; case "oneof": parseOneOf(type, tokenLower); break; case "extensions": readRanges(type.extensions || (type.extensions = [])); break; case "reserved": readRanges(type.reserved || (type.reserved = []), true); break; default: /* istanbul ignore next */ if (!isProto3 || !typeRefRe.test(token)) throw illegal(token); push(token); parseField(type, "optional"); break; } } skip(";", true); } else skip(";"); parent.add(type); } function parseField(parent, rule, extend) { var type = next(); if (type === "group") { parseGroup(parent, rule); return; } /* istanbul ignore next */ if (!typeRefRe.test(type)) throw illegal(type, "type"); var name = next(); /* istanbul ignore next */ if (!nameRe.test(name)) throw illegal(name, "name"); name = applyCase(name); skip("="); var field = new Field(name, parseId(next()), type, rule, extend), trailingLine = tn.line(); field.comment = cmnt(); field.filename = parse.filename; parseInlineOptions(field); if (!field.comment) field.comment = cmnt(trailingLine); // JSON defaults to packed=true if not set so we have to set packed=false explicity when // parsing proto2 descriptors without the option, where applicable. This must be done for // any type (not just packable types) because enums also use varint encoding and it is not // yet known whether a type is an enum or not. if (!isProto3 && field.repeated) field.setOption("packed", false, /* ifNotSet */ true); parent.add(field); } function parseGroup(parent, rule) { var name = next(); /* istanbul ignore next */ if (!nameRe.test(name)) throw illegal(name, "name"); var fieldName = util.lcFirst(name); if (name === fieldName) name = util.ucFirst(name); skip("="); var id = parseId(next()); var type = new Type(name); type.group = true; type.comment = cmnt(); var field = new Field(fieldName, id, name, rule); type.filename = field.filename = parse.filename; skip("{"); while ((token = next()) !== "}") { switch (token = lower(token)) { case "option": parseOption(type, token); skip(";"); break; case "required": case "optional": case "repeated": parseField(type, token); break; /* istanbul ignore next */ default: throw illegal(token); // there are no groups with proto3 semantics } } skip(";", true); parent.add(type).add(field); } function parseMapField(parent) { skip("<"); var keyType = next(); /* istanbul ignore next */ if (types.mapKey[keyType] === undefined) throw illegal(keyType, "type"); skip(","); var valueType = next(); /* istanbul ignore next */ if (!typeRefRe.test(valueType)) throw illegal(valueType, "type"); skip(">"); var name = next(); /* istanbul ignore next */ if (!nameRe.test(name)) throw illegal(name, "name"); name = applyCase(name); skip("="); var field = new MapField(name, parseId(next()), keyType, valueType), trailingLine = tn.line(); field.comment = cmnt(); field.filename = parse.filename; parseInlineOptions(field); if (!field.comment) field.comment = cmnt(trailingLine); parent.add(field); } function parseOneOf(parent, token) { var name = next(); /* istanbul ignore next */ if (!nameRe.test(name)) throw illegal(name, "name"); name = applyCase(name); var oneof = new OneOf(name), trailingLine = tn.line(); oneof.comment = cmnt(); oneof.filename = parse.filename; if (skip("{", true)) { while ((token = next()) !== "}") { if (token === "option") { parseOption(oneof, token); skip(";"); } else { push(token); parseField(oneof, "optional"); } } skip(";", true); } else { skip(";"); if (!oneof.comment) oneof.comment = cmnt(trailingLine); } parent.add(oneof); } function parseEnum(parent, token) { var name = next(); /* istanbul ignore next */ if (!nameRe.test(name)) throw illegal(name, "name"); var enm = new Enum(name); enm.comment = cmnt(); enm.filename = parse.filename; if (skip("{", true)) { while ((token = next()) !== "}") { if (lower(token) === "option") { parseOption(enm, token); skip(";"); } else parseEnumValue(enm, token); } skip(";", true); } else skip(";"); parent.add(enm); } function parseEnumValue(parent, token) { /* istanbul ignore next */ if (!nameRe.test(token)) throw illegal(token, "name"); var name = token; skip("="); var value = parseId(next(), true), trailingLine = tn.line(); parent.add(name, value, cmnt()); parseInlineOptions({}); // skips enum value options if (!parent.comments[name]) parent.comments[name] = cmnt(trailingLine); } function parseOption(parent, token) { var custom = skip("(", true); var name = next(); /* istanbul ignore next */ if (!typeRefRe.test(name)) throw illegal(name, "name"); if (custom) { skip(")"); name = "(" + name + ")"; token = peek(); if (fqTypeRefRe.test(token)) { name += token; next(); } } skip("="); parseOptionValue(parent, name); } function parseOptionValue(parent, name) { if (skip("{", true)) { // { a: "foo" b { c: "bar" } } /* istanbul ignore next */ do { if (!nameRe.test(token = next())) throw illegal(token, "name"); if (peek() === "{") parseOptionValue(parent, name + "." + token); else { skip(":"); setOption(parent, name + "." + token, readValue(true)); } } while (!skip("}", true)); } else setOption(parent, name, readValue(true)); // Does not enforce a delimiter to be universal } function setOption(parent, name, value) { if (parent.setOption) parent.setOption(name, value); } function parseInlineOptions(parent) { if (skip("[", true)) { do { parseOption(parent, "option"); } while (skip(",", true)); skip("]"); } skip(";"); return parent; } function parseService(parent, token) { token = next(); /* istanbul ignore next */ if (!nameRe.test(token)) throw illegal(token, "service name"); var name = token; var service = new Service(name); service.comment = cmnt(); service.filename = parse.filename; if (skip("{", true)) { while ((token = next()) !== "}") { var tokenLower = lower(token); switch (tokenLower) { case "option": parseOption(service, tokenLower); skip(";"); break; case "rpc": parseMethod(service, tokenLower); break; /* istanbul ignore next */ default: throw illegal(token); } } skip(";", true); } else skip(";"); parent.add(service); } function parseMethod(parent, token) { var type = token; var name = next(); /* istanbul ignore next */ if (!nameRe.test(name)) throw illegal(name, "name"); var requestType, requestStream, responseType, responseStream; skip("("); if (skip("stream", true)) requestStream = true; /* istanbul ignore next */ if (!typeRefRe.test(token = next())) throw illegal(token); requestType = token; skip(")"); skip("returns"); skip("("); if (skip("stream", true)) responseStream = true; /* istanbul ignore next */ if (!typeRefRe.test(token = next())) throw illegal(token); responseType = token; skip(")"); var method = new Method(name, type, requestType, responseType, requestStream, responseStream), trailingLine = tn.line(); method.comment = cmnt(); method.filename = parse.filename; if (skip("{", true)) { while ((token = next()) !== "}") { var tokenLower = lower(token); switch (tokenLower) { case "option": parseOption(method, tokenLower); skip(";"); break; /* istanbul ignore next */ default: throw illegal(token); } } skip(";", true); } else { skip(";"); if (!method.comment) method.comment = cmnt(trailingLine); } parent.add(method); } function parseExtension(parent, token) { var reference = next(); /* istanbul ignore next */ if (!typeRefRe.test(reference)) throw illegal(reference, "reference"); if (skip("{", true)) { while ((token = next()) !== "}") { var tokenLower = lower(token); switch (tokenLower) { case "required": case "repeated": case "optional": parseField(parent, tokenLower, reference); break; default: /* istanbul ignore next */ if (!isProto3 || !typeRefRe.test(token)) throw illegal(token); push(token); parseField(parent, "optional", reference); break; } } skip(";", true); } else skip(";"); } var token; while ((token = next()) !== null) { var tokenLower = lower(token); switch (tokenLower) { case "package": /* istanbul ignore next */ if (!head) throw illegal(token); parsePackage(); break; case "import": /* istanbul ignore next */ if (!head) throw illegal(token); parseImport(); break; case "syntax": /* istanbul ignore next */ if (!head) throw illegal(token); parseSyntax(); break; case "option": /* istanbul ignore next */ if (!head) throw illegal(token); parseOption(ptr, token); skip(";"); break; default: /* istanbul ignore else */ if (parseCommon(ptr, token)) { head = false; continue; } /* istanbul ignore next */ throw illegal(token); } } parse.filename = null; return { "package" : pkg, "imports" : imports, weakImports : weakImports, syntax : syntax, root : root }; } /** * Parses the given .proto source and returns an object with the parsed contents. * @name parse * @function * @param {string} source Source contents * @param {ParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. * @returns {ParserResult} Parser result * @property {string} filename=null Currently processing file name for error reporting, if known * @property {ParseOptions} defaults Default {@link ParseOptions} * @variation 2 */ },{"15":15,"16":16,"20":20,"22":22,"25":25,"29":29,"32":32,"33":33,"34":34,"35":35,"36":36}],27:[function(require,module,exports){ "use strict"; module.exports = Reader; var util = require(38); var BufferReader; // cyclic var LongBits = util.LongBits, utf8 = util.utf8; /* istanbul ignore next */ function indexOutOfRange(reader, writeLength) { return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); } /** * Constructs a new reader instance using the specified buffer. * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. * @constructor * @param {Uint8Array} buffer Buffer to read from */ function Reader(buffer) { /** * Read buffer. * @type {Uint8Array} */ this.buf = buffer; /** * Read buffer position. * @type {number} */ this.pos = 0; /** * Read buffer length. * @type {number} */ this.len = buffer.length; } var create_array = typeof Uint8Array !== "undefined" ? function create_typed_array(buffer) { if (buffer instanceof Uint8Array || Array.isArray(buffer)) return new Reader(buffer); throw Error("illegal buffer"); } /* istanbul ignore next */ : function create_array(buffer) { if (Array.isArray(buffer)) return new Reader(buffer); throw Error("illegal buffer"); }; /** * Creates a new reader using the specified buffer. * @function * @param {Uint8Array|Buffer} buffer Buffer to read from * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} * @throws {Error} If `buffer` is not a valid buffer */ Reader.create = util.Buffer ? function create_buffer_setup(buffer) { return (Reader.create = function create_buffer(buffer) { return util.Buffer.isBuffer(buffer) ? new BufferReader(buffer) /* istanbul ignore next */ : create_array(buffer); })(buffer); } /* istanbul ignore next */ : create_array; Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; /** * Reads a varint as an unsigned 32 bit value. * @function * @returns {number} Value read */ Reader.prototype.uint32 = (function read_uint32_setup() { var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) return function read_uint32() { value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; /* istanbul ignore next */ if ((this.pos += 5) > this.len) { this.pos = this.len; throw indexOutOfRange(this, 10); } return value; }; })(); /** * Reads a varint as a signed 32 bit value. * @returns {number} Value read */ Reader.prototype.int32 = function read_int32() { return this.uint32() | 0; }; /** * Reads a zig-zag encoded varint as a signed 32 bit value. * @returns {number} Value read */ Reader.prototype.sint32 = function read_sint32() { var value = this.uint32(); return value >>> 1 ^ -(value & 1) | 0; }; /* eslint-disable no-invalid-this */ function readLongVarint() { // tends to deopt with local vars for octet etc. var bits = new LongBits(0, 0); var i = 0; if (this.len - this.pos > 4) { // fast route (lo) for (; i < 4; ++i) { // 1st..4th bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; if (this.buf[this.pos++] < 128) return bits; } // 5th bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; if (this.buf[this.pos++] < 128) return bits; i = 0; } else { for (; i < 3; ++i) { /* istanbul ignore next */ if (this.pos >= this.len) throw indexOutOfRange(this); // 1st..3th bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; if (this.buf[this.pos++] < 128) return bits; } // 4th bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; return bits; } if (this.len - this.pos > 4) { // fast route (hi) for (; i < 5; ++i) { // 6th..10th bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; if (this.buf[this.pos++] < 128) return bits; } } else { for (; i < 5; ++i) { /* istanbul ignore next */ if (this.pos >= this.len) throw indexOutOfRange(this); // 6th..10th bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; if (this.buf[this.pos++] < 128) return bits; } } /* istanbul ignore next */ throw Error("invalid varint encoding"); } /* eslint-enable no-invalid-this */ /** * Reads a varint as a signed 64 bit value. * @name Reader#int64 * @function * @returns {Long|number} Value read */ /** * Reads a varint as an unsigned 64 bit value. * @name Reader#uint64 * @function * @returns {Long|number} Value read */ /** * Reads a zig-zag encoded varint as a signed 64 bit value. * @name Reader#sint64 * @function * @returns {Long|number} Value read */ /** * Reads a varint as a boolean. * @returns {boolean} Value read */ Reader.prototype.bool = function read_bool() { return this.uint32() !== 0; }; function readFixed32(buf, end) { return (buf[end - 4] | buf[end - 3] << 8 | buf[end - 2] << 16 | buf[end - 1] << 24) >>> 0; } /** * Reads fixed 32 bits as an unsigned 32 bit integer. * @returns {number} Value read */ Reader.prototype.fixed32 = function read_fixed32() { /* istanbul ignore next */ if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4); return readFixed32(this.buf, this.pos += 4); }; /** * Reads fixed 32 bits as a signed 32 bit integer. * @returns {number} Value read */ Reader.prototype.sfixed32 = function read_sfixed32() { /* istanbul ignore next */ if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4); return readFixed32(this.buf, this.pos += 4) | 0; }; /* eslint-disable no-invalid-this */ function readFixed64(/* this: Reader */) { /* istanbul ignore next */ if (this.pos + 8 > this.len) throw indexOutOfRange(this, 8); return new LongBits(readFixed32(this.buf, this.pos += 4), readFixed32(this.buf, this.pos += 4)); } /* eslint-enable no-invalid-this */ /** * Reads fixed 64 bits. * @name Reader#fixed64 * @function * @returns {Long|number} Value read */ /** * Reads zig-zag encoded fixed 64 bits. * @name Reader#sfixed64 * @function * @returns {Long|number} Value read */ var readFloat = typeof Float32Array !== "undefined" ? (function() { var f32 = new Float32Array(1), f8b = new Uint8Array(f32.buffer); f32[0] = -0; return f8b[3] // already le? ? function readFloat_f32(buf, pos) { f8b[0] = buf[pos ]; f8b[1] = buf[pos + 1]; f8b[2] = buf[pos + 2]; f8b[3] = buf[pos + 3]; return f32[0]; } /* istanbul ignore next */ : function readFloat_f32_le(buf, pos) { f8b[0] = buf[pos + 3]; f8b[1] = buf[pos + 2]; f8b[2] = buf[pos + 1]; f8b[3] = buf[pos ]; return f32[0]; }; })() /* istanbul ignore next */ : function readFloat_ieee754(buf, pos) { var uint = readFixed32(buf, pos + 4), sign = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; return exponent === 255 ? mantissa ? NaN : sign * Infinity : exponent === 0 // denormal ? sign * 1.401298464324817e-45 * mantissa : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); }; /** * Reads a float (32 bit) as a number. * @function * @returns {number} Value read */ Reader.prototype.float = function read_float() { /* istanbul ignore next */ if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4); var value = readFloat(this.buf, this.pos); this.pos += 4; return value; }; var readDouble = typeof Float64Array !== "undefined" ? (function() { var f64 = new Float64Array(1), f8b = new Uint8Array(f64.buffer); f64[0] = -0; return f8b[7] // already le? ? function readDouble_f64(buf, pos) { f8b[0] = buf[pos ]; f8b[1] = buf[pos + 1]; f8b[2] = buf[pos + 2]; f8b[3] = buf[pos + 3]; f8b[4] = buf[pos + 4]; f8b[5] = buf[pos + 5]; f8b[6] = buf[pos + 6]; f8b[7] = buf[pos + 7]; return f64[0]; } /* istanbul ignore next */ : function readDouble_f64_le(buf, pos) { f8b[0] = buf[pos + 7]; f8b[1] = buf[pos + 6]; f8b[2] = buf[pos + 5]; f8b[3] = buf[pos + 4]; f8b[4] = buf[pos + 3]; f8b[5] = buf[pos + 2]; f8b[6] = buf[pos + 1]; f8b[7] = buf[pos ]; return f64[0]; }; })() /* istanbul ignore next */ : function readDouble_ieee754(buf, pos) { var lo = readFixed32(buf, pos + 4), hi = readFixed32(buf, pos + 8); var sign = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo; return exponent === 2047 ? mantissa ? NaN : sign * Infinity : exponent === 0 // denormal ? sign * 5e-324 * mantissa : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); }; /** * Reads a double (64 bit float) as a number. * @function * @returns {number} Value read */ Reader.prototype.double = function read_double() { /* istanbul ignore next */ if (this.pos + 8 > this.len) throw indexOutOfRange(this, 4); var value = readDouble(this.buf, this.pos); this.pos += 8; return value; }; /** * Reads a sequence of bytes preceeded by its length as a varint. * @returns {Uint8Array} Value read */ Reader.prototype.bytes = function read_bytes() { var length = this.uint32(), start = this.pos, end = this.pos + length; /* istanbul ignore next */ if (end > this.len) throw indexOutOfRange(this, length); this.pos += length; return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1 ? new this.buf.constructor(0) : this._slice.call(this.buf, start, end); }; /** * Reads a string preceeded by its byte length as a varint. * @returns {string} Value read */ Reader.prototype.string = function read_string() { var bytes = this.bytes(); return utf8.read(bytes, 0, bytes.length); }; /** * Skips the specified number of bytes if specified, otherwise skips a varint. * @param {number} [length] Length if known, otherwise a varint is assumed * @returns {Reader} `this` */ Reader.prototype.skip = function skip(length) { if (typeof length === "number") { /* istanbul ignore next */ if (this.pos + length > this.len) throw indexOutOfRange(this, length); this.pos += length; } else { /* istanbul ignore next */ do { if (this.pos >= this.len) throw indexOutOfRange(this); } while (this.buf[this.pos++] & 128); } return this; }; /** * Skips the next element of the specified wire type. * @param {number} wireType Wire type received * @returns {Reader} `this` */ Reader.prototype.skipType = function(wireType) { switch (wireType) { case 0: this.skip(); break; case 1: this.skip(8); break; case 2: this.skip(this.uint32()); break; case 3: do { // eslint-disable-line no-constant-condition if ((wireType = this.uint32() & 7) === 4) break; this.skipType(wireType); } while (true); break; case 5: this.skip(4); break; /* istanbul ignore next */ default: throw Error("invalid wire type " + wireType + " at offset " + this.pos); } return this; }; Reader._configure = function(BufferReader_) { BufferReader = BufferReader_; var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; util.merge(Reader.prototype, { int64: function read_int64() { return readLongVarint.call(this)[fn](false); }, uint64: function read_uint64() { return readLongVarint.call(this)[fn](true); }, sint64: function read_sint64() { return readLongVarint.call(this).zzDecode()[fn](false); }, fixed64: function read_fixed64() { return readFixed64.call(this)[fn](true); }, sfixed64: function read_sfixed64() { return readFixed64.call(this)[fn](false); } }); }; },{"38":38}],28:[function(require,module,exports){ "use strict"; module.exports = BufferReader; // extends Reader var Reader = require(27); (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; var util = require(38); /** * Constructs a new buffer reader instance. * @classdesc Wire format reader using node buffers. * @extends Reader * @constructor * @param {Buffer} buffer Buffer to read from */ function BufferReader(buffer) { Reader.call(this, buffer); /** * Read buffer. * @name BufferReader#buf * @type {Buffer} */ } /* istanbul ignore else */ if (util.Buffer) BufferReader.prototype._slice = util.Buffer.prototype.slice; /** * @override */ BufferReader.prototype.string = function read_string_buffer() { var len = this.uint32(); // modifies pos return this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)); }; /** * Reads a sequence of bytes preceeded by its length as a varint. * @name BufferReader#bytes * @function * @returns {Buffer} Value read */ },{"27":27,"38":38}],29:[function(require,module,exports){ "use strict"; module.exports = Root; // extends Namespace var Namespace = require(23); ((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; var Field = require(16), Enum = require(15), util = require(36); var Type, // cyclic parse, // might be excluded common; // " /** * Constructs a new root namespace instance. * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. * @extends NamespaceBase * @constructor * @param {Object.} [options] Top level options */ function Root(options) { Namespace.call(this, "", options); /** * Deferred extension fields. * @type {Field[]} */ this.deferred = []; /** * Resolved file names of loaded files. * @type {string[]} */ this.files = []; } /** * Loads a JSON definition into a root namespace. * @param {Object.} json JSON definition * @param {Root} [root] Root namespace, defaults to create a new one if omitted * @returns {Root} Root namespace */ Root.fromJSON = function fromJSON(json, root) { if (!root) root = new Root(); if (json.options) root.setOptions(json.options); return root.addJSON(json.nested); }; /** * Resolves the path of an imported file, relative to the importing origin. * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. * @function * @param {string} origin The file name of the importing file * @param {string} target The file name being imported * @returns {?string} Resolved path to `target` or `null` to skip the file */ Root.prototype.resolvePath = util.path.resolve; // A symbol-like function to safely signal synchronous loading /* istanbul ignore next */ function SYNC() {} // eslint-disable-line no-empty-function /** * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. * @param {string|string[]} filename Names of one or multiple files to load * @param {ParseOptions} options Parse options * @param {LoadCallback} callback Callback function * @returns {undefined} */ Root.prototype.load = function load(filename, options, callback) { if (typeof options === "function") { callback = options; options = undefined; } var self = this; if (!callback) return util.asPromise(load, self, filename, options); var sync = callback === SYNC; // undocumented // Finishes loading by calling the callback (exactly once) function finish(err, root) { /* istanbul ignore next */ if (!callback) return; var cb = callback; callback = null; if (sync) throw err; cb(err, root); } // Processes a single file function process(filename, source) { try { if (util.isString(source) && source.charAt(0) === "{") source = JSON.parse(source); if (!util.isString(source)) self.setOptions(source.options).addJSON(source.nested); else { parse.filename = filename; var parsed = parse(source, self, options), resolved, i = 0; if (parsed.imports) for (; i < parsed.imports.length; ++i) if (resolved = self.resolvePath(filename, parsed.imports[i])) fetch(resolved); if (parsed.weakImports) for (i = 0; i < parsed.weakImports.length; ++i) if (resolved = self.resolvePath(filename, parsed.weakImports[i])) fetch(resolved, true); } } catch (err) { finish(err); } if (!sync && !queued) finish(null, self); // only once anyway } // Fetches a single file function fetch(filename, weak) { // Strip path if this file references a bundled definition var idx = filename.lastIndexOf("google/protobuf/"); if (idx > -1) { var altname = filename.substring(idx); if (altname in common) filename = altname; } // Skip if already loaded / attempted if (self.files.indexOf(filename) > -1) return; self.files.push(filename); // Shortcut bundled definitions if (filename in common) { if (sync) process(filename, common[filename]); else { ++queued; setTimeout(function() { --queued; process(filename, common[filename]); }); } return; } // Otherwise fetch from disk or network if (sync) { var source; try { source = util.fs.readFileSync(filename).toString("utf8"); } catch (err) { if (!weak) finish(err); return; } process(filename, source); } else { ++queued; util.fetch(filename, function(err, source) { --queued; /* istanbul ignore next */ if (!callback) return; // terminated meanwhile if (err) { if (!weak) finish(err); else /* istanbul ignore next */ if (!queued) // can't be covered reliably finish(null, self); return; } process(filename, source); }); } } var queued = 0; // Assembling the root namespace doesn't require working type // references anymore, so we can load everything in parallel if (util.isString(filename)) filename = [ filename ]; for (var i = 0, resolved; i < filename.length; ++i) if (resolved = self.resolvePath("", filename[i])) fetch(resolved); if (sync) return self; if (!queued) finish(null, self); return undefined; }; // function load(filename:string, options:ParseOptions, callback:LoadCallback):undefined /** * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. * @param {string|string[]} filename Names of one or multiple files to load * @param {LoadCallback} callback Callback function * @returns {undefined} * @variation 2 */ // function load(filename:string, callback:LoadCallback):undefined /** * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. * @name Root#load * @function * @param {string|string[]} filename Names of one or multiple files to load * @param {ParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. * @returns {Promise} Promise * @variation 3 */ // function load(filename:string, [options:ParseOptions]):Promise /** * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). * @name Root#loadSync * @function * @param {string|string[]} filename Names of one or multiple files to load * @param {ParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. * @returns {Root} Root namespace * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid */ Root.prototype.loadSync = function loadSync(filename, options) { if (!util.isNode) throw Error("not supported"); return this.load(filename, options, SYNC); }; /** * @override */ Root.prototype.resolveAll = function resolveAll() { if (this.deferred.length) throw Error("unresolvable extensions: " + this.deferred.map(function(field) { return "'extend " + field.extend + "' in " + field.parent.fullName; }).join(", ")); return Namespace.prototype.resolveAll.call(this); }; // only uppercased (and thus conflict-free) children are exposed, see below var exposeRe = /^[A-Z]/; /** * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. * @param {Root} root Root instance * @param {Field} field Declaring extension field witin the declaring type * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise * @inner * @ignore */ function tryHandleExtension(root, field) { var extendedType = field.parent.lookup(field.extend); if (extendedType) { var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); sisterField.declaringField = field; field.extensionField = sisterField; extendedType.add(sisterField); return true; } return false; } /** * Called when any object is added to this root or its sub-namespaces. * @param {ReflectionObject} object Object added * @returns {undefined} * @private */ Root.prototype._handleAdd = function _handleAdd(object) { if (object instanceof Field) { if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) if (!tryHandleExtension(this, object)) this.deferred.push(object); } else if (object instanceof Enum) { if (exposeRe.test(object.name)) object.parent[object.name] = object.values; // expose enum values as property of its parent } else /* everything else is a namespace */ { if (object instanceof Type) // Try to handle any deferred extensions for (var i = 0; i < this.deferred.length;) if (tryHandleExtension(this, this.deferred[i])) this.deferred.splice(i, 1); else ++i; for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace this._handleAdd(object._nestedArray[j]); if (exposeRe.test(object.name)) object.parent[object.name] = object; // expose namespace as property of its parent } // The above also adds uppercased (and thus conflict-free) nested types, services and enums as // properties of namespaces just like static code does. This allows using a .d.ts generated for // a static module with reflection-based solutions where the condition is met. }; /** * Called when any object is removed from this root or its sub-namespaces. * @param {ReflectionObject} object Object removed * @returns {undefined} * @private */ Root.prototype._handleRemove = function _handleRemove(object) { if (object instanceof Field) { if (/* an extension field */ object.extend !== undefined) { if (/* already handled */ object.extensionField) { // remove its sister field object.extensionField.parent.remove(object.extensionField); object.extensionField = null; } else { // cancel the extension var index = this.deferred.indexOf(object); /* istanbul ignore else */ if (index > -1) this.deferred.splice(index, 1); } } } else if (object instanceof Enum) { if (exposeRe.test(object.name)) delete object.parent[object.name]; // unexpose enum values } else if (object instanceof Namespace) { for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace this._handleRemove(object._nestedArray[i]); if (exposeRe.test(object.name)) delete object.parent[object.name]; // unexpose namespaces } }; Root._configure = function(Type_, parse_, common_) { Type = Type_; parse = parse_; common = common_; }; },{"15":15,"16":16,"23":23,"36":36}],30:[function(require,module,exports){ "use strict"; /** * Streaming RPC helpers. * @namespace */ var rpc = exports; /** * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. * @typedef RPCImpl * @type {function} * @param {Method|rpc.ServiceMethod} method Reflected or static method being called * @param {Uint8Array} requestData Request data * @param {RPCImplCallback} callback Callback function * @returns {undefined} * @example * function rpcImpl(method, requestData, callback) { * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code * throw Error("no such method"); * asynchronouslyObtainAResponse(requestData, function(err, responseData) { * callback(err, responseData); * }); * } */ /** * Node-style callback as used by {@link RPCImpl}. * @typedef RPCImplCallback * @type {function} * @param {?Error} error Error, if any, otherwise `null` * @param {?Uint8Array} [response] Response data or `null` to signal end of stream, if there hasn't been an error * @returns {undefined} */ rpc.Service = require(31); },{"31":31}],31:[function(require,module,exports){ "use strict"; module.exports = Service; var util = require(38); // Extends EventEmitter (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; /** * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. * * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. * @typedef rpc.ServiceMethodCallback * @type {function} * @param {?Error} error Error, if any * @param {?Message} [response] Response message * @returns {undefined} */ /** * A service method part of a {@link rpc.ServiceMethodMixin|ServiceMethodMixin} and thus {@link rpc.Service} as created by {@link Service.create}. * @typedef rpc.ServiceMethod * @type {function} * @param {Message|Object} request Request message or plain object * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message * @returns {Promise} Promise if `callback` has been omitted, otherwise `undefined` */ /** * A service method mixin. * * When using TypeScript, mixed in service methods are only supported directly with a type definition of a static module (used with reflection). Otherwise, explicit casting is required. * @typedef rpc.ServiceMethodMixin * @type {Object.} * @example * // Explicit casting with TypeScript * (myRpcService["myMethod"] as protobuf.rpc.ServiceMethod)(...) */ /** * Constructs a new RPC service instance. * @classdesc An RPC service as returned by {@link Service#create}. * @exports rpc.Service * @extends util.EventEmitter * @augments rpc.ServiceMethodMixin * @constructor * @param {RPCImpl} rpcImpl RPC implementation * @param {boolean} [requestDelimited=false] Whether requests are length-delimited * @param {boolean} [responseDelimited=false] Whether responses are length-delimited */ function Service(rpcImpl, requestDelimited, responseDelimited) { if (typeof rpcImpl !== "function") throw TypeError("rpcImpl must be a function"); util.EventEmitter.call(this); /** * RPC implementation. Becomes `null` once the service is ended. * @type {?RPCImpl} */ this.rpcImpl = rpcImpl; /** * Whether requests are length-delimited. * @type {boolean} */ this.requestDelimited = Boolean(requestDelimited); /** * Whether responses are length-delimited. * @type {boolean} */ this.responseDelimited = Boolean(responseDelimited); } /** * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. * @param {Method|rpc.ServiceMethod} method Reflected or static method * @param {function} requestCtor Request constructor * @param {function} responseCtor Response constructor * @param {Message|Object} request Request message or plain object * @param {rpc.ServiceMethodCallback} callback Service callback * @returns {undefined} */ Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { if (!request) throw TypeError("request must be specified"); var self = this; if (!callback) return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); if (!self.rpcImpl) { setTimeout(function() { callback(Error("already ended")); }, 0); return undefined; } try { return self.rpcImpl( method, requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), function rpcCallback(err, response) { if (err) { self.emit("error", err, method); return callback(err); } if (response === null) { self.end(/* endedByRPC */ true); return undefined; } if (!(response instanceof responseCtor)) { try { response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); } catch (err) { self.emit("error", err, method); return callback(err); } } self.emit("data", response, method); return callback(null, response); } ); } catch (err) { self.emit("error", err, method); setTimeout(function() { callback(err); }, 0); return undefined; } }; /** * Ends this service and emits the `end` event. * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. * @returns {rpc.Service} `this` */ Service.prototype.end = function end(endedByRPC) { if (this.rpcImpl) { if (!endedByRPC) // signal end to rpcImpl this.rpcImpl(null, null, null); this.rpcImpl = null; this.emit("end").off(); } return this; }; },{"38":38}],32:[function(require,module,exports){ "use strict"; module.exports = Service; // extends Namespace var Namespace = require(23); ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; var Method = require(22), util = require(36), rpc = require(30); /** * Constructs a new service instance. * @classdesc Reflected service. * @extends NamespaceBase * @constructor * @param {string} name Service name * @param {Object.} [options] Service options * @throws {TypeError} If arguments are invalid */ function Service(name, options) { Namespace.call(this, name, options); /** * Service methods. * @type {Object.} */ this.methods = {}; // toJSON, marker /** * Cached methods as an array. * @type {?Method[]} * @private */ this._methodsArray = null; } /** * Constructs a service from JSON. * @param {string} name Service name * @param {Object.} json JSON object * @returns {Service} Created service * @throws {TypeError} If arguments are invalid */ Service.fromJSON = function fromJSON(name, json) { var service = new Service(name, json.options); /* istanbul ignore else */ if (json.methods) for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) service.add(Method.fromJSON(names[i], json.methods[names[i]])); return service; }; /** * Methods of this service as an array for iteration. * @name Service#methodsArray * @type {Method[]} * @readonly */ Object.defineProperty(Service.prototype, "methodsArray", { get: function() { return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); } }); function clearCache(service) { service._methodsArray = null; return service; } /** * @override */ Service.prototype.toJSON = function toJSON() { var inherited = Namespace.prototype.toJSON.call(this); return { options : inherited && inherited.options || undefined, methods : Namespace.arrayToJSON(this.methodsArray) || /* istanbul ignore next */ {}, nested : inherited && inherited.nested || undefined }; }; /** * @override */ Service.prototype.get = function get(name) { return this.methods[name] || Namespace.prototype.get.call(this, name); }; /** * @override */ Service.prototype.resolveAll = function resolveAll() { var methods = this.methodsArray; for (var i = 0; i < methods.length; ++i) methods[i].resolve(); return Namespace.prototype.resolve.call(this); }; /** * @override */ Service.prototype.add = function add(object) { /* istanbul ignore next */ if (this.get(object.name)) throw Error("duplicate name '" + object.name + "' in " + this); if (object instanceof Method) { this.methods[object.name] = object; object.parent = this; return clearCache(this); } return Namespace.prototype.add.call(this, object); }; /** * @override */ Service.prototype.remove = function remove(object) { if (object instanceof Method) { /* istanbul ignore next */ if (this.methods[object.name] !== object) throw Error(object + " is not a member of " + this); delete this.methods[object.name]; object.parent = null; return clearCache(this); } return Namespace.prototype.remove.call(this, object); }; /** * Creates a runtime service using the specified rpc implementation. * @param {RPCImpl} rpcImpl RPC implementation * @param {boolean} [requestDelimited=false] Whether requests are length-delimited * @param {boolean} [responseDelimited=false] Whether responses are length-delimited * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. */ Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); for (var i = 0; i < /* initializes */ this.methodsArray.length; ++i) { rpcService[util.lcFirst(this._methodsArray[i].resolve().name)] = util.codegen("r","c")("return this.rpcCall(m,q,s,r,c)").eof(util.lcFirst(this._methodsArray[i].name), { m: this._methodsArray[i], q: this._methodsArray[i].resolvedRequestType.ctor, s: this._methodsArray[i].resolvedResponseType.ctor }); } return rpcService; }; },{"22":22,"23":23,"30":30,"36":36}],33:[function(require,module,exports){ "use strict"; module.exports = tokenize; var delimRe = /[\s{}=;:[\],'"()<>]/g, stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; var setCommentRe = /^ *[*/]+ */, setCommentSplitRe = /\n/g, whitespaceRe = /\s/, unescapeRe = /\\(.?)/g; var unescapeMap = { "0": "\0", "r": "\r", "n": "\n", "t": "\t" }; /** * Unescapes a string. * @param {string} str String to unescape * @returns {string} Unescaped string * @property {Object.} map Special characters map * @ignore */ function unescape(str) { return str.replace(unescapeRe, function($0, $1) { switch ($1) { case "\\": case "": return $1; default: return unescapeMap[$1] || ""; } }); } tokenize.unescape = unescape; /** * Handle object returned from {@link tokenize}. * @typedef {Object.} TokenizerHandle * @property {function():number} line Gets the current line number * @property {function():?string} next Gets the next token and advances (`null` on eof) * @property {function():?string} peek Peeks for the next token (`null` on eof) * @property {function(string)} push Pushes a token back to the stack * @property {function(string, boolean=):boolean} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws * @property {function(number=):?string} cmnt Gets the comment on the previous line or the line comment on the specified line, if any */ /** * Tokenizes the given .proto source and returns an object with useful utility functions. * @param {string} source Source contents * @returns {TokenizerHandle} Tokenizer handle * @property {function(string):string} unescape Unescapes a string */ function tokenize(source) { /* eslint-disable callback-return */ source = source.toString(); var offset = 0, length = source.length, line = 1, commentType = null, commentText = null, commentLine = 0; var stack = []; var stringDelim = null; /* istanbul ignore next */ /** * Creates an error for illegal syntax. * @param {string} subject Subject * @returns {Error} Error created * @inner */ function illegal(subject) { return Error("illegal " + subject + " (line " + line + ")"); } /** * Reads a string till its end. * @returns {string} String read * @inner */ function readString() { var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; re.lastIndex = offset - 1; var match = re.exec(source); if (!match) throw illegal("string"); offset = re.lastIndex; push(stringDelim); stringDelim = null; return unescape(match[1]); } /** * Gets the character at `pos` within the source. * @param {number} pos Position * @returns {string} Character * @inner */ function charAt(pos) { return source.charAt(pos); } /** * Sets the current comment text. * @param {number} start Start offset * @param {number} end End offset * @returns {undefined} * @inner */ function setComment(start, end) { commentType = source.charAt(start++); commentLine = line; var lines = source .substring(start, end) .split(setCommentSplitRe); for (var i = 0; i < lines.length; ++i) lines[i] = lines[i].replace(setCommentRe, "").trim(); commentText = lines .join("\n") .trim(); } /** * Obtains the next token. * @returns {?string} Next token or `null` on eof * @inner */ function next() { if (stack.length > 0) return stack.shift(); if (stringDelim) return readString(); var repeat, prev, curr, start, isComment; do { if (offset === length) return null; repeat = false; while (whitespaceRe.test(curr = charAt(offset))) { if (curr === "\n") ++line; if (++offset === length) return null; } if (charAt(offset) === "/") { if (++offset === length) throw illegal("comment"); if (charAt(offset) === "/") { // Line isComment = charAt(start = offset + 1) === "/"; while (charAt(++offset) !== "\n") if (offset === length) return null; ++offset; if (isComment) setComment(start, offset - 1); ++line; repeat = true; } else if ((curr = charAt(offset)) === "*") { /* Block */ isComment = charAt(start = offset + 1) === "*"; do { if (curr === "\n") ++line; if (++offset === length) throw illegal("comment"); prev = curr; curr = charAt(offset); } while (prev !== "*" || curr !== "/"); ++offset; if (isComment) setComment(start, offset - 2); repeat = true; } else return "/"; } } while (repeat); // offset !== length if we got here var end = offset; delimRe.lastIndex = 0; var delim = delimRe.test(charAt(end++)); if (!delim) while (end < length && !delimRe.test(charAt(end))) ++end; var token = source.substring(offset, offset = end); if (token === "\"" || token === "'") stringDelim = token; return token; } /** * Pushes a token back to the stack. * @param {string} token Token * @returns {undefined} * @inner */ function push(token) { stack.push(token); } /** * Peeks for the next token. * @returns {?string} Token or `null` on eof * @inner */ function peek() { if (!stack.length) { var token = next(); if (token === null) return null; push(token); } return stack[0]; } /** * Skips a token. * @param {string} expected Expected token * @param {boolean} [optional=false] Whether the token is optional * @returns {boolean} `true` when skipped, `false` if not * @throws {Error} When a required token is not present * @inner */ function skip(expected, optional) { var actual = peek(), equals = actual === expected; if (equals) { next(); return true; } if (!optional) throw illegal("token '" + actual + "', '" + expected + "' expected"); return false; } return { next: next, peek: peek, push: push, skip: skip, line: function() { return line; }, cmnt: function(trailingLine) { var ret; if (trailingLine === undefined) ret = commentLine === line - 1 && commentText || null; else { if (!commentText) peek(); ret = commentLine === trailingLine && commentType === "/" && commentText || null; } if (ret) { commentType = commentText = null; commentLine = 0; } return ret; } }; /* eslint-enable callback-return */ } },{}],34:[function(require,module,exports){ "use strict"; module.exports = Type; // extends Namespace var Namespace = require(23); ((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; var Enum = require(15), OneOf = require(25), Field = require(16), MapField = require(20), Service = require(32), Class = require(10), Message = require(21), Reader = require(27), Writer = require(40), util = require(36), encoder = require(14), decoder = require(13), verifier = require(39), converter = require(12); /** * Creates a type from JSON. * @param {string} name Message name * @param {Object.} json JSON object * @returns {Type} Created message type */ Type.fromJSON = function fromJSON(name, json) { var type = new Type(name, json.options); type.extensions = json.extensions; type.reserved = json.reserved; var names = Object.keys(json.fields), i = 0; for (; i < names.length; ++i) type.add( ( typeof json.fields[names[i]].keyType !== "undefined" ? MapField.fromJSON : Field.fromJSON )(names[i], json.fields[names[i]]) ); if (json.oneofs) for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); if (json.nested) for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { var nested = json.nested[names[i]]; type.add( // most to least likely ( nested.id !== undefined ? Field.fromJSON : nested.fields !== undefined ? Type.fromJSON : nested.values !== undefined ? Enum.fromJSON : nested.methods !== undefined ? Service.fromJSON : Namespace.fromJSON )(names[i], nested) ); } if (json.extensions && json.extensions.length) type.extensions = json.extensions; if (json.reserved && json.reserved.length) type.reserved = json.reserved; if (json.group) type.group = true; return type; }; /** * Constructs a new reflected message type instance. * @classdesc Reflected message type. * @extends NamespaceBase * @constructor * @param {string} name Message name * @param {Object.} [options] Declared options */ function Type(name, options) { Namespace.call(this, name, options); /** * Message fields. * @type {Object.} */ this.fields = {}; // toJSON, marker /** * Oneofs declared within this namespace, if any. * @type {Object.} */ this.oneofs = undefined; // toJSON /** * Extension ranges, if any. * @type {number[][]} */ this.extensions = undefined; // toJSON /** * Reserved ranges, if any. * @type {Array.} */ this.reserved = undefined; // toJSON /*? * Whether this type is a legacy group. * @type {boolean|undefined} */ this.group = undefined; // toJSON /** * Cached fields by id. * @type {?Object.} * @private */ this._fieldsById = null; /** * Cached fields as an array. * @type {?Field[]} * @private */ this._fieldsArray = null; /** * Cached oneofs as an array. * @type {?OneOf[]} * @private */ this._oneofsArray = null; /** * Cached constructor. * @type {*} * @private */ this._ctor = null; } Object.defineProperties(Type.prototype, { /** * Message fields by id. * @name Type#fieldsById * @type {Object.} * @readonly */ fieldsById: { get: function() { /* istanbul ignore next */ if (this._fieldsById) return this._fieldsById; this._fieldsById = {}; for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { var field = this.fields[names[i]], id = field.id; /* istanbul ignore next */ if (this._fieldsById[id]) throw Error("duplicate id " + id + " in " + this); this._fieldsById[id] = field; } return this._fieldsById; } }, /** * Fields of this message as an array for iteration. * @name Type#fieldsArray * @type {Field[]} * @readonly */ fieldsArray: { get: function() { return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); } }, /** * Oneofs of this message as an array for iteration. * @name Type#oneofsArray * @type {OneOf[]} * @readonly */ oneofsArray: { get: function() { return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); } }, /** * The registered constructor, if any registered, otherwise a generic constructor. * @name Type#ctor * @type {Class} */ ctor: { get: function() { return this._ctor || (this._ctor = Class(this).constructor); }, set: function(ctor) { if (ctor && !(ctor.prototype instanceof Message)) throw TypeError("ctor must be a Message constructor"); if (!ctor.from) ctor.from = Message.from; this._ctor = ctor; } } }); function clearCache(type) { type._fieldsById = type._fieldsArray = type._oneofsArray = type._ctor = null; delete type.encode; delete type.decode; delete type.verify; return type; } /** * @override */ Type.prototype.toJSON = function toJSON() { var inherited = Namespace.prototype.toJSON.call(this); return { options : inherited && inherited.options || undefined, oneofs : Namespace.arrayToJSON(this.oneofsArray), fields : Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; })) || {}, extensions : this.extensions && this.extensions.length ? this.extensions : undefined, reserved : this.reserved && this.reserved.length ? this.reserved : undefined, group : this.group || undefined, nested : inherited && inherited.nested || undefined }; }; /** * @override */ Type.prototype.resolveAll = function resolveAll() { var fields = this.fieldsArray, i = 0; while (i < fields.length) fields[i++].resolve(); var oneofs = this.oneofsArray; i = 0; while (i < oneofs.length) oneofs[i++].resolve(); return Namespace.prototype.resolve.call(this); }; /** * @override */ Type.prototype.get = function get(name) { return this.fields[name] || this.oneofs && this.oneofs[name] || this.nested && this.nested[name] || null; }; /** * Adds a nested object to this type. * @param {ReflectionObject} object Nested object to add * @returns {Type} `this` * @throws {TypeError} If arguments are invalid * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id */ Type.prototype.add = function add(object) { if (this.get(object.name)) throw Error("duplicate name '" + object.name + "' in " + this); if (object instanceof Field && object.extend === undefined) { // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. // The root object takes care of adding distinct sister-fields to the respective extended // type instead. // avoids calling the getter if not absolutely necessary because it's called quite frequently if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) throw Error("duplicate id " + object.id + " in " + this); if (this.isReservedId(object.id)) throw Error("id " + object.id + " is reserved in " + this); if (this.isReservedName(object.name)) throw Error("name '" + object.name + "' is reserved in " + this); if (object.parent) object.parent.remove(object); this.fields[object.name] = object; object.message = this; object.onAdd(this); return clearCache(this); } if (object instanceof OneOf) { if (!this.oneofs) this.oneofs = {}; this.oneofs[object.name] = object; object.onAdd(this); return clearCache(this); } return Namespace.prototype.add.call(this, object); }; /** * Removes a nested object from this type. * @param {ReflectionObject} object Nested object to remove * @returns {Type} `this` * @throws {TypeError} If arguments are invalid * @throws {Error} If `object` is not a member of this type */ Type.prototype.remove = function remove(object) { if (object instanceof Field && object.extend === undefined) { // See Type#add for the reason why extension fields are excluded here. /* istanbul ignore next */ if (!this.fields || this.fields[object.name] !== object) throw Error(object + " is not a member of " + this); delete this.fields[object.name]; object.parent = null; object.onRemove(this); return clearCache(this); } if (object instanceof OneOf) { /* istanbul ignore next */ if (!this.oneofs || this.oneofs[object.name] !== object) throw Error(object + " is not a member of " + this); delete this.oneofs[object.name]; object.parent = null; object.onRemove(this); return clearCache(this); } return Namespace.prototype.remove.call(this, object); }; /** * Tests if the specified id is reserved. * @param {number} id Id to test * @returns {boolean} `true` if reserved, otherwise `false` */ Type.prototype.isReservedId = function isReservedId(id) { if (this.reserved) for (var i = 0; i < this.reserved.length; ++i) if (typeof this.reserved[i] !== "string" && this.reserved[i][0] <= id && this.reserved[i][1] >= id) return true; return false; }; /** * Tests if the specified name is reserved. * @param {string} name Name to test * @returns {boolean} `true` if reserved, otherwise `false` */ Type.prototype.isReservedName = function isReservedName(name) { if (this.reserved) for (var i = 0; i < this.reserved.length; ++i) if (this.reserved[i] === name) return true; return false; }; /** * Creates a new message of this type using the specified properties. * @param {Object.} [properties] Properties to set * @returns {Message} Runtime message */ Type.prototype.create = function create(properties) { return new this.ctor(properties); }; /** * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. * @returns {Type} `this` */ Type.prototype.setup = function setup() { // Sets up everything at once so that the prototype chain does not have to be re-evaluated // multiple times (V8, soft-deopt prototype-check). var fullName = this.fullName, types = []; for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) types.push(this._fieldsArray[i].resolve().resolvedType); this.encode = encoder(this).eof(fullName + "$encode", { Writer : Writer, types : types, util : util }); this.decode = decoder(this).eof(fullName + "$decode", { Reader : Reader, types : types, util : util }); this.verify = verifier(this).eof(fullName + "$verify", { types : types, util : util }); this.fromObject = this.from = converter.fromObject(this).eof(fullName + "$fromObject", { types : types, util : util }); this.toObject = converter.toObject(this).eof(fullName + "$toObject", { types : types, util : util }); return this; }; /** * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. * @param {Message|Object} message Message instance or plain object * @param {Writer} [writer] Writer to encode to * @returns {Writer} writer */ Type.prototype.encode = function encode_setup(message, writer) { return this.setup().encode(message, writer); // overrides this method }; /** * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. * @param {Message|Object} message Message instance or plain object * @param {Writer} [writer] Writer to encode to * @returns {Writer} writer */ Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); }; /** * Decodes a message of this type. * @param {Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Length of the message, if known beforehand * @returns {Message} Decoded message * @throws {Error} If the payload is not a reader or valid buffer * @throws {util.ProtocolError} If required fields are missing */ Type.prototype.decode = function decode_setup(reader, length) { return this.setup().decode(reader, length); // overrides this method }; /** * Decodes a message of this type preceeded by its byte length as a varint. * @param {Reader|Uint8Array} reader Reader or buffer to decode from * @returns {Message} Decoded message * @throws {Error} If the payload is not a reader or valid buffer * @throws {util.ProtocolError} If required fields are missing */ Type.prototype.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof Reader)) reader = Reader.create(reader); return this.decode(reader, reader.uint32()); }; /** * Verifies that field values are valid and that required fields are present. * @param {Message|Object} message Message to verify * @returns {?string} `null` if valid, otherwise the reason why it is not */ Type.prototype.verify = function verify_setup(message) { return this.setup().verify(message); // overrides this method }; /** * Creates a new message of this type from a plain object. Also converts values to their respective internal types. * @param {Object.} object Plain object * @returns {Message} Message instance */ Type.prototype.fromObject = function fromObject(object) { return this.setup().fromObject(object); }; /** * Creates a new message of this type from a plain object. Also converts values to their respective internal types. * This is an alias of {@link Type#fromObject}. * @function * @param {Object.} object Plain object * @returns {Message} Message instance */ Type.prototype.from = Type.prototype.fromObject; /** * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. * @typedef ConversionOptions * @type {Object} * @property {*} [longs] Long conversion type. * Valid values are `String` and `Number` (the global types). * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. * @property {*} [enums] Enum value conversion type. * Only valid value is `String` (the global type). * Defaults to copy the present value, which is the numeric id. * @property {*} [bytes] Bytes value conversion type. * Valid values are `Array` and (a base64 encoded) `String` (the global types). * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. * @property {boolean} [defaults=false] Also sets default values on the resulting object * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` */ /** * Creates a plain object from a message of this type. Also converts values to other types if specified. * @param {Message} message Message instance * @param {ConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ Type.prototype.toObject = function toObject(message, options) { return this.setup().toObject(message, options); }; },{"10":10,"12":12,"13":13,"14":14,"15":15,"16":16,"20":20,"21":21,"23":23,"25":25,"27":27,"32":32,"36":36,"39":39,"40":40}],35:[function(require,module,exports){ "use strict"; /** * Common type constants. * @namespace */ var types = exports; var util = require(36); var s = [ "double", // 0 "float", // 1 "int32", // 2 "uint32", // 3 "sint32", // 4 "fixed32", // 5 "sfixed32", // 6 "int64", // 7 "uint64", // 8 "sint64", // 9 "fixed64", // 10 "sfixed64", // 11 "bool", // 12 "string", // 13 "bytes" // 14 ]; function bake(values, offset) { var i = 0, o = {}; offset |= 0; while (i < values.length) o[s[i + offset]] = values[i++]; return o; } /** * Basic type wire types. * @type {Object.} * @property {number} double=1 Fixed64 wire type * @property {number} float=5 Fixed32 wire type * @property {number} int32=0 Varint wire type * @property {number} uint32=0 Varint wire type * @property {number} sint32=0 Varint wire type * @property {number} fixed32=5 Fixed32 wire type * @property {number} sfixed32=5 Fixed32 wire type * @property {number} int64=0 Varint wire type * @property {number} uint64=0 Varint wire type * @property {number} sint64=0 Varint wire type * @property {number} fixed64=1 Fixed64 wire type * @property {number} sfixed64=1 Fixed64 wire type * @property {number} bool=0 Varint wire type * @property {number} string=2 Ldelim wire type * @property {number} bytes=2 Ldelim wire type */ types.basic = bake([ /* double */ 1, /* float */ 5, /* int32 */ 0, /* uint32 */ 0, /* sint32 */ 0, /* fixed32 */ 5, /* sfixed32 */ 5, /* int64 */ 0, /* uint64 */ 0, /* sint64 */ 0, /* fixed64 */ 1, /* sfixed64 */ 1, /* bool */ 0, /* string */ 2, /* bytes */ 2 ]); /** * Basic type defaults. * @type {Object.} * @property {number} double=0 Double default * @property {number} float=0 Float default * @property {number} int32=0 Int32 default * @property {number} uint32=0 Uint32 default * @property {number} sint32=0 Sint32 default * @property {number} fixed32=0 Fixed32 default * @property {number} sfixed32=0 Sfixed32 default * @property {number} int64=0 Int64 default * @property {number} uint64=0 Uint64 default * @property {number} sint64=0 Sint32 default * @property {number} fixed64=0 Fixed64 default * @property {number} sfixed64=0 Sfixed64 default * @property {boolean} bool=false Bool default * @property {string} string="" String default * @property {Array.} bytes=Array(0) Bytes default * @property {Message} message=null Message default */ types.defaults = bake([ /* double */ 0, /* float */ 0, /* int32 */ 0, /* uint32 */ 0, /* sint32 */ 0, /* fixed32 */ 0, /* sfixed32 */ 0, /* int64 */ 0, /* uint64 */ 0, /* sint64 */ 0, /* fixed64 */ 0, /* sfixed64 */ 0, /* bool */ false, /* string */ "", /* bytes */ util.emptyArray, /* message */ null ]); /** * Basic long type wire types. * @type {Object.} * @property {number} int64=0 Varint wire type * @property {number} uint64=0 Varint wire type * @property {number} sint64=0 Varint wire type * @property {number} fixed64=1 Fixed64 wire type * @property {number} sfixed64=1 Fixed64 wire type */ types.long = bake([ /* int64 */ 0, /* uint64 */ 0, /* sint64 */ 0, /* fixed64 */ 1, /* sfixed64 */ 1 ], 7); /** * Allowed types for map keys with their associated wire type. * @type {Object.} * @property {number} int32=0 Varint wire type * @property {number} uint32=0 Varint wire type * @property {number} sint32=0 Varint wire type * @property {number} fixed32=5 Fixed32 wire type * @property {number} sfixed32=5 Fixed32 wire type * @property {number} int64=0 Varint wire type * @property {number} uint64=0 Varint wire type * @property {number} sint64=0 Varint wire type * @property {number} fixed64=1 Fixed64 wire type * @property {number} sfixed64=1 Fixed64 wire type * @property {number} bool=0 Varint wire type * @property {number} string=2 Ldelim wire type */ types.mapKey = bake([ /* int32 */ 0, /* uint32 */ 0, /* sint32 */ 0, /* fixed32 */ 5, /* sfixed32 */ 5, /* int64 */ 0, /* uint64 */ 0, /* sint64 */ 0, /* fixed64 */ 1, /* sfixed64 */ 1, /* bool */ 0, /* string */ 2 ], 2); /** * Allowed types for packed repeated fields with their associated wire type. * @type {Object.} * @property {number} double=1 Fixed64 wire type * @property {number} float=5 Fixed32 wire type * @property {number} int32=0 Varint wire type * @property {number} uint32=0 Varint wire type * @property {number} sint32=0 Varint wire type * @property {number} fixed32=5 Fixed32 wire type * @property {number} sfixed32=5 Fixed32 wire type * @property {number} int64=0 Varint wire type * @property {number} uint64=0 Varint wire type * @property {number} sint64=0 Varint wire type * @property {number} fixed64=1 Fixed64 wire type * @property {number} sfixed64=1 Fixed64 wire type * @property {number} bool=0 Varint wire type */ types.packed = bake([ /* double */ 1, /* float */ 5, /* int32 */ 0, /* uint32 */ 0, /* sint32 */ 0, /* fixed32 */ 5, /* sfixed32 */ 5, /* int64 */ 0, /* uint64 */ 0, /* sint64 */ 0, /* fixed64 */ 1, /* sfixed64 */ 1, /* bool */ 0 ]); },{"36":36}],36:[function(require,module,exports){ "use strict"; /** * Various utility functions. * @namespace */ var util = module.exports = require(38); util.codegen = require(3); util.fetch = require(5); util.path = require(7); /** * Node's fs module if available. * @type {Object.} */ util.fs = util.inquire("fs"); /** * Converts an object's values to an array. * @param {Object.} object Object to convert * @returns {Array.<*>} Converted array */ util.toArray = function toArray(object) { var array = []; if (object) for (var keys = Object.keys(object), i = 0; i < keys.length; ++i) array.push(object[keys[i]]); return array; }; var safePropBackslashRe = /\\/g, safePropQuoteRe = /"/g; /** * Returns a safe property accessor for the specified properly name. * @param {string} prop Property name * @returns {string} Safe accessor */ util.safeProp = function safeProp(prop) { return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; }; /** * Converts the first character of a string to upper case. * @param {string} str String to convert * @returns {string} Converted string */ util.ucFirst = function ucFirst(str) { return str.charAt(0).toUpperCase() + str.substring(1); }; },{"3":3,"38":38,"5":5,"7":7}],37:[function(require,module,exports){ "use strict"; module.exports = LongBits; var util = require(38); /** * Any compatible Long instance. * * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. * @typedef Long * @type {Object} * @property {number} low Low bits * @property {number} high High bits * @property {boolean} unsigned Whether unsigned or not */ /** * Constructs new long bits. * @classdesc Helper class for working with the low and high bits of a 64 bit value. * @memberof util * @constructor * @param {number} lo Low 32 bits, unsigned * @param {number} hi High 32 bits, unsigned */ function LongBits(lo, hi) { // note that the casts below are theoretically unnecessary as of today, but older statically // generated converter code might still call the ctor with signed 32bits. kept for compat. /** * Low bits. * @type {number} */ this.lo = lo >>> 0; /** * High bits. * @type {number} */ this.hi = hi >>> 0; } /** * Zero bits. * @memberof util.LongBits * @type {util.LongBits} */ var zero = LongBits.zero = new LongBits(0, 0); zero.toNumber = function() { return 0; }; zero.zzEncode = zero.zzDecode = function() { return this; }; zero.length = function() { return 1; }; /** * Zero hash. * @memberof util.LongBits * @type {string} */ var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; /** * Constructs new long bits from the specified number. * @param {number} value Value * @returns {util.LongBits} Instance */ LongBits.fromNumber = function fromNumber(value) { if (value === 0) return zero; var sign = value < 0; if (sign) value = -value; var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0; if (sign) { hi = ~hi >>> 0; lo = ~lo >>> 0; if (++lo > 4294967295) { lo = 0; if (++hi > 4294967295) hi = 0; } } return new LongBits(lo, hi); }; /** * Constructs new long bits from a number, long or string. * @param {Long|number|string} value Value * @returns {util.LongBits} Instance */ LongBits.from = function from(value) { if (typeof value === "number") return LongBits.fromNumber(value); if (util.isString(value)) { /* istanbul ignore else */ if (util.Long) value = util.Long.fromString(value); else return LongBits.fromNumber(parseInt(value, 10)); } return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; }; /** * Converts this long bits to a possibly unsafe JavaScript number. * @param {boolean} [unsigned=false] Whether unsigned or not * @returns {number} Possibly unsafe number */ LongBits.prototype.toNumber = function toNumber(unsigned) { if (!unsigned && this.hi >>> 31) { var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0; if (!lo) hi = hi + 1 >>> 0; return -(lo + hi * 4294967296); } return this.lo + this.hi * 4294967296; }; /** * Converts this long bits to a long. * @param {boolean} [unsigned=false] Whether unsigned or not * @returns {Long} Long */ LongBits.prototype.toLong = function toLong(unsigned) { return util.Long ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) /* istanbul ignore next */ : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; }; var charCodeAt = String.prototype.charCodeAt; /** * Constructs new long bits from the specified 8 characters long hash. * @param {string} hash Hash * @returns {util.LongBits} Bits */ LongBits.fromHash = function fromHash(hash) { if (hash === zeroHash) return zero; return new LongBits( ( charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0 , ( charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0 ); }; /** * Converts this long bits to a 8 characters long hash. * @returns {string} Hash */ LongBits.prototype.toHash = function toHash() { return String.fromCharCode( this.lo & 255, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24 , this.hi & 255, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24 ); }; /** * Zig-zag encodes this long bits. * @returns {util.LongBits} `this` */ LongBits.prototype.zzEncode = function zzEncode() { var mask = this.hi >> 31; this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; this.lo = ( this.lo << 1 ^ mask) >>> 0; return this; }; /** * Zig-zag decodes this long bits. * @returns {util.LongBits} `this` */ LongBits.prototype.zzDecode = function zzDecode() { var mask = -(this.lo & 1); this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; this.hi = ( this.hi >>> 1 ^ mask) >>> 0; return this; }; /** * Calculates the length of this longbits when encoded as a varint. * @returns {number} Length */ LongBits.prototype.length = function length() { var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24; return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10; }; },{"38":38}],38:[function(require,module,exports){ "use strict"; var util = exports; // used to return a Promise where callback is omitted util.asPromise = require(1); // converts to / from base64 encoded strings util.base64 = require(2); // base class of rpc.Service util.EventEmitter = require(4); // requires modules optionally and hides the call from bundlers util.inquire = require(6); // converts to / from utf8 encoded strings util.utf8 = require(9); // provides a node-like buffer pool in the browser util.pool = require(8); // utility to work with the low and high bits of a 64 bit value util.LongBits = require(37); /** * An immuable empty array. * @memberof util * @type {Array.<*>} */ util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes /** * An immutable empty object. * @type {Object} */ util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes /** * Whether running within node or not. * @memberof util * @type {boolean} */ util.isNode = Boolean(global.process && global.process.versions && global.process.versions.node); /** * Tests if the specified value is an integer. * @function * @param {*} value Value to test * @returns {boolean} `true` if the value is an integer */ util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { return typeof value === "number" && isFinite(value) && Math.floor(value) === value; }; /** * Tests if the specified value is a string. * @param {*} value Value to test * @returns {boolean} `true` if the value is a string */ util.isString = function isString(value) { return typeof value === "string" || value instanceof String; }; /** * Tests if the specified value is a non-null object. * @param {*} value Value to test * @returns {boolean} `true` if the value is a non-null object */ util.isObject = function isObject(value) { return value && typeof value === "object"; }; /** * Node's Buffer class if available. * @type {?function(new: Buffer)} */ util.Buffer = (function() { try { var Buffer = util.inquire("buffer").Buffer; // refuse to use non-node buffers if not explicitly assigned (perf reasons): return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; } catch (e) { /* istanbul ignore next */ return null; } })(); /** * Internal alias of or polyfull for Buffer.from. * @type {?function} * @param {string|number[]} value Value * @param {string} [encoding] Encoding if value is a string * @returns {Uint8Array} * @private */ util._Buffer_from = null; /** * Internal alias of or polyfill for Buffer.allocUnsafe. * @type {?function} * @param {number} size Buffer size * @returns {Uint8Array} * @private */ util._Buffer_allocUnsafe = null; /** * Creates a new buffer of whatever type supported by the environment. * @param {number|number[]} [sizeOrArray=0] Buffer size or number array * @returns {Uint8Array|Buffer} Buffer */ util.newBuffer = function newBuffer(sizeOrArray) { /* istanbul ignore next */ return typeof sizeOrArray === "number" ? util.Buffer ? util._Buffer_allocUnsafe(sizeOrArray) : new util.Array(sizeOrArray) : util.Buffer ? util._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray); }; /** * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. * @type {?function(new: Uint8Array, *)} */ util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; /** * Long.js's Long class if available. * @type {?function(new: Long)} */ util.Long = /* istanbul ignore next */ global.dcodeIO && /* istanbul ignore next */ global.dcodeIO.Long || util.inquire("long"); /** * Regular expression used to verify 2 bit (`bool`) map keys. * @type {RegExp} */ util.key2Re = /^true|false|0|1$/; /** * Regular expression used to verify 32 bit (`int32` etc.) map keys. * @type {RegExp} */ util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; /** * Regular expression used to verify 64 bit (`int64` etc.) map keys. * @type {RegExp} */ util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; /** * Converts a number or long to an 8 characters long hash string. * @param {Long|number} value Value to convert * @returns {string} Hash */ util.longToHash = function longToHash(value) { return value ? util.LongBits.from(value).toHash() : util.LongBits.zeroHash; }; /** * Converts an 8 characters long hash string to a long or number. * @param {string} hash Hash * @param {boolean} [unsigned=false] Whether unsigned or not * @returns {Long|number} Original value */ util.longFromHash = function longFromHash(hash, unsigned) { var bits = util.LongBits.fromHash(hash); if (util.Long) return util.Long.fromBits(bits.lo, bits.hi, unsigned); return bits.toNumber(Boolean(unsigned)); }; /** * Merges the properties of the source object into the destination object. * @memberof util * @param {Object.} dst Destination object * @param {Object.} src Source object * @param {boolean} [ifNotSet=false] Merges only if the key is not already set * @returns {Object.} Destination object */ function merge(dst, src, ifNotSet) { // used by converters for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) if (dst[keys[i]] === undefined || !ifNotSet) dst[keys[i]] = src[keys[i]]; return dst; } util.merge = merge; /** * Converts the first character of a string to lower case. * @param {string} str String to convert * @returns {string} Converted string */ util.lcFirst = function lcFirst(str) { return str.charAt(0).toLowerCase() + str.substring(1); }; /** * Creates a custom error constructor. * @memberof util * @param {string} name Error name * @returns {function} Custom error constructor */ function newError(name) { function CustomError(message, properties) { if (!(this instanceof CustomError)) return new CustomError(message, properties); // Error.call(this, message); // ^ just returns a new error instance because the ctor can be called as a function Object.defineProperty(this, "message", { get: function() { return message; } }); /* istanbul ignore next */ if (Error.captureStackTrace) // node Error.captureStackTrace(this, CustomError); else Object.defineProperty(this, "stack", { value: (new Error()).stack || "" }); if (properties) merge(this, properties); } (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError; Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } }); CustomError.prototype.toString = function toString() { return this.name + ": " + this.message; }; return CustomError; } util.newError = newError; /** * Constructs a new protocol error. * @classdesc Error subclass indicating a protocol specifc error. * @memberof util * @extends Error * @constructor * @param {string} message Error message * @param {Object.=} properties Additional properties * @example * try { * MyMessage.decode(someBuffer); // throws if required fields are missing * } catch (e) { * if (e instanceof ProtocolError && e.instance) * console.log("decoded so far: " + JSON.stringify(e.instance)); * } */ util.ProtocolError = newError("ProtocolError"); /** * So far decoded message instance. * @name util.ProtocolError#instance * @type {Message} */ /** * Builds a getter for a oneof's present field name. * @param {string[]} fieldNames Field names * @returns {function():string|undefined} Unbound getter */ util.oneOfGetter = function getOneOf(fieldNames) { var fieldMap = {}; for (var i = 0; i < fieldNames.length; ++i) fieldMap[fieldNames[i]] = 1; /** * @returns {string|undefined} Set field name, if any * @this Object * @ignore */ return function() { // eslint-disable-line consistent-return for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) return keys[i]; }; }; /** * Builds a setter for a oneof's present field name. * @param {string[]} fieldNames Field names * @returns {function(?string):undefined} Unbound setter */ util.oneOfSetter = function setOneOf(fieldNames) { /** * @param {string} name Field name * @returns {undefined} * @this Object * @ignore */ return function(name) { for (var i = 0; i < fieldNames.length; ++i) if (fieldNames[i] !== name) delete this[fieldNames[i]]; }; }; /** * Lazily resolves fully qualified type names against the specified root. * @param {Root} root Root instanceof * @param {Object.} lazyTypes Type names * @returns {undefined} */ util.lazyResolve = function lazyResolve(root, lazyTypes) { for (var i = 0; i < lazyTypes.length; ++i) { for (var keys = Object.keys(lazyTypes[i]), j = 0; j < keys.length; ++j) { var path = lazyTypes[i][keys[j]].split("."), ptr = root; while (path.length) ptr = ptr[path.shift()]; lazyTypes[i][keys[j]] = ptr; } } }; /** * Default conversion options used for toJSON implementations. Converts longs, enums and bytes to strings. * @type {ConversionOptions} */ util.toJSONOptions = { longs: String, enums: String, bytes: String }; util._configure = function() { var Buffer = util.Buffer; /* istanbul ignore if */ if (!Buffer) { util._Buffer_from = util._Buffer_allocUnsafe = null; return; } // because node 4.x buffers are incompatible & immutable // see: https://github.com/dcodeIO/protobuf.js/pull/665 util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || /* istanbul ignore next */ function Buffer_from(value, encoding) { return new Buffer(value, encoding); }; util._Buffer_allocUnsafe = Buffer.allocUnsafe || /* istanbul ignore next */ function Buffer_allocUnsafe(size) { return new Buffer(size); }; }; },{"1":1,"2":2,"37":37,"4":4,"6":6,"8":8,"9":9}],39:[function(require,module,exports){ "use strict"; module.exports = verifier; var Enum = require(15), util = require(36); function invalid(field, expected) { return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; } /** * Generates a partial value verifier. * @param {Codegen} gen Codegen instance * @param {Field} field Reflected field * @param {number} fieldIndex Field index * @param {string} ref Variable reference * @returns {Codegen} Codegen instance * @ignore */ function genVerifyValue(gen, field, fieldIndex, ref) { /* eslint-disable no-unexpected-multiline */ if (field.resolvedType) { if (field.resolvedType instanceof Enum) { gen ("switch(%s){", ref) ("default:") ("return%j", invalid(field, "enum value")); for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen ("case %d:", field.resolvedType.values[keys[j]]); gen ("break") ("}"); } else gen ("var e=types[%d].verify(%s);", fieldIndex, ref) ("if(e)") ("return%j+e", field.name + "."); } else { switch (field.type) { case "int32": case "uint32": case "sint32": case "fixed32": case "sfixed32": gen ("if(!util.isInteger(%s))", ref) ("return%j", invalid(field, "integer")); break; case "int64": case "uint64": case "sint64": case "fixed64": case "sfixed64": gen ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref) ("return%j", invalid(field, "integer|Long")); break; case "float": case "double": gen ("if(typeof %s!==\"number\")", ref) ("return%j", invalid(field, "number")); break; case "bool": gen ("if(typeof %s!==\"boolean\")", ref) ("return%j", invalid(field, "boolean")); break; case "string": gen ("if(!util.isString(%s))", ref) ("return%j", invalid(field, "string")); break; case "bytes": gen ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) ("return%j", invalid(field, "buffer")); break; } } return gen; /* eslint-enable no-unexpected-multiline */ } /** * Generates a partial key verifier. * @param {Codegen} gen Codegen instance * @param {Field} field Reflected field * @param {string} ref Variable reference * @returns {Codegen} Codegen instance * @ignore */ function genVerifyKey(gen, field, ref) { /* eslint-disable no-unexpected-multiline */ switch (field.keyType) { case "int32": case "uint32": case "sint32": case "fixed32": case "sfixed32": gen ("if(!util.key32Re.test(%s))", ref) ("return%j", invalid(field, "integer key")); break; case "int64": case "uint64": case "sint64": case "fixed64": case "sfixed64": gen ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not ("return%j", invalid(field, "integer|Long key")); break; case "bool": gen ("if(!util.key2Re.test(%s))", ref) ("return%j", invalid(field, "boolean key")); break; } return gen; /* eslint-enable no-unexpected-multiline */ } /** * Generates a verifier specific to the specified message type. * @param {Type} mtype Message type * @returns {Codegen} Codegen instance */ function verifier(mtype) { /* eslint-disable no-unexpected-multiline */ var gen = util.codegen("m") ("if(typeof m!==\"object\"||m===null)") ("return%j", "object expected"); for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) { var field = mtype._fieldsArray[i].resolve(), ref = "m" + util.safeProp(field.name); // map fields if (field.map) { gen ("if(%s!==undefined){", ref) ("if(!util.isObject(%s))", ref) ("return%j", invalid(field, "object")) ("var k=Object.keys(%s)", ref) ("for(var i=0;i 127) { buf[pos++] = val & 127 | 128; val >>>= 7; } buf[pos] = val; } /** * Constructs a new varint writer operation instance. * @classdesc Scheduled varint writer operation. * @extends Op * @constructor * @param {number} len Value byte length * @param {number} val Value to write * @ignore */ function VarintOp(len, val) { this.len = len; this.next = undefined; this.val = val; } VarintOp.prototype = Object.create(Op.prototype); VarintOp.prototype.fn = writeVarint32; /** * Writes an unsigned 32 bit value as a varint. * @param {number} value Value to write * @returns {Writer} `this` */ Writer.prototype.uint32 = function write_uint32(value) { // here, the call to this.push has been inlined and a varint specific Op subclass is used. // uint32 is by far the most frequently used operation and benefits significantly from this. this.len += (this.tail = this.tail.next = new VarintOp( (value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, value)).len; return this; }; /** * Writes a signed 32 bit value as a varint. * @function * @param {number} value Value to write * @returns {Writer} `this` */ Writer.prototype.int32 = function write_int32(value) { return value < 0 ? this.push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec : this.uint32(value); }; /** * Writes a 32 bit value as a varint, zig-zag encoded. * @param {number} value Value to write * @returns {Writer} `this` */ Writer.prototype.sint32 = function write_sint32(value) { return this.uint32((value << 1 ^ value >> 31) >>> 0); }; function writeVarint64(val, buf, pos) { while (val.hi) { buf[pos++] = val.lo & 127 | 128; val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; val.hi >>>= 7; } while (val.lo > 127) { buf[pos++] = val.lo & 127 | 128; val.lo = val.lo >>> 7; } buf[pos++] = val.lo; } /** * Writes an unsigned 64 bit value as a varint. * @param {Long|number|string} value Value to write * @returns {Writer} `this` * @throws {TypeError} If `value` is a string and no long library is present. */ Writer.prototype.uint64 = function write_uint64(value) { var bits = LongBits.from(value); return this.push(writeVarint64, bits.length(), bits); }; /** * Writes a signed 64 bit value as a varint. * @function * @param {Long|number|string} value Value to write * @returns {Writer} `this` * @throws {TypeError} If `value` is a string and no long library is present. */ Writer.prototype.int64 = Writer.prototype.uint64; /** * Writes a signed 64 bit value as a varint, zig-zag encoded. * @param {Long|number|string} value Value to write * @returns {Writer} `this` * @throws {TypeError} If `value` is a string and no long library is present. */ Writer.prototype.sint64 = function write_sint64(value) { var bits = LongBits.from(value).zzEncode(); return this.push(writeVarint64, bits.length(), bits); }; /** * Writes a boolish value as a varint. * @param {boolean} value Value to write * @returns {Writer} `this` */ Writer.prototype.bool = function write_bool(value) { return this.push(writeByte, 1, value ? 1 : 0); }; function writeFixed32(val, buf, pos) { buf[pos++] = val & 255; buf[pos++] = val >>> 8 & 255; buf[pos++] = val >>> 16 & 255; buf[pos ] = val >>> 24; } /** * Writes an unsigned 32 bit value as fixed 32 bits. * @param {number} value Value to write * @returns {Writer} `this` */ Writer.prototype.fixed32 = function write_fixed32(value) { return this.push(writeFixed32, 4, value >>> 0); }; /** * Writes a signed 32 bit value as fixed 32 bits. * @function * @param {number} value Value to write * @returns {Writer} `this` */ Writer.prototype.sfixed32 = Writer.prototype.fixed32; /** * Writes an unsigned 64 bit value as fixed 64 bits. * @param {Long|number|string} value Value to write * @returns {Writer} `this` * @throws {TypeError} If `value` is a string and no long library is present. */ Writer.prototype.fixed64 = function write_fixed64(value) { var bits = LongBits.from(value); return this.push(writeFixed32, 4, bits.lo).push(writeFixed32, 4, bits.hi); }; /** * Writes a signed 64 bit value as fixed 64 bits. * @function * @param {Long|number|string} value Value to write * @returns {Writer} `this` * @throws {TypeError} If `value` is a string and no long library is present. */ Writer.prototype.sfixed64 = Writer.prototype.fixed64; var writeFloat = typeof Float32Array !== "undefined" ? (function() { var f32 = new Float32Array(1), f8b = new Uint8Array(f32.buffer); f32[0] = -0; return f8b[3] // already le? ? function writeFloat_f32(val, buf, pos) { f32[0] = val; buf[pos++] = f8b[0]; buf[pos++] = f8b[1]; buf[pos++] = f8b[2]; buf[pos ] = f8b[3]; } /* istanbul ignore next */ : function writeFloat_f32_le(val, buf, pos) { f32[0] = val; buf[pos++] = f8b[3]; buf[pos++] = f8b[2]; buf[pos++] = f8b[1]; buf[pos ] = f8b[0]; }; })() /* istanbul ignore next */ : function writeFloat_ieee754(value, buf, pos) { var sign = value < 0 ? 1 : 0; if (sign) value = -value; if (value === 0) writeFixed32(1 / value > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); else if (isNaN(value)) writeFixed32(2147483647, buf, pos); else if (value > 3.4028234663852886e+38) // +-Infinity writeFixed32((sign << 31 | 2139095040) >>> 0, buf, pos); else if (value < 1.1754943508222875e-38) // denormal writeFixed32((sign << 31 | Math.round(value / 1.401298464324817e-45)) >>> 0, buf, pos); else { var exponent = Math.floor(Math.log(value) / Math.LN2), mantissa = Math.round(value * Math.pow(2, -exponent) * 8388608) & 8388607; writeFixed32((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); } }; /** * Writes a float (32 bit). * @function * @param {number} value Value to write * @returns {Writer} `this` */ Writer.prototype.float = function write_float(value) { return this.push(writeFloat, 4, value); }; var writeDouble = typeof Float64Array !== "undefined" ? (function() { var f64 = new Float64Array(1), f8b = new Uint8Array(f64.buffer); f64[0] = -0; return f8b[7] // already le? ? function writeDouble_f64(val, buf, pos) { f64[0] = val; buf[pos++] = f8b[0]; buf[pos++] = f8b[1]; buf[pos++] = f8b[2]; buf[pos++] = f8b[3]; buf[pos++] = f8b[4]; buf[pos++] = f8b[5]; buf[pos++] = f8b[6]; buf[pos ] = f8b[7]; } /* istanbul ignore next */ : function writeDouble_f64_le(val, buf, pos) { f64[0] = val; buf[pos++] = f8b[7]; buf[pos++] = f8b[6]; buf[pos++] = f8b[5]; buf[pos++] = f8b[4]; buf[pos++] = f8b[3]; buf[pos++] = f8b[2]; buf[pos++] = f8b[1]; buf[pos ] = f8b[0]; }; })() /* istanbul ignore next */ : function writeDouble_ieee754(value, buf, pos) { var sign = value < 0 ? 1 : 0; if (sign) value = -value; if (value === 0) { writeFixed32(0, buf, pos); writeFixed32(1 / value > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + 4); } else if (isNaN(value)) { writeFixed32(4294967295, buf, pos); writeFixed32(2147483647, buf, pos + 4); } else if (value > 1.7976931348623157e+308) { // +-Infinity writeFixed32(0, buf, pos); writeFixed32((sign << 31 | 2146435072) >>> 0, buf, pos + 4); } else { var mantissa; if (value < 2.2250738585072014e-308) { // denormal mantissa = value / 5e-324; writeFixed32(mantissa >>> 0, buf, pos); writeFixed32((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + 4); } else { var exponent = Math.floor(Math.log(value) / Math.LN2); if (exponent === 1024) exponent = 1023; mantissa = value * Math.pow(2, -exponent); writeFixed32(mantissa * 4503599627370496 >>> 0, buf, pos); writeFixed32((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + 4); } } }; /** * Writes a double (64 bit float). * @function * @param {number} value Value to write * @returns {Writer} `this` */ Writer.prototype.double = function write_double(value) { return this.push(writeDouble, 8, value); }; var writeBytes = util.Array.prototype.set ? function writeBytes_set(val, buf, pos) { buf.set(val, pos); // also works for plain array values } /* istanbul ignore next */ : function writeBytes_for(val, buf, pos) { for (var i = 0; i < val.length; ++i) buf[pos + i] = val[i]; }; /** * Writes a sequence of bytes. * @param {Uint8Array|string} value Buffer or base64 encoded string to write * @returns {Writer} `this` */ Writer.prototype.bytes = function write_bytes(value) { var len = value.length >>> 0; if (!len) return this.push(writeByte, 1, 0); if (util.isString(value)) { var buf = Writer.alloc(len = base64.length(value)); base64.decode(value, buf, 0); value = buf; } return this.uint32(len).push(writeBytes, len, value); }; /** * Writes a string. * @param {string} value Value to write * @returns {Writer} `this` */ Writer.prototype.string = function write_string(value) { var len = utf8.length(value); return len ? this.uint32(len).push(utf8.write, len, value) : this.push(writeByte, 1, 0); }; /** * Forks this writer's state by pushing it to a stack. * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. * @returns {Writer} `this` */ Writer.prototype.fork = function fork() { this.states = new State(this); this.head = this.tail = new Op(noop, 0, 0); this.len = 0; return this; }; /** * Resets this instance to the last state. * @returns {Writer} `this` */ Writer.prototype.reset = function reset() { if (this.states) { this.head = this.states.head; this.tail = this.states.tail; this.len = this.states.len; this.states = this.states.next; } else { this.head = this.tail = new Op(noop, 0, 0); this.len = 0; } return this; }; /** * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. * @returns {Writer} `this` */ Writer.prototype.ldelim = function ldelim() { var head = this.head, tail = this.tail, len = this.len; this.reset().uint32(len); if (len) { this.tail.next = head.next; // skip noop this.tail = tail; this.len += len; } return this; }; /** * Finishes the write operation. * @returns {Uint8Array} Finished buffer */ Writer.prototype.finish = function finish() { var head = this.head.next, // skip noop buf = this.constructor.alloc(this.len), pos = 0; while (head) { head.fn(head.val, buf, pos); pos += head.len; head = head.next; } // this.head = this.tail = null; return buf; }; Writer._configure = function(BufferWriter_) { BufferWriter = BufferWriter_; }; },{"38":38}],41:[function(require,module,exports){ "use strict"; module.exports = BufferWriter; // extends Writer var Writer = require(40); (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; var util = require(38); var Buffer = util.Buffer; /** * Constructs a new buffer writer instance. * @classdesc Wire format writer using node buffers. * @extends Writer * @constructor */ function BufferWriter() { Writer.call(this); } /** * Allocates a buffer of the specified size. * @param {number} size Buffer size * @returns {Buffer} Buffer */ BufferWriter.alloc = function alloc_buffer(size) { return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size); }; var writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === "set" ? function writeBytesBuffer_set(val, buf, pos) { buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) // also works for plain array values } /* istanbul ignore next */ : function writeBytesBuffer_copy(val, buf, pos) { if (val.copy) // Buffer values val.copy(buf, pos, 0, val.length); else for (var i = 0; i < val.length;) // plain array values buf[pos++] = val[i++]; }; /** * @override */ BufferWriter.prototype.bytes = function write_bytes_buffer(value) { if (util.isString(value)) value = util._Buffer_from(value, "base64"); var len = value.length >>> 0; this.uint32(len); if (len) this.push(writeBytesBuffer, len, value); return this; }; function writeStringBuffer(val, buf, pos) { if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) util.utf8.write(val, buf, pos); else buf.utf8Write(val, pos); } /** * @override */ BufferWriter.prototype.string = function write_string_buffer(value) { var len = Buffer.byteLength(value); this.uint32(len); if (len) this.push(writeStringBuffer, len, value); return this; }; /** * Finishes the write operation. * @name BufferWriter#finish * @function * @returns {Buffer} Finished buffer */ },{"38":38,"40":40}]},{},[19]) })(typeof window==="object"&&window||typeof self==="object"&&self||this); //# sourceMappingURL=protobuf.js.map ================================================ FILE: public/libs/laya/worker.js ================================================ function testCanImageData(){try{cc=new ImageData(20,20),canUseImageData=!0}catch(t){}}function loadImage(t){PNG.load(t.url,pngLoaded)}function loadImage2(t){var e,a=t.url;e=new XMLHttpRequest,e.open("GET",a,!0),e.responseType="arraybuffer",e.onload=function(){var t,i,r=e.response||e.mozResponseArrayBuffer;if(t=new Uint8Array(r),self.createImageBitmap)return void doCreateImageBitmap(t,a);try{startTime=getTimeNow(),i=new PNG(t),i.url=a,i.startTime=startTime,i.decodeEndTime=getTimeNow(),i.decodeTime=i.decodeEndTime-startTime,pngLoaded(i)}catch(s){pngFail(a,"parse fail"+s.toString()+":ya")}},e.onerror=function(t){pngFail(a,"loadFail")},e.send(null)}function doCreateImageBitmap(t,e){try{var a=getTimeNow();t=new self.Blob([t],{type:"image/png"}),self.createImageBitmap(t).then(function(t){var i={};i.url=e,i.imageBitmap=t,i.dataType="imageBitmap",i.startTime=a,i.decodeTime=getTimeNow()-a,i.sendTime=getTimeNow(),console.log("Decode By createImageBitmap,"+i.decodeTime,e),i.type="Image",postMessage(i,[i.imageBitmap])})["catch"](function(t){showMsgToMain("cache:"+t),pngFail(e,"parse fail"+t+":ya")})}catch(i){pngFail(e,"parse fail"+i.toString()+":ya")}}function getTimeNow(){return(new Date).getTime()}function pngFail(t,e){var a={};a.url=t,a.imagedata=null,a.type="Image",a.msg=e,console.log(e),postMessage(a)}function showMsgToMain(t){var e={};e.type="Msg",e.msg=t,postMessage(e)}function pngLoaded(t){var e={};e.url=t.url,canUseImageData?(e.imagedata=t.getImageData(),e.dataType="imagedata"):(e.buffer=t.getImageDataBuffer(),e.dataType="buffer"),e.width=t.width,e.height=t.height,e.decodeTime=getTimeNow()-t.startTime,console.log("Decode By PNG.js,"+(getTimeNow()-t.startTime),t.url),e.type="Image",canUseImageData?postMessage(e,[e.imagedata.data.buffer]):postMessage(e,[e.buffer.buffer])}var DecodeStream=function(){function t(){this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=null}return t.prototype={ensureBuffer:function(t){var e=this.buffer,a=e?e.byteLength:0;if(a>t)return e;for(var i=512;t>i;)i<<=1;for(var r=new Uint8Array(i),s=0;a>s;++s)r[s]=e[s];return this.buffer=r},getByte:function(){for(var t=this.pos;this.bufferLength<=t;){if(this.eof)return null;this.readBlock()}return this.buffer[this.pos++]},getBytes:function(t){var e=this.pos;if(t){this.ensureBuffer(e+t);for(var a=e+t;!this.eof&&this.bufferLengthi&&(a=i)}else{for(;!this.eof;)this.readBlock();var a=this.bufferLength}return this.pos=a,this.buffer.subarray(e,a)},lookChar:function(){for(var t=this.pos;this.bufferLength<=t;){if(this.eof)return null;this.readBlock()}return String.fromCharCode(this.buffer[this.pos])},getChar:function(){for(var t=this.pos;this.bufferLength<=t;){if(this.eof)return null;this.readBlock()}return String.fromCharCode(this.buffer[this.pos++])},makeSubStream:function(t,e,a){for(var i=t+e;this.bufferLength<=i&&!this.eof;)this.readBlock();return new Stream(this.buffer,t,e,a)},skip:function(t){t||(t=1),this.pos+=t},reset:function(){this.pos=0}},t}(),FlateStream=function(){function t(t){throw new Error(t)}function e(e){var a=0,i=e[a++],r=e[a++];-1!=i&&-1!=r||t("Invalid header in flate stream"),8!=(15&i)&&t("Unknown compression method in flate stream"),((i<<8)+r)%31!=0&&t("Bad FCHECK in flate stream"),32&r&&t("FDICT bit set in flate stream"),this.bytes=e,this.bytesPos=a,this.codeSize=0,this.codeBuf=0,DecodeStream.call(this)}var a=new Uint32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),i=new Uint32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),r=new Uint32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),s=[new Uint32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],n=[new Uint32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];return e.prototype=Object.create(DecodeStream.prototype),e.prototype.getBits=function(e){for(var a,i=this.codeSize,r=this.codeBuf,s=this.bytes,n=this.bytesPos;e>i;)"undefined"==typeof(a=s[n++])&&t("Bad encoding in flate stream"),r|=a<>e,this.codeSize=i-=e,this.bytesPos=n,a},e.prototype.getCode=function(e){for(var a=e[0],i=e[1],r=this.codeSize,s=this.codeBuf,n=this.bytes,o=this.bytesPos;i>r;){var h;"undefined"==typeof(h=n[o++])&&t("Bad encoding in flate stream"),s|=h<>16,c=65535&f;return(0==r||d>r||0==d)&&t("Bad encoding in flate stream"),this.codeBuf=s>>d,this.codeSize=r-d,this.bytesPos=o,c},e.prototype.generateHuffmanTable=function(t){for(var e=t.length,a=0,i=0;e>i;++i)t[i]>a&&(a=t[i]);for(var r=1<=n;++n,o<<=1,h<<=1)for(var f=0;e>f;++f)if(t[f]==n){for(var d=0,c=o,i=0;n>i;++i)d=d<<1|1&c,c>>=1;for(var i=d;r>i;i+=h)s[i]=n<<16|f;++o}return[s,a]},e.prototype.readBlock=function(){function e(t,e,a,i,r){for(var s=t.getBits(a)+i;s-- >0;)e[I++]=r}var o=this.getBits(3);if(1&o&&(this.eof=!0),o>>=1,0==o){var h,f=this.bytes,d=this.bytesPos;"undefined"==typeof(h=f[d++])&&t("Bad block header in flate stream");var c=h;"undefined"==typeof(h=f[d++])&&t("Bad block header in flate stream"),c|=h<<8,"undefined"==typeof(h=f[d++])&&t("Bad block header in flate stream");var l=h;"undefined"==typeof(h=f[d++])&&t("Bad block header in flate stream"),l|=h<<8,l!=(65535&~c)&&t("Bad uncompressed block length in flate stream"),this.codeBuf=0,this.codeSize=0;var u=this.bufferLength,p=this.ensureBuffer(u+c),g=u+c;this.bufferLength=g;for(var m=u;g>m;++m){if("undefined"==typeof(h=f[d++])){this.eof=!0;break}p[m]=h}return void(this.bytesPos=d)}var y,v;if(1==o)y=s,v=n;else if(2==o){for(var b=this.getBits(5)+257,w=this.getBits(5)+1,B=this.getBits(4)+4,T=Array(a.length),I=0;B>I;)T[a[I++]]=this.getBits(3);for(var U=this.generateHuffmanTable(T),D=0,I=0,k=b+w,A=new Array(k);k>I;){var C=this.getCode(U);16==C?e(this,A,2,3,D):17==C?e(this,A,3,3,D=0):18==C?e(this,A,7,11,D=0):A[I++]=D=C}y=this.generateHuffmanTable(A.slice(0,b)),v=this.generateHuffmanTable(A.slice(b,k))}else t("Unknown block type in flate stream");for(var p=this.buffer,S=p?p.length:0,P=this.bufferLength;;){var M=this.getCode(y);if(256>M)P+1>=S&&(p=this.ensureBuffer(P+1),S=p.length),p[P++]=M;else{if(256==M)return void(this.bufferLength=P);M-=257,M=i[M];var L=M>>16;L>0&&(L=this.getBits(L));var D=(65535&M)+L;M=this.getCode(v),M=r[M],L=M>>16,L>0&&(L=this.getBits(L));var x=(65535&M)+L;P+D>=S&&(p=this.ensureBuffer(P+D),S=p.length);for(var N=0;D>N;++N,++P)p[P]=p[P-x]}}},e}();(function(){var t;t=function(){function t(t){var e,a,i,r,s,n,o,h,f,d,c,l,u,p;for(this.data=t,this.pos=8,this.palette=[],this.imgData=[],this.transparency={},this.animation=null,this.text={},s=null;;){switch(e=this.readUInt32(),f=function(){var t,e;for(e=[],n=t=0;4>t;n=++t)e.push(String.fromCharCode(this.data[this.pos++]));return e}.call(this).join("")){case"IHDR":if(this.width=this.readUInt32(),this.height=this.readUInt32(),this.bits=this.data[this.pos++],this.colorType=this.data[this.pos++],this.compressionMethod=this.data[this.pos++],this.filterMethod=this.data[this.pos++],this.interlaceMethod=this.data[this.pos++],0!=this.interlaceMethod)throw new Error("Invalid interlaceMethod: "+this.interlaceMethod);break;case"acTL":this.animation={numFrames:this.readUInt32(),numPlays:this.readUInt32()||1/0,frames:[]};break;case"PLTE":this.palette=this.read(e);break;case"fcTL":s&&this.animation.frames.push(s),this.pos+=4,s={width:this.readUInt32(),height:this.readUInt32(),xOffset:this.readUInt32(),yOffset:this.readUInt32()},r=this.readUInt16(),i=this.readUInt16()||100,s.delay=1e3*r/i,s.disposeOp=this.data[this.pos++],s.blendOp=this.data[this.pos++],s.data=[];break;case"IDAT":case"fdAT":for("fdAT"===f&&(this.pos+=4,e-=4),t=(null!=s?s.data:void 0)||this.imgData,n=l=0;e>=0?e>l:l>e;n=e>=0?++l:--l)t.push(this.data[this.pos++]);break;case"tRNS":switch(this.transparency={},this.colorType){case 3:if(this.transparency.indexed=this.read(e),d=255-this.transparency.indexed.length,d>0)for(n=u=0;d>=0?d>u:u>d;n=d>=0?++u:--u)this.transparency.indexed.push(255);break;case 0:this.transparency.grayscale=this.read(e)[0];break;case 2:this.transparency.rgb=this.read(e)}break;case"tEXt":c=this.read(e),o=c.indexOf(0),h=String.fromCharCode.apply(String,c.slice(0,o)),this.text[h]=String.fromCharCode.apply(String,c.slice(o+1));break;case"IEND":return s&&this.animation.frames.push(s),this.colors=function(){switch(this.colorType){case 0:case 3:case 4:return 1;case 2:case 6:return 3}}.call(this),this.hasAlphaChannel=4===(p=this.colorType)||6===p,a=this.colors+(this.hasAlphaChannel?1:0),this.pixelBitlength=this.bits*a,this.colorSpace=function(){switch(this.colors){case 1:return"DeviceGray";case 3:return"DeviceRGB"}}.call(this),void(this.imgData=new Uint8Array(this.imgData));default:this.pos+=e}if(this.pos+=4,this.pos>this.data.length)throw new Error("Incomplete or corrupt PNG file")}}var e,a,i,r,s,n;return t.load=function(e,a){var i;return"function"==typeof canvas&&(a=canvas),i=new XMLHttpRequest,i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(){var r,s;return r=new Uint8Array(i.response||i.mozResponseArrayBuffer),s=new t(r),s.url=e,"function"==typeof a?a(s):void 0},i.send(null)},r=0,i=1,s=2,a=0,e=1,t.prototype.read=function(t){var e,a,i;for(i=[],e=a=0;t>=0?t>a:a>t;e=t>=0?++a:--a)i.push(this.data[this.pos++]);return i},t.prototype.readUInt32=function(){var t,e,a,i;return t=this.data[this.pos++]<<24,e=this.data[this.pos++]<<16,a=this.data[this.pos++]<<8,i=this.data[this.pos++],t|e|a|i},t.prototype.readUInt16=function(){var t,e;return t=this.data[this.pos++]<<8,e=this.data[this.pos++],t|e},t.prototype.decodePixels=function(t){var e,a,i,r,s,n,o,h,f,d,c,l,u,p,g,m,y,v,b,w,B,T,I;if(null==t&&(t=this.imgData),0===t.length)return new Uint8Array(0);for(t=new FlateStream(t),t=t.getBytes(),l=this.pixelBitlength/8,m=l*this.width,u=new Uint8Array(m*this.height),n=t.length,g=0,p=0,a=0;n>p;){switch(t[p++]){case 0:for(r=b=0;m>b;r=b+=1)u[a++]=t[p++];break;case 1:for(r=w=0;m>w;r=w+=1)e=t[p++],s=l>r?0:u[a-l],u[a++]=(e+s)%256;break;case 2:for(r=B=0;m>B;r=B+=1)e=t[p++],i=(r-r%l)/l,y=g&&u[(g-1)*m+i*l+r%l],u[a++]=(y+e)%256;break;case 3:for(r=T=0;m>T;r=T+=1)e=t[p++],i=(r-r%l)/l,s=l>r?0:u[a-l],y=g&&u[(g-1)*m+i*l+r%l],u[a++]=(e+Math.floor((s+y)/2))%256;break;case 4:for(r=I=0;m>I;r=I+=1)e=t[p++],i=(r-r%l)/l,s=l>r?0:u[a-l],0===g?y=v=0:(y=u[(g-1)*m+i*l+r%l],v=i&&u[(g-1)*m+(i-1)*l+r%l]),o=s+y-v,h=Math.abs(o-s),d=Math.abs(o-y),c=Math.abs(o-v),f=d>=h&&c>=h?s:c>=d?y:v,u[a++]=(e+f)%256;break;default:throw new Error("Invalid filter algorithm: "+t[p-1])}g++}return u},t.prototype.decodePalette=function(){var t,e,a,i,r,s,n,o,h,f;i=this.palette,n=this.transparency.indexed||[];var d;for(d=4*i.length/3,s=new Uint8Array(d),r=0,a=i.length,t=0,e=o=0,h=i.length;h>o;e=o+=3)s[r++]=i[e],s[r++]=i[e+1],s[r++]=i[e+2],s[r++]=null!=(f=n[t++])?f:255;return s},t.prototype.getImageData=function(){var t=new self.ImageData(this.width,this.height);return this.copyToImageData(t,this.decodePixels()),t},t.prototype.getImageDataBuffer=function(){var t;return t=self.Uint8ClampedArray?new self.Uint8ClampedArray(this.width*this.height*4):new self.Uint8Array(this.width*this.height*4),this.copyToImageData(t,this.decodePixels()),t},t.prototype.copyToImageData=function(t,e){var a,i,r,s,n,o,h,f,d,c,l;if(i=this.colors,d=null,a=this.hasAlphaChannel,this.palette.length&&(d=null!=(l=this._decodedPalette)?l:this._decodedPalette=this.decodePalette(),i=4,a=!0),r=t.data||t,f=r.length,n=d||e,s=o=0,1===i)for(;f>s;)h=d?4*e[s/4]:o,c=n[h++],r[s++]=c,r[s++]=c,r[s++]=c,r[s++]=a?n[h++]:255,o=h;else for(;f>s;)h=d?4*e[s/4]:o,r[s++]=n[h++],r[s++]=n[h++],r[s++]=n[h++],r[s++]=a?n[h++]:255,o=h},t.prototype.decode=function(){var t;return t=new Uint8Array(this.width*this.height*4),this.copyToImageData(t,this.decodePixels()),t},t.prototype.decodeFrames=function(t){var e,a,i,r,s,o,h,f;if(this.animation){for(h=this.animation.frames,f=[],a=s=0,o=h.length;o>s;a=++s)e=h[a],i=t.createImageData(e.width,e.height),r=this.decodePixels(new Uint8Array(e.data)),this.copyToImageData(i,r),e.imageData=i,f.push(e.image=n(i));return f}},t}(),this.PNG=t}).call(this),onmessage=function(t){var e=t.data;switch(e.type){case"load":loadImage2(e)}};var canUseImageData=!1;testCanImageData(); ================================================ FILE: public/particle/fly.part ================================================ {"textureName":"images/texture/texture_1.png","positionVariance":{"0":0,"1":0,"2":0},"minVerticalVelocity":-100,"minVerticalEndRadian":0,"minStartSize":0,"minStartRadius":0,"minRotateSpeed":0,"minHorizontalVelocity":100,"minHorizontalEndRadian":0,"minEndSize":18.55,"minEndRadius":218.75,"minColor":{"0":0.15,"1":0.92,"2":0.91,"3":0.6000000238418579},"maxVerticalVelocity":100,"maxVerticalEndRadian":0,"maxStartSize":2.04,"maxStartRadius":0,"maxRotateSpeed":0,"maxPartices":400,"maxHorizontalVelocity":100,"maxHorizontalEndRadian":0,"maxEndSize":24.35,"maxEndRadius":84.82,"maxColor":{"0":0.57,"1":1,"2":0,"3":1},"gravity":{"0":0,"1":0,"2":0},"endVelocity":2,"emitterVelocitySensitivity":56.89,"duration":9.52,"colorComponentInter":true,"blendState":0,"ageAddScale":10,"backColor":"#ffffff","textureFileName":"comp\\clip_num.png","textureCount":1,"minHorizontalStartRadian":0,"maxHorizontalStartRadian":0,"minVerticalStartRadian":0,"maxVerticalStartRadian":0,"emitterType":"null","emissionRate":0,"sphereEmitterRadius":1,"sphereEmitterVelocity":0,"sphereEmitterVelocityAddVariance":0,"ringEmitterRadius":30,"ringEmitterVelocity":0,"ringEmitterVelocityAddVariance":0,"ringEmitterUp":2,"minStartColor":{"0":0.5,"1":0.5,"2":0.5,"3":0.2},"maxStartColor":{"0":1,"1":1,"2":1,"3":1},"minEndColor":{"0":0,"1":0,"2":0,"3":0.08},"maxEndColor":{"0":1,"1":1,"2":1,"3":1},"pointEmitterPosition":{"0":0,"1":0,"2":0},"pointEmitterPositionVariance":{"0":0,"1":0,"2":0},"pointEmitterVelocity":{"0":0,"1":0,"2":0},"pointEmitterVelocityAddVariance":{"0":0,"1":0,"2":0},"boxEmitterCenterPosition":{"0":0,"1":0,"2":0},"boxEmitterSize":{"0":0,"1":0,"2":0},"boxEmitterVelocity":{"0":0,"1":0,"2":0},"boxEmitterVelocityAddVariance":{"0":0,"1":0,"2":0},"sphereEmitterCenterPosition":{"0":0,"1":0,"2":0},"ringEmitterCenterPosition":{"0":0,"1":0,"2":0},"useEndRadian":true,"disableColor":false} ================================================ FILE: public/unpack.json ================================================ ["images/accessories/insert_coin@3x.png","images/accessories/title@3x.png","images/accessories/titlebar@3x.png","images/accessories/title_neon@3x.png","images/background/background_1@3x.png","images/background/background_2@3x.png","images/border/achievement_complete@3x.png","images/border/border_1@3x.png","images/border/border_2@3x.png","images/border/card@3x.png","images/border/talent_item@3x.png","images/border/talent_item_selected@3x.png","images/border/up@3x.png","images/button/button_main@3x.png","images/slider/vslider_1@3x$bar.png","images/slider/vslider_1@3x.png"] ================================================ FILE: public/view/CyberTheme/animation/bottomBreath.ani ================================================ {"type":"View","props":{"sceneWidth":200,"sceneHeight":200,"sceneColor":"#000000"},"compId":1,"child":[{"type":"GraphicNode","props":{},"compId":2}],"animations":[{"nodes":[{"target":2,"keyframes":{"y":[{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"y","index":0}],"x":[{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"x","index":0}],"skin":[{"value":"images/resource/bottombreath.png","tweenMethod":"linearNone","tween":false,"target":2,"key":"skin","index":0}],"anchorY":[{"value":1,"tweenMethod":"linearNone","tween":true,"target":2,"key":"anchorY","index":0}],"anchorX":[{"value":0.5,"tweenMethod":"linearNone","tween":true,"target":2,"key":"anchorX","index":0}],"alpha":[{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"alpha","index":0},{"value":0.5,"tweenMethod":"linearNone","tween":true,"target":2,"key":"alpha","index":36},{"value":1,"tweenMethod":"linearNone","tween":true,"target":2,"key":"alpha","index":48},{"value":0.8,"tweenMethod":"linearNone","tween":true,"target":2,"key":"alpha","index":96},{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"alpha","index":120}]}}],"name":"ani1","id":1,"frameRate":24,"action":0}]} ================================================ FILE: public/view/CyberTheme/animation/circleFlash.ani ================================================ {"type":"View","props":{"sceneWidth":200,"sceneHeight":200,"sceneColor":"#000000"},"compId":1,"child":[{"type":"GraphicNode","props":{},"compId":2}],"animations":[{"nodes":[{"target":2,"keyframes":{"y":[{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"y","index":0}],"x":[{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"x","index":0}],"skin":[{"value":"images/resource/circleflash.png","tweenMethod":"linearNone","tween":false,"target":2,"key":"skin","index":0}],"skewX":[{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"skewX","index":0}],"scaleX":[{"value":-1,"tweenMethod":"linearNone","tween":true,"target":2,"key":"scaleX","index":0}],"rotation":[{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":0},{"value":-90,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":10},{"value":-135,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":15},{"value":-270,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":20},{"value":-360,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":25},{"value":-650,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":35},{"value":-680,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":37},{"value":-710,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":39},{"value":-720,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":41}],"anchorY":[{"value":0.5,"tweenMethod":"linearNone","tween":true,"target":2,"key":"anchorY","index":0}],"anchorX":[{"value":0.5,"tweenMethod":"linearNone","tween":true,"target":2,"key":"anchorX","index":0}]}}],"name":"ani1","id":1,"frameRate":24,"action":0}]} ================================================ FILE: public/view/CyberTheme/animation/jumpBackground.ani ================================================ {"type":"View","props":{"sceneWidth":200,"sceneHeight":200,"sceneColor":"#000000"},"compId":1,"child":[{"type":"GraphicNode","props":{},"compId":3}],"animations":[{"nodes":[{"target":3,"keyframes":{"y":[{"value":-13,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":0},{"value":-13,"tweenMethod":"strongOut","tween":true,"target":3,"key":"y","index":2},{"value":-5,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":3},{"value":-3,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":5},{"value":-15,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":6},{"value":-15,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":9},{"value":3,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":10},{"value":-14,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":11},{"value":-14,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":15},{"value":-22,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":16},{"value":-22,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":19},{"value":-13,"tweenMethod":"linearNone","tween":true,"target":3,"key":"y","index":20}],"x":[{"value":-18,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":0},{"value":-18,"tweenMethod":"strongOut","tween":true,"target":3,"key":"x","index":2},{"value":-3,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":3},{"value":-5,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":5},{"value":-16,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":6},{"value":-12,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":9},{"value":0,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":10},{"value":-8,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":11},{"value":-8,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":15},{"value":-11,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":16},{"value":-11,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":19},{"value":-18,"tweenMethod":"linearNone","tween":true,"target":3,"key":"x","index":20}],"skin":[{"value":"images/background/background_1@3x.png","tweenMethod":"linearNone","tween":false,"target":3,"key":"skin","index":0}],"scaleY":[{"value":1.01,"tweenMethod":"linearNone","tween":true,"target":3,"key":"scaleY","index":0}],"scaleX":[{"value":1.01,"tweenMethod":"linearNone","tween":true,"target":3,"key":"scaleX","index":0}]}}],"name":"ani1","id":1,"frameRate":24,"action":0}]} ================================================ FILE: public/view/CyberTheme/animation/lightRotation.ani ================================================ {"type":"View","props":{"sceneWidth":600,"sceneHeight":400,"sceneColor":"#000000"},"compId":1,"child":[{"type":"GraphicNode","props":{},"compId":2}],"animations":[{"nodes":[{"target":2,"keyframes":{"y":[{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"y","index":0}],"x":[{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"x","index":0}],"width":[{"value":1715,"tweenMethod":"linearNone","tween":true,"target":2,"key":"width","index":0}],"skin":[{"value":"images/background/background_2@3x.png","tweenMethod":"linearNone","tween":false,"target":2,"key":"skin","index":0}],"rotation":[{"value":0,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":0},{"value":360,"tweenMethod":"linearNone","tween":true,"target":2,"key":"rotation","index":279}],"pivotY":[{"value":862,"tweenMethod":"linearNone","tween":true,"target":2,"key":"pivotY","index":0}],"pivotX":[{"value":868,"tweenMethod":"linearNone","tween":true,"target":2,"key":"pivotX","index":0}],"height":[{"value":1716,"tweenMethod":"linearNone","tween":true,"target":2,"key":"height","index":0}]}}],"name":"ani1","id":1,"frameRate":24,"action":0}]} ================================================ FILE: repl/app.js ================================================ import { fileURLToPath } from 'url' import { dirname } from 'path' const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename) import { readFile } from 'fs/promises' import Life from '../src/modules/life.js' import $lang from '../src/i18n/zh-cn.js' globalThis.$lang = $lang globalThis.json = async fileName => JSON.parse(await readFile(`${__dirname}/../public/data/${fileName}.json`)) globalThis.$$eventMap = new Map() globalThis.$$event = (tag, data) => { const listener = $$eventMap.get(tag) if (listener) listener.forEach(fn => fn(data)) } globalThis.$$on = (tag, fn) => { let listener = $$eventMap.get(tag) if (!listener) { listener = new Set() $$eventMap.set(tag, listener) } listener.add(fn) } globalThis.$$off = (tag, fn) => { const listener = $$eventMap.get(tag) if (listener) listener.delete(fn) } class App { constructor() { this.#life.config({ defaultPropertyPoints: 20, // default number of points for a property talentSelectLimit: 3, // max number of talents that can be selected propertyAllocateLimit: [0, 10], // scoop of properties that can be allocated, defaultPropertys: { SPR: 5 }, // default properties talentConfig: { // config for talent talentPullCount: 10, // number of talents to pull from the talent pool talentRate: { 1: 100, 2: 10, 3: 1, total: 1000 }, // rate of talent pull additions: { TMS: [ [10, { 2: 1 }], [30, { 2: 2 }], [50, { 2: 3 }], [70, { 2: 4 }], [100, { 2: 5 }], ], CACHV: [ [10, { 2: 1 }], [30, { 2: 2 }], [50, { 2: 3 }], [70, { 2: 4 }], [100, { 2: 5 }], ], }, }, propertyConfig: { // config for property judge: { // type: [min, grade, judge] RTLT: [ [0, 0], [0.3, 1], [0.6, 2], [0.9, 3], ], REVT: [ [0, 0], [0.2, 1], [0.4, 2], [0.6, 3], ], TMS: [ [0, 0, 'UI_Remake_Times_Judge_Level_0'], [10, 1, 'UI_Remake_Times_Judge_Level_1'], [30, 1, 'UI_Remake_Times_Judge_Level_2'], [50, 2, 'UI_Remake_Times_Judge_Level_3'], [70, 2, 'UI_Remake_Times_Judge_Level_4'], [100, 3, 'UI_Remake_Times_Judge_Level_5'], ], CACHV: [ [0, 0, 'UI_Achievement_Count_Judge_Level_0'], [10, 1, 'UI_Achievement_Count_Judge_Level_1'], [30, 1, 'UI_Achievement_Count_Judge_Level_2'], [50, 2, 'UI_Achievement_Count_Judge_Level_3'], [70, 2, 'UI_Achievement_Count_Judge_Level_4'], [100, 3, 'UI_Achievement_Count_Judge_Level_5'], ], HCHR: [ [0, 0, 'UI_Judge_Level_0'], [1, 0, 'UI_Judge_Level_1'], [2, 0, 'UI_Judge_Level_2'], [4, 0, 'UI_Judge_Level_3'], [7, 1, 'UI_Judge_Level_4'], [9, 2, 'UI_Judge_Level_5'], [11, 3, 'UI_Judge_Level_6'], ], HMNY: [ [0, 0, 'UI_Judge_Level_0'], [1, 0, 'UI_Judge_Level_1'], [2, 0, 'UI_Judge_Level_2'], [4, 0, 'UI_Judge_Level_3'], [7, 1, 'UI_Judge_Level_4'], [9, 2, 'UI_Judge_Level_5'], [11, 3, 'UI_Judge_Level_6'], ], HSPR: [ [0, 0, 'UI_Spirit_Judge_Level_0'], [1, 0, 'UI_Spirit_Judge_Level_1'], [2, 0, 'UI_Spirit_Judge_Level_2'], [4, 0, 'UI_Spirit_Judge_Level_3'], [7, 1, 'UI_Spirit_Judge_Level_4'], [9, 2, 'UI_Spirit_Judge_Level_5'], [11, 3, 'UI_Spirit_Judge_Level_6'], ], HINT: [ [0, 0, 'UI_Judge_Level_0'], [1, 0, 'UI_Judge_Level_1'], [2, 0, 'UI_Judge_Level_2'], [4, 0, 'UI_Judge_Level_3'], [7, 1, 'UI_Judge_Level_4'], [9, 2, 'UI_Judge_Level_5'], [11, 3, 'UI_Judge_Level_6'], [21, 3, 'UI_Intelligence_Judge_Level_7'], [131, 3, 'UI_Intelligence_Judge_Level_8'], [501, 3, 'UI_Intelligence_Judge_Level_9'], ], HSTR: [ [0, 0, 'UI_Judge_Level_0'], [1, 0, 'UI_Judge_Level_1'], [2, 0, 'UI_Judge_Level_2'], [4, 0, 'UI_Judge_Level_3'], [7, 1, 'UI_Judge_Level_4'], [9, 2, 'UI_Judge_Level_5'], [11, 3, 'UI_Judge_Level_6'], [21, 3, 'UI_Strength_Judge_Level_7'], [101, 3, 'UI_Strength_Judge_Level_8'], [401, 3, 'UI_Strength_Judge_Level_9'], [1001, 3, 'UI_Strength_Judge_Level_10'], [2001, 3, 'UI_Strength_Judge_Level_11'], ], HAGE: [ [0, 0, 'UI_AGE_Judge_Level_0'], [1, 0, 'UI_AGE_Judge_Level_1'], [10, 0, 'UI_AGE_Judge_Level_2'], [18, 0, 'UI_AGE_Judge_Level_3'], [40, 0, 'UI_AGE_Judge_Level_4'], [60, 1, 'UI_AGE_Judge_Level_5'], [70, 1, 'UI_AGE_Judge_Level_6'], [80, 2, 'UI_AGE_Judge_Level_7'], [90, 2, 'UI_AGE_Judge_Level_8'], [95, 3, 'UI_AGE_Judge_Level_9'], [100, 3, 'UI_AGE_Judge_Level_10'], [500, 3, 'UI_AGE_Judge_Level_11'], ], SUM: [ [0, 0, 'UI_Judge_Level_0'], [41, 0, 'UI_Judge_Level_1'], [50, 0, 'UI_Judge_Level_2'], [60, 0, 'UI_Judge_Level_3'], [80, 1, 'UI_Judge_Level_4'], [100, 2, 'UI_Judge_Level_5'], [110, 3, 'UI_Judge_Level_6'], [120, 3, 'UI_Judge_Level_7'], ], }, }, characterConfig: { // config for character characterPullCount: 3, rateableKnife: 10, propertyWeight: [ [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 5], [7, 4], [8, 3], [9, 2], [10, 1], ], talentWeight: [ [1, 1], [2, 2], [3, 3], [4, 2], [5, 1], ], }, }) } Steps = { TALENT: 'talent', PROPERTY: 'property', TRAJECTORY: 'trajectory', SUMMARY: 'summary', } #language = 'zh-cn' #step = this.Steps.SUMMARY #life = new Life() #talentSelected = new Set() #talentExtend = new Set() #auto #isEnd #propertyAllocation #output #exit #interval #style = { warn: ['\x1B[93m', '\x1B[39m'], // Bright Yellow grade1: ['\x1B[94m', '\x1B[39m'], // Bright Blue grade2: ['\x1B[95m', '\x1B[39m'], // Bright Magenta grade3: ['\x1B[93m', '\x1B[39m'], // Bright Yellow grade1b: ['\x1B[94m\x1B[7m', '\x1B[0m'], // Bright Blue BG grade2b: ['\x1B[95m\x1B[7m', '\x1B[0m'], // Bright Magenta BG grade3b: ['\x1B[93m\x1B[7m', '\x1B[0m'], // Bright Yellow BG } #randomTalents style(type, str) { const style = this.#style[type] if (!style) return str return `${style[0]}${str}${style[1]}` } async initial() { this.output('Now Loading...') this.#talentExtend = localStorage.talentExtend await this.#life.initial( dataSet => json(`${this.#language}/${dataSet}`), json ) this.output( `\rLoading Complete. 人生重开模拟器 这垃圾人生一秒也不想待了 键入 \x1B[4m/remake\x1B[24m 开始游戏 键入 \x1B[4m/help\x1B[24m 获取帮助`, true ) $$on('achievement', ({ name }) => this.output(` ------------------------- 解锁成就【${name}】 ------------------------- `) ) } io(input, output, exit) { this.#output = output this.#exit = exit input(command => { const ret = this.repl(command) if (!ret) return if (typeof ret == 'string') return this.output(ret, true) if (Array.isArray(ret)) return this.output(...ret) const { message, isRepl } = ret return this.output(message, isRepl) }) } output(data, isRepl) { if (!this.#output) return this.#output(data, isRepl) } exit(code) { if (this.#exit) this.#exit(code) process.exit(code) } repl(command) { command = command.split(/\s+/) switch (command.shift()) { case 'r': case 'remake': case '/remake': return this.remake() case 's': case 'select': case '/select': return this.select(...command) case 'u': case 'unselect': case '/unselect': return this.unselect(...command) case 'n': case 'next': case '/next': case '': return this.next(true) case 'a': case 'alloc': case 'allocate': case 'attrib': case 'attribute': case '/alloc': case '/allocate': case '/attrib': case '/attribute': return this.attrib(...command) case 'rd': case 'random': case '/random': return this.random() case 'at': case 'auto': case '/auto': return this.auto(...command) case 'x': case 'exit': case '/exit': return this.exit(0) case '?': case 'h': case 'help': case '/?': case '/h': case '/help': default: return this.help(...command) } } help(key) { switch (key) { case 'x': case 'exit': case '/exit': return `退出 x, exit, /exit 命令同等效果` case 'r': case 'remake': case '/remake': return `重开 r, remake, /remake 命令同等效果` case 's': case 'select': case '/select': return `选择 s, select, /select 命令同等效果 Example: /select 1 2 3 意味着选择 1 2 3 三个天赋 /select [id2] [id3] 参数解释 通常来说要指定至少一个id 虽然不指定也可以 [id2] [id3] 可以不指定` case 'u': case 'unselect': case '/unselect': return `取消选择 u, unselect, /unselect 命令同等效果 Example: /unselect 1 2 3 意味着取消选择 1 2 3 三个天赋 参数解释 /unselect [id2] [id3] 通常来说要指定至少一个id 虽然不指定也可以 [id2] [id3] 可以不指定` case 'a': case 'alloc': case 'allocate': case 'attrib': case 'attribute': case '/alloc': case '/allocate': case '/attrib': case '/attribute': return `分配或查看属性点 a, alloc, allocate, attrib, attribute /alloc, /allocate, /attrib, /attribute 命令同等效果 Example: /attribute /allocate STR 1 /allocate INT -3 /allocate CHR +5 效果 在属性分配时分配属性点 在人生的过程中查看当前属性点 参数解释 /allocate <[+/-]value> 表示要分配的属性标签 可选有 CHR, chr, c, C 表示颜值 INT, int, i, I 表示智力 STR, str, s, S 表示体质 MNY, mny, m, M 表示家境 必填 <[+/-]value> 表示属性的调整 其中 + 表示在当前基础上增加 - 表示在当前基础上减少 无符号表示直接设置为此值 必填` case 'n': case 'next': case '/next': return `继续 n, next, /next 命令同等效果 效果 通常用于各步骤结束后 例如: 选择天赋后 分配属性后 每个年龄事件后 总评后 继承天赋后` case 'at': case 'auto': case '/auto': return `自动播放 at, auto, /auto 命令同等效果 效果 用于人生的过程中 每个年龄会自动下一年 播放速度 1 秒 1 年` case '?': case 'h': case 'help': case '/?': case '/h': case '/help': return `显示帮助 ?, h, help /?, /h, /help 命令同等效果 Example: /help /help /select 参数解释 /help [command] [command] 要详细显示帮助的命令 可以不填` } return `Help --- 命令 说明 示例 x exit /exit 退出 /exit r remake /remake 重开 /remake s select /select 选择天赋 /select [id2] [id3] u unselect /unselect 取消选择 /unselect [id2] [id3] a alloc allocate attrib attribute /alloc /allocate /attrib /attribute 分配或查看属性点 /allocate <[+/-]value> n next /next 继续 /next at auto /auto 自动播放 /auto ? h help /? /h /help 显示帮助 /help [command]` } auto(arg) { this.#auto = arg != 'off' return this.next(true) } remake() { if (this.#talentExtend) { this.#life.talentExtend(this.#talentExtend) dumpLocalStorage() this.#talentExtend = null } this.#isEnd = false this.#talentSelected.clear() this.#propertyAllocation = { CHR: 0, INT: 0, STR: 0, MNY: 0, SPR: 5, } this.#step = this.Steps.TALENT this.#randomTalents = this.#life.talentRandom() return this.list() } select(...select) { switch (this.#step) { case this.Steps.TALENT: return this.talentSelect(...select) case this.Steps.SUMMARY: return this.talentExtend(...select) } } unselect(...select) { switch (this.#step) { case this.Steps.TALENT: return this.talentUnSelect(...select) case this.Steps.SUMMARY: return this.talentExtendCancle(...select) } } talentSelect(...select) { const warn = str => `${this.list()}\n${this.style('warn', str)}` for (const number of select) { const s = this.#randomTalents[number] if (!s) return warn(`${number} 为未知天赋`) if (this.#talentSelected.has(s)) continue if (this.#talentSelected.size == 3) return warn( '你只能选3个天赋。请使用 \x1B[4m/unselect\x1B[24m 取消选择你不想要的天赋' ) const exclusive = this.#life.exclude( Array.from(this.#talentSelected).map(({ id }) => id), s.id ) if (exclusive != null) for (const { name, id } of this.#talentSelected) if (id == exclusive) return warn( `天赋【${s.name}】与已选择的天赋【${name}】冲突` ) this.#talentSelected.add(s) } return this.list() } talentUnSelect(...select) { for (const number of select) { const s = this.#randomTalents[number] if (this.#talentSelected.has(s)) this.#talentSelected.delete(s) } return this.list() } talentExtend(select) { const warn = str => `${this.list()}\n${this.style('warn', str)}` const list = Array.from(this.#talentSelected) const s = list[select] if (!s) return warn(`${select} 为未知天赋`) this.#talentExtend = s.id return this.list() } talentExtendCancle() { this.#talentExtend = null return this.list() } list() { let description, list, check switch (this.#step) { case this.Steps.TALENT: description = '🎉 请选择(\x1B[4m/select\x1B[24m)3 个天赋' list = this.#randomTalents check = talent => this.#talentSelected.has(talent) break case this.Steps.SUMMARY: description = '🎉 你可以选(\x1B[4m/select\x1B[24m)一个天赋继承' list = Array.from(this.#talentSelected) check = ({ id }) => this.#talentExtend == id break } if (!list) return '' return [ description, list.map((talent, i) => this.style( `grade${talent.grade}b`, `${check(talent) ? '√' : ' '} ${i} ${talent.name}(${ talent.description })` ) ), ] .flat() .join('\n') } next(enter) { const warn = (a, b) => `${a}\n${this.style('warn', this.style('warn', b))}` switch (this.#step) { case this.Steps.TALENT: if (this.#talentSelected.size != 3) return warn(this.list(), `请选择 3 个天赋`) this.#step = this.Steps.PROPERTY this.#life.remake( Array.from(this.#talentSelected).map(({ id }) => id) ) this.#propertyAllocation.total = this.#life.getPropertyPoints() return this.prop() case this.Steps.PROPERTY: const less = this.less() if (less > 0) return warn(this.prop(), `你还有 ${less} 属性点没有分配完`) this.#step = this.Steps.TRAJECTORY delete this.#propertyAllocation.total this.#life.start(this.#propertyAllocation) return this.trajectory(enter) case this.Steps.TRAJECTORY: if (!this.#isEnd) return this.trajectory(enter) this.#step = this.Steps.SUMMARY return `${this.summary()}\n\n${this.list()}` case this.Steps.SUMMARY: return this.remake() } } trajectory(enter) { if (enter) { if (this.#interval) { clearInterval(this.#interval) this.#interval = null this.#auto = false } else if (this.#auto) { this.#interval = setInterval(() => { const trajectory = this.next() if (this.#isEnd && this.#interval) { clearInterval(this.#interval) this.#interval = null } if (!this.#isEnd) return this.output(`${trajectory}\n`) return this.output(trajectory, true) }, Number(this.#auto) || 1000) return } } const trajectory = this.#life.next() const { age, content, isEnd } = trajectory if (isEnd) this.#isEnd = true return `${age}岁:\t${content .map(({ type, description, grade, name, postEvent }) => { switch (type) { case 'TLT': return `天赋【${name}】发动:${description}` case 'EVT': return ( description + (postEvent ? `\n\t${postEvent}` : '') ) } }) .join('\n\t')}` } prop() { const { CHR, INT, STR, MNY } = this.#propertyAllocation return `🎉 属性分配 请使用 \x1B[4m/alloc\x1B[24m 分配属性 剩余点数 ${this.less()} 属性(TAG) 当前值 颜值(CHR) ${CHR} 智力(INT) ${INT} 体质(STR) ${STR} 家境(MNY) ${MNY} ` } less() { const { total, CHR, INT, STR, MNY } = this.#propertyAllocation return total - CHR - INT - STR - MNY } attrib(tag, value) { switch (this.#step) { case this.Steps.PROPERTY: return this.alloc(tag, value) case this.Steps.TRAJECTORY: return this.showProperty() default: return undefined } } showProperty() { let property = this.#life.getLastRecord() return `当前属性 属性(TAG) 当前值 颜值(CHR) ${property.CHR} 智力(INT) ${property.INT} 体质(STR) ${property.STR} 家境(MNY) ${property.MNY} 快乐(SPR) ${property.SPR}` } alloc(tag, value) { const warn = str => `${this.prop()}\n${this.style('warn', str)}` if (!value) return warn('⚠ 分配的数值没有给定') const isSet = !(value[0] == '-' || value[0] == '+') value = Number(value) if (isNaN(value)) return warn('⚠ 分配的数值不正确') switch (tag) { case 'c': case 'chr': case 'C': tag = 'CHR' break case 'i': case 'int': case 'I': tag = 'INT' break case 's': case 'S': case 'str': tag = 'STR' break case 'm': case 'M': case 'mny': tag = 'MNY' break } switch (tag) { case 'CHR': case 'INT': case 'STR': case 'MNY': break default: return warn('⚠ 未知的tag') } if (isSet) value = value - this.#propertyAllocation[tag] const tempLess = this.less() - value const tempSet = this.#propertyAllocation[tag] + value if (tempLess < 0) return warn('⚠ 你没有更多的点数可以分配了') if (tempLess > this.#propertyAllocation.total || tempSet < 0) return warn('⚠ 不能分配负数属性') if (tempSet > 10) return warn('⚠ 单项属性最高分配10点') this.#propertyAllocation[tag] += value return this.prop() } random() { switch (this.#step) { case this.Steps.TALENT: this.#talentSelected.clear() Array.from(this.#randomTalents) .sort(() => Math.random() - 0.5) .slice(0, 3) .forEach(talent => { this.#talentSelected.add(talent) }) return this.list() case this.Steps.PROPERTY: let t = this.#propertyAllocation.total const arr = [10, 10, 10, 10] while (t > 0) { const sub = Math.round(Math.random() * (Math.min(t, 10) - 1)) + 1 while (true) { const select = Math.floor(Math.random() * 4) % 4 if (arr[select] - sub < 0) continue arr[select] -= sub t -= sub break } } this.#propertyAllocation.CHR = 10 - arr[0] this.#propertyAllocation.INT = 10 - arr[1] this.#propertyAllocation.STR = 10 - arr[2] this.#propertyAllocation.MNY = 10 - arr[3] return this.prop() case this.Steps.SUMMARY: this.#talentExtend = Array.from(this.#talentSelected).sort( () => Math.random() - 0.5 )[0].id return this.list() } } summary() { const summaryData = this.#life.summary const format = (name, type) => { const { judge, grade, value } = summaryData[type] return this.style( `grade${grade}b`, `${name}:${value} ${$lang[judge]}` ) } return [ '🎉 总评', format('颜值', this.#life.PropertyTypes.HCHR), format('智力', this.#life.PropertyTypes.HINT), format('体质', this.#life.PropertyTypes.HSTR), format('家境', this.#life.PropertyTypes.HMNY), format('快乐', this.#life.PropertyTypes.HSPR), format('享年', this.#life.PropertyTypes.HAGE), format('总评', this.#life.PropertyTypes.SUM), ].join('\n') } } export default App ================================================ FILE: repl/index.js ================================================ import { fileURLToPath } from 'url' import { dirname } from 'path' const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename) import App from './app.js' import { readFile, writeFile } from 'fs/promises' async function main() { try { globalThis.localStorage = JSON.parse( await readFile(__dirname + '/__localStorage.json') ) } catch (e) { globalThis.localStorage = {} } localStorage.getItem = key => localStorage[key] === void 0 ? null : localStorage[key] localStorage.setItem = (key, value) => (localStorage[key] = value) globalThis.dumpLocalStorage = async () => await writeFile( __dirname + '/__localStorage.json', JSON.stringify(global.localStorage) ) const app = new App() app.io( repl => process.stdin.on('data', data => repl(data.toString().trim())), (data, isRepl) => process.stdout.write(`${data}${isRepl ? '\n>' : ''}`), code => process.exit(code) ) await app.initial() } main() // process.stdin.setRawMode(true); // process.openStdin().on('keypress', function (chunk, key) { // process.stdout.write('Get Chunk: ' + chunk + '\n'); // if (key && key.ctrl && key.name == 'c') process.exit(); // }); ================================================ FILE: src/@types/LayaAir.d.ts ================================================ declare module laya.ani { /** * @private * @author ... */ class AnimationContent { nodes: Array; name: string; playTime: number; bone3DMap: any; totalKeyframeDatasLength: number; } } declare module laya.ani { /** * @private * @author ... */ class AnimationNodeContent { name: string; parentIndex: number; parent: AnimationNodeContent; keyframeWidth: number; lerpType: number; interpolationMethod: Array; childs: Array; keyFrame: Array; playTime: number; extenData: ArrayBuffer; dataOffset: number; } } declare module laya.ani { import Byte = laya.utils.Byte; /** * @private */ class AnimationParser01 { /** * @private */ static parse(templet: AnimationTemplet, reader: Byte): void; } } declare module laya.ani { import Byte = laya.utils.Byte; /** * @private */ class AnimationParser02 { /** * @private */ static parse(templet: AnimationTemplet, reader: Byte): void; static READ_ANIMATIONS(): void; } } declare module laya.ani { import EventDispatcher = laya.events.EventDispatcher; import IDestroy = laya.resource.IDestroy; /** * AnimationPlayer 类用于动画播放器。 */ class AnimationPlayer extends EventDispatcher implements IDestroy { _fullFrames: Array; /**是否缓存*/ isCache: boolean; /** 播放速率*/ playbackRate: number; /** 停止时是否归零*/ returnToZeroStopped: boolean; /** * 获取动画数据模板 * @param value 动画数据模板 */ /** * 设置动画数据模板,注意:修改此值会有计算开销。 * @param value 动画数据模板 */ templet: AnimationTemplet; /** * 动画播放的起始时间位置。 * @return 起始时间位置。 */ readonly playStart: number; /** * 动画播放的结束时间位置。 * @return 结束时间位置。 */ readonly playEnd: number; /** * 获取动画播放一次的总时间 * @return 动画播放一次的总时间 */ readonly playDuration: number; /** * 获取动画播放的总总时间 * @return 动画播放的总时间 */ readonly overallDuration: number; /** * 获取当前动画索引 * @return value 当前动画索引 */ readonly currentAnimationClipIndex: number; /** * 获取当前帧数 * @return 当前帧数 */ readonly currentKeyframeIndex: number; /** * 获取当前精确时间,不包括重播时间 * @return value 当前时间 */ readonly currentPlayTime: number; /** * 获取当前帧时间,不包括重播时间 * @return value 当前时间 */ readonly currentFrameTime: number; /** * 获取缓存播放速率。* * @return 缓存播放速率。 */ /** * 设置缓存播放速率,默认值为1.0,注意:修改此值会有计算开销。* * @return value 缓存播放速率。 */ cachePlayRate: number; /** * 获取默认帧率* * @return value 默认帧率 */ /** * 设置默认帧率,每秒60帧,注意:修改此值会有计算开销。* * @return value 缓存帧率 */ cacheFrameRate: number; /** * 设置当前播放位置 * @param value 当前时间 */ currentTime: number; /** * 获取当前是否暂停 * @return 是否暂停 */ /** * 设置是否暂停 * @param value 是否暂停 */ paused: boolean; /** * 获取缓存帧率间隔时间 * @return 缓存帧率间隔时间 */ readonly cacheFrameRateInterval: number; /** * 获取当前播放状态 * @return 当前播放状态 */ readonly state: number; /** * 获取是否已销毁。 * @return 是否已销毁。 */ readonly destroyed: boolean; /** * 创建一个 AnimationPlayer 实例。 */ constructor(); /** * @private */ _onTempletLoadedComputeFullKeyframeIndices(cachePlayRate: number, cacheFrameRate: number, templet: AnimationTemplet): void; /** * @private */ _update(elapsedTime: number): void; /** * @private */ _destroy(): void; /** * 播放动画。 * @param index 动画索引。 * @param playbackRate 播放速率。 * @param duration 播放时长(0为1次,Number.MAX_VALUE为循环播放)。 * @param playStart 播放的起始时间位置。 * @param playEnd 播放的结束时间位置。(0为动画一次循环的最长结束时间位置)。 */ play(index?: number, playbackRate?: number, overallDuration?: number, playStart?: number, playEnd?: number): void; /** * 播放动画。 * @param index 动画索引。 * @param playbackRate 播放速率。 * @param duration 播放时长(0为1次,Number.MAX_VALUE为循环播放)。 * @param playStartFrame 播放的原始起始帧率位置。 * @param playEndFrame 播放的原始结束帧率位置。(0为动画一次循环的最长结束时间位置)。 */ playByFrame(index?: number, playbackRate?: number, overallDuration?: number, playStartFrame?: number, playEndFrame?: number, fpsIn3DBuilder?: number): void; /** * 停止播放当前动画 * @param immediate 是否立即停止 */ stop(immediate?: boolean): void; } } declare module laya.ani { /** * @private */ class AnimationState { static stopped: number; static paused: number; static playing: number; constructor(); } } declare module laya.ani { import Resource = laya.resource.Resource; /** * AnimationTemplet 类用于动画模板资源。 */ class AnimationTemplet extends Resource { static interpolation: Array; /** * 加载动画模板。 * @param url 动画模板地址。 */ static load(url: string): AnimationTemplet; _aniVersion: string; _anis: Array; _aniMap: any; _publicExtData: ArrayBuffer; _useParent: boolean; protected unfixedCurrentFrameIndexes: Uint32Array; protected unfixedCurrentTimes: Float32Array; protected unfixedKeyframes: Array; protected unfixedLastAniIndex: number; _aniClassName: string; _animationDatasCache: any; constructor(); /** * @private */ parse(data: ArrayBuffer): void; /** * @private */ _calculateKeyFrame(node: AnimationNodeContent, keyframeCount: number, keyframeDataCount: number): void; /** * @inheritDoc */ onAsynLoaded(url: string, data: any, params: Array): void; protected disposeResource(): void; getAnimationCount(): number; getAnimation(aniIndex: number): any; getAniDuration(aniIndex: number): number; getNodes(aniIndex: number): any; getNodeIndexWithName(aniIndex: number, name: string): number; getNodeCount(aniIndex: number): number; getTotalkeyframesLength(aniIndex: number): number; getPublicExtData(): ArrayBuffer; getAnimationDataWithCache(key: any, cacheDatas: any, aniIndex: number, frameIndex: number): Float32Array; setAnimationDataWithCache(key: any, cacheDatas: Array, aniIndex: number, frameIndex: number, data: any): void; getOriginalData(aniIndex: number, originalData: Float32Array, nodesFrameIndices: Array, frameIndex: number, playCurTime: number): void; getNodesCurrentFrameIndex(aniIndex: number, playCurTime: number): Uint32Array; getOriginalDataUnfixedRate(aniIndex: number, originalData: Float32Array, playCurTime: number): void; } } declare module laya.ani.bone { import Matrix = laya.maths.Matrix; /** * @private */ class Bone { static ShowBones: any; name: string; root: Bone; parentBone: Bone; length: number; transform: Transform; resultTransform: Transform; resultMatrix: Matrix; inheritScale: boolean; inheritRotation: boolean; rotation: number; resultRotation: number; d: number; constructor(); setTempMatrix(matrix: Matrix): void; update(pMatrix?: Matrix): void; updateChild(): void; setRotation(rd: number): void; updateDraw(x: number, y: number): void; addChild(bone: Bone): void; findBone(boneName: string): Bone; localToWorld(local: Array): void; } } declare module laya.ani.bone { import GraphicsAni = laya.ani.GraphicsAni; import Graphics = laya.display.Graphics; import Matrix = laya.maths.Matrix; import Texture = laya.resource.Texture; /** * @private */ class BoneSlot { /** 插槽名称 */ name: string; /** 插槽绑定的骨骼名称 */ parent: string; /** 插糟显示数据数据的名称 */ attachmentName: string; /** 原始数据的索引 */ srcDisplayIndex: number; /** 判断对象是否是原对象 */ type: string; /** 模板的指针 */ templet: Templet; /** 当前插槽对应的数据 */ currSlotData: SlotData; /** 当前插槽显示的纹理 */ currTexture: Texture; /** 显示对象对应的数据 */ currDisplayData: SkinSlotDisplayData; /** 显示皮肤的索引 */ displayIndex: number; deformData: Array; /** * 设置要显示的插槽数据 * @param slotData * @param disIndex * @param freshIndex 是否重置纹理 */ showSlotData(slotData: SlotData, freshIndex?: boolean): void; /** * 通过名字显示指定对象 * @param name */ showDisplayByName(name: string): void; /** * 替换贴图名 * @param tarName 要替换的贴图名 * @param newName 替换后的贴图名 */ replaceDisplayByName(tarName: string, newName: string): void; /** * 替换贴图索引 * @param tarIndex 要替换的索引 * @param newIndex 替换后的索引 */ replaceDisplayByIndex(tarIndex: number, newIndex: number): void; /** * 指定显示对象 * @param index */ showDisplayByIndex(index: number): void; /** * 替换皮肤 * @param _texture */ replaceSkin(_texture: Texture): void; /** * 保存父矩阵的索引 * @param parentMatrix */ setParentMatrix(parentMatrix: Matrix): void; static createSkinMesh(): any; /** * 把纹理画到Graphics上 * @param graphics * @param noUseSave */ draw(graphics: GraphicsAni, boneMatrixArray: Array, noUseSave?: boolean, alpha?: number): void; /** * 画骨骼的起始点,方便调试 * @param graphics */ drawBonePoint(graphics: Graphics): void; /** * 得到插糟的矩阵 * @return */ getMatrix(): Matrix; /** * 用原始数据拷贝出一个 * @return */ copy(): BoneSlot; } } declare module laya.ani.bone.canvasmesh { import Rectangle = laya.maths.Rectangle; import HTMLCanvas = laya.resource.HTMLCanvas; import Texture = laya.resource.Texture; /** * @private * 将mesh元素缓存到canvas中并进行绘制 */ class CacheAbleSkinMesh extends SkinMeshCanvas { constructor(); isCached: boolean; canvas: HTMLCanvas; tex: Texture; rec: Rectangle; getCanvasPic(): Texture; render(context: any, x: number, y: number): void; _renderTextureToContext(context: any): void; } } declare module laya.ani.bone.canvasmesh { import Matrix = laya.maths.Matrix; import RenderContext = laya.renders.RenderContext; /** * @private * canvas mesh渲染器 */ class CanvasMeshRender { /** * mesh数据 */ mesh: MeshData; /** * 矩阵 */ transform: Matrix; /** * 绘图环境 */ context: any; /** * 绘制mesh的模式 0:顶点索引模式 1:无顶点索引模式 */ mode: number; /** * 将mesh数据渲染到context上面 * @param context * */ renderToContext(context: RenderContext): void; /** * 无顶点索引的模式 * @param mesh * */ _renderNoIndexes(mesh: MeshData): void; /** * 使用顶点索引模式绘制 * @param mesh * */ _renderWithIndexes(mesh: MeshData): void; /** * 绘制三角形 * @param mesh mesh * @param index0 顶点0 * @param index1 顶点1 * @param index2 顶点2 * */ _renderDrawTriangle(mesh: MeshData, index0: number, index1: number, index2: number): void; } } declare module laya.ani.bone.canvasmesh { import Matrix = laya.maths.Matrix; import Rectangle = laya.maths.Rectangle; import Texture = laya.resource.Texture; /** * @private */ class MeshData { /** * 纹理 */ texture: Texture; /** * uv数据 */ uvs: Array; /** * 顶点数据 */ vertices: Array; /** * 顶点索引 */ indexes: Array; /** * uv变换矩阵 */ uvTransform: Matrix; /** * 是否有uv变化矩阵 */ useUvTransform: boolean; /** * 扩展像素,用来去除黑边 */ canvasPadding: number; /** * 计算mesh的Bounds * @return * */ getBounds(): Rectangle; } } declare module laya.ani.bone.canvasmesh { import RenderContext = laya.renders.RenderContext; import Texture = laya.resource.Texture; /** * @private * 简化mesh绘制,多顶点mesh改为四顶点mesh,只绘制矩形不绘制三角形 */ class SimpleSkinMeshCanvas extends SkinMeshCanvas { init2(texture: Texture, vs: Array, ps: Array, verticles: Array, uvs: Array): void; renderToContext(context: RenderContext): void; _renderWithIndexes(mesh: MeshData): void; _renderDrawTriangle(mesh: MeshData, index0: number, index1: number, index2: number): void; } } declare module laya.ani.bone.canvasmesh { import Matrix = laya.maths.Matrix; import Texture = laya.resource.Texture; /** * @private * Canvas版本的SkinMesh */ class SkinMeshCanvas extends CanvasMeshRender { constructor(); init2(texture: Texture, vs: Array, ps: Array, verticles: Array, uvs: Array): void; static _tempMatrix: Matrix; render(context: any, x: number, y: number): void; } } declare module laya.ani.bone { /** * @private */ class DeformAniData { skinName: string; deformSlotDataList: Array; constructor(); } } declare module laya.ani.bone { /** * @private */ class DeformSlotData { deformSlotDisplayList: Array; constructor(); } } declare module laya.ani.bone { /** * @private */ class DeformSlotDisplayData { boneSlot: BoneSlot; slotIndex: number; attachment: string; timeList: Array; vectices: Array; tweenKeyList: Array; deformData: Array; frameIndex: number; constructor(); apply(time: number, boneSlot: BoneSlot, alpha?: number): void; } } declare module laya.ani.bone { /** * @private */ class DrawOrderData { time: number; drawOrder: Array; constructor(); } } declare module laya.ani.bone { /** * @private */ class EventData { name: string; intValue: number; floatValue: number; stringValue: string; time: number; constructor(); } } declare module laya.ani.bone { /** * @private */ class IkConstraint { name: string; mix: number; bendDirection: number; isSpine: boolean; static radDeg: number; static degRad: number; constructor(data: IkConstraintData, bones: Array); apply(): void; updatePos(x: number, y: number): void; } } declare module laya.ani.bone { /** * @private */ class IkConstraintData { name: string; targetBoneName: string; boneNames: Array; bendDirection: number; mix: number; isSpine: boolean; targetBoneIndex: number; boneIndexs: Array; constructor(); } } declare module laya.ani.bone { import MeshData = laya.ani.bone.canvasmesh.MeshData; import Point = laya.maths.Point; /** * @private * Mesh数据处理工具 * @version 1.0 * * @created 2017-4-28 下午2:46:23 */ class MeshTools { /** * 查找边界索引 * @param verticles 顶点表 * @param offI 0表示x 1表示y * @param min 是否是最小值 * @return * */ static findEdge(verticles: Array, offI?: number, min?: boolean): number; /** * 从顶点列表中选取一个跨度最大的三角形 * @param verticles 顶点列表 * @return 三角形顶点索引数组 * */ static findBestTriangle(verticles: Array): Array; /** * 根据mesh的多顶点列表生成四顶点列表 * @param mesh mesh数据 * @param rst * @return * */ static solveMesh(mesh: MeshData, rst?: Array): Array; /** * 计算ab列表,pointC=point0+a*v1+b*v2 * @param pointList pointC列表 * @param oX point0.x * @param oY point0.y * @param v1x v1.x * @param v1y v1.y * @param v2x v2.x * @param v2y v2.y * @param rst * @return * */ static solvePoints(pointList: Array, oX: number, oY: number, v1x: number, v1y: number, v2x: number, v2y: number, rst?: Array): Array; /** * 根据偏移ab列表,生成对应的点,pointC=point0+a*v1+b*v2 * @param abs ab列表 * @param oX point0.x * @param oY point0.y * @param v1x v1.x * @param v1y v1.y * @param v2x v2.x * @param v2y v2.y * @param rst * @return * */ static transPoints(abs: Array, oX: number, oY: number, v1x: number, v1y: number, v2x: number, v2y: number, rst?: Array): Array; /** * 获取 pointC=point0+a*v1+b*v2 * @param a * @param b * @param oX point0.x * @param oY point0.y * @param v1x v1.x * @param v1y v1.y * @param v2x v2.x * @param v2y v2.y * @param rst * @return * */ static transPoint(a: number, b: number, oX: number, oY: number, v1x: number, v1y: number, v2x: number, v2y: number, rst?: Array): Array; /** * 解方程 求解 pointC=point0+a*v1+b*v2,计算过程要求v1.x!=0 * @param rx pointC.x * @param ry pointC.y * @param oX point0.x * @param oY point0.y * @param v1x v1.x * @param v1y v1.y * @param v2x v2.x * @param v2y v2.y * @param rv 是否交换v1,v2 * @param rst * @return * */ static solve2(rx: number, ry: number, oX: number, oY: number, v1x: number, v1y: number, v2x: number, v2y: number, rv?: boolean, rst?: Array): Array; /** * 求解 pointC=point0+a*v1+b*v2,计算过程要求v1.x!=0 * v1,v2为不平行的向量 * @param pointC 目标点 * @param point0 起点 * @param v1 向量1 * @param v2 向量2 * @return * */ static solve(pointC: Point, point0: Point, v1: Point, v2: Point): Array; } } declare module laya.ani.bone { import Graphics = laya.display.Graphics; /** * @private * 路径作用器 * 1,生成根据骨骼计算控制点 * 2,根据控制点生成路径,并计算路径上的节点 * 3,根据节点,重新调整骨骼位置 */ class PathConstraint { target: BoneSlot; data: PathConstraintData; bones: Array; position: number; spacing: number; rotateMix: number; translateMix: number; constructor(data: PathConstraintData, bones: Array); /** * 计算骨骼在路径上的节点 * @param boneSlot * @param boneMatrixArray * @param graphics */ apply(boneList: Array, graphics: Graphics): void; /** * 计算顶点的世界坐标 * @param boneSlot * @param boneList * @param start * @param count * @param worldVertices * @param offset */ computeWorldVertices2(boneSlot: BoneSlot, boneList: Array, start: number, count: number, worldVertices: Array, offset: number): void; } } declare module laya.ani.bone { /** * @private */ class PathConstraintData { name: string; bones: Array; target: string; positionMode: string; spacingMode: string; rotateMode: string; offsetRotation: number; position: number; spacing: number; rotateMix: number; translateMix: number; constructor(); } } declare module laya.ani.bone { import AnimationPlayer = laya.ani.AnimationPlayer; import Sprite = laya.display.Sprite; import Texture = laya.resource.Texture; import Handler = laya.utils.Handler; /** * 骨骼动画由TempletAnimationPlayerSkeleton三部分组成。 */ class Skeleton extends Sprite { /** * 在canvas模式是否使用简化版的mesh绘制,简化版的mesh将不进行三角形绘制,而改为矩形绘制,能极大提高性能,但是可能某些mesh动画效果会不太正常 */ static useSimpleMeshInCanvas: boolean; protected _templet: Templet; protected _player: AnimationPlayer; protected _curOriginalData: Float32Array; protected _aniClipIndex: number; protected _clipIndex: number; protected _boneList: Array; protected _aniSectionDic: any; /** * 创建一个Skeleton对象 * * @param templet 骨骼动画模板 * @param aniMode 动画模式,0不支持换装,1、2支持换装 */ constructor(templet?: Templet, aniMode?: number); /** * 初始化动画 * @param templet 模板 * @param aniMode 动画模式 * * * * * * * * * * * *
    模式描述
    0 使用模板缓冲的数据,模板缓冲的数据,不允许修改(内存开销小,计算开销小,不支持换装)
    1 使用动画自己的缓冲区,每个动画都会有自己的缓冲区,相当耗费内存 (内存开销大,计算开销小,支持换装)
    2 使用动态方式,去实时去画(内存开销小,计算开销大,支持换装,不建议使用)
    */ init(templet: Templet, aniMode?: number): void; /** * 得到资源的URL */ /** * 设置动画路径 */ url: string; /** * 通过加载直接创建动画 * @param path 要加载的动画文件路径 * @param complete 加载完成的回调函数 * @param aniMode 与Skeleton.initaniMode作用一致 */ load(path: string, complete?: Handler, aniMode?: number): void; protected _createGraphics(_clipIndex?: number): void; /** * 得到当前动画的数量 * @return 当前动画的数量 */ getAnimNum(): number; /** * 得到指定动画的名字 * @param index 动画的索引 */ getAniNameByIndex(index: number): string; /** * 通过名字得到插槽的引用 * @param name 动画的名字 * @return 插槽的引用 */ getSlotByName(name: string): BoneSlot; /** * 通过名字显示一套皮肤 * @param name 皮肤的名字 * @param freshSlotIndex 是否将插槽纹理重置到初始化状态 */ showSkinByName(name: string, freshSlotIndex?: boolean): void; /** * 通过索引显示一套皮肤 * @param skinIndex 皮肤索引 * @param freshSlotIndex 是否将插槽纹理重置到初始化状态 */ showSkinByIndex(skinIndex: number, freshSlotIndex?: boolean): void; /** * 设置某插槽的皮肤 * @param slotName 插槽名称 * @param index 插糟皮肤的索引 */ showSlotSkinByIndex(slotName: string, index: number): void; /** * 设置某插槽的皮肤 * @param slotName 插槽名称 * @param name 皮肤名称 */ showSlotSkinByName(slotName: string, name: string): void; /** * 替换插槽贴图名 * @param slotName 插槽名称 * @param oldName 要替换的贴图名 * @param newName 替换后的贴图名 */ replaceSlotSkinName(slotName: string, oldName: string, newName: string): void; /** * 替换插槽的贴图索引 * @param slotName 插槽名称 * @param oldIndex 要替换的索引 * @param newIndex 替换后的索引 */ replaceSlotSkinByIndex(slotName: string, oldIndex: number, newIndex: number): void; /** * 设置自定义皮肤 * @param name 插糟的名字 * @param texture 自定义的纹理 */ setSlotSkin(slotName: string, texture: Texture): void; /** * 播放动画 * * @param nameOrIndex 动画名字或者索引 * @param loop 是否循环播放 * @param force false,如果要播的动画跟上一个相同就不生效,true,强制生效 * @param start 起始时间 * @param end 结束时间 * @param freshSkin 是否刷新皮肤数据 */ play(nameOrIndex: any, loop: boolean, force?: boolean, start?: number, end?: number, freshSkin?: boolean): void; /** * 停止动画 */ stop(): void; /** * 设置动画播放速率 * @param value 1为标准速率 */ playbackRate(value: number): void; /** * 暂停动画的播放 */ paused(): void; /** * 恢复动画的播放 */ resume(): void; /** * 销毁当前动画 */ destroy(destroyChild?: boolean): void; /** * @private * 得到帧索引 */ /** * @private * 设置帧索引 */ index: number; /** * 得到总帧数据 */ readonly total: number; /** * 得到播放器的引用 */ readonly player: AnimationPlayer; /** * 得到动画模板的引用 */ readonly templet: Templet; } } declare module laya.ani.bone { /** * @private */ class SkinData { name: string; slotArr: Array; } } declare module laya.ani.bone { import Texture = laya.resource.Texture; /** * @private */ class SkinSlotDisplayData { name: string; attachmentName: string; type: number; transform: Transform; width: number; height: number; texture: Texture; bones: Array; uvs: Array; weights: Array; triangles: Array; vertices: Array; lengths: Array; verLen: number; createTexture(currTexture: Texture): Texture; destory(): void; } } declare module laya.ani.bone { /** * @private */ class SlotData { name: string; displayArr: Array; getDisplayByName(name: string): number; } } declare module laya.ani.bone { import AnimationTemplet = laya.ani.AnimationTemplet; import Graphics = laya.display.Graphics; import Matrix = laya.maths.Matrix; import Texture = laya.resource.Texture; /** * 动画模板类 */ class Templet extends AnimationTemplet { static LAYA_ANIMATION_VISION: string; static TEMPLET_DICTIONARY: any; /** 存放原始骨骼信息 */ srcBoneMatrixArr: Array; /** IK数据 */ ikArr: Array; /** transform数据 */ tfArr: Array; /** path数据 */ pathArr: Array; /** 存放插槽数据的字典 */ boneSlotDic: any; /** 绑定插槽数据的字典 */ bindBoneBoneSlotDic: any; /** 存放插糟数据的数组 */ boneSlotArray: Array; /** 皮肤数据 */ skinDataArray: Array; /** 皮肤的字典数据 */ skinDic: any; /** 存放纹理数据 */ subTextureDic: any; /** 是否解析失败 */ isParseFail: boolean; /** 反转矩阵,有些骨骼动画要反转才能显示 */ yReverseMatrix: Matrix; /** 渲染顺序动画数据 */ drawOrderAniArr: Array; /** 事件动画数据 */ eventAniArr: Array; attachmentNames: Array; /** 顶点动画数据 */ deformAniArr: Array; /** 实际显示对象列表,用于销毁用 */ skinSlotDisplayDataArr: Array; isParserComplete: boolean; aniSectionDic: any; tMatrixDataLen: number; mRootBone: Bone; mBoneArr: Array; loadAni(url: string): void; /** * 解析骨骼动画数据 * @param texture 骨骼动画用到的纹理 * @param skeletonData 骨骼动画信息及纹理分块信息 * @param playbackRate 缓冲的帧率数据(会根据帧率去分帧) */ parseData(texture: Texture, skeletonData: ArrayBuffer, playbackRate?: number): void; /** * 创建动画 * 0,使用模板缓冲的数据,模板缓冲的数据,不允许修改 (内存开销小,计算开销小,不支持换装) * 1,使用动画自己的缓冲区,每个动画都会有自己的缓冲区,相当耗费内存 (内存开销大,计算开销小,支持换装) * 2,使用动态方式,去实时去画 (内存开销小,计算开销大,支持换装,不建议使用) * @param aniMode 0 动画模式,0:不支持换装,1,2支持换装 * @return */ buildArmature(aniMode?: number): Skeleton; /** * @private * 解析动画 * @param data 解析的二进制数据 * @param playbackRate 帧率 */ parse(data: ArrayBuffer): void; /** * 得到指定的纹理 * @param name 纹理的名字 * @return */ getTexture(name: string): Texture; /** * @private * 显示指定的皮肤 * @param boneSlotDic 插糟字典的引用 * @param skinIndex 皮肤的索引 * @param freshDisplayIndex 是否重置插槽纹理 */ showSkinByIndex(boneSlotDic: any, skinIndex: number, freshDisplayIndex?: boolean): boolean; /** * 通过皮肤名字得到皮肤索引 * @param skinName 皮肤名称 * @return */ getSkinIndexByName(skinName: string): number; /** * @private * 得到缓冲数据 * @param aniIndex 动画索引 * @param frameIndex 帧索引 * @return */ getGrahicsDataWithCache(aniIndex: number, frameIndex: number): Graphics; /** * @private * 保存缓冲grahpics * @param aniIndex 动画索引 * @param frameIndex 帧索引 * @param graphics 要保存的数据 */ setGrahicsDataWithCache(aniIndex: number, frameIndex: number, graphics: Graphics): void; /** * 释放纹理 */ destroy(): void; /** * 通过索引得动画名称 * @param index * @return */ getAniNameByIndex(index: number): string; rate: number; } } declare module laya.ani.bone { /** * @private */ class TfConstraint { target: Bone; rotateMix: number; translateMix: number; scaleMix: number; shearMix: number; constructor(data: TfConstraintData, bones: Array); apply(): void; } } declare module laya.ani.bone { /** * @private */ class TfConstraintData { name: string; boneIndexs: Array; targetIndex: number; rotateMix: number; translateMix: number; scaleMix: number; shearMix: number; offsetRotation: number; offsetX: number; offsetY: number; offsetScaleX: number; offsetScaleY: number; offsetShearY: number; } } declare module laya.ani.bone { import Matrix = laya.maths.Matrix; /** * @private */ class Transform { skX: number; skY: number; scX: number; scY: number; x: number; y: number; skewX: number; skewY: number; initData(data: any): void; getMatrix(): Matrix; skew(m: Matrix, x: number, y: number): Matrix; } } declare module laya.ani.bone { /** * 用于UV转换的工具类 * @private */ class UVTools { constructor(); /** * 将相对于大图图集的小UV转换成相对某个大图的UV * @param bigUV 某个大图的UV * @param smallUV 大图图集中的UV * @return 相对于某个大图的UV */ static getRelativeUV(bigUV: Array, smallUV: Array, rst?: Array): Array; /** * 将相对于某个大图的UV转换成相对于大图图集的UV * @param bigUV 某个大图的UV * @param smallUV 相对于某个大图的UV * @return 相对于大图图集的UV */ static getAbsoluteUV(bigUV: Array, smallUV: Array, rst?: Array): Array; } } declare module laya.ani { import Graphics = laya.display.Graphics; /** * @private */ class GraphicsAni extends Graphics { constructor(); /** * @private * 画自定义蒙皮动画 * @param skin */ drawSkin(skin: any): void; } } declare module laya.ani { /** * @private * @author ... */ class KeyFramesContent { startTime: number; duration: number; interpolationData: Array; data: Float32Array; nextData: Float32Array; } } declare module laya.ani.math { /** * @private * ... * @author ww */ class BezierLerp { constructor(); static getBezierRate(t: number, px0: number, py0: number, px1: number, py1: number): number; } } declare module laya.ani.swf { import Sprite = laya.display.Sprite; import Byte = laya.utils.Byte; import Handler = laya.utils.Handler; /** *

    MovieClip 用于播放经过工具处理后的 swf 动画。

    */ class MovieClip extends Sprite { protected static _ValueList: Array; protected _start: number; protected _Pos: number; protected _data: Byte; protected _curIndex: number; protected _preIndex: number; protected _playIndex: number; protected _playing: boolean; protected _ended: boolean; protected _count: number; _ids: any; protected _loadedImage: any; _idOfSprite: Array; _parentMovieClip: MovieClip; _movieClipList: Array; protected _labels: any; /**资源根目录。*/ basePath: string; /** 播放间隔(单位:毫秒)。*/ interval: number; /**是否循环播放 */ loop: boolean; /** * 创建一个 MovieClip 实例。 * @param parentMovieClip 父MovieClip,自己创建时不需要传该参数 */ constructor(parentMovieClip?: MovieClip); /** *

    销毁此对象。以及销毁引用的Texture

    * @param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ destroy(destroyChild?: boolean): void; _setDisplay(value: boolean): void; updates(): void; /**当前播放索引。*/ index: number; /** * 增加一个标签到index帧上,播放到此index后会派发label事件 * @param label 标签名称 * @param index 索引位置 */ addLabel(label: string, index: number): void; /** * 删除某个标签 * @param label 标签名字,如果label为空,则删除所有Label */ removeLabel(label: string): void; /** * 帧总数。 */ readonly count: number; /** * 是否在播放中 */ readonly playing: boolean; /** * 停止播放动画。 */ stop(): void; /** * 跳到某帧并停止播放动画。 * @param frame 要跳到的帧 */ gotoAndStop(index: number): void; /** * 播放动画。 * @param index 帧索引。 */ play(index?: number, loop?: boolean): void; _setData(data: Byte, start: number): void; /** * 资源地址。 */ url: string; /** * 加载资源。 * @param url swf 资源地址。 * @param atlas 是否使用图集资源 * @param atlasPath 图集路径,默认使用与swf同名的图集 */ load(url: string, atlas?: boolean, atlasPath?: string): void; /** * 从开始索引播放到结束索引,结束之后出发complete回调 * @param start 开始索引 * @param end 结束索引 * @param complete 结束回调 */ playTo(start: number, end: number, complete?: Handler): void; } } declare module laya.d3.animation { import Animator = laya.d3.component.Animator; import Avatar = laya.d3.core.Avatar; import Resource = laya.resource.Resource; /** * AnimationClip 类用于动画片段资源。 */ class AnimationClip extends Resource { /** * 加载动画模板。 * @param url 动画模板地址。 */ static load(url: string): AnimationClip; _version: string; _nodes: Array; _nodesMap: any; _cachePropertyMap: Int32Array; _nodeToCachePropertyMap: Int32Array; _unCachePropertyMap: Int32Array; _duration: number; _frameRate: number; _animationEvents: Array; _publicClipDatas: Array; /**是否循环。*/ islooping: boolean; /** * 获取动画片段时长。 */ duration(): number; /** * 创建一个 AnimationClip 实例。 */ constructor(); /** * @private */ _getFullKeyframeIndicesWithCache(cacheInterval: number): Array; /** * @private */ _cacheFullKeyframeIndices(cacheInterval: number, datas: Array): void; /** * @private */ _getAnimationDataWithCache(cacheRate: number, frameIndex: number): Array; /** * @private */ _cacheAnimationData(cacheRate: number, frameIndex: number, datas: Array): void; /** * @private */ _getAvatarDataWithCache(avatar: Avatar, cacheRate: number, frameIndex: number): Array; /** * @private */ _cacheAvatarData(avatar: Avatar, cacheRate: number, frameIndex: number, datas: Array): void; /** * @private */ _evaluateAnimationlDatasCacheMode(nodeOwners: any, nodesFrameIndices: Array, animator: Animator, clipDatas: Array, propertyMap: Int32Array): void; /** * @private */ _evaluateAnimationlDatasRealTime(nodeOwners: any, playCurTime: number, outAnimationDatas: Array, propertyMap: Int32Array): void; /** * 添加动画事件。 */ addEvent(event: AnimationEvent): void; /** * @inheritDoc */ onAsynLoaded(url: string, data: any, params: Array): void; protected disposeResource(): void; } } declare module laya.d3.animation { import Byte = laya.utils.Byte; /** * @private */ class AnimationClipParser01 { /** * @private */ static parse(clip: AnimationClip, reader: Byte): void; /** * @private */ static READ_ANIMATIONS(): void; } } declare module laya.d3.animation { import Byte = laya.utils.Byte; /** * @private */ class AnimationClipParser02 { /** * @private */ static parse(clip: AnimationClip, reader: Byte): void; /** * @private */ static READ_ANIMATIONS(): void; } } declare module laya.d3.animation { /** * AnimationEvent 类用于实现动画事件。 */ class AnimationEvent { /** 事件触发时间。*/ time: number; /** 事件触发名称。*/ eventName: string; /** 事件触发参数。*/ params: Array; /** * 创建一个 AnimationEvent 实例。 */ constructor(); } } declare module laya.d3.animation { import IClone = laya.d3.core.IClone; /** * BoneNode 类用于实现骨骼节点。 */ class AnimationNode implements IClone { static _propertyIndexDic: any; static _propertySetFuncs: Array; static _propertyGetFuncs: Array; /** *@private */ static __init__(): void; /** *注册Animator动画。 */ static registerAnimationNodeProperty(propertyName: string, getFunc: Function, setFunc: Function): void; _parent: AnimationNode; transform: AnimationTransform3D; /**节点名称。 */ name: string; /** * 创建一个新的 BoneNode 实例。 */ constructor(); /** * 添加子节点。 * @param child 子节点。 */ addChild(child: AnimationNode): void; /** * 移除子节点。 * @param child 子节点。 */ removeChild(child: AnimationNode): void; /** * 根据名字获取子节点。 * @param name 名字。 */ getChildByName(name: string): AnimationNode; /** * 根据索引获取子节点。 * @param index 索引。 */ getChildByIndex(index: number): AnimationNode; /** * 获取子节点的个数。 */ getChildCount(): number; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.animation { import Transform3D = laya.d3.core.Transform3D; import EventDispatcher = laya.events.EventDispatcher; /** * Transform3D 类用于实现3D变换。 */ class AnimationTransform3D extends EventDispatcher { _localRotationEuler: Float32Array; _owner: AnimationNode; _worldUpdate: boolean; _entity: Transform3D; /** * 创建一个 Transform3D 实例。 * @param owner 所属精灵。 */ constructor(owner: AnimationNode); /** * @private */ _setWorldMatrixAndUpdate(matrix: Float32Array): void; /** * @private */ _setWorldMatrixNoUpdate(matrix: Float32Array): void; /** * @private */ _setWorldMatrixIgnoreUpdate(matrix: Float32Array): void; /** * 获取局部位置。 * @return 局部位置。 */ getLocalPosition(): Float32Array; /** * 设置局部位置。 * @param value 局部位置。 */ setLocalPosition(value: Float32Array): void; /** * 获取局部旋转。 * @return 局部旋转。 */ getLocalRotation(): Float32Array; /** * 设置局部旋转。 * @param value 局部旋转。 */ setLocalRotation(value: Float32Array): void; /** * 获取局部缩放。 * @return 局部缩放。 */ getLocalScale(): Float32Array; /** * 设置局部缩放。 * @param value 局部缩放。 */ setLocalScale(value: Float32Array): void; /** * 获取局部空间的旋转角度。 * @return 欧拉角的旋转值,顺序为x、y、z。 */ getLocalRotationEuler(): Float32Array; /** * 设置局部空间的旋转角度。 * @param value 欧拉角的旋转值,顺序为x、y、z。 */ setLocalRotationEuler(value: Float32Array): void; /** * 获取世界矩阵。 * @return 世界矩阵。 */ getWorldMatrix(): Float32Array; /** * 设置父3D变换。 * @param value 父3D变换。 */ setParent(value: AnimationTransform3D): void; } } declare module laya.d3.animation { /** * @private */ class Keyframe { startTime: number; inTangent: Float32Array; outTangent: Float32Array; data: Float32Array; duration: number; next: Keyframe; } } declare module laya.d3.animation { /** * @private */ class KeyframeNode { _cacheProperty: boolean; path: Array; componentType: string; propertyNameID: number; keyFrameWidth: number; defaultData: Float32Array; keyFrames: Array; } } declare module laya.d3.component.animation { import AnimationPlayer = laya.ani.AnimationPlayer; import AnimationTemplet = laya.ani.AnimationTemplet; import Component3D = laya.d3.component.Component3D; import ComponentNode = laya.d3.core.ComponentNode; /** * KeyframeAnimation 类用于帧动画组件的父类。 */ class KeyframeAnimations extends Component3D { protected _player: AnimationPlayer; protected _templet: AnimationTemplet; /** * 设置url地址。 * @param value 地址。 */ url: string; /** * 获取动画模板。 * @return value 动画模板。 */ /** * 设置动画模板。 * @param value 设置动画模板。 */ templet: AnimationTemplet; /** * 获取动画播放器。 * @return 动画播放器。 */ readonly player: AnimationPlayer; /** * 获取播放器帧数。 * @return 播放器帧数。 */ readonly currentFrameIndex: number; /** * 获取播放器的动画索引。 * @return 动画索引。 */ readonly currentAnimationClipIndex: number; /** * 获取播放器当前动画的节点数量。 * @return 节点数量。 */ readonly nodeCount: number; /** * 创建一个新的 KeyframeAnimation 实例。 */ constructor(); /** * @private * 载入组件时执行 */ _load(owner: ComponentNode): void; /** * @private * 卸载组件时执行 */ _unload(owner: ComponentNode): void; } } declare module laya.d3.component.animation { import AnimationTemplet = laya.ani.AnimationTemplet; import RenderState = laya.d3.core.render.RenderState; import ComponentNode = laya.d3.core.ComponentNode; /** * RigidAnimations 类用于创建变换动画组件。 */ class RigidAnimations extends KeyframeAnimations { /** * 设置url地址。 * @param value 地址。 */ url: string; templet: AnimationTemplet; /** * 创建一个新的 RigidAnimations 实例。 */ constructor(); /** * @private * 初始化载入摄像机动画组件。 * @param owner 所属精灵对象。 */ _load(owner: ComponentNode): void; /** * @private * 更新摄像机动画组件。 * @param state 渲染状态。 */ _update(state: RenderState): void; /** * @private * 卸载组件时执行。 */ _unload(owner: ComponentNode): void; } } declare module laya.d3.component.animation { import AnimationTemplet = laya.ani.AnimationTemplet; import ComponentNode = laya.d3.core.ComponentNode; import MeshSprite3D = laya.d3.core.MeshSprite3D; import RenderState = laya.d3.core.render.RenderState; /** * SkinAnimations 类用于创建蒙皮动画组件。 */ class SkinAnimations extends KeyframeAnimations { protected static _splitAnimationDatas(indices: Uint8Array, bonesData: Float32Array, subAnimationDatas: Float32Array): void; protected _tempCurAnimationData: Array; protected _tempCurBonesData: Float32Array; protected _curOriginalData: Float32Array; protected _lastFrameIndex: number; protected _curMeshAnimationData: Float32Array; protected _curBonesDatas: Float32Array; protected _curAnimationDatas: Array; protected _ownerMesh: MeshSprite3D; protected _boneIndexToMeshList: Array; protected _oldVersion: boolean; /** * 获取骨骼数据。 * @return 骨骼数据。 */ readonly curBonesDatas: Float32Array; templet: AnimationTemplet; /** * 创建一个新的 SkinAnimations 实例。 */ constructor(); /** * @private * 初始化载入蒙皮动画组件。 * @param owner 所属精灵对象。 */ _load(owner: ComponentNode): void; /** * @private * 更新蒙皮动画组件。 * @param state 渲染状态参数。 */ _update(state: RenderState): void; /** * @private * 在渲染前更新蒙皮动画组件渲染参数。 * @param state 渲染状态参数。 */ _preRenderUpdate(state: RenderState): void; /** * @private * 卸载组件时执行 */ _unload(owner: ComponentNode): void; } } declare module laya.d3.component { import AnimationClip = laya.d3.animation.AnimationClip; import Avatar = laya.d3.core.Avatar; import ComponentNode = laya.d3.core.ComponentNode; import Sprite3D = laya.d3.core.Sprite3D; import RenderState = laya.d3.core.render.RenderState; import IDestroy = laya.resource.IDestroy; /** * Animations 类用于创建动画组件。 */ class Animator extends Component3D implements IDestroy { /**无效矩阵,禁止修改*/ static deafaultMatrix: Float32Array; _cacheNodesSpriteOwners: Array; _curAvatarNodeDatas: Array; _cacheNodesToSpriteMap: Array; _cacheSpriteToNodesMap: Array; _cacheFullFrames: Array; /**@private */ _avatarNodeMap: any; /**@private */ _avatarNodes: Array; /**@private */ _canCache: boolean; _lastFrameIndex: number; /** 是否为缓存模式*/ isCache: boolean; /** 播放速率*/ playbackRate: number; /** 激活时是否自动播放*/ playOnWake: boolean; /** * 获取avatar。 * @return avator。 */ /** * 设置avatar。 * @param value avatar。 */ avatar: Avatar; /** * 获取默认动画片段。 * @return 默认动画片段。 */ /** * 设置默认动画片段,AnimationClip名称为默认playName。 * @param value 默认动画片段。 */ clip: AnimationClip; /** * 获取缓存播放帧,缓存模式下生效。 * @return value 缓存播放帧率。 */ /** * 设置缓存播放帧率,缓存模式下生效。注意:修改此值会有计算开销。* * @return value 缓存播放帧率 */ cacheFrameRate: number; /** * 获取缓存播放速率,缓存模式下生效。* * @return 缓存播放速率。 */ /** * 设置缓存播放速率,缓存模式下生效。注意:修改此值会有计算开销。* * @return value 缓存播放速率。 */ cachePlayRate: number; /** * 获取当前动画索引 * @return value 当前动画索引 */ readonly currentPlayClip: AnimationClip; /** * 获取当前帧数 * @return 当前帧数 */ readonly currentFrameIndex: number; /** * 获取当前精确时间,不包括重播时间 * @return value 当前时间 */ readonly currentPlayTime: number; /** * 获取当前帧时间,不包括重播时间 * @return value 当前时间 */ readonly currentFrameTime: number; /** * 获取当前播放状态 * @return 当前播放状态 */ readonly playState: number; /** * 设置当前播放位置 * @param value 当前时间 */ playbackTime: number; /** * 创建一个 Animation 实例。 */ constructor(); /** * @private */ _handleSpriteOwnersBySprite(clipIndex: number, isLink: boolean, path: Array, sprite: Sprite3D): void; /** *@private */ _evaluateAvatarNodesCacheMode(avatarOwners: Array, clip: AnimationClip, publicClipDatas: Array, avatarNodeDatas: Array, unCacheMap: Int32Array): void; /** *@private */ _evaluateAvatarNodesRealTime(avatarOwners: Array, clip: AnimationClip, publicClipDatas: Array, avatarNodeDatas: Array, unCacheMap: Int32Array): void; /** *@private */ _updateAvatarNodesToSpriteCacheMode(clip: AnimationClip, avatarNodeDatas: Array): void; /** *@private */ _updateAvatarNodesToSpriteRealTime(): void; /** * @private */ _updatePlayer(elapsedTime: number): void; /** * @private * 更新蒙皮动画组件。 * @param state 渲染状态参数。 */ _update(state: RenderState): void; /** * @inheritDoc */ _load(owner: ComponentNode): void; /** * @inheritDoc */ _unload(owner: ComponentNode): void; /** * @private */ _destroy(): void; /** * @private */ _cloneTo(dest: Component3D): void; /** * 添加动画片段。 * @param clip 动画片段。 * @param playName 动画片段播放名称,如果为null,则使用clip.name作为播放名称。 * @param 开始帧率。 * @param 结束帧率。 */ addClip(clip: AnimationClip, playName?: string, startFrame?: number, endFrame?: number): void; /** * 移除动画片段。 * @param clip 动画片段。 */ removeClip(clip: AnimationClip): void; /** * 通过播放名字移除动画片段。 * @param playName 播放名字。 */ removeClipByName(playName: string): void; /** * 通过播放名字获取动画片段。 * @param playName 播放名字。 * @return 动画片段。 */ getClip(playName: string): AnimationClip; /** * 获取动画片段个数。 * @return 动画个数。 */ getClipCount(): number; /** * 播放动画。 * @param name 如果为null则播放默认动画,否则按名字播放动画片段。 * @param playbackRate 播放速率。 * @param startFrame 开始帧率。 * @param endFrame 结束帧率.-1表示为最大结束帧率。 */ play(name?: string, playbackRate?: number): void; /** * 停止播放当前动画 */ stop(): void; /** * 关联精灵节点到Avatar节点,此Animator必须有Avatar文件。 * @param nodeName 关联节点的名字。 * @param sprite3D 精灵节点。 * @return 是否关联成功。 */ linkSprite3DToAvatarNode(nodeName: string, sprite3D: Sprite3D): boolean; /** * 解除精灵节点到Avatar节点的关联,此Animator必须有Avatar文件。 * @param sprite3D 精灵节点。 * @return 是否解除关联成功。 */ unLinkSprite3DToAvatarNode(sprite3D: Sprite3D): boolean; /** * 获取当前是否暂停 * @return 是否暂停 */ /** * 设置是否暂停 * @param value 是否暂停 */ paused: boolean; } } declare module laya.d3.component { import SkinAnimations = laya.d3.component.animation.SkinAnimations; import ComponentNode = laya.d3.core.ComponentNode; import RenderState = laya.d3.core.render.RenderState; /** * AttachPoint 类用于创建挂点组件。 */ class AttachPoint extends Component3D { protected _attachSkeleton: SkinAnimations; protected _extenData: Float32Array; /**挂点骨骼的名称。*/ attachBones: Array; /**挂点骨骼的变换矩阵。*/ matrixs: Array; /** * 创建一个新的 AttachPoint 实例。 */ constructor(); /** * @private * 初始化载入挂点组件。 * @param owner 所属精灵对象。 */ _load(owner: ComponentNode): void; /** * @private * 更新挂点组件。 * @param state 渲染状态。 */ _update(state: RenderState): void; } } declare module laya.d3.component { import ComponentNode = laya.d3.core.ComponentNode; import IUpdate = laya.d3.core.render.IUpdate; import RenderState = laya.d3.core.render.RenderState; import EventDispatcher = laya.events.EventDispatcher; import IDestroy = laya.resource.IDestroy; /** * Component3D 类用于创建组件的父类。 */ class Component3D extends EventDispatcher implements IUpdate, IDestroy { protected static _uniqueIDCounter: number; protected _id: number; protected _enable: boolean; protected _owner: ComponentNode; /**是否已执行start函数。*/ started: boolean; /** * 获取唯一标识ID。 * @return 唯一标识ID。 */ readonly id: number; /** * 获取所属Sprite3D节点。 * @return 所属Sprite3D节点。 */ readonly owner: ComponentNode; /** * 获取是否启用。 * @return 是否启动。 */ /** * 设置是否启用。 * @param value 是否启动 */ enable: boolean; /** * 获取是否为单实例组件。 * @return 是否为单实例组件。 */ readonly isSingleton: boolean; /** * 获取是否已销毁。 * @return 是否已销毁。 */ readonly destroyed: boolean; /** * 创建一个新的 Component3D 实例。 */ constructor(); /** * @private * 初始化组件。 * @param owner 所属Sprite3D节点。 */ _initialize(owner: ComponentNode): void; /** * @private * 销毁组件。 */ _destroy(): void; /** * @private * 载入组件时执行,可重写此函数。 */ _load(owner: ComponentNode): void; /** * @private * 在任意第一次更新时执行,可重写此函数。 */ _start(state: RenderState): void; /** * @private * 更新组件,可重写此函数。 * @param state 渲染状态参数。 */ _update(state: RenderState): void; /** * @private * 更新的最后阶段执行,可重写此函数。 * @param state 渲染状态参数。 */ _lateUpdate(state: RenderState): void; /** * @private * 渲染前设置组件相关参数,可重写此函数。 * @param state 渲染状态参数。 */ _preRenderUpdate(state: RenderState): void; /** * @private * 渲染的最后阶段执行,可重写此函数。 * @param state 渲染状态参数。 */ _postRenderUpdate(state: RenderState): void; /** * @private * 卸载组件时执行,可重写此函数。 */ _unload(owner: ComponentNode): void; /** * @private */ _cloneTo(dest: Component3D): void; } } declare module laya.d3.component { import Sprite3D = laya.d3.core.Sprite3D; /** * PathFinding 类用于创建寻路。 */ class PathFind extends Component3D { _setting: any; /**寻路网格。*/ grid: any; /** * 获取寻路设置。 * @return 寻路设置。 */ /** * 设置寻路设置。 * @param value 寻路设置。 */ setting: any; /** * 创建一个新的 PathFinding 实例。 */ constructor(); /** * @private * 初始化载入蒙皮动画组件。 * @param owner 所属精灵对象。 */ _load(owner: Sprite3D): void; /** * 寻找路径。 * @param startX 开始X。 * @param startZ 开始Z。 * @param endX 结束X。 * @param endZ 结束Z。 * @return 路径。 */ findPath(startX: number, startZ: number, endX: number, endZ: number): Array; } } declare module laya.d3.component.physics { import Component3D = laya.d3.component.Component3D; import BoundBox = laya.d3.math.BoundBox; import OrientedBoundBox = laya.d3.math.OrientedBoundBox; import Ray = laya.d3.math.Ray; import Vector3 = laya.d3.math.Vector3; import RaycastHit = laya.d3.utils.RaycastHit; import ComponentNode = laya.d3.core.ComponentNode; /** * BoxCollider 类用于创建盒子碰撞器。 */ class BoxCollider extends Collider { /** 中心点 */ center: Vector3; /** * 获取盒子碰撞器长宽高的一半。 * @return 长宽高的一半。 */ /** * 设置盒子碰撞器长宽高的一半。 * @param 长宽高的一半。 */ size: Vector3; /** * 获取包围盒子,只读,不允许修改。 * @return 包围球。 */ readonly boundBox: OrientedBoundBox; /** * 创建一个 BoxCollider 实例。 */ constructor(); /** * @inheritDoc */ _initialize(owner: ComponentNode): void; /** * @inheritDoc */ _getType(): number; /** * @inheritDoc */ _collisonTo(other: Collider): boolean; /** * @inheritDoc */ _cloneTo(dest: Component3D): void; /** * @inheritDoc */ raycast(ray: Ray, hitInfo: RaycastHit, maxDistance?: number): boolean; /** * 从AABB碰撞盒设置center和Size。 * @param boundBox 碰撞盒。 */ setFromBoundBox(boundBox: BoundBox): void; } } declare module laya.d3.component.physics { import Component3D = laya.d3.component.Component3D; import ComponentNode = laya.d3.core.ComponentNode; import Ray = laya.d3.math.Ray; import RaycastHit = laya.d3.utils.RaycastHit; /** * Collider 类用于创建碰撞器的父类,抽象类,不允许实例。 */ class Collider extends Component3D { protected _needUpdate: boolean; _isRigidbody: boolean; _runtimeCollisonMap: any; _runtimeCollisonTestMap: any; _ignoreCollisonMap: any; /** 是否为触发器。*/ isTrigger: boolean; /** * @inheritDoc */ enable: boolean; /** * @inheritDoc */ readonly isSingleton: boolean; /** * 创建一个 Collider 实例。 */ constructor(); /** * @private */ _clearCollsionMap(): void; /** * @inheritDoc */ _unload(owner: ComponentNode): void; /** * @private */ _setIsRigidbody(value: boolean): void; /** *@private */ _getType(): number; /** * @private */ _collisonTo(other: Collider): boolean; /** * 在场景中投下可与球体碰撞器碰撞的一条光线,获取发生碰撞的球体碰撞器信息。 * @param ray 射线 * @param outHitInfo 与该射线发生碰撞球体碰撞器的碰撞信息 * @param distance 射线长度,默认为最大值 */ raycast(ray: Ray, hitInfo: RaycastHit, maxDistance?: number): boolean; } } declare module laya.d3.component.physics { import Component3D = laya.d3.component.Component3D; import ComponentNode = laya.d3.core.ComponentNode; import BoundBox = laya.d3.math.BoundBox; import Ray = laya.d3.math.Ray; import BaseMesh = laya.d3.resource.models.BaseMesh; import RaycastHit = laya.d3.utils.RaycastHit; /** * MeshCollider 类用于创建网格碰撞器。 */ class MeshCollider extends Collider { /** * @private 只读,不允许修改。 */ readonly _boundBox: BoundBox; /** * 获取碰撞器网格。 * @return 碰撞其网格。 */ /** * 设置碰撞器网格。 * @param value 碰撞其网格。 */ mesh: BaseMesh; /** * 创建一个 SphereCollider 实例。 */ constructor(); /** * @inheritDoc */ _initialize(owner: ComponentNode): void; /** * @inheritDoc */ _getType(): number; /** * @inheritDoc */ _collisonTo(other: Collider): boolean; /** * @inheritDoc */ _cloneTo(dest: Component3D): void; /** * @inheritDoc */ raycast(ray: Ray, hitInfo: RaycastHit, maxDistance?: number): boolean; } } declare module laya.d3.component.physics { import Component3D = laya.d3.component.Component3D; import BoundSphere = laya.d3.math.BoundSphere; import Ray = laya.d3.math.Ray; import Vector3 = laya.d3.math.Vector3; import RaycastHit = laya.d3.utils.RaycastHit; import ComponentNode = laya.d3.core.ComponentNode; /** * SphereCollider 类用于创建球碰撞器。 */ class SphereCollider extends Collider { /** * 获取中心点。 * @return 中心点。 */ /** * 设置中心点。 * @param value 中心点。 */ center: Vector3; /** * 获取半径。 * @return 半径。 */ /** * 设置半径。 * @param value 半径。 */ radius: number; /** * 获取包围球,只读,不允许修改。 * @return 包围球。 */ readonly boundSphere: BoundSphere; /** * 创建一个 SphereCollider 实例。 */ constructor(); /** * @inheritDoc */ _initialize(owner: ComponentNode): void; /** * @inheritDoc */ _getType(): number; /** * @inheritDoc */ _collisonTo(other: Collider): boolean; /** * @inheritDoc */ _cloneTo(dest: Component3D): void; /** * @inheritDoc */ raycast(ray: Ray, hitInfo: RaycastHit, maxDistance?: number): boolean; } } declare module laya.d3.component { /** * Rigidbody 类用于创建动画组件。 */ class Rigidbody extends Component3D { /** * @inheritDoc */ enable: boolean; /** * 创建一个 Rigidbody 实例。 */ constructor(); } } declare module laya.d3.component { import Collider = laya.d3.component.physics.Collider; /** * Script 类用于创建脚本的父类。 */ class Script extends Component3D { /** * @inheritDoc */ readonly isSingleton: boolean; /** * 创建一个新的 Script 实例。 */ constructor(); /** *当其他碰撞器进入时触发。 */ onTriggerEnter(other: Collider): void; /** *当其他碰撞器退出时触发。 */ onTriggerExit(other: Collider): void; /** *当其他碰撞器保持进入状态时逐帧触发。 */ onTriggerStay(other: Collider): void; } } declare module laya.d3.core { import Animator = laya.d3.component.Animator; import Resource = laya.resource.Resource; /** * Avatar 类用于创建Avatar。 */ class Avatar extends Resource implements IClone { _version: string; /** * 加载Avatar文件。 * @param url Avatar文件。 */ static load(url: string): Avatar; /** * 创建一个 Avatar 实例。 */ constructor(); /** * @inheritDoc */ onAsynLoaded(url: string, data: any, params: Array): void; /** * 克隆数据到Avatr。 * @param destObject 克隆源。 */ _cloneDatasToAnimator(destAnimator: Animator): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core { import RenderState = laya.d3.core.render.RenderState; import Scene = laya.d3.core.scene.Scene; import Matrix4x4 = laya.d3.math.Matrix4x4; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; import RenderTexture = laya.d3.resource.RenderTexture; import Sky = laya.d3.resource.models.Sky; import Size = laya.d3.utils.Size; import WebGLContext = laya.webgl.WebGLContext; /** * BaseCamera 类用于创建摄像机的父类。 */ class BaseCamera extends Sprite3D { static CAMERAPOS: number; static VIEWMATRIX: number; static PROJECTMATRIX: number; static VPMATRIX: number; static VPMATRIX_NO_TRANSLATE: number; static CAMERADIRECTION: number; static CAMERAUP: number; static ENVIRONMENTDIFFUSE: number; static ENVIRONMENTSPECULAR: number; static SIMLODINFO: number; static DIFFUSEIRRADMATR: number; static DIFFUSEIRRADMATG: number; static DIFFUSEIRRADMATB: number; static HDREXPOSURE: number; /**渲染模式,延迟光照渲染,暂未开放。*/ static RENDERINGTYPE_DEFERREDLIGHTING: string; /**渲染模式,前向渲染。*/ static RENDERINGTYPE_FORWARDRENDERING: string; /**清除标记,固定颜色。*/ static CLEARFLAG_SOLIDCOLOR: number; /**清除标记,天空。*/ static CLEARFLAG_SKY: number; /**清除标记,仅深度。*/ static CLEARFLAG_DEPTHONLY: number; /**清除标记,不清除。*/ static CLEARFLAG_NONE: number; protected _tempVector3: Vector3; protected _orthographic: boolean; protected _renderTarget: RenderTexture; protected _useUserProjectionMatrix: boolean; protected _viewportExpressedInClipSpace: boolean; /**清楚标记。*/ clearFlag: number; /**摄像机的清除颜色。*/ clearColor: Vector4; /** 可视遮罩图层。 */ cullingMask: number; /** 渲染时是否用遮挡剔除。 */ useOcclusionCulling: boolean; /**获取天空。*/ /**设置天空。*/ sky: Sky; /**获取位置。*/ readonly position: Vector3; /** * 获取上向量。 * @return 上向量。 */ readonly up: Vector3; /** * 获取前向量。 * @return 前向量。 */ readonly forward: Vector3; /** * 获取右向量。 * @return 右向量。 */ readonly right: Vector3; /** * 获取渲染场景的渲染目标。 * @return 渲染场景的渲染目标。 */ /** * 设置渲染场景的渲染目标。 * @param value 渲染场景的渲染目标。 */ renderTarget: RenderTexture; /** * 获取渲染目标的尺寸 * @return 渲染目标的尺寸。 */ /** * 设置渲染目标的尺寸 * @param value 渲染目标的尺寸。 */ renderTargetSize: Size; /** * 获取视野。 * @return 视野。 */ /** * 设置视野。 * @param value 视野。 */ fieldOfView: number; /** * 获取近裁面。 * @return 近裁面。 */ /** * 设置近裁面。 * @param value 近裁面。 */ nearPlane: number; /** * 获取远裁面。 * @return 远裁面。 */ /** * 设置远裁面。 * @param value 远裁面。 */ farPlane: number; /** * 获取是否正交投影矩阵。 * @return 是否正交投影矩阵。 */ /** * 设置是否正交投影矩阵。 * @param 是否正交投影矩阵。 */ orthographic: boolean; /** * 获取正交投影垂直矩阵尺寸。 * @return 正交投影垂直矩阵尺寸。 */ /** * 设置正交投影垂直矩阵尺寸。 * @param 正交投影垂直矩阵尺寸。 */ orthographicVerticalSize: number; renderingOrder: number; /** * 创建一个 BaseCamera 实例。 * @param fieldOfView 视野。 * @param nearPlane 近裁面。 * @param farPlane 远裁面。 */ constructor(nearPlane?: number, farPlane?: number); createConchModel(): any; /** * 通过RenderingOrder属性对摄像机机型排序。 */ _sortCamerasByRenderingOrder(): void; protected _calculateProjectionMatrix(): void; /** * @private */ _prepareCameraToRender(): void; /** * @private */ _prepareCameraViewProject(viewMatrix: Matrix4x4, projectMatrix: Matrix4x4): void; /** * @private */ _renderCamera(gl: WebGLContext, state: RenderState, scene: Scene): void; /** * 增加可视图层。 * @param layer 图层。 */ addLayer(layer: Layer): void; /** * 移除可视图层。 * @param layer 图层。 */ removeLayer(layer: Layer): void; /** * 增加所有图层。 */ addAllLayers(): void; /** * 移除所有图层。 */ removeAllLayers(): void; ResetProjectionMatrix(): void; /** * 向前移动。 * @param distance 移动距离。 */ moveForward(distance: number): void; /** * 向右移动。 * @param distance 移动距离。 */ moveRight(distance: number): void; /** * 向上移动。 * @param distance 移动距离。 */ moveVertical(distance: number): void; protected _addSelfRenderObjects(): void; protected _clearSelfRenderObjects(): void; /** * @inheritDoc */ destroy(destroyChild?: boolean): void; } } declare module laya.d3.core { import RenderState = laya.d3.core.render.RenderState; import Scene = laya.d3.core.scene.Scene; import BoundFrustum = laya.d3.math.BoundFrustum; import Matrix4x4 = laya.d3.math.Matrix4x4; import Ray = laya.d3.math.Ray; import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Viewport = laya.d3.math.Viewport; import WebGLContext = laya.webgl.WebGLContext; /** * Camera 类用于创建摄像机。 */ class Camera extends BaseCamera { /** * 获取横纵比。 * @return 横纵比。 */ /** * 设置横纵比。 * @param value 横纵比。 */ aspectRatio: number; /** * 获取屏幕空间的视口。 * @return 屏幕空间的视口。 */ /** * 设置屏幕空间的视口。 * @param 屏幕空间的视口。 */ viewport: Viewport; /** * 获取裁剪空间的视口。 * @return 裁剪空间的视口。 */ /** * 设置裁剪空间的视口。 * @return 裁剪空间的视口。 */ normalizedViewport: Viewport; readonly needViewport: boolean; /** * 获取视图矩阵。 * @return 视图矩阵。 */ readonly viewMatrix: Matrix4x4; /**获取投影矩阵。*/ /**设置投影矩阵。*/ projectionMatrix: Matrix4x4; /** * 获取视图投影矩阵。 * @return 视图投影矩阵。 */ readonly projectionViewMatrix: Matrix4x4; /** * 获取摄像机视锥。 */ readonly boundFrustum: BoundFrustum; /** * 创建一个 Camera 实例。 * @param aspectRatio 横纵比。 * @param nearPlane 近裁面。 * @param farPlane 远裁面。 */ constructor(aspectRatio?: number, nearPlane?: number, farPlane?: number); protected _parseCustomProps(rootNode: ComponentNode, innerResouMap: any, customProps: any, json: any): void; protected _calculateProjectionMatrix(): void; /** * @inheritDoc */ _update(state: RenderState): void; /** * @inheritDoc */ _renderCamera(gl: WebGLContext, state: RenderState, scene: Scene): void; /** * 计算从屏幕空间生成的射线。 * @param point 屏幕空间的位置位置。 * @return out 输出射线。 */ viewportPointToRay(point: Vector2, out: Ray): void; /** * 计算从裁切空间生成的射线。 * @param point 裁切空间的位置。。 * @return out 输出射线。 */ normalizedViewportPointToRay(point: Vector2, out: Ray): void; /** * 计算从世界空间准换三维坐标到屏幕空间。 * @param position 世界空间的位置。 * @return out 输出位置。 */ worldToViewportPoint(position: Vector3, out: Vector3): void; /** * 计算从世界空间准换三维坐标到裁切空间。 * @param position 世界空间的位置。 * @return out 输出位置。 */ worldToNormalizedViewportPoint(position: Vector3, out: Vector3): void; /** * 转换2D屏幕坐标系统到3D正交投影下的坐标系统,注:只有正交模型下有效。 * @param source 源坐标。 * @param out 输出坐标。 * @return 是否转换成功。 */ convertScreenCoordToOrthographicCoord(source: Vector3, out: Vector3): boolean; } } declare module laya.d3.core { import Component3D = laya.d3.component.Component3D; import RenderState = laya.d3.core.render.RenderState; import Node = laya.display.Node; /** * @private * ComponentNode 类用于实现组件精灵,该类为抽象类。 */ class ComponentNode extends Node { protected _componentsMap: Array; protected _typeComponentsIndices: Array; protected _components: Array; _scripts: Array; /** * 创建一个 ComponentNode 实例。 */ constructor(); /** * 添加指定类型组件。 * @param type 组件类型。 * @return 组件。 */ addComponent(type: any): Component3D; protected _removeComponent(mapIndex: number, index: number): void; /** * 通过指定类型和类型索引获得组件。 * @param type 组件类型。 * @param typeIndex 类型索引。 * @return 组件。 */ getComponentByType(type: any, typeIndex?: number): Component3D; /** * 通过指定类型获得所有组件。 * @param type 组件类型。 * @param components 组件输出队列。 */ getComponentsByType(type: any, components: Array): void; /** * 通过指定索引获得组件。 * @param index 索引。 * @return 组件。 */ getComponentByIndex(index: number): Component3D; /** * 通过指定类型和类型索引移除组件。 * @param type 组件类型。 * @param typeIndex 类型索引。 */ removeComponentByType(type: any, typeIndex?: number): void; /** * 通过指定类型移除所有组件。 * @param type 组件类型。 */ removeComponentsByType(type: any): void; /** * 移除全部组件。 */ removeAllComponent(): void; protected _updateComponents(state: RenderState): void; protected _lateUpdateComponents(state: RenderState): void; /** * @private */ _preRenderUpdateComponents(state: RenderState): void; /** * @private */ _postRenderUpdateComponents(state: RenderState): void; } } declare module laya.d3.core { import BoundBox = laya.d3.math.BoundBox; import BoundSphere = laya.d3.math.BoundSphere; import EventDispatcher = laya.events.EventDispatcher; import IDestroy = laya.resource.IDestroy; /** * GeometryFilter 类用于创建集合体过滤器,抽象类不允许实例。 */ class GeometryFilter extends EventDispatcher implements IDestroy { readonly _isAsyncLoaded: boolean; /** * @private */ readonly _originalBoundingSphere: BoundSphere; /** * @private */ readonly _originalBoundingBox: BoundBox; /** * @private */ readonly _originalBoundingBoxCorners: Array; /** * 获取是否已销毁。 * @return 是否已销毁。 */ readonly destroyed: boolean; /** * 创建一个 GeometryFilter 实例。 */ constructor(); /** * @private */ _destroy(): void; } } declare module laya.d3.core.glitter { import GlitterRender = laya.d3.core.GlitterRender; import RenderableSprite3D = laya.d3.core.RenderableSprite3D; import RenderState = laya.d3.core.render.RenderState; import Vector3 = laya.d3.math.Vector3; import GlitterTemplet = laya.d3.resource.tempelet.GlitterTemplet; /** * Glitter 类用于创建闪光。 */ class Glitter extends RenderableSprite3D { static CURRENTTIME: number; static DURATION: number; /** * 获取闪光模板。 * @return 闪光模板。 */ readonly templet: GlitterTemplet; /** * 获取刀光渲染器。 * @return 刀光渲染器。 */ readonly glitterRender: GlitterRender; /** * 创建一个 Glitter 实例。 * @param settings 配置信息。 */ constructor(); protected _clearSelfRenderObjects(): void; protected _addSelfRenderObjects(): void; _update(state: RenderState): void; /** * 通过位置添加刀光。 * @param position0 位置0。 * @param position1 位置1。 */ addGlitterByPositions(position0: Vector3, position1: Vector3): void; /** * 通过位置和速度添加刀光。 * @param position0 位置0。 * @param velocity0 速度0。 * @param position1 位置1。 * @param velocity1 速度1。 */ addGlitterByPositionsVelocitys(position0: Vector3, velocity0: Vector3, position1: Vector3, velocity1: Vector3): void; cloneTo(destObject: any): void; /** *

    销毁此对象。

    * @param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ destroy(destroyChild?: boolean): void; } } declare module laya.d3.core.glitter { import Vector3 = laya.d3.math.Vector3; /** * SplineCurvePosition 类用于通过顶点创建闪光插值。 */ class SplineCurvePosition extends SplineCurvePositionVelocity { /** * 创建一个 SplineCurvePosition 实例。 */ constructor(); /** * 初始化插值所需信息。 * @param lastPosition0 顶点0的上次位置。 * @param position0 顶点0的位置。 * @param lastPosition1 顶点1的上次位置。 * @param position1 顶点1的位置。 */ Init(lastPosition0: Vector3, position0: Vector3, lastPosition1: Vector3, position1: Vector3): void; } } declare module laya.d3.core.glitter { import Vector3 = laya.d3.math.Vector3; /** * SplineCurvePositionVelocity 类用于通过顶点和速度创建闪光插值。 */ class SplineCurvePositionVelocity { protected _tempVector30: Vector3; protected _tempVector31: Vector3; protected _tempVector32: Vector3; protected _a: Vector3; protected _b: Vector3; protected _c: Vector3; protected _d: Vector3; /** * 创建一个 SplineCurvePositionVelocity 实例。 */ constructor(); /** * 初始化插值所需信息。 * @param position0 顶点0的位置。 * @param velocity0 顶点0的速度。 * @param position1 顶点1的位置。 * @param velocity1 顶点1的速度。 */ Init(position0: Vector3, velocity0: Vector3, position1: Vector3, velocity1: Vector3): void; /** * 初始化插值所需信息。 * @param t 插值比例 * @param out 输出结果 */ Slerp(t: number, out: Vector3): void; } } declare module laya.d3.core { import Glitter = laya.d3.core.glitter.Glitter; import BaseRender = laya.d3.core.render.BaseRender; import Matrix4x4 = laya.d3.math.Matrix4x4; /** * ... * @author ... */ class GlitterRender extends BaseRender { constructor(owner: Glitter); protected _calculateBoundingBox(): void; protected _calculateBoundingSphere(): void; /** * @private */ _renderUpdate(projectionView: Matrix4x4): boolean; } } declare module laya.d3.core { import Vector2 = laya.d3.math.Vector2; import Texture2D = laya.d3.resource.Texture2D; import Mesh = laya.d3.resource.models.Mesh; /** * HeightMap 类用于实现高度图数据。 */ class HeightMap { /** * 从网格精灵生成高度图。 * @param meshSprite 网格精灵。 * @param width 高度图宽度。 * @param height 高度图高度。 * @param outCellSize 输出 单元尺寸。 */ static creatFromMesh(mesh: Mesh, width: number, height: number, outCellSize: Vector2): HeightMap; /** * 从图片生成高度图。 * @param image 图片。 * @param maxHeight 最小高度。 * @param maxHeight 最大高度。 */ static createFromImage(texture: Texture2D, minHeight: number, maxHeight: number): HeightMap; /** * 获取宽度。 * @return value 宽度。 */ readonly width: number; /** * 获取高度。 * @return value 高度。 */ readonly height: number; /** * 最大高度。 * @return value 最大高度。 */ readonly maxHeight: number; /** * 最大高度。 * @return value 最大高度。 */ readonly minHeight: number; /** * 创建一个 HeightMap 实例。 * @param width 宽度。 * @param height 高度。 * @param minHeight 最大高度。 * @param maxHeight 最大高度。 */ constructor(width: number, height: number, minHeight: number, maxHeight: number); /** * 获取高度。 * @param row 列数。 * @param col 行数。 * @return 高度。 */ getHeight(row: number, col: number): number; } } declare module laya.d3.core { /** * @private * IClone 资源克隆接口。 */ interface IClone { clone(): any; cloneTo(destObject: any): void; } } declare module laya.d3.core { import Collider = laya.d3.component.physics.Collider; /** * Layer 类用于实现层。 */ class Layer { static _collsionTestList: Array; static _currentCameraCullingMask: number; static maxCount: number; /**当前创建精灵所属遮罩层。*/ static currentCreationLayer: Layer; /** *获取Layer显示层。 * @return 显示层。 */ /** *设置Layer显示层。 * @param value 显示层。 */ static visibleLayers: number; /** * @private */ static __init__(): void; /** *通过编号获取蒙版。 * @param number 编号。 * @return 蒙版。 */ static getLayerByNumber(number: number): Layer; /** *通过蒙版值获取蒙版。 * @param name 名字。 * @return 蒙版。 */ static getLayerByName(name: string): Layer; /** *通过蒙版值获取蒙版是否显示。 * @param mask 蒙版值。 * @return 是否显示。 */ static isVisible(mask: number): boolean; _nonRigidbodyOffset: number; _colliders: Array; /**名字。*/ name: string; /** *获取编号。 * @return 编号。 */ readonly number: number; /** *获取蒙版值。 * @return 蒙版值。 */ readonly mask: number; /** *获取是否显示。 * @return 是否显示。 */ /** *设置是否显示。 * @param value 是否显示。 */ visible: boolean; /** * 创建一个 Layer 实例。 */ constructor(); /** * @private */ _addCollider(collider: Collider): void; /** * @private */ _removeCollider(collider: Collider): void; } } declare module laya.d3.core.light { import RenderState = laya.d3.core.render.RenderState; import Vector3 = laya.d3.math.Vector3; /** * DirectionLight 类用于创建平行光。 */ class DirectionLight extends LightSprite { /** * @inheritDoc */ shadow: boolean; /** * 创建一个 DirectionLight 实例。 */ constructor(); protected _addSelfRenderObjects(): void; protected _clearSelfRenderObjects(): void; /** * 更新平行光相关渲染状态参数。 * @param state 渲染状态参数。 */ _prepareToScene(state: RenderState): boolean; /** * 获取平行光的方向。 * @return 平行光的方向。 */ /** * 设置平行光的方向。 * @param value 平行光的方向。 */ direction: Vector3; } } declare module laya.d3.core.light { import ComponentNode = laya.d3.core.ComponentNode; import Sprite3D = laya.d3.core.Sprite3D; import RenderState = laya.d3.core.render.RenderState; import Vector3 = laya.d3.math.Vector3; import ParallelSplitShadowMap = laya.d3.shadowMap.ParallelSplitShadowMap; /** * LightSprite 类用于创建灯光的父类。 */ class LightSprite extends Sprite3D { /** 灯光烘培类型-实时。*/ static LIGHTMAPBAKEDTYPE_REALTIME: number; /** 灯光烘培类型-混合。*/ static LIGHTMAPBAKEDTYPE_MIXED: number; /** 灯光烘培类型-烘焙。*/ static LIGHTMAPBAKEDTYPE_BAKED: number; protected _intensityColor: Vector3; protected _intensity: number; protected _shadow: boolean; protected _shadowFarPlane: number; protected _shadowMapSize: number; protected _shadowMapCount: number; protected _shadowMapPCFType: number; protected _parallelSplitShadowMap: ParallelSplitShadowMap; _lightmapBakedType: number; /** 灯光颜色。 */ color: Vector3; /** * 获取灯光强度。 * @return 灯光强度 */ /** * 设置灯光强度。 * @param value 灯光强度 */ intensity: number; /** * 获取是否产生阴影。 * @return 是否产生阴影。 */ /** * 设置是否产生阴影。 * @param value 是否产生阴影。 */ shadow: boolean; /** * 获取阴影最远范围。 * @return 阴影最远范围。 */ /** * 设置阴影最远范围。 * @param value 阴影最远范围。 */ shadowDistance: number; /** * 获取阴影贴图尺寸。 * @return 阴影贴图尺寸。 */ /** * 设置阴影贴图尺寸。 * @param value 阴影贴图尺寸。 */ shadowResolution: number; /** * 获取阴影分段数。 * @return 阴影分段数。 */ /** * 设置阴影分段数。 * @param value 阴影分段数。 */ shadowPSSMCount: number; /** * 获取阴影PCF类型。 * @return PCF类型。 */ /** * 设置阴影PCF类型。 * @param value PCF类型。 */ shadowPCFType: number; /** * 获取灯光烘培类型。 */ /** * 设置灯光烘培类型。 */ lightmapBakedType: number; /** * 创建一个 LightSprite 实例。 */ constructor(); protected _parseCustomProps(rootNode: ComponentNode, innerResouMap: any, customProps: any, nodeData: any): void; protected _addSelfRenderObjects(): void; protected _clearSelfRenderObjects(): void; /** * 更新灯光相关渲染状态参数。 * @param state 渲染状态参数。 */ _prepareToScene(state: RenderState): boolean; /** * 获取灯光的漫反射颜色。 * @return 灯光的漫反射颜色。 */ /** * 设置灯光的漫反射颜色。 * @param value 灯光的漫反射颜色。 */ diffuseColor: Vector3; } } declare module laya.d3.core.light { import RenderState = laya.d3.core.render.RenderState; import Vector3 = laya.d3.math.Vector3; /** * PointLight 类用于创建点光。 */ class PointLight extends LightSprite { /** * 创建一个 PointLight 实例。 */ constructor(); /** * 获取点光的范围。 * @return 点光的范围。 */ /** * 设置点光的范围。 * @param value 点光的范围。 */ range: number; protected _clearSelfRenderObjects(): void; /** * 更新点光相关渲染状态参数。 * @param state 渲染状态参数。 */ _prepareToScene(state: RenderState): boolean; /** * 获取点光的衰减。 * @return 点光的衰减。 */ /** * 设置点光的衰减。 * @param value 点光的衰减。 */ attenuation: Vector3; } } declare module laya.d3.core.light { import RenderState = laya.d3.core.render.RenderState; import Vector3 = laya.d3.math.Vector3; /** * SpotLight 类用于创建聚光。 */ class SpotLight extends LightSprite { /** * 创建一个 SpotLight 实例。 */ constructor(); /** * 获取聚光的聚光值。 * @return 聚光的聚光值。 */ /** * 设置聚光的聚光值。 * @param value 聚光的聚光值。 */ spot: number; /** * 获取聚光的范围。 * @return 聚光的范围值。 */ /** * 设置聚光的范围。 * @param value 聚光的范围值。 */ range: number; protected _clearSelfRenderObjects(): void; /** * 更新聚光相关渲染状态参数。 * @param state 渲染状态参数。 */ _prepareToScene(state: RenderState): boolean; /** * 获取聚光的衰减。 * @return 聚光的衰减。 */ /** * 设置聚光的衰减。 * @param value 聚光的衰减。 */ attenuation: Vector3; /** * 获取平行光的方向。 * @return 平行光的方向。 */ /** * 设置平行光的方向。 * @param value 平行光的方向。 */ direction: Vector3; } } declare module laya.d3.core.material { import IClone = laya.d3.core.IClone; import Transform3D = laya.d3.core.Transform3D; import Matrix4x4 = laya.d3.math.Matrix4x4; import Vector2 = laya.d3.math.Vector2; import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import Shader3D = laya.d3.shader.Shader3D; import ShaderDefines = laya.d3.shader.ShaderDefines; import Resource = laya.resource.Resource; /** * BaseMaterial 类用于创建材质,抽象类,不允许实例。 */ class BaseMaterial extends Resource implements IClone { /**剔除枚举_不剔除。*/ static CULL_NONE: number; /**剔除枚举_剔除正面。*/ static CULL_FRONT: number; /**剔除枚举_剔除背面。*/ static CULL_BACK: number; /**混合枚举_禁用。*/ static BLEND_DISABLE: number; /**混合枚举_启用_RGB和Alpha统一混合。*/ static BLEND_ENABLE_ALL: number; /**混合枚举_启用_RGB和Alpha单独混合。*/ static BLEND_ENABLE_SEPERATE: number; /**混合参数枚举_零,例:RGB(0,0,0),Alpha:(1)。*/ static BLENDPARAM_ZERO: number; /**混合参数枚举_一,例:RGB(1,1,1),Alpha:(1)。*/ static BLENDPARAM_ONE: number; /**混合参数枚举_源颜色,例:RGB(Rs,Gs,Bs),Alpha(As)。*/ static BLENDPARAM_SRC_COLOR: number; /**混合参数枚举_一减源颜色,例:RGB(1-Rs,1-Gs,1-Bs),Alpha(1-As)。*/ static BLENDPARAM_ONE_MINUS_SRC_COLOR: number; /**混合参数枚举_目标颜色,例:RGB(Rd,Gd,Bd),Alpha(Ad)。*/ static BLENDPARAM_DST_COLOR: number; /**混合参数枚举_一减目标颜色,例:RGB(1-Rd,1-Gd,1-Bd),Alpha(1-Ad)。*/ static BLENDPARAM_ONE_MINUS_DST_COLOR: number; /**混合参数枚举_源透明,例:RGB(As,As,As),Alpha(1-As)。*/ static BLENDPARAM_SRC_ALPHA: number; /**混合参数枚举_一减源阿尔法,例:RGB(1-As,1-As,1-As),Alpha(1-As)。*/ static BLENDPARAM_ONE_MINUS_SRC_ALPHA: number; /**混合参数枚举_目标阿尔法,例:RGB(Ad,Ad,Ad),Alpha(Ad)。*/ static BLENDPARAM_DST_ALPHA: number; /**混合参数枚举_一减目标阿尔法,例:RGB(1-Ad,1-Ad,1-Ad),Alpha(Ad)。*/ static BLENDPARAM_ONE_MINUS_DST_ALPHA: number; /**混合参数枚举_阿尔法饱和,例:RGB(min(As,1 - Ad),min(As,1 - Ad),min(As,1 - Ad)),Alpha(1)。*/ static BLENDPARAM_SRC_ALPHA_SATURATE: number; /**混合方程枚举_加法,例:source + destination*/ static BLENDEQUATION_ADD: number; /**混合方程枚举_减法,例:source - destination*/ static BLENDEQUATION_SUBTRACT: number; /**混合方程枚举_反序减法,例:destination - source*/ static BLENDEQUATION_REVERSE_SUBTRACT: number; /**深度测试函数枚举_关闭深度测试。*/ static DEPTHTEST_OFF: number; /**深度测试函数枚举_从不通过。*/ static DEPTHTEST_NEVER: number; /**深度测试函数枚举_小于时通过。*/ static DEPTHTEST_LESS: number; /**深度测试函数枚举_等于时通过。*/ static DEPTHTEST_EQUAL: number; /**深度测试函数枚举_小于等于时通过。*/ static DEPTHTEST_LEQUAL: number; /**深度测试函数枚举_大于时通过。*/ static DEPTHTEST_GREATER: number; /**深度测试函数枚举_不等于时通过。*/ static DEPTHTEST_NOTEQUAL: number; /**深度测试函数枚举_大于等于时通过。*/ static DEPTHTEST_GEQUAL: number; /**深度测试函数枚举_总是通过。*/ static DEPTHTEST_ALWAYS: number; static SHADERDEFINE_ALPHATEST: number; static ALPHATESTVALUE: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /**渲染剔除状态。*/ cull: number; /**透明混合。*/ blend: number; /**源混合参数,在blend为BLEND_ENABLE_ALL时生效。*/ srcBlend: number; /**目标混合参数,在blend为BLEND_ENABLE_ALL时生效。*/ dstBlend: number; /**RGB源混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ srcBlendRGB: number; /**RGB目标混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ dstBlendRGB: number; /**Alpha源混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ srcBlendAlpha: number; /**Alpha目标混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ dstBlendAlpha: number; /**混合常量颜色。*/ blendConstColor: Vector4; /**混合方程。*/ blendEquation: number; /**RGB混合方程。*/ blendEquationRGB: number; /**Alpha混合方程。*/ blendEquationAlpha: number; /**深度测试函数。*/ depthTest: number; /**是否深度写入。*/ depthWrite: boolean; /** 所属渲染队列. */ renderQueue: number; _conchMaterial: any; /** * 获取透明测试模式裁剪值。 * @return 透明测试模式裁剪值。 */ /** * 设置透明测试模式裁剪值。 * @param value 透明测试模式裁剪值。 */ alphaTestValue: number; /** * 获取是否透明裁剪。 * @return 是否透明裁剪。 */ /** * 设置是否透明裁剪。 * @param value 是否透明裁剪。 */ alphaTest: boolean; /** * 创建一个 BaseMaterial 实例。 */ constructor(); protected _addShaderDefine(value: number): void; protected _removeShaderDefine(value: number): void; protected _addDisablePublicShaderDefine(value: number): void; protected _removeDisablePublicShaderDefine(value: number): void; protected _setBuffer(shaderIndex: number, buffer: Float32Array): void; protected _getBuffer(shaderIndex: number): any; protected _setMatrix4x4(shaderIndex: number, matrix4x4: Matrix4x4): void; protected _getMatrix4x4(shaderIndex: number): any; protected _setInt(shaderIndex: number, i: number): void; protected _getInt(shaderIndex: number): any; protected _setNumber(shaderIndex: number, number: number): void; protected _getNumber(shaderIndex: number): any; protected _setBool(shaderIndex: number, b: boolean): void; protected _getBool(shaderIndex: number): any; protected _setVector2(shaderIndex: number, vector2: Vector2): void; protected _getVector2(shaderIndex: number): any; protected _setColor(shaderIndex: number, color: any): void; protected _getColor(shaderIndex: number): any; protected _setTexture(shaderIndex: number, texture: BaseTexture): void; protected _getTexture(shaderIndex: number): BaseTexture; /** * 上传材质。 * @param state 相关渲染状态。 * @param bufferUsageShader Buffer相关绑定。 * @param shader 着色器。 * @return 是否成功。 */ _upload(): void; /** * @private */ _getShader(sceneDefineValue: number, vertexDefineValue: number, spriteDefineValue: number): Shader3D; /** * 设置渲染相关状态。 */ _setRenderStateBlendDepth(): void; /** * 设置渲染相关状态。 */ _setRenderStateFrontFace(isTarget: boolean, transform: Transform3D): void; /** * @inheritDoc */ onAsynLoaded(url: string, data: any, params: Array): void; /** * @inheritDoc */ _addReference(): void; /** * @inheritDoc */ _removeReference(): void; protected disposeResource(): void; /** * 设置使用Shader名字。 * @param name 名称。 */ setShaderName(name: string): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.material { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * BlinnPhongMaterial 类用于实现Blinn-Phong材质。 */ class BlinnPhongMaterial extends BaseMaterial { /**高光强度数据源_漫反射贴图的Alpha通道。*/ static SPECULARSOURCE_DIFFUSEMAPALPHA: number; /**高光强度数据源_高光贴图的RGB通道。*/ static SPECULARSOURCE_SPECULARMAP: number; /**渲染状态_不透明。*/ static RENDERMODE_OPAQUE: number; /**渲染状态_透明测试。*/ static RENDERMODE_CUTOUT: number; /**渲染状态__透明混合。*/ static RENDERMODE_TRANSPARENT: number; /**渲染状态__加色法混合。*/ static RENDERMODE_ADDTIVE: number; static SHADERDEFINE_DIFFUSEMAP: number; static SHADERDEFINE_NORMALMAP: number; static SHADERDEFINE_SPECULARMAP: number; static SHADERDEFINE_REFLECTMAP: number; static SHADERDEFINE_TILINGOFFSET: number; static SHADERDEFINE_ADDTIVEFOG: number; static ALBEDOTEXTURE: number; static NORMALTEXTURE: number; static SPECULARTEXTURE: number; static EMISSIVETEXTURE: number; static REFLECTTEXTURE: number; static ALBEDOCOLOR: number; static MATERIALSPECULAR: number; static SHININESS: number; static MATERIALREFLECT: number; static TILINGOFFSET: number; /** 默认材质,禁止修改*/ static defaultMaterial: BlinnPhongMaterial; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 加载标准材质。 * @param url 标准材质地址。 */ static load(url: string): BlinnPhongMaterial; /** * 设置渲染模式。 * @return 渲染模式。 */ renderMode: number; /** * 获取纹理平铺和偏移。 * @return 纹理平铺和偏移。 */ /** * 获取纹理平铺和偏移。 * @param value 纹理平铺和偏移。 */ tilingOffset: Vector4; /** * 获取漫反射颜色。 * @return 漫反射颜色。 */ /** * 设置漫反射颜色。 * @param value 漫反射颜色。 */ albedoColor: Vector4; /** * 获取漫反射颜色。 * @return 漫反射颜色。 */ /** * 设置漫反射颜色。 * @param value 漫反射颜色。 */ albedoIntensity: number; /** * 获取高光颜色。 * @return 高光颜色。 */ /** * 设置高光颜色。 * @param value 高光颜色。 */ specularColor: Vector3; /** * 获取高光强度,范围为0到1。 * @return 高光强度。 */ /** * 设置高光强度,范围为0到1。 * @param value 高光强度。 */ shininess: number; /** * 获取反射颜色。 * @return value 反射颜色。 */ /** * 设置反射颜色。 * @param value 反射颜色。 */ reflectColor: Vector3; /** * 获取漫反射贴图。 * @return 漫反射贴图。 */ /** * 设置漫反射贴图。 * @param value 漫反射贴图。 */ albedoTexture: BaseTexture; /** * 获取法线贴图。 * @return 法线贴图。 */ /** * 设置法线贴图。 * @param value 法线贴图。 */ normalTexture: BaseTexture; /** * 获取高光贴图。 * @return 高光贴图。 */ /** * 设置高光贴图,高光强度则从该贴图RGB值中获取,如果该值为空则从漫反射贴图的Alpha通道获取。 * @param value 高光贴图。 */ specularTexture: BaseTexture; /** * 获取反射贴图。 * @return 反射贴图。 */ /** * 设置反射贴图。 * @param value 反射贴图。 */ reflectTexture: BaseTexture; /** * 获取是否启用光照。 * @return 是否启用光照。 */ /** * 设置是否启用光照。 * @param value 是否启用光照。 */ enableLighting: boolean; constructor(); /** * 禁用灯光。 */ disableLight(): void; /** * 禁用雾化。 */ disableFog(): void; } } declare module laya.d3.core.material { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * ... * @author ... */ class ExtendTerrainMaterial extends BaseMaterial { /**渲染状态_不透明。*/ static RENDERMODE_OPAQUE: number; /**渲染状态_透明混合。*/ static RENDERMODE_TRANSPARENT: number; /**渲染状态_透明混合。*/ static SPLATALPHATEXTURE: number; static DIFFUSETEXTURE1: number; static DIFFUSETEXTURE2: number; static DIFFUSETEXTURE3: number; static DIFFUSETEXTURE4: number; static DIFFUSETEXTURE5: number; static DIFFUSESCALEOFFSET1: number; static DIFFUSESCALEOFFSET2: number; static DIFFUSESCALEOFFSET3: number; static DIFFUSESCALEOFFSET4: number; static DIFFUSESCALEOFFSET5: number; static MATERIALAMBIENT: number; static MATERIALDIFFUSE: number; static MATERIALSPECULAR: number; static MATERIALALBEDO: number; /**地形细节宏定义。*/ static SHADERDEFINE_DETAIL_NUM1: number; static SHADERDEFINE_DETAIL_NUM2: number; static SHADERDEFINE_DETAIL_NUM3: number; static SHADERDEFINE_DETAIL_NUM4: number; static SHADERDEFINE_DETAIL_NUM5: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 获取splatAlpha贴图。 * @return splatAlpha贴图。 */ /** * 设置splatAlpha贴图。 * @param value splatAlpha贴图。 */ splatAlphaTexture: BaseTexture; /** * 设置第一层贴图。 * @param value 第一层贴图。 */ diffuseTexture1: BaseTexture; /** * 获取第二层贴图。 * @return 第二层贴图。 */ /** * 设置第二层贴图。 * @param value 第二层贴图。 */ diffuseTexture2: BaseTexture; /** * 获取第三层贴图。 * @return 第三层贴图。 */ /** * 设置第三层贴图。 * @param value 第三层贴图。 */ diffuseTexture3: BaseTexture; /** * 获取第四层贴图。 * @return 第四层贴图。 */ /** * 设置第四层贴图。 * @param value 第四层贴图。 */ diffuseTexture4: BaseTexture; /** * 获取第五层贴图。 * @return 第五层贴图。 */ /** * 设置第五层贴图。 * @param value 第五层贴图。 */ diffuseTexture5: BaseTexture; diffuseScaleOffset1: Vector4; diffuseScaleOffset2: Vector4; diffuseScaleOffset3: Vector4; diffuseScaleOffset4: Vector4; diffuseScaleOffset5: Vector4; /** * 获取反射率颜色。 * @return 反射率颜色。 */ /** * 设置反射率颜色。 * @param value 反射率颜色。 */ albedo: Vector4; /** * 获取环境光颜色。 * @return 环境光颜色。 */ /** * 设置环境光颜色。 * @param value 环境光颜色 */ ambientColor: Vector3; /** * 获取漫反射颜色。 * @return 漫反射颜色。 */ /** * 设置漫反射颜色。 * @param value 漫反射颜色。 */ diffuseColor: Vector3; /** * 获取高光颜色。 * @return 高光颜色。 */ /** * 设置高光颜色。 * @param value 高光颜色。 */ specularColor: Vector4; /** * 设置禁受光照影响。 */ disableLight(): void; /** * 设置渲染模式。 * @return 渲染模式。 */ renderMode: number; constructor(); } } declare module laya.d3.core.material { import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; /** * ... * @author ... */ class GlitterMaterial extends BaseMaterial { /**渲染状态_不透明。*/ static RENDERMODE_OPAQUE: number; /**渲染状态_不透明_双面。*/ static RENDERMODE_OPAQUEDOUBLEFACE: number; /**渲染状态_透明混合。*/ static RENDERMODE_TRANSPARENT: number; /**渲染状态_透明混合_双面。*/ static RENDERMODE_TRANSPARENTDOUBLEFACE: number; /**渲染状态_加色法混合。*/ static RENDERMODE_ADDTIVE: number; /**渲染状态_加色法混合_双面。*/ static RENDERMODE_ADDTIVEDOUBLEFACE: number; /**渲染状态_只读深度_透明混合。*/ static RENDERMODE_DEPTHREAD_TRANSPARENT: number; /**渲染状态_只读深度_透明混合_双面。*/ static RENDERMODE_DEPTHREAD_TRANSPARENTDOUBLEFACE: number; /**渲染状态_只读深度_加色法混合。*/ static RENDERMODE_DEPTHREAD_ADDTIVE: number; /**渲染状态_只读深度_加色法混合_双面。*/ static RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE: number; /**渲染状态_无深度_透明混合。*/ static RENDERMODE_NONDEPTH_TRANSPARENT: number; /**渲染状态_无深度_透明混合_双面。*/ static RENDERMODE_NONDEPTH_TRANSPARENTDOUBLEFACE: number; /**渲染状态_无深度_加色法混合。*/ static RENDERMODE_NONDEPTH_ADDTIVE: number; /**渲染状态_无深度_加色法混合_双面。*/ static RENDERMODE_NONDEPTH_ADDTIVEDOUBLEFACE: number; static DIFFUSETEXTURE: number; static ALBEDO: number; static UNICOLOR: number; /** 默认材质,禁止修改*/ static defaultMaterial: GlitterMaterial; /** * 加载闪光材质。 * @param url 闪光材质地址。 */ static load(url: string): GlitterMaterial; /** * 设置渲染模式。 * @return 渲染模式。 */ renderMode: number; /** * 获取漫反射贴图。 * @return 漫反射贴图。 */ /** * 设置漫反射贴图。 * @param value 漫反射贴图。 */ diffuseTexture: BaseTexture; /** * 获取颜色。 * @return 漫反射颜色。 */ /** * 设置颜色。 * @param value 颜色。 */ color: Vector4; /** * 获取反射率。 * @return 反射率。 */ /** * 设置反射率。 * @param value 反射率。 */ albedo: Vector4; /** * @inheritDoc */ setShaderName(name: string): void; constructor(); } } declare module laya.d3.core.material { import TransformUV = laya.d3.core.TransformUV; import BaseTexture = laya.d3.resource.BaseTexture; import DataTexture2D = laya.d3.resource.DataTexture2D; import ShaderDefines = laya.d3.shader.ShaderDefines; class PBRMaterial extends BaseMaterial { static DIFFUSETEXTURE: number; static NORMALTEXTURE: number; static PBRINFOTEXTURE: number; static PBRLUTTEXTURE: number; static UVANIAGE: number; static MATERIALROUGHNESS: number; static MATERIALMETALESS: number; static UVMATRIX: number; static UVAGE: number; static AOOBJPOS: number; static HSNOISETEXTURE: number; static SHADERDEFINE_FIX_ROUGHNESS: number; static SHADERDEFINE_FIX_METALESS: number; static SHADERDEFINE_HAS_TANGENT: number; static SHADERDEFINE_TEST_CLIPZ: number; static SHADERDEFINE_HAS_PBRINFO: number; static SHADERDEFINE_USE_GROUNDTRUTH: number; /**渲染状态_不透明。*/ static RENDERMODE_OPAQUE: number; /**渲染状态_不透明_双面。*/ static RENDERMODE_OPAQUEDOUBLEFACE: number; /**渲染状态_透明测试。*/ static RENDERMODE_CUTOUT: number; /**渲染状态_透明测试_双面。*/ static RENDERMODE_CUTOUTDOUBLEFACE: number; /**渲染状态_透明混合。*/ static RENDERMODE_TRANSPARENT: number; static pbrlutTex: DataTexture2D; static HammersleyNoiseTex: DataTexture2D; protected _transformUV: TransformUV; /** 默认材质,禁止修改*/ static defaultMaterial: PBRMaterial; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 加载标准材质。 * @param url 标准材质地址。 */ static load(url: string): PBRMaterial; /** * 获取粗糙度的值,0为特别光滑,1为特别粗糙。 * @return 粗糙度的值。 */ /** * 设置粗糙度的值,0为特别光滑,1为特别粗糙。 * @param value 粗糙度。 */ roughness: number; metaless: number; has_tangent: boolean; use_groundtruth: boolean; /** * 获取漫反射贴图。 * @return 漫反射贴图。 */ /** * 设置漫反射贴图。 * @param value 漫反射贴图。 */ diffuseTexture: BaseTexture; /** * 获取PBRLUT贴图。 * @return PBRLUT贴图。 */ /** * 设置PBRLUT贴图。 * @param value PBRLUT贴图。 */ pbrlutTexture: BaseTexture; /** * 获取法线贴图。 * @return 法线贴图。 */ /** * 设置法线贴图。 * @param value 法线贴图。 */ normalTexture: BaseTexture; /** * 获取pbr信息贴图。 * @return pbr信息贴图。 */ /** * 设置pbr信息贴图。 * @param value pbr信息贴图。 */ pbrInfoTexture: BaseTexture; /** * 获取UV变换。 * @return UV变换。 */ /** * 设置UV变换。 * @param value UV变换。 */ transformUV: TransformUV; constructor(); /** * 禁用灯光。 */ disableLight(): void; /** * 禁用雾化。 */ disableFog(): void; renderMode: number; testClipZ: boolean; onAsynLoaded(url: string, data: any, params: Array): void; /** * vdc算法产生的序列。这个比random要均匀一些。 */ radicalInverse_VdC(bits: number): number; /** * */ createHammersleyTex(w: number, h: number): Uint8Array; } } declare module laya.d3.core.material { import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * ... * @author WuTaiLang */ class PBRSpecularMaterial extends BaseMaterial { static SmoothnessSource_MetallicGlossTexture_Alpha: number; static SmoothnessSource_DiffuseTexture_Alpha: number; static SHADERDEFINE_DIFFUSETEXTURE: number; static SHADERDEFINE_NORMALTEXTURE: number; static SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA: number; static SHADERDEFINE_SPECULARTEXTURE: number; static SHADERDEFINE_OCCLUSIONTEXTURE: number; static SHADERDEFINE_PARALLAXTEXTURE: number; static SHADERDEFINE_EMISSION: number; static SHADERDEFINE_EMISSIONTEXTURE: number; static SHADERDEFINE_TILINGOFFSET: number; static DIFFUSETEXTURE: number; static SPECULARTEXTURE: number; static NORMALTEXTURE: number; static PARALLAXTEXTURE: number; static OCCLUSIONTEXTURE: number; static EMISSIONTEXTURE: number; static DIFFUSECOLOR: number; static SPECULARCOLOR: number; static EMISSIONCOLOR: number; static SMOOTHNESS: number; static SMOOTHNESSSCALE: number; static SMOOTHNESSSOURCE: number; static OCCLUSIONSTRENGTH: number; static NORMALSCALE: number; static PARALLAXSCALE: number; static ENABLEEMISSION: number; static TILINGOFFSET: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 获取漫反射颜色。 * @return 漫反射颜色。 */ /** * 设置漫反射颜色。 * @param value 漫反射颜色。 */ albedoColor: Vector4; /** * 获取漫反射贴图。 * @return 漫反射贴图。 */ /** * 设置漫反射贴图。 * @param value 漫反射贴图。 */ albedoTexture: BaseTexture; /** * 获取法线贴图。 * @return 法线贴图。 */ /** * 设置法线贴图。 * @param value 法线贴图。 */ normalTexture: BaseTexture; /** * 获取法线贴图缩放系数。 * @return 法线贴图缩放系数。 */ /** * 设置法线贴图缩放系数。 * @param value 法线贴图缩放系数。 */ normalTextureScale: number; /** * 获取视差贴图。 * @return 视察贴图。 */ /** * 设置视差贴图。 * @param value 视察贴图。 */ parallaxTexture: BaseTexture; /** * 获取视差贴图缩放系数。 * @return 视差缩放系数。 */ /** * 设置视差贴图缩放系数。 * @param value 视差缩放系数。 */ parallaxTextureScale: number; /** * 获取遮挡贴图。 * @return 遮挡贴图。 */ /** * 设置遮挡贴图。 * @param value 遮挡贴图。 */ occlusionTexture: BaseTexture; /** * 获取遮挡贴图强度。 * @return 遮挡贴图强度,范围为0到1。 */ /** * 设置遮挡贴图强度。 * @param value 遮挡贴图强度,范围为0到1。 */ occlusionTextureStrength: number; /** * 获取高光贴图。 * @return 高光贴图。 */ /** * 设置高光贴图。 * @param value 高光贴图。 */ specularTexture: BaseTexture; /** * 获取高光颜色。 * @return 高光颜色。 */ /** * 设置高光颜色。 * @param value 高光颜色。 */ specularColor: Vector4; /** * 获取光滑度。 * @return 光滑度,范围为0到1。 */ /** * 设置光滑度。 * @param value 光滑度,范围为0到1。 */ smoothness: number; /** * 获取光滑度缩放系数。 * @return 光滑度缩放系数,范围为0到1。 */ /** * 设置光滑度缩放系数。 * @param value 光滑度缩放系数,范围为0到1。 */ smoothnessTextureScale: number; /** * 获取光滑度数据源 * @return 光滑滑度数据源,0或1。 */ /** * 设置光滑度数据源。 * @param value 光滑滑度数据源,0或1。 */ smoothnessSource: number; /** * 获取是否激活放射属性。 * @return 是否激活放射属性。 */ /** * 设置是否激活放射属性。 * @param value 是否激活放射属性 */ enableEmission: boolean; /** * 获取放射颜色。 * @return 放射颜色。 */ /** * 设置放射颜色。 * @param value 放射颜色。 */ emissionColor: Vector4; /** * 获取放射贴图。 * @return 放射贴图。 */ /** * 设置放射贴图。 * @param value 放射贴图。 */ emissionTexture: BaseTexture; /** * 获取纹理平铺和偏移。 * @return 纹理平铺和偏移。 */ /** * 设置纹理平铺和偏移。 * @param value 纹理平铺和偏移。 */ tilingOffset: Vector4; constructor(); } } declare module laya.d3.core.material { import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * ... * @author WuTaiLang */ class PBRStandardMaterial extends BaseMaterial { static SmoothnessSource_MetallicGlossTexture_Alpha: number; static SmoothnessSource_DiffuseTexture_Alpha: number; static SHADERDEFINE_DIFFUSETEXTURE: number; static SHADERDEFINE_NORMALTEXTURE: number; static SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA: number; static SHADERDEFINE_METALLICGLOSSTEXTURE: number; static SHADERDEFINE_OCCLUSIONTEXTURE: number; static SHADERDEFINE_PARALLAXTEXTURE: number; static SHADERDEFINE_EMISSION: number; static SHADERDEFINE_EMISSIONTEXTURE: number; static SHADERDEFINE_TILINGOFFSET: number; static DIFFUSETEXTURE: number; static METALLICGLOSSTEXTURE: number; static NORMALTEXTURE: number; static PARALLAXTEXTURE: number; static OCCLUSIONTEXTURE: number; static EMISSIONTEXTURE: number; static DIFFUSECOLOR: number; static EMISSIONCOLOR: number; static METALLIC: number; static SMOOTHNESS: number; static SMOOTHNESSSCALE: number; static SMOOTHNESSSOURCE: number; static OCCLUSIONSTRENGTH: number; static NORMALSCALE: number; static PARALLAXSCALE: number; static ENABLEEMISSION: number; static TILINGOFFSET: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 获取漫反射颜色。 * @return 漫反射颜色。 */ /** * 设置漫反射颜色。 * @param value 漫反射颜色。 */ albedoColor: Vector4; /** * 获取漫反射贴图。 * @return 漫反射贴图。 */ /** * 设置漫反射贴图。 * @param value 漫反射贴图。 */ albedoTexture: BaseTexture; /** * 获取法线贴图。 * @return 法线贴图。 */ /** * 设置法线贴图。 * @param value 法线贴图。 */ normalTexture: BaseTexture; /** * 获取法线贴图缩放系数。 * @return 法线贴图缩放系数。 */ /** * 设置法线贴图缩放系数。 * @param value 法线贴图缩放系数。 */ normalTextureScale: number; /** * 获取视差贴图。 * @return 视察贴图。 */ /** * 设置视差贴图。 * @param value 视察贴图。 */ parallaxTexture: BaseTexture; /** * 获取视差贴图缩放系数。 * @return 视差缩放系数。 */ /** * 设置视差贴图缩放系数。 * @param value 视差缩放系数。 */ parallaxTextureScale: number; /** * 获取遮挡贴图。 * @return 遮挡贴图。 */ /** * 设置遮挡贴图。 * @param value 遮挡贴图。 */ occlusionTexture: BaseTexture; /** * 获取遮挡贴图强度。 * @return 遮挡贴图强度,范围为0到1。 */ /** * 设置遮挡贴图强度。 * @param value 遮挡贴图强度,范围为0到1。 */ occlusionTextureStrength: number; /** * 获取金属光滑度贴图。 * @return 金属光滑度贴图。 */ /** * 设置金属光滑度贴图。 * @param value 金属光滑度贴图。 */ metallicGlossTexture: BaseTexture; /** * 获取金属度。 * @return 金属度,范围为0到1。 */ /** * 设置金属度。 * @param value 金属度,范围为0到1。 */ metallic: number; /** * 获取光滑度。 * @return 光滑度,范围为0到1。 */ /** * 设置光滑度。 * @param value 光滑度,范围为0到1。 */ smoothness: number; /** * 获取光滑度缩放系数。 * @return 光滑度缩放系数,范围为0到1。 */ /** * 设置光滑度缩放系数。 * @param value 光滑度缩放系数,范围为0到1。 */ smoothnessTextureScale: number; /** * 获取光滑度数据源 * @return 光滑滑度数据源,0或1。 */ /** * 设置光滑度数据源。 * @param value 光滑滑度数据源,0或1。 */ smoothnessSource: number; /** * 获取是否激活放射属性。 * @return 是否激活放射属性。 */ /** * 设置是否激活放射属性。 * @param value 是否激活放射属性 */ enableEmission: boolean; /** * 获取放射颜色。 * @return 放射颜色。 */ /** * 设置放射颜色。 * @param value 放射颜色。 */ emissionColor: Vector4; /** * 获取放射贴图。 * @return 放射贴图。 */ /** * 设置放射贴图。 * @param value 放射贴图。 */ emissionTexture: BaseTexture; /** * 获取纹理平铺和偏移。 * @return 纹理平铺和偏移。 */ /** * 设置纹理平铺和偏移。 * @param value 纹理平铺和偏移。 */ tilingOffset: Vector4; constructor(); } } declare module laya.d3.core.material { import TransformUV = laya.d3.core.TransformUV; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * ... * @author ... */ class StandardMaterial extends BaseMaterial { /**渲染状态_不透明。*/ static RENDERMODE_OPAQUE: number; /**渲染状态_不透明_双面。*/ static RENDERMODE_OPAQUEDOUBLEFACE: number; /**渲染状态_透明测试。*/ static RENDERMODE_CUTOUT: number; /**渲染状态_透明测试_双面。*/ static RENDERMODE_CUTOUTDOUBLEFACE: number; /**渲染状态_透明混合。*/ static RENDERMODE_TRANSPARENT: number; /**渲染状态_透明混合_双面。*/ static RENDERMODE_TRANSPARENTDOUBLEFACE: number; /**渲染状态_加色法混合。*/ static RENDERMODE_ADDTIVE: number; /**渲染状态_加色法混合_双面。*/ static RENDERMODE_ADDTIVEDOUBLEFACE: number; /**渲染状态_只读深度_透明混合。*/ static RENDERMODE_DEPTHREAD_TRANSPARENT: number; /**渲染状态_只读深度_透明混合_双面。*/ static RENDERMODE_DEPTHREAD_TRANSPARENTDOUBLEFACE: number; /**渲染状态_只读深度_加色法混合。*/ static RENDERMODE_DEPTHREAD_ADDTIVE: number; /**渲染状态_只读深度_加色法混合_双面。*/ static RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE: number; /**渲染状态_无深度_透明混合。*/ static RENDERMODE_NONDEPTH_TRANSPARENT: number; /**渲染状态_无深度_透明混合_双面。*/ static RENDERMODE_NONDEPTH_TRANSPARENTDOUBLEFACE: number; /**渲染状态_无深度_加色法混合。*/ static RENDERMODE_NONDEPTH_ADDTIVE: number; /**渲染状态_无深度_加色法混合_双面。*/ static RENDERMODE_NONDEPTH_ADDTIVEDOUBLEFACE: number; static SHADERDEFINE_DIFFUSEMAP: number; static SHADERDEFINE_NORMALMAP: number; static SHADERDEFINE_SPECULARMAP: number; static SHADERDEFINE_EMISSIVEMAP: number; static SHADERDEFINE_AMBIENTMAP: number; static SHADERDEFINE_REFLECTMAP: number; static SHADERDEFINE_UVTRANSFORM: number; static SHADERDEFINE_TILINGOFFSET: number; static SHADERDEFINE_ADDTIVEFOG: number; static DIFFUSETEXTURE: number; static NORMALTEXTURE: number; static SPECULARTEXTURE: number; static EMISSIVETEXTURE: number; static AMBIENTTEXTURE: number; static REFLECTTEXTURE: number; static ALBEDO: number; static UVANIAGE: number; static MATERIALAMBIENT: number; static MATERIALDIFFUSE: number; static MATERIALSPECULAR: number; static MATERIALREFLECT: number; static UVMATRIX: number; static UVAGE: number; static TILINGOFFSET: number; /** 默认材质,禁止修改*/ static defaultMaterial: StandardMaterial; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 加载标准材质。 * @param url 标准材质地址。 */ static load(url: string): StandardMaterial; protected _transformUV: TransformUV; /** * 设置渲染模式。 * @return 渲染模式。 */ renderMode: number; /** * 获取纹理平铺和偏移。 * @return 纹理平铺和偏移。 */ /** * 获取纹理平铺和偏移。 * @param value 纹理平铺和偏移。 */ tilingOffset: Vector4; /** * 设置环境光颜色。 * @param value 环境光颜色。 */ ambientColor: Vector3; /** * 设置漫反射光颜色。 * @param value 漫反射光颜色。 */ diffuseColor: Vector3; /** * 设置高光颜色。 * @param value 高光颜色。 */ specularColor: Vector4; /** * 设置反射颜色。 * @param value 反射颜色。 */ reflectColor: Vector3; /** * 设置反射率。 * @param value 反射率。 */ albedoColor: Vector4; /** * 设置反射率。 * @param value 反射率。 */ albedo: Vector4; /** * 获取漫反射贴图。 * @return 漫反射贴图。 */ /** * 设置漫反射贴图。 * @param value 漫反射贴图。 */ diffuseTexture: BaseTexture; /** * 获取法线贴图。 * @return 法线贴图。 */ /** * 设置法线贴图。 * @param value 法线贴图。 */ normalTexture: BaseTexture; /** * 获取高光贴图。 * @return 高光贴图。 */ /** * 设置高光贴图。 * @param value 高光贴图。 */ specularTexture: BaseTexture; /** * 获取放射贴图。 * @return 放射贴图。 */ /** * 设置放射贴图。 * @param value 放射贴图。 */ emissiveTexture: BaseTexture; /** * 获取环境贴图。 * @return 环境贴图。 */ /** * 设置环境贴图。 * @param value 环境贴图。 */ ambientTexture: BaseTexture; /** * 获取反射贴图。 * @return 反射贴图。 */ /** * 设置反射贴图。 * @param value 反射贴图。 */ reflectTexture: BaseTexture; /** * 获取UV变换。 * @return UV变换。 */ /** * 设置UV变换。 * @param value UV变换。 */ transformUV: TransformUV; constructor(); /** * @private */ static _parseStandardMaterial(textureMap: any, material: StandardMaterial, json: any): void; /** * 禁用灯光。 */ disableLight(): void; /** * 禁用雾化。 */ disableFog(): void; /** * @inheritDoc */ onAsynLoaded(url: string, data: any, params: Array): void; /** * @inheritDoc */ cloneTo(destObject: any): void; } } declare module laya.d3.core.material { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * ... * @author ... */ class TerrainMaterial extends BaseMaterial { /**渲染状态_不透明。*/ static RENDERMODE_OPAQUE: number; /**渲染状态_透明混合。*/ static RENDERMODE_TRANSPARENT: number; /**渲染状态_透明混合。*/ static SPLATALPHATEXTURE: number; static NORMALTEXTURE: number; static DIFFUSETEXTURE1: number; static DIFFUSETEXTURE2: number; static DIFFUSETEXTURE3: number; static DIFFUSETEXTURE4: number; static DIFFUSESCALE1: number; static DIFFUSESCALE2: number; static DIFFUSESCALE3: number; static DIFFUSESCALE4: number; static MATERIALAMBIENT: number; static MATERIALDIFFUSE: number; static MATERIALSPECULAR: number; /**地形细节宏定义。*/ static SHADERDEFINE_DETAIL_NUM1: number; static SHADERDEFINE_DETAIL_NUM2: number; static SHADERDEFINE_DETAIL_NUM3: number; static SHADERDEFINE_DETAIL_NUM4: number; /** 默认材质,禁止修改*/ static defaultMaterial: TerrainMaterial; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 加载闪光材质。 * @param url 闪光材质地址。 */ static load(url: string): TerrainMaterial; setDiffuseScale1(x: number, y: number): void; setDiffuseScale2(x: number, y: number): void; setDiffuseScale3(x: number, y: number): void; setDiffuseScale4(x: number, y: number): void; setDetailNum(value: number): void; ambientColor: Vector3; diffuseColor: Vector3; specularColor: Vector4; /** * 设置渲染模式。 * @return 渲染模式。 */ renderMode: number; /** * 获取第一层贴图。 * @return 第一层贴图。 */ /** * 设置第一层贴图。 * @param value 第一层贴图。 */ diffuseTexture1: BaseTexture; /** * 获取第二层贴图。 * @return 第二层贴图。 */ /** * 设置第二层贴图。 * @param value 第二层贴图。 */ diffuseTexture2: BaseTexture; /** * 获取第三层贴图。 * @return 第三层贴图。 */ /** * 设置第三层贴图。 * @param value 第三层贴图。 */ diffuseTexture3: BaseTexture; /** * 获取第四层贴图。 * @return 第四层贴图。 */ /** * 设置第四层贴图。 * @param value 第四层贴图。 */ diffuseTexture4: BaseTexture; /** * 获取splatAlpha贴图。 * @return splatAlpha贴图。 */ /** * 设置splatAlpha贴图。 * @param value splatAlpha贴图。 */ splatAlphaTexture: BaseTexture; normalTexture: BaseTexture; disableLight(): void; /** * @inheritDoc */ setShaderName(name: string): void; constructor(); } } declare module laya.d3.core.material { import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; class WaterMaterial extends BaseMaterial { static DIFFUSETEXTURE: number; static NORMALTEXTURE: number; static UNDERWATERTEXTURE: number; static VERTEXDISPTEXTURE: number; static UVANIAGE: number; static UVMATRIX: number; static UVAGE: number; static CURTM: number; static DETAILTEXTURE: number; static DEEPCOLORTEXTURE: number; static SKYTEXTURE: number; static WAVEINFO: number; static WAVEINFOD: number; static WAVEMAINDIR: number; static SCRSIZE: number; static WATERINFO: number; static FOAMTEXTURE: number; static GEOWAVE_UV_SCALE: number; static SEA_COLOR: number; static WAVEINFODEEPSCALE: number; static SHADERDEFINE_SHOW_NORMAL: number; static SHADERDEFINE_CUBE_ENV: number; static SHADERDEFINE_HDR_ENV: number; static SHADERDEFINE_USE_FOAM: number; static SHADERDEFINE_USE_REFRACT_TEX: number; /** * 如果定义了这个宏,就不再使用深度纹理,可以提高速度,但是建模麻烦一些。 */ static SHADERDEFINE_USEVERTEXHEIGHT: number; /**渲染状态_不透明。*/ static RENDERMODE_OPAQUE: number; /**渲染状态_不透明_双面。*/ static RENDERMODE_OPAQUEDOUBLEFACE: number; /**渲染状态_透明测试。*/ static RENDERMODE_CUTOUT: number; /**渲染状态_透明测试_双面。*/ static RENDERMODE_CUTOUTDOUBLEFACE: number; /**渲染状态_透明混合。*/ static RENDERMODE_TRANSPARENT: number; /** 默认材质,禁止修改*/ static defaultMaterial: WaterMaterial; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 加载标准材质。 * @param url 标准材质地址。 */ static load(url: string): WaterMaterial; /** * 获取漫反射贴图。 * @return 漫反射贴图。 */ /** * 设置漫反射贴图。 * @param value 漫反射贴图。 */ diffuseTexture: BaseTexture; /** * 获取法线贴图。 * @return 法线贴图。 */ /** * 设置法线贴图。 * @param value 法线贴图。 */ normalTexture: BaseTexture; underWaterTexture: BaseTexture; skyTexture: BaseTexture; waterInfoTexture: BaseTexture; foamTexture: BaseTexture; /** * 对定点进行变换的纹理。现在不用 */ vertexDispTexture: BaseTexture; detailTexture: BaseTexture; deepColorTexture: BaseTexture; currentTm: number; waveInfo: Float32Array; waveInfoD: Float32Array; waveMainDir: number; deepScale: number; geoWaveUVScale: number; scrsize: Float32Array; seaColor: Float32Array; useVertexDeep: boolean; windDir: number; windSpeed: number; useFoam: boolean; useRefractTexture: boolean; constructor(); /** * 禁用雾化。 */ disableFog(): void; renderMode: number; onAsynLoaded(url: string, data: any, params: Array): void; } } declare module laya.d3.core { import BoundBox = laya.d3.math.BoundBox; import BoundSphere = laya.d3.math.BoundSphere; import BaseMesh = laya.d3.resource.models.BaseMesh; /** * MeshFilter 类用于创建网格过滤器。 */ class MeshFilter extends GeometryFilter { /** * 获取共享网格。 * @return 共享网格。 */ /** * 设置共享网格。 * @return value 共享网格。 */ sharedMesh: BaseMesh; /** * @inheritDoc */ readonly _isAsyncLoaded: boolean; /** * @inheritDoc */ readonly _originalBoundingSphere: BoundSphere; /** * @inheritDoc */ readonly _originalBoundingBox: BoundBox; /** * @inheritDoc */ readonly _originalBoundingBoxCorners: Array; /** * 创建一个新的 MeshFilter 实例。 * @param owner 所属网格精灵。 */ constructor(owner: RenderableSprite3D); /** * @inheritDoc */ _destroy(): void; } } declare module laya.d3.core { import BaseRender = laya.d3.core.render.BaseRender; import BoundSphere = laya.d3.math.BoundSphere; import Matrix4x4 = laya.d3.math.Matrix4x4; /** * MeshRender 类用于网格渲染器。 */ class MeshRender extends BaseRender { /** * 创建一个新的 MeshRender 实例。 */ constructor(owner: RenderableSprite3D); protected _calculateBoundingSphereByInitSphere(boundSphere: BoundSphere): void; protected _calculateBoundBoxByInitCorners(corners: Array): void; protected _calculateBoundingSphere(): void; protected _calculateBoundingBox(): void; /** * @private */ _renderUpdate(projectionView: Matrix4x4): boolean; } } declare module laya.d3.core { import BaseMesh = laya.d3.resource.models.BaseMesh; import Mesh = laya.d3.resource.models.Mesh; /** * MeshSprite3D 类用于创建网格。 */ class MeshSprite3D extends RenderableSprite3D { /** * @private */ static __init__(): void; /** * 加载网格模板。 * @param url 模板地址。 */ static load(url: string): MeshSprite3D; /** * 获取网格过滤器。 * @return 网格过滤器。 */ readonly meshFilter: MeshFilter; /** * 获取网格渲染器。 * @return 网格渲染器。 */ readonly meshRender: MeshRender; /** * 创建一个 MeshSprite3D 实例。 * @param mesh 网格,同时会加载网格所用默认材质。 * @param name 名字。 */ constructor(mesh?: BaseMesh, name?: string); protected _clearSelfRenderObjects(): void; protected _addSelfRenderObjects(): void; protected _parseCustomProps(rootNode: ComponentNode, innerResouMap: any, customProps: any, json: any): void; /** * @private */ _applyMeshMaterials(mesh: Mesh): void; /** * @inheritDoc */ _addToInitStaticBatchManager(): void; /** * @inheritDoc */ cloneTo(destObject: any): void; /** * @inheritDoc */ destroy(destroyChild?: boolean): void; /** * @private */ createConchModel(): any; } } declare module laya.d3.core { import RenderState = laya.d3.core.render.RenderState; import Texture2D = laya.d3.resource.Texture2D; import Mesh = laya.d3.resource.models.Mesh; /** * TerrainMeshSprite3D 类用于创建网格。 */ class MeshTerrainSprite3D extends MeshSprite3D { /** * 从网格创建一个TerrainMeshSprite3D实例和其高度图属性。 * @param mesh 网格。 * @param heightMapWidth 高度图宽度。 * @param heightMapHeight 高度图高度。 * @param name 名字。 */ static createFromMesh(mesh: Mesh, heightMapWidth: number, heightMapHeight: number, name?: string): MeshTerrainSprite3D; /** * 从网格创建一个TerrainMeshSprite3D实例、图片读取高度图属性。 * @param mesh 网格。 * @param image 高度图。 * @param name 名字。 */ static createFromMeshAndHeightMap(mesh: Mesh, texture: Texture2D, minHeight: number, maxHeight: number, name?: string): MeshTerrainSprite3D; /** * 获取地形X轴最小位置。 * @return 地形X轴最小位置。 */ readonly minX: number; /** * 获取地形Z轴最小位置。 * @return 地形X轴最小位置。 */ readonly minZ: number; /** * 获取地形X轴长度。 * @return 地形X轴长度。 */ readonly width: number; /** * 获取地形Z轴长度。 * @return 地形Z轴长度。 */ readonly depth: number; /** * 创建一个 TerrainMeshSprite3D 实例。 * @param mesh 网格。 * @param heightMap 高度图。 * @param name 名字。 */ constructor(mesh: Mesh, heightMap: HeightMap, name?: string); /** * @private */ _update(state: RenderState): void; /** * 获取地形高度。 * @param x X轴坐标。 * @param z Z轴坐标。 */ getHeight(x: number, z: number): number; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; /** * Burst 类用于粒子的爆裂描述。 */ class Burst implements IClone { /** * 获取爆裂时间,单位为秒。 * @return 爆裂时间,单位为秒。 */ readonly time: number; /** * 获取爆裂的最小数量。 * @return 爆裂的最小数量。 */ readonly minCount: number; /** * 获取爆裂的最大数量。 * @return 爆裂的最大数量。 */ readonly maxCount: number; /** * 创建一个 Burst 实例。 * @param time 爆裂时间,单位为秒。 * @param minCount 爆裂的最小数量。 * @param time 爆裂的最大数量。 */ constructor(time: number, minCount: number, maxCount: number); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { /** * ColorOverLifetime 类用于粒子的生命周期颜色。 */ class ColorOverLifetime { /**是否启用。*/ enbale: boolean; /** *获取颜色。 */ readonly color: GradientColor; /** * 创建一个 ColorOverLifetime 实例。 */ constructor(color: GradientColor); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; import IDestroy = laya.resource.IDestroy; /** * Emission 类用于粒子发射器。 */ class Emission implements IClone, IDestroy { _bursts: Array; /**是否启用。*/ enbale: boolean; /** * 获取粒子发射速率。 * @return 粒子发射速率 (个/秒)。 */ /** * 设置粒子发射速率。 * @param emissionRate 粒子发射速率 (个/秒)。 */ emissionRate: number; /** * 获取是否已销毁。 * @return 是否已销毁。 */ readonly destroyed: boolean; /** * 创建一个 Emission 实例。 */ constructor(); /** * @private */ _destroy(): void; /** * 获取粒子爆裂个数。 * @return 粒子爆裂个数。 */ getBurstsCount(): number; /** * 通过索引获取粒子爆裂。 * @param index 爆裂索引。 * @return 粒子爆裂。 */ getBurstByIndex(index: number): Burst; /** * 增加粒子爆裂。 * @param burst 爆裂。 */ addBurst(burst: Burst): void; /** * 移除粒子爆裂。 * @param burst 爆裂。 */ removeBurst(burst: Burst): void; /** * 通过索引移除粒子爆裂。 * @param index 爆裂索引。 */ removeBurstByIndex(index: number): void; /** * 清空粒子爆裂。 */ clearBurst(): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; /** * FrameOverTime 类用于创建时间帧。 */ class FrameOverTime implements IClone { /** * 通过固定帧创建一个 FrameOverTime 实例。 * @param constant 固定帧。 * @return 时间帧。 */ static createByConstant(constant: number): FrameOverTime; /** * 通过时间帧创建一个 FrameOverTime 实例。 * @param overTime 时间帧。 * @return 时间帧。 */ static createByOverTime(overTime: GradientDataInt): FrameOverTime; /** * 通过随机双固定帧创建一个 FrameOverTime 实例。 * @param constantMin 最小固定帧。 * @param constantMax 最大固定帧。 * @return 时间帧。 */ static createByRandomTwoConstant(constantMin: number, constantMax: number): FrameOverTime; /** * 通过随机双时间帧创建一个 FrameOverTime 实例。 * @param gradientFrameMin 最小时间帧。 * @param gradientFrameMax 最大时间帧。 * @return 时间帧。 */ static createByRandomTwoOverTime(gradientFrameMin: GradientDataInt, gradientFrameMax: GradientDataInt): FrameOverTime; /** *生命周期旋转类型,0常量模式,1曲线模式,2随机双常量模式,3随机双曲线模式。 */ readonly type: number; /** * 固定帧。 */ readonly constant: number; /** * 时间帧。 */ readonly frameOverTimeData: GradientDataInt; /** * 最小固定帧。 */ readonly constantMin: number; /** * 最大固定帧。 */ readonly constantMax: number; /** * 最小时间帧。 */ readonly frameOverTimeDataMin: GradientDataInt; /** * 最大时间帧。 */ readonly frameOverTimeDataMax: GradientDataInt; /** * 创建一个 FrameOverTime,不允许new,请使用静态创建函数。 实例。 */ constructor(); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * GradientRotation 类用于创建渐变角速度。 */ class GradientAngularVelocity implements IClone { /** * 通过固定角速度创建一个 GradientAngularVelocity 实例。 * @param constant 固定角速度。 * @return 渐变角速度。 */ static createByConstant(constant: number): GradientAngularVelocity; /** * 通过分轴固定角速度创建一个 GradientAngularVelocity 实例。 * @param separateConstant 分轴固定角速度。 * @return 渐变角速度。 */ static createByConstantSeparate(separateConstant: Vector4): GradientAngularVelocity; /** * 通过渐变角速度创建一个 GradientAngularVelocity 实例。 * @param gradient 渐变角速度。 * @return 渐变角速度。 */ static createByGradient(gradient: GradientDataNumber): GradientAngularVelocity; /** * 通过分轴渐变角速度创建一个 GradientAngularVelocity 实例。 * @param gradientX X轴渐变角速度。 * @param gradientY Y轴渐变角速度。 * @param gradientZ Z轴渐变角速度。 * @return 渐变角速度。 */ static createByGradientSeparate(gradientX: GradientDataNumber, gradientY: GradientDataNumber, gradientZ: GradientDataNumber, gradientW: GradientDataNumber): GradientAngularVelocity; /** * 通过随机双固定角速度创建一个 GradientAngularVelocity 实例。 * @param constantMin 最小固定角速度。 * @param constantMax 最大固定角速度。 * @return 渐变角速度。 */ static createByRandomTwoConstant(constantMin: number, constantMax: number): GradientAngularVelocity; /** * 通过随机分轴双固定角速度创建一个 GradientAngularVelocity 实例。 * @param separateConstantMin 最小分轴固定角速度。 * @param separateConstantMax 最大分轴固定角速度。 * @return 渐变角速度。 */ static createByRandomTwoConstantSeparate(separateConstantMin: Vector3, separateConstantMax: Vector3): GradientAngularVelocity; /** * 通过随机双渐变角速度创建一个 GradientAngularVelocity 实例。 * @param gradientMin 最小渐变角速度。 * @param gradientMax 最大渐变角速度。 * @return 渐变角速度。 */ static createByRandomTwoGradient(gradientMin: GradientDataNumber, gradientMax: GradientDataNumber): GradientAngularVelocity; /** * 通过分轴随机双渐变角速度创建一个 GradientAngularVelocity 实例。 * @param gradientXMin 最小X轴渐变角速度。 * @param gradientXMax 最大X轴渐变角速度。 * @param gradientYMin 最小Y轴渐变角速度。 * @param gradientYMax 最大Y轴渐变角速度。 * @param gradientZMin 最小Z轴渐变角速度。 * @param gradientZMax 最大Z轴渐变角速度。 * @return 渐变角速度。 */ static createByRandomTwoGradientSeparate(gradientXMin: GradientDataNumber, gradientXMax: GradientDataNumber, gradientYMin: GradientDataNumber, gradientYMax: GradientDataNumber, gradientZMin: GradientDataNumber, gradientZMax: GradientDataNumber, gradientWMin: GradientDataNumber, gradientWMax: GradientDataNumber): GradientAngularVelocity; /** *生命周期角速度类型,0常量模式,1曲线模式,2随机双常量模式,3随机双曲线模式。 */ readonly type: number; /** *是否分轴。 */ readonly separateAxes: boolean; /** * 固定角速度。 */ readonly constant: number; /** * 分轴固定角速度。 */ readonly constantSeparate: Vector4; /** * 渐变角速度。 */ readonly gradient: GradientDataNumber; /** * 渐变角角速度X。 */ readonly gradientX: GradientDataNumber; /** * 渐变角速度Y。 */ readonly gradientY: GradientDataNumber; /** *渐变角速度Z。 */ readonly gradientZ: GradientDataNumber; /** *渐变角速度Z。 */ readonly gradientW: GradientDataNumber; /** * 最小随机双固定角速度。 */ readonly constantMin: number; /** * 最大随机双固定角速度。 */ readonly constantMax: number; /** * 最小分轴随机双固定角速度。 */ readonly constantMinSeparate: Vector3; /** * 最大分轴随机双固定角速度。 */ readonly constantMaxSeparate: Vector3; /** *最小渐变角速度。 */ readonly gradientMin: GradientDataNumber; /** * 最大渐变角速度。 */ readonly gradientMax: GradientDataNumber; /** * 最小渐变角速度X。 */ readonly gradientXMin: GradientDataNumber; /** * 最大渐变角速度X。 */ readonly gradientXMax: GradientDataNumber; /** * 最小渐变角速度Y。 */ readonly gradientYMin: GradientDataNumber; /** *最大渐变角速度Y。 */ readonly gradientYMax: GradientDataNumber; /** * 最小渐变角速度Z。 */ readonly gradientZMin: GradientDataNumber; /** * 最大渐变角速度Z。 */ readonly gradientZMax: GradientDataNumber; /** * 最小渐变角速度Z。 */ readonly gradientWMin: GradientDataNumber; /** * 最大渐变角速度Z。 */ readonly gradientWMax: GradientDataNumber; /** * 创建一个 GradientAngularVelocity,不允许new,请使用静态创建函数。 实例。 */ constructor(); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; import Vector4 = laya.d3.math.Vector4; /** * GradientColor 类用于创建渐变颜色。 */ class GradientColor implements IClone { /** * 通过固定颜色创建一个 GradientColor 实例。 * @param constant 固定颜色。 */ static createByConstant(constant: Vector4): GradientColor; /** * 通过渐变颜色创建一个 GradientColor 实例。 * @param gradient 渐变色。 */ static createByGradient(gradient: GradientDataColor): GradientColor; /** * 通过随机双固定颜色创建一个 GradientColor 实例。 * @param minConstant 最小固定颜色。 * @param maxConstant 最大固定颜色。 */ static createByRandomTwoConstant(minConstant: Vector4, maxConstant: Vector4): GradientColor; /** * 通过随机双渐变颜色创建一个 GradientColor 实例。 * @param minGradient 最小渐变颜色。 * @param maxGradient 最大渐变颜色。 */ static createByRandomTwoGradient(minGradient: GradientDataColor, maxGradient: GradientDataColor): GradientColor; /** *生命周期颜色类型,0为固定颜色模式,1渐变模式,2为随机双固定颜色模式,3随机双渐变模式。 */ readonly type: number; /** * 固定颜色。 */ readonly constant: Vector4; /** * 最小固定颜色。 */ readonly constantMin: Vector4; /** * 最大固定颜色。 */ readonly constantMax: Vector4; /** * 渐变颜色。 */ readonly gradient: GradientDataColor; /** * 最小渐变颜色。 */ readonly gradientMin: GradientDataColor; /** * 最大渐变颜色。 */ readonly gradientMax: GradientDataColor; /** * 创建一个 GradientColor,不允许new,请使用静态创建函数。 实例。 */ constructor(); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; import Vector3 = laya.d3.math.Vector3; /** * GradientDataColor 类用于创建颜色渐变。 */ class GradientDataColor implements IClone { _alphaElements: Float32Array; _rgbElements: Float32Array; /**渐变Alpha数量。*/ readonly alphaGradientCount: number; /**渐变RGB数量。*/ readonly rgbGradientCount: number; /** * 创建一个 GradientDataColor 实例。 */ constructor(); /** * 增加Alpha渐变。 * @param key 生命周期,范围为0到1。 * @param value rgb值。 */ addAlpha(key: number, value: number): void; /** * 增加RGB渐变。 * @param key 生命周期,范围为0到1。 * @param value RGB值。 */ addRGB(key: number, value: Vector3): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; /** * GradientDataInt 类用于创建整形渐变。 */ class GradientDataInt implements IClone { _elements: Float32Array; /**整形渐变数量。*/ readonly gradientCount: number; /** * 创建一个 GradientDataInt 实例。 */ constructor(); /** * 增加整形渐变。 * @param key 生命周期,范围为0到1。 * @param value 整形值。 */ add(key: number, value: number): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; /** * GradientDataNumber 类用于创建浮点渐变。 */ class GradientDataNumber implements IClone { _elements: Float32Array; /**渐变浮点数量。*/ readonly gradientCount: number; /** * 创建一个 GradientDataNumber 实例。 */ constructor(); /** * 增加浮点渐变。 * @param key 生命周期,范围为0到1。 * @param value 浮点值。 */ add(key: number, value: number): void; /** * 通过索引获取键。 * @param index 索引。 * @return value 键。 */ getKeyByIndex(index: number): number; /** * 通过索引获取值。 * @param index 索引。 * @return value 值。 */ getValueByIndex(index: number): number; /** * 获取平均值。 */ getAverageValue(): number; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; import Vector2 = laya.d3.math.Vector2; /** * GradientDataVector2 类用于创建二维向量渐变。 */ class GradientDataVector2 implements IClone { _elements: Float32Array; /**二维向量渐变数量。*/ readonly gradientCount: number; /** * 创建一个 GradientDataVector2 实例。 */ constructor(); /** * 增加二维向量渐变。 * @param key 生命周期,范围为0到1。 * @param value 二维向量值。 */ add(key: number, value: Vector2): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; import Vector3 = laya.d3.math.Vector3; /** * GradientSize 类用于创建渐变尺寸。 */ class GradientSize implements IClone { /** * 通过渐变尺寸创建一个 GradientSize 实例。 * @param gradient 渐变尺寸。 * @return 渐变尺寸。 */ static createByGradient(gradient: GradientDataNumber): GradientSize; /** * 通过分轴渐变尺寸创建一个 GradientSize 实例。 * @param gradientX 渐变尺寸X。 * @param gradientY 渐变尺寸Y。 * @param gradientZ 渐变尺寸Z。 * @return 渐变尺寸。 */ static createByGradientSeparate(gradientX: GradientDataNumber, gradientY: GradientDataNumber, gradientZ: GradientDataNumber): GradientSize; /** * 通过随机双固定尺寸创建一个 GradientSize 实例。 * @param constantMin 最小固定尺寸。 * @param constantMax 最大固定尺寸。 * @return 渐变尺寸。 */ static createByRandomTwoConstant(constantMin: number, constantMax: number): GradientSize; /** * 通过分轴随机双固定尺寸创建一个 GradientSize 实例。 * @param constantMinSeparate 分轴最小固定尺寸. * @param constantMaxSeparate 分轴最大固定尺寸。 * @return 渐变尺寸。 */ static createByRandomTwoConstantSeparate(constantMinSeparate: Vector3, constantMaxSeparate: Vector3): GradientSize; /** * 通过随机双渐变尺寸创建一个 GradientSize 实例。 * @param gradientMin 最小渐变尺寸。 * @param gradientMax 最大渐变尺寸。 * @return 渐变尺寸。 */ static createByRandomTwoGradient(gradientMin: GradientDataNumber, gradientMax: GradientDataNumber): GradientSize; /** * 通过分轴随机双渐变尺寸创建一个 GradientSize 实例。 * @param gradientXMin X轴最小渐变尺寸。 * @param gradientXMax X轴最大渐变尺寸。 * @param gradientYMin Y轴最小渐变尺寸。 * @param gradientYMax Y轴最大渐变尺寸。 * @param gradientZMin Z轴最小渐变尺寸。 * @param gradientZMax Z轴最大渐变尺寸。 * @return 渐变尺寸。 */ static createByRandomTwoGradientSeparate(gradientXMin: GradientDataNumber, gradientXMax: GradientDataNumber, gradientYMin: GradientDataNumber, gradientYMax: GradientDataNumber, gradientZMin: GradientDataNumber, gradientZMax: GradientDataNumber): GradientSize; /** *生命周期尺寸类型,0曲线模式,1随机双常量模式,2随机双曲线模式。 */ readonly type: number; /** *是否分轴。 */ readonly separateAxes: boolean; /** * 渐变尺寸。 */ readonly gradient: GradientDataNumber; /** * 渐变尺寸X。 */ readonly gradientX: GradientDataNumber; /** * 渐变尺寸Y。 */ readonly gradientY: GradientDataNumber; /** *渐变尺寸Z。 */ readonly gradientZ: GradientDataNumber; /** *最小随机双固定尺寸。 */ readonly constantMin: number; /** * 最大随机双固定尺寸。 */ readonly constantMax: number; /** * 最小分轴随机双固定尺寸。 */ readonly constantMinSeparate: Vector3; /** * 最小分轴随机双固定尺寸。 */ readonly constantMaxSeparate: Vector3; /** *渐变最小尺寸。 */ readonly gradientMin: GradientDataNumber; /** * 渐变最大尺寸。 */ readonly gradientMax: GradientDataNumber; /** * 渐变最小尺寸X。 */ readonly gradientXMin: GradientDataNumber; /** * 渐变最大尺寸X。 */ readonly gradientXMax: GradientDataNumber; /** * 渐变最小尺寸Y。 */ readonly gradientYMin: GradientDataNumber; /** *渐变最大尺寸Y。 */ readonly gradientYMax: GradientDataNumber; /** * 渐变最小尺寸Z。 */ readonly gradientZMin: GradientDataNumber; /** * 渐变最大尺寸Z。 */ readonly gradientZMax: GradientDataNumber; /** * 创建一个 GradientSize,不允许new,请使用静态创建函数。 实例。 */ constructor(); /** * 获取最大尺寸。 */ getMaxSizeInGradient(): number; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; import Vector3 = laya.d3.math.Vector3; /** * GradientVelocity 类用于创建渐变速度。 */ class GradientVelocity implements IClone { /** * 通过固定速度创建一个 GradientVelocity 实例。 * @param constant 固定速度。 * @return 渐变速度。 */ static createByConstant(constant: Vector3): GradientVelocity; /** * 通过渐变速度创建一个 GradientVelocity 实例。 * @param gradientX 渐变速度X。 * @param gradientY 渐变速度Y。 * @param gradientZ 渐变速度Z。 * @return 渐变速度。 */ static createByGradient(gradientX: GradientDataNumber, gradientY: GradientDataNumber, gradientZ: GradientDataNumber): GradientVelocity; /** * 通过随机双固定速度创建一个 GradientVelocity 实例。 * @param constantMin 最小固定角速度。 * @param constantMax 最大固定角速度。 * @return 渐变速度。 */ static createByRandomTwoConstant(constantMin: Vector3, constantMax: Vector3): GradientVelocity; /** * 通过随机双渐变速度创建一个 GradientVelocity 实例。 * @param gradientXMin X轴最小渐变速度。 * @param gradientXMax X轴最大渐变速度。 * @param gradientYMin Y轴最小渐变速度。 * @param gradientYMax Y轴最大渐变速度。 * @param gradientZMin Z轴最小渐变速度。 * @param gradientZMax Z轴最大渐变速度。 * @return 渐变速度。 */ static createByRandomTwoGradient(gradientXMin: GradientDataNumber, gradientXMax: GradientDataNumber, gradientYMin: GradientDataNumber, gradientYMax: GradientDataNumber, gradientZMin: GradientDataNumber, gradientZMax: GradientDataNumber): GradientVelocity; /** *生命周期速度类型,0常量模式,1曲线模式,2随机双常量模式,3随机双曲线模式。 */ readonly type: number; /**固定速度。*/ readonly constant: Vector3; /** * 渐变速度X。 */ readonly gradientX: GradientDataNumber; /** * 渐变速度Y。 */ readonly gradientY: GradientDataNumber; /** *渐变速度Z。 */ readonly gradientZ: GradientDataNumber; /**最小固定速度。*/ readonly constantMin: Vector3; /**最大固定速度。*/ readonly constantMax: Vector3; /** * 渐变最小速度X。 */ readonly gradientXMin: GradientDataNumber; /** * 渐变最大速度X。 */ readonly gradientXMax: GradientDataNumber; /** * 渐变最小速度Y。 */ readonly gradientYMin: GradientDataNumber; /** *渐变最大速度Y。 */ readonly gradientYMax: GradientDataNumber; /** * 渐变最小速度Z。 */ readonly gradientZMin: GradientDataNumber; /** * 渐变最大速度Z。 */ readonly gradientZMax: GradientDataNumber; /** * 创建一个 GradientVelocity,不允许new,请使用静态创建函数。 实例。 */ constructor(); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; /** * RotationOverLifetime 类用于粒子的生命周期旋转。 */ class RotationOverLifetime implements IClone { /**是否启用*/ enbale: boolean; /** *获取角速度。 */ readonly angularVelocity: GradientAngularVelocity; /** * 创建一个 RotationOverLifetime,不允许new,请使用静态创建函数。 实例。 */ constructor(angularVelocity: GradientAngularVelocity); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module.shape { import IClone = laya.d3.core.IClone; import BoundBox = laya.d3.math.BoundBox; import Rand = laya.d3.math.Rand; import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * BaseShape 类用于粒子形状。 */ class BaseShape implements IClone { /**是否启用。*/ enable: boolean; /**随机方向。*/ randomDirection: boolean; /** * 创建一个 BaseShape 实例。 */ constructor(); protected _getShapeBoundBox(boundBox: BoundBox): void; protected _getSpeedBoundBox(boundBox: BoundBox): void; /** * 用于生成粒子初始位置和方向。 * @param position 粒子位置。 * @param direction 粒子方向。 */ generatePositionAndDirection(position: Vector3, direction: Vector3, rand?: Rand, randomSeeds?: Uint32Array): void; /** * @private */ _calculateProceduralBounds(boundBox: BoundBox, emitterPosScale: Vector3, minMaxBounds: Vector2): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module.shape { import BoundBox = laya.d3.math.BoundBox; import Rand = laya.d3.math.Rand; import Vector3 = laya.d3.math.Vector3; /** * BoxShape 类用于创建球形粒子形状。 */ class BoxShape extends BaseShape { /**发射器X轴长度。*/ x: number; /**发射器Y轴长度。*/ y: number; /**发射器Z轴长度。*/ z: number; /** * 创建一个 BoxShape 实例。 */ constructor(); protected _getShapeBoundBox(boundBox: BoundBox): void; protected _getSpeedBoundBox(boundBox: BoundBox): void; /** * 用于生成粒子初始位置和方向。 * @param position 粒子位置。 * @param direction 粒子方向。 */ generatePositionAndDirection(position: Vector3, direction: Vector3, rand?: Rand, randomSeeds?: Uint32Array): void; cloneTo(destObject: any): void; } } declare module laya.d3.core.particleShuriKen.module.shape { import BoundBox = laya.d3.math.BoundBox; import Rand = laya.d3.math.Rand; import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * CircleShape 类用于创建环形粒子形状。 */ class CircleShape extends BaseShape { protected static _tempPositionPoint: Vector2; /**发射器半径。*/ radius: number; /**环形弧度。*/ arc: number; /**从边缘发射。*/ emitFromEdge: boolean; /** * 创建一个 CircleShape 实例。 */ constructor(); protected _getShapeBoundBox(boundBox: BoundBox): void; protected _getSpeedBoundBox(boundBox: BoundBox): void; /** * 用于生成粒子初始位置和方向。 * @param position 粒子位置。 * @param direction 粒子方向。 */ generatePositionAndDirection(position: Vector3, direction: Vector3, rand?: Rand, randomSeeds?: Uint32Array): void; cloneTo(destObject: any): void; } } declare module laya.d3.core.particleShuriKen.module.shape { import BoundBox = laya.d3.math.BoundBox; import Rand = laya.d3.math.Rand; import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * ConeShape 类用于创建锥形粒子形状。 */ class ConeShape extends BaseShape { protected static _tempPositionPoint: Vector2; protected static _tempDirectionPoint: Vector2; /**发射角度。*/ angle: number; /**发射器半径。*/ radius: number; /**椎体长度。*/ length: number; /**发射类型,0为Base,1为BaseShell,2为Volume,3为VolumeShell。*/ emitType: number; /** * 创建一个 ConeShape 实例。 */ constructor(); protected _getShapeBoundBox(boundBox: BoundBox): void; protected _getSpeedBoundBox(boundBox: BoundBox): void; /** * 用于生成粒子初始位置和方向。 * @param position 粒子位置。 * @param direction 粒子方向。 */ generatePositionAndDirection(position: Vector3, direction: Vector3, rand?: Rand, randomSeeds?: Uint32Array): void; cloneTo(destObject: any): void; } } declare module laya.d3.core.particleShuriKen.module.shape { import BoundBox = laya.d3.math.BoundBox; import Rand = laya.d3.math.Rand; import Vector3 = laya.d3.math.Vector3; /** * HemisphereShape 类用于创建半球形粒子形状。 */ class HemisphereShape extends BaseShape { /**发射器半径。*/ radius: number; /**从外壳发射。*/ emitFromShell: boolean; /** * 创建一个 HemisphereShape 实例。 */ constructor(); protected _getShapeBoundBox(boundBox: BoundBox): void; protected _getSpeedBoundBox(boundBox: BoundBox): void; /** * 用于生成粒子初始位置和方向。 * @param position 粒子位置。 * @param direction 粒子方向。 */ generatePositionAndDirection(position: Vector3, direction: Vector3, rand?: Rand, randomSeeds?: Uint32Array): void; cloneTo(destObject: any): void; } } declare module laya.d3.core.particleShuriKen.module.shape { import Rand = laya.d3.math.Rand; import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * ... * @author ... */ class ShapeUtils { static _randomPointUnitArcCircle(arc: number, out: Vector2, rand?: Rand): void; static _randomPointInsideUnitArcCircle(arc: number, out: Vector2, rand?: Rand): void; static _randomPointUnitCircle(out: Vector2, rand?: Rand): void; static _randomPointInsideUnitCircle(out: Vector2, rand?: Rand): void; static _randomPointUnitSphere(out: Vector3, rand?: Rand): void; static _randomPointInsideUnitSphere(out: Vector3, rand?: Rand): void; static _randomPointInsideHalfUnitBox(out: Vector3, rand?: Rand): void; constructor(); } } declare module laya.d3.core.particleShuriKen.module.shape { import BoundBox = laya.d3.math.BoundBox; import Rand = laya.d3.math.Rand; import Vector3 = laya.d3.math.Vector3; /** * SphereShape 类用于创建球形粒子形状。 */ class SphereShape extends BaseShape { /**发射器半径。*/ radius: number; /**从外壳发射。*/ emitFromShell: boolean; /** * 创建一个 SphereShape 实例。 */ constructor(); protected _getShapeBoundBox(boundBox: BoundBox): void; protected _getSpeedBoundBox(boundBox: BoundBox): void; /** * 用于生成粒子初始位置和方向。 * @param position 粒子位置。 * @param direction 粒子方向。 */ generatePositionAndDirection(position: Vector3, direction: Vector3, rand?: Rand, randomSeeds?: Uint32Array): void; cloneTo(destObject: any): void; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; /** * SizeOverLifetime 类用于粒子的生命周期尺寸。 */ class SizeOverLifetime implements IClone { /**是否启用*/ enbale: boolean; /** *获取尺寸。 */ readonly size: GradientSize; /** * 创建一个 SizeOverLifetime 实例。 */ constructor(size: GradientSize); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; /** * StartFrame 类用于创建开始帧。 */ class StartFrame implements IClone { /** * 通过随机常量旋转创建一个 StartFrame 实例。 * @param constant 固定帧。 * @return 开始帧。 */ static createByConstant(constant: number): StartFrame; /** * 通过随机双常量旋转创建一个 StartFrame 实例。 * @param constantMin 最小固定帧。 * @param constantMax 最大固定帧。 * @return 开始帧。 */ static createByRandomTwoConstant(constantMin: number, constantMax: number): StartFrame; /** *开始帧类型,0常量模式,1随机双常量模式。 */ readonly type: number; /** * 固定帧。 */ readonly constant: number; /** * 最小固定帧。 */ readonly constantMin: number; /** * 最大固定帧。 */ readonly constantMax: number; /** * 创建一个 StartFrame,不允许new,请使用静态创建函数。 实例。 */ constructor(); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; import Vector2 = laya.d3.math.Vector2; /** * TextureSheetAnimation 类用于创建粒子帧动画。 */ class TextureSheetAnimation implements IClone { /**纹理平铺。*/ tiles: Vector2; /**类型,0为whole sheet、1为singal row。*/ type: number; /**是否随机行,type为1时有效。*/ randomRow: boolean; /**行索引,type为1时有效。*/ rowIndex: number; /**循环次数。*/ cycles: number; /**UV通道类型,0为Noting,1为Everything,待补充,暂不支持。*/ enableUVChannels: number; /**是否启用*/ enable: boolean; /**获取时间帧率。*/ readonly frame: FrameOverTime; /**获取开始帧率。*/ readonly startFrame: StartFrame; /** * 创建一个 TextureSheetAnimation 实例。 * @param frame 动画帧。 * @param startFrame 开始帧。 */ constructor(frame: FrameOverTime, startFrame: StartFrame); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen.module { import IClone = laya.d3.core.IClone; /** * VelocityOverLifetime 类用于粒子的生命周期速度。 */ class VelocityOverLifetime implements IClone { /**是否启用*/ enbale: boolean; /**速度空间,0为local,1为world。*/ space: number; /** *获取尺寸。 */ readonly velocity: GradientVelocity; /** * 创建一个 VelocityOverLifetime 实例。 */ constructor(velocity: GradientVelocity); /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core.particleShuriKen { import ComponentNode = laya.d3.core.ComponentNode; import RenderableSprite3D = laya.d3.core.RenderableSprite3D; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * ShuriKenParticle3D 3D粒子。 */ class ShuriKenParticle3D extends RenderableSprite3D { static SHADERDEFINE_RENDERMODE_BILLBOARD: number; static SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD: number; static SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD: number; static SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD: number; static SHADERDEFINE_COLOROVERLIFETIME: number; static SHADERDEFINE_RANDOMCOLOROVERLIFETIME: number; static SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT: number; static SHADERDEFINE_VELOCITYOVERLIFETIMECURVE: number; static SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT: number; static SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE: number; static SHADERDEFINE_TEXTURESHEETANIMATIONCURVE: number; static SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE: number; static SHADERDEFINE_ROTATIONOVERLIFETIME: number; static SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE: number; static SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT: number; static SHADERDEFINE_ROTATIONOVERLIFETIMECURVE: number; static SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS: number; static SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES: number; static SHADERDEFINE_SIZEOVERLIFETIMECURVE: number; static SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE: number; static SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES: number; static SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE: number; static SHADERDEFINE_RENDERMODE_MESH: number; static SHADERDEFINE_SHAPE: number; static WORLDPOSITION: number; static WORLDROTATION: number; static POSITIONSCALE: number; static SIZESCALE: number; static SCALINGMODE: number; static GRAVITY: number; static THREEDSTARTROTATION: number; static STRETCHEDBILLBOARDLENGTHSCALE: number; static STRETCHEDBILLBOARDSPEEDSCALE: number; static SIMULATIONSPACE: number; static CURRENTTIME: number; static VOLVELOCITYCONST: number; static VOLVELOCITYGRADIENTX: number; static VOLVELOCITYGRADIENTY: number; static VOLVELOCITYGRADIENTZ: number; static VOLVELOCITYCONSTMAX: number; static VOLVELOCITYGRADIENTXMAX: number; static VOLVELOCITYGRADIENTYMAX: number; static VOLVELOCITYGRADIENTZMAX: number; static VOLSPACETYPE: number; static COLOROVERLIFEGRADIENTALPHAS: number; static COLOROVERLIFEGRADIENTCOLORS: number; static MAXCOLOROVERLIFEGRADIENTALPHAS: number; static MAXCOLOROVERLIFEGRADIENTCOLORS: number; static SOLSIZEGRADIENT: number; static SOLSIZEGRADIENTX: number; static SOLSIZEGRADIENTY: number; static SOLSizeGradientZ: number; static SOLSizeGradientMax: number; static SOLSIZEGRADIENTXMAX: number; static SOLSIZEGRADIENTYMAX: number; static SOLSizeGradientZMAX: number; static ROLANGULARVELOCITYCONST: number; static ROLANGULARVELOCITYCONSTSEPRARATE: number; static ROLANGULARVELOCITYGRADIENT: number; static ROLANGULARVELOCITYGRADIENTX: number; static ROLANGULARVELOCITYGRADIENTY: number; static ROLANGULARVELOCITYGRADIENTZ: number; static ROLANGULARVELOCITYGRADIENTW: number; static ROLANGULARVELOCITYCONSTMAX: number; static ROLANGULARVELOCITYCONSTMAXSEPRARATE: number; static ROLANGULARVELOCITYGRADIENTMAX: number; static ROLANGULARVELOCITYGRADIENTXMAX: number; static ROLANGULARVELOCITYGRADIENTYMAX: number; static ROLANGULARVELOCITYGRADIENTZMAX: number; static ROLANGULARVELOCITYGRADIENTWMAX: number; static TEXTURESHEETANIMATIONCYCLES: number; static TEXTURESHEETANIMATIONSUBUVLENGTH: number; static TEXTURESHEETANIMATIONGRADIENTUVS: number; static TEXTURESHEETANIMATIONGRADIENTMAXUVS: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 加载网格模板。 * @param url 模板地址。 */ static load(url: string): ShuriKenParticle3D; /** * 获取粒子系统。 * @return 粒子系统。 */ readonly particleSystem: ShurikenParticleSystem; /** * 获取粒子渲染器。 * @return 粒子渲染器。 */ readonly particleRender: ShurikenParticleRender; /** * 创建一个 Particle3D 实例。 * @param settings value 粒子配置。 */ constructor(material?: ShurikenParticleMaterial); protected _clearSelfRenderObjects(): void; protected _addSelfRenderObjects(): void; protected _parseCustomProps(rootNode: ComponentNode, innerResouMap: any, customProps: any, nodeData: any): void; /** * @inheritDoc */ _activeHierarchy(): void; /** * @inheritDoc */ _inActiveHierarchy(): void; /** * @private */ cloneTo(destObject: any): void; /** *

    销毁此对象。

    * @param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ destroy(destroyChild?: boolean): void; } } declare module laya.d3.core.particleShuriKen { import Transform3D = laya.d3.core.Transform3D; /** * @private */ class ShurikenParticleData { static startLifeTime: number; static startColor: Float32Array; static startSize: Float32Array; static startRotation: Float32Array; static startSpeed: number; static startUVInfo: Float32Array; static simulationWorldPostion: Float32Array; static simulationWorldRotation: Float32Array; constructor(); /** * @private */ static create(particleSystem: ShurikenParticleSystem, particleRender: ShurikenParticleRender, transform: Transform3D): void; } } declare module laya.d3.core.particleShuriKen { import BaseMaterial = laya.d3.core.material.BaseMaterial; import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * ... * @author ... */ class ShurikenParticleMaterial extends BaseMaterial { /**渲染状态_不透明。*/ static RENDERMODE_OPAQUE: number; /**渲染状态_不透明_双面。*/ static RENDERMODE_OPAQUEDOUBLEFACE: number; /**渲染状态_透明测试。*/ static RENDERMODE_CUTOUT: number; /**渲染状态_透明测试_双面。*/ static RENDERMODE_CUTOUTDOUBLEFACE: number; /**渲染状态_透明混合。*/ static RENDERMODE_TRANSPARENT: number; /**渲染状态_透明混合_双面。*/ static RENDERMODE_TRANSPARENTDOUBLEFACE: number; /**渲染状态_加色法混合。*/ static RENDERMODE_ADDTIVE: number; /**渲染状态_加色法混合_双面。*/ static RENDERMODE_ADDTIVEDOUBLEFACE: number; /**渲染状态_只读深度_透明混合。*/ static RENDERMODE_DEPTHREAD_TRANSPARENT: number; /**渲染状态_只读深度_透明混合_双面。*/ static RENDERMODE_DEPTHREAD_TRANSPARENTDOUBLEFACE: number; /**渲染状态_只读深度_加色法混合。*/ static RENDERMODE_DEPTHREAD_ADDTIVE: number; /**渲染状态_只读深度_加色法混合_双面。*/ static RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE: number; /**渲染状态_无深度_透明混合。*/ static RENDERMODE_NONDEPTH_TRANSPARENT: number; /**渲染状态_无深度_透明混合_双面。*/ static RENDERMODE_NONDEPTH_TRANSPARENTDOUBLEFACE: number; /**渲染状态_无深度_加色法混合。*/ static RENDERMODE_NONDEPTH_ADDTIVE: number; /**渲染状态_无深度_加色法混合_双面。*/ static RENDERMODE_NONDEPTH_ADDTIVEDOUBLEFACE: number; static SHADERDEFINE_DIFFUSEMAP: number; static SHADERDEFINE_TINTCOLOR: number; static SHADERDEFINE_TILINGOFFSET: number; static SHADERDEFINE_ADDTIVEFOG: number; static DIFFUSETEXTURE: number; static TINTCOLOR: number; static TILINGOFFSET: number; /** 默认材质,禁止修改*/ static defaultMaterial: ShurikenParticleMaterial; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 加载手里剑粒子材质。 * @param url 手里剑粒子材质地址。 */ static load(url: string): ShurikenParticleMaterial; /** * 设置渲染模式。 * @return 渲染模式。 */ renderMode: number; /** * 获取颜色。 * @return 颜色。 */ /** * 设置颜色。 * @param value 颜色。 */ tintColor: Vector4; /** * 获取纹理平铺和偏移。 * @return 纹理平铺和偏移。 */ /** * 获取纹理平铺和偏移。 * @param value 纹理平铺和偏移。 */ tilingOffset: Vector4; /** * 获取漫反射贴图。 * @return 漫反射贴图。 */ /** * 设置漫反射贴图。 * @param value 漫反射贴图。 */ diffuseTexture: BaseTexture; constructor(); /** * @private */ static _parseShurikenParticleMaterial(textureMap: any, material: ShurikenParticleMaterial, json: any): void; /** *@private */ onAsynLoaded(url: string, data: any, params: Array): void; } } declare module laya.d3.core.particleShuriKen { import BaseRender = laya.d3.core.render.BaseRender; import BoundBox = laya.d3.math.BoundBox; import Matrix4x4 = laya.d3.math.Matrix4x4; import Mesh = laya.d3.resource.models.Mesh; /** * ShurikenParticleRender 类用于创建3D粒子渲染器。 */ class ShurikenParticleRender extends BaseRender { /**拉伸广告牌模式摄像机速度缩放,暂不支持。*/ stretchedBillboardCameraSpeedScale: number; /**拉伸广告牌模式速度缩放。*/ stretchedBillboardSpeedScale: number; /**拉伸广告牌模式长度缩放。*/ stretchedBillboardLengthScale: number; /** * 获取渲染模式。 * @return 渲染模式。 */ /** * 设置渲染模式,0为BILLBOARD、1为STRETCHEDBILLBOARD、2为HORIZONTALBILLBOARD、3为VERTICALBILLBOARD、4为MESH。 * @param value 渲染模式。 */ renderMode: number; /** * 获取网格渲染模式所使用的Mesh,rendderMode为4时生效。 * @return 网格模式所使用Mesh。 */ /** * 设置网格渲染模式所使用的Mesh,rendderMode为4时生效。 * @param value 网格模式所使用Mesh。 */ mesh: Mesh; /** * 创建一个 ShurikenParticleRender 实例。 */ constructor(owner: ShuriKenParticle3D); protected _calculateBoundingBox(): void; protected _calculateBoundingSphere(): void; /** * @inheritDoc */ _renderUpdate(projectionView: Matrix4x4): boolean; /** * @inheritDoc */ readonly boundingBox: BoundBox; /** * @inheritDoc */ _destroy(): void; } } declare module laya.d3.core.particleShuriKen { import GeometryFilter = laya.d3.core.GeometryFilter; import IClone = laya.d3.core.IClone; import ColorOverLifetime = laya.d3.core.particleShuriKen.module.ColorOverLifetime; import Emission = laya.d3.core.particleShuriKen.module.Emission; import GradientDataNumber = laya.d3.core.particleShuriKen.module.GradientDataNumber; import RotationOverLifetime = laya.d3.core.particleShuriKen.module.RotationOverLifetime; import SizeOverLifetime = laya.d3.core.particleShuriKen.module.SizeOverLifetime; import TextureSheetAnimation = laya.d3.core.particleShuriKen.module.TextureSheetAnimation; import VelocityOverLifetime = laya.d3.core.particleShuriKen.module.VelocityOverLifetime; import BaseShape = laya.d3.core.particleShuriKen.module.shape.BaseShape; import IRenderable = laya.d3.core.render.IRenderable; import RenderElement = laya.d3.core.render.RenderElement; import RenderState = laya.d3.core.render.RenderState; import IndexBuffer3D = laya.d3.graphics.IndexBuffer3D; import VertexBuffer3D = laya.d3.graphics.VertexBuffer3D; import BoundBox = laya.d3.math.BoundBox; import BoundSphere = laya.d3.math.BoundSphere; import Rand = laya.d3.math.Rand; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * ShurikenParticleSystem 类用于创建3D粒子数据模板。 */ class ShurikenParticleSystem extends GeometryFilter implements IRenderable, IClone { static _RANDOMOFFSET: Uint32Array; static _maxElapsedTime: number; _boundingSphere: BoundSphere; _boundingBox: BoundBox; _boundingBoxCorners: Array; _currentTime: number; _startUpdateLoopCount: number; _rand: Rand; _randomSeeds: Uint32Array; /**粒子运行的总时长,单位为秒。*/ duration: number; /**是否循环。*/ looping: boolean; /**是否预热。暂不支持*/ prewarm: boolean; /**开始延迟类型,0为常量模式,1为随机随机双常量模式,不能和prewarm一起使用。*/ startDelayType: number; /**开始播放延迟,不能和prewarm一起使用。*/ startDelay: number; /**开始播放最小延迟,不能和prewarm一起使用。*/ startDelayMin: number; /**开始播放最大延迟,不能和prewarm一起使用。*/ startDelayMax: number; /**开始速度模式,0为恒定速度,2为两个恒定速度的随机插值。缺少1、3模式*/ startSpeedType: number; /**开始速度,0模式。*/ startSpeedConstant: number; /**最小开始速度,1模式。*/ startSpeedConstantMin: number; /**最大开始速度,1模式。*/ startSpeedConstantMax: number; /**开始尺寸是否为3D模式。*/ threeDStartSize: boolean; /**开始尺寸模式,0为恒定尺寸,2为两个恒定尺寸的随机插值。缺少1、3模式和对应的二种3D模式*/ startSizeType: number; /**开始尺寸,0模式。*/ startSizeConstant: number; /**开始三维尺寸,0模式。*/ startSizeConstantSeparate: Vector3; /**最小开始尺寸,2模式。*/ startSizeConstantMin: number; /**最大开始尺寸,2模式。*/ startSizeConstantMax: number; /**最小三维开始尺寸,2模式。*/ startSizeConstantMinSeparate: Vector3; /**最大三维开始尺寸,2模式。*/ startSizeConstantMaxSeparate: Vector3; /**3D开始旋转,暂不支持*/ threeDStartRotation: boolean; /**开始旋转模式,0为恒定尺寸,2为两个恒定旋转的随机插值,缺少2种模式,和对应的四种3D模式。*/ startRotationType: number; /**开始旋转,0模式。*/ startRotationConstant: number; /**开始三维旋转,0模式。*/ startRotationConstantSeparate: Vector3; /**最小开始旋转,1模式。*/ startRotationConstantMin: number; /**最大开始旋转,1模式。*/ startRotationConstantMax: number; /**最小开始三维旋转,1模式。*/ startRotationConstantMinSeparate: Vector3; /**最大开始三维旋转,1模式。*/ startRotationConstantMaxSeparate: Vector3; /**随机旋转方向,范围为0.0到1.0*/ randomizeRotationDirection: number; /**开始颜色模式,0为恒定颜色,2为两个恒定颜色的随机插值,缺少2种模式。*/ startColorType: number; /**开始颜色,0模式。*/ startColorConstant: Vector4; /**最小开始颜色,1模式。*/ startColorConstantMin: Vector4; /**最大开始颜色,1模式。*/ startColorConstantMax: Vector4; /**重力敏感度。*/ gravityModifier: number; /**模拟器空间,0为World,1为Local。暂不支持Custom。*/ simulationSpace: number; /**缩放模式,0为Hiercachy,1为Local,2为World。暂不支持1,2*/ scaleMode: number; /**激活时是否自动播放。*/ playOnAwake: boolean; /**随机种子,注:play()前设置有效。*/ randomSeed: Uint32Array; /**是否使用随机种子。 */ autoRandomSeed: boolean; /**是否为性能模式,性能模式下会延迟粒子释放。*/ isPerformanceMode: boolean; /**获取最大粒子数。*/ /**设置最大粒子数,注意:谨慎修改此属性,有性能损耗。*/ maxParticles: number; /** * 获取发射器。 */ readonly emission: Emission; /** * 粒子存活个数。 */ readonly aliveParticleCount: number; /** * 获取一次循环内的累计时间。 * @return 一次循环内的累计时间。 */ readonly emissionTime: number; /** * 获取形状。 */ /** * 设置形状。 */ shape: BaseShape; /** * 是否存活。 */ readonly isAlive: boolean; /** * 是否正在发射。 */ readonly isEmitting: boolean; /** * 是否正在播放。 */ readonly isPlaying: boolean; /** * 是否已暂停。 */ readonly isPaused: boolean; /** * 获取开始生命周期模式,0为固定时间,1为渐变时间,2为两个固定之间的随机插值,3为两个渐变时间的随机插值。 */ /** * 设置开始生命周期模式,0为固定时间,1为渐变时间,2为两个固定之间的随机插值,3为两个渐变时间的随机插值。 */ startLifetimeType: number; /** * 获取开始生命周期,0模式,单位为秒。 */ /** * 设置开始生命周期,0模式,单位为秒。 */ startLifetimeConstant: number; /** * 获取开始渐变生命周期,1模式,单位为秒。 */ /** * 设置开始渐变生命周期,1模式,单位为秒。 */ startLifeTimeGradient: GradientDataNumber; /** * 获取最小开始生命周期,2模式,单位为秒。 */ /** * 设置最小开始生命周期,2模式,单位为秒。 */ startLifetimeConstantMin: number; /** * 获取最大开始生命周期,2模式,单位为秒。 */ /** * 设置最大开始生命周期,2模式,单位为秒。 */ startLifetimeConstantMax: number; /** * 获取开始渐变最小生命周期,3模式,单位为秒。 */ /** * 设置开始渐变最小生命周期,3模式,单位为秒。 */ startLifeTimeGradientMin: GradientDataNumber; /** * 获取开始渐变最大生命周期,3模式,单位为秒。 */ /** * 设置开始渐变最大生命周期,3模式,单位为秒。 */ startLifeTimeGradientMax: GradientDataNumber; /** * 获取生命周期速度,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 * @return 生命周期速度. */ /** * 设置生命周期速度,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 * @param value 生命周期速度. */ velocityOverLifetime: VelocityOverLifetime; /** * 获取生命周期颜色,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 * @return 生命周期颜色 */ /** * 设置生命周期颜色,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 * @param value 生命周期颜色 */ colorOverLifetime: ColorOverLifetime; /** * 获取生命周期尺寸,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 * @return 生命周期尺寸 */ /** * 设置生命周期尺寸,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 * @param value 生命周期尺寸 */ sizeOverLifetime: SizeOverLifetime; /** * 获取生命周期旋转,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 * @return 生命周期旋转。 */ /** * 设置生命周期旋转,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 * @param value 生命周期旋转。 */ rotationOverLifetime: RotationOverLifetime; /** * 获取生命周期纹理动画,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 * @return 生命周期纹理动画。 */ /** * 设置生命周期纹理动画,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 * @param value 生命周期纹理动画。 */ textureSheetAnimation: TextureSheetAnimation; readonly _vertexBufferCount: number; readonly triangleCount: number; _getVertexBuffer(index?: number): VertexBuffer3D; _getIndexBuffer(): IndexBuffer3D; /** * @inheritDoc */ readonly _originalBoundingSphere: BoundSphere; /** * @inheritDoc */ readonly _originalBoundingBox: BoundBox; /** * @inheritDoc */ readonly _originalBoundingBoxCorners: Array; constructor(owner: ShuriKenParticle3D); /** * @private */ _generateBoundingSphere(): void; /** * @private */ _generateBoundingBox(): void; /** * @private */ _initBufferDatas(): void; /** * @private */ _destroy(): void; /** * 发射一个粒子。 */ emit(time: number): boolean; addParticle(position: Vector3, direction: Vector3, time: number): boolean; addNewParticlesToVertexBuffer(): void; _beforeRender(state: RenderState): boolean; /** * @private */ _render(state: RenderState): void; /** * 开始发射粒子。 */ play(): void; /** * 暂停发射粒子。 */ pause(): void; /** * 通过指定时间增加粒子播放进度,并暂停播放。 * @param time 进度时间.如果restart为true,粒子播放时间会归零后再更新进度。 * @param restart 是否重置播放状态。 */ simulate(time: number, restart?: boolean): void; /** * 停止发射粒子。 */ stop(): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; /** * @private */ _getVertexBuffers(): Array; _renderRuntime(conchGraphics3D: any, renderElement: RenderElement, state: RenderState): void; } } declare module laya.d3.core { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; import ShaderCompile3D = laya.d3.shader.ShaderCompile3D; /** * @private * PhasorSpriter3D 类用于创建矢量笔刷。 */ class PhasorSpriter3D { protected _shaderCompile: ShaderCompile3D; constructor(); line(startPosition: Vector3, startColor: Vector4, endPosition: Vector3, endColor: Vector4): PhasorSpriter3D; circle(radius: number, numberOfPoints: number, r: number, g: number, b: number, a: number): PhasorSpriter3D; plane(positionX: number, positionY: number, positionZ: number, width: number, height: number, r: number, g: number, b: number, a: number): PhasorSpriter3D; box(positionX: number, positionY: number, positionZ: number, width: number, height: number, depth: number, r: number, g: number, b: number, a: number): PhasorSpriter3D; cone(radius: number, length: number, Slices: number, r: number, g: number, b: number, a: number): PhasorSpriter3D; boundingBoxLine(minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, r: number, g: number, b: number, a: number): PhasorSpriter3D; begin(primitive: number, camera: BaseCamera): PhasorSpriter3D; end(): PhasorSpriter3D; } } declare module laya.d3.core.render { import RenderableSprite3D = laya.d3.core.RenderableSprite3D; import Sprite3D = laya.d3.core.Sprite3D; import BaseMaterial = laya.d3.core.material.BaseMaterial; import ITreeNode = laya.d3.core.scene.ITreeNode; import BoundBox = laya.d3.math.BoundBox; import BoundSphere = laya.d3.math.BoundSphere; import Matrix4x4 = laya.d3.math.Matrix4x4; import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import EventDispatcher = laya.events.EventDispatcher; import IDestroy = laya.resource.IDestroy; /** * Render 类用于渲染器的父类,抽象类不允许实例。 */ class BaseRender extends EventDispatcher implements IDestroy { static _tempBoundBoxCorners: Array; protected _boundingSphere: BoundSphere; protected _boundingBox: BoundBox; protected _boundingBoxCenter: Vector3; protected _boundingSphereNeedChange: boolean; protected _boundingBoxNeedChange: boolean; protected _boundingBoxCenterNeedChange: boolean; protected _octreeNodeNeedChange: boolean; _indexInSceneFrustumCullingObjects: number; _materials: Array; _owner: RenderableSprite3D; _renderElements: Array; _distanceForSort: number; _treeNode: ITreeNode; _isPartOfStaticBatch: boolean; _staticBatchRootSprite3D: Sprite3D; _staticBatchRenderElements: Array; /**排序矫正值。*/ sortingFudge: number; /** 是否产生阴影。 */ castShadow: boolean; /** * 获取唯一标识ID,通常用于识别。 */ readonly id: number; /** * 获取光照贴图的索引。 * @return 光照贴图的索引。 */ /** * 设置光照贴图的索引。 * @param value 光照贴图的索引。 */ lightmapIndex: number; /** * 获取光照贴图的缩放和偏移。 * @return 光照贴图的缩放和偏移。 */ /** * 设置光照贴图的缩放和偏移。 * @param 光照贴图的缩放和偏移。 */ lightmapScaleOffset: Vector4; /** * 获取是否可用。 * @return 是否可用。 */ /** * 设置是否可用。 * @param value 是否可用。 */ enable: boolean; /** * 返回第一个实例材质,第一次使用会拷贝实例对象。 * @return 第一个实例材质。 */ /** * 设置第一个实例材质。 * @param value 第一个实例材质。 */ material: BaseMaterial; /** * 获取潜拷贝实例材质列表,第一次使用会拷贝实例对象。 * @return 浅拷贝实例材质列表。 */ /** * 设置实例材质列表。 * @param value 实例材质列表。 */ materials: Array; /** * 返回第一个材质。 * @return 第一个材质。 */ /** * 设置第一个材质。 * @param value 第一个材质。 */ sharedMaterial: BaseMaterial; /** * 获取浅拷贝材质列表。 * @return 浅拷贝材质列表。 */ /** * 设置材质列表。 * @param value 材质列表。 */ sharedMaterials: Array; /** * 获取包围球,只读,不允许修改其值。 * @return 包围球。 */ readonly boundingSphere: BoundSphere; /** * 获取包围盒,只读,不允许修改其值。 * @return 包围盒。 */ readonly boundingBox: BoundBox; /** * 获取包围盒中心,不允许修改其值。 * @return 包围盒中心。 */ readonly boundingBoxCenter: Vector3; /** * 获得是否接收阴影属性 */ /** * 设置是否接收阴影属性 */ receiveShadow: boolean; /** * 获取是否已销毁。 * @return 是否已销毁。 */ readonly destroyed: boolean; /** * 创建一个新的 BaseRender 实例。 */ constructor(owner: RenderableSprite3D); protected _onWorldMatNeedChange(): void; protected _renderRenderableBoundBox(): void; protected _calculateBoundingSphere(): void; protected _calculateBoundingBox(): void; /** * @private */ _setShaderValueTexture(shaderName: number, texture: BaseTexture): void; /** * @private */ _setShaderValueMatrix4x4(shaderName: number, matrix4x4: Matrix4x4): void; /** * 设置颜色。 * @param shaderIndex shader索引。 * @param color 颜色向量。 */ _setShaderValueColor(shaderIndex: number, color: any): void; /** * 设置Buffer。 * @param shaderIndex shader索引。 * @param buffer buffer数据。 */ _setShaderValueBuffer(shaderIndex: number, buffer: Float32Array): void; /** * 设置整型。 * @param shaderIndex shader索引。 * @param i 整形。 */ _setShaderValueInt(shaderIndex: number, i: number): void; /** * 设置布尔。 * @param shaderIndex shader索引。 * @param b 布尔。 */ _setShaderValueBool(shaderIndex: number, b: boolean): void; /** * 设置浮点。 * @param shaderIndex shader索引。 * @param i 浮点。 */ _setShaderValueNumber(shaderIndex: number, number: number): void; /** * 设置二维向量。 * @param shaderIndex shader索引。 * @param vector2 二维向量。 */ _setShaderValueVector2(shaderIndex: number, vector2: Vector2): void; /** * 增加Shader宏定义。 * @param value 宏定义。 */ _addShaderDefine(value: number): void; /** * 移除Shader宏定义。 * @param value 宏定义。 */ _removeShaderDefine(value: number): void; /** * @private */ _renderUpdate(projectionView: Matrix4x4): boolean; /** * @private */ _applyLightMapParams(): void; /** * @private */ _updateOctreeNode(): void; /** * @private */ _destroy(): void; } } declare module laya.d3.core.render { import IndexBuffer3D = laya.d3.graphics.IndexBuffer3D; import VertexBuffer3D = laya.d3.graphics.VertexBuffer3D; /** * IRender 接口用于实现3D对象的渲染相关功能。 */ interface IRenderable { _getVertexBuffer(index: number): VertexBuffer3D; _getIndexBuffer(): IndexBuffer3D; _beforeRender(state: RenderState): boolean; _getVertexBuffers(): Array; _render(state: RenderState): void; _renderRuntime(conchGraphics3D: any, renderElement: RenderElement, state: RenderState): void; } } declare module laya.d3.core.render { /** * IUpdate 接口用于实现3D对象的更新相关功能。 */ interface IUpdate { _update(state: RenderState): void; } } declare module laya.d3.core.render { import RenderableSprite3D = laya.d3.core.RenderableSprite3D; import BaseMaterial = laya.d3.core.material.BaseMaterial; import StaticBatch = laya.d3.graphics.StaticBatch; import ValusArray = laya.d3.shader.ValusArray; /** * @private * RenderElement 类用于实现渲染物体。 */ class RenderElement { _type: number; _mainSortID: number; _render: BaseRender; _sprite3D: RenderableSprite3D; _material: BaseMaterial; _staticBatch: StaticBatch; _tempBatchIndexStart: number; _tempBatchIndexEnd: number; _canDynamicBatch: boolean; /**当前ShaderValue。*/ _shaderValue: ValusArray; _onPreRenderFunction: Function; _conchSubmesh: any; /** * 获取唯一标识ID,通常用于识别。 */ readonly id: number; renderObj: IRenderable; /** * 创建一个 RenderElement 实例。 */ constructor(); /** * @private */ getDynamicBatchBakedVertexs(index: number): Float32Array; /** * @private */ getBakedIndices(): any; /** * @private */ _destroy(): void; } } declare module laya.d3.core.render { import Scene = laya.d3.core.scene.Scene; import Vector3 = laya.d3.math.Vector3; /** * @private * RenderQuene 类用于实现渲染队列。 */ class RenderQueue { /** 定义非透明渲染队列标记。*/ static OPAQUE: number; /** 透明混合渲染队列标记。*/ static TRANSPARENT: number; _renderElements: Array; /** * 获取唯一标识ID(通常用于优化或识别)。 */ readonly id: number; /** * 创建一个 RenderQuene 实例。 * @param renderConfig 渲染配置。 */ constructor(scene: Scene); /** * @private */ _sortAlpha(cameraPos: Vector3): void; /** * @private */ _sortOpaque(cameraPos: Vector3): void; /** * @private * 准备渲染队列。 * @param state 渲染状态。 */ _preRender(state: RenderState): void; /** * @private * 渲染队列。 * @param state 渲染状态。 */ _render(state: RenderState, isTarget: boolean): void; /** * @private * 渲染队列。 * @param state 渲染状态。 */ _renderShadow(state: RenderState, isOnePSSM: boolean): void; /** * 清空队列中的渲染物体。 */ _clearRenderElements(): void; /** * 添加渲染物体。 * @param renderObj 渲染物体。 */ _addRenderElement(renderElement: RenderElement): void; /** * 添加动态批处理。 * @param renderObj 动态批处理。 */ _addDynamicBatchElement(dynamicBatchElement: RenderElement): void; } } declare module laya.d3.core.render { import BaseCamera = laya.d3.core.BaseCamera; import Sprite3D = laya.d3.core.Sprite3D; import Scene = laya.d3.core.scene.Scene; import StaticBatch = laya.d3.graphics.StaticBatch; import Matrix4x4 = laya.d3.math.Matrix4x4; import Viewport = laya.d3.math.Viewport; import Shader3D = laya.d3.shader.Shader3D; /** * RenderState 类用于实现渲染状态。 */ class RenderState { /**渲染区宽度。*/ static clientWidth: number; /**渲染区高度。*/ static clientHeight: number; _staticBatch: StaticBatch; _batchIndexStart: number; _batchIndexEnd: number; _viewMatrix: Matrix4x4; _projectionMatrix: Matrix4x4; _projectionViewMatrix: Matrix4x4; _viewport: Viewport; _shader: Shader3D; /**距上一帧间隔时间。*/ elapsedTime: number; /**当前场景。*/ scene: Scene; /**当前渲染3D精灵。*/ owner: Sprite3D; /**当前渲染物体。*/ renderElement: RenderElement; /**当前摄像机。*/ camera: BaseCamera; /** * 创建一个 RenderState 实例。 */ constructor(); } } declare module laya.d3.core.render { /** * @private */ class SubMeshRenderElement extends RenderElement { _batchIndexStart: number; _batchIndexEnd: number; _skinAnimationDatas: Array; constructor(); } } declare module laya.d3.core { import BaseRender = laya.d3.core.render.BaseRender; import RenderState = laya.d3.core.render.RenderState; import Scene = laya.d3.core.scene.Scene; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * RenderableSprite3D 类用于可渲染3D精灵的父类,抽象类不允许实例。 */ class RenderableSprite3D extends Sprite3D { /**精灵级着色器宏定义,光照贴图便宜和缩放。*/ static SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV: number; /**精灵级着色器宏定义,光照贴图。*/ static SAHDERDEFINE_LIGHTMAP: number; /**着色器变量名,光照贴图缩放和偏移。*/ static LIGHTMAPSCALEOFFSET: number; /**着色器变量名,光照贴图缩。*/ static LIGHTMAP: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; _render: BaseRender; _geometryFilter: GeometryFilter; /** * 创建一个 RenderableSprite3D 实例。 */ constructor(name?: string); /** * @private */ _addToInitStaticBatchManager(): void; /** * @inheritDoc */ _setBelongScene(scene: Scene): void; /** * @inheritDoc */ _setUnBelongScene(): void; /** * @inheritDoc */ _update(state: RenderState): void; /** * @inheritDoc */ destroy(destroyChild?: boolean): void; /** * @inheritDoc */ _updateConch(state: RenderState): void; } } declare module laya.d3.core.scene { import PhasorSpriter3D = laya.d3.core.PhasorSpriter3D; import BaseRender = laya.d3.core.render.BaseRender; import RenderQueue = laya.d3.core.render.RenderQueue; import BoundFrustum = laya.d3.math.BoundFrustum; import Matrix4x4 = laya.d3.math.Matrix4x4; import Vector3 = laya.d3.math.Vector3; /** * ... * @author lv */ interface ITreeNode { init(center: Vector3, treeSize: Vector3): void; addTreeNode(renderObj: BaseRender): void; cullingObjects(boundFrustum: BoundFrustum, testVisible: boolean, flags: number, cameraPosition: Vector3, projectionView: Matrix4x4): void; cullingShadowObjects(lightBoundFrustum: Array, splitShadowQueues: Array, testVisible: boolean, flags: number, scene: Scene): void; cullingShadowObjectsOnePSSM(lightBoundFrustum: BoundFrustum, splitShadowQueues: Array, lightViewProjectMatrix: Matrix4x4, testVisible: boolean, flags: number, scene: Scene): void; renderBoudingBox(linePhasor: PhasorSpriter3D): void; removeObject(object: BaseRender): boolean; updateObject(object: BaseRender): void; } } declare module laya.d3.core.scene { import PhasorSpriter3D = laya.d3.core.PhasorSpriter3D; import BaseRender = laya.d3.core.render.BaseRender; import BoundBox = laya.d3.math.BoundBox; import BoundFrustum = laya.d3.math.BoundFrustum; import Matrix4x4 = laya.d3.math.Matrix4x4; import Vector3 = laya.d3.math.Vector3; class OctreeNode implements ITreeNode { /**是否开启四/八叉树调试模式。 */ static debugMode: boolean; _children: Array; init(center: Vector3, treeSize: Vector3): void; addTreeNode(render: BaseRender): void; exactBox: BoundBox; relaxBox: BoundBox; constructor(scene: Scene, currentDepth: number); addChild(index: number): OctreeNode; addObject(object: BaseRender): void; removeObject(object: BaseRender): boolean; clearObject(): void; addNodeUp(render: BaseRender, depth: number): void; addNodeDown(render: BaseRender, depth: number): void; inChildIndex(objectCenter: Vector3): number; updateObject(render: BaseRender): void; cullingObjects(boundFrustum: BoundFrustum, testVisible: boolean, flags: number, cameraPosition: Vector3, projectionView: Matrix4x4): void; /** * @private */ cullingShadowObjects(lightBoundFrustum: Array, splitShadowQueues: Array, testVisible: boolean, flags: number, scene: Scene): void; /** * @private */ cullingShadowObjectsOnePSSM(lightBoundFrustum: BoundFrustum, splitShadowQueues: Array, lightViewProjectMatrix: Matrix4x4, testVisible: boolean, flags: number, scene: Scene): void; renderBoudingBox(linePhasor: PhasorSpriter3D): void; buildAllChild(depth: number): void; } } declare module laya.d3.core.scene { import Component3D = laya.d3.component.Component3D; import Script = laya.d3.component.Script; import BaseCamera = laya.d3.core.BaseCamera; import ComponentNode = laya.d3.core.ComponentNode; import LightSprite = laya.d3.core.light.LightSprite; import BaseRender = laya.d3.core.render.BaseRender; import RenderQueue = laya.d3.core.render.RenderQueue; import RenderState = laya.d3.core.render.RenderState; import DynamicBatchManager = laya.d3.graphics.DynamicBatchManager; import BoundFrustum = laya.d3.math.BoundFrustum; import Matrix4x4 = laya.d3.math.Matrix4x4; import Vector3 = laya.d3.math.Vector3; import RenderTexture = laya.d3.resource.RenderTexture; import ValusArray = laya.d3.shader.ValusArray; import Node = laya.display.Node; import Sprite = laya.display.Sprite; import RenderContext = laya.renders.RenderContext; import ICreateResource = laya.resource.ICreateResource; import WebGLContext = laya.webgl.WebGLContext; import ISubmit = laya.webgl.submit.ISubmit; /** * BaseScene 类用于实现场景。 */ class Scene extends Sprite implements ISubmit, ICreateResource { static FOGCOLOR: number; static FOGSTART: number; static FOGRANGE: number; static LIGHTDIRECTION: number; static LIGHTDIRCOLOR: number; static POINTLIGHTPOS: number; static POINTLIGHTRANGE: number; static POINTLIGHTATTENUATION: number; static POINTLIGHTCOLOR: number; static SPOTLIGHTPOS: number; static SPOTLIGHTDIRECTION: number; static SPOTLIGHTSPOT: number; static SPOTLIGHTRANGE: number; static SPOTLIGHTATTENUATION: number; static SPOTLIGHTCOLOR: number; static SHADOWDISTANCE: number; static SHADOWLIGHTVIEWPROJECT: number; static SHADOWMAPPCFOFFSET: number; static SHADOWMAPTEXTURE1: number; static SHADOWMAPTEXTURE2: number; static SHADOWMAPTEXTURE3: number; static AMBIENTCOLOR: number; /** * 加载场景,注意:不缓存。 * @param url 模板地址。 */ static load(url: string): Scene; protected _renderState: RenderState; protected _lights: Array; protected _enableLightCount: number; protected _renderTargetTexture: RenderTexture; protected _customRenderQueneIndex: number; protected _lastCurrentTime: number; protected _enableFog: boolean; protected _enableDepthFog: boolean; protected _fogStart: number; protected _fogRange: number; protected _fogColor: Vector3; protected _ambientColor: Vector3; _shaderValues: ValusArray; _shaderDefineValue: number; _cullingRendersLength: number; _cullingRenders: Array; _dynamicBatchManager: DynamicBatchManager; _quenes: Array; _cameraPool: Array; _renderableSprite3Ds: Array; /** 是否启用灯光。*/ enableLight: boolean; /** 四/八叉树的根节点。*/ treeRoot: ITreeNode; /** 四/八叉树的尺寸。*/ treeSize: Vector3; /** 四/八叉树的层数。*/ treeLevel: number; parallelSplitShadowMaps: Array; protected _componentsMap: Array; protected _typeComponentsIndices: Array; protected _components: Array; /** * @private */ _loaded: boolean; /** * 获取资源的URL地址。 * @return URL地址。 */ readonly url: string; /** * 获取是否已加载完成。 */ readonly loaded: boolean; /** * 获取是否允许雾化。 * @return 是否允许雾化。 */ /** * 设置是否允许雾化。 * @param value 是否允许雾化。 */ enableFog: boolean; enableDepthFog: boolean; /** * 获取雾化颜色。 * @return 雾化颜色。 */ /** * 设置雾化颜色。 * @param value 雾化颜色。 */ fogColor: Vector3; /** * 获取雾化起始位置。 * @return 雾化起始位置。 */ /** * 设置雾化起始位置。 * @param value 雾化起始位置。 */ fogStart: number; /** * 获取雾化范围。 * @return 雾化范围。 */ /** * 设置雾化范围。 * @param value 雾化范围。 */ fogRange: number; /** * 获取环境光颜色。 * @return 环境光颜色。 */ /** * 设置环境光颜色。 * @param value 环境光颜色。 */ ambientColor: Vector3; /** * 获取当前场景。 * @return 当前场景。 */ readonly scene: Scene; /** * 获取场景的可渲染精灵。 */ readonly renderableSprite3Ds: Array; /** * 创建一个 Scene 实例。 */ constructor(); /** * @private */ _setUrl(url: string): void; /** * @private */ _getGroup(): string; /** * @private */ _setGroup(value: string): void; /** * 初始化八叉树。 * @param width 八叉树宽度。 * @param height 八叉树高度。 * @param depth 八叉树深度。 * @param center 八叉树中心点 * @param level 八叉树层级。 */ initOctree(width: number, height: number, depth: number, center: Vector3, level?: number): void; protected _prepareUpdateToRenderState(gl: WebGLContext, state: RenderState): void; protected _prepareSceneToRender(state: RenderState): void; protected _updateChilds(state: RenderState): void; protected _updateChildsConch(state: RenderState): void; /** * @private */ _preRenderScene(gl: WebGLContext, state: RenderState, boundFrustum: BoundFrustum): void; /** * @private */ _clear(gl: WebGLContext, state: RenderState): void; /** * @private */ _renderScene(gl: WebGLContext, state: RenderState): void; protected _set3DRenderConfig(gl: WebGLContext): void; protected _set2DRenderConfig(gl: WebGLContext): void; protected _parseCustomProps(rootNode: ComponentNode, innerResouMap: any, customProps: any, nodeData: any): void; /** * @private */ _addLight(light: LightSprite): void; /** * @private */ _removeLight(light: LightSprite): void; /** * @private */ _updateScene(): void; /** * @private */ _updateSceneConch(): void; protected _preRenderShadow(state: RenderState, lightFrustum: Array, shdowQueues: Array, lightViewProjectMatrix: Matrix4x4, nPSSMNum: number): void; /** * @private */ _renderShadowMap(gl: WebGLContext, state: RenderState, sceneCamera: BaseCamera): void; /** * @private */ addTreeNode(renderObj: BaseRender): void; /** * @private */ removeTreeNode(renderObj: BaseRender): void; /** * 设置光照贴图。 * @param value 光照贴图。 */ setlightmaps(value: Array): void; /** * 获取光照贴图。 * @return 获取光照贴图。 */ getlightmaps(): Array; /** * @inheritDoc */ addChildAt(node: Node, index: number): Node; /** * @inheritDoc */ addChild(node: Node): Node; /** * @inheritDoc */ removeChildAt(index: number): Node; /** * @inheritDoc */ removeChildren(beginIndex?: number, endIndex?: number): Node; /** * @inheritDoc */ addFrustumCullingObject(renderObject: BaseRender): void; /** * @private */ removeFrustumCullingObject(renderObject: BaseRender): void; /** * 获得某个渲染队列。 * @param index 渲染队列索引。 * @return 渲染队列。 */ getRenderQueue(index: number): RenderQueue; /** * 添加渲染队列。 * @param renderConfig 渲染队列配置文件。 */ addRenderQuene(): void; /** * 增加shader宏定义。 * @param define shader宏定义。 */ addShaderDefine(define: number): void; /** * 移除shader宏定义。 * @param define shader宏定义。 */ removeShaderDefine(define: number): void; /** * 添加指定类型脚本。 * @param type 脚本类型。 * @return 组件。 */ addScript(type: any): Script; /** * 通过指定类型和类型索引获得脚本。 * @param type 脚本类型。 * @param typeIndex 脚本索引。 * @return 脚本。 */ getScriptByType(type: any, typeIndex?: number): Script; /** * 通过指定类型获得所有脚本。 * @param type 脚本类型。 * @param scripts 脚本输出队列。 */ getScriptsByType(type: any, scripts: Array): void; /** * 通过指定索引获得脚本。 * @param index 索引。 * @return 脚本。 */ getScriptByIndex(index: number): Script; /** * 通过指定类型和类型索引移除脚本。 * @param type 脚本类型。 * @param typeIndex 类型索引。 */ removeScriptByType(type: any, typeIndex?: number): void; /** * 通过指定类型移除所有脚本。 * @param type 组件类型。 */ removeScriptsByType(type: any): void; /** * 移除全部脚本。 */ removeAllScript(): void; /** * @private */ render(context: RenderContext, x: number, y: number): void; /** * @private */ renderSubmit(): number; /** *@private */ onAsynLoaded(url: string, data: any, params: Array): void; /** *@private */ destroy(destroyChild?: boolean): void; /** * @private */ getRenderType(): number; /** * @private */ releaseRender(): void; /** * @private */ createConchModel(): any; protected _addComponent(type: any): Component3D; protected _removeComponent(mapIndex: number, index: number): void; protected _getComponentByType(type: any, typeIndex?: number): Component3D; protected _getComponentsByType(type: any, components: Array): void; protected _getComponentByIndex(index: number): Component3D; protected _removeComponentByType(type: any, typeIndex?: number): void; protected _removeComponentsByType(type: any): void; protected _removeAllComponent(): void; protected _updateComponents(state: RenderState): void; protected _lateUpdateComponents(state: RenderState): void; /** * @private */ _preRenderUpdateComponents(state: RenderState): void; /** * @private */ _postRenderUpdateComponents(state: RenderState): void; } } declare module laya.d3.core.scene { /** * ... * @author ... */ class SceneManager { constructor(); } } declare module laya.d3.core { import Animator = laya.d3.component.Animator; import BoundBox = laya.d3.math.BoundBox; import BoundSphere = laya.d3.math.BoundSphere; import Matrix4x4 = laya.d3.math.Matrix4x4; import Vector3 = laya.d3.math.Vector3; /** * SkinMeshRender 类用于蒙皮渲染器。 */ class SkinnedMeshRender extends MeshRender { _rootBone: string; /**用于裁剪的包围球。 */ localBoundSphere: BoundSphere; /** * 获取包围球。 * @return 包围球。 */ /** * 设置包围球。 * @param value */ localBoundBox: BoundBox; /** * @inheritDoc */ readonly boundingSphere: BoundSphere; /** * @inheritDoc */ readonly boundingBox: BoundBox; /** * @inheritDoc */ readonly boundingBoxCenter: Vector3; /** * 创建一个新的 SkinnedMeshRender 实例。 */ constructor(owner: RenderableSprite3D); /** * @private */ _setCacheAnimator(animator: Animator): void; /** * @private */ _setRootBone(name: string): void; /** * @private */ _setCacheAvatar(value: Avatar): void; protected _calculateBoundingBox(): void; protected _calculateBoundingSphere(): void; /** * @inheritDoc */ _updateOctreeNode(): void; /** * @inheritDoc */ _renderUpdate(projectionView: Matrix4x4): boolean; _hasIndependentBound: boolean; } } declare module laya.d3.core { import Animator = laya.d3.component.Animator; import BaseMesh = laya.d3.resource.models.BaseMesh; import Mesh = laya.d3.resource.models.Mesh; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * SkinnedMeshSprite3D 类用于创建网格。 */ class SkinnedMeshSprite3D extends RenderableSprite3D { /**精灵级着色器宏定义,蒙皮动画。*/ static SHADERDEFINE_BONE: number; /**着色器变量名,蒙皮动画。*/ static BONES: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 加载网格模板。 * @param url 模板地址。 */ static load(url: string): SkinnedMeshSprite3D; /** * 获取网格过滤器。 * @return 网格过滤器。 */ readonly meshFilter: MeshFilter; /** * 获取网格渲染器。 * @return 网格渲染器。 */ readonly skinnedMeshRender: SkinnedMeshRender; /** * 创建一个 MeshSprite3D 实例。 * @param mesh 网格,同时会加载网格所用默认材质。 * @param name 名字。 */ constructor(mesh?: BaseMesh, name?: string); protected _parseCustomProps(rootNode: ComponentNode, innerResouMap: any, customProps: any, json: any): void; protected _changeHierarchyAnimator(animator: Animator): void; protected _clearSelfRenderObjects(): void; protected _addSelfRenderObjects(): void; /** * @private */ _applyMeshMaterials(mesh: Mesh): void; /** * @inheritDoc */ cloneTo(destObject: any): void; /** * @inheritDoc */ destroy(destroyChild?: boolean): void; /** * @private */ createConchModel(): any; } } declare module laya.d3.core { import AnimationNode = laya.d3.animation.AnimationNode; import Animator = laya.d3.component.Animator; import Component3D = laya.d3.component.Component3D; import BaseMaterial = laya.d3.core.material.BaseMaterial; import IRenderable = laya.d3.core.render.IRenderable; import IUpdate = laya.d3.core.render.IUpdate; import RenderState = laya.d3.core.render.RenderState; import Scene = laya.d3.core.scene.Scene; import Matrix4x4 = laya.d3.math.Matrix4x4; import Quaternion = laya.d3.math.Quaternion; import Vector3 = laya.d3.math.Vector3; import ValusArray = laya.d3.shader.ValusArray; import Node = laya.display.Node; import ICreateResource = laya.resource.ICreateResource; /** * Sprite3D 类用于实现3D精灵。 */ class Sprite3D extends ComponentNode implements IUpdate, ICreateResource, IClone { static WORLDMATRIX: number; static MVPMATRIX: number; protected static _uniqueIDCounter: number; protected static _nameNumberCounter: number; /** * 创建精灵的克隆实例。 * @param original 原始精灵。 * @param parent 父节点。 * @param worldPositionStays 是否保持自身世界变换。 * @param position 世界位置,worldPositionStays为false时生效。 * @param rotation 世界旋转,worldPositionStays为false时生效。 * @return 克隆实例。 */ static instantiate(original: Sprite3D, parent?: Node, worldPositionStays?: boolean, position?: Vector3, rotation?: Quaternion): Sprite3D; /** * 加载网格模板。 * @param url 模板地址。 */ static load(url: string): Sprite3D; _projectionViewWorldUpdateLoopCount: number; _projectionViewWorldUpdateCamera: BaseCamera; protected _active: boolean; protected _activeInHierarchy: boolean; protected _layer: Layer; _shaderDefineValue: number; _shaderValues: ValusArray; _colliders: Array; _scene: Scene; _transform: Transform3D; _hierarchyAnimator: Animator; /**是否静态,静态包含一系列的静态处理。*/ isStatic: boolean; /** * @private */ _loaded: boolean; /** * 获取唯一标识ID。 * @return 唯一标识ID。 */ readonly id: number; /** * 获取是否已加载完成。 */ readonly loaded: boolean; /** * 获取自身是否激活。 * @return 自身是否激活。 */ /** * 设置是否激活。 * @param value 是否激活。 */ active: boolean; /** * 获取在场景中是否激活。 * @return 在场景中是否激活。 */ readonly activeInHierarchy: boolean; /** * 获取蒙版。 * @return 蒙版。 */ /** * 设置蒙版。 * @param value 蒙版。 */ layer: Layer; /** * 获得所属场景。 * @return 场景。 */ readonly scene: Scene; /** * 获得组件的数量。 * @return 组件数量。 */ readonly componentsCount: number; /** * 获取资源的URL地址。 * @return URL地址。 */ readonly url: string; /** * 获取精灵变换。 */ readonly transform: Transform3D; /** * 创建一个 Sprite3D 实例。 */ constructor(name?: string); /** * @private */ _setUrl(url: string): void; /** * @private */ _getGroup(): string; /** * @private */ _setGroup(value: string): void; protected _changeHierarchyAnimator(animator: Animator): void; /** * @private */ _isLinkSpriteToAnimationNode(animator: Animator, node: AnimationNode, isLink: boolean): void; /** * @private */ _setBelongScene(scene: Scene): void; /** * @private */ _setUnBelongScene(): void; /** * @private */ _activeHierarchy(): void; /** * @private */ _inActiveHierarchy(): void; /** * @private */ addComponent(type: any): Component3D; protected _removeComponent(mapIndex: number, index: number): void; /** * @private */ createConchModel(): any; protected _clearSelfRenderObjects(): void; protected _addSelfRenderObjects(): void; protected _parseCustomProps(rootNode: ComponentNode, innerResouMap: any, customProps: any, nodeData: any): void; protected _updateChilds(state: RenderState): void; protected _updateChildsConch(state: RenderState): void; /** * 排序函数。 * @param state 渲染相关状态。 */ _getSortID(renderElement: IRenderable, material: BaseMaterial): number; /** * 更新 * @param state 渲染相关状态 */ _update(state: RenderState): void; /** * 更新 * @param state 渲染相关状态 */ _updateConch(state: RenderState): void; /** * 获取投影视图世界矩阵。 * @param projectionViewMatrix 投影视图矩阵。 * @return 投影视图世界矩阵。 */ getProjectionViewWorldMatrix(projectionViewMatrix: Matrix4x4): Matrix4x4; /** * 加载层级文件,并作为该节点的子节点。 * @param url */ loadHierarchy(url: string): void; /** * @inheritDoc */ addChildAt(node: Node, index: number): Node; /** * @inheritDoc */ addChild(node: Node): Node; /** * @inheritDoc */ removeChildAt(index: number): Node; /** * @inheritDoc */ removeChildren(beginIndex?: number, endIndex?: number): Node; /** *@private */ onAsynLoaded(url: string, data: any, params: Array): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; /** * @inheritDoc */ destroy(destroyChild?: boolean): void; } } declare module laya.d3.core.trail.module { class Color { /** * 红色 */ static RED: Color; /** * 绿色 */ static GREEN: Color; /** * 蓝色 */ static BLUE: Color; /** * 蓝绿色 */ static CYAN: Color; /** * 黄色 */ static YELLOW: Color; /** * 品红色 */ static MAGENTA: Color; /** * 灰色 */ static GRAY: Color; /** * 白色 */ static WHITE: Color; /** * 黑色 */ static BLACK: Color; r: number; g: number; b: number; a: number; constructor(r: number, g: number, b: number, a: number); } } declare module laya.d3.core.trail.module { class Gradient { _colorKeyData: Float32Array; _alphaKeyData: Float32Array; /** * 获取梯度模式。 * @return 梯度模式。 */ /** * 设置梯度模式。 * @param value 梯度模式。 */ mode: number; /** * 获取颜色值关键帧数据 */ /** * 设置颜色值关键帧数据 */ colorKeys: Array; /** * 获取透明度关键帧数据 */ /** * 设置透明度关键帧数据 */ alphaKeys: Array; constructor(); /** * 设置渐变,使用一组颜色关键帧数据和透明度关键帧数据。 * @param colorKeys 渐变的颜色值关键帧数据(最大长度为10)。 * @param alphaKeys 渐变的透明度关键帧数据(最大长度为10)。 */ setKeys(colorKeys: Array, alphaKeys: Array): void; } } declare module laya.d3.core.trail.module { class GradientAlphaKey { /** * 获取透明度。 * @return 透明度。 */ /** * 设置透明度。 * @param value 透明度。 */ alpha: number; /** * 获取时间。 * @return 时间。 */ /** * 设置时间。 * @param value 时间。 */ time: number; constructor(alpha: number, time: number); } } declare module laya.d3.core.trail.module { class GradientColorKey { /** * 获取颜色值。 * @return 颜色值。 */ /** * 设置颜色值。 * @param value 颜色值。 */ color: Color; /** * 获取时间。 * @return 时间。 */ /** * 设置时间。 * @param value 时间。 */ time: number; constructor(color: Color, time: number); } } declare module laya.d3.core.trail.module { /** * ... * @author ... */ class GradientMode { /** * 找到与请求的评估时间相邻的两个键,并线性插值在他们之间,以获得一种混合的颜色。 */ static Blend: number; /** * 返回一个固定的颜色,通过查找第一个键的时间值大于所请求的评估时间。 */ static Fixed: number; } } declare module laya.d3.core.trail.module { /** * ... * @author ... */ class TextureMode { /** * 拉伸模式。 */ static Stretch: number; /** * 平铺模式。 */ static Tile: number; } } declare module laya.d3.core.trail.module { class TrailKeyFrame { time: number; inTangent: number; outTangent: number; value: number; } } declare module laya.d3.core.trail { import GeometryFilter = laya.d3.core.GeometryFilter; import IRenderable = laya.d3.core.render.IRenderable; import RenderState = laya.d3.core.render.RenderState; import Gradient = laya.d3.core.trail.module.Gradient; import Vector3 = laya.d3.math.Vector3; /** * ... * @author ... */ class TrailFilter extends GeometryFilter { _owner: TrailSprite3D; _curtime: number; _curSubTrailFinishPosition: Vector3; _curSubTrailFinishDirection: Vector3; _curSubTrailFinishCurTime: number; _curSubTrailFinished: boolean; _hasLifeSubTrail: boolean; _trailTotalLength: number; _trailSupplementLength: number; _trailDeadLength: number; /** * 获取淡出时间。 * @return 淡出时间。 */ /** * 设置淡出时间。 * @param value 淡出时间。 */ time: number; /** * 获取新旧顶点之间最小距离。 * @return 新旧顶点之间最小距离。 */ /** * 设置新旧顶点之间最小距离。 * @param value 新旧顶点之间最小距离。 */ minVertexDistance: number; /** * 获取宽度倍数。 * @return 宽度倍数。 */ /** * 设置宽度倍数。 * @param value 宽度倍数。 */ widthMultiplier: number; /** * 获取宽度曲线。 * @return 宽度曲线。 */ /** * 设置宽度曲线。 * @param value 宽度曲线。 */ widthCurve: Array; /** * 获取颜色梯度。 * @return 颜色梯度。 */ /** * 设置颜色梯度。 * @param value 颜色梯度。 */ colorGradient: Gradient; /** * 获取纹理模式。 * @return 纹理模式。 */ /** * 设置纹理模式。 * @param value 纹理模式。 */ textureMode: number; constructor(owner: TrailSprite3D); getRenderElementsCount(): number; addRenderElement(): number; getRenderElement(index: number): IRenderable; _update(state: RenderState): void; /** * @private */ _destroy(): void; } } declare module laya.d3.core.trail { import BaseMaterial = laya.d3.core.material.BaseMaterial; import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * ... * @author ... */ class TrailMaterial extends BaseMaterial { /** 默认材质,禁止修改*/ static defaultMaterial: TrailMaterial; static SHADERDEFINE_DIFFUSETEXTURE: number; static SHADERDEFINE_TILINGOFFSET: number; static DIFFUSETEXTURE: number; static TINTCOLOR: number; static TILINGOFFSET: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 加载标准材质。 * @param url 标准材质地址。 */ static load(url: string): TrailMaterial; /** * 获取颜色。 * @return 颜色。 */ /** * 设置颜色。 * @param value 颜色。 */ tintColor: Vector4; /** * 获取贴图。 * @return 贴图。 */ /** * 设置贴图。 * @param value 贴图。 */ diffuseTexture: BaseTexture; /** * 获取纹理平铺和偏移。 * @return 纹理平铺和偏移。 */ /** * 设置纹理平铺和偏移。 * @param value 纹理平铺和偏移。 */ tilingOffset: Vector4; constructor(); } } declare module laya.d3.core.trail { import IRenderable = laya.d3.core.render.IRenderable; import RenderElement = laya.d3.core.render.RenderElement; import RenderState = laya.d3.core.render.RenderState; import IndexBuffer3D = laya.d3.graphics.IndexBuffer3D; import VertexBuffer3D = laya.d3.graphics.VertexBuffer3D; /** * ... * @author ... */ class TrailRenderElement implements IRenderable { _id: number; _isDead: boolean; constructor(owner: TrailFilter); /** * 更新VertexBuffer2数据 */ _updateVertexBuffer2(): void; /** * @private */ _updateDisappear(): void; /** * 渲染前调用 * @param state 渲染状态 * @return 是否渲染 */ _beforeRender(state: RenderState): boolean; /** * 渲染时调用 * @param state 渲染状态 */ _render(state: RenderState): void; /** * 获取vertexBuffer * @param index vertexBuffer索引 * @return vertexBuffer */ _getVertexBuffer(index?: number): VertexBuffer3D; /** * 获取vertexBuffer数组 * @return vertexBuffer数组 */ _getVertexBuffers(): Array; /** * 获取顶点索引缓冲 * @return 顶点索引缓冲 */ _getIndexBuffer(): IndexBuffer3D; /** * 获取vertexBuffer数量 * @return vertexBuffer数量 */ readonly _vertexBufferCount: number; /** * 获取三角面数量 * @return 三角面数量 */ readonly triangleCount: number; /** * @private */ _renderRuntime(conchGraphics3D: any, renderElement: RenderElement, state: RenderState): void; /** * 重新激活该renderElement */ reActivate(): void; /** * @private */ _destroy(): void; } } declare module laya.d3.core.trail { import BaseRender = laya.d3.core.render.BaseRender; import Matrix4x4 = laya.d3.math.Matrix4x4; /** * ... * @author ... */ class TrailRenderer extends BaseRender { constructor(owner: TrailSprite3D); protected _calculateBoundingBox(): void; protected _calculateBoundingSphere(): void; _renderUpdate(projectionView: Matrix4x4): boolean; } } declare module laya.d3.core.trail { import ComponentNode = laya.d3.core.ComponentNode; import RenderableSprite3D = laya.d3.core.RenderableSprite3D; import BaseMaterial = laya.d3.core.material.BaseMaterial; import RenderState = laya.d3.core.render.RenderState; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * ... * @author ... */ class TrailSprite3D extends RenderableSprite3D { static CURTIME: number; static LIFETIME: number; static WIDTHCURVE: number; static WIDTHCURVEKEYLENGTH: number; static GRADIENTCOLORKEY: number; static GRADIENTALPHAKEY: number; static SHADERDEFINE_GRADIENTMODE_BLEND: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 获取Trail过滤器。 * @return Trail过滤器。 */ readonly trailFilter: TrailFilter; /** * 获取Trail渲染器。 * @return Trail渲染器。 */ readonly trailRender: TrailRenderer; constructor(); _changeRenderObjectsByMaterial(sender: TrailRenderer, index: number, material: BaseMaterial): void; _changeRenderObjectsByRenderElement(index: number, trailRenderElement: TrailRenderElement): void; protected _clearSelfRenderObjects(): void; protected _addSelfRenderObjects(): void; _update(state: RenderState): void; protected _parseCustomProps(rootNode: ComponentNode, innerResouMap: any, customProps: any, json: any): void; /** *

    销毁此对象。

    * @param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ destroy(destroyChild?: boolean): void; } } declare module laya.d3.core.trail { import IVertex = laya.d3.graphics.IVertex; import VertexDeclaration = laya.d3.graphics.VertexDeclaration; /** * VertexTrail 类用于创建拖尾顶点结构。 */ class VertexTrail implements IVertex { static readonly vertexDeclaration1: VertexDeclaration; static readonly vertexDeclaration2: VertexDeclaration; readonly vertexDeclaration: VertexDeclaration; constructor(); } } declare module laya.d3.core { import AnimationTransform3D = laya.d3.animation.AnimationTransform3D; import Matrix4x4 = laya.d3.math.Matrix4x4; import Quaternion = laya.d3.math.Quaternion; import Vector3 = laya.d3.math.Vector3; import EventDispatcher = laya.events.EventDispatcher; /** * Transform3D 类用于实现3D变换。 */ class Transform3D extends EventDispatcher { /** 变换中心点,注意:该中心点不受变换的影响。*/ pivot: Vector3; /** * @private */ readonly _isFrontFaceInvert: boolean; /** * 获取所属精灵。 */ readonly owner: Sprite3D; /** * 获取世界矩阵是否需要更新。 * @return 世界矩阵是否需要更新。 */ readonly worldNeedUpdate: boolean; /** * 获取局部矩阵。 * @return 局部矩阵。 */ /** * 设置局部矩阵。 * @param value 局部矩阵。 */ localMatrix: Matrix4x4; /** * 获取世界矩阵。 * @return 世界矩阵。 */ /** * 设置世界矩阵。 * @param value 世界矩阵。 */ worldMatrix: Matrix4x4; /** * 获取局部位置。 * @return 局部位置。 */ /** * 设置局部位置。 * @param value 局部位置。 */ localPosition: Vector3; /** * 获取局部旋转。 * @return 局部旋转。 */ /** * 设置局部旋转。 * @param value 局部旋转。 */ localRotation: Quaternion; /** * 获取局部缩放。 * @return 局部缩放。 */ /** * 设置局部缩放。 * @param value 局部缩放。 */ localScale: Vector3; /** * 获取局部空间的旋转角度。 * @return 欧拉角的旋转值,顺序为x、y、z。 */ /** * 设置局部空间的旋转角度。 * @param value 欧拉角的旋转值,顺序为x、y、z。 */ localRotationEuler: Vector3; /** * 获取世界位置。 * @return 世界位置。 */ /** * 设置世界位置。 * @param value 世界位置。 */ position: Vector3; /** * 获取世界旋转。 * @return 世界旋转。 */ /** * 设置世界旋转。 * @param value 世界旋转。 */ rotation: Quaternion; /** * 获取世界缩放。 * @return 世界缩放。 */ /** * 设置世界缩放。 * @param value 世界缩放。 */ scale: Vector3; /** * 设置局部空间的旋转角度。 * @param 欧拉角的旋转值,顺序为x、y、z。 */ rotationEuler: Vector3; /** * 获取向前方向。 * @return 向前方向。 */ readonly forward: Vector3; /** * 获取向上方向。 * @return 向上方向。 */ readonly up: Vector3; /** * 获取向右方向。 * @return 向右方向。 */ readonly right: Vector3; /** * 获取父3D变换。 * @return 父3D变换。 */ /** * 设置父3D变换。 * @param value 父3D变换。 */ parent: Transform3D; /** *获取关联虚拟变换。 * @return 虚拟变换。 */ /** *设置关联虚拟变换。 * @param value 虚拟变换。 */ dummy: AnimationTransform3D; /** * 创建一个 Transform3D 实例。 * @param owner 所属精灵。 */ constructor(owner: Sprite3D); /** * @private */ _onWorldTransform(): void; /** * 平移变换。 * @param translation 移动距离。 * @param isLocal 是否局部空间。 */ translate(translation: Vector3, isLocal?: boolean): void; /** * 旋转变换。 * @param rotations 旋转幅度。 * @param isLocal 是否局部空间。 * @param isRadian 是否弧度制。 */ rotate(rotation: Vector3, isLocal?: boolean, isRadian?: boolean): void; /** * 观察目标位置。 * @param target 观察目标。 * @param up 向上向量。 * @param isLocal 是否局部空间。 */ lookAt(target: Vector3, up: Vector3, isLocal?: boolean): void; } } declare module laya.d3.core { import Matrix4x4 = laya.d3.math.Matrix4x4; import Quaternion = laya.d3.math.Quaternion; import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import EventDispatcher = laya.events.EventDispatcher; /** * TransformUV 类用于实现UV变换。 */ class TransformUV extends EventDispatcher implements IClone { protected static _tempOffsetV3: Vector3; protected static _tempRotationQua: Quaternion; protected static _tempTitlingV3: Vector3; protected _matrix: Matrix4x4; protected _offset: Vector2; protected _rotation: number; protected _tiling: Vector2; protected _matNeedUpdte: boolean; /** *获取变换矩阵。 * @return 变换矩阵。 */ readonly matrix: Matrix4x4; /** *获取偏移。 * @return 偏移。 */ /** *设置偏移。 * @param value 偏移。 */ offset: Vector2; /** *获取旋转。 * @return 旋转。 */ /** *设置旋转。 * @param value 旋转。 */ rotation: number; /** *获取平铺次数。 * @return 平铺次数。 */ /** *设置平铺次数。 * @param value 平铺次数。 */ tiling: Vector2; /** * 创建一个 TransformUV 实例。 */ constructor(); protected _updateMatrix(): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.core { import RenderState = laya.d3.core.render.RenderState; import Scene = laya.d3.core.scene.Scene; import BoundFrustum = laya.d3.math.BoundFrustum; import Matrix4x4 = laya.d3.math.Matrix4x4; import Viewport = laya.d3.math.Viewport; import WebGLContext = laya.webgl.WebGLContext; /** * Camera 类用于创建VR摄像机。 */ class VRCamera extends BaseCamera { /** * 获取左横纵比。 * @return 左横纵比。 */ readonly leftAspectRatio: number; /** * 获取右横纵比。 * @return 右横纵比。 */ readonly rightAspectRatio: number; /** * 设置横纵比。 * @param value 横纵比。 */ aspectRatio: number; /** * 获取屏幕空间的左视口。 * @return 屏幕空间的左视口。 */ readonly leftViewport: Viewport; /** * 获取屏幕空间的右视口。 * @return 屏幕空间的右视口。 */ readonly rightViewport: Viewport; /** * 设置屏幕空间的视口。 * @param 屏幕空间的视口。 */ viewport: Viewport; /** * 获取裁剪空间的左视口。 * @return 裁剪空间的左视口。 */ readonly leftNormalizedViewport: Viewport; /** * 获取裁剪空间的右视口。 * @return 裁剪空间的右视口。 */ readonly rightNormalizedViewport: Viewport; /** * 设置裁剪空间的视口。 * @return 裁剪空间的视口。 */ normalizedViewport: Viewport; readonly needLeftViewport: boolean; readonly needRightViewport: boolean; /** * 获取左视图矩阵。 * @return 左视图矩阵。 */ readonly leftViewMatrix: Matrix4x4; /** * 获取右视图矩阵。 * @return 右视图矩阵。 */ readonly rightViewMatrix: Matrix4x4; /** * 获取左投影矩阵。 * @return 左投影矩阵。 */ readonly leftProjectionMatrix: Matrix4x4; /** * 获取右投影矩阵。 * @return 右投影矩阵。 */ readonly rightProjectionMatrix: Matrix4x4; /** * 获取左投影视图矩阵。 * @return 左投影视图矩阵。 */ readonly leftProjectionViewMatrix: Matrix4x4; /** * 获取右投影视图矩阵。 * @return 右投影视图矩阵。 */ readonly rightProjectionViewMatrix: Matrix4x4; /** * 获取摄像机左视锥。 */ readonly leftBoundFrustum: BoundFrustum; /** * 获取摄像机右视锥。 */ readonly rightBoundFrustum: BoundFrustum; /** * 创建一个 VRCamera 实例。 * @param leftViewport 左视口。 * @param rightViewport 右视口。 * @param pupilDistande 瞳距。 * @param fieldOfView 视野。 * @param leftAspectRatio 左横纵比。 * @param rightAspectRatio 右横纵比。 * @param nearPlane 近裁面。 * @param farPlane 远裁面。 */ constructor(pupilDistande?: number, leftAspectRatio?: number, rightAspectRatio?: number, nearPlane?: number, farPlane?: number); protected _calculateProjectionMatrix(): void; /** * @inheritDoc */ _renderCamera(gl: WebGLContext, state: RenderState, scene: Scene): void; } } declare module laya.d3.extension.cartoonRender { import BaseMaterial = laya.d3.core.material.BaseMaterial; import Vector4 = laya.d3.math.Vector4; import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; class CartoonMaterial extends BaseMaterial { static ALBEDOTEXTURE: number; static SPECULARTEXTURE: number; static TILINGOFFSET: number; static SHADOWCOLOR: number; static SHADOWRANGE: number; static SHADOWINTENSITY: number; static SPECULARRANGE: number; static SPECULARINTENSITY: number; static SHADERDEFINE_ALBEDOTEXTURE: number; static SHADERDEFINE_SPECULARTEXTURE: number; static SHADERDEFINE_TILINGOFFSET: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 获取漫反射贴图。 * @return 漫反射贴图。 */ /** * 设置漫反射贴图。 * @param value 漫反射贴图。 */ albedoTexture: BaseTexture; /** * 获取高光贴图。 * @return 高光贴图。 */ /** * 设置高光贴图。 * @param value 高光贴图。 */ specularTexture: BaseTexture; /** * 获取阴影颜色。 * @return 阴影颜色。 */ /** * 设置阴影颜色。 * @param value 阴影颜色。 */ shadowColor: Vector4; /** * 获取阴影范围。 * @return 阴影范围,范围为0到1。 */ /** * 设置阴影范围。 * @param value 阴影范围,范围为0到1。 */ shadowRange: number; /** * 获取阴影强度。 * @return 阴影强度,范围为0到1。 */ /** * 设置阴影强度。 * @param value 阴影强度,范围为0到1。 */ shadowIntensity: number; /** * 获取高光范围。 * @return 高光范围,范围为0.9到1。 */ /** * 设置高光范围。 * @param value 高光范围,范围为0.9到1。 */ specularRange: number; /** * 获取高光强度。 * @return 高光强度,范围为0到1。 */ /** * 设置高光强度。 * @param value 高光范围,范围为0到1。 */ specularIntensity: number; /** * 获取纹理平铺和偏移。 * @return 纹理平铺和偏移。 */ /** * 设置纹理平铺和偏移。 * @param value 纹理平铺和偏移。 */ tilingOffset: Vector4; static initShader(): void; constructor(); } } declare module laya.d3.extension.cartoonRender { import BaseMaterial = laya.d3.core.material.BaseMaterial; import BaseTexture = laya.d3.resource.BaseTexture; import ShaderDefines = laya.d3.shader.ShaderDefines; /** * ... * @author ... */ class OutlineMaterial extends BaseMaterial { static OUTLINETEXTURE: number; static OUTLINEWIDTH: number; static OUTLINELIGHTNESS: number; static SHADERDEFINE_OUTLINETEXTURE: number; static shaderDefines: ShaderDefines; /** * @private */ static __init__(): void; /** * 获取漫轮廓贴图。 * @return 轮廓贴图。 */ /** * 设置轮廓贴图。 * @param value 轮廓贴图。 */ outlineTexture: BaseTexture; /** * 获取轮廓宽度。 * @return 轮廓宽度,范围为0到0.05。 */ /** * 设置轮廓宽度。 * @param value 轮廓宽度,范围为0到0.05。 */ outlineWidth: number; /** * 获取轮廓亮度。 * @return 轮廓亮度,范围为0到1。 */ /** * 设置轮廓亮度。 * @param value 轮廓亮度,范围为0到1。 */ outlineLightness: number; static initShader(): void; constructor(); } } declare module laya.d3.graphics { import BaseMaterial = laya.d3.core.material.BaseMaterial; import IRenderable = laya.d3.core.render.IRenderable; import RenderElement = laya.d3.core.render.RenderElement; import RenderState = laya.d3.core.render.RenderState; import Scene = laya.d3.core.scene.Scene; import Matrix4x4 = laya.d3.math.Matrix4x4; /** * @private * DynamicBatch 类用于动态批处理。 */ class DynamicBatch implements IRenderable { static maxVertexCount: number; static maxIndexCount: number; static maxCombineTriangleCount: number; _vertexDeclaration: VertexDeclaration; readonly _vertexBufferCount: number; readonly triangleCount: number; readonly combineRenderElementsCount: number; _getVertexBuffer(index?: number): VertexBuffer3D; _getIndexBuffer(): IndexBuffer3D; constructor(vertexDeclaration: VertexDeclaration); _addCombineRenderObjTest(renderElement: RenderElement): boolean; _addCombineRenderObj(renderElement: RenderElement): void; _addCombineMaterial(material: BaseMaterial): void; _addMaterialToRenderElementOffset(offset: number): void; _clearRenderElements(): void; _addToRenderQueue(scene: Scene, view: Matrix4x4, projection: Matrix4x4, projectionView: Matrix4x4): void; _beforeRender(state: RenderState): boolean; _render(state: RenderState): void; /** * @private */ _getVertexBuffers(): Array; /**NATIVE*/ _renderRuntime(conchGraphics3D: any, renderElement: RenderElement, state: RenderState): void; } } declare module laya.d3.graphics { import RenderElement = laya.d3.core.render.RenderElement; import Scene = laya.d3.core.scene.Scene; import Matrix4x4 = laya.d3.math.Matrix4x4; /** * @private * DynamicBatchManager 类用于管理动态批处理。 */ class DynamicBatchManager { constructor(); getDynamicBatch(_vertexDeclaration: VertexDeclaration, number: number): DynamicBatch; /**需手动调用*/ _garbageCollection(): void; _addPrepareRenderElement(renderElement: RenderElement): void; _finishCombineDynamicBatch(scene: Scene): void; _clearRenderElements(): void; _addToRenderQueue(scene: Scene, view: Matrix4x4, projection: Matrix4x4, projectionView: Matrix4x4): void; dispose(): void; } } declare module laya.d3.graphics { import BaseCamera = laya.d3.core.BaseCamera; import Scene = laya.d3.core.scene.Scene; import BoundFrustum = laya.d3.math.BoundFrustum; import Matrix4x4 = laya.d3.math.Matrix4x4; /** * @private */ class FrustumCulling { constructor(); /** * @private */ static renderShadowObjectCulling(scene: Scene, lightFrustum: Array, shadowQueues: Array, lightViewProjectMatrix: Matrix4x4, nPSSMNum: number): void; /** * @private */ static renderShadowObjectCullingOctree(scene: Scene, lightFrustum: Array, quenesResult: Array, lightViewProjectMatrix: Matrix4x4, nPSSMNum: number): void; /** * @private */ static renderObjectCulling(boundFrustum: BoundFrustum, scene: Scene, camera: BaseCamera, view: Matrix4x4, projection: Matrix4x4, projectionView: Matrix4x4): void; /** * @private */ static renderObjectCullingOctree(boundFrustum: BoundFrustum, scene: Scene, camera: BaseCamera, view: Matrix4x4, projection: Matrix4x4, projectionView: Matrix4x4): void; /** * @private */ static renderObjectCullingNoBoundFrustum(scene: Scene, camera: BaseCamera, view: Matrix4x4, projection: Matrix4x4, projectionView: Matrix4x4): void; } } declare module laya.d3.graphics { import Buffer = laya.webgl.utils.Buffer; /** * IndexBuffer3D 类用于创建索引缓冲。 */ class IndexBuffer3D extends Buffer { /** 8位ubyte无符号索引类型。*/ static INDEXTYPE_UBYTE: string; /** 16位ushort无符号索引类型。*/ static INDEXTYPE_USHORT: string; /** * 创建IndexBuffer3D。 * @param indexType 索引类型。 * @param indexCount 索引个数。 * @param bufferUsage IndexBuffer3D用途类型。 * @param canRead 是否可读。 * @return 索引缓冲。 */ static create: Function; /** * 获取索引类型。 * @return 索引类型。 */ readonly indexType: string; /** * 获取索引类型字节数量。 * @return 索引类型字节数量。 */ readonly indexTypeByteCount: number; /** * 获取索引个数。 * @return 索引个数。 */ readonly indexCount: number; /** * 获取是否可读。 * @return 是否可读。 */ readonly canRead: boolean; /** * 创建一个 IndexBuffer3D,不建议开发者使用并用IndexBuffer3D.create()代替 实例。 * @param indexType 索引类型。 * @param indexCount 索引个数。 * @param bufferUsage IndexBuffer3D用途类型。 * @param canRead 是否可读。 */ constructor(indexType: string, indexCount: number, bufferUsage?: number, canRead?: boolean); /** * 设置数据。 * @param data 索引数据。 * @param bufferOffset 索引缓冲中的偏移。 * @param dataStartIndex 索引数据的偏移。 * @param dataCount 索引数据的数量。 */ setData(data: any, bufferOffset?: number, dataStartIndex?: number, dataCount?: number): void; /** * 获取索引数据。 * @return 索引数据。 */ getData(): Uint16Array; protected disposeResource(): void; } } declare module laya.d3.graphics { /** * IVertex 接口用于实现创建顶点声明。 */ interface IVertex { } } declare module laya.d3.graphics { import Sprite3D = laya.d3.core.Sprite3D; import SubMeshRenderElement = laya.d3.core.render.SubMeshRenderElement; /** * @private * MeshSprite3DStaticBatchManager 类用于网格精灵静态批处理管理。 */ class MeshSprite3DStaticBatchManager extends StaticBatchManager { /** * @private */ static _sortPrepareStaticBatch(a: SubMeshRenderElement, b: SubMeshRenderElement): any; /**i * 创建一个 MeshSprite3DStaticBatchManager 实例。 */ constructor(); protected _initStaticBatchs(rootOwner: Sprite3D): void; } } declare module laya.d3.graphics { import Sprite3D = laya.d3.core.Sprite3D; import BaseMaterial = laya.d3.core.material.BaseMaterial; import IRenderable = laya.d3.core.render.IRenderable; import RenderElement = laya.d3.core.render.RenderElement; import RenderState = laya.d3.core.render.RenderState; import Scene = laya.d3.core.scene.Scene; import Matrix4x4 = laya.d3.math.Matrix4x4; import IDispose = laya.resource.IDispose; /** * StaticBatch 类用于静态合并的父类,该类为抽象类。 */ class StaticBatch implements IRenderable, IDispose { static maxBatchVertexCount: number; /** * 兼容性接口,请使用StaticBatchManager.combine()代替。 */ static combine(staticBatchRoot: Sprite3D): void; protected _combineRenderElementPoolIndex: number; protected _combineRenderElementPool: Array; _initBatchRenderElements: Array; _batchRenderElements: Array; _material: BaseMaterial; _rootOwner: Sprite3D; _key: string; _manager: StaticBatchManager; readonly _vertexBufferCount: number; readonly triangleCount: number; /** * 创建一个 StaticBatch 实例。 */ constructor(key: string, manager: StaticBatchManager, rootOwner: Sprite3D); protected _compareBatchRenderElement(a: RenderElement, b: RenderElement): boolean; protected _getVertexDecLightMap(vertexDeclaration: VertexDeclaration): VertexDeclaration; protected _getCombineRenderElementFromPool(): RenderElement; /** * @private */ _addBatchRenderElement(renderElement: RenderElement): void; /** * @private */ _updateToRenderQueue(scene: Scene, projectionView: Matrix4x4): void; protected _getRenderElement(mergeElements: Array, scene: Scene, projectionView: Matrix4x4): void; /** * @private */ _finishInit(): void; /** * @private */ _clearRenderElements(): void; /** * @private */ dispose(): void; _getVertexBuffer(index?: number): VertexBuffer3D; _getIndexBuffer(): IndexBuffer3D; _beforeRender(state: RenderState): boolean; _render(state: RenderState): void; /** * @private */ _getVertexBuffers(): Array; /**NATIVE*/ _renderRuntime(conchGraphics3D: any, renderElement: RenderElement, state: RenderState): void; } } declare module laya.d3.graphics { import RenderableSprite3D = laya.d3.core.RenderableSprite3D; import Sprite3D = laya.d3.core.Sprite3D; import RenderElement = laya.d3.core.render.RenderElement; import Scene = laya.d3.core.scene.Scene; import Matrix4x4 = laya.d3.math.Matrix4x4; /** * @private * StaticBatchManager 类用于静态批处理管理的父类。 */ class StaticBatchManager { static _staticBatchManagers: Array; /** * 静态批处理合并,合并后子节点修改Transform属性无效,根节点staticBatchRoot可为null,如果根节点不为null,根节点可移动。 * 如果renderableSprite3Ds为null,合并staticBatchRoot以及其所有子节点为静态批处理,staticBatchRoot作为静态根节点。 * 如果renderableSprite3Ds不为null,合并renderableSprite3Ds为静态批处理,staticBatchRoot作为静态根节点。 * @param staticBatchRoot 静态批处理根节点。 * @param renderableSprite3Ds 静态批处理子节点队列。 */ static combine(staticBatchRoot: Sprite3D, renderableSprite3Ds?: Array): void; protected _initBatchRenderElements: Array; protected _staticBatches: any; /** * 创建一个 StaticBatchManager 实例。 */ constructor(); protected _finishInit(): void; protected _initStaticBatchs(rootSprite: Sprite3D): void; /** * @private */ _addInitBatchSprite(renderableSprite3D: RenderableSprite3D): void; /** * @private */ _clearRenderElements(): void; /** * @private */ _garbageCollection(renderElement: RenderElement): void; /** * @private */ _addToRenderQueue(scene: Scene, view: Matrix4x4, projection: Matrix4x4, projectionView: Matrix4x4): void; dispose(): void; } } declare module laya.d3.graphics { import Sprite3D = laya.d3.core.Sprite3D; import BaseMaterial = laya.d3.core.material.BaseMaterial; import RenderElement = laya.d3.core.render.RenderElement; import RenderState = laya.d3.core.render.RenderState; import Scene = laya.d3.core.scene.Scene; import Matrix4x4 = laya.d3.math.Matrix4x4; /** * SubMeshStaticBatch 类用于网格静态合并。 */ class SubMeshStaticBatch extends StaticBatch { _vertexDeclaration: VertexDeclaration; /** * 创建一个 SubMeshStaticBatch 实例。 */ constructor(key: string, manager: StaticBatchManager, rootOwner: Sprite3D, vertexDeclaration: VertexDeclaration, material: BaseMaterial); protected _compareBatchRenderElement(a: RenderElement, b: RenderElement): boolean; /** * @private */ _addCombineBatchRenderObjTest(renderElement: RenderElement): boolean; /** * @private */ _addCombineBatchRenderObj(renderElement: RenderElement): void; /** * @private */ _deleteCombineBatchRenderObj(renderElement: RenderElement): void; /** * @inheritDoc */ _finishInit(): void; protected _getCombineRenderElementFromPool(): RenderElement; protected _getRenderElement(renderQueueElements: Array, scene: Scene, projectionView: Matrix4x4): void; /** * @inheritDoc */ _beforeRender(state: RenderState): boolean; /** * @inheritDoc */ _render(state: RenderState): void; /** * @inheritDoc */ dispose(): void; _getVertexBuffer(index?: number): VertexBuffer3D; } } declare module laya.d3.graphics { import Buffer = laya.webgl.utils.Buffer; /** * VertexBuffer3D 类用于创建顶点缓冲。 */ class VertexBuffer3D extends Buffer { /** * 创建VertexBuffer3D。 * @param vertexDeclaration 顶点声明。 * @param vertexCount 顶点个数。 * @param bufferUsage VertexBuffer3D用途类型。 * @param canRead 是否可读。 * @return 顶点缓冲。 */ static create: Function; /** * 获取顶点结构声明。 * @return 顶点结构声明。 */ readonly vertexDeclaration: VertexDeclaration; /** * 获取顶点个数。 * @return 顶点个数。 */ readonly vertexCount: number; /** * 获取是否可读。 * @return 是否可读。 */ readonly canRead: boolean; /** * 创建一个 VertexBuffer3D,不建议开发者使用并用VertexBuffer3D.create()代替 实例。 * @param vertexDeclaration 顶点声明。 * @param vertexCount 顶点个数。 * @param bufferUsage VertexBuffer3D用途类型。 * @param canRead 是否可读。 */ constructor(vertexDeclaration: VertexDeclaration, vertexCount: number, bufferUsage: number, canRead?: boolean); /** * 和索引缓冲一起绑定。 * @param ib 索引缓冲。 */ bindWithIndexBuffer(ib: IndexBuffer3D): void; /** * 设置数据。 * @param data 顶点数据。 * @param bufferOffset 顶点缓冲中的偏移。 * @param dataStartIndex 顶点数据的偏移。 * @param dataCount 顶点数据的数量。 */ setData(data: Float32Array, bufferOffset?: number, dataStartIndex?: number, dataCount?: number): void; /** * 获取顶点数据。 * @return 顶点数据。 */ getData(): Float32Array; protected disposeResource(): void; } } declare module laya.d3.graphics { import ValusArray = laya.d3.shader.ValusArray; /** * ... * @author ... */ class VertexDeclaration { static _maxVertexDeclarationBit: number; static maxVertexDeclaration: number; static getVertexStride(vertexElements: Array): number; _conchVertexDeclaration: any; /** * 获取唯一标识ID(通常用于优化或识别)。 * @return 唯一标识ID */ readonly id: number; readonly vertexStride: number; readonly shaderValues: ValusArray; readonly shaderDefineValue: number; /** * 增加Shader宏定义。 * @param value 宏定义。 */ _addShaderDefine(value: number): void; protected _removeShaderDefine(value: number): void; constructor(vertexStride: number, vertexElements: Array); getVertexElements(): Array; getVertexElementByUsage(usage: number): VertexElement; unBinding(): void; } } declare module laya.d3.graphics { /** * VertexElement 类用于创建顶点结构分配。 */ class VertexElement { offset: number; elementFormat: string; elementUsage: number; constructor(offset: number, elementFormat: string, elementUsage: number); } } declare module laya.d3.graphics { /** * ... * @author ... */ class VertexElementFormat { static Single: string; static Vector2: string; static Vector3: string; static Vector4: string; static Color: string; static Byte4: string; static Short2: string; static Short4: string; static NormalizedShort2: string; static NormalizedShort4: string; static HalfVector2: string; static HalfVector4: string; } } declare module laya.d3.graphics { /** * ... * @author ... */ class VertexElementUsage { static POSITION0: number; static COLOR0: number; static TEXTURECOORDINATE0: number; static NORMAL0: number; static BINORMAL0: number; static TANGENT0: number; static BLENDINDICES0: number; static BLENDWEIGHT0: number; static DEPTH0: number; static FOG0: number; static POINTSIZE0: number; static SAMPLE0: number; static TESSELLATEFACTOR0: number; static COLOR1: number; static NEXTTEXTURECOORDINATE0: number; static TEXTURECOORDINATE1: number; static NEXTTEXTURECOORDINATE1: number; static CORNERTEXTURECOORDINATE0: number; static VELOCITY0: number; static STARTCOLOR0: number; static STARTSIZE: number; static AGEADDSCALE0: number; static STARTROTATION: number; static ENDCOLOR0: number; static STARTLIFETIME: number; static TIME0: number; static SHAPEPOSITIONSTARTLIFETIME: number; static DIRECTIONTIME: number; static SIZEROTATION0: number; static RADIUS0: number; static RADIAN0: number; static STARTSPEED: number; static RANDOM0: number; static RANDOM1: number; static SIMULATIONWORLDPOSTION: number; static SIMULATIONWORLDROTATION: number; static TEXTURECOORDINATE0X: number; static TEXTURECOORDINATE0X1: number; static TEXTURECOORDINATE0Y: number; static OFFSETVECTOR: number; } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionNormalColorTangent 类用于创建粒子顶点结构。 */ class VertexGlitter implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly textureCoordinate: Vector2; readonly time: number; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, textureCoordinate: Vector2, time: number); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTangent 类用于创建粒子顶点结构。 */ class VertexParticle implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly cornerTextureCoordinate: Vector4; readonly position: Vector3; readonly velocity: Vector3; readonly startColor: Vector4; readonly endColor: Vector4; readonly sizeRotation: Vector3; readonly radius: Vector2; readonly radian: Vector4; readonly ageAddScale: number; readonly time: number; readonly vertexDeclaration: VertexDeclaration; constructor(cornerTextureCoordinate: Vector4, position: Vector3, velocity: Vector3, startColor: Vector4, endColor: Vector4, sizeRotation: Vector3, radius: Vector2, radian: Vector4, ageAddScale: number, time: number); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; class VertexPosition implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; class VertexPositionNormal implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColor 类用于创建位置、法线、颜色顶点结构。 */ class VertexPositionNormalColor implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorSkin 类用于创建位置、法线、颜色、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalColorSkin implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorSkin 类用于创建位置、法线、颜色、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalColorSkinSTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector4; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, tangent: Vector4, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorSkin 类用于创建位置、法线、颜色、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalColorSkinTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector4; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, tangent: Vector4, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTangent 类用于创建位置、法线、颜色、切线顶点结构。 */ class VertexPositionNormalColorSTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly tangent: Vector4; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, tangent: Vector4); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTangent 类用于创建位置、法线、颜色、切线顶点结构。 */ class VertexPositionNormalColorTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly tangent: Vector4; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, tangent: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTexture 类用于创建位置、法线、颜色、纹理顶点结构。 */ class VertexPositionNormalColorTexture implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate: Vector2; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate: Vector2); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTexture 类用于创建位置、法线、颜色、纹理顶点结构。 */ class VertexPositionNormalColorTexture0Texture1 implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate0: Vector2, textureCoordinate1: Vector2); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalColorTexture0Texture1Skin implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate0: Vector2, textureCoordinate1: Vector2, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalColorTexture0Texture1SkinSTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate0: Vector2, textureCoordinate1: Vector2, tangent: Vector3, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalColorTexture0Texture1SkinTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; VertexPositionNormalColorTexture0SkinTangent(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate0: Vector2, textureCoordinate1: Vector2, tangent: Vector3, blendIndex: Vector4, blendWeight: Vector4): void; } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ class VertexPositionNormalColorTexture0Texture1STangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate0: Vector2, textureCoordinate1: Vector2, tangent: Vector3); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ class VertexPositionNormalColorTexture0Texture1Tangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; VertexPositionNormalColorTexture0Tangent(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate0: Vector2, textureCoordinate1: Vector2, tangent: Vector3): void; } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalColorTextureSkin implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate: Vector2, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalColorTextureSkinSTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate: Vector2, tangent: Vector3, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalColorTextureSkinTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate: Vector2, tangent: Vector3, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ class VertexPositionNormalColorTextureSTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate: Vector2; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate: Vector2, tangent: Vector3); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ class VertexPositionNormalColorTextureTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly color: Vector4; readonly textureCoordinate: Vector2; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, color: Vector4, textureCoordinate: Vector2, tangent: Vector3); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; class VertexPositionNormalSTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, tangent: Vector3); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; class VertexPositionNormalTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, tangent: Vector3); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ class VertexPositionNormalTexture implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate: Vector2; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate: Vector2); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ class VertexPositionNormalTexture0Texture1 implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate0: Vector2, textureCoordinate1: Vector2); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalTexture0Texture1Skin implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate0: Vector2, textureCoordinate1: Vector2, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalTexture0Texture1SkinSTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate0: Vector2, textureCoordinate1: Vector2, tangent: Vector3, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalTexture0Texture1SkinTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; VertexPositionNormalTexture0SkinTangent(position: Vector3, normal: Vector3, textureCoordinate0: Vector2, textureCoordinate1: Vector2, tangent: Vector3, blendIndex: Vector4, blendWeight: Vector4): void; } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ class VertexPositionNormalTexture0Texture1STangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate0: Vector2, textureCoordinate1: Vector2, tangent: Vector3); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ class VertexPositionNormalTexture0Texture1Tangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; VertexPositionNormalTexture0Tangent(position: Vector3, normal: Vector3, textureCoordinate0: Vector2, textureCoordinate1: Vector2, tangent: Vector3): void; } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalTextureSkin implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate: Vector2, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalTextureSkinSTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate: Vector2, tangent: Vector3, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNormalTextureSkinTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate: Vector2, tangent: Vector3, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ class VertexPositionNormalTextureSTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate: Vector2; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate: Vector2, tangent: Vector3); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ class VertexPositionNormalTextureTangent implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate: Vector2; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate: Vector2, tangent: Vector3); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ class VertexPositionNTBTexture implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate: Vector2; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate: Vector2); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ class VertexPositionNTBTexture0Texture1Skin implements IVertex { static readonly vertexDeclaration: VertexDeclaration; binormal: Vector3; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate0: Vector2; readonly textureCoordinate1: Vector2; readonly blendIndex: Vector4; readonly blendWeight: Vector4; readonly tangent: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, binormal: Vector3, textureCoordinate0: Vector2, textureCoordinate1: Vector2, tangent: Vector3, blendIndex: Vector4, blendWeight: Vector4); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ class VertexPositionNTBTextureSkin implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoordinate: Vector2; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoordinate: Vector2); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionTerrain 类用于创建位置、法线、纹理1、纹理2顶点结构。 */ class VertexPositionTerrain implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly normal: Vector3; readonly textureCoord0: Vector2; readonly textureCoord1: Vector2; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, normal: Vector3, textureCoord0: Vector2, textureCoord1: Vector2); } } declare module laya.d3.graphics { import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * VertexPositionNormalTexture 类用于创建位置、纹理顶点结构。 */ class VertexPositionTexture0 implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly position: Vector3; readonly textureCoordinate0: Vector2; readonly vertexDeclaration: VertexDeclaration; constructor(position: Vector3, textureCoordinate0: Vector2); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexShurikenParticle 类用于创建粒子顶点结构。 */ class VertexShurikenParticleBillboard implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly cornerTextureCoordinate: Vector4; readonly positionStartLifeTime: Vector4; readonly velocity: Vector3; readonly startColor: Vector4; readonly startSize: Vector3; readonly startRotation0: Vector3; readonly startRotation1: Vector3; readonly startRotation2: Vector3; readonly startLifeTime: number; readonly time: number; readonly startSpeed: number; readonly random0: Vector4; readonly random1: Vector4; readonly simulationWorldPostion: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(cornerTextureCoordinate: Vector4, positionStartLifeTime: Vector4, velocity: Vector3, startColor: Vector4, startSize: Vector3, startRotation0: Vector3, startRotation1: Vector3, startRotation2: Vector3, ageAddScale: number, time: number, startSpeed: number, randoms0: Vector4, randoms1: Vector4, simulationWorldPostion: Vector3); } } declare module laya.d3.graphics { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * VertexShurikenParticle 类用于创建粒子顶点结构。 */ class VertexShurikenParticleMesh implements IVertex { static readonly vertexDeclaration: VertexDeclaration; readonly cornerTextureCoordinate: Vector4; readonly position: Vector4; readonly velocity: Vector3; readonly startColor: Vector4; readonly startSize: Vector3; readonly startRotation0: Vector3; readonly startRotation1: Vector3; readonly startRotation2: Vector3; readonly startLifeTime: number; readonly time: number; readonly startSpeed: number; readonly random0: Vector4; readonly random1: Vector4; readonly simulationWorldPostion: Vector3; readonly vertexDeclaration: VertexDeclaration; constructor(cornerTextureCoordinate: Vector4, positionStartLifeTime: Vector4, velocity: Vector3, startColor: Vector4, startSize: Vector3, startRotation0: Vector3, startRotation1: Vector3, startRotation2: Vector3, ageAddScale: number, time: number, startSpeed: number, randoms0: Vector4, randoms1: Vector4, simulationWorldPostion: Vector3); } } declare module laya.d3.loaders { import Mesh = laya.d3.resource.models.Mesh; import Byte = laya.utils.Byte; /** * @private * LoadModel 类用于模型加载。 */ class LoadModelV01 { readonly mesh: Mesh; /** * 创建一个 LoadModel 实例。 */ constructor(readData: Byte, version: string, mesh: Mesh, materials: Array, subMeshes: Array, materialMap: any); onError(): void; READ_BLOCK(): boolean; READ_DATA(): boolean; READ_STRINGS(): boolean; READ_MATERIAL(): boolean; READ_MESH(): boolean; READ_SUBMESH(): boolean; READ_DATAAREA(): boolean; } } declare module laya.d3.loaders { import Mesh = laya.d3.resource.models.Mesh; import Byte = laya.utils.Byte; /** * @private * LoadModel 类用于模型加载。 */ class LoadModelV02 { /** * @private */ static parse(readData: Byte, version: string, mesh: Mesh, materials: Array, subMeshes: Array, materialMap: any): void; } } declare module laya.d3.loaders { import Mesh = laya.d3.resource.models.Mesh; import Byte = laya.utils.Byte; /** * @private * LoadModel 类用于模型加载。 */ class LoadModelV03 { static _vertexDeclarationMap_Discard: any; static _vertexDeclarationMap: any; /** * @private */ static parse(readData: Byte, version: string, mesh: Mesh, subMeshes: Array, materialMap: any): void; } } declare module laya.d3.loaders { import Mesh = laya.d3.resource.models.Mesh; /** * ... * @author ... */ class MeshReader { constructor(); static read(data: ArrayBuffer, mesh: Mesh, materials: Array, subMeshes: Array, materialMap: any): void; } } declare module laya.d3.math { import IClone = laya.d3.core.IClone; /** * BoundBox 类用于创建包围盒。 */ class BoundBox implements IClone { /**最小顶点。*/ min: Vector3; /**最大顶点。*/ max: Vector3; /** * 创建一个 BoundBox 实例。 * @param min 包围盒的最小顶点。 * @param max 包围盒的最大顶点。 */ constructor(min: Vector3, max: Vector3); /** * 获取包围盒的8个角顶点。 * @param corners 返回顶点的输出队列。 */ getCorners(corners: Array): void; toDefault(): void; /** * 从顶点生成包围盒。 * @param points 所需顶点队列。 * @param out 生成的包围盒。 */ static createfromPoints(points: Array, out: BoundBox): void; /** * 合并两个包围盒。 * @param box1 包围盒1。 * @param box2 包围盒2。 * @param out 生成的包围盒。 */ static merge(box1: BoundBox, box2: BoundBox, out: BoundBox): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.math { /** * BoundFrustum 类用于创建锥截体。 */ class BoundFrustum { /** * 创建一个 BoundFrustum 实例。 * @param matrix 锥截体的描述4x4矩阵。 */ constructor(matrix: Matrix4x4); /** * 获取描述矩阵。 * @return 描述矩阵。 */ /** * 设置描述矩阵。 * @param matrix 描述矩阵。 */ matrix: Matrix4x4; /** * 获取近平面。 * @return 近平面。 */ readonly near: Plane; /** * 获取远平面。 * @return 远平面。 */ readonly far: Plane; /** * 获取左平面。 * @return 左平面。 */ readonly left: Plane; /** * 获取右平面。 * @return 右平面。 */ readonly right: Plane; /** * 获取顶平面。 * @return 顶平面。 */ readonly top: Plane; /** * 获取底平面。 * @return 底平面。 */ readonly bottom: Plane; /** * 判断是否与其他锥截体相等。 * @param other 锥截体。 */ equalsBoundFrustum(other: BoundFrustum): boolean; /** * 判断是否与其他对象相等。 * @param obj 对象。 */ equalsObj(obj: any): boolean; /** * 获取锥截体的任意一平面。 * 0:近平面 * 1:远平面 * 2:左平面 * 3:右平面 * 4:顶平面 * 5:底平面 * @param index 索引。 */ getPlane(index: number): Plane; /** * 锥截体的8个顶点。 * @param corners 返回顶点的输出队列。 */ getCorners(corners: Array): void; /** * 与点的位置关系。返回-1,包涵;0,相交;1,不相交 * @param point 点。 */ containsPoint(point: Vector3): number; /** * 与包围盒的位置关系。返回-1,包涵;0,相交;1,不相交 * @param box 包围盒。 */ containsBoundBox(box: BoundBox): number; /** * 与包围球的位置关系。返回-1,包涵;0,相交;1,不相交 * @param sphere 包围球。 */ containsBoundSphere(sphere: BoundSphere): number; } } declare module laya.d3.math { import IClone = laya.d3.core.IClone; /** * BoundSphere 类用于创建包围球。 */ class BoundSphere implements IClone { /**包围球的中心。*/ center: Vector3; /**包围球的半径。*/ radius: number; /** * 创建一个 BoundSphere 实例。 * @param center 包围球的中心。 * @param radius 包围球的半径。 */ constructor(center: Vector3, radius: number); toDefault(): void; /** * 从顶点的子队列生成包围球。 * @param points 顶点的队列。 * @param start 顶点子队列的起始偏移。 * @param count 顶点子队列的顶点数。 * @param result 生成的包围球。 */ static createFromSubPoints(points: Array, start: number, count: number, out: BoundSphere): void; /** * 从顶点队列生成包围球。 * @param points 顶点的队列。 * @param result 生成的包围球。 */ static createfromPoints(points: Array, out: BoundSphere): void; /** * 判断射线是否与碰撞球交叉,并返回交叉距离。 * @param ray 射线。 * @return 距离交叉点的距离,-1表示不交叉。 */ intersectsRayDistance(ray: Ray): number; /** * 判断射线是否与碰撞球交叉,并返回交叉点。 * @param ray 射线。 * @param outPoint 交叉点。 * @return 距离交叉点的距离,-1表示不交叉。 */ intersectsRayPoint(ray: Ray, outPoint: Vector3): number; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.math { /** * Collision 类用于检测碰撞。 */ class Collision { /** * 创建一个 Collision 实例。 */ constructor(); /** * 空间中点到平面的距离 * @param plane 平面 * @param point 点 */ static distancePlaneToPoint(plane: Plane, point: Vector3): number; /** * 空间中点到包围盒的距离 * @param box 包围盒 * @param point 点 */ static distanceBoxToPoint(box: BoundBox, point: Vector3): number; /** * 空间中包围盒到包围盒的距离 * @param box1 包围盒1 * @param box2 包围盒2 */ static distanceBoxToBox(box1: BoundBox, box2: BoundBox): number; /** * 空间中点到包围球的距离 * @param sphere 包围球 * @param point 点 */ static distanceSphereToPoint(sphere: BoundSphere, point: Vector3): number; /** * 空间中包围球到包围球的距离 * @param sphere1 包围球1 * @param sphere2 包围球2 */ static distanceSphereToSphere(sphere1: BoundSphere, sphere2: BoundSphere): number; /** * 空间中射线和三角面是否相交,输出距离 * @param ray 射线 * @param vertex1 三角面顶点1 * @param vertex2 三角面顶点2 * @param vertex3 三角面顶点3 * @param out 点和三角面的距离 * @return 是否相交 */ static intersectsRayAndTriangleRD(ray: Ray, vertex1: Vector3, vertex2: Vector3, vertex3: Vector3, out: number): boolean; /** * 空间中射线和三角面是否相交,输出相交点 * @param ray 射线 * @param vertex1 三角面顶点1 * @param vertex2 三角面顶点2 * @param vertex3 三角面顶点3 * @param out 相交点 * @return 是否相交 */ static intersectsRayAndTriangleRP(ray: Ray, vertex1: Vector3, vertex2: Vector3, vertex3: Vector3, out: Vector3): boolean; /** * 空间中射线和点是否相交 * @param ray 射线 * @param point 点 */ static intersectsRayAndPoint(ray: Ray, point: Vector3): boolean; /** * 空间中射线和射线是否相交 * @param ray1 射线1 * @param ray2 射线2 * @param out 相交点 */ static intersectsRayAndRay(ray1: Ray, ray2: Ray, out: Vector3): boolean; /** * 空间中平面和三角面是否相交 * @param plane 平面 * @param vertex1 三角面顶点1 * @param vertex2 三角面顶点2 * @param vertex3 三角面顶点3 * @return 返回空间位置关系 */ static intersectsPlaneAndTriangle(plane: Plane, vertex1: Vector3, vertex2: Vector3, vertex3: Vector3): number; /** * 空间中射线和平面是否相交 * @param ray 射线 * @param plane 平面 * @param out 相交距离,如果为0,不相交 */ static intersectsRayAndPlaneRD(ray: Ray, plane: Plane, out: number): boolean; /** * 空间中射线和平面是否相交 * @param ray 射线 * @param plane 平面 * @param out 相交点 */ static intersectsRayAndPlaneRP(ray: Ray, plane: Plane, out: Vector3): boolean; /** * 空间中射线和包围盒是否相交 * @param ray 射线 * @param box 包围盒 * @param out 相交距离,如果为0,不相交 */ static intersectsRayAndBoxRD(ray: Ray, box: BoundBox): number; /** * 空间中射线和包围盒是否相交 * @param ray 射线 * @param box 包围盒 * @param out 相交点 */ static intersectsRayAndBoxRP(ray: Ray, box: BoundBox, out: Vector3): number; /** * 空间中射线和包围球是否相交 * @param ray 射线 * @param sphere 包围球 * @return 相交距离,-1表示不相交 */ static intersectsRayAndSphereRD(ray: Ray, sphere: BoundSphere): number; /** * 空间中射线和包围球是否相交 * @param ray 射线 * @param sphere 包围球 * @param out 相交点 * @return 相交距离,-1表示不相交 */ static intersectsRayAndSphereRP(ray: Ray, sphere: BoundSphere, out: Vector3): number; /** * 空间中包围球和三角面是否相交 * @param sphere 包围球 * @param vertex1 三角面顶点1 * @param vertex2 三角面顶点2 * @param vertex3 三角面顶点3 * @return 返回是否相交 */ static intersectsSphereAndTriangle(sphere: BoundSphere, vertex1: Vector3, vertex2: Vector3, vertex3: Vector3): boolean; /** * 空间中点和平面是否相交 * @param plane 平面 * @param point 点 * @return 碰撞状态 */ static intersectsPlaneAndPoint(plane: Plane, point: Vector3): number; /** * 空间中平面和平面是否相交 * @param plane1 平面1 * @param plane2 平面2 * @return 是否相交 */ static intersectsPlaneAndPlane(plane1: Plane, plane2: Plane): boolean; /** * 空间中平面和平面是否相交 * @param plane1 平面1 * @param plane2 平面2 * @param line 相交线 * @return 是否相交 */ static intersectsPlaneAndPlaneRL(plane1: Plane, plane2: Plane, line: Ray): boolean; /** * 空间中平面和包围盒是否相交 * @param plane 平面 * @param box 包围盒 * @return 碰撞状态 */ static intersectsPlaneAndBox(plane: Plane, box: BoundBox): number; /** * 空间中平面和包围球是否相交 * @param plane 平面 * @param sphere 包围球 * @return 碰撞状态 */ static intersectsPlaneAndSphere(plane: Plane, sphere: BoundSphere): number; /** * 空间中包围盒和包围盒是否相交 * @param box1 包围盒1 * @param box2 包围盒2 * @return 是否相交 */ static intersectsBoxAndBox(box1: BoundBox, box2: BoundBox): boolean; /** * 空间中包围盒和包围球是否相交 * @param box 包围盒 * @param sphere 包围球 * @return 是否相交 */ static intersectsBoxAndSphere(box: BoundBox, sphere: BoundSphere): boolean; /** * 空间中包围球和包围球是否相交 * @param sphere1 包围球1 * @param sphere2 包围球2 * @return 是否相交 */ static intersectsSphereAndSphere(sphere1: BoundSphere, sphere2: BoundSphere): boolean; /** * 空间中包围盒是否包含另一个点 * @param box 包围盒 * @param point 点 * @return 位置关系:0 不想交,1 包含, 2 相交 */ static boxContainsPoint(box: BoundBox, point: Vector3): number; /** * 空间中包围盒是否包含另一个包围盒 * @param box1 包围盒1 * @param box2 包围盒2 * @return 位置关系:0 不想交,1 包含, 2 相交 */ static boxContainsBox(box1: BoundBox, box2: BoundBox): number; /** * 空间中包围盒是否包含另一个包围球 * @param box 包围盒 * @param sphere 包围球 * @return 位置关系:0 不想交,1 包含, 2 相交 */ static boxContainsSphere(box: BoundBox, sphere: BoundSphere): number; /** * 空间中包围球是否包含另一个点 * @param sphere 包围球 * @param point 点 * @return 位置关系:0 不想交,1 包含, 2 相交 */ static sphereContainsPoint(sphere: BoundSphere, point: Vector3): number; /** * 空间中包围球是否包含另一个三角面 * @param sphere * @param vertex1 三角面顶点1 * @param vertex2 三角面顶点2 * @param vertex3 三角面顶点3 * @return 返回空间位置关系 */ static sphereContainsTriangle(sphere: BoundSphere, vertex1: Vector3, vertex2: Vector3, vertex3: Vector3): number; /** * 空间中包围球是否包含另一包围盒 * @param sphere 包围球 * @param box 包围盒 * @return 位置关系:0 不想交,1 包含, 2 相交 */ static sphereContainsBox(sphere: BoundSphere, box: BoundBox): number; /** * 空间中包围球是否包含另一包围球 * @param sphere1 包围球 * @param sphere2 包围球 * @return 位置关系:0 不想交,1 包含, 2 相交 */ static sphereContainsSphere(sphere1: BoundSphere, sphere2: BoundSphere): number; /** * 空间中点与三角面的最近点 * @param point 点 * @param vertex1 三角面顶点1 * @param vertex2 三角面顶点2 * @param vertex3 三角面顶点3 * @param out 最近点 */ static closestPointPointTriangle(point: Vector3, vertex1: Vector3, vertex2: Vector3, vertex3: Vector3, out: Vector3): void; /** * 空间中平面与一点的最近点 * @param plane 平面 * @param point 点 * @param out 最近点 */ static closestPointPlanePoint(plane: Plane, point: Vector3, out: Vector3): void; /** * 空间中包围盒与一点的最近点 * @param box 包围盒 * @param point 点 * @param out 最近点 */ static closestPointBoxPoint(box: BoundBox, point: Vector3, out: Vector3): void; /** * 空间中包围球与一点的最近点 * @param sphere 包围球 * @param point 点 * @param out 最近点 */ static closestPointSpherePoint(sphere: BoundSphere, point: Vector3, out: Vector3): void; /** * 空间中包围球与包围球的最近点 * @param sphere1 包围球1 * @param sphere2 包围球2 * @param out 最近点 */ static closestPointSphereSphere(sphere1: BoundSphere, sphere2: BoundSphere, out: Vector3): void; } } declare module laya.d3.math { /** * ContainmentType 类用于定义空间物体位置关系。 */ class ContainmentType { static Disjoint: number; static Contains: number; static Intersects: number; } } declare module laya.d3.math { /** * MathUtils 类用于创建数学工具。 */ class MathUtils3D { /**单精度浮点(float)零的容差*/ static zeroTolerance: number; /**浮点数默认最大值*/ static MaxValue: number; /**浮点数默认最小值*/ static MinValue: number; /** * 创建一个 MathUtils 实例。 */ constructor(); /** * 是否在容差的范围内近似于0 * @param 判断值 * @return 是否近似于0 */ static isZero(v: number): boolean; /** * 两个值是否在容差的范围内近似相等Sqr Magnitude * @param 判断值 * @return 是否近似于0 */ static nearEqual(n1: number, n2: number): boolean; static fastInvSqrt(value: number): number; } } declare module laya.d3.math { import IClone = laya.d3.core.IClone; /** * Matrix3x3 类用于创建3x3矩阵。 */ class Matrix3x3 implements IClone { /**默认矩阵,禁止修改*/ static DEFAULT: Matrix3x3; /** * 根据指定平移生成3x3矩阵 * @param tra 平移 * @param out 输出矩阵 */ static createFromTranslation(trans: Vector2, out: Matrix3x3): void; /** * 根据指定旋转生成3x3矩阵 * @param rad 旋转值 * @param out 输出矩阵 */ static createFromRotation(rad: number, out: Matrix3x3): void; /** * 根据制定缩放生成3x3矩阵 * @param scale 缩放值 * @param out 输出矩阵 */ static createFromScaling(scale: Vector2, out: Matrix3x3): void; /** * 从4x4矩阵转换为一个3x3的矩阵(原则为upper-left,忽略第四行四列) * @param sou 4x4源矩阵 * @param out 3x3输出矩阵 */ static createFromMatrix4x4(sou: Matrix4x4, out: Matrix3x3): void; /** * 两个3x3矩阵的相乘 * @param left 左矩阵 * @param right 右矩阵 * @param out 输出矩阵 */ static multiply(left: Matrix3x3, right: Matrix3x3, out: Matrix3x3): void; /**矩阵元素数组*/ elements: Float32Array; /** * 创建一个 Matrix3x3 实例。 */ constructor(); /** * 计算3x3矩阵的行列式 * @return 矩阵的行列式 */ determinant(): number; /** * 通过一个二维向量转换3x3矩阵 * @param tra 转换向量 * @param out 输出矩阵 */ translate(trans: Vector2, out: Matrix3x3): void; /** * 根据指定角度旋转3x3矩阵 * @param rad 旋转角度 * @param out 输出矩阵 */ rotate(rad: number, out: Matrix3x3): void; /** *根据制定缩放3x3矩阵 * @param scale 缩放值 * @param out 输出矩阵 */ scale(scale: Vector2, out: Matrix3x3): void; /** * 计算3x3矩阵的逆矩阵 * @param out 输出的逆矩阵 */ invert(out: Matrix3x3): void; /** * 计算3x3矩阵的转置矩阵 * @param out 输出矩阵 */ transpose(out: Matrix3x3): void; /** 设置已有的矩阵为单位矩阵*/ identity(): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; /** * 计算观察3x3矩阵 * @param eye 观察者位置 * @param target 目标位置 * @param up 上向量 * @param out 输出3x3矩阵 */ static lookAt(eye: Vector3, target: Vector3, up: Vector3, out: Matrix3x3): void; } } declare module laya.d3.math { import IClone = laya.d3.core.IClone; /** * Matrix4x4 类用于创建4x4矩阵。 */ class Matrix4x4 implements IClone { /**默认矩阵,禁止修改*/ static DEFAULT: Matrix4x4; /**默认矩阵,禁止修改*/ static ZERO: Matrix4x4; /** * 绕X轴旋转 * @param rad 旋转角度 * @param out 输出矩阵 */ static createRotationX(rad: number, out: Matrix4x4): void; /** * * 绕Y轴旋转 * @param rad 旋转角度 * @param out 输出矩阵 */ static createRotationY(rad: number, out: Matrix4x4): void; /** * 绕Z轴旋转 * @param rad 旋转角度 * @param out 输出矩阵 */ static createRotationZ(rad: number, out: Matrix4x4): void; /** * 通过yaw pitch roll旋转创建旋转矩阵。 * @param yaw * @param pitch * @param roll * @param result */ static createRotationYawPitchRoll(yaw: number, pitch: number, roll: number, result: Matrix4x4): void; /** * 通过旋转轴axis和旋转角度angle计算旋转矩阵。 * @param axis 旋转轴,假定已经归一化。 * @param angle 旋转角度。 * @param result 结果矩阵。 */ static createRotationAxis(axis: Vector3, angle: number, result: Matrix4x4): void; /** * 通过四元数创建旋转矩阵。 * @param rotation 旋转四元数。 * @param result 输出旋转矩阵 */ static createRotationQuaternion(rotation: Quaternion, result: Matrix4x4): void; /** * 根据平移计算输出矩阵 * @param trans 平移向量 * @param out 输出矩阵 */ static createTranslate(trans: Vector3, out: Matrix4x4): void; /** * 根据缩放计算输出矩阵 * @param scale 缩放值 * @param out 输出矩阵 */ static createScaling(scale: Vector3, out: Matrix4x4): void; /** * 计算两个矩阵的乘法 * @param left left矩阵 * @param right right矩阵 * @param out 输出矩阵 */ static multiply(left: Matrix4x4, right: Matrix4x4, out: Matrix4x4): void; /** * 从四元数计算旋转矩阵 * @param rotation 四元数 * @param out 输出矩阵 */ static createFromQuaternion(rotation: Quaternion, out: Matrix4x4): void; /** * 计算仿射矩阵 * @param trans 平移 * @param rot 旋转 * @param scale 缩放 * @param out 输出矩阵 */ static createAffineTransformation(trans: Vector3, rot: Quaternion, scale: Vector3, out: Matrix4x4): void; /** * 计算观察矩阵 * @param eye 视点位置 * @param center 视点目标 * @param up 向上向量 * @param out 输出矩阵 */ static createLookAt(eye: Vector3, target: Vector3, up: Vector3, out: Matrix4x4): void; /** * 计算透视投影矩阵。 * @param fov 视角。 * @param aspect 横纵比。 * @param near 近裁面。 * @param far 远裁面。 * @param out 输出矩阵。 */ static createPerspective(fov: number, aspect: number, near: number, far: number, out: Matrix4x4): void; /** * 计算正交投影矩阵。 * @param left 视椎左边界。 * @param right 视椎右边界。 * @param bottom 视椎底边界。 * @param top 视椎顶边界。 * @param near 视椎近边界。 * @param far 视椎远边界。 * @param out 输出矩阵。 */ static createOrthoOffCenterRH(left: number, right: number, bottom: number, top: number, near: number, far: number, out: Matrix4x4): void; /**矩阵元素数组*/ elements: Float32Array; /** * 创建一个 Matrix4x4 实例。 * @param 4x4矩阵的各元素 */ constructor(m11?: number, m12?: number, m13?: number, m14?: number, m21?: number, m22?: number, m23?: number, m24?: number, m31?: number, m32?: number, m33?: number, m34?: number, m41?: number, m42?: number, m43?: number, m44?: number); getElementByRowColumn(row: number, column: number): number; setElementByRowColumn(row: number, column: number, value: number): void; /** * 判断两个4x4矩阵的值是否相等。 * @param other 4x4矩阵 */ equalsOtherMatrix(other: Matrix4x4): boolean; /** * 分解矩阵为平移向量、旋转四元数、缩放向量。 * @param translation 平移向量。 * @param rotation 旋转四元数。 * @param scale 缩放向量。 * @return 是否分解成功。 */ decomposeTransRotScale(translation: Vector3, rotation: Quaternion, scale: Vector3): boolean; /** * 分解矩阵为平移向量、旋转矩阵、缩放向量。 * @param translation 平移向量。 * @param rotationMatrix 旋转矩阵。 * @param scale 缩放向量。 * @return 是否分解成功。 */ decomposeTransRotMatScale(translation: Vector3, rotationMatrix: Matrix4x4, scale: Vector3): boolean; /** * 分解旋转矩阵的旋转为YawPitchRoll欧拉角。 * @param out float yaw * @param out float pitch * @param out float roll * @return */ decomposeYawPitchRoll(yawPitchRoll: Vector3): void; /**归一化矩阵 */ normalize(): void; /**计算矩阵的转置矩阵*/ transpose(): Matrix4x4; /** * 计算一个矩阵的逆矩阵 * @param out 输出矩阵 */ invert(out: Matrix4x4): void; /**设置矩阵为单位矩阵*/ identity(): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; static translation(v3: Vector3, out: Matrix4x4): void; /** * 获取平移向量。 * @param out 平移向量。 */ getTranslationVector(out: Vector3): void; /** * 设置平移向量。 * @param translate 平移向量。 */ setTranslationVector(translate: Vector3): void; /** * 获取前向量。 * @param out 前向量。 */ getForward(out: Vector3): void; /** * 设置前向量。 * @param forward 前向量。 */ setForward(forward: Vector3): void; } } declare module laya.d3.math { /** * OrientedBoundBox 类用于创建OBB包围盒。 */ class OrientedBoundBox { /**每个轴长度的一半*/ extents: Vector3; /**这个矩阵表示包围盒的位置和缩放,它的平移向量表示该包围盒的中心*/ transformation: Matrix4x4; /** * 创建一个 OrientedBoundBox 实例。 * @param extents 每个轴长度的一半 * @param transformation 包围盒的位置和缩放, */ constructor(extents: Vector3, transformation: Matrix4x4); /** * 根据AABB包围盒创建一个 OrientedBoundBox 实例。 * @param box AABB包围盒。 */ static createByBoundBox(box: BoundBox, out: OrientedBoundBox): void; /** * 根据包围盒的最大最小两顶点创建一个 OrientedBoundBox 实例。 * @param min 包围盒的最小顶点。 * @param max 包围盒的最大顶点。 */ static createByMinAndMaxVertex(min: Vector3, max: Vector3): OrientedBoundBox; /** * 获取OBB包围盒的8个顶点。 * @param corners 返回顶点的输出队列。 */ getCorners(corners: Array): void; /** * 变换该包围盒的矩阵信息。 * @param mat 矩阵 */ transform(mat: Matrix4x4): void; /** * 缩放该包围盒 * @param scaling 各轴的缩放比。 */ scale(scaling: Vector3): void; /** * 平移该包围盒。 * @param translation 平移参数 */ translate(translation: Vector3): void; /** * 该包围盒的尺寸。 * @param out 输出 */ Size(out: Vector3): void; /** * 该包围盒需要考虑的尺寸 * @param out 输出 */ getSize(out: Vector3): void; /** * 该包围盒需要考虑尺寸的平方 * @param out 输出 */ getSizeSquared(out: Vector3): void; /** * 该包围盒的几何中心 */ getCenter(center: Vector3): void; /** * 该包围盒是否包含空间中一点 * @param point 点 * @return 返回位置关系 */ containsPoint(point: Vector3): number; /** * 该包围盒是否包含空间中多点 * @param point 点 * @return 返回位置关系 */ containsPoints(points: Array): number; /** * 该包围盒是否包含空间中一包围球 * @param sphere 包围球 * @param ignoreScale 是否考虑该包围盒的缩放 * @return 返回位置关系 */ containsSphere(sphere: BoundSphere, ignoreScale?: boolean): number; /** * For accuracy, The transformation matrix for both must not have any scaling applied to it. * Anyway, scaling using Scale method will keep this method accurate. * 该包围盒是否包含空间中另一OBB包围盒 * @param obb OBB包围盒 * @return 返回位置关系 */ containsOrientedBoundBox(obb: OrientedBoundBox): number; /** * 该包围盒是否包含空间中一条线 * @param point1 点1 * @param point2 点2 * @return 返回位置关系 */ containsLine(point1: Vector3, point2: Vector3): number; /** * 该包围盒是否包含空间中另一OBB包围盒 * @param box 包围盒 * @return 返回位置关系 */ containsBoundBox(box: BoundBox): number; /** * 该包围盒是否与空间中另一射线相交 * @param ray * @param out * @return */ intersectsRay(ray: Ray, out: Vector3): number; /** * 计算Obb包围盒变换到另一Obb包围盒的矩阵 * @param a Obb包围盒 * @param b Obb包围盒 * @param noMatrixScaleApplied 是否考虑缩放 * @param out 输出变换矩阵 */ static getObbtoObbMatrix4x4(a: OrientedBoundBox, b: OrientedBoundBox, noMatrixScaleApplied: boolean, out: Matrix4x4): void; /** * 把一个Obb类型的包围盒b合入另一Obb型包围盒a * @param a obb包围盒 * @param b obb包围盒 * @param noMatrixScaleApplied 是否考虑缩放 */ static merge(a: OrientedBoundBox, b: OrientedBoundBox, noMatrixScaleApplied: boolean): void; /** * 判断两个包围盒是否相等 * @param obb obb包围盒 * @return Boolean */ equals(obb: OrientedBoundBox): boolean; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; } } declare module laya.d3.math { /** * Plane 类用于创建平面。 */ class Plane { /**平面的向量*/ normal: Vector3; /**平面到坐标系原点的距离*/ distance: number; /**平面与其他几何体相交类型*/ static PlaneIntersectionType_Back: number; static PlaneIntersectionType_Front: number; static PlaneIntersectionType_Intersecting: number; /** * 创建一个 Plane 实例。 * @param normal 平面的向量 * @param d 平面到原点的距离 */ constructor(normal: Vector3, d?: number); /** * 创建一个 Plane 实例。 * @param point1 第一点 * @param point2 第二点 * @param point3 第三点 */ static createPlaneBy3P(point1: Vector3, point2: Vector3, point3: Vector3): Plane; /** * 更改平面法线向量的系数,使之成单位长度。 */ normalize(): void; } } declare module laya.d3.math { import IClone = laya.d3.core.IClone; /** * Quaternion 类用于创建四元数。 */ class Quaternion implements IClone { static TEMPVector30: Vector3; static TEMPVector31: Vector3; static TEMPVector32: Vector3; static TEMPVector33: Vector3; static TEMPMatrix0: Matrix4x4; static TEMPMatrix1: Matrix4x4; static _tempMatrix3x3: Matrix3x3; /**默认矩阵,禁止修改*/ static DEFAULT: Quaternion; /**无效矩阵,禁止修改*/ static NAN: Quaternion; /** * 从欧拉角生成四元数(顺序为Yaw、Pitch、Roll) * @param yaw yaw值 * @param pitch pitch值 * @param roll roll值 * @param out 输出四元数 */ static createFromYawPitchRoll(yaw: number, pitch: number, roll: number, out: Quaternion): void; /** * 计算两个四元数相乘 * @param left left四元数 * @param right right四元数 * @param out 输出四元数 */ static multiply(left: Quaternion, right: Quaternion, out: Quaternion): void; /** * 从指定的轴和角度计算四元数 * @param axis 轴 * @param rad 角度 * @param out 输出四元数 */ static createFromAxisAngle(axis: Vector3, rad: number, out: Quaternion): void; /** * 根据3x3矩阵计算四元数 * @param sou 源矩阵 * @param out 输出四元数 */ static createFromMatrix3x3(sou: Matrix3x3, out: Quaternion): void; /** * 从旋转矩阵计算四元数 * @param mat 旋转矩阵 * @param out 输出四元数 */ static createFromMatrix4x4(mat: Matrix4x4, out: Quaternion): void; /** * 球面插值 * @param left left四元数 * @param right right四元数 * @param a 插值比例 * @param out 输出四元数 * @return 输出Float32Array */ static slerp(left: Quaternion, right: Quaternion, t: number, out: Quaternion): Float32Array; /** * 计算两个四元数的线性插值 * @param left left四元数 * @param right right四元数b * @param t 插值比例 * @param out 输出四元数 */ static lerp(left: Quaternion, right: Quaternion, t: number, out: Quaternion): void; /** * 计算两个四元数的和 * @param left left四元数 * @param right right 四元数 * @param out 输出四元数 */ static add(left: Quaternion, right: Quaternion, out: Quaternion): void; /** * 计算两个四元数的点积 * @param left left四元数 * @param right right四元数 * @return 点积 */ static dot(left: Quaternion, right: Quaternion): number; /**四元数元素数组*/ elements: Float32Array; /** * 获取四元数的x值 */ readonly x: number; /** * 获取四元数的y值 */ readonly y: number; /** * 获取四元数的z值 */ readonly z: number; /** * 获取四元数的w值 */ readonly w: number; /** * 创建一个 Quaternion 实例。 * @param x 四元数的x值 * @param y 四元数的y值 * @param z 四元数的z值 * @param w 四元数的w值 */ constructor(x?: number, y?: number, z?: number, w?: number); /** * 根据缩放值缩放四元数 * @param scale 缩放值 * @param out 输出四元数 */ scaling(scaling: number, out: Quaternion): void; /** * 归一化四元数 * @param out 输出四元数 */ normalize(out: Quaternion): void; /** * 计算四元数的长度 * @return 长度 */ length(): number; /** * 根据绕X轴的角度旋转四元数 * @param rad 角度 * @param out 输出四元数 */ rotateX(rad: number, out: Quaternion): void; /** * 根据绕Y轴的制定角度旋转四元数 * @param rad 角度 * @param out 输出四元数 */ rotateY(rad: number, out: Quaternion): void; /** * 根据绕Z轴的制定角度旋转四元数 * @param rad 角度 * @param out 输出四元数 */ rotateZ(rad: number, out: Quaternion): void; /** * 分解四元数到欧拉角(顺序为Yaw、Pitch、Roll),参考自http://xboxforums.create.msdn.com/forums/p/4574/23988.aspx#23988,问题绕X轴翻转超过±90度时有,会产生瞬间反转 * @param quaternion 源四元数 * @param out 欧拉角值 */ getYawPitchRoll(out: Vector3): void; /** * 求四元数的逆 * @param out 输出四元数 */ invert(out: Quaternion): void; /** *设置四元数为单位算数 * @param out 输出四元数 */ identity(): void; /** * 从Array数组拷贝值。 * @param array 数组。 * @param offset 数组偏移。 */ fromArray(array: Array, offset?: number): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; equals(b: Quaternion): boolean; /** * 计算旋转观察四元数 * @param forward 方向 * @param up 上向量 * @param out 输出四元数 */ static rotationLookAt(forward: Vector3, up: Vector3, out: Quaternion): void; /** * 计算观察四元数 * @param eye 观察者位置 * @param target 目标位置 * @param up 上向量 * @param out 输出四元数 */ static lookAt(eye: Vector3, target: Vector3, up: Vector3, out: Quaternion): void; /** * 计算长度的平方。 * @return 长度的平方。 */ lengthSquared(): number; /** * 计算四元数的逆四元数。 * @param value 四元数。 * @param out 逆四元数。 */ static invert(value: Quaternion, out: Quaternion): void; /** * 通过一个3x3矩阵创建一个四元数 * @param matrix3x3 3x3矩阵 * @param out 四元数 */ static rotationMatrix(matrix3x3: Matrix3x3, out: Quaternion): void; } } declare module laya.d3.math { /** * Rand 类用于通过32位无符号整型随机种子创建随机数。 */ class Rand { /** * 通过无符号32位整形,获取32位浮点随机数。 * @param 无符号32位整形随机数。 * @return 32位浮点随机数。 */ static getFloatFromInt(v: number): number; /** * 通过无符号32位整形,获取无符号8位字节随机数。 * @param 无符号32位整形随机数。 * @return 无符号8位字节随机数。 */ static getByteFromInt(v: number): number; /**获取随机种子。*/ seeds: Uint32Array; /** * 获取随机种子。 * @return 随机种子。 */ /** * 设置随机种子。 * @param seed 随机种子。 */ seed: number; /** * 创建一个 Rand 实例。 * @param seed 32位无符号整型随机种子。 */ constructor(seed: number); /** * 获取无符号32位整形随机数。 * @return 无符号32位整形随机数。 */ getUint(): number; /** * 获取0到1之间的浮点随机数。 * @return 0到1之间的浮点随机数。 */ getFloat(): number; /** * 获取-1到1之间的浮点随机数。 * @return -1到1之间的浮点随机数。 */ getSignedFloat(): number; } } declare module laya.d3.math { /** * Rand 类用于通过128位整型种子创建随机数,算法来自:https://github.com/AndreasMadsen/xorshift。 */ class RandX { /**基于时间种子的随机数。*/ static defaultRand: RandX; /** * 创建一个 Rand 实例。 * @param seed 随机种子。 */ constructor(seed: Array); /** * 通过2x32位的数组,返回64位的随机数。 * @return 64位的随机数。 */ randomint(): Array; /** * 返回[0,1)之间的随机数。 * @return */ random(): number; } } declare module laya.d3.math { /** * Ray 类用于创建射线。 */ class Ray { /**原点*/ origin: Vector3; /**方向*/ direction: Vector3; /** * 创建一个 Ray 实例。 * @param origin 射线的起点 * @param direction 射线的方向 */ constructor(origin: Vector3, direction: Vector3); } } declare module laya.d3.math { import IClone = laya.d3.core.IClone; /** * Vector2 类用于创建二维向量。 */ class Vector2 implements IClone { /**零向量,禁止修改*/ static ZERO: Vector2; /**一向量,禁止修改*/ static ONE: Vector2; /**二维向量元素数组*/ elements: any; /** * 获取X轴坐标。 * @return X轴坐标。 */ /** * 设置X轴坐标。 * @param value X轴坐标。 */ x: number; /** * 获取Y轴坐标。 * @return Y轴坐标。 */ /** * 设置Y轴坐标。 * @param value Y轴坐标。 */ y: number; /** * 创建一个 Vector2 实例。 * @param x X轴坐标。 * @param y Y轴坐标。 */ constructor(x?: number, y?: number); /** * 缩放二维向量。 * @param a 源二维向量。 * @param b 缩放值。 * @param out 输出二维向量。 */ static scale(a: Vector2, b: number, out: Vector2): void; /** * 从Array数组拷贝值。 * @param array 数组。 * @param offset 数组偏移。 */ fromArray(array: Array, offset?: number): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; } } declare module laya.d3.math { import IClone = laya.d3.core.IClone; /** * Vector3 类用于创建三维向量。 */ class Vector3 implements IClone { /**@private */ static _tempVector4: Vector4; /**零向量,禁止修改*/ static ZERO: Vector3; /**一向量,禁止修改*/ static ONE: Vector3; /**X轴单位向量,禁止修改*/ static NegativeUnitX: Vector3; /**X轴单位向量,禁止修改*/ static UnitX: Vector3; /**Y轴单位向量,禁止修改*/ static UnitY: Vector3; /**Z轴单位向量,禁止修改*/ static UnitZ: Vector3; /**右手坐标系统前向量,禁止修改*/ static ForwardRH: Vector3; /**左手坐标系统前向量,禁止修改*/ static ForwardLH: Vector3; /**上向量,禁止修改*/ static Up: Vector3; /**无效矩阵,禁止修改*/ static NAN: Vector3; /** * 两个三维向量距离的平方。 * @param value1 向量1。 * @param value2 向量2。 * @return 距离的平方。 */ static distanceSquared(value1: Vector3, value2: Vector3): number; /** * 两个三维向量距离。 * @param value1 向量1。 * @param value2 向量2。 * @return 距离。 */ static distance(value1: Vector3, value2: Vector3): number; /** * 分别取两个三维向量x、y、z的最小值计算新的三维向量。 * @param a。 * @param b。 * @param out。 */ static min(a: Vector3, b: Vector3, out: Vector3): void; /** * 分别取两个三维向量x、y、z的最大值计算新的三维向量。 * @param a a三维向量。 * @param b b三维向量。 * @param out 结果三维向量。 */ static max(a: Vector3, b: Vector3, out: Vector3): void; /** * 根据四元数旋转三维向量。 * @param source 源三维向量。 * @param rotation 旋转四元数。 * @param out 输出三维向量。 */ static transformQuat(source: Vector3, rotation: Quaternion, out: Vector3): void; /** * 计算标量长度。 * @param a 源三维向量。 * @return 标量长度。 */ static scalarLength(a: Vector3): number; /** * 计算标量长度。 * @param a 源三维向量。 * @return 标量长度的平方。 */ static scalarLengthSquared(a: Vector3): number; /** * 归一化三维向量。 * @param s 源三维向量。 * @param out 输出三维向量。 */ static normalize(s: Vector3, out: Vector3): void; /** * 计算两个三维向量的乘积。 * @param a left三维向量。 * @param b right三维向量。 * @param out 输出三维向量。 */ static multiply(a: Vector3, b: Vector3, out: Vector3): void; /** * 缩放三维向量。 * @param a 源三维向量。 * @param b 缩放值。 * @param out 输出三维向量。 */ static scale(a: Vector3, b: number, out: Vector3): void; /** * 插值三维向量。 * @param a left向量。 * @param b right向量。 * @param t 插值比例。 * @param out 输出向量。 */ static lerp(a: Vector3, b: Vector3, t: number, out: Vector3): void; /** * 通过矩阵转换一个三维向量到另外一个三维向量。 * @param vector 源三维向量。 * @param transform 变换矩阵。 * @param result 输出三维向量。 */ static transformV3ToV3(vector: Vector3, transform: Matrix4x4, result: Vector3): void; /** * 通过矩阵转换一个三维向量到另外一个四维向量。 * @param vector 源三维向量。 * @param transform 变换矩阵。 * @param result 输出四维向量。 */ static transformV3ToV4(vector: Vector3, transform: Matrix4x4, result: Vector4): void; /** * 通过法线矩阵转换一个法线三维向量到另外一个三维向量。 * @param normal 源法线三维向量。 * @param transform 法线变换矩阵。 * @param result 输出法线三维向量。 */ static TransformNormal(normal: Vector3, transform: Matrix4x4, result: Vector3): void; /** * 通过矩阵转换一个三维向量到另外一个归一化的三维向量。 * @param vector 源三维向量。 * @param transform 变换矩阵。 * @param result 输出三维向量。 */ static transformCoordinate(coordinate: Vector3, transform: Matrix4x4, result: Vector3): void; /** * 求一个指定范围的向量 * @param value clamp向量 * @param min 最小 * @param max 最大 * @param out 输出向量 */ static Clamp(value: Vector3, min: Vector3, max: Vector3, out: Vector3): void; /** * 求两个三维向量的和。 * @param a left三维向量。 * @param b right三维向量。 * @param out 输出向量。 */ static add(a: Vector3, b: Vector3, out: Vector3): void; /** * 求两个三维向量的差。 * @param a left三维向量。 * @param b right三维向量。 * @param o out 输出向量。 */ static subtract(a: Vector3, b: Vector3, o: Vector3): void; /** * 求两个三维向量的叉乘。 * @param a left向量。 * @param b right向量。 * @param o 输出向量。 */ static cross(a: Vector3, b: Vector3, o: Vector3): void; /** * 求两个三维向量的点积。 * @param a left向量。 * @param b right向量。 * @return 点积。 */ static dot(a: Vector3, b: Vector3): number; /** * 判断两个三维向量是否相等。 * @param a 三维向量。 * @param b 三维向量。 * @return 是否相等。 */ static equals(a: Vector3, b: Vector3): boolean; /**三维向量元素数组*/ elements: Float32Array; /** * 获取X轴坐标。 * @return X轴坐标。 */ /** * 设置X轴坐标。 * @param value X轴坐标。 */ x: number; /** * 获取Y轴坐标。 * @return Y轴坐标。 */ /** * 设置Y轴坐标。 * @param value Y轴坐标。 */ y: number; /** * 获取Z轴坐标。 * @return Z轴坐标。 */ /** * 设置Z轴坐标。 * @param value Z轴坐标。 */ z: number; /** * 创建一个 Vector3 实例。 * @param x X轴坐标。 * @param y Y轴坐标。 * @param z Z轴坐标。 */ constructor(x?: number, y?: number, z?: number); /** * 从Array数组拷贝值。 * @param array 数组。 * @param offset 数组偏移。 */ fromArray(array: Array, offset?: number): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; toDefault(): void; } } declare module laya.d3.math { import IClone = laya.d3.core.IClone; /** * Vector4 类用于创建四维向量。 */ class Vector4 implements IClone { /**零向量,禁止修改*/ static ZERO: Vector4; static ONE: Vector4; static UnitX: Vector4; static UnitY: Vector4; static UnitZ: Vector4; static UnitW: Vector4; /**四维向量元素数组*/ elements: any; /** * 获取X轴坐标。 * @return X轴坐标。 */ /** * 设置X轴坐标。 * @param value X轴坐标。 */ x: number; /** * 获取Y轴坐标。 * @return Y轴坐标。 */ /** * 设置Y轴坐标。 * @param value Y轴坐标。 */ y: number; /** * 获取Z轴坐标。 * @return Z轴坐标。 */ /** * 设置Z轴坐标。 * @param value Z轴坐标。 */ z: number; /** * 获取W轴坐标。 * @return W轴坐标。 */ /** * 设置W轴坐标。 * @param value W轴坐标。 */ w: number; /** * 创建一个 Vector4 实例。 * @param x X轴坐标。 * @param y Y轴坐标。 * @param z Z轴坐标。 * @param w W轴坐标。 */ constructor(x?: number, y?: number, z?: number, w?: number); /** * 从Array数组拷贝值。 * @param array 数组。 * @param offset 数组偏移。 */ fromArray(array: Array, offset?: number): void; /** * 克隆。 * @param destObject 克隆源。 */ cloneTo(destObject: any): void; /** * 克隆。 * @return 克隆副本。 */ clone(): any; /** * 插值四维向量。 * @param a left向量。 * @param b right向量。 * @param t 插值比例。 * @param out 输出向量。 */ static lerp(a: Vector4, b: Vector4, t: number, out: Vector4): void; /** * 通过4x4矩阵把一个四维向量转换为另一个四维向量 * @param vector4 带转换四维向量。 * @param M4x4 4x4矩阵。 * @param out 转换后四维向量。 */ static transformByM4x4(vector4: Vector4, m4x4: Matrix4x4, out: Vector4): void; /** * 判断两个四维向量是否相等。 * @param a 四维向量。 * @param b 四维向量。 * @return 是否相等。 */ static equals(a: Vector4, b: Vector4): boolean; /** * 求四维向量的长度。 * @return 长度。 */ length(): number; /** * 求四维向量长度的平方。 * @return 长度的平方。 */ lengthSquared(): number; /** * 归一化四维向量。 * @param s 源四维向量。 * @param out 输出四维向量。 */ static normalize(s: Vector4, out: Vector4): void; /** * 求两个四维向量的和。 * @param a 四维向量。 * @param b 四维向量。 * @param out 输出向量。 */ static add(a: Vector4, b: Vector4, out: Vector4): void; /** * 求两个四维向量的差。 * @param a 四维向量。 * @param b 四维向量。 * @param out 输出向量。 */ static subtract(a: Vector4, b: Vector4, out: Vector4): void; /** * 计算两个四维向量的乘积。 * @param a 四维向量。 * @param b 四维向量。 * @param out 输出向量。 */ static multiply(a: Vector4, b: Vector4, out: Vector4): void; /** * 缩放四维向量。 * @param a 源四维向量。 * @param b 缩放值。 * @param out 输出四维向量。 */ static scale(a: Vector4, b: number, out: Vector4): void; /** * 求一个指定范围的四维向量 * @param value clamp向量 * @param min 最小 * @param max 最大 * @param out 输出向量 */ static Clamp(value: Vector4, min: Vector4, max: Vector4, out: Vector4): void; /** * 两个四维向量距离的平方。 * @param value1 向量1。 * @param value2 向量2。 * @return 距离的平方。 */ static distanceSquared(value1: Vector4, value2: Vector4): number; /** * 两个四维向量距离。 * @param value1 向量1。 * @param value2 向量2。 * @return 距离。 */ static distance(value1: Vector4, value2: Vector4): number; /** * 求两个四维向量的点积。 * @param a 向量。 * @param b 向量。 * @return 点积。 */ static dot(a: Vector4, b: Vector4): number; /** * 分别取两个四维向量x、y、z的最小值计算新的四维向量。 * @param a 四维向量。 * @param b 四维向量。 * @param out 结果三维向量。 */ static min(a: Vector4, b: Vector4, out: Vector4): void; /** * 分别取两个四维向量x、y、z的最大值计算新的四维向量。 * @param a 四维向量。 * @param b 四维向量。 * @param out 结果三维向量。 */ static max(a: Vector4, b: Vector4, out: Vector4): void; } } declare module laya.d3.math { /** * Viewport 类用于创建视口。 */ class Viewport { /**X轴坐标*/ x: number; /**Y轴坐标*/ y: number; /**宽度*/ width: number; /**高度*/ height: number; /**最小深度*/ minDepth: number; /**最大深度*/ maxDepth: number; /** * 创建一个 Viewport 实例。 * @param x x坐标。 * @param y y坐标。 * @param width 宽度。 * @param height 高度。 */ constructor(x: number, y: number, width: number, height: number); /** * 变换一个三维向量。 * @param source 源三维向量。 * @param matrix 变换矩阵。 * @param vector 输出三维向量。 */ project(source: Vector3, matrix: Matrix4x4, out: Vector3): void; /** * 反变换一个三维向量。 * @param source 源三维向量。 * @param matrix 变换矩阵。 * @param vector 输出三维向量。 */ unprojectFromMat(source: Vector3, matrix: Matrix4x4, out: Vector3): void; /** * 反变换一个三维向量。 * @param source 源三维向量。 * @param projection 透视投影矩阵。 * @param view 视图矩阵。 * @param world 世界矩阵,可设置为null。 * @param out 输出向量。 */ unprojectFromWVP(source: Vector3, projection: Matrix4x4, view: Matrix4x4, world: Matrix4x4, out: Vector3): void; } } declare module laya.d3.resource { import Size = laya.d3.utils.Size; import Resource = laya.resource.Resource; /** * BaseTexture 纹理的父类,抽象类,不允许实例。 */ class BaseTexture extends Resource { protected _type: number; protected _width: number; protected _height: number; protected _size: Size; protected _repeat: boolean; protected _mipmap: boolean; protected _minFifter: number; protected _magFifter: number; protected _format: number; protected _source: any; _conchTexture: any; /** * 获取宽度。 */ readonly width: number; /** * 获取高度。 */ readonly height: number; /** * 获取尺寸。 */ readonly size: Size; /** * 是否使用重复模式纹理寻址 */ /** * 是否使用重复模式纹理寻址 */ repeat: boolean; /** * 是否使用mipLevel */ /** * 是否使用mipLevel */ mipmap: boolean; /** * 缩小过滤器 */ /** * 缩小过滤器 */ minFifter: number; /** * 放大过滤器 */ /** * 放大过滤器 */ magFifter: number; /** * 纹理格式 */ readonly format: number; /** * 获取纹理资源。 */ readonly source: any; /** * 获取纹理资源。 */ readonly defaulteTexture: BaseTexture; /** * 创建一个 BaseTexture 实例。 */ constructor(); } } declare module laya.d3.resource { class DataTexture2D extends BaseTexture { simLodInfo: Float32Array; static simLodRect: Uint32Array; static create(data: ArrayBuffer, w: number, h: number, magfilter?: number, minfilter?: number, mipmap?: boolean): DataTexture2D; /** * 加载Texture2D。 * @param url Texture2D地址。 */ static load(url: string, w?: number, h?: number, magfilter?: number, minfilter?: number): DataTexture2D; /** * 获取文件路径全名。 */ readonly src: string; /** * 创建一个 Texture2D 实例。 */ constructor(); protected recreateResource(): void; /** *@private */ onAsynLoaded(url: string, data: any, params: Array): void; /** * 返回图片像素。 * @return 图片像素。 */ getPixels(): Uint8Array; protected disposeResource(): void; } } declare module laya.d3.resource.models { import IRenderable = laya.d3.core.render.IRenderable; import BoundBox = laya.d3.math.BoundBox; import BoundSphere = laya.d3.math.BoundSphere; import Resource = laya.resource.Resource; /** * BaseMesh 类用于创建网格,抽象类,不允许实例。 */ class BaseMesh extends Resource { protected _subMeshCount: number; protected _boundingBox: BoundBox; protected _boundingSphere: BoundSphere; protected _boundingBoxCorners: Array; _positions: Array; /** * 获取SubMesh的个数。 * @return SubMesh的个数。 */ readonly subMeshCount: number; /** * 获取AABB包围盒,禁止修改其数据。 * @return AABB包围盒。 */ readonly boundingBox: BoundBox; /** * 获取包围球,禁止修改其数据。 * @return 包围球。 */ readonly boundingSphere: BoundSphere; /** * 获取包围球顶点,禁止修改其数据。 * @return 包围球。 */ readonly boundingBoxCorners: Array; /** * 创建一个 BaseMesh 实例。 */ constructor(); /** * 获取网格顶点,请重载此方法。 * @return 网格顶点。 */ _getPositions(): Array; protected _generateBoundingObject(): void; /** * 获取渲染单元数量,请重载此方法。 * @return 渲染单元数量。 */ getRenderElementsCount(): number; /** * 获取渲染单元,请重载此方法。 * @param index 索引。 * @return 渲染单元。 */ getRenderElement(index: number): IRenderable; } } declare module laya.d3.resource.models { /** * Sphere 类用于创建方体。 */ class BoxMesh extends PrimitiveMesh { /** * 返回长度 * @return 长 */ /** * 设置长度(改变此属性会重新生成顶点和索引) * @param value 长度 */ long: number; /** * 返回宽度 * @return 宽 */ /** * 设置宽度(改变此属性会重新生成顶点和索引) * @param value 宽度 */ width: number; /** * 返回高度 * @return 高 */ /** * 设置高度(改变此属性会重新生成顶点和索引) * @param value 高度 */ height: number; /** * 创建一个方体模型 * @param radius 半径 * @param stacks 水平层数 * @param slices 垂直层数 */ constructor(long?: number, width?: number, height?: number); protected recreateResource(): void; } } declare module laya.d3.resource.models { /** * CapsuleMesh 类用于创建胶囊体。 */ class CapsuleMesh extends PrimitiveMesh { /** * 返回半径 * @return 半径 */ /** * 设置半径(改变此属性会重新生成顶点和索引) * @param value 半径 */ radius: number; /** * 返回高度 * @return 高度 */ /** * 设置高度(改变此属性会重新生成顶点和索引) * @param value 高度 */ height: number; /** * 获取高度分段 * @return 高度分段 */ /** * 设置高度分段(改变此属性会重新生成顶点和索引) * @param value高度分段 */ stacks: number; /** * 获取宽度分段 * @return 宽度分段 */ /** * 设置宽度分段(改变此属性会重新生成顶点和索引) * @param value 宽度分段 */ slices: number; /** * 创建一个胶囊体模型 * @param radius 半径 * @param height 高度 * @param stacks 水平层数,一般设为垂直层数的一半 * @param slices 垂直层数 */ constructor(radius?: number, height?: number, stacks?: number, slices?: number); protected recreateResource(): void; } } declare module laya.d3.resource.models { /** * CylinderMesh 类用于创建圆柱体。 */ class CylinderMesh extends PrimitiveMesh { /** * 返回半径 * @return 半径 */ /** * 设置半径(改变此属性会重新生成顶点和索引) * @param value 半径 */ radius: number; /** * 返回高度 * @return 高度 */ /** * 设置高度(改变此属性会重新生成顶点和索引) * @param value 高度 */ height: number; /** * 获取宽度分段 * @return 宽度分段 */ /** * 设置宽度分段(改变此属性会重新生成顶点和索引) * @param value 宽度分段 */ slices: number; /** * 创建一个圆柱体模型 * @param radius 半径 * @param height 高度 * @param slices 垂直层数 */ constructor(radius?: number, height?: number, slices?: number); protected recreateResource(): void; } } declare module laya.d3.resource.models { import IRenderable = laya.d3.core.render.IRenderable; import IndexBuffer3D = laya.d3.graphics.IndexBuffer3D; /** * Mesh 类用于创建文件网格数据模板。 */ class Mesh extends BaseMesh { /** * 加载网格模板。 * @param url 模板地址。 */ static load(url: string): Mesh; _vertexBuffers: Array; _indexBuffer: IndexBuffer3D; _boneNames: Array; _inverseBindPoses: Array; _skinnedDatas: Float32Array; /** * 获取材质队列的浅拷贝。 * @return 材质队列的浅拷贝。 */ readonly materials: Array; /** * 获取网格的全局默认绑定动作逆矩阵。 * @return 网格的全局默认绑定动作逆矩阵。 */ readonly InverseAbsoluteBindPoses: Array; /** * 创建一个 Mesh 实例,禁止使用。 * @param url 文件地址。 */ constructor(); /** * 获取网格顶点,并产生数据 * @return 网格顶点。 */ _getPositions(): Array; /** * 添加子网格(开发者禁止修改)。 * @param subMesh 子网格。 */ _setSubMeshes(subMeshes: Array): void; /** *@private */ onAsynLoaded(url: string, data: any, params: Array): void; /** * 获得子网格。 * @param index 子网格索引。 * @return 子网格。 */ getSubMesh(index: number): SubMesh; /** * 获得子网格数量。 * @return 子网格数量。 */ getSubMeshCount(): number; /** * @inheritDoc */ getRenderElementsCount(): number; /** * @inheritDoc */ getRenderElement(index: number): IRenderable; protected disposeResource(): void; } } declare module laya.d3.resource.models { /** * QuadMesh 类用于创建平面。 */ class PlaneMesh extends PrimitiveMesh { /** * 返回长度 * @return 长 */ /** * 设置长度(改变此属性会重新生成顶点和索引) * @param value 长度 */ long: number; /** * 返回宽度 * @return 宽 */ /** * 设置宽度(改变此属性会重新生成顶点和索引) * @param value 宽度 */ width: number; /** * 获取长度分段 * @return 长度分段 */ /** * 设置长度分段(改变此属性会重新生成顶点和索引) * @param value长度分段 */ stacks: number; /** * 获取宽度分段 * @return 宽度分段 */ /** * 设置宽度分段(改变此属性会重新生成顶点和索引) * @param value 宽度分段 */ slices: number; /** * 创建一个平面模型 * @param long 长 * @param width 宽 */ constructor(long?: number, width?: number, stacks?: number, slices?: number); protected recreateResource(): void; } } declare module laya.d3.resource.models { import IRenderable = laya.d3.core.render.IRenderable; import RenderElement = laya.d3.core.render.RenderElement; import RenderState = laya.d3.core.render.RenderState; import IndexBuffer3D = laya.d3.graphics.IndexBuffer3D; import VertexBuffer3D = laya.d3.graphics.VertexBuffer3D; /** * @private * PrimitiveMesh 类用于创建基本网格的父类。 */ class PrimitiveMesh extends BaseMesh implements IRenderable { protected _numberVertices: number; protected _numberIndices: number; protected _vertexBuffer: VertexBuffer3D; protected _indexBuffer: IndexBuffer3D; readonly _vertexBufferCount: number; readonly triangleCount: number; _getVertexBuffer(index?: number): VertexBuffer3D; _getVertexBuffers(): Array; _getIndexBuffer(): IndexBuffer3D; constructor(); /** * 获取网格顶点 * @return 网格顶点。 */ _getPositions(): Array; getRenderElement(index: number): IRenderable; getRenderElementsCount(): number; protected disposeResource(): void; _beforeRender(state: RenderState): boolean; _render(state: RenderState): void; /**NATIVE*/ _renderRuntime(conchGraphics3D: any, renderElement: RenderElement, state: RenderState): void; } } declare module laya.d3.resource.models { /** * QuadMesh 类用于创建四边形。 */ class QuadMesh extends PrimitiveMesh { /** * 返回长度 * @return 长 */ /** * 设置长度(改变此属性会重新生成顶点和索引) * @param value 长度 */ long: number; /** * 返回宽度 * @return 宽 */ /** * 设置宽度(改变此属性会重新生成顶点和索引) * @param value 宽度 */ width: number; /** * 创建一个四边形模型 * @param long 长 * @param width 宽 */ constructor(long?: number, width?: number); protected recreateResource(): void; } } declare module laya.d3.resource.models { import BaseCamera = laya.d3.core.BaseCamera; import RenderState = laya.d3.core.render.RenderState; import IndexBuffer3D = laya.d3.graphics.IndexBuffer3D; import VertexBuffer3D = laya.d3.graphics.VertexBuffer3D; import BaseTexture = laya.d3.resource.BaseTexture; import Shader3D = laya.d3.shader.Shader3D; import ShaderCompile3D = laya.d3.shader.ShaderCompile3D; import ValusArray = laya.d3.shader.ValusArray; /** * Sky 类用于创建天空的父类,抽象类不允许实例。 */ class Sky { static MVPMATRIX: number; static INTENSITY: number; static ALPHABLENDING: number; static DIFFUSETEXTURE: number; protected __ownerCamera: BaseCamera; protected _alphaBlending: number; protected _colorIntensity: number; protected _vertexBuffer: VertexBuffer3D; protected _indexBuffer: IndexBuffer3D; protected _sharderNameID: number; protected _shader: Shader3D; protected _shaderValue: ValusArray; protected _shaderCompile: ShaderCompile3D; protected _environmentDiffuse: BaseTexture; protected _environmentSpecular: BaseTexture; _conchSky: any; /** * @private */ _ownerCamera: BaseCamera; /** * 获取透明混合度。 * @return 透明混合度。 */ /** * 设置透明混合度。 * @param value 透明混合度。 */ alphaBlending: number; /** * 获取颜色强度。 * @return 颜色强度。 */ /** * 设置颜色强度。 * @param value 颜色强度。 */ colorIntensity: number; /** * 获取环境漫反射贴图。 * @return 环境漫反射贴图。 */ /** * 设置环境漫反射贴图。 * @param value 环境漫反射贴图。 */ environmentDiffuse: BaseTexture; /** * 获取环境高光贴图。 * @return 环境高光贴图。 */ /** * 设置环境高光贴图。 * @param value 环境高光贴图。 */ environmentSpecular: BaseTexture; envDiffuseSHRed: Float32Array; envDiffuseSHGreen: Float32Array; envDiffuseSHBlue: Float32Array; /** * * 创建一个 Sky 实例。 */ constructor(); /** * @private */ _render(state: RenderState): void; /** * 销毁天空。 */ destroy(): void; } } declare module laya.d3.resource.models { import RenderState = laya.d3.core.render.RenderState; import TextureCube = laya.d3.resource.TextureCube; import Shader3D = laya.d3.shader.Shader3D; /** * Sky 类用于创建天空盒。 */ class SkyBox extends Sky { /** * 获取天空立方体纹理。 * @return 天空立方体纹理。 */ /** * 设置天空立方体纹理。 * @param value 天空立方体纹理。 */ textureCube: TextureCube; /** * 创建一个 SkyBox 实例。 */ constructor(); protected _getShader(state: RenderState): Shader3D; protected createResource(): void; protected loadShaderParams(): void; _render(state: RenderState): void; /** * @inheritDoc */ destroy(): void; } } declare module laya.d3.resource.models { import RenderState = laya.d3.core.render.RenderState; import Texture2D = laya.d3.resource.Texture2D; import Shader3D = laya.d3.shader.Shader3D; /** * Sky 类用于创建天空盒。 */ class SkyDome extends Sky { /** * 获取天空立方体纹理。 * @return 天空立方体纹理。 */ /** * 设置天空纹理。 * @param value 天空纹理。 */ texture: Texture2D; /** * 创建一个 SkyBox 实例。 */ constructor(); protected _getShader(state: RenderState): Shader3D; protected recreateResource(): void; protected loadShaderParams(): void; _render(state: RenderState): void; onEnvDescLoaded(envInfoFile: string): void; loadEnvInfo(envInfo: string): void; /** * @inheritDoc */ destroy(): void; } } declare module laya.d3.resource.models { /** * Sphere 类用于创建球体。 */ class SphereMesh extends PrimitiveMesh { /** * 返回半径 * @return 半径 */ /** * 设置半径(改变此属性会重新生成顶点和索引) * @param value 半径 */ radius: number; /** * 获取宽度分段 * @return 宽度分段 */ /** * 设置宽度分段(改变此属性会重新生成顶点和索引) * @param value 宽度分段 */ slices: number; /** * 获取高度分段 * @return 高度分段 */ /** * 设置高度分段(改变此属性会重新生成顶点和索引) * @param value高度分段 */ stacks: number; /** * 创建一个球体模型 * @param radius 半径 * @param stacks 水平层数 * @param slices 垂直层数 */ constructor(radius?: number, stacks?: number, slices?: number); protected recreateResource(): void; } } declare module laya.d3.resource.models { import MeshSprite3D = laya.d3.core.MeshSprite3D; import Transform3D = laya.d3.core.Transform3D; import IRenderable = laya.d3.core.render.IRenderable; import RenderElement = laya.d3.core.render.RenderElement; import RenderState = laya.d3.core.render.RenderState; import IndexBuffer3D = laya.d3.graphics.IndexBuffer3D; import VertexBuffer3D = laya.d3.graphics.VertexBuffer3D; import IDispose = laya.resource.IDispose; /** * SubMesh 类用于创建子网格数据模板。 */ class SubMesh implements IRenderable, IDispose { _boneIndicesList: Array; _subIndexBufferStart: Array; _subIndexBufferCount: Array; _skinAnimationDatas: Array; _bufferUsage: any; _indexInMesh: number; _vertexBuffer: VertexBuffer3D; _vertexStart: number; _vertexCount: number; _indexBuffer: IndexBuffer3D; _indexStart: number; _indexCount: number; _indices: Uint16Array; /** * @private */ readonly _vertexBufferCount: number; /** * @private */ readonly triangleCount: number; /** * 创建一个 SubMesh 实例。 * @param mesh 网格数据模板。 */ constructor(mesh: Mesh); /** * @private */ _getVertexBuffer(index?: number): VertexBuffer3D; /** * @private */ _getIndexBuffer(): IndexBuffer3D; /** * @private */ _getStaticBatchBakedVertexs(batchOwnerTransform: Transform3D, owner: MeshSprite3D): Float32Array; /** * @private */ _getVertexBuffers(): Array; /** * @private */ _beforeRender(state: RenderState): boolean; /** * @private * 渲染。 * @param state 渲染状态。 */ _render(state: RenderState): void; /** * @private */ getIndices(): Uint16Array; /** *

    彻底清理资源。

    *

    注意:会强制解锁清理。

    */ dispose(): void; /**NATIVE*/ _renderRuntime(conchGraphics3D: any, renderElement: RenderElement, state: RenderState): void; } } declare module laya.d3.resource { /** * RenderTarget 类用于创建渲染目标。 */ class RenderTexture extends BaseTexture { /** * 获取表面格式。 *@return 表面格式。 */ readonly surfaceFormat: number; /** * 获取表面类型。 *@return 表面类型。 */ readonly surfaceType: number; /** * 获取深度格式。 *@return 深度格式。 */ readonly depthStencilFormat: number; readonly frameBuffer: any; readonly depthStencilBuffer: any; /** * 获取RenderTarget数据源,如果alreadyResolved等于false,则返回null。 * @return RenderTarget数据源。 */ readonly source: any; /** * 创建一个 RenderTarget 实例。 * @param width 宽度。 * @param height 高度。 * @param mipMap 是否生成mipMap。 * @param surfaceFormat 表面格式。 * @param surfaceType 表面类型。 * @param depthFormat 深度格式。 */ constructor(width: number, height: number, surfaceFormat?: number, surfaceType?: number, depthStencilFormat?: number, mipMap?: boolean, repeat?: boolean, minFifter?: number, magFifter?: number); protected recreateResource(): void; /** * 开始绑定。 */ start(): void; /** * 结束绑定。 */ end(): void; /** * 获得像素数据。 * @param x X像素坐标。 * @param y Y像素坐标。 * @param width 宽度。 * @param height 高度。 * @return 像素数据。 */ getData(x: number, y: number, width: number, height: number): Uint8Array; protected disposeResource(): void; } } declare module laya.d3.resource { import Vector4 = laya.d3.math.Vector4; /** * SolidColorTexture2D 二维纯色纹理。 */ class SolidColorTexture2D extends BaseTexture { /**洋红色纯色纹理。*/ static magentaTexture: SolidColorTexture2D; /**灰色纯色纹理。*/ static grayTexture: SolidColorTexture2D; /** * 创建一个 SolidColorTexture2D 实例。 */ constructor(color: Vector4); protected recreateResource(): void; protected disposeResource(): void; } } declare module laya.d3.resource { import Vector4 = laya.d3.math.Vector4; class SolidColorTextureCube extends BaseTexture { /**洋红色纯色纹理。*/ static magentaTexture: SolidColorTextureCube; /**灰色纯色纹理。*/ static grayTexture: SolidColorTextureCube; constructor(color: Vector4); protected recreateResource(): void; protected disposeResource(): void; } } declare module laya.d3.resource.tempelet { import GeometryFilter = laya.d3.core.GeometryFilter; import Glitter = laya.d3.core.glitter.Glitter; import IRenderable = laya.d3.core.render.IRenderable; import RenderElement = laya.d3.core.render.RenderElement; import RenderState = laya.d3.core.render.RenderState; import IndexBuffer3D = laya.d3.graphics.IndexBuffer3D; import VertexBuffer3D = laya.d3.graphics.VertexBuffer3D; import BoundBox = laya.d3.math.BoundBox; import BoundSphere = laya.d3.math.BoundSphere; import Vector3 = laya.d3.math.Vector3; /** * @private * GlitterTemplet 类用于创建闪光数据模板。 */ class GlitterTemplet extends GeometryFilter implements IRenderable { _currentTime: number; /** 声明周期。 */ lifeTime: number; /** 最小分段距离。 */ minSegmentDistance: number; /** 最小插值距离。 */ minInterpDistance: number; /** 最大插值数量。 */ maxSlerpCount: number; /** 最大段数。 */ _maxSegments: number; /**获取最大分段数。*/ /**设置最大分段数,注意:谨慎修改此属性,有性能损耗。*/ maxSegments: number; readonly _vertexBufferCount: number; readonly triangleCount: number; _getVertexBuffer(index?: number): VertexBuffer3D; _getIndexBuffer(): IndexBuffer3D; /** * @inheritDoc */ readonly _originalBoundingSphere: BoundSphere; /** * @inheritDoc */ readonly _originalBoundingBox: BoundBox; constructor(owner: Glitter); _onActiveHierarchyChanged(active: boolean): void; /** * @private * 更新闪光。 * @param elapsedTime 间隔时间 */ _update(elapsedTime: number): void; _beforeRender(state: RenderState): boolean; /** * @private * 渲染闪光。 * @param state 相关渲染状态 */ _render(state: RenderState): void; /** * 通过位置添加刀光。 * @param position0 位置0。 * @param position1 位置1。 */ addVertexPosition(position0: Vector3, position1: Vector3): void; /** * 通过位置和速度添加刀光。 * @param position0 位置0。 * @param velocity0 速度0。 * @param position1 位置1。 * @param velocity1 速度1。 */ addVertexPositionVelocity(position0: Vector3, velocity0: Vector3, position1: Vector3, velocity1: Vector3): void; _destroy(): void; /** * @private */ _getVertexBuffers(): Array; _renderRuntime(conchGraphics3D: any, renderElement: RenderElement, state: RenderState): void; } } declare module laya.d3.resource { /** * Texture2D 二维纹理。 */ class Texture2D extends BaseTexture { /** * 加载Texture2D。 * @param url Texture2D地址。 */ static load(url: string): Texture2D; readonly _src: string; readonly src: string; /** * 创建一个 Texture2D 实例。 */ constructor(canRead?: boolean, reapeat?: boolean, format?: number, mipmap?: boolean); protected recreateResource(): void; /** *@private */ onAsynLoaded(url: string, data: any, params: Array): void; /** * 返回图片像素。 * @return 图片像素。 */ getPixels(): Uint8Array; protected disposeResource(): void; } } declare module laya.d3.resource { class TextureCube extends BaseTexture { /** * 加载TextureCube。 * @param url TextureCube地址。 */ static load(url: string): TextureCube; /** * @inheritDoc */ readonly defaulteTexture: BaseTexture; constructor(); protected recreateResource(): void; /** * @private */ onAsynLoaded(url: string, data: any, params: Array): void; protected disposeResource(): void; } } declare module laya.d3.shader { import BaseCamera = laya.d3.core.BaseCamera; import Sprite3D = laya.d3.core.Sprite3D; import BaseMaterial = laya.d3.core.material.BaseMaterial; import RenderElement = laya.d3.core.render.RenderElement; import Scene = laya.d3.core.scene.Scene; import VertexBuffer3D = laya.d3.graphics.VertexBuffer3D; import StringKey = laya.utils.StringKey; import BaseShader = laya.webgl.shader.BaseShader; class Shader3D extends BaseShader { /**shader变量提交周期,逐渲染单元。*/ static PERIOD_RENDERELEMENT: number; /**shader变量提交周期,逐材质。*/ static PERIOD_MATERIAL: number; /**shader变量提交周期,逐精灵和相机,注:因为精灵包含MVP矩阵,为复合属性,所以摄像机发生变化时也应提交。*/ static PERIOD_SPRITE: number; /**shader变量提交周期,逐相机。*/ static PERIOD_CAMERA: number; /**shader变量提交周期,逐场景。*/ static PERIOD_SCENE: number; protected static shaderParamsMap: any; static nameKey: StringKey; static create(vs: string, ps: string, attributeMap: any, sceneUniformMap: any, cameraUniformMap: any, spriteUniformMap: any, materialUniformMap: any, renderElementUniformMap: any): Shader3D; static addInclude(fileName: string, txt: string): void; _vshader: any; _pshader: any; _program: any; _attributeParams: Array; _uniformParams: Array; _attributeParamsMap: Array; _sceneUniformParamsMap: Array; _cameraUniformParamsMap: Array; _spriteUniformParamsMap: Array; _materialUniformParamsMap: Array; _renderElementUniformParamsMap: Array; _id: number; _uploadLoopCount: number; _uploadRenderElement: RenderElement; _uploadMaterial: BaseMaterial; _uploadSprite3D: Sprite3D; _uploadCamera: BaseCamera; _uploadScene: Scene; _uploadVertexBuffer: any; /** * 根据vs和ps信息生成shader对象 * @param vs * @param ps * @param name: * @param nameMap 帮助里要详细解释为什么需要nameMap */ constructor(vs: string, ps: string, attributeMap: any, sceneUniformMap: any, cameraUniformMap: any, spriteUniformMap: any, materialUniformMap: any, renderElementUniformMap: any); protected recreateResource(): void; protected disposeResource(): void; bind(): boolean; /** * 按数组的定义提交 * @param shaderValue 数组格式[name,value,...] */ uploadAttributes(attributeShaderValue: Array, _bufferUsage: any): void; /** * 按数组的定义提交 * @param shaderValue 数组格式[name,value,...] */ uploadAttributesX(attributeShaderValue: Array, vb: VertexBuffer3D): void; /** * 按数组的定义提交 * @param shaderValue 数组格式[name,value,...] */ uploadSceneUniforms(shaderValue: Array): void; /** * 按数组的定义提交 * @param shaderValue 数组格式[name,value,...] */ uploadCameraUniforms(shaderValue: Array): void; /** * 按数组的定义提交 * @param shaderValue 数组格式[name,value,...] */ uploadSpriteUniforms(shaderValue: Array): void; /** * 按数组的定义提交 * @param shaderValue 数组格式[name,value,...] */ uploadMaterialUniforms(shaderValue: Array): void; /** * 按数组的定义提交 * @param shaderValue 数组格式[name,value,...] */ uploadRenderElementUniforms(shaderValue: Array): void; } } declare module laya.d3.shader { import ShaderCompile = laya.webgl.utils.ShaderCompile; /** * @private * ShaderCompile 类用于创建Shader编译类型。 */ class ShaderCompile3D extends ShaderCompile { static _preCompileShader: any; /**是否开启调试模式。 */ static debugMode: boolean; static SHADERDEFINE_HIGHPRECISION: number; static SHADERDEFINE_FOG: number; static SHADERDEFINE_DIRECTIONLIGHT: number; static SHADERDEFINE_POINTLIGHT: number; static SHADERDEFINE_SPOTLIGHT: number; static SHADERDEFINE_UV0: number; static SHADERDEFINE_COLOR: number; static SHADERDEFINE_UV1: number; static SAHDERDEFINE_DEPTHFOG: number; /** * @private */ static _globalRegDefine(name: string, value: number): void; /** * 添加预编译shader文件,主要是处理宏定义 * @param nameID,一般是特殊宏+shaderNameID*0.0002组成的一个浮点数当做唯一标识 * @param vs * @param ps */ static add(nameID: number, vs: string, ps: string, attributeMap: any, uniformMap: any): ShaderCompile3D; /** * 获取ShaderCompile3D。 * @param name * @return ShaderCompile3D。 */ static get(name: string): ShaderCompile3D; sharders: Array; _materialInt2name: Array; _materialName2Int: any; _conchShader: any; /** * @private */ constructor(name: number, vs: string, ps: string, attributeMap: any, uniformMap: any, includeFiles: any); /** * 根据宏动态生成shader文件,支持#include?COLOR_FILTER "parts/ColorFilter_ps_logic.glsl";条件嵌入文件 * @param name * @param vs * @param ps * @param define 宏定义,格式: * @return */ withCompile(publicDefine: number, spriteDefine: number, materialDefine: number): Shader3D; /** * 通过宏定义预编译shader。 * @param spriteIntToNameDic 精灵宏定义数组。 * @param publicDefine 公共宏定义值。 * @param spriteDefine 精灵宏定义值。 * @param materialDefine 材质宏定义值。 */ precompileShaderWithShaderDefine(publicDefine: number, spriteDefine: number, materialDefine: number): void; /** * 注册材质宏定义。 * @param name 宏定义名称。 * @return */ addMaterialDefines(shaderdefines: ShaderDefines): void; /** * 注册精灵宏定义。 * @param name 宏定义名称。 * @return */ addSpriteDefines(shaderdefines: ShaderDefines): void; /** * 通过名称获取宏定义值。 * @param name 名称。 * @return 宏定义值。 */ getMaterialDefineByName(name: string): number; /** * 注册材质宏定义。 * @param name 宏定义名称。 * @return */ registerMaterialDefine(name: string): number; /** * 注册精灵宏定义。 * @param name 宏定义名称。 * @return */ registerSpriteDefine(name: string): number; } } declare module laya.d3.shader { /** * @private */ class ShaderDefines { defineCounter: number; defines: Array; /** * @private */ constructor(shaderdefines?: ShaderDefines); /** * @private */ registerDefine(name: string): number; } } declare module laya.d3.shader { /** * @private * ShaderInit 类用于初始化内置Shader。 */ class ShaderInit3D { /** * 创建一个 ShaderInit 实例。 */ constructor(); /** * @private */ static __init__(): void; } } declare module laya.d3.shader { /** * @private * Shader3D 主要用数组的方式保存shader变量定义,后期合并ShaderValue不使用for in,性能较高。 */ class ValusArray { constructor(); setValue(name: number, value: any): void; readonly data: Array; } } declare module laya.d3.shadowMap { import BaseCamera = laya.d3.core.BaseCamera; import Camera = laya.d3.core.Camera; import Scene = laya.d3.core.scene.Scene; import BoundFrustum = laya.d3.math.BoundFrustum; import Matrix4x4 = laya.d3.math.Matrix4x4; import Vector3 = laya.d3.math.Vector3; import RenderTexture = laya.d3.resource.RenderTexture; /** * ... * @author ... */ class ParallelSplitShadowMap { static SHADERDEFINE_RECEIVE_SHADOW: number; static SHADERDEFINE_CAST_SHADOW: number; static SHADERDEFINE_SHADOW_PSSM1: number; static SHADERDEFINE_SHADOW_PSSM2: number; static SHADERDEFINE_SHADOW_PSSM3: number; static SHADERDEFINE_SHADOW_PCF_NO: number; static SHADERDEFINE_SHADOW_PCF1: number; static SHADERDEFINE_SHADOW_PCF2: number; static SHADERDEFINE_SHADOW_PCF3: number; static MAX_PSSM_COUNT: number; _lightCulling: Array; _renderTarget: Array; _lightVPMatrix: Array; _shadowQuenes: Array; _boundingBox: Array; constructor(); setInfo(scene: Scene, maxDistance: number, globalParallelDir: Vector3, shadowMapTextureSize: number, numberOfPSSM: number, PCFType: number): void; setPCFType(PCFtype: number): void; getPCFType(): number; setFarDistance(value: number): void; getFarDistance(): number; PSSMNum: number; _setGlobalParallelLightDir(dir: Vector3): void; getGlobalParallelLightDir(): Vector3; getCurrentPSSM(): number; getLightCamera(index: number): Camera; /** * @private */ endSampler(sceneCamera: BaseCamera): void; /** * @private */ _calcAllLightCameraInfo(sceneCamera: BaseCamera): void; /** * @private */ _calcBoundingBox(fieldOfView: number, aspectRatio: number): void; calcSplitFrustum(sceneCamera: BaseCamera): void; /** * 计算两个矩阵的乘法 * @param left left矩阵 * @param right right矩阵 * @param out 输出矩阵 */ static multiplyMatrixOutFloat32Array(left: Matrix4x4, right: Matrix4x4, out: Float32Array): void; getLightFrustumCulling(currentPSSM: number): BoundFrustum; getSplitFrustumCulling(): BoundFrustum; getSplitDistance(index: number): number; setShadowMapTextureSize(size: number): void; getShadowMapTextureSize(): number; beginRenderTarget(index: number): void; endRenderTarget(index: number): void; getRenderTarget(index: number): RenderTexture; disposeAllRenderTarget(): void; } } declare module laya.d3.terrain { import ComponentNode = laya.d3.core.ComponentNode; import Sprite3D = laya.d3.core.Sprite3D; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * Terrain 类用于创建地块。 */ class Terrain extends Sprite3D { static RENDER_LINE_MODEL: boolean; static LOD_TOLERANCE_VALUE: number; static LOD_DISTANCE_FACTOR: number; static __VECTOR3__: Vector3; terrainRes: TerrainRes; /** * 加载网格模板,注意:不缓存。 * @param url 模板地址。 */ static load(url: string): Terrain; /** * 创建一个 MeshSprite3D 实例。 * @param mesh 网格,同时会加载网格所用默认材质。 * @param name 名字。 */ constructor(terrainRes?: TerrainRes); protected _parseCustomProps(rootNode: ComponentNode, innerResouMap: any, customProps: any, json: any): void; setLightmapIndex(value: number): void; setLightmapScaleOffset(value: Vector4): void; disableLight(): void; buildTerrain(terrainRes: TerrainRes): void; /** * 获取地形X轴长度。 * @return 地形X轴长度。 */ width(): number; /** * 获取地形Z轴长度。 * @return 地形Z轴长度。 */ depth(): number; /** * 获取地形高度。 * @param x X轴坐标。 * @param z Z轴坐标。 */ getHeightXZ(x: number, z: number): number; } } declare module laya.d3.terrain { import RenderableSprite3D = laya.d3.core.RenderableSprite3D; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; import Mesh = laya.d3.resource.models.Mesh; /** * TerrainChunk 类用于创建地块。 */ class TerrainChunk extends RenderableSprite3D { /** * 加载网格模板,注意:不缓存。 * @param url 模板地址。 */ static load(url: string): TerrainChunk; /** * 获取地形过滤器。 * @return 地形过滤器。 */ readonly terrainFilter: TerrainFilter; /** * 获取地形渲染器。 * @return 地形渲染器。 */ readonly terrainRender: TerrainRender; /** * 创建一个 MeshSprite3D 实例。 * @param mesh 网格,同时会加载网格所用默认材质。 * @param name 名字。 */ constructor(chunkOffsetX: number, chunkOffsetZ: number, girdSize: number, terrainHeightData: Float32Array, heightDataWidth: number, heightDataHeight: number, cameraCoordinateInverse: boolean, name?: string); buildRenderElementAndMaterial(detailNum: number, normalMap: string, alphaMapUrl: string, detailUrl1: string, detailUrl2: string, detailUrl3: string, detailUrl4: string, ambientColor: Vector3, diffuseColor: Vector3, specularColor: Vector4, sx1?: number, sy1?: number, sx2?: number, sy2?: number, sx3?: number, sy3?: number, sx4?: number, sy4?: number): void; /** * @private */ createConchModel(): any; protected _clearSelfRenderObjects(): void; protected _addSelfRenderObjects(): void; /** * @private */ _applyMeshMaterials(mesh: Mesh): void; cloneTo(destObject: any): void; destroy(destroyChild?: boolean): void; } } declare module laya.d3.terrain { import Camera = laya.d3.core.Camera; import GeometryFilter = laya.d3.core.GeometryFilter; import IRenderable = laya.d3.core.render.IRenderable; import RenderElement = laya.d3.core.render.RenderElement; import RenderState = laya.d3.core.render.RenderState; import IndexBuffer3D = laya.d3.graphics.IndexBuffer3D; import VertexBuffer3D = laya.d3.graphics.VertexBuffer3D; import BoundBox = laya.d3.math.BoundBox; import BoundSphere = laya.d3.math.BoundSphere; import Matrix4x4 = laya.d3.math.Matrix4x4; import Vector3 = laya.d3.math.Vector3; /** * TerrainFilter 类用于创建TerrainFilter过滤器。 */ class TerrainFilter extends GeometryFilter implements IRenderable { static _TEMP_ARRAY_BUFFER: Uint32Array; _owner: TerrainChunk; _gridSize: number; memorySize: number; protected _numberVertices: number; protected _maxNumberIndices: number; protected _currentNumberIndices: number; protected _numberTriangle: number; protected _vertexBuffer: VertexBuffer3D; protected _indexBuffer: IndexBuffer3D; protected _boundingSphere: BoundSphere; protected _boundingBox: BoundBox; protected _indexArrayBuffer: Uint16Array; _boundingBoxCorners: Array; /** * 创建一个新的 MeshFilter 实例。 * @param owner 所属网格精灵。 */ constructor(owner: TerrainChunk, chunkOffsetX: number, chunkOffsetZ: number, gridSize: number, terrainHeightData: Float32Array, heightDataWidth: number, heightDataHeight: number, cameraCoordinateInverse: boolean); /** * @inheritDoc */ readonly _originalBoundingSphere: BoundSphere; /** * @inheritDoc */ readonly _originalBoundingBox: BoundBox; /** * @inheritDoc */ _destroy(): void; protected recreateResource(): void; protected assembleIndexInit(): void; protected isNeedAssemble(camera: Camera, cameraPostion: Vector3): number; protected assembleIndex(camera: Camera, cameraPostion: Vector3): boolean; calcOriginalBoudingBoxAndSphere(): void; calcLeafBoudingBox(worldMatrix: Matrix4x4): void; calcLeafBoudingSphere(worldMatrix: Matrix4x4, maxScale: number): void; readonly _vertexBufferCount: number; readonly triangleCount: number; _getVertexBuffer(index?: number): VertexBuffer3D; _getIndexBuffer(): IndexBuffer3D; _beforeRender(state: RenderState): boolean; /** * @private */ _getVertexBuffers(): Array; _render(state: RenderState): void; _renderRuntime(conchGraphics3D: any, renderElement: RenderElement, state: RenderState): void; } } declare module laya.d3.terrain { import Resource = laya.resource.Resource; /** * TerrainHeightData 类用于描述地形高度信息。 */ class TerrainHeightData extends Resource { _terrainHeightData: Float32Array; _width: number; _height: number; _bitType: number; _value: number; /** * 加载地形高度模板,注意:不缓存。 * @param url 模板地址。 * @param width 高度图的宽。 * @param height 高度图的高。 */ static load(url: string, widht: number, height: number, bitType: number, value: number): TerrainHeightData; /** * 创建一个 TerrainHeightData 实例。 */ constructor(); /** * 异步回调 */ onAsynLoaded(url: string, data: any, params: Array): void; } } declare module laya.d3.terrain { import BoundBox = laya.d3.math.BoundBox; import BoundSphere = laya.d3.math.BoundSphere; import Matrix4x4 = laya.d3.math.Matrix4x4; import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; /** * TerrainLeaf Terrain的叶子节点 */ class TerrainLeaf { static CHUNK_GRID_NUM: number; static LEAF_GRID_NUM: number; static LEAF_PLANE_VERTEXT_COUNT: number; static LEAF_SKIRT_VERTEXT_COUNT: number; static LEAF_VERTEXT_COUNT: number; static LEAF_PLANE_MAX_INDEX_COUNT: number; static LEAF_SKIRT_MAX_INDEX_COUNT: number; static LEAF_MAX_INDEX_COUNT: number; static __ADAPT_MATRIX__: Matrix4x4; static __ADAPT_MATRIX_INV__: Matrix4x4; static __VECTOR3__: Vector3; _boundingSphere: BoundSphere; _boundingBox: BoundBox; _sizeOfY: Vector2; _currentLODLevel: number; static __init__(): void; static getPlaneLODIndex(leafIndex: number, LODLevel: number): Uint16Array; static getSkirtLODIndex(leafIndex: number, LODLevel: number): Uint16Array; static getHeightFromTerrainHeightData(x: number, z: number, terrainHeightData: Float32Array, heighDataWidth: number, heightDataHeight: number): number; /** * 创建一个新的 TerrainLeaf 实例。 * @param owner 地形的叶子。 */ constructor(); calcVertextNorml(x: number, z: number, terrainHeightData: Float32Array, heighDataWidth: number, heightDataHeight: number, normal: Vector3): void; calcVertextNormlUV(x: number, z: number, terrainWidth: number, terrainHeight: number, normal: Vector3): void; calcVertextBuffer(offsetChunkX: number, offsetChunkZ: number, beginX: number, beginZ: number, girdSize: number, vertextBuffer: Float32Array, offset: number, strideSize: number, terrainHeightData: Float32Array, heighDataWidth: number, heightDataHeight: number, cameraCoordinateInverse: boolean): void; calcSkirtVertextBuffer(offsetChunkX: number, offsetChunkZ: number, beginX: number, beginZ: number, girdSize: number, vertextBuffer: Float32Array, offset: number, strideSize: number, terrainHeightData: Float32Array, heighDataWidth: number, heightDataHeight: number): void; calcOriginalBoudingBoxAndSphere(): void; calcLeafBoudingBox(worldMatrix: Matrix4x4): void; calcLeafBoudingSphere(worldMatrix: Matrix4x4, maxScale: number): void; calcLODErrors(terrainHeightData: Float32Array, heighDataWidth: number, heightDataHeight: number): void; determineLod(eyePos: Vector3, perspectiveFactor: number, tolerance: number, tolerAndPerspectiveChanged: boolean): number; } } declare module laya.d3.terrain { import BaseRender = laya.d3.core.render.BaseRender; import Matrix4x4 = laya.d3.math.Matrix4x4; /** * MeshRender 类用于网格渲染器。 */ class TerrainRender extends BaseRender { /** * 创建一个新的 MeshRender 实例。 */ constructor(owner: TerrainChunk); protected _calculateBoundingSphere(): void; protected _calculateBoundingBox(): void; /** * @private */ _renderUpdate(projectionView: Matrix4x4): boolean; /** * @private */ _destroy(): void; } } declare module laya.d3.terrain { import MaterialInfo = laya.d3.terrain.unit.MaterialInfo; import Resource = laya.resource.Resource; /** * TerrainRes 类用于描述地形信息。 */ class TerrainRes extends Resource { _version: number; _cameraCoordinateInverse: boolean; _gridSize: number; _chunkNumX: number; _chunkNumZ: number; _heightDataX: number; _heightDataZ: number; _heightDataBitType: number; _heightDataValue: number; _heightDataUrl: string; _detailTextureInfos: Array; _chunkInfos: Array; _heightData: TerrainHeightData; _materialInfo: MaterialInfo; _alphaMaps: Array; _normalMaps: Array; /** * 加载地形模板,注意:不缓存。 * @param url 模板地址。 */ static load(url: string): TerrainRes; /** * 创建一个 TerrainHeightData 实例。 */ constructor(); parseData(data: any): boolean; onLoadTerrainComplete(heightData: TerrainHeightData): void; /** * 异步回调 */ onAsynLoaded(url: string, data: any, params: Array): void; } } declare module laya.d3.terrain.unit { /** * DetailTextureInfo 类用于描述地形细节纹理。 */ class ChunkInfo { alphaMap: Array; detailID: Array; normalMap: string; constructor(); } } declare module laya.d3.terrain.unit { import Vector2 = laya.d3.math.Vector2; /** * DetailTextureInfo 类用于描述地形细节纹理。 */ class DetailTextureInfo { diffuseTexture: string; normalTexture: string; scale: Vector2; offset: Vector2; constructor(); } } declare module laya.d3.terrain.unit { import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * MaterialInfo 类用于描述地形材质信息。 */ class MaterialInfo { ambientColor: Vector3; diffuseColor: Vector3; specularColor: Vector4; constructor(); } } declare module laya.d3.utils { import EventDispatcher = laya.events.EventDispatcher; /** * CollsionManager 类用于碰撞管理器。 */ class CollisionManager extends EventDispatcher { /** *@private */ static _triggerCollision(): void; /** * 创建一个新的 CollsionManager 实例。 */ constructor(); } } declare module laya.d3.utils { import Collider = laya.d3.component.physics.Collider; import Layer = laya.d3.core.Layer; import Ray = laya.d3.math.Ray; import Vector3 = laya.d3.math.Vector3; /** * Physics 类用于简单物理检测。 */ class Physics { static _layerCollsionMatrix: Array; /**碰撞管理器。*/ static collisionManager: CollisionManager; /**重力值。*/ static gravity: Vector3; /** * @private */ static __init__(): void; /** * 创建一个 Physics 实例。 */ constructor(); /** * 是否忽略两个层之间所有碰撞器的碰撞检测。 * @param layer1 层一。 * @param layer2 层二。 * @param ignore 是否忽略。 */ static setLayerCollision(layer1: Layer, layer2: Layer, collison: boolean): void; /** * 获取两个层之间是否忽略碰撞检测。 * @param layer1 层一。 * @param layer2 层二。 * @return 是否忽略。 */ static getLayerCollision(layer1: Layer, layer2: Layer): boolean; /** * 是否忽略两个碰撞器的碰撞检测。 * @param collider1 碰撞器一。 * @param collider2 碰撞器二。 * @param ignore 是否忽略。 */ static setColliderCollision(collider1: Collider, collider2: Collider, collsion: boolean): void; /** * 获取是否忽略两个碰撞器的碰撞检测。 * @param collider1 碰撞器一。 * @param collider2 碰撞器二。 * @return 是否忽略。 */ static getIColliderCollision(collider1: Collider, collider2: Collider): boolean; /** * 在场景中投下可与所有碰撞器碰撞的一条光线,获取发生碰撞的第一个碰撞器。 * @param ray 射线 * @param outHitInfo 与该射线发生碰撞的第一个碰撞器的碰撞信息 * @param distance 射线长度,默认为最大值 * @param layer 选定制定层内的碰撞器,其他层内碰撞器忽略 */ static rayCast(ray: Ray, outHitInfo: RaycastHit, distance?: number, layer?: number): void; /** * 在场景中投下可与所有碰撞器碰撞的一条光线,获取发生碰撞的所有碰撞器。 * @param ray 射线 * @param outHitAllInfo 与该射线发生碰撞的所有碰撞器的碰撞信息 * @param distance 射线长度,默认为最大值 * @param layer 选定制定层内的碰撞器,其他层内碰撞器忽略 */ static rayCastAll(ray: Ray, outHitAllInfo: Array, distance?: number, layer?: number): void; } } declare module laya.d3.utils { import VertexDeclaration = laya.d3.graphics.VertexDeclaration; import Matrix4x4 = laya.d3.math.Matrix4x4; import Ray = laya.d3.math.Ray; import Vector2 = laya.d3.math.Vector2; import Vector3 = laya.d3.math.Vector3; import Viewport = laya.d3.math.Viewport; /** * Picker 类用于创建拾取。 */ class Picker { /** * 创建一个 Picker 实例。 */ constructor(); /** * 计算鼠标生成的射线。 * @param point 鼠标位置。 * @param viewPort 视口。 * @param projectionMatrix 透视投影矩阵。 * @param viewMatrix 视图矩阵。 * @param world 世界偏移矩阵。 * @return out 输出射线。 */ static calculateCursorRay(point: Vector2, viewPort: Viewport, projectionMatrix: Matrix4x4, viewMatrix: Matrix4x4, world: Matrix4x4, out: Ray): void; /** * 计算射线和三角形碰撞并返回碰撞三角形和碰撞距离。 * @param ray 射线。 * @param positions 顶点数据。 * @param indices 索引数据。 * @param outVertex0 输出三角形顶点0。 * @param outVertex1 输出三角形顶点1。 * @param outVertex2 输出三角形顶点2。 * @return 射线距离三角形的距离,返回Number.NaN则不相交。 */ static rayIntersectsPositionsAndIndices(ray: Ray, vertexDatas: Float32Array, vertexDeclaration: VertexDeclaration, indices: Uint16Array, outHitInfo: RaycastHit): boolean; /** * 计算射线和三角形碰撞并返回碰撞距离。 * @param ray 射线。 * @param vertex1 顶点1。 * @param vertex2 顶点2。 * @param vertex3 顶点3。 * @return 射线距离三角形的距离,返回Number.NaN则不相交。 */ static rayIntersectsTriangle(ray: Ray, vertex1: Vector3, vertex2: Vector3, vertex3: Vector3): number; } } declare module laya.d3.utils { import Sprite3D = laya.d3.core.Sprite3D; import Vector3 = laya.d3.math.Vector3; /** * ... * @author ... */ class RaycastHit { distance: number; trianglePositions: Array; triangleNormals: Array; position: Vector3; sprite3D: Sprite3D; constructor(); cloneTo(dec: RaycastHit): void; } } declare module laya.d3.utils { class Size { static readonly fullScreen: Size; readonly width: number; readonly height: number; constructor(width: number, height: number); } } declare module laya.d3.utils { import ComponentNode = laya.d3.core.ComponentNode; import Matrix4x4 = laya.d3.math.Matrix4x4; import Quaternion = laya.d3.math.Quaternion; import Vector3 = laya.d3.math.Vector3; import Vector4 = laya.d3.math.Vector4; /** * Utils3D 类用于创建3D工具。 */ class Utils3D { /** * @private */ static _createNodeByJson(rootNode: ComponentNode, nodeData: any, node: any, innerResouMap: any): any; static _computeBoneAndAnimationDatasByBindPoseMatrxix(bones: any, curData: Float32Array, inverGlobalBindPose: Array, outBonesDatas: Float32Array, outAnimationDatas: Float32Array, boneIndexToMesh: Array): void; static _computeAnimationDatasByArrayAndMatrixFast(inverGlobalBindPose: Array, bonesDatas: Float32Array, outAnimationDatas: Float32Array, boneIndexToMesh: Array): void; static _computeBoneAndAnimationDatasByBindPoseMatrxixOld(bones: any, curData: Float32Array, inverGlobalBindPose: Array, outBonesDatas: Float32Array, outAnimationDatas: Float32Array): void; static _computeAnimationDatasByArrayAndMatrixFastOld(inverGlobalBindPose: Array, bonesDatas: Float32Array, outAnimationDatas: Float32Array): void; static _computeRootAnimationData(bones: any, curData: Float32Array, animationDatas: Float32Array): void; /** * 根据四元数旋转三维向量。 * @param source 源三维向量。 * @param rotation 旋转四元数。 * @param out 输出三维向量。 */ static transformVector3ArrayByQuat(sourceArray: Float32Array, sourceOffset: number, rotation: Quaternion, outArray: Float32Array, outOffset: number): void; /** *通过数组数据计算矩阵乘法。 * @param leftArray left矩阵数组。 * @param leftOffset left矩阵数组的偏移。 * @param rightArray right矩阵数组。 * @param rightOffset right矩阵数组的偏移。 * @param outArray 输出矩阵数组。 * @param outOffset 输出矩阵数组的偏移。 */ static mulMatrixByArray(leftArray: Float32Array, leftOffset: number, rightArray: Float32Array, rightOffset: number, outArray: Float32Array, outOffset: number): void; /** *通过数组数据计算矩阵乘法,rightArray和outArray不能为同一数组引用。 * @param leftArray left矩阵数组。 * @param leftOffset left矩阵数组的偏移。 * @param rightArray right矩阵数组。 * @param rightOffset right矩阵数组的偏移。 * @param outArray 结果矩阵数组。 * @param outOffset 结果矩阵数组的偏移。 */ static mulMatrixByArrayFast(leftArray: Float32Array, leftOffset: number, rightArray: Float32Array, rightOffset: number, outArray: Float32Array, outOffset: number): void; /** *通过数组数据计算矩阵乘法,rightArray和outArray不能为同一数组引用。 * @param leftArray left矩阵数组。 * @param leftOffset left矩阵数组的偏移。 * @param rightMatrix right矩阵。 * @param outArray 结果矩阵数组。 * @param outOffset 结果矩阵数组的偏移。 */ static mulMatrixByArrayAndMatrixFast(leftArray: Float32Array, leftOffset: number, rightMatrix: Matrix4x4, outArray: Float32Array, outOffset: number): void; /** *通过数平移、旋转、缩放值计算到结果矩阵数组。 * @param tX left矩阵数组。 * @param tY left矩阵数组的偏移。 * @param tZ right矩阵数组。 * @param qX right矩阵数组的偏移。 * @param qY 输出矩阵数组。 * @param qZ 输出矩阵数组的偏移。 * @param qW 输出矩阵数组的偏移。 * @param sX 输出矩阵数组的偏移。 * @param sY 输出矩阵数组的偏移。 * @param sZ 输出矩阵数组的偏移。 * @param outArray 结果矩阵数组。 * @param outOffset 结果矩阵数组的偏移。 */ static createAffineTransformationArray(tX: number, tY: number, tZ: number, rX: number, rY: number, rZ: number, rW: number, sX: number, sY: number, sZ: number, outArray: Float32Array, outOffset: number): void; /** * 通过矩阵转换一个三维向量数组到另外一个归一化的三维向量数组。 * @param source 源三维向量所在数组。 * @param sourceOffset 源三维向量数组偏移。 * @param transform 变换矩阵。 * @param result 输出三维向量所在数组。 * @param resultOffset 输出三维向量数组偏移。 */ static transformVector3ArrayToVector3ArrayCoordinate(source: Float32Array, sourceOffset: number, transform: Matrix4x4, result: Float32Array, resultOffset: number): void; /** * @private */ static transformLightingMapTexcoordByUV0Array(source: Float32Array, sourceOffset: number, lightingMapScaleOffset: Vector4, result: Float32Array, resultOffset: number): void; /** * @private */ static transformLightingMapTexcoordByUV1Array(source: Float32Array, sourceOffset: number, lightingMapScaleOffset: Vector4, result: Float32Array, resultOffset: number): void; /** * 获取URL版本字符。 * @param url * @return */ static getURLVerion(url: string): string; /** * @private */ static _quaternionCreateFromYawPitchRollArray(yaw: number, pitch: number, roll: number, out: Float32Array): void; /** * @private */ static _createAffineTransformationArray(trans: Float32Array, rot: Float32Array, scale: Float32Array, outE: Float32Array): void; /** * @private */ static _mulMatrixArray(leftMatrixE: Float32Array, rightMatrix: Matrix4x4, outArray: Float32Array, outOffset: number): void; static getYawPitchRoll(quaternion: Float32Array, out: Float32Array): void; static transformQuat(source: Vector3, rotation: Float32Array, out: Vector3): void; /** * @private */ static quaterionNormalize(f: Float32Array, e: Float32Array): void; static matrix4x4MultiplyFFF(a: Float32Array, b: Float32Array, e: Float32Array): void; static matrix4x4MultiplyMFM(left: Matrix4x4, right: Float32Array, out: Matrix4x4): void; } } declare module laya.d3.water { import BaseMaterial = laya.d3.core.material.BaseMaterial; /** * ... * @author ... */ class WaterDetailMaterial extends BaseMaterial { static WAVEINFO: number; static WAVEINFOD: number; static WAVEMAINDIR: number; static TEXWAVE_UV_SCALE: number; constructor(); static init(): void; currentTm: number; waveInfo: Float32Array; waveInfoD: Float32Array; texWaveUVScale: number; } } declare module laya.d3.water { import RenderableSprite3D = laya.d3.core.RenderableSprite3D; import BaseRender = laya.d3.core.render.BaseRender; /** * ... * @author ... */ class WaterRender extends BaseRender { constructor(owner: RenderableSprite3D); protected _calculateBoundingSphere(): void; protected _calculateBoundingBox(): void; _destroy(): void; } } declare module laya.device.geolocation { import Handler = laya.utils.Handler; /** * 使用前可用supported查看浏览器支持。 */ class Geolocation { /** * 由于权限被拒绝造成的地理信息获取失败。 */ static PERMISSION_DENIED: number; /** * 由于内部位置源返回了内部错误导致地理信息获取失败。 */ static POSITION_UNAVAILABLE: number; /** * 信息获取所用时长超出timeout所设置时长。 */ static TIMEOUT: number; /** * 是否支持。 */ static supported: boolean; /** * 如果enableHighAccuracy为true,并且设备能够提供一个更精确的位置,则会获取最佳可能的结果。 * 请注意,这可能会导致较慢的响应时间或增加电量消耗(如使用GPS)。 * 另一方面,如果设置为false,将会得到更快速的响应和更少的电量消耗。 * 默认值为false。 */ static enableHighAccuracy: boolean; static timeout: number; /** * 表示可被返回的缓存位置信息的最大时限。 * 如果设置为0,意味着设备不使用缓存位置,并且尝试获取实时位置。 * 如果设置为Infinity,设备必须返回缓存位置而无论其时限。 */ static maximumAge: number; constructor(); /** * 获取设备当前位置。 * @param onSuccess 带有唯一Position参数的回调处理器。 * @param onError 可选的。带有错误信息的回调处理器。错误代码为Geolocation.PERMISSION_DENIED、Geolocation.POSITION_UNAVAILABLE和Geolocation.TIMEOUT之一。 */ static getCurrentPosition(onSuccess: Handler, onError?: Handler): void; /** * 监视设备当前位置。回调处理器在设备位置改变时被执行。 * @param onSuccess 带有唯一Position参数的回调处理器。 * @param onError 可选的。带有错误信息的回调处理器。错误代码为Geolocation.PERMISSION_DENIED、Geolocation.POSITION_UNAVAILABLE和Geolocation.TIMEOUT之一。 */ static watchPosition(onSuccess: Handler, onError: Handler): number; /** * 移除watchPosition安装的指定处理器。 * @param id */ static clearWatch(id: number): void; } } declare module laya.device.geolocation { class GeolocationInfo { setPosition(pos: any): void; readonly latitude: number; readonly longitude: number; readonly altitude: number; readonly accuracy: number; readonly altitudeAccuracy: number; readonly heading: number; readonly speed: number; readonly timestamp: number; } } declare module laya.device.media { import Bitmap = laya.resource.Bitmap; /** * @private */ class HtmlVideo extends Bitmap { protected video: any; constructor(); static create: Function; setSource(url: string, extension: number): void; getVideo(): any; } } declare module laya.device.media { import Handler = laya.utils.Handler; /** * Media用于捕捉摄像头和麦克风。可以捕捉任意之一,或者同时捕捉两者。getCamera前可以使用supported()检查当前浏览器是否支持。 * NOTE: *

    目前Media在移动平台只支持Android,不支持IOS。只可在FireFox完整地使用,Chrome测试时无法捕捉视频。

    */ class Media { constructor(); /** * 检查浏览器兼容性。 */ static supported(): boolean; /** * 获取用户媒体。 * @param options 简单的可选项可以使 * @param onSuccess 获取成功的处理器,唯一参数返回媒体的Blob地址,可以将其传给Video。 * @param onError 获取失败的处理器,唯一参数是Error。 */ static getMedia(options: any, onSuccess: Handler, onError: Handler): void; } } declare module laya.device.media { import Sprite = laya.display.Sprite; /** * Video将视频显示到Canvas上。Video可能不会在所有浏览器有效。 *

    关于Video支持的所有事件参见:http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp

    *

    * 注意:
    * 在PC端可以在任何时机调用play()因此,可以在程序开始运行时就使Video开始播放。但是在移动端,只有在用户第一次触碰屏幕后才可以调用play(),所以移动端不可能在程序开始运行时就自动开始播放Video。 *

    * *

    MDN Video链接: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video

    */ class Video extends Sprite { static MP4: number; static OGG: number; static CAMERA: number; static WEBM: number; /** 表示最有可能支持。 */ static SUPPORT_PROBABLY: string; /** 表示可能支持。*/ static SUPPORT_MAYBY: string; /** 表示不支持。 */ static SUPPORT_NO: string; constructor(width?: number, height?: number); /** * 设置播放源。 * @param url 播放源路径。 */ load(url: string): void; /** * 开始播放视频。 */ play(): void; /** * 暂停视频播放。 */ pause(): void; /** * 重新加载视频。 */ reload(): void; /** * 检测是否支持播放指定格式视频。 * @param type 参数为Video.MP4 / Video.OGG / Video.WEBM之一。 * @return 表示支持的级别。可能的值: *
      *
    • "probably",Video.SUPPORT_PROBABLY - 浏览器最可能支持该音频/视频类型
    • *
    • "maybe",Video.SUPPORT_MAYBY - 浏览器也许支持该音频/视频类型
    • *
    • "",Video.SUPPORT_NO- (空字符串)浏览器不支持该音频/视频类型
    • *
    */ canPlayType(type: number): string; /** * buffered 属性返回 TimeRanges(JS)对象。TimeRanges 对象表示用户的音视频缓冲范围。缓冲范围指的是已缓冲音视频的时间范围。如果用户在音视频中跳跃播放,会得到多个缓冲范围。 *

    buffered.length返回缓冲范围个数。如获取第一个缓冲范围则是buffered.start(0)和buffered.end(0)。以秒计。

    * @return TimeRanges(JS)对象 */ readonly buffered: any; /** * 获取当前播放源路径。 */ readonly currentSrc: string; /** * 设置和获取当前播放头位置。 */ currentTime: number; /** * 设置和获取当前音量。 */ volume: number; /** * 表示视频元素的就绪状态: *
      *
    • 0 = HAVE_NOTHING - 没有关于音频/视频是否就绪的信息
    • *
    • 1 = HAVE_METADATA - 关于音频/视频就绪的元数据
    • *
    • 2 = HAVE_CURRENT_DATA - 关于当前播放位置的数据是可用的,但没有足够的数据来播放下一帧/毫秒
    • *
    • 3 = HAVE_FUTURE_DATA - 当前及至少下一帧的数据是可用的
    • *
    • 4 = HAVE_ENOUGH_DATA - 可用数据足以开始播放
    • *
    */ readonly readyState: any; /** * 获取视频源尺寸。ready事件触发后可用。 */ readonly videoWidth: number; readonly videoHeight: number; /** * 获取视频长度(秒)。ready事件触发后可用。 */ readonly duration: number; /** * 返回音频/视频的播放是否已结束 */ readonly ended: boolean; /** * 返回表示音频/视频错误状态的 MediaError(JS)对象。 */ readonly error: boolean; /** * 设置或返回音频/视频是否应在结束时重新播放。 */ loop: boolean; /** * playbackRate 属性设置或返回音频/视频的当前播放速度。如: *
      *
    • 1.0 正常速度
    • *
    • 0.5 半速(更慢)
    • *
    • 2.0 倍速(更快)
    • *
    • -1.0 向后,正常速度
    • *
    • -0.5 向后,半速
    • *
    *

    只有 Google Chrome 和 Safari 支持 playbackRate 属性。

    */ playbackRate: number; /** * 获取和设置静音状态。 */ muted: boolean; /** * 返回视频是否暂停 */ readonly paused: boolean; /** * preload 属性设置或返回是否在页面加载后立即加载视频。可赋值如下: *
      *
    • auto 指示一旦页面加载,则开始加载视频。
    • *
    • metadata 指示当页面加载后仅加载音频/视频的元数据。
    • *
    • none 指示页面加载后不应加载音频/视频。
    • *
    */ preload: string; /** * 参见 http://www.w3school.com.cn/tags/av_prop_seekable.asp。 */ readonly seekable: any; /** * seeking 属性返回用户目前是否在音频/视频中寻址。 * 寻址中(Seeking)指的是用户在音频/视频中移动/跳跃到新的位置。 */ readonly seeking: boolean; height: number; size(width: number, height: number): Sprite; width: number; /** * 销毁内部事件绑定。 */ destroy(detroyChildren?: boolean): void; } } declare module laya.device.media { import HtmlVideo = laya.device.media.HtmlVideo; /** * @private */ class WebGLVideo extends HtmlVideo { constructor(); updateTexture(): void; } } declare module laya.device.motion { /** * 加速度x/y/z的单位均为m/s²。 * 在硬件(陀螺仪)不支持的情况下,alpha、beta和gamma值为null。 * * @author Survivor */ class AccelerationInfo { /** * x轴上的加速度值。 */ x: number; /** * y轴上的加速度值。 */ y: number; /** * z轴上的加速度值。 */ z: number; constructor(); } } declare module laya.device.motion { import EventDispatcher = laya.events.EventDispatcher; /** * Accelerator.instance获取唯一的Accelerator引用,请勿调用构造函数。 * *

    * listen()的回调处理器接受四个参数: *

      *
    1. acceleration: 表示用户给予设备的加速度。
    2. *
    3. accelerationIncludingGravity: 设备受到的总加速度(包含重力)。
    4. *
    5. rotationRate: 设备的自转速率。
    6. *
    7. interval: 加速度获取的时间间隔(毫秒)。
    8. *
    *

    *

    * NOTE
    * 如,rotationRate的alpha在apple和moz文档中都是z轴旋转角度,但是实测是x轴旋转角度。为了使各属性表示的值与文档所述相同,实际值与其他属性进行了对调。 * 其中: *

      *
    • alpha使用gamma值。
    • *
    • beta使用alpha值。
    • *
    • gamma使用beta。
    • *
    * 目前孰是孰非尚未可知,以此为注。 *

    */ class Accelerator extends EventDispatcher { static readonly instance: Accelerator; constructor(singleton: number); /** * 侦听加速器运动。 * @param observer 回调函数接受4个参数,见类说明。 */ on(type: string, caller: any, listener: Function, args?: Array): EventDispatcher; /** * 取消侦听加速器。 * @param handle 侦听加速器所用处理器。 */ off(type: string, caller: any, listener: Function, onceOnly?: boolean): EventDispatcher; /** * 把加速度值转换为视觉上正确的加速度值。依赖于Browser.window.orientation,可能在部分低端机无效。 * @param acceleration * @return */ static getTransformedAcceleration(acceleration: AccelerationInfo): AccelerationInfo; } } declare module laya.device.motion { import EventDispatcher = laya.events.EventDispatcher; /** * 使用Gyroscope.instance获取唯一的Gyroscope引用,请勿调用构造函数。 * *

    * listen()的回调处理器接受两个参数: * function onOrientationChange(absolute:Boolean, info:RotationInfo):void *

      *
    1. absolute: 指示设备是否可以提供绝对方位数据(指向地球坐标系),或者设备决定的任意坐标系。关于坐标系参见https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Orientation_and_motion_data_explained
    2. *
    3. info: RotationInfo类型参数,保存设备的旋转值。
    4. *
    *

    * *

    * 浏览器兼容性参见:http://caniuse.com/#search=deviceorientation *

    */ class Gyroscope extends EventDispatcher { static readonly instance: Gyroscope; constructor(singleton: number); /** * 监视陀螺仪运动。 * @param observer 回调函数接受一个Boolean类型的absoluteGyroscopeInfo类型参数。 */ on(type: string, caller: any, listener: Function, args?: Array): EventDispatcher; /** * 取消指定处理器对陀螺仪的监视。 * @param observer */ off(type: string, caller: any, listener: Function, onceOnly?: boolean): EventDispatcher; } } declare module laya.device.motion { /** * 保存旋转信息的类。请勿修改本类的属性。 * @author Survivor */ class RotationInfo { /** *

    * 指示设备是否可以提供绝对方位数据(指向地球坐标系),或者设备决定的任意坐标系。 * 关于坐标系参见https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Orientation_and_motion_data_explained。 *

    * 需要注意的是,IOS环境下,该值始终为false。即使如此,你依旧可以从alpha中取得正确的值。 */ absolute: boolean; /** * Z轴旋转角度,其值范围从0至360。 * 若absolute为true或者在IOS中,alpha值是从北方到当前设备方向的角度值。 */ alpha: number; /** * X轴旋转角度, 其值范围从-180至180。代表设备从前至后的运动。 */ beta: number; /** * Y轴旋转角度,其值范围从-90至90。代表设备从左至右的运动。 */ gamma: number; /** * 罗盘数据的精确度(角度)。仅IOS可用。 */ compassAccuracy: number; constructor(); } } declare module laya.device { import EventDispatcher = laya.events.EventDispatcher; /** * Shake只能在支持此操作的设备上有效。 * * @author Survivor */ class Shake extends EventDispatcher { constructor(); static readonly instance: Shake; /** * 开始响应设备摇晃。 * @param throushold 响应的瞬时速度阈值,轻度摇晃的值约在5~10间。 * @param timeout 设备摇晃的响应间隔时间。 * @param callback 在设备摇晃触发时调用的处理器。 */ start(throushold: number, interval: number): void; /** * 停止响应设备摇晃。 */ stop(): void; } } declare module laya.display { import Handler = laya.utils.Handler; /** *

    Animation 是Graphics动画类。实现了基于Graphics的动画创建、播放、控制接口。

    *

    本类使用了动画模版缓存池,它以一定的内存开销来节省CPU开销,当相同的动画模版被多次使用时,相比于每次都创建新的动画模版,使用动画模版缓存池,只需创建一次,缓存之后多次复用,从而节省了动画模版创建的开销。

    *

    动画模版缓存池,以key-value键值对存储,key可以自定义,也可以从指定的配置文件中读取,value为对应的动画模版,是一个Graphics对象数组,每个Graphics对象对应一个帧图像,动画的播放实质就是定时切换Graphics对象。

    *

    使用set source、loadImages(...)、loadAtlas(...)、loadAnimation(...)方法可以创建动画模版。使用play(...)可以播放指定动画。

    * @example 以下示例代码,创建了一个 Text 实例。 * package * { * import laya.display.Animation; * import laya.net.Loader; * import laya.utils.Handler; * public class Animation_Example * { * public function Animation_Example() * { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * init();//初始化 * } * private function init():void * { * var animation:Animation = new Animation();//创建一个 Animation 类的实例对象 animation 。 * animation.loadAtlas("resource/ani/fighter.json");//加载图集并播放 * animation.x = 200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 * animation.y = 200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 * animation.interval = 50;//设置 animation 对象的动画播放间隔时间,单位:毫秒。 * animation.play();//播放动画。 * Laya.stage.addChild(animation);//将 animation 对象添加到显示列表。 * } * } * } * * @example * Animation_Example(); * function Animation_Example(){ * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * init();//初始化 * } * function init() * { * var animation = new Laya.Animation();//创建一个 Animation 类的实例对象 animation 。 * animation.loadAtlas("resource/ani/fighter.json");//加载图集并播放 * animation.x = 200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 * animation.y = 200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 * animation.interval = 50;//设置 animation 对象的动画播放间隔时间,单位:毫秒。 * animation.play();//播放动画。 * Laya.stage.addChild(animation);//将 animation 对象添加到显示列表。 * } * * @example * import Animation = laya.display.Animation; * class Animation_Example { * constructor() { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * this.init(); * } * private init(): void { * var animation:Animation = new Laya.Animation();//创建一个 Animation 类的实例对象 animation 。 * animation.loadAtlas("resource/ani/fighter.json");//加载图集并播放 * animation.x = 200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 * animation.y = 200;//设置 animation 对象的属性 x 的值,用于控制 animation 对象的显示位置。 * animation.interval = 50;//设置 animation 对象的动画播放间隔时间,单位:毫秒。 * animation.play();//播放动画。 * Laya.stage.addChild(animation);//将 animation 对象添加到显示列表。 * } * } * new Animation_Example(); */ class Animation extends AnimationPlayerBase { /** *

    动画模版缓存池,以key-value键值对存储,key可以自定义,也可以从指定的配置文件中读取,value为对应的动画模版,是一个Graphics对象数组,每个Graphics对象对应一个帧图像,动画的播放实质就是定时切换Graphics对象。

    *

    使用loadImages(...)、loadAtlas(...)、loadAnimation(...)、set source方法可以创建动画模版。使用play(...)可以播放指定动画。

    */ static framesMap: any; protected _frames: Array; protected _url: string; /** * 创建一个新的 Animation 实例。 */ constructor(); /** @inheritDoc */ destroy(destroyChild?: boolean): void; /** *

    开始播放动画。会在动画模版缓存池中查找key值为name的动画模版,存在则用此动画模版初始化当前序列帧, 如果不存在,则使用当前序列帧。

    *

    play(...)方法被设计为在创建实例后的任何时候都可以被调用,调用后就处于播放状态,当相应的资源加载完毕、调用动画帧填充方法(set frames)或者将实例显示在舞台上时,会判断是否处于播放状态,如果是,则开始播放。

    *

    配合wrapMode属性,可设置动画播放顺序类型。

    * @param start (可选)指定动画播放开始的索引(int)或帧标签(String)。帧标签可以通过addLabel(...)和removeLabel(...)进行添加和删除。 * @param loop (可选)是否循环播放。 * @param name (可选)动画模板在动画模版缓存池中的key,也可认为是动画名称。如果name为空,则播放当前动画序列帧;如果不为空,则在动画模版缓存池中寻找key值为name的动画模版,如果存在则用此动画模版初始化当前序列帧并播放,如果不存在,则仍然播放当前动画序列帧;如果没有当前动画的帧数据,则不播放,但该实例仍然处于播放状态。 * @param showWarn(可选)是否动画不存在时打印警告 */ play(start?: any, loop?: boolean, name?: string, showWarn?: boolean): void; protected _setFramesFromCache(name: string, showWarn?: boolean): boolean; protected _frameLoop(): void; protected _displayToIndex(value: number): void; /** * 当前动画的帧图像数组。本类中,每个帧图像是一个Graphics对象,而动画播放就是定时切换Graphics对象的过程。 */ frames: Array; /** *

    动画数据源。

    *

    类型如下:
    * 1. LayaAir IDE动画文件路径:使用此类型需要预加载所需的图集资源,否则会创建失败,如果不想预加载或者需要创建完毕的回调,请使用loadAnimation(...)方法;
    * 2. 图集路径:使用此类型创建的动画模版不会被缓存到动画模版缓存池中,如果需要缓存或者创建完毕的回调,请使用loadAtlas(...)方法;
    * 3. 图片路径集合:使用此类型创建的动画模版不会被缓存到动画模版缓存池中,如果需要缓存,请使用loadImages(...)方法。

    * @param value 数据源。比如:图集:"xx/a1.atlas";图片集合:"a1.png,a2.png,a3.png";LayaAir IDE动画"xx/a1.ani"。 */ source: string; /** * 设置自动播放的动画名称,在LayaAir IDE中可以创建的多个动画组成的动画集合,选择其中一个动画名称进行播放。 */ autoAnimation: string; /** * 是否自动播放,默认为false。如果设置为true,则动画被创建并添加到舞台后自动播放。 */ autoPlay: boolean; /** * 停止动画播放,并清理对象属性。之后可存入对象池,方便对象复用。 */ clear(): void; /** *

    根据指定的动画模版初始化当前动画序列帧。选择动画模版的过程如下:1. 动画模版缓存池中key为cacheName的动画模版;2. 如果不存在,则加载指定的图片集合并创建动画模版。注意:只有指定不为空的cacheName,才能将创建好的动画模版以此为key缓存到动画模版缓存池,否则不进行缓存。

    *

    动画模版缓存池是以一定的内存开销来节省CPU开销,当相同的动画模版被多次使用时,相比于每次都创建新的动画模版,使用动画模版缓存池,只需创建一次,缓存之后多次复用,从而节省了动画模版创建的开销。

    *

    因为返回值为Animation对象本身,所以可以使用如下语法:ani.loadImages(...).loadImages(...).play(...);。

    * @param urls 图片路径集合。需要创建动画模版时,会以此为数据源。参数形如:[url1,url2,url3,...]。 * @param cacheName (可选)动画模板在动画模版缓存池中的key。如果此参数不为空,表示使用动画模版缓存池。如果动画模版缓存池中存在key为cacheName的动画模版,则使用此模版。否则,创建新的动画模版,如果cacheName不为空,则以cacheName为key缓存到动画模版缓存池中,如果cacheName为空,不进行缓存。 * @return 返回Animation对象本身。 */ loadImages(urls: Array, cacheName?: string): Animation; /** *

    根据指定的动画模版初始化当前动画序列帧。选择动画模版的过程如下:1. 动画模版缓存池中key为cacheName的动画模版;2. 如果不存在,则加载指定的图集并创建动画模版。

    *

    注意:只有指定不为空的cacheName,才能将创建好的动画模版以此为key缓存到动画模版缓存池,否则不进行缓存。

    *

    动画模版缓存池是以一定的内存开销来节省CPU开销,当相同的动画模版被多次使用时,相比于每次都创建新的动画模版,使用动画模版缓存池,只需创建一次,缓存之后多次复用,从而节省了动画模版创建的开销。

    *

    因为返回值为Animation对象本身,所以可以使用如下语法:ani.loadAtlas(...).loadAtlas(...).play(...);。

    * @param url 图集路径。需要创建动画模版时,会以此为数据源。 * @param loaded (可选)使用指定图集初始化动画完毕的回调。 * @param cacheName (可选)动画模板在动画模版缓存池中的key。如果此参数不为空,表示使用动画模版缓存池。如果动画模版缓存池中存在key为cacheName的动画模版,则使用此模版。否则,创建新的动画模版,如果cacheName不为空,则以cacheName为key缓存到动画模版缓存池中,如果cacheName为空,不进行缓存。 * @return 返回动画本身。 */ loadAtlas(url: string, loaded?: Handler, cacheName?: string): Animation; /** *

    加载并解析由LayaAir IDE制作的动画文件,此文件中可能包含多个动画。默认帧率为在IDE中设计的帧率,如果调用过set interval,则使用此帧间隔对应的帧率。加载后创建动画模版,并缓存到动画模版缓存池,key "url#动画名称" 对应相应动画名称的动画模板,key "url#" 对应动画模版集合的默认动画模版。

    *

    注意:如果调用本方法前,还没有预加载动画使用的图集,请将atlas参数指定为对应的图集路径,否则会导致动画创建失败。

    *

    动画模版缓存池是以一定的内存开销来节省CPU开销,当相同的动画模版被多次使用时,相比于每次都创建新的动画模版,使用动画模版缓存池,只需创建一次,缓存之后多次复用,从而节省了动画模版创建的开销。

    *

    因为返回值为Animation对象本身,所以可以使用如下语法:ani.loadAnimation(...).loadAnimation(...).play(...);。

    * @param url 动画文件路径。可由LayaAir IDE创建并发布。 * @param loaded (可选)使用指定动画资源初始化动画完毕的回调。 * @param atlas (可选)动画用到的图集地址(可选)。 * @return 返回动画本身。 */ loadAnimation(url: string, loaded?: Handler, atlas?: string): Animation; protected _parseGraphicAnimation(animationData: any): any; protected _parseGraphicAnimationByData(animationObject: any): any; /** *

    创建动画模板,多个动画可共享同一份动画模板,而不必每次都创建一份新的,从而节省创建Graphics集合的开销。

    * @param url 图集路径或者图片路径数组。如果是图集路径,需要相应图集已经被预加载,如果没有预加载,会导致创建失败。 * @param name 动画模板在动画模版缓存池中的key。如果不为空,则以此为key缓存动画模板,否则不缓存。 * @return 动画模板。 */ static createFrames(url: any, name: string): Array; /** *

    从动画模版缓存池中清除指定key值的动画数据。

    *

    开发者在调用创建动画模版函数时,可以手动指定此值。而如果是由LayaAir IDE创建的动画集,解析后的key格式为:"url#":表示动画集的默认动画模版,如果以此值为参数,会清除整个动画集数据;"url#aniName":表示相应名称的动画模版。

    * @param key 动画模板在动画模版缓存池中的key。 */ static clearCache(key: string): void; } } declare module laya.display { /** *

    动画播放基类,提供了基础的动画播放控制方法和帧标签事件相关功能。

    *

    可以继承此类,但不要直接实例化此类,因为有些方法需要由子类实现。

    */ class AnimationPlayerBase extends Sprite { /**动画播放顺序类型:正序播放。 */ static WRAP_POSITIVE: number; /**动画播放顺序类型:逆序播放。 */ static WRAP_REVERSE: number; /**动画播放顺序类型:pingpong播放(当按指定顺序播放完结尾后,如果继续播发,则会改变播放顺序)。 */ static WRAP_PINGPONG: number; /** * 是否循环播放,调用play(...)方法时,会将此值设置为指定的参数值。 */ loop: boolean; /** *

    播放顺序类型:AnimationPlayerBase.WRAP_POSITIVE为正序播放,AnimationPlayerBase.WRAP_REVERSE为倒序播放,AnimationPlayerBase.WRAP_PINGPONG为pingpong播放(当按指定顺序播放完结尾后,如果继续播发,则会改变播放顺序)。

    *

    默认为正序播放。

    */ wrapMode: number; protected _interval: number; protected _index: number; protected _count: number; protected _isPlaying: boolean; protected _labels: any; protected _isReverse: boolean; protected _frameRateChanged: boolean; protected _actionName: string; /** * 可以继承此类,但不要直接实例化此类,因为有些方法需要由子类实现。 */ constructor(); /** *

    开始播放动画。play(...)方法被设计为在创建实例后的任何时候都可以被调用,当相应的资源加载完毕、调用动画帧填充方法(set frames)或者将实例显示在舞台上时,会判断是否正在播放中,如果是,则进行播放。

    *

    配合wrapMode属性,可设置动画播放顺序类型。

    * @param start (可选)指定动画播放开始的索引(int)或帧标签(String)。帧标签可以通过addLabel(...)和removeLabel(...)进行添加和删除。 * @param loop (可选)是否循环播放。 * @param name (可选)动画名称。 * @param showWarn(可选)是否动画不存在时打印警告 */ play(start?: any, loop?: boolean, name?: string, showWarn?: boolean): void; /** *

    动画播放的帧间隔时间(单位:毫秒)。默认值依赖于Config.animationInterval=50,通过Config.animationInterval可以修改默认帧间隔时间。

    *

    要想为某动画设置独立的帧间隔时间,可以使用set interval,注意:如果动画正在播放,设置后会重置帧循环定时器的起始时间为当前时间,也就是说,如果频繁设置interval,会导致动画帧更新的时间间隔会比预想的要慢,甚至不更新。

    */ interval: number; protected _getFrameByLabel(label: string): number; protected _frameLoop(): void; _setControlNode(node: Sprite): void; _setDisplay(value: boolean): void; protected _checkResumePlaying(): void; /** * 停止动画播放。 */ stop(): void; /** * 是否正在播放中。 */ readonly isPlaying: boolean; /** * 增加一个帧标签到指定索引的帧上。当动画播放到此索引的帧时会派发Event.LABEL事件,派发事件是在完成当前帧画面更新之后。 * @param label 帧标签名称 * @param index 帧索引 */ addLabel(label: string, index: number): void; /** * 删除指定的帧标签。 * @param label 帧标签名称。注意:如果为空,则删除所有帧标签! */ removeLabel(label: string): void; /** * 将动画切换到指定帧并停在那里。 * @param position 帧索引或帧标签 */ gotoAndStop(position: any): void; /** * 动画当前帧的索引。 */ index: number; protected _displayToIndex(value: number): void; /** * 当前动画中帧的总数。 */ readonly count: number; /** * 停止动画播放,并清理对象属性。之后可存入对象池,方便对象复用。 */ clear(): void; } } declare module laya.display { import Texture = laya.resource.Texture; import Handler = laya.utils.Handler; /** * BitmapFont 是位图字体类,用于定义位图字体信息。 */ class BitmapFont { protected _texture: Texture; protected _fontCharDic: any; protected _fontWidthMap: any; protected _complete: Handler; protected _path: string; protected _maxWidth: number; protected _spaceWidth: number; protected _padding: Array; /**当前位图字体字号。*/ fontSize: number; /**表示是否根据实际使用的字体大小缩放位图字体大小。*/ autoScaleSize: boolean; /**字符间距(以像素为单位)。*/ letterSpacing: number; /** * 通过指定位图字体文件路径,加载位图字体文件,加载完成后会自动解析。 * @param path 位图字体文件的路径。 * @param complete 加载并解析完成的回调。如果成功返回this,如果失败返回null */ loadFont(path: string, complete: Handler): void; protected onLoaded(): void; /** * 解析字体文件。 * @param xml 字体文件XML。 * @param texture 字体的纹理。 */ parseFont(xml: any, texture: Texture): void; /** * @private * 解析字体文件。 * @param xml 字体文件XML。 * @param texture 字体的纹理。 */ parseFont2(xml: any, texture: Texture): void; /** * 获取指定字符的字体纹理对象。 * @param char 字符。 * @return 指定的字体纹理对象。 */ getCharTexture(char: string): Texture; /** * 销毁位图字体,调用Text.unregisterBitmapFont 时,默认会销毁。 */ destroy(): void; /** * 设置空格的宽(如果字体库有空格,这里就可以不用设置了)。 * @param spaceWidth 宽度,单位为像素。 */ setSpaceWidth(spaceWidth: number): void; /** * 获取指定字符的宽度。 * @param char 字符。 * @return 宽度。 */ getCharWidth(char: string): number; /** * 获取指定文本内容的宽度。 * @param text 文本内容。 * @return 宽度。 */ getTextWidth(text: string): number; /** * 获取最大字符宽度。 */ getMaxWidth(): number; /** * 获取最大字符高度。 */ getMaxHeight(): number; /** * @private * 将指定的文本绘制到指定的显示对象上。 */ drawText(text: string, sprite: Sprite, drawX: number, drawY: number, align: string, width: number): void; } } declare module laya.display.css { import Sprite = laya.display.Sprite; import Style = laya.display.css.Style; import URL = laya.net.URL; import RenderContext = laya.renders.RenderContext; /** * @private * CSSStyle 类是元素CSS样式定义类。 */ class CSSStyle extends Style { static EMPTY: CSSStyle; /** * 样式表信息。 */ static styleSheets: any; /**水平居中对齐方式。 */ static ALIGN_CENTER: number; /**水平居右对齐方式。 */ static ALIGN_RIGHT: number; /**垂直居中对齐方式。 */ static VALIGN_MIDDLE: number; /**垂直居底部对齐方式。 */ static VALIGN_BOTTOM: number; /**添加布局。 */ static ADDLAYOUTED: number; underLine: number; /** * 是否显示为块级元素。 */ block: boolean; /**行高。 */ lineHeight: number; /** * 创建一个新的 CSSStyle 类实例。 * @param ower 当前 CSSStyle 对象的拥有者。 */ constructor(ower: Sprite); /**@inheritDoc */ destroy(): void; /** * 复制传入的 CSSStyle 属性值。 * @param src 待复制的 CSSStyle 对象。 */ inherit(src: CSSStyle): void; _widthAuto(): boolean; /**@inheritDoc */ widthed(sprite: any): boolean; /** * @private */ _calculation(type: string, value: string): boolean; /** * 宽度。 */ width: any; /** * 高度。 */ height: any; /** * 是否已设置高度。 * @param sprite 显示对象 Sprite。 * @return 一个Boolean 表示是否已设置高度。 */ heighted(sprite: any): boolean; /** * 设置宽高。 * @param w 宽度。 * @param h 高度。 */ size(w: number, h: number): void; /** * 表示左边距。 */ left: any; /** * 表示上边距。 */ top: any; /** * 边距信息。 */ padding: Array; /** * 是否是行元素。 */ lineElement: boolean; /** * 水平对齐方式。 */ align: string; _getAlign(): number; /** * 垂直对齐方式。 */ valign: string; _getValign(): number; /** * 浮动方向。 */ cssFloat: string; _getCssFloat(): number; /** * 设置如何处理元素内的空白。 */ whiteSpace: string; /** * 表示是否换行。 */ wordWrap: boolean; /** * 表示是否加粗。 */ bold: boolean; /** *

    指定文本字段是否是密码文本字段。

    * 如果此属性的值为 true,则文本字段被视为密码文本字段,并使用星号而不是实际字符来隐藏输入的字符。如果为 false,则不会将文本字段视为密码文本字段。 */ password: boolean; /** * 字体信息。 */ font: string; /** * 文本的粗细。 */ weight: string; /** * 间距。 */ letterSpacing: number; /** * 字体大小。 */ fontSize: number; /** * 行间距。 */ leading: number; /** * 表示是否为斜体。 */ italic: boolean; /** * 字体系列。 */ fontFamily: string; /** * 字体粗细。 */ fontWeight: string; /** * 添加到文本的修饰。 */ textDecoration: string; /** * 字体颜色。 */ color: string; /** *

    描边宽度(以像素为单位)。

    * 默认值0,表示不描边。 * @default 0 */ stroke: number; /** *

    描边颜色,以字符串表示。

    * @default "#000000"; */ strokeColor: string; /** * 边框属性,比如border="5px solid red" */ border: string; /** * 边框的颜色。 */ borderColor: string; /** * 背景颜色。 */ backgroundColor: string; background: string; /**@inheritDoc */ render(sprite: Sprite, context: RenderContext, x: number, y: number): void; /**@inheritDoc */ getCSSStyle(): CSSStyle; /** * 设置 CSS 样式字符串。 * @param text CSS样式字符串。 */ cssText(text: string): void; /** * 根据传入的属性名、属性值列表,设置此对象的属性值。 * @param attrs 属性名与属性值列表。 */ attrs(attrs: Array): void; /** * 元素的定位类型。 */ position: string; /**@inheritDoc */ readonly absolute: boolean; /** * 规定元素应该生成的框的类型。 */ display: string; /**@inheritDoc */ setTransform(value: any): void; /**@inheritDoc */ readonly paddingLeft: number; /**@inheritDoc */ readonly paddingTop: number; /** * 定义 X 轴、Y 轴移动转换。 * @param x X 轴平移量。 * @param y Y 轴平移量。 */ translate(x: number, y: number): void; /** * 定义 缩放转换。 * @param x X 轴缩放值。 * @param y Y 轴缩放值。 */ scale(x: number, y: number): void; _enableLayout(): boolean; /** * 通过传入的分割符,分割解析CSS样式字符串,返回样式列表。 * @param text CSS样式字符串。 * @param clipWord 分割符; * @return 样式列表。 */ static parseOneCSS(text: string, clipWord: string): Array; /** * 解析 CSS 样式文本。 * @param text CSS 样式文本。 * @param uri URL对象。 * @internal 此处需要再详细点注释。 */ static parseCSS(text: string, uri: URL): void; } } declare module laya.display.css { /** * @private * Font 类是字体显示定义类。 */ class Font { /** * 一个默认字体 Font 对象。 */ static EMPTY: Font; /** * 默认的颜色。 */ static defaultColor: string; /** * 默认字体大小。 */ static defaultSize: number; /** * 默认字体名称系列。 */ static defaultFamily: string; /** * 默认字体属性。 */ static defaultFont: string; static _STROKE: Array; static __init__(): void; /** * 字体名称系列。 */ family: string; /** * 描边宽度(以像素为单位)列表。 */ stroke: Array; /** * 首行缩进 (以像素为单位)。 */ indent: number; /** * 字体大小。 */ size: number; /** * 创建一个新的 Font 类实例。 * @param src 将此 Font 的成员属性值复制给当前 Font 对象。 */ constructor(src: Font); /** * 字体样式字符串。 */ set(value: string): void; /** * 表示颜色字符串。 */ color: string; /** * 表示是否为斜体。 */ italic: boolean; /** * 表示是否为粗体。 */ bold: boolean; /** * 表示是否为密码格式。 */ password: boolean; /** * 返回字体样式字符串。 * @return 字体样式字符串。 */ toString(): string; /** * 文本的粗细。 */ weight: string; /** * 规定添加到文本的修饰。 */ decoration: string; /** * 将当前的属性值复制到传入的 Font 对象。 * @param dec 一个 Font 对象。 */ copyTo(dec: Font): void; } } declare module laya.display.css { import Sprite = laya.display.Sprite; import CSSStyle = laya.display.css.CSSStyle; import Rectangle = laya.maths.Rectangle; import RenderContext = laya.renders.RenderContext; /** * @private * Style 类是元素样式定义类。 */ class Style { /** 一个默认样式 Style 对象。*/ static EMPTY: Style; protected static _TF_EMPTY: TransformInfo; _tf: TransformInfo; /**透明度。*/ alpha: number; /**表示是否显示。*/ visible: boolean; /**表示滚动区域。*/ scrollRect: Rectangle; /**混合模式。*/ blendMode: string; _type: number; static __init__(): void; /**元素应用的 2D 或 3D 转换的值。该属性允许我们对元素进行旋转、缩放、移动或倾斜。*/ transform: any; getTransform(): any; setTransform(value: any): void; /**定义转换,只是用 X 轴的值。*/ translateX: number; setTranslateX(value: number): void; /**定义转换,只是用 Y 轴的值。*/ translateY: number; setTranslateY(value: number): void; /**X 轴缩放值。*/ scaleX: number; setScaleX(value: number): void; setScale(x: number, y: number): void; /**Y 轴缩放值。*/ scaleY: number; setScaleY(value: number): void; /**定义旋转角度。*/ rotate: number; setRotate(value: number): void; /**定义沿着 X 轴的 2D 倾斜转换。*/ skewX: number; setSkewX(value: number): void; /**定义沿着 Y 轴的 2D 倾斜转换。*/ skewY: number; setSkewY(value: number): void; /**表示元素是否显示为块级元素。*/ readonly block: boolean; /**表示元素的左内边距。*/ readonly paddingLeft: number; /**表示元素的上内边距。*/ readonly paddingTop: number; /**是否为绝对定位。*/ readonly absolute: boolean; /**销毁此对象。*/ destroy(): void; render(sprite: Sprite, context: RenderContext, x: number, y: number): void; getCSSStyle(): CSSStyle; _enableLayout(): boolean; } } declare module laya.display.css { /** * @private */ class TransformInfo { translateX: number; translateY: number; scaleX: number; scaleY: number; rotate: number; skewX: number; skewY: number; } } declare module laya.display { /** *

    动效模板。用于为指定目标对象添加动画效果。每个动效有唯一的目标对象,而同一个对象可以添加多个动效。 当一个动效开始播放时,其他动效会自动停止播放。

    *

    可以通过LayaAir IDE创建。

    */ class EffectAnimation extends FrameAnimation { /** * 动效开始事件。 */ static EffectAnimationBegin: string; /** * 本实例的目标对象。通过本实例控制目标对象的属性变化。 * @param v 指定的目标对象。 */ target: any; /** * 设置开始播放的事件。本实例会侦听目标对象的指定事件,触发后播放相应动画效果。 * @param event */ playEvent: string; play(start?: any, loop?: boolean, name?: string, showWarn?: boolean): void; /** * 设置提供数据的类。 * @param classStr 类路径 */ effectClass: string; /** * 设置动画数据。 * @param uiData */ effectData: any; protected _displayToIndex(value: number): void; protected _displayNodeToFrame(node: any, frame: number, targetDic?: any): void; protected _calculateNodeKeyFrames(node: any): void; } } declare module laya.display { /** * 关键帧动画播放类。 */ class FrameAnimation extends AnimationPlayerBase { constructor(); /** * @private * id对象表 */ _targetDic: any; /** * @private * 动画数据 */ _animationData: any; protected _animationNewFrames: Array; /** * @private * 初始化动画数据 * @param targetDic 对象表 * @param animationData 动画数据 * */ _setUp(targetDic: any, animationData: any): void; /**@inheritDoc */ clear(): void; protected _displayToIndex(value: number): void; protected _displayNodeToFrame(node: any, frame: number, targetDic?: any): void; protected _calculateNodeKeyFrames(node: any): void; /** * 将动画控制对象还原到动画控制之前的状态 */ resetToInitState(): void; } } declare module laya.display { import Matrix = laya.maths.Matrix; import Point = laya.maths.Point; import Rectangle = laya.maths.Rectangle; import RenderContext = laya.renders.RenderContext; import Texture = laya.resource.Texture; /** * Graphics 类用于创建绘图显示对象。Graphics可以同时绘制多个位图或者矢量图,还可以结合save,restore,transform,scale,rotate,translate,alpha等指令对绘图效果进行变化。 * Graphics以命令流方式存储,可以通过cmds属性访问所有命令流。Graphics是比Sprite更轻量级的对象,合理使用能提高应用性能(比如把大量的节点绘图改为一个节点的Graphics命令集合,能减少大量节点创建消耗)。 * @see laya.display.Sprite#graphics */ class Graphics { _sp: Sprite; _one: Array; _render: Function; static __init__(): void; /** * 创建一个新的 Graphics 类实例。 */ constructor(); /** *

    销毁此对象。

    */ destroy(): void; /** *

    清空绘制命令。

    * @param recoverCmds 是否回收绘图指令 */ clear(recoverCmds?: boolean): void; /** * @private * 重绘此对象。 */ _repaint(): void; _isOnlyOne(): boolean; /** * @private * 命令流。存储了所有绘制命令。 */ cmds: Array; /** * 获取位置及宽高信息矩阵(比较耗CPU,频繁使用会造成卡顿,尽量少用)。 * @param realSize (可选)使用图片的真实大小,默认为false * @return 位置与宽高组成的 一个 Rectangle 对象。 */ getBounds(realSize?: boolean): Rectangle; /** * @private * @param realSize (可选)使用图片的真实大小,默认为false * 获取端点列表。 */ getBoundPoints(realSize?: boolean): Array; setFilters(fs: Array): void; /** * 绘制纹理。 * @param tex 纹理。 * @param x (可选)X轴偏移量。 * @param y (可选)Y轴偏移量。 * @param width (可选)宽度。 * @param height (可选)高度。 * @param m (可选)矩阵信息。 * @param alpha (可选)透明度。 */ drawTexture(tex: Texture, x?: number, y?: number, width?: number, height?: number, m?: Matrix, alpha?: number): Array; /** * @private 清理贴图并替换为最新的 * @param tex */ cleanByTexture(tex: Texture, x: number, y: number, width?: number, height?: number): void; /** * 批量绘制同样纹理。 * @param tex 纹理。 * @param pos 绘制坐标。 */ drawTextures(tex: Texture, pos: Array): void; /** * 用texture填充。 * @param tex 纹理。 * @param x X轴偏移量。 * @param y Y轴偏移量。 * @param width (可选)宽度。 * @param height (可选)高度。 * @param type (可选)填充类型 repeat|repeat-x|repeat-y|no-repeat * @param offset (可选)贴图纹理偏移 */ fillTexture(tex: Texture, x: number, y: number, width?: number, height?: number, type?: string, offset?: Point): void; /** * 填充一个圆形。这是一个临时函数,以后会删除,建议用户自己实现。 * @param x * @param y * @param tex * @param cx 圆心位置。 * @param cy * @param radius * @param segNum 分段数,越大越平滑。 */ fillCircle(x: number, y: number, tex: Texture, cx: number, cy: number, radius: number, segNum: number): void; /** * 绘制一组三角形 * @param texture 纹理。 * @param x X轴偏移量。 * @param y Y轴偏移量。 * @param vertices 顶点数组。 * @param indices 顶点索引。 * @param uvData UV数据。 * @param matrix 缩放矩阵。 * @param alpha alpha * @param color 颜色变换 * @param blendMode blend模式 */ drawTriangles(texture: Texture, x: number, y: number, vertices: Float32Array, uvs: Float32Array, indices: Uint16Array, matrix?: Matrix, alpha?: number, color?: string, blendMode?: string): void; /** * @private * 保存到命令流。 */ _saveToCmd(fun: Function, args: Array): Array; /** * 设置剪裁区域,超出剪裁区域的坐标不显示。 * @param x X 轴偏移量。 * @param y Y 轴偏移量。 * @param width 宽度。 * @param height 高度。 */ clipRect(x: number, y: number, width: number, height: number): void; /** * 在画布上绘制文本。 * @param text 在画布上输出的文本。 * @param x 开始绘制文本的 x 坐标位置(相对于画布)。 * @param y 开始绘制文本的 y 坐标位置(相对于画布)。 * @param font 定义字号和字体,比如"20px Arial"。 * @param color 定义文本颜色,比如"#ff0000"。 * @param textAlign 文本对齐方式,可选值:"left","center","right"。 */ fillText(text: string, x: number, y: number, font: string, color: string, textAlign: string, underLine?: number): void; /** * 在画布上绘制“被填充且镶边的”文本。 * @param text 在画布上输出的文本。 * @param x 开始绘制文本的 x 坐标位置(相对于画布)。 * @param y 开始绘制文本的 y 坐标位置(相对于画布)。 * @param font 定义字体和字号,比如"20px Arial"。 * @param fillColor 定义文本颜色,比如"#ff0000"。 * @param borderColor 定义镶边文本颜色。 * @param lineWidth 镶边线条宽度。 * @param textAlign 文本对齐方式,可选值:"left","center","right"。 */ fillBorderText(text: any, x: number, y: number, font: string, fillColor: string, borderColor: string, lineWidth: number, textAlign: string): void; /** * 在画布上绘制文本(没有填色)。文本的默认颜色是黑色。 * @param text 在画布上输出的文本。 * @param x 开始绘制文本的 x 坐标位置(相对于画布)。 * @param y 开始绘制文本的 y 坐标位置(相对于画布)。 * @param font 定义字体和字号,比如"20px Arial"。 * @param color 定义文本颜色,比如"#ff0000"。 * @param lineWidth 线条宽度。 * @param textAlign 文本对齐方式,可选值:"left","center","right"。 */ strokeText(text: any, x: number, y: number, font: string, color: string, lineWidth: number, textAlign: string): void; /** * 设置透明度。 * @param value 透明度。 */ alpha(value: number): void; /** * 设置当前透明度。 * @param value 透明度。 */ setAlpha(value: number): void; /** * 替换绘图的当前转换矩阵。 * @param mat 矩阵。 * @param pivotX (可选)水平方向轴心点坐标。 * @param pivotY (可选)垂直方向轴心点坐标。 */ transform(matrix: Matrix, pivotX?: number, pivotY?: number): void; /** * 旋转当前绘图。(推荐使用transform,性能更高) * @param angle 旋转角度,以弧度计。 * @param pivotX (可选)水平方向轴心点坐标。 * @param pivotY (可选)垂直方向轴心点坐标。 */ rotate(angle: number, pivotX?: number, pivotY?: number): void; /** * 缩放当前绘图至更大或更小。(推荐使用transform,性能更高) * @param scaleX 水平方向缩放值。 * @param scaleY 垂直方向缩放值。 * @param pivotX (可选)水平方向轴心点坐标。 * @param pivotY (可选)垂直方向轴心点坐标。 */ scale(scaleX: number, scaleY: number, pivotX?: number, pivotY?: number): void; /** * 重新映射画布上的 (0,0) 位置。 * @param x 添加到水平坐标(x)上的值。 * @param y 添加到垂直坐标(y)上的值。 */ translate(x: number, y: number): void; /** * 保存当前环境的状态。 */ save(): void; /** * 返回之前保存过的路径状态和属性。 */ restore(): void; /** * @private * 替换文本内容。 * @param text 文本内容。 * @return 替换成功则值为true,否则值为flase。 */ replaceText(text: string): boolean; /** * @private * 替换文本颜色。 * @param color 颜色。 */ replaceTextColor(color: string): void; /** * 加载并显示一个图片。 * @param url 图片地址。 * @param x (可选)显示图片的x位置。 * @param y (可选)显示图片的y位置。 * @param width (可选)显示图片的宽度,设置为0表示使用图片默认宽度。 * @param height (可选)显示图片的高度,设置为0表示使用图片默认高度。 * @param complete (可选)加载完成回调。 */ loadImage(url: string, x?: number, y?: number, width?: number, height?: number, complete?: Function): void; /** * @private */ _renderEmpty(sprite: Sprite, context: RenderContext, x: number, y: number): void; /** * @private */ _renderAll(sprite: Sprite, context: RenderContext, x: number, y: number): void; /** * @private */ _renderOne(sprite: Sprite, context: RenderContext, x: number, y: number): void; /** * @private */ _renderOneImg(sprite: Sprite, context: RenderContext, x: number, y: number): void; /** * 绘制一条线。 * @param fromX X轴开始位置。 * @param fromY Y轴开始位置。 * @param toX X轴结束位置。 * @param toY Y轴结束位置。 * @param lineColor 颜色。 * @param lineWidth (可选)线条宽度。 */ drawLine(fromX: number, fromY: number, toX: number, toY: number, lineColor: string, lineWidth?: number): void; /** * 绘制一系列线段。 * @param x 开始绘制的X轴位置。 * @param y 开始绘制的Y轴位置。 * @param points 线段的点集合。格式:[x1,y1,x2,y2,x3,y3...]。 * @param lineColor 线段颜色,或者填充绘图的渐变对象。 * @param lineWidth (可选)线段宽度。 */ drawLines(x: number, y: number, points: Array, lineColor: any, lineWidth?: number): void; /** * 绘制一系列曲线。 * @param x 开始绘制的 X 轴位置。 * @param y 开始绘制的 Y 轴位置。 * @param points 线段的点集合,格式[startx,starty,ctrx,ctry,startx,starty...]。 * @param lineColor 线段颜色,或者填充绘图的渐变对象。 * @param lineWidth (可选)线段宽度。 */ drawCurves(x: number, y: number, points: Array, lineColor: any, lineWidth?: number): void; /** * 绘制矩形。 * @param x 开始绘制的 X 轴位置。 * @param y 开始绘制的 Y 轴位置。 * @param width 矩形宽度。 * @param height 矩形高度。 * @param fillColor 填充颜色,或者填充绘图的渐变对象。 * @param lineColor (可选)边框颜色,或者填充绘图的渐变对象。 * @param lineWidth (可选)边框宽度。 */ drawRect(x: number, y: number, width: number, height: number, fillColor: any, lineColor?: any, lineWidth?: number): void; /** * 绘制圆形。 * @param x 圆点X 轴位置。 * @param y 圆点Y 轴位置。 * @param radius 半径。 * @param fillColor 填充颜色,或者填充绘图的渐变对象。 * @param lineColor (可选)边框颜色,或者填充绘图的渐变对象。 * @param lineWidth (可选)边框宽度。 */ drawCircle(x: number, y: number, radius: number, fillColor: any, lineColor?: any, lineWidth?: number): void; /** * 绘制扇形。 * @param x 开始绘制的 X 轴位置。 * @param y 开始绘制的 Y 轴位置。 * @param radius 扇形半径。 * @param startAngle 开始角度。 * @param endAngle 结束角度。 * @param fillColor 填充颜色,或者填充绘图的渐变对象。 * @param lineColor (可选)边框颜色,或者填充绘图的渐变对象。 * @param lineWidth (可选)边框宽度。 */ drawPie(x: number, y: number, radius: number, startAngle: number, endAngle: number, fillColor: any, lineColor?: any, lineWidth?: number): void; /** * 绘制多边形。 * @param x 开始绘制的 X 轴位置。 * @param y 开始绘制的 Y 轴位置。 * @param points 多边形的点集合。 * @param fillColor 填充颜色,或者填充绘图的渐变对象。 * @param lineColor (可选)边框颜色,或者填充绘图的渐变对象。 * @param lineWidth (可选)边框宽度。 */ drawPoly(x: number, y: number, points: Array, fillColor: any, lineColor?: any, lineWidth?: number): void; /** * 绘制路径。 * @param x 开始绘制的 X 轴位置。 * @param y 开始绘制的 Y 轴位置。 * @param paths 路径集合,路径支持以下格式:[["moveTo",x,y],["lineTo",x,y,x,y,x,y],["arcTo",x1,y1,x2,y2,r],["closePath"]]。 * @param brush (可选)刷子定义,支持以下设置 * @param pen (可选)画笔定义,支持以下设置 */ drawPath(x: number, y: number, paths: Array, brush?: any, pen?: any): void; } } declare module laya.display { import Rectangle = laya.maths.Rectangle; /** * @private * Graphic bounds数据类 */ class GraphicsBounds { _graphics: Graphics; /** * 销毁 */ destroy(): void; /** * 重置数据 */ reset(): void; /** * 获取位置及宽高信息矩阵(比较耗CPU,频繁使用会造成卡顿,尽量少用)。 * @param realSize (可选)使用图片的真实大小,默认为false * @return 位置与宽高组成的 一个 Rectangle 对象。 */ getBounds(realSize?: boolean): Rectangle; /** * @private * @param realSize (可选)使用图片的真实大小,默认为false * 获取端点列表。 */ getBoundPoints(realSize?: boolean): Array; } } declare module laya.display { import CSSStyle = laya.display.css.CSSStyle; /** * @private * ILayout 类是显示对象的布局接口。 */ interface ILayout { _isChar(): boolean; _getCSSStyle(): CSSStyle; } } declare module laya.display { /** *

    Input 类用于创建显示对象以显示和输入文本。

    *

    Input 类封装了原生的文本输入框,由于不同浏览器的差异,会导致此对象的默认文本的位置与用户点击输入时的文本的位置有少许的偏差。

    */ class Input extends Text { /** 常规文本域。*/ /** password 类型用于密码域输入。*/ /** email 类型用于应该包含 e-mail 地址的输入域。*/ static TYPE_EMAIL: string; /** url 类型用于应该包含 URL 地址的输入域。*/ static TYPE_URL: string; /** number 类型用于应该包含数值的输入域。*/ static TYPE_NUMBER: string; /** *

    range 类型用于应该包含一定范围内数字值的输入域。

    *

    range 类型显示为滑动条。

    *

    您还能够设定对所接受的数字的限定。

    */ static TYPE_RANGE: string; /** 选取日、月、年。*/ static TYPE_DATE: string; /** month - 选取月、年。*/ static TYPE_MONTH: string; /** week - 选取周和年。*/ static TYPE_WEEK: string; /** time - 选取时间(小时和分钟)。*/ static TYPE_TIME: string; /** datetime - 选取时间、日、月、年(UTC 时间)。*/ static TYPE_DATE_TIME: string; /** datetime-local - 选取时间、日、月、年(本地时间)。*/ static TYPE_DATE_TIME_LOCAL: string; /** *

    search 类型用于搜索域,比如站点搜索或 Google 搜索。

    *

    search 域显示为常规的文本域。

    */ static TYPE_SEARCH: string; protected static input: any; protected static area: any; protected static inputElement: any; protected static inputContainer: any; protected static confirmButton: any; protected static promptStyleDOM: any; protected _focus: boolean; protected _multiline: boolean; protected _editable: boolean; protected _restrictPattern: any; protected _maxChars: number; static IOS_IFRAME: boolean; /**表示是否处于输入状态。*/ static isInputting: boolean; /**创建一个新的 Input 类实例。*/ constructor(); static __init__(): void; /** * 设置光标位置和选取字符。 * @param startIndex 光标起始位置。 * @param endIndex 光标结束位置。 */ setSelection(startIndex: number, endIndex: number): void; /**表示是否是多行输入框。*/ multiline: boolean; /** * 获取对输入框的引用实例。 */ readonly nativeInput: any; /**选中当前实例的所有文本。*/ select(): void; /** * 表示焦点是否在此实例上。 */ focus: boolean; /**@inheritDoc */ text: string; changeText(text: string): void; /**@inheritDoc */ color: string; /**限制输入的字符。*/ restrict: string; /** * 是否可编辑。 */ editable: boolean; /** *

    字符数量限制,默认为10000。

    *

    设置字符数量限制时,小于等于0的值将会限制字符数量为10000。

    */ maxChars: number; /** * 设置输入提示符。 */ prompt: string; /** * 设置输入提示符颜色。 */ promptColor: string; /** *

    输入框类型为Input静态常量之一。

    *
      *
    • TYPE_TEXT
    • *
    • TYPE_PASSWORD
    • *
    • TYPE_EMAIL
    • *
    • TYPE_URL
    • *
    • TYPE_NUMBER
    • *
    • TYPE_RANGE
    • *
    • TYPE_DATE
    • *
    • TYPE_MONTH
    • *
    • TYPE_WEEK
    • *
    • TYPE_TIME
    • *
    • TYPE_DATE_TIME
    • *
    • TYPE_DATE_TIME_LOCAL
    • *
    *

    平台兼容性参见http://www.w3school.com.cn/html5/html_5_form_input_types.asp。

    */ type: string; /** *

    原生输入框 X 轴调整值,用来调整输入框坐标。

    *

    由于即使设置了该值,在各平台和浏览器之间也不一定一致,inputElementXAdjuster已弃用。

    * @deprecated */ inputElementXAdjuster: number; inputElementYAdjuster: number; asPassword: boolean; } } declare module laya.display { import EventDispatcher = laya.events.EventDispatcher; import Timer = laya.utils.Timer; /** * Node 类是可放在显示列表中的所有对象的基类。该显示列表管理 Laya 运行时中显示的所有对象。使用 Node 类排列显示列表中的显示对象。Node 对象可以有子显示对象。 */ class Node extends EventDispatcher { static NOTICE_DISPLAY: number; static MOUSEENABLE: number; _childs: Array; protected _displayedInStage: boolean; _parent: Node; _$P: any; conchModel: any; /**节点名称。*/ name: string; /**[只读]是否已经销毁。对象销毁后不能再使用。*/ _destroyed: boolean; /**时间控制器,默认为Laya.timer。*/ timer: Timer; /** * [只读]是否已经销毁。对象销毁后不能再使用。 * @return */ readonly destroyed: boolean; /** * Node 类用于创建节点对象,节点是最基本的元素。 */ constructor(); _setBit(type: number, value: boolean): void; _getBit(type: number): boolean; _setUpNoticeChain(): void; _setUpNoticeType(type: number): void; /** *

    增加事件侦听器,以使侦听器能够接收事件通知。

    *

    如果侦听鼠标事件,则会自动设置自己和父亲节点的属性 mouseEnabled 的值为 true(如果父节点mouseEnabled=false,则停止设置父节点mouseEnabled属性)。

    * @param type 事件的类型。 * @param caller 事件侦听函数的执行域。 * @param listener 事件侦听函数。 * @param args (可选)事件侦听函数的回调参数。 * @return 此 EventDispatcher 对象。 */ on(type: string, caller: any, listener: Function, args?: Array): EventDispatcher; /** *

    增加事件侦听器,以使侦听器能够接收事件通知,此侦听事件响应一次后则自动移除侦听。

    *

    如果侦听鼠标事件,则会自动设置自己和父亲节点的属性 mouseEnabled 的值为 true(如果父节点mouseEnabled=false,则停止设置父节点mouseEnabled属性)。

    * @param type 事件的类型。 * @param caller 事件侦听函数的执行域。 * @param listener 事件侦听函数。 * @param args (可选)事件侦听函数的回调参数。 * @return 此 EventDispatcher 对象。 */ once(type: string, caller: any, listener: Function, args?: Array): EventDispatcher; createConchModel(): any; /** *

    销毁此对象。destroy对象默认会把自己从父节点移除,并且清理自身引用关系,等待js自动垃圾回收机制回收。destroy后不能再使用。

    *

    destroy时会移除自身的事情监听,自身的timer监听,移除子对象及从父节点移除自己。

    * @param destroyChild (可选)是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ destroy(destroyChild?: boolean): void; /** * 销毁所有子对象,不销毁自己本身。 */ destroyChildren(): void; /** * 添加子节点。 * @param node 节点对象 * @return 返回添加的节点 */ addChild(node: Node): Node; /** * 批量增加子节点 * @param ...args 无数子节点。 */ addChildren(...args: any[]): void; /** * 添加子节点到指定的索引位置。 * @param node 节点对象。 * @param index 索引位置。 * @return 返回添加的节点。 */ addChildAt(node: Node, index: number): Node; /** * 根据子节点对象,获取子节点的索引位置。 * @param node 子节点。 * @return 子节点所在的索引位置。 */ getChildIndex(node: Node): number; /** * 根据子节点的名字,获取子节点对象。 * @param name 子节点的名字。 * @return 节点对象。 */ getChildByName(name: string): Node; _get$P(key: string): any; _set$P(key: string, value: any): any; /** * 根据子节点的索引位置,获取子节点对象。 * @param index 索引位置 * @return 子节点 */ getChildAt(index: number): Node; /** * 设置子节点的索引位置。 * @param node 子节点。 * @param index 新的索引。 * @return 返回子节点本身。 */ setChildIndex(node: Node, index: number): Node; protected _childChanged(child?: Node): void; /** * 删除子节点。 * @param node 子节点 * @return 被删除的节点 */ removeChild(node: Node): Node; /** * 从父容器删除自己,如已经被删除不会抛出异常。 * @return 当前节点( Node )对象。 */ removeSelf(): Node; /** * 根据子节点名字删除对应的子节点对象,如果找不到不会抛出异常。 * @param name 对象名字。 * @return 查找到的节点( Node )对象。 */ removeChildByName(name: string): Node; /** * 根据子节点索引位置,删除对应的子节点对象。 * @param index 节点索引位置。 * @return 被删除的节点。 */ removeChildAt(index: number): Node; /** * 删除指定索引区间的所有子对象。 * @param beginIndex 开始索引。 * @param endIndex 结束索引。 * @return 当前节点对象。 */ removeChildren(beginIndex?: number, endIndex?: number): Node; /** * 替换子节点。 * @internal 将传入的新节点对象替换到已有子节点索引位置处。 * @param newNode 新节点。 * @param oldNode 老节点。 * @return 返回新节点。 */ replaceChild(newNode: Node, oldNode: Node): Node; /** * 子对象数量。 */ readonly numChildren: number; /**父节点。*/ parent: Node; /**表示是否在显示列表中显示。*/ readonly displayedInStage: boolean; _setDisplay(value: boolean): void; /** * 当前容器是否包含指定的 Node 节点对象 。 * @param node 指定的 Node 节点对象 。 * @return 一个布尔值表示是否包含指定的 Node 节点对象 。 */ contains(node: Node): boolean; /** * 定时重复执行某函数。功能同Laya.timer.timerLoop()。 * @param delay 间隔时间(单位毫秒)。 * @param caller 执行域(this)。 * @param method 结束时的回调方法。 * @param args (可选)回调参数。 * @param coverBefore (可选)是否覆盖之前的延迟执行,默认为true。 * @param jumpFrame 时钟是否跳帧。基于时间的循环回调,单位时间间隔内,如能执行多次回调,出于性能考虑,引擎默认只执行一次,设置jumpFrame=true后,则回调会连续执行多次 */ timerLoop(delay: number, caller: any, method: Function, args?: Array, coverBefore?: boolean, jumpFrame?: boolean): void; /** * 定时执行某函数一次。功能同Laya.timer.timerOnce()。 * @param delay 延迟时间(单位毫秒)。 * @param caller 执行域(this)。 * @param method 结束时的回调方法。 * @param args (可选)回调参数。 * @param coverBefore (可选)是否覆盖之前的延迟执行,默认为true。 */ timerOnce(delay: number, caller: any, method: Function, args?: Array, coverBefore?: boolean): void; /** * 定时重复执行某函数(基于帧率)。功能同Laya.timer.frameLoop()。 * @param delay 间隔几帧(单位为帧)。 * @param caller 执行域(this)。 * @param method 结束时的回调方法。 * @param args (可选)回调参数。 * @param coverBefore (可选)是否覆盖之前的延迟执行,默认为true。 */ frameLoop(delay: number, caller: any, method: Function, args?: Array, coverBefore?: boolean): void; /** * 定时执行一次某函数(基于帧率)。功能同Laya.timer.frameOnce()。 * @param delay 延迟几帧(单位为帧)。 * @param caller 执行域(this) * @param method 结束时的回调方法 * @param args (可选)回调参数 * @param coverBefore (可选)是否覆盖之前的延迟执行,默认为true */ frameOnce(delay: number, caller: any, method: Function, args?: Array, coverBefore?: boolean): void; /** * 清理定时器。功能同Laya.timer.clearTimer()。 * @param caller 执行域(this)。 * @param method 结束时的回调方法。 */ clearTimer(caller: any, method: Function): void; } } declare module laya.display { import CSSStyle = laya.display.css.CSSStyle; import Style = laya.display.css.Style; import EventDispatcher = laya.events.EventDispatcher; import Matrix = laya.maths.Matrix; import Point = laya.maths.Point; import Rectangle = laya.maths.Rectangle; import RenderContext = laya.renders.RenderContext; import HTMLCanvas = laya.resource.HTMLCanvas; import Texture = laya.resource.Texture; import Handler = laya.utils.Handler; /** *

    Sprite 是基本的显示图形的显示列表节点。 Sprite 默认没有宽高,默认不接受鼠标事件。通过 graphics 可以绘制图片或者矢量图,支持旋转,缩放,位移等操作。Sprite同时也是容器类,可用来添加多个子节点。

    *

    注意: Sprite 默认没有宽高,可以通过getBounds函数获取;也可手动设置宽高;还可以设置autoSize=true,然后再获取宽高。Sprite的宽高一般用于进行碰撞检测和排版,并不影响显示图像大小,如果需要更改显示图像大小,请使用 scaleXscaleYscale

    *

    Sprite 默认不接受鼠标事件,即mouseEnabled=false,但是只要对其监听任意鼠标事件,会自动打开自己以及所有父对象的mouseEnabled=true。所以一般也无需手动设置mouseEnabled

    *

    LayaAir引擎API设计精简巧妙。核心显示类只有一个SpriteSprite针对不同的情况做了渲染优化,所以保证一个类实现丰富功能的同时,又达到高性能。

    * * @example 创建了一个 Sprite 实例。 * package * { * import laya.display.Sprite; * import laya.events.Event; * * public class Sprite_Example * { * private var sprite:Sprite; * private var shape:Sprite * public function Sprite_Example() * { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * onInit(); * } * private function onInit():void * { * sprite = new Sprite();//创建一个 Sprite 类的实例对象 sprite 。 * sprite.loadImage("resource/ui/bg.png");//加载并显示图片。 * sprite.x = 200;//设置 sprite 对象相对于父容器的水平方向坐标值。 * sprite.y = 200;//设置 sprite 对象相对于父容器的垂直方向坐标值。 * sprite.pivotX = 0;//设置 sprite 对象的水平方法轴心点坐标。 * sprite.pivotY = 0;//设置 sprite 对象的垂直方法轴心点坐标。 * Laya.stage.addChild(sprite);//将此 sprite 对象添加到显示列表。 * sprite.on(Event.CLICK, this, onClickSprite);//给 sprite 对象添加点击事件侦听。 * shape = new Sprite();//创建一个 Sprite 类的实例对象 sprite 。 * shape.graphics.drawRect(0, 0, 100, 100, "#ccff00", "#ff0000", 2);//绘制一个有边框的填充矩形。 * shape.x = 400;//设置 shape 对象相对于父容器的水平方向坐标值。 * shape.y = 200;//设置 shape 对象相对于父容器的垂直方向坐标值。 * shape.width = 100;//设置 shape 对象的宽度。 * shape.height = 100;//设置 shape 对象的高度。 * shape.pivotX = 50;//设置 shape 对象的水平方法轴心点坐标。 * shape.pivotY = 50;//设置 shape 对象的垂直方法轴心点坐标。 * Laya.stage.addChild(shape);//将此 shape 对象添加到显示列表。 * shape.on(Event.CLICK, this, onClickShape);//给 shape 对象添加点击事件侦听。 * } * private function onClickSprite():void * { * trace("点击 sprite 对象。"); * sprite.rotation += 5;//旋转 sprite 对象。 * } * private function onClickShape():void * { * trace("点击 shape 对象。"); * shape.rotation += 5;//旋转 shape 对象。 * } * } * } * * @example * var sprite; * var shape; * Sprite_Example(); * function Sprite_Example() * { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * onInit(); * } * function onInit() * { * sprite = new laya.display.Sprite();//创建一个 Sprite 类的实例对象 sprite 。 * sprite.loadImage("resource/ui/bg.png");//加载并显示图片。 * sprite.x = 200;//设置 sprite 对象相对于父容器的水平方向坐标值。 * sprite.y = 200;//设置 sprite 对象相对于父容器的垂直方向坐标值。 * sprite.pivotX = 0;//设置 sprite 对象的水平方法轴心点坐标。 * sprite.pivotY = 0;//设置 sprite 对象的垂直方法轴心点坐标。 * Laya.stage.addChild(sprite);//将此 sprite 对象添加到显示列表。 * sprite.on(Event.CLICK, this, onClickSprite);//给 sprite 对象添加点击事件侦听。 * shape = new laya.display.Sprite();//创建一个 Sprite 类的实例对象 sprite 。 * shape.graphics.drawRect(0, 0, 100, 100, "#ccff00", "#ff0000", 2);//绘制一个有边框的填充矩形。 * shape.x = 400;//设置 shape 对象相对于父容器的水平方向坐标值。 * shape.y = 200;//设置 shape 对象相对于父容器的垂直方向坐标值。 * shape.width = 100;//设置 shape 对象的宽度。 * shape.height = 100;//设置 shape 对象的高度。 * shape.pivotX = 50;//设置 shape 对象的水平方法轴心点坐标。 * shape.pivotY = 50;//设置 shape 对象的垂直方法轴心点坐标。 * Laya.stage.addChild(shape);//将此 shape 对象添加到显示列表。 * shape.on(laya.events.Event.CLICK, this, onClickShape);//给 shape 对象添加点击事件侦听。 * } * function onClickSprite() * { * console.log("点击 sprite 对象。"); * sprite.rotation += 5;//旋转 sprite 对象。 * } * function onClickShape() * { * console.log("点击 shape 对象。"); * shape.rotation += 5;//旋转 shape 对象。 * } * * @example * import Sprite = laya.display.Sprite; * class Sprite_Example { * private sprite: Sprite; * private shape: Sprite * public Sprite_Example() { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * this.onInit(); * } * private onInit(): void { * this.sprite = new Sprite();//创建一个 Sprite 类的实例对象 sprite 。 * this.sprite.loadImage("resource/ui/bg.png");//加载并显示图片。 * this.sprite.x = 200;//设置 sprite 对象相对于父容器的水平方向坐标值。 * this.sprite.y = 200;//设置 sprite 对象相对于父容器的垂直方向坐标值。 * this.sprite.pivotX = 0;//设置 sprite 对象的水平方法轴心点坐标。 * this.sprite.pivotY = 0;//设置 sprite 对象的垂直方法轴心点坐标。 * Laya.stage.addChild(this.sprite);//将此 sprite 对象添加到显示列表。 * this.sprite.on(laya.events.Event.CLICK, this, this.onClickSprite);//给 sprite 对象添加点击事件侦听。 * this.shape = new Sprite();//创建一个 Sprite 类的实例对象 sprite 。 * this.shape.graphics.drawRect(0, 0, 100, 100, "#ccff00", "#ff0000", 2);//绘制一个有边框的填充矩形。 * this.shape.x = 400;//设置 shape 对象相对于父容器的水平方向坐标值。 * this.shape.y = 200;//设置 shape 对象相对于父容器的垂直方向坐标值。 * this.shape.width = 100;//设置 shape 对象的宽度。 * this.shape.height = 100;//设置 shape 对象的高度。 * this.shape.pivotX = 50;//设置 shape 对象的水平方法轴心点坐标。 * this.shape.pivotY = 50;//设置 shape 对象的垂直方法轴心点坐标。 * Laya.stage.addChild(this.shape);//将此 shape 对象添加到显示列表。 * this.shape.on(laya.events.Event.CLICK, this, this.onClickShape);//给 shape 对象添加点击事件侦听。 * } * private onClickSprite(): void { * console.log("点击 sprite 对象。"); * this.sprite.rotation += 5;//旋转 sprite 对象。 * } * private onClickShape(): void { * console.log("点击 shape 对象。"); * this.shape.rotation += 5;//旋转 shape 对象。 * } * } */ class Sprite extends Node implements ILayout { protected _transform: Matrix; protected _tfChanged: boolean; protected _x: number; protected _y: number; _width: number; _height: number; protected _repaint: number; protected _mouseEnableState: number; _zOrder: number; _style: Style; _graphics: Graphics; _renderType: number; /** *

    鼠标事件与此对象的碰撞检测是否可穿透。碰撞检测发生在鼠标事件的捕获阶段,此阶段引擎会从stage开始递归检测stage及其子对象,直到找到命中的目标对象或者未命中任何对象。

    *

    穿透表示鼠标事件发生的位置处于本对象绘图区域内时,才算命中,而与对象宽高和值为Rectangle对象的hitArea属性无关。如果sprite.hitArea值是HitArea对象,表示显式声明了此对象的鼠标事件响应区域,而忽略对象的宽高、mouseThrough属性。

    *

    影响对象鼠标事件响应区域的属性为:width、height、hitArea,优先级顺序为:hitArea(type:HitArea)>hitArea(type:Rectangle)>width/height。

    * @default false 不可穿透,此对象的鼠标响应区域由width、height、hitArea属性决定。

    */ mouseThrough: boolean; /** *

    指定是否自动计算宽高数据。默认值为 false 。

    *

    Sprite宽高默认为0,并且不会随着绘制内容的变化而变化,如果想根据绘制内容获取宽高,可以设置本属性为true,或者通过getBounds方法获取。设置为true,对性能有一定影响。

    */ autoSize: boolean; /** *

    指定鼠标事件检测是优先检测自身,还是优先检测其子对象。鼠标事件检测发生在鼠标事件的捕获阶段,此阶段引擎会从stage开始递归检测stage及其子对象,直到找到命中的目标对象或者未命中任何对象。

    *

    如果为false,优先检测子对象,当有子对象被命中时,中断检测,获得命中目标。如果未命中任何子对象,最后再检测此对象;如果为true,则优先检测本对象,如果本对象没有被命中,直接中断检测,表示没有命中目标;如果本对象被命中,则进一步递归检测其子对象,以确认最终的命中目标。

    *

    合理使用本属性,能减少鼠标事件检测的节点,提高性能。可以设置为true的情况:开发者并不关心此节点的子节点的鼠标事件检测结果,也就是以此节点作为其子节点的鼠标事件检测依据。

    *

    Stage对象和UI的View组件默认为true。

    * @default false 优先检测此对象的子对象,当递归检测完所有子对象后,仍然没有找到目标对象,最后再检测此对象。 */ hitTestPrior: boolean; /** *

    视口大小,视口外的子对象,将不被渲染(如果想实现裁剪效果,请使用srollRect),合理使用能提高渲染性能。比如由一个个小图片拼成的地图块,viewport外面的小图片将不渲染

    *

    srollRect和viewport的区别:
    * 1. srollRect自带裁剪效果,viewport只影响子对象渲染是否渲染,不具有裁剪效果(性能更高)。
    * 2. 设置rect的x,y属性均能实现区域滚动效果,但scrollRect会保持0,0点位置不变。

    * @default null */ viewport: Rectangle; createConchModel(): any; /** *

    指定是否对使用了 scrollRect 的显示对象进行优化处理。默认为false(不优化)。

    *

    当值为ture时:将对此对象使用了scrollRect 设定的显示区域以外的显示内容不进行渲染,以提高性能(如果子对象有旋转缩放或者中心点偏移,则显示筛选会不精确)。

    */ optimizeScrollRect: boolean; /**@inheritDoc */ destroy(destroyChild?: boolean): void; /**根据zOrder进行重新排序。*/ updateZOrder(): void; /** * 指定显示对象是否缓存为静态图像。功能同cacheAs的normal模式。建议优先使用cacheAs代替。 */ cacheAsBitmap: boolean; /** * 设置是否开启自定义渲染,只有开启自定义渲染,才能使用customRender函数渲染。 */ customRenderEnable: boolean; /** *

    指定显示对象是否缓存为静态图像,cacheAs时,子对象发生变化,会自动重新缓存,同时也可以手动调用reCache方法更新缓存。

    *

    建议把不经常变化的“复杂内容”缓存为静态图像,能极大提高渲染性能。cacheAs有"none","normal"和"bitmap"三个值可选。 *

  • 默认为"none",不做任何缓存。
  • *
  • 当值为"normal"时,canvas模式下进行画布缓存,webgl模式下进行命令缓存。
  • *
  • 当值为"bitmap"时,canvas模式下进行依然是画布缓存,webgl模式下使用renderTarget缓存。
  • *

    webgl下renderTarget缓存模式缺点:会额外创建renderTarget对象,增加内存开销,缓存面积有最大2048限制,不断重绘时会增加CPU开销。优点:大幅减少drawcall,渲染性能最高。 * webgl下命令缓存模式缺点:只会减少节点遍历及命令组织,不会减少drawcall数,性能中等。优点:没有额外内存开销,无需renderTarget支持。

    */ cacheAs: string; /** * 是否静态缓存此对象的当前帧的最终属性。为 true 时,子对象变化时不会自动更新缓存,但是可以通过调用 reCache 方法手动刷新。 * 注意: 1. 设置 cacheAs 为非空和非"none"时才有效。 2. 由于渲染的时机在脚本执行之后,也就是说当前帧渲染的是对象的最终属性,所以如果在当前帧渲染之前、设置静态缓存之后改变对象属性,则最终渲染结果表现的是对象的最终属性。 */ staticCache: boolean; /**在设置cacheAs的情况下,调用此方法会重新刷新缓存。*/ reCache(): void; /**表示显示对象相对于父容器的水平方向坐标值。*/ x: number; /**表示显示对象相对于父容器的垂直方向坐标值。*/ y: number; /** *

    显示对象的宽度,单位为像素,默认为0。

    *

    此宽度用于鼠标碰撞检测,并不影响显示对象图像大小。需要对显示对象的图像进行缩放,请使用scale、scaleX、scaleY。

    *

    可以通过getbounds获取显示对象图像的实际宽度。

    */ width: number; /** *

    显示对象的高度,单位为像素,默认为0。

    *

    此高度用于鼠标碰撞检测,并不影响显示对象图像大小。需要对显示对象的图像进行缩放,请使用scale、scaleX、scaleY。

    *

    可以通过getbounds获取显示对象图像的实际高度。

    */ height: number; /** *

    设置对象在自身坐标系下的边界范围。与 getSelfBounds 对应。当 autoSize==true 时,会影响对象宽高。设置后,当需要获取自身边界范围时,就不再需要计算,合理使用能提高性能。比如 getBounds 会优先使用 setBounds 指定的值,如果没有指定则进行计算,此计算会对性能消耗比较大。

    *

    注意: setBoundsgetBounds 并非对应相等关系, getBounds 获取的是本对象在父容器坐标系下的边界范围,通过设置 setBounds 会影响 getBounds 的结果。

    * @param bound bounds矩形区域 */ setBounds(bound: Rectangle): void; /** *

    获取本对象在父容器坐标系的矩形显示区域。

    *

    注意: 1.计算量较大,尽量少用,如果需要频繁使用,可以通过手动设置 setBounds 来缓存自身边界信息,从而避免比较消耗性能的计算。2. setBoundsgetBounds 并非对应相等关系, getBounds 获取的是本对象在父容器坐标系下的边界范围,通过设置 setBounds 会影响 getBounds 的结果。

    * @return 矩形区域。 */ getBounds(): Rectangle; /** * 获取对象在自身坐标系的边界范围。与 setBounds 对应。 *

    注意:计算量较大,尽量少用,如果需要频繁使用,可以提前手动设置 setBounds 来缓存自身边界信息,从而避免比较消耗性能的计算。

    * @return 矩形区域。 */ getSelfBounds(): Rectangle; /** * @private * 获取本对象在父容器坐标系的显示区域多边形顶点列表。 * 当显示对象链中有旋转时,返回多边形顶点列表,无旋转时返回矩形的四个顶点。 * @param ifRotate (可选)之前的对象链中是否有旋转。 * @return 顶点列表。结构:[x1,y1,x2,y2,x3,y3,...]。 */ _boundPointsToParent(ifRotate?: boolean): Array; /** * 返回此实例中的绘图对象( Graphics )的显示区域,不包括子对象。 * @param realSize (可选)使用图片的真实大小,默认为false * @return 一个 Rectangle 对象,表示获取到的显示区域。 */ getGraphicBounds(realSize?: boolean): Rectangle; /** * @private * 获取自己坐标系的显示区域多边形顶点列表 * @param ifRotate (可选)当前的显示对象链是否由旋转 * @return 顶点列表。结构:[x1,y1,x2,y2,x3,y3,...]。 */ _getBoundPointsM(ifRotate?: boolean): Array; /** * @private * 获取样式。 * @return 样式 Style 。 */ getStyle(): Style; /** * @private * 设置样式。 * @param value 样式。 */ setStyle(value: Style): void; /**X轴缩放值,默认值为1。设置为负数,可以实现水平反转效果,比如scaleX=-1。*/ scaleX: number; /**Y轴缩放值,默认值为1。设置为负数,可以实现垂直反转效果,比如scaleX=-1。*/ scaleY: number; /**旋转角度,默认值为0。以角度为单位。*/ rotation: number; /**水平倾斜角度,默认值为0。以角度为单位。*/ skewX: number; /**垂直倾斜角度,默认值为0。以角度为单位。*/ skewY: number; protected _adjustTransform(): Matrix; /** *

    对象的矩阵信息。通过设置矩阵可以实现节点旋转,缩放,位移效果。

    *

    矩阵更多信息请参考 Matrix

    */ transform: Matrix; /**X轴 轴心点的位置,单位为像素,默认为0。轴心点会影响对象位置,缩放中心,旋转中心。*/ pivotX: number; /**Y轴 轴心点的位置,单位为像素,默认为0。轴心点会影响对象位置,缩放中心,旋转中心。*/ pivotY: number; /**透明度,值为0-1,默认值为1,表示不透明。更改alpha值会影响drawcall。*/ alpha: number; /**表示是否可见,默认为true。如果设置不可见,节点将不被渲染。*/ visible: boolean; /**指定要使用的混合模式。目前只支持"lighter"。*/ blendMode: string; /**绘图对象。封装了绘制位图和矢量图的接口,Sprite所有的绘图操作都通过Graphics来实现的。*/ graphics: Graphics; /** *

    显示对象的滚动矩形范围,具有裁剪效果(如果只想限制子对象渲染区域,请使用viewport),设置optimizeScrollRect=true,可以优化裁剪区域外的内容不进行渲染。

    *

    srollRect和viewport的区别:
    * 1.srollRect自带裁剪效果,viewport只影响子对象渲染是否渲染,不具有裁剪效果(性能更高)。
    * 2.设置rect的x,y属性均能实现区域滚动效果,但scrollRect会保持0,0点位置不变。

    */ scrollRect: Rectangle; /** *

    设置坐标位置。相当于分别设置x和y属性。

    *

    因为返回值为Sprite对象本身,所以可以使用如下语法:spr.pos(...).scale(...);

    * @param x X轴坐标。 * @param y Y轴坐标。 * @param speedMode (可选)是否极速模式,正常是调用this.x=value进行赋值,极速模式直接调用内部函数处理,如果未重写x,y属性,建议设置为急速模式性能更高。 * @return 返回对象本身。 */ pos(x: number, y: number, speedMode?: boolean): Sprite; /** *

    设置轴心点。相当于分别设置pivotX和pivotY属性。

    *

    因为返回值为Sprite对象本身,所以可以使用如下语法:spr.pivot(...).pos(...);

    * @param x X轴心点。 * @param y Y轴心点。 * @return 返回对象本身。 */ pivot(x: number, y: number): Sprite; /** *

    设置宽高。相当于分别设置width和height属性。

    *

    因为返回值为Sprite对象本身,所以可以使用如下语法:spr.size(...).pos(...);

    * @param width 宽度值。 * @param hegiht 高度值。 * @return 返回对象本身。 */ size(width: number, height: number): Sprite; /** *

    设置缩放。相当于分别设置scaleX和scaleY属性。

    *

    因为返回值为Sprite对象本身,所以可以使用如下语法:spr.scale(...).pos(...);

    * @param scaleX X轴缩放比例。 * @param scaleY Y轴缩放比例。 * @param speedMode (可选)是否极速模式,正常是调用this.scaleX=value进行赋值,极速模式直接调用内部函数处理,如果未重写scaleX,scaleY属性,建议设置为急速模式性能更高。 * @return 返回对象本身。 */ scale(scaleX: number, scaleY: number, speedMode?: boolean): Sprite; /** *

    设置倾斜角度。相当于分别设置skewX和skewY属性。

    *

    因为返回值为Sprite对象本身,所以可以使用如下语法:spr.skew(...).pos(...);

    * @param skewX 水平倾斜角度。 * @param skewY 垂直倾斜角度。 * @return 返回对象本身 */ skew(skewX: number, skewY: number): Sprite; /** * 更新、呈现显示对象。由系统调用。 * @param context 渲染的上下文引用。 * @param x X轴坐标。 * @param y Y轴坐标。 */ render(context: RenderContext, x: number, y: number): void; /** *

    绘制 当前SpriteCanvas 上,并返回一个HtmlCanvas。

    *

    绘制的结果可以当作图片源,再次绘制到其他Sprite里面,示例:

    * * var htmlCanvas:HTMLCanvas = sprite.drawToCanvas(100, 100, 0, 0);//把精灵绘制到canvas上面 * var texture:Texture = new Texture(htmlCanvas);//使用htmlCanvas创建Texture * var sp:Sprite = new Sprite().pos(0, 200);//创建精灵并把它放倒200位置 * sp.graphics.drawTexture(texture);//把截图绘制到精灵上 * Laya.stage.addChild(sp);//把精灵显示到舞台 * *

    也可以获取原始图片数据,分享到网上,从而实现截图效果,示例:

    * * var htmlCanvas:HTMLCanvas = sprite.drawToCanvas(100, 100, 0, 0);//把精灵绘制到canvas上面 * * htmlCanvas.toBase64("image/png",0.92,function(base64) * trace(base64);//打印图片base64信息,可以发给服务器或者保存为图片 * }); * * @param canvasWidth 画布宽度。 * @param canvasHeight 画布高度。 * @param x 绘制的 X 轴偏移量。 * @param y 绘制的 Y 轴偏移量。 * @return HTMLCanvas 对象。 */ drawToCanvas(canvasWidth: number, canvasHeight: number, offsetX: number, offsetY: number): HTMLCanvas; /** *

    自定义更新、呈现显示对象。一般用来扩展渲染模式,请合理使用,可能会导致在加速器上无法渲染。

    *

    注意不要在此函数内增加或删除树节点,否则会对树节点遍历造成影响。

    * @param context 渲染的上下文引用。 * @param x X轴坐标。 * @param y Y轴坐标。 */ customRender(context: RenderContext, x: number, y: number): void; /** * @private * 应用滤镜。 */ _applyFilters(): void; /**滤镜集合。可以设置多个滤镜组合。*/ filters: Array; /** * @private * 查看当前原件中是否包含发光滤镜。 * @return 一个 Boolean 值,表示当前原件中是否包含发光滤镜。 */ _isHaveGlowFilter(): boolean; /** * 把本地坐标转换为相对stage的全局坐标。 * @param point 本地坐标点。 * @param createNewPoint (可选)是否创建一个新的Point对象作为返回值,默认为false,使用输入的point对象返回,减少对象创建开销。 * @return 转换后的坐标的点。 */ localToGlobal(point: Point, createNewPoint?: boolean): Point; /** * 把stage的全局坐标转换为本地坐标。 * @param point 全局坐标点。 * @param createNewPoint (可选)是否创建一个新的Point对象作为返回值,默认为false,使用输入的point对象返回,减少对象创建开销。 * @return 转换后的坐标的点。 */ globalToLocal(point: Point, createNewPoint?: boolean): Point; /** * 将本地坐标系坐标转转换到父容器坐标系。 * @param point 本地坐标点。 * @return 转换后的点。 */ toParentPoint(point: Point): Point; /** * 将父容器坐标系坐标转换到本地坐标系。 * @param point 父容器坐标点。 * @return 转换后的点。 */ fromParentPoint(point: Point): Point; /** *

    增加事件侦听器,以使侦听器能够接收事件通知。

    *

    如果侦听鼠标事件,则会自动设置自己和父亲节点的属性 mouseEnabled 的值为 true(如果父节点mouseEnabled=false,则停止设置父节点mouseEnabled属性)。

    * @param type 事件的类型。 * @param caller 事件侦听函数的执行域。 * @param listener 事件侦听函数。 * @param args (可选)事件侦听函数的回调参数。 * @return 此 EventDispatcher 对象。 */ on(type: string, caller: any, listener: Function, args?: Array): EventDispatcher; /** *

    增加事件侦听器,以使侦听器能够接收事件通知,此侦听事件响应一次后则自动移除侦听。

    *

    如果侦听鼠标事件,则会自动设置自己和父亲节点的属性 mouseEnabled 的值为 true(如果父节点mouseEnabled=false,则停止设置父节点mouseEnabled属性)。

    * @param type 事件的类型。 * @param caller 事件侦听函数的执行域。 * @param listener 事件侦听函数。 * @param args (可选)事件侦听函数的回调参数。 * @return 此 EventDispatcher 对象。 */ once(type: string, caller: any, listener: Function, args?: Array): EventDispatcher; parent: Node; /** *

    加载并显示一个图片。功能等同于graphics.loadImage方法。支持异步加载。

    *

    注意:多次调用loadImage绘制不同的图片,会同时显示。

    * @param url 图片地址。 * @param x (可选)显示图片的x位置。 * @param y (可选)显示图片的y位置。 * @param width (可选)显示图片的宽度,设置为0表示使用图片默认宽度。 * @param height (可选)显示图片的高度,设置为0表示使用图片默认高度。 * @param complete (可选)加载完成回调。 * @return 返回精灵对象本身。 */ loadImage(url: string, x?: number, y?: number, width?: number, height?: number, complete?: Handler): Sprite; /** * 根据图片地址创建一个新的 Sprite 对象用于加载并显示此图片。 * @param url 图片地址。 * @return 返回新的 Sprite 对象。 */ static fromImage(url: string): Sprite; /**cacheAs后,设置自己和父对象缓存失效。*/ repaint(): void; /** * @private * 获取是否重新缓存。 * @return 如果重新缓存值为 true,否则值为 false。 */ _needRepaint(): boolean; protected _childChanged(child?: Node): void; /**cacheAs时,设置所有父对象缓存失效。 */ parentRepaint(): void; /**对舞台 stage 的引用。*/ readonly stage: Stage; /** *

    可以设置一个Rectangle区域作为点击区域,或者设置一个HitArea实例作为点击区域,HitArea内可以设置可点击和不可点击区域。

    *

    如果不设置hitArea,则根据宽高形成的区域进行碰撞。

    */ hitArea: any; /** *

    遮罩,可以设置一个对象(支持位图和矢量图),根据对象形状进行遮罩显示。

    *

    【注意】遮罩对象坐标系是相对遮罩对象本身的,和Flash机制不同

    */ mask: Sprite; /** * 是否接受鼠标事件。 * 默认为false,如果监听鼠标事件,则会自动设置本对象及父节点的属性 mouseEnable 的值都为 true(如果父节点手动设置为false,则不会更改)。 * */ mouseEnabled: boolean; /** * 开始拖动此对象。 * @param area (可选)拖动区域,此区域为当前对象注册点活动区域(不包括对象宽高),可选。 * @param hasInertia (可选)鼠标松开后,是否还惯性滑动,默认为false,可选。 * @param elasticDistance (可选)橡皮筋效果的距离值,0为无橡皮筋效果,默认为0,可选。 * @param elasticBackTime (可选)橡皮筋回弹时间,单位为毫秒,默认为300毫秒,可选。 * @param data (可选)拖动事件携带的数据,可选。 * @param disableMouseEvent (可选)禁用其他对象的鼠标检测,默认为false,设置为true能提高性能。 * @param ratio (可选)惯性阻尼系数,影响惯性力度和时长。 */ startDrag(area?: Rectangle, hasInertia?: boolean, elasticDistance?: number, elasticBackTime?: number, data?: any, disableMouseEvent?: boolean, ratio?: number): void; /**停止拖动此对象。*/ stopDrag(): void; _setDisplay(value: boolean): void; /** * 检测某个点是否在此对象内。 * @param x 全局x坐标。 * @param y 全局y坐标。 * @return 表示是否在对象内。 */ hitTestPoint(x: number, y: number): boolean; /**获得相对于本对象上的鼠标坐标信息。*/ getMousePoint(): Point; /** * 获得相对于stage的全局X轴缩放值(会叠加父亲节点的缩放值)。 */ readonly globalScaleX: number; /** * 获得相对于stage的全局Y轴缩放值(会叠加父亲节点的缩放值)。 */ readonly globalScaleY: number; /** * 返回鼠标在此对象坐标系上的 X 轴坐标信息。 */ readonly mouseX: number; /** * 返回鼠标在此对象坐标系上的 Y 轴坐标信息。 */ readonly mouseY: number; /**z排序,更改此值,则会按照值的大小对同一容器的所有对象重新排序。值越大,越靠上。默认为0,则根据添加顺序排序。*/ zOrder: number; /**设置一个Texture实例,并显示此图片(如果之前有其他绘制,则会被清除掉)。等同于graphics.clear();graphics.drawTexture()*/ texture: Texture; _getWords(): Array; _addChildsToLayout(out: Array): boolean; _addToLayout(out: Array): void; _isChar(): boolean; _getCSSStyle(): CSSStyle; /** * @private * 设置指定属性名的属性值。 * @param name 属性名。 * @param value 属性值。 */ _setAttributes(name: string, value: string): void; /** * @private */ _layoutLater(): void; } } declare module laya.display { import Matrix = laya.maths.Matrix; import Point = laya.maths.Point; import RenderContext = laya.renders.RenderContext; /** *

    Stage 是舞台类,显示列表的根节点,所有显示对象都在舞台上显示。通过 Laya.stage 单例访问。

    *

    Stage提供几种适配模式,不同的适配模式会产生不同的画布大小,画布越大,渲染压力越大,所以要选择合适的适配方案。

    *

    Stage提供不同的帧率模式,帧率越高,渲染压力越大,越费电,合理使用帧率甚至动态更改帧率有利于改进手机耗电。

    */ class Stage extends Sprite { /**应用保持设计宽高不变,不缩放不变型,stage的宽高等于设计宽高。*/ static SCALE_NOSCALE: string; /**应用根据屏幕大小铺满全屏,非等比缩放会变型,stage的宽高等于设计宽高。*/ static SCALE_EXACTFIT: string; /**应用显示全部内容,按照最小比率缩放,等比缩放不变型,一边可能会留空白,stage的宽高等于设计宽高。*/ static SCALE_SHOWALL: string; /**应用按照最大比率缩放显示,宽或高方向会显示一部分,等比缩放不变型,stage的宽高等于设计宽高。*/ static SCALE_NOBORDER: string; /**应用保持设计宽高不变,不缩放不变型,stage的宽高等于屏幕宽高。*/ static SCALE_FULL: string; /**应用保持设计宽度不变,高度根据屏幕比缩放,stage的宽度等于设计高度,高度根据屏幕比率大小而变化*/ static SCALE_FIXED_WIDTH: string; /**应用保持设计高度不变,宽度根据屏幕比缩放,stage的高度等于设计宽度,宽度根据屏幕比率大小而变化*/ static SCALE_FIXED_HEIGHT: string; /**应用保持设计比例不变,全屏显示全部内容(类似showall,但showall非全屏,会有黑边),根据屏幕长宽比,自动选择使用SCALE_FIXED_WIDTH或SCALE_FIXED_HEIGHT*/ static SCALE_FIXED_AUTO: string; /**画布水平居左对齐。*/ static ALIGN_LEFT: string; /**画布水平居右对齐。*/ static ALIGN_RIGHT: string; /**画布水平居中对齐。*/ static ALIGN_CENTER: string; /**画布垂直居上对齐。*/ static ALIGN_TOP: string; /**画布垂直居中对齐。*/ static ALIGN_MIDDLE: string; /**画布垂直居下对齐。*/ static ALIGN_BOTTOM: string; /**不更改屏幕。*/ static SCREEN_NONE: string; /**自动横屏。*/ static SCREEN_HORIZONTAL: string; /**自动竖屏。*/ static SCREEN_VERTICAL: string; /**全速模式,以60的帧率运行。*/ static FRAME_FAST: string; /**慢速模式,以30的帧率运行。*/ static FRAME_SLOW: string; /**自动模式,以30的帧率运行,但鼠标活动后会自动加速到60,鼠标不动2秒后降低为30帧,以节省消耗。*/ static FRAME_MOUSE: string; /**休眠模式,以1的帧率运行*/ static FRAME_SLEEP: string; /**当前焦点对象,此对象会影响当前键盘事件的派发主体。*/ focus: Node; offset: Point; /**设计宽度(初始化时设置的宽度Laya.init(width,height))*/ designWidth: number; /**设计高度(初始化时设置的高度Laya.init(width,height))*/ designHeight: number; /**画布是否发生翻转。*/ canvasRotation: boolean; /**画布的旋转角度。*/ canvasDegree: number; /**使用物理分辨率模式 */ useRetinalCanvas:boolean; /** *

    设置是否渲染,设置为false,可以停止渲染,画面会停留到最后一次渲染上,减少cpu消耗,此设置不影响时钟。

    *

    比如非激活状态,可以设置renderingEnabled=true以节省消耗。

    * */ renderingEnabled: boolean; /**是否启用屏幕适配,可以适配后,在某个时候关闭屏幕适配,防止某些操作导致的屏幕以外改变*/ screenAdaptationEnabled: boolean; _canvasTransform: Matrix; _scenes: Array; static _wgColor: Array; static FRAME_MOUSE_THREDHOLD: number; /**场景类,引擎中只有一个stage实例,此实例可以通过Laya.stage访问。*/ constructor(); /**帧率类型,支持三种模式:fast-60帧(默认),slow-30帧,mouse-30帧(鼠标活动后会自动加速到60,鼠标不动2秒后降低为30帧,以节省消耗),sleep-1帧。*/ frameRate: string; width: number; height: number; readonly transform: Matrix; readonly desginWidth: number; readonly desginHeight: number; /** * 舞台是否获得焦点。 */ readonly isFocused: boolean; /** * 舞台是否处于可见状态(是否进入后台)。 */ readonly isVisibility: boolean; protected _resetCanvas(): void; /** * 设置屏幕大小,场景会根据屏幕大小进行适配。可以动态调用此方法,来更改游戏显示的大小。 * @param screenWidth 屏幕宽度。 * @param screenHeight 屏幕高度。 */ setScreenSize(screenWidth: number, screenHeight: number): void; /** *

    缩放模式。默认值为 "noscale"。

    *

      取值范围: *
    • "noscale" :不缩放;
    • *
    • "exactfit" :全屏不等比缩放;
    • *
    • "showall" :最小比例缩放;
    • *
    • "noborder" :最大比例缩放;
    • *
    • "full" :不缩放,stage的宽高等于屏幕宽高;
    • *
    • "fixedwidth" :宽度不变,高度根据屏幕比缩放;
    • *
    • "fixedheight" :高度不变,宽度根据屏幕比缩放;
    • *
    • "fixedauto" :根据宽高比,自动选择使用fixedwidth或fixedheight;
    • *

    */ scaleMode: string; /** *

    水平对齐方式。默认值为"left"。

    *

      取值范围: *
    • "left" :居左对齐;
    • *
    • "center" :居中对齐;
    • *
    • "right" :居右对齐;
    • *

    */ alignH: string; /** *

    垂直对齐方式。默认值为"top"。

    *

      取值范围: *
    • "top" :居顶部对齐;
    • *
    • "middle" :居中对齐;
    • *
    • "bottom" :居底部对齐;
    • *

    */ alignV: string; /**舞台的背景颜色,默认为黑色,null为透明。*/ bgColor: string; /**鼠标在 Stage 上的 X 轴坐标。*/ readonly mouseX: number; /**鼠标在 Stage 上的 Y 轴坐标。*/ readonly mouseY: number; /**@inheritDoc */ getMousePoint(): Point; /**当前视窗由缩放模式导致的 X 轴缩放系数。*/ readonly clientScaleX: number; /**当前视窗由缩放模式导致的 Y 轴缩放系数。*/ readonly clientScaleY: number; /** *

    场景布局类型。

    *

      取值范围: *
    • "none" :不更改屏幕
    • *
    • "horizontal" :自动横屏
    • *
    • "vertical" :自动竖屏
    • *

    */ screenMode: string; /**@inheritDoc */ repaint(): void; /**@inheritDoc */ parentRepaint(): void; _loop(): boolean; /** *

    获得距当前帧开始后,过了多少时间,单位为毫秒。

    *

    可以用来判断函数内时间消耗,通过合理控制每帧函数处理消耗时长,避免一帧做事情太多,对复杂计算分帧处理,能有效降低帧率波动。

    */ getTimeFromFrameStart(): number; visible: boolean; /**@inheritDoc */ render(context: RenderContext, x: number, y: number): void; /** *

    是否开启全屏,用户点击后进入全屏。

    *

    兼容性提示:部分浏览器不允许点击进入全屏,比如Iphone等。

    */ fullScreenEnabled: boolean; /**退出全屏模式*/ exitFullscreen(): void; } } declare module laya.display { import CSSStyle = laya.display.css.CSSStyle; import Point = laya.maths.Point; import Rectangle = laya.maths.Rectangle; /** *

    Text 类用于创建显示对象以显示文本。

    *

    * 注意:如果运行时系统找不到设定的字体,则用系统默认的字体渲染文字,从而导致显示异常。(通常电脑上显示正常,在一些移动端因缺少设置的字体而显示异常)。 *

    * @example * package * { * import laya.display.Text; * public class Text_Example * { * public function Text_Example() * { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * onInit(); * } * private function onInit():void * { * var text:Text = new Text();//创建一个 Text 类的实例对象 text 。 * text.text = "这个是一个 Text 文本示例。"; * text.color = "#008fff";//设置 text 的文本颜色。 * text.font = "Arial";//设置 text 的文本字体。 * text.bold = true;//设置 text 的文本显示为粗体。 * text.fontSize = 30;//设置 text 的字体大小。 * text.wordWrap = true;//设置 text 的文本自动换行。 * text.x = 100;//设置 text 对象的属性 x 的值,用于控制 text 对象的显示位置。 * text.y = 100;//设置 text 对象的属性 y 的值,用于控制 text 对象的显示位置。 * text.width = 300;//设置 text 的宽度。 * text.height = 200;//设置 text 的高度。 * text.italic = true;//设置 text 的文本显示为斜体。 * text.borderColor = "#fff000";//设置 text 的文本边框颜色。 * Laya.stage.addChild(text);//将 text 添加到显示列表。 * } * } * } * @example * Text_Example(); * function Text_Example() * { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * onInit(); * } * function onInit() * { * var text = new laya.display.Text();//创建一个 Text 类的实例对象 text 。 * text.text = "这个是一个 Text 文本示例。"; * text.color = "#008fff";//设置 text 的文本颜色。 * text.font = "Arial";//设置 text 的文本字体。 * text.bold = true;//设置 text 的文本显示为粗体。 * text.fontSize = 30;//设置 text 的字体大小。 * text.wordWrap = true;//设置 text 的文本自动换行。 * text.x = 100;//设置 text 对象的属性 x 的值,用于控制 text 对象的显示位置。 * text.y = 100;//设置 text 对象的属性 y 的值,用于控制 text 对象的显示位置。 * text.width = 300;//设置 text 的宽度。 * text.height = 200;//设置 text 的高度。 * text.italic = true;//设置 text 的文本显示为斜体。 * text.borderColor = "#fff000";//设置 text 的文本边框颜色。 * Laya.stage.addChild(text);//将 text 添加到显示列表。 * } * @example * class Text_Example { * constructor() { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * this.onInit(); * } * private onInit(): void { * var text: laya.display.Text = new laya.display.Text();//创建一个 Text 类的实例对象 text 。 * text.text = "这个是一个 Text 文本示例。"; * text.color = "#008fff";//设置 text 的文本颜色。 * text.font = "Arial";//设置 text 的文本字体。 * text.bold = true;//设置 text 的文本显示为粗体。 * text.fontSize = 30;//设置 text 的字体大小。 * text.wordWrap = true;//设置 text 的文本自动换行。 * text.x = 100;//设置 text 对象的属性 x 的值,用于控制 text 对象的显示位置。 * text.y = 100;//设置 text 对象的属性 y 的值,用于控制 text 对象的显示位置。 * text.width = 300;//设置 text 的宽度。 * text.height = 200;//设置 text 的高度。 * text.italic = true;//设置 text 的文本显示为斜体。 * text.borderColor = "#fff000";//设置 text 的文本边框颜色。 * Laya.stage.addChild(text);//将 text 添加到显示列表。 * } * } */ class Text extends Sprite { static _testWord: string; /**语言包*/ static langPacks: any; /**visible不进行任何裁切。*/ static VISIBLE: string; /**scroll 不显示文本域外的字符像素,并且支持 scroll 接口。*/ static SCROLL: string; /**hidden 不显示超出文本域的字符。*/ static HIDDEN: string; /** * WebGL渲染文字时是否启用字符缓存,对于字形多的语种,禁用缓存。
    * 对于字形随字母组合变化的语种,如阿拉伯文,启用将使显示错误。但是即使禁用,自动换行也会在错误的地方截断。 */ static CharacterCache: boolean; /**是否是从右向左的显示顺序*/ static RightToLeft: boolean; protected _text: string; protected _isChanged: boolean; protected _textWidth: number; protected _textHeight: number; protected _lines: Array; protected _lineWidths: Array; protected _startX: number; protected _startY: number; protected _lastVisibleLineIndex: number; protected _words: Array; protected _charSize: any; protected static _fontFamilyMap: any; /** *

    overflow 指定文本超出文本域后的行为。其值为"hidden"、"visible"和"scroll"之一。

    *

    性能从高到低依次为:hidden > visible > scroll。

    */ overflow: string; /** * 是否显示下划线。 */ underline: boolean; /** * 创建一个新的 Text 实例。 */ constructor(); /** * 注册位图字体。 * @param name 位图字体的名称。 * @param bitmapFont 位图字体文件。 */ static registerBitmapFont(name: string, bitmapFont: BitmapFont): void; /** * 移除注册的位图字体文件。 * @param name 位图字体的名称。 * @param destroy 是否销毁指定的字体文件。 */ static unregisterBitmapFont(name: string, destroy?: boolean): void; /** * 设置文字排版模式为右到左。 */ static setTextRightToLeft(): void; /**@inheritDoc */ destroy(destroyChild?: boolean): void; /** * @private * @inheritDoc */ _getBoundPointsM(ifRotate?: boolean): Array; /** * @inheritDoc */ getGraphicBounds(realSize?: boolean): Rectangle; /** * @inheritDoc */ width: number; /** * @private * @inheritDoc */ _getCSSStyle(): CSSStyle; /** * @inheritDoc */ height: number; /** * 表示文本的宽度,以像素为单位。 */ readonly textWidth: number; /** * 表示文本的高度,以像素为单位。 */ readonly textHeight: number; /** 当前文本的内容字符串。*/ text: string; /** *

    根据指定的文本,从语言包中取当前语言的文本内容。并对此文本中的 *

    设置Text.langPacks语言包后,即可使用lang获取里面的语言

    *

    例如: *

  • (1)text 的值为“我的名字”,先取到这个文本对应的当前语言版本里的值“My name”,将“My name”设置为当前文本的内容。
  • *
  • (2)text 的值为“恭喜你赢得 * 则先取到这个文本对应的当前语言版本里的值“Congratulations on your winning * 然后将文本里的 * 将替换处理后的文本“Congratulations on your winning 100 diamonds, 200 experience.”设置为当前文本的内容。 *
  • *

    * @param text 文本内容。 * @param ...args 文本替换参数。 */ lang(text: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any, arg9?: any, arg10?: any): void; /** *

    文本的字体名称,以字符串形式表示。

    *

    默认值为:"Arial",可以通过Font.defaultFont设置默认字体。

    *

    如果运行时系统找不到设定的字体,则用系统默认的字体渲染文字,从而导致显示异常。(通常电脑上显示正常,在一些移动端因缺少设置的字体而显示异常)。

    * @see laya.display.css.Font#defaultFamily */ font: string; /** *

    指定文本的字体大小(以像素为单位)。

    *

    默认为20像素,可以通过 Text.defaultSize 设置默认大小。

    */ fontSize: number; /** *

    指定文本是否为粗体字。

    *

    默认值为 false,这意味着不使用粗体字。如果值为 true,则文本为粗体字。

    */ bold: boolean; /** *

    表示文本的颜色值。可以通过 Text.defaultColor 设置默认颜色。

    *

    默认值为黑色。

    */ color: string; /** *

    表示使用此文本格式的文本是否为斜体。

    *

    默认值为 false,这意味着不使用斜体。如果值为 true,则文本为斜体。

    */ italic: boolean; /** *

    表示文本的水平显示方式。

    *

    取值: *

  • "left": 居左对齐显示。
  • *
  • "center": 居中对齐显示。
  • *
  • "right": 居右对齐显示。
  • *

    */ align: string; /** *

    表示文本的垂直显示方式。

    *

    取值: *

  • "top": 居顶部对齐显示。
  • *
  • "middle": 居中对齐显示。
  • *
  • "bottom": 居底部对齐显示。
  • *

    */ valign: string; /** *

    表示文本是否自动换行,默认为false。

    *

    若值为true,则自动换行;否则不自动换行。

    */ wordWrap: boolean; /** * 垂直行间距(以像素为单位)。 */ leading: number; /** *

    边距信息。

    *

    数据格式:[上边距,右边距,下边距,左边距](边距以像素为单位)。

    */ padding: Array; /** * 文本背景颜色,以字符串表示。 */ bgColor: string; /** * 文本边框背景颜色,以字符串表示。 */ borderColor: string; /** *

    描边宽度(以像素为单位)。

    *

    默认值0,表示不描边。

    */ stroke: number; /** *

    描边颜色,以字符串表示。

    *

    默认值为 "#000000"(黑色);

    */ strokeColor: string; protected isChanged: boolean; protected _isPassWordMode(): boolean; protected _getPassWordTxt(txt: string): string; protected renderText(begin: number, visibleLineCount: number): void; /** *

    排版文本。

    *

    进行宽高计算,渲染、重绘文本。

    */ typeset(): void; /** *

    快速更改显示文本。不进行排版计算,效率较高。

    *

    如果只更改文字内容,不更改文字样式,建议使用此接口,能提高效率。

    * @param text 文本内容。 */ changeText(text: string): void; protected parseLines(text: string): void; protected parseLine(line: string, wordWrapWidth: number): void; /** * 返回字符在本类实例的父坐标系下的坐标。 * @param charIndex 索引位置。 * @param out (可选)输出的Point引用。 * @return Point 字符在本类实例的父坐标系下的坐标。如果out参数不为空,则将结果赋值给指定的Point对象,否则创建一个新的Point对象返回。建议使用Point.TEMP作为out参数,可以省去Point对象创建和垃圾回收的开销,尤其是在需要频繁执行的逻辑中,比如帧循环和MOUSE_MOVE事件回调函数里面。 */ getCharPoint(charIndex: number, out?: Point): Point; /** * 获取横向滚动量。 */ /** *

    设置横向滚动量。

    *

    即使设置超出滚动范围的值,也会被自动限制在可能的最大值处。

    */ scrollX: number; /** * 获取纵向滚动量。 */ /** * 设置纵向滚动量(px)。即使设置超出滚动范围的值,也会被自动限制在可能的最大值处。 */ scrollY: number; /** * 获取横向可滚动最大值。 */ readonly maxScrollX: number; /** * 获取纵向可滚动最大值。 */ readonly maxScrollY: number; readonly lines: Array; underlineColor: string; /** * 判断系统是否支持指定的font。 * * @param font 对font进行支持测试 * @return true表示系统支持 */ static supportFont(font: string): boolean; } } declare module laya.events { import Sprite = laya.display.Sprite; /** * Event 是事件类型的集合。一般当发生事件时,Event 对象将作为参数传递给事件侦听器。 */ class Event { /** 一个空的 Event 对象。用于事件派发中转使用。*/ static EMPTY: Event; /** 定义 mousedown 事件对象的 type 属性值。*/ static MOUSE_DOWN: string; /** 定义 mouseup 事件对象的 type 属性值。*/ static MOUSE_UP: string; /** 定义 click 事件对象的 type 属性值。*/ static CLICK: string; /** 定义 rightmousedown 事件对象的 type 属性值。*/ static RIGHT_MOUSE_DOWN: string; /** 定义 rightmouseup 事件对象的 type 属性值。*/ static RIGHT_MOUSE_UP: string; /** 定义 rightclick 事件对象的 type 属性值。*/ static RIGHT_CLICK: string; /** 定义 mousemove 事件对象的 type 属性值。*/ static MOUSE_MOVE: string; /** 定义 mouseover 事件对象的 type 属性值。*/ static MOUSE_OVER: string; /** 定义 mouseout 事件对象的 type 属性值。*/ static MOUSE_OUT: string; /** 定义 mousewheel 事件对象的 type 属性值。*/ static MOUSE_WHEEL: string; /** 定义 mouseover 事件对象的 type 属性值。*/ static ROLL_OVER: string; /** 定义 mouseout 事件对象的 type 属性值。*/ static ROLL_OUT: string; /** 定义 doubleclick 事件对象的 type 属性值。*/ static DOUBLE_CLICK: string; /** 定义 change 事件对象的 type 属性值。*/ static CHANGE: string; /** 定义 changed 事件对象的 type 属性值。*/ static CHANGED: string; /** 定义 resize 事件对象的 type 属性值。*/ static RESIZE: string; /** 定义 added 事件对象的 type 属性值。*/ static ADDED: string; /** 定义 removed 事件对象的 type 属性值。*/ static REMOVED: string; /** 定义 display 事件对象的 type 属性值。*/ static DISPLAY: string; /** 定义 undisplay 事件对象的 type 属性值。*/ static UNDISPLAY: string; /** 定义 error 事件对象的 type 属性值。*/ static ERROR: string; /** 定义 complete 事件对象的 type 属性值。*/ static COMPLETE: string; /** 定义 loaded 事件对象的 type 属性值。*/ static LOADED: string; /** 定义 progress 事件对象的 type 属性值。*/ static PROGRESS: string; /** 定义 input 事件对象的 type 属性值。*/ static INPUT: string; /** 定义 render 事件对象的 type 属性值。*/ static RENDER: string; /** 定义 open 事件对象的 type 属性值。*/ static OPEN: string; /** 定义 message 事件对象的 type 属性值。*/ static MESSAGE: string; /** 定义 close 事件对象的 type 属性值。*/ static CLOSE: string; /** 定义 keydown 事件对象的 type 属性值。*/ static KEY_DOWN: string; /** 定义 keypress 事件对象的 type 属性值。*/ static KEY_PRESS: string; /** 定义 keyup 事件对象的 type 属性值。*/ static KEY_UP: string; /** 定义 frame 事件对象的 type 属性值。*/ static FRAME: string; /** 定义 dragstart 事件对象的 type 属性值。*/ static DRAG_START: string; /** 定义 dragmove 事件对象的 type 属性值。*/ static DRAG_MOVE: string; /** 定义 dragend 事件对象的 type 属性值。*/ static DRAG_END: string; /** 定义 enter 事件对象的 type 属性值。*/ static ENTER: string; /** 定义 select 事件对象的 type 属性值。*/ static SELECT: string; /** 定义 blur 事件对象的 type 属性值。*/ static BLUR: string; /** 定义 focus 事件对象的 type 属性值。*/ static FOCUS: string; /** 定义 visibilitychange 事件对象的 type 属性值。*/ static VISIBILITY_CHANGE: string; /** 定义 focuschange 事件对象的 type 属性值。*/ static FOCUS_CHANGE: string; /** 定义 played 事件对象的 type 属性值。*/ static PLAYED: string; /** 定义 paused 事件对象的 type 属性值。*/ static PAUSED: string; /** 定义 stopped 事件对象的 type 属性值。*/ static STOPPED: string; /** 定义 start 事件对象的 type 属性值。*/ static START: string; /** 定义 end 事件对象的 type 属性值。*/ static END: string; /** 定义 enablechanged 事件对象的 type 属性值。*/ static ENABLE_CHANGED: string; /** 定义 activeinhierarchychanged 事件对象的 type 属性值。*/ static ACTIVE_IN_HIERARCHY_CHANGED: string; /** 定义 componentadded 事件对象的 type 属性值。*/ static COMPONENT_ADDED: string; /** 定义 componentremoved 事件对象的 type 属性值。*/ static COMPONENT_REMOVED: string; /** 定义 layerchanged 事件对象的 type 属性值。*/ static LAYER_CHANGED: string; /** 定义 hierarchyloaded 事件对象的 type 属性值。*/ static HIERARCHY_LOADED: string; /** 定义 recovered 事件对象的 type 属性值。*/ static RECOVERED: string; /** 定义 released 事件对象的 type 属性值。*/ static RELEASED: string; /** 定义 link 事件对象的 type 属性值。*/ static LINK: string; /** 定义 label 事件对象的 type 属性值。*/ static LABEL: string; /**浏览器全屏更改时触发*/ static FULL_SCREEN_CHANGE: string; /**显卡设备丢失时触发*/ static DEVICE_LOST: string; /**模型更换时触发*/ static MESH_CHANGED: string; /**材质更换时触发*/ static MATERIAL_CHANGED: string; /**世界矩阵更新时触发。*/ static WORLDMATRIX_NEEDCHANGE: string; /**更换动作时触发。*/ static ANIMATION_CHANGED: string; /**进入触发器时触发。*/ static TRIGGER_ENTER: string; /**保持触发器时触发。*/ static TRIGGER_STAY: string; /**退出触发器时触发。*/ static TRIGGER_EXIT: string; /**拖尾渲染节点改变时触发。*/ static TRAIL_FILTER_CHANGE: string; /**多米诺渲染节点改变时触发。*/ static DOMINO_FILTER_CHANGE: string; /** 事件类型。*/ type: string; /** 原生浏览器事件。*/ nativeEvent: any; /** 事件目标触发对象。*/ target: Sprite; /** 事件当前冒泡对象。*/ currentTarget: Sprite; _stoped: boolean; /** 分配给触摸点的唯一标识号(作为 int)。*/ touchId: number; /**键盘值*/ keyCode: number; /**滚轮滑动增量*/ delta: number; /** * 设置事件数据。 * @param type 事件类型。 * @param currentTarget 事件目标触发对象。 * @param target 事件当前冒泡对象。 * @return 返回当前 Event 对象。 */ setTo(type: string, currentTarget: Sprite, target: Sprite): Event; /** * 阻止对事件流中当前节点的后续节点中的所有事件侦听器进行处理。此方法不会影响当前节点 (currentTarget) 中的任何事件侦听器。 */ stopPropagation(): void; /** * 触摸点列表。 */ readonly touches: Array; /** * 表示 Alt 键是处于活动状态 (true) 还是非活动状态 (false)。 */ readonly altKey: boolean; /** * 表示 Ctrl 键是处于活动状态 (true) 还是非活动状态 (false)。 */ readonly ctrlKey: boolean; /** * 表示 Shift 键是处于活动状态 (true) 还是非活动状态 (false)。 */ readonly shiftKey: boolean; /** * 包含按下或释放的键的字符代码值。字符代码值为英文键盘值。 */ readonly charCode: boolean; /** * 表示键在键盘上的位置。这对于区分在键盘上多次出现的键非常有用。
    * 例如,您可以根据此属性的值来区分左 Shift 键和右 Shift 键:左 Shift 键的值为 KeyLocation.LEFT,右 Shift 键的值为 KeyLocation.RIGHT。另一个示例是区分标准键盘 (KeyLocation.STANDARD) 与数字键盘 (KeyLocation.NUM_PAD) 上按下的数字键。 */ readonly keyLocation: number; /**鼠标在 Stage 上的 X 轴坐标*/ readonly stageX: number; /**鼠标在 Stage 上的 Y 轴坐标*/ readonly stageY: number; } } declare module laya.events { import Handler = laya.utils.Handler; /** * EventDispatcher 类是可调度事件的所有类的基类。 */ class EventDispatcher { static MOUSE_EVENTS: any; /** * 检查 EventDispatcher 对象是否为特定事件类型注册了任何侦听器。 * @param type 事件的类型。 * @return 如果指定类型的侦听器已注册,则值为 true;否则,值为 false。 */ hasListener(type: string): boolean; /** * 派发事件。 * @param type 事件类型。 * @param data (可选)回调数据。注意:如果是需要传递多个参数 p1,p2,p3,...可以使用数组结构如:[p1,p2,p3,...] ;如果需要回调单个参数 p ,且 p 是一个数组,则需要使用结构如:[p],其他的单个参数 p ,可以直接传入参数 p。 * @return 此事件类型是否有侦听者,如果有侦听者则值为 true,否则值为 false。 */ event(type: string, data?: any): boolean; /** * 使用 EventDispatcher 对象注册指定类型的事件侦听器对象,以使侦听器能够接收事件通知。 * @param type 事件的类型。 * @param caller 事件侦听函数的执行域。 * @param listener 事件侦听函数。 * @param args (可选)事件侦听函数的回调参数。 * @return 此 EventDispatcher 对象。 */ on(type: string, caller: any, listener: Function, args?: Array): EventDispatcher; /** * 使用 EventDispatcher 对象注册指定类型的事件侦听器对象,以使侦听器能够接收事件通知,此侦听事件响应一次后自动移除。 * @param type 事件的类型。 * @param caller 事件侦听函数的执行域。 * @param listener 事件侦听函数。 * @param args (可选)事件侦听函数的回调参数。 * @return 此 EventDispatcher 对象。 */ once(type: string, caller: any, listener: Function, args?: Array): EventDispatcher; _createListener(type: string, caller: any, listener: Function, args: Array, once: boolean, offBefore?: boolean): EventDispatcher; /** * 从 EventDispatcher 对象中删除侦听器。 * @param type 事件的类型。 * @param caller 事件侦听函数的执行域。 * @param listener 事件侦听函数。 * @param onceOnly (可选)如果值为 true ,则只移除通过 once 方法添加的侦听器。 * @return 此 EventDispatcher 对象。 */ off(type: string, caller: any, listener: Function, onceOnly?: boolean): EventDispatcher; /** * 从 EventDispatcher 对象中删除指定事件类型的所有侦听器。 * @param type (可选)事件类型,如果值为 null,则移除本对象所有类型的侦听器。 * @return 此 EventDispatcher 对象。 */ offAll(type?: string): EventDispatcher; /** * 检测指定事件类型是否是鼠标事件。 * @param type 事件的类型。 * @return 如果是鼠标事件,则值为 true;否则,值为 false。 */ isMouseEvent(type: string): boolean; } class EventHandler extends Handler { EventHandler(caller: any, method: Function, args: Array, once: boolean): any; recover(): void; /** * 从对象池内创建一个Handler,默认会执行一次回收,如果不需要自动回收,设置once参数为false。 * @param caller 执行域(this)。 * @param method 回调方法。 * @param args (可选)携带的参数。 * @param once (可选)是否只执行一次,如果为true,回调后执行recover()进行回收,默认为true。 * @return 返回创建的handler实例。 */ static create(caller: any, method: Function, args?: Array, once?: boolean): Handler; } } declare module laya.events { /** * Keyboard 类的属性是一些常数,这些常数表示控制游戏时最常用的键。 */ class Keyboard { /** 与 0 的键控代码值(48)关联的常数。*/ static NUMBER_0: number; /** 与 1 的键控代码值(49)关联的常数。*/ static NUMBER_1: number; /** 与 2 的键控代码值(50)关联的常数。*/ static NUMBER_2: number; /** 与 3 的键控代码值(51)关联的常数。*/ static NUMBER_3: number; /** 与 4 的键控代码值(52)关联的常数。*/ static NUMBER_4: number; /** 与 5 的键控代码值(53)关联的常数。*/ static NUMBER_5: number; /** 与 6 的键控代码值(54)关联的常数。*/ static NUMBER_6: number; /** 与 7 的键控代码值(55)关联的常数。*/ static NUMBER_7: number; /** 与 8 的键控代码值(56)关联的常数。*/ static NUMBER_8: number; /** 与 9 的键控代码值(57)关联的常数。*/ static NUMBER_9: number; /** 与 A 键的键控代码值(65)关联的常数。*/ static A: number; /** 与 B 键的键控代码值(66)关联的常数。*/ static B: number; /** 与 C 键的键控代码值(67)关联的常数。*/ static C: number; /** 与 D 键的键控代码值(68)关联的常数。*/ static D: number; /** 与 E 键的键控代码值(69)关联的常数。*/ static E: number; /** 与 F 键的键控代码值(70)关联的常数。*/ static F: number; /** 与 G 键的键控代码值(71)关联的常数。*/ static G: number; /** 与 H 键的键控代码值(72)关联的常数。*/ static H: number; /** 与 I 键的键控代码值(73)关联的常数。*/ static I: number; /** 与 J 键的键控代码值(74)关联的常数。*/ static J: number; /** 与 K 键的键控代码值(75)关联的常数。*/ static K: number; /** 与 L 键的键控代码值(76)关联的常数。*/ static L: number; /** 与 M 键的键控代码值(77)关联的常数。*/ static M: number; /** 与 N 键的键控代码值(78)关联的常数。*/ static N: number; /** 与 O 键的键控代码值(79)关联的常数。*/ static O: number; /** 与 P 键的键控代码值(80)关联的常数。*/ static P: number; /** 与 Q 键的键控代码值(81)关联的常数。*/ static Q: number; /** 与 R 键的键控代码值(82)关联的常数。*/ static R: number; /** 与 S 键的键控代码值(83)关联的常数。*/ static S: number; /** 与 T 键的键控代码值(84)关联的常数。*/ static T: number; /** 与 U 键的键控代码值(85)关联的常数。*/ static U: number; /** 与 V 键的键控代码值(86)关联的常数。*/ static V: number; /** 与 W 键的键控代码值(87)关联的常数。*/ static W: number; /** 与 X 键的键控代码值(88)关联的常数。*/ static X: number; /** 与 Y 键的键控代码值(89)关联的常数。*/ static Y: number; /** 与 Z 键的键控代码值(90)关联的常数。*/ static Z: number; /** 与 F1 的键控代码值(112)关联的常数。*/ static F1: number; /** 与 F2 的键控代码值(113)关联的常数。*/ static F2: number; /** 与 F3 的键控代码值(114)关联的常数。*/ static F3: number; /** 与 F4 的键控代码值(115)关联的常数。*/ static F4: number; /** 与 F5 的键控代码值(116)关联的常数。*/ static F5: number; /** 与 F6 的键控代码值(117)关联的常数。*/ static F6: number; /** 与 F7 的键控代码值(118)关联的常数。*/ static F7: number; /** 与 F8 的键控代码值(119)关联的常数。*/ static F8: number; /** 与 F9 的键控代码值(120)关联的常数。*/ static F9: number; /** 与 F10 的键控代码值(121)关联的常数。*/ static F10: number; /** 与 F11 的键控代码值(122)关联的常数。*/ static F11: number; /** 与 F12 的键控代码值(123)关联的常数。*/ static F12: number; /** 与 F13 的键控代码值(124)关联的常数。*/ static F13: number; /** 与 F14 的键控代码值(125)关联的常数。*/ static F14: number; /** 与 F15 的键控代码值(126)关联的常数。*/ static F15: number; /** 与数字键盘的伪键控代码(21)关联的常数。*/ static NUMPAD: number; /** 与数字键盘上的数字 0 的键控代码值(96)关联的常数。*/ static NUMPAD_0: number; /** 与数字键盘上的数字 1 的键控代码值(97)关联的常数。*/ static NUMPAD_1: number; /** 与数字键盘上的数字 2 的键控代码值(98)关联的常数。*/ static NUMPAD_2: number; /** 与数字键盘上的数字 3 的键控代码值(99)关联的常数。*/ static NUMPAD_3: number; /** 与数字键盘上的数字 4 的键控代码值(100)关联的常数。*/ static NUMPAD_4: number; /** 与数字键盘上的数字 5 的键控代码值(101)关联的常数。*/ static NUMPAD_5: number; /** 与数字键盘上的数字 6 的键控代码值(102)关联的常数。*/ static NUMPAD_6: number; /** 与数字键盘上的数字 7 的键控代码值(103)关联的常数。*/ static NUMPAD_7: number; /** 与数字键盘上的数字 8 的键控代码值(104)关联的常数。*/ static NUMPAD_8: number; /** 与数字键盘上的数字 9 的键控代码值(105)关联的常数。*/ static NUMPAD_9: number; /** 与数字键盘上的加号(+)的键控代码值(107)关联的常数。*/ static NUMPAD_ADD: number; /** 与数字键盘上的小数点(.)的键控代码值(110)关联的常数。*/ static NUMPAD_DECIMAL: number; /** 与数字键盘上的除号(/)的键控代码值(111)关联的常数。*/ static NUMPAD_DIVIDE: number; /** 与数字键盘上的 Enter 的键控代码值(108)关联的常数。*/ static NUMPAD_ENTER: number; /** 与数字键盘上的乘号(*)的键控代码值(106)关联的常数。*/ static NUMPAD_MULTIPLY: number; /** 与数字键盘上的减号(-)的键控代码值(109)关联的常数。*/ static NUMPAD_SUBTRACT: number; /** 与 ; 键的键控代码值(186)关联的常数。*/ static SEMICOLON: number; /** 与=键的键控代码值(187)关联的常数。*/ static EQUAL: number; /** 与 F15 的键控代码值(188)关联的常数。*/ static COMMA: number; /** 与 - 键的键控代码值(189)关联的常数。*/ static MINUS: number; /** 与 . 键的键控代码值(190)关联的常数。*/ static PERIOD: number; /** 与 / 键的键控代码值(191)关联的常数。*/ static SLASH: number; /** 与 ` 键的键控代码值(192)关联的常数。*/ static BACKQUOTE: number; /** 与 [ 键的键控代码值(219)关联的常数。*/ static LEFTBRACKET: number; /** 与 \ 键的键控代码值(220)关联的常数。*/ static BACKSLASH: number; /** 与 ] 键的键控代码值(221)关联的常数。*/ static RIGHTBRACKET: number; /** 与 ' 键的键控代码值(222)关联的常数。*/ static QUOTE: number; /** 与 Alternate(Option)键的键控代码值(18)关联的常数。*/ static ALTERNATE: number; /** 与 Backspace 的键控代码值(8)关联的常数。*/ static BACKSPACE: number; /** 与 Caps Lock 的键控代码值(20)关联的常数。*/ static CAPS_LOCK: number; /** 与 Mac 命令键(15)关联的常数。*/ static COMMAND: number; /** 与 Ctrl 的键控代码值(17)关联的常数。*/ static CONTROL: number; /** 与 Delete 的键控代码值(46)关联的常数。*/ static DELETE: number; /** 与 Enter 的键控代码值(13)关联的常数。*/ static ENTER: number; /** 与 Esc 的键控代码值(27)关联的常数。*/ static ESCAPE: number; /** 与 Page Up 的键控代码值(33)关联的常数。*/ static PAGE_UP: number; /** 与 Page Down 的键控代码值(34)关联的常数。*/ static PAGE_DOWN: number; /** 与 End 的键控代码值(35)关联的常数。*/ static END: number; /** 与 Home 的键控代码值(36)关联的常数。*/ static HOME: number; /** 与向左箭头键的键控代码值(37)关联的常数。*/ static LEFT: number; /** 与向上箭头键的键控代码值(38)关联的常数。*/ static UP: number; /** 与向右箭头键的键控代码值(39)关联的常数。*/ static RIGHT: number; /** 与向下箭头键的键控代码值(40)关联的常数。*/ static DOWN: number; /** 与 Shift 的键控代码值(16)关联的常数。*/ static SHIFT: number; /** 与空格键的键控代码值(32)关联的常数。*/ static SPACE: number; /** 与 Tab 的键控代码值(9)关联的常数。*/ static TAB: number; /** 与 Insert 的键控代码值(45)关联的常数。*/ static INSERT: number; } } declare module laya.events { /** *

    KeyBoardManager 是键盘事件管理类。该类从浏览器中接收键盘事件,并派发该事件。

    *

    派发事件时若 Stage.focus 为空则只从 Stage 上派发该事件,否则将从 Stage.focus 对象开始一直冒泡派发该事件。所以在 Laya.stage 上监听键盘事件一定能够收到,如果在其他地方监听,则必须处在Stage.focus的冒泡链上才能收到该事件。

    *

    用户可以通过代码 Laya.stage.focus=someNode 的方式来设置focus对象。

    *

    用户可统一的根据事件对象中 e.keyCode 来判断按键类型,该属性兼容了不同浏览器的实现。

    */ class KeyBoardManager { /**是否开启键盘事件,默认为true*/ static enabled: boolean; static _event: Event; static __init__(): void; /** * 返回指定键是否被按下。 * @param key 键值。 * @return 是否被按下。 */ static hasKeyDown(key: number): boolean; } } declare module laya.events { /** *

    KeyLocation 类包含表示在键盘或类似键盘的输入设备上按键位置的常量。

    *

    KeyLocation 常数用在键盘事件对象的 keyLocation 属性中。

    */ class KeyLocation { /** * 表示激活的键不区分位于左侧还是右侧,也不区分是否位于数字键盘(或者是使用对应于数字键盘的虚拟键激活的)。 */ static STANDARD: number; /** * 表示激活的键在左侧键位置(此键有多个可能的位置)。 */ static LEFT: number; /** * 表示激活的键在右侧键位置(此键有多个可能的位置)。 */ static RIGHT: number; /** *

    表示激活的键位于数字键盘或者是使用对应于数字键盘的虚拟键激活的。

    *

    注意:此属性只在flash模式下有效。

    * */ static NUM_PAD: number; } } declare module laya.events { import Stage = laya.display.Stage; /** *

    MouseManager 是鼠标、触摸交互管理器。

    *

    鼠标事件流包括捕获阶段、目标阶段、冒泡阶段。
    * 捕获阶段:此阶段引擎会从stage开始递归检测stage及其子对象,直到找到命中的目标对象或者未命中任何对象;
    * 目标阶段:找到命中的目标对象;
    * 冒泡阶段:事件离开目标对象,按节点层级向上逐层通知,直到到达舞台的过程。

    */ class MouseManager { /** * MouseManager 单例引用。 */ static instance: MouseManager; /**是否开启鼠标检测,默认为true*/ static enabled: boolean; /**是否开启多点触控*/ static multiTouchEnabled: boolean; /** canvas 上的鼠标X坐标。*/ mouseX: number; /** canvas 上的鼠标Y坐标。*/ mouseY: number; /** 是否禁用除 stage 以外的鼠标事件检测。*/ disableMouseEvent: boolean; /** 鼠标按下的时间。单位为毫秒。*/ mouseDownTime: number; /** 鼠标移动精度。*/ mouseMoveAccuracy: number; _event: Event; /** * @private * 初始化。 */ __init__(stage: Stage, canvas: any): void; /** * 执行事件处理。 */ runEvent(): void; } } declare module laya.events { /** * @private * Touch事件管理类,处理多点触控下的鼠标事件 */ class TouchManager { static I: TouchManager; /** * 是否启用 */ enable: boolean; /** * 用于派发事件用的Event对象 */ _event: Event; /** * 处理touchStart * @param ele 根节点 * @param touchID touchID * @param isLeft (可选)是否为左键 */ onMouseDown(ele: any, touchID: number, isLeft?: boolean): void; /** * 处理TouchMove事件 * @param ele 根节点 * @param touchID touchID * */ onMouseMove(ele: any, touchID: number): void; getLastOvers(): Array; stageMouseOut(): void; /** * 处理TouchEnd事件 * @param ele 根节点 * @param touchID touchID * @param isLeft 是否为左键 */ onMouseUp(ele: any, touchID: number, isLeft?: boolean): void; } } declare module laya.filters { import Sprite = laya.display.Sprite; /** * 模糊滤镜 */ class BlurFilter extends Filter { /**模糊滤镜的强度(值越大,越不清晰 */ strength: number; strength_sig2_2sig2_gauss1: Array; /** * 模糊滤镜 * @param strength 模糊滤镜的强度值 */ constructor(strength?: number); /** * @private * 当前滤镜对应的操作器 */ readonly action: IFilterAction; /** * @private * 当前滤镜的类型 */ readonly type: number; /** * @private 通知微端 */ callNative(sp: Sprite): void; } } declare module laya.filters { import Sprite = laya.display.Sprite; /** *

    ColorFilter 是颜色滤镜。使用 ColorFilter 类可以将 4 x 5 矩阵转换应用于输入图像上的每个像素的 RGBA 颜色和 Alpha 值,以生成具有一组新的 RGBA 颜色和 Alpha 值的结果。该类允许饱和度更改、色相旋转、亮度转 Alpha 以及各种其他效果。您可以将滤镜应用于任何显示对象(即,从 Sprite 类继承的对象)。

    *

    注意:对于 RGBA 值,最高有效字节代表红色通道值,其后的有效字节分别代表绿色、蓝色和 Alpha 通道值。

    */ class ColorFilter extends Filter implements IFilter { _mat: Float32Array; _alpha: Float32Array; /** * 创建一个 ColorFilter 实例。 * @param mat (可选)由 20 个项目(排列成 4 x 5 矩阵)组成的数组,用于颜色转换。 */ constructor(mat?: Array); readonly type: number; readonly action: IFilterAction; /** * @private 通知微端 */ callNative(sp: Sprite): void; } } declare module laya.filters { /** * @private * ColorFilterAction 是一个颜色滤镜应用类。 */ class ColorFilterAction implements IFilterAction { data: ColorFilter; /** * 创建一个 ColorFilterAction 实例。 */ constructor(); /** * 给指定的对象应用颜色滤镜。 * @param srcCanvas 需要应用画布对象。 * @return 应用了滤镜后的画布对象。 */ apply(srcCanvas: any): any; } } declare module laya.filters { import Sprite = laya.display.Sprite; /** * Filter 是滤镜基类。 */ class Filter implements IFilter { static BLUR: number; static COLOR: number; static GLOW: number; static _filterStart: Function; static _filterEnd: Function; static _EndTarget: Function; static _recycleScope: Function; static _filter: Function; static _useSrc: Function; static _endSrc: Function; static _useOut: Function; static _endOut: Function; _action: any; /** * 创建一个 Filter 实例。 * */ constructor(); readonly type: number; readonly action: IFilterAction; callNative(sp: Sprite): void; } } declare module laya.filters { /** * 默认的FILTER,什么都不做 * @private */ class FilterAction implements IFilterAction { data: any; apply(data: any): any; } } declare module laya.filters { import Sprite = laya.display.Sprite; /** * 发光滤镜(也可以当成阴影滤使用) */ class GlowFilter extends Filter { /** * 创建发光滤镜 * @param color 滤镜的颜色 * @param blur 边缘模糊的大小 * @param offX X轴方向的偏移 * @param offY Y轴方向的偏移 */ constructor(color: string, blur?: number, offX?: number, offY?: number); /** * @private * 滤镜类型 */ readonly type: number; readonly action: IFilterAction; offY: number; offX: number; getColor(): Array; blur: number; /** * @private 通知微端 */ callNative(sp: Sprite): void; } } declare module laya.filters { /** * 滤镜接口。 */ interface IFilter { } } declare module laya.filters { /** * IFilterAction 是滤镜动画接口。 */ interface IFilterAction { apply(srcCanvas: any): any; } } declare module laya.filters { import Sprite = laya.display.Sprite; import RenderContext = laya.renders.RenderContext; import Value2D = laya.webgl.shader.d2.value.Value2D; import SubmitCMDScope = laya.webgl.submit.SubmitCMDScope; interface IFilterActionGL extends IFilterAction { setValue(shader: any): void; setValueMix(shader: Value2D): void; apply3d(scope: SubmitCMDScope, sprite: Sprite, context: RenderContext, x: number, y: number): any; } } declare module laya.filters.webgl { import Sprite = laya.display.Sprite; import BlurFilter = laya.filters.BlurFilter; import RenderContext = laya.renders.RenderContext; import Value2D = laya.webgl.shader.d2.value.Value2D; import SubmitCMDScope = laya.webgl.submit.SubmitCMDScope; /** * @private */ class BlurFilterActionGL extends FilterActionGL { data: BlurFilter; constructor(); readonly typeMix: number; setValueMix(shader: Value2D): void; apply3d(scope: SubmitCMDScope, sprite: Sprite, context: RenderContext, x: number, y: number): any; setValue(shader: any): void; } } declare module laya.filters.webgl { import Sprite = laya.display.Sprite; import ColorFilter = laya.filters.ColorFilter; import IFilterActionGL = laya.filters.IFilterActionGL; import RenderContext = laya.renders.RenderContext; import SubmitCMDScope = laya.webgl.submit.SubmitCMDScope; class ColorFilterActionGL extends FilterActionGL implements IFilterActionGL { data: ColorFilter; constructor(); setValue(shader: any): void; apply3d(scope: SubmitCMDScope, sprite: Sprite, context: RenderContext, x: number, y: number): any; } } declare module laya.filters.webgl { import Sprite = laya.display.Sprite; import IFilterActionGL = laya.filters.IFilterActionGL; import RenderContext = laya.renders.RenderContext; import Value2D = laya.webgl.shader.d2.value.Value2D; import SubmitCMDScope = laya.webgl.submit.SubmitCMDScope; class FilterActionGL implements IFilterActionGL { constructor(); readonly typeMix: number; setValue(shader: any): void; setValueMix(shader: Value2D): void; apply3d(scope: SubmitCMDScope, sprite: Sprite, context: RenderContext, x: number, y: number): any; apply(srcCanvas: any): any; } } declare module laya.filters.webgl { import Sprite = laya.display.Sprite; import GlowFilter = laya.filters.GlowFilter; import IFilterActionGL = laya.filters.IFilterActionGL; import RenderContext = laya.renders.RenderContext; import Value2D = laya.webgl.shader.d2.value.Value2D; import SubmitCMDScope = laya.webgl.submit.SubmitCMDScope; /** * @private */ class GlowFilterActionGL extends FilterActionGL implements IFilterActionGL { data: GlowFilter; constructor(); readonly typeMix: number; setValueMix(shader: Value2D): void; static tmpTarget(scope: SubmitCMDScope, sprite: Sprite, context: RenderContext, x: number, y: number): void; static startOut(scope: SubmitCMDScope, sprite: Sprite, context: RenderContext, x: number, y: number): void; static recycleTarget(scope: SubmitCMDScope, sprite: Sprite, context: RenderContext, x: number, y: number): void; apply3d(scope: SubmitCMDScope, sprite: Sprite, context: RenderContext, x: number, y: number): any; setSpriteWH(sprite: Sprite): void; setValue(shader: any): void; } } declare module laya.filters { /** * @private */ class WebGLFilter { static enable(): void; } } declare module laya.html.dom { /** * @private */ class HTMLBrElement extends HTMLElement { constructor(); } } declare module laya.html.dom { /** * DIV标签 */ class HTMLDivElement extends HTMLElement { /** 实际内容的高 */ contextHeight: number; /** 实际内容的宽 */ contextWidth: number; constructor(); /** * 设置标签内容 */ innerHTML: string; /** * 获取对象的宽 */ width: number; /** * 追加内容,解析并对显示对象排版 * @param text */ appendHTML(text: string): void; /** * @private * @param out * @return */ _addChildsToLayout(out: Array): boolean; /** * @private * @param out */ _addToLayout(out: Array): void; /** * @private * 对显示内容进行排版 */ layout(): void; /** * 获取对象的高 */ readonly height: number; } } declare module laya.html.dom { /** * @private */ class HTMLDocument extends HTMLElement { static document: HTMLDocument; all: Array; styleSheets: any; constructor(); getElementById(id: string): HTMLElement; setElementById(id: string, e: HTMLElement): void; } } declare module laya.html.dom { import Node = laya.display.Node; import Sprite = laya.display.Sprite; import CSSStyle = laya.display.css.CSSStyle; import URL = laya.net.URL; /** * @private */ class HTMLElement extends Sprite { URI: URL; constructor(); /** * @private */ layaoutCallNative(): void; id: string; text: string; innerTEXT: string; parent: Node; appendChild(c: HTMLElement): HTMLElement; readonly style: CSSStyle; /** * rtl模式的getWords函數 */ _getWords2(): Array; _getWords(): Array; showLinkSprite(): void; _layoutLater(): void; onClick: string; _setAttributes(name: string, value: string): void; href: string; formatURL(url: string): string; color: string; className: string; static fillWords(ele: HTMLElement, words: Array, x: number, y: number, font: string, color: string, underLine: number): void; } } declare module laya.html.dom { /** * iframe标签类,目前用于加载外并解析数据 */ class HTMLIframeElement extends HTMLDivElement { constructor(); /** * 加载html文件,并解析数据 * @param url */ href: string; } } declare module laya.html.dom { import RenderContext = laya.renders.RenderContext; /** * @private */ class HTMLImageElement extends HTMLElement { constructor(); src: string; _addToLayout(out: Array): void; render(context: RenderContext, x: number, y: number): void; /** * @private */ layaoutCallNative(): void; } } declare module laya.html.dom { /** * @private */ class HTMLLinkElement extends HTMLElement { type: string; static _cuttingStyle: RegExp; constructor(); _onload(data: string): void; href: string; } } declare module laya.html.dom { /** * @private */ class HTMLStyleElement extends HTMLElement { constructor(); /** * 解析样式 */ text: string; } } declare module laya.html.utils { import HTMLDivElement = laya.html.dom.HTMLDivElement; import URL = laya.net.URL; /** * @private */ class HTMLParse { /** * 解析HTML * @param ower * @param xmlString * @param url */ static parse(ower: HTMLDivElement, xmlString: string, url: URL): void; } } declare module laya.html.utils { import Sprite = laya.display.Sprite; /** * @private * HTML的布局类 * 对HTML的显示对象进行排版 */ class Layout { static later(element: Sprite): void; static layout(element: Sprite): Array; static _multiLineLayout(element: Sprite): Array; /** * rtl模式的排版函数 */ static _multiLineLayout2(element: Sprite): Array; } } declare module laya.html.utils { /** * @private */ class LayoutLine { elements: Array; x: number; y: number; w: number; h: number; wordStartIndex: number; minTextHeight: number; mWidth: number; constructor(); /** * 底对齐(默认) * @param left * @param width * @param dy * @param align 水平 * @param valign 垂直 * @param lineHeight 行高 */ updatePos(left: number, width: number, lineNum: number, dy: number, align: number, valign: number, lineHeight: number): void; /** * 布局反向,目前用于将ltr模式布局转为rtl模式布局 */ revertOrder(width: number): void; } } declare module laya.map { import Sprite = laya.display.Sprite; /** * 地图的每层都会分块渲染处理 * 本类就是地图的块数据 * @author ... */ class GridSprite extends Sprite { /**相对于地图X轴的坐标*/ relativeX: number; /**相对于地图Y轴的坐标*/ relativeY: number; /**是否用于对象层的独立物件*/ isAloneObject: boolean; /**当前GRID中是否有动画*/ isHaveAnimation: boolean; /**当前GRID包含的动画*/ aniSpriteArray: Array; /**当前GRID包含多少个TILE(包含动画)*/ drawImageNum: number; /** * 传入必要的参数,用于裁剪,跟确认此对象类型 * @param map 把地图的引用传进来,参与一些裁剪计算 * @param objectKey true:表示当前GridSprite是个活动对象,可以控制,false:地图层的组成块 */ initData(map: TiledMap, objectKey?: boolean): void; _setDisplay(value: boolean): void; /** * 把一个动画对象绑定到当前GridSprite * @param sprite 动画的显示对象 */ addAniSprite(sprite: TileAniSprite): void; /** * 显示当前GridSprite,并把上面的动画全部显示 */ show(): void; /** * 隐藏当前GridSprite,并把上面绑定的动画全部移除 */ hide(): void; /** * 刷新坐标,当我们自己控制一个GridSprite移动时,需要调用此函数,手动刷新 */ updatePos(): void; /** * 重置当前对象的所有属性 */ clearAll(): void; } } declare module laya.map { import Sprite = laya.display.Sprite; import GridSprite = laya.map.GridSprite; import Point = laya.maths.Point; import RenderContext = laya.renders.RenderContext; /** * 地图支持多层渲染(例如,地表层,植被层,建筑层等) * 本类就是层级类 * @author ... */ class MapLayer extends Sprite { _mapData: Array; /** * @private */ _gridSpriteArray: Array; /**被合到的层*/ tarLayer: MapLayer; /**当前Layer的名称*/ layerName: string; /** * 解析LAYER数据,以及初始化一些数据 * @param layerData 地图数据中,layer数据的引用 * @param map 地图的引用 */ init(layerData: any, map: TiledMap): void; /** * 通过名字获取控制对象,如果找不到返回为null * @param objName 所要获取对象的名字 * @return */ getObjectByName(objName: string): GridSprite; /** * 通过名字获取数据,如果找不到返回为null * @param objName 所要获取对象的名字 * @return */ getObjectDataByName(objName: string): GridSprite; /** * 得到地图层的自定义属性 * @param name * @return */ getLayerProperties(name: string): any; /** * 得到指定格子的数据 * @param tileX 格子坐标X * @param tileY 格子坐标Y * @return */ getTileData(tileX: number, tileY: number): number; /** * 通过地图坐标得到屏幕坐标 * @param tileX 格子坐标X * @param tileY 格子坐标Y * @param screenPos 把计算好的屏幕坐标数据,放到此对象中 */ getScreenPositionByTilePos(tileX: number, tileY: number, screenPos?: Point): void; /** * 通过屏幕坐标来获取选中格子的数据 * @param screenX 屏幕坐标x * @param screenY 屏幕坐标y * @return */ getTileDataByScreenPos(screenX: number, screenY: number): number; /** * 通过屏幕坐标来获取选中格子的索引 * @param screenX 屏幕坐标x * @param screenY 屏幕坐标y * @param result 把计算好的格子坐标,放到此对象中 * @return */ getTilePositionByScreenPos(screenX: number, screenY: number, result?: Point): boolean; /** * 得到一个GridSprite * @param gridX 当前Grid的X轴索引 * @param gridY 当前Grid的Y轴索引 * @return 一个GridSprite对象 */ getDrawSprite(gridX: number, gridY: number): GridSprite; /** * 将gridSprite设为显示状态 * @param gridSprite */ showGridSprite(gridSprite: GridSprite): void; /** * 将gridSprite设为隐藏状态 * @param gridSprite * */ hideGridSprite(gridSprite: GridSprite): void; /** * 更新此层中块的坐标 * 手动刷新的目的是,保持层级的宽和高保持最小,加快渲染 */ updateGridPos(): void; /** * 更新此层中的活动对象 */ updateAloneObject(): void; /** * 渲染时使用需要更新的列表进行渲染,减少遍历 * @param context * @param x * @param y * */ render(context: RenderContext, x: number, y: number): void; /** * @private * 把tile画到指定的显示对象上 * @param gridSprite 被指定显示的目标 * @param tileX 格子的X轴坐标 * @param tileY 格子的Y轴坐标 * @return */ drawTileTexture(gridSprite: GridSprite, tileX: number, tileY: number): boolean; /** * @private * 清理当前对象 */ clearAll(): void; } } declare module laya.map { import Sprite = laya.display.Sprite; /** * TildMap的动画显示对象(一个动画(TileTexSet),可以绑定多个动画显示对象(TileAniSprite)) * @author ... */ class TileAniSprite extends Sprite { /** * 确定当前显示对象的名称以及属于哪个动画 * @param aniName 当前动画显示对象的名字,名字唯一 * @param tileTextureSet 当前显示对象属于哪个动画(一个动画,可以绑定多个同类显示对象) */ setTileTextureSet(aniName: string, tileTextureSet: TileTexSet): void; /** * 把当前动画加入到对应的动画刷新列表中 */ show(): void; /** * 把当前动画从对应的动画刷新列表中移除 */ hide(): void; /** * 清理 */ clearAll(): void; } } declare module laya.map { import Sprite = laya.display.Sprite; import GridSprite = laya.map.GridSprite; import Point = laya.maths.Point; import Rectangle = laya.maths.Rectangle; import Handler = laya.utils.Handler; import MapLayer = laya.map.MapLayer; /** * tiledMap是整个地图的核心 * 地图以层级来划分地图(例如:地表层,植被层,建筑层) * 每层又以分块(GridSprite)来处理显示对象,只显示在视口区域的区 * 每块又包括N*N个格子(tile) * 格子类型又分为动画格子跟图片格子两种 * @author ... */ class TiledMap { /**四边形地图*/ static ORIENTATION_ORTHOGONAL: string; /**菱形地图*/ static ORIENTATION_ISOMETRIC: string; /**45度交错地图*/ static ORIENTATION_STAGGERED: string; /**六边形地图*/ static ORIENTATION_HEXAGONAL: string; /**地图格子从左上角开始渲染*/ static RENDERORDER_RIGHTDOWN: string; /**地图格子从左下角开始渲染*/ static RENDERORDER_RIGHTUP: string; /**地图格子从右上角开始渲染*/ static RENDERORDER_LEFTDOWN: string; /**地图格子右下角开始渲染*/ static RENDERORDER_LEFTUP: string; _viewPortX: number; _viewPortY: number; /** * 是否自动缓存没有动画的地块 */ autoCache: boolean; /** * 自动缓存类型,地图较大时建议使用normal */ autoCacheType: string; /** * 是否合并图层,开启合并图层时,图层属性内可添加layer属性,运行时将会将相邻的layer属性相同的图层进行合并以提高性能 */ enableMergeLayer: boolean; /** * 是否移除被覆盖的格子,地块可添加type属性,type不为0时表示不透明,被不透明地块遮挡的地块将会被剔除以提高性能 */ removeCoveredTile: boolean; /** * 是否显示大格子里显示的贴图数量 */ showGridTextureCount: boolean; /** * 是否调整地块边缘消除缩放导致的缝隙 */ antiCrack: boolean; /** * 是否在加载完成之后cache所有大格子 */ cacheAllAfterInit: boolean; constructor(); /** * 创建地图 * @param mapName JSON文件名字 * @param viewRect 视口区域 * @param completeHandler 地图创建完成的回调函数 * @param viewRectPadding 视口扩充区域,把视口区域上、下、左、右扩充一下,防止视口移动时的穿帮 * @param gridSize grid大小 * @param enableLinear 是否开启线性取样(为false时,可以解决地图黑线的问题,但画质会锐化) * @param limitRange 把地图限制在显示区域 */ createMap(mapName: string, viewRect: Rectangle, completeHandler: Handler, viewRectPadding?: Rectangle, gridSize?: Point, enableLinear?: boolean, limitRange?: boolean): void; getTileUserData(id: number, sign: string, defaultV?: any): any; /** * 得到一块指定的地图纹理 * @param index 纹理的索引值,默认从1开始 * @return */ getTexture(index: number): TileTexSet; /** * 得到地图的自定义属性 * @param name 属性名称 * @return */ getMapProperties(name: string): any; /** * 得到tile自定义属性 * @param index 地图块索引 * @param id 具体的TileSetID * @param name 属性名称 * @return */ getTileProperties(index: number, id: number, name: string): any; /** * 通过纹理索引,生成一个可控制物件 * @param index 纹理的索引值,默认从1开始 * @return */ getSprite(index: number, width: number, height: number): GridSprite; /** * 设置视口的缩放中心点(例如:scaleX= scaleY= 0.5,就是以视口中心缩放) * @param scaleX * @param scaleY */ setViewPortPivotByScale(scaleX: number, scaleY: number): void; /** * 得到当前地图的缩放 */ /** * 设置地图缩放 * @param scale */ scale: number; /** * 移动视口 * @param moveX 视口的坐标x * @param moveY 视口的坐标y */ moveViewPort(moveX: number, moveY: number): void; /** * 改变视口大小 * @param moveX 视口的坐标x * @param moveY 视口的坐标y * @param width 视口的宽 * @param height 视口的高 */ changeViewPort(moveX: number, moveY: number, width: number, height: number): void; /** * 在锚点的基础上计算,通过宽和高,重新计算视口 * @param width 新视口宽 * @param height 新视口高 * @param rect 返回的结果 * @return */ changeViewPortBySize(width: number, height: number, rect?: Rectangle): Rectangle; /** * 得到对象层上的某一个物品 * @param layerName 层的名称 * @param objectName 所找物品的名称 * @return */ getLayerObject(layerName: string, objectName: string): GridSprite; /** * 销毁地图 */ destroy(): void; readonly tileWidth: number; /** * 格子的高度 */ readonly tileHeight: number; /** * 地图的宽度 */ readonly width: number; /** * 地图的高度 */ readonly height: number; /** * 地图横向的格子数 */ readonly numColumnsTile: number; /** * 地图竖向的格子数 */ readonly numRowsTile: number; /** * @private * 视口x坐标 */ readonly viewPortX: number; /** * @private * 视口的y坐标 */ readonly viewPortY: number; /** * @private * 视口的宽度 */ readonly viewPortWidth: number; /** * @private * 视口的高度 */ readonly viewPortHeight: number; /** * 地图的x坐标 */ readonly x: number; /** * 地图的y坐标 */ readonly y: number; /** * 块的宽度 */ readonly gridWidth: number; /** * 块的高度 */ readonly gridHeight: number; /** * 地图的横向块数 */ readonly numColumnsGrid: number; /** * 地图的坚向块数 */ readonly numRowsGrid: number; /** * 当前地图类型 */ readonly orientation: string; /** * tile渲染顺序 */ readonly renderOrder: string; /** * 整个地图的显示容器 * @return 地图的显示容器 */ mapSprite(): Sprite; /** * 得到指定的MapLayer * @param layerName 要找的层名称 * @return */ getLayerByName(layerName: string): MapLayer; /** * 通过索引得MapLayer * @param index 要找的层索引 * @return */ getLayerByIndex(index: number): MapLayer; } class GRect { left: number; top: number; right: number; bottom: number; clearAll(): void; } class TileMapAniData { mAniIdArray: Array; mDurationTimeArray: Array; mTileTexSetArr: Array; image: any; } class TileSet { firstgid: number; image: string; imageheight: number; imagewidth: number; margin: number; name: number; properties: any; spacing: number; tileheight: number; tilewidth: number; titleoffsetX: number; titleoffsetY: number; tileproperties: any; init(data: any): void; } } declare module laya.map { import TileAniSprite = laya.map.TileAniSprite; import Texture = laya.resource.Texture; /** * 此类是子纹理类,也包括同类动画的管理 * TiledMap会把纹理分割成无数子纹理,也可以把其中的某块子纹理替换成一个动画序列 * 本类的实现就是如果发现子纹理被替换成一个动画序列,animationKey会被设为true * 即animationKey为true,就使用TileAniSprite来做显示,把动画序列根据时间画到TileAniSprite上 * @author ... */ class TileTexSet { /**唯一标识*/ gid: number; /**子纹理的引用*/ texture: Texture; /**纹理显示时的坐标偏移X*/ offX: number; /**纹理显示时的坐标偏移Y*/ offY: number; /**当前要播放动画的纹理序列*/ textureArray: Array; /** 当前动画每帧的时间间隔*/ durationTimeArray: Array; /** 动画播放的总时间 */ animationTotalTime: number; /**true表示当前纹理,是一组动画,false表示当前只有一个纹理*/ isAnimation: boolean; /** * 加入一个动画显示对象到此动画中 * @param aniName //显示对象的名字 * @param sprite //显示对象 */ addAniSprite(aniName: string, sprite: TileAniSprite): void; /** * 移除不需要更新的SPRITE * @param _name */ removeAniSprite(_name: string): void; /** * 显示当前动画的使用情况 */ showDebugInfo(): string; /** * 清理 */ clearAll(): void; } } declare module laya.maths { /** * @private */ class Arith { static formatR(r: number): number; static isPOT(w: number, h: number): boolean; static setMatToArray(mat: Matrix, array: any): void; } } declare module laya.maths { /** * @private * 计算贝塞尔曲线的工具类。 */ class Bezier { /** * 工具类单例 */ static I: Bezier; /** * 计算二次贝塞尔点。 * @param t * @param rst * */ getPoint2(t: number, rst: Array): void; /** * 计算三次贝塞尔点 * @param t * @param rst * */ getPoint3(t: number, rst: Array): void; /** * 计算贝塞尔点序列 * @param count * @param rst * */ insertPoints(count: number, rst: Array): void; /** * 获取贝塞尔曲线上的点。 * @param pList 控制点[x0,y0,x1,y1...] * @param inSertCount 每次曲线的插值数量 * @return * */ getBezierPoints(pList: Array, inSertCount?: number, count?: number): Array; } } declare module laya.maths { /** * @private * 凸包算法。 */ class GrahamScan { static multiply(p1: Point, p2: Point, p0: Point): number; /** * 计算两个点的距离。 * @param p1 * @param p2 * @return */ static dis(p1: Point, p2: Point): number; /** * 将数组 src 从索引0位置 依次取 cout 个项添加至 tst 数组的尾部。 * @param rst 原始数组,用于添加新的子元素。 * @param src 用于取子元素的数组。 * @param count 需要取得子元素个数。 * @return 添加完子元素的 rst 对象。 */ static getFrom(rst: Array, src: Array, count: number): Array; /** * 将数组 src 从末尾索引位置往头部索引位置方向 依次取 cout 个项添加至 tst 数组的尾部。 * @param rst 原始数组,用于添加新的子元素。 * @param src 用于取子元素的数组。 * @param count 需要取得子元素个数。 * @return 添加完子元素的 rst 对象。 */ static getFromR(rst: Array, src: Array, count: number): Array; /** * [x,y...]列表 转 Point列表 * @param pList Point列表 * @return [x,y...]列表 */ static pListToPointList(pList: Array, tempUse?: boolean): Array; /** * Point列表转[x,y...]列表 * @param pointList Point列表 * @return [x,y...]列表 */ static pointListToPlist(pointList: Array): Array; /** * 寻找包括所有点的最小多边形顶点集合 * @param pList 形如[x0,y0,x1,y1...]的点列表 * @return 最小多边形顶点集合 */ static scanPList(pList: Array): Array; /** * 寻找包括所有点的最小多边形顶点集合 * @param PointSet Point列表 * @return 最小多边形顶点集合 */ static scan(PointSet: Array): Array; } } declare module laya.maths { /** * @private * MathUtil 是一个数据处理工具类。 */ class MathUtil { static subtractVector3(l: Float32Array, r: Float32Array, o: Float32Array): void; static lerp(left: number, right: number, amount: number): number; static scaleVector3(f: Float32Array, b: number, e: Float32Array): void; static lerpVector3(l: Float32Array, r: Float32Array, t: number, o: Float32Array): void; static lerpVector4(l: Float32Array, r: Float32Array, t: number, o: Float32Array): void; static slerpQuaternionArray(a: Float32Array, Offset1: number, b: Float32Array, Offset2: number, t: number, out: Float32Array, Offset3: number): Float32Array; /** * 获取指定的两个点组成的线段的弧度值。 * @param x0 点一的 X 轴坐标值。 * @param y0 点一的 Y 轴坐标值。 * @param x1 点二的 X 轴坐标值。 * @param y1 点二的 Y 轴坐标值。 * @return 弧度值。 */ static getRotation(x0: number, y0: number, x1: number, y1: number): number; /** * 一个用来确定数组元素排序顺序的比较函数。 * @param a 待比较数字。 * @param b 待比较数字。 * @return 如果a等于b 则值为0;如果b>a则值为1;如果b<则值为-1。 */ static sortBigFirst(a: number, b: number): number; /** * 一个用来确定数组元素排序顺序的比较函数。 * @param a 待比较数字。 * @param b 待比较数字。 * @return 如果a等于b 则值为0;如果b>a则值为-1;如果b<则值为1。 */ static sortSmallFirst(a: number, b: number): number; /** * 将指定的元素转为数字进行比较。 * @param a 待比较元素。 * @param b 待比较元素。 * @return b、a转化成数字的差值 (b-a)。 */ static sortNumBigFirst(a: any, b: any): number; /** * 将指定的元素转为数字进行比较。 * @param a 待比较元素。 * @param b 待比较元素。 * @return a、b转化成数字的差值 (a-b)。 */ static sortNumSmallFirst(a: any, b: any): number; /** * 返回根据对象指定的属性进行排序的比较函数。 * @param key 排序要依据的元素属性名。 * @param bigFirst 如果值为true,则按照由大到小的顺序进行排序,否则按照由小到大的顺序进行排序。 * @param forceNum 如果值为true,则将排序的元素转为数字进行比较。 * @return 排序函数。 */ static sortByKey(key: string, bigFirst?: boolean, forceNum?: boolean): Function; } } declare module laya.maths { /** *

    Matrix 类表示一个转换矩阵,它确定如何将点从一个坐标空间映射到另一个坐标空间。

    *

    您可以对一个显示对象执行不同的图形转换,方法是设置 Matrix 对象的属性,将该 Matrix 对象应用于 Transform 对象的 matrix 属性,然后应用该 Transform 对象作为显示对象的 transform 属性。这些转换函数包括平移(x 和 y 重新定位)、旋转、缩放和倾斜。

    */ class Matrix { static EMPTY: Matrix; /** 用于中转使用的 Matrix 对象。*/ static TEMP: Matrix; static _cache: any; /**缩放或旋转图像时影响像素沿 x 轴定位的值。*/ a: number; /**旋转或倾斜图像时影响像素沿 y 轴定位的值。*/ b: number; /**旋转或倾斜图像时影响像素沿 x 轴定位的值。*/ c: number; /**缩放或旋转图像时影响像素沿 y 轴定位的值。*/ d: number; /**沿 x 轴平移每个点的距离。*/ tx: number; /**沿 y 轴平移每个点的距离。*/ ty: number; inPool: boolean; bTransform: boolean; /** * 使用指定参数创建新的 Matrix 对象。 * @param a (可选)缩放或旋转图像时影响像素沿 x 轴定位的值。 * @param b (可选)旋转或倾斜图像时影响像素沿 y 轴定位的值。 * @param c (可选)旋转或倾斜图像时影响像素沿 x 轴定位的值。 * @param d (可选)缩放或旋转图像时影响像素沿 y 轴定位的值。 * @param tx (可选)沿 x 轴平移每个点的距离。 * @param ty (可选)沿 y 轴平移每个点的距离。 */ constructor(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number); /** * 将本矩阵设置为单位矩阵。 * @return 返回当前矩形。 */ identity(): Matrix; _checkTransform(): boolean; /** * 设置沿 x 、y 轴平移每个点的距离。 * @param x 沿 x 轴平移每个点的距离。 * @param y 沿 y 轴平移每个点的距离。 * @return 返回对象本身 */ setTranslate(x: number, y: number): Matrix; /** * 沿 x 和 y 轴平移矩阵,平移的变化量由 x 和 y 参数指定。 * @param x 沿 x 轴向右移动的量(以像素为单位)。 * @param y 沿 y 轴向下移动的量(以像素为单位)。 * @return 返回此矩形对象。 */ translate(x: number, y: number): Matrix; /** * 对矩阵应用缩放转换。 * @param x 用于沿 x 轴缩放对象的乘数。 * @param y 用于沿 y 轴缩放对象的乘数。 */ scale(x: number, y: number): void; /** * 对 Matrix 对象应用旋转转换。 * @param angle 以弧度为单位的旋转角度。 */ rotate(angle: number): void; /** * 对 Matrix 对象应用倾斜转换。 * @param x 沿着 X 轴的 2D 倾斜弧度。 * @param y 沿着 Y 轴的 2D 倾斜弧度。 * @return 当前 Matrix 对象。 */ skew(x: number, y: number): Matrix; /** * 对指定的点应用当前矩阵的逆转化并返回此点。 * @param out 待转化的点 Point 对象。 * @return 返回out */ invertTransformPoint(out: Point): Point; /** * 将 Matrix 对象表示的几何转换应用于指定点。 * @param out 用来设定输出结果的点。 * @return 返回out */ transformPoint(out: Point): Point; /** * 将 Matrix 对象表示的几何转换应用于指定点,忽略tx、ty。 * @param out 用来设定输出结果的点。 * @return 返回out */ transformPointN(out: Point): Point; /** * @private * 将 Matrix 对象表示的几何转换应用于指定点。 * @param data 点集合。 * @param out 存储应用转化的点的列表。 * @return 返回out数组 */ transformPointArray(data: Array, out: Array): Array; /** * @private * 将 Matrix 对象表示的几何缩放转换应用于指定点。 * @param data 点集合。 * @param out 存储应用转化的点的列表。 * @return 返回out数组 */ transformPointArrayScale(data: Array, out: Array): Array; /** * 获取 X 轴缩放值。 * @return X 轴缩放值。 */ getScaleX(): number; /** * 获取 Y 轴缩放值。 * @return Y 轴缩放值。 */ getScaleY(): number; /** * 执行原始矩阵的逆转换。 * @return 当前矩阵对象。 */ invert(): Matrix; /** * 将 Matrix 的成员设置为指定值。 * @param a 缩放或旋转图像时影响像素沿 x 轴定位的值。 * @param b 旋转或倾斜图像时影响像素沿 y 轴定位的值。 * @param c 旋转或倾斜图像时影响像素沿 x 轴定位的值。 * @param d 缩放或旋转图像时影响像素沿 y 轴定位的值。 * @param tx 沿 x 轴平移每个点的距离。 * @param ty 沿 y 轴平移每个点的距离。 * @return 当前矩阵对象。 */ setTo(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix; /** * 将指定矩阵与当前矩阵连接,从而将这两个矩阵的几何效果有效地结合在一起。 * @param matrix 要连接到源矩阵的矩阵。 * @return 当前矩阵。 */ concat(matrix: Matrix): Matrix; /** * 将指定的两个矩阵相乘后的结果赋值给指定的输出对象。 * @param m1 矩阵一。 * @param m2 矩阵二。 * @param out 输出对象。 * @return 结果输出对象 out。 */ static mul(m1: Matrix, m2: Matrix, out: Matrix): Matrix; /** * 将指定的两个矩阵相乘,结果赋值给指定的输出数组,长度为16。 * @param m1 矩阵一。 * @param m2 矩阵二。 * @param out 输出对象Array。 * @return 结果输出对象 out。 */ static mul16(m1: Matrix, m2: Matrix, out: Array): Array; /** * @private * 对矩阵应用缩放转换。反向相乘 * @param x 用于沿 x 轴缩放对象的乘数。 * @param y 用于沿 y 轴缩放对象的乘数。 */ scaleEx(x: number, y: number): void; /** * @private * 对 Matrix 对象应用旋转转换。反向相乘 * @param angle 以弧度为单位的旋转角度。 */ rotateEx(angle: number): void; static mulPre(m1: Matrix, ba: number, bb: number, bc: number, bd: number, btx: number, bty: number, out: Matrix): Matrix; static mulPos(m1: Matrix, aa: number, ab: number, ac: number, ad: number, atx: number, aty: number, out: Matrix): Matrix; static preMul(parent: Matrix, self: Matrix, out: Matrix): Matrix; static preMulXY(parent: Matrix, x: number, y: number, out: Matrix): Matrix; /** * 返回此 Matrix 对象的副本。 * @return 与原始实例具有完全相同的属性的新 Matrix 实例。 */ clone(): Matrix; /** * 将当前 Matrix 对象中的所有矩阵数据复制到指定的 Matrix 对象中。 * @param dec 要复制当前矩阵数据的 Matrix 对象。 * @return 已复制当前矩阵数据的 Matrix 对象。 */ copyTo(dec: Matrix): Matrix; /** * 返回列出该 Matrix 对象属性的文本值。 * @return 一个字符串,它包含 Matrix 对象的属性值:a、b、c、d、tx 和 ty。 */ toString(): string; /** * 销毁此对象。 */ destroy(): void; /** * 从对象池中创建一个 Matrix 对象。 * @return Matrix 对象。 */ static create(): Matrix; } } declare module laya.maths { /** * Point 对象表示二维坐标系统中的某个位置,其中 x 表示水平轴,y 表示垂直轴。 */ class Point { /**临时使用的公用对象。*/ static TEMP: Point; static EMPTY: Point; /**该点的水平坐标。*/ x: number; /**该点的垂直坐标。*/ y: number; /** * 根据指定坐标,创建一个新的 Point 对象。 * @param x (可选)水平坐标。 * @param y (可选)垂直坐标。 */ constructor(x?: number, y?: number); /** * 将 Point 的成员设置为指定值。 * @param x 水平坐标。 * @param y 垂直坐标。 * @return 当前 Point 对象。 */ setTo(x: number, y: number): Point; /** * 计算当前点和目标点(x,y)的距离。 * @param x 水平坐标。 * @param y 垂直坐标。 * @return 返回当前点和目标点之间的距离。 */ distance(x: number, y: number): number; /**返回包含 x 和 y 坐标的值的字符串。*/ toString(): string; /** * 标准化向量。 */ normalize(): void; } } declare module laya.maths { /** *

    Rectangle 对象是按其位置(由它左上角的点 (x, y) 确定)以及宽度和高度定义的区域。

    *

    Rectangle 类的 x、y、width 和 height 属性相互独立;更改一个属性的值不会影响其他属性。

    */ class Rectangle { static EMPTY: Rectangle; /**全局临时的矩形区域,此对象用于全局复用,以减少对象创建*/ static TEMP: Rectangle; /** 矩形左上角的 X 轴坐标。*/ x: number; /** 矩形左上角的 Y 轴坐标。*/ y: number; /** 矩形的宽度。*/ width: number; /** 矩形的高度。*/ height: number; /** * 创建一个 Rectangle 对象。 * @param x 矩形左上角的 X 轴坐标。 * @param y 矩形左上角的 Y 轴坐标。 * @param width 矩形的宽度。 * @param height 矩形的高度。 */ constructor(x?: number, y?: number, width?: number, height?: number); /** 此矩形右侧的 X 轴坐标。 x 和 width 属性的和。*/ readonly right: number; /** 此矩形底端的 Y 轴坐标。y 和 height 属性的和。*/ readonly bottom: number; /** * 将 Rectangle 的属性设置为指定值。 * @param x x 矩形左上角的 X 轴坐标。 * @param y x 矩形左上角的 Y 轴坐标。 * @param width 矩形的宽度。 * @param height 矩形的高。 * @return 返回属性值修改后的矩形对象本身。 */ setTo(x: number, y: number, width: number, height: number): Rectangle; /** * 复制 source 对象的属性值到此矩形对象中。 * @param sourceRect 源 Rectangle 对象。 * @return 返回属性值修改后的矩形对象本身。 */ copyFrom(source: Rectangle): Rectangle; /** * 确定由此 Rectangle 对象定义的矩形区域内是否包含指定的点。 * @param x 点的 X 轴坐标值(水平位置)。 * @param y 点的 Y 轴坐标值(垂直位置)。 * @return 如果 Rectangle 对象包含指定的点,则值为 true;否则为 false。 */ contains(x: number, y: number): boolean; /** * 确定在 rect 参数中指定的对象是否与此 Rectangle 对象相交。此方法检查指定的 Rectangle 对象的 x、y、width 和 height 属性,以查看它是否与此 Rectangle 对象相交。 * @param rect Rectangle 对象。 * @return 如果传入的矩形对象与此对象相交,则返回 true 值,否则返回 false。 */ intersects(rect: Rectangle): boolean; /** * 如果在 rect 参数中指定的 Rectangle 对象与此 Rectangle 对象相交,则返回交集区域作为 Rectangle 对象。如果矩形不相交,则此方法返回null。 * @param rect 待比较的矩形区域。 * @param out (可选)待输出的矩形区域。如果为空则创建一个新的。建议:尽量复用对象,减少对象创建消耗。 * @return 返回相交的矩形区域对象。 */ intersection(rect: Rectangle, out?: Rectangle): Rectangle; /** *

    矩形联合,通过填充两个矩形之间的水平和垂直空间,将这两个矩形组合在一起以创建一个新的 Rectangle 对象。

    *

    注意:union() 方法忽略高度或宽度值为 0 的矩形,如:var rect2:Rectangle = new Rectangle(300,300,50,0);

    * @param 要添加到此 Rectangle 对象的 Rectangle 对象。 * @param out 用于存储输出结果的矩形对象。如果为空,则创建一个新的。建议:尽量复用对象,减少对象创建消耗。Rectangle.TEMP对象用于对象复用。 * @return 充当两个矩形的联合的新 Rectangle 对象。 */ union(source: Rectangle, out?: Rectangle): Rectangle; /** * 返回一个 Rectangle 对象,其 x、y、width 和 height 属性的值与当前 Rectangle 对象的对应值相同。 * @param out (可选)用于存储结果的矩形对象。如果为空,则创建一个新的。建议:尽量复用对象,减少对象创建消耗。。Rectangle.TEMP对象用于对象复用。 * @return Rectangle 对象,其 x、y、width 和 height 属性的值与当前 Rectangle 对象的对应值相同。 */ clone(out?: Rectangle): Rectangle; /** * 当前 Rectangle 对象的水平位置 x 和垂直位置 y 以及高度 width 和宽度 height 以逗号连接成的字符串。 */ toString(): string; /** * 检测传入的 Rectangle 对象的属性是否与当前 Rectangle 对象的属性 x、y、width、height 属性值都相等。 * @param rect 待比较的 Rectangle 对象。 * @return 如果判断的属性都相等,则返回 true ,否则返回 false。 */ equals(rect: Rectangle): boolean; /** *

    为当前矩形对象加一个点,以使当前矩形扩展为包含当前矩形和此点的最小矩形。

    *

    此方法会修改本对象。

    * @param x 点的 X 坐标。 * @param y 点的 Y 坐标。 * @return 返回此 Rectangle 对象。 */ addPoint(x: number, y: number): Rectangle; /** * @private * 返回代表当前矩形的顶点数据。 * @return 顶点数据。 */ _getBoundPoints(): Array; /** * @private * 返回矩形的顶点数据。 */ static _getBoundPointS(x: number, y: number, width: number, height: number): Array; /** * @private * 返回包含所有点的最小矩形。 * @param pointList 点列表。 * @return 包含所有点的最小矩形矩形对象。 */ static _getWrapRec(pointList: Array, rst?: Rectangle): Rectangle; /** * 确定此 Rectangle 对象是否为空。 * @return 如果 Rectangle 对象的宽度或高度小于等于 0,则返回 true 值,否则返回 false。 */ isEmpty(): boolean; } } declare module laya.media.h5audio { import EventDispatcher = laya.events.EventDispatcher; import SoundChannel = laya.media.SoundChannel; /** * @private * 使用Audio标签播放声音 */ class AudioSound extends EventDispatcher { /** * 声音URL */ url: string; /** * 播放用的audio标签 */ audio: any; /** * 是否已加载完成 */ loaded: boolean; static _musicAudio: any; /** * 释放声音 * */ dispose(): void; static _initMusicAudio(): void; /** * 加载声音 * @param url * */ load(url: string): void; /** * 播放声音 * @param startTime 起始时间 * @param loops 循环次数 * @return * */ play(startTime?: number, loops?: number): SoundChannel; /** * 获取总时间。 */ readonly duration: number; } } declare module laya.media.h5audio { import SoundChannel = laya.media.SoundChannel; /** * @private * audio标签播放声音的音轨控制 */ class AudioSoundChannel extends SoundChannel { constructor(audio: any); /** * 播放 */ play(): void; /** * 当前播放到的位置 * @return * */ readonly position: number; /** * 获取总时间。 */ readonly duration: number; /** * 停止播放 * */ stop(): void; pause(): void; resume(): void; /** * 获取音量 * @return * */ /** * 设置音量 * @param v * */ volume: number; } } declare module laya.media { import EventDispatcher = laya.events.EventDispatcher; /** * Sound 类是用来播放控制声音的类。 */ class Sound extends EventDispatcher { /** * 加载声音。 * @param url 地址。 * */ load(url: string): void; /** * 播放声音。 * @param startTime 开始时间,单位秒 * @param loops 循环次数,0表示一直循环 * @return 声道 SoundChannel 对象。 * */ play(startTime?: number, loops?: number): SoundChannel; /** * 获取总时间。 */ readonly duration: number; /** * 释放声音资源。 * */ dispose(): void; } } declare module laya.media { import EventDispatcher = laya.events.EventDispatcher; import Handler = laya.utils.Handler; /** *

    SoundChannel 用来控制程序中的声音。每个声音均分配给一个声道,而且应用程序可以具有混合在一起的多个声道。

    *

    SoundChannel 类包含控制声音的播放、暂停、停止、音量的方法,以及获取声音的播放状态、总时间、当前播放时间、总循环次数、播放地址等信息的方法。

    */ class SoundChannel extends EventDispatcher { /** * 声音地址。 */ url: string; /** * 循环次数。 */ loops: number; /** * 开始时间。 */ startTime: number; /** * 表示声音是否已暂停。 */ isStopped: boolean; /** * 播放完成处理器。 */ completeHandler: Handler; /** * 音量范围从 0(静音)至 1(最大音量)。 */ volume: number; /** * 获取当前播放时间。 */ readonly position: number; /** * 获取总时间。 */ readonly duration: number; /** * 播放。 */ play(): void; /** * 停止。 */ stop(): void; /** * 暂停。 */ pause(): void; /** * 继续播放。 */ resume(): void; protected __runComplete(handler: Handler): void; } } declare module laya.media { import Handler = laya.utils.Handler; /** * SoundManager 是一个声音管理类。提供了对背景音乐、音效的播放控制方法。 * 引擎默认有两套声音方案:WebAudio和H5Audio * 播放音效,优先使用WebAudio播放声音,如果WebAudio不可用,则用H5Audio播放,H5Audio在部分机器上有兼容问题(比如不能混音,播放有延迟等)。 * 播放背景音乐,则使用H5Audio播放(使用WebAudio会增加特别大的内存,并且要等加载完毕后才能播放,有延迟) * 建议背景音乐用mp3类型,音效用wav或者mp3类型(如果打包为app,音效只能用wav格式)。 * 详细教程及声音格式请参考:http://ldc.layabox.com/doc/?nav=ch-as-1-7-0 */ class SoundManager { /** * 背景音乐音量。 * @default 1 */ static musicVolume: number; /** * 音效音量。 * @default 1 */ static soundVolume: number; /** * 声音播放速率。 * @default 1 */ static playbackRate: number; static _tMusic: string; static _soundClass: any; static _musicClass: any; /** * 音效播放后自动删除。 * @default true */ static autoReleaseSound: boolean; /** * 添加播放的声音实例。 * @param channel SoundChannel 对象。 */ static addChannel(channel: SoundChannel): void; /** * 移除播放的声音实例。 * @param channel SoundChannel 对象。 */ static removeChannel(channel: SoundChannel): void; static disposeSoundIfNotUsed(url: string): void; /** * 失去焦点后是否自动停止背景音乐。 */ /** * 失去焦点后是否自动停止背景音乐。 * @param v Boolean 失去焦点后是否自动停止背景音乐。 * */ static autoStopMusic: boolean; /** * 背景音乐和所有音效是否静音。 */ static muted: boolean; /** * 所有音效(不包括背景音乐)是否静音。 */ static soundMuted: boolean; /** * 背景音乐(不包括音效)是否静音。 */ static musicMuted: boolean; static useAudioMusic: boolean; /** * 播放音效。音效可以同时播放多个。 * @param url 声音文件地址。 * @param loops 循环次数,0表示无限循环。 * @param complete 声音播放完成回调 Handler对象。 * @param soundClass 使用哪个声音类进行播放,null表示自动选择。 * @param startTime 声音播放起始时间。 * @return SoundChannel对象,通过此对象可以对声音进行控制,以及获取声音信息。 */ static playSound(url: string, loops?: number, complete?: Handler, soundClass?: any, startTime?: number): SoundChannel; /** * 释放声音资源。 * @param url 声音播放地址。 */ static destroySound(url: string): void; /** * 播放背景音乐。背景音乐同时只能播放一个,如果在播放背景音乐时再次调用本方法,会先停止之前的背景音乐,再播发当前的背景音乐。 * @param url 声音文件地址。 * @param loops 循环次数,0表示无限循环。 * @param complete 声音播放完成回调。 * @param startTime 声音播放起始时间。 * @return SoundChannel对象,通过此对象可以对声音进行控制,以及获取声音信息。 */ static playMusic(url: string, loops?: number, complete?: Handler, startTime?: number): SoundChannel; /** * 停止声音播放。此方法能够停止任意声音的播放(包括背景音乐和音效),只需传入对应的声音播放地址。 * @param url 声音文件地址。 */ static stopSound(url: string): void; /** * 停止播放所有声音(包括背景音乐和音效)。 */ static stopAll(): void; /** * 停止播放所有音效(不包括背景音乐)。 */ static stopAllSound(): void; /** * 停止播放背景音乐(不包括音效)。 * @param url 声音文件地址。 */ static stopMusic(): void; /** * 设置声音音量。根据参数不同,可以分别设置指定声音(背景音乐或音效)音量或者所有音效(不包括背景音乐)音量。 * @param volume 音量。初始值为1。音量范围从 0(静音)至 1(最大音量)。 * @param url (default = null)声音播放地址。默认为null。为空表示设置所有音效(不包括背景音乐)的音量,不为空表示设置指定声音(背景音乐或音效)的音量。 */ static setSoundVolume(volume: number, url?: string): void; /** * 设置背景音乐音量。音量范围从 0(静音)至 1(最大音量)。 * @param volume 音量。初始值为1。音量范围从 0(静音)至 1(最大音量)。 */ static setMusicVolume(volume: number): void; } } declare module laya.media { import Sprite = laya.display.Sprite; import Handler = laya.utils.Handler; /** * @private */ class SoundNode extends Sprite { url: string; constructor(); /** * 播放 * @param loops 循环次数 * @param complete 完成回调 * */ play(loops?: number, complete?: Handler): void; /** * 停止播放 * */ stop(): void; /** * 设置触发播放的事件 * @param events * */ playEvent: string; /** * 设置控制播放的对象 * @param tar * */ target: Sprite; /** * 设置触发停止的事件 * @param events * */ stopEvent: string; } } declare module laya.media.webaudio { import EventDispatcher = laya.events.EventDispatcher; import SoundChannel = laya.media.SoundChannel; /** * @private * web audio api方式播放声音 */ class WebAudioSound extends EventDispatcher { static window: any; /** * 是否支持web audio api */ static webAudioEnabled: boolean; /** * 播放设备 */ static ctx: any; /** * 当前要解码的声音文件列表 */ static buffs: Array; /** * 是否在解码中 */ static isDecoding: boolean; /** * 用于播放解锁声音以及解决Ios9版本的内存释放 */ static _miniBuffer: any; /** * 事件派发器,用于处理加载解码完成事件的广播 */ static e: EventDispatcher; /** * 当前解码的声音信息 */ static tInfo: any; /** * 声音URL */ url: string; /** * 是否已加载完成 */ loaded: boolean; /** * 声音文件数据 */ data: ArrayBuffer; /** * 声音原始文件数据 */ audioBuffer: any; /** * 解码声音文件 * */ static decode(): void; static initWebAudio(): void; /** * 加载声音 * @param url * */ load(url: string): void; /** * 播放声音 * @param startTime 起始时间 * @param loops 循环次数 * @return * */ play(startTime?: number, loops?: number, channel?: SoundChannel): SoundChannel; readonly duration: number; dispose(): void; } } declare module laya.media.webaudio { import SoundChannel = laya.media.SoundChannel; /** * @private * web audio api方式播放声音的音轨控制 */ class WebAudioSoundChannel extends SoundChannel { /** * 声音原始文件数据 */ audioBuffer: any; constructor(); /** * 播放声音 */ play(): void; /** * 获取当前播放位置 */ readonly position: number; readonly duration: number; /** * 停止播放 */ stop(): void; pause(): void; resume(): void; /** * 获取音量 */ /** * 设置音量 */ volume: number; } } declare module laya.net { import EventDispatcher = laya.events.EventDispatcher; /** *

    HttpRequest 通过封装 HTML XMLHttpRequest 对象提供了对 HTTP 协议的完全的访问,包括做出 POST 和 HEAD 请求以及普通的 GET 请求的能力。 HttpRequest 只提供以异步的形式返回 Web 服务器的响应,并且能够以文本或者二进制的形式返回内容。

    *

    注意:建议每次请求都使用新的 HttpRequest 对象,因为每次调用该对象的send方法时,都会清空之前设置的数据,并重置 HTTP 请求的状态,这会导致之前还未返回响应的请求被重置,从而得不到之前请求的响应结果。

    */ class HttpRequest extends EventDispatcher { protected _http: any; protected _responseType: string; protected _data: any; /** * 发送 HTTP 请求。 * @param url 请求的地址。大多数浏览器实施了一个同源安全策略,并且要求这个 URL 与包含脚本的文本具有相同的主机名和端口。 * @param data (default = null)发送的数据。 * @param method (default = "get")用于请求的 HTTP 方法。值包括 "get"、"post"、"head"。 * @param responseType (default = "text")Web 服务器的响应类型,可设置为 "text"、"json"、"xml"、"arraybuffer"。 * @param headers (default = null) HTTP 请求的头部信息。参数形如key-value数组:key是头部的名称,不应该包括空白、冒号或换行;value是头部的值,不应该包括换行。比如["Content-Type", "application/json"]。 */ send(url: string, data?: any, method?: string, responseType?: string, headers?: Array): void; protected _onProgress(e: any): void; protected _onAbort(e: any): void; protected _onError(e: any): void; protected _onLoad(e: any): void; protected error(message: string): void; protected complete(): void; protected clear(): void; /** 请求的地址。*/ readonly url: string; /** 返回的数据。*/ readonly data: any; /** * 本对象所封装的原生 XMLHttpRequest 引用。 */ readonly http: any; } } declare module laya.net { import EventDispatcher = laya.events.EventDispatcher; /** * Loader 类可用来加载文本、JSON、XML、二进制、图像等资源。 */ class Loader extends EventDispatcher { /** 文本类型,加载完成后返回文本。*/ static TEXT: string; /** JSON 类型,加载完成后返回json数据。*/ static JSON: string; /** XML 类型,加载完成后返回domXML。*/ static XML: string; /** 二进制类型,加载完成后返回arraybuffer二进制数据。*/ static BUFFER: string; /** 纹理类型,加载完成后返回Texture。*/ static IMAGE: string; /** 声音类型,加载完成后返回sound。*/ static SOUND: string; /** 图集类型,加载完成后返回图集json信息(并创建图集内小图Texture)。*/ static ATLAS: string; /** 位图字体类型,加载完成后返回BitmapFont。*/ static FONT: string; /** TTF字体类型,加载完成后返回null。*/ static TTF: string; static PKM: string; /** 文件后缀和类型对应表。*/ static typeMap: any; /**资源解析函数对应表,用来扩展更多类型的资源加载解析。*/ static parserMap: any; /** 资源分组对应表。*/ static groupMap: any; /** 每帧回调最大超时时间,如果超时,则下帧再处理。*/ static maxTimeOut: number; static loadedMap: any; static preLoadedAtlasConfigMap: any; protected static _loaders: Array; protected static _isWorking: boolean; protected static _startIndex: number; _data: any; _class: any; protected _url: string; protected _type: string; protected _cache: boolean; protected _http: HttpRequest; _customParse: boolean; /** * 加载资源。加载错误会派发 Event.ERROR 事件,参数为错误信息。 * @param url 资源地址。 * @param type (default = null)资源类型。可选值为:Loader.TEXT、Loader.JSON、Loader.XML、Loader.BUFFER、Loader.IMAGE、Loader.SOUND、Loader.ATLAS、Loader.FONT。如果为null,则根据文件后缀分析类型。 * @param cache (default = true)是否缓存数据。 * @param group (default = null)分组名称。 * @param ignoreCache (default = false)是否忽略缓存,强制重新加载。 */ load(url: string, type?: string, cache?: boolean, group?: string, ignoreCache?: boolean): void; protected getTypeFromUrl(url: string): string; protected _loadTTF(url: string): void; protected _loadImage(url: string): void; protected _loadSound(url: string): void; protected onProgress(value: number): void; protected onError(message: string): void; protected onLoaded(data?: any): void; protected complete(data: any): void; /** * 结束加载,处理是否缓存及派发完成事件 Event.COMPLETE 。 * @param content 加载后的数据 */ endLoad(content?: any): void; /** 加载地址。*/ readonly url: string; /**加载类型。*/ readonly type: string; /**是否缓存。*/ readonly cache: boolean; /**返回的数据。*/ readonly data: any; /** * 清理指定资源地址的缓存。 * 如果是Texture,则采用引用计数方式销毁,【注意】如果图片本身在自动合集里面(默认图片小于512*512),内存是不能被销毁的,此图片会被大图合集管理器管理 * @param url 资源地址。 * @param forceDispose 是否强制销毁,有些资源是采用引用计数方式销毁,如果forceDispose=true,则忽略引用计数,直接销毁,比如Texture,默认为false */ static clearRes(url: string, forceDispose?: boolean): void; /** * 销毁Texture使用的图片资源,保留texture壳,如果下次渲染的时候,发现texture使用的图片资源不存在,则会自动恢复 * 相比clearRes,clearTextureRes只是清理texture里面使用的图片资源,并不销毁texture,再次使用到的时候会自动恢复图片资源 * 而clearRes会彻底销毁texture,导致不能再使用;clearTextureRes能确保立即销毁图片资源,并且不用担心销毁错误,clearRes则采用引用计数方式销毁 * 【注意】如果图片本身在自动合集里面(默认图片小于512*512),内存是不能被销毁的,此图片被大图合集管理器管理 * @param url 图集地址或者texture地址,比如 Loader.clearTextureRes("res/atlas/comp.atlas"); Loader.clearTextureRes("hall/bg.jpg"); */ static clearTextureRes(url: string): void; /** * 设置预加载的图集配置文件 * @param url 资源地址。 * @param configO 配置数据 */ static setAtlasConfigs(url: string, config: any): void; /** * 获取指定资源地址的资源。 * @param url 资源地址。 * @return 返回资源。 */ static getRes(url: string): any; /** * 获取指定资源地址的图集地址列表。 * @param url 图集地址。 * @return 返回地址集合。 */ static getAtlas(url: string): Array; /** * 缓存资源。 * @param url 资源地址。 * @param data 要缓存的内容。 */ static cacheRes(url: string, data: any): void; /** * 设置资源分组。 * @param url 资源地址。 * @param group 分组名。 */ static setGroup(url: string, group: string): void; /** * 根据分组清理资源。 * @param group 分组名。 */ static clearResByGroup(group: string): void; } } declare module laya.net { import EventDispatcher = laya.events.EventDispatcher; import Handler = laya.utils.Handler; /** *

    LoaderManager 类用于用于批量加载资源。此类是单例,不要手动实例化此类,请通过Laya.loader访问。

    *

    全部队列加载完成,会派发 Event.COMPLETE 事件;如果队列中任意一个加载失败,会派发 Event.ERROR 事件,事件回调参数值为加载出错的资源地址。

    *

    LoaderManager 类提供了以下几种功能:
    * 多线程:默认5个加载线程,可以通过maxLoader属性修改线程数量;
    * 多优先级:有0-4共5个优先级,优先级高的优先加载。0最高,4最低;
    * 重复过滤:自动过滤重复加载(不会有多个相同地址的资源同时加载)以及复用缓存资源,防止重复加载;
    * 错误重试:资源加载失败后,会重试加载(以最低优先级插入加载队列),retryNum设定加载失败后重试次数,retryDelay设定加载重试的时间间隔。

    * @see laya.net.Loader */ class LoaderManager extends EventDispatcher { static createMap: any; /** 加载出错后的重试次数,默认重试一次*/ retryNum: number; /** 延迟时间多久再进行错误重试,默认立即重试*/ retryDelay: number; /** 最大下载线程,默认为5个*/ maxLoader: number; /** *

    创建一个新的 LoaderManager 实例。

    *

    注意:请使用Laya.loader加载资源,这是一个单例,不要手动实例化此类,否则会导致不可预料的问题。

    */ constructor(); /** *

    根据clas类型创建一个未初始化资源的对象,随后进行异步加载,资源加载完成后,初始化对象的资源,并通过此对象派发 Event.LOADED 事件,事件回调参数值为此对象本身。套嵌资源的子资源会保留资源路径"?"后的部分。

    *

    如果url为数组,返回true;否则返回指定的资源类对象,可以通过侦听此对象的 Event.LOADED 事件来判断资源是否已经加载完毕。

    *

    注意:cache参数只能对文件后缀为atlas的资源进行缓存控制,其他资源会忽略缓存,强制重新加载。

    * @param url 资源地址或者数组。如果url和clas同时指定了资源类型,优先使用url指定的资源类型。参数形如:[ * @param complete 加载结束回调。根据url类型不同分为2种情况:1. url为String类型,也就是单个资源地址,如果加载成功,则回调参数值为加载完成的资源,否则为null;2. url为数组类型,指定了一组要加载的资源,如果全部加载成功,则回调参数值为true,否则为false。 * @param progress 资源加载进度回调,回调参数值为当前资源加载的进度信息(0-1)。 * @param clas 资源类名。如果url和clas同时指定了资源类型,优先使用url指定的资源类型。参数形如:Texture。 * @param params 资源构造参数。 * @param priority (default = 1)加载的优先级,优先级高的优先加载。有0-4共5个优先级,0最高,4最低。 * @param cache 是否缓存加载的资源。 * @return 如果url为数组,返回true;否则返回指定的资源类对象。 */ create(url: any, complete?: Handler, progress?: Handler, clas?: any, params?: Array, priority?: number, cache?: boolean, group?: string): any; /** *

    加载资源。资源加载错误时,本对象会派发 Event.ERROR 事件,事件回调参数值为加载出错的资源地址。

    *

    因为返回值为 LoaderManager 对象本身,所以可以使用如下语法:Laya.loader.load(...).load(...);

    * @param url 要加载的单个资源地址或资源信息数组。比如:简单数组:["a.png","b.png"];复杂数组[ * @param complete 加载结束回调。根据url类型不同分为2种情况:1. url为String类型,也就是单个资源地址,如果加载成功,则回调参数值为加载完成的资源,否则为null;2. url为数组类型,指定了一组要加载的资源,如果全部加载成功,则回调参数值为true,否则为false。 * @param progress 加载进度回调。回调参数值为当前资源的加载进度信息(0-1)。 * @param type 资源类型。比如:Loader.IMAGE。 * @param priority (default = 1)加载的优先级,优先级高的优先加载。有0-4共5个优先级,0最高,4最低。 * @param cache 是否缓存加载结果。 * @param group 分组,方便对资源进行管理。 * @param ignoreCache 是否忽略缓存,强制重新加载。 * @return 此 LoaderManager 对象本身。 */ load(url: any, complete?: Handler, progress?: Handler, type?: string, priority?: number, cache?: boolean, group?: string, ignoreCache?: boolean): LoaderManager; /** * @private */ _createLoad(item: any, url: any, complete?: Handler, progress?: Handler, type?: string, priority?: number, cache?: boolean, group?: string, ignoreCache?: boolean): LoaderManager; /** * 清理指定资源地址缓存。 * @param url 资源地址。 * @param forceDispose 是否强制销毁,有些资源是采用引用计数方式销毁,如果forceDispose=true,则忽略引用计数,直接销毁,比如Texture,默认为false */ clearRes(url: string, forceDispose?: boolean): void; /** * 获取指定资源地址的资源。 * @param url 资源地址。 * @return 返回资源。 */ getRes(url: string): any; /** * 缓存资源。 * @param url 资源地址。 * @param data 要缓存的内容。 */ cacheRes(url: string, data: any): void; /** * 销毁Texture使用的图片资源,保留texture壳,如果下次渲染的时候,发现texture使用的图片资源不存在,则会自动恢复 * 相比clearRes,clearTextureRes只是清理texture里面使用的图片资源,并不销毁texture,再次使用到的时候会自动恢复图片资源 * 而clearRes会彻底销毁texture,导致不能再使用;clearTextureRes能确保立即销毁图片资源,并且不用担心销毁错误,clearRes则采用引用计数方式销毁 * 【注意】如果图片本身在自动合集里面(默认图片小于512*512),内存是不能被销毁的,此图片被大图合集管理器管理 * @param url 图集地址或者texture地址,比如 Loader.clearTextureRes("res/atlas/comp.atlas"); Loader.clearTextureRes("hall/bg.jpg"); */ clearTextureRes(url: string): void; /** * 设置资源分组。 * @param url 资源地址。 * @param group 分组名 */ setGroup(url: string, group: string): void; /** * 根据分组清理资源。 * @param group 分组名 */ clearResByGroup(group: string): void; /** * @private * 缓存资源。 * @param url 资源地址。 * @param data 要缓存的内容。 */ static cacheRes(url: string, data: any): void; /** 清理当前未完成的加载,所有未加载的内容全部停止加载。*/ clearUnLoaded(): void; /** * 根据地址集合清理掉未加载的内容 * @param urls 资源地址集合 */ cancelLoadByUrls(urls: Array): void; /** * 根据地址清理掉未加载的内容 * @param url 资源地址 */ cancelLoadByUrl(url: string): void; } class ResInfo extends EventDispatcher { url: string; type: string; cache: boolean; group: string; ignoreCache: boolean; clas: any; } } declare module laya.net { /** *

    LocalStorage 类用于没有时间限制的数据存储。

    */ class LocalStorage { static _baseClass: any; /** * 数据列表。 */ static items: any; /** * 表示是否支持 LocalStorage。 */ static support: boolean; static __init__(): void; /** * 存储指定键名和键值,字符串类型。 * @param key 键名。 * @param value 键值。 */ static setItem(key: string, value: string): void; /** * 获取指定键名的值。 * @param key 键名。 * @return 字符串型值。 */ static getItem(key: string): string; /** * 存储指定键名及其对应的 Object 类型值。 * @param key 键名。 * @param value 键值。是 Object 类型,此致会被转化为 JSON 字符串存储。 */ static setJSON(key: string, value: any): void; /** * 获取指定键名对应的 Object 类型值。 * @param key 键名。 * @return Object 类型值 */ static getJSON(key: string): any; /** * 删除指定键名的信息。 * @param key 键名。 */ static removeItem(key: string): void; /** * 清除本地存储信息。 */ static clear(): void; } class Storage { /** * 数据列表。 */ static items: any; /** * 表示是否支持 LocalStorage。 */ static support: boolean; static init(): void; /** * 存储指定键名和键值,字符串类型。 * @param key 键名。 * @param value 键值。 */ static setItem(key: string, value: string): void; /** * 获取指定键名的值。 * @param key 键名。 * @return 字符串型值。 */ static getItem(key: string): string; /** * 存储指定键名和它的 Object 类型值。 * @param key 键名。 * @param value 键值。是 Object 类型,此致会被转化为 JSON 字符串存储。 */ static setJSON(key: string, value: any): void; /** * 获取指定键名的 Object 类型值。 * @param key 键名。 * @return Object 类型值 */ static getJSON(key: string): any; /** * 删除指定键名的信息。 * @param key 键名。 */ static removeItem(key: string): void; /** * 清除本地存储信息。 */ static clear(): void; } } declare module laya.net { import Handler = laya.utils.Handler; /** *

    资源版本的生成由layacmd或IDE完成,使用 ResourceVersion 简化使用过程。

    *

    调用 enable 启用资源版本管理。

    */ class ResourceVersion { /**基于文件夹的资源管理方式(老版本IDE默认类型)*/ static FOLDER_VERSION: number; /**基于文件名映射管理方式(新版本IDE默认类型)*/ static FILENAME_VERSION: number; /**版本清单*/ static manifest: any; /**当前使用的版本管理类型*/ static type: number; /** *

    启用资源版本管理。

    *

    由于只有发布版本需要资源管理。因此没有资源管理文件时,可以设置manifestFile为null或者不存在的路径。

    * @param manifestFile 清单(json)文件的路径。 * @param callback 清单(json)文件加载完成后执行。 * @param type FOLDER_VERSION为基于文件夹管理方式(老版本IDE默认类型),FILENAME_VERSION为基于文件名映射管理(新版本IDE默认类型 */ static enable(manifestFile: string, callback: Handler, type?: number): void; /** * 为加载路径添加版本前缀。 * @param originURL 源路径。 * @return 格式化后的新路径。 */ static addVersionPrefix(originURL: string): string; } } declare module laya.net { import EventDispatcher = laya.events.EventDispatcher; /** *

    Socket 封装了 HTML5 WebSocket ,允许服务器端与客户端进行全双工(full-duplex)的实时通信,并且允许跨域通信。在建立连接后,服务器和 Browser/Client Agent 都能主动的向对方发送或接收文本和二进制数据。

    *

    要使用 Socket 类的方法,请先使用构造函数 new Socket 创建一个 Socket 对象。 Socket 以异步方式传输和接收数据。

    */ class Socket extends EventDispatcher { /** *

    主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。

    *

    LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。

    *

    BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。

    */ static LITTLE_ENDIAN: string; /** *

    主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。

    *

    BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。

    *

    LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。

    */ static BIG_ENDIAN: string; _endian: string; protected _socket: any; /** * @private * 表示建立连接时需等待的毫秒数。 */ timeout: number; /** * @private * 在写入或读取对象时,控制所使用的 AMF 的版本。 */ objectEncoding: number; /** * 不再缓存服务端发来的数据。 */ disableInput: boolean; /** *

    子协议名称。子协议名称字符串,或由多个子协议名称字符串构成的数组。必须在调用 connect 或者 connectByUrl 之前进行赋值,否则无效。

    *

    指定后,只有当服务器选择了其中的某个子协议,连接才能建立成功,否则建立失败,派发 Event.ERROR 事件。

    * @see https://html.spec.whatwg.org/multipage/comms.html#dom-websocket */ protocols: any; /** * 缓存的服务端发来的数据。 */ readonly input: any; /** * 表示需要发送至服务端的缓冲区中的数据。 */ readonly output: any; /** * 表示此 Socket 对象目前是否已连接。 */ readonly connected: boolean; /** *

    主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。

    *

    LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。

    *

    BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。

    */ endian: string; /** *

    创建新的 Socket 对象。默认字节序为 Socket.BIG_ENDIAN 。若未指定参数,将创建一个最初处于断开状态的套接字。若指定了有效参数,则尝试连接到指定的主机和端口。

    *

    注意:强烈建议使用不带参数的构造函数形式,并添加任意事件侦听器和设置 protocols 等属性,然后使用 host 和 port 参数调用 connect 方法。此顺序将确保所有事件侦听器和其他相关流程工作正常。

    * @param host 服务器地址。 * @param port 服务器端口。 * @param byteClass 用于接收和发送数据的 Byte 类。如果为 null ,则使用 Byte 类,也可传入 Byte 类的子类。 * @see laya.utils.Byte */ constructor(host?: string, port?: number, byteClass?: any); /** *

    连接到指定的主机和端口。

    *

    连接成功派发 Event.OPEN 事件;连接失败派发 Event.ERROR 事件;连接被关闭派发 Event.CLOSE 事件;接收到数据派发 Event.MESSAGE 事件; 除了 Event.MESSAGE 事件参数为数据内容,其他事件参数都是原生的 HTML DOM Event 对象。

    * @param host 服务器地址。 * @param port 服务器端口。 */ connect(host: string, port: number): void; /** *

    连接到指定的服务端 WebSocket URL。 URL 类似 ws://yourdomain:port。

    *

    连接成功派发 Event.OPEN 事件;连接失败派发 Event.ERROR 事件;连接被关闭派发 Event.CLOSE 事件;接收到数据派发 Event.MESSAGE 事件; 除了 Event.MESSAGE 事件参数为数据内容,其他事件参数都是原生的 HTML DOM Event 对象。

    * @param url 要连接的服务端 WebSocket URL。 URL 类似 ws://yourdomain:port。 */ connectByUrl(url: string): void; /** * 清理socket。 */ cleanSocket(): void; /** * 关闭连接。 */ close(): void; protected _onOpen(e: any): void; protected _onMessage(msg: any): void; protected _onClose(e: any): void; protected _onError(e: any): void; /** * 发送数据到服务器。 * @param data 需要发送的数据,可以是String或者ArrayBuffer。 */ send(data: any): void; /** * 发送缓冲区中的数据到服务器。 */ flush(): void; } } declare module laya.net { import Handler = laya.utils.Handler; /** * @private */ class TTFLoader { constructor(); fontName: string; complete: Handler; err: Handler; load(fontPath: string): void; } } declare module laya.net { /** *

    URL 类用于定义地址信息。

    */ class URL { /**版本号。*/ static version: any; /**创建一个新的 URL 实例。*/ constructor(url: string); /**格式化后的地址。*/ readonly url: string; /**地址的路径。*/ readonly path: string; /**基础路径。*/ static basePath: string; /**根路径。*/ static rootPath: string; /** 自定义url格式化。例如: customFormat=function(url:string):string} */ static customFormat: Function; /** * 格式化指定的地址并 返回。 * @param url 地址。 * @param base 路径。 * @return 格式化处理后的地址。 */ static formatURL(url: string, base?: string): string; /** * @private * 获取指定 URL 的路径。 *

    注意:末尾有斜杠(/)。

    * @param url 地址。 * @return url 的路径。 */ static getPath(url: string): string; /** * 获取指定 URL 的文件名。 * @param url 地址。 * @return url 的文件名。 */ static getFileName(url: string): string; } } declare module laya.net { import EventDispatcher = laya.events.EventDispatcher; /** * @private * Worker Image加载器 */ class WorkerLoader extends EventDispatcher { /** * 图片加载完成事件 */ static IMAGE_LOADED: string; /** * 图片加载失败事件 */ static IMAGE_ERR: string; /** * 图片加载过程中的信息 */ static IMAGE_MSG: string; /** * 实例 */ static I: WorkerLoader; /** * worker.js的路径 */ static workerPath: string; /** * 是否禁用js解码,如果禁用则如果浏览器不支持解码接口自动关闭WorkerLoader */ static disableJSDecode: boolean; /** * 尝试使用Work加载Image * @return 是否启动成功 */ static __init__(): boolean; /** * 是否支持worker * @return 是否支持worker */ static workerSupported(): boolean; /** * 是否启用。 */ static enable: boolean; /** * 使用的Worker对象。 */ worker: Worker; constructor(); /** * 加载图片 * @param url 图片地址 */ loadImage(url: string): void; protected _loadImage(url: string): void; } } declare module laya.particle.emitter { import ParticleSetting = laya.particle.ParticleSetting; import ParticleTemplateBase = laya.particle.ParticleTemplateBase; /** * * @private */ class Emitter2D extends EmitterBase { setting: ParticleSetting; constructor(_template: ParticleTemplateBase); template: ParticleTemplateBase; emit(): void; getRandom(value: number): number; webGLEmit(): void; canvasEmit(): void; } } declare module laya.particle.emitter { import ParticleTemplateBase = laya.particle.ParticleTemplateBase; /** * EmitterBase 类是粒子发射器类 */ class EmitterBase { protected _frameTime: number; protected _emissionRate: number; protected _emissionTime: number; /** * 发射粒子最小时间间隔 */ minEmissionTime: number; _particleTemplate: ParticleTemplateBase; /** * 设置粒子粒子模板 * @param particleTemplate 粒子模板 * */ particleTemplate: ParticleTemplateBase; /** * 获取粒子发射速率 * @return 发射速率 粒子发射速率 (个/秒) */ /** * 设置粒子发射速率 * @param emissionRate 粒子发射速率 (个/秒) */ emissionRate: number; /** * 开始发射粒子 * @param duration 发射持续的时间(秒) */ start(duration?: number): void; /** * 停止发射粒子 * @param clearParticles 是否清理当前的粒子 */ stop(): void; /** * 清理当前的活跃粒子 * @param clearTexture 是否清理贴图数据,若清除贴图数据将无法再播放 */ clear(): void; /** * 发射一个粒子 * */ emit(): void; /** * 时钟前进 * @param passedTime 前进时间 * */ advanceTime(passedTime?: number): void; } } declare module laya.particle { import Sprite = laya.display.Sprite; import EmitterBase = laya.particle.emitter.EmitterBase; import RenderContext = laya.renders.RenderContext; /** * Particle2D 类是2D粒子播放类 * */ class Particle2D extends Sprite { /**是否自动播放*/ autoPlay: boolean; /** * 创建一个新的 Particle2D 类实例。 * @param setting 粒子配置数据 */ constructor(setting: ParticleSetting); /** * 设置 粒子文件地址 * @param path 粒子文件地址 */ url: string; /** * 加载粒子文件 * @param url 粒子文件地址 */ load(url: string): void; /** * 设置粒子配置数据 * @param settings 粒子配置数据 */ setParticleSetting(setting: ParticleSetting): void; /** * 获取粒子发射器 */ readonly emitter: EmitterBase; /** * 播放 */ play(): void; /** * 停止 */ stop(): void; /** * 时钟前进 * @param passedTime 时钟前进时间 */ advanceTime(passedTime?: number): void; customRender(context: RenderContext, x: number, y: number): void; destroy(destroyChild?: boolean): void; } } declare module laya.particle { /** * @private */ class ParticleData { position: Float32Array; velocity: Float32Array; startColor: Float32Array; endColor: Float32Array; sizeRotation: Float32Array; radius: Float32Array; radian: Float32Array; durationAddScale: number; time: number; constructor(); static Create(settings: ParticleSetting, position: Float32Array, velocity: Float32Array, time: number): ParticleData; } } declare module laya.particle { /** * @private */ class ParticleEmitter { constructor(templet: ParticleTemplateBase, particlesPerSecond: number, initialPosition: Float32Array); update(elapsedTime: number, newPosition: Float32Array): void; } } declare module laya.particle { /** * ParticleSettings 类是粒子配置数据类 */ class ParticleSetting { /**贴图*/ textureName: string; /**贴图个数,默认为1可不设置*/ textureCount: number; /**最大同屏粒子个数,最大饱和粒子数为maxPartices-1。注意:WebGL模式下释放粒子时间为最大声明周期,可能会出现释放延迟,实际看到的同屏粒子数小于该数值,如连续喷发出现中断,请调大该数值。*/ maxPartices: number; /**粒子持续时间(单位:秒)*/ duration: number; /**如果大于0,某些粒子的持续时间会小于其他粒子,并具有随机性(单位:无)*/ ageAddScale: number; /**粒子受发射器速度的敏感度(需在自定义发射器中编码设置)*/ emitterVelocitySensitivity: number; /**最小开始尺寸(单位:2D像素、3D坐标)*/ minStartSize: number; /**最大开始尺寸(单位:2D像素、3D坐标)*/ maxStartSize: number; /**最小结束尺寸(单位:2D像素、3D坐标)*/ minEndSize: number; /**最大结束尺寸(单位:2D像素、3D坐标)*/ maxEndSize: number; /**最小水平速度(单位:2D像素、3D坐标)*/ minHorizontalVelocity: number; /**最大水平速度(单位:2D像素、3D坐标)*/ maxHorizontalVelocity: number; /**最小垂直速度(单位:2D像素、3D坐标)*/ minVerticalVelocity: number; /**最大垂直速度(单位:2D像素、3D坐标)*/ maxVerticalVelocity: number; /**等于1时粒子从出生到消亡保持一致的速度,等于0时粒子消亡时速度为0,大于1时粒子会保持加速(单位:无)*/ endVelocity: number; /**(单位:2D像素、3D坐标)*/ gravity: Float32Array; /**最小旋转速度(单位:2D弧度/秒、3D弧度/秒)*/ minRotateSpeed: number; /**最大旋转速度(单位:2D弧度/秒、3D弧度/秒)*/ maxRotateSpeed: number; /**最小开始半径(单位:2D像素、3D坐标)*/ minStartRadius: number; /**最大开始半径(单位:2D像素、3D坐标)*/ maxStartRadius: number; /**最小结束半径(单位:2D像素、3D坐标)*/ minEndRadius: number; /**最大结束半径(单位:2D像素、3D坐标)*/ maxEndRadius: number; /**最小水平开始弧度(单位:2D弧度、3D弧度)*/ minHorizontalStartRadian: number; /**最大水平开始弧度(单位:2D弧度、3D弧度)*/ maxHorizontalStartRadian: number; /**最小垂直开始弧度(单位:2D弧度、3D弧度)*/ minVerticalStartRadian: number; /**最大垂直开始弧度(单位:2D弧度、3D弧度)*/ maxVerticalStartRadian: number; /**是否使用结束弧度,false为结束时与起始弧度保持一致,true为根据minHorizontalEndRadian、maxHorizontalEndRadian、minVerticalEndRadian、maxVerticalEndRadian计算结束弧度。*/ useEndRadian: boolean; /**最小水平结束弧度(单位:2D弧度、3D弧度)*/ minHorizontalEndRadian: number; /**最大水平结束弧度(单位:2D弧度、3D弧度)*/ maxHorizontalEndRadian: number; /**最小垂直结束弧度(单位:2D弧度、3D弧度)*/ minVerticalEndRadian: number; /**最大垂直结束弧度(单位:2D弧度、3D弧度)*/ maxVerticalEndRadian: number; /**最小开始颜色*/ minStartColor: Float32Array; /**最大开始颜色*/ maxStartColor: Float32Array; /**最小结束颜色*/ minEndColor: Float32Array; /**最大结束颜色*/ maxEndColor: Float32Array; /**false代表RGBA整体插值,true代表RGBA逐分量插值*/ colorComponentInter: boolean; /**false代表使用参数颜色数据,true代表使用原图颜色数据*/ disableColor: boolean; /**混合模式,待调整,引擎中暂无BlendState抽象*/ blendState: number; /**发射器类型,"point","box","sphere","ring"*/ emitterType: string; /**发射器发射速率*/ emissionRate: number; /**点发射器位置*/ pointEmitterPosition: Float32Array; /**点发射器位置随机值*/ pointEmitterPositionVariance: Float32Array; /**点发射器速度*/ pointEmitterVelocity: Float32Array; /**点发射器速度随机值*/ pointEmitterVelocityAddVariance: Float32Array; /**盒发射器中心位置*/ boxEmitterCenterPosition: Float32Array; /**盒发射器尺寸*/ boxEmitterSize: Float32Array; /**盒发射器速度*/ boxEmitterVelocity: Float32Array; /**盒发射器速度随机值*/ boxEmitterVelocityAddVariance: Float32Array; /**球发射器中心位置*/ sphereEmitterCenterPosition: Float32Array; /**球发射器半径*/ sphereEmitterRadius: number; /**球发射器速度*/ sphereEmitterVelocity: number; /**球发射器速度随机值*/ sphereEmitterVelocityAddVariance: number; /**环发射器中心位置*/ ringEmitterCenterPosition: Float32Array; /**环发射器半径*/ ringEmitterRadius: number; /**环发射器速度*/ ringEmitterVelocity: number; /**环发射器速度随机值*/ ringEmitterVelocityAddVariance: number; /**环发射器up向量,0代表X轴,1代表Y轴,2代表Z轴*/ ringEmitterUp: number; /**发射器位置随机值,2D使用*/ positionVariance: Float32Array; /** * 创建一个新的 ParticleSettings 类实例。 * */ constructor(); static checkSetting(setting: any): void; } } declare module laya.particle { import ParticleShaderValue = laya.particle.shader.value.ParticleShaderValue; import ISubmit = laya.webgl.submit.ISubmit; /** * @private */ class ParticleTemplate2D extends ParticleTemplateWebGL implements ISubmit { static activeBlendType: number; x: number; y: number; protected _blendFn: Function; sv: ParticleShaderValue; constructor(parSetting: ParticleSetting); getRenderType(): number; releaseRender(): void; addParticleArray(position: Float32Array, velocity: Float32Array): void; protected loadContent(): void; addNewParticlesToVertexBuffer(): void; renderSubmit(): number; blend(): void; dispose(): void; } } declare module laya.particle { import Texture = laya.resource.Texture; /** * * ParticleTemplateBase 类是粒子模板基类 * */ class ParticleTemplateBase { /** * 粒子配置数据 */ settings: ParticleSetting; protected texture: Texture; /** * 创建一个新的 ParticleTemplateBase 类实例。 * */ constructor(); /** * 添加一个粒子 * @param position 粒子位置 * @param velocity 粒子速度 * */ addParticleArray(position: Float32Array, velocity: Float32Array): void; } } declare module laya.particle { import RenderContext = laya.renders.RenderContext; /** * @private */ class ParticleTemplateCanvas extends ParticleTemplateBase { /** * 贴图列表 */ textureList: Array; /** * 粒子列表 */ particleList: Array; /** * 贴图中心偏移x */ pX: number; /** * 贴图中心偏移y */ pY: number; /** * 当前活跃的粒子 */ activeParticles: Array; /** * 粒子pool */ deadParticles: Array; /** * 粒子播放进度列表 */ iList: Array; protected _maxNumParticles: number; /** * 纹理的宽度 */ textureWidth: number; /** * 宽度倒数 */ dTextureWidth: number; /** * 是否支持颜色变化 */ colorChange: boolean; /** * 采样步长 */ step: number; constructor(particleSetting: ParticleSetting); clear(clearTexture?: boolean): void; /** * 设置纹理 * @param texture * */ setTexture(texture: any): void; static changeTexture(texture: any, rst: Array, settings?: ParticleSetting): Array; addParticleArray(position: Float32Array, velocity: Float32Array): void; advanceTime(passedTime?: number): void; render(context: RenderContext, x: number, y: number): void; noColorRender(context: RenderContext, x: number, y: number): void; canvasRender(context: RenderContext, x: number, y: number): void; } } declare module laya.particle { import Buffer = laya.webgl.utils.Buffer; /** * @private */ class ParticleTemplateWebGL extends ParticleTemplateBase { protected _vertices: Float32Array; protected _vertexBuffer: Buffer; protected _indexBuffer: Buffer; protected _floatCountPerVertex: number; protected _firstActiveElement: number; protected _firstNewElement: number; protected _firstFreeElement: number; protected _firstRetiredElement: number; _currentTime: number; protected _drawCounter: number; constructor(parSetting: ParticleSetting); protected initialize(): void; protected loadContent(): void; update(elapsedTime: number): void; addNewParticlesToVertexBuffer(): void; addParticleArray(position: Float32Array, velocity: Float32Array): void; } } declare module laya.particle.particleUtils { /** * @private */ class CanvasShader { u_Duration: number; u_EndVelocity: number; u_Gravity: Float32Array; a_Position: Float32Array; a_Velocity: Float32Array; a_StartColor: Float32Array; a_EndColor: Float32Array; a_SizeRotation: Float32Array; a_Radius: Float32Array; a_Radian: Float32Array; a_AgeAddScale: number; _color: Float32Array; gl_Position: Float32Array; v_Color: Float32Array; oSize: number; _position: Float32Array; constructor(); getLen(position: Float32Array): number; ComputeParticlePosition(position: Float32Array, velocity: Float32Array, age: number, normalizedAge: number): Float32Array; ComputeParticleSize(startSize: number, endSize: number, normalizedAge: number): number; ComputeParticleRotation(rot: number, age: number): number; ComputeParticleColor(startColor: Float32Array, endColor: Float32Array, normalizedAge: number): Float32Array; clamp(value: number, min: number, max: number): number; getData(age: number): Array; } } declare module laya.particle.particleUtils { /** * * @private * * @created 2015-8-25 下午3:41:07 */ class CMDParticle { constructor(); /** * 最大帧 */ maxIndex: number; /** * 帧命令数组 */ cmds: Array; /** * 粒子id */ id: number; setCmds(cmds: Array): void; } } declare module laya.particle.particleUtils { class PicTool { static getCanvasPic(img: any, color: number): any; static getRGBPic(img: any): Array; } } declare module laya.particle.shader { import Shader = laya.webgl.shader.Shader; /** * @private */ class ParticleShader extends Shader { static vs: string; static ps: string; constructor(); } } declare module laya.particle.shader.value { import Value2D = laya.webgl.shader.d2.value.Value2D; /** * @private */ class ParticleShaderValue extends Value2D { a_CornerTextureCoordinate: Array; a_Position: Array; a_Velocity: Array; a_StartColor: Array; a_EndColor: Array; a_SizeRotation: Array; a_Radius: Array; a_Radian: Array; a_AgeAddScale: Array; a_Time: Array; u_CurrentTime: number; u_Duration: number; u_Gravity: Float32Array; u_EndVelocity: number; u_texture: any; constructor(); upload(): void; } } declare module laya.renders { import HTMLCanvas = laya.resource.HTMLCanvas; /** * @private * Render 是渲染管理类。它是一个单例,可以使用 Laya.render 访问。 */ class Render { static _context: RenderContext; static _mainCanvas: HTMLCanvas; static WebGL: any; /**是否是Flash模式*/ static isFlash: boolean; /**加速器模式下设置是否是节点模式 如果是否就是非节点模式 默认为canvas模式 如果设置了isConchWebGL则是webGL模式*/ static isConchNode: boolean; /**是否是加速器 只读*/ static isConchApp: boolean; /**加速器模式下设置是否是节点模式 如果是否就是非节点模式 默认为canvas模式 如果设置了isConchWebGL则是webGL模式*/ static isConchWebGL: boolean; /**是否是WebGL模式*/ static isWebGL: boolean; /** 表示是否是 3D 模式。*/ static is3DMode: boolean; static optimizeTextureMemory: Function; constructor(width: number, height: number); /** 目前使用的渲染器。*/ static readonly context: RenderContext; /** 渲染使用的原生画布引用。 */ static readonly canvas: any; } } declare module laya.renders { import Matrix = laya.maths.Matrix; import HTMLCanvas = laya.resource.HTMLCanvas; import Texture = laya.resource.Texture; /** * @private * 渲染环境 */ class RenderContext { /**Math.PI*2的结果缓存 */ static PI2: number; /**全局x坐标 */ x: number; /**全局y坐标 */ y: number; /**当前使用的画布 */ canvas: HTMLCanvas; /**当前使用的画布上下文 */ ctx: any; /**销毁当前渲染环境*/ destroy(): void; constructor(width: number, height: number, canvas?: HTMLCanvas); drawTexture(tex: Texture, x: number, y: number, width: number, height: number): void; _drawTexture: Function; _drawTextures(x: number, y: number, args: Array): void; _fillTexture: Function; drawTextureWithTransform(tex: Texture, x: number, y: number, width: number, height: number, m: Matrix, alpha: number): void; _drawTextureWithTransform: Function; fillQuadrangle(tex: any, x: number, y: number, point4: Array, m: Matrix): void; _fillQuadrangle: Function; drawCanvas(canvas: HTMLCanvas, x: number, y: number, width: number, height: number): void; drawRect(x: number, y: number, width: number, height: number, color: string, lineWidth?: number): void; _drawRect: Function; _drawPie: Function; clipRect(x: number, y: number, width: number, height: number): void; _clipRect: Function; fillRect(x: number, y: number, width: number, height: number, fillStyle: any): void; _fillRect: Function; drawCircle(x: number, y: number, radius: number, color: string, lineWidth?: number): void; _drawCircle: Function; /** * 绘制三角形 * @param x * @param y * @param tex * @param args [x, y, texture,vertices,indices,uvs,matrix] */ drawTriangles(x: number, y: number, args: Array): void; fillCircle(x: number, y: number, radius: number, color: string): void; _fillCircle: Function; setShader(shader: any): void; _setShader: Function; drawLine(fromX: number, fromY: number, toX: number, toY: number, color: string, lineWidth?: number): void; _drawLine: Function; _drawLines: Function; _drawLinesWebGL: Function; _drawCurves: Function; _draw: Function; clear(): void; transformByMatrix(value: Matrix): void; _transformByMatrix: Function; setTransform(a: number, b: number, c: number, d: number, tx: number, ty: number): void; _setTransform: Function; setTransformByMatrix(value: Matrix): void; _setTransformByMatrix: Function; save(): void; _save: Function; restore(): void; _restore: Function; translate(x: number, y: number): void; _translate: Function; transform(a: number, b: number, c: number, d: number, tx: number, ty: number): void; _transform: Function; rotate(angle: number): void; _rotate: Function; scale(scaleX: number, scaleY: number): void; _scale: Function; alpha(value: number): void; _alpha: Function; setAlpha(value: number): void; _setAlpha: Function; fillWords(words: Array, x: number, y: number, font: string, color: string, underLine?: number): void; fillBorderWords(words: Array, x: number, y: number, font: string, fillColor: string, borderColor: string, lineWidth: number): void; fillText(text: string, x: number, y: number, font: string, color: string, textAlign: string): void; _fillText: Function; strokeText(text: string, x: number, y: number, font: string, color: string, lineWidth: number, textAlign: string): void; _strokeText: Function; _fillBorderText: Function; blendMode(type: string): void; _blendMode: Function; flush(): void; addRenderObject(o: any): void; beginClip(x: number, y: number, w: number, h: number): void; _beginClip: Function; endClip(): void; _setIBVB: Function; fillTrangles(x: number, y: number, args: Array): void; _fillTrangles: Function; _drawPath: Function; drawPoly: Function; _drawPoly: Function; _drawSkin: Function; _drawParticle: Function; _setFilters: Function; } } declare module laya.renders { import Sprite = laya.display.Sprite; /** * @private * 精灵渲染器 */ class RenderSprite { static IMAGE: number; static ALPHA: number; static TRANSFORM: number; static BLEND: number; static CANVAS: number; static FILTERS: number; static MASK: number; static CLIP: number; static STYLE: number; static GRAPHICS: number; static CUSTOM: number; static CHILDS: number; static INIT: number; static renders: Array; protected static NORENDER: RenderSprite; _next: RenderSprite; _fun: Function; static __init__(): void; constructor(type: number, next: RenderSprite); protected onCreate(type: number): void; _style(sprite: Sprite, context: RenderContext, x: number, y: number): void; _no(sprite: Sprite, context: RenderContext, x: number, y: number): void; _custom(sprite: Sprite, context: RenderContext, x: number, y: number): void; _clip(sprite: Sprite, context: RenderContext, x: number, y: number): void; _blend(sprite: Sprite, context: RenderContext, x: number, y: number): void; _mask(sprite: Sprite, context: RenderContext, x: number, y: number): void; _graphics(sprite: Sprite, context: RenderContext, x: number, y: number): void; _image(sprite: Sprite, context: RenderContext, x: number, y: number): void; _image2(sprite: Sprite, context: RenderContext, x: number, y: number): void; _alpha(sprite: Sprite, context: RenderContext, x: number, y: number): void; _transform(sprite: Sprite, context: RenderContext, x: number, y: number): void; _canvas(sprite: Sprite, context: RenderContext, x: number, y: number): void; } } declare module laya.resource { /** * @private * Bitmap 是图片资源类。 */ class Bitmap extends Resource { protected _source: any; protected _w: number; protected _h: number; /*** * 宽度。 */ readonly width: number; /*** * 高度。 */ readonly height: number; /*** * HTML Image 或 HTML Canvas 或 WebGL Texture 。 */ readonly source: any; /** * 创建一个 Bitmap 实例。 */ constructor(); } } declare module laya.resource { import Matrix = laya.maths.Matrix; import Point = laya.maths.Point; /** * @private * Context扩展类 */ class Context { _canvas: HTMLCanvas; _repaint: boolean; static __init__(to?: any): void; setIsMainContext(): void; font: string; textBaseline: string; fillStyle: any; translate(x: number, y: number): void; scale(scaleX: number, scaleY: number): void; drawImage(...args: any[]): void; getImageData(...args: any[]): any; measureText(text: string): any; setTransform(...args: any[]): void; beginPath(): void; strokeStyle: any; globalCompositeOperation: string; rect(x: number, y: number, width: number, height: number): void; stroke(): void; transform(a: number, b: number, c: number, d: number, tx: number, ty: number): void; save(): void; restore(): void; clip(): void; arcTo(x1: number, y1: number, x2: number, y2: number, r: number): void; quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; lineJoin: string; lineCap: string; miterLimit: string; globalAlpha: number; clearRect(x: number, y: number, width: number, height: number): void; drawTextures(tex: Texture, pos: Array, tx: number, ty: number): void; drawCanvas(canvas: HTMLCanvas, x: number, y: number, width: number, height: number): void; fillRect(x: number, y: number, width: number, height: number, style: any): void; fillText(text: any, x: number, y: number, font: string, color: string, textAlign: string): void; fillBorderText(text: any, x: number, y: number, font: string, fillColor: string, borderColor: string, lineWidth: number, textAlign: string): void; strokeText(text: any, x: number, y: number, font: string, color: string, lineWidth: number, textAlign: string): void; transformByMatrix(value: Matrix): void; setTransformByMatrix(value: Matrix): void; clipRect(x: number, y: number, width: number, height: number): void; drawTexture(tex: Texture, x: number, y: number, width: number, height: number, tx: number, ty: number): void; drawTextureWithTransform(tex: Texture, x: number, y: number, width: number, height: number, m: Matrix, tx: number, ty: number, alpha: number): void; drawTexture2(x: number, y: number, pivotX: number, pivotY: number, m: Matrix, alpha: number, blendMode: string, args2: Array): void; fillTexture(texture: Texture, x: number, y: number, width: number, height: number, type: string, offset: Point, other: any): void; drawTriangle(texture: Texture, vertices: Float32Array, uvs: Float32Array, index0: number, index1: number, index2: number, matrix: Matrix, canvasPadding: boolean): void; flush(): number; fillWords(words: Array, x: number, y: number, font: string, color: string, underLine: number): void; fillBorderWords(words: Array, x: number, y: number, font: string, color: string, borderColor: string, lineWidth: number): void; destroy(): void; clear(): void; drawCurves(x: number, y: number, args: Array): void; } } declare module laya.resource { /** * @private * FileBitmap 是图片文件资源类。 */ class FileBitmap extends Bitmap { protected _src: string; /** * 文件路径全名。 */ src: string; protected _onload: Function; protected _onerror: Function; /** * 载入完成处理函数。 */ onload: Function; /** * 错误处理函数。 */ onerror: Function; } } declare module laya.resource { /** * HTMLCanvas 是 Html Canvas 的代理类,封装了 Canvas 的属性和方法。。请不要直接使用 new HTMLCanvas! */ class HTMLCanvas extends Bitmap { /** * 根据指定的类型,创建一个 HTMLCanvas 实例。 * @param type 类型。2D、3D。 */ static create: Function; /** 2D 模式。*/ static TYPE2D: string; /** 3D 模式。*/ static TYPE3D: string; /** 自动模式。*/ static TYPEAUTO: string; static _createContext: Function; /** * 根据指定的类型,创建一个 HTMLCanvas 实例。请不要直接使用 new HTMLCanvas! * @param type 类型。2D、3D。 */ constructor(type: string, canvas?: any); /** * 清空画布内容。 */ clear(): void; /** * 销毁。 */ destroy(): void; /** * 释放。 */ release(): void; /** * Canvas 渲染上下文。 */ readonly context: Context; /** * @private * 设置 Canvas 渲染上下文。 * @param context Canvas 渲染上下文。 */ _setContext(context: Context): void; /** * 获取 Canvas 渲染上下文。 * @param contextID 上下文ID. * @param other * @return Canvas 渲染上下文 Context 对象。 */ getContext: Function; /** * 获取内存大小。 * @return 内存大小。 */ getMemSize(): number; return: any; asBitmap: boolean; /** * 设置宽高。 * @param w 宽度。 * @param h 高度。 */ size(w: number, h: number): void; getCanvas(): any; toBase64(type: string, encoderOptions: number, callBack: Function): void; } } declare module laya.resource { /** * @private *

    HTMLImage 用于创建 HTML Image 元素。

    *

    请使用 HTMLImage.create()获取新实例,不要直接使用 new HTMLImage

    */ class HTMLImage extends FileBitmap { /** *

    创建一个 HTMLImage 实例。

    *

    请使用 HTMLImage.create()创建实例,不要直接使用 new HTMLImage

    */ static create: Function; protected _recreateLock: boolean; protected _needReleaseAgain: boolean; /** * @inheritDoc */ onload: Function; /** * @inheritDoc */ onerror: Function; /** *

    创建一个 HTMLImage 实例。

    *

    请使用 HTMLImage.create()创建实例,不要直接使用 new HTMLImage

    */ constructor(src: string, def?: any); protected _init_(src: string, def: any): void; enableMerageInAtlas: boolean; protected recreateResource(): void; protected disposeResource(): void; protected onresize(): void; } } declare module laya.resource { /** * @private */ class HTMLSubImage extends Bitmap { static create: Function; constructor(canvas: any, offsetX: number, offsetY: number, width: number, height: number, atlasImage: any, src: string, allowMerageInAtlas: boolean); } } declare module laya.resource { /** * @private * ICreateResource 对象创建接口。 */ interface ICreateResource { _getGroup(): string; _setGroup(value: string): void; _setUrl(url: string): void; onAsynLoaded(url: string, data: any, params: Array): void; } } declare module laya.resource { /** * @private * IDestroy 是对象销毁的接口。 */ interface IDestroy { _destroy(): void; } } declare module laya.resource { /** * @private * IDispose 是资源销毁的接口。 */ interface IDispose { dispose(): void; } } declare module laya.resource { import EventDispatcher = laya.events.EventDispatcher; /** * @private * Resource 资源存取类。 */ class Resource extends EventDispatcher implements ICreateResource, IDispose { /** * 通过资源ID返回已载入资源。 * @param id 资源ID * @return 资源 Resource 对象。 */ static getResourceByID(id: number): Resource; /** * 通过url返回已载入资源。 * @param url 资源URL * @param index 索引 * @return 资源 Resource 对象。 */ static getResourceByURL(url: string, index?: number): Resource; /** * 通过url返回已载入资源。 * @param url 资源URL * @return 资源 Resource 对象。 * @param index 索引 */ static getResourceCountByURL(url: string): number; /** * 销毁当前没有被使用的资源,该函数会忽略lock=true的资源。 * @param group 指定分组。 */ static destroyUnusedResources(group?: string): void; protected _url: string; _resourceManager: ResourceManager; _lastUseFrameCount: number; /**是否加锁,如果true为不能使用自动释放机制。*/ lock: boolean; /**名称。 */ name: string; /** * @private */ _loaded: boolean; /** * 获取唯一标识ID,通常用于识别。 */ readonly id: number; /** * 资源管理员。 */ readonly resourceManager: ResourceManager; /** * 占用内存尺寸。 */ /** * @private */ memorySize: number; /** * 是否已释放。 */ readonly released: boolean; /** * 是否已处理。 */ readonly destroyed: boolean; /** * 获取是否已加载完成。 */ readonly loaded: boolean; /** * 获取资源的URL地址。 * @return URL地址。 */ readonly url: string; /** * 获取资源组名。 */ /** * 设置资源组名。 */ group: string; /** * 获取资源的引用计数。 */ readonly referenceCount: number; /** * 创建一个 Resource 实例。 */ constructor(); /** * @private */ _setUrl(url: string): void; /** * @private */ _getGroup(): string; /** * @private */ _setGroup(value: string): void; /** * @private */ _addReference(): void; /** * @private */ _removeReference(): void; /** * @private */ _clearReference(): void; /** * @private */ _endLoaded(): void; protected recreateResource(): void; protected disposeResource(): void; /** * 激活资源,使用资源前应先调用此函数激活。 * @param force 是否强制创建。 */ activeResource(force?: boolean): void; /** * 释放资源。 * @param force 是否强制释放。 * @return 是否成功释放。 */ releaseResource(force?: boolean): boolean; /** *@private */ onAsynLoaded(url: string, data: any, params: Array): void; /** *

    彻底处理资源,处理后不能恢复。

    *

    注意:会强制解锁清理。

    */ destroy(): void; protected completeCreate(): void; /** * @private */ dispose(): void; } } declare module laya.resource { /** * @private * ResourceManager 是资源管理类。它用于资源的载入、获取、销毁。 */ class ResourceManager implements IDispose { /** 当前资源管理器。*/ static currentResourceManager: ResourceManager; /** * 系统资源管理器。 */ static readonly systemResourceManager: ResourceManager; /** * @private * 资源管理类初始化。 */ static __init__(): void; /** * 获取指定索引的资源管理器。 * @param index 索引。 * @return 资源管理器。 */ static getLoadedResourceManagerByIndex(index: number): ResourceManager; /** * 获取资源管理器总个数。 * @return 资源管理器总个数。 */ static getLoadedResourceManagersCount(): number; /** * 重新强制创建资源管理员以及所拥有资源(显卡丢失时处理)。 */ static recreateContentManagers(force?: boolean): void; /**释放资源管理员所拥有资源(显卡丢失时处理)。*/ static releaseContentManagers(force?: boolean): void; /** 是否启用自动释放机制。*/ autoRelease: boolean; /**自动释放机制的内存触发上限,以字节为单位。*/ autoReleaseMaxSize: number; /** * 唯一标识 ID 。 */ readonly id: number; /** * 名字。 */ name: string; /** * 此管理器所管理资源的累计内存,以字节为单位。 */ readonly memorySize: number; /** * 创建一个 ResourceManager 实例。 */ constructor(name?: string); /** * 获取指定索引的资源 Resource 对象。 * @param 索引。 * @return 资源 Resource 对象。 */ getResourceByIndex(index: number): Resource; /** * 获取此管理器所管理的资源个数。 * @return 资源个数。 */ getResourcesLength(): number; /** * 添加指定资源。 * @param resource 需要添加的资源 Resource 对象。 * @return 是否添加成功。 */ addResource(resource: Resource): boolean; /** * 移除指定资源。 * @param resource 需要移除的资源 Resource 对象 * @return 是否移除成功。 */ removeResource(resource: Resource): boolean; /** * 卸载此资源管理器载入的资源。 */ unload(): void; /** 释放资源。*/ dispose(): void; /** * 增加内存。 * @param add 需要增加的内存大小。 */ addSize(add: number): void; } } declare module laya.resource { import EventDispatcher = laya.events.EventDispatcher; /** * Texture 是一个纹理处理类。 */ class Texture extends EventDispatcher { /**默认 UV 信息。*/ static DEF_UV: Array; static INV_UV: Array; /** 图片或者canvas 。*/ bitmap: any; /** UV信息。*/ uv: Array; /**沿 X 轴偏移量。*/ offsetX: number; /**沿 Y 轴偏移量。*/ offsetY: number; /**原始宽度(包括被裁剪的透明区域)。*/ sourceWidth: number; /**原始高度(包括被裁剪的透明区域)。*/ sourceHeight: number; _loaded: boolean; protected _w: number; protected _h: number; $_GID: number; /**图片地址*/ url: string; _uvID: number; _atlasID: number; scaleRate: number; /** * 创建一个 Texture 实例。 * @param bitmap 位图资源。 * @param uv UV 数据信息。 */ constructor(bitmap?: Bitmap, uv?: Array); /** * @private */ _setUrl(url: string): void; /** * 设置此对象的位图资源、UV数据信息。 * @param bitmap 位图资源 * @param uv UV数据信息 */ setTo(bitmap?: Bitmap, uv?: Array): void; /** * 平移 UV。 * @param offsetX 沿 X 轴偏移量。 * @param offsetY 沿 Y 轴偏移量。 * @param uv 需要平移操作的的 UV。 * @return 平移后的UV。 */ static moveUV(offsetX: number, offsetY: number, uv: Array): Array; /** * 根据指定资源和坐标、宽高、偏移量等创建 Texture 对象。 * @param source 绘图资源 img 或者 Texture 对象。 * @param x 起始绝对坐标 x 。 * @param y 起始绝对坐标 y 。 * @param width 宽绝对值。 * @param height 高绝对值。 * @param offsetX X 轴偏移量(可选)。 * @param offsetY Y 轴偏移量(可选)。 * @param sourceWidth 原始宽度,包括被裁剪的透明区域(可选)。 * @param sourceHeight 原始高度,包括被裁剪的透明区域(可选)。 * @return Texture 对象。 */ static create(source: any, x: number, y: number, width: number, height: number, offsetX?: number, offsetY?: number, sourceWidth?: number, sourceHeight?: number): Texture; /** * 截取Texture的一部分区域,生成新的Texture,如果两个区域没有相交,则返回null。 * @param texture 目标Texture。 * @param x 相对于目标Texture的x位置。 * @param y 相对于目标Texture的y位置。 * @param width 截取的宽度。 * @param height 截取的高度。 * @return 返回一个新的Texture。 */ static createFromTexture(texture: Texture, x: number, y: number, width: number, height: number): Texture; /** * 表示是否加载成功,只能表示初次载入成功(通常包含下载和载入),并不能完全表示资源是否可立即使用(资源管理机制释放影响等)。 */ readonly loaded: boolean; /** * 表示资源是否已释放。 */ readonly released: boolean; active(): void; /** 激活并获取资源。*/ readonly source: any; /** * 销毁纹理(分直接销毁,跟计数销毁两种)。 * @param forceDispose (default = false)true为强制销毁主纹理,false是通过计数销毁纹理。 */ destroy(forceDispose?: boolean): void; /** 实际宽度。*/ width: number; /** 实际高度。*/ height: number; /** * 获取当前纹理是否启用了线性采样。 */ /** * 设置线性采样的状态(目前只能第一次绘制前设置false生效,来关闭线性采样)。 */ isLinearSampling: boolean; /** * 获取当前纹理是否启用了纹理平铺 */ /** * 通过外部设置是否启用纹理平铺(后面要改成在着色器里计算) */ repeat: boolean; /** * 加载指定地址的图片。 * @param url 图片地址。 */ load(url: string): void; addTextureToAtlas(e?: any): void; /** * 获取Texture上的某个区域的像素点 * @param x * @param y * @param width * @param height * @return 返回像素点集合 */ getPixels(x: number, y: number, width: number, height: number): Array; onAsynLoaded(url: string, bitmap: Bitmap): void; } } declare module laya.runtime { import Graphics = laya.display.Graphics; import Context = laya.resource.Context; /** * @private */ interface IConchNode { /**@private */ setRootNode(): void; /**@private */ addChildAt(c: IConchNode, i: number): void; /**@private */ removeChild(c: IConchNode): void; /**@private */ size(w: number, h: number): void; /**@private */ pos(x: number, y: number): void; /**@private */ pivot(x: number, y: number): void; /**@private */ scale(x: number, y: number): void; /**@private */ skew(x: number, y: number): void; /**@private */ rotate(r: number): void; /**@private */ bgColor(bg: string): void; /**@private */ font(str: string): void; /**@private */ text(d: any): void; /**@private */ transform(a: number, b: number, c: number, d: number, tx: number, ty: number): void; /**@private */ alpha(a: number): void; /**@private */ setFilterMatrix(mat: Float32Array, alpha: Float32Array): void; /**@private */ visible(b: boolean): void; /**@private */ blendMode(v: string): void; /**@private */ scrollRect(x: number, y: number, w: number, h: number): void; /**@private */ mask(node: IConchNode): void; /**@private */ graphics(g: Graphics): void; /**@private */ custom(context: Context): void; /**@private */ removeType(type: number): void; /**@private */ cacheAs(type: number): void; /**@private */ border(color: string): void; /**@private */ optimizeScrollRect(b: boolean): void; /**@private */ blurFilter(strength: number): void; /**@private */ glowFilter(color: string, blur: number, offX: number, offY: number): void; /**@private */ repaint(): void; /**@private */ setZOrder(z: number): void; /**@private */ updateZOrder(): void; } } declare module laya.runtime { /** * @private * @author hugao */ interface IConchRenderObject { drawSubmesh(submesh: any, drawType: number, renderMode: number, offset: number, count: number): void; matrix(matrix: Float32Array): void; boundingBox(min: Float32Array, max: Float32Array): void; } } declare module laya.runtime { /** * @private * @author hugao */ interface ICPlatformClass { /** * 创建平台类 * @param clsName 类全名 * @return 创建的类 */ createClass(clsName: string): IPlatformClass; } } declare module laya.runtime { /** * @private */ interface IMarket { /** * 登录 * @param jsonParm * @param callback */ login(jsonParm: string, callback: Function): void; /** * 登出 * @param jsonParm * @param callback */ logout(jsonParm: string, callback: Function): void; /** * 授权 * @param jsonParm * @param callback */ authorize(jsonParm: string, callback: Function): void; /** * 进入论坛 * @param jsonParm * @param callback */ enterBBS(jsonParm: string, callback: Function): void; /** * 刷新票据 * @param jsonParm * @param callback */ refreshToken(jsonParm: string, callback: Function): void; /** * 支付 * @param jsonParm * @param callback */ recharge(jsonParm: string, callback: Function): void; /** * 分享 * @param jsonParm * @param callback */ enterShareAndFeed(jsonParm: string, callback: Function): void; /** * 邀请 * @param jsonParm * @param callback */ enterInvite(jsonParm: string, callback: Function): void; /** * 获取游戏好友 * @param jsonParm * @param callback */ getGameFriends(jsonParm: string, callback: Function): void; /** * 发送到桌面 * @param jsonParm * @param callback */ sendToDesktop(jsonParm: string, callback: Function): void; /** * 发送自定义消息 * @param jsonParm * @param callback */ sendMessageToPlatform(jsonParm: string, callback: Function): void; /** * 获取用户信息 * @param jsonParm * @param callback */ getUserInfo(jsonParm: string, callback: Function): void; /** * 返回Market名称 */ getMarketName(): string; /** * 返回支付类型 自定义 */ getPayType(): number; /** * 返回登录类型 自定义 */ getLoginType(): number; /** * */ getChargeType(): number; } } declare module laya.runtime { /** * @private * @author hugao */ interface IPlatform { /** * 调用方法 * @param methodName 方法名 * @param ...args 参数 * @return 返回值 目前只用android能直接返回 */ call(methodName: string, ...args: any[]): any; /** * 调用方法通过回调接收返回值 * @param callback 回调方法 参数为返回值 * @param methodName 方法名 * @param ...args 参数 */ callWithBack(callback: Function, methodName: string, ...args: any[]): void; } } declare module laya.runtime { /** * @private * @author hugao */ interface IPlatformClass extends IPlatform { /** * 创建对象 * @param ...args 构造函数的参数 * @return 创建出来的对象 */ newObject(...args: any[]): IPlatform; } } declare module laya.system { /** * @private */ class System { /** * 替换指定名称的定义。用来动态更改类的定义。 * @param name 属性名。 * @param classObj 属性值。 */ static changeDefinition(name: string, classObj: any): void; /** * @private * 初始化。 */ static __init__(): void; } } declare module laya.ui { /** * 异步Dialog的生命周期:show或者popup > onCreate(如果没有创建过) > onOpen > onClose > onDestroy(如果销毁) * onCreate在页面未创建时执行一次,再次打开页面不会再执行,适合写一些只执行一次的逻辑,比如资源加载,节点事件监听 * onOpen在页面每次打开都会执行,适合做一些每次都需要处理的事情,比如消息请求,根据数据初始化页面 * onClose在每次关闭的时候调用,适合关闭时停止动画,网络消息监听等逻辑 * onDestroy在页面被销毁的时候调用,适合置空引用对象 */ class AsynDialog extends Dialog { protected _uiView: any; /**打开时是否关闭其他页面*/ isCloseOther: boolean; protected createView(uiView: any): void; protected _open(modal: boolean, closeOther: boolean, showEffect: boolean): void; /** * 在页面未创建时执行一次,再次打开页面不会再执行,适合写一些只执行一次的逻辑,比如资源加载,节点事件监听 */ onCreated(): void; /**根据节点数据创建UI*/ createUI(): void; /** * 在页面每次打开都会执行,适合做一些每次都需要处理的事情,比如消息请求,根据数据初始化页面 */ onOpen(): void; close(type?: string, showEffect?: boolean): void; /** * 在每次关闭的时候调用,适合关闭时停止动画,网络消息监听等逻辑 */ onClose(): void; destroy(destroyChild?: boolean): void; /** * 在页面被销毁的时候调用,适合置空引用对象 */ onDestroy(): void; } } declare module laya.ui { import Graphics = laya.display.Graphics; import Texture = laya.resource.Texture; /** * AutoBitmap 类是用于表示位图图像或绘制图形的显示对象。 *

    封装了位置,宽高及九宫格的处理,供UI组件使用。

    */ class AutoBitmap extends Graphics { autoCacheCmd: boolean; protected _isChanged: boolean; _offset: Array; /**@inheritDoc */ destroy(): void; /** * 当前实例的有效缩放网格数据。 *

    如果设置为null,则在应用任何缩放转换时,将正常缩放整个显示对象。

    *

    数据格式:[上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)]。 *

    • 例如:[4,4,4,4,1]

    *

    sizeGrid 的值如下所示: *

      *
    1. 上边距
    2. *
    3. 右边距
    4. *
    5. 下边距
    6. *
    7. 左边距
    8. *
    9. 是否重复填充(值为0:不重复填充,1:重复填充)
    10. *

    *

    当定义 sizeGrid 属性时,该显示对象被分割到以 sizeGrid 数据中的"上边距,右边距,下边距,左边距" 组成的矩形为基础的具有九个区域的网格中,该矩形定义网格的中心区域。网格的其它八个区域如下所示: *

      *
    • 矩形上方的区域
    • *
    • 矩形外的右上角
    • *
    • 矩形左侧的区域
    • *
    • 矩形右侧的区域
    • *
    • 矩形外的左下角
    • *
    • 矩形下方的区域
    • *
    • 矩形外的右下角
    • *
    • 矩形外的左上角
    • *
    * 同时也支持3宫格,比如0,4,0,4,1为水平3宫格,4,0,4,0,1为垂直3宫格,3宫格性能比9宫格高。 *

    */ sizeGrid: Array; /** * 表示显示对象的宽度,以像素为单位。 */ width: number; /** * 表示显示对象的高度,以像素为单位。 */ height: number; /** * 对象的纹理资源。 * @see laya.resource.Texture */ source: Texture; protected _setChanged(): void; protected changeSource(): void; clear(recoverCmds?: boolean): void; } } declare module laya.ui { /** * Box 类是一个控件容器类。 */ class Box extends Component implements IBox { /**@inheritDoc */ dataSource: any; } } declare module laya.ui { import Text = laya.display.Text; import Event = laya.events.Event; import AutoBitmap = laya.ui.AutoBitmap; import Handler = laya.utils.Handler; /** * Button 组件用来表示常用的多态按钮。 Button 组件可显示文本标签、图标或同时显示两者。 * *

    可以是单态,两态和三态,默认三态(up,over,down)。

    * * @example 以下示例代码,创建了一个 Button 实例。 * package * { * import laya.ui.Button; * import laya.utils.Handler; * public class Button_Example * { * public function Button_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/button.png", Handler.create(this,onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * trace("资源加载完成!"); * var button:Button = new Button("resource/ui/button.png","label");//创建一个 Button 类的实例对象 button ,并传入它的皮肤。 * button.x = 100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 * button.y = 100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 * button.clickHandler = new Handler(this, onClickButton,[button]);//设置 button 的点击事件处理器。 * Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 * } * private function onClickButton(button:Button):void * { * trace("按钮button被点击了!"); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/button.png",laya.utils.Handler.create(this,loadComplete));//加载资源 * function loadComplete() * { * console.log("资源加载完成!"); * var button = new laya.ui.Button("resource/ui/button.png","label");//创建一个 Button 类的实例对象 button ,传入它的皮肤skin和标签label。 * button.x =100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 * button.y =100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 * button.clickHandler = laya.utils.Handler.create(this,onClickButton,[button],false);//设置 button 的点击事件处理函数。 * Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 * } * function onClickButton(button) * { * console.log("按钮被点击了。",button); * } * @example * import Button=laya.ui.Button; * import Handler=laya.utils.Handler; * class Button_Example{ * constructor() * { * Laya.init(640, 800); * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/button.png", laya.utils.Handler.create(this,this.onLoadComplete));//加载资源。 * } * private onLoadComplete() * { * var button:Button = new Button("resource/ui/button.png","label");//创建一个 Button 类的实例对象 button ,并传入它的皮肤。 * button.x = 100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 * button.y = 100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 * button.clickHandler = new Handler(this, this.onClickButton,[button]);//设置 button 的点击事件处理器。 * Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 * } * private onClickButton(button:Button):void * { * console.log("按钮button被点击了!") * } * } */ class Button extends Component implements ISelect { protected static stateMap: any; /** * 指定按钮按下时是否是切换按钮的显示状态。 * * @example 以下示例代码,创建了一个 Button 实例,并设置为切换按钮。 * @example * package * { * import laya.ui.Button; * import laya.utils.Handler; * public class Button_toggle * { * public function Button_toggle() * { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/button.png", Handler.create(this,onLoadComplete)); * } * private function onLoadComplete():void * { * trace("资源加载完成!"); * var button:Button = new Button("resource/ui/button.png","label");//创建一个 Button 实例对象 button ,传入它的皮肤skin和标签label。 * button.x = 100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 * button.y = 100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 * button.toggle = true;//设置 button 对象为切换按钮。 * button.clickHandler = new Handler(this, onClickButton,[button]);//设置 button 的点击事件处理器。 * Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 * } * private function onClickButton(button:Button):void * { * trace("button.selected = "+ button.selected); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/button.png",laya.utils.Handler.create(this,loadComplete));//加载资源 * function loadComplete() * { * console.log("资源加载完成!"); * var button = new laya.ui.Button("resource/ui/button.png","label");//创建一个 Button 类的实例对象 button ,传入它的皮肤skin和标签label。 * button.x =100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 * button.y =100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 * button.toggle = true;//设置 button 对象为切换按钮。 * button.clickHandler = laya.utils.Handler.create(this,onClickButton,[button],false);//设置 button 的点击事件处理器。 * Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 * } * function onClickButton(button) * { * console.log("button.selected = ",button.selected); * } * @example * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("button.png", null,null, null, null, null);//加载资源 * function loadComplete() { * console.log("资源加载完成!"); * var button:laya.ui.Button = new laya.ui.Button("button.png", "label");//创建一个 Button 类的实例对象 button ,传入它的皮肤skin和标签label。 * button.x = 100;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 * button.y = 100;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 * button.toggle = true;//设置 button 对象为切换按钮。 * button.clickHandler = laya.utils.Handler.create(this, onClickButton, [button], false);//设置 button 的点击事件处理器。 * Laya.stage.addChild(button);//将此 button 对象添加到显示列表。 * } * function onClickButton(button) { * console.log("button.selected = ", button.selected); * } */ toggle: boolean; protected _bitmap: AutoBitmap; protected _text: Text; protected _labelColors: Array; protected _strokeColors: Array; protected _state: number; protected _selected: boolean; protected _skin: string; protected _autoSize: boolean; protected _stateNum: number; protected _sources: Array; protected _clickHandler: Handler; protected _stateChanged: boolean; /** * 创建一个新的 Button 类实例。 * @param skin 皮肤资源地址。 * @param label 按钮的文本内容。 */ constructor(skin?: string, label?: string); /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected createChildren(): void; protected createText(): void; protected initialize(): void; protected onMouse(e: Event): void; /** *

    对象的皮肤资源地址。

    * 支持单态,两态和三态,用 stateNum 属性设置 *

    对象的皮肤地址,以字符串表示。

    * @see #stateNum */ skin: string; /** *

    指定对象的状态值,以数字表示。

    *

    默认值为3。此值决定皮肤资源图片的切割方式。

    *

    取值: *

  • 1:单态。图片不做切割,按钮的皮肤状态只有一种。
  • *
  • 2:两态。图片将以竖直方向被等比切割为2部分,从上向下,依次为 * 弹起状态皮肤、 * 按下和经过及选中状态皮肤。
  • *
  • 3:三态。图片将以竖直方向被等比切割为3部分,从上向下,依次为 * 弹起状态皮肤、 * 经过状态皮肤、 * 按下和选中状态皮肤
  • *

    */ stateNum: number; protected changeClips(): void; protected readonly measureWidth: number; protected readonly measureHeight: number; /** * 按钮的文本内容。 */ label: string; /** * 表示按钮的选中状态。 *

    如果值为true,表示该对象处于选中状态。否则该对象处于未选中状态。

    */ selected: boolean; protected state: number; protected changeState(): void; /** * 表示按钮各个状态下的文本颜色。 *

    格式: "upColor,overColor,downColor,disableColor"。

    */ labelColors: string; /** * 表示按钮各个状态下的描边颜色。 *

    格式: "upColor,overColor,downColor,disableColor"。

    */ strokeColors: string; /** * 表示按钮文本标签的边距。 *

    格式:"上边距,右边距,下边距,左边距"。

    */ labelPadding: string; /** * 表示按钮文本标签的字体大小。 * @see laya.display.Text.fontSize() */ labelSize: number; /** *

    描边宽度(以像素为单位)。

    * 默认值0,表示不描边。 * @see laya.display.Text.stroke() */ labelStroke: number; /** *

    描边颜色,以字符串表示。

    * 默认值为 "#000000"(黑色); * @see laya.display.Text.strokeColor() */ labelStrokeColor: string; /** * 表示按钮文本标签是否为粗体字。 * @see laya.display.Text.bold() */ labelBold: boolean; /** * 表示按钮文本标签的字体名称,以字符串形式表示。 * @see laya.display.Text.font() */ labelFont: string; /**标签对齐模式,默认为居中对齐。*/ labelAlign: string; /** * 对象的点击事件处理器函数(无默认参数)。 */ clickHandler: Handler; /** * 按钮文本标签 Text 控件。 */ readonly text: Text; /** *

    当前实例的位图 AutoImage 实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    * @see laya.ui.AutoBitmap.sizeGrid */ sizeGrid: string; /**@inheritDoc */ width: number; /**@inheritDoc */ height: number; /**@inheritDoc */ dataSource: any; /**图标x,y偏移,格式:100,100*/ iconOffset: string; protected _setStateChanged(): void; } } declare module laya.ui { import Button = laya.ui.Button; /** * CheckBox 组件显示一个小方框,该方框内可以有选中标记。 * CheckBox 组件还可以显示可选的文本标签,默认该标签位于 CheckBox 右侧。 *

    CheckBox 使用 dataSource赋值时的的默认属性是:selected

    * * @example 以下示例代码,创建了一个 CheckBox 实例。 * package * { * import laya.ui.CheckBox; * import laya.utils.Handler; * public class CheckBox_Example * { * public function CheckBox_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/check.png", Handler.create(this,onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * trace("资源加载完成!"); * var checkBox:CheckBox = new CheckBox("resource/ui/check.png", "这个是一个CheckBox组件。");//创建一个 CheckBox 类的实例对象 checkBox ,传入它的皮肤skin和标签label。 * checkBox.x = 100;//设置 checkBox 对象的属性 x 的值,用于控制 checkBox 对象的显示位置。 * checkBox.y = 100;//设置 checkBox 对象的属性 y 的值,用于控制 checkBox 对象的显示位置。 * checkBox.clickHandler = new Handler(this, onClick, [checkBox]);//设置 checkBox 的点击事件处理器。 * Laya.stage.addChild(checkBox);//将此 checkBox 对象添加到显示列表。 * } * private function onClick(checkBox:CheckBox):void * { * trace("输出选中状态: checkBox.selected = " + checkBox.selected); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * Laya.loader.load("resource/ui/check.png",laya.utils.Handler.create(this,loadComplete));//加载资源 * function loadComplete() * { * console.log("资源加载完成!"); * var checkBox:laya.ui.CheckBox= new laya.ui.CheckBox("resource/ui/check.png", "这个是一个CheckBox组件。");//创建一个 CheckBox 类的类的实例对象 checkBox ,传入它的皮肤skin和标签label。 * checkBox.x =100;//设置 checkBox 对象的属性 x 的值,用于控制 checkBox 对象的显示位置。 * checkBox.y =100;//设置 checkBox 对象的属性 y 的值,用于控制 checkBox 对象的显示位置。 * checkBox.clickHandler = new laya.utils.Handler(this,this.onClick,[checkBox],false);//设置 checkBox 的点击事件处理器。 * Laya.stage.addChild(checkBox);//将此 checkBox 对象添加到显示列表。 * } * function onClick(checkBox) * { * console.log("checkBox.selected = ",checkBox.selected); * } * @example * import CheckBox= laya.ui.CheckBox; * import Handler=laya.utils.Handler; * class CheckBox_Example{ * constructor() * { * Laya.init(640, 800); * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/check.png", Handler.create(this,this.onLoadComplete));//加载资源。 * } * private onLoadComplete() * { * var checkBox:CheckBox = new CheckBox("resource/ui/check.png", "这个是一个CheckBox组件。");//创建一个 CheckBox 类的实例对象 checkBox ,传入它的皮肤skin和标签label。 * checkBox.x = 100;//设置 checkBox 对象的属性 x 的值,用于控制 checkBox 对象的显示位置。 * checkBox.y = 100;//设置 checkBox 对象的属性 y 的值,用于控制 checkBox 对象的显示位置。 * checkBox.clickHandler = new Handler(this, this.onClick,[checkBox]);//设置 checkBox 的点击事件处理器。 * Laya.stage.addChild(checkBox);//将此 checkBox 对象添加到显示列表。 * } * private onClick(checkBox:CheckBox):void * { * console.log("输出选中状态: checkBox.selected = " + checkBox.selected); * } * } */ class CheckBox extends Button { /** * 创建一个新的 CheckBox 组件实例。 * @param skin 皮肤资源地址。 * @param label 文本标签的内容。 */ constructor(skin?: string, label?: string); protected preinitialize(): void; protected initialize(): void; /**@inheritDoc */ dataSource: any; } } declare module laya.ui { import Event = laya.events.Event; import Texture = laya.resource.Texture; import Handler = laya.utils.Handler; /** *

    Clip 类是位图切片动画。

    *

    Clip 可将一张图片,按横向分割数量 clipX 、竖向分割数量 clipY , * 或横向分割每个切片的宽度 clipWidth 、竖向分割每个切片的高度 clipHeight , * 从左向右,从上到下,分割组合为一个切片动画。

    * Image和Clip组件是唯一支持异步加载的两个组件,比如clip.skin = "abc/xxx.png",其他UI组件均不支持异步加载。 * * @example 以下示例代码,创建了一个 Clip 实例。 * package * { * import laya.ui.Clip; * public class Clip_Example * { * private var clip:Clip; * public function Clip_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * onInit(); * } * private function onInit():void * { * clip = new Clip("resource/ui/clip_num.png", 10, 1);//创建一个 Clip 类的实例对象 clip ,传入它的皮肤skin和横向分割数量、竖向分割数量。 * clip.autoPlay = true;//设置 clip 动画自动播放。 * clip.interval = 100;//设置 clip 动画的播放时间间隔。 * clip.x = 100;//设置 clip 对象的属性 x 的值,用于控制 clip 对象的显示位置。 * clip.y = 100;//设置 clip 对象的属性 y 的值,用于控制 clip 对象的显示位置。 * clip.on(Event.CLICK, this, onClick);//给 clip 添加点击事件函数侦听。 * Laya.stage.addChild(clip);//将此 clip 对象添加到显示列表。 * } * private function onClick():void * { * trace("clip 的点击事件侦听处理函数。clip.total="+ clip.total); * if (clip.isPlaying == true) * { * clip.stop();//停止动画。 * }else { * clip.play();//播放动画。 * } * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * var clip; * Laya.loader.load("resource/ui/clip_num.png",laya.utils.Handler.create(this,loadComplete));//加载资源 * function loadComplete() { * console.log("资源加载完成!"); * clip = new laya.ui.Clip("resource/ui/clip_num.png",10,1);//创建一个 Clip 类的实例对象 clip ,传入它的皮肤skin和横向分割数量、竖向分割数量。 * clip.autoPlay = true;//设置 clip 动画自动播放。 * clip.interval = 100;//设置 clip 动画的播放时间间隔。 * clip.x =100;//设置 clip 对象的属性 x 的值,用于控制 clip 对象的显示位置。 * clip.y =100;//设置 clip 对象的属性 y 的值,用于控制 clip 对象的显示位置。 * clip.on(Event.CLICK,this,onClick);//给 clip 添加点击事件函数侦听。 * Laya.stage.addChild(clip);//将此 clip 对象添加到显示列表。 * } * function onClick() * { * console.log("clip 的点击事件侦听处理函数。"); * if(clip.isPlaying == true) * { * clip.stop(); * }else { * clip.play(); * } * } * @example * import Clip = laya.ui.Clip; * import Handler = laya.utils.Handler; * class Clip_Example { * private clip: Clip; * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * this.onInit(); * } * private onInit(): void { * this.clip = new Clip("resource/ui/clip_num.png", 10, 1);//创建一个 Clip 类的实例对象 clip ,传入它的皮肤skin和横向分割数量、竖向分割数量。 * this.clip.autoPlay = true;//设置 clip 动画自动播放。 * this.clip.interval = 100;//设置 clip 动画的播放时间间隔。 * this.clip.x = 100;//设置 clip 对象的属性 x 的值,用于控制 clip 对象的显示位置。 * this.clip.y = 100;//设置 clip 对象的属性 y 的值,用于控制 clip 对象的显示位置。 * this.clip.on(laya.events.Event.CLICK, this, this.onClick);//给 clip 添加点击事件函数侦听。 * Laya.stage.addChild(this.clip);//将此 clip 对象添加到显示列表。 * } * private onClick(): void { * console.log("clip 的点击事件侦听处理函数。clip.total=" + this.clip.total); * if (this.clip.isPlaying == true) { * this.clip.stop();//停止动画。 * } else { * this.clip.play();//播放动画。 * } * } * } * */ class Clip extends Component { protected _sources: Array; protected _bitmap: AutoBitmap; protected _skin: string; protected _clipX: number; protected _clipY: number; protected _clipWidth: number; protected _clipHeight: number; protected _autoPlay: boolean; protected _interval: number; protected _complete: Handler; protected _isPlaying: boolean; protected _index: number; protected _clipChanged: boolean; protected _group: string; protected _toIndex: number; /** * 创建一个新的 Clip 示例。 * @param url 资源类库名或者地址 * @param clipX x方向分割个数 * @param clipY y方向分割个数 */ constructor(url?: string, clipX?: number, clipY?: number); /**@inheritDoc */ destroy(destroyChild?: boolean): void; /** * 销毁对象并释放加载的皮肤资源。 */ dispose(): void; protected createChildren(): void; protected _onDisplay(e?: Event): void; /** * @copy laya.ui.Image#skin */ skin: string; /**X轴(横向)切片数量。*/ clipX: number; /**Y轴(竖向)切片数量。*/ clipY: number; /** * 横向分割时每个切片的宽度,与 clipX 同时设置时优先级高于 clipX 。 */ clipWidth: number; /** * 竖向分割时每个切片的高度,与 clipY 同时设置时优先级高于 clipY 。 */ clipHeight: number; protected changeClip(): void; protected loadComplete(url: string, img: Texture): void; /** * 源数据。 */ sources: Array; /** * 资源分组。 */ group: string; /**@inheritDoc */ width: number; /**@inheritDoc */ height: number; protected readonly measureWidth: number; protected readonly measureHeight: number; /** *

    当前实例的位图 AutoImage 实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    * @see laya.ui.AutoBitmap.sizeGrid */ sizeGrid: string; /** * 当前帧索引。 */ index: number; /** * 切片动画的总帧数。 */ readonly total: number; /** * 表示是否自动播放动画,若自动播放值为true,否则值为false; *

    可控制切片动画的播放、停止。

    */ autoPlay: boolean; /** * 表示动画播放间隔时间(以毫秒为单位)。 */ interval: number; /** * 表示动画的当前播放状态。 * 如果动画正在播放中,则为true,否则为flash。 */ isPlaying: boolean; /** * 播放动画。 * @param from 开始索引 * @param to 结束索引,-1为不限制 */ play(from?: number, to?: number): void; protected _loop(): void; /** * 停止动画。 */ stop(): void; /**@inheritDoc */ dataSource: any; /** * AutoBitmap 位图实例。 */ readonly bitmap: AutoBitmap; protected _setClipChanged(): void; } } declare module laya.ui { import Input = laya.display.Input; import Sprite = laya.display.Sprite; import Handler = laya.utils.Handler; /** * ColorPicker 组件将显示包含多个颜色样本的列表,用户可以从中选择颜色。 * * @example 以下示例代码,创建了一个 ColorPicker 实例。 * package * { * import laya.ui.ColorPicker; * import laya.utils.Handler; * public class ColorPicker_Example * { * public function ColorPicker_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/color.png", Handler.create(this,onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * trace("资源加载完成!"); * var colorPicket:ColorPicker = new ColorPicker();//创建一个 ColorPicker 类的实例对象 colorPicket 。 * colorPicket.skin = "resource/ui/color.png";//设置 colorPicket 的皮肤。 * colorPicket.x = 100;//设置 colorPicket 对象的属性 x 的值,用于控制 colorPicket 对象的显示位置。 * colorPicket.y = 100;//设置 colorPicket 对象的属性 y 的值,用于控制 colorPicket 对象的显示位置。 * colorPicket.changeHandler = new Handler(this, onChangeColor,[colorPicket]);//设置 colorPicket 的颜色改变回调函数。 * Laya.stage.addChild(colorPicket);//将此 colorPicket 对象添加到显示列表。 * } * private function onChangeColor(colorPicket:ColorPicker):void * { * trace("当前选择的颜色: " + colorPicket.selectedColor); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * Laya.loader.load("resource/ui/color.png",laya.utils.Handler.create(this,loadComplete));//加载资源 * function loadComplete() * { * console.log("资源加载完成!"); * var colorPicket = new laya.ui.ColorPicker();//创建一个 ColorPicker 类的实例对象 colorPicket 。 * colorPicket.skin = "resource/ui/color.png";//设置 colorPicket 的皮肤。 * colorPicket.x = 100;//设置 colorPicket 对象的属性 x 的值,用于控制 colorPicket 对象的显示位置。 * colorPicket.y = 100;//设置 colorPicket 对象的属性 y 的值,用于控制 colorPicket 对象的显示位置。 * colorPicket.changeHandler = laya.utils.Handler.create(this, onChangeColor,[colorPicket],false);//设置 colorPicket 的颜色改变回调函数。 * Laya.stage.addChild(colorPicket);//将此 colorPicket 对象添加到显示列表。 * } * function onChangeColor(colorPicket) * { * console.log("当前选择的颜色: " + colorPicket.selectedColor); * } * @example * import ColorPicker = laya.ui.ColorPicker; * import Handler = laya.utils.Handler; * class ColorPicker_Example { * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/color.png", Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * console.log("资源加载完成!"); * var colorPicket: ColorPicker = new ColorPicker();//创建一个 ColorPicker 类的实例对象 colorPicket 。 * colorPicket.skin = "resource/ui/color.png";//设置 colorPicket 的皮肤。 * colorPicket.x = 100;//设置 colorPicket 对象的属性 x 的值,用于控制 colorPicket 对象的显示位置。 * colorPicket.y = 100;//设置 colorPicket 对象的属性 y 的值,用于控制 colorPicket 对象的显示位置。 * colorPicket.changeHandler = new Handler(this, this.onChangeColor, [colorPicket]);//设置 colorPicket 的颜色改变回调函数。 * Laya.stage.addChild(colorPicket);//将此 colorPicket 对象添加到显示列表。 * } * private onChangeColor(colorPicket: ColorPicker): void { * console.log("当前选择的颜色: " + colorPicket.selectedColor); * } * } */ class ColorPicker extends Component { /** * 当颜色发生改变时执行的函数处理器。 * 默认返回参数color:颜色值字符串。 */ changeHandler: Handler; protected _gridSize: number; protected _bgColor: string; protected _borderColor: string; protected _inputColor: string; protected _inputBgColor: string; protected _colorPanel: Box; protected _colorTiles: Sprite; protected _colorBlock: Sprite; protected _colorInput: Input; protected _colorButton: Button; protected _colors: Array; protected _selectedColor: string; protected _panelChanged: boolean; /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected createChildren(): void; protected initialize(): void; protected changePanel(): void; /** * 打开颜色样本列表面板。 */ open(): void; /** * 关闭颜色样本列表面板。 */ close(): void; protected getColorByMouse(): string; /** * 表示选择的颜色值。 */ selectedColor: string; /** * @copy laya.ui.Button#skin */ skin: string; /** * 表示颜色样本列表面板的背景颜色值。 */ bgColor: string; /** * 表示颜色样本列表面板的边框颜色值。 */ borderColor: string; /** * 表示颜色样本列表面板选择或输入的颜色值。 */ inputColor: string; /** * 表示颜色输入框的背景颜色值。 */ inputBgColor: string; protected _setPanelChanged(): void; } } declare module laya.ui { import Event = laya.events.Event; import Handler = laya.utils.Handler; /** * ComboBox 组件包含一个下拉列表,用户可以从该列表中选择单个值。 * * @example 以下示例代码,创建了一个 ComboBox 实例。 * package * { * import laya.ui.ComboBox; * import laya.utils.Handler; * public class ComboBox_Example * { * public function ComboBox_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/button.png", Handler.create(this,onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * trace("资源加载完成!"); * var comboBox:ComboBox = new ComboBox("resource/ui/button.png", "item0,item1,item2,item3,item4,item5");//创建一个 ComboBox 类的实例对象 comboBox ,传入它的皮肤和标签集。 * comboBox.x = 100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 * comboBox.y = 100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 * comboBox.selectHandler = new Handler(this, onSelect);//设置 comboBox 选择项改变时执行的处理器。 * Laya.stage.addChild(comboBox);//将此 comboBox 对象添加到显示列表。 * } * private function onSelect(index:int):void * { * trace("当前选中的项对象索引: ",index); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/button.png",laya.utils.Handler.create(this,loadComplete));//加载资源 * function loadComplete() { * console.log("资源加载完成!"); * var comboBox = new laya.ui.ComboBox("resource/ui/button.png", "item0,item1,item2,item3,item4,item5");//创建一个 ComboBox 类的实例对象 comboBox ,传入它的皮肤和标签集。 * comboBox.x = 100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 * comboBox.y = 100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 * comboBox.selectHandler = new laya.utils.Handler(this, onSelect);//设置 comboBox 选择项改变时执行的处理器。 * Laya.stage.addChild(comboBox);//将此 comboBox 对象添加到显示列表。 * } * function onSelect(index) * { * console.log("当前选中的项对象索引: ",index); * } * @example * import ComboBox = laya.ui.ComboBox; * import Handler = laya.utils.Handler; * class ComboBox_Example { * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/button.png", Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * console.log("资源加载完成!"); * var comboBox: ComboBox = new ComboBox("resource/ui/button.png", "item0,item1,item2,item3,item4,item5");//创建一个 ComboBox 类的实例对象 comboBox ,传入它的皮肤和标签集。 * comboBox.x = 100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 * comboBox.y = 100;//设置 comboBox 对象的属性 x 的值,用于控制 comboBox 对象的显示位置。 * comboBox.selectHandler = new Handler(this, this.onSelect);//设置 comboBox 选择项改变时执行的处理器。 * Laya.stage.addChild(comboBox);//将此 comboBox 对象添加到显示列表。 * } * private onSelect(index: number): void { * console.log("当前选中的项对象索引: ", index); * } * } * */ class ComboBox extends Component { protected _visibleNum: number; protected _button: Button; protected _list: List; protected _isOpen: boolean; protected _itemColors: Array; protected _itemSize: number; protected _labels: Array; protected _selectedIndex: number; protected _selectHandler: Handler; protected _itemHeight: number; protected _listHeight: number; protected _listChanged: boolean; protected _itemChanged: boolean; protected _scrollBarSkin: string; protected _isCustomList: boolean; /** * 渲染项,用来显示下拉列表展示对象 */ itemRender: any; /** * 创建一个新的 ComboBox 组件实例。 * @param skin 皮肤资源地址。 * @param labels 下拉列表的标签集字符串。以逗号做分割,如"item0,item1,item2,item3,item4,item5"。 */ constructor(skin?: string, labels?: string); /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected createChildren(): void; /** * @copy laya.ui.Button#skin */ skin: string; protected readonly measureWidth: number; protected readonly measureHeight: number; protected changeList(): void; protected onlistItemMouse(e: Event, index: number): void; protected changeOpen(): void; /**@inheritDoc */ width: number; /**@inheritDoc */ height: number; /** * 标签集合字符串。 */ labels: string; protected changeItem(): void; /** * 表示选择的下拉列表项的索引。 */ selectedIndex: number; /** * 改变下拉列表的选择项时执行的处理器(默认返回参数index:int)。 */ selectHandler: Handler; /** * 表示选择的下拉列表项的的标签。 */ selectedLabel: string; /** * 获取或设置没有滚动条的下拉列表中可显示的最大行数。 */ visibleNum: number; /** * 下拉列表项颜色。 *

    格式:"悬停或被选中时背景颜色,悬停或被选中时标签颜色,标签颜色,边框颜色,背景颜色"

    */ itemColors: string; /** * 下拉列表项标签的字体大小。 */ itemSize: number; /** * 表示下拉列表的打开状态。 */ isOpen: boolean; protected removeList(e: Event): void; /** * 滚动条皮肤。 */ scrollBarSkin: string; /** *

    当前实例的位图 AutoImage 实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    * @see laya.ui.AutoBitmap.sizeGrid */ sizeGrid: string; /** * 获取对 ComboBox 组件所包含的 VScrollBar 滚动条组件的引用。 */ readonly scrollBar: VScrollBar; /** * 获取对 ComboBox 组件所包含的 Button 组件的引用。 */ readonly button: Button; /** * 获取对 ComboBox 组件所包含的 List 列表组件的引用。 */ list: List; /**@inheritDoc */ dataSource: any; /** * 获取或设置对 ComboBox 组件所包含的 Button 组件的文本标签颜色。 *

    格式:upColor,overColor,downColor,disableColor

    */ labelColors: string; /** * 获取或设置对 ComboBox 组件所包含的 Button 组件的文本边距。 *

    格式:上边距,右边距,下边距,左边距

    */ labelPadding: string; /** * 获取或设置对 ComboBox 组件所包含的 Button 组件的标签字体大小。 */ labelSize: number; /** * 表示按钮文本标签是否为粗体字。 * @see laya.display.Text#bold */ labelBold: boolean; /** * 表示按钮文本标签的字体名称,以字符串形式表示。 * @see laya.display.Text#font */ labelFont: string; /** * 表示按钮的状态值。 * @see laya.ui.Button#stateNum */ stateNum: number; } } declare module laya.ui { import Sprite = laya.display.Sprite; /** * Component 是ui控件类的基类。 *

    生命周期:preinitialize > createChildren > initialize > 组件构造函数

    */ class Component extends Sprite implements IComponent { protected _layout: LayoutStyle; protected _dataSource: any; protected _toolTip: any; protected _tag: any; protected _disabled: boolean; protected _gray: boolean; /** * 是否启用相对布局 */ layoutEnabled: boolean; /** *

    创建一个新的 Component 实例。

    */ constructor(); /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected preinitialize(): void; protected createChildren(): void; protected initialize(): void; /** *

    延迟运行指定的函数。

    *

    在控件被显示在屏幕之前调用,一般用于延迟计算数据。

    * @param method 要执行的函数的名称。例如,functionName。 * @param args 传递给 method 函数的可选参数列表。 * * @see #runCallLater() */ callLater(method: Function, args?: Array): void; /** *

    如果有需要延迟调用的函数(通过 callLater 函数设置),则立即执行延迟调用函数。

    * @param method 要执行的函数名称。例如,functionName。 * @see #callLater() */ runCallLater(method: Function): void; /** *

    表示显示对象的宽度,以像素为单位。

    *

    注:当值为0时,宽度为自适应大小。

    */ width: number; /** *

    对象的显示宽度(以像素为单位)。

    */ readonly displayWidth: number; protected readonly measureWidth: number; protected commitMeasure(): void; /** *

    表示显示对象的高度,以像素为单位。

    *

    注:当值为0时,高度为自适应大小。

    */ height: number; /** *

    对象的显示高度(以像素为单位)。

    */ readonly displayHeight: number; protected readonly measureHeight: number; /**@inheritDoc */ scaleX: number; /**@inheritDoc */ scaleY: number; protected changeSize(): void; /** *

    数据赋值,通过对UI赋值来控制UI显示逻辑。

    *

    简单赋值会更改组件的默认属性,使用大括号可以指定组件的任意属性进行赋值。

    * @example //默认属性赋值 dataSource = //任意属性赋值 dataSource = */ dataSource: any; /** *

    从组件顶边到其内容区域顶边之间的垂直距离(以像素为单位)。

    */ top: number; /** *

    从组件底边到其内容区域底边之间的垂直距离(以像素为单位)。

    */ bottom: number; /** *

    从组件左边到其内容区域左边之间的水平距离(以像素为单位)。

    */ left: number; /** *

    从组件右边到其内容区域右边之间的水平距离(以像素为单位)。

    */ right: number; /** *

    在父容器中,此对象的水平方向中轴线与父容器的水平方向中心线的距离(以像素为单位)。

    */ centerX: number; /** *

    在父容器中,此对象的垂直方向中轴线与父容器的垂直方向中心线的距离(以像素为单位)。

    */ centerY: number; /**X轴锚点,值为0-1*/ anchorX: number; /**Y轴锚点,值为0-1*/ anchorY: number; /** *

    对象的标签。

    * @internal 冗余字段,可以用来储存数据。 */ tag: any; protected onCompResize(): void; protected resetLayoutX(): void; protected resetLayoutY(): void; /** *

    鼠标悬停提示。

    *

    可以赋值为文本 String 或函数 Handler ,用来实现自定义样式的鼠标提示和参数携带等。

    * @example * private var _testTips:TestTipsUI = new TestTipsUI(); * private function testTips():void { //简单鼠标提示 * btn2.toolTip = "这里是鼠标提示<b>粗体</b><br>换行"; //自定义的鼠标提示 * btn1.toolTip = showTips1; //带参数的自定义鼠标提示 * clip.toolTip = new Handler(this,showTips2, ["clip"]); * } * private function showTips1():void { * _testTips.label.text = "这里是按钮[" + btn1.label + "]"; * tip.addChild(_testTips); * } * private function showTips2(name:String):void { * _testTips.label.text = "这里是" + name; * tip.addChild(_testTips); * } */ toolTip: any; /** * XML 数据。 */ comXml: any; /** 是否变灰。*/ gray: boolean; /** 是否禁用页面,设置为true后,会变灰并且禁用鼠标。*/ disabled: boolean; } } declare module laya.ui { import Event = laya.events.Event; import Rectangle = laya.maths.Rectangle; import Handler = laya.utils.Handler; /** * Dialog 组件是一个弹出对话框,实现对话框弹出,拖动,模式窗口功能。 * 可以通过UIConfig设置弹出框背景透明度,模式窗口点击边缘是否关闭等 * 通过设置zOrder属性,可以更改弹出的层次 * 通过设置popupEffect和closeEffect可以设置弹出效果和关闭效果,如果不想有任何弹出关闭效果,可以设置前述属性为空 * * @example 以下示例代码,创建了一个 Dialog 实例。 * package * { * import laya.ui.Dialog; * import laya.utils.Handler; * public class Dialog_Example * { * private var dialog:Dialog_Instance; * public function Dialog_Example() * { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/btn_close.png", Handler.create(this, onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * dialog = new Dialog_Instance();//创建一个 Dialog_Instance 类的实例对象 dialog。 * dialog.dragArea = "0,0,150,50";//设置 dialog 的拖拽区域。 * dialog.show();//显示 dialog。 * dialog.closeHandler = new Handler(this, onClose);//设置 dialog 的关闭函数处理器。 * } * private function onClose(name:String):void * { * if (name == Dialog.CLOSE) * { * trace("通过点击 name 为" + name +"的组件,关闭了dialog。"); * } * } * } * } * import laya.ui.Button; * import laya.ui.Dialog; * import laya.ui.Image; * class Dialog_Instance extends Dialog * { * function Dialog_Instance():void * { * var bg:Image = new Image("resource/ui/bg.png"); * bg.sizeGrid = "40,10,5,10"; * bg.width = 150; * bg.height = 250; * addChild(bg); * var image:Image = new Image("resource/ui/image.png"); * addChild(image); * var button:Button = new Button("resource/ui/btn_close.png"); * button.name = Dialog.CLOSE;//设置button的name属性值。 * button.x = 0; * button.y = 0; * addChild(button); * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高、渲染模式 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * var dialog; * Laya.loader.load("resource/ui/btn_close.png", laya.utils.Handler.create(this, loadComplete));//加载资源 * (function (_super) {//新建一个类Dialog_Instance继承自laya.ui.Dialog。 * function Dialog_Instance() { * Dialog_Instance.__super.call(this);//初始化父类 * var bg = new laya.ui.Image("resource/ui/bg.png");//新建一个 Image 类的实例 bg 。 * bg.sizeGrid = "10,40,10,5";//设置 bg 的网格信息。 * bg.width = 150;//设置 bg 的宽度。 * bg.height = 250;//设置 bg 的高度。 * this.addChild(bg);//将 bg 添加到显示列表。 * var image = new laya.ui.Image("resource/ui/image.png");//新建一个 Image 类的实例 image 。 * this.addChild(image);//将 image 添加到显示列表。 * var button = new laya.ui.Button("resource/ui/btn_close.png");//新建一个 Button 类的实例 bg 。 * button.name = laya.ui.Dialog.CLOSE;//设置 button 的 name 属性值。 * button.x = 0;//设置 button 对象的属性 x 的值,用于控制 button 对象的显示位置。 * button.y = 0;//设置 button 对象的属性 y 的值,用于控制 button 对象的显示位置。 * this.addChild(button);//将 button 添加到显示列表。 * }; * Laya.class(Dialog_Instance,"mypackage.dialogExample.Dialog_Instance",_super);//注册类Dialog_Instance。 * })(laya.ui.Dialog); * function loadComplete() { * console.log("资源加载完成!"); * dialog = new mypackage.dialogExample.Dialog_Instance();//创建一个 Dialog_Instance 类的实例对象 dialog。 * dialog.dragArea = "0,0,150,50";//设置 dialog 的拖拽区域。 * dialog.show();//显示 dialog。 * dialog.closeHandler = new laya.utils.Handler(this, onClose);//设置 dialog 的关闭函数处理器。 * } * function onClose(name) { * if (name == laya.ui.Dialog.CLOSE) { * console.log("通过点击 name 为" + name + "的组件,关闭了dialog。"); * } * } * @example * import Dialog = laya.ui.Dialog; * import Handler = laya.utils.Handler; * class Dialog_Example { * private dialog: Dialog_Instance; * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load("resource/ui/btn_close.png", Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * this.dialog = new Dialog_Instance();//创建一个 Dialog_Instance 类的实例对象 dialog。 * this.dialog.dragArea = "0,0,150,50";//设置 dialog 的拖拽区域。 * this.dialog.show();//显示 dialog。 * this.dialog.closeHandler = new Handler(this, this.onClose);//设置 dialog 的关闭函数处理器。 * } * private onClose(name: string): void { * if (name == Dialog.CLOSE) { * console.log("通过点击 name 为" + name + "的组件,关闭了dialog。"); * } * } * } * import Button = laya.ui.Button; * class Dialog_Instance extends Dialog { * Dialog_Instance(): void { * var bg: laya.ui.Image = new laya.ui.Image("resource/ui/bg.png"); * bg.sizeGrid = "40,10,5,10"; * bg.width = 150; * bg.height = 250; * this.addChild(bg); * var image: laya.ui.Image = new laya.ui.Image("resource/ui/image.png"); * this.addChild(image); * var button: Button = new Button("resource/ui/btn_close.png"); * button.name = Dialog.CLOSE;//设置button的name属性值。 * button.x = 0; * button.y = 0; * this.addChild(button); * } * } */ class Dialog extends View { /**对话框内的某个按钮命名为close,点击此按钮则会关闭*/ static CLOSE: string; /**对话框内的某个按钮命名为cancel,点击此按钮则会关闭*/ static CANCEL: string; /**对话框内的某个按钮命名为sure,点击此按钮则会关闭*/ static SURE: string; /**对话框内的某个按钮命名为no,点击此按钮则会关闭*/ static NO: string; /**对话框内的某个按钮命名为ok,点击此按钮则会关闭*/ static OK: string; /**对话框内的某个按钮命名为yes,点击此按钮则会关闭*/ static YES: string; /**对话框管理容器,所有的对话框都在该容器内,并且受管理器管,可以自定义自己的管理器,来更改窗口管理的流程。 * 任意对话框打开和关闭,都会触发管理类的open和close事件*/ static manager: DialogManager; /** * 一个布尔值,指定对话框是否居中弹。 *

    如果值为true,则居中弹出,否则,则根据对象坐标显示,默认为true。

    */ popupCenter: boolean; /** * 对话框被关闭时会触发的回调函数处理器。 *

    回调函数参数为用户点击的按钮名字name:String。

    */ closeHandler: Handler; /** * 弹出对话框效果,可以设置一个效果代替默认的弹出效果,如果不想有任何效果,可以赋值为null * 全局默认弹出效果可以通过manager.popupEffect修改 */ popupEffect: Handler; /** * 关闭对话框效果,可以设置一个效果代替默认的关闭效果,如果不想有任何效果,可以赋值为null * 全局默认关闭效果可以通过manager.closeEffect修改 */ closeEffect: Handler; /**组名称*/ group: string; /**是否是模式窗口*/ isModal: boolean; protected _dragArea: Rectangle; protected initialize(): void; protected _dealDragArea(): void; protected _onClick(e: Event): void; /** * 显示对话框(以非模式窗口方式显示)。 * @param closeOther 是否关闭其它的对话框。若值为true则关闭其它对话框。 * @param showEffect 是否显示弹出效果 */ show(closeOther?: boolean, showEffect?: boolean): void; /** * 显示对话框(以模式窗口方式显示)。 * @param closeOther 是否关闭其它的对话框。若值为true则关闭其它对话框。 * @param showEffect 是否显示弹出效果 */ popup(closeOther?: boolean, showEffect?: boolean): void; protected _open(modal: boolean, closeOther: boolean, showEffect: boolean): void; /**打开完成后,调用此方法(如果有弹出动画,则在动画完成后执行)*/ onOpened(): void; /** * 关闭对话框。 * @param type 如果是点击默认关闭按钮触发,则传入关闭按钮的名字(name),否则为null。 * @param showEffect 是否显示关闭效果 */ close(type?: string, showEffect?: boolean): void; /**关闭完成后,调用此方法(如果有关闭动画,则在动画完成后执行) * @param type 如果是点击默认关闭按钮触发,则传入关闭按钮的名字(name),否则为null。 */ onClosed(type?: string): void; /** * 用来指定对话框的拖拽区域。默认值为"0,0,0,0"。 *

    格式:构成一个矩形所需的 x,y,width,heith 值,用逗号连接为字符串。 * 例如:"0,0,100,200"。 *

    * * @see #includeExamplesSummary 请参考示例 */ dragArea: string; /** * 弹出框的显示状态;如果弹框处于显示中,则为true,否则为false; */ readonly isPopup: boolean; zOrder: number; /** * 设置锁定界面,在界面未准备好前显示锁定界面,准备完毕后则移除锁定层,如果为空则什么都不显示 * @param view 锁定界面内容 */ static setLockView(view: Component): void; /** * 锁定所有层,显示加载条信息,防止下面内容被点击 */ static lock(value: boolean): void; /**关闭所有对话框。*/ static closeAll(): void; /** * 根据组获取对话框集合 * @param group 组名称 * @return 对话框数组 */ static getDialogsByGroup(group: string): Array; /** * 根据组关闭所有弹出框 * @param group 需要关闭的组名称 */ static closeByGroup(group: string): Array; } } declare module laya.ui { import Sprite = laya.display.Sprite; import Component = laya.ui.Component; import Dialog = laya.ui.Dialog; import Handler = laya.utils.Handler; /** * DialogManager 对话框管理容器,所有的对话框都在该容器内,并且受管理器管理。 * 任意对话框打开和关闭,都会出发管理类的open和close事件 * 可以通过UIConfig设置弹出框背景透明度,模式窗口点击边缘是否关闭,点击窗口是否切换层次等 * 通过设置对话框的zOrder属性,可以更改弹出的层次 */ class DialogManager extends Sprite { /**遮罩层*/ maskLayer: Sprite; /**锁屏层*/ lockLayer: Sprite; popupEffect: Function; closeEffect: Function; /**全局默认关闭对话框效果,可以设置一个效果代替默认的关闭效果,如果不想有任何效果,可以赋值为null*/ popupEffectHandler: Handler; /**全局默认弹出对话框效果,可以设置一个效果代替默认的弹出效果,如果不想有任何效果,可以赋值为null*/ closeEffectHandler: Handler; /** * 创建一个新的 DialogManager 类实例。 */ constructor(); /**设置锁定界面,如果为空则什么都不显示*/ setLockView(value: Component): void; /** * 显示对话框(非模式窗口类型)。 * @param dialog 需要显示的对象框 Dialog 实例。 * @param closeOther 是否关闭其它对话框,若值为ture,则关闭其它的对话框。 * @param showEffect 是否显示弹出效果 */ open(dialog: Dialog, closeOther?: boolean, showEffect?: boolean): void; /** * 执行打开对话框。 * @param dialog 需要关闭的对象框 Dialog 实例。 * @param type 关闭的类型,默认为空 */ doOpen(dialog: Dialog): void; /** * 锁定所有层,显示加载条信息,防止双击 */ lock(value: boolean): void; /** * 关闭对话框。 * @param dialog 需要关闭的对象框 Dialog 实例。 * @param type 关闭的类型,默认为空 * @param showEffect 是否显示弹出效果 */ close(dialog: Dialog, type?: string, showEffect?: boolean): void; /** * 执行关闭对话框。 * @param dialog 需要关闭的对象框 Dialog 实例。 * @param type 关闭的类型,默认为空 */ doClose(dialog: Dialog, type?: string): void; /** * 关闭所有的对话框。 */ closeAll(): void; /** * 根据组获取所有对话框 * @param group 组名称 * @return 对话框数组 */ getDialogsByGroup(group: string): Array; /** * 根据组关闭所有弹出框 * @param group 需要关闭的组名称 * @return 需要关闭的对话框数组 */ closeByGroup(group: string): Array; _checkMask(): void; } } declare module laya.ui { import Clip = laya.ui.Clip; /** * 字体切片,简化版的位图字体,只需设置一个切片图片和文字内容即可使用,效果同位图字体 * 使用方式:设置位图字体皮肤skin,设置皮肤对应的字体内容sheet(如果多行,可以使用空格换行),示例: * fontClip.skin = "font1.png";//设置皮肤 * fontClip.sheet = "abc123 456";//设置皮肤对应的内容,空格换行。此皮肤为2行5列(显示时skin会被等分为2行5列),第一行对应的文字为"abc123",第二行为"456" * fontClip.value = "a1326";//显示"a1326"文字 */ class FontClip extends Clip { protected _valueArr: string; protected _indexMap: any; protected _sheet: string; protected _direction: string; protected _spaceX: number; protected _spaceY: number; /** * @param skin 位图字体皮肤 * @param sheet 位图字体内容,空格代表换行 */ constructor(skin?: string, sheet?: string); protected createChildren(): void; /** * 设置位图字体内容,空格代表换行。比如"abc123 456",代表第一行对应的文字为"abc123",第二行为"456" */ sheet: string; /** * 设置位图字体的显示内容 */ value: string; /** * 布局方向。 *

    默认值为"horizontal"。

    *

    取值: *

  • "horizontal":表示水平布局。
  • *
  • "vertical":表示垂直布局。
  • *

    */ direction: string; /**X方向文字间隙*/ spaceX: number; /**Y方向文字间隙*/ spaceY: number; /**水平对齐方式*/ align: string; protected changeValue(): void; width: number; height: number; protected readonly measureWidth: number; protected readonly measureHeight: number; destroy(destroyChild?: boolean): void; } } declare module laya.ui { /** * HBox 是一个水平布局容器类。 */ class HBox extends LayoutBox { /** * 无对齐。 */ static NONE: string; /** * 居顶部对齐。 */ static TOP: string; /** * 居中对齐。 */ static MIDDLE: string; /** * 居底部对齐。 */ static BOTTOM: string; protected sortItem(items: Array): void; height: number; protected changeItems(): void; } } declare module laya.ui { /** * 使用 HScrollBar (水平 ScrollBar )控件,可以在因数据太多而不能在显示区域完全显示时控制显示的数据部分。 * @example 以下示例代码,创建了一个 HScrollBar 实例。 * package * { * import laya.ui.HScrollBar; * import laya.utils.Handler; * public class HScrollBar_Example * { * private var hScrollBar:HScrollBar; * public function HScrollBar_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/hscroll.png", "resource/ui/hscroll$bar.png", "resource/ui/hscroll$down.png", "resource/ui/hscroll$up.png"], Handler.create(this, onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * hScrollBar = new HScrollBar();//创建一个 HScrollBar 类的实例对象 hScrollBar 。 * hScrollBar.skin = "resource/ui/hscroll.png";//设置 hScrollBar 的皮肤。 * hScrollBar.x = 100;//设置 hScrollBar 对象的属性 x 的值,用于控制 hScrollBar 对象的显示位置。 * hScrollBar.y = 100;//设置 hScrollBar 对象的属性 y 的值,用于控制 hScrollBar 对象的显示位置。 * hScrollBar.changeHandler = new Handler(this, onChange);//设置 hScrollBar 的滚动变化处理器。 * Laya.stage.addChild(hScrollBar);//将此 hScrollBar 对象添加到显示列表。 * } * private function onChange(value:Number):void * { * trace("滚动条的位置: value=" + value); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * var hScrollBar; * var res = ["resource/ui/hscroll.png", "resource/ui/hscroll$bar.png", "resource/ui/hscroll$down.png", "resource/ui/hscroll$up.png"]; * Laya.loader.load(res,laya.utils.Handler.create(this, onLoadComplete));//加载资源。 * function onLoadComplete() { * console.log("资源加载完成!"); * hScrollBar = new laya.ui.HScrollBar();//创建一个 HScrollBar 类的实例对象 hScrollBar 。 * hScrollBar.skin = "resource/ui/hscroll.png";//设置 hScrollBar 的皮肤。 * hScrollBar.x = 100;//设置 hScrollBar 对象的属性 x 的值,用于控制 hScrollBar 对象的显示位置。 * hScrollBar.y = 100;//设置 hScrollBar 对象的属性 y 的值,用于控制 hScrollBar 对象的显示位置。 * hScrollBar.changeHandler = new laya.utils.Handler(this, onChange);//设置 hScrollBar 的滚动变化处理器。 * Laya.stage.addChild(hScrollBar);//将此 hScrollBar 对象添加到显示列表。 * } * function onChange(value) * { * console.log("滚动条的位置: value=" + value); * } * @example * import HScrollBar = laya.ui.HScrollBar; * import Handler = laya.utils.Handler; * class HScrollBar_Example { * private hScrollBar: HScrollBar; * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/hscroll.png", "resource/ui/hscroll$bar.png", "resource/ui/hscroll$down.png", "resource/ui/hscroll$up.png"], Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * this.hScrollBar = new HScrollBar();//创建一个 HScrollBar 类的实例对象 hScrollBar 。 * this.hScrollBar.skin = "resource/ui/hscroll.png";//设置 hScrollBar 的皮肤。 * this.hScrollBar.x = 100;//设置 hScrollBar 对象的属性 x 的值,用于控制 hScrollBar 对象的显示位置。 * this.hScrollBar.y = 100;//设置 hScrollBar 对象的属性 y 的值,用于控制 hScrollBar 对象的显示位置。 * this.hScrollBar.changeHandler = new Handler(this, this.onChange);//设置 hScrollBar 的滚动变化处理器。 * Laya.stage.addChild(this.hScrollBar);//将此 hScrollBar 对象添加到显示列表。 * } * private onChange(value: number): void { * console.log("滚动条的位置: value=" + value); * } * } */ class HScrollBar extends ScrollBar { protected initialize(): void; } } declare module laya.ui { /** * 使用 HSlider 控件,用户可以通过在滑块轨道的终点之间移动滑块来选择值。 *

    HSlider 控件采用水平方向。滑块轨道从左向右扩展,而标签位于轨道的顶部或底部。

    * * @example 以下示例代码,创建了一个 HSlider 实例。 * package * { * import laya.ui.HSlider; * import laya.utils.Handler; * public class HSlider_Example * { * private var hSlider:HSlider; * public function HSlider_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/hslider.png", "resource/ui/hslider$bar.png"], Handler.create(this, onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * hSlider = new HSlider();//创建一个 HSlider 类的实例对象 hSlider 。 * hSlider.skin = "resource/ui/hslider.png";//设置 hSlider 的皮肤。 * hSlider.min = 0;//设置 hSlider 最低位置值。 * hSlider.max = 10;//设置 hSlider 最高位置值。 * hSlider.value = 2;//设置 hSlider 当前位置值。 * hSlider.tick = 1;//设置 hSlider 刻度值。 * hSlider.x = 100;//设置 hSlider 对象的属性 x 的值,用于控制 hSlider 对象的显示位置。 * hSlider.y = 100;//设置 hSlider 对象的属性 y 的值,用于控制 hSlider 对象的显示位置。 * hSlider.changeHandler = new Handler(this, onChange);//设置 hSlider 位置变化处理器。 * Laya.stage.addChild(hSlider);//把 hSlider 添加到显示列表。 * } * private function onChange(value:Number):void * { * trace("滑块的位置: value=" + value); * } * } * } * @example * Laya.init(640, 800, "canvas");//设置游戏画布宽高、渲染模式 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * var hSlider; * var res = ["resource/ui/hslider.png", "resource/ui/hslider$bar.png"]; * Laya.loader.load(res, laya.utils.Handler.create(this, onLoadComplete)); * function onLoadComplete() { * console.log("资源加载完成!"); * hSlider = new laya.ui.HSlider();//创建一个 HSlider 类的实例对象 hSlider 。 * hSlider.skin = "resource/ui/hslider.png";//设置 hSlider 的皮肤。 * hSlider.min = 0;//设置 hSlider 最低位置值。 * hSlider.max = 10;//设置 hSlider 最高位置值。 * hSlider.value = 2;//设置 hSlider 当前位置值。 * hSlider.tick = 1;//设置 hSlider 刻度值。 * hSlider.x = 100;//设置 hSlider 对象的属性 x 的值,用于控制 hSlider 对象的显示位置。 * hSlider.y = 100;//设置 hSlider 对象的属性 y 的值,用于控制 hSlider 对象的显示位置。 * hSlider.changeHandler = new laya.utils.Handler(this, onChange);//设置 hSlider 位置变化处理器。 * Laya.stage.addChild(hSlider);//把 hSlider 添加到显示列表。 * } * function onChange(value) * { * console.log("滑块的位置: value=" + value); * } * @example * import Handler = laya.utils.Handler; * import HSlider = laya.ui.HSlider; * class HSlider_Example { * private hSlider: HSlider; * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/hslider.png", "resource/ui/hslider$bar.png"], Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * this.hSlider = new HSlider();//创建一个 HSlider 类的实例对象 hSlider 。 * this.hSlider.skin = "resource/ui/hslider.png";//设置 hSlider 的皮肤。 * this.hSlider.min = 0;//设置 hSlider 最低位置值。 * this.hSlider.max = 10;//设置 hSlider 最高位置值。 * this.hSlider.value = 2;//设置 hSlider 当前位置值。 * this.hSlider.tick = 1;//设置 hSlider 刻度值。 * this.hSlider.x = 100;//设置 hSlider 对象的属性 x 的值,用于控制 hSlider 对象的显示位置。 * this.hSlider.y = 100;//设置 hSlider 对象的属性 y 的值,用于控制 hSlider 对象的显示位置。 * this.hSlider.changeHandler = new Handler(this, this.onChange);//设置 hSlider 位置变化处理器。 * Laya.stage.addChild(this.hSlider);//把 hSlider 添加到显示列表。 * } * private onChange(value: number): void { * console.log("滑块的位置: value=" + value); * } * } * * @see laya.ui.Slider */ class HSlider extends Slider { /** * 创建一个 HSlider 类实例。 * @param skin 皮肤。 */ constructor(skin?: string); } } declare module laya.ui { /**容器接口,实现了编辑器容器类型。*/ interface IBox extends IComponent { } } declare module laya.ui { /**组件接口,实现了编辑器组件类型。*/ interface IComponent { } } declare module laya.ui { /** * Item接口。 */ interface IItem { /** * 初始化列表项。 */ initItems(): void; } } declare module laya.ui { import Texture = laya.resource.Texture; import AutoBitmap = laya.ui.AutoBitmap; import Component = laya.ui.Component; /** * Image 类是用于表示位图图像或绘制图形的显示对象。 * Image和Clip组件是唯一支持异步加载的两个组件,比如img.skin = "abc/xxx.png",其他UI组件均不支持异步加载。 * * @example 以下示例代码,创建了一个新的 Image 实例,设置了它的皮肤、位置信息,并添加到舞台上。 * package * { * import laya.ui.Image; * public class Image_Example * { * public function Image_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * onInit(); * } * private function onInit():void * { * var bg:Image = new Image("resource/ui/bg.png");//创建一个 Image 类的实例对象 bg ,并传入它的皮肤。 * bg.x = 100;//设置 bg 对象的属性 x 的值,用于控制 bg 对象的显示位置。 * bg.y = 100;//设置 bg 对象的属性 y 的值,用于控制 bg 对象的显示位置。 * bg.sizeGrid = "40,10,5,10";//设置 bg 对象的网格信息。 * bg.width = 150;//设置 bg 对象的宽度。 * bg.height = 250;//设置 bg 对象的高度。 * Laya.stage.addChild(bg);//将此 bg 对象添加到显示列表。 * var image:Image = new Image("resource/ui/image.png");//创建一个 Image 类的实例对象 image ,并传入它的皮肤。 * image.x = 100;//设置 image 对象的属性 x 的值,用于控制 image 对象的显示位置。 * image.y = 100;//设置 image 对象的属性 y 的值,用于控制 image 对象的显示位置。 * Laya.stage.addChild(image);//将此 image 对象添加到显示列表。 * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * onInit(); * function onInit() { * var bg = new laya.ui.Image("resource/ui/bg.png");//创建一个 Image 类的实例对象 bg ,并传入它的皮肤。 * bg.x = 100;//设置 bg 对象的属性 x 的值,用于控制 bg 对象的显示位置。 * bg.y = 100;//设置 bg 对象的属性 y 的值,用于控制 bg 对象的显示位置。 * bg.sizeGrid = "40,10,5,10";//设置 bg 对象的网格信息。 * bg.width = 150;//设置 bg 对象的宽度。 * bg.height = 250;//设置 bg 对象的高度。 * Laya.stage.addChild(bg);//将此 bg 对象添加到显示列表。 * var image = new laya.ui.Image("resource/ui/image.png");//创建一个 Image 类的实例对象 image ,并传入它的皮肤。 * image.x = 100;//设置 image 对象的属性 x 的值,用于控制 image 对象的显示位置。 * image.y = 100;//设置 image 对象的属性 y 的值,用于控制 image 对象的显示位置。 * Laya.stage.addChild(image);//将此 image 对象添加到显示列表。 * } * @example * class Image_Example { * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * this.onInit(); * } * private onInit(): void { * var bg: laya.ui.Image = new laya.ui.Image("resource/ui/bg.png");//创建一个 Image 类的实例对象 bg ,并传入它的皮肤。 * bg.x = 100;//设置 bg 对象的属性 x 的值,用于控制 bg 对象的显示位置。 * bg.y = 100;//设置 bg 对象的属性 y 的值,用于控制 bg 对象的显示位置。 * bg.sizeGrid = "40,10,5,10";//设置 bg 对象的网格信息。 * bg.width = 150;//设置 bg 对象的宽度。 * bg.height = 250;//设置 bg 对象的高度。 * Laya.stage.addChild(bg);//将此 bg 对象添加到显示列表。 * var image: laya.ui.Image = new laya.ui.Image("resource/ui/image.png");//创建一个 Image 类的实例对象 image ,并传入它的皮肤。 * image.x = 100;//设置 image 对象的属性 x 的值,用于控制 image 对象的显示位置。 * image.y = 100;//设置 image 对象的属性 y 的值,用于控制 image 对象的显示位置。 * Laya.stage.addChild(image);//将此 image 对象添加到显示列表。 * } * } * @see laya.ui.AutoBitmap */ class Image extends Component { _bitmap: AutoBitmap; protected _skin: string; protected _group: string; /** * 创建一个 Image 实例。 * @param skin 皮肤资源地址。 */ constructor(skin?: string); /**@inheritDoc */ destroy(destroyChild?: boolean): void; /** * 销毁对象并释放加载的皮肤资源。 */ dispose(): void; protected createChildren(): void; /** *

    对象的皮肤地址,以字符串表示。

    *

    如果资源未加载,则先加载资源,加载完成后应用于此对象。

    * 注意:资源加载完成后,会自动缓存至资源库中。 */ skin: string; /** * @copy laya.ui.AutoBitmap#source */ source: Texture; /** * 资源分组。 */ group: string; protected setSource(url: string, img?: any): void; protected readonly measureWidth: number; protected readonly measureHeight: number; /**@inheritDoc */ width: number; /**@inheritDoc */ height: number; /** *

    当前实例的位图 AutoImage 实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"。

    * @see laya.ui.AutoBitmap#sizeGrid */ sizeGrid: string; /**@inheritDoc */ dataSource: any; } } declare module laya.ui { /** * IRender 接口,实现设置项的渲染类型。 */ interface IRender { } } declare module laya.ui { /** * ISelect 接口,实现对象的 selected 属性和 clickHandler 选择回调函数处理器。 */ interface ISelect { } } declare module laya.ui { import Text = laya.display.Text; import Component = laya.ui.Component; /** *

    Label 类用于创建显示对象以显示文本。

    * * @example 以下示例代码,创建了一个 Label 实例。 * package * { * import laya.ui.Label; * public class Label_Example * { * public function Label_Example() * { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * onInit(); * } * private function onInit():void * { * var label:Label = new Label();//创建一个 Label 类的实例对象 label 。 * label.font = "Arial";//设置 label 的字体。 * label.bold = true;//设置 label 显示为粗体。 * label.leading = 4;//设置 label 的行间距。 * label.wordWrap = true;//设置 label 自动换行。 * label.padding = "10,10,10,10";//设置 label 的边距。 * label.color = "#ff00ff";//设置 label 的颜色。 * label.text = "Hello everyone,我是一个可爱的文本!";//设置 label 的文本内容。 * label.x = 100;//设置 label 对象的属性 x 的值,用于控制 label 对象的显示位置。 * label.y = 100;//设置 label 对象的属性 y 的值,用于控制 label 对象的显示位置。 * label.width = 300;//设置 label 的宽度。 * label.height = 200;//设置 label 的高度。 * Laya.stage.addChild(label);//将 label 添加到显示列表。 * var passwordLabel:Label = new Label("请原谅我,我不想被人看到我心里话。");//创建一个 Label 类的实例对象 passwordLabel 。 * passwordLabel.asPassword = true;//设置 passwordLabel 的显示反式为密码显示。 * passwordLabel.x = 100;//设置 passwordLabel 对象的属性 x 的值,用于控制 passwordLabel 对象的显示位置。 * passwordLabel.y = 350;//设置 passwordLabel 对象的属性 y 的值,用于控制 passwordLabel 对象的显示位置。 * passwordLabel.width = 300;//设置 passwordLabel 的宽度。 * passwordLabel.color = "#000000";//设置 passwordLabel 的文本颜色。 * passwordLabel.bgColor = "#ccffff";//设置 passwordLabel 的背景颜色。 * passwordLabel.fontSize = 20;//设置 passwordLabel 的文本字体大小。 * Laya.stage.addChild(passwordLabel);//将 passwordLabel 添加到显示列表。 * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * onInit(); * function onInit(){ * var label = new laya.ui.Label();//创建一个 Label 类的实例对象 label 。 * label.font = "Arial";//设置 label 的字体。 * label.bold = true;//设置 label 显示为粗体。 * label.leading = 4;//设置 label 的行间距。 * label.wordWrap = true;//设置 label 自动换行。 * label.padding = "10,10,10,10";//设置 label 的边距。 * label.color = "#ff00ff";//设置 label 的颜色。 * label.text = "Hello everyone,我是一个可爱的文本!";//设置 label 的文本内容。 * label.x = 100;//设置 label 对象的属性 x 的值,用于控制 label 对象的显示位置。 * label.y = 100;//设置 label 对象的属性 y 的值,用于控制 label 对象的显示位置。 * label.width = 300;//设置 label 的宽度。 * label.height = 200;//设置 label 的高度。 * Laya.stage.addChild(label);//将 label 添加到显示列表。 * var passwordLabel = new laya.ui.Label("请原谅我,我不想被人看到我心里话。");//创建一个 Label 类的实例对象 passwordLabel 。 * passwordLabel.asPassword = true;//设置 passwordLabel 的显示反式为密码显示。 * passwordLabel.x = 100;//设置 passwordLabel 对象的属性 x 的值,用于控制 passwordLabel 对象的显示位置。 * passwordLabel.y = 350;//设置 passwordLabel 对象的属性 y 的值,用于控制 passwordLabel 对象的显示位置。 * passwordLabel.width = 300;//设置 passwordLabel 的宽度。 * passwordLabel.color = "#000000";//设置 passwordLabel 的文本颜色。 * passwordLabel.bgColor = "#ccffff";//设置 passwordLabel 的背景颜色。 * passwordLabel.fontSize = 20;//设置 passwordLabel 的文本字体大小。 * Laya.stage.addChild(passwordLabel);//将 passwordLabel 添加到显示列表。 * } * @example * import Label = laya.ui.Label; * class Label_Example { * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * this.onInit(); * } * private onInit(): void { * var label: Label = new Label();//创建一个 Label 类的实例对象 label 。 * label.font = "Arial";//设置 label 的字体。 * label.bold = true;//设置 label 显示为粗体。 * label.leading = 4;//设置 label 的行间距。 * label.wordWrap = true;//设置 label 自动换行。 * label.padding = "10,10,10,10";//设置 label 的边距。 * label.color = "#ff00ff";//设置 label 的颜色。 * label.text = "Hello everyone,我是一个可爱的文本!";//设置 label 的文本内容。 * label.x = 100;//设置 label 对象的属性 x 的值,用于控制 label 对象的显示位置。 * label.y = 100;//设置 label 对象的属性 y 的值,用于控制 label 对象的显示位置。 * label.width = 300;//设置 label 的宽度。 * label.height = 200;//设置 label 的高度。 * Laya.stage.addChild(label);//将 label 添加到显示列表。 * var passwordLabel: Label = new Label("请原谅我,我不想被人看到我心里话。");//创建一个 Label 类的实例对象 passwordLabel 。 * passwordLabel.asPassword = true;//设置 passwordLabel 的显示反式为密码显示。 * passwordLabel.x = 100;//设置 passwordLabel 对象的属性 x 的值,用于控制 passwordLabel 对象的显示位置。 * passwordLabel.y = 350;//设置 passwordLabel 对象的属性 y 的值,用于控制 passwordLabel 对象的显示位置。 * passwordLabel.width = 300;//设置 passwordLabel 的宽度。 * passwordLabel.color = "#000000";//设置 passwordLabel 的文本颜色。 * passwordLabel.bgColor = "#ccffff";//设置 passwordLabel 的背景颜色。 * passwordLabel.fontSize = 20;//设置 passwordLabel 的文本字体大小。 * Laya.stage.addChild(passwordLabel);//将 passwordLabel 添加到显示列表。 * } * } * @see laya.display.Text */ class Label extends Component { protected _tf: Text; /** * 创建一个新的 Label 实例。 * @param text 文本内容字符串。 */ constructor(text?: string); /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected createChildren(): void; /** * 当前文本内容字符串。 * @see laya.display.Text.text */ text: string; /**@copy laya.display.Text#changeText() **/ changeText(text: string): void; /** * @copy laya.display.Text#wordWrap */ /** * @copy laya.display.Text#wordWrap */ wordWrap: boolean; /** * @copy laya.display.Text#color */ color: string; /** * @copy laya.display.Text#font */ font: string; /** * @copy laya.display.Text#align */ align: string; /** * @copy laya.display.Text#valign */ valign: string; /** * @copy laya.display.Text#bold */ bold: boolean; /** * @copy laya.display.Text#italic */ italic: boolean; /** * @copy laya.display.Text#leading */ leading: number; /** * @copy laya.display.Text#fontSize */ fontSize: number; /** *

    边距信息

    *

    "上边距,右边距,下边距 , 左边距(边距以像素为单位)"

    * @see laya.display.Text.padding */ padding: string; /** * @copy laya.display.Text#bgColor */ bgColor: string; /** * @copy laya.display.Text#borderColor */ borderColor: string; /** * @copy laya.display.Text#stroke */ stroke: number; /** * @copy laya.display.Text#strokeColor */ strokeColor: string; /** * 文本控件实体 Text 实例。 */ readonly textField: Text; protected readonly measureWidth: number; protected readonly measureHeight: number; /** * @inheritDoc */ /** * @inheritDoc */ width: number; /** * @inheritDoc */ /** * @inheritDoc */ height: number; /**@inheritDoc */ dataSource: any; /** * @copy laya.display.Text#overflow */ /** * @copy laya.display.Text#overflow */ overflow: string; /** * @copy laya.display.Text#underline */ /** * @copy laya.display.Text#underline */ underline: boolean; /** * @copy laya.display.Text#underlineColor */ /** * @copy laya.display.Text#underlineColor */ underlineColor: string; } } declare module laya.ui { import Node = laya.display.Node; /** * LayoutBox 是一个布局容器类。 */ class LayoutBox extends Box { protected _space: number; protected _align: string; protected _itemChanged: boolean; /** @inheritDoc */ addChild(child: Node): Node; /** @inheritDoc */ addChildAt(child: Node, index: number): Node; /** @inheritDoc */ removeChild(child: Node): Node; /** @inheritDoc */ removeChildAt(index: number): Node; /** 刷新。*/ refresh(): void; protected changeItems(): void; /** 子对象的间隔。*/ space: number; /** 子对象对齐方式。*/ align: string; protected sortItem(items: Array): void; protected _setItemChanged(): void; } } declare module laya.ui { /** * LayoutStyle 是一个布局样式类。 */ class LayoutStyle { /**一个已初始化的 LayoutStyle 实例。*/ static EMPTY: LayoutStyle; /**表示距顶边的距离(以像素为单位)。*/ top: number; /**表示距底边的距离(以像素为单位)。*/ bottom: number; /**表示距左边的距离(以像素为单位)。*/ left: number; /**表示距右边的距离(以像素为单位)。*/ right: number; /**表示距水平方向中心轴的距离(以像素为单位)。*/ centerX: number; /**表示距垂直方向中心轴的距离(以像素为单位)。*/ centerY: number; /**X锚点,值为0-1。*/ anchorX: number; /**Y锚点,值为0-1。*/ anchorY: number; /**一个布尔值,表示是否有效。*/ enable: boolean; } } declare module laya.ui { import Event = laya.events.Event; import Point = laya.maths.Point; import Handler = laya.utils.Handler; /** * List 控件可显示项目列表。默认为垂直方向列表。可通过UI编辑器自定义列表。 * * @example 以下示例代码,创建了一个 List 实例。 * package * { * import laya.ui.List; * import laya.utils.Handler; * public class List_Example * { * public function List_Example() * { * Laya.init(640, 800, "false");//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png"], Handler.create(this, onLoadComplete)); * } * private function onLoadComplete():void * { * var arr:Array = [];//创建一个数组,用于存贮列表的数据信息。 * for (var i:int = 0; i < 20; i++) * { * arr.push({label: "item" + i}); * } * var list:List = new List();//创建一个 List 类的实例对象 list 。 * list.itemRender = Item;//设置 list 的单元格渲染器。 * list.repeatX = 1;//设置 list 的水平方向单元格数量。 * list.repeatY = 10;//设置 list 的垂直方向单元格数量。 * list.vScrollBarSkin = "resource/ui/vscroll.png";//设置 list 的垂直方向滚动条皮肤。 * list.array = arr;//设置 list 的列表数据源。 * list.pos(100, 100);//设置 list 的位置。 * list.selectEnable = true;//设置 list 可选。 * list.selectHandler = new Handler(this, onSelect);//设置 list 改变选择项执行的处理器。 * Laya.stage.addChild(list);//将 list 添加到显示列表。 * } * private function onSelect(index:int):void * { * trace("当前选择的项目索引: index= ", index); * } * } * } * import laya.ui.Box; * import laya.ui.Label; * class Item extends Box * { * public function Item() * { * graphics.drawRect(0, 0, 100, 20,null, "#ff0000"); * var label:Label = new Label(); * label.text = "100000"; * label.name = "label";//设置 label 的name属性值。 * label.size(100, 20); * addChild(label); * } * } * @example * (function (_super){ * function Item(){ * Item.__super.call(this);//初始化父类 * this.graphics.drawRect(0, 0, 100, 20, "#ff0000"); * var label = new laya.ui.Label();//创建一个 Label 类的实例对象 label 。 * label.text = "100000";//设置 label 的文本内容。 * label.name = "label";//设置 label 的name属性值。 * label.size(100, 20);//设置 label 的宽度、高度。 * this.addChild(label);//将 label 添加到显示列表。 * }; * Laya.class(Item,"mypackage.listExample.Item",_super);//注册类 Item 。 * })(laya.ui.Box); * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * var res = ["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png"]; * Laya.loader.load(res, new laya.utils.Handler(this, onLoadComplete));//加载资源。 * function onLoadComplete() { * var arr = [];//创建一个数组,用于存贮列表的数据信息。 * for (var i = 0; i < 20; i++) { * arr.push({label: "item" + i}); * } * var list = new laya.ui.List();//创建一个 List 类的实例对象 list 。 * list.itemRender = mypackage.listExample.Item;//设置 list 的单元格渲染器。 * list.repeatX = 1;//设置 list 的水平方向单元格数量。 * list.repeatY = 10;//设置 list 的垂直方向单元格数量。 * list.vScrollBarSkin = "resource/ui/vscroll.png";//设置 list 的垂直方向滚动条皮肤。 * list.array = arr;//设置 list 的列表数据源。 * list.pos(100, 100);//设置 list 的位置。 * list.selectEnable = true;//设置 list 可选。 * list.selectHandler = new laya.utils.Handler(this, onSelect);//设置 list 改变选择项执行的处理器。 * Laya.stage.addChild(list);//将 list 添加到显示列表。 * } * function onSelect(index) * { * console.log("当前选择的项目索引: index= ", index); * } * * @example * import List = laya.ui.List; * import Handler = laya.utils.Handler; * public class List_Example { * public List_Example() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png"], Handler.create(this, this.onLoadComplete)); * } * private onLoadComplete(): void { * var arr= [];//创建一个数组,用于存贮列表的数据信息。 * for (var i: number = 0; i < 20; i++) * { * arr.push({ label: "item" + i }); * } * var list: List = new List();//创建一个 List 类的实例对象 list 。 * list.itemRender = Item;//设置 list 的单元格渲染器。 * list.repeatX = 1;//设置 list 的水平方向单元格数量。 * list.repeatY = 10;//设置 list 的垂直方向单元格数量。 * list.vScrollBarSkin = "resource/ui/vscroll.png";//设置 list 的垂直方向滚动条皮肤。 * list.array = arr;//设置 list 的列表数据源。 * list.pos(100, 100);//设置 list 的位置。 * list.selectEnable = true;//设置 list 可选。 * list.selectHandler = new Handler(this, this.onSelect);//设置 list 改变选择项执行的处理器。 * Laya.stage.addChild(list);//将 list 添加到显示列表。 * } * private onSelect(index: number): void { * console.log("当前选择的项目索引: index= ", index); * } * } * import Box = laya.ui.Box; * import Label = laya.ui.Label; * class Item extends Box { * constructor() { * this.graphics.drawRect(0, 0, 100, 20, null, "#ff0000"); * var label: Label = new Label(); * label.text = "100000"; * label.name = "label";//设置 label 的name属性值。 * label.size(100, 20); * this.addChild(label); * } * } */ class List extends Box implements IRender, IItem { /**改变 List 的选择项时执行的处理器,(默认返回参数: 项索引(index:number))。*/ selectHandler: Handler; /**单元格渲染处理器(默认返回参数cell:Box,index:number)。*/ renderHandler: Handler; /**单元格鼠标事件处理器(默认返回参数e:Event,index:number)。*/ mouseHandler: Handler; /**指定是否可以选择,若值为true则可以选择,否则不可以选择。 @default false*/ selectEnable: boolean; /**最大分页数。*/ totalPage: number; protected _content: Box; protected _scrollBar: ScrollBar; protected _itemRender: any; protected _repeatX: number; protected _repeatY: number; protected _repeatX2: number; protected _repeatY2: number; protected _spaceX: number; protected _spaceY: number; protected _cells: Array; protected _array: Array; protected _startIndex: number; protected _selectedIndex: number; protected _page: number; protected _isVertical: boolean; protected _cellSize: number; protected _cellOffset: number; protected _isMoved: boolean; /**是否缓存内容,如果数据源较少,并且list内无动画,设置此属性为true能大大提高性能 */ cacheContent: boolean; protected _createdLine: number; protected _cellChanged: boolean; protected _offset: Point; /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected createChildren(): void; /**@inheritDoc */ cacheAs: string; /** * 获取对 List 组件所包含的内容容器 Box 组件的引用。 */ readonly content: Box; /** * 垂直方向滚动条皮肤。 */ vScrollBarSkin: string; /** * 水平方向滚动条皮肤。 */ hScrollBarSkin: string; /** * 获取对 List 组件所包含的滚动条 ScrollBar 组件的引用。 */ scrollBar: ScrollBar; /** * 单元格渲染器。 *

    取值: *

      *
    1. 单元格类对象。
    2. *
    3. UI 的 JSON 描述。
    4. *

    */ itemRender: any; /**@inheritDoc */ width: number; /**@inheritDoc */ height: number; /** * 水平方向显示的单元格数量。 */ repeatX: number; /** * 垂直方向显示的单元格数量。 */ repeatY: number; /** * 水平方向显示的单元格之间的间距(以像素为单位)。 */ spaceX: number; /** * 垂直方向显示的单元格之间的间距(以像素为单位)。 */ spaceY: number; protected changeCells(): void; protected createItem(): Box; protected addCell(cell: Box): void; /** * 初始化单元格信息。 */ initItems(): void; /** * 设置可视区域大小。 *

    以(0,0,width参数,height参数)组成的矩形区域为可视区域。

    * @param width 可视区域宽度。 * @param height 可视区域高度。 */ setContentSize(width: number, height: number): void; protected onCellMouse(e: Event): void; protected changeCellState(cell: Box, visable: boolean, index: number): void; protected changeSize(): void; protected onScrollBarChange(e?: Event): void; /** * 表示当前选择的项索引。selectedIndex值更改会引起list重新渲染 */ selectedIndex: number; protected changeSelectStatus(): void; /** * 当前选中的单元格数据源。 */ selectedItem: any; /** * 获取或设置当前选择的单元格对象。 */ selection: Box; /** * 当前显示的单元格列表的开始索引。 */ startIndex: number; protected renderItems(from?: number, to?: number): void; protected renderItem(cell: any, index: number): void; /** * 列表数据源。 */ array: Array; /** * 列表的当前页码。 */ page: number; /** * 列表的数据总个数。 */ readonly length: number; /**@inheritDoc */ dataSource: any; /** * 单元格集合。 */ readonly cells: Array; /** * 刷新列表数据源。 */ refresh(): void; /** * 获取单元格数据源。 * @param index 单元格索引。 */ getItem(index: number): any; /** * 修改单元格数据源。 * @param index 单元格索引。 * @param source 单元格数据源。 */ changeItem(index: number, source: any): void; /** * 设置单元格数据源。 * @param index 单元格索引。 * @param source 单元格数据源。 */ setItem(index: number, source: any): void; /** * 添加单元格数据源。 * @param souce 数据源。 */ addItem(souce: any): void; /** * 添加单元格数据源到对应的数据索引处。 * @param souce 单元格数据源。 * @param index 索引。 */ addItemAt(souce: any, index: number): void; /** * 通过数据源索引删除单元格数据源。 * @param index 需要删除的数据源索引值。 */ deleteItem(index: number): void; /** * 通过可视单元格索引,获取单元格。 * @param index 可视单元格索引。 * @return 单元格对象。 */ getCell(index: number): Box; /** *

    滚动列表,以设定的数据索引对应的单元格为当前可视列表的第一项。

    * @param index 单元格在数据列表中的索引。 */ scrollTo(index: number): void; /** *

    缓动滚动列表,以设定的数据索引对应的单元格为当前可视列表的第一项。

    * @param index 单元格在数据列表中的索引。 * @param time 缓动时间。 * @param complete 缓动结束回掉 */ tweenTo(index: number, time?: number, complete?: Handler): void; protected _setCellChanged(): void; protected commitMeasure(): void; } } declare module laya.ui { import Node = laya.display.Node; import Sprite = laya.display.Sprite; /** * Panel 是一个面板容器类。 */ class Panel extends Box { protected _content: Box; protected _vScrollBar: VScrollBar; protected _hScrollBar: HScrollBar; protected _scrollChanged: boolean; /** * 创建一个新的 Panel 类实例。 *

    Panel 构造函数中设置属性width、height的值都为100。

    */ constructor(); /**@inheritDoc */ destroy(destroyChild?: boolean): void; /**@inheritDoc */ destroyChildren(): void; protected createChildren(): void; /**@inheritDoc */ addChild(child: Node): Node; /**@inheritDoc */ addChildAt(child: Node, index: number): Node; /**@inheritDoc */ removeChild(child: Node): Node; /**@inheritDoc */ removeChildAt(index: number): Node; /**@inheritDoc */ removeChildren(beginIndex?: number, endIndex?: number): Node; /**@inheritDoc */ getChildAt(index: number): Node; /**@inheritDoc */ getChildByName(name: string): Node; /**@inheritDoc */ getChildIndex(child: Node): number; /**@inheritDoc */ readonly numChildren: number; protected changeSize(): void; /** * @private * 获取内容宽度(以像素为单位)。 */ readonly contentWidth: number; /** * @private * 获取内容高度(以像素为单位)。 */ readonly contentHeight: number; /** * @inheritDoc */ width: number; /**@inheritDoc */ height: number; /** * 垂直方向滚动条皮肤。 */ vScrollBarSkin: string; /** * 水平方向滚动条皮肤。 */ hScrollBarSkin: string; /** * 垂直方向滚动条对象。 */ readonly vScrollBar: ScrollBar; /** * 水平方向滚动条对象。 */ readonly hScrollBar: ScrollBar; /** * 获取内容容器对象。 */ readonly content: Sprite; protected onScrollBarChange(scrollBar: ScrollBar): void; /** *

    滚动内容容器至设定的垂直、水平方向滚动条位置。

    * @param x 水平方向滚动条属性value值。滚动条位置数字。 * @param y 垂直方向滚动条属性value值。滚动条位置数字。 */ scrollTo(x?: number, y?: number): void; /** * 刷新滚动内容。 */ refresh(): void; /**@inheritDoc */ cacheAs: string; protected _setScrollChanged(): void; } } declare module laya.ui { import Component = laya.ui.Component; import Image = laya.ui.Image; import Handler = laya.utils.Handler; /** * ProgressBar 组件显示内容的加载进度。 * @example 以下示例代码,创建了一个新的 ProgressBar 实例,设置了它的皮肤、位置、宽高、网格等信息,并添加到舞台上。 * package * { * import laya.ui.ProgressBar; * import laya.utils.Handler; * public class ProgressBar_Example * { * private var progressBar:ProgressBar; * public function ProgressBar_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/progress.png", "resource/ui/progress$bar.png"], Handler.create(this, onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * progressBar = new ProgressBar("resource/ui/progress.png");//创建一个 ProgressBar 类的实例对象 progressBar 。 * progressBar.x = 100;//设置 progressBar 对象的属性 x 的值,用于控制 progressBar 对象的显示位置。 * progressBar.y = 100;//设置 progressBar 对象的属性 y 的值,用于控制 progressBar 对象的显示位置。 * progressBar.value = 0.3;//设置 progressBar 的进度值。 * progressBar.width = 200;//设置 progressBar 的宽度。 * progressBar.height = 50;//设置 progressBar 的高度。 * progressBar.sizeGrid = "5,10,5,10";//设置 progressBar 的网格信息。 * progressBar.changeHandler = new Handler(this, onChange);//设置 progressBar 的value值改变时执行的处理器。 * Laya.stage.addChild(progressBar);//将 progressBar 添加到显示列表。 * Laya.timer.once(3000, this, changeValue);//设定 3000ms(毫秒)后,执行函数changeValue。 * } * private function changeValue():void * { * trace("改变进度条的进度值。"); * progressBar.value = 0.6; * } * private function onChange(value:Number):void * { * trace("进度发生改变: value=" ,value); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * var res = ["resource/ui/progress.png", "resource/ui/progress$bar.png"]; * Laya.loader.load(res, laya.utils.Handler.create(this, onLoadComplete));//加载资源。 * function onLoadComplete() * { * progressBar = new laya.ui.ProgressBar("resource/ui/progress.png");//创建一个 ProgressBar 类的实例对象 progressBar 。 * progressBar.x = 100;//设置 progressBar 对象的属性 x 的值,用于控制 progressBar 对象的显示位置。 * progressBar.y = 100;//设置 progressBar 对象的属性 y 的值,用于控制 progressBar 对象的显示位置。 * progressBar.value = 0.3;//设置 progressBar 的进度值。 * progressBar.width = 200;//设置 progressBar 的宽度。 * progressBar.height = 50;//设置 progressBar 的高度。 * progressBar.sizeGrid = "10,5,10,5";//设置 progressBar 的网格信息。 * progressBar.changeHandler = new laya.utils.Handler(this, onChange);//设置 progressBar 的value值改变时执行的处理器。 * Laya.stage.addChild(progressBar);//将 progressBar 添加到显示列表。 * Laya.timer.once(3000, this, changeValue);//设定 3000ms(毫秒)后,执行函数changeValue。 * } * function changeValue() * { * console.log("改变进度条的进度值。"); * progressBar.value = 0.6; * } * function onChange(value) * { * console.log("进度发生改变: value=" ,value); * } * @example * import ProgressBar = laya.ui.ProgressBar; * import Handler = laya.utils.Handler; * class ProgressBar_Example { * private progressBar: ProgressBar; * public ProgressBar_Example() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/progress.png", "resource/ui/progress$bar.png"], Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * this.progressBar = new ProgressBar("resource/ui/progress.png");//创建一个 ProgressBar 类的实例对象 progressBar 。 * this.progressBar.x = 100;//设置 progressBar 对象的属性 x 的值,用于控制 progressBar 对象的显示位置。 * this.progressBar.y = 100;//设置 progressBar 对象的属性 y 的值,用于控制 progressBar 对象的显示位置。 * this.progressBar.value = 0.3;//设置 progressBar 的进度值。 * this.progressBar.width = 200;//设置 progressBar 的宽度。 * this.progressBar.height = 50;//设置 progressBar 的高度。 * this.progressBar.sizeGrid = "5,10,5,10";//设置 progressBar 的网格信息。 * this.progressBar.changeHandler = new Handler(this, this.onChange);//设置 progressBar 的value值改变时执行的处理器。 * Laya.stage.addChild(this.progressBar);//将 progressBar 添加到显示列表。 * Laya.timer.once(3000, this, this.changeValue);//设定 3000ms(毫秒)后,执行函数changeValue。 * } * private changeValue(): void { * console.log("改变进度条的进度值。"); * this.progressBar.value = 0.6; * } * private onChange(value: number): void { * console.log("进度发生改变: value=", value); * } * } */ class ProgressBar extends Component { /** * 当 ProgressBar 实例的 value 属性发生变化时的函数处理器。 *

    默认返回参数value 属性(进度值)。

    */ changeHandler: Handler; protected _bg: Image; protected _bar: Image; protected _skin: string; protected _value: number; /** * 创建一个新的 ProgressBar 类实例。 * @param skin 皮肤地址。 */ constructor(skin?: string); /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected createChildren(): void; /** * @copy laya.ui.Image#skin */ skin: string; protected readonly measureWidth: number; protected readonly measureHeight: number; /** * 当前的进度量。 *

    取值:介于0和1之间。

    */ value: number; protected changeValue(): void; /** * 获取进度条对象。 */ readonly bar: Image; /** * 获取背景条对象。 */ readonly bg: Image; /** *

    当前 ProgressBar 实例的进度条背景位图( Image 实例)的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    * @see laya.ui.AutoBitmap.sizeGrid */ sizeGrid: string; /**@inheritDoc */ width: number; /**@inheritDoc */ height: number; /**@inheritDoc */ dataSource: any; } } declare module laya.ui { import Event = laya.events.Event; import Button = laya.ui.Button; /** * Radio 控件使用户可在一组互相排斥的选择中做出一种选择。 * 用户一次只能选择 Radio 组中的一个成员。选择未选中的组成员将取消选择该组中当前所选的 Radio 控件。 * @see laya.ui.RadioGroup */ class Radio extends Button { protected _value: any; /** * 创建一个新的 Radio 类实例。 * @param skin 皮肤。 * @param label 标签。 */ constructor(skin?: string, label?: string); /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected preinitialize(): void; protected initialize(): void; protected onClick(e: Event): void; /** * 获取或设置 Radio 关联的可选用户定义值。 */ value: any; } } declare module laya.ui { import Sprite = laya.display.Sprite; /** * RadioGroup 控件定义一组 Radio 控件,这些控件相互排斥; * 因此,用户每次只能选择一个 Radio 控件。 * * @example 以下示例代码,创建了一个 RadioGroup 实例。 * package * { * import laya.ui.Radio; * import laya.ui.RadioGroup; * import laya.utils.Handler; * public class RadioGroup_Example * { * public function RadioGroup_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/radio.png"], Handler.create(this, onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * var radioGroup:RadioGroup = new RadioGroup();//创建一个 RadioGroup 类的实例对象 radioGroup 。 * radioGroup.pos(100, 100);//设置 radioGroup 的位置信息。 * radioGroup.labels = "item0,item1,item2";//设置 radioGroup 的标签集。 * radioGroup.skin = "resource/ui/radio.png";//设置 radioGroup 的皮肤。 * radioGroup.space = 10;//设置 radioGroup 的项间隔距离。 * radioGroup.selectHandler = new Handler(this, onSelect);//设置 radioGroup 的选择项发生改变时执行的处理器。 * Laya.stage.addChild(radioGroup);//将 radioGroup 添加到显示列表。 * } * private function onSelect(index:int):void * { * trace("当前选择的单选按钮索引: index= ", index); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高、渲染模式 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * Laya.loader.load(["resource/ui/radio.png"], laya.utils.Handler.create(this, onLoadComplete)); * function onLoadComplete() { * var radioGroup= new laya.ui.RadioGroup();//创建一个 RadioGroup 类的实例对象 radioGroup 。 * radioGroup.pos(100, 100);//设置 radioGroup 的位置信息。 * radioGroup.labels = "item0,item1,item2";//设置 radioGroup 的标签集。 * radioGroup.skin = "resource/ui/radio.png";//设置 radioGroup 的皮肤。 * radioGroup.space = 10;//设置 radioGroup 的项间隔距离。 * radioGroup.selectHandler = new laya.utils.Handler(this, onSelect);//设置 radioGroup 的选择项发生改变时执行的处理器。 * Laya.stage.addChild(radioGroup);//将 radioGroup 添加到显示列表。 * } * function onSelect(index) { * console.log("当前选择的单选按钮索引: index= ", index); * } * @example * import Radio = laya.ui.Radio; * import RadioGroup = laya.ui.RadioGroup; * import Handler = laya.utils.Handler; * class RadioGroup_Example { * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/radio.png"], Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * var radioGroup: RadioGroup = new RadioGroup();//创建一个 RadioGroup 类的实例对象 radioGroup 。 * radioGroup.pos(100, 100);//设置 radioGroup 的位置信息。 * radioGroup.labels = "item0,item1,item2";//设置 radioGroup 的标签集。 * radioGroup.skin = "resource/ui/radio.png";//设置 radioGroup 的皮肤。 * radioGroup.space = 10;//设置 radioGroup 的项间隔距离。 * radioGroup.selectHandler = new Handler(this, this.onSelect);//设置 radioGroup 的选择项发生改变时执行的处理器。 * Laya.stage.addChild(radioGroup);//将 radioGroup 添加到显示列表。 * } * private onSelect(index: number): void { * console.log("当前选择的单选按钮索引: index= ", index); * } * } */ class RadioGroup extends UIGroup { protected createItem(skin: string, label: string): Sprite; } } declare module laya.ui { import Sprite = laya.display.Sprite; import Event = laya.events.Event; import Point = laya.maths.Point; import Handler = laya.utils.Handler; /** * ScrollBar 组件是一个滚动条组件。 *

    当数据太多以至于显示区域无法容纳时,最终用户可以使用 ScrollBar 组件控制所显示的数据部分。

    *

    滚动条由四部分组成:两个箭头按钮、一个轨道和一个滑块。

    * * * @see laya.ui.VScrollBar * @see laya.ui.HScrollBar */ class ScrollBar extends Component { /**滚动衰减系数*/ rollRatio: number; /**滚动变化时回调,回传value参数。*/ changeHandler: Handler; /**是否缩放滑动条,默认值为true。 */ scaleBar: boolean; /**一个布尔值,指定是否自动隐藏滚动条(无需滚动时),默认值为false。*/ autoHide: boolean; /**橡皮筋效果极限距离,0为没有橡皮筋效果。*/ elasticDistance: number; /**橡皮筋回弹时间,单位为毫秒。*/ elasticBackTime: number; /**上按钮 */ upButton: Button; /**下按钮 */ downButton: Button; /**滑条 */ slider: Slider; protected _showButtons: boolean; protected _scrollSize: number; protected _skin: string; protected _thumbPercent: number; protected _target: Sprite; protected _lastPoint: Point; protected _lastOffset: number; protected _checkElastic: boolean; protected _isElastic: boolean; protected _value: number; protected _hide: boolean; protected _clickOnly: boolean; protected _offsets: Array; protected _touchScrollEnable: boolean; protected _mouseWheelEnable: boolean; /** * 创建一个新的 ScrollBar 实例。 * @param skin 皮肤资源地址。 */ constructor(skin?: string); /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected createChildren(): void; protected initialize(): void; protected onSliderChange(): void; protected onButtonMouseDown(e: Event): void; protected startLoop(isUp: boolean): void; protected slide(isUp: boolean): void; protected onStageMouseUp(e: Event): void; /** * @copy laya.ui.Image#skin */ skin: string; protected changeScrollBar(): void; protected changeSize(): void; protected resetButtonPosition(): void; protected readonly measureWidth: number; protected readonly measureHeight: number; /** * 设置滚动条信息。 * @param min 滚动条最小位置值。 * @param max 滚动条最大位置值。 * @param value 滚动条当前位置值。 */ setScroll(min: number, max: number, value: number): void; /** * 获取或设置表示最高滚动位置的数字。 */ max: number; /** * 获取或设置表示最低滚动位置的数字。 */ min: number; /** * 获取或设置表示当前滚动位置的数字。 */ value: number; /** * 一个布尔值,指示滚动条是否为垂直滚动。如果值为true,则为垂直滚动,否则为水平滚动。 *

    默认值为:true。

    */ isVertical: boolean; /** *

    当前实例的 Slider 实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    * @see laya.ui.AutoBitmap.sizeGrid */ sizeGrid: string; /**获取或设置一个值,该值表示按下滚动条轨道时页面滚动的增量。 */ scrollSize: number; /**@inheritDoc */ dataSource: any; /**获取或设置一个值,该值表示滑条长度比例,值为:(0-1)。 */ thumbPercent: number; /** * 设置滚动对象。 * @see laya.ui.TouchScroll#target */ target: Sprite; /**是否隐藏滚动条,不显示滚动条,但是可以正常滚动,默认为false。*/ hide: boolean; /**一个布尔值,指定是否显示向上、向下按钮,默认值为true。*/ showButtons: boolean; /**一个布尔值,指定是否开启触摸,默认值为true。*/ touchScrollEnable: boolean; /** 一个布尔值,指定是否滑轮滚动,默认值为true。*/ mouseWheelEnable: boolean; protected onTargetMouseWheel(e: Event): void; protected onTargetMouseDown(e: Event): void; protected loop(): void; protected onStageMouseUp2(e: Event): void; protected tweenMove(maxDistance: number): void; /** * 停止滑动。 */ stopScroll(): void; /** * 滚动的刻度值,滑动数值为tick的整数倍。默认值为1。 */ tick: number; } } declare module laya.ui { import Event = laya.events.Event; import Point = laya.maths.Point; import Handler = laya.utils.Handler; /** * 使用 Slider 控件,用户可以通过在滑块轨道的终点之间移动滑块来选择值。 *

    滑块的当前值由滑块端点(对应于滑块的最小值和最大值)之间滑块的相对位置确定。

    *

    滑块允许最小值和最大值之间特定间隔内的值。滑块还可以使用数据提示显示其当前值。

    * * @see laya.ui.HSlider * @see laya.ui.VSlider */ class Slider extends Component { static label: Label; /** * 数据变化处理器。 *

    默认回调参数为滑块位置属性 value属性值:Number 。

    */ changeHandler: Handler; /** * 一个布尔值,指示是否为垂直滚动。如果值为true,则为垂直方向,否则为水平方向。 *

    默认值为:true。

    * @default true */ isVertical: boolean; /** * 一个布尔值,指示是否显示标签。 * @default true */ showLabel: boolean; protected _allowClickBack: boolean; protected _max: number; protected _min: number; protected _tick: number; protected _skin: string; protected _bg: Image; protected _progress: Image; protected _bar: Button; protected _tx: number; protected _ty: number; protected _maxMove: number; protected _globalSacle: Point; /** * 创建一个新的 Slider 类示例。 * @param skin 皮肤。 */ constructor(skin?: string); /** *@inheritDoc */ destroy(destroyChild?: boolean): void; protected createChildren(): void; protected initialize(): void; protected onBarMouseDown(e: Event): void; protected showValueText(): void; protected hideValueText(): void; protected sendChangeEvent(type?: string): void; /** * @copy laya.ui.Image#skin */ skin: string; protected setBarPoint(): void; protected readonly measureWidth: number; protected readonly measureHeight: number; protected changeSize(): void; /** *

    当前实例的背景图( Image )和滑块按钮( Button )实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    * @see laya.ui.AutoBitmap.sizeGrid */ sizeGrid: string; /** * 设置滑动条的信息。 * @param min 滑块的最小值。 * @param max 滑块的最小值。 * @param value 滑块的当前值。 */ setSlider(min: number, max: number, value: number): void; /** * 滑动的刻度值,滑动数值为tick的整数倍。默认值为1。 */ tick: number; /** * @private * 改变滑块的位置值。 */ changeValue(): void; /** * 获取或设置表示最高位置的数字。 默认值为100。 */ max: number; /** * 获取或设置表示最低位置的数字。 默认值为0。 */ min: number; /** * 获取或设置表示当前滑块位置的数字。 */ value: number; /** * 一个布尔值,指定是否允许通过点击滑动条改变 Slidervalue 属性值。 */ allowClickBack: boolean; protected onBgMouseDown(e: Event): void; /**@inheritDoc */ dataSource: any; /** * 表示滑块按钮的引用。 */ readonly bar: Button; } } declare module laya.ui { /** * Styles 定义了组件常用的样式属性。 */ class Styles { /** * 默认九宫格信息。 * @see laya.ui.AutoBitmap#sizeGrid */ static defaultSizeGrid: Array; /** * 标签颜色。 */ static labelColor: string; /** * 标签的边距。 *

    格式:[上边距,右边距,下边距,左边距]。

    */ static labelPadding: Array; /** * 标签的边距。 *

    格式:[上边距,右边距,下边距,左边距]。

    */ static inputLabelPadding: Array; /** * 按钮皮肤的状态数,支持1,2,3三种状态值。 */ static buttonStateNum: number; /** * 按钮标签颜色。 *

    格式:[upColor,overColor,downColor,disableColor]。

    */ static buttonLabelColors: Array; /** * 下拉框项颜色。 *

    格式:[overBgColor,overLabelColor,outLabelColor,borderColor,bgColor]。

    */ static comboBoxItemColors: Array; /** * 滚动条的最小值。 */ static scrollBarMinNum: number; /** * 长按按钮,等待时间,使其可激活连续滚动。 */ static scrollBarDelayTime: number; } } declare module laya.ui { import Sprite = laya.display.Sprite; import UIGroup = laya.ui.UIGroup; /** * Tab 组件用来定义选项卡按钮组。 * * @internal

    属性:selectedIndex 的默认值为-1。

    * * @example 以下示例代码,创建了一个 Tab 实例。 * package * { * import laya.ui.Tab; * import laya.utils.Handler; * public class Tab_Example * { * public function Tab_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/tab.png"], Handler.create(this, onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * var tab:Tab = new Tab();//创建一个 Tab 类的实例对象 tab 。 * tab.skin = "resource/ui/tab.png";//设置 tab 的皮肤。 * tab.labels = "item0,item1,item2";//设置 tab 的标签集。 * tab.x = 100;//设置 tab 对象的属性 x 的值,用于控制 tab 对象的显示位置。 * tab.y = 100;//设置 tab 对象的属性 y 的值,用于控制 tab 对象的显示位置。 * tab.selectHandler = new Handler(this, onSelect);//设置 tab 的选择项发生改变时执行的处理器。 * Laya.stage.addChild(tab);//将 tab 添到显示列表。 * } * private function onSelect(index:int):void * { * trace("当前选择的表情页索引: index= ", index); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * Laya.loader.load(["resource/ui/tab.png"], laya.utils.Handler.create(this, onLoadComplete)); * function onLoadComplete() { * var tab = new laya.ui.Tab();//创建一个 Tab 类的实例对象 tab 。 * tab.skin = "resource/ui/tab.png";//设置 tab 的皮肤。 * tab.labels = "item0,item1,item2";//设置 tab 的标签集。 * tab.x = 100;//设置 tab 对象的属性 x 的值,用于控制 tab 对象的显示位置。 * tab.y = 100;//设置 tab 对象的属性 y 的值,用于控制 tab 对象的显示位置。 * tab.selectHandler = new laya.utils.Handler(this, onSelect);//设置 tab 的选择项发生改变时执行的处理器。 * Laya.stage.addChild(tab);//将 tab 添到显示列表。 * } * function onSelect(index) { * console.log("当前选择的标签页索引: index= ", index); * } * @example * import Tab = laya.ui.Tab; * import Handler = laya.utils.Handler; * class Tab_Example { * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/tab.png"], Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * var tab: Tab = new Tab();//创建一个 Tab 类的实例对象 tab 。 * tab.skin = "resource/ui/tab.png";//设置 tab 的皮肤。 * tab.labels = "item0,item1,item2";//设置 tab 的标签集。 * tab.x = 100;//设置 tab 对象的属性 x 的值,用于控制 tab 对象的显示位置。 * tab.y = 100;//设置 tab 对象的属性 y 的值,用于控制 tab 对象的显示位置。 * tab.selectHandler = new Handler(this, this.onSelect);//设置 tab 的选择项发生改变时执行的处理器。 * Laya.stage.addChild(tab);//将 tab 添到显示列表。 * } * private onSelect(index: number): void { * console.log("当前选择的表情页索引: index= ", index); * } * } */ class Tab extends UIGroup { protected createItem(skin: string, label: string): Sprite; } } declare module laya.ui { import Event = laya.events.Event; /** * TextArea 类用于创建显示对象以显示和输入文本。 * @example 以下示例代码,创建了一个 TextArea 实例。 * package * { * import laya.ui.TextArea; * import laya.utils.Handler; * public class TextArea_Example * { * public function TextArea_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/input.png"], Handler.create(this, onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * var textArea:TextArea = new TextArea("这个一个TextArea实例。");//创建一个 TextArea 类的实例对象 textArea 。 * textArea.skin = "resource/ui/input.png";//设置 textArea 的皮肤。 * textArea.sizeGrid = "4,4,4,4";//设置 textArea 的网格信息。 * textArea.color = "#008fff";//设置 textArea 的文本颜色。 * textArea.font = "Arial";//设置 textArea 的字体。 * textArea.bold = true;//设置 textArea 的文本显示为粗体。 * textArea.fontSize = 20;//设置 textArea 的文本字体大小。 * textArea.wordWrap = true;//设置 textArea 的文本自动换行。 * textArea.x = 100;//设置 textArea 对象的属性 x 的值,用于控制 textArea 对象的显示位置。 * textArea.y = 100;//设置 textArea 对象的属性 y 的值,用于控制 textArea 对象的显示位置。 * textArea.width = 300;//设置 textArea 的宽度。 * textArea.height = 200;//设置 textArea 的高度。 * Laya.stage.addChild(textArea);//将 textArea 添加到显示列表。 * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高、渲染模式 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * Laya.loader.load(["resource/ui/input.png"], laya.utils.Handler.create(this, onLoadComplete));//加载资源。 * function onLoadComplete() { * var textArea = new laya.ui.TextArea("这个一个TextArea实例。");//创建一个 TextArea 类的实例对象 textArea 。 * textArea.skin = "resource/ui/input.png";//设置 textArea 的皮肤。 * textArea.sizeGrid = "4,4,4,4";//设置 textArea 的网格信息。 * textArea.color = "#008fff";//设置 textArea 的文本颜色。 * textArea.font = "Arial";//设置 textArea 的字体。 * textArea.bold = true;//设置 textArea 的文本显示为粗体。 * textArea.fontSize = 20;//设置 textArea 的文本字体大小。 * textArea.wordWrap = true;//设置 textArea 的文本自动换行。 * textArea.x = 100;//设置 textArea 对象的属性 x 的值,用于控制 textArea 对象的显示位置。 * textArea.y = 100;//设置 textArea 对象的属性 y 的值,用于控制 textArea 对象的显示位置。 * textArea.width = 300;//设置 textArea 的宽度。 * textArea.height = 200;//设置 textArea 的高度。 * Laya.stage.addChild(textArea);//将 textArea 添加到显示列表。 * } * @example * import TextArea = laya.ui.TextArea; * import Handler = laya.utils.Handler; * class TextArea_Example { * constructor() { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/input.png"], Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * var textArea: TextArea = new TextArea("这个一个TextArea实例。");//创建一个 TextArea 类的实例对象 textArea 。 * textArea.skin = "resource/ui/input.png";//设置 textArea 的皮肤。 * textArea.sizeGrid = "4,4,4,4";//设置 textArea 的网格信息。 * textArea.color = "#008fff";//设置 textArea 的文本颜色。 * textArea.font = "Arial";//设置 textArea 的字体。 * textArea.bold = true;//设置 textArea 的文本显示为粗体。 * textArea.fontSize = 20;//设置 textArea 的文本字体大小。 * textArea.wordWrap = true;//设置 textArea 的文本自动换行。 * textArea.x = 100;//设置 textArea 对象的属性 x 的值,用于控制 textArea 对象的显示位置。 * textArea.y = 100;//设置 textArea 对象的属性 y 的值,用于控制 textArea 对象的显示位置。 * textArea.width = 300;//设置 textArea 的宽度。 * textArea.height = 200;//设置 textArea 的高度。 * Laya.stage.addChild(textArea);//将 textArea 添加到显示列表。 * } * } */ class TextArea extends TextInput { protected _vScrollBar: VScrollBar; protected _hScrollBar: HScrollBar; /** *

    创建一个新的 TextArea 示例。

    * @param text 文本内容字符串。 */ constructor(text?: string); destroy(destroyChild?: boolean): void; protected initialize(): void; width: number; height: number; /**垂直滚动条皮肤*/ vScrollBarSkin: string; /**水平滚动条皮肤*/ hScrollBarSkin: string; protected onVBarChanged(e: Event): void; protected onHBarChanged(e: Event): void; /**垂直滚动条实体*/ readonly vScrollBar: VScrollBar; /**水平滚动条实体*/ readonly hScrollBar: HScrollBar; /**垂直滚动最大值*/ readonly maxScrollY: number; /**垂直滚动值*/ readonly scrollY: number; /**水平滚动最大值*/ readonly maxScrollX: number; /**水平滚动值*/ readonly scrollX: number; /**滚动到某个位置*/ scrollTo(y: number): void; } } declare module laya.ui { import AutoBitmap = laya.ui.AutoBitmap; /** * TextInput 类用于创建显示对象以显示和输入文本。 * * @example 以下示例代码,创建了一个 TextInput 实例。 * package * { * import laya.display.Stage; * import laya.ui.TextInput; * import laya.utils.Handler; * public class TextInput_Example * { * public function TextInput_Example() * { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/input.png"], Handler.create(this, onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * var textInput:TextInput = new TextInput("这是一个TextInput实例。");//创建一个 TextInput 类的实例对象 textInput 。 * textInput.skin = "resource/ui/input.png";//设置 textInput 的皮肤。 * textInput.sizeGrid = "4,4,4,4";//设置 textInput 的网格信息。 * textInput.color = "#008fff";//设置 textInput 的文本颜色。 * textInput.font = "Arial";//设置 textInput 的文本字体。 * textInput.bold = true;//设置 textInput 的文本显示为粗体。 * textInput.fontSize = 30;//设置 textInput 的字体大小。 * textInput.wordWrap = true;//设置 textInput 的文本自动换行。 * textInput.x = 100;//设置 textInput 对象的属性 x 的值,用于控制 textInput 对象的显示位置。 * textInput.y = 100;//设置 textInput 对象的属性 y 的值,用于控制 textInput 对象的显示位置。 * textInput.width = 300;//设置 textInput 的宽度。 * textInput.height = 200;//设置 textInput 的高度。 * Laya.stage.addChild(textInput);//将 textInput 添加到显示列表。 * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * Laya.loader.load(["resource/ui/input.png"], laya.utils.Handler.create(this, onLoadComplete));//加载资源。 * function onLoadComplete() { * var textInput = new laya.ui.TextInput("这是一个TextInput实例。");//创建一个 TextInput 类的实例对象 textInput 。 * textInput.skin = "resource/ui/input.png";//设置 textInput 的皮肤。 * textInput.sizeGrid = "4,4,4,4";//设置 textInput 的网格信息。 * textInput.color = "#008fff";//设置 textInput 的文本颜色。 * textInput.font = "Arial";//设置 textInput 的文本字体。 * textInput.bold = true;//设置 textInput 的文本显示为粗体。 * textInput.fontSize = 30;//设置 textInput 的字体大小。 * textInput.wordWrap = true;//设置 textInput 的文本自动换行。 * textInput.x = 100;//设置 textInput 对象的属性 x 的值,用于控制 textInput 对象的显示位置。 * textInput.y = 100;//设置 textInput 对象的属性 y 的值,用于控制 textInput 对象的显示位置。 * textInput.width = 300;//设置 textInput 的宽度。 * textInput.height = 200;//设置 textInput 的高度。 * Laya.stage.addChild(textInput);//将 textInput 添加到显示列表。 * } * @example * import Stage = laya.display.Stage; * import TextInput = laya.ui.TextInput; * import Handler = laya.utils.Handler; * class TextInput_Example { * constructor() { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/input.png"], Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * var textInput: TextInput = new TextInput("这是一个TextInput实例。");//创建一个 TextInput 类的实例对象 textInput 。 * textInput.skin = "resource/ui/input.png";//设置 textInput 的皮肤。 * textInput.sizeGrid = "4,4,4,4";//设置 textInput 的网格信息。 * textInput.color = "#008fff";//设置 textInput 的文本颜色。 * textInput.font = "Arial";//设置 textInput 的文本字体。 * textInput.bold = true;//设置 textInput 的文本显示为粗体。 * textInput.fontSize = 30;//设置 textInput 的字体大小。 * textInput.wordWrap = true;//设置 textInput 的文本自动换行。 * textInput.x = 100;//设置 textInput 对象的属性 x 的值,用于控制 textInput 对象的显示位置。 * textInput.y = 100;//设置 textInput 对象的属性 y 的值,用于控制 textInput 对象的显示位置。 * textInput.width = 300;//设置 textInput 的宽度。 * textInput.height = 200;//设置 textInput 的高度。 * Laya.stage.addChild(textInput);//将 textInput 添加到显示列表。 * } * } */ class TextInput extends Label { protected _bg: AutoBitmap; protected _skin: string; /** * 创建一个新的 TextInput 类实例。 * @param text 文本内容。 */ constructor(text?: string); protected preinitialize(): void; /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected createChildren(): void; protected initialize(): void; /** * 表示此对象包含的文本背景 AutoBitmap 组件实例。 */ bg: AutoBitmap; /** * @copy laya.ui.Image#skin */ skin: string; /** *

    当前实例的背景图( AutoBitmap )实例的有效缩放网格数据。

    *

    数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。 *

    • 例如:"4,4,4,4,1"

    * @see laya.ui.AutoBitmap.sizeGrid */ sizeGrid: string; /** * 当前文本内容字符串。 * @see laya.display.Text.text */ text: string; /**@inheritDoc */ width: number; /**@inheritDoc */ height: number; /** *

    指示当前是否是文本域。

    * 值为true表示当前是文本域,否则不是文本域。 */ multiline: boolean; /** * 设置可编辑状态。 */ editable: boolean; /** * 设置原生input输入框的x坐标偏移。 */ inputElementXAdjuster: number; /** * 设置原生input输入框的y坐标偏移。 */ inputElementYAdjuster: number; /**选中输入框内的文本。*/ select(): void; /**限制输入的字符。*/ restrict: string; /** * @copy laya.display.Input#prompt */ prompt: string; /** * @copy laya.display.Input#promptColor */ promptColor: string; /** * @copy laya.display.Input#maxChars */ maxChars: number; /** * @copy laya.display.Input#focus */ focus: boolean; /** * @copy laya.display.Input#type */ type: string; /** * @copy laya.display.Input#asPassword */ asPassword: boolean; setSelection(startIndex: number, endIndex: number): void; } } declare module laya.ui { import Sprite = laya.display.Sprite; import Component = laya.ui.Component; /**鼠标提示管理类*/ class TipManager extends Component { static offsetX: number; static offsetY: number; static tipTextColor: string; static tipBackColor: string; static tipDelay: number; constructor(); /**关闭所有鼠标提示*/ closeAll(): void; /** * 显示显示对象类型的tip */ showDislayTip(tip: Sprite): void; /**默认鼠标提示函数*/ defaultTipHandler: Function; } } declare module laya.ui { import Event = laya.events.Event; import Handler = laya.utils.Handler; /** * Tree 控件使用户可以查看排列为可扩展树的层次结构数据。 * * @example * package * { * import laya.ui.Tree; * import laya.utils.Browser; * import laya.utils.Handler; * public class Tree_Example * { * public function Tree_Example() * { * Laya.init(640, 800); * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png", "resource/ui/clip_selectBox.png", "resource/ui/clip_tree_folder.png", "resource/ui/clip_tree_arrow.png"], Handler.create(this, onLoadComplete)); * } * private function onLoadComplete():void * { * var xmlString:String;//创建一个xml字符串,用于存储树结构数据。 * xmlString = "<root><item label='box1'><abc label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/><abc label='child5'/></item><item label='box2'><abc label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/></item></root>"; * var domParser:* = new Browser.window.DOMParser();//创建一个DOMParser实例domParser。 * var xml:* = domParser.parseFromString(xmlString, "text/xml");//解析xml字符。 * var tree:Tree = new Tree();//创建一个 Tree 类的实例对象 tree 。 * tree.scrollBarSkin = "resource/ui/vscroll.png";//设置 tree 的皮肤。 * tree.itemRender = Item;//设置 tree 的项渲染器。 * tree.xml = xml;//设置 tree 的树结构数据。 * tree.x = 100;//设置 tree 对象的属性 x 的值,用于控制 tree 对象的显示位置。 * tree.y = 100;//设置 tree 对象的属性 y 的值,用于控制 tree 对象的显示位置。 * tree.width = 200;//设置 tree 的宽度。 * tree.height = 100;//设置 tree 的高度。 * Laya.stage.addChild(tree);//将 tree 添加到显示列表。 * } * } * } * import laya.ui.Box; * import laya.ui.Clip; * import laya.ui.Label; * class Item extends Box * { * public function Item() * { * this.name = "render"; * this.right = 0; * this.left = 0; * var selectBox:Clip = new Clip("resource/ui/clip_selectBox.png", 1, 2); * selectBox.name = "selectBox"; * selectBox.height = 24; * selectBox.x = 13; * selectBox.y = 0; * selectBox.left = 12; * addChild(selectBox); * var folder:Clip = new Clip("resource/ui/clip_tree_folder.png", 1, 3); * folder.name = "folder"; * folder.x = 14; * folder.y = 4; * addChild(folder); * var label:Label = new Label("treeItem"); * label.name = "label"; * label.color = "#ffff00"; * label.width = 150; * label.height = 22; * label.x = 33; * label.y = 1; * label.left = 33; * label.right = 0; * addChild(label); * var arrow:Clip = new Clip("resource/ui/clip_tree_arrow.png", 1, 2); * arrow.name = "arrow"; * arrow.x = 0; * arrow.y = 5; * addChild(arrow); * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高、渲染模式 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * var res = ["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png", "resource/ui/clip_selectBox.png", "resource/ui/clip_tree_folder.png", "resource/ui/clip_tree_arrow.png"]; * Laya.loader.load(res, new laya.utils.Handler(this, onLoadComplete)); * function onLoadComplete() { * var xmlString;//创建一个xml字符串,用于存储树结构数据。 * xmlString = "<root><item label='box1'><abc label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/><abc label='child5'/></item><item label='box2'><abc label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/></item></root>"; * var domParser = new laya.utils.Browser.window.DOMParser();//创建一个DOMParser实例domParser。 * var xml = domParser.parseFromString(xmlString, "text/xml");//解析xml字符。 * var tree = new laya.ui.Tree();//创建一个 Tree 类的实例对象 tree 。 * tree.scrollBarSkin = "resource/ui/vscroll.png";//设置 tree 的皮肤。 * tree.itemRender = mypackage.treeExample.Item;//设置 tree 的项渲染器。 * tree.xml = xml;//设置 tree 的树结构数据。 * tree.x = 100;//设置 tree 对象的属性 x 的值,用于控制 tree 对象的显示位置。 * tree.y = 100;//设置 tree 对象的属性 y 的值,用于控制 tree 对象的显示位置。 * tree.width = 200;//设置 tree 的宽度。 * tree.height = 100;//设置 tree 的高度。 * Laya.stage.addChild(tree);//将 tree 添加到显示列表。 * } * (function (_super) { * function Item() { * Item.__super.call(this);//初始化父类。 * this.right = 0; * this.left = 0; * var selectBox = new laya.ui.Clip("resource/ui/clip_selectBox.png", 1, 2); * selectBox.name = "selectBox";//设置 selectBox 的name 为“selectBox”时,将被识别为树结构的项的背景。2帧:悬停时背景、选中时背景。 * selectBox.height = 24; * selectBox.x = 13; * selectBox.y = 0; * selectBox.left = 12; * this.addChild(selectBox);//需要使用this.访问父类的属性或方法。 * var folder = new laya.ui.Clip("resource/ui/clip_tree_folder.png", 1, 3); * folder.name = "folder";//设置 folder 的name 为“folder”时,将被识别为树结构的文件夹开启状态图表。2帧:折叠状态、打开状态。 * folder.x = 14; * folder.y = 4; * this.addChild(folder); * var label = new laya.ui.Label("treeItem"); * label.name = "label";//设置 label 的name 为“label”时,此值将用于树结构数据赋值。 * label.color = "#ffff00"; * label.width = 150; * label.height = 22; * label.x = 33; * label.y = 1; * label.left = 33; * label.right = 0; * this.addChild(label); * var arrow = new laya.ui.Clip("resource/ui/clip_tree_arrow.png", 1, 2); * arrow.name = "arrow";//设置 arrow 的name 为“arrow”时,将被识别为树结构的文件夹开启状态图表。2帧:折叠状态、打开状态。 * arrow.x = 0; * arrow.y = 5; * this.addChild(arrow); * }; * Laya.class(Item,"mypackage.treeExample.Item",_super);//注册类 Item 。 * })(laya.ui.Box); * @example * import Tree = laya.ui.Tree; * import Browser = laya.utils.Browser; * import Handler = laya.utils.Handler; * class Tree_Example { * constructor() { * Laya.init(640, 800); * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png", "resource/ui/vscroll$up.png", "resource/ui/clip_selectBox.png", "resource/ui/clip_tree_folder * . * png", "resource/ui/clip_tree_arrow.png"], Handler.create(this, this.onLoadComplete)); * } * private onLoadComplete(): void { * var xmlString: String;//创建一个xml字符串,用于存储树结构数据。 * xmlString = "<root><item label='box1'><abc label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/><abc label='child5'/></item><item label='box2'><abc * label='child1'/><abc label='child2'/><abc label='child3'/><abc label='child4'/></item></root>"; * var domParser: any = new Browser.window.DOMParser();//创建一个DOMParser实例domParser。 * var xml: any = domParser.parseFromString(xmlString, "text/xml");//解析xml字符。 * var tree: Tree = new Tree();//创建一个 Tree 类的实例对象 tree 。 * tree.scrollBarSkin = "resource/ui/vscroll.png";//设置 tree 的皮肤。 * tree.itemRender = Item;//设置 tree 的项渲染器。 * tree.xml = xml;//设置 tree 的树结构数据。 * tree.x = 100;//设置 tree 对象的属性 x 的值,用于控制 tree 对象的显示位置。 * tree.y = 100;//设置 tree 对象的属性 y 的值,用于控制 tree 对象的显示位置。 * tree.width = 200;//设置 tree 的宽度。 * tree.height = 100;//设置 tree 的高度。 * Laya.stage.addChild(tree);//将 tree 添加到显示列表。 * } * } * import Box = laya.ui.Box; * import Clip = laya.ui.Clip; * import Label = laya.ui.Label; * class Item extends Box { * constructor() { * super(); * this.name = "render"; * this.right = 0; * this.left = 0; * var selectBox: Clip = new Clip("resource/ui/clip_selectBox.png", 1, 2); * selectBox.name = "selectBox"; * selectBox.height = 24; * selectBox.x = 13; * selectBox.y = 0; * selectBox.left = 12; * this.addChild(selectBox); * var folder: Clip = new Clip("resource/ui/clip_tree_folder.png", 1, 3); * folder.name = "folder"; * folder.x = 14; * folder.y = 4; * this.addChild(folder); * var label: Label = new Label("treeItem"); * label.name = "label"; * label.color = "#ffff00"; * label.width = 150; * label.height = 22; * label.x = 33; * label.y = 1; * label.left = 33; * label.right = 0; * this.addChild(label); * var arrow: Clip = new Clip("resource/ui/clip_tree_arrow.png", 1, 2); * arrow.name = "arrow"; * arrow.x = 0; * arrow.y = 5; * this.addChild(arrow); * } * } */ class Tree extends Box implements IRender { protected _list: List; protected _source: Array; protected _renderHandler: Handler; protected _spaceLeft: number; protected _spaceBottom: number; protected _keepStatus: boolean; /** * 创建一个新的 Tree 类实例。 *

    Tree 构造函数中设置属性width、height的值都为200。

    */ constructor(); /**@inheritDoc */ destroy(destroyChild?: boolean): void; protected createChildren(): void; protected onListChange(e?: Event): void; /** * 数据源发生变化后,是否保持之前打开状态,默认为true。 *

    取值: *

  • true:保持之前打开状态。
  • *
  • false:不保持之前打开状态。
  • *

    */ keepStatus: boolean; /** * 列表数据源,只包含当前可视节点数据。 */ array: Array; /** * 数据源,全部节点数据。 */ readonly source: Array; /** * 此对象包含的List实例对象。 */ readonly list: List; /** * 此对象包含的List实例的单元格渲染器。 *

    取值: *

      *
    1. 单元格类对象。
    2. *
    3. UI 的 JSON 描述。
    4. *

    */ itemRender: any; /** * 滚动条皮肤。 */ scrollBarSkin: string; /**滚动条*/ readonly scrollBar: ScrollBar; /** * 单元格鼠标事件处理器。 *

    默认返回参数(e:Event,index:int)。

    */ mouseHandler: Handler; /** * Tree 实例的渲染处理器。 */ renderHandler: Handler; /** * 左侧缩进距离(以像素为单位)。 */ spaceLeft: number; /** * 每一项之间的间隔距离(以像素为单位)。 */ spaceBottom: number; /** * 表示当前选择的项索引。 */ selectedIndex: number; /** * 当前选中的项对象的数据源。 */ selectedItem: any; /** * @inheritDoc */ width: number; /**@inheritDoc */ height: number; protected getArray(): Array; protected getDepth(item: any, num?: number): number; protected getParentOpenStatus(item: any): boolean; protected renderItem(cell: Box, index: number): void; /** * 设置指定项索引的项对象的打开状态。 * @param index 项索引。 * @param isOpen 是否处于打开状态。 */ setItemState(index: number, isOpen: boolean): void; /** * 刷新项列表。 */ fresh(): void; /**@inheritDoc */ dataSource: any; /** * xml结构的数据源。 */ xml: any; protected parseXml(xml: any, source: Array, nodeParent: any, isRoot: boolean): void; protected parseOpenStatus(oldSource: Array, newSource: Array): void; protected isSameParent(item1: any, item2: any): boolean; /** * 表示选择的树节点项的path属性值。 */ readonly selectedPath: string; /** * 更新项列表,显示指定键名的数据项。 * @param key 键名。 */ filter(key: string): void; } } declare module laya.ui { import Event = laya.events.Event; /** * UIEvent 类用来定义UI组件类的事件类型。 */ class UIEvent extends Event { /** * 显示提示信息。 */ static SHOW_TIP: string; /** * 隐藏提示信息。 */ static HIDE_TIP: string; } } declare module laya.ui { import Sprite = laya.display.Sprite; import Handler = laya.utils.Handler; /** * Group 是一个可以自动布局的项集合控件。 *

    Group 的默认项对象为 Button 类实例。 * GroupTabRadioGroup 的基类。

    */ class UIGroup extends Box implements IItem { /** * 改变 Group 的选择项时执行的处理器,(默认返回参数: 项索引(index:int))。 */ selectHandler: Handler; protected _items: Array; protected _selectedIndex: number; protected _skin: string; protected _direction: string; protected _space: number; protected _labels: string; protected _labelColors: string; protected _labelStrokeColor: string; protected _strokeColors: string; protected _labelStroke: number; protected _labelSize: number; protected _labelBold: boolean; protected _labelPadding: string; protected _labelAlign: string; protected _stateNum: number; protected _labelChanged: boolean; /** * 创建一个新的 Group 类实例。 * @param labels 标签集字符串。以逗号做分割,如"item0,item1,item2,item3,item4,item5"。 * @param skin 皮肤。 */ constructor(labels?: string, skin?: string); protected preinitialize(): void; /**@inheritDoc */ destroy(destroyChild?: boolean): void; /** * 添加一个项对象,返回此项对象的索引id。 * * @param item 需要添加的项对象。 * @param autoLayOut 是否自动布局,如果为true,会根据 directionspace 属性计算item的位置。 * @return */ addItem(item: ISelect, autoLayOut?: boolean): number; /** * 删除一个项对象。 * @param item 需要删除的项对象。 * @param autoLayOut 是否自动布局,如果为true,会根据 directionspace 属性计算item的位置。 */ delItem(item: ISelect, autoLayOut?: boolean): void; /** * 初始化项对象们。 */ initItems(): void; protected itemClick(index: number): void; /** * 表示当前选择的项索引。默认值为-1。 */ selectedIndex: number; protected setSelect(index: number, selected: boolean): void; /** * @copy laya.ui.Image#skin */ skin: string; /** * 标签集合字符串。以逗号做分割,如"item0,item1,item2,item3,item4,item5"。 */ labels: string; protected createItem(skin: string, label: string): Sprite; /** * @copy laya.ui.Button#labelColors() */ labelColors: string; /** *

    描边宽度(以像素为单位)。

    * 默认值0,表示不描边。 * @see laya.display.Text.stroke() */ labelStroke: number; /** *

    描边颜色,以字符串表示。

    * 默认值为 "#000000"(黑色); * @see laya.display.Text.strokeColor() */ labelStrokeColor: string; /** *

    表示各个状态下的描边颜色。

    * @see laya.display.Text.strokeColor() */ strokeColors: string; /** * 表示按钮文本标签的字体大小。 */ labelSize: number; /** * 表示按钮的状态值,以数字表示,默认为3态。 * @see laya.ui.Button#stateNum */ stateNum: number; /** * 表示按钮文本标签是否为粗体字。 */ labelBold: boolean; /** * 表示按钮文本标签的字体名称,以字符串形式表示。 * @see laya.display.Text.font() */ labelFont: string; /** * 表示按钮文本标签的边距。 *

    格式:"上边距,右边距,下边距,左边距"。

    */ labelPadding: string; /** * 布局方向。 *

    默认值为"horizontal"。

    *

    取值: *

  • "horizontal":表示水平布局。
  • *
  • "vertical":表示垂直布局。
  • *

    */ direction: string; /** * 项对象们之间的间隔(以像素为单位)。 */ space: number; protected changeLabels(): void; protected commitMeasure(): void; /** * 项对象们的存放数组。 */ readonly items: Array; /** * 获取或设置当前选择的项对象。 */ selection: ISelect; /**@inheritDoc */ dataSource: any; protected _setLabelChanged(): void; } } declare module laya.ui { import Sprite = laya.display.Sprite; import IFilter = laya.filters.IFilter; /** * UIUtils 是文本工具集。 */ class UIUtils { /** * 需要替换的转义字符表 */ static escapeSequence: any; /** * 用字符串填充数组,并返回数组副本。 * @param arr 源数组对象。 * @param str 用逗号连接的字符串。如"p1,p2,p3,p4"。 * @param type 如果值不为null,则填充的是新增值得类型。 * @return 填充后的数组。 */ static fillArray(arr: Array, str: string, type?: any): Array; /** * 转换uint类型颜色值为字符型颜色值。 * @param color uint颜色值。 * @return 字符型颜色值。 */ static toColor(color: number): string; /** * 给指定的目标显示对象添加或移除灰度滤镜。 * @param traget 目标显示对象。 * @param isGray 如果值true,则添加灰度滤镜,否则移除灰度滤镜。 */ static gray(traget: Sprite, isGray?: boolean): void; /** * 给指定的目标显示对象添加滤镜。 * @param target 目标显示对象。 * @param filter 滤镜对象。 */ static addFilter(target: Sprite, filter: IFilter): void; /** * 移除目标显示对象的指定类型滤镜。 * @param target 目标显示对象。 * @param filterType 滤镜类型。 */ static clearFilter(target: Sprite, filterType: any): void; /** * 替换字符串中的转义字符 * @param str */ static adptString(str: string): string; /** * @private 根据字符串,返回函数表达式 */ static getBindFun(value: string): Function; } } declare module laya.ui { /** * VBox 是一个垂直布局容器类。 */ class VBox extends LayoutBox { /** * 无对齐。 */ static NONE: string; /** * 左对齐。 */ static LEFT: string; /** * 居中对齐。 */ static CENTER: string; /** * 右对齐。 */ static RIGHT: string; width: number; protected changeItems(): void; } } declare module laya.ui { import Event = laya.events.Event; import Box = laya.ui.Box; import Component = laya.ui.Component; /** * View 是一个视图类。 * @internal

    View

    */ class View extends Box { /**存储UI配置数据(用于加载模式)。*/ static uiMap: any; /**UI类映射。*/ static uiClassMap: any; protected static viewClassMap: any; static eventDic: any; _idMap: any; _aniList: Array; _watchMap: any; static _sheet: any; protected createView(uiView: any): void; protected onEvent(type: string, event: Event): void; protected loadUI(path: string): void; /** * 根据UI数据实例化组件。 * @param uiView UI数据。 * @param comp 组件本体,如果为空,会新创建一个。 * @param view 组件所在的视图实例,用来注册var全局变量,如果值为空则不注册。 * @return 一个 Component 对象。 */ static createComp(uiView: any, comp?: any, view?: View, dataMap?: Array): any; protected static getCompInstance(json: any): any; /** * 注册组件类映射。 *

    用于扩展组件及修改组件对应关系。

    * @param key 组件类的关键字。 * @param compClass 组件类对象。 */ static regComponent(key: string, compClass: any): void; /** * 注册UI视图类的逻辑处理类。 * @internal 注册runtime解析。 * @param key UI视图类的关键字。 * @param compClass UI视图类对应的逻辑处理类。 */ static regViewRuntime(key: string, compClass: any): void; /** *

    销毁此对象。

    * @param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ destroy(destroyChild?: boolean): void; changeData(key: string): void; } class DataWatcher { comp: Component; prop: string; value: string; DataWatcher(comp: Component, prop: string, value: string): void; exe(view: View): void; } } declare module laya.ui { import Node = laya.display.Node; import Box = laya.ui.Box; import Handler = laya.utils.Handler; /** * ViewStack 类用于视图堆栈类,用于视图的显示等设置处理。 */ class ViewStack extends Box implements IItem { protected _items: Array; protected _setIndexHandler: Handler; protected _selectedIndex: number; /** * 批量设置视图对象。 * @param views 视图对象数组。 */ setItems(views: Array): void; /** * 添加视图。 * @internal 添加视图对象,并设置此视图对象的name 属性。 * @param view 需要添加的视图对象。 */ addItem(view: Node): void; /** * 初始化视图对象集合。 */ initItems(): void; /** * 表示当前视图索引。 */ selectedIndex: number; protected setSelect(index: number, selected: boolean): void; /** * 获取或设置当前选择的项对象。 */ selection: Node; /** * 索引设置处理器。 *

    默认回调参数:index:int

    */ setIndexHandler: Handler; protected setIndex(index: number): void; /** * 视图集合数组。 */ readonly items: Array; /**@inheritDoc */ dataSource: any; } } declare module laya.ui { /** * * 使用 VScrollBar (垂直 ScrollBar )控件,可以在因数据太多而不能在显示区域完全显示时控制显示的数据部分。 * * @example 以下示例代码,创建了一个 VScrollBar 实例。 * package * { * import laya.ui.vScrollBar; * import laya.ui.VScrollBar; * import laya.utils.Handler; * public class VScrollBar_Example * { * private var vScrollBar:VScrollBar; * public function VScrollBar_Example() * { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png"], Handler.create(this, onLoadComplete)); * } * private function onLoadComplete():void * { * vScrollBar = new VScrollBar();//创建一个 vScrollBar 类的实例对象 hScrollBar 。 * vScrollBar.skin = "resource/ui/vscroll.png";//设置 vScrollBar 的皮肤。 * vScrollBar.x = 100;//设置 vScrollBar 对象的属性 x 的值,用于控制 vScrollBar 对象的显示位置。 * vScrollBar.y = 100;//设置 vScrollBar 对象的属性 y 的值,用于控制 vScrollBar 对象的显示位置。 * vScrollBar.changeHandler = new Handler(this, onChange);//设置 vScrollBar 的滚动变化处理器。 * Laya.stage.addChild(vScrollBar);//将此 vScrollBar 对象添加到显示列表。 * } * private function onChange(value:Number):void * { * trace("滚动条的位置: value=" + value); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * var vScrollBar; * var res = ["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png"]; * Laya.loader.load(res, laya.utils.Handler.create(this, onLoadComplete));//加载资源。 * function onLoadComplete() { * vScrollBar = new laya.ui.VScrollBar();//创建一个 vScrollBar 类的实例对象 hScrollBar 。 * vScrollBar.skin = "resource/ui/vscroll.png";//设置 vScrollBar 的皮肤。 * vScrollBar.x = 100;//设置 vScrollBar 对象的属性 x 的值,用于控制 vScrollBar 对象的显示位置。 * vScrollBar.y = 100;//设置 vScrollBar 对象的属性 y 的值,用于控制 vScrollBar 对象的显示位置。 * vScrollBar.changeHandler = new laya.utils.Handler(this, onChange);//设置 vScrollBar 的滚动变化处理器。 * Laya.stage.addChild(vScrollBar);//将此 vScrollBar 对象添加到显示列表。 * } * function onChange(value) { * console.log("滚动条的位置: value=" + value); * } * @example * import VScrollBar = laya.ui.VScrollBar; * import Handler = laya.utils.Handler; * class VScrollBar_Example { * private vScrollBar: VScrollBar; * constructor() { * Laya.init(640, 800);//设置游戏画布宽高、渲染模式。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/vscroll.png", "resource/ui/vscroll$bar.png", "resource/ui/vscroll$down.png", "resource/ui/vscroll$up.png"], Handler.create(this, this.onLoadComplete)); * } * private onLoadComplete(): void { * this.vScrollBar = new VScrollBar();//创建一个 vScrollBar 类的实例对象 hScrollBar 。 * this.vScrollBar.skin = "resource/ui/vscroll.png";//设置 vScrollBar 的皮肤。 * this.vScrollBar.x = 100;//设置 vScrollBar 对象的属性 x 的值,用于控制 vScrollBar 对象的显示位置。 * this.vScrollBar.y = 100;//设置 vScrollBar 对象的属性 y 的值,用于控制 vScrollBar 对象的显示位置。 * this.vScrollBar.changeHandler = new Handler(this, this.onChange);//设置 vScrollBar 的滚动变化处理器。 * Laya.stage.addChild(this.vScrollBar);//将此 vScrollBar 对象添加到显示列表。 * } * private onChange(value: number): void { * console.log("滚动条的位置: value=" + value); * } * } */ class VScrollBar extends ScrollBar { } } declare module laya.ui { /** * 使用 VSlider 控件,用户可以通过在滑块轨道的终点之间移动滑块来选择值。 *

    VSlider 控件采用垂直方向。滑块轨道从下往上扩展,而标签位于轨道的左右两侧。

    * * @example 以下示例代码,创建了一个 VSlider 实例。 * package * { * import laya.ui.HSlider; * import laya.ui.VSlider; * import laya.utils.Handler; * public class VSlider_Example * { * private var vSlider:VSlider; * public function VSlider_Example() * { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/vslider.png", "resource/ui/vslider$bar.png"], Handler.create(this, onLoadComplete));//加载资源。 * } * private function onLoadComplete():void * { * vSlider = new VSlider();//创建一个 VSlider 类的实例对象 vSlider 。 * vSlider.skin = "resource/ui/vslider.png";//设置 vSlider 的皮肤。 * vSlider.min = 0;//设置 vSlider 最低位置值。 * vSlider.max = 10;//设置 vSlider 最高位置值。 * vSlider.value = 2;//设置 vSlider 当前位置值。 * vSlider.tick = 1;//设置 vSlider 刻度值。 * vSlider.x = 100;//设置 vSlider 对象的属性 x 的值,用于控制 vSlider 对象的显示位置。 * vSlider.y = 100;//设置 vSlider 对象的属性 y 的值,用于控制 vSlider 对象的显示位置。 * vSlider.changeHandler = new Handler(this, onChange);//设置 vSlider 位置变化处理器。 * Laya.stage.addChild(vSlider);//把 vSlider 添加到显示列表。 * } * private function onChange(value:Number):void * { * trace("滑块的位置: value=" + value); * } * } * } * @example * Laya.init(640, 800);//设置游戏画布宽高 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色 * var vSlider; * Laya.loader.load(["resource/ui/vslider.png", "resource/ui/vslider$bar.png"], laya.utils.Handler.create(this, onLoadComplete));//加载资源。 * function onLoadComplete() { * vSlider = new laya.ui.VSlider();//创建一个 VSlider 类的实例对象 vSlider 。 * vSlider.skin = "resource/ui/vslider.png";//设置 vSlider 的皮肤。 * vSlider.min = 0;//设置 vSlider 最低位置值。 * vSlider.max = 10;//设置 vSlider 最高位置值。 * vSlider.value = 2;//设置 vSlider 当前位置值。 * vSlider.tick = 1;//设置 vSlider 刻度值。 * vSlider.x = 100;//设置 vSlider 对象的属性 x 的值,用于控制 vSlider 对象的显示位置。 * vSlider.y = 100;//设置 vSlider 对象的属性 y 的值,用于控制 vSlider 对象的显示位置。 * vSlider.changeHandler = new laya.utils.Handler(this, onChange);//设置 vSlider 位置变化处理器。 * Laya.stage.addChild(vSlider);//把 vSlider 添加到显示列表。 * } * function onChange(value) { * console.log("滑块的位置: value=" + value); * } * @example * import HSlider = laya.ui.HSlider; * import VSlider = laya.ui.VSlider; * import Handler = laya.utils.Handler; * class VSlider_Example { * private vSlider: VSlider; * constructor() { * Laya.init(640, 800);//设置游戏画布宽高。 * Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。 * Laya.loader.load(["resource/ui/vslider.png", "resource/ui/vslider$bar.png"], Handler.create(this, this.onLoadComplete));//加载资源。 * } * private onLoadComplete(): void { * this.vSlider = new VSlider();//创建一个 VSlider 类的实例对象 vSlider 。 * this.vSlider.skin = "resource/ui/vslider.png";//设置 vSlider 的皮肤。 * this.vSlider.min = 0;//设置 vSlider 最低位置值。 * this.vSlider.max = 10;//设置 vSlider 最高位置值。 * this.vSlider.value = 2;//设置 vSlider 当前位置值。 * this.vSlider.tick = 1;//设置 vSlider 刻度值。 * this.vSlider.x = 100;//设置 vSlider 对象的属性 x 的值,用于控制 vSlider 对象的显示位置。 * this.vSlider.y = 100;//设置 vSlider 对象的属性 y 的值,用于控制 vSlider 对象的显示位置。 * this.vSlider.changeHandler = new Handler(this, this.onChange);//设置 vSlider 位置变化处理器。 * Laya.stage.addChild(this.vSlider);//把 vSlider 添加到显示列表。 * } * private onChange(value: number): void { * console.log("滑块的位置: value=" + value); * } * } * @see laya.ui.Slider */ class VSlider extends Slider { } } declare module laya.utils { import Context = laya.resource.Context; import HTMLCanvas = laya.resource.HTMLCanvas; /** * Browser 是浏览器代理类。封装浏览器及原生 js 提供的一些功能。 */ class Browser { /** 浏览器代理信息。*/ static userAgent: string; /** 表示是否在 ios 设备。*/ static onIOS: boolean; /** 表示是否在 Mac 设备。*/ static onMac: boolean; /** 表示是否在移动设备。*/ static onMobile: boolean; /** 表示是否在 iphone设备。*/ static onIPhone: boolean; /** 表示是否在 ipad 设备。*/ static onIPad: boolean; /** 表示是否在 Android设备。*/ static onAndroid: boolean; /** 表示是否在 Windows Phone 设备。*/ static onWP: boolean; /** 表示是否在 QQ 浏览器。*/ static onQQBrowser: boolean; /** 表示是否在移动端 QQ 或 QQ 浏览器。*/ static onMQQBrowser: boolean; /** 表示是否在移动端 Safari。*/ static onSafari: boolean; /** 表示是否在Firefox。*/ static onFirefox: boolean; /** 表示是否在Edge。*/ static onEdge: boolean; /** 表示是否在IE浏览器内*/ static onIE: boolean; /** 微信内*/ static onWeiXin: boolean; /** 表示是否在微信小游戏内 */ static onMiniGame: boolean; /** 表示是否在百度内 */ static onBDMiniGame: boolean; static onLimixiu: boolean; /** 表示是否在小米内 */ static onKGMiniGame:boolean; /** 表示是否在oppo内 */ static onQGMiniGame:boolean; /** 表示是否在 PC 端。*/ static onPC: boolean; /** 表示是否是 HTTP 协议。*/ static httpProtocol: boolean; static webAudioEnabled: boolean; static soundType: string; static enableTouch: boolean; /** 全局画布实例(非主画布)。*/ static canvas: HTMLCanvas; /** 全局画布上绘图的环境(非主画布)。 */ static context: Context; static __init__(): void; /** * 创建浏览器原生节点。 * @param type 节点类型。 * @return 创建的节点对象的引用。 */ static createElement(type: string): any; /** * 返回 Document 对象中拥有指定 id 的第一个对象的引用。 * @param type 节点id。 * @return 节点对象。 */ static getElementById(type: string): any; /** * 移除指定的浏览器原生节点对象。 * @param type 节点对象。 */ static removeElement(ele: any): void; /** * 获取浏览器当前时间戳,单位为毫秒。 */ static now(): number; /** * 浏览器窗口可视宽度。 * 通过分析浏览器信息获得。浏览器多个属性值优先级为:window.innerWidth(包含滚动条宽度) > document.body.clientWidth(不包含滚动条宽度),如果前者为0或为空,则选择后者。 */ static readonly clientWidth: number; /** * 浏览器窗口可视高度。 * 通过分析浏览器信息获得。浏览器多个属性值优先级为:window.innerHeight(包含滚动条高度) > document.body.clientHeight(不包含滚动条高度) > document.documentElement.clientHeight(不包含滚动条高度),如果前者为0或为空,则选择后者。 */ static readonly clientHeight: number; /** 浏览器窗口物理宽度,其值等于clientWidth * pixelRatio,并且浏览器发生反转之后,宽高会互换。*/ static readonly width: number; /** 浏览器窗口物理高度,其值等于clientHeight * pixelRatio,并且浏览器发生反转之后,宽高会互换。*/ static readonly height: number; /** 设备像素比。*/ static readonly pixelRatio: number; /**画布容器,用来盛放画布的容器。方便对画布进行控制*/ static container: any; /** 浏览器原生 window 对象的引用。*/ static readonly window: any; /** 浏览器原生 document 对象的引用。*/ static readonly document: any; } } declare module laya.utils { import Matrix = laya.maths.Matrix; /** *

    Byte 类提供用于优化读取、写入以及处理二进制数据的方法和属性。

    *

    注意: Byte 类适用于需要在字节层访问数据的高级开发人员。

    */ class Byte { /** *

    主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。通过 getSystemEndian 可以获取当前系统的字节序。

    *

    BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。
    * LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。

    */ static BIG_ENDIAN: string; /** *

    主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。通过 getSystemEndian 可以获取当前系统的字节序。

    *

    LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。
    * BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。

    */ static LITTLE_ENDIAN: string; protected _xd_: boolean; protected _d_: any; protected _u8d_: any; protected _pos_: number; protected _length: number; /** *

    获取当前主机的字节序。

    *

    主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。

    *

    BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。
    * LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。

    * @return 当前系统的字节序。 */ static getSystemEndian(): string; /** * 创建一个 Byte 类的实例。 * @param data 用于指定初始化的元素数目,或者用于初始化的TypedArray对象、ArrayBuffer对象。如果为 null ,则预分配一定的内存空间,当可用空间不足时,优先使用这部分内存,如果还不够,则重新分配所需内存。 */ constructor(data?: any); /** * 获取此对象的 ArrayBuffer 数据,数据只包含有效数据部分。 */ readonly buffer: ArrayBuffer; /** *

    Byte 实例的字节序。取值为:BIG_ENDIANBIG_ENDIAN

    *

    主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。通过 getSystemEndian 可以获取当前系统的字节序。

    *

    BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。
    * LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。

    */ endian: string; /** *

    Byte 对象的长度(以字节为单位)。

    *

    如果将长度设置为大于当前长度的值,则用零填充字节数组的右侧;如果将长度设置为小于当前长度的值,将会截断该字节数组。

    *

    如果要设置的长度大于当前已分配的内存空间的字节长度,则重新分配内存空间,大小为以下两者较大者:要设置的长度、当前已分配的长度的2倍,并将原有数据拷贝到新的内存空间中;如果要设置的长度小于当前已分配的内存空间的字节长度,也会重新分配内存空间,大小为要设置的长度,并将原有数据从头截断为要设置的长度存入新的内存空间中。

    */ length: number; /** *

    常用于解析固定格式的字节流。

    *

    先从字节流的当前字节偏移位置处读取一个 Uint16 值,然后以此值为长度,读取此长度的字符串。

    * @return 读取的字符串。 */ getString(): string; /** * 从字节流中 start 参数指定的位置开始,读取 len 参数指定的字节数的数据,用于创建一个 Float32Array 对象并返回此对象。 * @param start 开始位置。 * @param len 需要读取的字节长度。如果要读取的长度超过可读取范围,则只返回可读范围内的值。 * @return 读取的 Float32Array 对象。 */ getFloat32Array(start: number, len: number): any; /** * 从字节流中 start 参数指定的位置开始,读取 len 参数指定的字节数的数据,用于创建一个 Uint8Array 对象并返回此对象。 * @param start 开始位置。 * @param len 需要读取的字节长度。如果要读取的长度超过可读取范围,则只返回可读范围内的值。 * @return 读取的 Uint8Array 对象。 */ getUint8Array(start: number, len: number): Uint8Array; /** * 从字节流中 start 参数指定的位置开始,读取 len 参数指定的字节数的数据,用于创建一个 Int16Array 对象并返回此对象。 * @param start 开始读取的字节偏移量位置。 * @param len 需要读取的字节长度。如果要读取的长度超过可读取范围,则只返回可读范围内的值。 * @return 读取的 Uint8Array 对象。 */ getInt16Array(start: number, len: number): any; /** * 从字节流的当前字节偏移位置处读取一个 IEEE 754 单精度(32 位)浮点数。 * @return 单精度(32 位)浮点数。 */ getFloat32(): number; /** * 从字节流的当前字节偏移量位置处读取一个 IEEE 754 双精度(64 位)浮点数。 * @return 双精度(64 位)浮点数。 */ getFloat64(): number; /** * 在字节流的当前字节偏移量位置处写入一个 IEEE 754 单精度(32 位)浮点数。 * @param value 单精度(32 位)浮点数。 */ writeFloat32(value: number): void; /** * 在字节流的当前字节偏移量位置处写入一个 IEEE 754 双精度(64 位)浮点数。 * @param value 双精度(64 位)浮点数。 */ writeFloat64(value: number): void; /** * 从字节流的当前字节偏移量位置处读取一个 Int32 值。 * @return Int32 值。 */ getInt32(): number; /** * 从字节流的当前字节偏移量位置处读取一个 Uint32 值。 * @return Uint32 值。 */ getUint32(): number; /** * 在字节流的当前字节偏移量位置处写入指定的 Int32 值。 * @param value 需要写入的 Int32 值。 */ writeInt32(value: number): void; /** * 在字节流的当前字节偏移量位置处写入 Uint32 值。 * @param value 需要写入的 Uint32 值。 */ writeUint32(value: number): void; /** * 从字节流的当前字节偏移量位置处读取一个 Int16 值。 * @return Int16 值。 */ getInt16(): number; /** * 从字节流的当前字节偏移量位置处读取一个 Uint16 值。 * @return Uint16 值。 */ getUint16(): number; /** * 在字节流的当前字节偏移量位置处写入指定的 Uint16 值。 * @param value 需要写入的Uint16 值。 */ writeUint16(value: number): void; /** * 在字节流的当前字节偏移量位置处写入指定的 Int16 值。 * @param value 需要写入的 Int16 值。 */ writeInt16(value: number): void; /** * 从字节流的当前字节偏移量位置处读取一个 Uint8 值。 * @return Uint8 值。 */ getUint8(): number; /** * 在字节流的当前字节偏移量位置处写入指定的 Uint8 值。 * @param value 需要写入的 Uint8 值。 */ writeUint8(value: number): void; /** * @private * 从字节流的指定字节偏移量位置处读取一个 Uint8 值。 * @param pos 字节读取位置。 * @return Uint8 值。 */ _getUInt8(pos: number): number; /** * @private * 从字节流的指定字节偏移量位置处读取一个 Uint16 值。 * @param pos 字节读取位置。 * @return Uint16 值。 */ _getUint16(pos: number): number; /** * @private * 使用 getFloat32() 读取6个值,用于创建并返回一个 Matrix 对象。 * @return Matrix 对象。 */ _getMatrix(): Matrix; /** * @private * 读取 len 参数指定的长度的字符串。 * @param len 要读取的字符串的长度。 * @return 指定长度的字符串。 */ getCustomString(len: number): string; /** * 移动或返回 Byte 对象的读写指针的当前位置(以字节为单位)。下一次调用读取方法时将在此位置开始读取,或者下一次调用写入方法时将在此位置开始写入。 */ pos: number; /** * 可从字节流的当前位置到末尾读取的数据的字节数。 */ readonly bytesAvailable: number; /** * 清除字节数组的内容,并将 length 和 pos 属性重置为 0。调用此方法将释放 Byte 实例占用的内存。 */ clear(): void; /** * @private * 获取此对象的 ArrayBuffer 引用。 * @return */ __getBuffer(): ArrayBuffer; /** *

    将 UTF-8 字符串写入字节流。类似于 writeUTF() 方法,但 writeUTFBytes() 不使用 16 位长度的字为字符串添加前缀。

    *

    对应的读取方法为: getUTFBytes 。

    * @param value 要写入的字符串。 */ writeUTFBytes(value: string): void; /** *

    将 UTF-8 字符串写入字节流。先写入以字节表示的 UTF-8 字符串长度(作为 16 位整数),然后写入表示字符串字符的字节。

    *

    对应的读取方法为: getUTFString 。

    * @param value 要写入的字符串值。 */ writeUTFString(value: string): void; /** * @private * 读取 UTF-8 字符串。 * @return 读取的字符串。 */ readUTFString(): string; /** *

    从字节流中读取一个 UTF-8 字符串。假定字符串的前缀是一个无符号的短整型(以此字节表示要读取的长度)。

    *

    对应的写入方法为: writeUTFString 。

    * @return 读取的字符串。 */ getUTFString(): string; /** * @private * 读字符串,必须是 writeUTFBytes 方法写入的字符串。 * @param len 要读的buffer长度,默认将读取缓冲区全部数据。 * @return 读取的字符串。 */ readUTFBytes(len?: number): string; /** *

    从字节流中读取一个由 length 参数指定的长度的 UTF-8 字节序列,并返回一个字符串。

    *

    一般读取的是由 writeUTFBytes 方法写入的字符串。

    * @param len 要读的buffer长度,默认将读取缓冲区全部数据。 * @return 读取的字符串。 */ getUTFBytes(len?: number): string; /** *

    在字节流中写入一个字节。

    *

    使用参数的低 8 位。忽略高 24 位。

    * @param value */ writeByte(value: number): void; /** * @private * 从字节流中读取带符号的字节。 */ readByte(): number; /** *

    从字节流中读取带符号的字节。

    *

    返回值的范围是从 -128 到 127。

    * @return 介于 -128 和 127 之间的整数。 */ getByte(): number; /** *

    保证该字节流的可用长度不小于 lengthToEnsure 参数指定的值。

    * @param lengthToEnsure 指定的长度。 */ ensureWrite(lengthToEnsure: number): void; /** *

    将指定 arraybuffer 对象中的以 offset 为起始偏移量, length 为长度的字节序列写入字节流。

    *

    如果省略 length 参数,则使用默认长度 0,该方法将从 offset 开始写入整个缓冲区;如果还省略了 offset 参数,则写入整个缓冲区。

    *

    如果 offset 或 length 小于0,本函数将抛出异常。

    * $NEXTBIG 由于没有判断length和arraybuffer的合法性,当开发者填写了错误的length值时,会导致写入多余的空白数据甚至内存溢出,为了避免影响开发者正在使用此方法的功能,下个重大版本会修复这些问题。 * @param arraybuffer 需要写入的 Arraybuffer 对象。 * @param offset Arraybuffer 对象的索引的偏移量(以字节为单位) * @param length 从 Arraybuffer 对象写入到 Byte 对象的长度(以字节为单位) */ writeArrayBuffer(arraybuffer: any, offset?: number, length?: number): void; } } declare module laya.utils { /** * @private * 对象缓存统一管理类 */ class CacheManager { /** * 单次清理检测允许执行的时间,单位ms。 */ static loopTimeLimit: number; constructor(); /** * 注册cache管理函数 * @param disposeFunction 释放函数 fun(force:Boolean) * @param getCacheListFunction 获取cache列表函数fun():Array * */ static regCacheByFunction(disposeFunction: Function, getCacheListFunction: Function): void; /** * 移除cache管理函数 * @param disposeFunction 释放函数 fun(force:Boolean) * @param getCacheListFunction 获取cache列表函数fun():Array * */ static unRegCacheByFunction(disposeFunction: Function, getCacheListFunction: Function): void; /** * 强制清理所有管理器 * */ static forceDispose(): void; /** * 开始检测循环 * @param waitTime 检测间隔时间 * */ static beginCheck(waitTime?: number): void; /** * 停止检测循环 * */ static stopCheck(): void; } } declare module laya.utils { import Node = laya.display.Node; import Sprite = laya.display.Sprite; /** * ClassUtils 是一个类工具类。 */ class ClassUtils { static _classMap: any; /** * 注册 Class 映射。 * @param className 映射的名字,或者类名简写。 * @param classDef 类的全名或者类的引用,全名比如:"laya.display.Sprite"。 */ static regClass(className: string, classDef: any): void; /** * 返回注册 Class 映射。 * @param className 映射的名字。 */ static getRegClass(className: string): any; /** * 根据名字返回类对象。 * @param className 类名。 * @return 类对象 */ static getClass: Function; /** * 根据名称创建 Class 实例。 * @param className 类名。 * @return 返回类的实例。 */ static getInstance(className: string): any; /** * 根据指定的 json 数据创建节点对象。 * 比如: * * "type":"Sprite", * "props": * "x":100, * "y":50, * "name":"item1", * "scale":[2,2] * }, * "customProps": * "x":100, * "y":50, * "name":"item1", * "scale":[2,2] * }, * "child":[ * * "type":"Text", * "props": * "text":"this is a test", * "var":"label", * "rumtime":"" * } * } * ] * } * @param json json字符串或者Object对象。 * @param node node节点,如果为空,则新创建一个。 * @param root 根节点,用来设置var定义。 * @return 生成的节点。 */ static createByJson(json: any, node?: any, root?: Node, customHandler?: Handler, instanceHandler?: Handler): any; /** * 将graphic对象添加到Sprite上 * @param graphicO graphic对象描述 * @param sprite * */ static addGraphicsToSprite(graphicO: any, sprite: Sprite): void; /** * 将graphic绘图指令添加到sprite上 * @param graphicO 绘图指令描述 * @param sprite * */ static addGraphicToSprite(graphicO: any, sprite: Sprite, isChild?: boolean): void; /** * @private */ static isDrawType(type: string): boolean; /** * @private */ static _getPointListByStr(str: string): Array; } } declare module laya.utils { /** * @private * Color 是一个颜色值处理类。 */ class Color { static _SAVE: any; static _SAVE_SIZE: number; _color: Array; /** 字符串型颜色值。*/ strColor: string; /** uint 型颜色值。*/ numColor: number; _drawStyle: any; /** * 根据指定的属性值,创建一个 Color 类的实例。 * @param str 颜色值。 */ constructor(str: any); static _initDefault(): any; static _initSaveMap(): void; /** * 根据指定的属性值,创建并返回一个 Color 类的实例。 * @param str 颜色值。 * @return 一个 Color 类的实例。 */ static create(str: any): Color; } } declare module laya.utils { /** * Dictionary 是一个字典型的数据存取类。 */ class Dictionary { /** * 获取所有的子元素列表。 */ readonly values: Array; /** * 获取所有的子元素键名列表。 */ readonly keys: Array; /** * 给指定的键名设置值。 * @param key 键名。 * @param value 值。 */ set(key: any, value: any): void; /** * 获取指定对象的键名索引。 * @param key 键名对象。 * @return 键名索引。 */ indexOf(key: any): number; /** * 返回指定键名的值。 * @param key 键名对象。 * @return 指定键名的值。 */ get(key: any): any; /** * 移除指定键名的值。 * @param key 键名对象。 * @return 是否成功移除。 */ remove(key: any): boolean; /** * 清除此对象的键名列表和键值列表。 */ clear(): void; } } declare module laya.utils { import Sprite = laya.display.Sprite; import Rectangle = laya.maths.Rectangle; /** * @private * Dragging 类是触摸滑动控件。 */ class Dragging { /** 被拖动的对象。*/ target: Sprite; /** 缓动衰减系数。*/ ratio: number; /** 单帧最大偏移量。*/ maxOffset: number; /** 滑动范围。*/ area: Rectangle; /** 表示拖动是否有惯性。*/ hasInertia: boolean; /** 橡皮筋最大值。*/ elasticDistance: number; /** 橡皮筋回弹时间,单位为毫秒。*/ elasticBackTime: number; /** 事件携带数据。*/ data: any; /** * 开始拖拽。 * @param target 待拖拽的 Sprite 对象。 * @param area 滑动范围。 * @param hasInertia 拖动是否有惯性。 * @param elasticDistance 橡皮筋最大值。 * @param elasticBackTime 橡皮筋回弹时间,单位为毫秒。 * @param data 事件携带数据。 * @param disableMouseEvent 鼠标事件是否有效。 * @param ratio 惯性阻尼系数 */ start(target: Sprite, area: Rectangle, hasInertia: boolean, elasticDistance: number, elasticBackTime: number, data: any, disableMouseEvent: boolean, ratio?: number): void; /** * 停止拖拽。 */ stop(): void; } } declare module laya.utils { /** * Ease 类定义了缓动函数,以便实现 Tween 动画的缓动效果。 */ class Ease { /** * 定义无加速持续运动。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static linearNone(t: number, b: number, c: number, d: number): number; /** * 定义无加速持续运动。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static linearIn(t: number, b: number, c: number, d: number): number; /** * 定义无加速持续运动。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static linearInOut(t: number, b: number, c: number, d: number): number; /** * 定义无加速持续运动。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static linearOut(t: number, b: number, c: number, d: number): number; /** * 方法以零速率开始运动,然后在执行时加快运动速度。 * 它的运动是类似一个球落向地板又弹起后,几次逐渐减小的回弹运动。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static bounceIn(t: number, b: number, c: number, d: number): number; /** * 开始运动时速率为零,先对运动进行加速,再减速直到速率为零。 * 它的运动是类似一个球落向地板又弹起后,几次逐渐减小的回弹运动。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static bounceInOut(t: number, b: number, c: number, d: number): number; /** * 以较快速度开始运动,然后在执行时减慢运动速度,直至速率为零。 * 它的运动是类似一个球落向地板又弹起后,几次逐渐减小的回弹运动。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static bounceOut(t: number, b: number, c: number, d: number): number; /** * 开始时往后运动,然后反向朝目标移动。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @param s 指定过冲量,此处数值越大,过冲越大。 * @return 指定时间的插补属性的值。 */ static backIn(t: number, b: number, c: number, d: number, s?: number): number; /** * 开始运动时是向后跟踪,再倒转方向并朝目标移动,稍微过冲目标,然后再次倒转方向,回来朝目标移动。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @param s 指定过冲量,此处数值越大,过冲越大。 * @return 指定时间的插补属性的值。 */ static backInOut(t: number, b: number, c: number, d: number, s?: number): number; /** * 开始运动时是朝目标移动,稍微过冲,再倒转方向回来朝着目标。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @param s 指定过冲量,此处数值越大,过冲越大。 * @return 指定时间的插补属性的值。 */ static backOut(t: number, b: number, c: number, d: number, s?: number): number; /** * 方法以零速率开始运动,然后在执行时加快运动速度。 * 其中的运动由按照指数方式衰减的正弦波来定义。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @param a 指定正弦波的幅度。 * @param p 指定正弦波的周期。 * @return 指定时间的插补属性的值。 */ static elasticIn(t: number, b: number, c: number, d: number, a?: number, p?: number): number; /** * 开始运动时速率为零,先对运动进行加速,再减速直到速率为零。 * 其中的运动由按照指数方式衰减的正弦波来定义。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @param a 指定正弦波的幅度。 * @param p 指定正弦波的周期。 * @return 指定时间的插补属性的值。 */ static elasticInOut(t: number, b: number, c: number, d: number, a?: number, p?: number): number; /** * 以较快速度开始运动,然后在执行时减慢运动速度,直至速率为零。 * 其中的运动由按照指数方式衰减的正弦波来定义。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @param a 指定正弦波的幅度。 * @param p 指定正弦波的周期。 * @return 指定时间的插补属性的值。 */ static elasticOut(t: number, b: number, c: number, d: number, a?: number, p?: number): number; /** * 以零速率开始运动,然后在执行时加快运动速度。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static strongIn(t: number, b: number, c: number, d: number): number; /** * 开始运动时速率为零,先对运动进行加速,再减速直到速率为零。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static strongInOut(t: number, b: number, c: number, d: number): number; /** * 以较快速度开始运动,然后在执行时减慢运动速度,直至速率为零。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static strongOut(t: number, b: number, c: number, d: number): number; /** * 开始运动时速率为零,先对运动进行加速,再减速直到速率为零。 * Sine 缓动方程中的运动加速度小于 Quad 方程中的运动加速度。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static sineInOut(t: number, b: number, c: number, d: number): number; /** * 以零速率开始运动,然后在执行时加快运动速度。 * Sine 缓动方程中的运动加速度小于 Quad 方程中的运动加速度。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static sineIn(t: number, b: number, c: number, d: number): number; /** * 以较快速度开始运动,然后在执行时减慢运动速度,直至速率为零。 * Sine 缓动方程中的运动加速度小于 Quad 方程中的运动加速度。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static sineOut(t: number, b: number, c: number, d: number): number; /** * 以零速率开始运动,然后在执行时加快运动速度。 * Quint 缓动方程的运动加速大于 Quart 缓动方程。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static quintIn(t: number, b: number, c: number, d: number): number; /** * 开始运动时速率为零,先对运动进行加速,再减速直到速率为零。 * Quint 缓动方程的运动加速大于 Quart 缓动方程。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static quintInOut(t: number, b: number, c: number, d: number): number; /** * 以较快速度开始运动,然后在执行时减慢运动速度,直至速率为零。 * Quint 缓动方程的运动加速大于 Quart 缓动方程。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static quintOut(t: number, b: number, c: number, d: number): number; /** * 方法以零速率开始运动,然后在执行时加快运动速度。 * Quart 缓动方程的运动加速大于 Cubic 缓动方程。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static quartIn(t: number, b: number, c: number, d: number): number; /** * 开始运动时速率为零,先对运动进行加速,再减速直到速率为零。 * Quart 缓动方程的运动加速大于 Cubic 缓动方程。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static quartInOut(t: number, b: number, c: number, d: number): number; /** * 以较快速度开始运动,然后在执行时减慢运动速度,直至速率为零。 * Quart 缓动方程的运动加速大于 Cubic 缓动方程。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static quartOut(t: number, b: number, c: number, d: number): number; /** * 方法以零速率开始运动,然后在执行时加快运动速度。 * Cubic 缓动方程的运动加速大于 Quad 缓动方程。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static cubicIn(t: number, b: number, c: number, d: number): number; /** * 开始运动时速率为零,先对运动进行加速,再减速直到速率为零。 * Cubic 缓动方程的运动加速大于 Quad 缓动方程。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static cubicInOut(t: number, b: number, c: number, d: number): number; /** * 以较快速度开始运动,然后在执行时减慢运动速度,直至速率为零。 * Cubic 缓动方程的运动加速大于 Quad 缓动方程。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static cubicOut(t: number, b: number, c: number, d: number): number; /** * 方法以零速率开始运动,然后在执行时加快运动速度。 * Quad 缓动方程中的运动加速度等于 100% 缓动的时间轴补间的运动加速度,并且显著小于 Cubic 缓动方程中的运动加速度。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static quadIn(t: number, b: number, c: number, d: number): number; /** * 开始运动时速率为零,先对运动进行加速,再减速直到速率为零。 * Quad 缓动方程中的运动加速度等于 100% 缓动的时间轴补间的运动加速度,并且显著小于 Cubic 缓动方程中的运动加速度。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static quadInOut(t: number, b: number, c: number, d: number): number; /** * 以较快速度开始运动,然后在执行时减慢运动速度,直至速率为零。 * Quad 缓动方程中的运动加速度等于 100% 缓动的时间轴补间的运动加速度,并且显著小于 Cubic 缓动方程中的运动加速度。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static quadOut(t: number, b: number, c: number, d: number): number; /** * 方法以零速率开始运动,然后在执行时加快运动速度。 * 其中每个时间间隔是剩余距离减去一个固定比例部分。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static expoIn(t: number, b: number, c: number, d: number): number; /** * 开始运动时速率为零,先对运动进行加速,再减速直到速率为零。 * 其中每个时间间隔是剩余距离减去一个固定比例部分。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static expoInOut(t: number, b: number, c: number, d: number): number; /** * 以较快速度开始运动,然后在执行时减慢运动速度,直至速率为零。 * 其中每个时间间隔是剩余距离减去一个固定比例部分。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static expoOut(t: number, b: number, c: number, d: number): number; /** * 方法以零速率开始运动,然后在执行时加快运动速度。 * 缓动方程的运动加速会产生突然的速率变化。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static circIn(t: number, b: number, c: number, d: number): number; /** * 开始运动时速率为零,先对运动进行加速,再减速直到速率为零。 * 缓动方程的运动加速会产生突然的速率变化。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static circInOut(t: number, b: number, c: number, d: number): number; /** * 以较快速度开始运动,然后在执行时减慢运动速度,直至速率为零。 * 缓动方程的运动加速会产生突然的速率变化。 * @param t 指定当前时间,介于 0 和持续时间之间(包括二者)。 * @param b 指定动画属性的初始值。 * @param c 指定动画属性的更改总计。 * @param d 指定运动的持续时间。 * @return 指定时间的插补属性的值。 */ static circOut(t: number, b: number, c: number, d: number): number; } } declare module laya.utils { import FrameAnimation = laya.display.FrameAnimation; import Graphics = laya.display.Graphics; import Matrix = laya.maths.Matrix; /** * @private */ class GraphicAnimation extends FrameAnimation { /** * @private */ animationList: Array; /** * @private */ animationDic: any; protected _nodeList: Array; protected _nodeDefaultProps: any; protected _gList: Array; protected _nodeIDAniDic: any; protected static _temParam: Array; protected _createFrameGraphic(frame: number): any; protected _nodeGDic: any; protected _updateNodeGraphic(node: any, frame: number, parentTransfrom: Matrix, g: Graphics, alpha?: number): void; protected _updateNoChilds(tNodeG: GraphicNode, g: Graphics): void; protected _updateNodeGraphic2(node: any, frame: number, g: Graphics): void; protected _calculateNodeKeyFrames(node: any): void; protected getNodeDataByID(nodeID: number): any; protected _getParams(obj: any, params: Array, frame: number, obj2: any): Array; protected _getNodeGraphicData(nodeID: number, frame: number, rst: GraphicNode): GraphicNode; protected _getTextureByUrl(url: string): any; /** * @private */ setAniData(uiView: any, aniName?: string): void; parseByData(aniData: any): any; /** * @private */ setUpAniData(uiView: any): void; protected _clear(): void; static parseAnimationByData(animationObject: any): any; static parseAnimationData(aniData: any): any; } class GraphicNode { skin: string; transform: Matrix; resultTransform: Matrix; width: number; height: number; alpha: number; recover(): void; static create(): GraphicNode; } } declare module laya.utils { /** *

    Handler 是事件处理器类。

    *

    推荐使用 Handler.create() 方法从对象池创建,减少对象创建消耗。创建的 Handler 对象不再使用后,可以使用 Handler.recover() 将其回收到对象池,回收后不要再使用此对象,否则会导致不可预料的错误。

    *

    注意:由于鼠标事件也用本对象池,不正确的回收及调用,可能会影响鼠标事件的执行。

    */ class Handler { /** 执行域(this)。*/ caller: any; /** 处理方法。*/ method: Function; /** 参数。*/ args: Array; /** 表示是否只执行一次。如果为true,回调后执行recover()进行回收,回收后会被再利用,默认为false 。*/ once: boolean; protected _id: number; /** * 根据指定的属性值,创建一个 Handler 类的实例。 * @param caller 执行域。 * @param method 处理函数。 * @param args 函数参数。 * @param once 是否只执行一次。 */ constructor(caller?: any, method?: Function, args?: Array, once?: boolean); /** * 设置此对象的指定属性值。 * @param caller 执行域(this)。 * @param method 回调方法。 * @param args 携带的参数。 * @param once 是否只执行一次,如果为true,执行后执行recover()进行回收。 * @return 返回 handler 本身。 */ setTo(caller: any, method: Function, args: Array, once: boolean): Handler; /** * 执行处理器。 */ run(): any; /** * 执行处理器,携带额外数据。 * @param data 附加的回调数据,可以是单数据或者Array(作为多参)。 */ runWith(data: any): any; /** * 清理对象引用。 */ clear(): Handler; /** * 清理并回收到 Handler 对象池内。 */ recover(): void; /** * 从对象池内创建一个Handler,默认会执行一次并立即回收,如果不需要自动回收,设置once参数为false。 * @param caller 执行域(this)。 * @param method 回调方法。 * @param args 携带的参数。 * @param once 是否只执行一次,如果为true,回调后执行recover()进行回收,默认为true。 * @return 返回创建的handler实例。 */ static create(caller: any, method: Function, args?: Array, once?: boolean): Handler; } } declare module laya.utils { import Graphics = laya.display.Graphics; /** * 鼠标点击区域,可以设置绘制一系列矢量图作为点击区域和非点击区域(目前只支持圆形,矩形,多边形) */ class HitArea { /** * 是否包含某个点 * @param x x坐标 * @param y y坐标 * @return 是否点击到 */ isHit(x: number, y: number): boolean; /** * 检测对象是否包含指定的点。 * @param x 点的 X 轴坐标值(水平位置)。 * @param y 点的 Y 轴坐标值(垂直位置)。 * @return 如果包含指定的点,则值为 true;否则为 false。 */ contains(x: number, y: number): boolean; /** * @private * 是否击中Graphic */ static isHitGraphic(x: number, y: number, graphic: Graphics): boolean; /** * @private * 是否击中绘图指令 */ static isHitCmd(x: number, y: number, cmd: Array): boolean; /** * @private * 坐标是否在多边形内 */ static ptInPolygon(x: number, y: number, areaPoints: Array): boolean; /** * 可点击区域,可以设置绘制一系列矢量图作为点击区域(目前只支持圆形,矩形,多边形) */ hit: Graphics; /** * 不可点击区域,可以设置绘制一系列矢量图作为非点击区域(目前只支持圆形,矩形,多边形) */ unHit: Graphics; } } declare module laya.utils { import CSSStyle = laya.display.css.CSSStyle; import ILayout = laya.display.ILayout; import Sprite = laya.display.Sprite; /** * @private * HTMLChar 是一个 HTML 字符类。 */ class HTMLChar implements ILayout { /** 表示是否是正常单词(英文|.|数字)。*/ isWord: boolean; /** 字符。*/ char: string; /** 字符数量。*/ charNum: number; /** CSS 样式。*/ style: CSSStyle; /** * 根据指定的字符、宽高、样式,创建一个 HTMLChar 类的实例。 * @param char 字符。 * @param w 宽度。 * @param h 高度。 * @param style CSS 样式。 */ constructor(char: string, w: number, h: number, style: CSSStyle); /** * 设置与此对象绑定的显示对象 Sprite 。 * @param sprite 显示对象 Sprite 。 */ setSprite(sprite: Sprite): void; /** * 获取与此对象绑定的显示对象 Sprite。 * @return */ getSprite(): Sprite; /** * 此对象存储的 X 轴坐标值。 * 当设置此值时,如果此对象有绑定的 Sprite 对象,则改变 Sprite 对象的属性 x 的值。 */ x: number; /** * 此对象存储的 Y 轴坐标值。 * 当设置此值时,如果此对象有绑定的 Sprite 对象,则改变 Sprite 对象的属性 y 的值。 */ y: number; /** * 宽度。 */ width: number; /** * 高度。 */ height: number; _isChar(): boolean; _getCSSStyle(): CSSStyle; } } declare module laya.utils { /** * Log 类用于在界面内显示日志记录信息。 */ class Log { /**最大打印数量,超过这个数量,则自动清理一次*/ static maxCount: number; /** * 激活Log系统,使用方法Laya.init(800,600,Laya.Log); */ static enable(): void; /**隐藏/显示日志面板*/ static toggle(): void; /** * 增加日志内容。 * @param value 需要增加的日志内容。 */ static print(value: string): void; /** * 清理日志 */ static clear(): void; } } declare module laya.utils { /** * Mouse 类用于控制鼠标光标。 */ class Mouse { constructor(); /** * 设置鼠标样式 * @param cursorStr * 例如auto move no-drop col-resize * all-scroll pointer not-allowed row-resize * crosshair progress e-resize ne-resize * default text n-resize nw-resize * help vertical-text s-resize se-resize * inherit wait w-resize sw-resize * */ static cursor: string; /** * 隐藏鼠标 * */ static hide(): void; /** * 显示鼠标 * */ static show(): void; } } declare module laya.utils { /** *

    Pool 是对象池类,用于对象的存贮、重复使用。

    *

    合理使用对象池,可以有效减少对象创建的开销,避免频繁的垃圾回收,从而优化游戏流畅度。

    */ class Pool { /** * 根据对象类型标识字符,获取对象池。 * @param sign 对象类型标识字符。 * @return 对象池。 */ static getPoolBySign(sign: string): Array; /** * 清除对象池的对象。 * @param sign 对象类型标识字符。 */ static clearBySign(sign: string): void; /** * 将对象放到对应类型标识的对象池中。 * @param sign 对象类型标识字符。 * @param item 对象。 */ static recover(sign: string, item: any): void; /** *

    根据传入的对象类型标识字符,获取对象池中此类型标识的一个对象实例。

    *

    当对象池中无此类型标识的对象时,则根据传入的类型,创建一个新的对象返回。

    * @param sign 对象类型标识字符。 * @param cls 用于创建该类型对象的类。 * @return 此类型标识的一个对象。 */ static getItemByClass(sign: string, cls: any): any; /** *

    根据传入的对象类型标识字符,获取对象池中此类型标识的一个对象实例。

    *

    当对象池中无此类型标识的对象时,则使用传入的创建此类型对象的函数,新建一个对象返回。

    * @param sign 对象类型标识字符。 * @param createFun 用于创建该类型对象的方法。 * @return 此类型标识的一个对象。 */ static getItemByCreateFun(sign: string, createFun: Function): any; /** * 根据传入的对象类型标识字符,获取对象池中已存储的此类型的一个对象,如果对象池中无此类型的对象,则返回 null 。 * @param sign 对象类型标识字符。 * @return 对象池中此类型的一个对象,如果对象池中无此类型的对象,则返回 null 。 */ static getItem(sign: string): any; } } declare module laya.utils { /** * @private * 基于个数的对象缓存管理器 */ class PoolCache { /** * 对象在Pool中的标识 */ sign: string; /** * 允许缓存的最大数量 */ maxCount: number; /** * 获取缓存的对象列表 * @return * */ getCacheList(): Array; /** * 尝试清理缓存 * @param force 是否强制清理 * */ tryDispose(force: boolean): void; /** * 添加对象缓存管理 * @param sign 对象在Pool中的标识 * @param maxCount 允许缓存的最大数量 * */ static addPoolCacheManager(sign: string, maxCount?: number): void; } } declare module laya.utils { /** * @private */ class RunDriver { /** * 滤镜动作集。 */ static FILTER_ACTIONS: Array; static now: Function; static getWindow: Function; static getPixelRatio: Function; static getIncludeStr: Function; static createShaderCondition: Function; static measureText: Function; /** * @private */ static getWebGLContext: Function; /** * 开始函数。 */ static beginFlush: Function; static endFinish: Function; /** * 添加至图集的处理函数。 */ static addToAtlas: Function; static flashFlushImage: Function; /** * 绘制到画布。 */ static drawToCanvas: Function; /** * 创建2D例子模型的处理函数。 */ static createParticleTemplate2D: Function; /** * 用于创建 WebGL 纹理。 */ static createGLTextur: Function; /** * 用于创建 WebGLContext2D 对象。 */ static createWebGLContext2D: Function; /** * 用于改变 WebGL宽高信息。 */ static changeWebGLSize: Function; /** * 用于创建 RenderSprite 对象。 */ static createRenderSprite: Function; /** * 用于创建滤镜动作。 */ static createFilterAction: Function; /** * 用于创建 Graphics 对象。 */ static createGraphics: Function; static clear: Function; /** * 清空纹理函数。 */ static cancelLoadByUrl: Function; /** * 清空纹理函数。 */ static clearAtlas: Function; static isAtlas: Function; static addTextureToAtlas: Function; static getTexturePixels: Function; static skinAniSprite: Function; static update3DLoop: Function; } } declare module laya.utils { import Sprite = laya.display.Sprite; /** *

    Stat 是一个性能统计面板,可以实时更新相关的性能参数。

    *

    参与统计的性能参数如下(所有参数都是每大约1秒进行更新):
    * FPS(Canvas)/FPS(WebGL):Canvas 模式或者 WebGL 模式下的帧频,也就是每秒显示的帧数,值越高、越稳定,感觉越流畅;
    * Sprite:统计所有渲染节点(包括容器)数量,它的大小会影响引擎进行节点遍历、数据组织和渲染的效率。其值越小,游戏运行效率越高;
    * DrawCall:此值是决定性能的重要指标,其值越小,游戏运行效率越高。Canvas模式下表示每大约1秒的图像绘制次数;WebGL模式下表示每大约1秒的渲染提交批次,每次准备数据并通知GPU渲染绘制的过程称为1次DrawCall,在每次DrawCall中除了在通知GPU的渲染上比较耗时之外,切换材质与shader也是非常耗时的操作;
    * CurMem:Canvas模式下,表示内存占用大小,值越小越好,过高会导致游戏闪退;WebGL模式下,表示内存与显存的占用,值越小越好;
    * Shader:是 WebGL 模式独有的性能指标,表示每大约1秒 Shader 提交次数,值越小越好;
    * Canvas:由三个数值组成,只有设置 CacheAs 后才会有值,默认为0/0/0。从左到右数值的意义分别为:每帧重绘的画布数量 / 缓存类型为"normal"类型的画布数量 / 缓存类型为"bitmap"类型的画布数量。

    */ class Stat { /** 每秒帧数。*/ static FPS: number; /**主舞台 Stage 渲染次数计数。 */ static loopCount: number; /** 着色器请求次数。*/ static shaderCall: number; /** 描绘次数。*/ static drawCall: number; /** 三角形面数。*/ static trianglesFaces: number; /** 精灵Sprite 的数量。*/ static spriteCount: number; /** 精灵渲染使用缓存Sprite 的数量。*/ static spriteRenderUseCacheCount: number; /** 八叉树节点检测次数。*/ static treeNodeCollision: number; /** 八叉树精灵碰撞检测次数。*/ static treeSpriteCollision: number; /** 画布 canvas 使用标准渲染的次数。*/ static canvasNormal: number; /** 画布 canvas 使用位图渲染的次数。*/ static canvasBitmap: number; /** 画布 canvas 缓冲区重绘次数。*/ static canvasReCache: number; /** 表示当前使用的是否为慢渲染模式。*/ static renderSlow: boolean; /** 资源管理器所管理资源的累计内存,以字节为单位。*/ static currentMemorySize: number; static _sp: Sprite; static _show: boolean; static _useCanvas: boolean; /** * 显示性能统计信息。 * @param x X轴显示位置。 * @param y Y轴显示位置。 */ static show(x?: number, y?: number): void; /**激活性能统计*/ static enable(): void; /** * 隐藏性能统计信息。 */ static hide(): void; /** * @private * 清零性能统计计算相关的数据。 */ static clear(): void; /** * 点击性能统计显示区域的处理函数。 */ static onclick: Function; /** * @private * 性能统计参数计算循环处理函数。 */ static loop(): void; } } declare module laya.utils { /** * @private * StringKey 类用于存取字符串对应的数字。 */ class StringKey { /** * 添加一个字符。 * @param str 字符,将作为key 存储相应生成的数字。 * @return 此字符对应的数字。 */ add(str: string): number; /** * 获取指定字符对应的ID。 * @param str 字符。 * @return 此字符对应的ID。 */ getID(str: string): number; /** * 根据指定ID获取对应字符。 * @param id ID。 * @return 此id对应的字符。 */ getName(id: number): string; } } declare module laya.utils { import EventDispatcher = laya.events.EventDispatcher; /** * TimeLine 是一个用来创建时间轴动画的类。 */ class TimeLine extends EventDispatcher { /** 缩放动画播放的速度。*/ scale: number; /** * 控制一个对象,从当前点移动到目标点。 * @param target 要控制的对象。 * @param props 要控制对象的属性。 * @param duration 对象TWEEN的时间。 * @param ease 缓动类型 * @param offset 相对于上一个对象,偏移多长时间(单位:毫秒)。 */ static to(target: any, props: any, duration: number, ease?: Function, offset?: number): TimeLine; /** * 从 props 属性,缓动到当前状态。 * @param target target 目标对象(即将更改属性值的对象) * @param props 要控制对象的属性 * @param duration 对象TWEEN的时间 * @param ease 缓动类型 * @param offset 相对于上一个对象,偏移多长时间(单位:毫秒) */ static from(target: any, props: any, duration: number, ease?: Function, offset?: number): TimeLine; /** * 控制一个对象,从当前点移动到目标点。 * @param target 要控制的对象。 * @param props 要控制对象的属性。 * @param duration 对象TWEEN的时间。 * @param ease 缓动类型 * @param offset 相对于上一个对象,偏移多长时间(单位:毫秒)。 */ to(target: any, props: any, duration: number, ease?: Function, offset?: number): TimeLine; /** * 从 props 属性,缓动到当前状态。 * @param target target 目标对象(即将更改属性值的对象) * @param props 要控制对象的属性 * @param duration 对象TWEEN的时间 * @param ease 缓动类型 * @param offset 相对于上一个对象,偏移多长时间(单位:毫秒) */ from(target: any, props: any, duration: number, ease?: Function, offset?: number): TimeLine; /** * 在时间队列中加入一个标签。 * @param label 标签名称。 * @param offset 标签相对于上个动画的偏移时间(单位:毫秒)。 */ addLabel(label: string, offset: number): TimeLine; /** * 移除指定的标签 * @param label */ removeLabel(label: string): void; /** * 动画从整个动画的某一时间开始。 * @param time(单位:毫秒)。 */ gotoTime(time: number): void; /** * 从指定的标签开始播。 * @param Label 标签名。 */ gotoLabel(Label: string): void; /** * 暂停整个动画。 */ pause(): void; /** * 恢复暂停动画的播放。 */ resume(): void; /** * 播放动画。 * @param timeOrLabel 开启播放的时间点或标签名。 * @param loop 是否循环播放。 */ play(timeOrLabel?: any, loop?: boolean): void; /** * @private * 得到帧索引 */ /** * @private * 设置帧索引 */ index: number; /** * 得到总帧数。 */ readonly total: number; /** * 重置所有对象,复用对象的时候使用。 */ reset(): void; /** * 彻底销毁此对象。 */ destroy(): void; } class tweenData { type: number; isTo: boolean; startTime: number; endTime: number; target: any; duration: number; ease: Function; data: any; destroy(): void; } } declare module laya.utils { /** * Timer 是时钟管理类。它是一个单例,不要手动实例化此类,应该通过 Laya.timer 访问。 */ class Timer { /** 时针缩放。*/ scale: number; /** 当前帧开始的时间。*/ currTimer: number; /** 当前的帧数。*/ currFrame: number; /** *两帧之间的时间间隔,单位毫秒。 */ readonly delta: number; /** * 创建 Timer 类的一个实例。 */ constructor(); protected _init(): void; protected _now(): number; /** * @private * 帧循环处理函数。 */ _update(): void; _create(useFrame: boolean, repeat: boolean, delay: number, caller: any, method: Function, args: Array, coverBefore: boolean): TimerHandler; /** * 定时执行一次。 * @param delay 延迟时间(单位为毫秒)。 * @param caller 执行域(this)。 * @param method 定时器回调函数。 * @param args 回调参数。 * @param coverBefore 是否覆盖之前的延迟执行,默认为 true 。 */ once(delay: number, caller: any, method: Function, args?: Array, coverBefore?: boolean): void; /** * 定时重复执行。 * @param delay 间隔时间(单位毫秒)。 * @param caller 执行域(this)。 * @param method 定时器回调函数。 * @param args 回调参数。 * @param coverBefore 是否覆盖之前的延迟执行,默认为 true 。 * @param jumpFrame 时钟是否跳帧。基于时间的循环回调,单位时间间隔内,如能执行多次回调,出于性能考虑,引擎默认只执行一次,设置jumpFrame=true后,则回调会连续执行多次 */ loop(delay: number, caller: any, method: Function, args?: Array, coverBefore?: boolean, jumpFrame?: boolean): void; /** * 定时执行一次(基于帧率)。 * @param delay 延迟几帧(单位为帧)。 * @param caller 执行域(this)。 * @param method 定时器回调函数。 * @param args 回调参数。 * @param coverBefore 是否覆盖之前的延迟执行,默认为 true 。 */ frameOnce(delay: number, caller: any, method: Function, args?: Array, coverBefore?: boolean): void; /** * 定时重复执行(基于帧率)。 * @param delay 间隔几帧(单位为帧)。 * @param caller 执行域(this)。 * @param method 定时器回调函数。 * @param args 回调参数。 * @param coverBefore 是否覆盖之前的延迟执行,默认为 true 。 */ frameLoop(delay: number, caller: any, method: Function, args?: Array, coverBefore?: boolean): void; /** 返回统计信息。*/ toString(): string; /** * 清理定时器。 * @param caller 执行域(this)。 * @param method 定时器回调函数。 */ clear(caller: any, method: Function): void; /** * 清理对象身上的所有定时器。 * @param caller 执行域(this)。 */ clearAll(caller: any): void; /** * 延迟执行。 * @param caller 执行域(this)。 * @param method 定时器回调函数。 * @param args 回调参数。 */ callLater(caller: any, method: Function, args?: Array): void; /** * 立即执行 callLater 。 * @param caller 执行域(this)。 * @param method 定时器回调函数。 */ runCallLater(caller: any, method: Function): void; /** * 立即提前执行定时器,执行之后从队列中删除 * @param caller 执行域(this)。 * @param method 定时器回调函数。 */ runTimer(caller: any, method: Function): void; } class TimerHandler { key: number; repeat: boolean; delay: number; userFrame: boolean; exeTime: number; caller: any; method: Function; args: Array; jumpFrame: boolean; clear(): void; run(withClear: boolean): void; } } declare module laya.utils { /** * Tween 是一个缓动类。使用此类能够实现对目标对象属性的渐变。 */ class Tween { gid: number; /**更新回调,缓动数值发生变化时,回调变化的值*/ update: Handler; /** * 缓动对象的props属性到目标值。 * @param target 目标对象(即将更改属性值的对象)。 * @param props 变化的属性列表,比如 * @param duration 花费的时间,单位毫秒。 * @param ease 缓动类型,默认为匀速运动。 * @param complete 结束回调函数。 * @param delay 延迟执行时间。 * @param coverBefore 是否覆盖之前的缓动。 * @param autoRecover 是否自动回收,默认为true,缓动结束之后自动回收到对象池。 * @return 返回Tween对象。 */ static to(target: any, props: any, duration: number, ease?: Function, complete?: Handler, delay?: number, coverBefore?: boolean, autoRecover?: boolean): Tween; /** * 从props属性,缓动到当前状态。 * @param target 目标对象(即将更改属性值的对象)。 * @param props 变化的属性列表,比如 * @param duration 花费的时间,单位毫秒。 * @param ease 缓动类型,默认为匀速运动。 * @param complete 结束回调函数。 * @param delay 延迟执行时间。 * @param coverBefore 是否覆盖之前的缓动。 * @param autoRecover 是否自动回收,默认为true,缓动结束之后自动回收到对象池。 * @return 返回Tween对象。 */ static from(target: any, props: any, duration: number, ease?: Function, complete?: Handler, delay?: number, coverBefore?: boolean, autoRecover?: boolean): Tween; /** * 缓动对象的props属性到目标值。 * @param target 目标对象(即将更改属性值的对象)。 * @param props 变化的属性列表,比如 * @param duration 花费的时间,单位毫秒。 * @param ease 缓动类型,默认为匀速运动。 * @param complete 结束回调函数。 * @param delay 延迟执行时间。 * @param coverBefore 是否覆盖之前的缓动。 * @return 返回Tween对象。 */ to(target: any, props: any, duration: number, ease?: Function, complete?: Handler, delay?: number, coverBefore?: boolean): Tween; /** * 从props属性,缓动到当前状态。 * @param target 目标对象(即将更改属性值的对象)。 * @param props 变化的属性列表,比如 * @param duration 花费的时间,单位毫秒。 * @param ease 缓动类型,默认为匀速运动。 * @param complete 结束回调函数。 * @param delay 延迟执行时间。 * @param coverBefore 是否覆盖之前的缓动。 * @return 返回Tween对象。 */ from(target: any, props: any, duration: number, ease?: Function, complete?: Handler, delay?: number, coverBefore?: boolean): Tween; _create(target: any, props: any, duration: number, ease: Function, complete: Handler, delay: number, coverBefore: boolean, isTo: boolean, usePool: boolean, runNow: boolean): Tween; _updateEase(time: number): void; /**设置当前执行比例**/ progress: number; /** * 立即结束缓动并到终点。 */ complete(): void; /** * 暂停缓动,可以通过resume或restart重新开始。 */ pause(): void; /** * 设置开始时间。 * @param startTime 开始时间。 */ setStartTime(startTime: number): void; /** * 清理指定目标对象上的所有缓动。 * @param target 目标对象。 */ static clearAll(target: any): void; /** * 清理某个缓动。 * @param tween 缓动对象。 */ static clear(tween: Tween): void; static clearTween(target: any): void; /** * 停止并清理当前缓动。 */ clear(): void; /** * @private */ _clear(): void; /** 回收到对象池。*/ recover(): void; /** * 重新开始暂停的缓动。 */ restart(): void; /** * 恢复暂停的缓动。 */ resume(): void; } } declare module laya.utils { import Sprite = laya.display.Sprite; import Rectangle = laya.maths.Rectangle; /** * Utils 是工具类。 */ class Utils { protected static _extReg: RegExp; /** * 角度转弧度。 * @param angle 角度值。 * @return 返回弧度值。 */ static toRadian(angle: number): number; /** * 弧度转换为角度。 * @param radian 弧度值。 * @return 返回角度值。 */ static toAngle(radian: number): number; /** * 将传入的 uint 类型颜色值转换为字符串型颜色值。 * @param color 颜色值。 * @return 字符串型颜色值。 */ static toHexColor(color: number): string; /**获取一个全局唯一ID。*/ static getGID(): number; /** * 将字符串解析成 XML 对象。 * @param value 需要解析的字符串。 * @return js原生的XML对象。 */ static parseXMLFromString: Function; /** * @private *

    连接数组。和array的concat相比,此方法不创建新对象

    * 注意:若 参数 a 不为空,则会改变参数 source 的值为连接后的数组。 * @param source 待连接的数组目标对象。 * @param array 待连接的数组对象。 * @return 连接后的数组。 */ static concatArray(source: Array, array: Array): Array; /** * @private * 清空数组对象。 * @param array 数组。 * @return 清空后的 array 对象。 */ static clearArray(array: Array): Array; /** * @private * 清空source数组,复制array数组的值。 * @param source 需要赋值的数组。 * @param array 新的数组值。 * @return 复制后的数据 source 。 */ static copyArray(source: Array, array: Array): Array; /** * @private * 根据传入的显示对象 Sprite 和此显示对象上的 两个点,返回此对象上的两个点在舞台坐标系上组成的最小的矩形区域对象。 * @param sprite 显示对象 Sprite。 * @param x0 点一的 X 轴坐标点。 * @param y0 点一的 Y 轴坐标点。 * @param x1 点二的 X 轴坐标点。 * @param y1 点二的 Y 轴坐标点。 * @return 两个点在舞台坐标系组成的矩形对象 Rectangle。 */ static getGlobalRecByPoints(sprite: Sprite, x0: number, y0: number, x1: number, y1: number): Rectangle; /** * 计算传入的显示对象 Sprite 的全局坐标系的坐标和缩放值,返回 Rectangle 对象存放计算出的坐标X值、Y值、ScaleX值、ScaleY值。 * @param sprite Sprite 对象。 * @return 矩形对象 Rectangle */ static getGlobalPosAndScale(sprite: Sprite): Rectangle; /** * 给传入的函数绑定作用域,返回绑定后的函数。 * @param fun 函数对象。 * @param scope 函数作用域。 * @return 绑定后的函数。 */ static bind(fun: Function, scope: any): Function; /** * 测量文本在指定样式下的宽度、高度信息。 * @param txt 文本内容。 * @param font 文本字体样式。 * @return 文本的宽高信息对象。如: */ static measureText(txt: string, font: string): any; /** * @private * 对传入的数组列表,根据子项的属性 Z 值进行重新排序。返回是否已重新排序的 Boolean 值。 * @param array 子对象数组。 * @return Boolean 值,表示是否已重新排序。 */ static updateOrder(array: Array): boolean; /** * @private * 批量移动点坐标。 * @param points 坐标列表。 * @param x x轴偏移量。 * @param y y轴偏移量。 */ static transPointList(points: Array, x: number, y: number): void; /** * 解析一个字符串,并返回一个整数。和JS原生的parseInt不同:如果str为空或者非数字,原生返回NaN,这里返回0。 * @param str 要被解析的字符串。 * @param radix 表示要解析的数字的基数。默认值为0,表示10进制,其他值介于 2 ~ 36 之间。如果它以 “0x” 或 “0X” 开头,将以 16 为基数。如果该参数不在上述范围内,则此方法返回 0。 * @return 返回解析后的数字。 */ static parseInt(str: string, radix?: number): number; static getFileExtension(path: string): string; /** * 获取指定区域内相对于窗口左上角的transform。 * @param coordinateSpace 坐标空间,不能是Stage引用 * @param x 相对于coordinateSpace的x坐标 * @param y 相对于coordinateSpace的y坐标 * @return */ static getTransformRelativeToWindow(coordinateSpace: Sprite, x: number, y: number): any; /** * 使DOM元素使用舞台内的某块区域内。 * @param dom DOM元素引用 * @param coordinateSpace 坐标空间,不能是Stage引用 * @param x 相对于coordinateSpace的x坐标 * @param y 相对于coordinateSpace的y坐标 * @param width 宽度 * @param height 高度 */ static fitDOMElementInArea(dom: any, coordinateSpace: Sprite, x: number, y: number, width: number, height: number): void; /** * @private * 是否是可用的Texture数组 * @param textureList * @return */ static isOkTextureList(textureList: Array): boolean; /** * @private * 是否是可用的绘图指令数组 * @param cmds * @return */ static isOKCmdList(cmds: Array): boolean; } } declare module laya.utils { /** * @private */ class VectorGraphManager { static instance: VectorGraphManager; useDic: any; shapeDic: any; shapeLineDic: any; constructor(); static getInstance(): VectorGraphManager; /** * 得到个空闲的ID * @return */ getId(): number; /** * 添加一个图形到列表中 * @param id * @param shape */ addShape(id: number, shape: any): void; /** * 添加一个线图形到列表中 * @param id * @param Line */ addLine(id: number, Line: any): void; /** * 检测一个对象是否在使用中 * @param id */ getShape(id: number): void; /** * 删除一个图形对象 * @param id */ deleteShape(id: number): void; /** * 得到缓存列表 * @return */ getCacheList(): Array; /** * 开始清理状态,准备销毁 */ startDispose(key: boolean): void; /** * 确认销毁 */ endDispose(): void; } } declare module laya.utils { /** * 封装弱引用WeakMap * 如果支持WeakMap,则使用WeakMap,如果不支持,则用Object代替 * 注意:如果采用Object,为了防止内存泄漏,则采用定时清理缓存策略 */ class WeakObject { /**是否支持WeakMap*/ static supportWeakMap: boolean; /**如果不支持WeakMap,则多少时间清理一次缓存,默认5分钟清理一次*/ static delInterval: number; /**全局WeakObject单例*/ static I: WeakObject; _obj: any; static __init__(): void; /**清理缓存,回收内存*/ static clearCache(): void; constructor(); /** * 设置缓存 * @param key kye对象,可被回收 * @param value object对象,可被回收 */ set(key: any, value: any): void; /** * 获取缓存 * @param key kye对象,可被回收 */ get(key: any): any; /** * 删除缓存 */ del(key: any): void; /** * 是否有缓存 */ has(key: any): boolean; } } declare module laya.utils { /** * @private */ class WordText { id: number; save: Array; toUpperCase: string; changed: boolean; setText(txt: string): void; toString(): string; readonly length: number; charCodeAt(i: number): number; charAt(i: number): string; } } declare module laya.webgl.atlas { import Texture = laya.resource.Texture; import IMergeAtlasBitmap = laya.webgl.resource.IMergeAtlasBitmap; class Atlaser extends AtlasGrid { _inAtlasTextureKey: Array; _inAtlasTextureBitmapValue: Array; _inAtlasTextureOriUVValue: Array; readonly texture: AtlasWebGLCanvas; readonly inAtlasWebGLImagesKey: any; readonly InAtlasWebGLImagesOffsetValue: Array; constructor(gridNumX: number, gridNumY: number, width: number, height: number, atlasID: number); findBitmapIsExist(bitmap: any): number; /** * * @param inAtlasRes * @return 是否已经存在队列中 */ addToAtlasTexture(mergeAtlasBitmap: IMergeAtlasBitmap, offsetX: number, offsetY: number): void; addToAtlas(texture: Texture, offsetX: number, offsetY: number): void; clear(): void; dispose(): void; } } declare module laya.webgl.atlas { class AtlasGrid { _atlasID: number; constructor(width?: number, height?: number, atlasID?: number); getAltasID(): number; setAltasID(atlasID: number): void; addTex(type: number, width: number, height: number): MergeFillInfo; } class TexRowInfo { spaceCount: number; } class TexMergeTexSize { width: number; height: number; } } declare module laya.webgl.atlas { import Texture = laya.resource.Texture; class AtlasResourceManager { static gridSize: number; static atlasTextureWidth: number; static atlasTextureHeight: number; static maxTextureCount: number; static _atlasRestore: number; static BOARDER_TYPE_NO: number; static BOARDER_TYPE_RIGHT: number; static BOARDER_TYPE_LEFT: number; static BOARDER_TYPE_BOTTOM: number; static BOARDER_TYPE_TOP: number; static BOARDER_TYPE_ALL: number; static readonly instance: AtlasResourceManager; static readonly enabled: boolean; static atlasLimitWidth: number; static atlasLimitHeight: number; static _enable(): void; static _disable(): void; static __init__(): void; constructor(width: number, height: number, gridSize: number, maxTexNum: number); setAtlasParam(width: number, height: number, gridSize: number, maxTexNum: number): boolean; pushData(texture: Texture): boolean; addToAtlas(tex: Texture): void; /** * 回收大图合集,不建议手动调用 * @return */ garbageCollection(): boolean; freeAll(): void; getAtlaserCount(): number; getAtlaserByIndex(index: number): Atlaser; } } declare module laya.webgl.atlas { import Bitmap = laya.resource.Bitmap; import WebGLImage = laya.webgl.resource.WebGLImage; class AtlasWebGLCanvas extends Bitmap { _atlaser: Atlaser; /*** * 设置图片宽度 * @param value 图片宽度 */ width: number; /*** * 设置图片高度 * @param value 图片高度 */ height: number; constructor(); /**兼容Stage3D使用*/ _flashCacheImage: WebGLImage; _flashCacheImageNeedFlush: boolean; protected recreateResource(): void; protected disposeResource(): void; /**采样image到WebGLTexture的一部分*/ texSubImage2D(xoffset: number, yoffset: number, bitmap: any): void; /**采样image到WebGLTexture的一部分*/ texSubImage2DPixel(xoffset: number, yoffset: number, width: number, height: number, pixel: any): void; } } declare module laya.webgl.atlas { class MergeFillInfo { x: number; y: number; ret: boolean; constructor(); } } declare module laya.webgl.canvas { import WebGLContext = laya.webgl.WebGLContext; class BlendMode { static activeBlendFunction: Function; static NAMES: Array; static TOINT: any; static NORMAL: string; static ADD: string; static MULTIPLY: string; static SCREEN: string; static LIGHT: string; static OVERLAY: string; static DESTINATIONOUT: string; static fns: Array; static targetFns: Array; static _init_(gl: WebGLContext): void; static BlendNormal(gl: WebGLContext): void; static BlendAdd(gl: WebGLContext): void; static BlendMultiply(gl: WebGLContext): void; static BlendScreen(gl: WebGLContext): void; static BlendOverlay(gl: WebGLContext): void; static BlendLight(gl: WebGLContext): void; static BlendNormalTarget(gl: WebGLContext): void; static BlendAddTarget(gl: WebGLContext): void; static BlendMultiplyTarget(gl: WebGLContext): void; static BlendScreenTarget(gl: WebGLContext): void; static BlendOverlayTarget(gl: WebGLContext): void; static BlendLightTarget(gl: WebGLContext): void; static BlendMask(gl: WebGLContext): void; static BlendDestinationOut(gl: WebGLContext): void; } } declare module laya.webgl.canvas { import Color = laya.utils.Color; class DrawStyle { static DEFAULT: DrawStyle; _color: Color; static create(value: any): DrawStyle; constructor(value: any); setValue(value: any): void; reset(): void; equal(value: any): boolean; toColorStr(): string; } } declare module laya.webgl.canvas { import Rectangle = laya.maths.Rectangle; import IShape = laya.webgl.shapes.IShape; import IndexBuffer2D = laya.webgl.utils.IndexBuffer2D; import VertexBuffer2D = laya.webgl.utils.VertexBuffer2D; class Path { _x: number; _y: number; _rect: Rectangle; ib: IndexBuffer2D; vb: VertexBuffer2D; dirty: boolean; geomatrys: Array; _curGeomatry: IShape; offset: number; count: number; tempArray: Array; closePath: boolean; constructor(); addPoint(pointX: number, pointY: number): void; getEndPointX(): number; getEndPointY(): number; polygon(x: number, y: number, points: Array, color: number, borderWidth: number, borderColor: any): IShape; setGeomtry(shape: IShape): void; drawLine(x: number, y: number, points: Array, width: number, color: number): IShape; update(): void; reset(): void; recover(): void; } } declare module laya.webgl.display { import Graphics = laya.display.Graphics; import Shader = laya.webgl.shader.Shader; import Buffer2D = laya.webgl.utils.Buffer2D; class GraphicsGL extends Graphics { constructor(); setShader(shader: Shader): void; setIBVB(x: number, y: number, ib: Buffer2D, vb: Buffer2D, numElement: number, shader: Shader): void; drawParticle(x: number, y: number, ps: any): void; } } declare module laya.webgl.resource { interface IMergeAtlasBitmap { clearAtlasSource(): void; } } declare module laya.webgl.resource { import Bitmap = laya.resource.Bitmap; import Context = laya.resource.Context; class WebGLCanvas extends Bitmap { static _createContext: Function; flipY: boolean; premulAlpha: boolean; /**HTML Canvas*/ _canvas: any; _imgData: any; iscpuSource: boolean; alwaysChange: boolean; getCanvas(): any; clear(): void; destroy(): void; readonly context: Context; _setContext(context: Context): void; getContext(contextID: string, other?: any): Context; readonly source: any; size(w: number, h: number): void; asBitmap: boolean; activeResource(force?: boolean): void; protected recreateResource(): void; protected disposeResource(): void; texSubImage2D(webglCanvas: WebGLCanvas, xoffset: number, yoffset: number): void; toBase64(type: string, encoderOptions: number, callBack: Function): void; } } declare module laya.webgl.resource { import Bitmap = laya.resource.Bitmap; import Texture = laya.resource.Texture; class WebGLCharImage extends Bitmap implements IMergeAtlasBitmap { /**HTML Canvas,绘制字符载体,非私有数据载体*/ canvas: any; /**********************************************************************************/ cw: number; ch: number; xs: number; ys: number; char: string; fillColor: string; borderColor: string; borderSize: number; font: string; fontSize: number; texture: Texture; lineWidth: number; UV: Array; isSpace: boolean; underLine: number; /** * 创建单个文字 * @param content * @param drawValue * @return */ static createOneChar(content: string, drawValue: any): WebGLCharImage; active(): void; readonly atlasSource: any; /** * 是否创建私有Source * @return 是否创建 */ readonly allowMerageInAtlas: boolean; /** * 是否创建私有Source * @return 是否创建 */ /** * 是否创建私有Source,通常禁止修改 * @param value 是否创建 */ enableMerageInAtlas: boolean; /** * WebGLCharImage依赖于外部canvas,自身并无私有数据载体 * @param canvas * @param char */ constructor(content: string, drawValue: any); protected recreateResource(): void; clearAtlasSource(): void; } } declare module laya.webgl.resource { import HTMLImage = laya.resource.HTMLImage; class WebGLImage extends HTMLImage implements IMergeAtlasBitmap { _mipmap: boolean; /**是否使用重复模式纹理寻址*/ repeat: boolean; _image: any; /**缩小过滤器*/ minFifter: number; /**放大过滤器*/ magFifter: number; /** * 获取纹理格式。 */ readonly format: number; /** * 获取是否具有mipmap。 */ readonly mipmap: boolean; readonly atlasSource: any; /** * 是否创建私有Source * @return 是否创建 */ readonly allowMerageInAtlas: boolean; /** * 是否创建私有Source * @return 是否创建 */ /** * 是否创建私有Source,通常禁止修改 * @param value 是否创建 */ enableMerageInAtlas: boolean; /*** * 设置onload函数 * @param value onload函数 */ onload: Function; /*** * 设置onerror函数 * @param value onerror函数 */ onerror: Function; constructor(data: string, def: any, format?: number, mipmap?: boolean); protected _init_(src: string, def: any): void; protected recreateResource(): void; protected disposeResource(): void; protected onresize(): void; clearAtlasSource(): void; } } declare module laya.webgl.resource { import Bitmap = laya.resource.Bitmap; class WebGLRenderTarget extends Bitmap { readonly frameBuffer: any; readonly depthStencilBuffer: any; constructor(width: number, height: number, surfaceFormat?: number, surfaceType?: number, depthStencilFormat?: number, mipMap?: boolean, repeat?: boolean, minFifter?: number, magFifter?: number); protected recreateResource(): void; protected disposeResource(): void; } } declare module laya.webgl.resource { import Bitmap = laya.resource.Bitmap; class WebGLSubImage extends Bitmap implements IMergeAtlasBitmap { /**HTML Canvas,绘制子图载体,非私有数据载体*/ canvas: any; /**是否使用重复模式纹理寻址*/ repeat: boolean; /**是否使用mipLevel*/ mipmap: boolean; /**缩小过滤器*/ minFifter: number; /**放大过滤器*/ magFifter: number; atlasImage: any; offsetX: number; offsetY: number; src: string; readonly atlasSource: any; /** * 是否创建私有Source * @return 是否创建 */ readonly allowMerageInAtlas: boolean; /** * 是否创建私有Source * @return 是否创建 */ /** * 是否创建私有Source,通常禁止修改 * @param value 是否创建 */ enableMerageInAtlas: boolean; constructor(canvas: any, offsetX: number, offsetY: number, width: number, height: number, atlasImage: any, src: string); protected recreateResource(): void; protected disposeResource(): void; clearAtlasSource(): void; } } declare module laya.webgl.shader { import Resource = laya.resource.Resource; /** * ... * @author ... */ class BaseShader extends Resource { static activeShader: BaseShader; static bindShader: BaseShader; constructor(); } } declare module laya.webgl.shader.d2 { import Bitmap = laya.resource.Bitmap; import DrawStyle = laya.webgl.canvas.DrawStyle; import Shader = laya.webgl.shader.Shader; class Shader2D { ALPHA: number; glTexture: Bitmap; shader: Shader; filters: Array; defines: ShaderDefines2D; shaderType: number; colorAdd: Array; strokeStyle: DrawStyle; fillStyle: DrawStyle; destroy(): void; static __init__(): void; } } declare module laya.webgl.shader.d2 { import Shader = laya.webgl.shader.Shader; import ShaderValue = laya.webgl.shader.ShaderValue; class Shader2X extends Shader { _params2dQuick1: Array; _params2dQuick2: Array; _shaderValueWidth: number; _shaderValueHeight: number; constructor(vs: string, ps: string, saveName?: any, nameMap?: any); upload2dQuick1(shaderValue: ShaderValue): void; _make2dQuick1(): Array; protected disposeResource(): void; upload2dQuick2(shaderValue: ShaderValue): void; _make2dQuick2(): Array; static create(vs: string, ps: string, saveName?: any, nameMap?: any): Shader; } } declare module laya.webgl.shader.d2 { import ShaderDefines = laya.webgl.shader.ShaderDefines; class ShaderDefines2D extends ShaderDefines { static TEXTURE2D: number; static COLOR2D: number; static PRIMITIVE: number; static FILTERGLOW: number; static FILTERBLUR: number; static FILTERCOLOR: number; static COLORADD: number; static WORLDMAT: number; static FILLTEXTURE: number; static SKINMESH: number; static SHADERDEFINE_FSHIGHPRECISION: number; static __init__(): void; constructor(); static reg(name: string, value: number): void; static toText(value: number, int2name: Array, int2nameMap: any): any; static toInt(names: string): number; } } declare module laya.webgl.shader.d2.skinAnishader { import Matrix = laya.maths.Matrix; import Texture = laya.resource.Texture; import IndexBuffer2D = laya.webgl.utils.IndexBuffer2D; import VertexBuffer2D = laya.webgl.utils.VertexBuffer2D; /** * 这里销毁的问题,后面待确认 */ class SkinMesh { transform: Matrix; constructor(); init(texture: Texture, vs: Array, ps: Array): void; init2(texture: Texture, vs: Array, ps: Array, verticles: Array, uvs: Array): void; getData2(vb: VertexBuffer2D, ib: IndexBuffer2D, start: number): void; getData(vb: VertexBuffer2D, ib: IndexBuffer2D, start: number): void; render(context: any, x: number, y: number): void; } } declare module laya.webgl.shader.d2.skinAnishader { import IndexBuffer2D = laya.webgl.utils.IndexBuffer2D; import VertexBuffer2D = laya.webgl.utils.VertexBuffer2D; class SkinMeshBuffer { ib: IndexBuffer2D; vb: VertexBuffer2D; static instance: SkinMeshBuffer; constructor(); static getInstance(): SkinMeshBuffer; addSkinMesh(skinMesh: SkinMesh): void; reset(): void; } } declare module laya.webgl.shader.d2.skinAnishader { import Value2D = laya.webgl.shader.d2.value.Value2D; class SkinSV extends Value2D { texcoord: any; offsetX: number; offsetY: number; constructor(type: any); } } declare module laya.webgl.shader.d2.value { import Shader2D = laya.webgl.shader.d2.Shader2D; class Color2dSV extends Value2D { constructor(args: any); setValue(value: Shader2D): void; } } declare module laya.webgl.shader.d2.value { import Shader2D = laya.webgl.shader.d2.Shader2D; import Value2D = laya.webgl.shader.d2.value.Value2D; class FillTextureSV extends Value2D { texcoord: Array; u_colorMatrix: Array; strength: number; colorMat: Array; colorAlpha: Array; u_TexRange: Array; u_offset: Array; constructor(type: any); setValue(vo: Shader2D): void; clear(): void; } } declare module laya.webgl.shader.d2.value { import Shader2D = laya.webgl.shader.d2.Shader2D; class GlowSV extends TextureSV { u_blurX: boolean; u_color: Array; u_offset: Array; u_strength: number; u_texW: number; u_texH: number; constructor(args: any); setValue(vo: Shader2D): void; clear(): void; } } declare module laya.webgl.shader.d2.value { class PrimitiveSV extends Value2D { a_color: Array; u_pos: Array; constructor(args: any); } } declare module laya.webgl.shader.d2.value { class TextSV extends TextureSV { static pool: Array; constructor(args: any); release(): void; clear(): void; static create(): TextSV; } } declare module laya.webgl.shader.d2.value { import Shader2D = laya.webgl.shader.d2.Shader2D; class TextureSV extends Value2D { texcoord: Array; u_colorMatrix: Array; strength: number; blurInfo: Array; colorMat: Array; colorAlpha: Array; constructor(subID?: number); setValue(vo: Shader2D): void; clear(): void; } } declare module laya.webgl.shader.d2.value { import Bitmap = laya.resource.Bitmap; import Texture = laya.resource.Texture; import DrawStyle = laya.webgl.canvas.DrawStyle; import Shader = laya.webgl.shader.Shader; import ShaderValue = laya.webgl.shader.ShaderValue; import Shader2D = laya.webgl.shader.d2.Shader2D; import ShaderDefines2D = laya.webgl.shader.d2.ShaderDefines2D; class Value2D extends ShaderValue { static _POSITION: Array; static _TEXCOORD: Array; protected static _cache: Array; protected static _typeClass: any; static TEMPMAT4_ARRAY: Array; static __init__(): void; defines: ShaderDefines2D; position: Array; size: Array; alpha: number; mmat: Array; ALPHA: number; shader: Shader; mainID: number; subID: number; filters: Array; textureHost: Texture; texture: any; fillStyle: DrawStyle; color: Array; strokeStyle: DrawStyle; colorAdd: Array; glTexture: Bitmap; mul_mmat: Array; u_mmat2: Array; constructor(mainID: number, subID: number); setValue(value: Shader2D): void; refresh(): ShaderValue; upload(): void; setFilters(value: Array): void; clear(): void; release(): void; static create(mainType: number, subType: number): Value2D; } } declare module laya.webgl.shader { import StringKey = laya.utils.StringKey; class Shader extends BaseShader { static _preCompileShader: any; static SHADERNAME2ID: number; static nameKey: StringKey; static sharders: Array; static getShader(name: any): Shader; static create(vs: string, ps: string, saveName?: any, nameMap?: any): Shader; /** * 根据宏动态生成shader文件,支持#include?COLOR_FILTER "parts/ColorFilter_ps_logic.glsl";条件嵌入文件 * @param name * @param vs * @param ps * @param define 宏定义,格式: * @return */ static withCompile(nameID: number, define: any, shaderName: any, createShader: Function): Shader; /** * 根据宏动态生成shader文件,支持#include?COLOR_FILTER "parts/ColorFilter_ps_logic.glsl";条件嵌入文件 * @param name * @param vs * @param ps * @param define 宏定义,格式: * @return */ static withCompile2D(nameID: number, mainID: number, define: any, shaderName: any, createShader: Function): Shader; static addInclude(fileName: string, txt: string): void; /** * 预编译shader文件,主要是处理宏定义 * @param nameID,一般是特殊宏+shaderNameID*0.0002组成的一个浮点数当做唯一标识 * @param vs * @param ps */ static preCompile(nameID: number, vs: string, ps: string, nameMap: any): void; /** * 预编译shader文件,主要是处理宏定义 * @param nameID,一般是特殊宏+shaderNameID*0.0002组成的一个浮点数当做唯一标识 * @param vs * @param ps */ static preCompile2D(nameID: number, mainID: number, vs: string, ps: string, nameMap: any): void; tag: any; _vshader: any; _pshader: any; _program: any; _params: Array; _paramsMap: any; _offset: number; _id: number; /** * 根据vs和ps信息生成shader对象 * @param vs * @param ps * @param name: * @param nameMap 帮助里要详细解释为什么需要nameMap */ constructor(vs: string, ps: string, saveName?: any, nameMap?: any); protected recreateResource(): void; protected disposeResource(): void; /** * 根据变量名字获得 * @param name * @return */ getUniform(name: string): any; uploadOne(name: string, value: any): void; uploadTexture2D(value: any): void; /** * 提交shader到GPU * @param shaderValue */ upload(shaderValue: ShaderValue, params?: Array): void; /** * 按数组的定义提交 * @param shaderValue 数组格式[name,value,...] */ uploadArray(shaderValue: Array, length: number, _bufferUsage: any): void; /** * 得到编译后的变量及相关预定义 * @return */ getParams(): Array; } } declare module laya.webgl.shader { class ShaderDefines { _value: number; constructor(name2int: any, int2name: Array, int2nameMap: Array); add(value: any): number; addInt(value: number): number; remove(value: any): number; isDefine(def: number): boolean; getValue(): number; setValue(value: number): void; toNameDic(): any; static _reg(name: string, value: number, _name2int: any, _int2name: Array): void; static _toText(value: number, _int2name: Array, _int2nameMap: any): any; static _toInt(names: string, _name2int: any): number; } } declare module laya.webgl.shader { class ShaderValue { constructor(); } } declare module laya.webgl.shapes { import Matrix = laya.maths.Matrix; import Buffer2D = laya.webgl.utils.Buffer2D; class BasePoly implements IShape { x: number; y: number; r: number; width: number; height: number; edges: number; r0: number; color: number; borderColor: number; borderWidth: number; round: number; fill: boolean; protected mUint16Array: Uint16Array; protected mFloat32Array: Float32Array; constructor(x: number, y: number, width: number, height: number, edges: number, color: number, borderWidth: number, borderColor: number, round?: number); getData(ib: Buffer2D, vb: Buffer2D, start: number): void; rebuild(points: Array): void; setMatrix(mat: Matrix): void; needUpdate(mat: Matrix): boolean; protected sector(outVert: Array, outIndex: Array, start: number): void; protected createLine2(p: Array, indices: Array, lineWidth: number, len: number, outVertex: Array, indexCount: number): Array; protected createLine(p: Array, indices: Array, lineWidth: number, len: number): Array; createLoopLine(p: Array, indices: Array, lineWidth: number, len: number, outVertex?: Array, outIndex?: Array): Array; } } declare module laya.webgl.shapes { class Earcut { static earcut(data: any, holeIndices: any, dim: any): any; static linkedList(data: any, start: any, end: any, dim: any, clockwise: any): any; static filterPoints(start: any, end: any): any; static earcutLinked(ear: any, triangles: any, dim: any, minX: any, minY: any, invSize: any, pass?: any): any; static isEar(ear: any): any; static isEarHashed(ear: any, minX: any, minY: any, invSize: any): boolean; static cureLocalIntersections(start: any, triangles: any, dim: any): any; static splitEarcut(start: any, triangles: any, dim: any, minX: any, minY: any, invSize: any): void; static eliminateHoles(data: any, holeIndices: any, outerNode: any, dim: any): any; static compareX(a: any, b: any): any; static eliminateHole(hole: any, outerNode: any): void; static findHoleBridge(hole: any, outerNode: any): any; static indexCurve(start: any, minX: any, minY: any, invSize: any): void; static sortLinked(list: any): any; static zOrder(x: any, y: any, minX: any, minY: any, invSize: any): any; static getLeftmost(start: any): any; static pointInTriangle(ax: any, ay: any, bx: any, by: any, cx: any, cy: any, px: any, py: any): boolean; static isValidDiagonal(a: any, b: any): boolean; static area(p: any, q: any, r: any): any; static equals(p1: any, p2: any): boolean; static intersects(p1: any, q1: any, p2: any, q2: any): boolean; static intersectsPolygon(a: any, b: any): boolean; static locallyInside(a: any, b: any): boolean; static middleInside(a: any, b: any): boolean; static splitPolygon(a: any, b: any): any; static insertNode(i: any, x: any, y: any, last: any): any; static removeNode(p: any): void; static signedArea(data: any, start: any, end: any, dim: any): any; } } declare module laya.webgl.shapes { class EarcutNode { i: any; x: any; y: any; prev: any; next: any; z: any; prevZ: any; nextZ: any; steiner: any; constructor(i: any, x: any, y: any); } } declare module laya.webgl.shapes { class Ellipse extends BasePoly { constructor(x: number, y: number, width: number, height: number, color: number, borderWidth: number, borderColor: number); } } declare module laya.webgl.shapes { class GeometryData { lineWidth: number; lineColor: number; lineAlpha: number; fillColor: number; fillAlpha: number; shape: IShape; fill: boolean; constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, shape: IShape); clone(): GeometryData; getIndexData(): Uint16Array; getVertexData(): Float32Array; destroy(): void; } } declare module laya.webgl.shapes { import Matrix = laya.maths.Matrix; import Buffer2D = laya.webgl.utils.Buffer2D; interface IShape { getData(ib: Buffer2D, vb: Buffer2D, start: number): void; rebuild(points: Array): void; setMatrix(mat: Matrix): void; needUpdate(mat: Matrix): boolean; } } declare module laya.webgl.shapes { import Buffer2D = laya.webgl.utils.Buffer2D; class Line extends BasePoly { constructor(x: number, y: number, points: Array, borderWidth: number, color: number); rebuild(points: Array): void; getData(ib: Buffer2D, vb: Buffer2D, start: number): void; } } declare module laya.webgl.shapes { import Buffer2D = laya.webgl.utils.Buffer2D; class LoopLine extends BasePoly { constructor(x: number, y: number, points: Array, width: number, color: number); getData(ib: Buffer2D, vb: Buffer2D, start: number): void; createLoopLine(p: Array, indices: Array, lineWidth: number, len: number, outVertex?: Array, outIndex?: Array): Array; } } declare module laya.webgl.shapes { import Matrix = laya.maths.Matrix; import Buffer2D = laya.webgl.utils.Buffer2D; class Polygon extends BasePoly { constructor(x: number, y: number, points: Array, color: number, borderWidth: number, borderColor: number); rebuild(point: Array): void; setMatrix(mat: Matrix): void; needUpdate(mat: Matrix): boolean; getData(ib: Buffer2D, vb: Buffer2D, start: number): void; } } declare module laya.webgl.shapes { import Matrix = laya.maths.Matrix; import Buffer2D = laya.webgl.utils.Buffer2D; class Vertex implements IShape { points: Float32Array; constructor(p: any); getData(ib: Buffer2D, vb: Buffer2D, start: number): void; needUpdate(mat: Matrix): boolean; rebuild(points: Array): void; setMatrix(mat: Matrix): void; } } declare module laya.webgl.submit { interface ISubmit { renderSubmit(): number; getRenderType(): number; releaseRender(): void; } } declare module laya.webgl.submit { import ISubmit = laya.webgl.submit.ISubmit; class SubmitCMD implements ISubmit { static _cache: Array; fun: Function; args: Array; constructor(); renderSubmit(): number; getRenderType(): number; releaseRender(): void; static create(args: Array, fun: Function): SubmitCMD; } } declare module laya.webgl.submit { class SubmitCMDScope { constructor(); getValue(name: string): any; addValue(name: string, value: any): any; setValue(name: string, value: any): any; clear(): void; recycle(): void; static create(): SubmitCMDScope; } } declare module laya.webgl.text { /** * ...特殊的字符,如泰文,必须重新实现这个类 */ class CharSegment implements ICharSegment { constructor(); textToSpit(str: string): void; getChar(i: number): string; getCharCode(i: number): number; length(): number; } } declare module laya.webgl.text { class FontInContext { static EMPTY: FontInContext; static create(font: string): FontInContext; constructor(font?: string); setFont(value: string): void; size: number; getItalic(): number; hasType(name: string): number; removeType(name: string): void; copyTo(dec: FontInContext): FontInContext; toString(): string; } } declare module laya.webgl.text { interface ICharSegment { textToSpit(str: string): void; getChar(i: number): string; getCharCode(i: number): number; length(): number; } } declare module laya.webgl.utils { import Resource = laya.resource.Resource; import WebGLContext = laya.webgl.WebGLContext; class Buffer extends Resource { protected static _gl: WebGLContext; static _bindActive: any; static _bindVertexBuffer: any; static _enableAtributes: Array; protected _glBuffer: any; protected _buffer: any; protected _bufferType: number; protected _bufferUsage: number; _byteLength: number; readonly bufferUsage: number; constructor(); _bind(): void; protected recreateResource(): void; protected disposeResource(): void; } } declare module laya.webgl.utils { import WebGLContext = laya.webgl.WebGLContext; class Buffer2D extends Buffer { static FLOAT32: number; static SHORT: number; static __int__(gl: WebGLContext): void; protected _maxsize: number; _upload: boolean; protected _uploadSize: number; readonly bufferLength: number; byteLength: number; /** * 在当前的基础上需要多大空间,单位是byte * @param sz * @return 增加大小之前的写位置。单位是byte */ needSize(sz: number): number; constructor(); protected _bufferData(): void; protected _bufferSubData(offset?: number, dataStart?: number, dataLength?: number): void; protected _checkArrayUse(): void; _bind_upload(): boolean; _bind_subUpload(offset?: number, dataStart?: number, dataLength?: number): boolean; _resizeBuffer(nsz: number, copy: boolean): Buffer2D; append(data: any): void; /** * 附加Uint16Array的数据。数据长度是len。byte的话要*2 * @param data * @param len */ appendU16Array(data: Uint16Array, len: number): void; appendEx(data: any, type: any): void; appendEx2(data: any, type: any, dataLen: number, perDataLen?: number): void; getBuffer(): ArrayBuffer; setNeedUpload(): void; getNeedUpload(): boolean; upload(): boolean; subUpload(offset?: number, dataStart?: number, dataLength?: number): boolean; protected disposeResource(): void; clear(): void; } } declare module laya.webgl.utils { class CONST3D2D { static BYTES_PE: number; static BYTES_PIDX: number; static defaultMatrix4: Array; static defaultMinusYMatrix4: Array; static uniformMatrix3: Array; static _TMPARRAY: Array; static _OFFSETX: number; static _OFFSETY: number; } } declare module laya.webgl.utils { import Matrix = laya.maths.Matrix; import Rectangle = laya.maths.Rectangle; class GlUtils { static make2DProjection(width: number, height: number, depth: number): any; /** * 初始化全局IB,IB索引如下: * 0___1 * |\ | * | \ | * |__\| * 3 2 */ static fillIBQuadrangle(buffer: IndexBuffer2D, count: number): boolean; static expandIBQuadrangle(buffer: IndexBuffer2D, count: number): void; static mathCeilPowerOfTwo(value: number): number; static fillQuadrangleImgVb(vb: VertexBuffer2D, x: number, y: number, point4: Array, uv: Array, m: Matrix, _x: number, _y: number): boolean; static fillTranglesVB(vb: VertexBuffer2D, x: number, y: number, points: Array, m: Matrix, _x: number, _y: number): boolean; static copyPreImgVb(vb: VertexBuffer2D, dx: number, dy: number): void; static fillRectImgVb(vb: VertexBuffer2D, clip: Rectangle, x: number, y: number, width: number, height: number, uv: Array, m: Matrix, _x: number, _y: number, dx: number, dy: number, round?: boolean): boolean; static fillLineVb(vb: VertexBuffer2D, clip: Rectangle, fx: number, fy: number, tx: number, ty: number, width: number, mat: Matrix): boolean; } } declare module laya.webgl.utils { class IndexBuffer2D extends Buffer2D { static QuadrangleIB: IndexBuffer2D; static create: Function; protected _uint8Array: Uint8Array; protected _uint16Array: Uint16Array; constructor(bufferUsage?: number); protected _checkArrayUse(): void; getUint8Array(): Uint8Array; getUint16Array(): Uint16Array; destory(): void; } } declare module laya.webgl.utils { class MatirxArray { /** * 4*4矩阵数组相乘。 * o=a*b; * @param a 4*4矩阵数组。 * @param b 4*4矩阵数组。 * @param o 4*4矩阵数组。 */ static ArrayMul(a: Array, b: Array, o: Array): void; static copyArray(f: Array, t: Array): void; } } declare module laya.webgl.utils { /** * Mesh2d只是保存数据。描述attribute用的。本身不具有渲染功能。 */ class Mesh2D { _stride: number; vertNum: number; indexNum: number; protected _applied: boolean; protected _vb: VertexBuffer2D; protected _ib: IndexBuffer2D; protected _quadNum: number; canReuse: boolean; /** * * @param stride * @param vballoc vb预分配的大小。主要是用来提高效率。防止不断的resizebfufer * @param iballoc */ constructor(stride: number, vballoc: number, iballoc: number); /** * 重新创建一个mesh。复用这个对象的vertex结构,ib对象和attribinfo对象 */ cloneWithNewVB(): Mesh2D; /** * 创建一个mesh,使用当前对象的vertex结构。vb和ib自己提供。 * @return */ cloneWithNewVBIB(): Mesh2D; /** * 获得一个可以写的vb对象 */ getVBW(): VertexBuffer2D; /** * 获得一个只读vb */ getVBR(): VertexBuffer2D; getIBR(): IndexBuffer2D; /** * 获得一个可写的ib */ getIBW(): IndexBuffer2D; /** * 直接创建一个固定的ib。按照固定四边形的索引。 * @param var QuadNum */ createQuadIB(QuadNum: number): void; /** * 设置mesh的属性。每3个一组,对应的location分别是0,1,2... * 含义是:type,size,offset * 不允许多流。因此stride是固定的,offset只是在一个vertex之内。 * @param attribs */ setAttributes(attribs: Array): void; getEleNum(): number; /** * 子类实现。用来把自己放到对应的回收池中,以便复用。 */ releaseMesh(): void; /** * 释放资源。 */ destroy(): void; /** * 清理vb数据 */ clearVB(): void; } } declare module laya.webgl.utils { import Sprite = laya.display.Sprite; import RenderContext = laya.renders.RenderContext; import RenderSprite = laya.renders.RenderSprite; import SubmitCMDScope = laya.webgl.submit.SubmitCMDScope; class RenderSprite3D extends RenderSprite { static tempUV: Array; constructor(type: number, next: RenderSprite); protected onCreate(type: number): void; static tmpTarget(scope: SubmitCMDScope, context: RenderContext): void; static endTmpTarget(scope: SubmitCMDScope): void; static recycleTarget(scope: SubmitCMDScope): void; _mask(sprite: Sprite, context: RenderContext, x: number, y: number): void; _blend(sprite: Sprite, context: RenderContext, x: number, y: number): void; _transform(sprite: Sprite, context: RenderContext, x: number, y: number): void; } } declare module laya.webgl.utils { import Shader = laya.webgl.shader.Shader; /** * @private * ShaderCompile 类用于实现Shader编译。 */ class ShaderCompile { static IFDEF_NO: number; static IFDEF_YES: number; static IFDEF_ELSE: number; static IFDEF_PARENT: number; static _removeAnnotation: RegExp; static _reg: RegExp; static _splitToWordExps: RegExp; static includes: any; static shaderParamsMap: any; protected _VS: ShaderNode; protected _PS: ShaderNode; static addInclude(fileName: string, txt: string): void; static preGetParams(vs: string, ps: string): any; static splitToWords(str: string, block: ShaderNode): Array; constructor(name: number, vs: string, ps: string, nameMap: any, defs?: any); createShader(define: any, shaderName: any, createShader: Function): Shader; } class ShaderNode { childs: Array; text: string; parent: ShaderNode; name: string; noCompile: boolean; includefiles: Array; condition: any; conditionType: number; useFuns: string; z: number; src: string; ShaderNode(includefiles: Array): any; setParent(parent: ShaderNode): void; setCondition(condition: string, type: number): void; toscript(def: any, out: Array): Array; } class InlcudeFile { script: string; codes: any; funs: any; curUseID: number; funnames: string; InlcudeFile(txt: string): any; getWith(name?: string): string; getFunsScript(funsdef: string): string; } } declare module laya.webgl.utils { class VertexBuffer2D extends Buffer2D { static create: Function; protected _floatArray32: Float32Array; readonly vertexStride: number; constructor(vertexStride: number, bufferUsage: number); getFloat32Array(): any; bind(ibBuffer: IndexBuffer2D): void; insertData(data: Array, pos: number): void; bind_upload(ibBuffer: IndexBuffer2D): void; protected _checkArrayUse(): void; protected disposeResource(): void; destory(): void; } } declare module laya.webgl { import Sprite = laya.display.Sprite; import HTMLCanvas = laya.resource.HTMLCanvas; /** * @private */ class WebGL { static compressAstc: any; static compressAtc: any; static compressEtc: any; static compressEtc1: any; static compressPvrtc: any; static compressS3tc: any; static compressS3tc_srgb: any; static mainCanvas: HTMLCanvas; static mainContext: WebGLContext; static antialias: boolean; /**Shader是否支持高精度。 */ static shaderHighPrecision: boolean; static enable(): boolean; static onStageResize(width: number, height: number): void; static doNodeRepaint(sprite: Sprite): void; static init(canvas: HTMLCanvas, width: number, height: number): void; } } declare module laya.webgl { class WebGLContext { static DEPTH_BUFFER_BIT: number; static STENCIL_BUFFER_BIT: number; static COLOR_BUFFER_BIT: number; static POINTS: number; static LINES: number; static LINE_LOOP: number; static LINE_STRIP: number; static TRIANGLES: number; static TRIANGLE_STRIP: number; static TRIANGLE_FAN: number; static ZERO: number; static ONE: number; static SRC_COLOR: number; static ONE_MINUS_SRC_COLOR: number; static SRC_ALPHA: number; static ONE_MINUS_SRC_ALPHA: number; static DST_ALPHA: number; static ONE_MINUS_DST_ALPHA: number; static DST_COLOR: number; static ONE_MINUS_DST_COLOR: number; static SRC_ALPHA_SATURATE: number; static FUNC_ADD: number; static BLEND_EQUATION: number; static BLEND_EQUATION_RGB: number; static BLEND_EQUATION_ALPHA: number; static FUNC_SUBTRACT: number; static FUNC_REVERSE_SUBTRACT: number; static BLEND_DST_RGB: number; static BLEND_SRC_RGB: number; static BLEND_DST_ALPHA: number; static BLEND_SRC_ALPHA: number; static CONSTANT_COLOR: number; static ONE_MINUS_CONSTANT_COLOR: number; static CONSTANT_ALPHA: number; static ONE_MINUS_CONSTANT_ALPHA: number; static BLEND_COLOR: number; static ARRAY_BUFFER: number; static ELEMENT_ARRAY_BUFFER: number; static ARRAY_BUFFER_BINDING: number; static ELEMENT_ARRAY_BUFFER_BINDING: number; static STREAM_DRAW: number; static STATIC_DRAW: number; static DYNAMIC_DRAW: number; static BUFFER_SIZE: number; static BUFFER_USAGE: number; static CURRENT_VERTEX_ATTRIB: number; static FRONT: number; static BACK: number; static CULL_FACE: number; static FRONT_AND_BACK: number; static BLEND: number; static DITHER: number; static STENCIL_TEST: number; static DEPTH_TEST: number; static SCISSOR_TEST: number; static POLYGON_OFFSET_FILL: number; static SAMPLE_ALPHA_TO_COVERAGE: number; static SAMPLE_COVERAGE: number; static NO_ERROR: number; static INVALID_ENUM: number; static INVALID_VALUE: number; static INVALID_OPERATION: number; static OUT_OF_MEMORY: number; static CW: number; static CCW: number; static LINE_WIDTH: number; static ALIASED_POINT_SIZE_RANGE: number; static ALIASED_LINE_WIDTH_RANGE: number; static CULL_FACE_MODE: number; static FRONT_FACE: number; static DEPTH_RANGE: number; static DEPTH_WRITEMASK: number; static DEPTH_CLEAR_VALUE: number; static DEPTH_FUNC: number; static STENCIL_CLEAR_VALUE: number; static STENCIL_FUNC: number; static STENCIL_FAIL: number; static STENCIL_PASS_DEPTH_FAIL: number; static STENCIL_PASS_DEPTH_PASS: number; static STENCIL_REF: number; static STENCIL_VALUE_MASK: number; static STENCIL_WRITEMASK: number; static STENCIL_BACK_FUNC: number; static STENCIL_BACK_FAIL: number; static STENCIL_BACK_PASS_DEPTH_FAIL: number; static STENCIL_BACK_PASS_DEPTH_PASS: number; static STENCIL_BACK_REF: number; static STENCIL_BACK_VALUE_MASK: number; static STENCIL_BACK_WRITEMASK: number; static VIEWPORT: number; static SCISSOR_BOX: number; static COLOR_CLEAR_VALUE: number; static COLOR_WRITEMASK: number; static UNPACK_ALIGNMENT: number; static PACK_ALIGNMENT: number; static MAX_TEXTURE_SIZE: number; static MAX_VIEWPORT_DIMS: number; static SUBPIXEL_BITS: number; static RED_BITS: number; static GREEN_BITS: number; static BLUE_BITS: number; static ALPHA_BITS: number; static DEPTH_BITS: number; static STENCIL_BITS: number; static POLYGON_OFFSET_UNITS: number; static POLYGON_OFFSET_FACTOR: number; static TEXTURE_BINDING_2D: number; static SAMPLE_BUFFERS: number; static SAMPLES: number; static SAMPLE_COVERAGE_VALUE: number; static SAMPLE_COVERAGE_INVERT: number; static NUM_COMPRESSED_TEXTURE_FORMATS: number; static COMPRESSED_TEXTURE_FORMATS: number; static DONT_CARE: number; static FASTEST: number; static NICEST: number; static GENERATE_MIPMAP_HINT: number; static BYTE: number; static UNSIGNED_BYTE: number; static SHORT: number; static UNSIGNED_SHORT: number; static INT: number; static UNSIGNED_INT: number; static FLOAT: number; static DEPTH_COMPONENT: number; static ALPHA: number; static RGB: number; static RGBA: number; static LUMINANCE: number; static LUMINANCE_ALPHA: number; static UNSIGNED_SHORT_4_4_4_4: number; static UNSIGNED_SHORT_5_5_5_1: number; static UNSIGNED_SHORT_5_6_5: number; static FRAGMENT_SHADER: number; static VERTEX_SHADER: number; static MAX_VERTEX_ATTRIBS: number; static MAX_VERTEX_UNIFORM_VECTORS: number; static MAX_VARYING_VECTORS: number; static MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; static MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; static MAX_TEXTURE_IMAGE_UNITS: number; static MAX_FRAGMENT_UNIFORM_VECTORS: number; static SHADER_TYPE: number; static DELETE_STATUS: number; static LINK_STATUS: number; static VALIDATE_STATUS: number; static ATTACHED_SHADERS: number; static ACTIVE_UNIFORMS: number; static ACTIVE_ATTRIBUTES: number; static SHADING_LANGUAGE_VERSION: number; static CURRENT_PROGRAM: number; static NEVER: number; static LESS: number; static EQUAL: number; static LEQUAL: number; static GREATER: number; static NOTEQUAL: number; static GEQUAL: number; static ALWAYS: number; static KEEP: number; static REPLACE: number; static INCR: number; static DECR: number; static INVERT: number; static INCR_WRAP: number; static DECR_WRAP: number; static VENDOR: number; static RENDERER: number; static VERSION: number; static NEAREST: number; static LINEAR: number; static NEAREST_MIPMAP_NEAREST: number; static LINEAR_MIPMAP_NEAREST: number; static NEAREST_MIPMAP_LINEAR: number; static LINEAR_MIPMAP_LINEAR: number; static TEXTURE_MAG_FILTER: number; static TEXTURE_MIN_FILTER: number; static TEXTURE_WRAP_S: number; static TEXTURE_WRAP_T: number; static TEXTURE_2D: number; static TEXTURE: number; static TEXTURE_CUBE_MAP: number; static TEXTURE_BINDING_CUBE_MAP: number; static TEXTURE_CUBE_MAP_POSITIVE_X: number; static TEXTURE_CUBE_MAP_NEGATIVE_X: number; static TEXTURE_CUBE_MAP_POSITIVE_Y: number; static TEXTURE_CUBE_MAP_NEGATIVE_Y: number; static TEXTURE_CUBE_MAP_POSITIVE_Z: number; static TEXTURE_CUBE_MAP_NEGATIVE_Z: number; static MAX_CUBE_MAP_TEXTURE_SIZE: number; static TEXTURE0: number; static TEXTURE1: number; static TEXTURE2: number; static TEXTURE3: number; static TEXTURE4: number; static TEXTURE5: number; static TEXTURE6: number; static TEXTURE7: number; static TEXTURE8: number; static TEXTURE9: number; static TEXTURE10: number; static TEXTURE11: number; static TEXTURE12: number; static TEXTURE13: number; static TEXTURE14: number; static TEXTURE15: number; static TEXTURE16: number; static TEXTURE17: number; static TEXTURE18: number; static TEXTURE19: number; static TEXTURE20: number; static TEXTURE21: number; static TEXTURE22: number; static TEXTURE23: number; static TEXTURE24: number; static TEXTURE25: number; static TEXTURE26: number; static TEXTURE27: number; static TEXTURE28: number; static TEXTURE29: number; static TEXTURE30: number; static TEXTURE31: number; static ACTIVE_TEXTURE: number; static REPEAT: number; static CLAMP_TO_EDGE: number; static MIRRORED_REPEAT: number; static FLOAT_VEC2: number; static FLOAT_VEC3: number; static FLOAT_VEC4: number; static INT_VEC2: number; static INT_VEC3: number; static INT_VEC4: number; static BOOL: number; static BOOL_VEC2: number; static BOOL_VEC3: number; static BOOL_VEC4: number; static FLOAT_MAT2: number; static FLOAT_MAT3: number; static FLOAT_MAT4: number; static SAMPLER_2D: number; static SAMPLER_CUBE: number; static VERTEX_ATTRIB_ARRAY_ENABLED: number; static VERTEX_ATTRIB_ARRAY_SIZE: number; static VERTEX_ATTRIB_ARRAY_STRIDE: number; static VERTEX_ATTRIB_ARRAY_TYPE: number; static VERTEX_ATTRIB_ARRAY_NORMALIZED: number; static VERTEX_ATTRIB_ARRAY_POINTER: number; static VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; static COMPILE_STATUS: number; static LOW_FLOAT: number; static MEDIUM_FLOAT: number; static HIGH_FLOAT: number; static LOW_INT: number; static MEDIUM_INT: number; static HIGH_INT: number; static FRAMEBUFFER: number; static RENDERBUFFER: number; static RGBA4: number; static RGB5_A1: number; static RGB565: number; static DEPTH_COMPONENT16: number; static STENCIL_INDEX: number; static STENCIL_INDEX8: number; static DEPTH_STENCIL: number; static RENDERBUFFER_WIDTH: number; static RENDERBUFFER_HEIGHT: number; static RENDERBUFFER_INTERNAL_FORMAT: number; static RENDERBUFFER_RED_SIZE: number; static RENDERBUFFER_GREEN_SIZE: number; static RENDERBUFFER_BLUE_SIZE: number; static RENDERBUFFER_ALPHA_SIZE: number; static RENDERBUFFER_DEPTH_SIZE: number; static RENDERBUFFER_STENCIL_SIZE: number; static FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; static FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; static FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; static FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; static COLOR_ATTACHMENT0: number; static DEPTH_ATTACHMENT: number; static STENCIL_ATTACHMENT: number; static DEPTH_STENCIL_ATTACHMENT: number; static NONE: number; static FRAMEBUFFER_COMPLETE: number; static FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; static FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; static FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; static FRAMEBUFFER_UNSUPPORTED: number; static FRAMEBUFFER_BINDING: number; static RENDERBUFFER_BINDING: number; static MAX_RENDERBUFFER_SIZE: number; static INVALID_FRAMEBUFFER_OPERATION: number; static UNPACK_FLIP_Y_WEBGL: number; static UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; static CONTEXT_LOST_WEBGL: number; static UNPACK_COLORSPACE_CONVERSION_WEBGL: number; static BROWSER_DEFAULT_WEBGL: number; static _useProgram: any; static UseProgram(program: any): boolean; static _depthTest: boolean; static _depthMask: boolean; static _depthFunc: number; static _blend: boolean; static _sFactor: number; static _dFactor: number; static _cullFace: boolean; static _frontFace: number; static curBindTexTarget: any; static curBindTexValue: any; static setDepthTest(gl: WebGLContext, value: boolean): void; static setDepthMask(gl: WebGLContext, value: boolean): void; static setDepthFunc(gl: WebGLContext, value: number): void; static setBlend(gl: WebGLContext, value: boolean): void; static setBlendFunc(gl: WebGLContext, sFactor: number, dFactor: number): void; static setCullFace(gl: WebGLContext, value: boolean): void; static setFrontFace(gl: WebGLContext, value: number): void; static bindTexture(gl: WebGLContext, target: any, texture: any): void; alpha: number; depth: number; stencil: number; antialias: number; premultipliedAlpha: number; preserveDrawingBuffer: number; drawingBufferWidth: number; drawingBufferHeight: number; getAttachedShaders: any; uniform_float: any; getContextAttributes(): any; isContextLost(): void; getSupportedExtensions(): any; getExtension(name: string): any; activeTexture(texture: any): void; attachShader(program: any, shader: any): void; bindAttribLocation(program: any, index: number, name: string): void; bindBuffer(target: any, buffer: any): void; bindFramebuffer(target: any, framebuffer: any): void; bindRenderbuffer(target: any, renderbuffer: any): void; bindTexture(target: any, texture: any): void; useTexture(value: boolean): void; blendColor(red: any, green: any, blue: any, alpha: number): void; blendEquation(mode: any): void; blendEquationSeparate(modeRGB: any, modeAlpha: any): void; blendFunc(sfactor: any, dfactor: any): void; blendFuncSeparate(srcRGB: any, dstRGB: any, srcAlpha: any, dstAlpha: any): void; bufferData(target: any, size: any, usage: any): void; bufferSubData(target: any, offset: number, data: any): void; checkFramebufferStatus(target: any): any; clear(mask: number): void; clearColor(red: any, green: any, blue: any, alpha: number): void; clearDepth(depth: any): void; clearStencil(s: any): void; colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; compileShader(shader: any): void; copyTexImage2D(target: any, level: any, internalformat: any, x: number, y: number, width: number, height: number, border: any): void; copyTexSubImage2D(target: any, level: any, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; createBuffer(): any; createFramebuffer(): any; createProgram(): any; createRenderbuffer(): any; createShader(type: any): any; createTexture(): any; cullFace(mode: any): void; deleteBuffer(buffer: any): void; deleteFramebuffer(framebuffer: any): void; deleteProgram(program: any): void; deleteRenderbuffer(renderbuffer: any): void; deleteShader(shader: any): void; deleteTexture(texture: any): void; depthFunc(func: any): void; depthMask(flag: any): void; depthRange(zNear: any, zFar: any): void; detachShader(program: any, shader: any): void; disable(cap: any): void; disableVertexAttribArray(index: number): void; drawArrays(mode: any, first: number, count: number): void; drawElements(mode: any, count: number, type: any, offset: number): void; enable(cap: any): void; enableVertexAttribArray(index: number): void; finish(): void; flush(): void; framebufferRenderbuffer(target: any, attachment: any, renderbuffertarget: any, renderbuffer: any): void; framebufferTexture2D(target: any, attachment: any, textarget: any, texture: any, level: any): void; frontFace(mode: any): any; generateMipmap(target: any): any; getActiveAttrib(program: any, index: number): any; getActiveUniform(program: any, index: number): any; getAttribLocation(program: any, name: string): any; getParameter(pname: any): any; getBufferParameter(target: any, pname: any): any; getError(): any; getFramebufferAttachmentParameter(target: any, attachment: any, pname: any): void; getProgramParameter(program: any, pname: any): number; getProgramInfoLog(program: any): any; getRenderbufferParameter(target: any, pname: any): any; getShaderPrecisionFormat(...arg: any[]): any; getShaderParameter(shader: any, pname: any): any; getShaderInfoLog(shader: any): any; getShaderSource(shader: any): any; getTexParameter(target: any, pname: any): void; getUniform(program: any, location: number): void; getUniformLocation(program: any, name: string): any; getVertexAttrib(index: number, pname: any): any; getVertexAttribOffset(index: number, pname: any): any; hint(target: any, mode: any): void; isBuffer(buffer: any): void; isEnabled(cap: any): void; isFramebuffer(framebuffer: any): void; isProgram(program: any): void; isRenderbuffer(renderbuffer: any): void; isShader(shader: any): void; isTexture(texture: any): void; lineWidth(width: number): void; linkProgram(program: any): void; pixelStorei(pname: any, param: any): void; polygonOffset(factor: any, units: any): void; readPixels(x: number, y: number, width: number, height: number, format: any, type: any, pixels: any): void; renderbufferStorage(target: any, internalformat: any, width: number, height: number): void; sampleCoverage(value: any, invert: any): void; scissor(x: number, y: number, width: number, height: number): void; shaderSource(shader: any, source: any): void; stencilFunc(func: number, ref: number, mask: number): void; stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; stencilMask(mask: any): void; stencilMaskSeparate(face: any, mask: any): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; texImage2D(...args: any[]): void; texParameterf(target: any, pname: any, param: any): void; texParameteri(target: any, pname: any, param: any): void; texSubImage2D(...args: any[]): void; uniform1f(location: any, x: number): void; uniform1fv(location: any, v: any): void; uniform1i(location: any, x: number): void; uniform1iv(location: any, v: any): void; uniform2f(location: any, x: number, y: number): void; uniform2fv(location: any, v: any): void; uniform2i(location: any, x: number, y: number): void; uniform2iv(location: any, v: any): void; uniform3f(location: any, x: number, y: number, z: number): void; uniform3fv(location: any, v: any): void; uniform3i(location: any, x: number, y: number, z: number): void; uniform3iv(location: any, v: any): void; uniform4f(location: any, x: number, y: number, z: number, w: number): void; uniform4fv(location: any, v: any): void; uniform4i(location: any, x: number, y: number, z: number, w: number): void; uniform4iv(location: any, v: any): void; uniformMatrix2fv(location: any, transpose: any, value: any): void; uniformMatrix3fv(location: any, transpose: any, value: any): void; uniformMatrix4fv(location: any, transpose: any, value: any): void; useProgram(program: any): void; validateProgram(program: any): void; vertexAttrib1f(indx: any, x: number): void; vertexAttrib1fv(indx: any, values: any): void; vertexAttrib2f(indx: any, x: number, y: number): void; vertexAttrib2fv(indx: any, values: any): void; vertexAttrib3f(indx: any, x: number, y: number, z: number): void; vertexAttrib3fv(indx: any, values: any): void; vertexAttrib4f(indx: any, x: number, y: number, z: number, w: number): void; vertexAttrib4fv(indx: any, values: any): void; vertexAttribPointer(indx: any, size: any, type: any, normalized: any, stride: any, offset: number): void; viewport(x: number, y: number, width: number, height: number): void; configureBackBuffer(width: number, height: number, antiAlias: number, enableDepthAndStencil?: boolean, wantsBestResolution?: boolean): void; compressedTexImage2D(...args: any[]): void; } } declare module Laya { class AnimationContent extends laya.ani.AnimationContent { } class AnimationNodeContent extends laya.ani.AnimationNodeContent { } class AnimationParser01 extends laya.ani.AnimationParser01 { } class AnimationParser02 extends laya.ani.AnimationParser02 { } class AnimationPlayer extends laya.ani.AnimationPlayer { } class AnimationState extends laya.ani.AnimationState { } class AnimationTemplet extends laya.ani.AnimationTemplet { } class Bone extends laya.ani.bone.Bone { } class BoneSlot extends laya.ani.bone.BoneSlot { } class CacheAbleSkinMesh extends laya.ani.bone.canvasmesh.CacheAbleSkinMesh { } class CanvasMeshRender extends laya.ani.bone.canvasmesh.CanvasMeshRender { } class MeshData extends laya.ani.bone.canvasmesh.MeshData { } class SimpleSkinMeshCanvas extends laya.ani.bone.canvasmesh.SimpleSkinMeshCanvas { } class SkinMeshCanvas extends laya.ani.bone.canvasmesh.SkinMeshCanvas { } class DeformAniData extends laya.ani.bone.DeformAniData { } class DeformSlotData extends laya.ani.bone.DeformSlotData { } class DeformSlotDisplayData extends laya.ani.bone.DeformSlotDisplayData { } class DrawOrderData extends laya.ani.bone.DrawOrderData { } class EventData extends laya.ani.bone.EventData { } class IkConstraint extends laya.ani.bone.IkConstraint { } class IkConstraintData extends laya.ani.bone.IkConstraintData { } class MeshTools extends laya.ani.bone.MeshTools { } class PathConstraint extends laya.ani.bone.PathConstraint { } class PathConstraintData extends laya.ani.bone.PathConstraintData { } class Skeleton extends laya.ani.bone.Skeleton { } class SkinData extends laya.ani.bone.SkinData { } class SkinSlotDisplayData extends laya.ani.bone.SkinSlotDisplayData { } class SlotData extends laya.ani.bone.SlotData { } class Templet extends laya.ani.bone.Templet { } class TfConstraint extends laya.ani.bone.TfConstraint { } class TfConstraintData extends laya.ani.bone.TfConstraintData { } class Transform extends laya.ani.bone.Transform { } class UVTools extends laya.ani.bone.UVTools { } class GraphicsAni extends laya.ani.GraphicsAni { } class KeyFramesContent extends laya.ani.KeyFramesContent { } class BezierLerp extends laya.ani.math.BezierLerp { } class MovieClip extends laya.ani.swf.MovieClip { } class AnimationClip extends laya.d3.animation.AnimationClip { } class AnimationClipParser01 extends laya.d3.animation.AnimationClipParser01 { } class AnimationClipParser02 extends laya.d3.animation.AnimationClipParser02 { } class AnimationEvent extends laya.d3.animation.AnimationEvent { } class AnimationNode extends laya.d3.animation.AnimationNode { } class AnimationTransform3D extends laya.d3.animation.AnimationTransform3D { } class Keyframe extends laya.d3.animation.Keyframe { } class KeyframeNode extends laya.d3.animation.KeyframeNode { } class KeyframeAnimations extends laya.d3.component.animation.KeyframeAnimations { } class RigidAnimations extends laya.d3.component.animation.RigidAnimations { } class SkinAnimations extends laya.d3.component.animation.SkinAnimations { } class Animator extends laya.d3.component.Animator { } class AttachPoint extends laya.d3.component.AttachPoint { } class Component3D extends laya.d3.component.Component3D { } class PathFind extends laya.d3.component.PathFind { } class BoxCollider extends laya.d3.component.physics.BoxCollider { } class Collider extends laya.d3.component.physics.Collider { } class MeshCollider extends laya.d3.component.physics.MeshCollider { } class SphereCollider extends laya.d3.component.physics.SphereCollider { } class Rigidbody extends laya.d3.component.Rigidbody { } class Script extends laya.d3.component.Script { } class Avatar extends laya.d3.core.Avatar { } class BaseCamera extends laya.d3.core.BaseCamera { } class Camera extends laya.d3.core.Camera { } class ComponentNode extends laya.d3.core.ComponentNode { } class GeometryFilter extends laya.d3.core.GeometryFilter { } class Glitter extends laya.d3.core.glitter.Glitter { } class SplineCurvePosition extends laya.d3.core.glitter.SplineCurvePosition { } class SplineCurvePositionVelocity extends laya.d3.core.glitter.SplineCurvePositionVelocity { } class GlitterRender extends laya.d3.core.GlitterRender { } class HeightMap extends laya.d3.core.HeightMap { } interface IClone extends laya.d3.core.IClone { } class Layer extends laya.d3.core.Layer { } class DirectionLight extends laya.d3.core.light.DirectionLight { } class LightSprite extends laya.d3.core.light.LightSprite { } class PointLight extends laya.d3.core.light.PointLight { } class SpotLight extends laya.d3.core.light.SpotLight { } class BaseMaterial extends laya.d3.core.material.BaseMaterial { } class BlinnPhongMaterial extends laya.d3.core.material.BlinnPhongMaterial { } class ExtendTerrainMaterial extends laya.d3.core.material.ExtendTerrainMaterial { } class GlitterMaterial extends laya.d3.core.material.GlitterMaterial { } class PBRMaterial extends laya.d3.core.material.PBRMaterial { } class PBRSpecularMaterial extends laya.d3.core.material.PBRSpecularMaterial { } class PBRStandardMaterial extends laya.d3.core.material.PBRStandardMaterial { } class StandardMaterial extends laya.d3.core.material.StandardMaterial { } class TerrainMaterial extends laya.d3.core.material.TerrainMaterial { } class WaterMaterial extends laya.d3.core.material.WaterMaterial { } class MeshFilter extends laya.d3.core.MeshFilter { } class MeshRender extends laya.d3.core.MeshRender { } class MeshSprite3D extends laya.d3.core.MeshSprite3D { } class MeshTerrainSprite3D extends laya.d3.core.MeshTerrainSprite3D { } class Burst extends laya.d3.core.particleShuriKen.module.Burst { } class ColorOverLifetime extends laya.d3.core.particleShuriKen.module.ColorOverLifetime { } class Emission extends laya.d3.core.particleShuriKen.module.Emission { } class FrameOverTime extends laya.d3.core.particleShuriKen.module.FrameOverTime { } class GradientAngularVelocity extends laya.d3.core.particleShuriKen.module.GradientAngularVelocity { } class GradientColor extends laya.d3.core.particleShuriKen.module.GradientColor { } class GradientDataColor extends laya.d3.core.particleShuriKen.module.GradientDataColor { } class GradientDataInt extends laya.d3.core.particleShuriKen.module.GradientDataInt { } class GradientDataNumber extends laya.d3.core.particleShuriKen.module.GradientDataNumber { } class GradientDataVector2 extends laya.d3.core.particleShuriKen.module.GradientDataVector2 { } class GradientSize extends laya.d3.core.particleShuriKen.module.GradientSize { } class GradientVelocity extends laya.d3.core.particleShuriKen.module.GradientVelocity { } class RotationOverLifetime extends laya.d3.core.particleShuriKen.module.RotationOverLifetime { } class BaseShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape { } class BoxShape extends laya.d3.core.particleShuriKen.module.shape.BoxShape { } class CircleShape extends laya.d3.core.particleShuriKen.module.shape.CircleShape { } class ConeShape extends laya.d3.core.particleShuriKen.module.shape.ConeShape { } class HemisphereShape extends laya.d3.core.particleShuriKen.module.shape.HemisphereShape { } class ShapeUtils extends laya.d3.core.particleShuriKen.module.shape.ShapeUtils { } class SphereShape extends laya.d3.core.particleShuriKen.module.shape.SphereShape { } class SizeOverLifetime extends laya.d3.core.particleShuriKen.module.SizeOverLifetime { } class StartFrame extends laya.d3.core.particleShuriKen.module.StartFrame { } class TextureSheetAnimation extends laya.d3.core.particleShuriKen.module.TextureSheetAnimation { } class VelocityOverLifetime extends laya.d3.core.particleShuriKen.module.VelocityOverLifetime { } class ShuriKenParticle3D extends laya.d3.core.particleShuriKen.ShuriKenParticle3D { } class ShurikenParticleData extends laya.d3.core.particleShuriKen.ShurikenParticleData { } class ShurikenParticleMaterial extends laya.d3.core.particleShuriKen.ShurikenParticleMaterial { } class ShurikenParticleRender extends laya.d3.core.particleShuriKen.ShurikenParticleRender { } class ShurikenParticleSystem extends laya.d3.core.particleShuriKen.ShurikenParticleSystem { } class PhasorSpriter3D extends laya.d3.core.PhasorSpriter3D { } class BaseRender extends laya.d3.core.render.BaseRender { } interface IRenderable extends laya.d3.core.render.IRenderable { } interface IUpdate extends laya.d3.core.render.IUpdate { } class RenderElement extends laya.d3.core.render.RenderElement { } class RenderQueue extends laya.d3.core.render.RenderQueue { } class RenderState extends laya.d3.core.render.RenderState { } class SubMeshRenderElement extends laya.d3.core.render.SubMeshRenderElement { } class RenderableSprite3D extends laya.d3.core.RenderableSprite3D { } interface ITreeNode extends laya.d3.core.scene.ITreeNode { } class OctreeNode extends laya.d3.core.scene.OctreeNode { } class Scene extends laya.d3.core.scene.Scene { } class SceneManager extends laya.d3.core.scene.SceneManager { } class SkinnedMeshRender extends laya.d3.core.SkinnedMeshRender { } class SkinnedMeshSprite3D extends laya.d3.core.SkinnedMeshSprite3D { } class Sprite3D extends laya.d3.core.Sprite3D { } class Color extends laya.d3.core.trail.module.Color { } class Gradient extends laya.d3.core.trail.module.Gradient { } class GradientAlphaKey extends laya.d3.core.trail.module.GradientAlphaKey { } class GradientColorKey extends laya.d3.core.trail.module.GradientColorKey { } class GradientMode extends laya.d3.core.trail.module.GradientMode { } class TextureMode extends laya.d3.core.trail.module.TextureMode { } class TrailKeyFrame extends laya.d3.core.trail.module.TrailKeyFrame { } class TrailFilter extends laya.d3.core.trail.TrailFilter { } class TrailMaterial extends laya.d3.core.trail.TrailMaterial { } class TrailRenderElement extends laya.d3.core.trail.TrailRenderElement { } class TrailRenderer extends laya.d3.core.trail.TrailRenderer { } class TrailSprite3D extends laya.d3.core.trail.TrailSprite3D { } class VertexTrail extends laya.d3.core.trail.VertexTrail { } class Transform3D extends laya.d3.core.Transform3D { } class TransformUV extends laya.d3.core.TransformUV { } class VRCamera extends laya.d3.core.VRCamera { } class CartoonMaterial extends laya.d3.extension.cartoonRender.CartoonMaterial { } class OutlineMaterial extends laya.d3.extension.cartoonRender.OutlineMaterial { } class DynamicBatch extends laya.d3.graphics.DynamicBatch { } class DynamicBatchManager extends laya.d3.graphics.DynamicBatchManager { } class FrustumCulling extends laya.d3.graphics.FrustumCulling { } class IndexBuffer3D extends laya.d3.graphics.IndexBuffer3D { } interface IVertex extends laya.d3.graphics.IVertex { } class MeshSprite3DStaticBatchManager extends laya.d3.graphics.MeshSprite3DStaticBatchManager { } class StaticBatch extends laya.d3.graphics.StaticBatch { } class StaticBatchManager extends laya.d3.graphics.StaticBatchManager { } class SubMeshStaticBatch extends laya.d3.graphics.SubMeshStaticBatch { } class VertexBuffer3D extends laya.d3.graphics.VertexBuffer3D { } class VertexDeclaration extends laya.d3.graphics.VertexDeclaration { } class VertexElement extends laya.d3.graphics.VertexElement { } class VertexElementFormat extends laya.d3.graphics.VertexElementFormat { } class VertexElementUsage extends laya.d3.graphics.VertexElementUsage { } class VertexGlitter extends laya.d3.graphics.VertexGlitter { } class VertexParticle extends laya.d3.graphics.VertexParticle { } class VertexPosition extends laya.d3.graphics.VertexPosition { } class VertexPositionNormal extends laya.d3.graphics.VertexPositionNormal { } class VertexPositionNormalColor extends laya.d3.graphics.VertexPositionNormalColor { } class VertexPositionNormalColorSkin extends laya.d3.graphics.VertexPositionNormalColorSkin { } class VertexPositionNormalColorSkinSTangent extends laya.d3.graphics.VertexPositionNormalColorSkinSTangent { } class VertexPositionNormalColorSkinTangent extends laya.d3.graphics.VertexPositionNormalColorSkinTangent { } class VertexPositionNormalColorSTangent extends laya.d3.graphics.VertexPositionNormalColorSTangent { } class VertexPositionNormalColorTangent extends laya.d3.graphics.VertexPositionNormalColorTangent { } class VertexPositionNormalColorTexture extends laya.d3.graphics.VertexPositionNormalColorTexture { } class VertexPositionNormalColorTexture0Texture1 extends laya.d3.graphics.VertexPositionNormalColorTexture0Texture1 { } class VertexPositionNormalColorTexture0Texture1Skin extends laya.d3.graphics.VertexPositionNormalColorTexture0Texture1Skin { } class VertexPositionNormalColorTexture0Texture1SkinSTangent extends laya.d3.graphics.VertexPositionNormalColorTexture0Texture1SkinSTangent { } class VertexPositionNormalColorTexture0Texture1SkinTangent extends laya.d3.graphics.VertexPositionNormalColorTexture0Texture1SkinTangent { } class VertexPositionNormalColorTexture0Texture1STangent extends laya.d3.graphics.VertexPositionNormalColorTexture0Texture1STangent { } class VertexPositionNormalColorTexture0Texture1Tangent extends laya.d3.graphics.VertexPositionNormalColorTexture0Texture1Tangent { } class VertexPositionNormalColorTextureSkin extends laya.d3.graphics.VertexPositionNormalColorTextureSkin { } class VertexPositionNormalColorTextureSkinSTangent extends laya.d3.graphics.VertexPositionNormalColorTextureSkinSTangent { } class VertexPositionNormalColorTextureSkinTangent extends laya.d3.graphics.VertexPositionNormalColorTextureSkinTangent { } class VertexPositionNormalColorTextureSTangent extends laya.d3.graphics.VertexPositionNormalColorTextureSTangent { } class VertexPositionNormalColorTextureTangent extends laya.d3.graphics.VertexPositionNormalColorTextureTangent { } class VertexPositionNormalSTangent extends laya.d3.graphics.VertexPositionNormalSTangent { } class VertexPositionNormalTangent extends laya.d3.graphics.VertexPositionNormalTangent { } class VertexPositionNormalTexture extends laya.d3.graphics.VertexPositionNormalTexture { } class VertexPositionNormalTexture0Texture1 extends laya.d3.graphics.VertexPositionNormalTexture0Texture1 { } class VertexPositionNormalTexture0Texture1Skin extends laya.d3.graphics.VertexPositionNormalTexture0Texture1Skin { } class VertexPositionNormalTexture0Texture1SkinSTangent extends laya.d3.graphics.VertexPositionNormalTexture0Texture1SkinSTangent { } class VertexPositionNormalTexture0Texture1SkinTangent extends laya.d3.graphics.VertexPositionNormalTexture0Texture1SkinTangent { } class VertexPositionNormalTexture0Texture1STangent extends laya.d3.graphics.VertexPositionNormalTexture0Texture1STangent { } class VertexPositionNormalTexture0Texture1Tangent extends laya.d3.graphics.VertexPositionNormalTexture0Texture1Tangent { } class VertexPositionNormalTextureSkin extends laya.d3.graphics.VertexPositionNormalTextureSkin { } class VertexPositionNormalTextureSkinSTangent extends laya.d3.graphics.VertexPositionNormalTextureSkinSTangent { } class VertexPositionNormalTextureSkinTangent extends laya.d3.graphics.VertexPositionNormalTextureSkinTangent { } class VertexPositionNormalTextureSTangent extends laya.d3.graphics.VertexPositionNormalTextureSTangent { } class VertexPositionNormalTextureTangent extends laya.d3.graphics.VertexPositionNormalTextureTangent { } class VertexPositionNTBTexture extends laya.d3.graphics.VertexPositionNTBTexture { } class VertexPositionNTBTexture0Texture1Skin extends laya.d3.graphics.VertexPositionNTBTexture0Texture1Skin { } class VertexPositionNTBTextureSkin extends laya.d3.graphics.VertexPositionNTBTextureSkin { } class VertexPositionTerrain extends laya.d3.graphics.VertexPositionTerrain { } class VertexPositionTexture0 extends laya.d3.graphics.VertexPositionTexture0 { } class VertexShurikenParticleBillboard extends laya.d3.graphics.VertexShurikenParticleBillboard { } class VertexShurikenParticleMesh extends laya.d3.graphics.VertexShurikenParticleMesh { } class LoadModelV01 extends laya.d3.loaders.LoadModelV01 { } class LoadModelV02 extends laya.d3.loaders.LoadModelV02 { } class LoadModelV03 extends laya.d3.loaders.LoadModelV03 { } class MeshReader extends laya.d3.loaders.MeshReader { } class BoundBox extends laya.d3.math.BoundBox { } class BoundFrustum extends laya.d3.math.BoundFrustum { } class BoundSphere extends laya.d3.math.BoundSphere { } class Collision extends laya.d3.math.Collision { } class ContainmentType extends laya.d3.math.ContainmentType { } class MathUtils3D extends laya.d3.math.MathUtils3D { } class Matrix3x3 extends laya.d3.math.Matrix3x3 { } class Matrix4x4 extends laya.d3.math.Matrix4x4 { } class OrientedBoundBox extends laya.d3.math.OrientedBoundBox { } class Plane extends laya.d3.math.Plane { } class Quaternion extends laya.d3.math.Quaternion { } class Rand extends laya.d3.math.Rand { } class RandX extends laya.d3.math.RandX { } class Ray extends laya.d3.math.Ray { } class Vector2 extends laya.d3.math.Vector2 { } class Vector3 extends laya.d3.math.Vector3 { } class Vector4 extends laya.d3.math.Vector4 { } class Viewport extends laya.d3.math.Viewport { } class BaseTexture extends laya.d3.resource.BaseTexture { } class DataTexture2D extends laya.d3.resource.DataTexture2D { } class BaseMesh extends laya.d3.resource.models.BaseMesh { } class BoxMesh extends laya.d3.resource.models.BoxMesh { } class CapsuleMesh extends laya.d3.resource.models.CapsuleMesh { } class CylinderMesh extends laya.d3.resource.models.CylinderMesh { } class Mesh extends laya.d3.resource.models.Mesh { } class PlaneMesh extends laya.d3.resource.models.PlaneMesh { } class PrimitiveMesh extends laya.d3.resource.models.PrimitiveMesh { } class QuadMesh extends laya.d3.resource.models.QuadMesh { } class Sky extends laya.d3.resource.models.Sky { } class SkyBox extends laya.d3.resource.models.SkyBox { } class SkyDome extends laya.d3.resource.models.SkyDome { } class SphereMesh extends laya.d3.resource.models.SphereMesh { } class SubMesh extends laya.d3.resource.models.SubMesh { } class RenderTexture extends laya.d3.resource.RenderTexture { } class SolidColorTexture2D extends laya.d3.resource.SolidColorTexture2D { } class SolidColorTextureCube extends laya.d3.resource.SolidColorTextureCube { } class GlitterTemplet extends laya.d3.resource.tempelet.GlitterTemplet { } class Texture2D extends laya.d3.resource.Texture2D { } class TextureCube extends laya.d3.resource.TextureCube { } class Shader3D extends laya.d3.shader.Shader3D { } class ShaderCompile3D extends laya.d3.shader.ShaderCompile3D { } class ShaderDefines extends laya.d3.shader.ShaderDefines { } class ShaderInit3D extends laya.d3.shader.ShaderInit3D { } class ValusArray extends laya.d3.shader.ValusArray { } class ParallelSplitShadowMap extends laya.d3.shadowMap.ParallelSplitShadowMap { } class Terrain extends laya.d3.terrain.Terrain { } class TerrainChunk extends laya.d3.terrain.TerrainChunk { } class TerrainFilter extends laya.d3.terrain.TerrainFilter { } class TerrainHeightData extends laya.d3.terrain.TerrainHeightData { } class TerrainLeaf extends laya.d3.terrain.TerrainLeaf { } class TerrainRender extends laya.d3.terrain.TerrainRender { } class TerrainRes extends laya.d3.terrain.TerrainRes { } class ChunkInfo extends laya.d3.terrain.unit.ChunkInfo { } class DetailTextureInfo extends laya.d3.terrain.unit.DetailTextureInfo { } class MaterialInfo extends laya.d3.terrain.unit.MaterialInfo { } class CollisionManager extends laya.d3.utils.CollisionManager { } class Physics extends laya.d3.utils.Physics { } class Picker extends laya.d3.utils.Picker { } class RaycastHit extends laya.d3.utils.RaycastHit { } class Size extends laya.d3.utils.Size { } class Utils3D extends laya.d3.utils.Utils3D { } class WaterDetailMaterial extends laya.d3.water.WaterDetailMaterial { } class WaterRender extends laya.d3.water.WaterRender { } class Geolocation extends laya.device.geolocation.Geolocation { } class GeolocationInfo extends laya.device.geolocation.GeolocationInfo { } class HtmlVideo extends laya.device.media.HtmlVideo { } class Media extends laya.device.media.Media { } class Video extends laya.device.media.Video { } class WebGLVideo extends laya.device.media.WebGLVideo { } class AccelerationInfo extends laya.device.motion.AccelerationInfo { } class Accelerator extends laya.device.motion.Accelerator { } class Gyroscope extends laya.device.motion.Gyroscope { } class RotationInfo extends laya.device.motion.RotationInfo { } class Shake extends laya.device.Shake { } class Animation extends laya.display.Animation { } class AnimationPlayerBase extends laya.display.AnimationPlayerBase { } class BitmapFont extends laya.display.BitmapFont { } class CSSStyle extends laya.display.css.CSSStyle { } class Font extends laya.display.css.Font { } class Style extends laya.display.css.Style { } class TransformInfo extends laya.display.css.TransformInfo { } class EffectAnimation extends laya.display.EffectAnimation { } class FrameAnimation extends laya.display.FrameAnimation { } class Graphics extends laya.display.Graphics { } class GraphicsBounds extends laya.display.GraphicsBounds { } interface ILayout extends laya.display.ILayout { } class Input extends laya.display.Input { } class Node extends laya.display.Node { } class Sprite extends laya.display.Sprite { } class Stage extends laya.display.Stage { } class Text extends laya.display.Text { } class Event extends laya.events.Event { } class EventDispatcher extends laya.events.EventDispatcher { } class Keyboard extends laya.events.Keyboard { } class KeyBoardManager extends laya.events.KeyBoardManager { } class KeyLocation extends laya.events.KeyLocation { } class MouseManager extends laya.events.MouseManager { } class TouchManager extends laya.events.TouchManager { } class BlurFilter extends laya.filters.BlurFilter { } class ColorFilter extends laya.filters.ColorFilter { } class ColorFilterAction extends laya.filters.ColorFilterAction { } class Filter extends laya.filters.Filter { } class FilterAction extends laya.filters.FilterAction { } class GlowFilter extends laya.filters.GlowFilter { } interface IFilter extends laya.filters.IFilter { } interface IFilterAction extends laya.filters.IFilterAction { } interface IFilterActionGL extends laya.filters.IFilterActionGL { } class BlurFilterActionGL extends laya.filters.webgl.BlurFilterActionGL { } class ColorFilterActionGL extends laya.filters.webgl.ColorFilterActionGL { } class FilterActionGL extends laya.filters.webgl.FilterActionGL { } class GlowFilterActionGL extends laya.filters.webgl.GlowFilterActionGL { } class WebGLFilter extends laya.filters.WebGLFilter { } class HTMLBrElement extends laya.html.dom.HTMLBrElement { } class HTMLDivElement extends laya.html.dom.HTMLDivElement { } class HTMLDocument extends laya.html.dom.HTMLDocument { } class HTMLElement extends laya.html.dom.HTMLElement { } class HTMLIframeElement extends laya.html.dom.HTMLIframeElement { } class HTMLImageElement extends laya.html.dom.HTMLImageElement { } class HTMLLinkElement extends laya.html.dom.HTMLLinkElement { } class HTMLStyleElement extends laya.html.dom.HTMLStyleElement { } class HTMLParse extends laya.html.utils.HTMLParse { } class Layout extends laya.html.utils.Layout { } class LayoutLine extends laya.html.utils.LayoutLine { } class GridSprite extends laya.map.GridSprite { } class MapLayer extends laya.map.MapLayer { } class TileAniSprite extends laya.map.TileAniSprite { } class TiledMap extends laya.map.TiledMap { } class TileTexSet extends laya.map.TileTexSet { } class Arith extends laya.maths.Arith { } class Bezier extends laya.maths.Bezier { } class GrahamScan extends laya.maths.GrahamScan { } class MathUtil extends laya.maths.MathUtil { } class Matrix extends laya.maths.Matrix { } class Point extends laya.maths.Point { } class Rectangle extends laya.maths.Rectangle { } class AudioSound extends laya.media.h5audio.AudioSound { } class AudioSoundChannel extends laya.media.h5audio.AudioSoundChannel { } class Sound extends laya.media.Sound { } class SoundChannel extends laya.media.SoundChannel { } class SoundManager extends laya.media.SoundManager { } class SoundNode extends laya.media.SoundNode { } class WebAudioSound extends laya.media.webaudio.WebAudioSound { } class WebAudioSoundChannel extends laya.media.webaudio.WebAudioSoundChannel { } class HttpRequest extends laya.net.HttpRequest { } class Loader extends laya.net.Loader { } class LoaderManager extends laya.net.LoaderManager { } class LocalStorage extends laya.net.LocalStorage { } class ResourceVersion extends laya.net.ResourceVersion { } class Socket extends laya.net.Socket { } class TTFLoader extends laya.net.TTFLoader { } class URL extends laya.net.URL { } class WorkerLoader extends laya.net.WorkerLoader { } class Emitter2D extends laya.particle.emitter.Emitter2D { } class EmitterBase extends laya.particle.emitter.EmitterBase { } class Particle2D extends laya.particle.Particle2D { } class ParticleData extends laya.particle.ParticleData { } class ParticleEmitter extends laya.particle.ParticleEmitter { } class ParticleSetting extends laya.particle.ParticleSetting { } class ParticleTemplate2D extends laya.particle.ParticleTemplate2D { } class ParticleTemplateBase extends laya.particle.ParticleTemplateBase { } class ParticleTemplateCanvas extends laya.particle.ParticleTemplateCanvas { } class ParticleTemplateWebGL extends laya.particle.ParticleTemplateWebGL { } class CanvasShader extends laya.particle.particleUtils.CanvasShader { } class CMDParticle extends laya.particle.particleUtils.CMDParticle { } class PicTool extends laya.particle.particleUtils.PicTool { } class ParticleShader extends laya.particle.shader.ParticleShader { } class ParticleShaderValue extends laya.particle.shader.value.ParticleShaderValue { } class Render extends laya.renders.Render { } class RenderContext extends laya.renders.RenderContext { } class RenderSprite extends laya.renders.RenderSprite { } class Bitmap extends laya.resource.Bitmap { } class Context extends laya.resource.Context { } class FileBitmap extends laya.resource.FileBitmap { } class HTMLCanvas extends laya.resource.HTMLCanvas { } class HTMLImage extends laya.resource.HTMLImage { } class HTMLSubImage extends laya.resource.HTMLSubImage { } interface ICreateResource extends laya.resource.ICreateResource { } interface IDestroy extends laya.resource.IDestroy { } interface IDispose extends laya.resource.IDispose { } class Resource extends laya.resource.Resource { } class ResourceManager extends laya.resource.ResourceManager { } class Texture extends laya.resource.Texture { } interface IConchNode extends laya.runtime.IConchNode { } interface IConchRenderObject extends laya.runtime.IConchRenderObject { } interface ICPlatformClass extends laya.runtime.ICPlatformClass { } interface IMarket extends laya.runtime.IMarket { } interface IPlatform extends laya.runtime.IPlatform { } interface IPlatformClass extends laya.runtime.IPlatformClass { } class System extends laya.system.System { } class AsynDialog extends laya.ui.AsynDialog { } class AutoBitmap extends laya.ui.AutoBitmap { } class Box extends laya.ui.Box { } class Button extends laya.ui.Button { } class CheckBox extends laya.ui.CheckBox { } class Clip extends laya.ui.Clip { } class ColorPicker extends laya.ui.ColorPicker { } class ComboBox extends laya.ui.ComboBox { } class Component extends laya.ui.Component { } class Dialog extends laya.ui.Dialog { } class DialogManager extends laya.ui.DialogManager { } class FontClip extends laya.ui.FontClip { } class HBox extends laya.ui.HBox { } class HScrollBar extends laya.ui.HScrollBar { } class HSlider extends laya.ui.HSlider { } interface IBox extends laya.ui.IBox { } interface IComponent extends laya.ui.IComponent { } interface IItem extends laya.ui.IItem { } class Image extends laya.ui.Image { } interface IRender extends laya.ui.IRender { } interface ISelect extends laya.ui.ISelect { } class Label extends laya.ui.Label { } class LayoutBox extends laya.ui.LayoutBox { } class LayoutStyle extends laya.ui.LayoutStyle { } class List extends laya.ui.List { } class Panel extends laya.ui.Panel { } class ProgressBar extends laya.ui.ProgressBar { } class Radio extends laya.ui.Radio { } class RadioGroup extends laya.ui.RadioGroup { } class ScrollBar extends laya.ui.ScrollBar { } class Slider extends laya.ui.Slider { } class Styles extends laya.ui.Styles { } class Tab extends laya.ui.Tab { } class TextArea extends laya.ui.TextArea { } class TextInput extends laya.ui.TextInput { } class TipManager extends laya.ui.TipManager { } class Tree extends laya.ui.Tree { } class UIEvent extends laya.ui.UIEvent { } class UIGroup extends laya.ui.UIGroup { } class UIUtils extends laya.ui.UIUtils { } class VBox extends laya.ui.VBox { } class View extends laya.ui.View { } class ViewStack extends laya.ui.ViewStack { } class VScrollBar extends laya.ui.VScrollBar { } class VSlider extends laya.ui.VSlider { } class Browser extends laya.utils.Browser { } class Byte extends laya.utils.Byte { } class CacheManager extends laya.utils.CacheManager { } class ClassUtils extends laya.utils.ClassUtils { } class Dictionary extends laya.utils.Dictionary { } class Dragging extends laya.utils.Dragging { } class Ease extends laya.utils.Ease { } class GraphicAnimation extends laya.utils.GraphicAnimation { } class Handler extends laya.utils.Handler { } class HitArea extends laya.utils.HitArea { } class HTMLChar extends laya.utils.HTMLChar { } class Log extends laya.utils.Log { } class Mouse extends laya.utils.Mouse { } class Pool extends laya.utils.Pool { } class PoolCache extends laya.utils.PoolCache { } class RunDriver extends laya.utils.RunDriver { } class Stat extends laya.utils.Stat { } class StringKey extends laya.utils.StringKey { } class TimeLine extends laya.utils.TimeLine { } class Timer extends laya.utils.Timer { } class Tween extends laya.utils.Tween { } class Utils extends laya.utils.Utils { } class VectorGraphManager extends laya.utils.VectorGraphManager { } class WeakObject extends laya.utils.WeakObject { } class WordText extends laya.utils.WordText { } class Atlaser extends laya.webgl.atlas.Atlaser { } class AtlasGrid extends laya.webgl.atlas.AtlasGrid { } class AtlasResourceManager extends laya.webgl.atlas.AtlasResourceManager { } class AtlasWebGLCanvas extends laya.webgl.atlas.AtlasWebGLCanvas { } class MergeFillInfo extends laya.webgl.atlas.MergeFillInfo { } class BlendMode extends laya.webgl.canvas.BlendMode { } class DrawStyle extends laya.webgl.canvas.DrawStyle { } class Path extends laya.webgl.canvas.Path { } class GraphicsGL extends laya.webgl.display.GraphicsGL { } interface IMergeAtlasBitmap extends laya.webgl.resource.IMergeAtlasBitmap { } class WebGLCanvas extends laya.webgl.resource.WebGLCanvas { } class WebGLCharImage extends laya.webgl.resource.WebGLCharImage { } class WebGLImage extends laya.webgl.resource.WebGLImage { } class WebGLRenderTarget extends laya.webgl.resource.WebGLRenderTarget { } class WebGLSubImage extends laya.webgl.resource.WebGLSubImage { } class BaseShader extends laya.webgl.shader.BaseShader { } class Shader2D extends laya.webgl.shader.d2.Shader2D { } class Shader2X extends laya.webgl.shader.d2.Shader2X { } class ShaderDefines2D extends laya.webgl.shader.d2.ShaderDefines2D { } class SkinMesh extends laya.webgl.shader.d2.skinAnishader.SkinMesh { } class SkinMeshBuffer extends laya.webgl.shader.d2.skinAnishader.SkinMeshBuffer { } class SkinSV extends laya.webgl.shader.d2.skinAnishader.SkinSV { } class Color2dSV extends laya.webgl.shader.d2.value.Color2dSV { } class FillTextureSV extends laya.webgl.shader.d2.value.FillTextureSV { } class GlowSV extends laya.webgl.shader.d2.value.GlowSV { } class PrimitiveSV extends laya.webgl.shader.d2.value.PrimitiveSV { } class TextSV extends laya.webgl.shader.d2.value.TextSV { } class TextureSV extends laya.webgl.shader.d2.value.TextureSV { } class Value2D extends laya.webgl.shader.d2.value.Value2D { } class Shader extends laya.webgl.shader.Shader { } class ShaderValue extends laya.webgl.shader.ShaderValue { } class BasePoly extends laya.webgl.shapes.BasePoly { } class Earcut extends laya.webgl.shapes.Earcut { } class EarcutNode extends laya.webgl.shapes.EarcutNode { } class Ellipse extends laya.webgl.shapes.Ellipse { } class GeometryData extends laya.webgl.shapes.GeometryData { } interface IShape extends laya.webgl.shapes.IShape { } class Line extends laya.webgl.shapes.Line { } class LoopLine extends laya.webgl.shapes.LoopLine { } class Polygon extends laya.webgl.shapes.Polygon { } class Vertex extends laya.webgl.shapes.Vertex { } interface ISubmit extends laya.webgl.submit.ISubmit { } class SubmitCMD extends laya.webgl.submit.SubmitCMD { } class SubmitCMDScope extends laya.webgl.submit.SubmitCMDScope { } class CharSegment extends laya.webgl.text.CharSegment { } class FontInContext extends laya.webgl.text.FontInContext { } interface ICharSegment extends laya.webgl.text.ICharSegment { } class Buffer extends laya.webgl.utils.Buffer { } class Buffer2D extends laya.webgl.utils.Buffer2D { } class CONST3D2D extends laya.webgl.utils.CONST3D2D { } class GlUtils extends laya.webgl.utils.GlUtils { } class IndexBuffer2D extends laya.webgl.utils.IndexBuffer2D { } class MatirxArray extends laya.webgl.utils.MatirxArray { } class Mesh2D extends laya.webgl.utils.Mesh2D { } class RenderSprite3D extends laya.webgl.utils.RenderSprite3D { } class ShaderCompile extends laya.webgl.utils.ShaderCompile { } class VertexBuffer2D extends laya.webgl.utils.VertexBuffer2D { } class WebGL extends laya.webgl.WebGL { } class WebGLContext extends laya.webgl.WebGLContext { } // class Node extends PathFinding.core.Node { // } class DebugPanel extends laya.debug.DebugPanel { } class DebugTool extends laya.debug.DebugTool { } } declare class Laya3D { /** * 初始化Laya3D相关设置。 * @param width 3D画布宽度。 * @param height 3D画布高度。 */ static init(width:number, height:number, antialias?:boolean, alpha?:boolean, premultipliedAlpha?:boolean):void } /** * Laya 是全局对象的引用入口集。 */ declare class Laya { /** 舞台对象的引用。*/ static stage: laya.display.Stage; /** 时间管理器的引用。*/ static timer: laya.utils.Timer; /** 加载管理器的引用。*/ static loader: laya.net.LoaderManager; /** Render 类的引用。*/ static render: laya.renders.Render; /** 引擎版本。*/ static version: string; /**@private */ static stageBox: laya.display.Sprite; /**Market对象 只有加速器模式下才有值*/ static conchMarket: laya.runtime.IMarket; /**PlatformClass类,只有加速器模式下才有值 */ static PlatformClass: laya.runtime.ICPlatformClass; /** * 初始化引擎。 * @param width 游戏窗口宽度。 * @param height 游戏窗口高度。 * @param 插件列表,比如 WebGL。 * @return 返回原生canvas,方便控制 */ static init(width: number, height: number, ...plugins: any[]): any; /** * 表示是否捕获全局错误并弹出提示。 */ static alertGlobalError: boolean; static class(functionRef:Function, fullQulifiedName:String, superClass:Function, miniName:String):void; /** * JS中为目标定义getter/setter。 * function getter() { console.log('getter'); } * function setter(val) { console.log('setter'); } * Laya.getset(true, Laya.Sprite, "foo", getter, setter); * 上述代码为Laya.Sprite类加入了名为foo的getter/setter。通过Laya.Sprite.foo和Laya.Sprite.foo = val即可触发对应函数。 * 下面的代码为Laya.Sprite实例加入名为foo的getter/setter。 * function getter() { console.log('getter'); } function setter(val) { console.log('setter'); } var sp = new Laya.Sprite(); Laya.getset(false, sp, "foo", getter, setter); 通过sp.foo和sp.foo = val即可触发对应函数。 * @param isStatic * @param target * @param name * @param getter * @param setter */ static getset(isStatic:Boolean, target:any, name:String, getter:Function, setter:Function):void; /** * JS中实现接口。如: 使Myclass实现接口a.interface: Laya.imps(Myclass.prototype, { a.interface: true}); * 使MyClass2实现接口a.interface和a.interface2: Laya.imps(MyClass2.prototype, { a.interface: true, a.interface2: true}); * @param prototypeChain * @param superInterfaces */ static imps(prototypeChain:any, superInterfaces:Object):void; /** * JS中定义接口。如 Laya.interface("a.b.myinterface", null); Laya.interface("a.b.myInterface2", BaseInterface); * @param name * @param superClass */ static interface(name:String, superClass:Function):void; static superSet(clas:any,o:any,prop:any,value:any); static superGet(clas:any,o:any,prop:any); } /**全局配置*/ declare class UIConfig { /**是否开启触摸滚动(针对滚动条)*/ public static touchScrollEnable:boolean; /**是否开启滑轮滚动(针对滚动条)*/ public static mouseWheelEnable:boolean ; /**是否显示滚动条按钮*/ public static showButtons:boolean; /**弹出框背景颜色*/ public static popupBgColor:string; /**弹出框背景透明度*/ public static popupBgAlpha:number; /**模式窗口点击边缘,是否关闭窗口,默认是关闭的*/ public static closeDialogOnSide:boolean; } /** * Config 用于配置一些全局参数。 */ declare class Config { /** * WebGL模式下文本缓存最大数量。 */ public static WebGLTextCacheCount:number; /** * 表示是否使用了大图合集功能。 */ public static atlasEnable:boolean; /** * 是否显示画布图边框,用于调试。 */ public static showCanvasMark:boolean; /** * 动画 Animation 的默认播放时间间隔,单位为毫秒。 */ public static animationInterval:number; /** * 设置是否抗锯齿,只对2D(WebGL)、3D有效。 */ public static isAntialias:boolean; /** * 设置画布是否透明,只对2D(WebGL)、3D有效。 */ public static isAlpha:boolean; /** * 设置画布是否预乘,只对2D(WebGL)、3D有效。 */ public static premultipliedAlpha:boolean; /** * 设置画布的模板缓冲,只对2D(WebGL)、3D有效。 */ public static isStencil:boolean; /** * 是否强制WebGL同步刷新。 */ public static preserveDrawingBuffer:boolean; } declare module laya.debug { /** * * @author ww * @version 1.0 * * @created 2015-9-24 下午3:00:38 */ class DebugTool { static init(cacheAnalyseEnable?: boolean, loaderAnalyseEnable?: boolean, createAnalyseEnable?: boolean, renderAnalyseEnable?: boolean): void; } } declare module laya.debug{ class DebugPanel{ /** * 初始化调试面板 * @param underGame 是否在游戏下方显示,true:将改变原游戏的大小,false:直接覆盖在游戏上方 * @param bgColor 调试面板背景颜色 * */ static init(underGame?:boolean,bgColor?:string):void; } } /** * ETH区块链相关 */ declare class LayaGCS{ /* ETH的功能类实例,封装了bip协议以及账户签名算法 */ static ETHBip:Object; /* 得到当前已经unlock的ETH账户,如果是undefined说明玩家还没登陆 */ static get_current_account():string; /* 初始化LayaGCS,需要传入Laya.stage根节点以及网络network //初始化LayaGCS LayaGCS.initlize({ laya_stage_node:laya.stage, //Laya Air根节点 network:0 //ETH区块链网络(0位测试网络Rinkedby , 1为正式网络MainNet) auto_load_last_account:false //自动读取上次登入的账户 }) */ static initlize(t:Object):void; /* 是否已经初始化完成 */ static initlized:boolean; /* 当前使用的区块链网络,0为Rinkedby , 1是正式网络 */ static network:number; /* sdk资源回调完成 */ static onSDKResouceLoaded():void; /* 设置初始化完成回调 */ static set_inited_callback(t:Function):void; /* 打开登陆界面(如果已经登录,进入账户界面) */ static show_login_ui(t:any):void; /* 已经设定的Laya.stage */ static target_stage:Object; /* 这是一个完整的web3实例。LayaGCS的web3有一些改动。 由于LayaOne提供了一个全节点,所以游戏前端无需同步区块数据 为了更好的游戏体验,LayaGCS.web3不再提供同步方法,例如 var balance = web3.eth.getBalance(LayaGCS.get_default_account()); //同步的写法,LayaGCS不再支持 支持的写法 1. co(function*(){ var balance = yield function(done){ web3.eth.getBalance(LayaGCS.get_default_account(),done) } console.log('账户余额为',balalnce) }) 2. web3.eth.getBalance(LayaGCS.get_default_account,function(err,result){ console.log(result) }) */ static web3:Object; } ================================================ FILE: src/@types/layaAir.minigame.d.ts ================================================ declare module laya.wx.mini { import Handler = laya.utils.Handler; class MiniAdpter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.bd.mini { import Handler = laya.utils.Handler; class BMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.mi.mini { import Handler = laya.utils.Handler; class KGMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.qg.mini { import Handler = laya.utils.Handler; class QGMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.vv.mini { import Handler = laya.utils.Handler; class VVMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.bili.mini { import Handler = laya.utils.Handler; class BLMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.Alipay.mini { import Handler = laya.utils.Handler; class ALIMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.qq.mini { import Handler = laya.utils.Handler; class QQMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.tt.mini { import Handler = laya.utils.Handler; class TTMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.hw.mini { import Handler = laya.utils.Handler; class HWMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.tb.mini { import Handler = laya.utils.Handler; class TBMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.yk.mini { import Handler = laya.utils.Handler; class YKMiniAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module laya.tbplugin.mini { import Handler = laya.utils.Handler; class TBPluginAdapter { static EnvConfig: any; /**全局window对象**/ static window: any; static systemInfo: any; static isZiYu: boolean; static isPosMsgYu: boolean; /**是否自动缓存下载的图片跟声音文件,默认为true**/ static autoCacheFile: boolean; /**50M缓存容量满时每次清理容量值,默认每次清理5M**/ static minClearSize: number; /**本地资源列表**/ static nativefiles: Array; /**本地分包资源表**/ static subNativeFiles: any; /**本地分包文件目录数组**/ static subNativeheads: Array; /**本地分包文件目录映射表**/ static subMaps: Array; static AutoCacheDownFile: boolean; static getJson(data: string): any; /**激活微信小游戏适配器*/ static enable(): void; /** * 初始化回调 * @param isPosMsg 是否需要在主域中自动将加载的文本数据自动传递到子域,默认 false * @param isSon 是否是子域,默认为false */ static init(isPosMsg?: boolean, isSon?: boolean): void; /** * 获取url对应的encoding值 * @param url 文件路径 * @param type 文件类型 * @return */ static getUrlEncode(url: string, type: string): string; /** * 下载文件 * @param fileUrl 文件地址(全路径) * @param fileType 文件类型(image、text、json、xml、arraybuffer、sound、atlas、font) * @param callBack 文件加载回调,回调内容[errorCode码(0成功,1失败,2加载进度) * @param encoding 文件编码默认utf8,非图片文件加载需要设置相应的编码,二进制编码为空字符串 */ static downLoadFile(fileUrl: string, fileType?: string, callBack?: Handler, encoding?: string): void; /** * 从本地删除文件 * @param fileUrl 文件地址(全路径) * @param callBack 回调处理,在存储图片时用到 */ static remove(fileUrl: string, callBack?: Handler): void; /** * 清空缓存空间文件内容 */ static removeAll(): void; /** * 判断是否是4M包文件 * @param fileUrl 文件地址(全路径) * @return */ static hasNativeFile(fileUrl: string): boolean; /** * 判断缓存里是否存在文件 * @param fileUrl 文件地址(全路径) * @return */ static getFileInfo(fileUrl: string): any; /** * 获取缓存文件列表 * @return */ static getFileList(): any; static exitMiniProgram(): void; static pixelRatio(): number; static createElement(type: string): any; static createShaderCondition(conditionScript: string): Function; /** * 传递图集url地址到 * @param url 为绝对地址 */ static sendAtlasToOpenDataContext(url: string): void; /** * 发送单张图片到开放数据域 * @param url */ static sendSinglePicToOpenDataContext(url: string): void; /** * 传递json配置数据到开放数据域 * @param url 为绝对地址 */ static sendJsonDataToDataContext(url: string): void; } } declare module Laya { class MiniAdpter extends laya.wx.mini.MiniAdpter { } class BMiniAdapter extends laya.bd.mini.BMiniAdapter { } class KGMiniAdapter extends laya.mi.mini.KGMiniAdapter { } class QGMiniAdapter extends laya.qg.mini.QGMiniAdapter { } class VVMiniAdapter extends laya.vv.mini.VVMiniAdapter { } class BLMiniAdapter extends laya.bili.mini.BLMiniAdapter { } class ALIMiniAdapter extends laya.Alipay.mini.ALIMiniAdapter { } class QQMiniAdapter extends laya.qq.mini.QQMiniAdapter { } class TTMiniAdapter extends laya.tt.mini.TTMiniAdapter { } class HWMiniAdapter extends laya.hw.mini.HWMiniAdapter { } class TBMiniAdapter extends laya.tb.mini.TBMiniAdapter { } class YKMiniAdapter extends laya.yk.mini.YKMiniAdapter { } class TBPluginAdapter extends laya.tbplugin.mini.TBPluginAdapter { } } ================================================ FILE: src/@types/union.d.ts ================================================ interface CanvasContext { /** * 创建一个颜色的渐变点。 */ addColorStop: () => void; /** * 画一条弧线。 */ arc: () => void; /** * 开始创建一个路径,需要调用fill或者stroke才会使用路径进行填充或描边。 */ beginPath: () => void; /** * 创建三次方贝塞尔曲线路径。 */ bezierCurveTo: () => void; /** * 清空绘图上下文的绘图动作。 */ clearActions: () => void; /** * 清除画布上在该矩形区域内的内容。 */ clearRect: () => void; /** * clip() 方法从原始画布中剪切任意形状和尺寸。一旦剪切了某个区域,则所有之后的绘图都会被限制在被剪切的区域内(不能访问画布上的其他区域)。可以在使用 clip() 方法前通过使用 save() 方法对当前画布区域进行保存,并在以后的任意时间对其进行恢复(通过 restore() 方法)。 */ clip: () => void; /** * 关闭一个路径 */ closePath: () => void; /** * 创建一个圆形的渐变颜色。 */ createCircularGradient: () => void; /** * 创建一个线性的渐变颜色。 */ createLinearGradient: () => void; /** * 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。 */ draw: () => void; /** * 绘制图像到画布。 */ drawImage: () => void; /** * 对当前路径中的内容进行填充。默认的填充色为黑色。 */ fill: () => void; /** * 填充一个矩形。 */ fillRect: () => void; /** * 在画布上绘制被填充的文本。 */ fillText: () => void; /** * const ctx = wx.createCanvasContext('myCanvas') */ lineTo: () => void; /** * 把路径移动到画布中的指定点,不创建线条。 */ moveTo: () => void; /** * 创建二次贝塞尔曲线路径。 */ quadraticCurveTo: () => void; /** * 创建一个矩形。 */ rect: () => void; /** * 以原点为中心,原点可以用 [translate](#translate)方法修改。顺时针旋转当前坐标轴。多次调用`rotate`,旋转的角度会叠加。 */ rotate: () => void; /** * 保存当前的绘图上下文。 */ save: () => void; /** * 在调用`scale`方法后,之后创建的路径其横纵坐标会被缩放。多次调用`scale`,倍数会相乘。 */ scale: () => void; /** * 设置填充色。 */ setFillStyle: () => void; /** * 设置字体的字号。 */ setFontSize: () => void; /** * 设置全局画笔透明度。 */ setGlobalAlpha: () => void; /** * 设置线条的端点样式。 */ setLineCap: () => void; /** * 设置线条的宽度。 */ setLineDash: () => void; /** * 设置线条的交点样式。 */ setLineJoin: () => void; /** * 设置线条的宽度。 */ setLineWidth: () => void; /** * 设置最大斜接长度,斜接长度指的是在两条线交汇处内角和外角之间的距离。 当 `setLineJoin()` 为 miter 时才有效。超过最大倾斜长度的,连接处将以 lineJoin 为 bevel 来显示 */ setMiterLimit: () => void; /** * 设置阴影样式。 */ setShadow: () => void; /** * 设置边框颜色。 */ setStrokeStyle: () => void; /** * 用于设置文字的对齐 */ setTextAlign: () => void; /** * 用于设置文字的水平对齐 */ setTextBaseline: () => void; /** * 画出当前路径的边框。默认颜色色为黑色。 */ stroke: () => void; /** * 画一个矩形(非填充)。 */ strokeRect: () => void; /** * 对当前坐标系的原点(0, 0)进行变换,默认的坐标系原点为页面左上角。 */ translate: () => void; } interface _writeBLECharacteristicValueObject { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 蓝牙特征值对应服务的 uuid */ serviceId: string; /** * 蓝牙特征值的 uuid */ characteristicId: string; /** * 蓝牙设备特征值对应的二进制值 */ value: any; /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _writeBLECharacteristicValueSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _writeBLECharacteristicValueSuccessObject { /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _vibrateShortObject { /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _vibrateLongObject { /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _uploadFileObject { /** * 开发者服务器 url */ url: string; /** * 要上传文件资源的路径 */ filePath: string; /** * 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ name: string; /** * HTTP 请求 Header, header 中不能设置 Referer */ header: object; /** * HTTP 请求中其他额外的 form data */ formData: object; /** * 接口调用成功的回调函数 */ success: (result: _uploadFileSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _uploadFileSuccessObject { /** * 开发者服务器返回的数据 */ data: string; /** * 开发者服务器返回的 HTTP 状态码 */ statusCode: number; } interface _updateShareMenuObject { /** * 是否使用带 shareTicket 的转发[详情](./share.md#获取更多转发信息) */ withShareTicket: boolean; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _switchTabObject { /** * 需要跳转的 tabBar 页面的路径(需在 app.json 的 [tabBar](../framework/config.md#tabbar) 字段定义的页面),路径后不能带参数 */ url: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _stopWifiObject { /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _stopHCEObject { /** * 接口调用成功的回调函数 */ success: (result: _stopHCESuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _stopHCESuccessObject { /** * 错误信息 */ errMsg: string; /** * 错误码 */ errCode: number; } interface _stopCompassObject { /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _stopBluetoothDevicesDiscoveryObject { /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _stopBluetoothDevicesDiscoverySuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _stopBluetoothDevicesDiscoverySuccessObject { /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _stopBeaconDiscoveryObject { /** * 接口调用成功的回调函数 */ success: (result: _stopBeaconDiscoverySuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _stopBeaconDiscoverySuccessObject { /** * 调用结果 */ errMsg: string; } interface _stopAccelerometerObject { /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _startWifiObject { /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _startSoterAuthenticationObject { /** * 请求使用的可接受的生物认证方式 */ requestAuthModes: any; /** * 挑战因子。挑战因子为调用者为此次生物鉴权准备的用于签名的字符串关键是别信息,将作为result_json的一部分,供调用者识别本次请求。例如:如果场景为请求用户对某订单进行授权确认,则可以将订单号填入此参数。 */ challenge: string; /** * 验证描述,即识别过程中显示在界面上的对话框提示内容 */ authContent: string; /** * 接口调用成功的回调函数 */ success: (result: _startSoterAuthenticationSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _startSoterAuthenticationSuccessObject { /** * 错误码 */ errCode: number; /** * 生物认证方式 */ authMode: string; /** * 在设备安全区域(TEE)内获得的本机安全信息(如TEE名称版本号等以及防重放参数)以及本次认证信息(仅Android支持,本次认证的指纹ID)(仅Android支持,本次认证的指纹ID) */ resultJSON: string; /** * 用SOTER安全密钥对result_json的签名(SHA256withRSA/PSS, saltlen=20) */ resultJSONSignature: string; /** * 接口调用结果 */ errMsg: string; } interface _startRecordObject { /** * 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ success: (result: _startRecordSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _startRecordSuccessObject { /** * 录音文件的临时路径 */ tempFilePath: any; } interface _startPullDownRefreshObject { /** * 接口调用成功的回调函数 */ success: (result: _startPullDownRefreshSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _startPullDownRefreshSuccessObject { /** * 接口调用结果 */ errMsg: string; } interface _startHCEObject { /** * 需要注册到系统的 AID 列表,每个 AID 为 String 类型 */ aid_list: any; /** * 接口调用成功的回调函数 */ success: (result: _startHCESuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _startHCESuccessObject { /** * 错误信息 */ errMsg: string; /** * 错误码 */ errCode: number; } interface _startCompassObject { /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _startBluetoothDevicesDiscoveryObject { /** * 蓝牙设备主 service 的 uuid 列表 */ services: any; /** * 是否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同 */ allowDuplicatesKey: boolean; /** * 上报设备的间隔,默认为0,意思是找到新设备立即上报,否则根据传入的间隔上报 */ interval: number; /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _startBluetoothDevicesDiscoverySuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _startBluetoothDevicesDiscoverySuccessObject { /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _startBeaconDiscoveryObject { /** * iBeacon设备广播的 uuids */ uuids: any; /** * 接口调用成功的回调函数 */ success: (result: _startBeaconDiscoverySuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _startBeaconDiscoverySuccessObject { /** * 调用结果 */ errMsg: string; } interface _startAccelerometerObject { /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _showToastObject { /** * 提示的内容 */ title: string; /** * 图标,有效值 "success", "loading", "none" */ icon: string; /** * 自定义图标的本地路径,image 的优先级高于 icon */ image: string; /** * 提示的延迟时间,单位毫秒,默认:1500 */ duration: number; /** * 是否显示透明蒙层,防止触摸穿透,默认:false */ mask: boolean; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _showTabBarRedDotObject { /** * tabBar的哪一项,从左边算起 */ index: number; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _showTabBarObject { /** * 是否需要动画效果,默认无 */ aniamtion: boolean; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _showShareMenuObject { /** * 是否使用带 shareTicket 的转发[详情](./share.md#获取更多转发信息) */ withShareTicket: boolean; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _showModalObject { /** * 提示的标题 */ title: string; /** * 提示的内容 */ content: string; /** * 是否显示取消按钮,默认为 true */ showCancel: boolean; /** * 取消按钮的文字,默认为"取消",最多 4 个字符 */ cancelText: string; /** * 取消按钮的文字颜色,默认为"#000000" */ cancelColor: any; /** * 确定按钮的文字,默认为"确定",最多 4 个字符 */ confirmText: string; /** * 确定按钮的文字颜色,默认为"#3CC51F" */ confirmColor: any; /** * 接口调用成功的回调函数 */ success: (result: _showModalSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _showModalSuccessObject { /** * 为 true 时,表示用户点击了确定按钮 */ confirm: boolean; /** * 为 true 时,表示用户点击了取消(用于 Android 系统区分点击蒙层关闭还是点击取消按钮关闭) */ cancel: boolean; } interface _showLoadingObject { /** * 提示的内容 */ title: string; /** * 是否显示透明蒙层,防止触摸穿透,默认:false */ mask: boolean; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _showActionSheetObject { /** * 按钮的文字数组,数组长度最大为6个 */ itemList: any; /** * 按钮的文字颜色,默认为"#000000" */ itemColor: any; /** * 接口调用成功的回调函数,详见返回参数说明 */ success: (result: _showActionSheetSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _showActionSheetSuccessObject { /** * 用户点击的按钮,从上到下的顺序,从0开始 */ tapIndex: number; } interface _setWifiListObject { /** * 提供预设的 Wi-Fi 信息列表 */ wifiList: any; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setTopBarTextObject { /** * 置顶栏文字内容 */ text: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setTabBarStyleObject { /** * tab 上的文字默认颜色 */ color: any; /** * tab 上的文字选中时的颜色 */ selectedColor: any; /** * tab 的背景色 */ backgroundColor: any; /** * tabbar上边框的颜色, 仅支持 black/white */ borderStyle: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setTabBarItemObject { /** * tabBar 的哪一项,从左边算起 */ index: number; /** * tab 上按钮文字 */ text: string; /** * 图片路径,icon 大小限制为40kb,建议尺寸为 81px * 81px,当 postion 为 top 时,此参数无效,不支持网络图片 */ iconPath: string; /** * 选中时的图片路径,icon 大小限制为40kb,建议尺寸为 81px * 81px ,当 postion 为 top 时,此参数无效 */ selectedIconPath: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setTabBarBadgeObject { /** * tabBar的哪一项,从左边算起 */ index: number; /** * 显示的文本,超过 3 个字符则显示成“…” */ text: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setStorageObject { /** * 本地缓存中的指定的 key */ key: string; /** * 需要存储的内容 */ data: any; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setScreenBrightnessObject { /** * 屏幕亮度值,范围 0~1,0 最暗,1 最亮 */ value: number; /** * 接口调用成功 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setNavigationBarTitleObject { /** * 页面标题 */ title: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setNavigationBarColorObject { /** * 前景颜色值,包括按钮、标题、状态栏的颜色,仅支持 #ffffff 和 #000000 */ frontColor: string; /** * 背景颜色值,有效值为十六进制颜色 */ backgroundColor: string; /** * 动画效果 */ animation: object; /** * 接口调用成功的回调函数 */ success: (result: _setNavigationBarColorSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setNavigationBarColorSuccessObject { /** * 调用结果 */ errMsg: string; } interface _setKeepScreenOnObject { /** * 是否保持屏幕常亮 */ keepScreenOn: boolean; /** * 接口调用成功的回调函数 */ success: (result: _setKeepScreenOnSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setKeepScreenOnSuccessObject { /** * 调用结果 */ errMsg: string; } interface _setEnableDebugObject { /** * 是否打开调试 */ enableDebug: boolean; /** * 接口调用成功的回调函数 */ success: (result: _setEnableDebugSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _setEnableDebugSuccessObject { /** * 调用结果 */ errMsg: string; } interface _setClipboardDataObject { /** * 需要设置的内容 */ data: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _sendSocketMessageObject { /** * 需要发送的内容 */ data: any; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _sendHCEMessageObject { /** * 二进制数据 */ data: any; /** * 接口调用成功的回调函数 */ success: (result: _sendHCEMessageSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _sendHCEMessageSuccessObject { /** * 错误信息 */ errMsg: string; /** * 错误码 */ errCode: number; } interface _seekBackgroundAudioObject { /** * 音乐位置,单位:秒 */ position: number; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _scanCodeObject { /** * 是否只能从相机扫码,不允许从相册选择图片 */ onlyFromCamera: boolean; /** * 扫码类型,参数类型是数组,二维码是'qrCode',一维码是'barCode',DataMatrix是‘datamatrix’,pdf417是‘pdf417’。 */ scanType: any; /** * 接口调用成功的回调函数,返回内容详见返回参数说明。 */ success: (result: _scanCodeSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _scanCodeSuccessObject { /** * 所扫码的内容 */ result: any; /** * 所扫码的类型 */ scanType: any; /** * 所扫码的字符集 */ charSet: any; /** * 当所扫的码为当前小程序的合法二维码时,会返回此字段,内容为二维码携带的 path */ path: any; } interface _saveVideoToPhotosAlbumObject { /** * 视频文件路径,可以是临时文件路径也可以是永久文件路径 */ filePath: string; /** * 接口调用成功的回调函数 */ success: (result: _saveVideoToPhotosAlbumSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _saveVideoToPhotosAlbumSuccessObject { /** * 调用结果 */ errMsg: string; } interface _saveImageToPhotosAlbumObject { /** * 图片文件路径,可以是临时文件路径也可以是永久文件路径,不支持网络图片路径 */ filePath: string; /** * 接口调用成功的回调函数 */ success: (result: _saveImageToPhotosAlbumSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _saveImageToPhotosAlbumSuccessObject { /** * 调用结果 */ errMsg: string; } interface _saveFileObject { /** * 需要保存的文件的临时路径 */ tempFilePath: string; /** * 返回文件的保存路径,res = {savedFilePath: '文件的保存路径'} */ success: (result: _saveFileSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _saveFileSuccessObject { /** * 文件的保存路径 */ savedFilePath: any; } interface _requestPaymentObject { /** * 平台分配的游戏appId */ appId:number; /** * 游戏包名 */ pkgName:string; /** * qg.login成功时获得的用户token */ token:string; /** * 时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间 */ timeStamp: string; /** * 下单订单号,由统一下单接口返回 */ orderNo:string; /** * 支付签名,CP服务端生成。注:paySign 由 CP 服务端使用 appKey (不是 appId )、orderNo、timestamp 进行签名算法生成返回。签名规则,跟"统一下单接口"的签名规则一致。 */ paySign:string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _requestObject { /** * 开发者服务器接口地址 */ url: string; /** * 请求的参数 */ data: any; /** * 设置请求的 header,header 中不能设置 Referer。 */ header: object; /** * (需大写)有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ method: string; /** * 如果设为json,会尝试对返回的数据做一次 JSON.parse */ dataType: string; /** * 设置响应的数据类型。合法值:text、arraybuffer */ responseType: string; /** * 收到开发者服务成功返回的回调函数 */ success: (result: _requestSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _requestSuccessObject { /** * 开发者服务器返回的数据 */ data: any; /** * 开发者服务器返回的 HTTP 状态码 */ statusCode: number; /** * 开发者服务器返回的 HTTP Response Header */ header: object; } interface _removeTabBarBadgeObject { /** * tabBar的哪一项,从左边算起 */ index: number; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _removeStorageObject { /** * 本地缓存中的指定的 key */ key: string; /** * 接口调用的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _removeSavedFileObject { /** * 需要删除的文件路径 */ filePath: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _redirectToObject { /** * 需要跳转的应用内非 tabBar 的页面的路径,路径后可以带参数。参数与路径之间使用`?`分隔,参数键与参数值用`=`相连,不同参数用`&`分隔;如 'path?key=value&key2=value2' */ url: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _readBLECharacteristicValueObject { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 蓝牙特征值对应服务的 uuid */ serviceId: string; /** * 蓝牙特征值的 uuid */ characteristicId: string; /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _readBLECharacteristicValueSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _readBLECharacteristicValueSuccessObject { /** * 错误码 */ errCode: number; /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _reLaunchObject { /** * 需要跳转的应用内页面路径 , 路径后可以带参数。参数与路径之间使用`?`分隔,参数键与参数值用`=`相连,不同参数用`&`分隔;如 'path?key=value&key2=value2',如果跳转的页面路径是 tabBar 页面则不能带参数 */ url: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _previewImageObject { /** * 当前显示图片的链接,不填则默认为 urls 的第一张 */ current: string; /** * 需要预览的图片链接列表 */ urls: any; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _playVoiceObject { /** * 需要播放的语音文件的文件路径 */ filePath: string; /** * 指定录音时长,到达指定的录音时长后会自动停止录音,单位:秒,默认值:60 */ duration: number; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _playBackgroundAudioObject { /** * 音乐链接,目前支持的格式有 m4a, aac, mp3, wav */ dataUrl: string; /** * 音乐标题 */ title: string; /** * 封面URL */ coverImgUrl: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _pageScrollToObject { /** * 滚动到页面的目标位置(单位px) */ scrollTop: number; /** * 滚动动画的时长,默认300ms,单位 ms */ duration: number; } interface _openSettingObject { /** * 接口调用成功的回调函数,返回内容详见返回参数说明。 */ success: (result: _openSettingSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _openSettingSuccessObject { /** * 用户授权结果,其中 key 为 scope 值,value 为 Bool 值,表示用户是否允许授权,详见 [scope 列表](./authorize-index.md#scope-列表) */ authSetting: object; } interface _openLocationObject { /** * 纬度,范围为-90~90,负数表示南纬 */ latitude: any; /** * 经度,范围为-180~180,负数表示西经 */ longitude: any; /** * 缩放比例,范围5~18,默认为18 */ scale: any; /** * 位置名 */ name: string; /** * 地址的详细说明 */ address: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _openDocumentObject { /** * 文件路径,可通过 downFile 获得 */ filePath: any; /** * 文件类型,指定文件类型打开文件,有效值 doc, xls, ppt, pdf, docx, xlsx, pptx */ fileType: any; /** * 接口调用成功的回调函数 */ success: any; /** * 接口调用失败的回调函数 */ fail: any; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: any; } interface _openCardObject { /** * 需要打开的卡券列表,列表内参数详见[openCard 请求对象说明](#opencard-请求对象说明) */ cardList: any; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _openBluetoothAdapterObject { /** * 成功则返回成功初始化信息 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _onWifiConnectedCallbackResult { /** * Wi-Fi 信息 */ wifi: object; } interface _onUserCaptureScreenCallbackResult {} interface _onSocketMessageCallbackResult { /** * 服务器返回的消息 */ data: any; } interface _onNetworkStatusChangeCallbackResult { /** * 当前是否有网络连接 */ isConnected: boolean; /** * 网络类型 */ networkType: string; } interface _onHCEMessageCallbackResult { /** * 消息类型 */ messageType: number; /** * 客户端接收到 NFC 设备的指令,此参数当且仅当 `messageType=1` 时有效 */ data: any; /** * 此参数当且仅当 `messageType=2` 时有效 */ reason: number; } interface _onGetWifiListCallbackResult { /** * Wi-Fi 列表数据 */ wifiList: any; } interface _onEvaluateWifiCallbackResult { /** * Wi-Fi 信息 */ wifi: object; } interface _onCompassChangeCallbackResult { /** * 面对的方向度数 */ direction: number; } interface _onBluetoothDeviceFoundCallbackResult { /** * 新搜索到的设备列表 */ devices: any; } interface _onBluetoothAdapterStateChangeCallbackResult { /** * 蓝牙适配器是否可用 */ available: boolean; /** * 蓝牙适配器是否处于搜索状态 */ discovering: boolean; } interface _onBeaconUpdateCallbackResult { /** * 当前搜寻到的所有 iBeacon 设备列表 */ beacons: any; } interface _onBeaconServiceChangeCallbackResult { /** * 服务目前是否可用 */ available: boolean; /** * 目前是否处于搜索状态 */ discovering: boolean; } interface _onBLEConnectionStateChangeCallbackResult { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 连接目前的状态 */ connected: boolean; } interface _onBLECharacteristicValueChangeCallbackResult { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 特征值所属服务 uuid */ serviceId: string; /** * 特征值 uuid */ characteristicId: string; /** * 特征值最新的值 **(注意:vConsole 无法打印出 ArrayBuffer 类型数据)** */ value: any; } interface _onAccelerometerChangeCallbackResult { /** * X 轴 */ x: number; /** * Y 轴 */ y: number; /** * Z 轴 */ z: number; } interface _notifyBLECharacteristicValueChangeObject { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 蓝牙特征值对应服务的 uuid */ serviceId: string; /** * 蓝牙特征值的 uuid */ characteristicId: string; /** * true: 启用 notify; false: 停用 notify */ state: boolean; /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _notifyBLECharacteristicValueChangeSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _notifyBLECharacteristicValueChangeSuccessObject { /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _navigateToMiniProgramObject { /** * 要打开的小程序 appId */ appId: string; /** * 打开的页面路径,如果为空则打开首页 */ path: string; /** * 需要传递给目标小程序的数据,目标小程序可在 `App.onLaunch()`,`App.onShow()` 中获取到这份数据。[详情](../framework/app-service/app.md) */ extraData: object; /** * 要打开的小程序版本,有效值 develop(开发版),trial(体验版),release(正式版) ,仅在当前小程序为开发版或体验版时此参数有效;如果当前小程序是体验版或正式版,则打开的小程序必定是正式版。默认值 release */ envVersion: string; /** * 接口调用成功的回调函数 */ success: (result: _navigateToMiniProgramSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _navigateToMiniProgramSuccessObject { /** * 调用结果 */ errMsg: string; } interface _navigateToObject { /** * 需要跳转的应用内非 tabBar 的页面的路径 , 路径后可以带参数。参数与路径之间使用`?`分隔,参数键与参数值用`=`相连,不同参数用`&`分隔;如 'path?key=value&key2=value2' */ url: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _navigateBackMiniProgramObject { /** * 需要返回给上一个小程序的数据,上一个小程序可在 `App.onShow()` 中获取到这份数据。[详情](../framework/app-service/app.md) */ extraData: object; /** * 接口调用成功的回调函数 */ success: (result: _navigateBackMiniProgramSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _navigateBackMiniProgramSuccessObject { /** * 调用结果 */ errMsg: string; } interface _navigateBackObject { /** * 返回的页面数,如果 delta 大于现有页面数,则返回到首页。 */ delta: number; } interface _makeVoIPCallObject { /** * 是否展示切换按钮以允许用户转换到后置摄像头 */ allowBackCamera: boolean; /** * 是否显示对端视频流 */ showOther: boolean; /** * 客服头像的图像链接 */ avatarUrl: string; /** * 用于区分业务上下文的透传值 */ context: string; /** * 返回用户选择的收货地址信息 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _makePhoneCallObject { /** * 需要拨打的电话号码 */ phoneNumber: string; /** * 接口调用成功的回调 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _loginObject { /** * 游戏包名 */ pkgName: string; /** * 接口调用成功的回调函数 */ success: (result: _loginSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _loginSuccessObject { /** * 调用结果 */ errMsg: string; /** * 用户登录凭证(有效期五分钟)。开发者需要在开发者服务器后台调用 api,使用 code 换取 openid 和 session_key 等信息 */ code: string; } interface _hideTabBarRedDotObject { /** * tabBar的哪一项,从左边算起 */ index: number; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _hideTabBarObject { /** * 是否需要动画效果,默认无 */ aniamtion: boolean; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _hideShareMenuObject { /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getWifiListObject { /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getWeRunDataObject { /** * 接口调用成功的回调函数 */ success: (result: _getWeRunDataSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getWeRunDataSuccessObject { /** * 调用结果 */ errMsg: string; /** * 包括敏感数据在内的完整用户信息的加密数据,详细见[加密数据解密算法](./signature.md#加密数据解密算法) */ encryptedData: string; /** * 加密算法的初始向量,详细见[加密数据解密算法](./signature.md#加密数据解密算法) */ iv: string; } interface _getUserInfoObject { /** * 是否带上登录态信息 */ withCredentials: boolean; /** * 指定返回用户信息的语言,zh_CN 简体中文,zh_TW 繁体中文,en 英文。默认为en。 */ lang: string; /** * 接口调用成功的回调函数 */ success: (result: _getUserInfoSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getUserInfoSuccessObject { /** * 用户信息对象,不包含 openid 等敏感信息 */ userInfo: object; /** * 不包括敏感信息的原始数据字符串,用于计算签名。 */ rawData: string; /** * 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息,参考文档 [signature](./signature.md)。 */ signature: string; /** * 包括敏感数据在内的完整用户信息的加密数据,详细见[加密数据解密算法](./signature.md#加密数据解密算法) */ encryptedData: string; /** * 加密算法的初始向量,详细见[加密数据解密算法](./signature.md#加密数据解密算法) */ iv: string; } interface _getSystemInfoSyncReturnValue { /** * 手机品牌 */ brand: any; /** * 手机型号 */ model: any; /** * 设备像素比 */ pixelRatio: any; /** * 屏幕宽度 */ screenWidth: any; /** * 屏幕高度 */ screenHeight: any; /** * 可使用窗口宽度 */ windowWidth: any; /** * 可使用窗口高度 */ windowHeight: any; /** * 状态栏的高度 */ statusBarHeight: any; /** * 微信设置的语言 */ language: any; /** * 微信版本号 */ version: any; /** * 操作系统版本 */ system: any; /** * 客户端平台 */ platform: any; /** * 用户字体大小设置。以“我-设置-通用-字体大小”中的设置为准,单位:px */ fontSizeSetting: any; /** * 客户端基础库版本 */ SDKVersion: any; } interface _getSystemInfoObject { /** * 接口调用成功的回调 */ success: (result: _getSystemInfoSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getSystemInfoSuccessObject { /** * 手机品牌 */ brand: any; /** * 手机型号 */ model: any; /** * 设备像素比 */ pixelRatio: any; /** * 屏幕宽度 */ screenWidth: any; /** * 屏幕高度 */ screenHeight: any; /** * 可使用窗口宽度 */ windowWidth: any; /** * 可使用窗口高度 */ windowHeight: any; /** * 状态栏的高度 */ statusBarHeight: any; /** * 微信设置的语言 */ language: any; /** * 微信版本号 */ version: any; /** * 操作系统版本 */ system: any; /** * 客户端平台 */ platform: any; /** * 用户字体大小设置。以“我-设置-通用-字体大小”中的设置为准,单位:px */ fontSizeSetting: any; /** * 客户端基础库版本 */ SDKVersion: any; } interface _getStorageInfoObject { /** * 接口调用的回调函数,详见返回参数说明 */ success: (result: _getStorageInfoSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getStorageInfoSuccessObject { /** * 当前storage中所有的key */ keys: any; /** * 当前占用的空间大小, 单位kb */ currentSize: number; /** * 限制的空间大小,单位kb */ limitSize: number; } interface _getStorageObject { /** * 本地缓存中的指定的 key */ key: string; /** * 接口调用的回调函数,res = {data: key对应的内容} */ success: (result: _getStorageSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getStorageSuccessObject { /** * key对应的内容 */ data: string; } interface _getShareInfoObject { /** * shareTicket */ shareTicket: string; /** * 接口调用成功的回调函数 */ success: (result: _getShareInfoSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getShareInfoSuccessObject { /** * 错误信息 */ errMsg: string; /** * 包括敏感数据在内的完整转发信息的加密数据,详细见[加密数据解密算法](./signature.md#加密数据解密算法) */ encryptedData: string; /** * 加密算法的初始向量,详细见[加密数据解密算法](./signature.md#加密数据解密算法) */ iv: string; } interface _getSettingObject { /** * 接口调用成功的回调函数,返回内容详见返回参数说明。 */ success: (result: _getSettingSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getSettingSuccessObject { /** * 用户授权结果,其中 key 为 scope 值,value 为 Bool 值,表示用户是否允许授权,详见 [scope 列表](./authorize-index.md#scope-列表) */ authSetting: object; } interface _getScreenBrightnessObject { /** * 接口调用成功 */ success: (result: _getScreenBrightnessSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getScreenBrightnessSuccessObject { /** * 屏幕亮度值,范围 0~1,0 最暗,1 最亮 */ value: number; } interface _getSavedFileListObject { /** * 接口调用成功的回调函数,返回结果见`success返回参数说明` */ success: (result: _getSavedFileListSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getSavedFileListSuccessObject { /** * 接口调用结果 */ errMsg: string; /** * 文件列表 */ fileList: any; } interface _getSavedFileInfoObject { /** * 文件路径 */ filePath: string; /** * 接口调用成功的回调函数,返回结果见`success返回参数说明` */ success: (result: _getSavedFileInfoSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getSavedFileInfoSuccessObject { /** * 接口调用结果 */ errMsg: string; /** * 文件大小,单位B */ size: number; /** * 文件保存时的时间戳,从1970/01/01 08:00:00 到该时刻的秒数 */ createTime: number; } interface _getOpenDeviceIdObject { /** * 接口调用成功的回调函数 */ success: (result: _getOpenDeviceIdSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getOpenDeviceIdSuccessObject { /** * 接口调用结果 */ errMsg: string; /** * 包括敏感数据在内的完整用户信息的加密数据,详细见[加密数据解密算法](./signature.md#加密数据解密算法) */ encryptedData: string; /** * 加密算法的初始向量,详细见[加密数据解密算法](./signature.md#加密数据解密算法) */ iv: string; } interface _getNetworkTypeObject { /** * 接口调用成功,返回网络类型 networkType */ success: (result: _getNetworkTypeSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getNetworkTypeSuccessObject { /** * 网络类型 */ networkType: any; } interface _getLocationObject { /** * 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于`wx.openLocation`的坐标 */ type: string; /** * 传入 true 会返回高度信息,由于获取高度需要较高精确度,会减慢接口返回速度 */ altitude: boolean; /** * 接口调用成功的回调函数,返回内容详见返回参数说明。 */ success: (result: _getLocationSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getLocationSuccessObject { /** * 纬度,浮点数,范围为-90~90,负数表示南纬 */ latitude: any; /** * 经度,浮点数,范围为-180~180,负数表示西经 */ longitude: any; /** * 速度,浮点数,单位m/s */ speed: any; /** * 位置的精确度 */ accuracy: any; /** * 高度,单位 m */ altitude: any; /** * 垂直精度,单位 m(Android 无法获取,返回 0) */ verticalAccuracy: any; /** * 水平精度,单位 m */ horizontalAccuracy: any; } interface _getImageInfoObject { /** * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 */ src: string; /** * 接口调用成功的回调函数 */ success: (result: _getImageInfoSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getImageInfoSuccessObject { /** * 图片宽度,单位px */ width: number; /** * 图片高度,单位px */ height: number; /** * 返回图片的本地路径 */ path: string; } interface _getHCEStateObject { /** * 接口调用成功的回调函数 */ success: (result: _getHCEStateSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getHCEStateSuccessObject { /** * 错误信息 */ errMsg: string; /** * 错误码 */ errCode: number; } interface _getFileInfoObject { /** * 本地文件路径 */ filePath: string; /** * 计算文件摘要的算法,默认值 md5,有效值:md5,sha1 */ digestAlgorithm: string; /** * 接口调用成功的回调函数 */ success: (result: _getFileInfoSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getFileInfoSuccessObject { /** * 文件大小,单位:B */ size: number; /** * 按照传入的 digestAlgorithm 计算得出的的文件摘要 */ digest: string; /** * 调用结果 */ errMsg: string; } interface _getExtConfigSyncReturnValue { /** * 第三方平台自定义的数据 */ extConfig: object; } interface _getExtConfigObject { /** * 返回第三方平台自定义的数据 */ success: (result: _getExtConfigSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getExtConfigSuccessObject { /** * 调用结果 */ errMsg: string; /** * 第三方平台自定义的数据 */ extConfig: object; } interface _getConnectedWifiObject { /** * 接口调用成功的回调函数 */ success: (result: _getConnectedWifiSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getConnectedWifiSuccessObject { /** * Wi-Fi 信息 */ wifi: object; } interface _getConnectedBluetoothDevicesObject { /** * 蓝牙设备主 service 的 uuid 列表 */ services: any; /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _getConnectedBluetoothDevicesSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getConnectedBluetoothDevicesSuccessObject { /** * 搜索到的设备列表 */ devices: any; /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _getClipboardDataObject { /** * 接口调用成功的回调函数 */ success: (result: _getClipboardDataSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getClipboardDataSuccessObject { /** * 剪贴板的内容 */ data: string; } interface _getBluetoothDevicesObject { /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _getBluetoothDevicesSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getBluetoothDevicesSuccessObject { /** * uuid 对应的的已连接设备列表 */ devices: any; /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _getBluetoothAdapterStateObject { /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _getBluetoothAdapterStateSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getBluetoothAdapterStateSuccessObject { /** * 是否正在搜索设备 */ discovering: boolean; /** * 蓝牙适配器是否可用 */ available: boolean; /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _getBeaconsObject { /** * 接口调用成功的回调函数 */ success: (result: _getBeaconsSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getBeaconsSuccessObject { /** * iBeacon 设备列表 */ beacons: any; /** * 调用结果 */ errMsg: string; } interface _getBackgroundAudioPlayerStateObject { /** * 接口调用成功的回调函数 */ success: (result: _getBackgroundAudioPlayerStateSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getBackgroundAudioPlayerStateSuccessObject { /** * 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ duration: any; /** * 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ currentPosition: any; /** * 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ status: any; /** * 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ downloadPercent: any; /** * 歌曲数据链接,只有在当前有音乐播放时返回 */ dataUrl: any; } interface _getBackgroundAudioManagerReturnValue { /** * 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 */ duration: number; /** * 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 */ currentTime: number; /** * 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 */ paused: boolean; /** * 音频的数据源,默认为空字符串,**当设置了新的 src 时,会自动开始播放** ,目前支持的格式有 m4a, aac, mp3, wav */ src: string; /** * 音频开始播放的位置(单位:s) */ startTime: number; /** * 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲。 */ buffered: number; /** * 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 */ title: string; /** * 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值。 */ epname: string; /** * 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值。 */ singer: string; /** * 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 */ coverImgUrl: string; /** * 页面链接,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值。 */ webUrl: string; /** * 播放 */ play: () => void; /** * 暂停 */ pause: () => void; /** * 停止 */ stop: () => void; /** * 跳转到指定位置,单位 s */ seek: () => void; /** * 背景音频进入可以播放状态,但不保证后面可以流畅播放 */ onCanplay: () => void; /** * 背景音频播放事件 */ onPlay: () => void; /** * 背景音频暂停事件 */ onPause: () => void; /** * 背景音频停止事件 */ onStop: () => void; /** * 背景音频自然播放结束事件 */ onEnded: () => void; /** * 背景音频播放进度更新事件 */ onTimeUpdate: () => void; /** * 用户在系统音乐播放面板点击上一曲事件(iOS only) */ onPrev: () => void; /** * 用户在系统音乐播放面板点击下一曲事件(iOS only) */ onNext: () => void; /** * 背景音频播放错误事件 */ onError: () => void; /** * 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ onWaiting: () => void; } interface _getBLEDeviceServicesObject { /** * 蓝牙设备 id,参考 getDevices 接口 */ deviceId: string; /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _getBLEDeviceServicesSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getBLEDeviceServicesSuccessObject { /** * 设备服务列表 */ services: any; /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _getBLEDeviceCharacteristicsObject { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 蓝牙服务 uuid */ serviceId: string; /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _getBLEDeviceCharacteristicsSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _getBLEDeviceCharacteristicsSuccessObject { /** * 设备特征值列表 */ characteristics: any; /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _downloadFileObject { /** * 下载资源的 url */ url: string; /** * HTTP 请求的 Header,Header 中不能设置 Referer */ header: object; /** * 指定文件下载后存储的路径 */ filePath?:string; /** * 接口调用成功的回调函 */ success: (result: _downloadFileSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数 */ complete: () => void; } interface _downloadFileSuccessObject { /** * 临时文件路径,下载后的文件会存储到一个临时文件 */ tempFilePath: string; /** * 开发者服务器返回的 HTTP 状态码 */ statusCode: number; /** * 错误码 */ errCode:string; /** * 错误信息 */ errMsg:number; } interface _createBLEConnectionObject { /** * 蓝牙设备 id,参考 getDevices 接口 */ deviceId: string; /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _createBLEConnectionSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _createBLEConnectionSuccessObject { /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _createAnimationObject { /** * 动画持续时间,单位ms */ duration: any; /** * 定义动画的效果 */ timingFunction: string; /** * 动画延迟时间,单位 ms */ delay: any; /** * 设置transform-origin */ transformOrigin: string; } interface _connectWifiObject { /** * Wi-Fi 设备ssid */ SSID: string; /** * Wi-Fi 设备bssid */ BSSID: string; /** * Wi-Fi 设备密码 */ password: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _connectSocketObject { /** * 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名 */ url: string; /** * HTTP Header , header 中不能设置 Referer */ header: object; /** * 默认是GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ method: string; /** * 子协议数组 */ protocols: any; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _closeSocketObject { /** * 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) */ code: number; /** * 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) */ reason: string; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _closeBluetoothAdapterObject { /** * 成功则返回成功关闭模块信息 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _closeBLEConnectionObject { /** * 蓝牙设备 id,参考 getDevices 接口 */ deviceId: string; /** * 成功则返回本机蓝牙适配器状态 */ success: (result: _closeBLEConnectionSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _closeBLEConnectionSuccessObject { /** * 成功:ok,错误:详细信息 */ errMsg: string; } interface _chooseVideoObject { /** * album 从相册选视频,camera 使用相机拍摄,默认为:['album', 'camera'] */ sourceType: any; /** * 是否压缩所选的视频源文件,默认值为true,需要压缩 */ compressed: any; /** * 拍摄视频最长拍摄时间,单位秒。最长支持 60 秒 */ maxDuration: number; /** * 接口调用成功,返回视频文件的临时文件路径,详见返回参数说明 */ success: (result: _chooseVideoSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _chooseVideoSuccessObject { /** * 选定视频的临时文件路径 */ tempFilePath: any; /** * 选定视频的时间长度 */ duration: any; /** * 选定视频的数据量大小 */ size: any; /** * 返回选定视频的长 */ height: any; /** * 返回选定视频的宽 */ width: any; } interface _chooseLocationObject { /** * 接口调用成功的回调函数,返回内容详见返回参数说明。 */ success: (result: _chooseLocationSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _chooseLocationSuccessObject { /** * 位置名称 */ name: any; /** * 详细地址 */ address: any; /** * 纬度,浮点数,范围为-90~90,负数表示南纬 */ latitude: any; /** * 经度,浮点数,范围为-180~180,负数表示西经 */ longitude: any; } interface _chooseInvoiceTitleObject { /** * 接口调用成功的回调函数 */ success: (result: _chooseInvoiceTitleSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _chooseInvoiceTitleSuccessObject { /** * 抬头类型(0:单位,1:个人) */ type: string; /** * 抬头名称 */ title: string; /** * 抬头税号 */ taxNumber: string; /** * 单位地址 */ companyAddress: string; /** * 手机号码 */ telephone: string; /** * 银行名称 */ bankName: string; /** * 银行账号 */ bankAccount: string; /** * 接口调用结果 */ errMsg: string; } interface _chooseImageObject { /** * 最多可以选择的图片张数,默认9 */ count: number; /** * original 原图,compressed 压缩图,默认二者都有 */ sizeType: any; /** * album 从相册选图,camera 使用相机,默认二者都有 */ sourceType: any; /** * 成功则返回图片的本地文件路径列表 tempFilePaths */ success: (result: _chooseImageSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _chooseImageSuccessObject { /** * 图片的本地文件路径列表 */ tempFilePaths: any; /** * 图片的本地文件列表,每一项是一个 File 对象 */ tempFiles: any; } interface _chooseContactObject { /** * 返回用户选择的联系人信息 */ success: (result: _chooseContactSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _chooseContactSuccessObject { /** * 电话号码 */ phoneNumber: any; /** * 联系人名称 */ displayName: any; } interface _chooseAddressObject { /** * 返回用户选择的收货地址信息 */ success: (result: _chooseAddressSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _chooseAddressSuccessObject { /** * 调用结果 */ errMsg: string; /** * 收货人姓名 */ userName: string; /** * 邮编 */ postalCode: string; /** * 国标收货地址第一级地址 */ provinceName: string; /** * 国标收货地址第二级地址 */ cityName: string; /** * 国标收货地址第三级地址 */ countyName: string; /** * 详细收货地址信息 */ detailInfo: string; /** * 收货地址国家码 */ nationalCode: string; /** * 收货人手机号码 */ telNumber: string; } interface _checkSessionObject { /** * 接口调用成功的回调函数,登录态未过期 */ success: () => void; /** * 接口调用失败的回调函数,登录态已过期 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _checkIsSupportSoterAuthenticationObject { /** * 接口调用成功的回调函数 */ success: (result: _checkIsSupportSoterAuthenticationSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _checkIsSupportSoterAuthenticationSuccessObject { /** * 该设备支持的可被SOTER识别的生物识别方式 */ supportMode: any; /** * 接口调用结果 */ errMsg: string; } interface _checkIsSoterEnrolledInDeviceObject { /** * 认证方式 */ checkAuthMode: string; /** * 接口调用成功的回调函数 */ success: (result: _checkIsSoterEnrolledInDeviceSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _checkIsSoterEnrolledInDeviceSuccessObject { /** * 是否已录入信息 */ isEnrolled: boolean; /** * 接口调用结果 */ errMsg: string; } interface _canvasToTempFilePathObject { /** * 画布x轴起点(默认0) */ x: number; /** * 画布y轴起点(默认0) */ y: number; /** * 画布宽度(默认为canvas宽度-x) */ width: number; /** * 画布高度(默认为canvas高度-y) */ height: number; /** * 输出图片宽度(默认为width) */ destWidth: number; /** * 输出图片高度(默认为height) */ destHeight: number; /** * 画布标识,传入 [``](../../component/canvas.md) 的 canvas-id */ canvasId: string; /** * 目标文件的类型,只支持 'jpg' 或 'png'。默认为 'png' */ fileType: string; /** * 图片的质量,取值范围为 (0, 1],不在范围内时当作1.0处理 */ quality: number; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _canvasPutImageDataObject { /** * 画布标识,传入 [``](../../component/canvas.md) 的 canvas-id */ canvasId: string; /** * 图像像素点数据,一维数组,每四项表示一个像素点的rgba */ data: any; /** * 源图像数据在目标画布中的位置偏移量(x 轴方向的偏移量) */ x: number; /** * 源图像数据在目标画布中的位置偏移量(y 轴方向的偏移量) */ y: number; /** * 源图像数据矩形区域的宽度 */ width: number; /** * 源图像数据矩形区域的高度 */ height: number; /** * 接口调用成功的回调函数 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _canvasGetImageDataObject { /** * 画布标识,传入 [``](../../component/canvas.md) 的 canvas-id */ canvasId: string; /** * 将要被提取的图像数据矩形区域的左上角 x 坐标 */ x: number; /** * 将要被提取的图像数据矩形区域的左上角 y 坐标 */ y: number; /** * 将要被提取的图像数据矩形区域的宽度 */ width: number; /** * 将要被提取的图像数据矩形区域的高度 */ height: number; /** * 接口调用成功的回调函数 */ success: (result: _canvasGetImageDataSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _canvasGetImageDataSuccessObject { /** * */ errMsg: string; /** * 图像数据矩形的宽度 */ width: number; /** * 图像数据矩形的高度 */ height: number; /** * 图像像素点数据,一维数组,每四项表示一个像素点的rgba */ data: any; } interface _authorizeObject { /** * 需要获取权限的scope,详见 [scope 列表](./authorize-index.md#scope-列表) */ scope: string; /** * 接口调用成功的回调函数 */ success: (result: _authorizeSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _authorizeSuccessObject { /** * 调用结果 */ errMsg: string; } interface _addPhoneContactObject { /** * 头像本地文件路径 */ photoFilePath: string; /** * 昵称 */ nickName: string; /** * 姓氏 */ lastName: string; /** * 中间名 */ middleName: string; /** * 名字 */ firstName: string; /** * 备注 */ remark: string; /** * 手机号 */ mobilePhoneNumber: string; /** * 微信号 */ weChatNumber: string; /** * 联系地址国家 */ addressCountry: string; /** * 联系地址省份 */ addressState: string; /** * 联系地址城市 */ addressCity: string; /** * 联系地址街道 */ addressStreet: string; /** * 联系地址邮政编码 */ addressPostalCode: string; /** * 公司 */ organization: string; /** * 职位 */ title: string; /** * 工作传真 */ workFaxNumber: string; /** * 工作电话 */ workPhoneNumber: string; /** * 公司电话 */ hostNumber: string; /** * 电子邮件 */ email: string; /** * 网站 */ url: string; /** * 工作地址国家 */ workAddressCountry: string; /** * 工作地址省份 */ workAddressState: string; /** * 工作地址城市 */ workAddressCity: string; /** * 工作地址街道 */ workAddressStreet: string; /** * 工作地址邮政编码 */ workAddressPostalCode: string; /** * 住宅传真 */ homeFaxNumber: string; /** * 住宅电话 */ homePhoneNumber: string; /** * 住宅地址国家 */ homeAddressCountry: string; /** * 住宅地址省份 */ homeAddressState: string; /** * 住宅地址城市 */ homeAddressCity: string; /** * 住宅地址街道 */ homeAddressStreet: string; /** * 住宅地址邮政编码 */ homeAddressPostalCode: string; /** * 接口调用成功 */ success: () => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _addCardObject { /** * 需要添加的卡券列表,列表内对象说明请参见[请求对象说明](#请求对象说明) */ cardList: any; /** * 接口调用成功的回调函数 */ success: (result: _addCardSuccessObject) => void; /** * 接口调用失败的回调函数 */ fail: () => void; /** * 接口调用结束的回调函数(调用成功、失败都会执行) */ complete: () => void; } interface _addCardSuccessObject { /** * 卡券添加结果列表,列表内对象说明请详见[返回对象说明](#返回对象说明) */ cardList: any; } interface _ShareAppMessageReturnObject { /** * 分享标题。默认为当前小程序名称。 */ title: string; /** * 分享路径。默认为当前页面 path,必须是以 / 开头的完整路径。 */ path: string; } interface _AppShowOptions { /** * 打开小程序的路径 */ path: string; /** * 打开小程序的query */ query: object; /** * 打开小程序的场景值 */ scene: number; /** * shareTicket */ shareTicket: string; } declare interface _AppOptions { /** * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次) */ onLaunch?: (options: _AppShowOptions) => void; /** * 当小程序启动,或从后台进入前台显示,会触发 onShow */ onShow?: (options: _AppShowOptions) => void; /** * 当小程序从前台进入后台,会触发 onHide */ onHide?: () => void; /** * 当小程序发生脚本错误,或者 api 调用失败时,会触发 onError 并带上错误信息 */ onError?: (msg: string) => void; } interface _BatteryInfo{ /** * 设备电量,范围 1 - 100 */ level:number; /** * 是否正在充电中 */ isCharging:number; } interface _FileSystemManager{ /** * 判断文件/目录是否存在 */ access:(object:any)=>void; /** * FileSystemManager.access 的同步版本,判断文件/目录是否存在 */ accessSync:(path:string)=>any; /** * 在文件结尾追加内容 */ appendFile:(object:any)=>void; /** * FileSystemManager.appendFile 的同步版本,在文件结尾追加内容 * @param 要追加内容的文件路径 * @param 要追加的文本或二进制数据 * @param 指定写入文件的字符编码,当前支持:utf8、binary */ appendFileSync:(filePath:string,data:any,encoding?:string)=>any; /** * 复制文件异步方式 */ copyFile:(object:any)=>void; /** * FileSystemManager.copyFile 的同步版本,拷贝文件 * @param 源文件路径,只可以是普通文件 * @param 目标文件路径 */ copyFileSync:(srcPath:string,destPath:string)=>boolean; /** * 获取本地临时文件或本地用户文件的文件信息 */ getFileInfo:(object:any) => void; /** * 创建目录 */ mkdir:(object:any)=>void; /** * FileSystemManager.mkdir 的同步版本,创建目录 * @param 创建的目录路径 * @param 是否在递归创建该目录的上级目录后再创建该目录。如果对应的上级目录已经存在,则不创建该上级目录。如 dirPath 为 a/b/c/d 且 recursive 为 true,将创建 a 目录,再在 a 目录下创建 b 目录,以此类推直至创建 a/b/c 目录下的 d 目录。 */ mkdirSync:(dirPath:string,recursive:string)=>any; /** * 读取本地文件内容异步方式 */ readFile:(object:any)=>void; /** * FileSystemManager.readFile 的同步版本,读取文件 * @param 要读取的文件的路径 * @param 指定读取文件的字符编码,默认为 binary */ readFileSync:(filePath:string,encoding?:string)=>any; /** * 重命名文件,可以把文件从 oldPath 移动到 newPath */ rename:(object:any)=>void; /** * FileSystemManager.rename 的同步版本,重命名文件 */ renameSync:(oldPath:string,newPath:string)=>any; /** * 删除目录 */ rmdir:(object:any)=>void; /** * FileSystemManager.rmdir 的同步版本,移除目录 * @param 要删除的目录路径 * @param 是否递归删除目录。如果为 true,则删除该目录和该目录下的所有子目录以及文件。 */ rmdirSync:(dirPath:string,recursive?:boolean)=>void; /** * 读取目录内文件列表 */ readdir:(object:any)=>void; /** * FileSystemManager.readdir 的同步版本,读取目录 */ readdirSync:(dirPath:string)=>Array; /** * 删除文件 */ unlink:(object:any)=>void; /** * FileSystemManager.unlink 的同步版本,删除文件 */ unlinkSync:(filePath:string)=>any; /** * 解压文件 */ unzip:(object:any)=>void; /** * 写文件异步方式 */ writeFile:(object:any)=>void; /** * FileSystemManager.writeFile 的同步版本,写文件 * @param 要写入的文件路径 * @param 要写入的文本或二进制数据 * @param 指定写入文件的字符编码 utf8 or binary,默认值为 utf8 * @param 默认为 false,覆盖旧文件 */ writeFileSync:(filePath:string, data:any, encoding?:string, append?:boolean)=>boolean; /** * 保存临时文件到本地。此接口会移动临时文件,因此调用成功后,tempFilePath 将不可用。 */ saveFile:(object:any)=>void; /** * FileSystemManager.saveFile 的同步版本,保存临时文件到本地。 * @param 临时存储文件路径 * @param 要存储的文件路径 * @returns 存储后的文件路径 */ saveFileSync:(tempFilePath:string, filePath?:string)=>string; /** * 删除该OPPO小游戏下已保存的本地缓存文件 */ removeSavedFile:(object:any )=>void; /** * 获取文件 Stats 对象 */ stat:(object:any)=>void; } interface _LoadSubpackageTask{ /** * 用于获取分包加载状态 */ onProgressUpdate:(callback:Function)=>void; } interface _NativeAd{ /** * 获取广告数据,成功回调 onLoad,失败回调 onError */ load:()=>void; /** * 销毁广告组件,释放资源 */ destroy:()=>void; /** * 上报广告曝光,一个广告只有一次上报有效,adId 为 load 方法获取的广告数据的 adId 字段 */ reportAdShow:(callback:Function) => void; /** * 上报广告点击,一个广告只有一次上报有效,adId 为 load 方法获取的广告数据的 adId 字段 */ reportAdClick:(callback:Function) => void; /** * 设置广告加载成功回调 */ onLoad:(callback:Function)=>void; /** * 移除广告加载成功回调 */ offLoad:(callback:Function)=>void; /** * 设置出错回调 */ onError:(callback:Function)=>void; /** * 移除出错回调 */ offError:(callback:Function)=>void; } interface _InsertAd{ /** * 拉取插屏广告资源,成功回调 onLoad,失败回调 onError */ load:()=>void; /** * 展示插屏广告,成功回调 onShow,失败回调 onError */ show:()=>void; /** * 销毁组件,释放资源 */ destroy:()=>void; /** * 设置插屏广告加载成功回调 */ onLoad:(callback:Function)=>void; /** * 移除插屏广告加载成功回调 */ offLoad:(callback:Function)=>void; /** * 设置插屏广告展示成功回调 */ onShow:(callback:Function)=>void; /** * 移除banner 隐藏回调 */ offShow:(callback:Function)=>void; /** * 设置插屏广告失败回调 */ onError:(callback:Function)=>void; /** * 移除插屏广告失败回调 */ offError:(callback:Function)=>void; } interface _VideoAd{ /** * 手动拉取广告,成功回调 onLoad,失败回调 onError */ load:()=>void; /** * 视频广告组件默认是隐藏的,调用 show 方法展示广告,成功回调 onVideoStart,失败回调 onError. * 开发者不可控制视频广告的关闭,只有用户主动点击关闭按钮才会关闭广告 */ show:()=>void; /** * 销毁组件,释放资源 */ destroy:()=>void; /** * 设置视频广告加载成功回调 */ onLoad:(callback:Function)=>void; /** * 移除视频广告加载成功回调 */ offLoad:(callback:Function)=>void; /** * 设置视频广告开始播放回调 */ onVideoStart:(callback:Function)=>void; /** * 移除视频广告开始播放回调 */ offVideoStart:(callback:Function)=>void; /** * 设置视频奖励发放回调 */ onRewarded:(callback:Function)=>void; /** * 移除视频奖励发放回调 */ offRewarded:(callback:Function)=>void; /** * 设置视频广告出错回调 */ onError:(callback:Function)=>void; /** * 移除视频广告出错回调 */ offError:(callback:Function)=>void; } interface _BannerAd{ /** * 调用 load 方法请求展示 banner,成功的时候回调 onShow,出错的时候回调 onError */ show:()=>void; /** * 隐藏 banner,成功回调 onHide, 出错的时候回调 onError */ hide:()=>void; /** * 设置 banner 成功展示回调 */ onShow:(callback:Function)=>void; /** * 移除 banner 成功展示回调 */ offShow:(callback:Function)=>void; /** * 设置 banner 隐藏回调 */ onHide:(callback:Function)=>void; /** * 移除banner 隐藏回调 */ offHide:(callback:Function)=>void; /** * 设置失败回调 */ onError:(callback:Function)=>void; /** * 移除失败回调 */ offError:(callback:Function)=>void; } interface _Battle { /** * 对战初始化。初始化完成后可以获得对战信息,进行其他操作。(游戏双方都调用该方法后,才能触发success回调) */ init :(object:any) => void; /** * 发送游戏当前的状态给平台。**注:调用postGameStatus设置游戏状态时,每个状态都只能调用一次,不要重复调用。 */ postGameStatus :(object:any) =>void; /** * 平台通知游戏开始。平台主动调此方法触发开始逻辑。(双方都调用postGameStatus且status为1时,才会触发该方法) */ onGameStart:(callback:Function)=>void; /** * 弹出确认对话框,提示是否退出对局。**注:该方法用于CP自己实现了退出按钮的通用处理逻辑,一般情况下不需要调用该方法;success回调不代表真正退出,仅将退出请求发送到服务端,退出游戏还是需要通过服务端驱动。 */ quit:(object:any)=>void; /** * 游戏发送消息。 */ postMessage:(object:any) =>void; /** * 游戏接收推送的消息。 */ onMessage:(callback:Function)=>void; /** * 游戏传数据给游戏平台。 */ writeBlackboard:(object:any)=>void; } interface _DownloadTask { /** * 中断下载任务 */ abort:()=>void; /** * 监听下载进度变化事件 */ onProgressUpdate:(callback:Function)=>void; } declare function App(options: _AppOptions): void; /** * 获取到小程序实例 */ declare function getApp(): object; declare interface PageOptions { /** * 页面的初始数据 */ data?: any; /** * 生命周期函数--监听页面加载 */ onLoad?: (options?: object) => void; /** * 生命周期函数--监听页面初次渲染完成 */ onReady?: () => void; /** * 生命周期函数--监听页面显示 */ onShow?: () => void; /** * 生命周期函数--监听页面隐藏 */ onHide?: () => void; /** * 生命周期函数--监听页面卸载 */ onUnload?: () => void; /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh?: () => void; /** * 页面上拉触底事件的处理函数 */ onReachBottom?: () => void; /** * 用户点击右上角分享 */ onShareAppMessage?: () => _ShareAppMessageReturnObject; } declare function Page(page: PageOptions): void; declare function getCurrentPages(): object[]; declare namespace qg { /** * 批量添加卡券。 */ export function addCard(object: _addCardObject): void; /** * 调用后,用户可以选择将该表单以“新增联系人”或“添加到已有联系人”的方式,写入手机系统通讯录,完成手机通讯录联系人和联系方式的增加。 */ export function addPhoneContact(object: _addPhoneContactObject): void; /** * 将 ArrayBuffer 数据转成 Base64 字符串 */ export function arrayBufferToBase64(): void; /** * 提前向用户发起授权请求。调用后会立刻弹窗询问用户是否同意授权小程序使用某项功能或获取用户的某些数据,但不会实际调用对应接口。如果用户之前已经同意授权,则不会出现弹窗,直接返回成功。 */ export function authorize(object: _authorizeObject): void; /** * 将 Base64 字符串转成 ArrayBuffer 数据 */ export function base64ToArrayBuffer(base64: string): void; /** * 判断小程序的API,回调,参数,组件等是否在当前版本可用。 */ export function canIUse(string: string): void; /** * 返回一个数组,用来描述 canvas 区域隐含的像素数据 */ export function canvasGetImageData(object: _canvasGetImageDataObject): void; /** * 将像素数据绘制到画布的方法 */ export function canvasPutImageData(object: _canvasPutImageDataObject): void; /** * 把当前画布指定区域的内容导出生成指定大小的图片,并返回文件路径。 */ export function canvasToTempFilePath( this: string, object: _canvasToTempFilePathObject ): void; /** * 获取设备内是否录入如指纹等生物信息的接口 */ export function checkIsSoterEnrolledInDevice( object: _checkIsSoterEnrolledInDeviceObject ): void; /** * 获取本机支持的 SOTER 生物认证方式 */ export function checkIsSupportSoterAuthentication( object: _checkIsSupportSoterAuthenticationObject ): void; /** * 通过上述接口获得的用户登录态拥有一定的时效性。用户越久未使用小程序,用户登录态越有可能失效。反之如果用户一直在使用小程序,则用户登录态一直保持有效。具体时效逻辑由微信维护,对开发者透明。开发者只需要调用wx.checkSession接口**检测当前用户登录态是否有效**。登录态过期后开发者可以再调用wx.login获取新的用户登录态。 */ export function checkSession(object: _checkSessionObject): void; /** * 调起用户编辑收货地址原生界面,并在编辑完成后返回用户选择的地址。 */ export function chooseAddress(object: _chooseAddressObject): void; /** * 调起选择手机通讯录联系人界面,返回用户选择的联系人信息。 */ export function chooseContact(object: _chooseContactObject): void; /** * 从本地相册选择图片或使用相机拍照。 */ export function chooseImage(object: _chooseImageObject): void; /** * 选择用户的发票抬头。 */ export function chooseInvoiceTitle(object: _chooseInvoiceTitleObject): void; /** * 打开地图选择位置。 */ export function chooseLocation(object: _chooseLocationObject): void; /** * 拍摄视频或从手机相册中选视频,返回视频的临时文件路径。 */ export function chooseVideo(object: _chooseVideoObject): void; /** * 清理本地数据缓存。 */ export function clearStorage(): void; /** * 同步清理本地数据缓存 */ export function clearStorageSync(): void; /** * 断开与低功耗蓝牙设备的连接 */ export function closeBLEConnection(object: _closeBLEConnectionObject): void; /** * 关闭蓝牙模块,使其进入未初始化状态。调用该方法将断开所有已建立的链接并释放系统资源。建议在使用小程序蓝牙流程后调用,与`wx.openBluetoothAdapter`成对调用。 */ export function closeBluetoothAdapter( object: _closeBluetoothAdapterObject ): void; /** * 关闭 WebSocket 连接。 */ export function closeSocket(object: _closeSocketObject): void; /** * 创建一个 [WebSocket](https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket) 连接。**使用前请先阅读[说明](./api-network.md)**。 */ export function connectSocket(object: _connectSocketObject): void; /** * 连接 Wi-Fi。若已知 Wi-Fi 信息,可以直接利用该接口连接。仅 Android 与 iOS 11 以上版本支持。 */ export function connectWifi(object: _connectWifiObject): void; /** * 创建一个动画实例[animation](#animation)。调用实例的方法来描述动画。最后通过动画实例的`export`方法导出动画数据传递给组件的`animation`属性。 */ export function createAnimation(object: _createAnimationObject): void; /** * 创建并返回 audio 上下文 `audioContext` 对象。在自定义组件下,第二个参数传入组件实例this,以操作组件内 `