From 9f89b0ef24bff948c6b44250855cfa8724d9bbba Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 30 Aug 2019 11:35:22 +0800 Subject: [PATCH] New module division (#5285) * Temp * temp * move ui core * Arrange ui and terrain * Fix import path for all modules except core * Move primitives into core * Fix debug.getError * Move audio-downloader to audio module * export game from game.ts * Migrate load-pipeline to ts * Fix core modules and cleanup * Move animation into core * Fix module exports * Fix director issue * Remove most cc.director usage * Fix ts issues * Fix issues for unit test and editor running * Revert removing deprecated import * tweaks * tweaks * Fix ci * Fix ci * Add modules in module division * Upgrade coordinates-converts-utils --- EngineErrorMap.md | 4 +- cocos/3d/assets/primitive.ts | 30 - cocos/3d/ui/ui-vertex-format.ts | 19 - .../{3d/assets/audio => audio/assets}/clip.ts | 6 +- .../audio => audio/assets}/player-dom.ts | 0 .../audio => audio/assets}/player-web.ts | 5 +- .../audio => audio/assets}/player-wx.ts | 0 .../assets/audio => audio/assets}/player.ts | 0 .../audio-downloader.ts} | 41 +- .../audio-source-component.ts | 8 +- cocos/components/WXSubContextView.ts | 141 - cocos/compression/ZipUtils.js | 77 - cocos/compression/base64.js | 85 - cocos/compression/gzip.js | 733 ---- cocos/compression/zlib.min.js | 55 - cocos/{ => core}/3d/builtin/effects.ts | 0 cocos/{ => core}/3d/builtin/index.ts | 0 cocos/{ => core}/3d/builtin/init.ts | 6 +- .../3d/framework/avatar-model-component.ts | 15 +- .../batched-skinning-model-component.ts | 15 +- .../3d/framework/camera-component.ts | 13 +- .../framework/directional-light-component.ts | 2 +- .../3d/framework/editor-camera-component.ts | 13 +- cocos/{ => core}/3d/framework/index.ts | 13 - .../3d/framework/light-component.ts | 6 +- .../3d/framework/model-component.ts | 9 +- .../3d/framework/renderable-component.ts | 7 +- .../3d/framework/skinning-model-component.ts | 13 +- .../3d/framework/sphere-light-component.ts | 2 +- .../3d/framework/spot-light-component.ts | 4 +- cocos/{ => core}/3d/index.ts | 7 - cocos/{ => core}/3d/misc/buffer-blob.ts | 0 cocos/{ => core}/3d/misc/utils.ts | 12 +- .../animation/animation-blend-state.ts | 2 +- cocos/{ => core}/animation/animation-clip.ts | 11 +- .../animation/animation-component.ts | 16 +- cocos/{ => core}/animation/animation-curve.ts | 13 +- .../{ => core}/animation/animation-manager.ts | 22 +- cocos/{ => core}/animation/animation-state.ts | 23 +- cocos/{ => core}/animation/bezier.ts | 0 cocos/{ => core}/animation/blending.ts | 2 +- cocos/{ => core}/animation/cross-fade.ts | 14 +- .../animation/cubic-spline-value.ts | 4 +- .../animation/curve-value-adapters/index.ts | 0 .../animation/curve-value-adapters/uniform.ts | 4 +- cocos/{ => core}/animation/deprecated.ts | 2 +- cocos/{ => core}/animation/easing.ts | 0 cocos/{ => core}/animation/index.ts | 2 +- .../animation/motion-path-helper.ts | 26 +- cocos/{ => core}/animation/playable.ts | 2 +- .../animation/skeletal-animation-clip.ts | 6 +- .../animation/skeletal-animation-component.ts | 10 +- .../animation/skeletal-animation-state.ts | 6 +- cocos/{ => core}/animation/target-modifier.ts | 6 +- cocos/{ => core}/animation/transform-utils.ts | 4 +- cocos/{ => core}/animation/types.ts | 2 +- cocos/{ => core}/assets/asset-enum.ts | 0 cocos/{ => core}/assets/asset-library.ts | 12 +- cocos/{ => core}/assets/asset.ts | 16 +- cocos/{ => core}/assets/bitmap-font.ts | 2 +- cocos/{3d => core}/assets/effect-asset.ts | 17 +- cocos/{ => core}/assets/font.ts | 2 +- cocos/{ => core}/assets/image-asset.ts | 8 +- cocos/{ => core}/assets/index.ts | 7 +- cocos/{ => core}/assets/json-asset.ts | 2 +- cocos/{ => core}/assets/label-atlas.ts | 2 +- cocos/{3d => core}/assets/material.ts | 16 +- cocos/{3d => core}/assets/mesh.ts | 15 +- cocos/{ => core}/assets/prefab.ts | 8 +- cocos/{ => core}/assets/raw-asset.ts | 6 +- cocos/{ => core}/assets/render-texture.ts | 9 +- cocos/{ => core}/assets/scene-asset.ts | 2 +- cocos/{ => core}/assets/scripts.ts | 2 +- cocos/{ => core}/assets/simple-texture.ts | 4 +- cocos/{3d => core}/assets/skeleton.ts | 2 +- cocos/{ => core}/assets/sprite-atlas.ts | 4 +- cocos/{ => core}/assets/sprite-frame.ts | 6 +- cocos/{ => core}/assets/text-asset.ts | 2 +- cocos/{ => core}/assets/texture-2d.ts | 2 +- cocos/{ => core}/assets/texture-base.ts | 8 +- cocos/{3d => core}/assets/texture-cube.ts | 10 +- cocos/{ => core}/assets/texture-util.ts | 2 +- cocos/{ => core}/assets/ttf-font.ts | 2 +- .../{3d => core}/assets/utils/buffer-view.ts | 0 cocos/{3d => core}/assets/utils/mesh-utils.ts | 0 .../block-input-events-component.ts | 6 +- .../components/component-event-handler.ts | 2 +- cocos/{ => core}/components/component.ts | 32 +- cocos/{ => core}/components/index.ts | 7 +- cocos/{ => core}/components/missing-script.ts | 282 +- cocos/core/components/system.ts | 62 + .../components/ui-base}/canvas-component.ts | 60 +- .../components/ui-base}/index.ts | 19 +- .../components/ui-base}/ui-component.ts | 6 +- .../ui-base}/ui-render-component.ts | 15 +- .../ui-base}/ui-transfrom-component.ts | 7 +- cocos/core/data/class.ts | 2 +- cocos/core/data/utils/attribute.ts | 2 +- cocos/core/data/utils/preprocess-class.ts | 2 +- cocos/core/director.ts | 230 +- cocos/core/event/callbacks-invoker.ts | 2 +- cocos/core/game.ts | 11 +- cocos/{3d => core}/geom-utils/aabb.ts | 0 cocos/{3d => core}/geom-utils/curve.ts | 0 cocos/{3d => core}/geom-utils/deprecated.ts | 34 +- cocos/{3d => core}/geom-utils/distance.ts | 4 +- cocos/{3d => core}/geom-utils/enums.ts | 0 cocos/{3d => core}/geom-utils/frustum.ts | 2 +- cocos/{3d => core}/geom-utils/index.ts | 2 +- cocos/{3d => core}/geom-utils/intersect.ts | 2 +- cocos/{3d => core}/geom-utils/line.ts | 2 +- cocos/{3d => core}/geom-utils/obb.ts | 2 +- cocos/{3d => core}/geom-utils/octree.ts | 2 +- cocos/{3d => core}/geom-utils/plane.ts | 2 +- cocos/{3d => core}/geom-utils/ray.ts | 2 +- cocos/{3d => core}/geom-utils/sphere.ts | 2 +- cocos/{3d => core}/geom-utils/triangle.ts | 2 +- cocos/{ => core}/gfx/binding-layout.ts | 0 cocos/{ => core}/gfx/buffer.ts | 0 cocos/{ => core}/gfx/command-allocator.ts | 0 cocos/{ => core}/gfx/command-buffer.ts | 0 cocos/{ => core}/gfx/define.ts | 0 cocos/{ => core}/gfx/device.ts | 2 +- cocos/{ => core}/gfx/framebuffer.ts | 0 cocos/{ => core}/gfx/index.ts | 0 cocos/{ => core}/gfx/input-assembler.ts | 0 cocos/{ => core}/gfx/pipeline-layout.ts | 0 cocos/{ => core}/gfx/pipeline-state.ts | 0 cocos/{ => core}/gfx/queue.ts | 0 cocos/{ => core}/gfx/render-pass.ts | 0 cocos/{ => core}/gfx/sampler.ts | 0 cocos/{ => core}/gfx/shader.ts | 0 cocos/{ => core}/gfx/texture-view.ts | 0 cocos/{ => core}/gfx/texture.ts | 0 cocos/{ => core}/gfx/webgl/WebGL.d.ts | 0 .../gfx/webgl/webgl-binding-layout.ts | 0 cocos/{ => core}/gfx/webgl/webgl-buffer.ts | 0 .../gfx/webgl/webgl-command-allocator.ts | 2 +- .../gfx/webgl/webgl-command-buffer.ts | 0 cocos/{ => core}/gfx/webgl/webgl-commands.ts | 2 +- cocos/{ => core}/gfx/webgl/webgl-define.ts | 0 cocos/{ => core}/gfx/webgl/webgl-device.ts | 0 .../{ => core}/gfx/webgl/webgl-framebuffer.ts | 0 .../{ => core}/gfx/webgl/webgl-gpu-objects.ts | 0 .../gfx/webgl/webgl-input-assembler.ts | 0 .../gfx/webgl/webgl-pipeline-layout.ts | 0 .../gfx/webgl/webgl-pipeline-state.ts | 0 cocos/{ => core}/gfx/webgl/webgl-queue.ts | 0 .../{ => core}/gfx/webgl/webgl-render-pass.ts | 0 cocos/{ => core}/gfx/webgl/webgl-sampler.ts | 0 cocos/{ => core}/gfx/webgl/webgl-shader.ts | 0 .../{ => core}/gfx/webgl/webgl-state-cache.ts | 0 .../gfx/webgl/webgl-texture-view.ts | 0 cocos/{ => core}/gfx/webgl/webgl-texture.ts | 0 cocos/{ => core}/gfx/webgl/webgl-window.ts | 0 cocos/{ => core}/gfx/webgl2/WebGL2.d.ts | 0 .../gfx/webgl2/webgl2-binding-layout.ts | 0 cocos/{ => core}/gfx/webgl2/webgl2-buffer.ts | 0 .../gfx/webgl2/webgl2-command-allocator.ts | 2 +- .../gfx/webgl2/webgl2-command-buffer.ts | 0 .../{ => core}/gfx/webgl2/webgl2-commands.ts | 2 +- cocos/{ => core}/gfx/webgl2/webgl2-device.ts | 0 .../gfx/webgl2/webgl2-framebuffer.ts | 0 .../gfx/webgl2/webgl2-gpu-objects.ts | 0 .../gfx/webgl2/webgl2-input-assembler.ts | 0 .../gfx/webgl2/webgl2-pipeline-layout.ts | 0 .../gfx/webgl2/webgl2-pipeline-state.ts | 0 cocos/{ => core}/gfx/webgl2/webgl2-queue.ts | 0 .../gfx/webgl2/webgl2-render-pass.ts | 0 cocos/{ => core}/gfx/webgl2/webgl2-sampler.ts | 0 cocos/{ => core}/gfx/webgl2/webgl2-shader.ts | 0 .../gfx/webgl2/webgl2-state-cache.ts | 0 .../gfx/webgl2/webgl2-texture-view.ts | 0 cocos/{ => core}/gfx/webgl2/webgl2-texture.ts | 0 cocos/{ => core}/gfx/webgl2/webgl2-window.ts | 0 cocos/{ => core}/gfx/window.ts | 0 cocos/core/index.ts | 26 +- cocos/{ => core}/legacy.ts | 4 +- cocos/{ => core}/load-pipeline/CCLoader.ts | 32 +- .../load-pipeline/asset-loader.ts} | 35 +- .../load-pipeline/asset-table.ts} | 83 +- .../load-pipeline/auto-release-utils.ts} | 33 +- .../load-pipeline/binary-downloader.ts} | 0 .../load-pipeline/callback-params.ts | 0 .../load-pipeline/downloader.ts} | 113 +- .../load-pipeline/font-loader.ts} | 27 +- cocos/{ => core}/load-pipeline/index.ts | 0 .../load-pipeline/loader.ts} | 48 +- .../load-pipeline/loading-items.ts} | 406 +- .../load-pipeline/md5-pipe.ts} | 27 +- .../load-pipeline/pack-downloader.ts} | 38 +- .../load-pipeline/pipeline.ts} | 59 +- .../load-pipeline/plist-parser.ts} | 34 +- .../load-pipeline/released-asset-checker.ts} | 18 +- .../load-pipeline/subpackage-pipe.ts} | 75 +- .../load-pipeline/text-downloader.ts} | 4 +- .../load-pipeline/unpackers.ts} | 27 +- .../url.js => core/load-pipeline/url.ts} | 0 .../utils.js => core/load-pipeline/utils.ts} | 8 +- .../load-pipeline/uuid-loader.ts} | 118 +- cocos/core/math/color.ts | 12 +- cocos/core/math/deprecated.ts | 2 +- cocos/core/math/index.ts | 2 +- cocos/{3d => core}/memop/circular-pool.ts | 0 cocos/{3d => core}/memop/fixed-array.ts | 0 cocos/{3d => core}/memop/index.ts | 0 cocos/{3d => core}/memop/linked-array.ts | 0 cocos/{3d => core}/memop/optimized-array.ts | 0 cocos/{3d => core}/memop/pool.ts | 0 cocos/{3d => core}/memop/recycle-pool.ts | 0 cocos/{3d => core}/memop/sort.ts | 0 cocos/{3d => core}/memop/timsort.ts | 0 cocos/{3d => core}/memop/typed-array-pool.ts | 0 cocos/{ => core}/pipeline/culling.ts | 18 +- cocos/{ => core}/pipeline/define.ts | 0 .../pipeline/forward/forward-flow.ts | 0 .../pipeline/forward/forward-pipeline.ts | 8 +- .../pipeline/forward/forward-stage.ts | 0 cocos/{ => core}/pipeline/index.ts | 0 cocos/{ => core}/pipeline/pass-phase.ts | 0 cocos/{ => core}/pipeline/pipeline-funcs.ts | 0 .../{ => core}/pipeline/ppfx/tonemap-flow.ts | 0 .../{ => core}/pipeline/ppfx/tonemap-stage.ts | 0 cocos/{ => core}/pipeline/render-flow.ts | 2 +- cocos/{ => core}/pipeline/render-pipeline.ts | 6 +- cocos/{ => core}/pipeline/render-queue.ts | 2 +- cocos/{ => core}/pipeline/render-stage.ts | 0 cocos/{ => core}/pipeline/render-view.ts | 2 +- cocos/{ => core}/pipeline/ui/ui-flow.ts | 0 cocos/{ => core}/pipeline/ui/ui-stage.ts | 0 cocos/core/platform/{CCDebug.ts => debug.ts} | 4 +- .../platform/event-manager/event-listener.ts | 2 +- .../platform/event-manager/event-manager.ts | 2 +- .../event-manager/{CCEvent.ts => events.ts} | 5 +- cocos/core/platform/event-manager/index.ts | 10 +- .../platform/event-manager/input-manager.ts | 48 +- .../platform/event-manager/system-event.ts | 4 +- .../event-manager/{CCTouch.ts => touch.ts} | 3 +- cocos/core/platform/index.ts | 10 +- cocos/core/platform/{CCMacro.ts => macro.ts} | 0 .../core/platform/{CCScreen.ts => screen.ts} | 0 cocos/core/platform/{CCSys.ts => sys.ts} | 0 cocos/core/platform/{CCView.ts => view.ts} | 3249 +++++++++-------- .../{CCVisibleRect.ts => visible-rect.ts} | 0 cocos/{3d => core}/primitive/box.ts | 2 +- cocos/{3d => core}/primitive/capsule.ts | 2 +- cocos/{3d => core}/primitive/circle.ts | 2 +- cocos/{3d => core}/primitive/cone.ts | 0 cocos/{3d => core}/primitive/cylinder.ts | 2 +- cocos/{3d => core}/primitive/define.ts | 4 +- cocos/{3d => core}/primitive/index.ts | 0 cocos/{3d => core}/primitive/plane.ts | 2 +- cocos/core/primitive/primitive.ts | 31 + cocos/{3d => core}/primitive/quad.ts | 0 cocos/{3d => core}/primitive/sphere.ts | 2 +- cocos/{3d => core}/primitive/torus.ts | 2 +- cocos/{3d => core}/primitive/transform.ts | 2 +- cocos/{3d => core}/primitive/utils.ts | 2 +- cocos/{ => core}/renderer/config.ts | 0 cocos/{ => core}/renderer/core/constants.ts | 0 cocos/{ => core}/renderer/core/pass.ts | 13 +- cocos/{ => core}/renderer/core/program-lib.ts | 2 +- cocos/{ => core}/renderer/core/sampler-lib.ts | 0 .../renderer/core/texture-buffer-pool.ts | 0 cocos/{ => core}/renderer/index.ts | 3 - .../renderer/models/joints-texture-utils.ts | 6 +- .../renderer/models/model-uniforms.ts | 0 .../renderer/models/skinning-model.ts | 8 +- cocos/{ => core}/renderer/scene/ambient.ts | 0 cocos/{ => core}/renderer/scene/camera.ts | 8 +- .../renderer/scene/customization-manager.ts | 0 .../renderer/scene/directional-light.ts | 4 +- cocos/{ => core}/renderer/scene/light.ts | 4 +- cocos/{ => core}/renderer/scene/model.ts | 39 +- .../renderer/scene/planar-shadows.ts | 7 +- .../{ => core}/renderer/scene/render-scene.ts | 12 +- cocos/{ => core}/renderer/scene/skybox.ts | 6 +- .../{ => core}/renderer/scene/sphere-light.ts | 6 +- cocos/{ => core}/renderer/scene/spot-light.ts | 6 +- cocos/{ => core}/renderer/scene/submodel.ts | 9 +- .../ui/assembler => core/renderer/ui}/base.ts | 4 +- cocos/{3d => core/renderer}/ui/mesh-buffer.ts | 28 +- .../renderer/ui/render-data.ts} | 32 +- .../renderer/ui}/stencil-manager.ts | 63 +- .../{ => core}/renderer/ui/ui-batch-model.ts | 26 +- cocos/core/renderer/ui/ui-material.ts | 90 + cocos/core/renderer/ui/ui-vertex-format.ts | 43 + cocos/{ => core}/renderer/ui/ui.ts | 54 +- cocos/{ => core}/renderer/utils.ts | 0 cocos/core/root.ts | 16 +- cocos/{ => core}/scene-graph/base-node-dev.ts | 9 +- cocos/{ => core}/scene-graph/base-node.ts | 36 +- .../scene-graph/component-scheduler.ts | 10 +- cocos/{ => core}/scene-graph/deprecated.ts | 2 +- cocos/{ => core}/scene-graph/find.ts | 5 +- cocos/{ => core}/scene-graph/index.ts | 2 +- cocos/{ => core}/scene-graph/layers.ts | 0 .../{ => core}/scene-graph/node-activator.ts | 8 +- cocos/{ => core}/scene-graph/node-enum.ts | 0 .../scene-graph/node-event-processor.ts | 16 +- cocos/{ => core}/scene-graph/node.ts | 16 +- cocos/{ => core}/scene-graph/private-node.ts | 4 +- cocos/{ => core}/scene-graph/scene-globals.ts | 8 +- cocos/{ => core}/scene-graph/scene.ts | 2 +- cocos/core/scheduler.ts | 198 +- .../core/utils/coordinates-converts-utils.ts | 15 +- cocos/{ => core/utils}/deprecated.ts | 2 +- cocos/core/utils/index.ts | 4 +- cocos/core/utils/interfaces.ts | 12 +- cocos/core/utils/js-typed.ts | 2 +- cocos/core/utils/profiler/profiler.ts | 68 +- cocos/core/value-types/value-type.ts | 2 +- cocos/{ => core}/vmath.ts | 4 +- .../particle/animator/color-overtime.ts | 5 +- .../particle/animator/curve-range.ts | 9 +- .../particle/animator/force-overtime.ts | 7 +- .../particle/animator/gradient-range.ts | 17 +- .../particle/animator/gradient.ts | 11 +- .../animator/limit-velocity-overtime.ts | 7 +- .../particle/animator/optimized-curve.ts | 5 +- .../particle/animator/rotation-overtime.ts | 5 +- .../particle/animator/size-overtime.ts | 5 +- .../particle/animator/texture-animation.ts | 6 +- .../particle/animator/velocity-overtime.ts | 6 +- .../particle/billboard-component.ts | 21 +- cocos/{3d/framework => }/particle/burst.ts | 5 +- .../particle/emitter/shape-module.ts | 6 +- cocos/{3d/framework => }/particle/enum.ts | 2 +- cocos/particle/index.ts | 17 + .../framework => }/particle/line-component.ts | 19 +- .../models/line-model.ts | 18 +- .../models/particle-batch-model.ts | 21 +- .../particle/particle-general-function.ts | 4 +- .../particle/particle-system-component.ts | 12 +- .../framework => }/particle/particle-utils.ts | 18 +- cocos/{3d/framework => }/particle/particle.ts | 6 +- .../renderer/particle-system-renderer.ts | 24 +- .../framework => }/particle/renderer/trail.ts | 44 +- cocos/{3d => }/physics/ammo-impl.ts | 7 +- cocos/{3d => }/physics/ammo/debugger.ts | 18 +- cocos/{3d => }/physics/api.ts | 2 +- .../physics => physics/assets}/material.ts | 4 +- cocos/{3d => }/physics/cannon/cannon-body.ts | 2 +- cocos/{3d => }/physics/cannon/cannon-const.ts | 0 cocos/{3d => }/physics/cannon/cannon-util.ts | 1 - cocos/{3d => }/physics/cannon/cannon-world.ts | 2 +- .../cannon/constraint/cannon-constraint.ts | 0 .../constraint/cannon-distance-constraint.ts | 0 .../constraint/cannon-lock-constraint.ts | 0 .../cannon-point-to-point-constraint.ts | 2 +- cocos/{3d => }/physics/cannon/instantiate.ts | 0 .../physics/cannon/shapes/cannon-box-shape.ts | 2 +- .../physics/cannon/shapes/cannon-shape.ts | 4 +- .../cannon/shapes/cannon-sphere-shape.ts | 2 +- cocos/{3d => }/physics/cocos/builtin-body.ts | 4 +- .../physics/cocos/builtin-interface.ts | 2 +- cocos/{3d => }/physics/cocos/builtin-world.ts | 2 +- cocos/{3d => }/physics/cocos/instantiate.ts | 0 .../physics/cocos/object/builtin-object.ts | 0 .../physics/cocos/shapes/builtin-box-shape.ts | 4 +- .../physics/cocos/shapes/builtin-shape.ts | 2 +- .../cocos/shapes/builtin-sphere-shape.ts | 2 +- .../cocos/utils/array-collision-matrix.ts | 0 .../collider/box-collider-component.ts | 8 +- .../collider/collider-component.ts | 18 +- .../collider/sphere-collider-component.ts | 6 +- .../components}/constant-force.ts | 6 +- .../components}/default-material.ts | 2 +- .../detail/physics-based-component.ts | 23 +- .../physics => physics/components}/index.ts | 0 .../components}/physics-system.ts | 40 +- .../components}/rigid-body-component.ts | 4 +- cocos/{3d => }/physics/export-api.ts | 4 +- cocos/{3d => }/physics/impl-selector.ts | 0 cocos/{3d => }/physics/instance.ts | 2 +- cocos/{3d => }/physics/physic-enum.ts | 0 cocos/{3d => }/physics/raycast-result.ts | 6 +- cocos/{3d => }/physics/util.ts | 2 +- cocos/renderer/ui/ui-material.ts | 67 - cocos/{renderer => }/terrain/height-field.ts | 2 +- cocos/terrain/index.ts | 3 + cocos/{renderer => }/terrain/terrain.ts | 48 +- cocos/tween/deprecated.ts | 5 +- cocos/tween/tween.ts | 19 + .../{3d => }/ui/assembler/graphics/helper.ts | 0 cocos/{3d => }/ui/assembler/graphics/index.ts | 0 cocos/{3d => }/ui/assembler/graphics/types.ts | 2 +- .../ui/assembler/graphics/webgl/earcut.ts | 0 .../graphics/webgl/graphics-assembler.ts | 21 +- .../ui/assembler/graphics/webgl/impl.ts | 11 +- .../ui/assembler/graphics/webgl/index.ts | 2 +- cocos/{3d => }/ui/assembler/index.ts | 2 +- cocos/{3d => }/ui/assembler/label/bmfont.ts | 10 +- .../ui/assembler/label/bmfontUtils.ts | 13 +- .../{3d => }/ui/assembler/label/font-utils.ts | 0 cocos/{3d => }/ui/assembler/label/index.ts | 10 +- .../ui/assembler/label/letter-font.ts | 29 +- cocos/{3d => }/ui/assembler/label/letter.ts | 7 +- cocos/{3d => }/ui/assembler/label/ttf.ts | 10 +- cocos/{3d => }/ui/assembler/label/ttfUtils.ts | 20 +- cocos/{3d => }/ui/assembler/mask/index.ts | 2 - .../ui/assembler/mask/mask-assembler.ts | 10 +- .../ui/assembler/sprite/bar-filled.ts | 14 +- cocos/{3d => }/ui/assembler/sprite/index.ts | 2 +- cocos/{3d => }/ui/assembler/sprite/mesh.js | 2 - .../ui/assembler/sprite/radial-filled.ts | 11 +- cocos/{3d => }/ui/assembler/sprite/simple.ts | 8 +- cocos/{3d => }/ui/assembler/sprite/sliced.ts | 10 +- cocos/{3d => }/ui/assembler/sprite/tiled.ts | 11 +- cocos/{3d => }/ui/assembler/utils.ts | 8 +- .../ui/components/button-component.ts | 20 +- .../components/editbox/edit-box-component.ts | 28 +- .../ui/components/editbox/edit-box-impl.ts | 97 +- cocos/{3d => }/ui/components/editbox/types.ts | 2 +- .../ui/components/graphics-component.ts | 22 +- cocos/{3d => }/ui/components/index.ts | 4 - .../{3d => }/ui/components/label-component.ts | 18 +- .../ui/components/label-outline-component.ts | 6 +- .../ui/components/layout-component.ts | 19 +- .../{3d => }/ui/components/mask-component.ts | 31 +- .../ui/components/page-view-component.ts | 15 +- .../page-view-indicator-component.ts | 15 +- .../ui/components/progress-bar-component.ts | 19 +- .../ui/components/rich-text-component.ts | 38 +- .../ui/components/scroll-bar-component.ts | 14 +- .../ui/components/scroll-view-component.ts | 30 +- .../ui/components/slider-component.ts | 20 +- .../ui/components/sprite-component.ts | 18 +- .../ui/components/toggle-component.ts | 4 +- .../components/toggle-container-component.ts | 4 +- .../ui/components/ui-model-component.ts | 15 +- .../ui/components/ui-reorder-component.ts | 4 +- .../ui/components/view-group-component.ts | 4 +- .../components/webview/webView-component.ts | 6 +- .../ui/components/webview/webview-impl.ts | 36 +- .../ui/components/widget-component.ts | 56 +- .../{3d => }/ui/components/widget-manager.ts | 92 +- cocos/{3d => }/ui/index.ts | 6 +- exports/audio.ts | 4 +- exports/base.ts | 21 +- exports/gfx-webgl.ts | 2 +- exports/gfx-webgl2.ts | 2 +- exports/particle.ts | 5 + exports/physics-ammo.ts | 2 +- exports/physics-builtin.ts | 4 +- exports/physics-cannon.ts | 4 +- exports/physics-framework.ts | 10 +- exports/terrain.ts | 5 + exports/ui.ts | 5 + extensions/ccpool/node-pool.ts | 4 +- extensions/dragonbones/CCSlot.js | 2 +- extensions/videoplayer/video-player-impl.js | 2 +- index.ts | 5 +- predefine.js => predefine.ts | 8 +- scripts/module-division/division-config.json | 18 + ...imation-clip.js => animation-clip.test.js} | 0 tests/animation/animation-curve.test.ts | 6 +- tests/animation/animation.test.js | 1432 ++++++++ tests/animation/test-animation.js | 1412 ------- tests/init.ts | 2 +- tests/page.html | 35 - tests/page.js | 31 - tsconfig.json | 4 +- 463 files changed, 5883 insertions(+), 6701 deletions(-) delete mode 100644 cocos/3d/assets/primitive.ts delete mode 100644 cocos/3d/ui/ui-vertex-format.ts rename cocos/{3d/assets/audio => audio/assets}/clip.ts (96%) rename cocos/{3d/assets/audio => audio/assets}/player-dom.ts (100%) rename cocos/{3d/assets/audio => audio/assets}/player-web.ts (96%) rename cocos/{3d/assets/audio => audio/assets}/player-wx.ts (100%) rename cocos/{3d/assets/audio => audio/assets}/player.ts (100%) rename cocos/{load-pipeline/audio-downloader.js => audio/audio-downloader.ts} (77%) rename cocos/{3d/framework => audio}/audio-source-component.ts (96%) delete mode 100644 cocos/components/WXSubContextView.ts delete mode 100644 cocos/compression/ZipUtils.js delete mode 100644 cocos/compression/base64.js delete mode 100644 cocos/compression/gzip.js delete mode 100644 cocos/compression/zlib.min.js rename cocos/{ => core}/3d/builtin/effects.ts (100%) rename cocos/{ => core}/3d/builtin/index.ts (100%) rename cocos/{ => core}/3d/builtin/init.ts (96%) rename cocos/{ => core}/3d/framework/avatar-model-component.ts (96%) rename cocos/{ => core}/3d/framework/batched-skinning-model-component.ts (97%) rename cocos/{ => core}/3d/framework/camera-component.ts (96%) rename cocos/{ => core}/3d/framework/directional-light-component.ts (98%) rename cocos/{ => core}/3d/framework/editor-camera-component.ts (89%) rename cocos/{ => core}/3d/framework/index.ts (85%) rename cocos/{ => core}/3d/framework/light-component.ts (96%) rename cocos/{ => core}/3d/framework/model-component.ts (97%) rename cocos/{ => core}/3d/framework/renderable-component.ts (94%) rename cocos/{ => core}/3d/framework/skinning-model-component.ts (92%) rename cocos/{ => core}/3d/framework/sphere-light-component.ts (99%) rename cocos/{ => core}/3d/framework/spot-light-component.ts (98%) rename cocos/{ => core}/3d/index.ts (90%) rename cocos/{ => core}/3d/misc/buffer-blob.ts (100%) rename cocos/{ => core}/3d/misc/utils.ts (98%) rename cocos/{ => core}/animation/animation-blend-state.ts (98%) rename cocos/{ => core}/animation/animation-clip.ts (97%) rename cocos/{ => core}/animation/animation-component.ts (97%) rename cocos/{ => core}/animation/animation-curve.ts (96%) rename cocos/{ => core}/animation/animation-manager.ts (80%) rename cocos/{ => core}/animation/animation-state.ts (97%) rename cocos/{ => core}/animation/bezier.ts (100%) rename cocos/{ => core}/animation/blending.ts (97%) rename cocos/{ => core}/animation/cross-fade.ts (92%) rename cocos/{ => core}/animation/cubic-spline-value.ts (97%) rename cocos/{ => core}/animation/curve-value-adapters/index.ts (100%) rename cocos/{ => core}/animation/curve-value-adapters/uniform.ts (87%) rename cocos/{ => core}/animation/deprecated.ts (91%) rename cocos/{ => core}/animation/easing.ts (100%) rename cocos/{ => core}/animation/index.ts (96%) rename cocos/{ => core}/animation/motion-path-helper.ts (94%) rename cocos/{ => core}/animation/playable.ts (97%) rename cocos/{ => core}/animation/skeletal-animation-clip.ts (97%) rename cocos/{ => core}/animation/skeletal-animation-component.ts (96%) rename cocos/{ => core}/animation/skeletal-animation-state.ts (95%) rename cocos/{ => core}/animation/target-modifier.ts (95%) rename cocos/{ => core}/animation/transform-utils.ts (95%) rename cocos/{ => core}/animation/types.ts (97%) rename cocos/{ => core}/assets/asset-enum.ts (100%) rename cocos/{ => core}/assets/asset-library.ts (97%) rename cocos/{ => core}/assets/asset.ts (94%) rename cocos/{ => core}/assets/bitmap-font.ts (96%) rename cocos/{3d => core}/assets/effect-asset.ts (92%) rename cocos/{ => core}/assets/font.ts (96%) rename cocos/{ => core}/assets/image-asset.ts (97%) rename cocos/{ => core}/assets/index.ts (91%) rename cocos/{ => core}/assets/json-asset.ts (96%) rename cocos/{ => core}/assets/label-atlas.ts (96%) rename cocos/{3d => core}/assets/material.ts (96%) rename cocos/{3d => core}/assets/mesh.ts (99%) rename cocos/{ => core}/assets/prefab.ts (97%) rename cocos/{ => core}/assets/raw-asset.ts (92%) rename cocos/{ => core}/assets/render-texture.ts (93%) rename cocos/{ => core}/assets/scene-asset.ts (96%) rename cocos/{ => core}/assets/scripts.ts (97%) rename cocos/{ => core}/assets/simple-texture.ts (98%) rename cocos/{3d => core}/assets/skeleton.ts (98%) rename cocos/{ => core}/assets/sprite-atlas.ts (97%) rename cocos/{ => core}/assets/sprite-frame.ts (99%) rename cocos/{ => core}/assets/text-asset.ts (96%) rename cocos/{ => core}/assets/texture-2d.ts (99%) rename cocos/{ => core}/assets/texture-base.ts (97%) rename cocos/{3d => core}/assets/texture-cube.ts (97%) rename cocos/{ => core}/assets/texture-util.ts (98%) rename cocos/{ => core}/assets/ttf-font.ts (96%) rename cocos/{3d => core}/assets/utils/buffer-view.ts (100%) rename cocos/{3d => core}/assets/utils/mesh-utils.ts (100%) rename cocos/{ => core}/components/block-input-events-component.ts (94%) rename cocos/{ => core}/components/component-event-handler.ts (98%) rename cocos/{ => core}/components/component.ts (96%) rename cocos/{ => core}/components/index.ts (87%) rename cocos/{ => core}/components/missing-script.ts (93%) create mode 100644 cocos/core/components/system.ts rename cocos/{3d/ui/components => core/components/ui-base}/canvas-component.ts (84%) rename cocos/{3d/assets => core/components/ui-base}/index.ts (70%) rename cocos/{3d/ui/components => core/components/ui-base}/ui-component.ts (97%) rename cocos/{3d/ui/components => core/components/ui-base}/ui-render-component.ts (95%) rename cocos/{3d/ui/components => core/components/ui-base}/ui-transfrom-component.ts (98%) rename cocos/{3d => core}/geom-utils/aabb.ts (100%) rename cocos/{3d => core}/geom-utils/curve.ts (100%) rename cocos/{3d => core}/geom-utils/deprecated.ts (75%) rename cocos/{3d => core}/geom-utils/distance.ts (97%) rename cocos/{3d => core}/geom-utils/enums.ts (100%) rename cocos/{3d => core}/geom-utils/frustum.ts (99%) rename cocos/{3d => core}/geom-utils/index.ts (96%) rename cocos/{3d => core}/geom-utils/intersect.ts (99%) rename cocos/{3d => core}/geom-utils/line.ts (98%) rename cocos/{3d => core}/geom-utils/obb.ts (99%) rename cocos/{3d => core}/geom-utils/octree.ts (99%) rename cocos/{3d => core}/geom-utils/plane.ts (98%) rename cocos/{3d => core}/geom-utils/ray.ts (98%) rename cocos/{3d => core}/geom-utils/sphere.ts (99%) rename cocos/{3d => core}/geom-utils/triangle.ts (99%) rename cocos/{ => core}/gfx/binding-layout.ts (100%) rename cocos/{ => core}/gfx/buffer.ts (100%) rename cocos/{ => core}/gfx/command-allocator.ts (100%) rename cocos/{ => core}/gfx/command-buffer.ts (100%) rename cocos/{ => core}/gfx/define.ts (100%) rename cocos/{ => core}/gfx/device.ts (99%) rename cocos/{ => core}/gfx/framebuffer.ts (100%) rename cocos/{ => core}/gfx/index.ts (100%) rename cocos/{ => core}/gfx/input-assembler.ts (100%) rename cocos/{ => core}/gfx/pipeline-layout.ts (100%) rename cocos/{ => core}/gfx/pipeline-state.ts (100%) rename cocos/{ => core}/gfx/queue.ts (100%) rename cocos/{ => core}/gfx/render-pass.ts (100%) rename cocos/{ => core}/gfx/sampler.ts (100%) rename cocos/{ => core}/gfx/shader.ts (100%) rename cocos/{ => core}/gfx/texture-view.ts (100%) rename cocos/{ => core}/gfx/texture.ts (100%) rename cocos/{ => core}/gfx/webgl/WebGL.d.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-binding-layout.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-buffer.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-command-allocator.ts (98%) rename cocos/{ => core}/gfx/webgl/webgl-command-buffer.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-commands.ts (99%) rename cocos/{ => core}/gfx/webgl/webgl-define.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-device.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-framebuffer.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-gpu-objects.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-input-assembler.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-pipeline-layout.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-pipeline-state.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-queue.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-render-pass.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-sampler.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-shader.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-state-cache.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-texture-view.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-texture.ts (100%) rename cocos/{ => core}/gfx/webgl/webgl-window.ts (100%) rename cocos/{ => core}/gfx/webgl2/WebGL2.d.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-binding-layout.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-buffer.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-command-allocator.ts (98%) rename cocos/{ => core}/gfx/webgl2/webgl2-command-buffer.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-commands.ts (99%) rename cocos/{ => core}/gfx/webgl2/webgl2-device.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-framebuffer.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-gpu-objects.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-input-assembler.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-pipeline-layout.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-pipeline-state.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-queue.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-render-pass.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-sampler.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-shader.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-state-cache.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-texture-view.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-texture.ts (100%) rename cocos/{ => core}/gfx/webgl2/webgl2-window.ts (100%) rename cocos/{ => core}/gfx/window.ts (100%) rename cocos/{ => core}/legacy.ts (91%) rename cocos/{ => core}/load-pipeline/CCLoader.ts (98%) rename cocos/{load-pipeline/asset-loader.js => core/load-pipeline/asset-loader.ts} (77%) rename cocos/{load-pipeline/asset-table.js => core/load-pipeline/asset-table.ts} (71%) rename cocos/{load-pipeline/auto-release-utils.js => core/load-pipeline/auto-release-utils.ts} (84%) rename cocos/{load-pipeline/binary-downloader.js => core/load-pipeline/binary-downloader.ts} (100%) rename cocos/{ => core}/load-pipeline/callback-params.ts (100%) rename cocos/{load-pipeline/downloader.js => core/load-pipeline/downloader.ts} (78%) rename cocos/{load-pipeline/font-loader.js => core/load-pipeline/font-loader.ts} (89%) rename cocos/{ => core}/load-pipeline/index.ts (100%) rename cocos/{load-pipeline/loader.js => core/load-pipeline/loader.ts} (90%) rename cocos/{load-pipeline/loading-items.js => core/load-pipeline/loading-items.ts} (72%) rename cocos/{load-pipeline/md5-pipe.js => core/load-pipeline/md5-pipe.ts} (81%) rename cocos/{load-pipeline/pack-downloader.js => core/load-pipeline/pack-downloader.ts} (91%) rename cocos/{load-pipeline/pipeline.js => core/load-pipeline/pipeline.ts} (92%) rename cocos/{load-pipeline/plist-parser.js => core/load-pipeline/plist-parser.ts} (84%) rename cocos/{load-pipeline/released-asset-checker.js => core/load-pipeline/released-asset-checker.ts} (88%) rename cocos/{load-pipeline/subpackage-pipe.js => core/load-pipeline/subpackage-pipe.ts} (54%) rename cocos/{load-pipeline/text-downloader.js => core/load-pipeline/text-downloader.ts} (96%) rename cocos/{load-pipeline/unpackers.js => core/load-pipeline/unpackers.ts} (82%) rename cocos/{load-pipeline/url.js => core/load-pipeline/url.ts} (100%) rename cocos/{load-pipeline/utils.js => core/load-pipeline/utils.ts} (92%) rename cocos/{load-pipeline/uuid-loader.js => core/load-pipeline/uuid-loader.ts} (79%) rename cocos/{3d => core}/memop/circular-pool.ts (100%) rename cocos/{3d => core}/memop/fixed-array.ts (100%) rename cocos/{3d => core}/memop/index.ts (100%) rename cocos/{3d => core}/memop/linked-array.ts (100%) rename cocos/{3d => core}/memop/optimized-array.ts (100%) rename cocos/{3d => core}/memop/pool.ts (100%) rename cocos/{3d => core}/memop/recycle-pool.ts (100%) rename cocos/{3d => core}/memop/sort.ts (100%) rename cocos/{3d => core}/memop/timsort.ts (100%) rename cocos/{3d => core}/memop/typed-array-pool.ts (100%) rename cocos/{ => core}/pipeline/culling.ts (91%) rename cocos/{ => core}/pipeline/define.ts (100%) rename cocos/{ => core}/pipeline/forward/forward-flow.ts (100%) rename cocos/{ => core}/pipeline/forward/forward-pipeline.ts (97%) rename cocos/{ => core}/pipeline/forward/forward-stage.ts (100%) rename cocos/{ => core}/pipeline/index.ts (100%) rename cocos/{ => core}/pipeline/pass-phase.ts (100%) rename cocos/{ => core}/pipeline/pipeline-funcs.ts (100%) rename cocos/{ => core}/pipeline/ppfx/tonemap-flow.ts (100%) rename cocos/{ => core}/pipeline/ppfx/tonemap-stage.ts (100%) rename cocos/{ => core}/pipeline/render-flow.ts (98%) rename cocos/{ => core}/pipeline/render-pipeline.ts (99%) rename cocos/{ => core}/pipeline/render-queue.ts (98%) rename cocos/{ => core}/pipeline/render-stage.ts (100%) rename cocos/{ => core}/pipeline/render-view.ts (99%) rename cocos/{ => core}/pipeline/ui/ui-flow.ts (100%) rename cocos/{ => core}/pipeline/ui/ui-stage.ts (100%) rename cocos/core/platform/{CCDebug.ts => debug.ts} (99%) rename cocos/core/platform/event-manager/{CCEvent.ts => events.ts} (99%) rename cocos/core/platform/event-manager/{CCTouch.ts => touch.ts} (99%) rename cocos/core/platform/{CCMacro.ts => macro.ts} (100%) rename cocos/core/platform/{CCScreen.ts => screen.ts} (100%) rename cocos/core/platform/{CCSys.ts => sys.ts} (100%) rename cocos/core/platform/{CCView.ts => view.ts} (94%) rename cocos/core/platform/{CCVisibleRect.ts => visible-rect.ts} (100%) rename cocos/{3d => core}/primitive/box.ts (99%) rename cocos/{3d => core}/primitive/capsule.ts (99%) rename cocos/{3d => core}/primitive/circle.ts (97%) rename cocos/{3d => core}/primitive/cone.ts (100%) rename cocos/{3d => core}/primitive/cylinder.ts (99%) rename cocos/{3d => core}/primitive/define.ts (96%) rename cocos/{3d => core}/primitive/index.ts (100%) rename cocos/{3d => core}/primitive/plane.ts (98%) create mode 100644 cocos/core/primitive/primitive.ts rename cocos/{3d => core}/primitive/quad.ts (100%) rename cocos/{3d => core}/primitive/sphere.ts (97%) rename cocos/{3d => core}/primitive/torus.ts (98%) rename cocos/{3d => core}/primitive/transform.ts (98%) rename cocos/{3d => core}/primitive/utils.ts (98%) rename cocos/{ => core}/renderer/config.ts (100%) rename cocos/{ => core}/renderer/core/constants.ts (100%) rename cocos/{ => core}/renderer/core/pass.ts (98%) rename cocos/{ => core}/renderer/core/program-lib.ts (99%) rename cocos/{ => core}/renderer/core/sampler-lib.ts (100%) rename cocos/{ => core}/renderer/core/texture-buffer-pool.ts (100%) rename cocos/{ => core}/renderer/index.ts (80%) rename cocos/{ => core}/renderer/models/joints-texture-utils.ts (97%) rename cocos/{ => core}/renderer/models/model-uniforms.ts (100%) rename cocos/{ => core}/renderer/models/skinning-model.ts (96%) rename cocos/{ => core}/renderer/scene/ambient.ts (100%) rename cocos/{ => core}/renderer/scene/camera.ts (98%) rename cocos/{ => core}/renderer/scene/customization-manager.ts (100%) rename cocos/{ => core}/renderer/scene/directional-light.ts (91%) rename cocos/{ => core}/renderer/scene/light.ts (96%) rename cocos/{ => core}/renderer/scene/model.ts (92%) rename cocos/{ => core}/renderer/scene/planar-shadows.ts (97%) rename cocos/{ => core}/renderer/scene/render-scene.ts (97%) rename cocos/{ => core}/renderer/scene/skybox.ts (94%) rename cocos/{ => core}/renderer/scene/sphere-light.ts (90%) rename cocos/{ => core}/renderer/scene/spot-light.ts (94%) rename cocos/{ => core}/renderer/scene/submodel.ts (94%) rename cocos/{3d/ui/assembler => core/renderer/ui}/base.ts (91%) rename cocos/{3d => core/renderer}/ui/mesh-buffer.ts (83%) rename cocos/{renderer/ui/renderData.ts => core/renderer/ui/render-data.ts} (76%) rename cocos/{3d/ui/assembler/mask => core/renderer/ui}/stencil-manager.ts (77%) rename cocos/{ => core}/renderer/ui/ui-batch-model.ts (50%) create mode 100644 cocos/core/renderer/ui/ui-material.ts create mode 100644 cocos/core/renderer/ui/ui-vertex-format.ts rename cocos/{ => core}/renderer/ui/ui.ts (88%) rename cocos/{ => core}/renderer/utils.ts (100%) rename cocos/{ => core}/scene-graph/base-node-dev.ts (96%) rename cocos/{ => core}/scene-graph/base-node.ts (97%) rename cocos/{ => core}/scene-graph/component-scheduler.ts (98%) rename cocos/{ => core}/scene-graph/deprecated.ts (89%) rename cocos/{ => core}/scene-graph/find.ts (94%) rename cocos/{ => core}/scene-graph/index.ts (98%) rename cocos/{ => core}/scene-graph/layers.ts (100%) rename cocos/{ => core}/scene-graph/node-activator.ts (98%) rename cocos/{ => core}/scene-graph/node-enum.ts (100%) rename cocos/{ => core}/scene-graph/node-event-processor.ts (98%) rename cocos/{ => core}/scene-graph/node.ts (98%) rename cocos/{ => core}/scene-graph/private-node.ts (98%) rename cocos/{ => core}/scene-graph/scene-globals.ts (96%) rename cocos/{ => core}/scene-graph/scene.ts (98%) rename cocos/{ => core/utils}/deprecated.ts (99%) rename cocos/{ => core}/vmath.ts (96%) rename cocos/{3d/framework => }/particle/animator/color-overtime.ts (85%) rename cocos/{3d/framework => }/particle/animator/curve-range.ts (90%) rename cocos/{3d/framework => }/particle/animator/force-overtime.ts (91%) rename cocos/{3d/framework => }/particle/animator/gradient-range.ts (87%) rename cocos/{3d/framework => }/particle/animator/gradient.ts (93%) rename cocos/{3d/framework => }/particle/animator/limit-velocity-overtime.ts (94%) rename cocos/{3d/framework => }/particle/animator/optimized-curve.ts (98%) rename cocos/{3d/framework => }/particle/animator/rotation-overtime.ts (92%) rename cocos/{3d/framework => }/particle/animator/size-overtime.ts (93%) rename cocos/{3d/framework => }/particle/animator/texture-animation.ts (96%) rename cocos/{3d/framework => }/particle/animator/velocity-overtime.ts (94%) rename cocos/{3d/framework => }/particle/billboard-component.ts (88%) rename cocos/{3d/framework => }/particle/burst.ts (93%) rename cocos/{3d/framework => }/particle/emitter/shape-module.ts (98%) rename cocos/{3d/framework => }/particle/enum.ts (98%) create mode 100644 cocos/particle/index.ts rename cocos/{3d/framework => }/particle/line-component.ts (90%) rename cocos/{renderer => particle}/models/line-model.ts (95%) rename cocos/{renderer => particle}/models/particle-batch-model.ts (95%) rename cocos/{3d/framework => }/particle/particle-general-function.ts (97%) rename cocos/{3d/framework => }/particle/particle-system-component.ts (98%) rename cocos/{3d/framework => }/particle/particle-utils.ts (68%) rename cocos/{3d/framework => }/particle/particle.ts (90%) rename cocos/{3d/framework => }/particle/renderer/particle-system-renderer.ts (96%) rename cocos/{3d/framework => }/particle/renderer/trail.ts (95%) rename cocos/{3d => }/physics/ammo-impl.ts (99%) rename cocos/{3d => }/physics/ammo/debugger.ts (91%) rename cocos/{3d => }/physics/api.ts (99%) rename cocos/{3d/assets/physics => physics/assets}/material.ts (90%) rename cocos/{3d => }/physics/cannon/cannon-body.ts (99%) rename cocos/{3d => }/physics/cannon/cannon-const.ts (100%) rename cocos/{3d => }/physics/cannon/cannon-util.ts (97%) rename cocos/{3d => }/physics/cannon/cannon-world.ts (98%) rename cocos/{3d => }/physics/cannon/constraint/cannon-constraint.ts (100%) rename cocos/{3d => }/physics/cannon/constraint/cannon-distance-constraint.ts (100%) rename cocos/{3d => }/physics/cannon/constraint/cannon-lock-constraint.ts (100%) rename cocos/{3d => }/physics/cannon/constraint/cannon-point-to-point-constraint.ts (94%) rename cocos/{3d => }/physics/cannon/instantiate.ts (100%) rename cocos/{3d => }/physics/cannon/shapes/cannon-box-shape.ts (98%) rename cocos/{3d => }/physics/cannon/shapes/cannon-shape.ts (95%) rename cocos/{3d => }/physics/cannon/shapes/cannon-sphere-shape.ts (96%) rename cocos/{3d => }/physics/cocos/builtin-body.ts (97%) rename cocos/{3d => }/physics/cocos/builtin-interface.ts (82%) rename cocos/{3d => }/physics/cocos/builtin-world.ts (99%) rename cocos/{3d => }/physics/cocos/instantiate.ts (100%) rename cocos/{3d => }/physics/cocos/object/builtin-object.ts (100%) rename cocos/{3d => }/physics/cocos/shapes/builtin-box-shape.ts (86%) rename cocos/{3d => }/physics/cocos/shapes/builtin-shape.ts (97%) rename cocos/{3d => }/physics/cocos/shapes/builtin-sphere-shape.ts (92%) rename cocos/{3d => }/physics/cocos/utils/array-collision-matrix.ts (100%) rename cocos/{3d/framework/physics => physics/components}/collider/box-collider-component.ts (87%) rename cocos/{3d/framework/physics => physics/components}/collider/collider-component.ts (93%) rename cocos/{3d/framework/physics => physics/components}/collider/sphere-collider-component.ts (89%) rename cocos/{3d/framework/physics => physics/components}/constant-force.ts (95%) rename cocos/{3d/framework/physics => physics/components}/default-material.ts (78%) rename cocos/{3d/framework/physics => physics/components}/detail/physics-based-component.ts (94%) rename cocos/{3d/framework/physics => physics/components}/index.ts (100%) rename cocos/{3d/framework/physics => physics/components}/physics-system.ts (81%) rename cocos/{3d/framework/physics => physics/components}/rigid-body-component.ts (99%) rename cocos/{3d => }/physics/export-api.ts (93%) rename cocos/{3d => }/physics/impl-selector.ts (100%) rename cocos/{3d => }/physics/instance.ts (95%) rename cocos/{3d => }/physics/physic-enum.ts (100%) rename cocos/{3d => }/physics/raycast-result.ts (84%) rename cocos/{3d => }/physics/util.ts (95%) delete mode 100644 cocos/renderer/ui/ui-material.ts rename cocos/{renderer => }/terrain/height-field.ts (97%) create mode 100644 cocos/terrain/index.ts rename cocos/{renderer => }/terrain/terrain.ts (96%) rename cocos/{3d => }/ui/assembler/graphics/helper.ts (100%) rename cocos/{3d => }/ui/assembler/graphics/index.ts (100%) rename cocos/{3d => }/ui/assembler/graphics/types.ts (98%) rename cocos/{3d => }/ui/assembler/graphics/webgl/earcut.ts (100%) rename cocos/{3d => }/ui/assembler/graphics/webgl/graphics-assembler.ts (97%) rename cocos/{3d => }/ui/assembler/graphics/webgl/impl.ts (92%) rename cocos/{3d => }/ui/assembler/graphics/webgl/index.ts (95%) rename cocos/{3d => }/ui/assembler/index.ts (96%) rename cocos/{3d => }/ui/assembler/label/bmfont.ts (93%) rename cocos/{3d => }/ui/assembler/label/bmfontUtils.ts (98%) rename cocos/{3d => }/ui/assembler/label/font-utils.ts (100%) rename cocos/{3d => }/ui/assembler/label/index.ts (85%) rename cocos/{3d => }/ui/assembler/label/letter-font.ts (97%) rename cocos/{3d => }/ui/assembler/label/letter.ts (91%) rename cocos/{3d => }/ui/assembler/label/ttf.ts (94%) rename cocos/{3d => }/ui/assembler/label/ttfUtils.ts (96%) rename cocos/{3d => }/ui/assembler/mask/index.ts (66%) rename cocos/{3d => }/ui/assembler/mask/mask-assembler.ts (90%) rename cocos/{3d => }/ui/assembler/sprite/bar-filled.ts (96%) rename cocos/{3d => }/ui/assembler/sprite/index.ts (97%) rename cocos/{3d => }/ui/assembler/sprite/mesh.js (98%) rename cocos/{3d => }/ui/assembler/sprite/radial-filled.ts (97%) rename cocos/{3d => }/ui/assembler/sprite/simple.ts (97%) rename cocos/{3d => }/ui/assembler/sprite/sliced.ts (95%) rename cocos/{3d => }/ui/assembler/sprite/tiled.ts (96%) rename cocos/{3d => }/ui/assembler/utils.ts (95%) rename cocos/{3d => }/ui/components/button-component.ts (97%) rename cocos/{3d => }/ui/components/editbox/edit-box-component.ts (96%) rename cocos/{3d => }/ui/components/editbox/edit-box-impl.ts (88%) rename cocos/{3d => }/ui/components/editbox/types.ts (98%) rename cocos/{3d => }/ui/components/graphics-component.ts (93%) rename cocos/{3d => }/ui/components/index.ts (85%) rename cocos/{3d => }/ui/components/label-component.ts (96%) rename cocos/{3d => }/ui/components/label-outline-component.ts (94%) rename cocos/{3d => }/ui/components/layout-component.ts (98%) rename cocos/{3d => }/ui/components/mask-component.ts (93%) rename cocos/{3d => }/ui/components/page-view-component.ts (97%) rename cocos/{3d => }/ui/components/page-view-indicator-component.ts (93%) rename cocos/{3d => }/ui/components/progress-bar-component.ts (92%) rename cocos/{3d => }/ui/components/rich-text-component.ts (96%) rename cocos/{3d => }/ui/components/scroll-bar-component.ts (97%) rename cocos/{3d => }/ui/components/scroll-view-component.ts (98%) rename cocos/{3d => }/ui/components/slider-component.ts (93%) rename cocos/{3d => }/ui/components/sprite-component.ts (96%) rename cocos/{3d => }/ui/components/toggle-component.ts (98%) rename cocos/{3d => }/ui/components/toggle-container-component.ts (98%) rename cocos/{3d => }/ui/components/ui-model-component.ts (88%) rename cocos/{3d => }/ui/components/ui-reorder-component.ts (92%) rename cocos/{3d => }/ui/components/view-group-component.ts (93%) rename cocos/{3d => }/ui/components/webview/webView-component.ts (97%) rename cocos/{3d => }/ui/components/webview/webview-impl.ts (94%) rename cocos/{3d => }/ui/components/widget-component.ts (92%) rename cocos/{3d => }/ui/components/widget-manager.ts (90%) rename cocos/{3d => }/ui/index.ts (79%) create mode 100644 exports/particle.ts create mode 100644 exports/terrain.ts create mode 100644 exports/ui.ts rename predefine.js => predefine.ts (97%) rename tests/animation/{test-animation-clip.js => animation-clip.test.js} (100%) create mode 100644 tests/animation/animation.test.js delete mode 100644 tests/animation/test-animation.js delete mode 100644 tests/page.html delete mode 100644 tests/page.js diff --git a/EngineErrorMap.md b/EngineErrorMap.md index ad533b05e7..b29217e7dc 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -288,7 +288,7 @@ Argument target must be non-nullptr ### 1510 -cc.Scheduler: Illegal target which doesn't have uuid or instanceId. +cc.Scheduler: Illegal target which doesn't have id, you should do Scheduler.enableForTarget(target) before all scheduler API usage on target ### 1511 @@ -300,7 +300,7 @@ cc.Scheduler: updateFunc parameter is deprecated in scheduleUpdate function, and ### 1513 -cc.Scheduler: scheduler stopped using `__instanceId` as id since v2.0, you should do scheduler.enableForTarget(target) before all scheduler API usage on target +cc.Scheduler: scheduler stopped using `__instanceId` as id since v2.0, you should do Scheduler.enableForTarget(target) before all scheduler API usage on target ### 1600 diff --git a/cocos/3d/assets/primitive.ts b/cocos/3d/assets/primitive.ts deleted file mode 100644 index 79392c30d3..0000000000 --- a/cocos/3d/assets/primitive.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { ccclass, property } from '../../core/data/class-decorator'; -import { Enum } from '../../core/value-types'; -import { createMesh } from '../misc/utils'; -import * as primitives from '../primitive'; -import { Mesh } from './mesh'; - -const PrimitiveType = Enum({ - BOX: 0, - SPHERE: 1, - CYLINDER: 2, - CONE: 3, - CAPSULE: 4, - TORUS: 5, - PLANE: 6, - QUAD: 7, -}); - -@ccclass('cc.Primitive') -export class Primitive extends Mesh { - @property(PrimitiveType) - public type: number = PrimitiveType.BOX; - @property - public info: Record = {}; - - public onLoaded () { - createMesh(primitives[PrimitiveType[this.type]](this.info), this); - } -} - -cc.Primitive = Primitive; diff --git a/cocos/3d/ui/ui-vertex-format.ts b/cocos/3d/ui/ui-vertex-format.ts deleted file mode 100644 index 4ea53f7635..0000000000 --- a/cocos/3d/ui/ui-vertex-format.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * @category ui - */ -import { GFXAttributeName, GFXFormat } from '../../gfx/define'; - -export const vfmt = [ - { - name: GFXAttributeName.ATTR_POSITION, - format: GFXFormat.RGB32F, - }, - { - name: GFXAttributeName.ATTR_TEX_COORD, - format: GFXFormat.RG32F, - }, - { - name: GFXAttributeName.ATTR_COLOR, - format: GFXFormat.RGBA32F, - }, -]; diff --git a/cocos/3d/assets/audio/clip.ts b/cocos/audio/assets/clip.ts similarity index 96% rename from cocos/3d/assets/audio/clip.ts rename to cocos/audio/assets/clip.ts index 0ee77c5558..8e78f93474 100644 --- a/cocos/3d/assets/audio/clip.ts +++ b/cocos/audio/assets/clip.ts @@ -27,9 +27,9 @@ * @category component/audio */ -import { Asset } from '../../../assets/asset'; -import { ccclass, property } from '../../../core/data/class-decorator'; -import { Enum } from '../../../core/value-types'; +import { Asset } from '../../core/assets/asset'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { Enum } from '../../core/value-types'; import { AudioPlayer, PlayingState } from './player'; import { AudioPlayerDOM } from './player-dom'; import { AudioPlayerWeb } from './player-web'; diff --git a/cocos/3d/assets/audio/player-dom.ts b/cocos/audio/assets/player-dom.ts similarity index 100% rename from cocos/3d/assets/audio/player-dom.ts rename to cocos/audio/assets/player-dom.ts diff --git a/cocos/3d/assets/audio/player-web.ts b/cocos/audio/assets/player-web.ts similarity index 96% rename from cocos/3d/assets/audio/player-web.ts rename to cocos/audio/assets/player-web.ts index 398f48abc6..86d0391e55 100644 --- a/cocos/3d/assets/audio/player-web.ts +++ b/cocos/audio/assets/player-web.ts @@ -27,8 +27,9 @@ * @category component/audio */ -import sys from '../../../core/platform/CCSys'; +import sys from '../../core/platform/sys'; import { AudioPlayer, IAudioInfo, PlayingState } from './player'; +import { director, Director } from '../../core'; const audioSupport = sys.__audioSupport; @@ -74,7 +75,7 @@ export class AudioPlayerWeb extends AudioPlayer { this._state = PlayingState.PLAYING; this._startTime = this._context.currentTime; // delay eval here to yield uniform behavior with other platforms - cc.director.once(cc.Director.EVENT_AFTER_UPDATE, () => { this._eventTarget.emit('started'); }); + director.once(Director.EVENT_AFTER_UPDATE, () => { this._eventTarget.emit('started'); }); /* still not supported by all platforms * this._sourceNode.onended = this._on_ended; /* doing it manually for now */ diff --git a/cocos/3d/assets/audio/player-wx.ts b/cocos/audio/assets/player-wx.ts similarity index 100% rename from cocos/3d/assets/audio/player-wx.ts rename to cocos/audio/assets/player-wx.ts diff --git a/cocos/3d/assets/audio/player.ts b/cocos/audio/assets/player.ts similarity index 100% rename from cocos/3d/assets/audio/player.ts rename to cocos/audio/assets/player.ts diff --git a/cocos/load-pipeline/audio-downloader.js b/cocos/audio/audio-downloader.ts similarity index 77% rename from cocos/load-pipeline/audio-downloader.js rename to cocos/audio/audio-downloader.ts index 195c4c8a8f..c6bcf31616 100644 --- a/cocos/load-pipeline/audio-downloader.js +++ b/cocos/audio/audio-downloader.ts @@ -27,12 +27,13 @@ * @category loader */ -import sys from '../core/platform/CCSys'; -import * as debug from '../core/platform/CCDebug'; -import { AudioClip, AudioType } from '../3d/assets/audio/clip'; +import sys from '../core/platform/sys'; +import { log, getError } from '../core/platform/debug'; +import { AudioClip, AudioType } from './assets/clip'; +import { loader } from '../core/load-pipeline'; -var __audioSupport = sys.__audioSupport; -var formatSupport = __audioSupport.format; +const __audioSupport = sys.__audioSupport; +const formatSupport = __audioSupport.format; function loadWXAudio (item, callback) { var clip = wx.createInnerAudioContext(); @@ -64,7 +65,7 @@ function loadDomAudio (item, callback) { var failure = function () { clearEvent(); var message = 'load audio failure - ' + item.url; - cc.log(message); + log(message); callback(message); }; dom.addEventListener("canplaythrough", success, false); @@ -76,9 +77,9 @@ function loadDomAudio (item, callback) { function loadWebAudio (item, callback) { const context = __audioSupport.context; if (!context) - callback(new Error(debug.getError(4926))); + callback(new Error(getError(4926))); - var request = cc.loader.getXMLHttpRequest(); + var request = loader.getXMLHttpRequest(); request.open("GET", item.url, true); request.responseType = "arraybuffer"; @@ -100,23 +101,31 @@ function loadWebAudio (item, callback) { request.send(); } -export default function downloadAudio (item, callback) { +function downloadAudio (item, callback) { if (formatSupport.length === 0) { - return new Error(debug.getError(4927)); + return new Error(getError(4927)); } - let loader; + let audioLoader; if (CC_WECHATGAME) { - loader = loadWXAudio; + audioLoader = loadWXAudio; } else if (!__audioSupport.WEB_AUDIO) { - loader = loadDomAudio; // If WebAudio is not supported, load using DOM mode + audioLoader = loadDomAudio; // If WebAudio is not supported, load using DOM mode } else { let loadByDeserializedAudio = item._owner instanceof AudioClip; if (loadByDeserializedAudio) { - loader = (item._owner.loadMode === AudioType.WEB_AUDIO) ? loadWebAudio : loadDomAudio; + audioLoader = (item._owner.loadMode === AudioType.WEB_AUDIO) ? loadWebAudio : loadDomAudio; } else { - loader = (item.urlParam && item.urlParam['useDom']) ? loadDomAudio : loadWebAudio; + audioLoader = (item.urlParam && item.urlParam['useDom']) ? loadDomAudio : loadWebAudio; } } - loader(item, callback); + audioLoader(item, callback); } + +loader.downloader.addHandlers({ + // Audio + 'mp3' : downloadAudio, + 'ogg' : downloadAudio, + 'wav' : downloadAudio, + 'm4a' : downloadAudio, +}); \ No newline at end of file diff --git a/cocos/3d/framework/audio-source-component.ts b/cocos/audio/audio-source-component.ts similarity index 96% rename from cocos/3d/framework/audio-source-component.ts rename to cocos/audio/audio-source-component.ts index 9e06092d6a..1d67f5000e 100644 --- a/cocos/3d/framework/audio-source-component.ts +++ b/cocos/audio/audio-source-component.ts @@ -27,10 +27,10 @@ * @category component/audio */ -import { Component } from '../../components/component'; -import { ccclass, menu, property } from '../../core/data/class-decorator'; -import { clamp } from '../../core/math'; -import { AudioClip } from '../assets/audio/clip'; +import { Component } from '../core/components/component'; +import { ccclass, menu, property } from '../core/data/class-decorator'; +import { clamp } from '../core/math'; +import { AudioClip } from './assets/clip'; /** * @en diff --git a/cocos/components/WXSubContextView.ts b/cocos/components/WXSubContextView.ts deleted file mode 100644 index 419e495b69..0000000000 --- a/cocos/components/WXSubContextView.ts +++ /dev/null @@ -1,141 +0,0 @@ -/* - Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { Component } from './component'; - -import { ImageAsset } from '../assets/image-asset'; - -let WXSubContextView; - -if (!CC_EDITOR && !CC_WECHATGAME) { - WXSubContextView = cc.Class({ - name: 'cc.WXSubContextView', - extends: Component, - }); -} -else { - /** - * @en - * WXSubContextView is a view component which controls open data context viewport in Wechat game platform.
- * The component's node size decide the viewport of the sub context content in main context, - * the entire sub context texture will be scaled to the node's bounding box area.
- * This component provides multiple important features:
- * 1. Sub context could use its own resolution size and policy.
- * 2. Sub context could be minized to smallest size it needed.
- * 3. Resolution of sub context content could be increased.
- * 4. User touch input is transformed to the correct viewport.
- * 5. Texture update is handled by this component. User don't need to worry.
- * One important thing to be noted, whenever the node's bounding box change, - * you need to manually reset the viewport of sub context using updateSubContextViewport. - * @zh - * WXSubContextView 可以用来控制微信小游戏平台开放数据域在主域中的视窗的位置。
- * 这个组件的节点尺寸决定了开放数据域内容在主域中的尺寸,整个开放数据域会被缩放到节点的包围盒范围内。
- * 在这个组件的控制下,用户可以更自由得控制开放数据域:
- * 1. 子域中可以使用独立的设计分辨率和适配模式
- * 2. 子域区域尺寸可以缩小到只容纳内容即可
- * 3. 子域的分辨率也可以被放大,以便获得更清晰的显示效果
- * 4. 用户输入坐标会被自动转换到正确的子域视窗中
- * 5. 子域内容贴图的更新由组件负责,用户不需要处理
- * 唯一需要注意的是,当子域节点的包围盒发生改变时,开发者需要使用 `updateSubContextViewport` 来手动更新子域视窗。 - * @class WXSubContextView - * @extends Component - */ - WXSubContextView = cc.Class({ - name: 'cc.WXSubContextView', - extends: Component, - - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.others/WXSubContextView', - help: 'i18n:COMPONENT.help_url.wxSubContextView', - }, - - ctor () { - this._sprite = null; - this._tex = new cc.Texture2D(); - this._context = null; - }, - - onLoad () { - // Setup subcontext canvas size - if (wx.getOpenDataContext) { - this._context = wx.getOpenDataContext(); - const sharedCanvas = this._context.canvas; - if (sharedCanvas) { - sharedCanvas.width = this.node.width; - sharedCanvas.height = this.node.height; - } - this._tex.setPremultiplyAlpha(true); - this._tex.image = new ImageAsset(sharedCanvas); - - this._sprite = this.node.getComponent('cc.SpriteComponent'); - if (!this._sprite) { - this._sprite = this.node.addComponent('cc.SpriteComponent'); - this._sprite.srcBlendFactor = cc.macro.BlendFactor.ONE; - } - this._sprite.spriteFrame = new cc.SpriteFrame(this._tex); - } - else { - this.enabled = false; - } - }, - - onEnable () { - this.updateSubContextViewport(); - }, - - update () { - if (!this._tex || !this._context) { - return; - } - this._tex.updateImage(this._context.canvas); - this._sprite._activateMaterial(); - }, - - /** - * @en Update the sub context viewport manually, it should be called whenever the node's bounding box changes. - * @zh 更新开放数据域相对于主域的 viewport,这个函数应该在节点包围盒改变时手动调用。 - * @method updateSubContextViewport - */ - updateSubContextViewport () { - if (this._context) { - const box = this.node.getBoundingBoxToWorld(); - const sx = cc.view._scaleX; - const sy = cc.view._scaleY; - this._context.postMessage({ - fromEngine: true, - event: 'viewport', - x: box.x * sx + cc.view._viewportRect.x, - y: box.y * sy + cc.view._viewportRect.y, - width: box.width * sx, - height: box.height * sy, - }); - } - }, - }); - -} - -export default WXSubContextView; -cc.WXSubContextView = WXSubContextView; diff --git a/cocos/compression/ZipUtils.js b/cocos/compression/ZipUtils.js deleted file mode 100644 index 778946795f..0000000000 --- a/cocos/compression/ZipUtils.js +++ /dev/null @@ -1,77 +0,0 @@ -/*-- - Copyright 2009-2010 by Stefan Rusterholz. - All rights reserved. - You can choose between MIT and BSD-3-Clause license. License file will be added later. - --*/ - -var codec = {name:'Jacob__Codec'}; - -codec.Base64 = require('./base64'); -codec.GZip = require('./gzip'); - -/** - * Unpack a gzipped byte array - * @param {Array} input Byte array - * @returns {String} Unpacked byte string - */ -codec.unzip = function () { - return codec.GZip.gunzip.apply(codec.GZip, arguments); -}; - -/** - * Unpack a gzipped byte string encoded as base64 - * @param {String} input Byte string encoded as base64 - * @returns {String} Unpacked byte string - */ -codec.unzipBase64 = function () { - var buffer = codec.Base64.decode.apply(codec.Base64, arguments); - try { - return codec.GZip.gunzip.call(codec.GZip, buffer); - } - catch(e) { - // if not zipped, just skip - return buffer.slice(7); // get image data - } -}; - -/** - * Unpack a gzipped byte string encoded as base64 - * @param {String} input Byte string encoded as base64 - * @param {Number} bytes Bytes per array item - * @returns {Array} Unpacked byte array - */ -codec.unzipBase64AsArray = function (input, bytes) { - bytes = bytes || 1; - - var dec = this.unzipBase64(input), - ar = [], i, j, len; - for (i = 0, len = dec.length / bytes; i < len; i++) { - ar[i] = 0; - for (j = bytes - 1; j >= 0; --j) { - ar[i] += dec.charCodeAt((i * bytes) + j) << (j * 8); - } - } - return ar; -}; - -/** - * Unpack a gzipped byte array - * @param {Array} input Byte array - * @param {Number} bytes Bytes per array item - * @returns {Array} Unpacked byte array - */ -codec.unzipAsArray = function (input, bytes) { - bytes = bytes || 1; - - var dec = this.unzip(input), - ar = [], i, j, len; - for (i = 0, len = dec.length / bytes; i < len; i++) { - ar[i] = 0; - for (j = bytes - 1; j >= 0; --j) { - ar[i] += dec.charCodeAt((i * bytes) + j) << (j * 8); - } - } - return ar; -}; - -cc.codec = module.exports = codec; \ No newline at end of file diff --git a/cocos/compression/base64.js b/cocos/compression/base64.js deleted file mode 100644 index 9bfe9c9a94..0000000000 --- a/cocos/compression/base64.js +++ /dev/null @@ -1,85 +0,0 @@ -/*-- - Copyright 2009-2010 by Stefan Rusterholz. - All rights reserved. - You can choose between MIT and BSD-3-Clause license. License file will be added later. - --*/ - -var misc = require('../core/utils/misc'); -var strValue = misc.BASE64_VALUES; - -/** - * mixin cc.Codec.Base64 - */ -var Base64 = {name:'Jacob__Codec__Base64'}; - -/** - *

- * cc.Codec.Base64.decode(input[, unicode=false]) -> String (http://en.wikipedia.org/wiki/Base64). - *

- * @function - * @param {String} input The base64 encoded string to decode - * @return {String} Decodes a base64 encoded String - * @example - * //decode string - * cc.Codec.Base64.decode("U29tZSBTdHJpbmc="); // => "Some String" - */ -Base64.decode = function Jacob__Codec__Base64__decode(input) { - var output = [], - chr1, chr2, chr3, - enc1, enc2, enc3, enc4, - i = 0; - - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - - while (i < input.length) { - enc1 = strValue[input.charCodeAt(i++)]; - enc2 = strValue[input.charCodeAt(i++)]; - enc3 = strValue[input.charCodeAt(i++)]; - enc4 = strValue[input.charCodeAt(i++)]; - - chr1 = (enc1 << 2) | (enc2 >> 4); - chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - chr3 = ((enc3 & 3) << 6) | enc4; - - output.push(String.fromCharCode(chr1)); - - if (enc3 !== 64) { - output.push(String.fromCharCode(chr2)); - } - if (enc4 !== 64) { - output.push(String.fromCharCode(chr3)); - } - } - - output = output.join(''); - - return output; -}; - -/** - *

- * Converts an input string encoded in base64 to an array of integers whose
- * values represent the decoded string's characters' bytes. - *

- * @function - * @param {String} input The String to convert to an array of Integers - * @param {Number} bytes - * @return {Array} - * @example - * //decode string to array - * var decodeArr = cc.Codec.Base64.decodeAsArray("U29tZSBTdHJpbmc="); - */ -Base64.decodeAsArray = function Jacob__Codec__Base64___decodeAsArray(input, bytes) { - var dec = this.decode(input), - ar = [], i, j, len; - for (i = 0, len = dec.length / bytes; i < len; i++) { - ar[i] = 0; - for (j = bytes - 1; j >= 0; --j) { - ar[i] += dec.charCodeAt((i * bytes) + j) << (j * 8); - } - } - - return ar; -}; - -module.exports = Base64; diff --git a/cocos/compression/gzip.js b/cocos/compression/gzip.js deleted file mode 100644 index 88ff3ffd20..0000000000 --- a/cocos/compression/gzip.js +++ /dev/null @@ -1,733 +0,0 @@ -/*-- - Copyright 2009-2010 by Stefan Rusterholz. - All rights reserved. - You can choose between MIT and BSD-3-Clause license. License file will be added later. - --*/ - -/** - * See cc.Codec.GZip.gunzip. - * @param {Array | String} data The bytestream to decompress - * Constructor - */ -var GZip = function Jacob__GZip(data) { - this.data = data; - - this.debug = false; - this.gpflags = undefined; - this.files = 0; - this.unzipped = []; - this.buf32k = new Array(32768); - this.bIdx = 0; - this.modeZIP = false; - this.bytepos = 0; - this.bb = 1; - this.bits = 0; - this.nameBuf = []; - this.fileout = undefined; - this.literalTree = new Array(GZip.LITERALS); - this.distanceTree = new Array(32); - this.treepos = 0; - this.Places = null; - this.len = 0; - this.fpos = new Array(17); - this.fpos[0] = 0; - this.flens = undefined; - this.fmax = undefined; -}; - -/** - * Unzips the gzipped data of the 'data' argument. - * @param string The bytestream to decompress. Either an array of Integers between 0 and 255, or a String. - * @return {String} - */ -GZip.gunzip = function (string) { - if (string.constructor === Array) { - } else if (string.constructor === String) { - } - var gzip = new GZip(string); - return gzip.gunzip()[0][0]; -}; - -GZip.HufNode = function () { - this.b0 = 0; - this.b1 = 0; - this.jump = null; - this.jumppos = -1; -}; - -/** - * @constant - * @type Number - */ -GZip.LITERALS = 288; -/** - * @constant - * @type Number - */ -GZip.NAMEMAX = 256; - -GZip.bitReverse = [ - 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, - 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, - 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, - 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, - 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, - 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, - 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, - 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, - 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, - 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, - 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, - 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, - 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, - 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, - 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, - 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, - 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, - 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, - 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, - 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, - 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, - 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, - 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, - 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, - 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, - 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, - 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, - 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, - 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, - 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, - 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, - 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff -]; -GZip.cplens = [ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 -]; -GZip.cplext = [ - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, - 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99 -]; -/* 99==invalid */ -GZip.cpdist = [ - 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0007, 0x0009, 0x000d, - 0x0011, 0x0019, 0x0021, 0x0031, 0x0041, 0x0061, 0x0081, 0x00c1, - 0x0101, 0x0181, 0x0201, 0x0301, 0x0401, 0x0601, 0x0801, 0x0c01, - 0x1001, 0x1801, 0x2001, 0x3001, 0x4001, 0x6001 -]; -GZip.cpdext = [ - 0, 0, 0, 0, 1, 1, 2, 2, - 3, 3, 4, 4, 5, 5, 6, 6, - 7, 7, 8, 8, 9, 9, 10, 10, - 11, 11, 12, 12, 13, 13 -]; -GZip.border = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; - - -/** - * gunzip - * @return {Array} - */ -GZip.prototype.gunzip = function () { - this.outputArr = []; - - //convertToByteArray(input); - //if (this.debug) alert(this.data); - - this.nextFile(); - return this.unzipped; -}; - -GZip.prototype.readByte = function () { - this.bits += 8; - if (this.bytepos < this.data.length) { - //return this.data[this.bytepos++]; // Array - return this.data.charCodeAt(this.bytepos++); - } else { - return -1; - } -}; - -GZip.prototype.byteAlign = function () { - this.bb = 1; -}; - -GZip.prototype.readBit = function () { - var carry; - this.bits++; - carry = (this.bb & 1); - this.bb >>= 1; - if (this.bb === 0) { - this.bb = this.readByte(); - carry = (this.bb & 1); - this.bb = (this.bb >> 1) | 0x80; - } - return carry; -}; - -GZip.prototype.readBits = function (a) { - var res = 0, - i = a; - - while (i--) res = (res << 1) | this.readBit(); - if (a) res = GZip.bitReverse[res] >> (8 - a); - - return res; -}; - -GZip.prototype.flushBuffer = function () { - this.bIdx = 0; -}; - -GZip.prototype.addBuffer = function (a) { - this.buf32k[this.bIdx++] = a; - this.outputArr.push(String.fromCharCode(a)); - if (this.bIdx === 0x8000) this.bIdx = 0; -}; - -GZip.prototype.IsPat = function () { - while (1) { - if (this.fpos[this.len] >= this.fmax) return -1; - if (this.flens[this.fpos[this.len]] === this.len) return this.fpos[this.len]++; - this.fpos[this.len]++; - } -}; - -GZip.prototype.Rec = function () { - var curplace = this.Places[this.treepos]; - var tmp; - //if (this.debug) document.write("
len:"+this.len+" treepos:"+this.treepos); - if (this.len === 17) { //war 17 - return -1; - } - this.treepos++; - this.len++; - - tmp = this.IsPat(); - //if (this.debug) document.write("
IsPat "+tmp); - if (tmp >= 0) { - curplace.b0 = tmp; - /* leaf cell for 0-bit */ - //if (this.debug) document.write("
b0 "+curplace.b0); - } else { - /* Not a Leaf cell */ - curplace.b0 = 0x8000; - //if (this.debug) document.write("
b0 "+curplace.b0); - if (this.Rec()) return -1; - } - tmp = this.IsPat(); - if (tmp >= 0) { - curplace.b1 = tmp; - /* leaf cell for 1-bit */ - //if (this.debug) document.write("
b1 "+curplace.b1); - curplace.jump = null; - /* Just for the display routine */ - } else { - /* Not a Leaf cell */ - curplace.b1 = 0x8000; - //if (this.debug) document.write("
b1 "+curplace.b1); - curplace.jump = this.Places[this.treepos]; - curplace.jumppos = this.treepos; - if (this.Rec()) return -1; - } - this.len--; - return 0; -}; - -GZip.prototype.CreateTree = function (currentTree, numval, lengths, show) { - var i; - /* Create the Huffman decode tree/table */ - //if (this.debug) document.write("currentTree "+currentTree+" numval "+numval+" lengths "+lengths+" show "+show); - this.Places = currentTree; - this.treepos = 0; - this.flens = lengths; - this.fmax = numval; - for (i = 0; i < 17; i++) this.fpos[i] = 0; - this.len = 0; - if (this.Rec()) { - //if (this.debug) alert("invalid huffman tree\n"); - return -1; - } - // if (this.debug) { - // document.write('
Tree: '+this.Places.length); - // for (var a=0;a<32;a++){ - // document.write("Places["+a+"].b0="+this.Places[a].b0+"
"); - // document.write("Places["+a+"].b1="+this.Places[a].b1+"
"); - // } - // } - - return 0; -}; - -GZip.prototype.DecodeValue = function (currentTree) { - var len, i, - xtreepos = 0, - X = currentTree[xtreepos], - b; - - /* decode one symbol of the data */ - while (1) { - b = this.readBit(); - // if (this.debug) document.write("b="+b); - if (b) { - if (!(X.b1 & 0x8000)) { - // if (this.debug) document.write("ret1"); - return X.b1; - /* If leaf node, return data */ - } - X = X.jump; - len = currentTree.length; - for (i = 0; i < len; i++) { - if (currentTree[i] === X) { - xtreepos = i; - break; - } - } - } else { - if (!(X.b0 & 0x8000)) { - // if (this.debug) document.write("ret2"); - return X.b0; - /* If leaf node, return data */ - } - xtreepos++; - X = currentTree[xtreepos]; - } - } - // if (this.debug) document.write("ret3"); - - return -1; -}; - -GZip.prototype.DeflateLoop = function () { - var last, c, type, i, len; - do { - last = this.readBit(); - type = this.readBits(2); - - if (type === 0) { - var blockLen, cSum; - - // Stored - this.byteAlign(); - blockLen = this.readByte(); - blockLen |= (this.readByte() << 8); - - cSum = this.readByte(); - cSum |= (this.readByte() << 8); - - if (((blockLen ^ ~cSum) & 0xffff)) { - document.write("BlockLen checksum mismatch\n"); // FIXME: use throw - } - while (blockLen--) { - c = this.readByte(); - this.addBuffer(c); - } - } else if (type === 1) { - var j; - - /* Fixed Huffman tables -- fixed decode routine */ - while (1) { - /* - 256 0000000 0 - : : : - 279 0010111 23 - 0 00110000 48 - : : : - 143 10111111 191 - 280 11000000 192 - : : : - 287 11000111 199 - 144 110010000 400 - : : : - 255 111111111 511 - - Note the bit order! - */ - j = (GZip.bitReverse[this.readBits(7)] >> 1); - if (j > 23) { - j = (j << 1) | this.readBit(); - /* 48..255 */ - - if (j > 199) { /* 200..255 */ - j -= 128; - /* 72..127 */ - j = (j << 1) | this.readBit(); - /* 144..255 << */ - } else { /* 48..199 */ - j -= 48; - /* 0..151 */ - if (j > 143) { - j = j + 136; - /* 280..287 << */ - /* 0..143 << */ - } - } - } else { /* 0..23 */ - j += 256; - /* 256..279 << */ - } - if (j < 256) { - this.addBuffer(j); - } else if (j === 256) { - /* EOF */ - break; // FIXME: make this the loop-condition - } else { - var len, dist; - - j -= 256 + 1; - /* bytes + EOF */ - len = this.readBits(GZip.cplext[j]) + GZip.cplens[j]; - - j = GZip.bitReverse[this.readBits(5)] >> 3; - if (GZip.cpdext[j] > 8) { - dist = this.readBits(8); - dist |= (this.readBits(GZip.cpdext[j] - 8) << 8); - } else { - dist = this.readBits(GZip.cpdext[j]); - } - dist += GZip.cpdist[j]; - - for (j = 0; j < len; j++) { - var c = this.buf32k[(this.bIdx - dist) & 0x7fff]; - this.addBuffer(c); - } - } - } // while - - } else if (type === 2) { - var j, n, literalCodes, distCodes, lenCodes; - var ll = new Array(288 + 32); // "static" just to preserve stack - - // Dynamic Huffman tables - - literalCodes = 257 + this.readBits(5); - distCodes = 1 + this.readBits(5); - lenCodes = 4 + this.readBits(4); - for (j = 0; j < 19; j++) { - ll[j] = 0; - } - - // Get the decode tree code lengths - - for (j = 0; j < lenCodes; j++) { - ll[GZip.border[j]] = this.readBits(3); - } - len = this.distanceTree.length; - for (i = 0; i < len; i++) this.distanceTree[i] = new GZip.HufNode(); - if (this.CreateTree(this.distanceTree, 19, ll, 0)) { - this.flushBuffer(); - return 1; - } - // if (this.debug) { - // document.write("
distanceTree"); - // for(var a=0;a"+this.distanceTree[a].b0+" "+this.distanceTree[a].b1+" "+this.distanceTree[a].jump+" "+this.distanceTree[a].jumppos); - // } - // } - - //read in literal and distance code lengths - n = literalCodes + distCodes; - i = 0; - var z = -1; - // if (this.debug) document.write("
n="+n+" bits: "+this.bits+"
"); - while (i < n) { - z++; - j = this.DecodeValue(this.distanceTree); - // if (this.debug) document.write("
"+z+" i:"+i+" decode: "+j+" bits "+this.bits+"
"); - if (j < 16) { // length of code in bits (0..15) - ll[i++] = j; - } else if (j === 16) { // repeat last length 3 to 6 times - var l; - j = 3 + this.readBits(2); - if (i + j > n) { - this.flushBuffer(); - return 1; - } - l = i ? ll[i - 1] : 0; - while (j--) { - ll[i++] = l; - } - } else { - if (j === 17) { // 3 to 10 zero length codes - j = 3 + this.readBits(3); - } else { // j == 18: 11 to 138 zero length codes - j = 11 + this.readBits(7); - } - if (i + j > n) { - this.flushBuffer(); - return 1; - } - while (j--) { - ll[i++] = 0; - } - } - } // while - - // Can overwrite tree decode tree as it is not used anymore - len = this.literalTree.length; - for (i = 0; i < len; i++) - this.literalTree[i] = new GZip.HufNode(); - if (this.CreateTree(this.literalTree, literalCodes, ll, 0)) { - this.flushBuffer(); - return 1; - } - len = this.literalTree.length; - for (i = 0; i < len; i++) this.distanceTree[i] = new GZip.HufNode(); - var ll2 = new Array(); - for (i = literalCodes; i < ll.length; i++) ll2[i - literalCodes] = ll[i]; - if (this.CreateTree(this.distanceTree, distCodes, ll2, 0)) { - this.flushBuffer(); - return 1; - } - // if (this.debug) document.write("
literalTree"); - while (1) { - j = this.DecodeValue(this.literalTree); - if (j >= 256) { // In C64: if carry set - var len, dist; - j -= 256; - if (j === 0) { - // EOF - break; - } - j--; - len = this.readBits(GZip.cplext[j]) + GZip.cplens[j]; - - j = this.DecodeValue(this.distanceTree); - if (GZip.cpdext[j] > 8) { - dist = this.readBits(8); - dist |= (this.readBits(GZip.cpdext[j] - 8) << 8); - } else { - dist = this.readBits(GZip.cpdext[j]); - } - dist += GZip.cpdist[j]; - while (len--) { - var c = this.buf32k[(this.bIdx - dist) & 0x7fff]; - this.addBuffer(c); - } - } else { - this.addBuffer(j); - } - } // while - } - } while (!last); - this.flushBuffer(); - - this.byteAlign(); - return 0; -}; - -GZip.prototype.unzipFile = function (name) { - var i; - this.gunzip(); - for (i = 0; i < this.unzipped.length; i++) { - if (this.unzipped[i][1] === name) { - return this.unzipped[i][0]; - } - } -}; - -GZip.prototype.nextFile = function () { - // if (this.debug) alert("NEXTFILE"); - - this.outputArr = []; - this.modeZIP = false; - - var tmp = []; - tmp[0] = this.readByte(); - tmp[1] = this.readByte(); - // if (this.debug) alert("type: "+tmp[0]+" "+tmp[1]); - - if (tmp[0] === 0x78 && tmp[1] === 0xda) { //GZIP - // if (this.debug) alert("GEONExT-GZIP"); - this.DeflateLoop(); - // if (this.debug) alert(this.outputArr.join('')); - this.unzipped[this.files] = [this.outputArr.join(''), "geonext.gxt"]; - this.files++; - } - if (tmp[0] === 0x1f && tmp[1] === 0x8b) { //GZIP - // if (this.debug) alert("GZIP"); - this.skipdir(); - // if (this.debug) alert(this.outputArr.join('')); - this.unzipped[this.files] = [this.outputArr.join(''), "file"]; - this.files++; - } - if (tmp[0] === 0x50 && tmp[1] === 0x4b) { //ZIP - this.modeZIP = true; - tmp[2] = this.readByte(); - tmp[3] = this.readByte(); - if (tmp[2] === 0x03 && tmp[3] === 0x04) { - //MODE_ZIP - tmp[0] = this.readByte(); - tmp[1] = this.readByte(); - // if (this.debug) alert("ZIP-Version: "+tmp[1]+" "+tmp[0]/10+"."+tmp[0]%10); - - this.gpflags = this.readByte(); - this.gpflags |= (this.readByte() << 8); - // if (this.debug) alert("gpflags: "+this.gpflags); - - var method = this.readByte(); - method |= (this.readByte() << 8); - // if (this.debug) alert("method: "+method); - - this.readByte(); - this.readByte(); - this.readByte(); - this.readByte(); - -// var crc = this.readByte(); -// crc |= (this.readByte()<<8); -// crc |= (this.readByte()<<16); -// crc |= (this.readByte()<<24); - - var compSize = this.readByte(); - compSize |= (this.readByte() << 8); - compSize |= (this.readByte() << 16); - compSize |= (this.readByte() << 24); - - var size = this.readByte(); - size |= (this.readByte() << 8); - size |= (this.readByte() << 16); - size |= (this.readByte() << 24); - - // if (this.debug) alert("local CRC: "+crc+"\nlocal Size: "+size+"\nlocal CompSize: "+compSize); - - var filelen = this.readByte(); - filelen |= (this.readByte() << 8); - - var extralen = this.readByte(); - extralen |= (this.readByte() << 8); - - // if (this.debug) alert("filelen "+filelen); - i = 0; - this.nameBuf = []; - while (filelen--) { - var c = this.readByte(); - if (c === "/" | c === ":") { - i = 0; - } else if (i < GZip.NAMEMAX - 1) { - this.nameBuf[i++] = String.fromCharCode(c); - } - } - // if (this.debug) alert("nameBuf: "+this.nameBuf); - - if (!this.fileout) this.fileout = this.nameBuf; - - var i = 0; - while (i < extralen) { - c = this.readByte(); - i++; - } - - // if (size = 0 && this.fileOut.charAt(this.fileout.length-1)=="/"){ - // //skipdir - // // if (this.debug) alert("skipdir"); - // } - if (method === 8) { - this.DeflateLoop(); - // if (this.debug) alert(this.outputArr.join('')); - this.unzipped[this.files] = [this.outputArr.join(''), this.nameBuf.join('')]; - this.files++; - } - this.skipdir(); - } - } -}; - -GZip.prototype.skipdir = function () { - var tmp = []; - var compSize, size, os, i, c; - - if ((this.gpflags & 8)) { - tmp[0] = this.readByte(); - tmp[1] = this.readByte(); - tmp[2] = this.readByte(); - tmp[3] = this.readByte(); - -// if (tmp[0] == 0x50 && tmp[1] == 0x4b && tmp[2] == 0x07 && tmp[3] == 0x08) { -// crc = this.readByte(); -// crc |= (this.readByte()<<8); -// crc |= (this.readByte()<<16); -// crc |= (this.readByte()<<24); -// } else { -// crc = tmp[0] | (tmp[1]<<8) | (tmp[2]<<16) | (tmp[3]<<24); -// } - - compSize = this.readByte(); - compSize |= (this.readByte() << 8); - compSize |= (this.readByte() << 16); - compSize |= (this.readByte() << 24); - - size = this.readByte(); - size |= (this.readByte() << 8); - size |= (this.readByte() << 16); - size |= (this.readByte() << 24); - } - - if (this.modeZIP) this.nextFile(); - - tmp[0] = this.readByte(); - if (tmp[0] !== 8) { - // if (this.debug) alert("Unknown compression method!"); - return 0; - } - - this.gpflags = this.readByte(); - // if (this.debug && (this.gpflags & ~(0x1f))) alert("Unknown flags set!"); - - this.readByte(); - this.readByte(); - this.readByte(); - this.readByte(); - - this.readByte(); - os = this.readByte(); - - if ((this.gpflags & 4)) { - tmp[0] = this.readByte(); - tmp[2] = this.readByte(); - this.len = tmp[0] + 256 * tmp[1]; - // if (this.debug) alert("Extra field size: "+this.len); - for (i = 0; i < this.len; i++) - this.readByte(); - } - - if ((this.gpflags & 8)) { - i = 0; - this.nameBuf = []; - while (c = this.readByte()) { - if (c === "7" || c === ":") - i = 0; - if (i < GZip.NAMEMAX - 1) - this.nameBuf[i++] = c; - } - //this.nameBuf[i] = "\0"; - // if (this.debug) alert("original file name: "+this.nameBuf); - } - - if ((this.gpflags & 16)) { - while (c = this.readByte()) { // FIXME: looks like they read to the end of the stream, should be doable more efficiently - //FILE COMMENT - } - } - - if ((this.gpflags & 2)) { - this.readByte(); - this.readByte(); - } - - this.DeflateLoop(); - -// crc = this.readByte(); -// crc |= (this.readByte()<<8); -// crc |= (this.readByte()<<16); -// crc |= (this.readByte()<<24); - - size = this.readByte(); - size |= (this.readByte() << 8); - size |= (this.readByte() << 16); - size |= (this.readByte() << 24); - - if (this.modeZIP) this.nextFile(); -}; - -module.exports = GZip; diff --git a/cocos/compression/zlib.min.js b/cocos/compression/zlib.min.js deleted file mode 100644 index 1c197fb41e..0000000000 --- a/cocos/compression/zlib.min.js +++ /dev/null @@ -1,55 +0,0 @@ -/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */ -(function() {'use strict';function i(a){throw a;}var r=void 0,v=!0,aa=this;function y(a,c){var b=a.split("."),e=aa;!(b[0]in e)&&e.execScript&&e.execScript("var "+b[0]);for(var f;b.length&&(f=b.shift());)!b.length&&c!==r?e[f]=c:e=e[f]?e[f]:e[f]={}};var H="undefined"!==typeof Uint8Array&&"undefined"!==typeof Uint16Array&&"undefined"!==typeof Uint32Array;function ba(a){if("string"===typeof a){var c=a.split(""),b,e;b=0;for(e=c.length;b>>0;a=c}for(var f=1,d=0,g=a.length,h,m=0;0>>0};function J(a,c){this.index="number"===typeof c?c:0;this.i=0;this.buffer=a instanceof(H?Uint8Array:Array)?a:new (H?Uint8Array:Array)(32768);2*this.buffer.length<=this.index&&i(Error("invalid index"));this.buffer.length<=this.index&&this.f()}J.prototype.f=function(){var a=this.buffer,c,b=a.length,e=new (H?Uint8Array:Array)(b<<1);if(H)e.set(a);else for(c=0;c>>8&255]<<16|N[a>>>16&255]<<8|N[a>>>24&255])>>32-c:N[a]>>8-c);if(8>c+d)g=g<>c-h-1&1,8===++d&&(d=0,e[f++]=N[g],g=0,f===e.length&&(e=this.f()));e[f]=g;this.buffer=e;this.i=d;this.index=f};J.prototype.finish=function(){var a=this.buffer,c=this.index,b;0ha;++ha){for(var R=ha,ia=R,ja=7,R=R>>>1;R;R>>>=1)ia<<=1,ia|=R&1,--ja;ca[ha]=(ia<>>0}var N=ca;var ka=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759, -2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977, -2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755, -2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956, -3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270, -936918E3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];H&&new Uint32Array(ka);function la(a){this.buffer=new (H?Uint16Array:Array)(2*a);this.length=0}la.prototype.getParent=function(a){return 2*((a-2)/4|0)};la.prototype.push=function(a,c){var b,e,f=this.buffer,d;b=this.length;f[this.length++]=c;for(f[this.length++]=a;0f[e])d=f[b],f[b]=f[e],f[e]=d,d=f[b+1],f[b+1]=f[e+1],f[e+1]=d,b=e;else break;return this.length}; -la.prototype.pop=function(){var a,c,b=this.buffer,e,f,d;c=b[0];a=b[1];this.length-=2;b[0]=b[this.length];b[1]=b[this.length+1];for(d=0;;){f=2*d+2;if(f>=this.length)break;f+2b[f]&&(f+=2);if(b[f]>b[d])e=b[d],b[d]=b[f],b[f]=e,e=b[d+1],b[d+1]=b[f+1],b[f+1]=e;else break;d=f}return{index:a,value:c,length:this.length}};function S(a){var c=a.length,b=0,e=Number.POSITIVE_INFINITY,f,d,g,h,m,j,s,n,l;for(n=0;nb&&(b=a[n]),a[n]>=1;for(l=j;lT;T++)switch(v){case 143>=T:ra.push([T+48,8]);break;case 255>=T:ra.push([T-144+400,9]);break;case 279>=T:ra.push([T-256+0,7]);break;case 287>=T:ra.push([T-280+192,8]);break;default:i("invalid literal: "+T)} -ma.prototype.n=function(){var a,c,b,e,f=this.input;switch(this.h){case 0:b=0;for(e=f.length;b>>8&255;l[q++]=j&255;l[q++]=j>>>8&255;if(H)l.set(d,q),q+=d.length,l=l.subarray(0,q);else{s=0;for(n=d.length;sw)for(;0w?w:138,G>w-3&&G=G?(L[I++]=17,L[I++]=G-3,P[17]++):(L[I++]=18,L[I++]=G-11,P[18]++),w-=G;else if(L[I++]=M[u],P[M[u]]++,w--,3>w)for(;0w?w:6,G>w-3&&GF;F++)va[F]=na[da[F]];for(C=19;4=a:return[265,a-11,1];case 14>=a:return[266,a-13,1];case 16>=a:return[267,a-15,1];case 18>=a:return[268,a-17,1];case 22>=a:return[269,a-19,2];case 26>=a:return[270,a-23,2];case 30>=a:return[271,a-27,2];case 34>=a:return[272,a- -31,2];case 42>=a:return[273,a-35,3];case 50>=a:return[274,a-43,3];case 58>=a:return[275,a-51,3];case 66>=a:return[276,a-59,3];case 82>=a:return[277,a-67,4];case 98>=a:return[278,a-83,4];case 114>=a:return[279,a-99,4];case 130>=a:return[280,a-115,4];case 162>=a:return[281,a-131,5];case 194>=a:return[282,a-163,5];case 226>=a:return[283,a-195,5];case 257>=a:return[284,a-227,5];case 258===a:return[285,a-258,0];default:i("invalid length: "+a)}}var Aa=[],za,Ba; -for(za=3;258>=za;za++)Ba=xa(),Aa[za]=Ba[2]<<24|Ba[1]<<16|Ba[0];var Ca=H?new Uint32Array(Aa):Aa; -function sa(a,c){function b(a,c){var b=a.G,d=[],e=0,f;f=Ca[a.length];d[e++]=f&65535;d[e++]=f>>16&255;d[e++]=f>>24;var g;switch(v){case 1===b:g=[0,b-1,0];break;case 2===b:g=[1,b-2,0];break;case 3===b:g=[2,b-3,0];break;case 4===b:g=[3,b-4,0];break;case 6>=b:g=[4,b-5,1];break;case 8>=b:g=[5,b-7,1];break;case 12>=b:g=[6,b-9,2];break;case 16>=b:g=[7,b-13,2];break;case 24>=b:g=[8,b-17,3];break;case 32>=b:g=[9,b-25,3];break;case 48>=b:g=[10,b-33,4];break;case 64>=b:g=[11,b-49,4];break;case 96>=b:g=[12,b- -65,5];break;case 128>=b:g=[13,b-97,5];break;case 192>=b:g=[14,b-129,6];break;case 256>=b:g=[15,b-193,6];break;case 384>=b:g=[16,b-257,7];break;case 512>=b:g=[17,b-385,7];break;case 768>=b:g=[18,b-513,8];break;case 1024>=b:g=[19,b-769,8];break;case 1536>=b:g=[20,b-1025,9];break;case 2048>=b:g=[21,b-1537,9];break;case 3072>=b:g=[22,b-2049,10];break;case 4096>=b:g=[23,b-3073,10];break;case 6144>=b:g=[24,b-4097,11];break;case 8192>=b:g=[25,b-6145,11];break;case 12288>=b:g=[26,b-8193,12];break;case 16384>= -b:g=[27,b-12289,12];break;case 24576>=b:g=[28,b-16385,13];break;case 32768>=b:g=[29,b-24577,13];break;default:i("invalid distance")}f=g;d[e++]=f[0];d[e++]=f[1];d[e++]=f[2];var h,j;h=0;for(j=d.length;h=d;)t[d++]=0;for(d=0;29>=d;)z[d++]=0}t[256]=1;e=0;for(f=c.length;e=f){n&&b(n,-1);d=0;for(g=f-e;dp&&e+pk&&(B=x,k=p);if(258===p)break}s=new wa(k,e-B);n?n.length2*l[k-1]+q[k]&&(l[k]=2*l[k-1]+q[k]),t[k]=Array(l[k]),z[k]=Array(l[k]);for(B=0;Bh[B]?(t[k][p]=D,z[k][p]=n,C+=2): -(t[k][p]=h[B],z[k][p]=B,++B);K[k]=0;1===q[k]&&b(k)}m=E;j=0;for(s=g.length;j1<f&&i("undercommitted");d=0;for(g=a.length;d>>=1}return c};function Da(a,c){this.input=a;this.a=new (H?Uint8Array:Array)(32768);this.h=U.j;var b={},e;if((c||!(c={}))&&"number"===typeof c.compressionType)this.h=c.compressionType;for(e in c)b[e]=c[e];b.outputBuffer=this.a;this.z=new ma(this.input,b)}var U=qa; -Da.prototype.n=function(){var a,c,b,e,f,d,g,h=0;g=this.a;a=Ea;switch(a){case Ea:c=Math.LOG2E*Math.log(32768)-8;break;default:i(Error("invalid compression method"))}b=c<<4|a;g[h++]=b;switch(a){case Ea:switch(this.h){case U.NONE:f=0;break;case U.r:f=1;break;case U.j:f=2;break;default:i(Error("unsupported compression type"))}break;default:i(Error("invalid compression method"))}e=f<<6|0;g[h++]=e|31-(256*b+e)%31;d=ba(this.input);this.z.b=h;g=this.z.n();h=g.length;H&&(g=new Uint8Array(g.buffer),g.length<= -h+4&&(this.a=new Uint8Array(g.length+4),this.a.set(g),g=this.a),g=g.subarray(0,h+4));g[h++]=d>>24&255;g[h++]=d>>16&255;g[h++]=d>>8&255;g[h++]=d&255;return g};y("Zlib.Deflate",Da);y("Zlib.Deflate.compress",function(a,c){return(new Da(a,c)).n()});y("Zlib.Deflate.CompressionType",U);y("Zlib.Deflate.CompressionType.NONE",U.NONE);y("Zlib.Deflate.CompressionType.FIXED",U.r);y("Zlib.Deflate.CompressionType.DYNAMIC",U.j);function V(a,c){this.k=[];this.l=32768;this.e=this.g=this.c=this.q=0;this.input=H?new Uint8Array(a):a;this.s=!1;this.m=Fa;this.B=!1;if(c||!(c={}))c.index&&(this.c=c.index),c.bufferSize&&(this.l=c.bufferSize),c.bufferType&&(this.m=c.bufferType),c.resize&&(this.B=c.resize);switch(this.m){case Ga:this.b=32768;this.a=new (H?Uint8Array:Array)(32768+this.l+258);break;case Fa:this.b=0;this.a=new (H?Uint8Array:Array)(this.l);this.f=this.J;this.t=this.H;this.o=this.I;break;default:i(Error("invalid inflate mode"))}} -var Ga=0,Fa=1,Ha={D:Ga,C:Fa}; -V.prototype.p=function(){for(;!this.s;){var a=X(this,3);a&1&&(this.s=v);a>>>=1;switch(a){case 0:var c=this.input,b=this.c,e=this.a,f=this.b,d=r,g=r,h=r,m=e.length,j=r;this.e=this.g=0;d=c[b++];d===r&&i(Error("invalid uncompressed block header: LEN (first byte)"));g=d;d=c[b++];d===r&&i(Error("invalid uncompressed block header: LEN (second byte)"));g|=d<<8;d=c[b++];d===r&&i(Error("invalid uncompressed block header: NLEN (first byte)"));h=d;d=c[b++];d===r&&i(Error("invalid uncompressed block header: NLEN (second byte)"));h|= -d<<8;g===~h&&i(Error("invalid uncompressed block header: length verify"));b+g>c.length&&i(Error("input buffer is broken"));switch(this.m){case Ga:for(;f+g>e.length;){j=m-f;g-=j;if(H)e.set(c.subarray(b,b+j),f),f+=j,b+=j;else for(;j--;)e[f++]=c[b++];this.b=f;e=this.f();f=this.b}break;case Fa:for(;f+g>e.length;)e=this.f({v:2});break;default:i(Error("invalid inflate mode"))}if(H)e.set(c.subarray(b,b+g),f),f+=g,b+=g;else for(;g--;)e[f++]=c[b++];this.c=b;this.b=f;this.a=e;break;case 1:this.o(Ia,Ja);break; -case 2:Ka(this);break;default:i(Error("unknown BTYPE: "+a))}}return this.t()}; -var La=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Za=H?new Uint16Array(La):La,$a=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258],ab=H?new Uint16Array($a):$a,bb=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0],cb=H?new Uint8Array(bb):bb,db=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],eb=H?new Uint16Array(db):db,fb=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10, -10,11,11,12,12,13,13],gb=H?new Uint8Array(fb):fb,hb=new (H?Uint8Array:Array)(288),Y,ib;Y=0;for(ib=hb.length;Y=Y?8:255>=Y?9:279>=Y?7:8;var Ia=S(hb),jb=new (H?Uint8Array:Array)(30),kb,lb;kb=0;for(lb=jb.length;kb>>c;a.e=e-c;a.c=d;return g} -function mb(a,c){for(var b=a.g,e=a.e,f=a.input,d=a.c,g=c[0],h=c[1],m,j,s;e>>16;a.g=b>>s;a.e=e-s;a.c=d;return j&65535} -function Ka(a){function c(a,b,c){var d,e,f,g;for(g=0;gd)e>=f&&(this.b=e,b=this.f(),e=this.b),b[e++]=d;else{g=d-257;m=ab[g];0=f&&(this.b=e,b=this.f(),e=this.b);for(;m--;)b[e]=b[e++-h]}for(;8<=this.e;)this.e-=8,this.c--;this.b=e}; -V.prototype.I=function(a,c){var b=this.a,e=this.b;this.u=a;for(var f=b.length,d,g,h,m;256!==(d=mb(this,a));)if(256>d)e>=f&&(b=this.f(),f=b.length),b[e++]=d;else{g=d-257;m=ab[g];0f&&(b=this.f(),f=b.length);for(;m--;)b[e]=b[e++-h]}for(;8<=this.e;)this.e-=8,this.c--;this.b=e}; -V.prototype.f=function(){var a=new (H?Uint8Array:Array)(this.b-32768),c=this.b-32768,b,e,f=this.a;if(H)a.set(f.subarray(32768,a.length));else{b=0;for(e=a.length;bb;++b)f[b]=f[c+b];this.b=32768;return f}; -V.prototype.J=function(a){var c,b=this.input.length/this.c+1|0,e,f,d,g=this.input,h=this.a;a&&("number"===typeof a.v&&(b=a.v),"number"===typeof a.F&&(b+=a.F));2>b?(e=(g.length-this.c)/this.u[2],d=258*(e/2)|0,f=dc&&(this.a.length=c),a=this.a);return this.buffer=a};function nb(a,c){var b,e;this.input=a;this.c=0;if(c||!(c={}))c.index&&(this.c=c.index),c.verify&&(this.M=c.verify);b=a[this.c++];e=a[this.c++];switch(b&15){case Ea:this.method=Ea;break;default:i(Error("unsupported compression method"))}0!==((b<<8)+e)%31&&i(Error("invalid fcheck flag:"+((b<<8)+e)%31));e&32&&i(Error("fdict flag is not supported"));this.A=new V(a,{index:this.c,bufferSize:c.bufferSize,bufferType:c.bufferType,resize:c.resize})} -nb.prototype.p=function(){var a=this.input,c,b;c=this.A.p();this.c=this.A.c;this.M&&(b=(a[this.c++]<<24|a[this.c++]<<16|a[this.c++]<<8|a[this.c++])>>>0,b!==ba(c)&&i(Error("invalid adler-32 checksum")));return c};y("Zlib.Inflate",nb);y("Zlib.Inflate.BufferType",Ha);Ha.ADAPTIVE=Ha.C;Ha.BLOCK=Ha.D;y("Zlib.Inflate.prototype.decompress",nb.prototype.p);var ob=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];H&&new Uint16Array(ob);var pb=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258];H&&new Uint16Array(pb);var qb=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0];H&&new Uint8Array(qb);var rb=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577];H&&new Uint16Array(rb); -var sb=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];H&&new Uint8Array(sb);var tb=new (H?Uint8Array:Array)(288),Z,ub;Z=0;for(ub=tb.length;Z=Z?8:255>=Z?9:279>=Z?7:8;S(tb);var vb=new (H?Uint8Array:Array)(30),wb,xb;wb=0;for(xb=vb.length;wb 0) { device.copyBuffersToTexture(texBuffers, gfxTex!, texBufferRegions); diff --git a/cocos/3d/framework/batched-skinning-model-component.ts b/cocos/core/3d/framework/batched-skinning-model-component.ts similarity index 97% rename from cocos/3d/framework/batched-skinning-model-component.ts rename to cocos/core/3d/framework/batched-skinning-model-component.ts index 9dc39cf16f..4c96fa75b3 100644 --- a/cocos/3d/framework/batched-skinning-model-component.ts +++ b/cocos/core/3d/framework/batched-skinning-model-component.ts @@ -28,18 +28,19 @@ import { Filter, PixelFormat } from '../../assets/asset-enum'; import { Texture2D } from '../../assets/texture-2d'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; -import { CCString } from '../../core/data/utils/attribute'; -import { Mat4, Vec2 } from '../../core/math'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../data/class-decorator'; +import { CCString } from '../../data/utils/attribute'; +import { Mat4, Vec2 } from '../../math'; import { GFXAttributeName, GFXBufferTextureCopy, GFXFormatInfos } from '../../gfx/define'; import { GFXFormat, GFXType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { IGFXAttribute } from '../../gfx/input-assembler'; -import { Material } from '../assets/material'; -import { IMeshStruct, Mesh } from '../assets/mesh'; -import { Skeleton } from '../assets/skeleton'; +import { Material } from '../../assets/material'; +import { IMeshStruct, Mesh } from '../../assets/mesh'; +import { Skeleton } from '../../assets/skeleton'; import { mapBuffer } from '../misc/utils'; import { SkinningModelComponent } from './skinning-model-component'; +import { director } from '../../director'; const repeat = (n: number) => n - Math.floor(n); const batch_id: IGFXAttribute = { name: GFXAttributeName.ATTR_BATCH_ID, format: GFXFormat.R32F, isNormalized: false }; @@ -400,7 +401,7 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { } } const gfxTex = target.getGFXTexture()!; - const device: GFXDevice = cc.director.root.device; + const device: GFXDevice = director.root!.device; if (texBuffers.length > 0) { device.copyBuffersToTexture(texBuffers, gfxTex, texBufferRegions); } if (texImages.length > 0) { device.copyTexImagesToTexture(texImages, gfxTex, texImageRegions); } } diff --git a/cocos/3d/framework/camera-component.ts b/cocos/core/3d/framework/camera-component.ts similarity index 96% rename from cocos/3d/framework/camera-component.ts rename to cocos/core/3d/framework/camera-component.ts index ce89affebc..7adaf02bef 100644 --- a/cocos/3d/framework/camera-component.ts +++ b/cocos/core/3d/framework/camera-component.ts @@ -27,17 +27,18 @@ * @category component/camera */ -import { ray } from '../../3d/geom-utils'; +import { ray } from '../../geom-utils'; import { Component } from '../../components/component'; -import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; -import { Color, Rect, toRadian, Vec3 } from '../../core/math'; -import { Enum } from '../../core/value-types'; +import { ccclass, executeInEditMode, menu, property } from '../../data/class-decorator'; +import { Color, Rect, toRadian, Vec3 } from '../../math'; +import { Enum } from '../../value-types'; import { GFXClearFlag } from '../../gfx/define'; import { Camera } from '../../renderer'; import { Scene } from '../../scene-graph'; import { RenderTexture } from '../../assets'; import { GFXWindow } from '../../gfx/window'; import { CameraVisFlags } from '../../renderer/scene/camera'; +import { director, Director } from '../../director'; /** * @en @@ -331,7 +332,7 @@ export class CameraComponent extends Component { } public onLoad () { - cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneChanged, this); + director.on(Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneChanged, this); } public onEnable () { @@ -381,7 +382,7 @@ export class CameraComponent extends Component { name: this.node.name, node: this.node, projection: this._projection, - window: cc.director.root.tempWindow, + window: director.root && director.root.tempWindow, priority: this._priority, }); diff --git a/cocos/3d/framework/directional-light-component.ts b/cocos/core/3d/framework/directional-light-component.ts similarity index 98% rename from cocos/3d/framework/directional-light-component.ts rename to cocos/core/3d/framework/directional-light-component.ts index 62f0ad91a8..ea5e57f826 100644 --- a/cocos/3d/framework/directional-light-component.ts +++ b/cocos/core/3d/framework/directional-light-component.ts @@ -27,7 +27,7 @@ * @category component/light */ -import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; +import { ccclass, executeInEditMode, menu, property } from '../../data/class-decorator'; import { DirectionalLight } from '../../renderer/scene/directional-light'; import { LightType } from '../../renderer/scene/light'; import { RenderScene } from '../../renderer/scene/render-scene'; diff --git a/cocos/3d/framework/editor-camera-component.ts b/cocos/core/3d/framework/editor-camera-component.ts similarity index 89% rename from cocos/3d/framework/editor-camera-component.ts rename to cocos/core/3d/framework/editor-camera-component.ts index 3612fcaaeb..1dbd3580cb 100644 --- a/cocos/3d/framework/editor-camera-component.ts +++ b/cocos/core/3d/framework/editor-camera-component.ts @@ -2,11 +2,12 @@ * @hidden */ -import { ccclass } from '../../core/data/class-decorator'; -import { Color, toRadian } from '../../core/math'; +import { ccclass } from '../../data/class-decorator'; +import { toRadian } from '../../math'; import { Camera } from '../../renderer'; import { CameraComponent } from './camera-component'; import { CameraVisFlags } from '../../renderer/scene/camera'; +import { director } from '../../director'; @ccclass('cc.EditorCameraComponent') export class EditorCameraComponent extends CameraComponent { @@ -116,7 +117,7 @@ export class EditorCameraComponent extends CameraComponent { public onDestroy () { super.onDestroy(); if (this._uiEditorCamera) { - cc.director.root.ui.renderScene.destroyCamera(this._uiEditorCamera); + director.root!.ui.renderScene.destroyCamera(this._uiEditorCamera); this._uiEditorCamera = null; } } @@ -127,14 +128,14 @@ export class EditorCameraComponent extends CameraComponent { if (this._camera !== priorCamera && this._camera) { if (this._uiEditorCamera) { - cc.director.root.ui.renderScene.destroyCamera(this._uiEditorCamera); + director.root!.ui.renderScene.destroyCamera(this._uiEditorCamera); this._uiEditorCamera = null; } - this._uiEditorCamera = cc.director.root.ui.renderScene.createCamera({ + this._uiEditorCamera = director.root!.ui.renderScene.createCamera({ name: 'Editor UICamera', node: this._camera.node, projection: this._projection, - window: cc.director.root.mainWindow, + window: director.root!.mainWindow, priority: this._priority, isUI: true, flows: ['UIFlow'], diff --git a/cocos/3d/framework/index.ts b/cocos/core/3d/framework/index.ts similarity index 85% rename from cocos/3d/framework/index.ts rename to cocos/core/3d/framework/index.ts index e7c4bb2539..6b3b544467 100644 --- a/cocos/3d/framework/index.ts +++ b/cocos/core/3d/framework/index.ts @@ -35,10 +35,6 @@ import { DirectionalLightComponent } from './directional-light-component'; import { EditorCameraComponent } from './editor-camera-component'; import { LightComponent } from './light-component'; import { ModelComponent } from './model-component'; -import { BillboardComponent } from './particle/billboard-component'; -import { LineComponent } from './particle/line-component'; -import { ParticleSystemComponent } from './particle/particle-system-component'; -import { ParticleUtils } from './particle/particle-utils'; import { RenderableComponent } from './renderable-component'; import { SkinningModelComponent } from './skinning-model-component'; import { SphereLightComponent } from './sphere-light-component'; @@ -54,9 +50,6 @@ export { BatchedSkinningModelComponent, SkinningModelUnit, - ParticleSystemComponent, - BillboardComponent, - LineComponent, RenderableComponent, }; @@ -76,9 +69,3 @@ cc.LightComponent = LightComponent; cc.DirectionalLightComponent = DirectionalLightComponent; cc.SphereLightComponent = SphereLightComponent; cc.SpotLightComponent = SpotLightComponent; - -cc.ParticleSystemComponent = ParticleSystemComponent; -cc.BillboardComponent = BillboardComponent; -cc.LineComponent = LineComponent; - -cc.ParticleUtils = ParticleUtils; diff --git a/cocos/3d/framework/light-component.ts b/cocos/core/3d/framework/light-component.ts similarity index 96% rename from cocos/3d/framework/light-component.ts rename to cocos/core/3d/framework/light-component.ts index a84e59423e..a0a21444b5 100644 --- a/cocos/3d/framework/light-component.ts +++ b/cocos/core/3d/framework/light-component.ts @@ -28,9 +28,9 @@ */ import { Component } from '../../components/component'; -import { ccclass, property } from '../../core/data/class-decorator'; -import { Color } from '../../core/math'; -import { Enum } from '../../core/value-types'; +import { ccclass, property } from '../../data/class-decorator'; +import { Color } from '../../math'; +import { Enum } from '../../value-types'; import { Light, LightType } from '../../renderer/scene/light'; import { RenderScene } from '../../renderer/scene/render-scene'; diff --git a/cocos/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts similarity index 97% rename from cocos/3d/framework/model-component.ts rename to cocos/core/3d/framework/model-component.ts index e7d691a2af..5409ee429c 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -27,13 +27,12 @@ * @category model */ -import { builtinResMgr } from '../../3d/builtin'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; -import { Enum } from '../../core/value-types'; +import { builtinResMgr } from '../builtin'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../data/class-decorator'; +import { Enum } from '../../value-types'; import { Model } from '../../renderer/scene/model'; import { TransformDirtyBit } from '../../scene-graph/node-enum'; -import { Material } from '../assets/material'; -import { Mesh } from '../assets/mesh'; +import { Material, Mesh } from '../../assets'; import { RenderableComponent } from './renderable-component'; /** diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/core/3d/framework/renderable-component.ts similarity index 94% rename from cocos/3d/framework/renderable-component.ts rename to cocos/core/3d/framework/renderable-component.ts index 969d062fec..e4a0c8626b 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/core/3d/framework/renderable-component.ts @@ -4,10 +4,9 @@ // @ts-check import { Component } from '../../components/component'; -import { _decorator } from '../../core/data/index'; -import { Model } from '../../renderer'; -import { VisibilityFlags } from '../../renderer/scene/model'; -import { Material } from '../assets/material'; +import { _decorator } from '../../data/index'; +import { Model, VisibilityFlags } from '../../renderer/scene/model'; +import { Material } from '../../assets/material'; const { ccclass, property } = _decorator; @ccclass('cc.RenderableComponent') diff --git a/cocos/3d/framework/skinning-model-component.ts b/cocos/core/3d/framework/skinning-model-component.ts similarity index 92% rename from cocos/3d/framework/skinning-model-component.ts rename to cocos/core/3d/framework/skinning-model-component.ts index f294d54742..409eaf2c7f 100644 --- a/cocos/3d/framework/skinning-model-component.ts +++ b/cocos/core/3d/framework/skinning-model-component.ts @@ -27,17 +27,18 @@ * @category model */ -import { SkeletalAnimationClip } from '../../animation/skeletal-animation-clip'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; -import { INode } from '../../core/utils/interfaces'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../data/class-decorator'; +import { INode } from '../../utils/interfaces'; import { GFXDevice } from '../../gfx/device'; +import { SkeletalAnimationClip } from '../../animation/skeletal-animation-clip'; import { selectJointsMediumType } from '../../renderer/models/joints-texture-utils'; import { SkinningModel } from '../../renderer/models/skinning-model'; import { Node } from '../../scene-graph/node'; -import { Material } from '../assets/material'; -import { Skeleton } from '../assets/skeleton'; +import { Material } from '../../assets/material'; +import { Skeleton } from '../../assets/skeleton'; import { builtinResMgr } from '../builtin'; import { ModelComponent } from './model-component'; +import { director } from '../../director'; /** * @en The Skinning Model Component @@ -97,7 +98,7 @@ export class SkinningModelComponent extends ModelComponent { } protected _onMaterialModified (index: number, material: Material | null) { - const device: GFXDevice = cc.director.root && cc.director.root.device; + const device: GFXDevice = director.root!.device; const type = selectJointsMediumType(device); const mat = this.getMaterial(index) || this._getBuiltinMaterial(); mat.recompileShaders({ CC_USE_SKINNING: type }); diff --git a/cocos/3d/framework/sphere-light-component.ts b/cocos/core/3d/framework/sphere-light-component.ts similarity index 99% rename from cocos/3d/framework/sphere-light-component.ts rename to cocos/core/3d/framework/sphere-light-component.ts index 8f702bd5f4..738f2f0f21 100644 --- a/cocos/3d/framework/sphere-light-component.ts +++ b/cocos/core/3d/framework/sphere-light-component.ts @@ -26,7 +26,7 @@ * @category component/light */ -import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; +import { ccclass, executeInEditMode, menu, property } from '../../data/class-decorator'; import { LightType, nt2lm } from '../../renderer/scene/light'; import { RenderScene } from '../../renderer/scene/render-scene'; import { SphereLight } from '../../renderer/scene/sphere-light'; diff --git a/cocos/3d/framework/spot-light-component.ts b/cocos/core/3d/framework/spot-light-component.ts similarity index 98% rename from cocos/3d/framework/spot-light-component.ts rename to cocos/core/3d/framework/spot-light-component.ts index 3055562e14..1377ec78b8 100644 --- a/cocos/3d/framework/spot-light-component.ts +++ b/cocos/core/3d/framework/spot-light-component.ts @@ -27,8 +27,8 @@ * @category component/light */ -import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; -import { toRadian } from '../../core/math'; +import { ccclass, executeInEditMode, menu, property } from '../../data/class-decorator'; +import { toRadian } from '../../math'; import { LightType, nt2lm } from '../../renderer/scene/light'; import { RenderScene } from '../../renderer/scene/render-scene'; import { SpotLight } from '../../renderer/scene/spot-light'; diff --git a/cocos/3d/index.ts b/cocos/core/3d/index.ts similarity index 90% rename from cocos/3d/index.ts rename to cocos/core/3d/index.ts index 55f5ce97cd..b559449a01 100644 --- a/cocos/3d/index.ts +++ b/cocos/core/3d/index.ts @@ -27,18 +27,11 @@ * @hidden */ -export * from './assets'; export * from './builtin'; export * from './framework'; -export * from './memop'; -import * as geometry from './geom-utils'; import * as utils from './misc/utils'; -export * from './ui'; export { utils, - geometry, }; - -cc.geometry = geometry; cc.utils = utils; diff --git a/cocos/3d/misc/buffer-blob.ts b/cocos/core/3d/misc/buffer-blob.ts similarity index 100% rename from cocos/3d/misc/buffer-blob.ts rename to cocos/core/3d/misc/buffer-blob.ts diff --git a/cocos/3d/misc/utils.ts b/cocos/core/3d/misc/utils.ts similarity index 98% rename from cocos/3d/misc/utils.ts rename to cocos/core/3d/misc/utils.ts index 2a7ede6957..4abcba173f 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/core/3d/misc/utils.ts @@ -1,13 +1,13 @@ import { GFXAttributeName, GFXFormat, GFXFormatInfos, GFXFormatType, GFXPrimitiveMode, IGFXFormatInfo } from '../../gfx/define'; export { find } from '../../scene-graph/find'; -import { Mat4, Vec3 } from '../../core/math'; -import { INode } from '../../core/utils/interfaces'; +import { Mat4, Vec3 } from '../../math'; +import { INode } from '../../utils/interfaces'; import { IGFXAttribute } from '../../gfx/input-assembler'; -import { IMeshStruct, IPrimitive, IVertexBundle, Mesh } from '../assets/mesh'; -import { Skeleton } from '../assets/skeleton'; +import { IMeshStruct, IPrimitive, IVertexBundle, Mesh } from '../../assets/mesh'; +import { Skeleton } from '../../assets/skeleton'; import { SkinningModelComponent } from '../framework'; -import { aabb } from '../geom-utils'; -import { IGeometry } from '../primitive/define'; +import { aabb } from '../../geom-utils'; +import { IGeometry } from '../../primitive/define'; import { BufferBlob } from './buffer-blob'; import { JointsAnimationInfo } from '../../renderer/models/skinning-model'; diff --git a/cocos/animation/animation-blend-state.ts b/cocos/core/animation/animation-blend-state.ts similarity index 98% rename from cocos/animation/animation-blend-state.ts rename to cocos/core/animation/animation-blend-state.ts index 7e6690b58e..68bc25e212 100644 --- a/cocos/animation/animation-blend-state.ts +++ b/cocos/core/animation/animation-blend-state.ts @@ -2,7 +2,7 @@ * @category animation */ -import { Node } from '../scene-graph'; +import { Node } from '../scene-graph/node'; import { CurveTarget } from './animation-curve'; // tslint:disable:interface-over-type-literal diff --git a/cocos/animation/animation-clip.ts b/cocos/core/animation/animation-clip.ts similarity index 97% rename from cocos/animation/animation-clip.ts rename to cocos/core/animation/animation-clip.ts index a9536d7564..3b28a3d227 100644 --- a/cocos/animation/animation-clip.ts +++ b/cocos/core/animation/animation-clip.ts @@ -4,15 +4,14 @@ */ import { Asset, SpriteFrame } from '../assets'; -import { ccclass, property } from '../core/data/class-decorator'; -import { errorID } from '../core/platform/CCDebug'; -import binarySearchEpsilon from '../core/utils/binary-search'; +import { ccclass, property } from '../data/class-decorator'; +import { errorID } from '../platform/debug'; +import binarySearchEpsilon from '../utils/binary-search'; import { AnimCurve, IPropertyCurveData, RatioSampler, CurveValueAdapter } from './animation-curve'; import { WrapMode as AnimationWrapMode } from './types'; -import { INode } from '../core/utils/interfaces'; -import { murmurhash2_32_gc } from '../core/utils/murmurhash2_gc'; +import { INode } from '../utils/interfaces'; +import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; import { TargetModifier, HierachyModifier, ComponentModifier, isCustomTargetModifier, PropertyModifier, isPropertyModifier } from './target-modifier'; -import { UniformCurveValueAdapter } from './curve-value-adapters'; export interface ITargetCurveData { modifiers: TargetModifier[]; diff --git a/cocos/animation/animation-component.ts b/cocos/core/animation/animation-component.ts similarity index 97% rename from cocos/animation/animation-component.ts rename to cocos/core/animation/animation-component.ts index 5ce65047eb..cdd0dd399f 100644 --- a/cocos/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -28,14 +28,14 @@ */ import { Component } from '../components/component'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../core/data/class-decorator'; -import { Event, EventTarget } from '../core/event'; -import { CallbacksInvoker, ICallbackTable } from '../core/event/callbacks-invoker'; -import { applyMixins, IEventTarget } from '../core/event/event-target-factory'; -import { warnID } from '../core/platform/CCDebug'; -import * as ArrayUtils from '../core/utils/array'; -import { createMap } from '../core/utils/js-typed'; -import { ccenum } from '../core/value-types/enum'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../data/class-decorator'; +import { Event, EventTarget } from '../event'; +import { CallbacksInvoker, ICallbackTable } from '../event/callbacks-invoker'; +import { applyMixins, IEventTarget } from '../event/event-target-factory'; +import { warnID } from '../platform/debug'; +import * as ArrayUtils from '../utils/array'; +import { createMap } from '../utils/js-typed'; +import { ccenum } from '../value-types/enum'; import { AnimationClip } from './animation-clip'; import { AnimationState } from './animation-state'; import { CrossFade } from './cross-fade'; diff --git a/cocos/animation/animation-curve.ts b/cocos/core/animation/animation-curve.ts similarity index 96% rename from cocos/animation/animation-curve.ts rename to cocos/core/animation/animation-curve.ts index f90eae5715..9b6abcae9f 100644 --- a/cocos/animation/animation-curve.ts +++ b/cocos/core/animation/animation-curve.ts @@ -2,17 +2,14 @@ * @category animation */ -import { ccclass, property } from '../core/data/class-decorator'; -import { binarySearchEpsilon as binarySearch } from '../core/data/utils/binary-search'; -import { errorID } from '../core/platform/CCDebug'; -import { lerp, Quat } from '../core/math'; -import { ValueType } from '../core/value-types'; -import { PropertyBlendState } from './animation-blend-state'; +import { ccclass } from '../data/class-decorator'; +import { binarySearchEpsilon as binarySearch } from '../data/utils/binary-search'; +import { errorID } from '../platform/debug'; +import { lerp, Quat } from '../math'; +import { ValueType } from '../value-types'; import { bezierByTime, BezierControlPoints } from './bezier'; -import * as blending from './blending'; import * as easing from './easing'; import { ILerpable, isLerpable } from './types'; -import { deserialize } from '../core'; /** * 表示曲线值,曲线值可以是任意类型,但必须符合插值方式的要求。 diff --git a/cocos/animation/animation-manager.ts b/cocos/core/animation/animation-manager.ts similarity index 80% rename from cocos/animation/animation-manager.ts rename to cocos/core/animation/animation-manager.ts index 89b1f12684..0861606412 100644 --- a/cocos/animation/animation-manager.ts +++ b/cocos/core/animation/animation-manager.ts @@ -2,26 +2,25 @@ * @category animation */ -import { ccclass } from '../core/data/class-decorator'; -import { errorID } from '../core/platform/CCDebug'; -import { MutableForwardIterator, remove } from '../core/utils/array'; +import { ccclass } from '../data/class-decorator'; +import { errorID } from '../platform/debug'; +import { MutableForwardIterator, remove } from '../utils/array'; import { Node } from '../scene-graph'; import { AnimationBlendState } from './animation-blend-state'; import { AnimationState } from './animation-state'; import { CrossFade } from './cross-fade'; +import { director, Director } from '../director'; +import { Scheduler } from '../scheduler'; +import System from '../components/system'; @ccclass -export class AnimationManager { +export class AnimationManager extends System { private _anims = new MutableForwardIterator([]); private _delayEvents: Array<{target: Node; func: string; args: any[]; }> = []; private _blendState: AnimationBlendState = new AnimationBlendState(); private _crossFades: CrossFade[] = []; - constructor () { - if (cc.director._scheduler) { - cc.director._scheduler.enableForTarget(this); - } - } + public static ID = 'animation'; public get blendState () { return this._blendState; @@ -89,4 +88,9 @@ export class AnimationManager { } } +director.on(Director.EVENT_INIT, function () { + let animationManager = new AnimationManager(); + director.registerSystem(AnimationManager.ID, animationManager, Scheduler.PRIORITY_SYSTEM); +}); + cc.AnimationManager = AnimationManager; diff --git a/cocos/animation/animation-state.ts b/cocos/core/animation/animation-state.ts similarity index 97% rename from cocos/animation/animation-state.ts rename to cocos/core/animation/animation-state.ts index cea6ca0599..099fd875e9 100644 --- a/cocos/animation/animation-state.ts +++ b/cocos/core/animation/animation-state.ts @@ -27,18 +27,17 @@ * @category animation */ -import { Component } from '../components'; -import { EventArgumentsOf, EventCallbackOf } from '../core/event/defines'; -import { Node } from '../scene-graph'; +import { EventArgumentsOf, EventCallbackOf } from '../event/defines'; +import { Node } from '../scene-graph/node'; import { AnimationBlendState, PropertyBlendState } from './animation-blend-state'; import { AnimationClip, IRuntimeCurve } from './animation-clip'; import { AnimCurve, RatioSampler, ICurveValueProxy } from './animation-curve'; import { Playable } from './playable'; import { WrapMode, WrapModeMask, WrappedInfo } from './types'; -import { INode } from '../core/utils/interfaces'; +import { INode } from '../utils/interfaces'; import { BlendFunction, additive3D, additiveQuat } from './blending'; -import { BoundTarget, TargetModifier } from './target-modifier'; -import { warn } from '../core/platform/CCDebug'; +import { BoundTarget } from './target-modifier'; +import { director } from '../director'; enum PropertySpecialization { NodePosition, @@ -415,7 +414,7 @@ export class AnimationState extends Playable { for (let i = 0, l = args.length; i < l; i++) { args[i] = restargs[i]; } - cc.director.getAnimationManager().pushDelayEvent(this, '_emit', args); + director.getAnimationManager().pushDelayEvent(this, '_emit', args); } public on (type: K, callback: EventCallbackOf, target?: any): void; @@ -679,26 +678,26 @@ export class AnimationState extends Playable { this.setTime(0); this._delayTime = this._delay; - cc.director.getAnimationManager().addAnimation(this); + director.getAnimationManager().addAnimation(this); this.emit('play', this); } protected onStop () { if (!this.isPaused) { - cc.director.getAnimationManager().removeAnimation(this); + director.getAnimationManager().removeAnimation(this); } this.emit('stop', this); } protected onResume () { - cc.director.getAnimationManager().addAnimation(this); + director.getAnimationManager().addAnimation(this); this.emit('resume', this); } protected onPause () { - cc.director.getAnimationManager().removeAnimation(this); + director.getAnimationManager().removeAnimation(this); this.emit('pause', this); } @@ -805,7 +804,7 @@ export class AnimationState extends Playable { lastIndex += direction; - cc.director.getAnimationManager().pushDelayEvent(this, '_fireEvent', [lastIndex]); + director.getAnimationManager().pushDelayEvent(this, '_fireEvent', [lastIndex]); } while (lastIndex !== eventIndex && lastIndex > -1 && lastIndex < length); } diff --git a/cocos/animation/bezier.ts b/cocos/core/animation/bezier.ts similarity index 100% rename from cocos/animation/bezier.ts rename to cocos/core/animation/bezier.ts diff --git a/cocos/animation/blending.ts b/cocos/core/animation/blending.ts similarity index 97% rename from cocos/animation/blending.ts rename to cocos/core/animation/blending.ts index d22eb2a6dd..049bd6ef63 100644 --- a/cocos/animation/blending.ts +++ b/cocos/core/animation/blending.ts @@ -2,7 +2,7 @@ * @category animation */ -import { Quat, Vec3 } from '../core/math'; +import { Quat, Vec3 } from '../math'; import { PropertyBlendState } from './animation-blend-state'; /** diff --git a/cocos/animation/cross-fade.ts b/cocos/core/animation/cross-fade.ts similarity index 92% rename from cocos/animation/cross-fade.ts rename to cocos/core/animation/cross-fade.ts index 6a9ba8cfb5..7e2d781e8e 100644 --- a/cocos/animation/cross-fade.ts +++ b/cocos/core/animation/cross-fade.ts @@ -1,10 +1,12 @@ /** * @category animation */ -import { clamp01 } from '../core/math/utils'; + +import { clamp01 } from '../math/utils'; import { AnimationState } from './animation-state'; import { Playable } from './playable'; -import { remove } from '../core/utils/array'; +import { remove } from '../utils/array'; +import { director } from '../director'; interface IManagedState { state: AnimationState | null; @@ -99,7 +101,7 @@ export class CrossFade extends Playable { protected onPlay () { super.onPlay(); - cc.director.getAnimationManager().addCrossFade(this); + director.getAnimationManager().addCrossFade(this); } /** @@ -107,7 +109,7 @@ export class CrossFade extends Playable { */ protected onPause () { super.onPause(); - cc.director.getAnimationManager().removeCrossFade(this); + director.getAnimationManager().removeCrossFade(this); for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) { const state = this._managedStates[iManagedState].state; if (state) { @@ -121,7 +123,7 @@ export class CrossFade extends Playable { */ protected onResume () { super.onResume(); - cc.director.getAnimationManager().addCrossFade(this); + director.getAnimationManager().addCrossFade(this); for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) { const state = this._managedStates[iManagedState].state; if (state) { @@ -135,7 +137,7 @@ export class CrossFade extends Playable { */ protected onStop () { super.onStop(); - cc.director.getAnimationManager().removeCrossFade(this); + director.getAnimationManager().removeCrossFade(this); this.clear(); } diff --git a/cocos/animation/cubic-spline-value.ts b/cocos/core/animation/cubic-spline-value.ts similarity index 97% rename from cocos/animation/cubic-spline-value.ts rename to cocos/core/animation/cubic-spline-value.ts index e3093be52b..b174dd02f2 100644 --- a/cocos/animation/cubic-spline-value.ts +++ b/cocos/core/animation/cubic-spline-value.ts @@ -3,8 +3,8 @@ * @category animation */ -import { ccclass, property } from '../core/data/class-decorator'; -import { Quat, Vec2, Vec3, Vec4 } from '../core/math'; +import { ccclass, property } from '../data/class-decorator'; +import { Quat, Vec2, Vec3, Vec4 } from '../math'; import { ILerpable } from './types'; interface ICubicSplineValue extends ILerpable { diff --git a/cocos/animation/curve-value-adapters/index.ts b/cocos/core/animation/curve-value-adapters/index.ts similarity index 100% rename from cocos/animation/curve-value-adapters/index.ts rename to cocos/core/animation/curve-value-adapters/index.ts diff --git a/cocos/animation/curve-value-adapters/uniform.ts b/cocos/core/animation/curve-value-adapters/uniform.ts similarity index 87% rename from cocos/animation/curve-value-adapters/uniform.ts rename to cocos/core/animation/curve-value-adapters/uniform.ts index d09870af6a..6c68b0a1ed 100644 --- a/cocos/animation/curve-value-adapters/uniform.ts +++ b/cocos/core/animation/curve-value-adapters/uniform.ts @@ -3,8 +3,8 @@ */ import { CurveValueAdapter } from '../animation-curve'; -import { Material } from '../../3d'; -import { property, ccclass } from '../../core/data/class-decorator'; +import { Material } from '../../assets/material'; +import { property, ccclass } from '../../data/class-decorator'; @ccclass('cc.UniformCurveValueAdapter') export class UniformCurveValueAdapter extends CurveValueAdapter { diff --git a/cocos/animation/deprecated.ts b/cocos/core/animation/deprecated.ts similarity index 91% rename from cocos/animation/deprecated.ts rename to cocos/core/animation/deprecated.ts index bd7e6ff2af..4a5c354a05 100644 --- a/cocos/animation/deprecated.ts +++ b/cocos/core/animation/deprecated.ts @@ -2,7 +2,7 @@ * @hidden */ -import { replaceProperty } from '../deprecated'; +import { replaceProperty } from '../utils/deprecated'; import { AnimationComponent } from './animation-component'; import { AnimationClip } from './animation-clip'; diff --git a/cocos/animation/easing.ts b/cocos/core/animation/easing.ts similarity index 100% rename from cocos/animation/easing.ts rename to cocos/core/animation/easing.ts diff --git a/cocos/animation/index.ts b/cocos/core/animation/index.ts similarity index 96% rename from cocos/animation/index.ts rename to cocos/core/animation/index.ts index 78d92ef841..e00c504d26 100644 --- a/cocos/animation/index.ts +++ b/cocos/core/animation/index.ts @@ -25,4 +25,4 @@ export { } from './target-modifier'; export * from './curve-value-adapters'; -import './deprecated'; \ No newline at end of file +import './deprecated'; \ No newline at end of file diff --git a/cocos/animation/motion-path-helper.ts b/cocos/core/animation/motion-path-helper.ts similarity index 94% rename from cocos/animation/motion-path-helper.ts rename to cocos/core/animation/motion-path-helper.ts index 5b857b1abc..e4e7fd81a1 100644 --- a/cocos/animation/motion-path-helper.ts +++ b/cocos/core/animation/motion-path-helper.ts @@ -2,10 +2,10 @@ * @hidden */ -import { binarySearchEpsilon as binarySearch } from '../core/data/utils/binary-search'; -import { errorID } from '../core/platform/CCDebug'; -import { Vec2 } from '../core/math'; -import { AnimCurve, computeRatioByType, CurveType, CurveValue } from './animation-curve'; +import { binarySearchEpsilon as binarySearch } from '../data/utils/binary-search'; +import { errorID } from '../platform/debug'; +import { Vec2, Vec3 } from '../math'; +import { AnimCurve, computeRatioByType, CurveValue, EasingMethod } from './animation-curve'; import { bezier } from './bezier'; // tslint:disable:no-shadowed-variable @@ -247,9 +247,10 @@ export function sampleMotionPaths (motionPaths: Array<(MotionPath | undefined)>, }; }; + // @ts-ignore const values = data.values = data.values.map((value) => { if (Array.isArray(value)) { - value = value.length === 2 ? cc.v2(value[0], value[1]) : cc.v3(value[0], value[1], value[2]); + value = value.length === 2 ? new Vec2(value[0], value[1]) : new Vec3(value[0], value[1], value[2]); } return value; }); @@ -280,13 +281,16 @@ export function sampleMotionPaths (motionPaths: Array<(MotionPath | undefined)>, } const types = data.types; + // @ts-ignore const ratios = (data.ratioSampler ? data.ratioSampler.ratios : []); + // @ts-ignore const newValues: CurveValue[] = data.values = []; - const newTypes: CurveType[] = data.types = []; + const newTypes: any[] = data.types = []; + // @ts-ignore const newRatios: number[] = data.ratios = []; - function addNewDatas (value: CurveValue, type: CurveType, ratio: number) { + function addNewDatas (value: CurveValue, type: any, ratio: number) { newValues.push(value); newTypes.push(type); newRatios.push(ratio); @@ -296,7 +300,7 @@ export function sampleMotionPaths (motionPaths: Array<(MotionPath | undefined)>, let startRatioOffset = 0; const EPSILON = 1e-6; - let newType: CurveType = AnimCurve.Linear; + let newType: any = AnimCurve.Linear; // do not need to compute last path for (let i = 0, l = motionPaths.length; i < l - 1; i++) { @@ -309,7 +313,7 @@ export function sampleMotionPaths (motionPaths: Array<(MotionPath | undefined)>, const value = values[i]; const nextValue = values[i + 1]; - const type = types[i]; + const type = types && types[i]; const results: Vec2[] = []; let progress = startRatioOffset / betweenRatio; @@ -337,7 +341,7 @@ export function sampleMotionPaths (motionPaths: Array<(MotionPath | undefined)>, while (1 - progress > EPSILON) { finalProgress = progress; - finalProgress = computeRatioByType(finalProgress, type); + finalProgress = computeRatioByType(finalProgress, type as EasingMethod); let pos = new Vec2(); @@ -378,7 +382,7 @@ export function sampleMotionPaths (motionPaths: Array<(MotionPath | undefined)>, while (1 - progress > EPSILON) { finalProgress = progress; - finalProgress = computeRatioByType(finalProgress, type); + finalProgress = computeRatioByType(finalProgress, type as EasingMethod); results.push(value.lerp(nextValue, finalProgress)); diff --git a/cocos/animation/playable.ts b/cocos/core/animation/playable.ts similarity index 97% rename from cocos/animation/playable.ts rename to cocos/core/animation/playable.ts index 14e6cff35c..65ad245e0c 100644 --- a/cocos/animation/playable.ts +++ b/cocos/core/animation/playable.ts @@ -2,7 +2,7 @@ * @category animation */ -import { getError } from '../core/platform/CCDebug'; +import { getError } from '../platform/debug'; export class Playable { diff --git a/cocos/animation/skeletal-animation-clip.ts b/cocos/core/animation/skeletal-animation-clip.ts similarity index 97% rename from cocos/animation/skeletal-animation-clip.ts rename to cocos/core/animation/skeletal-animation-clip.ts index fe2d5f8c26..f318791a41 100644 --- a/cocos/animation/skeletal-animation-clip.ts +++ b/cocos/core/animation/skeletal-animation-clip.ts @@ -27,9 +27,9 @@ * @category animation */ -import { ccclass } from '../core/data/class-decorator'; -import { Mat4 } from '../core/math'; -import { INode } from '../core/utils/interfaces'; +import { ccclass } from '../data/class-decorator'; +import { Mat4 } from '../math'; +import { INode } from '../utils/interfaces'; import { AnimationClip, IObjectCurveData, IRuntimeCurve, ITargetCurveData } from './animation-clip'; import { IPropertyCurveData } from './animation-curve'; import { ComponentModifier, HierachyModifier, isCustomTargetModifier, isPropertyModifier } from './target-modifier'; diff --git a/cocos/animation/skeletal-animation-component.ts b/cocos/core/animation/skeletal-animation-component.ts similarity index 96% rename from cocos/animation/skeletal-animation-component.ts rename to cocos/core/animation/skeletal-animation-component.ts index 7cfc328652..0123c15adb 100644 --- a/cocos/animation/skeletal-animation-component.ts +++ b/cocos/core/animation/skeletal-animation-component.ts @@ -27,10 +27,10 @@ * @category animation */ -import { SkeletalAnimationClip } from '../animation/skeletal-animation-clip'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../core/data/class-decorator'; -import { Mat4 } from '../core/math'; -import { INode } from '../core/utils/interfaces'; +import { SkeletalAnimationClip } from './skeletal-animation-clip'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../data/class-decorator'; +import { Mat4 } from '../math'; +import { INode } from '../utils/interfaces'; import { IJointsAnimInfo, JointsAnimationInfo } from '../renderer/models/skinning-model'; import { Node } from '../scene-graph/node'; import { AnimationClip } from './animation-clip'; @@ -152,7 +152,7 @@ export class SkeletalAnimationComponent extends AnimationComponent { if (socket) { return socket.target; } const joint = this.node.getChildByPath(path); if (!joint) { console.warn('illegal socket path'); return null; } - const target = new cc.Node(); + const target = new Node() as INode; target.parent = this.node; this._sockets.push(new Socket(path, target)); this.rebuildSocketAnimations(); diff --git a/cocos/animation/skeletal-animation-state.ts b/cocos/core/animation/skeletal-animation-state.ts similarity index 95% rename from cocos/animation/skeletal-animation-state.ts rename to cocos/core/animation/skeletal-animation-state.ts index 96a0e846d5..ad23ea08c8 100644 --- a/cocos/animation/skeletal-animation-state.ts +++ b/cocos/core/animation/skeletal-animation-state.ts @@ -28,7 +28,7 @@ */ import { SkinningModelComponent } from '../3d/framework/skinning-model-component'; -import { Mat4 } from '../core/math'; +import { Mat4 } from '../math'; import { IObjectCurveData } from './animation-clip'; import { AnimCurve } from './animation-curve'; import { AnimationState, ICurveInstance } from './animation-state'; @@ -50,7 +50,9 @@ export class SkeletalAnimationState extends AnimationState { public onPlay () { super.onPlay(); - for (const comp of this._targetNode!.getComponentsInChildren(SkinningModelComponent)) { + let comps = this._targetNode!.getComponentsInChildren(SkinningModelComponent); + for (let i = 0; i < comps.length; ++i) { + const comp = comps[i] as SkinningModelComponent; if (comp.skinningRoot === this._targetNode) { comp.uploadAnimation(this.clip as SkeletalAnimationClip); } diff --git a/cocos/animation/target-modifier.ts b/cocos/core/animation/target-modifier.ts similarity index 95% rename from cocos/animation/target-modifier.ts rename to cocos/core/animation/target-modifier.ts index 9fa1e8bd23..a7953da7f1 100644 --- a/cocos/animation/target-modifier.ts +++ b/cocos/core/animation/target-modifier.ts @@ -2,10 +2,10 @@ * @hidden */ -import { ccclass, property } from '../core/data/class-decorator'; -import { INode } from '../core/utils/interfaces'; +import { ccclass, property } from '../data/class-decorator'; +import { INode } from '../utils/interfaces'; import { CurveValueAdapter, ICurveValueProxy } from './animation-curve'; -import { Node } from '../scene-graph'; +import { Node } from '../scene-graph/node'; export type PropertyModifier = string; diff --git a/cocos/animation/transform-utils.ts b/cocos/core/animation/transform-utils.ts similarity index 95% rename from cocos/animation/transform-utils.ts rename to cocos/core/animation/transform-utils.ts index 3244b09e27..4a04a38fa9 100644 --- a/cocos/animation/transform-utils.ts +++ b/cocos/core/animation/transform-utils.ts @@ -27,8 +27,8 @@ * @category animation */ -import { INode } from '../core/utils/interfaces'; -import { Vec3, Quat, Mat4 } from '../core/math'; +import { INode } from '../utils/interfaces'; +import { Mat4 } from '../math'; const m4_1 = new Mat4(); diff --git a/cocos/animation/types.ts b/cocos/core/animation/types.ts similarity index 97% rename from cocos/animation/types.ts rename to cocos/core/animation/types.ts index 401a0491a5..2421294ed0 100644 --- a/cocos/animation/types.ts +++ b/cocos/core/animation/types.ts @@ -3,7 +3,7 @@ * @category animation */ -import { ccenum } from '../core/value-types/enum'; +import { ccenum } from '../value-types/enum'; export enum WrapModeMask { Loop = 1 << 1, diff --git a/cocos/assets/asset-enum.ts b/cocos/core/assets/asset-enum.ts similarity index 100% rename from cocos/assets/asset-enum.ts rename to cocos/core/assets/asset-enum.ts diff --git a/cocos/assets/asset-library.ts b/cocos/core/assets/asset-library.ts similarity index 97% rename from cocos/assets/asset-library.ts rename to cocos/core/assets/asset-library.ts index 5a46ef027a..3164116344 100644 --- a/cocos/assets/asset-library.ts +++ b/cocos/core/assets/asset-library.ts @@ -28,15 +28,15 @@ * @category asset */ -import decodeUuid from '../core/utils/decode-uuid'; -import {_getClassById, createMap, isChildClassOf} from '../core/utils/js'; -import {callInNextTick} from '../core/utils/misc'; -import AssetTable from '../load-pipeline/asset-table'; +import decodeUuid from '../utils/decode-uuid'; +import {_getClassById, createMap, isChildClassOf} from '../utils/js'; +import {callInNextTick} from '../utils/misc'; +import { AssetTable } from '../load-pipeline/asset-table'; import {getDependsRecursively} from '../load-pipeline/auto-release-utils'; import Loader from '../load-pipeline/CCLoader'; import MD5Pipe from '../load-pipeline/md5-pipe'; import {initPacks} from '../load-pipeline/pack-downloader'; -import SubPackPipe from '../load-pipeline/subpackage-pipe'; +import { SubPackPipe } from '../load-pipeline/subpackage-pipe'; import { Asset } from './asset'; // tslint:disable: max-line-length @@ -98,7 +98,7 @@ const AssetLibrary = { * @param {Boolean} options.writeMainCache - 默认为true。如果为true,则结果将缓存到 AssetLibrary,并且必须由用户手动卸载。 * @param {Asset} options.existingAsset - 加载现有资源,此参数仅在编辑器中可用。 */ - loadAsset (uuid: String, callback: Function, options) { + loadAsset (uuid: String, callback: Function, options?) { if (typeof uuid !== 'string') { return callInNextTick(callback, new Error('[AssetLibrary] uuid must be string'), null); } diff --git a/cocos/assets/asset.ts b/cocos/core/assets/asset.ts similarity index 94% rename from cocos/assets/asset.ts rename to cocos/core/assets/asset.ts index 4e1ca15027..686cfd7a31 100644 --- a/cocos/assets/asset.ts +++ b/cocos/core/assets/asset.ts @@ -28,14 +28,14 @@ * @category asset */ -import { ccclass, property } from '../core/data/class-decorator'; -import { Event } from '../core/event'; -import { CallbacksInvoker } from '../core/event/callbacks-invoker'; -import { EventTarget } from '../core/event/event-target'; -import { applyMixins, IEventTarget } from '../core/event/event-target-factory'; -import { createMap } from '../core/utils/js-typed'; -import { Node } from '../scene-graph'; +import { ccclass, property } from '../data/class-decorator'; +import { Event } from '../event'; +import { CallbacksInvoker } from '../event/callbacks-invoker'; +import { EventTarget } from '../event/event-target'; +import { applyMixins, IEventTarget } from '../event/event-target-factory'; +import { createMap } from '../utils/js-typed'; import { RawAsset } from './raw-asset'; +import { INode } from '../utils/interfaces'; /** * @en @@ -271,7 +271,7 @@ applyMixins(Asset, [CallbacksInvoker, EventTarget]); * @param error - null or the error info * @param node - the created node or null */ -type CreateNodeCallback = (error: Error | null, node: Node) => void; +type CreateNodeCallback = (error: Error | null, node: INode) => void; // @ts-ignore Asset.prototype.createNode = null; diff --git a/cocos/assets/bitmap-font.ts b/cocos/core/assets/bitmap-font.ts similarity index 96% rename from cocos/assets/bitmap-font.ts rename to cocos/core/assets/bitmap-font.ts index 55d75d4c62..9e37455c1e 100644 --- a/cocos/assets/bitmap-font.ts +++ b/cocos/core/assets/bitmap-font.ts @@ -28,7 +28,7 @@ * @category asset */ -import { ccclass, property } from '../core/data/class-decorator'; +import { ccclass, property } from '../data/class-decorator'; import { Font } from './font'; import { SpriteFrame } from './sprite-frame'; diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/core/assets/effect-asset.ts similarity index 92% rename from cocos/3d/assets/effect-asset.ts rename to cocos/core/assets/effect-asset.ts index 1cdaad8157..dffce29d3a 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/core/assets/effect-asset.ts @@ -27,15 +27,16 @@ * @category material */ -import { Asset } from '../../assets/asset'; +import { Asset } from './asset'; import { ccclass, property } from '../../core/data/class-decorator'; import { Root } from '../../core/root'; -import { GFXDynamicState, GFXPrimitiveMode } from '../../gfx/define'; -import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../../gfx/pipeline-state'; -import { GFXUniformBlock, GFXUniformSampler } from '../../gfx/shader'; -import { RenderPassStage } from '../../pipeline/define'; -import { IDefineMap } from '../../renderer/core/pass'; -import { programLib } from '../../renderer/core/program-lib'; +import { GFXDynamicState, GFXPrimitiveMode } from '../gfx/define'; +import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../gfx/pipeline-state'; +import { GFXUniformBlock, GFXUniformSampler } from '../gfx/shader'; +import { RenderPassStage } from '../pipeline/define'; +import { IDefineMap } from '../renderer/core/pass'; +import { programLib } from '../renderer/core/program-lib'; +import { director } from '../director'; export interface IPropertyInfo { type: number; // auto-extracted @@ -181,7 +182,7 @@ export class EffectAsset extends Asset { } protected _precompile () { - const root = cc.director.root as Root; + const root = director.root as Root; for (let i = 0; i < this.shaders.length; i++) { const shader = this.shaders[i]; const combination = this.combinations[i]; diff --git a/cocos/assets/font.ts b/cocos/core/assets/font.ts similarity index 96% rename from cocos/assets/font.ts rename to cocos/core/assets/font.ts index 39c7f5006e..3f7c322006 100644 --- a/cocos/assets/font.ts +++ b/cocos/core/assets/font.ts @@ -28,7 +28,7 @@ * @category asset */ -import {ccclass} from '../core/data/class-decorator'; +import {ccclass} from '../data/class-decorator'; import { Asset } from './asset'; /** diff --git a/cocos/assets/image-asset.ts b/cocos/core/assets/image-asset.ts similarity index 97% rename from cocos/assets/image-asset.ts rename to cocos/core/assets/image-asset.ts index ac0cc2389a..92c3a688a2 100644 --- a/cocos/assets/image-asset.ts +++ b/cocos/core/assets/image-asset.ts @@ -28,11 +28,11 @@ */ // @ts-check -import {ccclass, property} from '../core/data/class-decorator'; +import {ccclass, property} from '../data/class-decorator'; import { GFXDevice, GFXFeature } from '../gfx/device'; -// import {addon} from '../core/utils/js'; import { Asset } from './asset'; import { PixelFormat } from './asset-enum'; +import { director } from '../director'; /** * 内存图像源。 @@ -277,8 +277,8 @@ export class ImageAsset extends Asset { } function _getGlobalDevice (): GFXDevice | null { - if (cc.director && cc.director.root) { - return cc.director.root.device; + if (director.root) { + return director.root.device; } else { return null; } diff --git a/cocos/assets/index.ts b/cocos/core/assets/index.ts similarity index 91% rename from cocos/assets/index.ts rename to cocos/core/assets/index.ts index ed1eef8fa3..a889f9eed6 100644 --- a/cocos/assets/index.ts +++ b/cocos/core/assets/index.ts @@ -40,11 +40,16 @@ export {default as JsonAsset} from './json-asset'; export {default as AssetLibrary} from './asset-library'; export { ImageAsset } from './image-asset'; export { Texture2D } from './texture-2d'; +export { TextureCube } from './texture-cube' export { TTFFont } from './ttf-font'; export { LabelAtlas } from './label-atlas'; export { BitmapFont } from './bitmap-font'; export { Font } from './font'; import * as textureUtil from './texture-util'; export { textureUtil }; -export { SimpleTexture as TrivialTexture } from './simple-texture'; +export { EffectAsset } from './effect-asset'; +export { Material } from './material'; +export { Mesh } from './mesh'; +export { Skeleton } from './skeleton'; export { RenderTexture } from './render-texture'; + diff --git a/cocos/assets/json-asset.ts b/cocos/core/assets/json-asset.ts similarity index 96% rename from cocos/assets/json-asset.ts rename to cocos/core/assets/json-asset.ts index aef6ddab9d..0ac53c6851 100644 --- a/cocos/assets/json-asset.ts +++ b/cocos/core/assets/json-asset.ts @@ -27,7 +27,7 @@ * @category asset */ -import {ccclass, property} from '../core/data/class-decorator'; +import {ccclass, property} from '../data/class-decorator'; import { Asset } from './asset'; /** diff --git a/cocos/assets/label-atlas.ts b/cocos/core/assets/label-atlas.ts similarity index 96% rename from cocos/assets/label-atlas.ts rename to cocos/core/assets/label-atlas.ts index 4435fb49af..6b47596a9c 100644 --- a/cocos/assets/label-atlas.ts +++ b/cocos/core/assets/label-atlas.ts @@ -28,7 +28,7 @@ * @category asset */ -import { ccclass } from '../core/data/class-decorator'; +import { ccclass } from '../data/class-decorator'; import { BitmapFont } from './bitmap-font'; /** * @en diff --git a/cocos/3d/assets/material.ts b/cocos/core/assets/material.ts similarity index 96% rename from cocos/3d/assets/material.ts rename to cocos/core/assets/material.ts index d02952f022..c906bb8916 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/core/assets/material.ts @@ -28,17 +28,17 @@ * @category material */ -import { Asset } from '../../assets/asset'; -import { TextureBase } from '../../assets/texture-base'; +import { Asset } from './asset'; +import { TextureBase } from './texture-base'; import { ccclass, property } from '../../core/data/class-decorator'; import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc'; -import { GFXBindingType } from '../../gfx/define'; -import { GFXTextureView } from '../../gfx/texture-view'; -import { IDefineMap, Pass, PassOverrides } from '../../renderer/core/pass'; -import { samplerLib } from '../../renderer/core/sampler-lib'; -import { builtinResMgr } from '../builtin'; -import { RenderableComponent } from '../framework/renderable-component'; +import { GFXBindingType } from '../gfx/define'; +import { GFXTextureView } from '../gfx/texture-view'; +import { IDefineMap, Pass, PassOverrides } from '../renderer/core/pass'; +import { samplerLib } from '../renderer/core/sampler-lib'; +import { RenderableComponent } from '../3d/framework/renderable-component'; import { EffectAsset } from './effect-asset'; +import { builtinResMgr } from '../3d/builtin'; /** * @zh diff --git a/cocos/3d/assets/mesh.ts b/cocos/core/assets/mesh.ts similarity index 99% rename from cocos/3d/assets/mesh.ts rename to cocos/core/assets/mesh.ts index 0dc777bf56..95237b81f3 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/core/assets/mesh.ts @@ -27,16 +27,17 @@ * @category asset */ -import { Asset } from '../../assets/asset'; +import { Asset } from './asset'; import { ccclass, property } from '../../core/data/class-decorator'; import { Vec3 } from '../../core/math'; -import { GFXBuffer } from '../../gfx/buffer'; -import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXFormatType, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; -import { GFXDevice } from '../../gfx/device'; -import { IGFXAttribute } from '../../gfx/input-assembler'; -import { BufferBlob } from '../misc/buffer-blob'; +import { GFXBuffer } from '../gfx/buffer'; +import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXFormatType, GFXMemoryUsageBit, GFXPrimitiveMode } from '../gfx/define'; +import { GFXDevice } from '../gfx/device'; +import { IGFXAttribute } from '../gfx/input-assembler'; +import { BufferBlob } from '../3d/misc/buffer-blob'; import { IBufferView } from './utils/buffer-view'; import { postLoadMesh } from './utils/mesh-utils'; +import { director } from '../director'; function getIndexStrideCtor (stride: number) { switch (stride) { @@ -338,7 +339,7 @@ export class Mesh extends Asset { postLoadMesh(this); } const buffer = this._data.buffer; - const gfxDevice: GFXDevice = cc.director.root.device; + const gfxDevice: GFXDevice = director.root!.device; const vertexBuffers = this._createVertexBuffers(gfxDevice, buffer); const indexBuffers: GFXBuffer[] = []; const submeshes: IRenderingSubmesh[] = []; diff --git a/cocos/assets/prefab.ts b/cocos/core/assets/prefab.ts similarity index 97% rename from cocos/assets/prefab.ts rename to cocos/core/assets/prefab.ts index 043f596d91..20c7a06088 100644 --- a/cocos/assets/prefab.ts +++ b/cocos/core/assets/prefab.ts @@ -28,10 +28,10 @@ * @category asset */ -import { ccclass, property } from '../core/data/class-decorator'; -import { compile } from '../core/data/instantiate-jit'; -import { obsolete } from '../core/utils/js'; -import { Enum } from '../core/value-types'; +import { ccclass, property } from '../data/class-decorator'; +import { compile } from '../data/instantiate-jit'; +import { obsolete } from '../utils/js'; +import { Enum } from '../value-types'; import { Asset } from './asset'; /** diff --git a/cocos/assets/raw-asset.ts b/cocos/core/assets/raw-asset.ts similarity index 92% rename from cocos/assets/raw-asset.ts rename to cocos/core/assets/raw-asset.ts index 22ea848269..2e18223a79 100644 --- a/cocos/assets/raw-asset.ts +++ b/cocos/core/assets/raw-asset.ts @@ -28,9 +28,9 @@ * @hidden */ -import { ccclass } from '../core/data/class-decorator'; -import { CCObject } from '../core/data/object'; -import { isChildClassOf } from '../core/utils/js'; +import { ccclass } from '../data/class-decorator'; +import { CCObject } from '../data/object'; +import { isChildClassOf } from '../utils/js'; /** * 原生资源的基类。内部使用。 diff --git a/cocos/assets/render-texture.ts b/cocos/core/assets/render-texture.ts similarity index 93% rename from cocos/assets/render-texture.ts rename to cocos/core/assets/render-texture.ts index 115b02911a..43f184ef3e 100644 --- a/cocos/assets/render-texture.ts +++ b/cocos/core/assets/render-texture.ts @@ -2,13 +2,14 @@ * @category asset */ -import { ccclass, property } from '../core/data/class-decorator'; -import { ccenum } from '../core/value-types/enum'; +import { ccclass, property } from '../data/class-decorator'; import { GFXFormat } from '../gfx'; import { GFXDevice } from '../gfx/device'; import { GFXWindow } from '../gfx/window'; import { DepthStencilFormat, PixelFormat } from './asset-enum'; import { TextureBase } from './texture-base'; +import { ccenum } from '../value-types/enum'; +import { director } from '../director'; export interface IRenderTextureCreateInfo { name?: string; @@ -83,7 +84,7 @@ export class RenderTexture extends TextureBase { public destroy () { if (this._window) { - cc.director.root.destroyWindow(this._window); + director.root!.destroyWindow(this._window); this._window = null; } @@ -146,7 +147,7 @@ export class RenderTexture extends TextureBase { return this._window; } - this._window = cc.director.root!.createWindow(config); + this._window = director.root!.createWindow(config); } } diff --git a/cocos/assets/scene-asset.ts b/cocos/core/assets/scene-asset.ts similarity index 96% rename from cocos/assets/scene-asset.ts rename to cocos/core/assets/scene-asset.ts index 04d8da2363..8d2c74ef7c 100644 --- a/cocos/assets/scene-asset.ts +++ b/cocos/core/assets/scene-asset.ts @@ -28,7 +28,7 @@ * @category asset */ -import {ccclass, property} from '../core/data/class-decorator'; +import {ccclass, property} from '../data/class-decorator'; import { Scene } from '../scene-graph'; import { Asset } from './asset'; diff --git a/cocos/assets/scripts.ts b/cocos/core/assets/scripts.ts similarity index 97% rename from cocos/assets/scripts.ts rename to cocos/core/assets/scripts.ts index 63eddb5866..1262a36d3a 100644 --- a/cocos/assets/scripts.ts +++ b/cocos/core/assets/scripts.ts @@ -28,7 +28,7 @@ * @category asset */ -import {ccclass} from '../core/data/class-decorator'; +import {ccclass} from '../data/class-decorator'; import { Asset } from './asset'; /** diff --git a/cocos/assets/simple-texture.ts b/cocos/core/assets/simple-texture.ts similarity index 98% rename from cocos/assets/simple-texture.ts rename to cocos/core/assets/simple-texture.ts index 56f66521b4..242c172fdb 100644 --- a/cocos/assets/simple-texture.ts +++ b/cocos/core/assets/simple-texture.ts @@ -2,8 +2,8 @@ * @category asset */ -import { ccclass } from '../core/data/class-decorator'; -import { error } from '../core/platform/CCDebug'; +import { ccclass } from '../data/class-decorator'; +import { error } from '../platform/debug'; import { GFXBufferTextureCopy, GFXTextureFlagBit, GFXTextureUsageBit } from '../gfx/define'; import { GFXDevice } from '../gfx/device'; import { GFXTexture, IGFXTextureInfo } from '../gfx/texture'; diff --git a/cocos/3d/assets/skeleton.ts b/cocos/core/assets/skeleton.ts similarity index 98% rename from cocos/3d/assets/skeleton.ts rename to cocos/core/assets/skeleton.ts index b2af5a2f74..130980de2a 100644 --- a/cocos/3d/assets/skeleton.ts +++ b/cocos/core/assets/skeleton.ts @@ -27,7 +27,7 @@ * @category asset */ -import { Asset } from '../../assets/asset'; +import { Asset } from './asset'; import { ccclass, property } from '../../core/data/class-decorator'; import { CCString } from '../../core/data/utils/attribute'; import { Mat4, Quat, Vec3 } from '../../core/math'; diff --git a/cocos/assets/sprite-atlas.ts b/cocos/core/assets/sprite-atlas.ts similarity index 97% rename from cocos/assets/sprite-atlas.ts rename to cocos/core/assets/sprite-atlas.ts index 1084968b0c..5f8879da74 100644 --- a/cocos/assets/sprite-atlas.ts +++ b/cocos/core/assets/sprite-atlas.ts @@ -28,8 +28,8 @@ * @category asset */ -import { ccclass, property } from '../core/data/class-decorator'; -import * as js from '../core/utils/js'; +import { ccclass, property } from '../data/class-decorator'; +import * as js from '../utils/js'; import { Asset } from './asset'; import { SpriteFrame } from './sprite-frame'; diff --git a/cocos/assets/sprite-frame.ts b/cocos/core/assets/sprite-frame.ts similarity index 99% rename from cocos/assets/sprite-frame.ts rename to cocos/core/assets/sprite-frame.ts index 4e8f19a856..ef50b14a47 100644 --- a/cocos/assets/sprite-frame.ts +++ b/cocos/core/assets/sprite-frame.ts @@ -30,10 +30,10 @@ * @category asset */ -import { ccclass } from '../core/data/class-decorator'; -import { Rect, Size, Vec2 } from '../core/math'; +import { ccclass } from '../data/class-decorator'; +import { Rect, Size, Vec2 } from '../math'; import { ImageAsset } from './image-asset'; -import { murmurhash2_32_gc } from '../core/utils/murmurhash2_gc'; +import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; import { TextureBase } from './texture-base'; import { Asset } from './asset'; import { Texture2D } from './texture-2d'; diff --git a/cocos/assets/text-asset.ts b/cocos/core/assets/text-asset.ts similarity index 96% rename from cocos/assets/text-asset.ts rename to cocos/core/assets/text-asset.ts index 9933cec089..f342612a57 100644 --- a/cocos/assets/text-asset.ts +++ b/cocos/core/assets/text-asset.ts @@ -28,7 +28,7 @@ * @category asset */ -import {ccclass, property} from '../core/data/class-decorator'; +import {ccclass, property} from '../data/class-decorator'; import { Asset } from './asset'; /** diff --git a/cocos/assets/texture-2d.ts b/cocos/core/assets/texture-2d.ts similarity index 99% rename from cocos/assets/texture-2d.ts rename to cocos/core/assets/texture-2d.ts index 29fb4b456b..3b370f1674 100644 --- a/cocos/assets/texture-2d.ts +++ b/cocos/core/assets/texture-2d.ts @@ -29,7 +29,7 @@ */ // @ts-check -import { ccclass, property } from '../core/data/class-decorator'; +import { ccclass, property } from '../data/class-decorator'; import { GFXTextureType, GFXTextureViewType } from '../gfx/define'; import { PixelFormat } from './asset-enum'; import { ImageAsset } from './image-asset'; diff --git a/cocos/assets/texture-base.ts b/cocos/core/assets/texture-base.ts similarity index 97% rename from cocos/assets/texture-base.ts rename to cocos/core/assets/texture-base.ts index 3e438cd373..4474d81183 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/core/assets/texture-base.ts @@ -29,14 +29,14 @@ */ // @ts-check -import {ccclass, property} from '../core/data/class-decorator'; -import { error } from '../core/platform/CCDebug'; -import IDGenerator from '../core/utils/id-generator'; +import {ccclass, property} from '../data/class-decorator'; +import IDGenerator from '../utils/id-generator'; import { GFXDevice } from '../gfx/device'; import { GFXTextureView } from '../gfx/texture-view'; import { SamplerInfoIndex, genSamplerHash } from '../renderer/core/sampler-lib'; import { Asset } from './asset'; import { Filter, PixelFormat, WrapMode } from './asset-enum'; +import { director } from '../director'; const CHAR_CODE_1 = 49; // '1' @@ -285,7 +285,7 @@ export class TextureBase extends Asset { } protected _getGFXDevice (): GFXDevice | null { - return cc.director.root && cc.director.root.device; + return director.root && director.root.device; } protected _getGFXFormat () { diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/core/assets/texture-cube.ts similarity index 97% rename from cocos/3d/assets/texture-cube.ts rename to cocos/core/assets/texture-cube.ts index c48021dc7a..cb0256adad 100644 --- a/cocos/3d/assets/texture-cube.ts +++ b/cocos/core/assets/texture-cube.ts @@ -28,12 +28,12 @@ */ // @ts-check -import { Texture2D, TrivialTexture } from '../../assets'; -import { ImageAsset } from '../../assets/image-asset'; -import { PresumedGFXTextureInfo, PresumedGFXTextureViewInfo } from '../../assets/simple-texture'; -import { ITexture2DCreateInfo } from '../../assets/texture-2d'; +import { Texture2D, ImageAsset } from '../assets'; +import { SimpleTexture as TrivialTexture } from '../assets/simple-texture'; +import { PresumedGFXTextureInfo, PresumedGFXTextureViewInfo } from '../assets/simple-texture'; +import { ITexture2DCreateInfo } from '../assets/texture-2d'; import { ccclass, property } from '../../core/data/class-decorator'; -import { GFXTextureFlagBit, GFXTextureType, GFXTextureViewType } from '../../gfx/define'; +import { GFXTextureFlagBit, GFXTextureType, GFXTextureViewType } from '../gfx/define'; export type ITextureCubeCreateInfo = ITexture2DCreateInfo; diff --git a/cocos/assets/texture-util.ts b/cocos/core/assets/texture-util.ts similarity index 98% rename from cocos/assets/texture-util.ts rename to cocos/core/assets/texture-util.ts index 3f46296cd7..6e4e8de620 100644 --- a/cocos/assets/texture-util.ts +++ b/cocos/core/assets/texture-util.ts @@ -28,7 +28,7 @@ * @category asset */ -import { assertID, error } from '../core/platform/CCDebug'; +import { assertID, error } from '../platform/debug'; import { LoadCallbackParams, loader } from '../load-pipeline'; import { ImageAsset, ImageSource } from './image-asset'; diff --git a/cocos/assets/ttf-font.ts b/cocos/core/assets/ttf-font.ts similarity index 96% rename from cocos/assets/ttf-font.ts rename to cocos/core/assets/ttf-font.ts index 7097315559..5384d3f4e1 100644 --- a/cocos/assets/ttf-font.ts +++ b/cocos/core/assets/ttf-font.ts @@ -28,7 +28,7 @@ * @category asset */ -import {ccclass, property} from '../core/data/class-decorator'; +import {ccclass, property} from '../data/class-decorator'; import { Font } from './font'; /** diff --git a/cocos/3d/assets/utils/buffer-view.ts b/cocos/core/assets/utils/buffer-view.ts similarity index 100% rename from cocos/3d/assets/utils/buffer-view.ts rename to cocos/core/assets/utils/buffer-view.ts diff --git a/cocos/3d/assets/utils/mesh-utils.ts b/cocos/core/assets/utils/mesh-utils.ts similarity index 100% rename from cocos/3d/assets/utils/mesh-utils.ts rename to cocos/core/assets/utils/mesh-utils.ts diff --git a/cocos/components/block-input-events-component.ts b/cocos/core/components/block-input-events-component.ts similarity index 94% rename from cocos/components/block-input-events-component.ts rename to cocos/core/components/block-input-events-component.ts index 2dd39bb0e3..b8320d6aa6 100644 --- a/cocos/components/block-input-events-component.ts +++ b/cocos/core/components/block-input-events-component.ts @@ -39,10 +39,10 @@ * 该组件没有任何 API 接口,直接添加到场景即可生效。 */ -import { ccclass, menu } from '../core/data/class-decorator'; +import { ccclass, menu } from '../data/class-decorator'; import { Component } from './component'; -import { Event } from '../core/event'; -import { SystemEventType } from '../core/platform/event-manager/event-enum'; +import { Event } from '../event'; +import { SystemEventType } from '../platform/event-manager/event-enum'; const BlockEvents = [SystemEventType.TOUCH_START, SystemEventType.TOUCH_END, SystemEventType.TOUCH_MOVE, SystemEventType.MOUSE_DOWN, SystemEventType.MOUSE_MOVE, SystemEventType.MOUSE_UP, diff --git a/cocos/components/component-event-handler.ts b/cocos/core/components/component-event-handler.ts similarity index 98% rename from cocos/components/component-event-handler.ts rename to cocos/core/components/component-event-handler.ts index 11f50877e5..f0c2e1d92f 100644 --- a/cocos/components/component-event-handler.ts +++ b/cocos/core/components/component-event-handler.ts @@ -28,7 +28,7 @@ * @category event */ -import {ccclass, property} from '../core/data/class-decorator'; +import {ccclass, property} from '../data/class-decorator'; import { Node } from '../scene-graph'; /** diff --git a/cocos/components/component.ts b/cocos/core/components/component.ts similarity index 96% rename from cocos/components/component.ts rename to cocos/core/components/component.ts index f78a5ab836..8deb97925f 100644 --- a/cocos/components/component.ts +++ b/cocos/core/components/component.ts @@ -31,14 +31,15 @@ */ import { Script } from '../assets'; -import { ccclass, property } from '../core/data/class-decorator'; -import { CCObject } from '../core/data/object'; -import IDGenerator from '../core/utils/id-generator'; -import { getClassName, value } from '../core/utils/js'; +import { ccclass, property } from '../data/class-decorator'; +import { CCObject } from '../data/object'; +import IDGenerator from '../utils/id-generator'; +import { getClassName, value } from '../utils/js'; import { RenderScene } from '../renderer/scene/render-scene'; -import { Rect } from '../core/math'; -import * as RF from '../core/data/utils/requiring-frame'; -import { INode } from '../core/utils/interfaces'; +import { Rect } from '../math'; +import * as RF from '../data/utils/requiring-frame'; +import { INode } from '../utils/interfaces'; +import { director } from '../director'; const idGenerator = new IDGenerator('Comp'); // @ts-ignore @@ -98,7 +99,6 @@ class Component extends CCObject { visible: false, }) get uuid () { - // @ts-ignore if (CC_EDITOR && window.EditorExtends) { // @ts-ignore @@ -137,7 +137,7 @@ class Component extends CCObject { if (this._enabled !== value) { this._enabled = value; if (this.node.activeInHierarchy) { - const compScheduler = cc.director._compScheduler; + const compScheduler = director._compScheduler; if (value) { compScheduler.enableComp(this); } @@ -391,7 +391,7 @@ class Component extends CCObject { } if (super.destroy()) { if (this._enabled && this.node.activeInHierarchy) { - cc.director._compScheduler.disableComp(this); + director._compScheduler.disableComp(this); } } } @@ -415,7 +415,7 @@ class Component extends CCObject { } // onDestroy - cc.director._nodeActivator.destroyComp(this); + director._nodeActivator.destroyComp(this); // do remove component this.node._removeComponent(this); @@ -451,7 +451,7 @@ class Component extends CCObject { * this.schedule(timeCallback, 1); * ``` */ - public schedule (callback, interval: Number = 0, repeat: number = cc.macro.REPEAT_FOREVER, delay: Number = 0) { + public schedule (callback, interval: number = 0, repeat: number = cc.macro.REPEAT_FOREVER, delay: number = 0) { cc.assertID(callback, 1619); cc.assertID(interval >= 0, 1620); @@ -459,7 +459,7 @@ class Component extends CCObject { repeat = isNaN(repeat) ? cc.macro.REPEAT_FOREVER : repeat; delay = delay || 0; - const scheduler = cc.director.getScheduler(); + const scheduler = director.getScheduler(); // should not use enabledInHierarchy to judge whether paused, // because enabledInHierarchy is assigned after onEnable. @@ -485,7 +485,7 @@ class Component extends CCObject { * this.scheduleOnce(timeCallback, 2); * ``` */ - public scheduleOnce (callback, delay: Number = 0) { + public scheduleOnce (callback, delay: number = 0) { this.schedule(callback, 0, 0, delay); } @@ -505,7 +505,7 @@ class Component extends CCObject { return; } - cc.director.getScheduler().unschedule(callback_fn, this); + director.getScheduler().unschedule(callback_fn, this); } /** @@ -520,7 +520,7 @@ class Component extends CCObject { * ``` */ public unscheduleAllCallbacks () { - cc.director.getScheduler().unscheduleAllForTarget(this); + director.getScheduler().unscheduleAllForTarget(this); } // LIFECYCLE METHODS diff --git a/cocos/components/index.ts b/cocos/core/components/index.ts similarity index 87% rename from cocos/components/index.ts rename to cocos/core/components/index.ts index d64760cda5..cc56f38260 100644 --- a/cocos/components/index.ts +++ b/cocos/core/components/index.ts @@ -1,6 +1,5 @@ /* - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2018-2019 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -30,5 +29,7 @@ export { Component } from './component'; export { EventHandler } from './component-event-handler'; -export {default as MissingScript} from './missing-script'; +export { default as MissingScript } from './missing-script'; export { BlockInputEventsComponent } from './block-input-events-component'; +export { default as System } from './system'; +export * from './ui-base'; diff --git a/cocos/components/missing-script.ts b/cocos/core/components/missing-script.ts similarity index 93% rename from cocos/components/missing-script.ts rename to cocos/core/components/missing-script.ts index b724bf577c..da3d70cf84 100644 --- a/cocos/components/missing-script.ts +++ b/cocos/core/components/missing-script.ts @@ -1,141 +1,141 @@ -/* - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -/** - * @category component - */ - -import {ccclass, inspector, property} from '../core/data/class-decorator'; -import {_getClassById} from '../core/utils/js'; -import {BUILTIN_CLASSID_RE} from '../core/utils/misc'; -import { Component } from './component'; - -/** - * @en - * A temp fallback to contain the original serialized data which can not be loaded. - * @zh - * 包含无法加载的原始序列化数据的临时回退。 - */ -@ccclass('cc.MissingClass') -class MissingClass { - // the serialized data for original object - @property({ - visible: false, - editorOnly: true, - }) - public _$erialized = null; -} - -/** - * @en - * A temp fallback to contain the original component which can not be loaded. - * @zh - * 包含无法加载的原始组件的临时回退。 - */ -@ccclass('cc.MissingScript') -@inspector('packages://inspector/inspectors/comps/missing-script.js') -export default class MissingScript extends Component { - - // _scriptUuid: { - // get: function () { - // var id = this._$erialized.__type__; - // if (Editor.Utils.UuidUtils.isUuid(id)) { - // return Editor.Utils.UuidUtils.decompressUuid(id); - // } - // return ''; - // }, - // set: function (value) { - // if ( !sandbox.compiled ) { - // cc.error('Scripts not yet compiled, please fix script errors and compile first.'); - // return; - // } - // if (value && Editor.Utils.UuidUtils.isUuid(value._uuid)) { - // var classId = Editor.Utils.UuidUtils.compressUuid(value); - // if (_getClassById(classId)) { - // this._$erialized.__type__ = classId; - // Editor.Ipc.sendToWins('reload:window-scripts', sandbox.compiled); - // } - // else { - // cc.error('Can not find a component in the script which uuid is "%s".', value); - // } - // } - // else { - // cc.error('invalid script'); - // } - // } - // }, - - /* - * @param {string} id - * @return {function} constructor - */ - public static safeFindClass (id: string, data) { - const cls = _getClassById(id); - if (cls) { - return cls; - } - if (id) { - cc.deserialize.reportMissingClass(id); - return MissingScript.getMissingWrapper(id, data); - } - return null; - } - public static getMissingWrapper (id, data) { - if (data.node && (/^[0-9a-zA-Z+/]{23}$/.test(id) || BUILTIN_CLASSID_RE.test(id))) { - // is component - return MissingScript; - } - else { - return MissingClass; - } - } - - @property({ - serializable: false, - }) - public compiled = false; - - // the serialized data for original script object - @property({ - visible: false, - editorOnly: true, - }) - public _$erialized = null; - - constructor () { - super(); - if (CC_EDITOR) { - // @ts-ignore - this.compiled = _Scene.Sandbox.compiled; - } - } - - public onLoad () { - cc.warnID(4600, this.node.name); - } -} - -cc._MissingScript = MissingScript; +/* + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/** + * @category component + */ + +import {ccclass, inspector, property} from '../data/class-decorator'; +import {_getClassById} from '../utils/js'; +import {BUILTIN_CLASSID_RE} from '../utils/misc'; +import { Component } from './component'; + +/** + * @en + * A temp fallback to contain the original serialized data which can not be loaded. + * @zh + * 包含无法加载的原始序列化数据的临时回退。 + */ +@ccclass('cc.MissingClass') +class MissingClass { + // the serialized data for original object + @property({ + visible: false, + editorOnly: true, + }) + public _$erialized = null; +} + +/** + * @en + * A temp fallback to contain the original component which can not be loaded. + * @zh + * 包含无法加载的原始组件的临时回退。 + */ +@ccclass('cc.MissingScript') +@inspector('packages://inspector/inspectors/comps/missing-script.js') +export default class MissingScript extends Component { + + // _scriptUuid: { + // get: function () { + // var id = this._$erialized.__type__; + // if (Editor.Utils.UuidUtils.isUuid(id)) { + // return Editor.Utils.UuidUtils.decompressUuid(id); + // } + // return ''; + // }, + // set: function (value) { + // if ( !sandbox.compiled ) { + // cc.error('Scripts not yet compiled, please fix script errors and compile first.'); + // return; + // } + // if (value && Editor.Utils.UuidUtils.isUuid(value._uuid)) { + // var classId = Editor.Utils.UuidUtils.compressUuid(value); + // if (_getClassById(classId)) { + // this._$erialized.__type__ = classId; + // Editor.Ipc.sendToWins('reload:window-scripts', sandbox.compiled); + // } + // else { + // cc.error('Can not find a component in the script which uuid is "%s".', value); + // } + // } + // else { + // cc.error('invalid script'); + // } + // } + // }, + + /* + * @param {string} id + * @return {function} constructor + */ + public static safeFindClass (id: string, data) { + const cls = _getClassById(id); + if (cls) { + return cls; + } + if (id) { + cc.deserialize.reportMissingClass(id); + return MissingScript.getMissingWrapper(id, data); + } + return null; + } + public static getMissingWrapper (id, data) { + if (data.node && (/^[0-9a-zA-Z+/]{23}$/.test(id) || BUILTIN_CLASSID_RE.test(id))) { + // is component + return MissingScript; + } + else { + return MissingClass; + } + } + + @property({ + serializable: false, + }) + public compiled = false; + + // the serialized data for original script object + @property({ + visible: false, + editorOnly: true, + }) + public _$erialized = null; + + constructor () { + super(); + if (CC_EDITOR) { + // @ts-ignore + this.compiled = _Scene.Sandbox.compiled; + } + } + + public onLoad () { + cc.warnID(4600, this.node.name); + } +} + +cc._MissingScript = MissingScript; diff --git a/cocos/core/components/system.ts b/cocos/core/components/system.ts new file mode 100644 index 0000000000..27c36fc06d --- /dev/null +++ b/cocos/core/components/system.ts @@ -0,0 +1,62 @@ +/* + Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +import { ISchedulable } from "../scheduler"; + +export default class System implements ISchedulable { + protected _id = ''; + protected _priority = 0; + protected _executeInEditMode = false; + + set priority (value:number) { + this._priority = value; + } + get priority ():number { + return this._priority; + } + + set id (id:string) { + this._id = id; + } + get id ():string { + return this._id; + } + + public static sortByPriority (a:System, b:System) { + if (a._priority < b._priority) { + return 1; + } + else if (a._priority > b.priority) { + return -1; + } + else { + return 0; + } + } + + init () {} + update (dt: number) {} + postUpdate (dt: number) {} +} \ No newline at end of file diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/core/components/ui-base/canvas-component.ts similarity index 84% rename from cocos/3d/ui/components/canvas-component.ts rename to cocos/core/components/ui-base/canvas-component.ts index d0368e5ec6..afbc9491a3 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/core/components/ui-base/canvas-component.ts @@ -1,6 +1,6 @@ /* Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2017-2019 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -28,15 +28,20 @@ * @category ui */ -import { Component } from '../../../components'; -import { ccclass, disallowMultiple, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../../core/data/class-decorator'; -import { Vec3 } from '../../../core/math'; -import { GFXClearFlag } from '../../../gfx/define'; -import { Camera } from '../../../renderer'; +import { Component } from '../component'; +import { ccclass, disallowMultiple, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../data/class-decorator'; +import { Vec3 } from '../../math'; +import { GFXClearFlag } from '../../gfx/define'; +import { Camera } from '../../renderer'; import { UITransformComponent } from './ui-transfrom-component'; -import { Node } from '../../../scene-graph/node'; -import { RenderTexture } from '../../../assets'; -import { GFXWindow } from '../../../gfx/window'; +import { Node } from '../../scene-graph/node'; +import { RenderTexture } from '../../assets/render-texture'; +import { GFXWindow } from '../../gfx/window'; +import { director, Director } from '../../director'; +import { view, ResolutionPolicy } from '../../platform/view'; +import visibleRect from '../../platform/visible-rect'; +import { CameraComponent } from '../../3d/framework/camera-component'; +import { INode } from '../../utils/interfaces'; const _worldPos = new Vec3(); @@ -199,20 +204,19 @@ export class CanvasComponent extends Component { const cameraNode = new Node('UICamera_' + this.node.name); cameraNode.setPosition(0, 0, 1000); if (!CC_EDITOR) { - this._camera = cc.director.root.ui.renderScene.createCamera({ + this._camera = director.root!.ui.renderScene.createCamera({ name: 'ui_' + this.node.name, - node: cameraNode, - projection: cc.CameraComponent.ProjectionType.ORTHO, + node: cameraNode as INode, + projection: CameraComponent.ProjectionType.ORTHO, priority: this._priority, isUI: true, - farClip: 2000, flows: ['UIFlow'], }); this._camera!.fov = 45; this._camera!.clearFlag = GFXClearFlag.COLOR | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL; - const device = cc.director.root.device; + const device = director.root!.device; this._camera!.resize(device.width, device.height); if (this._targetTexture) { const window = this._targetTexture.getGFXWindow(); @@ -222,15 +226,15 @@ export class CanvasComponent extends Component { } if (CC_EDITOR) { - cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); + director.on(Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); } - cc.view.on('design-resolution-changed', this._thisOnResized); + view.on('design-resolution-changed', this._thisOnResized); // this.applySettings(); this.alignWithScreen(); - cc.director.root.ui.addScreen(this); + director.root!.ui.addScreen(this); } // public onEnable (){ @@ -243,19 +247,19 @@ export class CanvasComponent extends Component { public onDestroy () { if (this._camera) { - cc.director.root.ui.renderScene.destroyCamera(this._camera); + director.root!.ui.renderScene.destroyCamera(this._camera); } if (CC_EDITOR) { - cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); + director.off(Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); } if (this._targetTexture) { this._targetTexture.off('resize'); } - cc.view.off('design-resolution-changed', this._thisOnResized); - cc.director.root.ui.removeScreen(this); + view.off('design-resolution-changed', this._thisOnResized); + director.root!.ui.removeScreen(this); // if (CanvasComponent.instance === this) { // CanvasComponent.instance = null; // } @@ -271,16 +275,16 @@ export class CanvasComponent extends Component { this.node.getPosition(this._pos); if (CC_EDITOR) { // nodeSize = designSize = cc.engine.getDesignResolutionSize(); - nodeSize = designSize = cc.view.getDesignResolutionSize(); + nodeSize = designSize = view.getDesignResolutionSize(); Vec3.set(_worldPos, designSize.width * 0.5, designSize.height * 0.5, 1); } else { - const canvasSize = cc.visibleRect; + const canvasSize = visibleRect; nodeSize = canvasSize; - designSize = cc.view.getDesignResolutionSize(); - const policy = cc.view.getResolutionPolicy(); + designSize = view.getDesignResolutionSize(); + const policy = view.getResolutionPolicy(); // const clipTopRight = !this.fitHeight && !this.fitWidth; - const clipTopRight = policy === cc.ResolutionPolicy.NO_BORDER; + const clipTopRight = policy === ResolutionPolicy.NO_BORDER; let offsetX = 0; let offsetY = 0; if (clipTopRight) { @@ -306,7 +310,7 @@ export class CanvasComponent extends Component { this.node.getWorldPosition(_worldPos); if (this._camera) { - const size = cc.view.getVisibleSize(); + const size = view.getVisibleSize(); this._camera.resize(size.width, size.height); this._camera.orthoHeight = this._camera.height / 2; this._camera.node.setPosition(_worldPos.x, _worldPos.y, 999); @@ -337,7 +341,7 @@ export class CanvasComponent extends Component { // // cc.engine.setDesignResolutionSize(designRes.width, designRes.height); // } // else { - // const root = cc.director.root; + // const root = director.root; // if (root && root.ui && root.ui.debugScreen && root.ui.debugScreen === this ){ // return; // } diff --git a/cocos/3d/assets/index.ts b/cocos/core/components/ui-base/index.ts similarity index 70% rename from cocos/3d/assets/index.ts rename to cocos/core/components/ui-base/index.ts index b352bc116b..bd089f0324 100644 --- a/cocos/3d/assets/index.ts +++ b/cocos/core/components/ui-base/index.ts @@ -1,10 +1,10 @@ /* - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. http://www.cocos.com Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the 'Software'), a limited, + of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license to use Cocos Creator solely to develop games on your target platforms. You shall not use Cocos Creator software for developing other software or tools that's @@ -14,7 +14,7 @@ The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + 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 @@ -23,12 +23,7 @@ THE SOFTWARE. */ -/** - * @hidden - */ -export { EffectAsset } from './effect-asset'; -export { Material } from './material'; -export { Mesh } from './mesh'; -export { Skeleton } from './skeleton'; - -export { PhysicsMaterial } from './physics/material'; +export * from './canvas-component'; +export * from './ui-component'; +export * from './ui-render-component'; +export * from './ui-transfrom-component'; \ No newline at end of file diff --git a/cocos/3d/ui/components/ui-component.ts b/cocos/core/components/ui-base/ui-component.ts similarity index 97% rename from cocos/3d/ui/components/ui-component.ts rename to cocos/core/components/ui-base/ui-component.ts index 3c2a151ae5..f39da6b946 100644 --- a/cocos/3d/ui/components/ui-component.ts +++ b/cocos/core/components/ui-base/ui-component.ts @@ -1,5 +1,5 @@ /* - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2017-2019 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -27,11 +27,11 @@ * @category ui */ -import { Component } from '../../../components'; +import { Component } from '../component'; import { ccclass, disallowMultiple, executeInEditMode, executionOrder, property } from '../../../core/data/class-decorator'; import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; import { INode } from '../../../core/utils/interfaces'; -import { UI } from '../../../renderer/ui/ui'; +import { UI } from '../../renderer/ui/ui'; import { CanvasComponent } from './canvas-component'; /** diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/core/components/ui-base/ui-render-component.ts similarity index 95% rename from cocos/3d/ui/components/ui-render-component.ts rename to cocos/core/components/ui-base/ui-render-component.ts index 10266739cf..297b9cb2dd 100644 --- a/cocos/3d/ui/components/ui-render-component.ts +++ b/cocos/core/components/ui-base/ui-render-component.ts @@ -1,5 +1,5 @@ /* - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2017-2019 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -37,14 +37,15 @@ import { import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; import { Color } from '../../../core/math'; import { ccenum } from '../../../core/value-types/enum'; -import { GFXBlendFactor } from '../../../gfx/define'; -import { RenderData } from '../../../renderer/ui/renderData'; -import { UI } from '../../../renderer/ui/ui'; +import { GFXBlendFactor } from '../../gfx/define'; +import { RenderData } from '../../renderer/ui/render-data'; +import { UI } from '../../renderer/ui/ui'; import { Material } from '../../assets'; -import { RenderableComponent } from '../../framework/renderable-component'; -import { IAssembler, IAssemblerManager } from '../assembler/base'; +import { RenderableComponent } from '../../../core/3d/framework/renderable-component'; +import { IAssembler, IAssemblerManager } from '../../renderer/ui/base'; import { UIComponent } from './ui-component'; import { UITransformComponent } from './ui-transfrom-component'; +import { director } from '../../director'; // hack ccenum(GFXBlendFactor); @@ -257,7 +258,7 @@ export class UIRenderComponent extends UIComponent { this.destroyRenderData(); if (this._material){ this._material.destroy(); - cc.director.root.ui._removeUIMaterial(this._material.hash); + director.root!.ui._removeUIMaterial(this._material.hash); } this._updateMaterial(null); diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/core/components/ui-base/ui-transfrom-component.ts similarity index 98% rename from cocos/3d/ui/components/ui-transfrom-component.ts rename to cocos/core/components/ui-base/ui-transfrom-component.ts index 8aa550343b..b841cc9bf1 100644 --- a/cocos/3d/ui/components/ui-transfrom-component.ts +++ b/cocos/core/components/ui-base/ui-transfrom-component.ts @@ -1,5 +1,5 @@ /* - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2017-2019 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -27,13 +27,14 @@ * @category ui */ -import { Component } from '../../../components'; +import { Component } from '../component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; import { EventListener, ILinstenerMask } from '../../../core/platform/event-manager/event-listener'; import { Mat4, Rect, Size, Vec2, Vec3 } from '../../../core/math'; import { aabb } from '../../geom-utils'; import { CanvasComponent } from './canvas-component'; +import { director } from '../../director'; const _vec2a = new Vec2(); const _vec2b = new Vec2(); @@ -304,7 +305,7 @@ export class UITransformComponent extends Component { visibility = renderComp.visibility; } - const canvas = cc.director.root.ui.getScreen(visibility); + const canvas = director.root!.ui.getScreen(visibility); if (!canvas) { return; } diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index a6c2bec12e..f59b5c48d4 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -35,7 +35,7 @@ // tslint:disable:jsdoc-format // tslint:disable:forin -import { errorID, warnID } from '../platform/CCDebug'; +import { errorID, warnID } from '../platform/debug'; import * as js from '../utils/js'; import { getSuper } from '../utils/js'; import { cloneable_DEV, isPlainEmptyObj_DEV } from '../utils/misc'; diff --git a/cocos/core/data/utils/attribute.ts b/cocos/core/data/utils/attribute.ts index b5dc3b11cc..5670beab13 100644 --- a/cocos/core/data/utils/attribute.ts +++ b/cocos/core/data/utils/attribute.ts @@ -27,7 +27,7 @@ // tslint:disable:only-arrow-functions // tslint:disable:one-variable-per-declaration -import { errorID, log, warnID } from '../../platform/CCDebug'; +import { errorID, log, warnID } from '../../platform/debug'; import { extend, formatStr, get, getClassName, isChildClassOf, value } from '../../utils/js'; import { isPlainEmptyObj_DEV } from '../../utils/misc'; diff --git a/cocos/core/data/utils/preprocess-class.ts b/cocos/core/data/utils/preprocess-class.ts index b4935c5dd7..de4eeb171d 100644 --- a/cocos/core/data/utils/preprocess-class.ts +++ b/cocos/core/data/utils/preprocess-class.ts @@ -24,7 +24,7 @@ THE SOFTWARE. */ -import { error, errorID, warn, warnID } from '../../platform/CCDebug'; +import { error, errorID, warn, warnID } from '../../platform/debug'; import * as js from '../../utils/js'; import { PrimitiveType } from './attribute'; diff --git a/cocos/core/director.ts b/cocos/core/director.ts index b4ccd73be3..14b53638b1 100644 --- a/cocos/core/director.ts +++ b/cocos/core/director.ts @@ -28,20 +28,18 @@ * @category core */ -import { widgetManager } from '../3d/ui/components/widget-manager'; -// import SkinningModelSystem from '../3d/framework/skinning-model-system'; -import { PhysicsSystem } from '../3d/framework/physics/physics-system'; -import { autoRelease } from '../load-pipeline/auto-release-utils'; -import { Scene, Node } from '../scene-graph'; -import ComponentScheduler from '../scene-graph/component-scheduler'; -import NodeActivator from '../scene-graph/node-activator'; +import { autoRelease } from './load-pipeline/auto-release-utils'; +import { Scene, Node } from './scene-graph'; +import ComponentScheduler from './scene-graph/component-scheduler'; +import NodeActivator from './scene-graph/node-activator'; import { CCObject } from './data/object'; import { EventTarget } from './event/event-target'; import { Game } from './game'; import eventManager from './platform/event-manager/event-manager'; import { Root } from './root'; -import Scheduler from './scheduler'; -import { getClassByName } from './utils/js'; +import { Scheduler } from './scheduler'; +import System from './components/system'; +import { js } from './utils'; // const ComponentScheduler = require('./component-scheduler'); // const NodeActivator = require('./node-activator'); @@ -118,10 +116,36 @@ import { getClassByName } from './utils/js'; */ export class Director extends EventTarget { + /** + * @en The event which will be triggered when the singleton of Director initialized. + * @zh Director 单例初始化时触发的事件 + * @event Director.EVENT_INIT + */ + /** + * @en The event which will be triggered when the singleton of Director initialized. + * @zh Director 单例初始化时触发的事件 + * @property {String} EVENT_INIT + * @readonly + */ + public static readonly EVENT_INIT = 'director_init'; + + /** + * @en The event which will be triggered when the singleton of Director reset. + * @zh Director 单例重置时触发的事件 + * @event Director.EVENT_RESET + */ + /** + * @en The event which will be triggered when the singleton of Director reset. + * @zh Director 单例重置时触发的事件 + * @property {String} EVENT_RESET + * @readonly + */ + public static readonly EVENT_RESET = 'director_reset'; + /** * @en The event which will be triggered before loading a new scene. * @zh 加载新场景之前所触发的事件。 - * @event cc.Director.EVENT_BEFORE_SCENE_LOADING + * @event Director.EVENT_BEFORE_SCENE_LOADING * @param {String} sceneName - The loading scene name */ /** @@ -132,12 +156,12 @@ export class Director extends EventTarget { */ public static readonly EVENT_BEFORE_SCENE_LOADING = 'director_before_scene_loading'; - /* - * @en The event which will be triggered before launching a new scene. - * @zh 运行新场景之前所触发的事件。 - * @event cc.Director.EVENT_BEFORE_SCENE_LAUNCH - * @param {String} sceneName - New scene which will be launched - */ + /** + * @en The event which will be triggered before launching a new scene. + * @zh 运行新场景之前所触发的事件。 + * @event Director.EVENT_BEFORE_SCENE_LAUNCH + * @param {String} sceneName - New scene which will be launched + */ /** * @en The event which will be triggered before launching a new scene. * @zh 运行新场景之前所触发的事件。 @@ -149,7 +173,7 @@ export class Director extends EventTarget { /** * @en The event which will be triggered after launching a new scene. * @zh 运行新场景之后所触发的事件。 - * @event cc.Director.EVENT_AFTER_SCENE_LAUNCH + * @event Director.EVENT_AFTER_SCENE_LAUNCH * @param {String} sceneName - New scene which is launched */ /** @@ -163,7 +187,7 @@ export class Director extends EventTarget { /** * @en The event which will be triggered at the beginning of every frame. * @zh 每个帧的开始时所触发的事件。 - * @event cc.Director.EVENT_BEFORE_UPDATE + * @event Director.EVENT_BEFORE_UPDATE */ /** * @en The event which will be triggered at the beginning of every frame. @@ -176,7 +200,7 @@ export class Director extends EventTarget { /** * @en The event which will be triggered after engine and components update logic. * @zh 将在引擎和组件 “update” 逻辑之后所触发的事件。 - * @event cc.Director.EVENT_AFTER_UPDATE + * @event Director.EVENT_AFTER_UPDATE */ /** * @en The event which will be triggered after engine and components update logic. @@ -189,7 +213,7 @@ export class Director extends EventTarget { /** * @en The event which will be triggered before the rendering process. * @zh 渲染过程之前所触发的事件。 - * @event cc.Director.EVENT_BEFORE_DRAW + * @event Director.EVENT_BEFORE_DRAW */ /** * @en The event which will be triggered before the rendering process. @@ -202,7 +226,7 @@ export class Director extends EventTarget { /** * @en The event which will be triggered after the rendering process. * @zh 渲染过程之后所触发的事件。 - * @event cc.Director.EVENT_AFTER_DRAW + * @event Director.EVENT_AFTER_DRAW */ /** * @en The event which will be triggered after the rendering process. @@ -215,7 +239,7 @@ export class Director extends EventTarget { /** * @en The event which will be triggered before the physics process. * @zh 物理过程之前所触发的事件。 - * @event cc.Director.EVENT_BEFORE_PHYSICS + * @event Director.EVENT_BEFORE_PHYSICS * @readonly */ public static readonly EVENT_BEFORE_PHYSICS = 'director_before_physics'; @@ -223,11 +247,15 @@ export class Director extends EventTarget { /** * @en The event which will be triggered after the physics process. * @zh 物理过程之后所触发的事件。 - * @event cc.Director.EVENT_AFTER_PHYSICS + * @event Director.EVENT_AFTER_PHYSICS * @readonly */ public static readonly EVENT_AFTER_PHYSICS = 'director_after_physics'; + public static instance: Director; + + public _compScheduler: ComponentScheduler; + public _nodeActivator: NodeActivator; private invalid: boolean; private _paused: boolean; private _purgeDirectorInNextLoop: boolean; @@ -238,11 +266,7 @@ export class Director extends EventTarget { private _lastUpdate: number; private _deltaTime: number; private _scheduler: Scheduler; - private _compScheduler: ComponentScheduler; - private _nodeActivator: NodeActivator; - private _physicsSystem: PhysicsSystem | null; - private _systems: any[]; - private _animationManager: any; + private _systems: System[]; constructor () { super(); @@ -272,11 +296,6 @@ export class Director extends EventTarget { // Node activator this._nodeActivator = new NodeActivator(); - /** - * @type {PhysicsSystem} - */ - this._physicsSystem = null; - this._systems = []; const self = this; @@ -288,13 +307,23 @@ export class Director extends EventTarget { } public init () { - this._totalFrames = 0; this._lastUpdate = performance.now(); this._paused = false; this._purgeDirectorInNextLoop = false; - this.sharedInit(); + cc.loader.init(this); + + // Event manager + if (eventManager) { + eventManager.setEnabled(true); + } + + // Scheduler + // TODO: have a solid organization of priority and expose to user + this.registerSystem(Scheduler.ID, this._scheduler, 200); + + this.emit(Director.EVENT_INIT); this._root = new Root(cc.game._gfxDevice); const rootInfo = {}; @@ -305,50 +334,6 @@ export class Director extends EventTarget { return true; } - /* - * Manage all init process shared between the web engine and jsb engine. - * All platform independent init process should be occupied here. - */ - public sharedInit () { - - // Event manager - if (eventManager) { - eventManager.setEnabled(true); - } - - // Animation manager - if (cc.AnimationManager) { - this._animationManager = new cc.AnimationManager(); - this._scheduler.scheduleUpdate(this._animationManager, Scheduler.PRIORITY_SYSTEM, false); - } - else { - this._animationManager = null; - } - - // widgetManager - if (widgetManager) { - widgetManager.init(this); - } - - // this.registerSystem('animation', AnimationSystem, ['AnimationComponent'], 200); - // this.registerSystem('skinning-model', SkinningModelSystem, ['SkinningModelComponent'], 100); - // init renderSystem - /* - { - this._renderSystem = new RenderSystem(); - let renderComps = ['cc.CameraComponent']; - renderComps.forEach((compName) => { - getClassByName(compName).system = this._renderSystem; - }); - } - */ - if (CC_PHYSICS_BUILT_IN || CC_PHYSICS_CANNON || CC_PHYSICS_AMMO) { - this._physicsSystem = new cc.PhysicsSystem(); - } - - cc.loader.init(this); - } - /** * calculates delta time since last time it was called */ @@ -515,20 +500,13 @@ export class Director extends EventTarget { */ public reset () { this.purgeDirector(); + + this.emit(Director.EVENT_RESET); if (eventManager) { eventManager.setEnabled(true); } - // Animation manager - if (this._animationManager) { - this._scheduler.scheduleUpdate(this._animationManager, cc.Scheduler.PRIORITY_SYSTEM, false); - } - - this._systems.forEach((sys) => { - this._scheduler.scheduleUpdate(sys, sys._priority, false); - }); - this.startAnimation(); } @@ -787,7 +765,7 @@ export class Director extends EventTarget { console.time('LoadScene ' + uuid); cc.AssetLibrary.loadAsset(uuid, (error, sceneAsset) => { console.timeEnd('LoadScene ' + uuid); - const self = cc.director; + const self = director; self._loadingScene = ''; if (error) { error = 'Failed to load scene: ' + error; @@ -899,7 +877,7 @@ export class Director extends EventTarget { * cc.director.getScene().getChildByName('Canvas'); * ``` */ - public getScene () { + public getScene (): Scene | null { return this._scene; } @@ -971,7 +949,9 @@ export class Director extends EventTarget { */ public setScheduler (scheduler: Scheduler) { if (this._scheduler !== scheduler) { + this.unregisterSystem(this._scheduler); this._scheduler = scheduler; + this.registerSystem(Scheduler.ID, scheduler, 200); } } @@ -979,17 +959,17 @@ export class Director extends EventTarget { * @en register a system. * @zh 注册一个 system。 */ - public registerSystem (name, cls, compClsNames, priority) { - const sys = new cls(); - sys._id = name; - sys._priority = priority; - compClsNames.forEach((compName) => { - getClassByName(compName).system = sys; - }); - this._scheduler.scheduleUpdate(sys, priority, false); + public registerSystem (name: string, sys: System, priority: number) { + sys.id = name; + sys.priority = priority; sys.init(); this._systems.push(sys); - return sys; + this._systems.sort(System.sortByPriority); + } + + public unregisterSystem (sys: System) { + js.array.fastRemove(this._systems, sys); + this._systems.sort(System.sortByPriority); } /** @@ -998,16 +978,17 @@ export class Director extends EventTarget { */ public getSystem (name) { return this._systems.find((sys) => { - return sys._id === name; + return sys.id === name; }); } /** - * @en Returns the cc.AnimationManager associated with this director. - * @zh 获取和 director 相关联的 cc.AnimationManager(动画管理器)。 + * @en Returns the cc.AnimationManager associated with this director. Please use getSystem(AnimationManager.ID) + * @zh 获取和 director 相关联的 cc.AnimationManager(动画管理器)。请使用 getSystem(AnimationManager.ID) 来替代 + * @deprecated */ - public getAnimationManager () { - return this._animationManager; + public getAnimationManager ():any { + return this.getSystem(cc.AnimationManager.ID); } // Loop management @@ -1040,6 +1021,7 @@ export class Director extends EventTarget { else if (!this.invalid) { // calculate "global" dt this.calculateDeltaTime(); + let dt = this._deltaTime; // Update if (!this._paused) { @@ -1047,42 +1029,35 @@ export class Director extends EventTarget { // Call start for new added components this._compScheduler.startPhase(); // Update for components - this._compScheduler.updatePhase(this._deltaTime); - // Engine update with scheduler - this._scheduler.update(this._deltaTime); + this._compScheduler.updatePhase(dt); + // Update systems + for (let i = 0; i < this._systems.length; ++i) { + this._systems[i].update(dt); + } // Late update for components - this._compScheduler.lateUpdatePhase(this._deltaTime); + this._compScheduler.lateUpdatePhase(dt); // User can use this event to do things after update this.emit(Director.EVENT_AFTER_UPDATE); // Destroy entities that have been removed recently CCObject._deferredDestroy(); - if (!CC_EDITOR) { - if (window.TWEEN != null) { - // Tween update - window.TWEEN.update(time); - } + // Post update systems + for (let i = 0; i < this._systems.length; ++i) { + this._systems[i].postUpdate(dt); } - - if (CC_PHYSICS_BUILT_IN || CC_PHYSICS_CANNON || CC_PHYSICS_AMMO) { - this.emit(Director.EVENT_BEFORE_PHYSICS); - this._physicsSystem!.update(this._deltaTime); - this.emit(Director.EVENT_AFTER_PHYSICS); - } - - this.emit(Director.EVENT_BEFORE_DRAW); - this._root!.frameMove(this._deltaTime); - // Present current frame - this._root!.device.present(); - this.emit(Director.EVENT_AFTER_DRAW); } + this.emit(Director.EVENT_BEFORE_DRAW); + this._root!.frameMove(this._deltaTime); + // Present current frame + this._root!.device.present(); + this.emit(Director.EVENT_AFTER_DRAW); + eventManager.frameUpdateListeners(); Node.bookOfChange.clear(); this._totalFrames++; } } - } cc.Director = Director; @@ -1091,5 +1066,4 @@ cc.Director = Director; * 导演类。 * @property director */ -export const director: Director = new Director(); -cc.director = director; +export const director: Director = Director.instance = cc.director = new Director(); diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index 9c34804e0f..b85d24e7ce 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -28,7 +28,7 @@ * @hidden */ -import Pool from '../../3d/memop/pool'; +import Pool from '../memop/pool'; import { array, createMap } from '../utils/js'; const fastRemoveAt = array.fastRemoveAt; diff --git a/cocos/core/game.ts b/cocos/core/game.ts index c8fdb11814..762f2fb6f9 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -27,10 +27,10 @@ * @category core */ -import { WebGLGFXDevice } from '../gfx/webgl/webgl-device'; -import { WebGL2GFXDevice } from '../gfx/webgl2/webgl2-device'; +import { WebGLGFXDevice } from './gfx/webgl/webgl-device'; +import { WebGL2GFXDevice } from './gfx/webgl2/webgl2-device'; import { EventTarget } from './event/event-target'; -import * as debug from './platform/CCDebug'; +import * as debug from './platform/debug'; import inputManager from './platform/event-manager/input-manager'; /** @@ -39,7 +39,6 @@ import inputManager from './platform/event-manager/input-manager'; * @class game * @static */ - export class Game extends EventTarget { /** * @en Event triggered when game hide to background.
@@ -890,6 +889,4 @@ export class Game extends EventTarget { } cc.Game = Game; - -export const game: Game = new Game(); -cc.game = game; +export const game = cc.game = new Game(); diff --git a/cocos/3d/geom-utils/aabb.ts b/cocos/core/geom-utils/aabb.ts similarity index 100% rename from cocos/3d/geom-utils/aabb.ts rename to cocos/core/geom-utils/aabb.ts diff --git a/cocos/3d/geom-utils/curve.ts b/cocos/core/geom-utils/curve.ts similarity index 100% rename from cocos/3d/geom-utils/curve.ts rename to cocos/core/geom-utils/curve.ts diff --git a/cocos/3d/geom-utils/deprecated.ts b/cocos/core/geom-utils/deprecated.ts similarity index 75% rename from cocos/3d/geom-utils/deprecated.ts rename to cocos/core/geom-utils/deprecated.ts index d287f77556..1a69ec01ad 100644 --- a/cocos/3d/geom-utils/deprecated.ts +++ b/cocos/core/geom-utils/deprecated.ts @@ -1,18 +1,18 @@ -/** - * @hidden - */ - -import { replaceProperty } from '../../deprecated'; -import line from './line'; - - -replaceProperty(line.prototype, 'line', [ - { - 'name': 'mag', - 'newName': 'len' - }, - { - 'name': 'magnitude', - 'newName': 'len' - } +/** + * @hidden + */ + +import { replaceProperty } from '../utils/deprecated'; +import line from './line'; + + +replaceProperty(line.prototype, 'line', [ + { + 'name': 'mag', + 'newName': 'len' + }, + { + 'name': 'magnitude', + 'newName': 'len' + } ]); \ No newline at end of file diff --git a/cocos/3d/geom-utils/distance.ts b/cocos/core/geom-utils/distance.ts similarity index 97% rename from cocos/3d/geom-utils/distance.ts rename to cocos/core/geom-utils/distance.ts index 48b208ce32..f89fa00599 100644 --- a/cocos/3d/geom-utils/distance.ts +++ b/cocos/core/geom-utils/distance.ts @@ -2,8 +2,8 @@ * @category gemotry-utils */ -import { plane } from '.'; -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; +import plane from './plane'; import aabb from './aabb'; import obb from './obb'; const X = new Vec3(); diff --git a/cocos/3d/geom-utils/enums.ts b/cocos/core/geom-utils/enums.ts similarity index 100% rename from cocos/3d/geom-utils/enums.ts rename to cocos/core/geom-utils/enums.ts diff --git a/cocos/3d/geom-utils/frustum.ts b/cocos/core/geom-utils/frustum.ts similarity index 99% rename from cocos/3d/geom-utils/frustum.ts rename to cocos/core/geom-utils/frustum.ts index be867c24ea..4367550a7f 100644 --- a/cocos/3d/geom-utils/frustum.ts +++ b/cocos/core/geom-utils/frustum.ts @@ -2,7 +2,7 @@ * @category gemotry-utils */ -import { Mat4, Vec3 } from '../../core/math'; +import { Mat4, Vec3 } from '../math'; import enums from './enums'; import plane from './plane'; diff --git a/cocos/3d/geom-utils/index.ts b/cocos/core/geom-utils/index.ts similarity index 96% rename from cocos/3d/geom-utils/index.ts rename to cocos/core/geom-utils/index.ts index c49f474614..cd7e7997d6 100644 --- a/cocos/3d/geom-utils/index.ts +++ b/cocos/core/geom-utils/index.ts @@ -17,4 +17,4 @@ export { frustum } from './frustum'; export { default as Octree } from './octree'; export { Keyframe, AnimationCurve } from './curve'; -import './deprecated'; +import './deprecated'; diff --git a/cocos/3d/geom-utils/intersect.ts b/cocos/core/geom-utils/intersect.ts similarity index 99% rename from cocos/3d/geom-utils/intersect.ts rename to cocos/core/geom-utils/intersect.ts index d36dc1420f..a015205444 100644 --- a/cocos/3d/geom-utils/intersect.ts +++ b/cocos/core/geom-utils/intersect.ts @@ -3,7 +3,7 @@ * @category gemotry-utils */ -import { Mat3, Vec3 } from '../../core/math'; +import { Mat3, Vec3 } from '../math'; import aabb from './aabb'; import * as distance from './distance'; import enums from './enums'; diff --git a/cocos/3d/geom-utils/line.ts b/cocos/core/geom-utils/line.ts similarity index 98% rename from cocos/3d/geom-utils/line.ts rename to cocos/core/geom-utils/line.ts index 32bf543925..899cb182b9 100644 --- a/cocos/3d/geom-utils/line.ts +++ b/cocos/core/geom-utils/line.ts @@ -2,7 +2,7 @@ * @category gemotry-utils */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; import enums from './enums'; /** diff --git a/cocos/3d/geom-utils/obb.ts b/cocos/core/geom-utils/obb.ts similarity index 99% rename from cocos/3d/geom-utils/obb.ts rename to cocos/core/geom-utils/obb.ts index ec225e98d4..a927c3ea86 100644 --- a/cocos/3d/geom-utils/obb.ts +++ b/cocos/core/geom-utils/obb.ts @@ -2,7 +2,7 @@ * @category gemotry-utils */ -import { Mat3, Mat4, Quat, Vec3 } from '../../core/math'; +import { Mat3, Mat4, Quat, Vec3 } from '../math'; import enums from './enums'; const _v3_tmp = new Vec3(); diff --git a/cocos/3d/geom-utils/octree.ts b/cocos/core/geom-utils/octree.ts similarity index 99% rename from cocos/3d/geom-utils/octree.ts rename to cocos/core/geom-utils/octree.ts index 84f19a53d9..d65e90d3a3 100644 --- a/cocos/3d/geom-utils/octree.ts +++ b/cocos/core/geom-utils/octree.ts @@ -2,7 +2,7 @@ * @category gemotry-utils */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; import { FixedArray } from '../memop'; import aabb from './aabb'; import intersect from './intersect'; diff --git a/cocos/3d/geom-utils/plane.ts b/cocos/core/geom-utils/plane.ts similarity index 98% rename from cocos/3d/geom-utils/plane.ts rename to cocos/core/geom-utils/plane.ts index ba62d5e744..32158899c9 100644 --- a/cocos/3d/geom-utils/plane.ts +++ b/cocos/core/geom-utils/plane.ts @@ -2,7 +2,7 @@ * @category gemotry-utils */ -import { Mat4, Vec3, Vec4 } from '../../core/math'; +import { Mat4, Vec3, Vec4 } from '../math'; import enums from './enums'; const v1 = new Vec3(0, 0, 0); diff --git a/cocos/3d/geom-utils/ray.ts b/cocos/core/geom-utils/ray.ts similarity index 98% rename from cocos/3d/geom-utils/ray.ts rename to cocos/core/geom-utils/ray.ts index c6f644a166..133d67bf71 100644 --- a/cocos/3d/geom-utils/ray.ts +++ b/cocos/core/geom-utils/ray.ts @@ -2,7 +2,7 @@ * @category gemotry-utils */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; import enums from './enums'; /** diff --git a/cocos/3d/geom-utils/sphere.ts b/cocos/core/geom-utils/sphere.ts similarity index 99% rename from cocos/3d/geom-utils/sphere.ts rename to cocos/core/geom-utils/sphere.ts index bfbea35cd7..0ef7a5b442 100644 --- a/cocos/3d/geom-utils/sphere.ts +++ b/cocos/core/geom-utils/sphere.ts @@ -2,7 +2,7 @@ * @category gemotry-utils */ -import { Mat4, Quat, Vec3 } from '../../core/math'; +import { Mat4, Quat, Vec3 } from '../math'; import enums from './enums'; const _v3_tmp = new Vec3(); diff --git a/cocos/3d/geom-utils/triangle.ts b/cocos/core/geom-utils/triangle.ts similarity index 99% rename from cocos/3d/geom-utils/triangle.ts rename to cocos/core/geom-utils/triangle.ts index d22d35a1cd..ef8ef9f01e 100644 --- a/cocos/3d/geom-utils/triangle.ts +++ b/cocos/core/geom-utils/triangle.ts @@ -2,7 +2,7 @@ * @category gemotry-utils */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; import enums from './enums'; /** diff --git a/cocos/gfx/binding-layout.ts b/cocos/core/gfx/binding-layout.ts similarity index 100% rename from cocos/gfx/binding-layout.ts rename to cocos/core/gfx/binding-layout.ts diff --git a/cocos/gfx/buffer.ts b/cocos/core/gfx/buffer.ts similarity index 100% rename from cocos/gfx/buffer.ts rename to cocos/core/gfx/buffer.ts diff --git a/cocos/gfx/command-allocator.ts b/cocos/core/gfx/command-allocator.ts similarity index 100% rename from cocos/gfx/command-allocator.ts rename to cocos/core/gfx/command-allocator.ts diff --git a/cocos/gfx/command-buffer.ts b/cocos/core/gfx/command-buffer.ts similarity index 100% rename from cocos/gfx/command-buffer.ts rename to cocos/core/gfx/command-buffer.ts diff --git a/cocos/gfx/define.ts b/cocos/core/gfx/define.ts similarity index 100% rename from cocos/gfx/define.ts rename to cocos/core/gfx/define.ts diff --git a/cocos/gfx/device.ts b/cocos/core/gfx/device.ts similarity index 99% rename from cocos/gfx/device.ts rename to cocos/core/gfx/device.ts index b4f7773f7a..b376da3269 100644 --- a/cocos/gfx/device.ts +++ b/cocos/core/gfx/device.ts @@ -2,7 +2,7 @@ * @category gfx */ -import { ccenum } from '../core/value-types/enum'; +import { ccenum } from '../value-types/enum'; import { GFXBindingLayout, IGFXBindingLayoutInfo } from './binding-layout'; import { GFXBuffer, IGFXBufferInfo } from './buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from './command-allocator'; diff --git a/cocos/gfx/framebuffer.ts b/cocos/core/gfx/framebuffer.ts similarity index 100% rename from cocos/gfx/framebuffer.ts rename to cocos/core/gfx/framebuffer.ts diff --git a/cocos/gfx/index.ts b/cocos/core/gfx/index.ts similarity index 100% rename from cocos/gfx/index.ts rename to cocos/core/gfx/index.ts diff --git a/cocos/gfx/input-assembler.ts b/cocos/core/gfx/input-assembler.ts similarity index 100% rename from cocos/gfx/input-assembler.ts rename to cocos/core/gfx/input-assembler.ts diff --git a/cocos/gfx/pipeline-layout.ts b/cocos/core/gfx/pipeline-layout.ts similarity index 100% rename from cocos/gfx/pipeline-layout.ts rename to cocos/core/gfx/pipeline-layout.ts diff --git a/cocos/gfx/pipeline-state.ts b/cocos/core/gfx/pipeline-state.ts similarity index 100% rename from cocos/gfx/pipeline-state.ts rename to cocos/core/gfx/pipeline-state.ts diff --git a/cocos/gfx/queue.ts b/cocos/core/gfx/queue.ts similarity index 100% rename from cocos/gfx/queue.ts rename to cocos/core/gfx/queue.ts diff --git a/cocos/gfx/render-pass.ts b/cocos/core/gfx/render-pass.ts similarity index 100% rename from cocos/gfx/render-pass.ts rename to cocos/core/gfx/render-pass.ts diff --git a/cocos/gfx/sampler.ts b/cocos/core/gfx/sampler.ts similarity index 100% rename from cocos/gfx/sampler.ts rename to cocos/core/gfx/sampler.ts diff --git a/cocos/gfx/shader.ts b/cocos/core/gfx/shader.ts similarity index 100% rename from cocos/gfx/shader.ts rename to cocos/core/gfx/shader.ts diff --git a/cocos/gfx/texture-view.ts b/cocos/core/gfx/texture-view.ts similarity index 100% rename from cocos/gfx/texture-view.ts rename to cocos/core/gfx/texture-view.ts diff --git a/cocos/gfx/texture.ts b/cocos/core/gfx/texture.ts similarity index 100% rename from cocos/gfx/texture.ts rename to cocos/core/gfx/texture.ts diff --git a/cocos/gfx/webgl/WebGL.d.ts b/cocos/core/gfx/webgl/WebGL.d.ts similarity index 100% rename from cocos/gfx/webgl/WebGL.d.ts rename to cocos/core/gfx/webgl/WebGL.d.ts diff --git a/cocos/gfx/webgl/webgl-binding-layout.ts b/cocos/core/gfx/webgl/webgl-binding-layout.ts similarity index 100% rename from cocos/gfx/webgl/webgl-binding-layout.ts rename to cocos/core/gfx/webgl/webgl-binding-layout.ts diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/core/gfx/webgl/webgl-buffer.ts similarity index 100% rename from cocos/gfx/webgl/webgl-buffer.ts rename to cocos/core/gfx/webgl/webgl-buffer.ts diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/core/gfx/webgl/webgl-command-allocator.ts similarity index 98% rename from cocos/gfx/webgl/webgl-command-allocator.ts rename to cocos/core/gfx/webgl/webgl-command-allocator.ts index ca92cfaaec..a96c4e17b9 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/core/gfx/webgl/webgl-command-allocator.ts @@ -1,4 +1,4 @@ -import { CachedArray } from '../../core/memop/cached-array'; +import { CachedArray } from '../../memop/cached-array'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/core/gfx/webgl/webgl-command-buffer.ts similarity index 100% rename from cocos/gfx/webgl/webgl-command-buffer.ts rename to cocos/core/gfx/webgl/webgl-command-buffer.ts diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts similarity index 99% rename from cocos/gfx/webgl/webgl-commands.ts rename to cocos/core/gfx/webgl/webgl-commands.ts index 91a6424276..519df7933d 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -1,4 +1,4 @@ -import { CachedArray } from '../../core/memop/cached-array'; +import { CachedArray } from '../../memop/cached-array'; import { GFXBufferSource, IGFXDrawInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXBindingType, diff --git a/cocos/gfx/webgl/webgl-define.ts b/cocos/core/gfx/webgl/webgl-define.ts similarity index 100% rename from cocos/gfx/webgl/webgl-define.ts rename to cocos/core/gfx/webgl/webgl-define.ts diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/core/gfx/webgl/webgl-device.ts similarity index 100% rename from cocos/gfx/webgl/webgl-device.ts rename to cocos/core/gfx/webgl/webgl-device.ts diff --git a/cocos/gfx/webgl/webgl-framebuffer.ts b/cocos/core/gfx/webgl/webgl-framebuffer.ts similarity index 100% rename from cocos/gfx/webgl/webgl-framebuffer.ts rename to cocos/core/gfx/webgl/webgl-framebuffer.ts diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/core/gfx/webgl/webgl-gpu-objects.ts similarity index 100% rename from cocos/gfx/webgl/webgl-gpu-objects.ts rename to cocos/core/gfx/webgl/webgl-gpu-objects.ts diff --git a/cocos/gfx/webgl/webgl-input-assembler.ts b/cocos/core/gfx/webgl/webgl-input-assembler.ts similarity index 100% rename from cocos/gfx/webgl/webgl-input-assembler.ts rename to cocos/core/gfx/webgl/webgl-input-assembler.ts diff --git a/cocos/gfx/webgl/webgl-pipeline-layout.ts b/cocos/core/gfx/webgl/webgl-pipeline-layout.ts similarity index 100% rename from cocos/gfx/webgl/webgl-pipeline-layout.ts rename to cocos/core/gfx/webgl/webgl-pipeline-layout.ts diff --git a/cocos/gfx/webgl/webgl-pipeline-state.ts b/cocos/core/gfx/webgl/webgl-pipeline-state.ts similarity index 100% rename from cocos/gfx/webgl/webgl-pipeline-state.ts rename to cocos/core/gfx/webgl/webgl-pipeline-state.ts diff --git a/cocos/gfx/webgl/webgl-queue.ts b/cocos/core/gfx/webgl/webgl-queue.ts similarity index 100% rename from cocos/gfx/webgl/webgl-queue.ts rename to cocos/core/gfx/webgl/webgl-queue.ts diff --git a/cocos/gfx/webgl/webgl-render-pass.ts b/cocos/core/gfx/webgl/webgl-render-pass.ts similarity index 100% rename from cocos/gfx/webgl/webgl-render-pass.ts rename to cocos/core/gfx/webgl/webgl-render-pass.ts diff --git a/cocos/gfx/webgl/webgl-sampler.ts b/cocos/core/gfx/webgl/webgl-sampler.ts similarity index 100% rename from cocos/gfx/webgl/webgl-sampler.ts rename to cocos/core/gfx/webgl/webgl-sampler.ts diff --git a/cocos/gfx/webgl/webgl-shader.ts b/cocos/core/gfx/webgl/webgl-shader.ts similarity index 100% rename from cocos/gfx/webgl/webgl-shader.ts rename to cocos/core/gfx/webgl/webgl-shader.ts diff --git a/cocos/gfx/webgl/webgl-state-cache.ts b/cocos/core/gfx/webgl/webgl-state-cache.ts similarity index 100% rename from cocos/gfx/webgl/webgl-state-cache.ts rename to cocos/core/gfx/webgl/webgl-state-cache.ts diff --git a/cocos/gfx/webgl/webgl-texture-view.ts b/cocos/core/gfx/webgl/webgl-texture-view.ts similarity index 100% rename from cocos/gfx/webgl/webgl-texture-view.ts rename to cocos/core/gfx/webgl/webgl-texture-view.ts diff --git a/cocos/gfx/webgl/webgl-texture.ts b/cocos/core/gfx/webgl/webgl-texture.ts similarity index 100% rename from cocos/gfx/webgl/webgl-texture.ts rename to cocos/core/gfx/webgl/webgl-texture.ts diff --git a/cocos/gfx/webgl/webgl-window.ts b/cocos/core/gfx/webgl/webgl-window.ts similarity index 100% rename from cocos/gfx/webgl/webgl-window.ts rename to cocos/core/gfx/webgl/webgl-window.ts diff --git a/cocos/gfx/webgl2/WebGL2.d.ts b/cocos/core/gfx/webgl2/WebGL2.d.ts similarity index 100% rename from cocos/gfx/webgl2/WebGL2.d.ts rename to cocos/core/gfx/webgl2/WebGL2.d.ts diff --git a/cocos/gfx/webgl2/webgl2-binding-layout.ts b/cocos/core/gfx/webgl2/webgl2-binding-layout.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-binding-layout.ts rename to cocos/core/gfx/webgl2/webgl2-binding-layout.ts diff --git a/cocos/gfx/webgl2/webgl2-buffer.ts b/cocos/core/gfx/webgl2/webgl2-buffer.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-buffer.ts rename to cocos/core/gfx/webgl2/webgl2-buffer.ts diff --git a/cocos/gfx/webgl2/webgl2-command-allocator.ts b/cocos/core/gfx/webgl2/webgl2-command-allocator.ts similarity index 98% rename from cocos/gfx/webgl2/webgl2-command-allocator.ts rename to cocos/core/gfx/webgl2/webgl2-command-allocator.ts index 736683cd18..740856db25 100644 --- a/cocos/gfx/webgl2/webgl2-command-allocator.ts +++ b/cocos/core/gfx/webgl2/webgl2-command-allocator.ts @@ -1,4 +1,4 @@ -import { CachedArray } from '../../core/memop/cached-array'; +import { CachedArray } from '../../memop/cached-array'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; diff --git a/cocos/gfx/webgl2/webgl2-command-buffer.ts b/cocos/core/gfx/webgl2/webgl2-command-buffer.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-command-buffer.ts rename to cocos/core/gfx/webgl2/webgl2-command-buffer.ts diff --git a/cocos/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts similarity index 99% rename from cocos/gfx/webgl2/webgl2-commands.ts rename to cocos/core/gfx/webgl2/webgl2-commands.ts index d006583fb0..bf3eba0dfc 100644 --- a/cocos/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -1,4 +1,4 @@ -import { CachedArray } from '../../core/memop/cached-array'; +import { CachedArray } from '../../memop/cached-array'; import { GFXBufferSource, IGFXDrawInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXBindingType, diff --git a/cocos/gfx/webgl2/webgl2-device.ts b/cocos/core/gfx/webgl2/webgl2-device.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-device.ts rename to cocos/core/gfx/webgl2/webgl2-device.ts diff --git a/cocos/gfx/webgl2/webgl2-framebuffer.ts b/cocos/core/gfx/webgl2/webgl2-framebuffer.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-framebuffer.ts rename to cocos/core/gfx/webgl2/webgl2-framebuffer.ts diff --git a/cocos/gfx/webgl2/webgl2-gpu-objects.ts b/cocos/core/gfx/webgl2/webgl2-gpu-objects.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-gpu-objects.ts rename to cocos/core/gfx/webgl2/webgl2-gpu-objects.ts diff --git a/cocos/gfx/webgl2/webgl2-input-assembler.ts b/cocos/core/gfx/webgl2/webgl2-input-assembler.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-input-assembler.ts rename to cocos/core/gfx/webgl2/webgl2-input-assembler.ts diff --git a/cocos/gfx/webgl2/webgl2-pipeline-layout.ts b/cocos/core/gfx/webgl2/webgl2-pipeline-layout.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-pipeline-layout.ts rename to cocos/core/gfx/webgl2/webgl2-pipeline-layout.ts diff --git a/cocos/gfx/webgl2/webgl2-pipeline-state.ts b/cocos/core/gfx/webgl2/webgl2-pipeline-state.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-pipeline-state.ts rename to cocos/core/gfx/webgl2/webgl2-pipeline-state.ts diff --git a/cocos/gfx/webgl2/webgl2-queue.ts b/cocos/core/gfx/webgl2/webgl2-queue.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-queue.ts rename to cocos/core/gfx/webgl2/webgl2-queue.ts diff --git a/cocos/gfx/webgl2/webgl2-render-pass.ts b/cocos/core/gfx/webgl2/webgl2-render-pass.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-render-pass.ts rename to cocos/core/gfx/webgl2/webgl2-render-pass.ts diff --git a/cocos/gfx/webgl2/webgl2-sampler.ts b/cocos/core/gfx/webgl2/webgl2-sampler.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-sampler.ts rename to cocos/core/gfx/webgl2/webgl2-sampler.ts diff --git a/cocos/gfx/webgl2/webgl2-shader.ts b/cocos/core/gfx/webgl2/webgl2-shader.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-shader.ts rename to cocos/core/gfx/webgl2/webgl2-shader.ts diff --git a/cocos/gfx/webgl2/webgl2-state-cache.ts b/cocos/core/gfx/webgl2/webgl2-state-cache.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-state-cache.ts rename to cocos/core/gfx/webgl2/webgl2-state-cache.ts diff --git a/cocos/gfx/webgl2/webgl2-texture-view.ts b/cocos/core/gfx/webgl2/webgl2-texture-view.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-texture-view.ts rename to cocos/core/gfx/webgl2/webgl2-texture-view.ts diff --git a/cocos/gfx/webgl2/webgl2-texture.ts b/cocos/core/gfx/webgl2/webgl2-texture.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-texture.ts rename to cocos/core/gfx/webgl2/webgl2-texture.ts diff --git a/cocos/gfx/webgl2/webgl2-window.ts b/cocos/core/gfx/webgl2/webgl2-window.ts similarity index 100% rename from cocos/gfx/webgl2/webgl2-window.ts rename to cocos/core/gfx/webgl2/webgl2-window.ts diff --git a/cocos/gfx/window.ts b/cocos/core/gfx/window.ts similarity index 100% rename from cocos/gfx/window.ts rename to cocos/core/gfx/window.ts diff --git a/cocos/core/index.ts b/cocos/core/index.ts index 6cf956eb3a..41a43dcde5 100644 --- a/cocos/core/index.ts +++ b/cocos/core/index.ts @@ -28,20 +28,14 @@ */ import * as math from './math'; +import * as geometry from './geom-utils'; cc.math = math; -export { math }; +cc.geometry = geometry; -export { AffineTransform } from './math/affine-transform'; -export { Color } from './math/color'; -export { Mat3 } from './math/mat3'; -export { Mat4 } from './math/mat4'; -export { Quat } from './math/quat'; -export { Rect } from './math/rect'; -export { Size } from './math/size'; -export { Vec2 } from './math/vec2'; -export { Vec3 } from './math/vec3'; -export { Vec4 } from './math/vec4'; +export { math, geometry }; +export * from './math'; +export * from './memop'; export * from './value-types'; export * from './utils'; export * from './data'; @@ -51,4 +45,14 @@ export * from './game'; export * from './scheduler'; export * from './director'; +export * from './gfx'; +import './pipeline'; +export * from './assets'; +export * from './load-pipeline'; +export * from './scene-graph'; +export * from './components'; +export * from './3d'; +export * from './animation'; +import './primitive'; + export * from './utils/profiler/profiler'; diff --git a/cocos/legacy.ts b/cocos/core/legacy.ts similarity index 91% rename from cocos/legacy.ts rename to cocos/core/legacy.ts index 2a1bc6464b..57f67da6de 100644 --- a/cocos/legacy.ts +++ b/cocos/core/legacy.ts @@ -2,8 +2,8 @@ * @hidden */ -import * as debug from './core/platform/CCDebug'; -import { _normalize, basename, changeBasename, changeExtname, dirname, extname, getSeperator, join, mainFileName, stripSep } from './core/utils/path'; +import * as debug from './platform/debug'; +import { _normalize, basename, changeBasename, changeExtname, dirname, extname, getSeperator, join, mainFileName, stripSep } from './utils/path'; // import Pipeline from './load-pipeline/pipeline'; // import Url from './load-pipeline/url'; diff --git a/cocos/load-pipeline/CCLoader.ts b/cocos/core/load-pipeline/CCLoader.ts similarity index 98% rename from cocos/load-pipeline/CCLoader.ts rename to cocos/core/load-pipeline/CCLoader.ts index 0bf02eb6c3..f5b92bd406 100644 --- a/cocos/load-pipeline/CCLoader.ts +++ b/cocos/core/load-pipeline/CCLoader.ts @@ -29,16 +29,16 @@ */ import { Asset, RawAsset } from '../assets'; -import { createMap, getClassName, isChildClassOf } from '../core/utils/js'; -import { callInNextTick } from '../core/utils/misc'; +import { createMap, getClassName, isChildClassOf } from '../utils/js'; +import { callInNextTick } from '../utils/misc'; import AssetLoader from './asset-loader'; -import AssetTable from './asset-table'; +import { AssetTable } from './asset-table'; import { getDependsRecursively } from './auto-release-utils'; import { LoadCompleteCallback, LoadProgressCallback } from './callback-params'; import Downloader from './downloader'; import Loader from './loader'; -import LoadingItems from './loading-items'; -import Pipeline from './pipeline'; +import { LoadingItems } from './loading-items'; +import { Pipeline } from './pipeline'; import ReleasedAssetChecker from './released-asset-checker'; const assetTables = Object.create(null); @@ -162,7 +162,7 @@ class CCLoader extends Pipeline { const assetLoader = new AssetLoader(); const downloader = new Downloader(); - // tslint:disable-next-line: no-shadowed-variable + // tslint:disable-next-line: no-shadowed-letiable const loader = new Loader(); super([ @@ -269,12 +269,12 @@ class CCLoader extends Pipeline { * * cc.loader.load(['a.png', 'b.json'], function (errors, results) { * if (errors) { - * for (var i = 0; i < errors.length; i++) { + * for (let i = 0; i < errors.length; i++) { * cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i])); * } * } - * var aTex = results.getContent('a.png'); - * var bJsonObj = results.getContent('b.json'); + * let aTex = results.getContent('a.png'); + * let bJsonObj = results.getContent('b.json'); * }); * ``` * @method load @@ -371,7 +371,9 @@ class CCLoader extends Pipeline { } // @ts-ignore const queue = LoadingItems.create(this, owner ? (completedCount, totalCount, item) => { + // @ts-ignore if (queue._ownerQueue && queue._ownerQueue.onProgress) { + // @ts-ignore queue._ownerQueue._childOnProgress(item); } } : null, (errors, items) => { @@ -538,20 +540,20 @@ class CCLoader extends Pipeline { * cc.error(err); * return; * } - * var texture = assets[0]; - * var spriteFrame = assets[1]; + * let texture = assets[0]; + * let spriteFrame = assets[1]; * }); * * // load all textures in "resources/imgs/" * cc.loader.loadResDir('imgs', cc.Texture2D, function (err, textures) { - * var texture1 = textures[0]; - * var texture2 = textures[1]; + * let texture1 = textures[0]; + * let texture2 = textures[1]; * }); * * // load all JSONs in "resources/data/" * cc.loader.loadResDir('data', function (err, objects, urls) { - * var data = objects[0]; - * var url = urls[0]; + * let data = objects[0]; + * let url = urls[0]; * }); * ``` */ diff --git a/cocos/load-pipeline/asset-loader.js b/cocos/core/load-pipeline/asset-loader.ts similarity index 77% rename from cocos/load-pipeline/asset-loader.js rename to cocos/core/load-pipeline/asset-loader.ts index e7d973d720..c5ef96d917 100644 --- a/cocos/load-pipeline/asset-loader.js +++ b/cocos/core/load-pipeline/asset-loader.ts @@ -27,30 +27,27 @@ * @category loader */ -import {extname} from '../core/utils/path'; -import * as debug from '../core/platform/CCDebug'; -import Pipeline from './pipeline'; -import LoadingItems from './loading-items'; +import {extname} from '../utils/path'; +import * as debug from '../platform/debug'; +import { Pipeline, IPipe } from './pipeline'; +import { LoadingItems } from './loading-items'; const ID = 'AssetLoader'; -var reusedArray = []; +let reusedArray:Array = []; -export default class AssetLoader { +export default class AssetLoader implements IPipe { static ID = ID; - constructor (extMap) { - this.id = ID; - this.async = true; - this.pipeline = null; - } + public id:string = ID; + public async:boolean = true; + public pipeline:Pipeline | null = null; handle (item, callback) { - var uuid = item.uuid; + let uuid = item.uuid; if (!uuid) { return item.content || null; } - var self = this; - cc.AssetLibrary.queryAssetInfo(uuid, function (error, url, isRawAsset) { + cc.AssetLibrary.queryAssetInfo(uuid, (error, url, isRawAsset) => { if (error) { callback(error); } @@ -58,13 +55,13 @@ export default class AssetLoader { item.url = item.rawUrl = url; item.isRawAsset = isRawAsset; if (isRawAsset) { - var ext = extname(url).toLowerCase(); + let ext = extname(url).toLowerCase(); if (!ext) { callback(new Error(debug.getError(4931, uuid, url))); return; } ext = ext.substr(1); - var queue = LoadingItems.getQueue(item); + let queue = LoadingItems.getQueue(item); reusedArray[0] = { queueId: item.queueId, id: url, @@ -74,8 +71,8 @@ export default class AssetLoader { alias: item, complete: true }; - if (CC_EDITOR) { - self.pipeline._cache[url] = reusedArray[0]; + if (CC_EDITOR && this.pipeline) { + this.pipeline._cache[url] = reusedArray[0]; } queue.append(reusedArray); // Dispatch to other raw type downloader @@ -91,4 +88,4 @@ export default class AssetLoader { } } -Pipeline.AssetLoader = AssetLoader; \ No newline at end of file +// Pipeline.AssetLoader = AssetLoader; \ No newline at end of file diff --git a/cocos/load-pipeline/asset-table.js b/cocos/core/load-pipeline/asset-table.ts similarity index 71% rename from cocos/load-pipeline/asset-table.js rename to cocos/core/load-pipeline/asset-table.ts index d2fd0c7848..2e01302dd9 100644 --- a/cocos/load-pipeline/asset-table.js +++ b/cocos/core/load-pipeline/asset-table.ts @@ -27,17 +27,25 @@ * @category loader */ -import {pushToMap} from '../core/utils/misc'; -import {createMap, isChildClassOf} from '../core/utils/js'; +import {pushToMap} from '../utils/misc'; +import {createMap, isChildClassOf} from '../utils/js'; +import url from './url'; +import { errorID } from '../platform/debug'; +import { extname } from '../utils/path'; +import { SpriteFrame, SpriteAtlas } from '../assets'; -function Entry (uuid, type) { - this.uuid = uuid; - this.type = type; +class Entry { + public uuid:string; + public type; + constructor (uuid, type) { + this.uuid = uuid; + this.type = type; + } } function isMatchByWord (path, test) { if (path.length > test.length) { - var nextAscii = path.charCodeAt(test.length); + let nextAscii = path.charCodeAt(test.length); return (nextAscii === 47); // '/' } return true; @@ -50,30 +58,31 @@ function isMatchByWord (path, test) { * */ -export default class AssetTable { +export class AssetTable { + private _pathToUuid:Map | Map>; constructor () { this._pathToUuid = createMap(true); } getUuid (path, type) { - path = cc.url.normalize(path); - var item = this._pathToUuid[path]; + path = url.normalize(path); + let item = this._pathToUuid[path]; if (item) { if (Array.isArray(item)) { if (type) { - for (var i = 0; i < item.length; i++) { - var entry = item[i]; + for (let i = 0; i < item.length; i++) { + let entry = item[i]; if (isChildClassOf(entry.type, type)) { return entry.uuid; } } // not found - if (CC_DEBUG && isChildClassOf(type, cc.SpriteFrame)) { + if (CC_DEBUG && isChildClassOf(type, SpriteFrame)) { for (let i = 0; i < item.length; i++) { let entry = item[i]; - if (isChildClassOf(entry.type, cc.SpriteAtlas)) { + if (isChildClassOf(entry.type, SpriteAtlas)) { // not support sprite frame in atlas - cc.errorID(4932, path); + errorID(4932, path); break; } } @@ -86,35 +95,35 @@ export default class AssetTable { else if (!type || isChildClassOf(item.type, type)) { return item.uuid; } - else if (CC_DEBUG && isChildClassOf(type, cc.SpriteFrame) && isChildClassOf(item.type, cc.SpriteAtlas)) { + else if (CC_DEBUG && isChildClassOf(type, SpriteFrame) && isChildClassOf(item.type, SpriteAtlas)) { // not support sprite frame in atlas - cc.errorID(4932, path); + errorID(4932, path); } } return ''; } getUuidArray (path, type, out_urls) { - path = cc.url.normalize(path); + path = url.normalize(path); if (path[path.length - 1] === '/') { path = path.slice(0, -1); } - var path2uuid = this._pathToUuid; - var uuids = []; - var _foundAtlasUrl; - for (var p in path2uuid) { + let path2uuid = this._pathToUuid; + let uuids:Array = []; + let _foundAtlasUrl; + for (let p in path2uuid) { if ((p.startsWith(path) && isMatchByWord(p, path)) || !path) { - var item = path2uuid[p]; + let item = path2uuid[p]; if (Array.isArray(item)) { - for (var i = 0; i < item.length; i++) { - var entry = item[i]; + for (let i = 0; i < item.length; i++) { + let entry = item[i]; if (!type || isChildClassOf(entry.type, type)) { uuids.push(entry.uuid); if (out_urls) { out_urls.push(p); } } - else if (CC_DEBUG && entry.type === cc.SpriteAtlas) { + else if (CC_DEBUG && entry.type === SpriteAtlas) { _foundAtlasUrl = p; } } @@ -126,15 +135,15 @@ export default class AssetTable { out_urls.push(p); } } - else if (CC_DEBUG && item.type === cc.SpriteAtlas) { + else if (CC_DEBUG && item.type === SpriteAtlas) { _foundAtlasUrl = p; } } } } - if (CC_DEBUG && uuids.length === 0 && _foundAtlasUrl && isChildClassOf(type, cc.SpriteFrame)) { + if (CC_DEBUG && uuids.length === 0 && _foundAtlasUrl && isChildClassOf(type, SpriteFrame)) { // not support sprite frame in atlas - cc.errorID(4932, _foundAtlasUrl); + errorID(4932, _foundAtlasUrl); } return uuids; } @@ -162,20 +171,20 @@ export default class AssetTable { add (path, uuid, type, isMainAsset) { // remove extname // (can not use path.slice because length of extname maybe 0) - isMainAsset && (path = path.substring(0, path.length - cc.path.extname(path).length)); - var newEntry = new Entry(uuid, type); + isMainAsset && (path = path.substring(0, path.length - extname(path).length)); + let newEntry = new Entry(uuid, type); pushToMap(this._pathToUuid, path, newEntry, isMainAsset); } _getInfo_DEBUG (uuid, out_info) { - var path2uuid = this._pathToUuid; - var paths = Object.keys(path2uuid); - for (var p = 0; p < paths.length; ++p) { - var path = paths[p]; - var item = path2uuid[path]; + let path2uuid = this._pathToUuid; + let paths = Object.keys(path2uuid); + for (let p = 0; p < paths.length; ++p) { + let path = paths[p]; + let item = path2uuid[path]; if (Array.isArray(item)) { - for (var i = 0; i < item.length; i++) { - var entry = item[i]; + for (let i = 0; i < item.length; i++) { + let entry = item[i]; if (entry.uuid === uuid) { out_info.path = path; out_info.type = entry.type; diff --git a/cocos/load-pipeline/auto-release-utils.js b/cocos/core/load-pipeline/auto-release-utils.ts similarity index 84% rename from cocos/load-pipeline/auto-release-utils.js rename to cocos/core/load-pipeline/auto-release-utils.ts index a4861e840c..37816f9af3 100644 --- a/cocos/load-pipeline/auto-release-utils.js +++ b/cocos/core/load-pipeline/auto-release-utils.ts @@ -27,15 +27,16 @@ * @category loader */ -import {createMap} from '../core/utils/js'; +import {createMap} from '../utils/js'; +import { RawAsset } from '../assets'; function parseDepends (key, parsed) { - var item = cc.loader.getItem(key); + let item = cc.loader.getItem(key); if (item) { - var depends = item.dependKeys; + let depends = item.dependKeys; if (depends) { - for (var i = 0; i < depends.length; i++) { - var depend = depends[i]; + for (let i = 0; i < depends.length; i++) { + let depend = depends[i]; if ( !parsed[depend] ) { parsed[depend] = true; parseDepends(depend, parsed); @@ -50,7 +51,7 @@ function visitAsset (asset, excludeMap) { if (!asset._uuid) { return; } - var key = cc.loader._getReferenceKey(asset); + let key = cc.loader._getReferenceKey(asset); if ( !excludeMap[key] ) { excludeMap[key] = true; parseDepends(key, excludeMap); @@ -58,14 +59,14 @@ function visitAsset (asset, excludeMap) { } function visitComponent (comp, excludeMap) { - var props = Object.getOwnPropertyNames(comp); - for (var i = 0; i < props.length; i++) { - var value = comp[props[i]]; + let props = Object.getOwnPropertyNames(comp); + for (let i = 0; i < props.length; i++) { + let value = comp[props[i]]; if (typeof value === 'object' && value) { if (Array.isArray(value)) { for (let j = 0; j < value.length; j++) { let val = value[j]; - if (val instanceof cc.RawAsset) { + if (val instanceof RawAsset) { visitAsset(val, excludeMap); } } @@ -74,12 +75,12 @@ function visitComponent (comp, excludeMap) { let keys = Object.getOwnPropertyNames(value); for (let j = 0; j < keys.length; j++) { let val = value[keys[j]]; - if (val instanceof cc.RawAsset) { + if (val instanceof RawAsset) { visitAsset(val, excludeMap); } } } - else if (value instanceof cc.RawAsset) { + else if (value instanceof RawAsset) { visitAsset(value, excludeMap); } } @@ -97,8 +98,8 @@ function visitNode (node, excludeMap) { // do auto release export function autoRelease (oldSceneAssets, nextSceneAssets, persistNodes) { - var releaseSettings = cc.loader._autoReleaseSetting; - var excludeMap = createMap(); + let releaseSettings = cc.loader._autoReleaseSetting; + let excludeMap = createMap(); // collect next scene assets if (nextSceneAssets) { @@ -124,7 +125,7 @@ export function autoRelease (oldSceneAssets, nextSceneAssets, persistNodes) { // remove auto release assets // (releasing asset will change _autoReleaseSetting, so don't use for-in) - var keys = Object.keys(releaseSettings); + let keys = Object.keys(releaseSettings); for (let i = 0; i < keys.length; i++) { let key = keys[i]; if (releaseSettings[key] === true && !excludeMap[key]) { @@ -135,7 +136,7 @@ export function autoRelease (oldSceneAssets, nextSceneAssets, persistNodes) { // get dependencies not including self export function getDependsRecursively (key) { - var depends = {}; + let depends = {}; parseDepends(key, depends); return Object.keys(depends); } \ No newline at end of file diff --git a/cocos/load-pipeline/binary-downloader.js b/cocos/core/load-pipeline/binary-downloader.ts similarity index 100% rename from cocos/load-pipeline/binary-downloader.js rename to cocos/core/load-pipeline/binary-downloader.ts diff --git a/cocos/load-pipeline/callback-params.ts b/cocos/core/load-pipeline/callback-params.ts similarity index 100% rename from cocos/load-pipeline/callback-params.ts rename to cocos/core/load-pipeline/callback-params.ts diff --git a/cocos/load-pipeline/downloader.js b/cocos/core/load-pipeline/downloader.ts similarity index 78% rename from cocos/load-pipeline/downloader.js rename to cocos/core/load-pipeline/downloader.ts index 92124ec052..3250db9b51 100644 --- a/cocos/load-pipeline/downloader.js +++ b/cocos/core/load-pipeline/downloader.ts @@ -27,33 +27,34 @@ * @category loader */ -import {mixin} from '../core/utils/js'; -import * as debug from '../core/platform/CCDebug'; -import Pipeline from './pipeline'; +import {mixin} from '../utils/js'; +import * as debug from '../platform/debug'; +import { Pipeline, IPipe } from './pipeline'; import * as PackDownloader from './pack-downloader'; import downloadBinary from './binary-downloader'; import downloadText from './text-downloader'; -import downloadAudio from './audio-downloader'; import {urlAppendTimestamp} from './utils'; function skip () { return null; } -function downloadScript (item, callback, isAsync) { - var url = item.url, +function downloadScript (item, callback, isAsync?) { + let url = item.url, d = document, s = document.createElement('script'); - s.async = isAsync; + s.async = !!isAsync; s.src = urlAppendTimestamp(url); function loadHandler () { - s.parentNode.removeChild(s); + if (s.parentNode) + s.parentNode.removeChild(s); s.removeEventListener('load', loadHandler, false); s.removeEventListener('error', errorHandler, false); callback(null, url); } function errorHandler() { - s.parentNode.removeChild(s); + if (s.parentNode) + s.parentNode.removeChild(s); s.removeEventListener('load', loadHandler, false); s.removeEventListener('error', errorHandler, false); callback(new Error(debug.getError(4928, url))); @@ -75,7 +76,7 @@ function downloadImage (item, callback, isCrossOrigin, img) { isCrossOrigin = true; } - var url = urlAppendTimestamp(item.url); + let url = urlAppendTimestamp(item.url); img = img || new Image(); if (isCrossOrigin && window.location.protocol !== 'file:') { img.crossOrigin = 'anonymous'; @@ -84,31 +85,31 @@ function downloadImage (item, callback, isCrossOrigin, img) { img.crossOrigin = null; } + function loadCallback () { + img.removeEventListener('load', loadCallback); + img.removeEventListener('error', errorCallback); + + img.id = item.id; + callback(null, img); + } + function errorCallback () { + img.removeEventListener('load', loadCallback); + img.removeEventListener('error', errorCallback); + + // Retry without crossOrigin mark if crossOrigin loading fails + // Do not retry if protocol is https, even if the image is loaded, cross origin image isn't renderable. + if (window.location.protocol !== 'https:' && img.crossOrigin && img.crossOrigin.toLowerCase() === 'anonymous') { + downloadImage(item, callback, false, img); + } + else { + callback(new Error(debug.getError(4930, url))); + } + } + if (img.complete && img.naturalWidth > 0 && img.src === url) { return img; } else { - function loadCallback () { - img.removeEventListener('load', loadCallback); - img.removeEventListener('error', errorCallback); - - img.id = item.id; - callback(null, img); - } - function errorCallback () { - img.removeEventListener('load', loadCallback); - img.removeEventListener('error', errorCallback); - - // Retry without crossOrigin mark if crossOrigin loading fails - // Do not retry if protocol is https, even if the image is loaded, cross origin image isn't renderable. - if (window.location.protocol !== 'https:' && img.crossOrigin && img.crossOrigin.toLowerCase() === 'anonymous') { - downloadImage(item, callback, false, img); - } - else { - callback(new Error(debug.getError(4930, url))); - } - } - img.addEventListener('load', loadCallback); img.addEventListener('error', errorCallback); img.src = url; @@ -116,15 +117,16 @@ function downloadImage (item, callback, isCrossOrigin, img) { } function downloadUuid (item, callback) { - var result = PackDownloader.load(item, callback); + let result = PackDownloader.load(item, callback); if (result === undefined) { + // @ts-ignore return this.extMap['json'](item, callback); } return result || undefined; } -var defaultMap = { +let defaultMap = { // JS 'js' : downloadScript, @@ -141,12 +143,6 @@ var defaultMap = { 'pvr': downloadBinary, 'pkm': downloadBinary, - // Audio - 'mp3' : downloadAudio, - 'ogg' : downloadAudio, - 'wav' : downloadAudio, - 'm4a' : downloadAudio, - // Txt 'txt' : downloadText, 'xml' : downloadText, @@ -181,7 +177,12 @@ var defaultMap = { 'default' : downloadText }; -var ID = 'Downloader'; +const ID = 'Downloader'; + +interface IDownloadItem { + item; + callback; +} /** * The downloader pipe, it can download several types of files: @@ -201,25 +202,25 @@ var ID = 'Downloader'; * @param {Object} extMap Custom supported types with corresponded handler * @example * ``` - * var downloader = new Downloader({ + * let downloader = new Downloader({ * // This will match all url with `.scene` extension or all url with `scene` type * 'scene' : function (url, callback) {} * }); * ``` */ -export default class Downloader { +export default class Downloader implements IPipe { static ID = ID; static PackDownloader = PackDownloader; - constructor (extMap) { - this.id = ID; - this.async = true; - this.pipeline = null; - this._curConcurrent = 0; - this._loadQueue = []; - - this._subpackages = {}; + public id:string = ID; + public async:boolean = true; + public pipeline:Pipeline | null = null; + private extMap:object; + private _curConcurrent = 0; + private _loadQueue:Array = []; + private _subpackages = {}; + constructor (extMap?) { this.extMap = mixin(extMap, defaultMap); } @@ -234,11 +235,11 @@ export default class Downloader { _handleLoadQueue () { while (this._curConcurrent < cc.macro.DOWNLOAD_MAX_CONCURRENT) { - var nextOne = this._loadQueue.shift(); + let nextOne = this._loadQueue.shift(); if (!nextOne) { break; } - var syncRet = this.handle(nextOne.item, nextOne.callback); + let syncRet = this.handle(nextOne.item, nextOne.callback) as any; if (syncRet !== undefined) { if (syncRet instanceof Error) { nextOne.callback(syncRet); @@ -251,9 +252,9 @@ export default class Downloader { } handle (item, callback) { - var self = this; - var downloadFunc = this.extMap[item.type] || this.extMap['default']; - var syncRet = undefined; + let self = this; + let downloadFunc = this.extMap[item.type] || this.extMap['default']; + let syncRet = undefined; if (this._curConcurrent < cc.macro.DOWNLOAD_MAX_CONCURRENT) { this._curConcurrent++; syncRet = downloadFunc.call(this, item, function (err, result) { @@ -312,4 +313,4 @@ export default class Downloader { } } -Pipeline.Downloader = Downloader; +// Pipeline.Downloader = Downloader; diff --git a/cocos/load-pipeline/font-loader.js b/cocos/core/load-pipeline/font-loader.ts similarity index 89% rename from cocos/load-pipeline/font-loader.js rename to cocos/core/load-pipeline/font-loader.ts index 03ae56209b..db9c576128 100644 --- a/cocos/load-pipeline/font-loader.js +++ b/cocos/core/load-pipeline/font-loader.ts @@ -27,14 +27,21 @@ * @category loader */ -import {safeMeasureText} from '../core/utils/text-utils'; +import {safeMeasureText} from '../utils/text-utils'; -let _canvasContext = null; -let _testString = "BES bswy:->@"; +interface IFontLoadHandle { + fontFamilyName; + refWidth; + callback; + startTime; +} + +let _canvasContext: CanvasRenderingContext2D|null = null; +const _testString = "BES bswy:->@"; let _fontFaces = {}; let _intervalId = -1; -let _loadingFonts = []; +let _loadingFonts:Array = []; // 60 seconds timeout let _timeout = 60000; @@ -54,7 +61,9 @@ function _checkFontLoaded () { } let oldWidth = fontLoadHandle.refWidth; + // @ts-ignore _canvasContext.font = '40px ' + fontFamily; + // @ts-ignore let newWidth = safeMeasureText(_canvasContext, _testString); // loaded successfully if (oldWidth !== newWidth) { @@ -90,7 +99,9 @@ export function loadFont (item, callback) { // Default width reference to test whether new font is loaded correctly let fontDesc = '40px ' + fontFamilyName; + // @ts-ignore _canvasContext.font = fontDesc; + // @ts-ignore let refWidth = safeMeasureText(_canvasContext, _testString); // Setup font face style @@ -116,7 +127,7 @@ export function loadFont (item, callback) { document.body.appendChild(preloadDiv); // Save loading font - let fontLoadHandle = { + let fontLoadHandle:IFontLoadHandle = { fontFamilyName, refWidth, callback, @@ -131,11 +142,11 @@ export function loadFont (item, callback) { } export function _getFontFamily (fontHandle) { - var ttfIndex = fontHandle.lastIndexOf(".ttf"); + let ttfIndex = fontHandle.lastIndexOf(".ttf"); if (ttfIndex === -1) return fontHandle; - var slashPos = fontHandle.lastIndexOf("/"); - var fontFamilyName; + let slashPos = fontHandle.lastIndexOf("/"); + let fontFamilyName; if (slashPos === -1) { fontFamilyName = fontHandle.substring(0, ttfIndex) + "_LABEL"; } else { diff --git a/cocos/load-pipeline/index.ts b/cocos/core/load-pipeline/index.ts similarity index 100% rename from cocos/load-pipeline/index.ts rename to cocos/core/load-pipeline/index.ts diff --git a/cocos/load-pipeline/loader.js b/cocos/core/load-pipeline/loader.ts similarity index 90% rename from cocos/load-pipeline/loader.js rename to cocos/core/load-pipeline/loader.ts index 0eca1a4c2a..dcd92e7ef9 100644 --- a/cocos/load-pipeline/loader.js +++ b/cocos/core/load-pipeline/loader.ts @@ -28,10 +28,10 @@ * @category loader */ -import {mixin} from '../core/utils/js'; +import {mixin} from '../utils/js'; import {ImageAsset} from '../assets/image-asset'; import plistParser from './plist-parser'; -import Pipeline from './pipeline'; +import { Pipeline, IPipe } from './pipeline'; import {loadUuid} from './uuid-loader'; import {loadFont} from './font-loader'; @@ -45,7 +45,7 @@ function loadJSON (item) { } try { - var result = JSON.parse(item.content); + let result = JSON.parse(item.content); return result; } catch (e) { @@ -54,20 +54,20 @@ function loadJSON (item) { } function loadImage (item) { - var loadByDeserializedAsset = (item._owner instanceof cc.Asset); + let loadByDeserializedAsset = (item._owner instanceof cc.Asset); if (loadByDeserializedAsset) { // already has cc.Asset return null; } - var image = item.content; + let image = item.content; if (!CC_WECHATGAME && !CC_QQPLAY && !(image instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); } // load cc.ImageAsset - var rawUrl = item.rawUrl; - var imageAsset = item.imageAsset || new ImageAsset(); + let rawUrl = item.rawUrl; + let imageAsset = item.imageAsset || new ImageAsset(); imageAsset._uuid = item.uuid; imageAsset._url = rawUrl; imageAsset._setRawAsset(rawUrl, false); @@ -78,13 +78,13 @@ function loadImage (item) { // If audio is loaded by url directly, than this loader will wrap it into a new cc.AudioClip object. // If audio is loaded by deserialized AudioClip, than this loader will be skipped. function loadAudioAsAsset (item, callback) { - var loadByDeserializedAsset = (item._owner instanceof cc.Asset); + let loadByDeserializedAsset = (item._owner instanceof cc.Asset); if (loadByDeserializedAsset) { // already has cc.Asset return null; } - var audioClip = new cc.AudioClip(); + let audioClip = new cc.AudioClip(); audioClip._setRawAsset(item.rawUrl, false); audioClip._nativeAsset = item.content; return audioClip; @@ -94,7 +94,7 @@ function loadPlist (item) { if (typeof item.content !== 'string') { return new Error('Plist Loader: Input item doesn\'t contain string content'); } - var result = plistParser.parse(item.content); + let result = plistParser.parse(item.content); if (result) { return result; } @@ -151,7 +151,7 @@ function loadPVRTex (item) { return pvrAsset; } else if (header[11] === 0x21525650) { - var headerLength = header[0], + let headerLength = header[0], height = header[1], width = header[2] // todo: use new Uint8Array(buffer, headerLength) instead @@ -214,7 +214,7 @@ function loadPKMTex(item) { return etcAsset; } -var defaultMap = { +let defaultMap = { // Images 'png' : loadImage, 'jpg' : loadImage, @@ -262,7 +262,7 @@ var defaultMap = { 'default' : loadNothing }; -var ID = 'Loader'; +let ID = 'Loader'; /** * The loader pipe, it can load several types of files: @@ -282,20 +282,20 @@ var ID = 'Loader'; * @param {Object} extMap Custom supported types with corresponded handler * @example * ``` - * var loader = new Loader({ + * let loader = new Loader({ * // This will match all url with `.scene` extension or all url with `scene` type * 'scene' : function (url, callback) {} * }); * ``` */ -export default class Loader { +export default class Loader implements IPipe { static ID = ID; - - constructor (extMap) { - this.id = ID; - this.async = true; - this.pipeline = null; - + + public id = ID; + public async = true; + public pipeline: Pipeline | null = null; + private extMap:object; + constructor (extMap?) { this.extMap = mixin(extMap, defaultMap); } @@ -303,14 +303,14 @@ export default class Loader { * Add custom supported types handler or modify existing type handler. * @param {Object} extMap Custom supported types with corresponded handler */ - addHandlers (extMap) { + addHandlers (extMap?) { this.extMap = mixin(this.extMap, extMap); } handle (item, callback) { - var loadFunc = this.extMap[item.type] || this.extMap['default']; + let loadFunc = this.extMap[item.type] || this.extMap['default']; return loadFunc.call(this, item, callback); } } -Pipeline.Loader = Loader; +// Pipeline.Loader = Loader; diff --git a/cocos/load-pipeline/loading-items.js b/cocos/core/load-pipeline/loading-items.ts similarity index 72% rename from cocos/load-pipeline/loading-items.js rename to cocos/core/load-pipeline/loading-items.ts index b42c36b25e..622c16ada3 100644 --- a/cocos/load-pipeline/loading-items.js +++ b/cocos/core/load-pipeline/loading-items.ts @@ -28,45 +28,60 @@ * @category loader */ -import {CallbacksInvoker} from '../core/event/callbacks-invoker'; -import {extname} from '../core/utils/path'; -import {createMap, mixin} from '../core/utils/js'; +import {CallbacksInvoker} from '../event/callbacks-invoker'; +import {extname} from '../utils/path'; +import {createMap, mixin} from '../utils/js'; -var _qid = (0|(Math.random()*998)); -var _queues = createMap(true); -var _pool = []; -var _POOL_MAX_LENGTH = 10; +let _qid = (0|(Math.random()*998)); +let _queues = createMap(true); +let _pool:Array = []; +const _POOL_MAX_LENGTH = 10; -var ItemState = { - WORKING: 1, - COMPLETE: 2, - ERROR: 3 +export interface IItem { + queueId; + id:string; + url; // real download url, maybe changed + rawUrl; // url used in scripts + urlParam; + type:string; + error:Error|null; + content:any; + complete:boolean; + states:object; + deps; + isScene:boolean; +} + +enum ItemState { + WORKING, + COMPLETE, + ERROR }; -var _queueDeps = createMap(true); +let _queueDeps = createMap(true); function isIdValid (id) { - var realId = id.url || id; + let realId = id.url || id; return (typeof realId === 'string'); } function _parseUrlParam (url) { if (!url) return undefined; - var split = url.split('?'); + let split = url.split('?'); if (!split || !split[0] || !split[1]) { return undefined; } - var urlParam = {}; - var queries = split[1].split('&'); + let urlParam = {}; + let queries = split[1].split('&'); queries.forEach(function (item) { - var itemSplit = item.split('='); + let itemSplit = item.split('='); urlParam[itemSplit[0]] = itemSplit[1]; }); return urlParam; } function createItem (id, queueId) { - var url = (typeof id === 'object') ? id.url : id; - var result = { + let url = (typeof id === 'object') ? id.url : id; + let result = { queueId: queueId, id: url, url: url, // real download url, maybe changed @@ -84,8 +99,8 @@ function createItem (id, queueId) { if (typeof id === 'object') { mixin(result, id); if (id.skips) { - for (var i = 0; i < id.skips.length; i++) { - var skip = id.skips[i]; + for (let i = 0; i < id.skips.length; i++) { + let skip = id.skips[i]; result.states[skip] = ItemState.COMPLETE; } } @@ -97,22 +112,22 @@ function createItem (id, queueId) { return result; } -var checkedIds = []; -function checkCircleReference(owner, item, recursiveCall) { +let _checkedIds:Array = []; +function checkCircleReference(owner, item:IItem, recursiveCall?) { if (!owner || !item) { return false; } - var result = false; - checkedIds.push(item.id); + let result = false; + _checkedIds.push(item.id); if (item.deps) { - var i, deps = item.deps, subDep; + let i, deps = item.deps, subDep; for (i = 0; i < deps.length; i++) { subDep = deps[i]; if (subDep.id === owner.id) { result = true; break; } - else if (checkedIds.indexOf(subDep.id) >= 0) { + else if (_checkedIds.indexOf(subDep.id) >= 0) { continue; } else if (subDep.deps && checkCircleReference(owner, subDep, true)) { @@ -122,7 +137,7 @@ function checkCircleReference(owner, item, recursiveCall) { } } if (!recursiveCall) { - checkedIds.length = 0; + _checkedIds.length = 0; } return result; } @@ -163,7 +178,7 @@ function checkCircleReference(owner, item, recursiveCall) { * @class LoadingItems * @extends CallbacksInvoker */ -export default class LoadingItems extends CallbacksInvoker { +export class LoadingItems extends CallbacksInvoker { /** * @en The item states of the LoadingItems, its value could be LoadingItems.ItemState.WORKING | LoadingItems.ItemState.COMPLETET | LoadingItems.ItemState.ERROR * @zh LoadingItems 队列中的加载项状态,状态的值可能是 LoadingItems.ItemState.WORKING | LoadingItems.ItemState.COMPLETET | LoadingItems.ItemState.ERROR @@ -184,100 +199,99 @@ export default class LoadingItems extends CallbacksInvoker { static ItemState = new cc.Enum(ItemState); /** - * @class LoadingItems - * @extends CallbacksInvoker + * @en This is a callback which will be invoked while an item flow out the pipeline. + * You can pass the callback function in LoadingItems.create or set it later. + * @zh 这个回调函数将在 item 加载结束后被调用。你可以在构造时传递这个回调函数或者是在构造之后直接设置。 + * @method onProgress + * @param {Number} completedCount The number of the items that are already completed. + * @param {Number} totalCount The total number of the items. + * @param {Object} item The latest item which flow out the pipeline. + * @example + * ``` + * loadingItems.onProgress (completedCount, totalCount, item) { + * let progress = (100 * completedCount / totalCount).toFixed(2); + * cc.log(progress + '%'); + * } + * ``` */ + public onProgress:Function|undefined; + + /** + * @en This is a callback which will be invoked while all items is completed, + * You can pass the callback function in LoadingItems.create or set it later. + * @zh 该函数将在加载队列全部完成时被调用。你可以在构造时传递这个回调函数或者是在构造之后直接设置。 + * @method onComplete + * @param {Array} errors All errored urls will be stored in this array, if no error happened, then it will be null + * @param {LoadingItems} items All items. + * @example + * ``` + * loadingItems.onComplete (errors, items) { + * if (error) + * cc.log('Completed with ' + errors.length + ' errors'); + * else + * cc.log('Completed ' + items.totalCount + ' items'); + * } + * ``` + */ + public onComplete:Function|undefined; + + /** + * @en The map of all items. + * @zh 存储所有加载项的对象。 + * @property map + * @type {Object} + */ + public map = createMap(true); + + /** + * @en The map of completed items. + * @zh 存储已经完成的加载项。 + * @property completed + * @type {Object} + */ + public completed = {}; + + /** + * @en Total count of all items. + * @zh 所有加载项的总数。 + * @property totalCount + * @type {Number} + */ + public totalCount = 0; + + /** + * @en Total count of completed items. + * @zh 所有完成加载项的总数。 + * @property completedCount + * @type {Number} + */ + public completedCount = 0; + + /** + * @en Activated or not. + * @zh 是否启用。 + * @property active + * @type {Boolean} + */ + public active:boolean; + + private _id:number; + private _pipeline; + private _errorUrls:Array = []; + private _appending = false; + public _ownerQueue = null; constructor (pipeline, urlList, onProgress, onComplete) { super(); this._id = ++_qid; - _queues[this._id] = this; this._pipeline = pipeline; - this._errorUrls = []; - - this._appending = false; - - this._ownerQueue = null; - - /** - * @en This is a callback which will be invoked while an item flow out the pipeline. - * You can pass the callback function in LoadingItems.create or set it later. - * @zh 这个回调函数将在 item 加载结束后被调用。你可以在构造时传递这个回调函数或者是在构造之后直接设置。 - * @method onProgress - * @param {Number} completedCount The number of the items that are already completed. - * @param {Number} totalCount The total number of the items. - * @param {Object} item The latest item which flow out the pipeline. - * @example - * ``` - * loadingItems.onProgress (completedCount, totalCount, item) { - * var progress = (100 * completedCount / totalCount).toFixed(2); - * cc.log(progress + '%'); - * } - * ``` - */ this.onProgress = onProgress; - - /** - * @en This is a callback which will be invoked while all items is completed, - * You can pass the callback function in LoadingItems.create or set it later. - * @zh 该函数将在加载队列全部完成时被调用。你可以在构造时传递这个回调函数或者是在构造之后直接设置。 - * @method onComplete - * @param {Array} errors All errored urls will be stored in this array, if no error happened, then it will be null - * @param {LoadingItems} items All items. - * @example - * ``` - * loadingItems.onComplete (errors, items) { - * if (error) - * cc.log('Completed with ' + errors.length + ' errors'); - * else - * cc.log('Completed ' + items.totalCount + ' items'); - * } - * ``` - */ this.onComplete = onComplete; - /** - * @en The map of all items. - * @zh 存储所有加载项的对象。 - * @property map - * @type {Object} - */ - this.map = createMap(true); - - /** - * @en The map of completed items. - * @zh 存储已经完成的加载项。 - * @property completed - * @type {Object} - */ - this.completed = {}; - - /** - * @en Total count of all items. - * @zh 所有加载项的总数。 - * @property totalCount - * @type {Number} - */ - this.totalCount = 0; - - /** - * @en Total count of completed items. - * @zh 所有完成加载项的总数。 - * @property completedCount - * @type {Number} - */ - this.completedCount = 0; - - /** - * @en Activated or not. - * @zh 是否启用。 - * @property active - * @type {Boolean} - */ if (this._pipeline) { this.active = true; } @@ -310,22 +324,22 @@ export default class LoadingItems extends CallbacksInvoker { * @example * ``` * cc.LoadingItems.create(cc.loader, ['a.png', 'b.plist'], function (completedCount, totalCount, item) { - * var progress = (100 * completedCount / totalCount).toFixed(2); + * let progress = (100 * completedCount / totalCount).toFixed(2); * cc.log(progress + '%'); * }, function (errors, items) { * if (errors) { - * for (var i = 0; i < errors.length; ++i) { + * for (let i = 0; i < errors.length; ++i) { * cc.log('Error url: ' + errors[i] + ', error: ' + items.getError(errors[i])); * } * } * else { - * var result_a = items.getContent('a.png'); + * let result_a = items.getContent('a.png'); * // ... * } * }) * ``` */ - static create (pipeline, urlList, onProgress, onComplete) { + static create (pipeline, urlList, onProgress?, onComplete?) { if (onProgress === undefined) { if (typeof urlList === 'function') { onComplete = urlList; @@ -344,7 +358,7 @@ export default class LoadingItems extends CallbacksInvoker { } } - var queue = _pool.pop(); + let queue = _pool.pop(); if (queue) { queue._pipeline = pipeline; queue.onProgress = onProgress; @@ -383,7 +397,7 @@ export default class LoadingItems extends CallbacksInvoker { * @param {Object} item The item which has completed */ static itemComplete (item) { - var queue = _queues[item.queueId]; + let queue = _queues[item.queueId]; if (queue) { // console.log('----- Completed by pipeline ' + item.id + ', rest: ' + (queue.totalCount - queue.completedCount-1)); queue.itemComplete(item.id); @@ -391,7 +405,7 @@ export default class LoadingItems extends CallbacksInvoker { } static initQueueDeps (queue) { - var dep = _queueDeps[queue._id]; + let dep = _queueDeps[queue._id]; if (!dep) { dep = _queueDeps[queue._id] = { completed: [], @@ -405,11 +419,11 @@ export default class LoadingItems extends CallbacksInvoker { } static registerQueueDep (owner, depId) { - var queueId = owner.queueId || owner; + let queueId = owner.queueId || owner; if (!queueId) { return false; } - var queueDepList = _queueDeps[queueId]; + let queueDepList = _queueDeps[queueId]; // Owner is root queue if (queueDepList) { if (queueDepList.deps.indexOf(depId) === -1) { @@ -418,8 +432,8 @@ export default class LoadingItems extends CallbacksInvoker { } // Owner is an item in the intermediate queue else if (owner.id) { - for (var id in _queueDeps) { - var queue = _queueDeps[id]; + for (let id in _queueDeps) { + let queue = _queueDeps[id]; // Found root queue if (queue.deps.indexOf(owner.id) !== -1) { if (queue.deps.indexOf(depId) === -1) { @@ -431,8 +445,8 @@ export default class LoadingItems extends CallbacksInvoker { } static finishDep (depId) { - for (var id in _queueDeps) { - var queue = _queueDeps[id]; + for (let id in _queueDeps) { + let queue = _queueDeps[id]; // Found root queue if (queue.deps.indexOf(depId) !== -1 && queue.completed.indexOf(depId) === -1) { queue.completed.push(depId); @@ -448,7 +462,7 @@ export default class LoadingItems extends CallbacksInvoker { * @param {any} [owner] * @return {Array} The accepted url list, some invalid items could be refused. */ - append (urlList, owner) { + append (urlList, owner?) { if (!this.active) { return []; } @@ -457,7 +471,7 @@ export default class LoadingItems extends CallbacksInvoker { } this._appending = true; - var accepted = [], i, url, item; + let accepted:Array = [], i, url, item; for (i = 0; i < urlList.length; ++i) { url = urlList[i]; @@ -475,8 +489,8 @@ export default class LoadingItems extends CallbacksInvoker { } // Not completed yet, should wait it else { - var self = this; - var queue = _queues[url.queueId]; + let self = this; + let queue = _queues[url.queueId]; if (queue) { this.totalCount++; LoadingItems.registerQueueDep(owner || this._id, url.id); @@ -492,7 +506,7 @@ export default class LoadingItems extends CallbacksInvoker { // Queue new items if (isIdValid(url)) { item = createItem(url, this._id); - var key = item.id; + let key = item.id; // No duplicated url if (!this.map[key]) { this.map[key] = item; @@ -520,7 +534,7 @@ export default class LoadingItems extends CallbacksInvoker { _childOnProgress (item) { if (this.onProgress) { - var dep = _queueDeps[this._id]; + let dep = _queueDeps[this._id]; this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item); } } @@ -531,7 +545,7 @@ export default class LoadingItems extends CallbacksInvoker { * @method allComplete */ allComplete () { - var errors = this._errorUrls.length === 0 ? null : this._errorUrls; + let errors = this._errorUrls.length === 0 ? null : this._errorUrls; if (this.onComplete) { this.onComplete(errors, this); } @@ -577,8 +591,8 @@ export default class LoadingItems extends CallbacksInvoker { * @return {Object} */ getContent (id) { - var item = this.map[id]; - var ret = null; + let item = this.map[id]; + let ret = null; if (item) { if (item.content) { ret = item.content; @@ -599,8 +613,8 @@ export default class LoadingItems extends CallbacksInvoker { * @return {Object} */ getError (id) { - var item = this.map[id]; - var ret = null; + let item = this.map[id]; + let ret = null; if (item) { if (item.error) { ret = item.error; @@ -618,7 +632,7 @@ export default class LoadingItems extends CallbacksInvoker { * @param {String} url */ removeItem (url) { - var item = this.map[url]; + let item = this.map[url]; if (!item) return; if (!this.completed[item.alias || url]) return; @@ -641,13 +655,13 @@ export default class LoadingItems extends CallbacksInvoker { * @param {String} id The item url */ itemComplete (id) { - var item = this.map[id]; + let item = this.map[id]; if (!item) { return; } // Register or unregister errors - var errorListId = this._errorUrls.indexOf(id); + let errorListId = this._errorUrls.indexOf(id); if (item.error && errorListId === -1) { this._errorUrls.push(id); } @@ -660,7 +674,7 @@ export default class LoadingItems extends CallbacksInvoker { LoadingItems.finishDep(item.id); if (this.onProgress) { - var dep = _queueDeps[this._id]; + let dep = _queueDeps[this._id]; this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item); } @@ -685,8 +699,8 @@ export default class LoadingItems extends CallbacksInvoker { this._pipeline = null; this._ownerQueue = null; this._errorUrls.length = 0; - this.onProgress = null; - this.onComplete = null; + this.onProgress = undefined; + this.onComplete = undefined; this.map = createMap(true); this.completed = {}; @@ -706,59 +720,65 @@ export default class LoadingItems extends CallbacksInvoker { _pool.push(this); } } + + /** + * @en Add a listener for an item, the callback will be invoked when the item is completed. + * @zh 监听加载项(通过 key 指定)的完成事件。 + * @method addListener + * @param {String} key + * @param {Function} callback - can be null + * @param {Object} target - can be null + * @return {Boolean} whether the key is new + */ + addListener (key, callback, target) { + return super.on(key, callback, target); + } + + /** + * @en + * Check if the specified key has any registered callback. + * If a callback is also specified, it will only return true if the callback is registered. + * @zh + * 检查指定的加载项是否有完成事件监听器。 + * 如果同时还指定了一个回调方法,并且回调有注册,它只会返回 true。 + * @method hasListener + * @param {String} key + * @param {Function} [callback] + * @param {Object} [target] + * @return {Boolean} + */ + hasListener (key, callback?, target?) { + return super.hasEventListener(key, callback, target); + } + + /** + * @en + * Removes a listener. + * It will only remove when key, callback, target all match correctly. + * @zh + * 移除指定加载项已经注册的完成事件监听器。 + * 只会删除 key, callback, target 均匹配的监听器。 + * @method remove + * @param {String} key + * @param {Function} callback + * @param {Object} target + * @return {Boolean} removed + */ + removeListener (key, callback?, target?) { + return super.off(key, callback, target); + } + + /** + * @en + * Removes all callbacks registered in a certain event + * type or all callbacks registered with a certain target. + * @zh 删除指定目标的所有完成事件监听器。 + * @method removeAllListeners + * @param {String|Object} key - The event key to be removed or the target to be removed + */ + removeAllListeners (key) { + super.removeAll(key); + } } -let proto = LoadingItems.prototype; - -/** - * @en Add a listener for an item, the callback will be invoked when the item is completed. - * @zh 监听加载项(通过 key 指定)的完成事件。 - * @method addListener - * @param {String} key - * @param {Function} callback - can be null - * @param {Object} target - can be null - * @return {Boolean} whether the key is new - */ -proto.addListener = CallbacksInvoker.prototype.on; - -/** - * @en - * Check if the specified key has any registered callback. - * If a callback is also specified, it will only return true if the callback is registered. - * @zh - * 检查指定的加载项是否有完成事件监听器。 - * 如果同时还指定了一个回调方法,并且回调有注册,它只会返回 true。 - * @method hasListener - * @param {String} key - * @param {Function} [callback] - * @param {Object} [target] - * @return {Boolean} - */ -proto.hasListener = CallbacksInvoker.prototype.hasEventListener; - -/** - * @en - * Removes a listener. - * It will only remove when key, callback, target all match correctly. - * @zh - * 移除指定加载项已经注册的完成事件监听器。 - * 只会删除 key, callback, target 均匹配的监听器。 - * @method remove - * @param {String} key - * @param {Function} callback - * @param {Object} target - * @return {Boolean} removed - */ -proto.removeListener = CallbacksInvoker.prototype.off; - -/** - * @en - * Removes all callbacks registered in a certain event - * type or all callbacks registered with a certain target. - * @zh 删除指定目标的所有完成事件监听器。 - * @method removeAllListeners - * @param {String|Object} key - The event key to be removed or the target to be removed - */ -proto.removeAllListeners = CallbacksInvoker.prototype.removeAll; - cc.LoadingItems = LoadingItems; diff --git a/cocos/load-pipeline/md5-pipe.js b/cocos/core/load-pipeline/md5-pipe.ts similarity index 81% rename from cocos/load-pipeline/md5-pipe.js rename to cocos/core/load-pipeline/md5-pipe.ts index adc042f302..5cc5d5d1ce 100644 --- a/cocos/load-pipeline/md5-pipe.js +++ b/cocos/core/load-pipeline/md5-pipe.ts @@ -28,23 +28,30 @@ * @category loader */ -import Pipeline from './pipeline'; +import { Pipeline, IPipe } from './pipeline'; const ID = 'MD5Pipe'; const ExtnameRegex = /(\.[^.\n\\/]*)$/; const UuidRegex = /([^/\\]*)\.[^\.]*$/; function getUuidFromURL (url) { - var matches = url.match(UuidRegex); + let matches = url.match(UuidRegex); if (matches) { return matches[1]; } return ""; } -export default class MD5Pipe { +export default class MD5Pipe implements IPipe { static ID = ID; + public id = ID; + public async = false; + public pipeline = null; + public md5AssetsMap; + public md5NativeAssetsMap; + public libraryBase; + constructor (md5AssetsMap, md5NativeAssetsMap, libraryBase) { this.id = ID; this.async = false; @@ -65,18 +72,18 @@ export default class MD5Pipe { } transformURL (url, hashPatchInFolder) { - var uuid = getUuidFromURL(url); + let uuid = getUuidFromURL(url); if (uuid) { - var isNativeAsset = !url.match(this.libraryBase); - var map = isNativeAsset ? this.md5NativeAssetsMap : this.md5AssetsMap; + let isNativeAsset = !url.match(this.libraryBase); + let map = isNativeAsset ? this.md5NativeAssetsMap : this.md5AssetsMap; let hashValue = map[uuid]; if (hashValue) { if (hashPatchInFolder) { - var dirname = cc.path.dirname(url); - var basename = cc.path.basename(url); + let dirname = cc.path.dirname(url); + let basename = cc.path.basename(url); url = `${dirname}.${hashValue}/${basename}`; } else { - var matched = false; + let matched = false; url = url.replace(ExtnameRegex, (function(match, p1) { matched = true; return "." + hashValue + p1; @@ -91,4 +98,4 @@ export default class MD5Pipe { } } -Pipeline.MD5Pipe = MD5Pipe; \ No newline at end of file +// Pipeline.MD5Pipe = MD5Pipe; \ No newline at end of file diff --git a/cocos/load-pipeline/pack-downloader.js b/cocos/core/load-pipeline/pack-downloader.ts similarity index 91% rename from cocos/load-pipeline/pack-downloader.js rename to cocos/core/load-pipeline/pack-downloader.ts index 26f3e2a9cb..488495e8fb 100644 --- a/cocos/load-pipeline/pack-downloader.js +++ b/cocos/core/load-pipeline/pack-downloader.ts @@ -28,35 +28,42 @@ * @category loader */ -import {pushToMap} from '../core/utils/misc'; +import {pushToMap} from '../utils/misc'; import {TextureUnpacker, JsonUnpacker} from './unpackers'; import { decompressJson } from './utils'; +import { errorID } from '../platform/debug'; +import { js } from '../utils'; +import { Texture2D, AssetLibrary } from '../assets'; // when more than one package contains the required asset, // choose to load from the package with the largest state value. -var PackState = { - Invalid: 0, - Removed: 1, - Downloading: 2, - Loaded: 3, +enum PackState { + Invalid, + Removed, + Downloading, + Loaded, }; -function UnpackerData () { - this.unpacker = null; - this.state = PackState.Invalid; +class UnpackerData { + public unpacker; + public state; + constructor () { + this.unpacker = null; + this.state = PackState.Invalid; + } } // {assetUuid: packUuid|[packUuid]} // If value is array of packUuid, then the first one will be prioritized for download, // so the smallest pack must be at the beginning of the array. -var uuidToPack = {}; +let uuidToPack = {}; // {packUuid: assetIndices} -var packIndices = {}; +let packIndices = {}; // {packUuid: UnpackerData} // We have to cache all packs in global because for now there's no operation context in loader. -var globalUnpackers = {}; +let globalUnpackers = {}; function error (uuid, packUuid) { @@ -77,11 +84,10 @@ export function initPacks (packs) { } export function _loadNewPack (uuid, packUuid, callback) { - var self = this; - var packUrl = cc.AssetLibrary.getLibUrlNoExt(packUuid) + '.json'; + var packUrl = AssetLibrary.getLibUrlNoExt(packUuid) + '.json'; cc.loader.load({ url: packUrl, ignoreMaxConcurrency: true }, function (err, packJson) { if (err) { - cc.errorID(4916, uuid); + errorID(4916, uuid); return callback(err); } var res = _doLoadNewPack(uuid, packUuid, packJson); @@ -124,7 +130,7 @@ export function _doLoadNewPack (uuid, packUuid, packedJson) { if (Array.isArray(packedJson)) { unpackerData.unpacker = new JsonUnpacker(); } - else if (packedJson.type === cc.js._getClassId(cc.Texture2D)) { + else if (packedJson.type === js._getClassId(Texture2D)) { unpackerData.unpacker = new TextureUnpacker(); } unpackerData.unpacker.load(packIndices[packUuid], packedJson); diff --git a/cocos/load-pipeline/pipeline.js b/cocos/core/load-pipeline/pipeline.ts similarity index 92% rename from cocos/load-pipeline/pipeline.js rename to cocos/core/load-pipeline/pipeline.ts index 291f54b077..e99b128e07 100644 --- a/cocos/load-pipeline/pipeline.js +++ b/cocos/core/load-pipeline/pipeline.ts @@ -28,15 +28,22 @@ * @category loader */ -import {createMap} from '../core/utils/js'; -import LoadingItems from './loading-items'; +import {createMap} from '../utils/js'; +import { LoadingItems, IItem } from './loading-items'; const ItemState = LoadingItems.ItemState; +export interface IPipe { + id:string; + async:boolean; + handle (item:IItem, callback); + next?:IPipe; +} + function flow (pipe, item) { - var pipeId = pipe.id; - var itemState = item.states[pipeId]; - var next = pipe.next; - var pipeline = pipe.pipeline; + let pipeId = pipe.id; + let itemState = item.states[pipeId]; + let next = pipe.next; + let pipeline = pipe.pipeline; if (item.error || itemState === ItemState.WORKING || itemState === ItemState.ERROR) { return; @@ -52,7 +59,7 @@ function flow (pipe, item) { else { item.states[pipeId] = ItemState.WORKING; // Pass async callback in case it's a async call - var result = pipe.handle(item, function (err, result) { + let result = pipe.handle(item, function (err, result) { if (err) { item.error = err; item.states[pipeId] = ItemState.ERROR; @@ -110,9 +117,12 @@ function flow (pipe, item) { * 最后当所有加载项都流出 pipeline 时,整个加载流程就结束了。 * @class Pipeline */ -export default class Pipeline { +export class Pipeline { static ItemState = ItemState; + protected _pipes:Array; + public _cache = createMap(true); + /** * 构造函数,通过一系列的 pipe 来构造一个新的 pipeline,pipes 将会在给定的顺序中被锁定。
* 一个 pipe 就是一个对象,它包含了字符串类型的 ‘id’ 和 ‘handle’ 函数,在 pipeline 中 id 必须是唯一的。
@@ -121,7 +131,7 @@ export default class Pipeline { * @param {Array} pipes * @example * ``` - * var pipeline = new Pipeline([ + * let pipeline = new Pipeline([ * { * id: 'Downloader', * handle: function (item, callback) {}, @@ -133,10 +143,9 @@ export default class Pipeline { */ constructor (pipes) { this._pipes = pipes; - this._cache = createMap(true); - for (var i = 0; i < pipes.length; ++i) { - var pipe = pipes[i]; + for (let i = 0; i < pipes.length; ++i) { + let pipe = pipes[i]; // Must have handle and id, handle for flow, id for state flag if (!pipe.handle || !pipe.id) { continue; @@ -172,12 +181,12 @@ export default class Pipeline { pipe.pipeline = this; - var nextPipe = null; + let nextPipe:IPipe|null = null; if (index < this._pipes.length) { nextPipe = this._pipes[index]; } - var previousPipe = null; + let previousPipe:IPipe|null = null; if (index > 0) { previousPipe = this._pipes[index-1]; } @@ -200,7 +209,7 @@ export default class Pipeline { * @param {Object} newPipe The pipe to be inserted. */ insertPipeAfter (refPipe, newPipe) { - var index = this._pipes.indexOf(refPipe); + let index = this._pipes.indexOf(refPipe); if (index < 0) { return; } @@ -261,7 +270,7 @@ export default class Pipeline { * ``` */ flowIn (items) { - var i, pipe = this._pipes[0], item; + let i, pipe = this._pipes[0], item; if (pipe) { // Cache all items first, in case synchronous loading flow same item repeatly for (i = 0; i < items.length; i++) { @@ -298,7 +307,7 @@ export default class Pipeline { * @return {Array} Items accepted by the pipeline */ flowInDeps (owner, urlList, callback) { - var deps = LoadingItems.create(this, function (errors, items) { + let deps = LoadingItems.create(this, function (errors, items) { callback(errors, items); items.destroy(); }); @@ -340,7 +349,7 @@ export default class Pipeline { dstItems.states = srcItem.states; return; } - for (var i = 0; i < dstItems.length; ++i) { + for (let i = 0; i < dstItems.length; ++i) { dstItems[i].states = srcItem.states; } } @@ -353,7 +362,7 @@ export default class Pipeline { * @return {Object} */ getItem (id) { - var item = this._cache[id]; + let item = this._cache[id]; if (!item) return item; @@ -378,15 +387,15 @@ export default class Pipeline { * @return {Boolean} succeed or not */ removeItem (id) { - var removed = this._cache[id]; + let removed = this._cache[id]; if (removed && removed.complete) { delete this._cache[id]; if (CC_EDITOR) { - var references = removed.references; + let references = removed.references; if (references) { - var dependListener = cc.AssetLibrary.dependListener; + let dependListener = cc.AssetLibrary.dependListener; if (dependListener) { - for (var uuid in references) { + for (let uuid in references) { dependListener.off(uuid, references[uuid]); } } @@ -402,8 +411,8 @@ export default class Pipeline { * @zh 清空当前 pipeline,该函数将清理 items。 */ clear () { - for (var id in this._cache) { - var item = this._cache[id]; + for (let id in this._cache) { + let item = this._cache[id]; delete this._cache[id]; if (!item.complete) { item.error = new Error('Canceled manually'); diff --git a/cocos/load-pipeline/plist-parser.js b/cocos/core/load-pipeline/plist-parser.ts similarity index 84% rename from cocos/load-pipeline/plist-parser.js rename to cocos/core/load-pipeline/plist-parser.ts index f1f032f699..28dc1817bb 100644 --- a/cocos/load-pipeline/plist-parser.js +++ b/cocos/core/load-pipeline/plist-parser.ts @@ -34,6 +34,8 @@ * @class saxParser */ class SAXParser { + private _isSupportDOMParser; + private _parser; constructor () { if (!(CC_EDITOR && Editor.isMainProcess) && window.DOMParser) { this._isSupportDOMParser = true; @@ -55,7 +57,7 @@ class SAXParser { _parseXML (textxml) { // get a reference to the requested corresponding xml file - var xmlDoc; + let xmlDoc; if (this._isSupportDOMParser) { xmlDoc = this._parser.parseFromString(textxml, "text/xml"); } else { @@ -81,17 +83,18 @@ class PlistParser extends SAXParser { * @return {*} plist object */ parse (xmlTxt) { - var xmlDoc = this._parseXML(xmlTxt); - var plist = xmlDoc.documentElement; + let xmlDoc = this._parseXML(xmlTxt); + let plist = xmlDoc.documentElement; if (plist.tagName !== 'plist') { cc.warnID(5100); return {}; } // Get first real node - var node = null; - for (var i = 0, len = plist.childNodes.length; i < len; i++) { + let node = null; + for (let i = 0, len = plist.childNodes.length; i < len; i++) { node = plist.childNodes[i]; + // @ts-ignore if (node.nodeType === 1) break; } @@ -100,7 +103,7 @@ class PlistParser extends SAXParser { } _parseNode (node) { - var data = null, tagName = node.tagName; + let data:any = null, tagName = node.tagName; if(tagName === "dict"){ data = this._parseDict(node); }else if(tagName === "array"){ @@ -111,7 +114,7 @@ class PlistParser extends SAXParser { else { //handle Firefox's 4KB nodeValue limit data = ""; - for (var i = 0; i < node.childNodes.length; i++) + for (let i = 0; i < node.childNodes.length; i++) data += node.childNodes[i].nodeValue; } }else if(tagName === "false"){ @@ -127,9 +130,9 @@ class PlistParser extends SAXParser { } _parseArray (node) { - var data = []; - for (var i = 0, len = node.childNodes.length; i < len; i++) { - var child = node.childNodes[i]; + let data:Array = []; + for (let i = 0, len = node.childNodes.length; i < len; i++) { + let child = node.childNodes[i]; if (child.nodeType !== 1) continue; data.push(this._parseNode(child)); @@ -138,10 +141,10 @@ class PlistParser extends SAXParser { } _parseDict (node) { - var data = {}; - var key = null; - for (var i = 0, len = node.childNodes.length; i < len; i++) { - var child = node.childNodes[i]; + let data = {}; + let key = null; + for (let i = 0, len = node.childNodes.length; i < len; i++) { + let child = node.childNodes[i]; if (child.nodeType !== 1) continue; @@ -149,6 +152,7 @@ class PlistParser extends SAXParser { if (child.tagName === 'key') key = child.firstChild.nodeValue; else + // @ts-ignore data[key] = this._parseNode(child); // Parse the value node } return data; @@ -160,6 +164,6 @@ class PlistParser extends SAXParser { * @name plistParser * A Plist Parser */ -var plistParser = new PlistParser(); +let plistParser = new PlistParser(); export default plistParser; \ No newline at end of file diff --git a/cocos/load-pipeline/released-asset-checker.js b/cocos/core/load-pipeline/released-asset-checker.ts similarity index 88% rename from cocos/load-pipeline/released-asset-checker.js rename to cocos/core/load-pipeline/released-asset-checker.ts index 702a91a4e1..87a66a546a 100644 --- a/cocos/load-pipeline/released-asset-checker.js +++ b/cocos/core/load-pipeline/released-asset-checker.ts @@ -28,18 +28,18 @@ * @category loader */ -import {createMap, getClassName, clear} from '../core/utils/js'; +import {createMap, getClassName, clear} from '../utils/js'; -var tmpInfo = null; +let _tmpInfo:any = null; function getItemDesc (item) { if (item.uuid) { - if (!tmpInfo) { - tmpInfo = { path: "", type: null }; + if (!_tmpInfo) { + _tmpInfo = { path: "", type: null }; } - if (cc.loader._assetTables.assets._getInfo_DEBUG(item.uuid, tmpInfo)) { - tmpInfo.path = 'resources/' + tmpInfo.path; - return `"${tmpInfo.path}" (type: ${getClassName(tmpInfo.type)}, uuid: ${item.uuid})`; + if (cc.loader._assetTables.assets._getInfo_DEBUG(item.uuid, _tmpInfo)) { + _tmpInfo.path = 'resources/' + _tmpInfo.path; + return `"${_tmpInfo.path}" (type: ${getClassName(_tmpInfo.type)}, uuid: ${item.uuid})`; } else { return `"${item.rawUrl}" (${item.uuid})`; @@ -60,6 +60,8 @@ function doCheckCouldRelease (releasedKey, refOwnerItem, caches) { // checks if asset was releasable export default class ReleasedAssetChecker { + private _releasedKeys; + private _dirty; constructor () { // { dependKey: true } this._releasedKeys = createMap(true); @@ -100,7 +102,7 @@ export default class ReleasedAssetChecker { } // // check current scene - // let depends = cc.director.getScene().dependAssets; + // let depends = director.getScene().dependAssets; // for (let i = 0; i < depends.length; ++i) { // let depend = depends[i]; // if (released[depend]) { diff --git a/cocos/load-pipeline/subpackage-pipe.js b/cocos/core/load-pipeline/subpackage-pipe.ts similarity index 54% rename from cocos/load-pipeline/subpackage-pipe.js rename to cocos/core/load-pipeline/subpackage-pipe.ts index ed69ff9059..3799450d15 100644 --- a/cocos/load-pipeline/subpackage-pipe.js +++ b/cocos/core/load-pipeline/subpackage-pipe.ts @@ -23,56 +23,57 @@ * @hidden */ -var decodeUuid = require('../core/utils/decode-uuid'); -var Pipeline = require('./pipeline'); +import decodeUuid from '../utils/decode-uuid'; +import { Pipeline, IPipe } from './pipeline'; const ID = 'SubPackPipe'; const UuidRegex = /([^/\\]*)\.[^\.]*$/; function getUuidFromURL(url) { - var matches = url.match(UuidRegex); + let matches = url.match(UuidRegex); if (matches) { return matches[1]; } return ""; } -var _uuidToSubPack = Object.create(null); +let _uuidToSubPack = Object.create(null); -var SubPackPipe = function (subpackage) { - this.id = ID; - this.async = false; - this.pipeline = null; - for (var packName in subpackage) { - var pack = subpackage[packName]; - pack.uuids && pack.uuids.forEach(function (val) { - var uuid = decodeUuid(val); - const uuids = uuid.split('@').map((name) => { - return encodeURIComponent(name); +export class SubPackPipe implements IPipe { + static ID = ID; + public id = ID; + public async = false; + public pipeline = null; + constructor (subpackage) { + for (let packName in subpackage) { + let pack = subpackage[packName]; + pack.uuids && pack.uuids.forEach(function (val) { + let uuid = decodeUuid(val); + const uuids = uuid.split('@').map((name) => { + return encodeURIComponent(name); + }); + uuid = uuids.join('@'); + _uuidToSubPack[uuid] = pack.path; }); - uuid = uuids.join('@'); - _uuidToSubPack[uuid] = pack.path; - }); - } -}; - -SubPackPipe.ID = ID; - -SubPackPipe.prototype.handle = function (item) { - item.url = this.transformURL(item.url); - return null; -}; - -SubPackPipe.prototype.transformURL = function (url) { - var uuid = getUuidFromURL(url); - if (uuid) { - var subpackage = _uuidToSubPack[uuid]; - if (subpackage) { - // only replace url of native assets - return url.replace('res/raw-assets/', subpackage + 'raw-assets/'); } } - return url; -}; -Pipeline.SubPackPipe = module.exports = SubPackPipe; + handle (item) { + item.url = this.transformURL(item.url); + return null; + } + + transformURL (url) { + let uuid = getUuidFromURL(url); + if (uuid) { + let subpackage = _uuidToSubPack[uuid]; + if (subpackage) { + // only replace url of native assets + return url.replace('res/raw-assets/', subpackage + 'raw-assets/'); + } + } + return url; + } +} + +// Pipeline.SubPackPipe = SubPackPipe; diff --git a/cocos/load-pipeline/text-downloader.js b/cocos/core/load-pipeline/text-downloader.ts similarity index 96% rename from cocos/load-pipeline/text-downloader.js rename to cocos/core/load-pipeline/text-downloader.ts index ac919c2e18..f251b776ba 100644 --- a/cocos/load-pipeline/text-downloader.js +++ b/cocos/core/load-pipeline/text-downloader.ts @@ -30,10 +30,10 @@ import {urlAppendTimestamp} from './utils'; export default function (item, callback) { - var url = item.url; + let url = item.url; url = urlAppendTimestamp(url); - var xhr = cc.loader.getXMLHttpRequest(), + let xhr = cc.loader.getXMLHttpRequest(), errInfo = 'Load text file failed: ' + url; xhr.open('GET', url, true); if (xhr.overrideMimeType) xhr.overrideMimeType('text/plain; charset=utf-8'); diff --git a/cocos/load-pipeline/unpackers.js b/cocos/core/load-pipeline/unpackers.ts similarity index 82% rename from cocos/load-pipeline/unpackers.js rename to cocos/core/load-pipeline/unpackers.ts index 93fa5fcedc..9b898953d8 100644 --- a/cocos/load-pipeline/unpackers.js +++ b/cocos/core/load-pipeline/unpackers.ts @@ -29,9 +29,7 @@ */ export class JsonUnpacker { - constructor () { - this.jsons = {}; - } + public jsons = {}; /* * @param {String[]} indices @@ -41,9 +39,9 @@ export class JsonUnpacker { if (packedJson.length !== indices.length) { cc.errorID(4915); } - for (var i = 0; i < indices.length; i++) { - var key = indices[i]; - var json = packedJson[i]; + for (let i = 0; i < indices.length; i++) { + let key = indices[i]; + let json = packedJson[i]; this.jsons[key] = json; } } @@ -55,26 +53,24 @@ export class JsonUnpacker { export class TextureUnpacker { - constructor () { - this.contents = {}; - } + public contents = {}; /* * @param {String[]} indices * @param {Object[]} packedJson */ load (indices, packedJson) { - var datas = packedJson.data; + let datas = packedJson.data; if (datas.length !== indices.length) { cc.errorID(4915); } - for (var i = 0; i < indices.length; i++) { + for (let i = 0; i < indices.length; i++) { this.contents[indices[i]] = {base: datas[i][0], mipmaps: datas[i][1]}; } } retrieve (key) { - var content = this.contents[key]; + let content = this.contents[key]; if (content) { return { __type__: cc.js._getClassId(cc.Texture2D), @@ -85,9 +81,4 @@ export class TextureUnpacker { return null; } } -} - -if (CC_TEST) { - cc._Test.JsonUnpacker = JsonUnpacker; - cc._Test.TextureUnpacker = TextureUnpacker; -} +} \ No newline at end of file diff --git a/cocos/load-pipeline/url.js b/cocos/core/load-pipeline/url.ts similarity index 100% rename from cocos/load-pipeline/url.js rename to cocos/core/load-pipeline/url.ts diff --git a/cocos/load-pipeline/utils.js b/cocos/core/load-pipeline/utils.ts similarity index 92% rename from cocos/load-pipeline/utils.js rename to cocos/core/load-pipeline/utils.ts index fcad0f4f01..9957fa5370 100644 --- a/cocos/load-pipeline/utils.js +++ b/cocos/core/load-pipeline/utils.ts @@ -27,13 +27,15 @@ * @category loader */ -var _noCacheRex = /\?/; +let _noCacheRex = /\?/; export function urlAppendTimestamp (url) { if (cc.game.config['noCache'] && typeof url === 'string') { if (_noCacheRex.test(url)) + //@ts-ignore url += '&_t=' + (new Date() - 0); else + //@ts-ignore url += '?_t=' + (new Date() - 0); } return url; @@ -42,11 +44,11 @@ export function urlAppendTimestamp (url) { export function decompressJson (data, keys) { if (Array.isArray(data)) { - for (var i = 0, l = data.length; i < l; i++) { + for (let i = 0, l = data.length; i < l; i++) { decompressJson(data[i], keys); } } else if (typeof data === 'object') { - for (var key in data) { + for (let key in data) { decompressJson(data[key], keys); if (!Number.isNaN(Number(key))) { data[keys[key]] = data[key]; diff --git a/cocos/load-pipeline/uuid-loader.js b/cocos/core/load-pipeline/uuid-loader.ts similarity index 79% rename from cocos/load-pipeline/uuid-loader.js rename to cocos/core/load-pipeline/uuid-loader.ts index 8d6b16d6b6..cebc013dc6 100644 --- a/cocos/load-pipeline/uuid-loader.js +++ b/cocos/core/load-pipeline/uuid-loader.ts @@ -28,16 +28,15 @@ * @category loader */ -import * as js from '../core/utils/js'; -import {_getClassById} from '../core/utils/js'; -import * as debug from '../core/platform/CCDebug'; -import deserialize from '../core/data/deserialize'; -import LoadingItems from './loading-items'; +import * as js from '../utils/js'; +import {_getClassById} from '../utils/js'; +import { getError } from '../platform/debug'; +import { LoadingItems } from './loading-items'; import {decompressJson} from './utils'; export function isSceneObj (json) { - var SCENE_ID = 'cc.Scene'; - var PREFAB_ID = 'cc.Prefab'; + let SCENE_ID = 'cc.Scene'; + let PREFAB_ID = 'cc.Prefab'; return json && ( (json[0] && json[0].__type__ === SCENE_ID) || (json[1] && json[1].__type__ === SCENE_ID) || @@ -46,26 +45,26 @@ export function isSceneObj (json) { } function parseDepends (item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { - var uuidList = tdInfo.uuidList; - var objList = tdInfo.uuidObjList; - var propList = tdInfo.uuidPropList; - var stillUseUrl = tdInfo._stillUseUrl; - var depends; - var i, dependUuid; + let uuidList = tdInfo.uuidList; + let objList = tdInfo.uuidObjList; + let propList = tdInfo.uuidPropList; + let stillUseUrl = tdInfo._stillUseUrl; + let depends; + let i, dependUuid; // cache dependencies for auto release - var dependKeys = item.dependKeys = []; + let dependKeys:Array = item.dependKeys = []; if (deferredLoadRawAssetsInRuntime) { depends = []; // parse depends assets for (i = 0; i < uuidList.length; i++) { dependUuid = uuidList[i]; - var obj = objList[i]; - var prop = propList[i]; - var info = cc.AssetLibrary._getAssetInfoInRuntime(dependUuid); + let obj = objList[i]; + let prop = propList[i]; + let info = cc.AssetLibrary._getAssetInfoInRuntime(dependUuid); if (info.raw) { // skip preloading raw assets - var url = info.url; + let url = info.url; obj[prop] = url; dependKeys.push(url); } @@ -113,33 +112,36 @@ function parseDepends (item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { function loadDepends (pipeline, item, asset, depends, callback) { // Predefine content for dependencies usage item.content = asset; - var dependKeys = item.dependKeys; + let dependKeys = item.dependKeys; pipeline.flowInDeps(item, depends, function (errors, items) { - var item, missingAssetReporter; - var itemsMap = items.map; - for (var src in itemsMap) { + let item, missingAssetReporter; + let itemsMap = items.map; + for (let src in itemsMap) { item = itemsMap[src]; if (item.uuid && item.content) { item.content._uuid = item.uuid; } } - for (var i = 0; i < depends.length; i++) { - var dep = depends[i]; - var dependSrc = dep.uuid; - var dependUrl = dep.url; - var dependObj = dep._owner; - var dependProp = dep._ownerProp; + for (let i = 0; i < depends.length; i++) { + let dep = depends[i]; + let dependSrc = dep.uuid; + let dependUrl = dep.url; + let dependObj = dep._owner; + let dependProp = dep._ownerProp; item = itemsMap[dependUrl]; if (!item) { continue; } - var loadCallbackCtx = dep; + let loadCallbackCtx = dep; + // @ts-ignore function loadCallback (item) { - var value = item.content; + let value = item.content; + // @ts-ignore if (this._stillUseUrl) { value = value ? value.nativeUrl : item.rawUrl; } + // @ts-ignore this._owner[this._ownerProp] = value; if (item.uuid !== asset._uuid && dependKeys.indexOf(item.id) < 0) { dependKeys.push(item.id); @@ -150,7 +152,7 @@ function loadDepends (pipeline, item, asset, depends, callback) { if (item.error) { if (CC_EDITOR && item.error.errorCode === 'db.NOTFOUND') { if (!missingAssetReporter) { - var MissingObjectReporter = Editor.require('app://editor/page/scene-utils/missing-object-reporter'); + let MissingObjectReporter = Editor.require('app://editor/page/scene-utils/missing-object-reporter'); missingAssetReporter = new MissingObjectReporter(asset); } missingAssetReporter.stashByOwner(dependObj, dependProp, Editor.serialize.asAsset(dependSrc)); @@ -165,9 +167,9 @@ function loadDepends (pipeline, item, asset, depends, callback) { } else { // item was removed from cache, but ready in pipeline actually - var queue = LoadingItems.getQueue(item); + let queue = LoadingItems.getQueue(item); // Hack to get a better behavior - var list = queue._callbackTable[dependSrc]; + let list = queue._callbackTable[dependSrc]; if (list) { list.unshift(loadCallback, loadCallbackCtx); } @@ -193,7 +195,7 @@ function canDeferredLoad (asset, item, isScene) { if (CC_EDITOR) { return false; } - var res = item.deferredLoadRaw; + let res = item.deferredLoadRaw; if (res) { // check if asset support deferred if ((asset instanceof cc.Asset) && asset.constructor.preventDeferredLoadDependents) { @@ -211,45 +213,45 @@ function canDeferredLoad (asset, item, isScene) { return res; } -var MissingClass; +let MissingClass; export function loadUuid (item, callback) { if (CC_EDITOR) { MissingClass = MissingClass || Editor.require('app://editor/page/scene-utils/missing-class-reporter').MissingClass; } - var json; + let json; if (typeof item.content === 'string') { try { json = JSON.parse(item.content); if (!CC_DEBUG && json.keys && json.data) { - var keys = json.keys; + let keys = json.keys; json = json.data; decompressJson(json, keys); } } catch (e) { - return new Error(debug.getError(4923, item.id, e.stack)); + return new Error(getError(4923, item.id, e.stack)); } } else if (typeof item.content === 'object') { json = item.content; } else { - return new Error(debug.getError(4924)); + return new Error(getError(4924)); } if (json === undefined || json === null) { - return new Error(debug.getError(4923, item.id)); + return new Error(getError(4923, item.id)); } - var classFinder; - var isScene = isSceneObj(json); + let classFinder; + let isScene = isSceneObj(json); if (isScene) { if (CC_EDITOR) { MissingClass.hasMissingClass = false; classFinder = function (type, data, owner, propName) { - var res = MissingClass.classFinder(type, data, owner, propName); + let res = MissingClass.classFinder(type, data, owner, propName); if (res) { return res; } @@ -263,7 +265,7 @@ export function loadUuid (item, callback) { } else { classFinder = function (id) { - var cls = js._getClassById(id); + let cls = js._getClassById(id); if (cls) { return cls; } @@ -272,9 +274,9 @@ export function loadUuid (item, callback) { }; } - var tdInfo = cc.deserialize.Details.pool.get(); + let tdInfo = cc.deserialize.Details.pool.get(); - var asset; + let asset; try { asset = cc.deserialize(json, tdInfo, { classFinder: classFinder, @@ -295,12 +297,12 @@ export function loadUuid (item, callback) { MissingClass.reportMissingClass(asset); } - var deferredLoad = canDeferredLoad(asset, item, isScene); - var depends = parseDepends(item, asset, tdInfo, deferredLoad); + let deferredLoad = canDeferredLoad(asset, item, isScene); + let depends = parseDepends(item, asset, tdInfo, deferredLoad); cc.deserialize.Details.pool.put(tdInfo); - var wrappedCallback = function(err, asset) { + let wrappedCallback = function(err, asset) { if (!err && asset.onLoaded) { try { asset.onLoaded(); @@ -309,9 +311,10 @@ export function loadUuid (item, callback) { } } if (CC_EDITOR && !isScene) { - var dependListener = cc.AssetLibrary.dependListener; - var assetListener = cc.AssetLibrary.assetListener; + let dependListener = cc.AssetLibrary.dependListener; + let assetListener = cc.AssetLibrary.assetListener; + // @ts-ignore function propSetter (asset, obj, propName, oldAsset, newAsset) { if (oldAsset === newAsset || obj[propName] === newAsset) { return; @@ -333,13 +336,13 @@ export function loadUuid (item, callback) { if (dependListener) { item.references = {}; - for (var i = 0, l = depends.length; i < l; i++) { - var dep = depends[i]; - var dependSrc = dep.uuid; + for (let i = 0, l = depends.length; i < l; i++) { + let dep = depends[i]; + let dependSrc = dep.uuid; if (dependSrc) { - var dependObj = dep._owner; - var dependProp = dep._ownerProp; - var onDirty = propSetter.bind(null, asset, dependObj, dependProp); + let dependObj = dep._owner; + let dependProp = dep._ownerProp; + let onDirty = propSetter.bind(null, asset, dependObj, dependProp); dependListener.on(dependSrc, onDirty); item.references[dependSrc] = onDirty; } @@ -353,6 +356,7 @@ export function loadUuid (item, callback) { return wrappedCallback(null, asset); } + // @ts-ignore loadDepends(this.pipeline, item, asset, depends, wrappedCallback); } diff --git a/cocos/core/math/color.ts b/cocos/core/math/color.ts index 2bdfa0fa5d..b0d6e7d695 100644 --- a/cocos/core/math/color.ts +++ b/cocos/core/math/color.ts @@ -31,7 +31,7 @@ import CCClass from '../data/class'; import { ValueType } from '../value-types/value-type'; import { IColorLike } from './type-define'; -import { EPSILON } from './utils'; +import { EPSILON, clamp } from './utils'; const toFloat = 1 / 255; @@ -180,7 +180,7 @@ export class Color extends ValueType { * @param ofs 数组起始偏移量 */ public static array (out: IWritableArrayLike, a: Out, ofs = 0) { - const scale = (a instanceof cc.Color || a.a > 1) ? 1 / 255 : 1; + const scale = (a instanceof Color || a.a > 1) ? 1 / 255 : 1; out[ofs + 0] = a.r * scale; out[ofs + 1] = a.g * scale; out[ofs + 2] = a.b * scale; @@ -221,7 +221,7 @@ export class Color extends ValueType { } set r (red) { - red = ~~cc.math.clamp(red, 0, 255); + red = ~~clamp(red, 0, 255); this._val = ((this._val & 0xffffff00) | red) >>> 0; } @@ -233,7 +233,7 @@ export class Color extends ValueType { } set g (green) { - green = ~~cc.math.clamp(green, 0, 255); + green = ~~clamp(green, 0, 255); this._val = ((this._val & 0xffff00ff) | (green << 8)) >>> 0; } @@ -245,7 +245,7 @@ export class Color extends ValueType { } set b (blue) { - blue = ~~cc.math.clamp(blue, 0, 255); + blue = ~~clamp(blue, 0, 255); this._val = ((this._val & 0xff00ffff) | (blue << 16)) >>> 0; } @@ -257,7 +257,7 @@ export class Color extends ValueType { } set a (alpha) { - alpha = ~~cc.math.clamp(alpha, 0, 255); + alpha = ~~clamp(alpha, 0, 255); this._val = ((this._val & 0x00ffffff) | ((alpha << 24) >>> 0)) >>> 0; } diff --git a/cocos/core/math/deprecated.ts b/cocos/core/math/deprecated.ts index 98f7f89ab4..25cd6b63c2 100644 --- a/cocos/core/math/deprecated.ts +++ b/cocos/core/math/deprecated.ts @@ -2,7 +2,7 @@ * @hidden */ -import { removeProperty, replaceProperty } from '../../deprecated'; +import { removeProperty, replaceProperty } from '../utils/deprecated'; import { Color } from './color'; import { Mat3 } from './mat3'; import { Mat4 } from './mat4'; diff --git a/cocos/core/math/index.ts b/cocos/core/math/index.ts index f1cfc55396..df41b15277 100644 --- a/cocos/core/math/index.ts +++ b/cocos/core/math/index.ts @@ -46,4 +46,4 @@ export { Rect } from './rect'; export { Color } from './color'; export * from './utils'; -import './deprecated'; +import './deprecated'; \ No newline at end of file diff --git a/cocos/3d/memop/circular-pool.ts b/cocos/core/memop/circular-pool.ts similarity index 100% rename from cocos/3d/memop/circular-pool.ts rename to cocos/core/memop/circular-pool.ts diff --git a/cocos/3d/memop/fixed-array.ts b/cocos/core/memop/fixed-array.ts similarity index 100% rename from cocos/3d/memop/fixed-array.ts rename to cocos/core/memop/fixed-array.ts diff --git a/cocos/3d/memop/index.ts b/cocos/core/memop/index.ts similarity index 100% rename from cocos/3d/memop/index.ts rename to cocos/core/memop/index.ts diff --git a/cocos/3d/memop/linked-array.ts b/cocos/core/memop/linked-array.ts similarity index 100% rename from cocos/3d/memop/linked-array.ts rename to cocos/core/memop/linked-array.ts diff --git a/cocos/3d/memop/optimized-array.ts b/cocos/core/memop/optimized-array.ts similarity index 100% rename from cocos/3d/memop/optimized-array.ts rename to cocos/core/memop/optimized-array.ts diff --git a/cocos/3d/memop/pool.ts b/cocos/core/memop/pool.ts similarity index 100% rename from cocos/3d/memop/pool.ts rename to cocos/core/memop/pool.ts diff --git a/cocos/3d/memop/recycle-pool.ts b/cocos/core/memop/recycle-pool.ts similarity index 100% rename from cocos/3d/memop/recycle-pool.ts rename to cocos/core/memop/recycle-pool.ts diff --git a/cocos/3d/memop/sort.ts b/cocos/core/memop/sort.ts similarity index 100% rename from cocos/3d/memop/sort.ts rename to cocos/core/memop/sort.ts diff --git a/cocos/3d/memop/timsort.ts b/cocos/core/memop/timsort.ts similarity index 100% rename from cocos/3d/memop/timsort.ts rename to cocos/core/memop/timsort.ts diff --git a/cocos/3d/memop/typed-array-pool.ts b/cocos/core/memop/typed-array-pool.ts similarity index 100% rename from cocos/3d/memop/typed-array-pool.ts rename to cocos/core/memop/typed-array-pool.ts diff --git a/cocos/pipeline/culling.ts b/cocos/core/pipeline/culling.ts similarity index 91% rename from cocos/pipeline/culling.ts rename to cocos/core/pipeline/culling.ts index b74da9f189..fe91235acc 100644 --- a/cocos/pipeline/culling.ts +++ b/cocos/core/pipeline/culling.ts @@ -2,8 +2,8 @@ * @hidden */ -import { frustum, intersect } from '../3d/geom-utils'; -import { Mat4, Vec3 } from '../core/math'; +import { frustum, intersect } from '../geom-utils'; +import { Mat4, Vec3, Quat } from '../math'; import { Camera, Light, Model } from '../renderer'; import { DirectionalLight } from '../renderer/scene/directional-light'; import { SphereLight } from '../renderer/scene/sphere-light'; @@ -47,15 +47,15 @@ export const cullSceneWithDirectionalLight = (() => { })(); export const calcDirectionalLightCullFrustum = (() => { - const lightPos = cc.v3(); - const lightViewCenter = cc.v3(); - const lightRot = cc.quat(); + const lightPos = new Vec3(); + const lightViewCenter = new Vec3(); + const lightRot = new Quat(); const camFrustum = new frustum(); camFrustum.accurate = true; - const lightViewMat = cc.mat4(); - const lightVeiwMatInv = cc.mat4(); - const minBoxCorner = cc.v3(); - const maxBoxCorner = cc.v3(); + const lightViewMat = new Mat4(); + const lightVeiwMatInv = new Mat4(); + const minBoxCorner = new Vec3(); + const maxBoxCorner = new Vec3(); return (out: frustum, sceneCamera: Camera, light: DirectionalLight, near: number, far: number, nearBias: number) => { Mat4.fromRT(lightViewMat, light.node.getWorldRotation(lightRot), sceneCamera.node.getWorldPosition(lightPos)); Mat4.invert(lightVeiwMatInv, lightViewMat); diff --git a/cocos/pipeline/define.ts b/cocos/core/pipeline/define.ts similarity index 100% rename from cocos/pipeline/define.ts rename to cocos/core/pipeline/define.ts diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/core/pipeline/forward/forward-flow.ts similarity index 100% rename from cocos/pipeline/forward/forward-flow.ts rename to cocos/core/pipeline/forward/forward-flow.ts diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/core/pipeline/forward/forward-pipeline.ts similarity index 97% rename from cocos/pipeline/forward/forward-pipeline.ts rename to cocos/core/pipeline/forward/forward-pipeline.ts index 0b45a30d42..626803eef0 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/core/pipeline/forward/forward-pipeline.ts @@ -2,9 +2,9 @@ * @category pipeline.forward */ -import { intersect, sphere } from '../../3d/geom-utils'; -import { Root } from '../../core/root'; -import { Vec3 } from '../../core/math'; +import { intersect, sphere } from '../../geom-utils'; +import { Root } from '../../root'; +import { Vec3 } from '../../math'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBindingType, GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; import { GFXRenderPass } from '../../gfx/render-pass'; @@ -14,7 +14,7 @@ import { LightType } from '../../renderer/scene/light'; import { SphereLight } from '../../renderer/scene/sphere-light'; import { SpotLight } from '../../renderer/scene/spot-light'; import { cullDirectionalLight, cullSphereLight, cullSpotLight } from '../culling'; -import { PIPELINE_FLOW_FORWARD, PIPELINE_FLOW_SMAA, PIPELINE_FLOW_TONEMAP, RenderPassStage, UBOForwardLight } from '../define'; +import { PIPELINE_FLOW_FORWARD, PIPELINE_FLOW_TONEMAP, RenderPassStage, UBOForwardLight } from '../define'; import { ToneMapFlow } from '../ppfx/tonemap-flow'; import { IRenderPipelineInfo, RenderPipeline } from '../render-pipeline'; import { RenderView } from '../render-view'; diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/core/pipeline/forward/forward-stage.ts similarity index 100% rename from cocos/pipeline/forward/forward-stage.ts rename to cocos/core/pipeline/forward/forward-stage.ts diff --git a/cocos/pipeline/index.ts b/cocos/core/pipeline/index.ts similarity index 100% rename from cocos/pipeline/index.ts rename to cocos/core/pipeline/index.ts diff --git a/cocos/pipeline/pass-phase.ts b/cocos/core/pipeline/pass-phase.ts similarity index 100% rename from cocos/pipeline/pass-phase.ts rename to cocos/core/pipeline/pass-phase.ts diff --git a/cocos/pipeline/pipeline-funcs.ts b/cocos/core/pipeline/pipeline-funcs.ts similarity index 100% rename from cocos/pipeline/pipeline-funcs.ts rename to cocos/core/pipeline/pipeline-funcs.ts diff --git a/cocos/pipeline/ppfx/tonemap-flow.ts b/cocos/core/pipeline/ppfx/tonemap-flow.ts similarity index 100% rename from cocos/pipeline/ppfx/tonemap-flow.ts rename to cocos/core/pipeline/ppfx/tonemap-flow.ts diff --git a/cocos/pipeline/ppfx/tonemap-stage.ts b/cocos/core/pipeline/ppfx/tonemap-stage.ts similarity index 100% rename from cocos/pipeline/ppfx/tonemap-stage.ts rename to cocos/core/pipeline/ppfx/tonemap-stage.ts diff --git a/cocos/pipeline/render-flow.ts b/cocos/core/pipeline/render-flow.ts similarity index 98% rename from cocos/pipeline/render-flow.ts rename to cocos/core/pipeline/render-flow.ts index 7211d294a1..4cbe1cf5d2 100644 --- a/cocos/pipeline/render-flow.ts +++ b/cocos/core/pipeline/render-flow.ts @@ -2,7 +2,7 @@ * @category pipeline */ -import { Material } from '../3d/assets/material'; +import { Material } from '../assets/material'; import { GFXDevice } from '../gfx/device'; import { RenderPipeline } from './render-pipeline'; import { IRenderStageInfo, RenderStage } from './render-stage'; diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts similarity index 99% rename from cocos/pipeline/render-pipeline.ts rename to cocos/core/pipeline/render-pipeline.ts index 0beb093be8..fd6db6d3f2 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -2,9 +2,9 @@ * @category pipeline */ -import { intersect } from '../3d/geom-utils'; -import { Root } from '../core/root'; -import { Mat4, Vec3, Vec4 } from '../core/math'; +import { intersect } from '../geom-utils'; +import { Root } from '../root'; +import { Mat4, Vec3, Vec4 } from '../math'; import { GFXBuffer } from '../gfx/buffer'; import { GFXBindingType, diff --git a/cocos/pipeline/render-queue.ts b/cocos/core/pipeline/render-queue.ts similarity index 98% rename from cocos/pipeline/render-queue.ts rename to cocos/core/pipeline/render-queue.ts index 1c2f0fdb9c..b2ef27f0d8 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/core/pipeline/render-queue.ts @@ -2,7 +2,7 @@ * @category pipeline */ -import { CachedArray } from '../core/memop/cached-array'; +import { CachedArray } from '../memop/cached-array'; import { GFXCommandBuffer } from '../gfx/command-buffer'; import { IRenderObject, IRenderPass, IRenderQueueDesc } from './define'; diff --git a/cocos/pipeline/render-stage.ts b/cocos/core/pipeline/render-stage.ts similarity index 100% rename from cocos/pipeline/render-stage.ts rename to cocos/core/pipeline/render-stage.ts diff --git a/cocos/pipeline/render-view.ts b/cocos/core/pipeline/render-view.ts similarity index 99% rename from cocos/pipeline/render-view.ts rename to cocos/core/pipeline/render-view.ts index f6164eaecb..313af18c5d 100644 --- a/cocos/pipeline/render-view.ts +++ b/cocos/core/pipeline/render-view.ts @@ -2,7 +2,7 @@ * @category pipeline */ -import { Root } from '../core/root'; +import { Root } from '../root'; import { GFXWindow } from '../gfx/window'; import { Camera, CameraVisFlags } from '../renderer/scene/camera'; import { RenderFlow } from './render-flow'; diff --git a/cocos/pipeline/ui/ui-flow.ts b/cocos/core/pipeline/ui/ui-flow.ts similarity index 100% rename from cocos/pipeline/ui/ui-flow.ts rename to cocos/core/pipeline/ui/ui-flow.ts diff --git a/cocos/pipeline/ui/ui-stage.ts b/cocos/core/pipeline/ui/ui-stage.ts similarity index 100% rename from cocos/pipeline/ui/ui-stage.ts rename to cocos/core/pipeline/ui/ui-stage.ts diff --git a/cocos/core/platform/CCDebug.ts b/cocos/core/platform/debug.ts similarity index 99% rename from cocos/core/platform/CCDebug.ts rename to cocos/core/platform/debug.ts index e5eaab32ef..5c9d38b16a 100644 --- a/cocos/core/platform/CCDebug.ts +++ b/cocos/core/platform/debug.ts @@ -339,8 +339,8 @@ export enum DebugMode { * @en Gets error message with the error id and possible parameters. * @zh 通过 error id 和必要的参数来获取错误信息。 */ -export function getError (errorId: any, param?: any): string { - return errorFormatter(errorId, param); +export function getError (errorId: any, ...param: any[]): string { + return errorFormatter(errorId, ...param); } /** diff --git a/cocos/core/platform/event-manager/event-listener.ts b/cocos/core/platform/event-manager/event-listener.ts index 25f69fe1fc..ac1fbf1a22 100644 --- a/cocos/core/platform/event-manager/event-listener.ts +++ b/cocos/core/platform/event-manager/event-listener.ts @@ -30,7 +30,7 @@ */ import { INode } from '../../utils/interfaces'; -import { EventKeyboard, EventAcceleration, EventMouse } from './CCEvent'; +import { EventKeyboard, EventAcceleration, EventMouse } from './events'; export interface IEventListenerCreateInfo { event?: number; diff --git a/cocos/core/platform/event-manager/event-manager.ts b/cocos/core/platform/event-manager/event-manager.ts index 39ac5f08a5..97627d8921 100644 --- a/cocos/core/platform/event-manager/event-manager.ts +++ b/cocos/core/platform/event-manager/event-manager.ts @@ -32,7 +32,7 @@ import { Event } from '../../event'; import { INode } from '../../utils/interfaces'; -import { EventTouch } from './CCEvent'; +import { EventTouch } from './events'; import { EventListener, TouchOneByOne } from './event-listener'; const ListenerID = EventListener.ListenerID; diff --git a/cocos/core/platform/event-manager/CCEvent.ts b/cocos/core/platform/event-manager/events.ts similarity index 99% rename from cocos/core/platform/event-manager/CCEvent.ts rename to cocos/core/platform/event-manager/events.ts index c66c2c15d7..a13ce6c9df 100644 --- a/cocos/core/platform/event-manager/CCEvent.ts +++ b/cocos/core/platform/event-manager/events.ts @@ -30,7 +30,8 @@ import Event from '../../event/event'; import { Vec2 } from '../../math'; -import { Touch } from './CCTouch'; +import { Touch } from './touch'; +import { view } from '../view'; /** * @en The mouse event @@ -261,7 +262,7 @@ export class EventMouse extends Event { out = new Vec2(); } - Vec2.set(out, this._x, cc.view._designResolutionSize.height - this._y); + Vec2.set(out, this._x, view._designResolutionSize.height - this._y); return out; } diff --git a/cocos/core/platform/event-manager/index.ts b/cocos/core/platform/event-manager/index.ts index 0260c6acdf..5b15441d6f 100644 --- a/cocos/core/platform/event-manager/index.ts +++ b/cocos/core/platform/event-manager/index.ts @@ -31,10 +31,6 @@ export * from './event-manager'; export * from './input-manager'; export * from './system-event'; -export * from './CCEvent'; -export * from './CCTouch'; -export * from './event-enum'; - -if (CC_TEST) { - // cc._Test.eventManager = eventManager; -} +export * from './events'; +export * from './touch'; +export * from './event-enum'; \ No newline at end of file diff --git a/cocos/core/platform/event-manager/input-manager.ts b/cocos/core/platform/event-manager/input-manager.ts index 1f86f88ddf..53cdaf7a72 100644 --- a/cocos/core/platform/event-manager/input-manager.ts +++ b/cocos/core/platform/event-manager/input-manager.ts @@ -30,11 +30,11 @@ import { Vec2 } from '../../math/index'; import { rect } from '../../math/rect'; -import { macro } from '../CCMacro'; -import sys from '../CCSys'; -import { EventAcceleration, EventKeyboard, EventMouse, EventTouch } from './CCEvent'; +import { macro } from '../macro'; +import sys from '../sys'; +import { EventAcceleration, EventKeyboard, EventMouse, EventTouch } from './events'; +import { Touch } from './touch'; import eventManager from './event-manager'; -import { Touch as CCTouch } from './CCTouch'; const TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; @@ -61,7 +61,7 @@ interface IView { _convertMouseToLocation (point: Vec2, elementPosition: IHTMLElementPosition): void; // _convertMouseToLocationInView (point: Vec2, elementPosition: IHTMLElementPosition): void; - // _convertTouchesWithScale (touches: CCTouch[]): void; + // _convertTouchesWithScale (touches: Touch[]): void; } /** @@ -92,10 +92,10 @@ class InputManager { private _preTouchPoint = new Vec2(); private _prevMousePoint = new Vec2(); - private _preTouchPool: CCTouch[] = []; + private _preTouchPool: Touch[] = []; private _preTouchPoolPointer = 0; - private _touches: CCTouch[] = []; + private _touches: Touch[] = []; private _touchesIntegerDict: { [index: number]: number | undefined; } = { }; private _indexBitsUsed = 0; @@ -114,8 +114,8 @@ class InputManager { private _pointLocked = false; - public handleTouchesBegin (touches: CCTouch[]) { - const handleTouches: CCTouch[] = []; + public handleTouchesBegin (touches: Touch[]) { + const handleTouches: Touch[] = []; const locTouchIntDict = this._touchesIntegerDict; const now = sys.now(); for (let i = 0; i < touches.length; ++i) { @@ -132,7 +132,7 @@ class InputManager { continue; } // curTouch = this._touches[unusedIndex] = touch; - const curTouch = new CCTouch(touch._point.x, touch._point.y, touch.getID()); + const curTouch = new Touch(touch._point.x, touch._point.y, touch.getID()); this._touches[unusedIndex] = curTouch; curTouch._lastModified = now; curTouch._setPrevPoint(touch._prevPoint); @@ -148,8 +148,8 @@ class InputManager { } } - public handleTouchesMove (touches: CCTouch[]) { - const handleTouches: CCTouch[] = []; + public handleTouchesMove (touches: Touch[]) { + const handleTouches: Touch[] = []; const locTouches = this._touches; const now = sys.now(); for (let i = 0; i < touches.length; ++i) { @@ -178,7 +178,7 @@ class InputManager { } } - public handleTouchesEnd (touches: CCTouch[]) { + public handleTouchesEnd (touches: Touch[]) { const handleTouches = this.getSetOfTouchesEndOrCancel(touches); if (handleTouches.length > 0) { // this._glView!._convertTouchesWithScale(handleTouches); @@ -189,7 +189,7 @@ class InputManager { this._preTouchPool.length = 0; } - public handleTouchesCancel (touches: CCTouch[]) { + public handleTouchesCancel (touches: Touch[]) { const handleTouches = this.getSetOfTouchesEndOrCancel(touches); if (handleTouches.length > 0) { // this._glView!._convertTouchesWithScale(handleTouches); @@ -200,8 +200,8 @@ class InputManager { this._preTouchPool.length = 0; } - public getSetOfTouchesEndOrCancel (touches: CCTouch[]) { - const handleTouches: CCTouch[] = []; + public getSetOfTouchesEndOrCancel (touches: Touch[]) { + const handleTouches: Touch[] = []; const locTouches = this._touches; const locTouchesIntDict = this._touchesIntegerDict; for (let i = 0; i < touches.length; ++i) { @@ -266,8 +266,8 @@ class InputManager { } } - public getPreTouch (touch: CCTouch) { - let preTouch: CCTouch | null = null; + public getPreTouch (touch: Touch) { + let preTouch: Touch | null = null; const locPreTouchPool = this._preTouchPool; const id = touch.getID(); for (let i = locPreTouchPool.length - 1; i >= 0; i--) { @@ -282,7 +282,7 @@ class InputManager { return preTouch; } - public setPreTouch (touch: CCTouch) { + public setPreTouch (touch: Touch) { let find = false; const locPreTouchPool = this._preTouchPool; const id = touch.getID(); @@ -310,7 +310,7 @@ class InputManager { location.x = locPreTouch.x + event.movementX; location.y = locPreTouch.y - event.movementY; } - const touch = new CCTouch(location.x, location.y, 0); + const touch = new Touch(location.x, location.y, 0); touch._setPrevPoint(locPreTouch.x, locPreTouch.y); locPreTouch.x = location.x; locPreTouch.y = location.y; @@ -346,7 +346,7 @@ class InputManager { } public getTouchesByEvent (event: TouchEvent, position: IHTMLElementPosition) { - const touches: CCTouch[] = []; + const touches: Touch[] = []; const locView = this._glView; const locPreTouch = this._preTouchPoint; @@ -365,15 +365,15 @@ class InputManager { location = locView!.convertToLocationInView( changedTouch.clientX, changedTouch.clientY, position, _vec2); } - let touch: CCTouch; + let touch: Touch; if (changedTouch.identifier != null) { - touch = new CCTouch(location.x, location.y, changedTouch.identifier); + touch = new Touch(location.x, location.y, changedTouch.identifier); // use Touch Pool this.getPreTouch(touch).getLocation(_preLocation); touch._setPrevPoint(_preLocation.x, _preLocation.y); this.setPreTouch(touch); } else { - touch = new CCTouch(location.x, location.y); + touch = new Touch(location.x, location.y); touch._setPrevPoint(locPreTouch.x, locPreTouch.y); } locPreTouch.x = location.x; diff --git a/cocos/core/platform/event-manager/system-event.ts b/cocos/core/platform/event-manager/system-event.ts index 6e37ccc2cc..469e0cd973 100644 --- a/cocos/core/platform/event-manager/system-event.ts +++ b/cocos/core/platform/event-manager/system-event.ts @@ -29,12 +29,12 @@ */ import { EventTarget } from '../../event/event-target'; -import { EventAcceleration, EventKeyboard, EventMouse, EventTouch } from './CCEvent'; +import { EventAcceleration, EventKeyboard, EventMouse, EventTouch } from './events'; import { SystemEventType } from './event-enum'; import { EventListener } from './event-listener'; import eventManager from './event-manager'; import inputManager from './input-manager'; -import { Touch } from './CCTouch'; +import { Touch } from './touch'; /** * @en diff --git a/cocos/core/platform/event-manager/CCTouch.ts b/cocos/core/platform/event-manager/touch.ts similarity index 99% rename from cocos/core/platform/event-manager/CCTouch.ts rename to cocos/core/platform/event-manager/touch.ts index bbbaf3dedc..131660b5ab 100644 --- a/cocos/core/platform/event-manager/CCTouch.ts +++ b/cocos/core/platform/event-manager/touch.ts @@ -29,6 +29,7 @@ */ import { Vec2 } from '../../math'; +import { view } from '../view'; const _vec2 = new Vec2(); /** @@ -91,7 +92,7 @@ export class Touch { } out.set(this._point.x, this._point.y); - cc.view._convertPointWithScale(out); + view._convertPointWithScale(out); return out; } diff --git a/cocos/core/platform/index.ts b/cocos/core/platform/index.ts index 7a4cdbe71b..93b739f380 100644 --- a/cocos/core/platform/index.ts +++ b/cocos/core/platform/index.ts @@ -24,11 +24,11 @@ THE SOFTWARE. */ -export * from './CCSys'; -export * from './CCMacro'; -export * from './CCVisibleRect'; -export * from './CCView'; +export * from './sys'; +export * from './macro'; +export * from './visible-rect'; +export * from './view'; export * from './event-manager'; -import { screen } from './CCScreen'; +import { screen } from './screen'; export { screen }; diff --git a/cocos/core/platform/CCMacro.ts b/cocos/core/platform/macro.ts similarity index 100% rename from cocos/core/platform/CCMacro.ts rename to cocos/core/platform/macro.ts diff --git a/cocos/core/platform/CCScreen.ts b/cocos/core/platform/screen.ts similarity index 100% rename from cocos/core/platform/CCScreen.ts rename to cocos/core/platform/screen.ts diff --git a/cocos/core/platform/CCSys.ts b/cocos/core/platform/sys.ts similarity index 100% rename from cocos/core/platform/CCSys.ts rename to cocos/core/platform/sys.ts diff --git a/cocos/core/platform/CCView.ts b/cocos/core/platform/view.ts similarity index 94% rename from cocos/core/platform/CCView.ts rename to cocos/core/platform/view.ts index 8b77ae2eea..512aa2808e 100644 --- a/cocos/core/platform/CCView.ts +++ b/cocos/core/platform/view.ts @@ -1,1624 +1,1625 @@ -/* - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - 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. -*/ - -import '../data/class'; -import { EventTarget } from '../event/event-target'; -import { Game } from '../game'; -import { Rect, Size } from '../math'; - -let _currentFrame = 0; - -class BrowserGetter { - - public html: HTMLHtmlElement | undefined; - - public meta = { - width: 'device-width', - }; - - public adaptationType: any = cc.sys.browserType; - - public init () { - if (!CC_WECHATGAME && !CC_QQPLAY) { - this.html = document.getElementsByTagName('html')[0]; - } - } - - public availWidth (frame) { - if (cc.sys.isMobile || !frame || frame === this.html) { - return window.innerWidth; - } - else { - return frame.clientWidth; - } - } - - public availHeight (frame) { - if (cc.sys.isMobile || !frame || frame === this.html) { - return window.innerHeight; - } - else { - return frame.clientHeight; - } - } -} - -const __BrowserGetter = new BrowserGetter(); - -if (cc.sys.os === cc.sys.OS_IOS) { // All browsers are WebView - __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI; -} - -if (CC_WECHATGAME) { - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { - __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB; - } - else { - __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME; - } -} - -if (CC_QQPLAY) { - __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_QQ_PLAY; -} - -switch (__BrowserGetter.adaptationType) { - case cc.sys.BROWSER_TYPE_SAFARI: - __BrowserGetter.meta['minimal-ui'] = 'true'; - case cc.sys.BROWSER_TYPE_SOUGOU: - case cc.sys.BROWSER_TYPE_WECHAT_GAME: - __BrowserGetter.availWidth = () => { - return window.innerWidth; - }; - __BrowserGetter.availHeight = () => { - return window.innerHeight; - }; - break; - case cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB: - const sharedCanvas = window.sharedCanvas || wx.getSharedCanvas(); - __BrowserGetter.availWidth = () => { - return sharedCanvas.width; - }; - __BrowserGetter.availHeight = () => { - return sharedCanvas.height; - }; - break; -} - -let _scissorRect: Rect | null = null; - -/** - * cc.view is the singleton object which represents the game window.
- * It's main task include:
- * - Apply the design resolution policy
- * - Provide interaction with the window, like resize event on web, retina display support, etc...
- * - Manage the game view port which can be different with the window
- * - Manage the content scale and translation
- *
- * Since the cc.view is a singleton, you don't need to call any constructor or create functions,
- * the standard way to use it is by calling:
- * - cc.view.methodName();
- * - * @class View - */ -class View extends EventTarget { - - private _frameSize: Size; - private _designResolutionSize: Size; - private _originalDesignResolutionSize: Size; - private _scaleX: number; - private _scaleY: number; - private _viewportRect: Rect; - private _visibleRect: Rect; - private _autoFullScreen: boolean; - private _devicePixelRatio: number; - private _retinaEnabled: boolean; - private _resizeCallback: null; - private _resizing: boolean; - private _resizeWithBrowserSize: boolean; - private _orientationChanging: boolean; - private _isRotated: boolean; - private _orientation: any; - private _isAdjustViewport: boolean; - private _antiAliasEnabled: boolean; - private _resolutionPolicy: any; - private _rpExactFit: ResolutionPolicy; - private _rpShowAll: ResolutionPolicy; - private _rpNoBorder: ResolutionPolicy; - private _rpFixedHeight: ResolutionPolicy; - private _rpFixedWidth: ResolutionPolicy; - - constructor () { - super(); - - const _t = this; - const _strategyer = ContainerStrategy; - const _strategy = ContentStrategy; - - // Size of parent node that contains cc.game.container and cc.game.canvas - this._frameSize = new Size(0, 0); - - // resolution size, it is the size appropriate for the app resources. - this._designResolutionSize = new Size(0, 0); - this._originalDesignResolutionSize = new Size(0, 0); - this._scaleX = 1; - this._scaleY = 1; - // Viewport is the container's rect related to content's coordinates in pixel - this._viewportRect = new Rect(0, 0, 0, 0); - // The visible rect in content's coordinate in point - this._visibleRect = new Rect(0, 0, 0, 0); - // Auto full screen disabled by default - this._autoFullScreen = false; - // The device's pixel ratio (for retina displays) - this._devicePixelRatio = 1; - // Retina disabled by default - this._retinaEnabled = false; - // Custom callback for resize event - this._resizeCallback = null; - this._resizing = false; - this._resizeWithBrowserSize = false; - this._orientationChanging = true; - this._isRotated = false; - this._orientation = cc.macro.ORIENTATION_AUTO; - this._isAdjustViewport = true; - this._antiAliasEnabled = false; - - // Setup system default resolution policies - this._resolutionPolicy = null; - this._rpExactFit = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT); - this._rpShowAll = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.SHOW_ALL); - this._rpNoBorder = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.NO_BORDER); - this._rpFixedHeight = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT); - this._rpFixedWidth = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); - - cc.game.once(Game.EVENT_ENGINE_INITED, this.init, this); - } - - public init () { - __BrowserGetter.init(); - - this._initFrameSize(); - this.enableAntiAlias(true); - - const w = cc.game.canvas.width; - const h = cc.game.canvas.height; - this._designResolutionSize.width = w; - this._designResolutionSize.height = h; - this._originalDesignResolutionSize.width = w; - this._originalDesignResolutionSize.height = h; - this._viewportRect.width = w; - this._viewportRect.height = h; - this._visibleRect.width = w; - this._visibleRect.height = h; - - cc.winSize.width = this._visibleRect.width; - cc.winSize.height = this._visibleRect.height; - if (cc.visibleRect) { - cc.visibleRect.init(this._visibleRect); - } - } - - /** - * @en - * Sets view's target-densitydpi for android mobile browser. it can be set to:
- * 1. macro.DENSITYDPI_DEVICE, value is "device-dpi"
- * 2. macro.DENSITYDPI_HIGH, value is "high-dpi" (default value)
- * 3. macro.DENSITYDPI_MEDIUM, value is "medium-dpi" (browser's default value)
- * 4. macro.DENSITYDPI_LOW, value is "low-dpi"
- * 5. Custom value, e.g: "480"
- * @zh 设置目标内容的每英寸像素点密度。 - * - * @method setTargetDensityDPI - * @param {String} densityDPI - * @deprecated since v2.0 - */ - - /** - * @en - * Returns the current target-densitydpi value of cc.view. - * @zh 获取目标内容的每英寸像素点密度。 - * @method getTargetDensityDPI - * @returns {String} - * @deprecated since v2.0 - */ - - /** - * @en - * Sets whether resize canvas automatically when browser's size changed.
- * Useful only on web. - * @zh 设置当发现浏览器的尺寸改变时,是否自动调整 canvas 尺寸大小。 - * 仅在 Web 模式下有效。 - * @method resizeWithBrowserSize - * @param {Boolean} enabled - Whether enable automatic resize with browser's resize event - */ - public resizeWithBrowserSize (enabled) { - if (enabled) { - // enable - if (!this._resizeWithBrowserSize) { - this._resizeWithBrowserSize = true; - window.addEventListener('resize', this._resizeEvent); - window.addEventListener('orientationchange', this._orientationChange); - } - } else { - // disable - if (this._resizeWithBrowserSize) { - this._resizeWithBrowserSize = false; - window.removeEventListener('resize', this._resizeEvent); - window.removeEventListener('orientationchange', this._orientationChange); - } - } - } - - /** - * @en - * Sets the callback function for cc.view's resize action,
- * this callback will be invoked before applying resolution policy,
- * so you can do any additional modifications within the callback.
- * Useful only on web. - * @zh 设置 cc.view 调整视窗尺寸行为的回调函数, - * 这个回调函数会在应用适配模式之前被调用, - * 因此你可以在这个回调函数内添加任意附加改变, - * 仅在 Web 平台下有效。 - * @method setResizeCallback - * @param {Function|Null} callback - The callback function - */ - public setResizeCallback (callback) { - if (typeof callback === 'function' || callback == null) { - this._resizeCallback = callback; - } - } - - /** - * @en - * Sets the orientation of the game, it can be landscape, portrait or auto. - * When set it to landscape or portrait, and screen w/h ratio doesn't fit, - * cc.view will automatically rotate the game canvas using CSS. - * Note that this function doesn't have any effect in native, - * in native, you need to set the application orientation in native project settings - * @zh 设置游戏屏幕朝向,它能够是横版,竖版或自动。 - * 当设置为横版或竖版,并且屏幕的宽高比例不匹配时, - * cc.view 会自动用 CSS 旋转游戏场景的 canvas, - * 这个方法不会对 native 部分产生任何影响,对于 native 而言,你需要在应用设置中的设置排版。 - * @method setOrientation - * @param {Number} orientation - Possible values: macro.ORIENTATION_LANDSCAPE | macro.ORIENTATION_PORTRAIT | macro.ORIENTATION_AUTO - */ - public setOrientation (orientation) { - orientation = orientation & cc.macro.ORIENTATION_AUTO; - if (orientation && this._orientation !== orientation) { - this._orientation = orientation; - } - } - - /** - * @en - * Sets whether the engine modify the "viewport" meta in your web page.
- * It's enabled by default, we strongly suggest you not to disable it.
- * And even when it's enabled, you can still set your own "viewport" meta, it won't be overridden
- * Only useful on web - * @zh 设置引擎是否调整 viewport meta 来配合屏幕适配。 - * 默认设置为启动,我们强烈建议你不要将它设置为关闭。 - * 即使当它启动时,你仍然能够设置你的 viewport meta,它不会被覆盖。 - * 仅在 Web 模式下有效 - * @method adjustViewportMeta - * @param {Boolean} enabled - Enable automatic modification to "viewport" meta - */ - public adjustViewportMeta (enabled) { - this._isAdjustViewport = enabled; - } - - /** - * @en - * Retina support is enabled by default for Apple device but disabled for other devices,
- * it takes effect only when you called setDesignResolutionPolicy
- * Only useful on web - * @zh 对于 Apple 这种支持 Retina 显示的设备上默认进行优化而其他类型设备默认不进行优化, - * 它仅会在你调用 setDesignResolutionPolicy 方法时有影响。 - * 仅在 Web 模式下有效。 - * @method enableRetina - * @param {Boolean} enabled - Enable or disable retina display - */ - public enableRetina (enabled) { - this._retinaEnabled = !!enabled; - } - - /** - * @en - * Check whether retina display is enabled.
- * Only useful on web - * @zh 检查是否对 Retina 显示设备进行优化。 - * 仅在 Web 模式下有效。 - * @method isRetinaEnabled - * @return {Boolean} - */ - public isRetinaEnabled () { - return this._retinaEnabled; - } - - /** - * @en Whether to Enable on anti-alias - * @zh 控制抗锯齿是否开启 - * @method enableAntiAlias - * @param {Boolean} enabled - Enable or not anti-alias - */ - public enableAntiAlias (enabled) { - if (this._antiAliasEnabled === enabled) { - return; - } - this._antiAliasEnabled = enabled; - if (cc.game.renderType === Game.RENDER_TYPE_WEBGL) { - const cache = cc.loader._cache; - // tslint:disable-next-line: forin - for (const key in cache) { - const item = cache[key]; - const tex = item && item.content instanceof cc.Texture2D ? item.content : null; - if (tex) { - const Filter = cc.Texture2D.Filter; - if (enabled) { - tex.setFilters(Filter.LINEAR, Filter.LINEAR); - } - else { - tex.setFilters(Filter.NEAREST, Filter.NEAREST); - } - } - } - } - else if (cc.game.renderType === Game.RENDER_TYPE_CANVAS) { - const ctx = cc.game.canvas.getContext('2d'); - ctx.imageSmoothingEnabled = enabled; - ctx.mozImageSmoothingEnabled = enabled; - } - } - - /** - * @en Returns whether the current enable on anti-alias - * @zh 返回当前是否抗锯齿 - * @method isAntiAliasEnabled - * @return {Boolean} - */ - public isAntiAliasEnabled () { - return this._antiAliasEnabled; - } - /** - * @en - * If enabled, the application will try automatically to enter full screen mode on mobile devices
- * You can pass true as parameter to enable it and disable it by passing false.
- * Only useful on web - * @zh 启动时,移动端游戏会在移动端自动尝试进入全屏模式。 - * 你能够传入 true 为参数去启动它,用 false 参数来关闭它。 - * @method enableAutoFullScreen - * @param {Boolean} enabled - Enable or disable auto full screen on mobile devices - */ - public enableAutoFullScreen (enabled) { - if (enabled && - enabled !== this._autoFullScreen && - cc.sys.isMobile && - cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT) { - // Automatically full screen when user touches on mobile version - this._autoFullScreen = true; - cc.screen.autoFullScreen(cc.game.frame); - } - else { - this._autoFullScreen = false; - } - } - - /** - * @en - * Check whether auto full screen is enabled.
- * Only useful on web - * @zh 检查自动进入全屏模式是否启动。 - * 仅在 Web 模式下有效。 - * @method isAutoFullScreenEnabled - * @return {Boolean} Auto full screen enabled or not - */ - public isAutoFullScreenEnabled () { - return this._autoFullScreen; - } - - /* - * Not support on native.
- * On web, it sets the size of the canvas. - * @zh 这个方法并不支持 native 平台,在 Web 平台下,可以用来设置 canvas 尺寸。 - * @method setCanvasSize - * @param {Number} width - * @param {Number} height - */ - public setCanvasSize (width, height) { - const canvas = cc.game.canvas; - const container = cc.game.container; - - canvas.width = width * this._devicePixelRatio; - canvas.height = height * this._devicePixelRatio; - - // canvas.width = width; - // canvas.height = height; - - canvas.style.width = width + 'px'; - canvas.style.height = height + 'px'; - - container.style.width = width + 'px'; - container.style.height = height + 'px'; - - this._resizeEvent(); - } - - /** - * @en - * Returns the canvas size of the view.
- * On native platforms, it returns the screen size since the view is a fullscreen view.
- * On web, it returns the size of the canvas element. - * @zh 返回视图中 canvas 的尺寸。 - * 在 native 平台下,它返回全屏视图下屏幕的尺寸。 - * 在 Web 平台下,它返回 canvas 元素尺寸。 - * @method getCanvasSize - * @return {Size} - */ - public getCanvasSize () { - return cc.size(cc.game.canvas.width, cc.game.canvas.height); - } - - /** - * @en - * Returns the frame size of the view.
- * On native platforms, it returns the screen size since the view is a fullscreen view.
- * On web, it returns the size of the canvas's outer DOM element. - * @zh 返回视图中边框尺寸。 - * 在 native 平台下,它返回全屏视图下屏幕的尺寸。 - * 在 web 平台下,它返回 canvas 元素的外层 DOM 元素尺寸。 - * @method getFrameSize - * @return {Size} - */ - public getFrameSize () { - return cc.size(this._frameSize.width, this._frameSize.height); - } - - /** - * @en - * On native, it sets the frame size of view.
- * On web, it sets the size of the canvas's outer DOM element. - * @zh 在 native 平台下,设置视图框架尺寸。 - * 在 web 平台下,设置 canvas 外层 DOM 元素尺寸。 - * @method setFrameSize - * @param {Number} width - * @param {Number} height - */ - public setFrameSize (width, height) { - this._frameSize.width = width; - this._frameSize.height = height; - cc.frame.style.width = width + 'px'; - cc.frame.style.height = height + 'px'; - this._resizeEvent(); - } - - /** - * @en - * Returns the visible area size of the view port. - * @zh 返回视图窗口可见区域尺寸。 - * @method getVisibleSize - * @return {Size} - */ - public getVisibleSize () { - return cc.size(this._visibleRect.width, this._visibleRect.height); - } - - /** - * @en - * Returns the visible area size of the view port. - * @zh 返回视图窗口可见区域像素尺寸。 - * @method getVisibleSizeInPixel - * @return {Size} - */ - public getVisibleSizeInPixel () { - return cc.size(this._visibleRect.width * this._scaleX, - this._visibleRect.height * this._scaleY); - } - - /** - * @en - * Returns the visible origin of the view port. - * @zh 返回视图窗口可见区域原点。 - * @method getVisibleOrigin - * @return {Vec2} - */ - public getVisibleOrigin () { - return cc.v2(this._visibleRect.x, this._visibleRect.y); - } - - /** - * @en - * Returns the visible origin of the view port. - * @zh 返回视图窗口可见区域像素原点。 - * @method getVisibleOriginInPixel - * @return {Vec2} - */ - public getVisibleOriginInPixel () { - return cc.v2(this._visibleRect.x * this._scaleX, - this._visibleRect.y * this._scaleY); - } - - /** - * @en - * Returns the current resolution policy - * @zh 返回当前分辨率方案 - * @see ResolutionPolicy - * @method getResolutionPolicy - * @return {ResolutionPolicy} - */ - public getResolutionPolicy () { - return this._resolutionPolicy; - } - - /** - * @en - * Sets the current resolution policy - * @zh 设置当前分辨率模式 - * @see ResolutionPolicy - * @method setResolutionPolicy - * @param {ResolutionPolicy|Number} resolutionPolicy - */ - public setResolutionPolicy (resolutionPolicy) { - const _t = this; - if (resolutionPolicy instanceof ResolutionPolicy) { - _t._resolutionPolicy = resolutionPolicy; - } - // Ensure compatibility with JSB - else { - const _locPolicy = ResolutionPolicy; - if (resolutionPolicy === _locPolicy.EXACT_FIT) { - _t._resolutionPolicy = _t._rpExactFit; - } - if (resolutionPolicy === _locPolicy.SHOW_ALL) { - _t._resolutionPolicy = _t._rpShowAll; - } - if (resolutionPolicy === _locPolicy.NO_BORDER) { - _t._resolutionPolicy = _t._rpNoBorder; - } - if (resolutionPolicy === _locPolicy.FIXED_HEIGHT) { - _t._resolutionPolicy = _t._rpFixedHeight; - } - if (resolutionPolicy === _locPolicy.FIXED_WIDTH) { - _t._resolutionPolicy = _t._rpFixedWidth; - } - } - } - - // tslint:disable: max-line-length - /** - * @en - * Sets the resolution policy with designed view size in points.
- * The resolution policy include:
- * [1] ResolutionExactFit Fill screen by stretch-to-fit: if the design resolution ratio of width to height is different from the screen resolution ratio, your game view will be stretched.
- * [2] ResolutionNoBorder Full screen without black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two areas of your game view will be cut.
- * [3] ResolutionShowAll Full screen with black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two black borders will be shown.
- * [4] ResolutionFixedHeight Scale the content's height to screen's height and proportionally scale its width
- * [5] ResolutionFixedWidth Scale the content's width to screen's width and proportionally scale its height
- * [ResolutionPolicy] [Web only feature] Custom resolution policy, constructed by ResolutionPolicy
- * @zh 通过设置设计分辨率和匹配模式来进行游戏画面的屏幕适配。 - * @method setDesignResolutionSize - * @param {Number} width Design resolution width. - * @param {Number} height Design resolution height. - * @param {ResolutionPolicy|Number} resolutionPolicy The resolution policy desired - */ - public setDesignResolutionSize (width, height, resolutionPolicy) { - // Defensive code - if (!(width > 0 || height > 0)) { - cc.logID(2200); - return; - } - - this.setResolutionPolicy(resolutionPolicy); - const policy = this._resolutionPolicy; - if (policy) { - policy.preApply(this); - } - - // Reinit frame size - if (cc.sys.isMobile) { - this._adjustViewportMeta(); - } - - // Permit to re-detect the orientation of device. - this._orientationChanging = true; - // If resizing, then frame size is already initialized, this logic should be improved - if (!this._resizing) { - this._initFrameSize(); - } - - if (!policy) { - cc.logID(2201); - return; - } - - this._originalDesignResolutionSize.width = this._designResolutionSize.width = width; - this._originalDesignResolutionSize.height = this._designResolutionSize.height = height; - - const result = policy.apply(this, this._designResolutionSize); - - if (result.scale && result.scale.length === 2) { - this._scaleX = result.scale[0]; - this._scaleY = result.scale[1]; - } - - if (result.viewport) { - const vp = this._viewportRect; - const vb = this._visibleRect; - const rv = result.viewport; - - vp.x = rv.x; - vp.y = rv.y; - vp.width = rv.width; - vp.height = rv.height; - - vb.x = 0; - vb.y = 0; - vb.width = rv.width / this._scaleX; - vb.height = rv.height / this._scaleY; - } - - policy.postApply(this); - cc.winSize.width = this._visibleRect.width; - cc.winSize.height = this._visibleRect.height; - - if (cc.visibleRect) { - cc.visibleRect.init(this._visibleRect); - } - - this.emit('design-resolution-changed'); - } - - /** - * @en - * Returns the designed size for the view. - * Default resolution size is the same as 'getFrameSize'. - * @zh 返回视图的设计分辨率。 - * 默认下分辨率尺寸同 `getFrameSize` 方法相同 - * @method getDesignResolutionSize - * @return {Size} - */ - public getDesignResolutionSize () { - return cc.size(this._designResolutionSize.width, this._designResolutionSize.height); - } - - /** - * @en - * Sets the container to desired pixel resolution and fit the game content to it. - * This function is very useful for adaptation in mobile browsers. - * In some HD android devices, the resolution is very high, but its browser performance may not be very good. - * In this case, enabling retina display is very costy and not suggested, and if retina is disabled, the image may be blurry. - * But this API can be helpful to set a desired pixel resolution which is in between. - * This API will do the following: - * 1. Set viewport's width to the desired width in pixel - * 2. Set body width to the exact pixel resolution - * 3. The resolution policy will be reset with designed view size in points. - * @zh 设置容器(container)需要的像素分辨率并且适配相应分辨率的游戏内容。 - * @method setRealPixelResolution - * @param {Number} width Design resolution width. - * @param {Number} height Design resolution height. - * @param {ResolutionPolicy|Number} resolutionPolicy The resolution policy desired - */ - public setRealPixelResolution (width, height, resolutionPolicy) { - if (!CC_JSB && !CC_WECHATGAME && !CC_QQPLAY) { - // Set viewport's width - this._setViewportMeta({ width }, true); - - // Set body width to the exact pixel resolution - document.documentElement.style.width = width + 'px'; - document.body.style.width = width + 'px'; - document.body.style.left = '0px'; - document.body.style.top = '0px'; - } - - // Reset the resolution size and policy - this.setDesignResolutionSize(width, height, resolutionPolicy); - } - - /** - * @en - * Sets view port rectangle with points. - * @zh 用设计分辨率下的点尺寸来设置视窗。 - * @method setViewportInPoints - * @deprecated since v2.0 - * @param {Number} x - * @param {Number} y - * @param {Number} w width - * @param {Number} h height - */ - public setViewportInPoints (x, y, w, h) { - const locScaleX = this._scaleX; - const locScaleY = this._scaleY; - cc.game._renderContext.viewport((x * locScaleX + this._viewportRect.x), - (y * locScaleY + this._viewportRect.y), - (w * locScaleX), - (h * locScaleY)); - } - - /** - * @en - * Sets Scissor rectangle with points. - * @zh 用设计分辨率下的点的尺寸来设置 scissor 剪裁区域。 - * @method setScissorInPoints - * @deprecated since v2.0 - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - */ - public setScissorInPoints (x, y, w, h) { - const scaleX = this._scaleX; - const scaleY = this._scaleY; - const sx = Math.ceil(x * scaleX + this._viewportRect.x); - const sy = Math.ceil(y * scaleY + this._viewportRect.y); - const sw = Math.ceil(w * scaleX); - const sh = Math.ceil(h * scaleY); - const gl = cc.game._renderContext; - - if (!_scissorRect) { - const boxArr = gl.getParameter(gl.SCISSOR_BOX); - _scissorRect = new Rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]); - } - - if (_scissorRect.x !== sx || _scissorRect.y !== sy || _scissorRect.width !== sw || _scissorRect.height !== sh) { - _scissorRect.x = sx; - _scissorRect.y = sy; - _scissorRect.width = sw; - _scissorRect.height = sh; - gl.scissor(sx, sy, sw, sh); - } - } - - /** - * @en - * Returns whether GL_SCISSOR_TEST is enable - * @zh 检查 scissor 是否生效。 - * @method isScissorEnabled - * @deprecated since v2.0 - * @return {Boolean} - */ - public isScissorEnabled () { - const gl = cc.game._renderContext; - return gl.isEnabled(gl.SCISSOR_TEST); - } - - /** - * @en - * Returns the current scissor rectangle - * @zh 返回当前的 scissor 剪裁区域。 - * @method getScissorRect - * @deprecated since v2.0 - * @return {Rect} - */ - public getScissorRect () { - const gl = cc.game._renderContext; - if (!_scissorRect) { - const boxArr = gl.getParameter(gl.SCISSOR_BOX); - _scissorRect = new Rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]); - } - const scaleXFactor = 1 / this._scaleX; - const scaleYFactor = 1 / this._scaleY; - return new Rect( - (_scissorRect.x - this._viewportRect.x) * scaleXFactor, - (_scissorRect.y - this._viewportRect.y) * scaleYFactor, - _scissorRect.width * scaleXFactor, - _scissorRect.height * scaleYFactor, - ); - } - - /** - * @en - * Returns the view port rectangle. - * @zh 返回视窗剪裁区域。 - * @method getViewportRect - * @return {Rect} - */ - public getViewportRect () { - return this._viewportRect; - } - - /** - * @en - * Returns scale factor of the horizontal direction (X axis). - * @zh 返回横轴的缩放比,这个缩放比是将画布像素分辨率放到设计分辨率的比例。 - * @method getScaleX - * @return {Number} - */ - public getScaleX () { - return this._scaleX; - } - - /** - * @en - * Returns scale factor of the vertical direction (Y axis). - * @zh 返回纵轴的缩放比,这个缩放比是将画布像素分辨率缩放到设计分辨率的比例。 - * @method getScaleY - * @return {Number} - */ - public getScaleY () { - return this._scaleY; - } - - /** - * @en - * Returns device pixel ratio for retina display. - * @zh 返回设备或浏览器像素比例。 - * @method getDevicePixelRatio - * @return {Number} - */ - public getDevicePixelRatio () { - return this._devicePixelRatio; - } - - /** - * @en - * Returns the real location in view for a translation based on a related position - * @zh 将屏幕坐标转换为游戏视图下的坐标。 - * @method convertToLocationInView - * @param {Number} tx - The X axis translation - * @param {Number} ty - The Y axis translation - * @param {Object} relatedPos - The related position object including "left", "top", "width", "height" informations - * @return {Vec2} - */ - public convertToLocationInView (tx, ty, relatedPos, out) { - const result = out || cc.v2(); - const x = this._devicePixelRatio * (tx - relatedPos.left); - const y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - ty); - if (this._isRotated) { - result.x = cc.game.canvas.width - y; - result.y = x; - } - else { - result.x = x; - result.y = y; - } - return result; - } - - // Resize helper functions - private _resizeEvent () { - const frameId = cc.director.getTotalFrames(); - if (_currentFrame !== frameId) { - _currentFrame = frameId; - } - else { - // Avoid adapte multiple times in a frame - return; - } - // tslint:disable: no-shadowed-variable - let view; - if (this.setDesignResolutionSize) { - view = this; - } else { - view = cc.view; - } - - // Check frame size changed or not - const prevFrameW = view._frameSize.width; - const prevFrameH = view._frameSize.height; - const prevRotated = view._isRotated; - if (cc.sys.isMobile) { - const containerStyle = cc.game.container.style; - const margin = containerStyle.margin; - containerStyle.margin = '0'; - containerStyle.display = 'none'; - view._initFrameSize(); - containerStyle.margin = margin; - containerStyle.display = 'block'; - } - else { - view._initFrameSize(); - } - if (!view._orientationChanging && view._isRotated === prevRotated && view._frameSize.width === prevFrameW && view._frameSize.height === prevFrameH) { - return; - } - - // Frame size changed, do resize works - const width = view._originalDesignResolutionSize.width; - const height = view._originalDesignResolutionSize.height; - - view._resizing = true; - if (width > 0) { - view.setDesignResolutionSize(width, height, view._resolutionPolicy); - } - view._resizing = false; - - if (view._resizeCallback) { - view._resizeCallback.call(); - } - } - - private _orientationChange () { - cc.view._orientationChanging = true; - cc.view._resizeEvent(); - } - - private _initFrameSize () { - const locFrameSize = this._frameSize; - const w = __BrowserGetter.availWidth(cc.game.frame); - const h = __BrowserGetter.availHeight(cc.game.frame); - const isLandscape: Boolean = w >= h; - - if (CC_EDITOR || !cc.sys.isMobile || - (isLandscape && this._orientation & cc.macro.ORIENTATION_LANDSCAPE) || - (!isLandscape && this._orientation & cc.macro.ORIENTATION_PORTRAIT)) { - locFrameSize.width = w; - locFrameSize.height = h; - cc.game.container.style['-webkit-transform'] = 'rotate(0deg)'; - cc.game.container.style.transform = 'rotate(0deg)'; - this._isRotated = false; - } - else { - locFrameSize.width = h; - locFrameSize.height = w; - cc.game.container.style['-webkit-transform'] = 'rotate(90deg)'; - cc.game.container.style.transform = 'rotate(90deg)'; - cc.game.container.style['-webkit-transform-origin'] = '0px 0px 0px'; - cc.game.container.style.transformOrigin = '0px 0px 0px'; - this._isRotated = true; - - // Fix for issue: https://github.com/cocos-creator/fireball/issues/8365 - // Reference: https://www.douban.com/note/343402554/ - // For Chrome, z-index not working after container transform rotate 90deg. - // Because 'transform' style adds canvas (the top-element of container) to a new stack context. - // That causes the DOM Input was hidden under canvas. - // This should be done after container rotated, instead of in style-mobile.css. - cc.game.canvas.style['-webkit-transform'] = 'translateZ(0px)'; - cc.game.canvas.style.transform = 'translateZ(0px)'; - } - if (this._orientationChanging) { - setTimeout(() => { - cc.view._orientationChanging = false; - }, 1000); - } - } - - // hack - private _adjustSizeKeepCanvasSize () { - const designWidth = this._originalDesignResolutionSize.width; - const designHeight = this._originalDesignResolutionSize.height; - if (designWidth > 0) { - this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy); - } - } - - private _setViewportMeta (metas, overwrite) { - let vp = document.getElementById('cocosMetaElement'); - if (vp && overwrite) { - document.head.removeChild(vp); - } - - const elems = document.getElementsByName('viewport'); - const currentVP = elems ? elems[0] : null; - let content; - let key; - let pattern; - - content = currentVP ? currentVP.content : ''; - vp = vp || document.createElement('meta'); - vp.id = 'cocosMetaElement'; - vp.name = 'viewport'; - vp.content = ''; - - for (key in metas) { - if (content.indexOf(key) === -1) { - content += ',' + key + '=' + metas[key]; - } - else if (overwrite) { - pattern = new RegExp(key + '\s*=\s*[^,]+'); - content.replace(pattern, key + '=' + metas[key]); - } - } - if (/^,/.test(content)) { - content = content.substr(1); - } - - vp.content = content; - // For adopting certain android devices which don't support second viewport - if (currentVP) { - currentVP.content = content; - } - - document.head.appendChild(vp); - } - - private _adjustViewportMeta () { - if (this._isAdjustViewport && !CC_JSB && !CC_WECHATGAME && !CC_QQPLAY) { - this._setViewportMeta(__BrowserGetter.meta, false); - this._isAdjustViewport = false; - } - } - - private _convertMouseToLocation (in_out_point, relatedPos) { - in_out_point.x = this._devicePixelRatio * (in_out_point.x - relatedPos.left); - in_out_point.y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y); - } - - // _convertMouseToLocationInView (in_out_point, relatedPos) { - // var viewport = this._viewportRect, _t = this; - // in_out_point.x = ((_t._devicePixelRatio * (in_out_point.x - relatedPos.left)) - viewport.x) / _t._scaleX; - // in_out_point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y) - viewport.y) / _t._scaleY; - // } - - private _convertPointWithScale (point) { - const viewport = this._viewportRect; - point.x = (point.x - viewport.x) / this._scaleX; - point.y = (point.y - viewport.y) / this._scaleY; - } - - private _convertTouchWidthScale (selTouch) { - const viewport = this._viewportRect; - const scaleX = this._scaleX; - const scaleY = this._scaleY; - - selTouch._point.x = (selTouch._point.x - viewport.x) / scaleX; - selTouch._point.y = (selTouch._point.y - viewport.y) / scaleY; - selTouch._prevPoint.x = (selTouch._prevPoint.x - viewport.x) / scaleX; - selTouch._prevPoint.y = (selTouch._prevPoint.y - viewport.y) / scaleY; - } - - private _convertTouchesWithScale (touches) { - const viewport = this._viewportRect; - const scaleX = this._scaleX; - const scaleY = this._scaleY; - let selPoint; - let selPrePoint; - // tslint:disable-next-line: prefer-for-of - for (let i = 0; i < touches.length; i++) { - const selTouch = touches[i]; - selPoint = selTouch._point; - selPrePoint = selTouch._prevPoint; - - selPoint.x = (selPoint.x - viewport.x) / scaleX; - selPoint.y = (selPoint.y - viewport.y) / scaleY; - selPrePoint.x = (selPrePoint.x - viewport.x) / scaleX; - selPrePoint.y = (selPrePoint.y - viewport.y) / scaleY; - } - } -} - -/** - * !en - * Emit when design resolution changed. - * !zh - * 当设计分辨率改变时发送。 - * @event design-resolution-changed - *

cc.game.containerStrategy class is the root strategy class of container's scale strategy, - * it controls the behavior of how to scale the cc.game.container and cc.game.canvas object

- * - * @class ContainerStrategy - */ -class ContainerStrategy { - public static EQUAL_TO_FRAME: any; - public static PROPORTION_TO_FRAME: any; - - public name: string = 'ContainerStrategy'; - - /** - * @en - * Manipulation before appling the strategy - * @zh 在应用策略之前的操作 - * @method preApply - * @param {View} view - The target view - */ - public preApply (view) { - } - - /** - * @en - * Function to apply this strategy - * @zh 策略应用方法 - * @method apply - * @param {View} view - * @param {Size} designedResolution - */ - public apply (view, designedResolution) { - } - - /** - * @en - * Manipulation after applying the strategy - * @zh 策略调用之后的操作 - * @method postApply - * @param {View} view The target view - */ - public postApply (view) { - - } - - protected _setupContainer (view, w, h) { - const locCanvas = cc.game.canvas; - const locContainer = cc.game.container; - - if (cc.sys.platform !== cc.sys.WECHAT_GAME) { - if (cc.sys.os === cc.sys.OS_ANDROID) { - document.body.style.width = (view._isRotated ? h : w) + 'px'; - document.body.style.height = (view._isRotated ? w : h) + 'px'; - } - // Setup style - locContainer.style.width = locCanvas.style.width = w + 'px'; - locContainer.style.height = locCanvas.style.height = h + 'px'; - } - // Setup pixel ratio for retina display - let devicePixelRatio = view._devicePixelRatio = 1; - if (view.isRetinaEnabled()) { - devicePixelRatio = view._devicePixelRatio = Math.min(2, window.devicePixelRatio || 1); - } - // Setup canvas - locCanvas.width = w * devicePixelRatio; - locCanvas.height = h * devicePixelRatio; - } - - protected _fixContainer () { - // Add container to document body - document.body.insertBefore(cc.game.container, document.body.firstChild); - // Set body's width height to window's size, and forbid overflow, so that game will be centered - const bs = document.body.style; - bs.width = window.innerWidth + 'px'; - bs.height = window.innerHeight + 'px'; - bs.overflow = 'hidden'; - // Body size solution doesn't work on all mobile browser so this is the aleternative: fixed container - const contStyle = cc.game.container.style; - contStyle.position = 'fixed'; - contStyle.left = contStyle.top = '0px'; - // Reposition body - document.body.scrollTop = 0; - } -} - -/** - *

ContentStrategy class is the root strategy class of content's scale strategy, - * it controls the behavior of how to scale the scene and setup the viewport for the game

- * - * @class ContentStrategy - */ -class ContentStrategy { - public static EXACT_FIT: any; - public static SHOW_ALL: any; - public static NO_BORDER: any; - public static FIXED_HEIGHT: any; - public static FIXED_WIDTH: any; - - public name = 'ContentStrategy'; - private _result: { scale: number[]; viewport: null | Rect; }; - constructor () { - this._result = { - scale: [1, 1], - viewport: null, - }; - } - - /** - * @en - * Manipulation before applying the strategy - * @zh 策略应用前的操作 - * @method preApply - * @param {View} view - The target view - */ - public preApply (view) { - } - - /** - * @en Function to apply this strategy - * The return value is {scale: [scaleX, scaleY], viewport: {new Rect}}, - * The target view can then apply these value to itself, it's preferred not to modify directly its private variables - * @zh 调用策略方法 - * @method apply - * @param {View} view - * @param {Size} designedResolution - * @return {Object} scaleAndViewportRect - */ - public apply (view, designedResolution) { - return { scale: [1, 1] }; - } - - /** - * @en - * Manipulation after applying the strategy - * @zh 策略调用之后的操作 - * @method postApply - * @param {View} view - The target view - */ - public postApply (view) { - } - - public _buildResult (containerW, containerH, contentW, contentH, scaleX, scaleY) { - // Makes content fit better the canvas - if (Math.abs(containerW - contentW) < 2) { - contentW = containerW; - } - if (Math.abs(containerH - contentH) < 2) { - contentH = containerH; - } - - const viewport = new Rect(Math.round((containerW - contentW) / 2), - Math.round((containerH - contentH) / 2), - contentW, contentH); - - // Translate the content - if (cc.game.renderType === Game.RENDER_TYPE_CANVAS) { - // TODO: modify something for setTransform - // game._renderContext.translate(viewport.x, viewport.y + contentH); - } - - this._result.scale = [scaleX, scaleY]; - this._result.viewport = viewport; - return this._result; - } -} - -(() => { - - // Container scale strategys - /** - * @class EqualToFrame - * @extends ContainerStrategy - */ - class EqualToFrame extends ContainerStrategy { - public name = 'EqualToFrame'; - public apply (view) { - const frameH = view._frameSize.height; - const containerStyle = cc.game.container.style; - this._setupContainer(view, view._frameSize.width, view._frameSize.height); - // Setup container's margin and padding - if (view._isRotated) { - containerStyle.margin = '0 0 0 ' + frameH + 'px'; - } - else { - containerStyle.margin = '0px'; - } - containerStyle.padding = '0px'; - } - } - - /** - * @class ProportionalToFrame - * @extends ContainerStrategy - */ - class ProportionalToFrame extends ContainerStrategy { - public name = 'ProportionalToFrame'; - public apply (view, designedResolution) { - const frameW = view._frameSize.width; - const frameH = view._frameSize.height; - const containerStyle = cc.game.container.style; - const designW = designedResolution.width; - const designH = designedResolution.height; - const scaleX = frameW / designW; - const scaleY = frameH / designH; - let containerW; - let containerH; - - scaleX < scaleY ? (containerW = frameW, containerH = designH * scaleX) : (containerW = designW * scaleY, containerH = frameH); - - // Adjust container size with integer value - const offx = Math.round((frameW - containerW) / 2); - const offy = Math.round((frameH - containerH) / 2); - containerW = frameW - 2 * offx; - containerH = frameH - 2 * offy; - - this._setupContainer(view, containerW, containerH); - if (!CC_EDITOR) { - // Setup container's margin and padding - if (view._isRotated) { - containerStyle.margin = '0 0 0 ' + frameH + 'px'; - } - else { - containerStyle.margin = '0px'; - } - containerStyle.paddingLeft = offx + 'px'; - containerStyle.paddingRight = offx + 'px'; - containerStyle.paddingTop = offy + 'px'; - containerStyle.paddingBottom = offy + 'px'; - } - } - } - - // Alias: Strategy that makes the container's size equals to the frame's size - ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame(); - // Alias: Strategy that scale proportionally the container's size to frame's size - ContainerStrategy.PROPORTION_TO_FRAME = new ProportionalToFrame(); - - // Content scale strategys - class ExactFit extends ContentStrategy { - public name = 'ExactFit'; - public apply (view, designedResolution) { - const containerW = cc.game.canvas.width; - const containerH = cc.game.canvas.height; - const scaleX = containerW / designedResolution.width; - const scaleY = containerH / designedResolution.height; - - return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY); - } - } - - class ShowAll extends ContentStrategy { - public name = 'ShowAll'; - public apply (view, designedResolution) { - const containerW = cc.game.canvas.width; - const containerH = cc.game.canvas.height; - const designW = designedResolution.width; - const designH = designedResolution.height; - const scaleX = containerW / designW; - const scaleY = containerH / designH; - let scale = 0; - let contentW; - let contentH; - - scaleX < scaleY ? (scale = scaleX, contentW = containerW, contentH = designH * scale) - : (scale = scaleY, contentW = designW * scale, contentH = containerH); - - return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); - } - } - - class NoBorder extends ContentStrategy { - public name = 'NoBorder'; - public apply (view, designedResolution) { - const containerW = cc.game.canvas.width; - const containerH = cc.game.canvas.height; - const designW = designedResolution.width; - const designH = designedResolution.height; - const scaleX = containerW / designW; - const scaleY = containerH / designH; - let scale; - let contentW; - let contentH; - - scaleX < scaleY ? (scale = scaleY, contentW = designW * scale, contentH = containerH) - : (scale = scaleX, contentW = containerW, contentH = designH * scale); - - return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); - } - } - - class FixedHeight extends ContentStrategy { - public name = 'FixedHeight'; - public apply (view, designedResolution) { - const containerW = cc.game.canvas.width; - const containerH = cc.game.canvas.height; - const designH = designedResolution.height; - const scale = containerH / designH; - const contentW = containerW; - const contentH = containerH; - - return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); - } - } - - class FixedWidth extends ContentStrategy { - public name = 'FixedWidth'; - public apply (view, designedResolution) { - const containerW = cc.game.canvas.width; - const containerH = cc.game.canvas.height; - const designW = designedResolution.width; - const scale = containerW / designW; - const contentW = containerW; - const contentH = containerH; - - return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); - } - } - - // Alias: Strategy to scale the content's size to container's size, non proportional - ContentStrategy.EXACT_FIT = new ExactFit(); - // Alias: Strategy to scale the content's size proportionally to maximum size and keeps the whole content area to be visible - ContentStrategy.SHOW_ALL = new ShowAll(); - // Alias: Strategy to scale the content's size proportionally to fill the whole container area - ContentStrategy.NO_BORDER = new NoBorder(); - // Alias: Strategy to scale the content's height to container's height and proportionally scale its width - ContentStrategy.FIXED_HEIGHT = new FixedHeight(); - // Alias: Strategy to scale the content's width to container's width and proportionally scale its height - ContentStrategy.FIXED_WIDTH = new FixedWidth(); - -})(); - -/** - *

ResolutionPolicy class is the root strategy class of scale strategy, - * its main task is to maintain the compatibility with Cocos2d-x

- * - * @class ResolutionPolicy - */ -/** - * @method constructor - * @param {ContainerStrategy} containerStg The container strategy - * @param {ContentStrategy} contentStg The content strategy - */ -class ResolutionPolicy { - public static EXACT_FIT: number; - public static SHOW_ALL: number; - public static NO_BORDER: number; - public static FIXED_HEIGHT: number; - public static FIXED_WIDTH: number; - public static UNKNOWN: number; - public static ContainerStrategy: typeof ContainerStrategy; - public static ContentStrategy: typeof ContentStrategy; - - public name = 'ResolutionPolicy'; - - private _containerStrategy: null | ContainerStrategy; - private _contentStrategy: null | ContentStrategy; - - /** - * Constructor of ResolutionPolicy - * @param {ContainerStrategy} containerStg - * @param {ContentStrategy} contentStg - */ - constructor (containerStg, contentStg) { - this._containerStrategy = null; - this._contentStrategy = null; - this.setContainerStrategy(containerStg); - this.setContentStrategy(contentStg); - } - - get canvasSize () { - return cc.v2(cc.game.canvas.width, cc.game.canvas.height); - } - - /** - * @en Manipulation before applying the resolution policy - * @zh 策略应用前的操作 - * @method preApply - * @param {View} view The target view - */ - public preApply (view) { - this._containerStrategy!.preApply(view); - this._contentStrategy!.preApply(view); - } - - /** - * @en Function to apply this resolution policy - * The return value is {scale: [scaleX, scaleY], viewport: {new Rect}}, - * The target view can then apply these value to itself, it's preferred not to modify directly its private variables - * @zh 调用策略方法 - * @method apply - * @param {View} view - The target view - * @param {Size} designedResolution - The user defined design resolution - * @return {Object} An object contains the scale X/Y values and the viewport rect - */ - public apply (view, designedResolution) { - this._containerStrategy!.apply(view, designedResolution); - return this._contentStrategy!.apply(view, designedResolution); - } - - /** - * @en Manipulation after appyling the strategy - * @zh 策略应用之后的操作 - * @method postApply - * @param {View} view - The target view - */ - public postApply (view) { - this._containerStrategy!.postApply(view); - this._contentStrategy!.postApply(view); - } - - /** - * @en - * Setup the container's scale strategy - * @zh 设置容器的适配策略 - * @method setContainerStrategy - * @param {ContainerStrategy} containerStg - */ - public setContainerStrategy (containerStg) { - if (containerStg instanceof ContainerStrategy) { - this._containerStrategy = containerStg; - } - } - - /** - * @en - * Setup the content's scale strategy - * @zh 设置内容的适配策略 - * @method setContentStrategy - * @param {ContentStrategy} contentStg - */ - public setContentStrategy (contentStg) { - if (contentStg instanceof ContentStrategy) { - this._contentStrategy = contentStg; - } - } -} - -/** - * The entire application is visible in the specified area without trying to preserve the original aspect ratio.
- * Distortion can occur, and the application may appear stretched or compressed. - * @property {Number} EXACT_FIT - * @readonly - * @static - */ -ResolutionPolicy.EXACT_FIT = 0; - -/** - * The entire application fills the specified area, without distortion but possibly with some cropping,
- * while maintaining the original aspect ratio of the application. - * @property {Number} NO_BORDER - * @readonly - * @static - */ -ResolutionPolicy.NO_BORDER = 1; - -/** - * The entire application is visible in the specified area without distortion while maintaining the original
- * aspect ratio of the application. Borders can appear on two sides of the application. - * @property {Number} SHOW_ALL - * @readonly - * @static - */ -ResolutionPolicy.SHOW_ALL = 2; - -/** - * The application takes the height of the design resolution size and modifies the width of the internal
- * canvas so that it fits the aspect ratio of the device
- * no distortion will occur however you must make sure your application works on different
- * aspect ratios - * @property {Number} FIXED_HEIGHT - * @readonly - * @static - */ -ResolutionPolicy.FIXED_HEIGHT = 3; - -/** - * The application takes the width of the design resolution size and modifies the height of the internal
- * canvas so that it fits the aspect ratio of the device
- * no distortion will occur however you must make sure your application works on different
- * aspect ratios - * @property {Number} FIXED_WIDTH - * @readonly - * @static - */ -ResolutionPolicy.FIXED_WIDTH = 4; - -/** - * Unknow policy - * @property {Number} UNKNOWN - * @readonly - * @static - */ -ResolutionPolicy.UNKNOWN = 5; - -ResolutionPolicy.ContainerStrategy = ContainerStrategy; -ResolutionPolicy.ContentStrategy = ContentStrategy; -cc.ResolutionPolicy = ResolutionPolicy; - -/** - * @module cc - */ - -/** - * @en cc.view is the shared view object. - * @zh cc.view 是全局的视图对象。 - * @property view - * @static - * @type {View} - */ -const view = cc.view = new View(); - -/** - * @en cc.winSize is the alias object for the size of the current game window. - * @zh cc.winSize 为当前的游戏窗口的大小。 - * @property winSize - * @type Size - */ -cc.winSize = cc.v2(); - -export default view; +/* + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + 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. +*/ + +import '../data/class'; +import { EventTarget } from '../event/event-target'; +import { Game } from '../game'; +import { Rect, Size } from '../math'; +import { director } from '../director'; + +let _currentFrame = 0; + +class BrowserGetter { + + public html: HTMLHtmlElement | undefined; + + public meta = { + width: 'device-width', + }; + + public adaptationType: any = cc.sys.browserType; + + public init () { + if (!CC_WECHATGAME && !CC_QQPLAY) { + this.html = document.getElementsByTagName('html')[0]; + } + } + + public availWidth (frame) { + if (cc.sys.isMobile || !frame || frame === this.html) { + return window.innerWidth; + } + else { + return frame.clientWidth; + } + } + + public availHeight (frame) { + if (cc.sys.isMobile || !frame || frame === this.html) { + return window.innerHeight; + } + else { + return frame.clientHeight; + } + } +} + +const __BrowserGetter = new BrowserGetter(); + +if (cc.sys.os === cc.sys.OS_IOS) { // All browsers are WebView + __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI; +} + +if (CC_WECHATGAME) { + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { + __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB; + } + else { + __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME; + } +} + +if (CC_QQPLAY) { + __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_QQ_PLAY; +} + +switch (__BrowserGetter.adaptationType) { + case cc.sys.BROWSER_TYPE_SAFARI: + __BrowserGetter.meta['minimal-ui'] = 'true'; + case cc.sys.BROWSER_TYPE_SOUGOU: + case cc.sys.BROWSER_TYPE_WECHAT_GAME: + __BrowserGetter.availWidth = () => { + return window.innerWidth; + }; + __BrowserGetter.availHeight = () => { + return window.innerHeight; + }; + break; + case cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB: + const sharedCanvas = window.sharedCanvas || wx.getSharedCanvas(); + __BrowserGetter.availWidth = () => { + return sharedCanvas.width; + }; + __BrowserGetter.availHeight = () => { + return sharedCanvas.height; + }; + break; +} + +let _scissorRect: Rect | null = null; + +/** + * cc.view is the singleton object which represents the game window.
+ * It's main task include:
+ * - Apply the design resolution policy
+ * - Provide interaction with the window, like resize event on web, retina display support, etc...
+ * - Manage the game view port which can be different with the window
+ * - Manage the content scale and translation
+ *
+ * Since the cc.view is a singleton, you don't need to call any constructor or create functions,
+ * the standard way to use it is by calling:
+ * - cc.view.methodName();
+ * + * @class View + */ +export class View extends EventTarget { + + private _frameSize: Size; + private _scaleX: number; + private _scaleY: number; + private _viewportRect: Rect; + private _visibleRect: Rect; + private _autoFullScreen: boolean; + private _devicePixelRatio: number; + private _retinaEnabled: boolean; + private _resizeCallback: null; + private _resizing: boolean; + private _orientationChanging: boolean; + private _isRotated: boolean; + private _orientation: any; + private _isAdjustViewport: boolean; + private _antiAliasEnabled: boolean; + private _resolutionPolicy: any; + private _rpExactFit: ResolutionPolicy; + private _rpShowAll: ResolutionPolicy; + private _rpNoBorder: ResolutionPolicy; + private _rpFixedHeight: ResolutionPolicy; + private _rpFixedWidth: ResolutionPolicy; + public _resizeWithBrowserSize: boolean; + public _designResolutionSize: Size; + public _originalDesignResolutionSize: Size; + + public static instance: View; + + constructor () { + super(); + + const _t = this; + const _strategyer = ContainerStrategy; + const _strategy = ContentStrategy; + + // Size of parent node that contains cc.game.container and cc.game.canvas + this._frameSize = new Size(0, 0); + + // resolution size, it is the size appropriate for the app resources. + this._designResolutionSize = new Size(0, 0); + this._originalDesignResolutionSize = new Size(0, 0); + this._scaleX = 1; + this._scaleY = 1; + // Viewport is the container's rect related to content's coordinates in pixel + this._viewportRect = new Rect(0, 0, 0, 0); + // The visible rect in content's coordinate in point + this._visibleRect = new Rect(0, 0, 0, 0); + // Auto full screen disabled by default + this._autoFullScreen = false; + // The device's pixel ratio (for retina displays) + this._devicePixelRatio = 1; + // Retina disabled by default + this._retinaEnabled = false; + // Custom callback for resize event + this._resizeCallback = null; + this._resizing = false; + this._resizeWithBrowserSize = false; + this._orientationChanging = true; + this._isRotated = false; + this._orientation = cc.macro.ORIENTATION_AUTO; + this._isAdjustViewport = true; + this._antiAliasEnabled = false; + + // Setup system default resolution policies + this._resolutionPolicy = null; + this._rpExactFit = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT); + this._rpShowAll = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.SHOW_ALL); + this._rpNoBorder = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.NO_BORDER); + this._rpFixedHeight = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT); + this._rpFixedWidth = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); + + cc.game.once(Game.EVENT_ENGINE_INITED, this.init, this); + } + + public init () { + __BrowserGetter.init(); + + this._initFrameSize(); + this.enableAntiAlias(true); + + const w = cc.game.canvas.width; + const h = cc.game.canvas.height; + this._designResolutionSize.width = w; + this._designResolutionSize.height = h; + this._originalDesignResolutionSize.width = w; + this._originalDesignResolutionSize.height = h; + this._viewportRect.width = w; + this._viewportRect.height = h; + this._visibleRect.width = w; + this._visibleRect.height = h; + + cc.winSize.width = this._visibleRect.width; + cc.winSize.height = this._visibleRect.height; + if (cc.visibleRect) { + cc.visibleRect.init(this._visibleRect); + } + } + + /** + * @en + * Sets view's target-densitydpi for android mobile browser. it can be set to:
+ * 1. macro.DENSITYDPI_DEVICE, value is "device-dpi"
+ * 2. macro.DENSITYDPI_HIGH, value is "high-dpi" (default value)
+ * 3. macro.DENSITYDPI_MEDIUM, value is "medium-dpi" (browser's default value)
+ * 4. macro.DENSITYDPI_LOW, value is "low-dpi"
+ * 5. Custom value, e.g: "480"
+ * @zh 设置目标内容的每英寸像素点密度。 + * + * @method setTargetDensityDPI + * @param {String} densityDPI + * @deprecated since v2.0 + */ + + /** + * @en + * Returns the current target-densitydpi value of cc.view. + * @zh 获取目标内容的每英寸像素点密度。 + * @method getTargetDensityDPI + * @returns {String} + * @deprecated since v2.0 + */ + + /** + * @en + * Sets whether resize canvas automatically when browser's size changed.
+ * Useful only on web. + * @zh 设置当发现浏览器的尺寸改变时,是否自动调整 canvas 尺寸大小。 + * 仅在 Web 模式下有效。 + * @method resizeWithBrowserSize + * @param {Boolean} enabled - Whether enable automatic resize with browser's resize event + */ + public resizeWithBrowserSize (enabled) { + if (enabled) { + // enable + if (!this._resizeWithBrowserSize) { + this._resizeWithBrowserSize = true; + window.addEventListener('resize', this._resizeEvent); + window.addEventListener('orientationchange', this._orientationChange); + } + } else { + // disable + if (this._resizeWithBrowserSize) { + this._resizeWithBrowserSize = false; + window.removeEventListener('resize', this._resizeEvent); + window.removeEventListener('orientationchange', this._orientationChange); + } + } + } + + /** + * @en + * Sets the callback function for cc.view's resize action,
+ * this callback will be invoked before applying resolution policy,
+ * so you can do any additional modifications within the callback.
+ * Useful only on web. + * @zh 设置 cc.view 调整视窗尺寸行为的回调函数, + * 这个回调函数会在应用适配模式之前被调用, + * 因此你可以在这个回调函数内添加任意附加改变, + * 仅在 Web 平台下有效。 + * @method setResizeCallback + * @param {Function|Null} callback - The callback function + */ + public setResizeCallback (callback) { + if (typeof callback === 'function' || callback == null) { + this._resizeCallback = callback; + } + } + + /** + * @en + * Sets the orientation of the game, it can be landscape, portrait or auto. + * When set it to landscape or portrait, and screen w/h ratio doesn't fit, + * cc.view will automatically rotate the game canvas using CSS. + * Note that this function doesn't have any effect in native, + * in native, you need to set the application orientation in native project settings + * @zh 设置游戏屏幕朝向,它能够是横版,竖版或自动。 + * 当设置为横版或竖版,并且屏幕的宽高比例不匹配时, + * cc.view 会自动用 CSS 旋转游戏场景的 canvas, + * 这个方法不会对 native 部分产生任何影响,对于 native 而言,你需要在应用设置中的设置排版。 + * @method setOrientation + * @param {Number} orientation - Possible values: macro.ORIENTATION_LANDSCAPE | macro.ORIENTATION_PORTRAIT | macro.ORIENTATION_AUTO + */ + public setOrientation (orientation) { + orientation = orientation & cc.macro.ORIENTATION_AUTO; + if (orientation && this._orientation !== orientation) { + this._orientation = orientation; + } + } + + /** + * @en + * Sets whether the engine modify the "viewport" meta in your web page.
+ * It's enabled by default, we strongly suggest you not to disable it.
+ * And even when it's enabled, you can still set your own "viewport" meta, it won't be overridden
+ * Only useful on web + * @zh 设置引擎是否调整 viewport meta 来配合屏幕适配。 + * 默认设置为启动,我们强烈建议你不要将它设置为关闭。 + * 即使当它启动时,你仍然能够设置你的 viewport meta,它不会被覆盖。 + * 仅在 Web 模式下有效 + * @method adjustViewportMeta + * @param {Boolean} enabled - Enable automatic modification to "viewport" meta + */ + public adjustViewportMeta (enabled) { + this._isAdjustViewport = enabled; + } + + /** + * @en + * Retina support is enabled by default for Apple device but disabled for other devices,
+ * it takes effect only when you called setDesignResolutionPolicy
+ * Only useful on web + * @zh 对于 Apple 这种支持 Retina 显示的设备上默认进行优化而其他类型设备默认不进行优化, + * 它仅会在你调用 setDesignResolutionPolicy 方法时有影响。 + * 仅在 Web 模式下有效。 + * @method enableRetina + * @param {Boolean} enabled - Enable or disable retina display + */ + public enableRetina (enabled) { + this._retinaEnabled = !!enabled; + } + + /** + * @en + * Check whether retina display is enabled.
+ * Only useful on web + * @zh 检查是否对 Retina 显示设备进行优化。 + * 仅在 Web 模式下有效。 + * @method isRetinaEnabled + * @return {Boolean} + */ + public isRetinaEnabled () { + return this._retinaEnabled; + } + + /** + * @en Whether to Enable on anti-alias + * @zh 控制抗锯齿是否开启 + * @method enableAntiAlias + * @param {Boolean} enabled - Enable or not anti-alias + */ + public enableAntiAlias (enabled) { + if (this._antiAliasEnabled === enabled) { + return; + } + this._antiAliasEnabled = enabled; + if (cc.game.renderType === Game.RENDER_TYPE_WEBGL) { + const cache = cc.loader._cache; + // tslint:disable-next-line: forin + for (const key in cache) { + const item = cache[key]; + const tex = item && item.content instanceof cc.Texture2D ? item.content : null; + if (tex) { + const Filter = cc.Texture2D.Filter; + if (enabled) { + tex.setFilters(Filter.LINEAR, Filter.LINEAR); + } + else { + tex.setFilters(Filter.NEAREST, Filter.NEAREST); + } + } + } + } + else if (cc.game.renderType === Game.RENDER_TYPE_CANVAS) { + const ctx = cc.game.canvas.getContext('2d'); + ctx.imageSmoothingEnabled = enabled; + ctx.mozImageSmoothingEnabled = enabled; + } + } + + /** + * @en Returns whether the current enable on anti-alias + * @zh 返回当前是否抗锯齿 + * @method isAntiAliasEnabled + * @return {Boolean} + */ + public isAntiAliasEnabled () { + return this._antiAliasEnabled; + } + /** + * @en + * If enabled, the application will try automatically to enter full screen mode on mobile devices
+ * You can pass true as parameter to enable it and disable it by passing false.
+ * Only useful on web + * @zh 启动时,移动端游戏会在移动端自动尝试进入全屏模式。 + * 你能够传入 true 为参数去启动它,用 false 参数来关闭它。 + * @method enableAutoFullScreen + * @param {Boolean} enabled - Enable or disable auto full screen on mobile devices + */ + public enableAutoFullScreen (enabled) { + if (enabled && + enabled !== this._autoFullScreen && + cc.sys.isMobile && + cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT) { + // Automatically full screen when user touches on mobile version + this._autoFullScreen = true; + cc.screen.autoFullScreen(cc.game.frame); + } + else { + this._autoFullScreen = false; + } + } + + /** + * @en + * Check whether auto full screen is enabled.
+ * Only useful on web + * @zh 检查自动进入全屏模式是否启动。 + * 仅在 Web 模式下有效。 + * @method isAutoFullScreenEnabled + * @return {Boolean} Auto full screen enabled or not + */ + public isAutoFullScreenEnabled () { + return this._autoFullScreen; + } + + /* + * Not support on native.
+ * On web, it sets the size of the canvas. + * @zh 这个方法并不支持 native 平台,在 Web 平台下,可以用来设置 canvas 尺寸。 + * @method setCanvasSize + * @param {Number} width + * @param {Number} height + */ + public setCanvasSize (width, height) { + const canvas = cc.game.canvas; + const container = cc.game.container; + + canvas.width = width * this._devicePixelRatio; + canvas.height = height * this._devicePixelRatio; + + // canvas.width = width; + // canvas.height = height; + + canvas.style.width = width + 'px'; + canvas.style.height = height + 'px'; + + container.style.width = width + 'px'; + container.style.height = height + 'px'; + + this._resizeEvent(); + } + + /** + * @en + * Returns the canvas size of the view.
+ * On native platforms, it returns the screen size since the view is a fullscreen view.
+ * On web, it returns the size of the canvas element. + * @zh 返回视图中 canvas 的尺寸。 + * 在 native 平台下,它返回全屏视图下屏幕的尺寸。 + * 在 Web 平台下,它返回 canvas 元素尺寸。 + * @method getCanvasSize + * @return {Size} + */ + public getCanvasSize () { + return cc.size(cc.game.canvas.width, cc.game.canvas.height); + } + + /** + * @en + * Returns the frame size of the view.
+ * On native platforms, it returns the screen size since the view is a fullscreen view.
+ * On web, it returns the size of the canvas's outer DOM element. + * @zh 返回视图中边框尺寸。 + * 在 native 平台下,它返回全屏视图下屏幕的尺寸。 + * 在 web 平台下,它返回 canvas 元素的外层 DOM 元素尺寸。 + * @method getFrameSize + * @return {Size} + */ + public getFrameSize () { + return cc.size(this._frameSize.width, this._frameSize.height); + } + + /** + * @en + * On native, it sets the frame size of view.
+ * On web, it sets the size of the canvas's outer DOM element. + * @zh 在 native 平台下,设置视图框架尺寸。 + * 在 web 平台下,设置 canvas 外层 DOM 元素尺寸。 + * @method setFrameSize + * @param {Number} width + * @param {Number} height + */ + public setFrameSize (width, height) { + this._frameSize.width = width; + this._frameSize.height = height; + cc.frame.style.width = width + 'px'; + cc.frame.style.height = height + 'px'; + this._resizeEvent(); + } + + /** + * @en + * Returns the visible area size of the view port. + * @zh 返回视图窗口可见区域尺寸。 + * @method getVisibleSize + * @return {Size} + */ + public getVisibleSize () { + return cc.size(this._visibleRect.width, this._visibleRect.height); + } + + /** + * @en + * Returns the visible area size of the view port. + * @zh 返回视图窗口可见区域像素尺寸。 + * @method getVisibleSizeInPixel + * @return {Size} + */ + public getVisibleSizeInPixel () { + return cc.size( this._visibleRect.width * this._scaleX, + this._visibleRect.height * this._scaleY ); + } + + /** + * @en + * Returns the visible origin of the view port. + * @zh 返回视图窗口可见区域原点。 + * @method getVisibleOrigin + * @return {Vec2} + */ + public getVisibleOrigin () { + return cc.v2(this._visibleRect.x, this._visibleRect.y); + } + + /** + * @en + * Returns the visible origin of the view port. + * @zh 返回视图窗口可见区域像素原点。 + * @method getVisibleOriginInPixel + * @return {Vec2} + */ + public getVisibleOriginInPixel () { + return cc.v2(this._visibleRect.x * this._scaleX, + this._visibleRect.y * this._scaleY); + } + + /** + * @en + * Returns the current resolution policy + * @zh 返回当前分辨率方案 + * @see ResolutionPolicy + * @method getResolutionPolicy + * @return {ResolutionPolicy} + */ + public getResolutionPolicy () { + return this._resolutionPolicy; + } + + /** + * @en + * Sets the current resolution policy + * @zh 设置当前分辨率模式 + * @see ResolutionPolicy + * @method setResolutionPolicy + * @param {ResolutionPolicy|Number} resolutionPolicy + */ + public setResolutionPolicy (resolutionPolicy) { + const _t = this; + if (resolutionPolicy instanceof ResolutionPolicy) { + _t._resolutionPolicy = resolutionPolicy; + } + // Ensure compatibility with JSB + else { + const _locPolicy = ResolutionPolicy; + if (resolutionPolicy === _locPolicy.EXACT_FIT) { + _t._resolutionPolicy = _t._rpExactFit; + } + if (resolutionPolicy === _locPolicy.SHOW_ALL) { + _t._resolutionPolicy = _t._rpShowAll; + } + if (resolutionPolicy === _locPolicy.NO_BORDER) { + _t._resolutionPolicy = _t._rpNoBorder; + } + if (resolutionPolicy === _locPolicy.FIXED_HEIGHT) { + _t._resolutionPolicy = _t._rpFixedHeight; + } + if (resolutionPolicy === _locPolicy.FIXED_WIDTH) { + _t._resolutionPolicy = _t._rpFixedWidth; + } + } + } + + // tslint:disable: max-line-length + /** + * @en + * Sets the resolution policy with designed view size in points.
+ * The resolution policy include:
+ * [1] ResolutionExactFit Fill screen by stretch-to-fit: if the design resolution ratio of width to height is different from the screen resolution ratio, your game view will be stretched.
+ * [2] ResolutionNoBorder Full screen without black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two areas of your game view will be cut.
+ * [3] ResolutionShowAll Full screen with black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two black borders will be shown.
+ * [4] ResolutionFixedHeight Scale the content's height to screen's height and proportionally scale its width
+ * [5] ResolutionFixedWidth Scale the content's width to screen's width and proportionally scale its height
+ * [ResolutionPolicy] [Web only feature] Custom resolution policy, constructed by ResolutionPolicy
+ * @zh 通过设置设计分辨率和匹配模式来进行游戏画面的屏幕适配。 + * @method setDesignResolutionSize + * @param {Number} width Design resolution width. + * @param {Number} height Design resolution height. + * @param {ResolutionPolicy|Number} resolutionPolicy The resolution policy desired + */ + public setDesignResolutionSize (width, height, resolutionPolicy) { + // Defensive code + if ( !(width > 0 || height > 0) ){ + cc.logID(2200); + return; + } + + this.setResolutionPolicy(resolutionPolicy); + const policy = this._resolutionPolicy; + if (policy) { + policy.preApply(this); + } + + // Reinit frame size + if (cc.sys.isMobile) { + this._adjustViewportMeta(); + } + + // Permit to re-detect the orientation of device. + this._orientationChanging = true; + // If resizing, then frame size is already initialized, this logic should be improved + if (!this._resizing) { + this._initFrameSize(); + } + + if (!policy) { + cc.logID(2201); + return; + } + + this._originalDesignResolutionSize.width = this._designResolutionSize.width = width; + this._originalDesignResolutionSize.height = this._designResolutionSize.height = height; + + const result = policy.apply(this, this._designResolutionSize); + + if (result.scale && result.scale.length === 2){ + this._scaleX = result.scale[0]; + this._scaleY = result.scale[1]; + } + + if (result.viewport){ + const vp = this._viewportRect; + const vb = this._visibleRect; + const rv = result.viewport; + + vp.x = rv.x; + vp.y = rv.y; + vp.width = rv.width; + vp.height = rv.height; + + vb.x = 0; + vb.y = 0; + vb.width = rv.width / this._scaleX; + vb.height = rv.height / this._scaleY; + } + + policy.postApply(this); + cc.winSize.width = this._visibleRect.width; + cc.winSize.height = this._visibleRect.height; + + if (cc.visibleRect) { + cc.visibleRect.init(this._visibleRect); + } + + this.emit('design-resolution-changed'); + } + + /** + * @en + * Returns the designed size for the view. + * Default resolution size is the same as 'getFrameSize'. + * @zh 返回视图的设计分辨率。 + * 默认下分辨率尺寸同 `getFrameSize` 方法相同 + * @method getDesignResolutionSize + * @return {Size} + */ + public getDesignResolutionSize () { + return cc.size(this._designResolutionSize.width, this._designResolutionSize.height); + } + + /** + * @en + * Sets the container to desired pixel resolution and fit the game content to it. + * This function is very useful for adaptation in mobile browsers. + * In some HD android devices, the resolution is very high, but its browser performance may not be very good. + * In this case, enabling retina display is very costy and not suggested, and if retina is disabled, the image may be blurry. + * But this API can be helpful to set a desired pixel resolution which is in between. + * This API will do the following: + * 1. Set viewport's width to the desired width in pixel + * 2. Set body width to the exact pixel resolution + * 3. The resolution policy will be reset with designed view size in points. + * @zh 设置容器(container)需要的像素分辨率并且适配相应分辨率的游戏内容。 + * @method setRealPixelResolution + * @param {Number} width Design resolution width. + * @param {Number} height Design resolution height. + * @param {ResolutionPolicy|Number} resolutionPolicy The resolution policy desired + */ + public setRealPixelResolution (width, height, resolutionPolicy) { + if (!CC_JSB && !CC_WECHATGAME && !CC_QQPLAY) { + // Set viewport's width + this._setViewportMeta({width}, true); + + // Set body width to the exact pixel resolution + document.documentElement.style.width = width + 'px'; + document.body.style.width = width + 'px'; + document.body.style.left = '0px'; + document.body.style.top = '0px'; + } + + // Reset the resolution size and policy + this.setDesignResolutionSize(width, height, resolutionPolicy); + } + + /** + * @en + * Sets view port rectangle with points. + * @zh 用设计分辨率下的点尺寸来设置视窗。 + * @method setViewportInPoints + * @deprecated since v2.0 + * @param {Number} x + * @param {Number} y + * @param {Number} w width + * @param {Number} h height + */ + public setViewportInPoints (x, y, w, h) { + const locScaleX = this._scaleX; + const locScaleY = this._scaleY; + cc.game._renderContext.viewport((x * locScaleX + this._viewportRect.x), + (y * locScaleY + this._viewportRect.y), + (w * locScaleX), + (h * locScaleY)); + } + + /** + * @en + * Sets Scissor rectangle with points. + * @zh 用设计分辨率下的点的尺寸来设置 scissor 剪裁区域。 + * @method setScissorInPoints + * @deprecated since v2.0 + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + */ + public setScissorInPoints (x, y, w, h) { + const scaleX = this._scaleX; + const scaleY = this._scaleY; + const sx = Math.ceil(x * scaleX + this._viewportRect.x); + const sy = Math.ceil(y * scaleY + this._viewportRect.y); + const sw = Math.ceil(w * scaleX); + const sh = Math.ceil(h * scaleY); + const gl = cc.game._renderContext; + + if (!_scissorRect) { + const boxArr = gl.getParameter(gl.SCISSOR_BOX); + _scissorRect = new Rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]); + } + + if (_scissorRect.x !== sx || _scissorRect.y !== sy || _scissorRect.width !== sw || _scissorRect.height !== sh) { + _scissorRect.x = sx; + _scissorRect.y = sy; + _scissorRect.width = sw; + _scissorRect.height = sh; + gl.scissor(sx, sy, sw, sh); + } + } + + /** + * @en + * Returns whether GL_SCISSOR_TEST is enable + * @zh 检查 scissor 是否生效。 + * @method isScissorEnabled + * @deprecated since v2.0 + * @return {Boolean} + */ + public isScissorEnabled () { + const gl = cc.game._renderContext; + return gl.isEnabled(gl.SCISSOR_TEST); + } + + /** + * @en + * Returns the current scissor rectangle + * @zh 返回当前的 scissor 剪裁区域。 + * @method getScissorRect + * @deprecated since v2.0 + * @return {Rect} + */ + public getScissorRect () { + const gl = cc.game._renderContext; + if (!_scissorRect) { + const boxArr = gl.getParameter(gl.SCISSOR_BOX); + _scissorRect = new Rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]); + } + const scaleXFactor = 1 / this._scaleX; + const scaleYFactor = 1 / this._scaleY; + return new Rect( + (_scissorRect.x - this._viewportRect.x) * scaleXFactor, + (_scissorRect.y - this._viewportRect.y) * scaleYFactor, + _scissorRect.width * scaleXFactor, + _scissorRect.height * scaleYFactor, + ); + } + + /** + * @en + * Returns the view port rectangle. + * @zh 返回视窗剪裁区域。 + * @method getViewportRect + * @return {Rect} + */ + public getViewportRect () { + return this._viewportRect; + } + + /** + * @en + * Returns scale factor of the horizontal direction (X axis). + * @zh 返回横轴的缩放比,这个缩放比是将画布像素分辨率放到设计分辨率的比例。 + * @method getScaleX + * @return {Number} + */ + public getScaleX () { + return this._scaleX; + } + + /** + * @en + * Returns scale factor of the vertical direction (Y axis). + * @zh 返回纵轴的缩放比,这个缩放比是将画布像素分辨率缩放到设计分辨率的比例。 + * @method getScaleY + * @return {Number} + */ + public getScaleY () { + return this._scaleY; + } + + /** + * @en + * Returns device pixel ratio for retina display. + * @zh 返回设备或浏览器像素比例。 + * @method getDevicePixelRatio + * @return {Number} + */ + public getDevicePixelRatio () { + return this._devicePixelRatio; + } + + /** + * @en + * Returns the real location in view for a translation based on a related position + * @zh 将屏幕坐标转换为游戏视图下的坐标。 + * @method convertToLocationInView + * @param {Number} tx - The X axis translation + * @param {Number} ty - The Y axis translation + * @param {Object} relatedPos - The related position object including "left", "top", "width", "height" informations + * @return {Vec2} + */ + public convertToLocationInView (tx, ty, relatedPos, out) { + const result = out || cc.v2(); + const x = this._devicePixelRatio * (tx - relatedPos.left); + const y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - ty); + if (this._isRotated) { + result.x = cc.game.canvas.width - y; + result.y = x; + } + else { + result.x = x; + result.y = y; + } + return result; + } + + // Resize helper functions + private _resizeEvent () { + const frameId = director.getTotalFrames(); + if (_currentFrame !== frameId) { + _currentFrame = frameId; + } + else { + // Avoid adapte multiple times in a frame + return; + } + // tslint:disable: no-shadowed-variable + let view; + if (this.setDesignResolutionSize) { + view = this; + } else { + view = cc.view; + } + + // Check frame size changed or not + const prevFrameW = view._frameSize.width; + const prevFrameH = view._frameSize.height; + const prevRotated = view._isRotated; + if (cc.sys.isMobile) { + const containerStyle = cc.game.container.style; + const margin = containerStyle.margin; + containerStyle.margin = '0'; + containerStyle.display = 'none'; + view._initFrameSize(); + containerStyle.margin = margin; + containerStyle.display = 'block'; + } + else { + view._initFrameSize(); + } + if (!view._orientationChanging && view._isRotated === prevRotated && view._frameSize.width === prevFrameW && view._frameSize.height === prevFrameH) { + return; + } + + // Frame size changed, do resize works + const width = view._originalDesignResolutionSize.width; + const height = view._originalDesignResolutionSize.height; + + view._resizing = true; + if (width > 0) { + view.setDesignResolutionSize(width, height, view._resolutionPolicy); + } + view._resizing = false; + + if (view._resizeCallback) { + view._resizeCallback.call(); + } + } + + private _orientationChange () { + cc.view._orientationChanging = true; + cc.view._resizeEvent(); + } + + private _initFrameSize () { + const locFrameSize = this._frameSize; + const w = __BrowserGetter.availWidth(cc.game.frame); + const h = __BrowserGetter.availHeight(cc.game.frame); + const isLandscape: Boolean = w >= h; + + if (CC_EDITOR || !cc.sys.isMobile || + (isLandscape && this._orientation & cc.macro.ORIENTATION_LANDSCAPE) || + (!isLandscape && this._orientation & cc.macro.ORIENTATION_PORTRAIT)) { + locFrameSize.width = w; + locFrameSize.height = h; + cc.game.container.style['-webkit-transform'] = 'rotate(0deg)'; + cc.game.container.style.transform = 'rotate(0deg)'; + this._isRotated = false; + } + else { + locFrameSize.width = h; + locFrameSize.height = w; + cc.game.container.style['-webkit-transform'] = 'rotate(90deg)'; + cc.game.container.style.transform = 'rotate(90deg)'; + cc.game.container.style['-webkit-transform-origin'] = '0px 0px 0px'; + cc.game.container.style.transformOrigin = '0px 0px 0px'; + this._isRotated = true; + + // Fix for issue: https://github.com/cocos-creator/fireball/issues/8365 + // Reference: https://www.douban.com/note/343402554/ + // For Chrome, z-index not working after container transform rotate 90deg. + // Because 'transform' style adds canvas (the top-element of container) to a new stack context. + // That causes the DOM Input was hidden under canvas. + // This should be done after container rotated, instead of in style-mobile.css. + cc.game.canvas.style['-webkit-transform'] = 'translateZ(0px)'; + cc.game.canvas.style.transform = 'translateZ(0px)'; + } + if (this._orientationChanging) { + setTimeout(() => { + cc.view._orientationChanging = false; + }, 1000); + } + } + + // hack + private _adjustSizeKeepCanvasSize () { + const designWidth = this._originalDesignResolutionSize.width; + const designHeight = this._originalDesignResolutionSize.height; + if (designWidth > 0) { + this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy); + } + } + + private _setViewportMeta (metas, overwrite) { + let vp = document.getElementById('cocosMetaElement'); + if (vp && overwrite) { + document.head.removeChild(vp); + } + + const elems = document.getElementsByName('viewport'); + const currentVP = elems ? elems[0] : null; + let content; + let key; + let pattern; + + content = currentVP ? currentVP.content : ''; + vp = vp || document.createElement('meta'); + vp.id = 'cocosMetaElement'; + vp.name = 'viewport'; + vp.content = ''; + + for (key in metas) { + if (content.indexOf(key) === -1) { + content += ',' + key + '=' + metas[key]; + } + else if (overwrite) { + pattern = new RegExp(key + '\s*=\s*[^,]+'); + content.replace(pattern, key + '=' + metas[key]); + } + } + if (/^,/.test(content)) { + content = content.substr(1); + } + + vp.content = content; + // For adopting certain android devices which don't support second viewport + if (currentVP) { + currentVP.content = content; + } + + document.head.appendChild(vp); + } + + private _adjustViewportMeta () { + if (this._isAdjustViewport && !CC_JSB && !CC_WECHATGAME && !CC_QQPLAY) { + this._setViewportMeta(__BrowserGetter.meta, false); + this._isAdjustViewport = false; + } + } + + private _convertMouseToLocation (in_out_point, relatedPos){ + in_out_point.x = this._devicePixelRatio * (in_out_point.x - relatedPos.left); + in_out_point.y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y); + } + + // _convertMouseToLocationInView (in_out_point, relatedPos) { + // var viewport = this._viewportRect, _t = this; + // in_out_point.x = ((_t._devicePixelRatio * (in_out_point.x - relatedPos.left)) - viewport.x) / _t._scaleX; + // in_out_point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y) - viewport.y) / _t._scaleY; + // } + + public _convertPointWithScale (point) { + const viewport = this._viewportRect; + point.x = (point.x - viewport.x) / this._scaleX; + point.y = (point.y - viewport.y) / this._scaleY; + } + + private _convertTouchWidthScale (selTouch){ + const viewport = this._viewportRect; + const scaleX = this._scaleX; + const scaleY = this._scaleY; + + selTouch._point.x = (selTouch._point.x - viewport.x) / scaleX; + selTouch._point.y = (selTouch._point.y - viewport.y) / scaleY; + selTouch._prevPoint.x = (selTouch._prevPoint.x - viewport.x) / scaleX; + selTouch._prevPoint.y = (selTouch._prevPoint.y - viewport.y) / scaleY; + } + + private _convertTouchesWithScale (touches) { + const viewport = this._viewportRect; + const scaleX = this._scaleX; + const scaleY = this._scaleY; + let selPoint; + let selPrePoint; + // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < touches.length; i++) { + const selTouch = touches[i]; + selPoint = selTouch._point; + selPrePoint = selTouch._prevPoint; + + selPoint.x = (selPoint.x - viewport.x) / scaleX; + selPoint.y = (selPoint.y - viewport.y) / scaleY; + selPrePoint.x = (selPrePoint.x - viewport.x) / scaleX; + selPrePoint.y = (selPrePoint.y - viewport.y) / scaleY; + } + } +} + +/** + * !en + * Emit when design resolution changed. + * !zh + * 当设计分辨率改变时发送。 + * @event design-resolution-changed + *

cc.game.containerStrategy class is the root strategy class of container's scale strategy, + * it controls the behavior of how to scale the cc.game.container and cc.game.canvas object

+ * + * @class ContainerStrategy + */ +class ContainerStrategy { + public static EQUAL_TO_FRAME: any; + public static PROPORTION_TO_FRAME: any; + + public name: string = 'ContainerStrategy'; + + /** + * @en + * Manipulation before appling the strategy + * @zh 在应用策略之前的操作 + * @method preApply + * @param {View} view - The target view + */ + public preApply (view) { + } + + /** + * @en + * Function to apply this strategy + * @zh 策略应用方法 + * @method apply + * @param {View} view + * @param {Size} designedResolution + */ + public apply (view, designedResolution) { + } + + /** + * @en + * Manipulation after applying the strategy + * @zh 策略调用之后的操作 + * @method postApply + * @param {View} view The target view + */ + public postApply (view) { + + } + + protected _setupContainer (view, w, h) { + const locCanvas = cc.game.canvas; + const locContainer = cc.game.container; + + if (cc.sys.platform !== cc.sys.WECHAT_GAME) { + if (cc.sys.os === cc.sys.OS_ANDROID) { + document.body.style.width = (view._isRotated ? h : w) + 'px'; + document.body.style.height = (view._isRotated ? w : h) + 'px'; + } + // Setup style + locContainer.style.width = locCanvas.style.width = w + 'px'; + locContainer.style.height = locCanvas.style.height = h + 'px'; + } + // Setup pixel ratio for retina display + let devicePixelRatio = view._devicePixelRatio = 1; + if (view.isRetinaEnabled()) { + devicePixelRatio = view._devicePixelRatio = Math.min(2, window.devicePixelRatio || 1); + } + // Setup canvas + locCanvas.width = w * devicePixelRatio; + locCanvas.height = h * devicePixelRatio; + } + + protected _fixContainer () { + // Add container to document body + document.body.insertBefore(cc.game.container, document.body.firstChild); + // Set body's width height to window's size, and forbid overflow, so that game will be centered + const bs = document.body.style; + bs.width = window.innerWidth + 'px'; + bs.height = window.innerHeight + 'px'; + bs.overflow = 'hidden'; + // Body size solution doesn't work on all mobile browser so this is the aleternative: fixed container + const contStyle = cc.game.container.style; + contStyle.position = 'fixed'; + contStyle.left = contStyle.top = '0px'; + // Reposition body + document.body.scrollTop = 0; + } +} + +/** + *

ContentStrategy class is the root strategy class of content's scale strategy, + * it controls the behavior of how to scale the scene and setup the viewport for the game

+ * + * @class ContentStrategy + */ +class ContentStrategy { + public static EXACT_FIT: any; + public static SHOW_ALL: any; + public static NO_BORDER: any; + public static FIXED_HEIGHT: any; + public static FIXED_WIDTH: any; + + public name = 'ContentStrategy'; + private _result: { scale: number[]; viewport: null | Rect; }; + constructor () { + this._result = { + scale: [1, 1], + viewport: null, + }; + } + + /** + * @en + * Manipulation before applying the strategy + * @zh 策略应用前的操作 + * @method preApply + * @param {View} view - The target view + */ + public preApply (view) { + } + + /** + * @en Function to apply this strategy + * The return value is {scale: [scaleX, scaleY], viewport: {new Rect}}, + * The target view can then apply these value to itself, it's preferred not to modify directly its private variables + * @zh 调用策略方法 + * @method apply + * @param {View} view + * @param {Size} designedResolution + * @return {Object} scaleAndViewportRect + */ + public apply (view, designedResolution) { + return {scale: [1, 1]}; + } + + /** + * @en + * Manipulation after applying the strategy + * @zh 策略调用之后的操作 + * @method postApply + * @param {View} view - The target view + */ + public postApply (view) { + } + + public _buildResult (containerW, containerH, contentW, contentH, scaleX, scaleY) { + // Makes content fit better the canvas + if ( Math.abs(containerW - contentW) < 2 ) { + contentW = containerW; + } + if ( Math.abs(containerH - contentH) < 2 ) { + contentH = containerH; + } + + const viewport = new Rect(Math.round((containerW - contentW) / 2), + Math.round((containerH - contentH) / 2), + contentW, contentH); + + // Translate the content + if (cc.game.renderType === Game.RENDER_TYPE_CANVAS){ + // TODO: modify something for setTransform + // game._renderContext.translate(viewport.x, viewport.y + contentH); + } + + this._result.scale = [scaleX, scaleY]; + this._result.viewport = viewport; + return this._result; + } +} + +(() => { + +// Container scale strategys + /** + * @class EqualToFrame + * @extends ContainerStrategy + */ + class EqualToFrame extends ContainerStrategy { + public name = 'EqualToFrame'; + public apply (view) { + const frameH = view._frameSize.height; + const containerStyle = cc.game.container.style; + this._setupContainer(view, view._frameSize.width, view._frameSize.height); + // Setup container's margin and padding + if (view._isRotated) { + containerStyle.margin = '0 0 0 ' + frameH + 'px'; + } + else { + containerStyle.margin = '0px'; + } + containerStyle.padding = '0px'; + } + } + + /** + * @class ProportionalToFrame + * @extends ContainerStrategy + */ + class ProportionalToFrame extends ContainerStrategy { + public name = 'ProportionalToFrame'; + public apply (view, designedResolution) { + const frameW = view._frameSize.width; + const frameH = view._frameSize.height; + const containerStyle = cc.game.container.style; + const designW = designedResolution.width; + const designH = designedResolution.height; + const scaleX = frameW / designW; + const scaleY = frameH / designH; + let containerW; + let containerH; + + scaleX < scaleY ? (containerW = frameW, containerH = designH * scaleX) : (containerW = designW * scaleY, containerH = frameH); + + // Adjust container size with integer value + const offx = Math.round((frameW - containerW) / 2); + const offy = Math.round((frameH - containerH) / 2); + containerW = frameW - 2 * offx; + containerH = frameH - 2 * offy; + + this._setupContainer(view, containerW, containerH); + if (!CC_EDITOR) { + // Setup container's margin and padding + if (view._isRotated) { + containerStyle.margin = '0 0 0 ' + frameH + 'px'; + } + else { + containerStyle.margin = '0px'; + } + containerStyle.paddingLeft = offx + 'px'; + containerStyle.paddingRight = offx + 'px'; + containerStyle.paddingTop = offy + 'px'; + containerStyle.paddingBottom = offy + 'px'; + } + } + } + +// Alias: Strategy that makes the container's size equals to the frame's size + ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame(); +// Alias: Strategy that scale proportionally the container's size to frame's size + ContainerStrategy.PROPORTION_TO_FRAME = new ProportionalToFrame(); + +// Content scale strategys + class ExactFit extends ContentStrategy { + public name = 'ExactFit'; + public apply (view, designedResolution) { + const containerW = cc.game.canvas.width; + const containerH = cc.game.canvas.height; + const scaleX = containerW / designedResolution.width; + const scaleY = containerH / designedResolution.height; + + return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY); + } + } + + class ShowAll extends ContentStrategy { + public name = 'ShowAll'; + public apply (view, designedResolution) { + const containerW = cc.game.canvas.width; + const containerH = cc.game.canvas.height; + const designW = designedResolution.width; + const designH = designedResolution.height; + const scaleX = containerW / designW; + const scaleY = containerH / designH; + let scale = 0; + let contentW; + let contentH; + + scaleX < scaleY ? (scale = scaleX, contentW = containerW, contentH = designH * scale) + : (scale = scaleY, contentW = designW * scale, contentH = containerH); + + return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); + } + } + + class NoBorder extends ContentStrategy { + public name = 'NoBorder'; + public apply (view, designedResolution) { + const containerW = cc.game.canvas.width; + const containerH = cc.game.canvas.height; + const designW = designedResolution.width; + const designH = designedResolution.height; + const scaleX = containerW / designW; + const scaleY = containerH / designH; + let scale; + let contentW; + let contentH; + + scaleX < scaleY ? (scale = scaleY, contentW = designW * scale, contentH = containerH) + : (scale = scaleX, contentW = containerW, contentH = designH * scale); + + return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); + } + } + + class FixedHeight extends ContentStrategy { + public name = 'FixedHeight'; + public apply (view, designedResolution) { + const containerW = cc.game.canvas.width; + const containerH = cc.game.canvas.height; + const designH = designedResolution.height; + const scale = containerH / designH; + const contentW = containerW; + const contentH = containerH; + + return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); + } + } + + class FixedWidth extends ContentStrategy { + public name = 'FixedWidth'; + public apply (view, designedResolution) { + const containerW = cc.game.canvas.width; + const containerH = cc.game.canvas.height; + const designW = designedResolution.width; + const scale = containerW / designW; + const contentW = containerW; + const contentH = containerH; + + return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); + } + } + +// Alias: Strategy to scale the content's size to container's size, non proportional + ContentStrategy.EXACT_FIT = new ExactFit(); +// Alias: Strategy to scale the content's size proportionally to maximum size and keeps the whole content area to be visible + ContentStrategy.SHOW_ALL = new ShowAll(); +// Alias: Strategy to scale the content's size proportionally to fill the whole container area + ContentStrategy.NO_BORDER = new NoBorder(); +// Alias: Strategy to scale the content's height to container's height and proportionally scale its width + ContentStrategy.FIXED_HEIGHT = new FixedHeight(); +// Alias: Strategy to scale the content's width to container's width and proportionally scale its height + ContentStrategy.FIXED_WIDTH = new FixedWidth(); + +})(); + +/** + *

ResolutionPolicy class is the root strategy class of scale strategy, + * its main task is to maintain the compatibility with Cocos2d-x

+ * + * @class ResolutionPolicy + */ +/** + * @method constructor + * @param {ContainerStrategy} containerStg The container strategy + * @param {ContentStrategy} contentStg The content strategy + */ +export class ResolutionPolicy { + public static EXACT_FIT: number; + public static SHOW_ALL: number; + public static NO_BORDER: number; + public static FIXED_HEIGHT: number; + public static FIXED_WIDTH: number; + public static UNKNOWN: number; + public static ContainerStrategy: typeof ContainerStrategy; + public static ContentStrategy: typeof ContentStrategy; + + public name = 'ResolutionPolicy'; + + private _containerStrategy: null | ContainerStrategy; + private _contentStrategy: null | ContentStrategy; + + /** + * Constructor of ResolutionPolicy + * @param {ContainerStrategy} containerStg + * @param {ContentStrategy} contentStg + */ + constructor (containerStg, contentStg) { + this._containerStrategy = null; + this._contentStrategy = null; + this.setContainerStrategy(containerStg); + this.setContentStrategy(contentStg); + } + + get canvasSize () { + return cc.v2(cc.game.canvas.width, cc.game.canvas.height); + } + + /** + * @en Manipulation before applying the resolution policy + * @zh 策略应用前的操作 + * @method preApply + * @param {View} view The target view + */ + public preApply (view) { + this._containerStrategy!.preApply(view); + this._contentStrategy!.preApply(view); + } + + /** + * @en Function to apply this resolution policy + * The return value is {scale: [scaleX, scaleY], viewport: {new Rect}}, + * The target view can then apply these value to itself, it's preferred not to modify directly its private variables + * @zh 调用策略方法 + * @method apply + * @param {View} view - The target view + * @param {Size} designedResolution - The user defined design resolution + * @return {Object} An object contains the scale X/Y values and the viewport rect + */ + public apply (view, designedResolution) { + this._containerStrategy!.apply(view, designedResolution); + return this._contentStrategy!.apply(view, designedResolution); + } + + /** + * @en Manipulation after appyling the strategy + * @zh 策略应用之后的操作 + * @method postApply + * @param {View} view - The target view + */ + public postApply (view) { + this._containerStrategy!.postApply(view); + this._contentStrategy!.postApply(view); + } + + /** + * @en + * Setup the container's scale strategy + * @zh 设置容器的适配策略 + * @method setContainerStrategy + * @param {ContainerStrategy} containerStg + */ + public setContainerStrategy (containerStg) { + if (containerStg instanceof ContainerStrategy) { + this._containerStrategy = containerStg; + } + } + + /** + * @en + * Setup the content's scale strategy + * @zh 设置内容的适配策略 + * @method setContentStrategy + * @param {ContentStrategy} contentStg + */ + public setContentStrategy (contentStg) { + if (contentStg instanceof ContentStrategy) { + this._contentStrategy = contentStg; + } + } +} + +/** + * The entire application is visible in the specified area without trying to preserve the original aspect ratio.
+ * Distortion can occur, and the application may appear stretched or compressed. + * @property {Number} EXACT_FIT + * @readonly + * @static + */ +ResolutionPolicy.EXACT_FIT = 0; + +/** + * The entire application fills the specified area, without distortion but possibly with some cropping,
+ * while maintaining the original aspect ratio of the application. + * @property {Number} NO_BORDER + * @readonly + * @static + */ +ResolutionPolicy.NO_BORDER = 1; + +/** + * The entire application is visible in the specified area without distortion while maintaining the original
+ * aspect ratio of the application. Borders can appear on two sides of the application. + * @property {Number} SHOW_ALL + * @readonly + * @static + */ +ResolutionPolicy.SHOW_ALL = 2; + +/** + * The application takes the height of the design resolution size and modifies the width of the internal
+ * canvas so that it fits the aspect ratio of the device
+ * no distortion will occur however you must make sure your application works on different
+ * aspect ratios + * @property {Number} FIXED_HEIGHT + * @readonly + * @static + */ +ResolutionPolicy.FIXED_HEIGHT = 3; + +/** + * The application takes the width of the design resolution size and modifies the height of the internal
+ * canvas so that it fits the aspect ratio of the device
+ * no distortion will occur however you must make sure your application works on different
+ * aspect ratios + * @property {Number} FIXED_WIDTH + * @readonly + * @static + */ +ResolutionPolicy.FIXED_WIDTH = 4; + +/** + * Unknow policy + * @property {Number} UNKNOWN + * @readonly + * @static + */ +ResolutionPolicy.UNKNOWN = 5; + +ResolutionPolicy.ContainerStrategy = ContainerStrategy; +ResolutionPolicy.ContentStrategy = ContentStrategy; +cc.ResolutionPolicy = ResolutionPolicy; + +/** + * @module cc + */ + +/** + * @en cc.view is the shared view object. + * @zh cc.view 是全局的视图对象。 + * @property view + * @static + * @type {View} + */ +export const view = View.instance = cc.view = new View(); + +/** + * @en cc.winSize is the alias object for the size of the current game window. + * @zh cc.winSize 为当前的游戏窗口的大小。 + * @property winSize + * @type Size + */ +cc.winSize = cc.v2(); diff --git a/cocos/core/platform/CCVisibleRect.ts b/cocos/core/platform/visible-rect.ts similarity index 100% rename from cocos/core/platform/CCVisibleRect.ts rename to cocos/core/platform/visible-rect.ts diff --git a/cocos/3d/primitive/box.ts b/cocos/core/primitive/box.ts similarity index 99% rename from cocos/3d/primitive/box.ts rename to cocos/core/primitive/box.ts index cbf7f1735b..5219737c23 100644 --- a/cocos/3d/primitive/box.ts +++ b/cocos/core/primitive/box.ts @@ -2,7 +2,7 @@ * @category 3d/primitive */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; import { IGeometry, IGeometryOptions } from './define'; /** diff --git a/cocos/3d/primitive/capsule.ts b/cocos/core/primitive/capsule.ts similarity index 99% rename from cocos/3d/primitive/capsule.ts rename to cocos/core/primitive/capsule.ts index 433d08e6e5..8b70d4af65 100644 --- a/cocos/3d/primitive/capsule.ts +++ b/cocos/core/primitive/capsule.ts @@ -2,7 +2,7 @@ * @category 3d/primitive */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; /** * @zh diff --git a/cocos/3d/primitive/circle.ts b/cocos/core/primitive/circle.ts similarity index 97% rename from cocos/3d/primitive/circle.ts rename to cocos/core/primitive/circle.ts index dba9a48097..0fd7990a72 100644 --- a/cocos/3d/primitive/circle.ts +++ b/cocos/core/primitive/circle.ts @@ -2,7 +2,7 @@ * @category 3d/primitive */ -import { GFXPrimitiveMode } from '../../gfx/define'; +import { GFXPrimitiveMode } from '../gfx/define'; import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './define'; /** diff --git a/cocos/3d/primitive/cone.ts b/cocos/core/primitive/cone.ts similarity index 100% rename from cocos/3d/primitive/cone.ts rename to cocos/core/primitive/cone.ts diff --git a/cocos/3d/primitive/cylinder.ts b/cocos/core/primitive/cylinder.ts similarity index 99% rename from cocos/3d/primitive/cylinder.ts rename to cocos/core/primitive/cylinder.ts index 4aaf95405c..ffe48103f5 100644 --- a/cocos/3d/primitive/cylinder.ts +++ b/cocos/core/primitive/cylinder.ts @@ -2,7 +2,7 @@ * @category 3d/primitive */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; import { IGeometry, IGeometryOptions } from './define'; /** diff --git a/cocos/3d/primitive/define.ts b/cocos/core/primitive/define.ts similarity index 96% rename from cocos/3d/primitive/define.ts rename to cocos/core/primitive/define.ts index c409b93798..56b0029c4b 100644 --- a/cocos/3d/primitive/define.ts +++ b/cocos/core/primitive/define.ts @@ -2,8 +2,8 @@ * @category 3d/primitive */ -import { GFXPrimitiveMode } from '../../gfx/define'; -import { IGFXAttribute } from '../../gfx/input-assembler'; +import { GFXPrimitiveMode } from '../gfx/define'; +import { IGFXAttribute } from '../gfx/input-assembler'; /** * @zh diff --git a/cocos/3d/primitive/index.ts b/cocos/core/primitive/index.ts similarity index 100% rename from cocos/3d/primitive/index.ts rename to cocos/core/primitive/index.ts diff --git a/cocos/3d/primitive/plane.ts b/cocos/core/primitive/plane.ts similarity index 98% rename from cocos/3d/primitive/plane.ts rename to cocos/core/primitive/plane.ts index d35aa4bd67..6822779555 100644 --- a/cocos/3d/primitive/plane.ts +++ b/cocos/core/primitive/plane.ts @@ -2,7 +2,7 @@ * @category 3d/primitive */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './define'; /** diff --git a/cocos/core/primitive/primitive.ts b/cocos/core/primitive/primitive.ts new file mode 100644 index 0000000000..df9e8826ab --- /dev/null +++ b/cocos/core/primitive/primitive.ts @@ -0,0 +1,31 @@ +import { ccclass, property } from '../data/class-decorator'; +import { createMesh } from '../3d/misc/utils'; +import * as primitives from '../primitive'; +import { Mesh } from '../assets/mesh'; +import { ccenum } from '../value-types/enum'; + +enum PrimitiveType { + BOX = 0, + SPHERE = 1, + CYLINDER = 2, + CONE = 3, + CAPSULE = 4, + TORUS = 5, + PLANE = 6, + QUAD = 7, +} +ccenum(PrimitiveType); + +@ccclass('cc.Primitive') +export class Primitive extends Mesh { + @property({type: PrimitiveType}) + public type: number = PrimitiveType.BOX; + @property + public info: Record = {}; + + public onLoaded () { + createMesh(primitives[PrimitiveType[this.type]](this.info), this); + } +} + +cc.Primitive = Primitive; diff --git a/cocos/3d/primitive/quad.ts b/cocos/core/primitive/quad.ts similarity index 100% rename from cocos/3d/primitive/quad.ts rename to cocos/core/primitive/quad.ts diff --git a/cocos/3d/primitive/sphere.ts b/cocos/core/primitive/sphere.ts similarity index 97% rename from cocos/3d/primitive/sphere.ts rename to cocos/core/primitive/sphere.ts index 5ff940cccf..0c16b29c04 100644 --- a/cocos/3d/primitive/sphere.ts +++ b/cocos/core/primitive/sphere.ts @@ -2,7 +2,7 @@ * @category 3d/primitive */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; import { IGeometry, IGeometryOptions } from './define'; /** diff --git a/cocos/3d/primitive/torus.ts b/cocos/core/primitive/torus.ts similarity index 98% rename from cocos/3d/primitive/torus.ts rename to cocos/core/primitive/torus.ts index 70dce7deec..085eb50a4a 100644 --- a/cocos/3d/primitive/torus.ts +++ b/cocos/core/primitive/torus.ts @@ -2,7 +2,7 @@ * @category 3d/primitive */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../math'; import { IGeometryOptions } from './define'; /** diff --git a/cocos/3d/primitive/transform.ts b/cocos/core/primitive/transform.ts similarity index 98% rename from cocos/3d/primitive/transform.ts rename to cocos/core/primitive/transform.ts index 0742c5233e..ea075eff6f 100644 --- a/cocos/3d/primitive/transform.ts +++ b/cocos/core/primitive/transform.ts @@ -2,7 +2,7 @@ * @category 3d/primitive */ -import { GFXPrimitiveMode } from '../../gfx/define'; +import { GFXPrimitiveMode } from '../gfx/define'; import { IGeometry } from './define'; /** diff --git a/cocos/3d/primitive/utils.ts b/cocos/core/primitive/utils.ts similarity index 98% rename from cocos/3d/primitive/utils.ts rename to cocos/core/primitive/utils.ts index 8b9f545b07..acba94ae4c 100644 --- a/cocos/3d/primitive/utils.ts +++ b/cocos/core/primitive/utils.ts @@ -3,7 +3,7 @@ * @category 3d/primitive */ -import { GFXPrimitiveMode } from '../../gfx/define'; +import { GFXPrimitiveMode } from '../gfx/define'; import { IGeometry } from './define'; /** diff --git a/cocos/renderer/config.ts b/cocos/core/renderer/config.ts similarity index 100% rename from cocos/renderer/config.ts rename to cocos/core/renderer/config.ts diff --git a/cocos/renderer/core/constants.ts b/cocos/core/renderer/core/constants.ts similarity index 100% rename from cocos/renderer/core/constants.ts rename to cocos/core/renderer/core/constants.ts diff --git a/cocos/renderer/core/pass.ts b/cocos/core/renderer/core/pass.ts similarity index 98% rename from cocos/renderer/core/pass.ts rename to cocos/core/renderer/core/pass.ts index fdabda622b..3735981fb4 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/core/renderer/core/pass.ts @@ -27,11 +27,11 @@ * @category material */ -import { EffectAsset, IPassInfo, IPassStates, IPropertyInfo, IShaderInfo } from '../../3d/assets/effect-asset'; +import { EffectAsset, IPassInfo, IPassStates, IPropertyInfo, IShaderInfo } from '../../assets/effect-asset'; import { builtinResMgr } from '../../3d/builtin'; import { TextureBase } from '../../assets/texture-base'; -import { Mat3, Mat4, Vec2, Vec3, Vec4 } from '../../core/math'; -import { Root } from '../../core/root'; +import { Mat3, Mat4, Vec2, Vec3, Vec4 } from '../../math'; +import { Root } from '../../root'; import { GFXBindingLayout, IGFXBinding } from '../../gfx/binding-layout'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBindingType, GFXBufferUsageBit, GFXDynamicState, @@ -48,6 +48,7 @@ import { RenderPassStage, RenderPriority, UniformBinding } from '../../pipeline/ import { getPhaseID } from '../../pipeline/pass-phase'; import { programLib } from './program-lib'; import { samplerLib } from './sampler-lib'; +import { director } from '../../director'; export interface IDefineMap { [name: string]: number | boolean | string; } export interface IPassInfoFull extends IPassInfo { @@ -390,7 +391,7 @@ export class Pass { block.dirty = false; } } - const source = (cc.director.root as Root).pipeline.globalBindings; + const source = (director.root as Root).pipeline.globalBindings; const target = this._shaderInfo.builtins.globals; const samplerLen = target.samplers.length; for (let i = 0; i < samplerLen; i++) { @@ -464,7 +465,7 @@ export class Pass { */ public tryCompile (defineOverrides?: IDefineMap) { if (defineOverrides) { Object.assign(this._defines, defineOverrides); } - const pipeline = (cc.director.root as Root).pipeline; + const pipeline = (director.root as Root).pipeline; if (!pipeline) { return false; } this._renderPass = pipeline.getRenderPass(this._stage); if (!this._renderPass) { console.warn(`illegal pass stage.`); return false; } @@ -505,7 +506,7 @@ export class Pass { bindingLayout.bindTextureView(parseInt(t), this._textureViews[t]); } // bind pipeline builtins - const source = (cc.director.root as Root).pipeline.globalBindings; + const source = (director.root as Root).pipeline.globalBindings; const target = this._shaderInfo.builtins.globals; for (const b of target.blocks) { const info = source.get(b.name); diff --git a/cocos/renderer/core/program-lib.ts b/cocos/core/renderer/core/program-lib.ts similarity index 99% rename from cocos/renderer/core/program-lib.ts rename to cocos/core/renderer/core/program-lib.ts index 2cc47a94d4..26120408bc 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/core/renderer/core/program-lib.ts @@ -27,7 +27,7 @@ * @category material */ -import { IBuiltinInfo, IDefineInfo, IShaderInfo } from '../../3d/assets/effect-asset'; +import { IBuiltinInfo, IDefineInfo, IShaderInfo } from '../../assets/effect-asset'; import { GFXBindingType, GFXShaderType } from '../../gfx/define'; import { GFXAPI, GFXDevice } from '../../gfx/device'; import { GFXShader } from '../../gfx/shader'; diff --git a/cocos/renderer/core/sampler-lib.ts b/cocos/core/renderer/core/sampler-lib.ts similarity index 100% rename from cocos/renderer/core/sampler-lib.ts rename to cocos/core/renderer/core/sampler-lib.ts diff --git a/cocos/renderer/core/texture-buffer-pool.ts b/cocos/core/renderer/core/texture-buffer-pool.ts similarity index 100% rename from cocos/renderer/core/texture-buffer-pool.ts rename to cocos/core/renderer/core/texture-buffer-pool.ts diff --git a/cocos/renderer/index.ts b/cocos/core/renderer/index.ts similarity index 80% rename from cocos/renderer/index.ts rename to cocos/core/renderer/index.ts index 619e15ce36..4c130908ae 100644 --- a/cocos/renderer/index.ts +++ b/cocos/core/renderer/index.ts @@ -15,9 +15,6 @@ export { samplerLib }; export { Light } from './scene/light'; export { Camera } from './scene/camera'; export { Model } from './scene/model'; -export * from './terrain/height-field'; -export * from './terrain/terrain'; -export { default as ParticleBatchModel } from './models/particle-batch-model'; export { SkinningModel } from './models/skinning-model'; export * from './models/joints-texture-utils'; diff --git a/cocos/renderer/models/joints-texture-utils.ts b/cocos/core/renderer/models/joints-texture-utils.ts similarity index 97% rename from cocos/renderer/models/joints-texture-utils.ts rename to cocos/core/renderer/models/joints-texture-utils.ts index de20893278..4ebb5c3fd0 100644 --- a/cocos/renderer/models/joints-texture-utils.ts +++ b/cocos/core/renderer/models/joints-texture-utils.ts @@ -27,12 +27,12 @@ * @hidden */ -import { Skeleton } from '../../3d/assets/skeleton'; -import { SkeletalAnimationClip } from '../../animation'; -import { Mat4, Quat, Vec3 } from '../../core/math'; +import { Skeleton } from '../../assets/skeleton'; +import { Mat4, Quat, Vec3 } from '../../math'; import { GFXFormat, GFXFormatInfos } from '../../gfx/define'; import { GFXDevice, GFXFeature } from '../../gfx/device'; import { ITextureBufferHandle, TextureBufferPool } from '../core/texture-buffer-pool'; +import { SkeletalAnimationClip } from '../../animation/skeletal-animation-clip'; // change here and cc-skinning.inc to use other skinning algorithms const uploadJointData = uploadJointDataDQS; diff --git a/cocos/renderer/models/model-uniforms.ts b/cocos/core/renderer/models/model-uniforms.ts similarity index 100% rename from cocos/renderer/models/model-uniforms.ts rename to cocos/core/renderer/models/model-uniforms.ts diff --git a/cocos/renderer/models/skinning-model.ts b/cocos/core/renderer/models/skinning-model.ts similarity index 96% rename from cocos/renderer/models/skinning-model.ts rename to cocos/core/renderer/models/skinning-model.ts index b6cbb7d211..617fc669eb 100644 --- a/cocos/renderer/models/skinning-model.ts +++ b/cocos/core/renderer/models/skinning-model.ts @@ -27,9 +27,8 @@ * @hidden */ -import { Skeleton } from '../../3d/assets/skeleton'; -import { SkeletalAnimationClip } from '../../animation'; -import { INode } from '../../core/utils/interfaces'; +import { Skeleton } from '../../assets/skeleton'; +import { INode } from '../../utils/interfaces'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXAddress, GFXBufferUsageBit, GFXFilter, GFXMemoryUsageBit } from '../../gfx/define'; import { UBOSkinningAnimation, UBOSkinningTexture, UniformJointsTexture } from '../../pipeline/define'; @@ -38,6 +37,7 @@ import { genSamplerHash, samplerLib } from '../core/sampler-lib'; import { Model } from '../scene/model'; import { RenderScene } from '../scene/render-scene'; import { IJointsTextureHandle } from './joints-texture-utils'; +import { SkeletalAnimationClip } from '../../animation/skeletal-animation-clip'; export interface IJointsAnimInfo { buffer: GFXBuffer; @@ -133,7 +133,7 @@ export class SkinningModel extends Model { this.uploadAnimation(this.uploadedAnim); } - public uploadAnimation (anim: SkeletalAnimationClip | null = null) { + public uploadAnimation (anim: SkeletalAnimationClip | null) { if (!this._skeleton) { return; } this.uploadedAnim = anim; const texture = this.uploadedAnim ? diff --git a/cocos/renderer/scene/ambient.ts b/cocos/core/renderer/scene/ambient.ts similarity index 100% rename from cocos/renderer/scene/ambient.ts rename to cocos/core/renderer/scene/ambient.ts diff --git a/cocos/renderer/scene/camera.ts b/cocos/core/renderer/scene/camera.ts similarity index 98% rename from cocos/renderer/scene/camera.ts rename to cocos/core/renderer/scene/camera.ts index 71e0fb83d6..f49975dc4e 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/core/renderer/scene/camera.ts @@ -1,6 +1,6 @@ -import { frustum, ray } from '../../3d/geom-utils'; -import { lerp, Mat4, Rect, toRadian, Vec3 } from '../../core/math'; -import { INode } from '../../core/utils/interfaces'; +import { frustum, ray } from '../../geom-utils'; +import { lerp, Mat4, Rect, toRadian, Vec3 } from '../../math'; +import { INode } from '../../utils/interfaces'; import { GFXClearFlag, IGFXColor } from '../../gfx/define'; import { GFXWindow } from '../../gfx/window'; import { RenderView } from '../../pipeline/render-view'; @@ -70,7 +70,7 @@ export interface ICameraInfo { node: INode; projection: number; targetDisplay?: number; - window?: GFXWindow; + window?: GFXWindow | null; priority: number; pipeline?: string; isUI?: boolean; diff --git a/cocos/renderer/scene/customization-manager.ts b/cocos/core/renderer/scene/customization-manager.ts similarity index 100% rename from cocos/renderer/scene/customization-manager.ts rename to cocos/core/renderer/scene/customization-manager.ts diff --git a/cocos/renderer/scene/directional-light.ts b/cocos/core/renderer/scene/directional-light.ts similarity index 91% rename from cocos/renderer/scene/directional-light.ts rename to cocos/core/renderer/scene/directional-light.ts index 90cf50254f..9d75905d29 100644 --- a/cocos/renderer/scene/directional-light.ts +++ b/cocos/core/renderer/scene/directional-light.ts @@ -1,5 +1,5 @@ -import { Quat, Vec3 } from '../../core/math'; -import { INode } from '../../core/utils/interfaces'; +import { Quat, Vec3 } from '../../math'; +import { INode } from '../../utils/interfaces'; import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; diff --git a/cocos/renderer/scene/light.ts b/cocos/core/renderer/scene/light.ts similarity index 96% rename from cocos/renderer/scene/light.ts rename to cocos/core/renderer/scene/light.ts index da07f23200..08d714024f 100644 --- a/cocos/renderer/scene/light.ts +++ b/cocos/core/renderer/scene/light.ts @@ -1,6 +1,6 @@ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../../math'; import { RenderScene } from './render-scene'; -import { INode } from '../../core/utils/interfaces'; +import { INode } from '../../utils/interfaces'; // Color temperature (in Kelvin) to RGB export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) { diff --git a/cocos/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts similarity index 92% rename from cocos/renderer/scene/model.ts rename to cocos/core/renderer/scene/model.ts index a35d4d8bf8..78b31d9f33 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -1,10 +1,9 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { Material } from '../../3d/assets/material'; -import { IRenderingSubmesh } from '../../3d/assets/mesh'; -import { aabb } from '../../3d/geom-utils'; -import Pool from '../../3d/memop/pool'; -import { Mat4, Vec3 } from '../../core/math'; -import { INode } from '../../core/utils/interfaces'; +import { Material } from '../../assets/material'; +import { IRenderingSubmesh } from '../../assets/mesh'; +import { aabb } from '../../geom-utils'; +import Pool from '../../memop/pool'; +import { Mat4, Vec3 } from '../../math'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBindingType, GFXBufferUsageBit, GFXGetTypeSize, GFXMemoryUsageBit } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; @@ -15,6 +14,9 @@ import { Pass } from '../core/pass'; import { customizationManager } from './customization-manager'; import { RenderScene } from './render-scene'; import { SubModel } from './submodel'; +import { INode } from '../../utils/interfaces'; +import { TransformDirtyBit } from '../../scene-graph/node-enum'; +import { director } from '../../director'; const m4_1 = new Mat4(); @@ -144,16 +146,16 @@ export class Model { return this._uboUpdated; } - protected _type = 'default'; + protected _type: string = 'default'; protected _device: GFXDevice; protected _scene: RenderScene; protected _node: INode; protected _transform: INode; protected _id: number; - protected _enabled = false; + protected _enabled: boolean = false; protected _visFlags = VisibilityFlags.GENERAL; - protected _cameraID = -1; - protected _userKey = -1; + protected _cameraID: number = -1; + protected _userKey: number = -1; protected _worldBounds: aabb | null = null; protected _modelBounds: aabb | null = null; protected _subModels: SubModel[] = []; @@ -162,16 +164,16 @@ export class Model { protected _uboLocal: UBOLocal; protected _localUBO: GFXBuffer | null = null; protected _localBindings: Map = new Map(); - protected _inited = false; - protected _uboUpdated = false; - protected _castShadow = false; - private _transformUpdated = true; + protected _inited: boolean = false; + protected _uboUpdated: boolean = false; + protected _castShadow: boolean = false; + private _transformUpdated: boolean = true; /** * Setup a default empty model */ constructor (scene: RenderScene, node: INode) { - this._device = cc.director.root.device; + this._device = director.root!.device; this._scene = scene; this._id = this._scene.generateModelId(); this._transform = this._node = node; @@ -233,11 +235,12 @@ export class Model { return false; } this._uboUpdated = true; + // @ts-ignore if (this._transformUpdated) { // @ts-ignore - const worldMatrix = this._transform._mat; + const worldMatrix = this._transform._mat; const rot = this._transform._rot; Mat4.array(this._uboLocal.view, worldMatrix, UBOLocal.MAT_WORLD_OFFSET); - Mat4.inverseTranspose(m4_1, worldMatrix); + Mat4.fromQuat(m4_1, rot); Mat4.array(this._uboLocal.view, m4_1, UBOLocal.MAT_WORLD_IT_OFFSET); const commonLocal = this._localBindings.get(UBOLocal.BLOCK.name); @@ -364,7 +367,7 @@ export class Model { break; } } - if (hasForwardLight && cc.director.root.pipeline.name === 'ForwardPipeline') { + if (hasForwardLight && director.root!.pipeline.name === 'ForwardPipeline') { if (!this._localBindings.has(UBOForwardLight.BLOCK.name)) { this._localBindings.set(UBOForwardLight.BLOCK.name, { type: GFXBindingType.UNIFORM_BUFFER, diff --git a/cocos/renderer/scene/planar-shadows.ts b/cocos/core/renderer/scene/planar-shadows.ts similarity index 97% rename from cocos/renderer/scene/planar-shadows.ts rename to cocos/core/renderer/scene/planar-shadows.ts index 6d10672df2..af8231cbb4 100644 --- a/cocos/renderer/scene/planar-shadows.ts +++ b/cocos/core/renderer/scene/planar-shadows.ts @@ -1,6 +1,7 @@ -import { EffectAsset } from '../../3d/assets/effect-asset'; -import { Color, Mat4, Quat, Vec3 } from '../../core/math'; -import { CachedArray } from '../../core/memop/cached-array'; + +import { CachedArray } from '../../memop/cached-array'; +import { Color, Mat4, Quat, Vec3 } from '../../math'; +import { EffectAsset } from '../../assets/effect-asset'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; import { GFXCommandBufferType } from '../../gfx/define'; import { GFXInputAssembler } from '../../gfx/input-assembler'; diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/core/renderer/scene/render-scene.ts similarity index 97% rename from cocos/renderer/scene/render-scene.ts rename to cocos/core/renderer/scene/render-scene.ts index d77519d591..e76ee11627 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/core/renderer/scene/render-scene.ts @@ -1,9 +1,9 @@ -import { IBArray } from '../../3d/assets/mesh'; -import { aabb, intersect, ray, triangle } from '../../3d/geom-utils'; -import { RecyclePool } from '../../3d/memop'; -import { Mat4, Vec3 } from '../../core/math'; -import { Root } from '../../core/root'; -import { INode } from '../../core/utils/interfaces'; +import { IBArray } from '../../assets/mesh'; +import { aabb, intersect, ray, triangle } from '../../geom-utils'; +import { RecyclePool } from '../../memop'; +import { Mat4, Vec3 } from '../../math'; +import { Root } from '../../root'; +import { INode } from '../../utils/interfaces'; import { GFXPrimitiveMode } from '../../gfx/define'; import { Layers } from '../../scene-graph/layers'; import { Node } from '../../scene-graph/node'; diff --git a/cocos/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts similarity index 94% rename from cocos/renderer/scene/skybox.ts rename to cocos/core/renderer/scene/skybox.ts index e9cf6b9f70..c1e160f578 100644 --- a/cocos/renderer/scene/skybox.ts +++ b/cocos/core/renderer/scene/skybox.ts @@ -1,8 +1,8 @@ -import { Material } from '../../3d/assets/material'; -import { TextureCube } from '../../3d/assets/texture-cube'; +import { Material } from '../../assets/material'; +import { TextureCube } from '../../assets/texture-cube'; import { builtinResMgr } from '../../3d/builtin'; import { createMesh } from '../../3d/misc/utils'; -import { box } from '../../3d/primitive'; +import { box } from '../../primitive'; import { IInternalBindingInst, UNIFORM_ENVIRONMENT } from '../../pipeline/define'; import { samplerLib } from '../core/sampler-lib'; import { Model } from './model'; diff --git a/cocos/renderer/scene/sphere-light.ts b/cocos/core/renderer/scene/sphere-light.ts similarity index 90% rename from cocos/renderer/scene/sphere-light.ts rename to cocos/core/renderer/scene/sphere-light.ts index c9010570ea..0af7861a13 100644 --- a/cocos/renderer/scene/sphere-light.ts +++ b/cocos/core/renderer/scene/sphere-light.ts @@ -1,8 +1,8 @@ -import { aabb } from '../../3d/geom-utils'; -import { Vec3 } from '../../core/math'; +import { aabb } from '../../geom-utils'; +import { Vec3 } from '../../math'; import { Light, LightType, nt2lm } from './light'; import { RenderScene } from './render-scene'; -import { INode } from '../../core/utils/interfaces'; +import { INode } from '../../utils/interfaces'; export class SphereLight extends Light { diff --git a/cocos/renderer/scene/spot-light.ts b/cocos/core/renderer/scene/spot-light.ts similarity index 94% rename from cocos/renderer/scene/spot-light.ts rename to cocos/core/renderer/scene/spot-light.ts index 4536fed01b..35f49b6805 100644 --- a/cocos/renderer/scene/spot-light.ts +++ b/cocos/core/renderer/scene/spot-light.ts @@ -1,8 +1,8 @@ -import { aabb, frustum } from '../../3d/geom-utils'; -import { Mat4, Quat, Vec3 } from '../../core/math'; +import { aabb, frustum } from '../../geom-utils'; +import { Mat4, Quat, Vec3 } from '../../math'; import { Light, LightType, nt2lm } from './light'; import { RenderScene } from './render-scene'; -import { INode } from '../../core/utils/interfaces'; +import { INode } from '../../utils/interfaces'; const _forward = new Vec3(0, 0, -1); const _v3 = new Vec3(); diff --git a/cocos/renderer/scene/submodel.ts b/cocos/core/renderer/scene/submodel.ts similarity index 94% rename from cocos/renderer/scene/submodel.ts rename to cocos/core/renderer/scene/submodel.ts index 5308537874..dffb665cb6 100644 --- a/cocos/renderer/scene/submodel.ts +++ b/cocos/core/renderer/scene/submodel.ts @@ -1,5 +1,5 @@ -import { Material } from '../../3d/assets/material'; -import { IRenderingSubmesh } from '../../3d/assets/mesh'; +import { Material } from '../../assets/material'; +import { IRenderingSubmesh } from '../../assets/mesh'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; import { GFXCommandBufferType, GFXStatus } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; @@ -7,6 +7,7 @@ import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../../gfx/input-assem import { GFXPipelineState } from '../../gfx/pipeline-state'; import { RenderPriority } from '../../pipeline/define'; import { Pass } from '../core/pass'; +import { director } from '../../director'; export class SubModel { protected _subMeshObject: IRenderingSubmesh | null; @@ -71,7 +72,7 @@ export class SubModel { if (this._inputAssembler) { this._inputAssembler.initialize(iaInfo); } else { - this._inputAssembler = (cc.director.root.device as GFXDevice).createInputAssembler(iaInfo); + this._inputAssembler = (director.root!.device as GFXDevice).createInputAssembler(iaInfo); } } @@ -122,7 +123,7 @@ export class SubModel { } protected recordCommandBuffer (index: number) { - const device = cc.director.root.device as GFXDevice; + const device = director.root!.device as GFXDevice; const pso = this._psos![index]; if (this._cmdBuffers[index] == null) { const cmdBufferInfo = { diff --git a/cocos/3d/ui/assembler/base.ts b/cocos/core/renderer/ui/base.ts similarity index 91% rename from cocos/3d/ui/assembler/base.ts rename to cocos/core/renderer/ui/base.ts index 4114770a5a..e196edaf86 100644 --- a/cocos/3d/ui/assembler/base.ts +++ b/cocos/core/renderer/ui/base.ts @@ -1,5 +1,5 @@ /* - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -29,7 +29,7 @@ */ -import { UIRenderComponent } from '../components'; +import { UIRenderComponent } from '../../components/ui-base/ui-render-component'; export interface IAssembler { [key: string]: any; diff --git a/cocos/3d/ui/mesh-buffer.ts b/cocos/core/renderer/ui/mesh-buffer.ts similarity index 83% rename from cocos/3d/ui/mesh-buffer.ts rename to cocos/core/renderer/ui/mesh-buffer.ts index 1d42bb2c84..d912964b14 100644 --- a/cocos/3d/ui/mesh-buffer.ts +++ b/cocos/core/renderer/ui/mesh-buffer.ts @@ -1,10 +1,36 @@ +/* + Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + /** * @category ui */ + import { GFXBuffer } from '../../gfx/buffer'; import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; import { GFXInputAssembler, IGFXAttribute } from '../../gfx/input-assembler'; -import { UI } from '../../renderer/ui/ui'; +import { UI } from './ui'; export class MeshBuffer { public batcher: UI; diff --git a/cocos/renderer/ui/renderData.ts b/cocos/core/renderer/ui/render-data.ts similarity index 76% rename from cocos/renderer/ui/renderData.ts rename to cocos/core/renderer/ui/render-data.ts index 4c8f26af9b..504eda2e4d 100644 --- a/cocos/renderer/ui/renderData.ts +++ b/cocos/core/renderer/ui/render-data.ts @@ -1,11 +1,35 @@ +/* + Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + /** * @hidden */ -import { Material } from '../../3d/assets/material'; -import Pool from '../../3d/memop/pool'; -import RecyclePool from '../../3d/memop/recycle-pool'; -import { Color, Rect } from '../../core/math'; +import { Pool, RecyclePool } from '../../memop'; +import { Material } from '../../assets'; +import { Color } from '../../math'; export interface IRenderData { x: number; diff --git a/cocos/3d/ui/assembler/mask/stencil-manager.ts b/cocos/core/renderer/ui/stencil-manager.ts similarity index 77% rename from cocos/3d/ui/assembler/mask/stencil-manager.ts rename to cocos/core/renderer/ui/stencil-manager.ts index c2ecbbf3f4..259e363732 100644 --- a/cocos/3d/ui/assembler/mask/stencil-manager.ts +++ b/cocos/core/renderer/ui/stencil-manager.ts @@ -1,39 +1,36 @@ +/* + Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ /** * @hidden */ -import { GFXComparisonFunc, GFXStencilOp } from '../../../../gfx/define'; -import { Pass } from '../../../../renderer'; -import { Material } from '../../../assets/material'; -import { MaskComponent } from '../../components/mask-component'; +import { GFXComparisonFunc, GFXStencilOp } from '../../gfx/define'; +import { Pass } from '../core/pass'; +import { Material } from '../../assets/material'; -// import { GFXStencilOp } from '../../../../gfx/define'; -// import { MaskComponent } from '../../components/mask-component'; - -// /* -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -// http://www.cocos.com - -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated engine source code (the "Software"), a limited, -// worldwide, royalty-free, non-assignable, revocable and non-exclusive license -// to use Cocos Creator solely to develop games on your target platforms. You shall -// not use Cocos Creator software for developing other software or tools that's -// used for developing games. You are not granted to publish, distribute, -// sublicense, and/or sell copies of Cocos Creator. - -// The software or tools in this License Agreement are licensed, not sold. -// Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// */ +// import { GFXStencilOp } from '../../gfx/define'; // Stage types export enum Stage { @@ -73,7 +70,7 @@ function updateDynamicStencilStates (material: Material, state: IStencilStateUpd export class StencilManager { public static sharedManager: StencilManager | null = null; public stage = Stage.DISABLED; - private _maskStack: MaskComponent[] = []; + private _maskStack: any[] = []; private _stencilPattern = { stencilTest: true, func: GFXComparisonFunc.ALWAYS, @@ -91,7 +88,7 @@ export class StencilManager { blendState: {}, }; - public pushMask (mask: MaskComponent) { + public pushMask (mask: any) { this._maskStack.push(mask); } diff --git a/cocos/renderer/ui/ui-batch-model.ts b/cocos/core/renderer/ui/ui-batch-model.ts similarity index 50% rename from cocos/renderer/ui/ui-batch-model.ts rename to cocos/core/renderer/ui/ui-batch-model.ts index e0137eded3..2bba8db22a 100644 --- a/cocos/renderer/ui/ui-batch-model.ts +++ b/cocos/core/renderer/ui/ui-batch-model.ts @@ -1,8 +1,32 @@ +/* + Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ /** * @hidden */ -import { Material } from '../../3d/assets/material'; +import { Material } from '../../assets/material'; import { GFXInputAssembler } from '../../gfx/input-assembler'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { Model } from '../scene/model'; diff --git a/cocos/core/renderer/ui/ui-material.ts b/cocos/core/renderer/ui/ui-material.ts new file mode 100644 index 0000000000..fdddbead75 --- /dev/null +++ b/cocos/core/renderer/ui/ui-material.ts @@ -0,0 +1,90 @@ +/* + Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ +/** + * @hidden + */ + +import { Material } from '../../assets/material'; +import Pool from '../../memop/pool'; +import { GFXPipelineState } from '../../gfx/pipeline-state'; +import { Pass } from '../../renderer/core/pass'; + +export interface IUIMaterialInfo { + material: Material; +} + +export class UIMaterial { + + public get material (): Material { + return this._material!; + } + + public get pass (): Pass { + return this._pass!; + } + + protected _material: Material | null = null; + protected _pass: Pass | null = null; + private _psos: Pool | null; + + constructor () { + this._psos = null; + } + + public initialize (info: IUIMaterialInfo): boolean { + + if (!info.material) { + return false; + } + + this._material = info.material; + + this._pass = this._material.passes[0]; + + this._psos = new Pool(() => { + const pso = this._pass!.createPipelineState()!; + return pso; + }, 1); + + return true; + } + + public getPipelineState (): GFXPipelineState { + return this._psos!.alloc(); + } + + public revertPipelineState (pso: GFXPipelineState) { + this._psos!.free(pso); + } + + public destroy () { + this._material = null; + if (this._psos) { + this._psos.clear((obj: GFXPipelineState) => { + this._pass!.destroyPipelineState(obj); + }); + } + } +} diff --git a/cocos/core/renderer/ui/ui-vertex-format.ts b/cocos/core/renderer/ui/ui-vertex-format.ts new file mode 100644 index 0000000000..7676ad373e --- /dev/null +++ b/cocos/core/renderer/ui/ui-vertex-format.ts @@ -0,0 +1,43 @@ +/* + Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ +/** + * @category ui + */ +import { GFXAttributeName, GFXFormat } from '../../gfx/define'; + +export const vfmt = [ + { + name: GFXAttributeName.ATTR_POSITION, + format: GFXFormat.RGB32F, + }, + { + name: GFXAttributeName.ATTR_TEX_COORD, + format: GFXFormat.RG32F, + }, + { + name: GFXAttributeName.ATTR_COLOR, + format: GFXFormat.RGBA32F, + }, +]; diff --git a/cocos/renderer/ui/ui.ts b/cocos/core/renderer/ui/ui.ts similarity index 88% rename from cocos/renderer/ui/ui.ts rename to cocos/core/renderer/ui/ui.ts index 10a6b2adb7..109484f775 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/core/renderer/ui/ui.ts @@ -1,13 +1,39 @@ +/* + Copyright (c) 2019 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ /** * @hidden */ -import { CanvasComponent, MeshBuffer, StencilManager, UIComponent, UIRenderComponent, UIVertexFormat } from '../../3d/ui'; -import { Material } from '../../3d/assets/material'; -import Pool from '../../3d/memop/pool'; -import RecyclePool from '../../3d/memop/recycle-pool'; -import { CachedArray } from '../../core/memop/cached-array'; -import { Root } from '../../core/root'; +import { CanvasComponent, UIComponent, UIRenderComponent } from '../../components/ui-base'; +import { MeshBuffer } from './mesh-buffer'; +import * as UIVertexFormat from './ui-vertex-format'; +import { StencilManager } from './stencil-manager'; +import { Material } from '../../assets/material'; +import { Pool, RecyclePool } from '../../memop'; +import { CachedArray } from '../../memop/cached-array'; +import { Root } from '../../root'; import { GFXBindingLayout } from '../../gfx/binding-layout'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; import { GFXCommandBufferType } from '../../gfx/define'; @@ -16,12 +42,14 @@ import { IGFXAttribute } from '../../gfx/input-assembler'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { GFXTextureView } from '../../gfx/texture-view'; import { UniformBinding } from '../../pipeline/define'; -import { Camera } from '../scene/camera'; -import { Model, VisibilityFlags } from '../scene/model'; -import { RenderScene } from '../scene/render-scene'; +import { Camera } from '../../renderer/scene/camera'; +import { Model, VisibilityFlags } from '../../renderer/scene/model'; +import { RenderScene } from '../../renderer/scene/render-scene'; import { UIBatchModel } from './ui-batch-model'; import { UIMaterial } from './ui-material'; -import { INode } from '../../core/utils/interfaces'; +import { INode } from '../../utils/interfaces'; +import { RenderableComponent } from '../../3d/framework'; +import { Director, director } from '../../director'; export class UIDrawBatch { public camera: Camera | null = null; @@ -105,7 +133,7 @@ export class UI { private _uiModelPool: Pool | null = null; private _modelInUse: CachedArray; // batcher - private _emptyMaterial = Material.getInstantiatedMaterial(new Material(), new cc.RenderableComponent(), CC_EDITOR ? true : false); + private _emptyMaterial = Material.getInstantiatedMaterial(new Material(), new RenderableComponent(), CC_EDITOR ? true : false); private _currMeshBuffer: MeshBuffer | null = null; private _currMaterial: Material = this._emptyMaterial; private _currTexView: GFXTextureView | null = null; @@ -124,7 +152,7 @@ export class UI { this._modelInUse = new CachedArray(10); this._batches = new CachedArray(64); - cc.director.on(cc.Director.EVENT_BEFORE_DRAW, this.update, this); + director.on(Director.EVENT_BEFORE_DRAW, this.update, this); } public initialize () { @@ -487,7 +515,7 @@ export class UI { this._recursiveScreenNode(this._debugScreen.node); } } - + private _preprocess (c: INode) { // ts-ignore let render = c._uiComp; diff --git a/cocos/renderer/utils.ts b/cocos/core/renderer/utils.ts similarity index 100% rename from cocos/renderer/utils.ts rename to cocos/core/renderer/utils.ts diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 9082663d70..03e8f2dbf8 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -2,14 +2,14 @@ * @category core */ -import { builtinResMgr } from '../3d/builtin'; -import { GFXDevice } from '../gfx/device'; -import { GFXWindow, IGFXWindowInfo } from '../gfx/window'; -import { ForwardPipeline } from '../pipeline/forward/forward-pipeline'; -import { RenderPipeline } from '../pipeline/render-pipeline'; -import { IRenderViewInfo, RenderView } from '../pipeline/render-view'; -import { IRenderSceneInfo, RenderScene } from '../renderer/scene/render-scene'; -import { UI } from '../renderer/ui/ui'; +import { builtinResMgr } from './3d/builtin'; +import { GFXDevice } from './gfx/device'; +import { GFXWindow, IGFXWindowInfo } from './gfx/window'; +import { ForwardPipeline } from './pipeline/forward/forward-pipeline'; +import { RenderPipeline } from './pipeline/render-pipeline'; +import { IRenderViewInfo, RenderView } from './pipeline/render-view'; +import { IRenderSceneInfo, RenderScene } from './renderer/scene/render-scene'; +import { UI } from './renderer/ui/ui'; export let _createSceneFun; export let _createViewFun; diff --git a/cocos/scene-graph/base-node-dev.ts b/cocos/core/scene-graph/base-node-dev.ts similarity index 96% rename from cocos/scene-graph/base-node-dev.ts rename to cocos/core/scene-graph/base-node-dev.ts index 07e368e0a9..e9463d5b40 100644 --- a/cocos/scene-graph/base-node-dev.ts +++ b/cocos/core/scene-graph/base-node-dev.ts @@ -27,8 +27,9 @@ * @category scene-graph */ -import { CCObject } from '../core/data/object'; -import * as js from '../core/utils/js'; +import { CCObject } from '../data/object'; +import * as js from '../utils/js'; +import { director } from '../director'; // @ts-ignore const Destroying = CCObject.Flags.Destroying; @@ -93,7 +94,7 @@ export function baseNodePolyfill (BaseNode) { cc.engine.attachedObjsForEditor[comp._id] = comp; } if (this._activeInHierarchy) { - cc.director._nodeActivator.activateComp(comp); + director._nodeActivator.activateComp(comp); } }; @@ -120,7 +121,7 @@ export function baseNodePolyfill (BaseNode) { // check activity state const shouldActiveNow = this._active && !!(this._parent && this._parent._activeInHierarchy); if (this._activeInHierarchy !== shouldActiveNow) { - cc.director._nodeActivator.activateNode(this, shouldActiveNow); + director._nodeActivator.activateNode(this, shouldActiveNow); } }; diff --git a/cocos/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts similarity index 97% rename from cocos/scene-graph/base-node.ts rename to cocos/core/scene-graph/base-node.ts index 8cc081e907..c932dbe016 100644 --- a/cocos/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -28,14 +28,16 @@ */ import { Component } from '../components/component'; -import { ccclass, property } from '../core/data/class-decorator'; -import { CCObject } from '../core/data/object'; -import { SystemEventType } from '../core/platform/event-manager/event-enum'; -import IdGenerator from '../core/utils/id-generator'; -import { IBaseNode } from '../core/utils/interfaces'; -import * as js from '../core/utils/js'; +import { ccclass, property } from '../data/class-decorator'; +import { CCObject } from '../data/object'; +import { SystemEventType } from '../platform/event-manager/event-enum'; +import IdGenerator from '../utils/id-generator'; +import { IBaseNode } from '../utils/interfaces'; +import * as js from '../utils/js'; import { baseNodePolyfill } from './base-node-dev'; import { Scene } from './scene'; +import { ISchedulable } from '../scheduler'; +import { director } from '../director'; /** * @@ -84,7 +86,7 @@ function getConstructor (typeOrClassName: string | Function): Function | null { * @protected */ @ccclass('cc._BaseNode') -export class BaseNode extends CCObject implements IBaseNode { +export class BaseNode extends CCObject implements IBaseNode, ISchedulable { /** * Gets all components attached to this node. */ @@ -201,7 +203,7 @@ export class BaseNode extends CCObject implements IBaseNode { if (parent) { const couldActiveInScene = parent._activeInHierarchy; if (couldActiveInScene) { - cc.director._nodeActivator.activateNode(this, isActive); + director._nodeActivator.activateNode(this, isActive); } } } @@ -359,6 +361,8 @@ export class BaseNode extends CCObject implements IBaseNode { // @ts-ignore protected _id: string = idGenerator.getNewId(); + protected _name: string; + /** * Register all related EventTargets, * all event callbacks will be removed in _onPreDestroy @@ -376,10 +380,6 @@ export class BaseNode extends CCObject implements IBaseNode { super(name); this._name = name !== undefined ? name : 'New Node'; - if (cc.director && cc.director._scheduler) { - cc.director._scheduler.enableForTarget(this); - } - // @ts-ignore if (CC_EDITOR && window.EditorExtends) { // @ts-ignore @@ -799,8 +799,8 @@ export class BaseNode extends CCObject implements IBaseNode { * node.isChildOf(newNode); * ``` */ - public isChildOf (parent: this): boolean { - let child: this | null = this; + public isChildOf (parent: this | null): boolean { + let child: BaseNode | null = this; do { if (child === parent) { return true; @@ -1027,7 +1027,7 @@ export class BaseNode extends CCObject implements IBaseNode { cc.engine.attachedObjsForEditor[component._id] = component; } if (this._activeInHierarchy) { - cc.director._nodeActivator.activateComp(component); + director._nodeActivator.activateComp(component); } return component; @@ -1216,7 +1216,7 @@ export class BaseNode extends CCObject implements IBaseNode { } if (CC_EDITOR || CC_TEST) { - const scene = cc.director.getScene(); + const scene = director.getScene() as this | null; const inCurrentSceneBefore = oldParent && oldParent.isChildOf(scene); const inCurrentSceneNow = newParent && newParent.isChildOf(scene); if (!inCurrentSceneBefore && inCurrentSceneNow) { @@ -1255,7 +1255,7 @@ export class BaseNode extends CCObject implements IBaseNode { const shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy); if (this._activeInHierarchy !== shouldActiveNow) { - cc.director._nodeActivator.activateNode(this, shouldActiveNow); + director._nodeActivator.activateNode(this, shouldActiveNow); } } @@ -1321,7 +1321,7 @@ export class BaseNode extends CCObject implements IBaseNode { for (let i = 0; i < comps.length; ++i) { const component = comps[i]; if (component._enabled) { - cc.director._compScheduler.disableComp(component); + director._compScheduler.disableComp(component); } } // deactivate recursively diff --git a/cocos/scene-graph/component-scheduler.ts b/cocos/core/scene-graph/component-scheduler.ts similarity index 98% rename from cocos/scene-graph/component-scheduler.ts rename to cocos/core/scene-graph/component-scheduler.ts index 8b29611300..287d95238d 100644 --- a/cocos/scene-graph/component-scheduler.ts +++ b/cocos/core/scene-graph/component-scheduler.ts @@ -27,10 +27,10 @@ * @category scene-graph */ -import { CCObject } from '../core/data/object'; -import { MutableForwardIterator } from '../core/utils/array'; -import { array } from '../core/utils/js'; -import { tryCatchFunctor_EDITOR } from '../core/utils/misc'; +import { CCObject } from '../data/object'; +import { MutableForwardIterator } from '../utils/array'; +import { array } from '../utils/js'; +import { tryCatchFunctor_EDITOR } from '../utils/misc'; const fastRemoveAt = array.fastRemoveAt; // @ts-ignore @@ -367,7 +367,7 @@ class ComponentScheduler { } } - public enableComp (comp, invoker) { + public enableComp (comp, invoker?) { if (!(comp._objFlags & IsOnEnableCalled)) { if (comp.onEnable) { if (invoker) { diff --git a/cocos/scene-graph/deprecated.ts b/cocos/core/scene-graph/deprecated.ts similarity index 89% rename from cocos/scene-graph/deprecated.ts rename to cocos/core/scene-graph/deprecated.ts index a0b7b8da3d..f4cb4536e6 100644 --- a/cocos/scene-graph/deprecated.ts +++ b/cocos/core/scene-graph/deprecated.ts @@ -3,7 +3,7 @@ */ import { BaseNode } from './base-node'; -import { replaceProperty } from '../deprecated'; +import { replaceProperty } from '../utils/deprecated'; // js.get(BaseNode.prototype, 'childrenCount', function () { // cc.warn("`childrenCount` is deprecated, please use `node.children.length` instead."); diff --git a/cocos/scene-graph/find.ts b/cocos/core/scene-graph/find.ts similarity index 94% rename from cocos/scene-graph/find.ts rename to cocos/core/scene-graph/find.ts index 0c8bd8ce78..3613b60e22 100644 --- a/cocos/scene-graph/find.ts +++ b/cocos/core/scene-graph/find.ts @@ -27,8 +27,9 @@ * @category scene-graph */ -import { warnID } from '../core/platform/CCDebug'; +import { warnID } from '../platform/debug'; import { Node } from './node'; +import { director } from '../director'; /** * Finds a node by hierarchy path, the path is case-sensitive. @@ -38,7 +39,7 @@ import { Node } from './node'; */ export function find (path: string, referenceNode?: Node): Node | null { if (!referenceNode) { - const scene = cc.director.getScene(); + const scene = director.getScene(); if (!scene) { if (CC_DEV) { warnID(5601); diff --git a/cocos/scene-graph/index.ts b/cocos/core/scene-graph/index.ts similarity index 98% rename from cocos/scene-graph/index.ts rename to cocos/core/scene-graph/index.ts index 08e1be2929..b62179a5b8 100644 --- a/cocos/scene-graph/index.ts +++ b/cocos/core/scene-graph/index.ts @@ -36,4 +36,4 @@ export { find } from './find'; export { PrivateNode } from './private-node'; export { default as NodeActivator } from './node-activator'; -import './deprecated'; \ No newline at end of file +import './deprecated'; \ No newline at end of file diff --git a/cocos/scene-graph/layers.ts b/cocos/core/scene-graph/layers.ts similarity index 100% rename from cocos/scene-graph/layers.ts rename to cocos/core/scene-graph/layers.ts diff --git a/cocos/scene-graph/node-activator.ts b/cocos/core/scene-graph/node-activator.ts similarity index 98% rename from cocos/scene-graph/node-activator.ts rename to cocos/core/scene-graph/node-activator.ts index 1a6dd2535e..4a91dec0bd 100644 --- a/cocos/scene-graph/node-activator.ts +++ b/cocos/core/scene-graph/node-activator.ts @@ -27,9 +27,9 @@ * @category scene-graph */ -import { CCObject } from '../core/data/object'; -import { array, Pool } from '../core/utils/js'; -import { tryCatchFunctor_EDITOR } from '../core/utils/misc'; +import { CCObject } from '../data/object'; +import { array, Pool } from '../utils/js'; +import { tryCatchFunctor_EDITOR } from '../utils/misc'; import ComponentScheduler from './component-scheduler'; const MAX_POOL_SIZE = 4; @@ -180,7 +180,7 @@ export default class NodeActivator { node.emit('active-in-hierarchy-changed', node); } - public activateComp (comp, preloadInvoker, onLoadInvoker, onEnableInvoker) { + public activateComp (comp, preloadInvoker?, onLoadInvoker?, onEnableInvoker?) { if (!(comp._objFlags & IsPreloadStarted)) { comp._objFlags |= IsPreloadStarted; if (comp.__preload) { diff --git a/cocos/scene-graph/node-enum.ts b/cocos/core/scene-graph/node-enum.ts similarity index 100% rename from cocos/scene-graph/node-enum.ts rename to cocos/core/scene-graph/node-enum.ts diff --git a/cocos/scene-graph/node-event-processor.ts b/cocos/core/scene-graph/node-event-processor.ts similarity index 98% rename from cocos/scene-graph/node-event-processor.ts rename to cocos/core/scene-graph/node-event-processor.ts index 73e619eae4..406c14d9c4 100644 --- a/cocos/scene-graph/node-event-processor.ts +++ b/cocos/core/scene-graph/node-event-processor.ts @@ -27,14 +27,14 @@ * @category scene-graph */ -import { INode } from '../core/utils/interfaces'; -import { ITargetImpl, EventTarget } from '../core/event/event-target'; -import { eventManager, EventMouse, EventTouch, Touch } from '../core/platform/event-manager'; -import { SystemEventType } from '../core/platform/event-manager/event-enum'; -import { EventListener } from '../core/platform/event-manager/event-listener'; -import { array } from '../core/utils/js'; -import Event from '../core/event/event'; -import { Vec2 } from '../core/math/vec2'; +import { INode } from '../utils/interfaces'; +import { ITargetImpl, EventTarget } from '../event/event-target'; +import { eventManager, EventMouse, EventTouch, Touch } from '../platform/event-manager'; +import { SystemEventType } from '../platform/event-manager/event-enum'; +import { EventListener } from '../platform/event-manager/event-listener'; +import { array } from '../utils/js'; +import Event from '../event/event'; +import { Vec2 } from '../math/vec2'; const fastRemove = array.fastRemove; diff --git a/cocos/scene-graph/node.ts b/cocos/core/scene-graph/node.ts similarity index 98% rename from cocos/scene-graph/node.ts rename to cocos/core/scene-graph/node.ts index d28683a18c..294e755f35 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -27,13 +27,13 @@ * @category scene-graph */ -import { UIComponent, UITransformComponent } from '../3d/ui/components'; -import { ccclass, property } from '../core/data/class-decorator'; -import Event from '../core/event/event'; -import { Mat3, Mat4, Quat, Size, Vec2, Vec3 } from '../core/math'; -import { eventManager } from '../core/platform/event-manager'; -import { SystemEventType } from '../core/platform/event-manager/event-enum'; -import { INode } from '../core/utils/interfaces'; +import { UIComponent, UITransformComponent } from '../components/ui-base'; +import { ccclass, property } from '../data/class-decorator'; +import Event from '../event/event'; +import { Mat3, Mat4, Quat, Size, Vec2, Vec3 } from '../math'; +import { eventManager } from '../platform/event-manager'; +import { SystemEventType } from '../platform/event-manager/event-enum'; +import { INode } from '../utils/interfaces'; import { BaseNode } from './base-node'; import { Layers } from './layers'; import { NodeSpace, TransformDirtyBit } from './node-enum'; @@ -108,7 +108,7 @@ export class Node extends BaseNode implements INode { protected _dirtyFlags = TransformDirtyBit.NONE; // does the world transform need to update? protected _eulerDirty = false; - protected _eventProcessor: NodeEventProcessor = new cc.NodeEventProcessor(this); + protected _eventProcessor: NodeEventProcessor = new NodeEventProcessor(this as INode); protected _eventMask = 0; private _uiTransfromComp: UITransformComponent | null = null; // tslint:disable-next-line: member-ordering diff --git a/cocos/scene-graph/private-node.ts b/cocos/core/scene-graph/private-node.ts similarity index 98% rename from cocos/scene-graph/private-node.ts rename to cocos/core/scene-graph/private-node.ts index 513e4ed4d9..04010389e6 100644 --- a/cocos/scene-graph/private-node.ts +++ b/cocos/core/scene-graph/private-node.ts @@ -27,8 +27,8 @@ * @category scene-graph */ -import { ccclass } from '../core/data/class-decorator'; -import { CCObject } from '../core/data/object'; +import { ccclass } from '../data/class-decorator'; +import { CCObject } from '../data/object'; import { Node } from './node'; // const LocalDirtyFlag = Node._LocalDirtyFlag; diff --git a/cocos/scene-graph/scene-globals.ts b/cocos/core/scene-graph/scene-globals.ts similarity index 96% rename from cocos/scene-graph/scene-globals.ts rename to cocos/core/scene-graph/scene-globals.ts index 37123299e2..1f0891d785 100644 --- a/cocos/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -27,10 +27,10 @@ * @category scene-graph */ -import { TextureCube } from '../3d/assets/texture-cube'; -import { ccclass, property } from '../core/data/class-decorator'; -import { CCBoolean, CCFloat } from '../core/data/utils/attribute'; -import { Color, Quat, Vec3 } from '../core/math'; +import { TextureCube } from '../assets/texture-cube'; +import { ccclass, property } from '../data/class-decorator'; +import { CCBoolean, CCFloat } from '../data/utils/attribute'; +import { Color, Quat, Vec3 } from '../math'; import { Ambient } from '../renderer/scene/ambient'; import { PlanarShadows } from '../renderer/scene/planar-shadows'; import { RenderScene } from '../renderer/scene/render-scene'; diff --git a/cocos/scene-graph/scene.ts b/cocos/core/scene-graph/scene.ts similarity index 98% rename from cocos/scene-graph/scene.ts rename to cocos/core/scene-graph/scene.ts index 4df17b6893..cb31de0967 100644 --- a/cocos/scene-graph/scene.ts +++ b/cocos/core/scene-graph/scene.ts @@ -27,7 +27,7 @@ * @category scene-graph */ -import { ccclass, property } from '../core/data/class-decorator'; +import { ccclass, property } from '../data/class-decorator'; import { RenderScene } from '../renderer/scene/render-scene'; import { BaseNode } from './base-node'; import { Node } from './node'; diff --git a/cocos/core/scheduler.ts b/cocos/core/scheduler.ts index 89918d3056..dc6b3b6f1d 100644 --- a/cocos/core/scheduler.ts +++ b/cocos/core/scheduler.ts @@ -29,11 +29,17 @@ import IdGenerator from './utils/id-generator'; import {createMap} from './utils/js'; +import System from './components/system'; const MAX_POOL_SIZE = 20; const idGenerator = new IdGenerator('Scheduler'); +export interface ISchedulable { + id?:string; + uuid?:string; +} + // data structures /** * @en A list double-linked list used for "updates with priority" @@ -46,7 +52,7 @@ const idGenerator = new IdGenerator('Scheduler'); */ class ListEntry { - public static get = (target: any, priority: Number, paused: Boolean, markedForDeletion: Boolean) => { + public static get = (target: ISchedulable, priority: Number, paused: Boolean, markedForDeletion: Boolean) => { let result = ListEntry._listEntries.pop(); if (result) { result.target = target; @@ -69,12 +75,12 @@ class ListEntry { private static _listEntries: any = []; - public target: any; + public target: ISchedulable; public priority: Number; public paused: Boolean; public markedForDeletion: Boolean; - constructor (target: any, priority: Number, paused: Boolean, markedForDeletion: Boolean) { + constructor (target: ISchedulable, priority: Number, paused: Boolean, markedForDeletion: Boolean) { this.target = target; this.priority = priority; this.paused = paused; @@ -93,7 +99,7 @@ class ListEntry { */ class HashUpdateEntry { - public static get = (list: any, entry: ListEntry, target: Object, callback: any) => { + public static get = (list: any, entry: ListEntry, target: ISchedulable, callback: any) => { let result = HashUpdateEntry._hashUpdateEntries.pop(); if (result) { result.list = list; @@ -118,10 +124,10 @@ class HashUpdateEntry { public list: any; public entry: ListEntry; - public target: Object; + public target: ISchedulable; public callback: any; - constructor (list: any, entry: ListEntry, target: Object, callback: any) { + constructor (list: any, entry: ListEntry, target: ISchedulable, callback: any) { this.list = list; this.entry = entry; this.target = target; @@ -142,7 +148,7 @@ class HashUpdateEntry { */ class HashTimerEntry { - public static get = (timers: any, target: Object, timerIndex: Number, currentTimer: any, currentTimerSalvaged: any, paused: any) => { + public static get = (timers: any, target: ISchedulable, timerIndex: Number, currentTimer: any, currentTimerSalvaged: any, paused: any) => { let result = HashTimerEntry._hashTimerEntries.pop(); if (result) { result.timers = timers; @@ -168,13 +174,13 @@ class HashTimerEntry { private static _hashTimerEntries: any = []; public timers: any; - public target: Object; + public target: ISchedulable; public timerIndex: Number; public currentTimer: any; public currentTimerSalvaged: any; public paused: any; - constructor (timers: any, target: Object, timerIndex: Number, currentTimer: any, currentTimerSalvaged: any, paused: any){ + constructor (timers: any, target: ISchedulable, timerIndex: Number, currentTimer: any, currentTimerSalvaged: any, paused: any){ this.timers = timers; this.target = target; this.timerIndex = timerIndex; @@ -209,7 +215,7 @@ class CallbackTimer { private _repeat: number; private _delay: number; private _interval: number; - private _target: any; + private _target: ISchedulable | null; private _callback: any; constructor () { @@ -227,7 +233,7 @@ class CallbackTimer { this._callback = null; } - public initWithCallback (scheduler: any, callback: any, target: any, seconds: number, repeat: number, delay: number) { + public initWithCallback (scheduler: any, callback: any, target: ISchedulable, seconds: number, repeat: number, delay: number) { this._lock = false; this._scheduler = scheduler; this._target = target; @@ -333,7 +339,7 @@ class CallbackTimer { * * @class Scheduler */ -class Scheduler { +export class Scheduler extends System { /** * @en Priority level reserved for system services. * @zh 系统服务的优先级。 @@ -348,6 +354,8 @@ class Scheduler { */ public static PRIORITY_NON_SYSTEM: number = Scheduler.PRIORITY_SYSTEM + 1; + public static ID = 'scheduler'; + private _timeScale: number; private _updatesNegList: any[]; private _updates0List: any[]; @@ -359,7 +367,34 @@ class Scheduler { private _updateHashLocked: boolean; private _arrayForTimers; + /** + * @en This method should be called for any target which needs to schedule tasks, and this method should be called before any scheduler API usage. + * This method will add a `id` property if it doesn't exist. + * @zh 任何需要用 Scheduler 管理任务的对象主体都应该调用这个方法,并且应该在调用任何 Scheduler API 之前调用这个方法。 + * 这个方法会给对象添加一个 `id` 属性,如果这个属性不存在的话。 + * @param {Object} target + */ + public static enableForTarget (target: ISchedulable) { + let found = false; + if (target.uuid) { + found = true; + } + else if (target.id) { + found = true; + } + if (!found) { + // @ts-ignore + if (target.__instanceId) { + cc.warnID(1513); + } + else { + target.id = idGenerator.getNewId(); + } + } + } + constructor () { + super(); this._timeScale = 1.0; this._updatesNegList = []; // list of priority < 0 this._updates0List = []; // list of priority == 0 @@ -375,23 +410,6 @@ class Scheduler { } // -----------------------public method------------------------- - /** - * @en This method should be called for any target which needs to schedule tasks, and this method should be called before any scheduler API usage. - * This method will add a `_id` property if it doesn't exist. - * @zh 任何需要用 Scheduler 管理任务的对象主体都应该调用这个方法,并且应该在调用任何 Scheduler API 之前调用这个方法。 - * 这个方法会给对象添加一个 `_id` 属性,如果这个属性不存在的话。 - * @param {Object} target - */ - public enableForTarget (target) { - if (!target._id) { - if (target.__instanceId) { - cc.warnID(1513); - } - else { - target._id = idGenerator.getNewId(); - } - } - } /** * @en @@ -547,10 +565,11 @@ class Scheduler { * @param {Number} [delay=0] * @param {Boolean} [paused=fasle] */ - public schedule (callback: Function, target: any, interval: number, repeat: number, delay: number, paused?: boolean) { + public schedule (callback: Function, target: ISchedulable, interval: number, repeat: number, delay: number, paused?: boolean) { 'use strict'; if (typeof callback !== 'function') { const tmp = callback; + // @ts-ignore callback = target; target = tmp; } @@ -564,15 +583,10 @@ class Scheduler { cc.assertID(target, 1502); - let targetId = target._id; + let targetId = target.uuid || target.id; if (!targetId) { - if (target.__instanceId) { - cc.warnID(1513); - targetId = target._id = target.__instanceId; - } - else { - cc.errorID(1510); - } + cc.errorID(1510); + return; } let element = this._hashForTimers[targetId]; if (!element) { @@ -621,16 +635,11 @@ class Scheduler { * @param {Number} priority * @param {Boolean} paused */ - public scheduleUpdate (target: any, priority: Number, paused: Boolean) { - let targetId = target._id; + public scheduleUpdate (target: ISchedulable, priority: Number, paused: Boolean) { + let targetId = target.uuid || target.id; if (!targetId) { - if (target.__instanceId) { - cc.warnID(1513); - targetId = target._id = target.__instanceId; - } - else { - cc.errorID(1510); - } + cc.errorID(1510); + return; } const hashElement = this._hashForUpdates[targetId]; if (hashElement && hashElement.entry){ @@ -680,22 +689,17 @@ class Scheduler { * @param {Function} callback The callback to be unscheduled * @param {Object} target The target bound to the callback. */ - public unschedule (callback, target) { + public unschedule (callback, target:ISchedulable) { // callback, target // explicity handle nil arguments when removing an object if (!target || !callback) { return; } - let targetId = target._id; + let targetId = target.uuid || target.id; if (!targetId) { - if (target.__instanceId) { - cc.warnID(1513); - targetId = target._id = target.__instanceId; - } - else { - cc.errorID(1510); - } + cc.errorID(1510); + return; } const self = this; @@ -733,19 +737,14 @@ class Scheduler { * @zh 取消指定对象的 update 定时器。 * @param {Object} target The target to be unscheduled. */ - public unscheduleUpdate (target) { + public unscheduleUpdate (target:ISchedulable) { if (!target) { return; } - let targetId = target._id; + let targetId = target.uuid || target.id; if (!targetId) { - if (target.__instanceId) { - cc.warnID(1513); - targetId = target._id = target.__instanceId; - } - else { - cc.errorID(1510); - } + cc.errorID(1510); + return; } const element = this._hashForUpdates[targetId]; @@ -770,15 +769,10 @@ class Scheduler { if (!target){ return; } - let targetId = target._id; + let targetId = target.uuid || target.id; if (!targetId) { - if (target.__instanceId) { - cc.warnID(1513); - targetId = target._id = target.__instanceId; - } - else { - cc.errorID(1510); - } + cc.errorID(1510); + return; } // Custom Selectors @@ -885,20 +879,15 @@ class Scheduler { * @param {Object} target The target of the callback. * @return {Boolean} True if the specified callback is invoked, false if not. */ - public isScheduled (callback, target){ + public isScheduled (callback, target:ISchedulable){ // key, target // selector, target cc.assertID(callback, 1508); cc.assertID(target, 1509); - let targetId = target._id; + let targetId = target.uuid || target.id; if (!targetId) { - if (target.__instanceId) { - cc.warnID(1513); - targetId = target._id = target.__instanceId; - } - else { - cc.errorID(1510); - } + cc.errorID(1510); + return; } const element = this._hashForTimers[targetId]; @@ -1027,17 +1016,12 @@ class Scheduler { * 如果指定的对象没有定时器,什么也不会发生。 * @param {Object} target */ - public pauseTarget (target) { + public pauseTarget (target:ISchedulable) { cc.assertID(target, 1503); - let targetId = target._id; + let targetId = target.uuid || target.id; if (!targetId) { - if (target.__instanceId) { - cc.warnID(1513); - targetId = target._id = target.__instanceId; - } - else { - cc.errorID(1510); - } + cc.errorID(1510); + return; } // customer selectors @@ -1065,17 +1049,12 @@ class Scheduler { * 如果指定的对象没有定时器,什么也不会发生。 * @param {Object} target */ - public resumeTarget (target) { + public resumeTarget (target:ISchedulable) { cc.assertID(target, 1504); - let targetId = target._id; + let targetId = target.uuid || target.id; if (!targetId) { - if (target.__instanceId) { - cc.warnID(1513); - targetId = target._id = target.__instanceId; - } - else { - cc.errorID(1510); - } + cc.errorID(1510); + return; } // custom selectors @@ -1098,17 +1077,12 @@ class Scheduler { * @param {Object} target * @return {Boolean} */ - public isTargetPaused (target) { + public isTargetPaused (target:ISchedulable) { cc.assertID(target, 1505); - let targetId = target._id; + let targetId = target.uuid || target.id; if (!targetId) { - if (target.__instanceId) { - cc.warnID(1513); - targetId = target._id = target.__instanceId; - } - else { - cc.errorID(1510); - } + cc.errorID(1510); + return; } // Custom selectors @@ -1125,7 +1099,8 @@ class Scheduler { // -----------------------private method---------------------- private _removeHashElement (element) { - delete this._hashForTimers[element.target._id]; + let targetId = element.target.uuid || element.target.id; + delete this._hashForTimers[targetId]; const arr = this._arrayForTimers; for (let i = 0, l = arr.length; i < l; i++) { if (arr[i] === element) { @@ -1137,7 +1112,7 @@ class Scheduler { } private _removeUpdateFromHash (entry) { - const targetId = entry.target._id; + const targetId = entry.target.uuid || entry.target.id; const self = this; const element = self._hashForUpdates[targetId]; if (element) { @@ -1174,4 +1149,3 @@ class Scheduler { } cc.Scheduler = Scheduler; -export default Scheduler; diff --git a/cocos/core/utils/coordinates-converts-utils.ts b/cocos/core/utils/coordinates-converts-utils.ts index 67948e62da..4d017e7144 100644 --- a/cocos/core/utils/coordinates-converts-utils.ts +++ b/cocos/core/utils/coordinates-converts-utils.ts @@ -2,10 +2,11 @@ * @category pipeline */ -import { UITransformComponent } from '../../3d/ui'; -import { CameraComponent } from '../../3d/framework'; +import { UITransformComponent } from '../components/ui-base/ui-transfrom-component'; +import { CameraComponent } from '../3d/framework'; import { Vec3 } from '../math'; -import { Node } from '../../scene-graph'; +import { Node } from '../scene-graph'; +import { view } from '../platform'; const _temp_vec3_1 = new Vec3(); @@ -25,8 +26,8 @@ export function WorldNode3DToLocalNodeUI (mainCamera: CameraComponent, wpos: Vec } mainCamera.worldToScreen(wpos, _temp_vec3_1); - _temp_vec3_1.x = _temp_vec3_1.x / cc.view.getScaleX(); - _temp_vec3_1.y = _temp_vec3_1.y / cc.view.getScaleY(); + _temp_vec3_1.x = _temp_vec3_1.x / view.getScaleX(); + _temp_vec3_1.y = _temp_vec3_1.y / view.getScaleY(); const cmp = uiNode.getComponent('cc.UITransformComponent') as UITransformComponent; if (!cmp){ @@ -55,8 +56,8 @@ export function WorldNode3DToWorldNodeUI (mainCamera: CameraComponent, wpos: Vec } mainCamera.worldToScreen(wpos, out); - out.x = out.x / cc.view.getScaleX(); - out.y = out.y / cc.view.getScaleY(); + out.x = out.x / view.getScaleX(); + out.y = out.y / view.getScaleY(); return out; } diff --git a/cocos/deprecated.ts b/cocos/core/utils/deprecated.ts similarity index 99% rename from cocos/deprecated.ts rename to cocos/core/utils/deprecated.ts index 3d2f38b588..7c97b4efcd 100644 --- a/cocos/deprecated.ts +++ b/cocos/core/utils/deprecated.ts @@ -2,7 +2,7 @@ * @hidden */ -import { error, warn } from './core/platform/CCDebug'; +import { error, warn } from '../platform/debug'; let defaultLogTimes = 10; diff --git a/cocos/core/utils/index.ts b/cocos/core/utils/index.ts index 0c263c4f04..14ee250d5e 100644 --- a/cocos/core/utils/index.ts +++ b/cocos/core/utils/index.ts @@ -35,7 +35,7 @@ import * as misc from './misc'; * 用于处理文件与目录的路径的模块 */ import * as path from './path'; -import { replaceProperty } from '../../deprecated'; +import { replaceProperty } from './deprecated'; import * as math from '../math'; // replaceProperty(misc,'misc',[ @@ -71,9 +71,9 @@ import * as math from '../math'; // }, // ]); +export * from './deprecated'; export * from './text-utils'; export * from './html-text-parser'; - export * from './prefab-helper'; export { js, diff --git a/cocos/core/utils/interfaces.ts b/cocos/core/utils/interfaces.ts index 5481b0fd67..cf65787685 100644 --- a/cocos/core/utils/interfaces.ts +++ b/cocos/core/utils/interfaces.ts @@ -25,11 +25,11 @@ import { SystemEventType } from '../platform/event-manager/event-enum'; import { Mat4, Quat, Size, Vec2, Vec3 } from '../math'; -import { Scene } from '../../scene-graph/scene'; -import { NodeEventProcessor } from '../../scene-graph/node-event-processor'; -import { Component } from '../../components/component'; +import { Scene } from '../scene-graph/scene'; +import { NodeEventProcessor } from '../scene-graph/node-event-processor'; +import { Component } from '../components/component'; import { Event } from '../event'; -import { TransformDirtyBit, NodeSpace } from '../../scene-graph/node-enum'; +import { TransformDirtyBit, NodeSpace } from '../scene-graph/node-enum'; export interface IBaseNode { @@ -172,7 +172,7 @@ export interface IBaseNode { * node.isChildOf(newNode); * ``` */ - isChildOf (parent: this): boolean; + isChildOf (parent: this | null): boolean; /** * @zh 增加一个孩子节点 @@ -519,8 +519,6 @@ export interface INode extends IBaseNode { _uiComp; - isValid: boolean; - uiTransfromComp; /** diff --git a/cocos/core/utils/js-typed.ts b/cocos/core/utils/js-typed.ts index 1bfd3e2e58..5523f16fc8 100644 --- a/cocos/core/utils/js-typed.ts +++ b/cocos/core/utils/js-typed.ts @@ -1,4 +1,4 @@ -import { warnID } from '../platform/CCDebug'; +import { warnID } from '../platform/debug'; import IDGenerator from './id-generator'; const tempCIDGenerator = new IDGenerator('TmpCId.'); diff --git a/cocos/core/utils/profiler/profiler.ts b/cocos/core/utils/profiler/profiler.ts index 1cc9bcc1c5..2614fa4853 100644 --- a/cocos/core/utils/profiler/profiler.ts +++ b/cocos/core/utils/profiler/profiler.ts @@ -24,18 +24,20 @@ THE SOFTWARE. */ -import { CameraComponent, Material, ModelComponent } from '../../../3d'; -import { createMesh } from '../../../3d/misc/utils'; -import { GFXBufferTextureCopy, GFXClearFlag, GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../../gfx/define'; -import { GFXDevice } from '../../../gfx/device'; -import { GFXTexture } from '../../../gfx/texture'; -import { GFXTextureView } from '../../../gfx/texture-view'; -import { CameraVisFlags } from '../../../renderer/scene/camera'; -import { VisibilityFlags } from '../../../renderer/scene/model'; -import { Node } from '../../../scene-graph/node'; +import { CameraComponent, ModelComponent } from '../../3d'; +import { Material } from '../../assets/material' +import { createMesh } from '../../3d/misc/utils'; +import { GFXTextureType, GFXTextureUsageBit, GFXFormat, GFXTextureViewType, GFXBufferTextureCopy, GFXClearFlag } from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; +import { GFXTexture } from '../../gfx/texture'; +import { GFXTextureView } from '../../gfx/texture-view'; +import { CameraVisFlags } from '../../renderer/scene/camera'; +import { VisibilityFlags } from '../../renderer/scene/model'; +import { Node } from '../../scene-graph/node'; import { Vec4 } from '../../math'; import { ICounterOption } from './counter'; import { PerfCounter } from './perf-counter'; +import { director, Director } from '../../director'; interface IProfilerState { frame: ICounterOption; @@ -69,7 +71,7 @@ export class Profiler { private _texture: GFXTexture | null = null; private _textureView: GFXTextureView | null = null; private readonly _region: GFXBufferTextureCopy = new GFXBufferTextureCopy(); - private readonly _canvasArr = [this._canvas]; + private readonly _canvasArr: HTMLCanvasElement[] = []; private readonly _regionArr = [this._region]; private _canvasDone = false; @@ -80,6 +82,7 @@ export class Profiler { this._canvas = document.createElement('canvas'); this._ctx = this._canvas.getContext('2d')!; this._region = new GFXBufferTextureCopy(); + this._canvasArr.push(this._canvas); } } @@ -93,12 +96,12 @@ export class Profiler { this._rootNode.active = false; } - cc.director.off(cc.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); - cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); - cc.director.off(cc.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); - cc.director.off(cc.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); - cc.director.off(cc.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); - cc.director.off(cc.Director.EVENT_AFTER_DRAW, this.afterDraw, this); + director.off(Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); + director.off(Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); + director.off(Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); + director.off(Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); + director.off(Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); + director.off(Director.EVENT_AFTER_DRAW, this.afterDraw, this); this._showFPS = false; } } @@ -113,12 +116,12 @@ export class Profiler { this._rootNode.active = true; } - cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); - cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); - cc.director.on(cc.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); - cc.director.on(cc.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); - cc.director.on(cc.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); - cc.director.on(cc.Director.EVENT_AFTER_DRAW, this.afterDraw, this); + director.on(Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); + director.on(Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); + director.on(Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); + director.on(Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); + director.on(Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); + director.on(Director.EVENT_AFTER_DRAW, this.afterDraw, this); this._showFPS = true; this._canvasDone = true; @@ -130,7 +133,7 @@ export class Profiler { if (this._device) { return; } - this._device = cc.director.root!.device; + this._device = director.root!.device; } public generateCanvas () { @@ -180,7 +183,7 @@ export class Profiler { } this._stats = null; - const now = cc.director.getCurrentTime(); + const now = director.getCurrentTime(); const opts = { frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: 500 }, @@ -275,7 +278,7 @@ export class Profiler { this.generateNode(); - const now = cc.director._lastUpdate; + const now = director.getCurrentTime(); this.getCounter('frame').end(now); this.getCounter('frame').start(now); this.getCounter('logic').start(now); @@ -286,8 +289,8 @@ export class Profiler { return; } - const now = cc.director.getCurrentTime(); - if (cc.director.isPaused()) { + const now = director.getCurrentTime(); + if (director.isPaused()) { this.getCounter('frame').start(now); } else { this.getCounter('logic').end(now); @@ -299,7 +302,7 @@ export class Profiler { return; } - const now = cc.director.getCurrentTime(); + const now = director.getCurrentTime(); this.getCounter('physics').start(now); } @@ -308,7 +311,7 @@ export class Profiler { return; } - const now = cc.director.getCurrentTime(); + const now = director.getCurrentTime(); this.getCounter('physics').end(now); } @@ -317,7 +320,7 @@ export class Profiler { return; } - const now = cc.director.getCurrentTime(); + const now = director.getCurrentTime(); this.getCounter('render').start(now); } @@ -325,7 +328,7 @@ export class Profiler { if (!this._stats || !this._ctx || !this._canvas) { return; } - const now = cc.director.getCurrentTime(); + const now = director.getCurrentTime(); this.getCounter('fps').frame(now); this.getCounter('draws').value = this._device!.numDrawCalls; @@ -358,9 +361,8 @@ export class Profiler { } public updateTexture () { - cc.director.root!.device.copyTexImagesToTexture(this._canvasArr, this._texture!, this._regionArr); + director.root!.device.copyTexImagesToTexture(this._canvasArr, this._texture!, this._regionArr); } - } export const profiler = new Profiler(); diff --git a/cocos/core/value-types/value-type.ts b/cocos/core/value-types/value-type.ts index 7fe457f766..a969e57057 100644 --- a/cocos/core/value-types/value-type.ts +++ b/cocos/core/value-types/value-type.ts @@ -28,7 +28,7 @@ * @category core/value-types */ -import { errorID } from '../platform/CCDebug'; +import { errorID } from '../platform/debug'; import * as js from '../utils/js'; /** diff --git a/cocos/vmath.ts b/cocos/core/vmath.ts similarity index 96% rename from cocos/vmath.ts rename to cocos/core/vmath.ts index 001edda547..e16d747876 100644 --- a/cocos/vmath.ts +++ b/cocos/core/vmath.ts @@ -2,8 +2,8 @@ * @hidden */ -import { replaceProperty } from './deprecated'; -import { math } from './core'; +import { replaceProperty } from './utils/deprecated'; +import { math } from './'; const vmath = {}; replaceProperty(vmath,'vmath',[ diff --git a/cocos/3d/framework/particle/animator/color-overtime.ts b/cocos/particle/animator/color-overtime.ts similarity index 85% rename from cocos/3d/framework/particle/animator/color-overtime.ts rename to cocos/particle/animator/color-overtime.ts index 58f31102b4..e33facdb7b 100644 --- a/cocos/3d/framework/particle/animator/color-overtime.ts +++ b/cocos/particle/animator/color-overtime.ts @@ -3,9 +3,8 @@ * @category particle */ -import { CCClass } from '../../../../core/data'; -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { pseudoRandom } from '../../../../core/math'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { pseudoRandom } from '../../core/math'; import Particle from '../particle'; import GradientRange from './gradient-range'; diff --git a/cocos/3d/framework/particle/animator/curve-range.ts b/cocos/particle/animator/curve-range.ts similarity index 90% rename from cocos/3d/framework/particle/animator/curve-range.ts rename to cocos/particle/animator/curve-range.ts index ba2a5c31be..f28413bd3b 100644 --- a/cocos/3d/framework/particle/animator/curve-range.ts +++ b/cocos/particle/animator/curve-range.ts @@ -2,11 +2,10 @@ * @hidden */ -import { CCClass } from '../../../../core/data'; -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { lerp } from '../../../../core/math'; -import { Enum } from '../../../../core/value-types'; -import { AnimationCurve } from '../../../geom-utils'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { lerp } from '../../core/math'; +import { Enum } from '../../core/value-types'; +import { AnimationCurve } from '../../core/geom-utils'; export const Mode = Enum({ Constant: 0, diff --git a/cocos/3d/framework/particle/animator/force-overtime.ts b/cocos/particle/animator/force-overtime.ts similarity index 91% rename from cocos/3d/framework/particle/animator/force-overtime.ts rename to cocos/particle/animator/force-overtime.ts index 1be6e205b8..64488cf196 100644 --- a/cocos/3d/framework/particle/animator/force-overtime.ts +++ b/cocos/particle/animator/force-overtime.ts @@ -3,9 +3,8 @@ * @category particle */ -import { CCClass } from '../../../../core/data'; -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { pseudoRandom, Quat, Vec3 } from '../../../../core/math'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { pseudoRandom, Quat, Vec3 } from '../../core/math'; import { Space } from '../enum'; import { calculateTransform } from '../particle-general-function'; import CurveRange from './curve-range'; @@ -13,7 +12,7 @@ import CurveRange from './curve-range'; // tslint:disable: max-line-length const FORCE_OVERTIME_RAND_OFFSET = 212165; -const _temp_v3 = cc.v3(); +const _temp_v3 = new Vec3(); @ccclass('cc.ForceOvertimeModule') export default class ForceOvertimeModule { diff --git a/cocos/3d/framework/particle/animator/gradient-range.ts b/cocos/particle/animator/gradient-range.ts similarity index 87% rename from cocos/3d/framework/particle/animator/gradient-range.ts rename to cocos/particle/animator/gradient-range.ts index 799af55b01..562f7ccf59 100644 --- a/cocos/3d/framework/particle/animator/gradient-range.ts +++ b/cocos/particle/animator/gradient-range.ts @@ -3,10 +3,9 @@ * @hidden */ -import { CCClass } from '../../../../core/data'; -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { Color } from '../../../../core/math'; -import { Enum } from '../../../../core/value-types'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { Color } from '../../core/math'; +import { Enum } from '../../core/value-types'; import Gradient, { AlphaKey, ColorKey } from './gradient'; // tslint:disable: max-line-length @@ -61,19 +60,19 @@ export default class GradientRange { * @zh 当mode为Color时的颜色。 */ @property - public color = cc.Color.WHITE.clone(); + public color = Color.WHITE.clone(); /** * @zh 当mode为TwoColors时的颜色下限。 */ @property - public colorMin = cc.Color.WHITE.clone(); + public colorMin = Color.WHITE.clone(); /** * @zh 当mode为TwoColors时的颜色上限。 */ @property - public colorMax = cc.Color.WHITE.clone(); + public colorMax = Color.WHITE.clone(); /** * @zh 当mode为Gradient时的颜色渐变。 @@ -104,7 +103,7 @@ export default class GradientRange { }) private _mode = Mode.Color; - private _color = cc.Color.WHITE.clone(); + private _color = Color.WHITE.clone(); public evaluate (time: number, rndRatio: number) { switch (this.mode) { @@ -120,6 +119,8 @@ export default class GradientRange { case Mode.TwoGradients: Color.lerp(this._color, this.gradientMin.evaluate(time), this.gradientMax.evaluate(time), rndRatio); return this._color; + default: + return this.color; } } } diff --git a/cocos/3d/framework/particle/animator/gradient.ts b/cocos/particle/animator/gradient.ts similarity index 93% rename from cocos/3d/framework/particle/animator/gradient.ts rename to cocos/particle/animator/gradient.ts index 29e92c7d65..c774b4ebb5 100644 --- a/cocos/3d/framework/particle/animator/gradient.ts +++ b/cocos/particle/animator/gradient.ts @@ -2,10 +2,9 @@ * @hidden */ -import { CCClass } from '../../../../core/data'; -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { Color, lerp, repeat } from '../../../../core/math'; -import { Enum } from '../../../../core/value-types'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { Color, lerp, repeat } from '../../core/math'; +import { Enum } from '../../core/value-types'; // tslint:disable: max-line-length @@ -18,7 +17,7 @@ const Mode = Enum({ export class ColorKey { @property - public color = cc.Color.WHITE.clone(); + public color = Color.WHITE.clone(); @property public time = 0; @@ -61,7 +60,7 @@ export default class Gradient { private _color: Color; constructor () { - this._color = cc.Color.WHITE.clone(); + this._color = Color.WHITE.clone(); } public setKeys (colorKeys: ColorKey[], alphaKeys: AlphaKey[]) { diff --git a/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts b/cocos/particle/animator/limit-velocity-overtime.ts similarity index 94% rename from cocos/3d/framework/particle/animator/limit-velocity-overtime.ts rename to cocos/particle/animator/limit-velocity-overtime.ts index ad32e04eed..51a0e61e2a 100644 --- a/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts +++ b/cocos/particle/animator/limit-velocity-overtime.ts @@ -3,9 +3,8 @@ * @category particle */ -import { CCClass } from '../../../../core/data'; -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { lerp, pseudoRandom, Vec3 } from '../../../../core/math'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { lerp, pseudoRandom, Vec3 } from '../../core/math'; import { Space } from '../enum'; import Particle from '../particle'; import CurveRange from './curve-range'; @@ -13,7 +12,7 @@ import CurveRange from './curve-range'; // tslint:disable: max-line-length const LIMIT_VELOCITY_RAND_OFFSET = 23541; -const _temp_v3 = cc.v3(); +const _temp_v3 = new Vec3(); @ccclass('cc.LimitVelocityOvertimeModule') export default class LimitVelocityOvertimeModule { diff --git a/cocos/3d/framework/particle/animator/optimized-curve.ts b/cocos/particle/animator/optimized-curve.ts similarity index 98% rename from cocos/3d/framework/particle/animator/optimized-curve.ts rename to cocos/particle/animator/optimized-curve.ts index 2748c6f51b..534d6019a1 100644 --- a/cocos/3d/framework/particle/animator/optimized-curve.ts +++ b/cocos/particle/animator/optimized-curve.ts @@ -3,9 +3,8 @@ * @hidden */ -import { repeat } from '../../../../core/math'; -import { AnimationCurve, evalOptCurve, OptimizedKey } from '../../../geom-utils/curve'; -import CurveRange, { Mode } from './curve-range'; +import { repeat } from '../../core/math'; +import { AnimationCurve, evalOptCurve, OptimizedKey } from '../../core/geom-utils/curve'; // tslint:disable: max-line-length diff --git a/cocos/3d/framework/particle/animator/rotation-overtime.ts b/cocos/particle/animator/rotation-overtime.ts similarity index 92% rename from cocos/3d/framework/particle/animator/rotation-overtime.ts rename to cocos/particle/animator/rotation-overtime.ts index 5cb608fb7d..fb02823cb1 100644 --- a/cocos/3d/framework/particle/animator/rotation-overtime.ts +++ b/cocos/particle/animator/rotation-overtime.ts @@ -3,9 +3,8 @@ * @category particle */ -import { CCClass } from '../../../../core/data'; -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { pseudoRandom } from '../../../../core/math'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { pseudoRandom } from '../../core/math'; import Particle from '../particle'; import CurveRange from './curve-range'; diff --git a/cocos/3d/framework/particle/animator/size-overtime.ts b/cocos/particle/animator/size-overtime.ts similarity index 93% rename from cocos/3d/framework/particle/animator/size-overtime.ts rename to cocos/particle/animator/size-overtime.ts index 637d27e0ac..226f8fe31b 100644 --- a/cocos/3d/framework/particle/animator/size-overtime.ts +++ b/cocos/particle/animator/size-overtime.ts @@ -3,9 +3,8 @@ * @category particle */ -import { CCClass } from '../../../../core/data'; -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { pseudoRandom, Vec3 } from '../../../../core/math'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { pseudoRandom, Vec3 } from '../../core/math'; import Particle from '../particle'; import CurveRange from './curve-range'; diff --git a/cocos/3d/framework/particle/animator/texture-animation.ts b/cocos/particle/animator/texture-animation.ts similarity index 96% rename from cocos/3d/framework/particle/animator/texture-animation.ts rename to cocos/particle/animator/texture-animation.ts index f9c7895a68..7241473335 100644 --- a/cocos/3d/framework/particle/animator/texture-animation.ts +++ b/cocos/particle/animator/texture-animation.ts @@ -3,9 +3,9 @@ * @category particle */ -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { lerp, pseudoRandom, repeat } from '../../../../core/math'; -import { Enum } from '../../../../core/value-types'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { lerp, pseudoRandom, repeat } from '../../core/math'; +import { Enum } from '../../core/value-types'; import Particle from '../particle'; import { ParticleSystemComponent } from '../particle-system-component'; import CurveRange from './curve-range'; diff --git a/cocos/3d/framework/particle/animator/velocity-overtime.ts b/cocos/particle/animator/velocity-overtime.ts similarity index 94% rename from cocos/3d/framework/particle/animator/velocity-overtime.ts rename to cocos/particle/animator/velocity-overtime.ts index d2af902a94..5d9bc81b31 100644 --- a/cocos/3d/framework/particle/animator/velocity-overtime.ts +++ b/cocos/particle/animator/velocity-overtime.ts @@ -3,8 +3,8 @@ * @category particle */ -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { Mat4, pseudoRandom, Quat, Vec3 } from '../../../../core/math'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { Mat4, pseudoRandom, Quat, Vec3 } from '../../core/math'; import { Space } from '../enum'; import Particle from '../particle'; import { calculateTransform } from '../particle-general-function'; @@ -13,7 +13,7 @@ import CurveRange from './curve-range'; // tslint:disable: max-line-length const VELOCITY_OVERTIME_RAND_OFFSET = 197866; -const _temp_v3 = cc.v3(); +const _temp_v3 = new Vec3(); @ccclass('cc.VelocityOvertimeModule') export default class VelocityOvertimeModule { diff --git a/cocos/3d/framework/particle/billboard-component.ts b/cocos/particle/billboard-component.ts similarity index 88% rename from cocos/3d/framework/particle/billboard-component.ts rename to cocos/particle/billboard-component.ts index 43b9531032..b5b13247af 100644 --- a/cocos/3d/framework/particle/billboard-component.ts +++ b/cocos/particle/billboard-component.ts @@ -3,15 +3,16 @@ * @category particle */ -import { ccclass, property, executeInEditMode, menu } from "../../../core/data/class-decorator"; -import { Material, Mesh } from "../../assets"; -import { Texture2D } from "../../../assets"; -import { createMesh } from "../../misc/utils"; -import { GFXPrimitiveMode, GFXAttributeName, GFXFormat } from "../../../gfx"; -import { Model } from "../../../renderer/scene/model"; -import { builtinResMgr } from "../../builtin"; -import { Component } from "../../../components"; -import { Color, toRadian, toDegree } from "../../../core/math"; +import { ccclass, property, executeInEditMode, menu } from "../core/data/class-decorator"; +import { Material, Mesh, Texture2D } from "../core/assets"; +import { createMesh } from "../core/3d/misc/utils"; +import { GFXPrimitiveMode, GFXAttributeName, GFXFormat } from "../core/gfx"; +import { Model } from "../core/renderer/scene/model"; +import { builtinResMgr } from "../core/3d/builtin"; +import { Component } from "../core/components/component"; +import { Color, toRadian, toDegree, Vec4 } from "../core/math"; + +createMesh @ccclass('cc.BillboardComponent') @menu('Components/BillboardComponent') @@ -103,7 +104,7 @@ export class BillboardComponent extends Component { private _material: Material | null = null; - private _uniform = cc.v4(1, 1, 0, 0); + private _uniform = new Vec4(1, 1, 0, 0); constructor () { super(); diff --git a/cocos/3d/framework/particle/burst.ts b/cocos/particle/burst.ts similarity index 93% rename from cocos/3d/framework/particle/burst.ts rename to cocos/particle/burst.ts index 0c105d8ad6..d8b4ff64f4 100644 --- a/cocos/3d/framework/particle/burst.ts +++ b/cocos/particle/burst.ts @@ -2,9 +2,8 @@ * @hidden */ -import { CCClass } from '../../../core/data'; -import { ccclass, property } from '../../../core/data/class-decorator'; -import { repeat } from '../../../core/math'; +import { ccclass, property } from '../core/data/class-decorator'; +import { repeat } from '../core/math'; import CurveRange from './animator/curve-range'; @ccclass('cc.Burst') diff --git a/cocos/3d/framework/particle/emitter/shape-module.ts b/cocos/particle/emitter/shape-module.ts similarity index 98% rename from cocos/3d/framework/particle/emitter/shape-module.ts rename to cocos/particle/emitter/shape-module.ts index f1036854fd..6c4647a02e 100644 --- a/cocos/3d/framework/particle/emitter/shape-module.ts +++ b/cocos/particle/emitter/shape-module.ts @@ -3,9 +3,9 @@ * @category particle */ -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { Mat4, Quat, Vec2, Vec3 } from '../../../../core/math'; -import { clamp, pingPong, random, randomRange, repeat, toDegree, toRadian } from '../../../../core/math'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { Mat4, Quat, Vec2, Vec3 } from '../../core/math'; +import { clamp, pingPong, random, randomRange, repeat, toDegree, toRadian } from '../../core/math'; import CurveRange from '../animator/curve-range'; import { ArcMode, EmitLocation, ShapeType } from '../enum'; import { fixedAngleUnitVector2, particleEmitZAxis, randomPointBetweenCircleAtFixedAngle, randomPointBetweenSphere, diff --git a/cocos/3d/framework/particle/enum.ts b/cocos/particle/enum.ts similarity index 98% rename from cocos/3d/framework/particle/enum.ts rename to cocos/particle/enum.ts index 5bfa655e54..c5add5ee53 100644 --- a/cocos/3d/framework/particle/enum.ts +++ b/cocos/particle/enum.ts @@ -3,7 +3,7 @@ * @category particle */ -import { Enum } from '../../../core/value-types'; +import { Enum } from '../core/value-types'; export const Space = Enum({ World: 0, diff --git a/cocos/particle/index.ts b/cocos/particle/index.ts new file mode 100644 index 0000000000..b2f50f9cd7 --- /dev/null +++ b/cocos/particle/index.ts @@ -0,0 +1,17 @@ +import { BillboardComponent } from './billboard-component'; +import { LineComponent } from './line-component'; +import { ParticleSystemComponent } from './particle-system-component'; +import { ParticleUtils } from './particle-utils'; + +export { + BillboardComponent, + LineComponent, + ParticleSystemComponent, + ParticleUtils +}; + +cc.ParticleSystemComponent = ParticleSystemComponent; +cc.BillboardComponent = BillboardComponent; +cc.LineComponent = LineComponent; + +cc.ParticleUtils = ParticleUtils; \ No newline at end of file diff --git a/cocos/3d/framework/particle/line-component.ts b/cocos/particle/line-component.ts similarity index 90% rename from cocos/3d/framework/particle/line-component.ts rename to cocos/particle/line-component.ts index 02122ac7cd..3023face82 100644 --- a/cocos/3d/framework/particle/line-component.ts +++ b/cocos/particle/line-component.ts @@ -5,13 +5,12 @@ */ -import { Texture2D } from '../../../assets'; -import { Component } from '../../../components'; -import { ccclass, executeInEditMode, menu, property } from '../../../core/data/class-decorator'; -import { Vec3, Vec2, Vec4 } from '../../../core/math'; -import { LineModel } from '../../../renderer/models/line-model'; -import { Material } from '../../assets'; -import { builtinResMgr } from '../../builtin'; +import { Material, Texture2D } from '../core/assets'; +import { Component } from '../core/components'; +import { ccclass, executeInEditMode, menu, property } from '../core/data/class-decorator'; +import { Vec3, Vec2, Vec4 } from '../core/math'; +import { LineModel } from './models/line-model'; +import { builtinResMgr } from '../core/3d/builtin'; import CurveRange from './animator/curve-range'; import GradientRange from './animator/gradient-range'; @@ -118,7 +117,7 @@ export class LineComponent extends Component { } @property - private _tile = cc.v2(1, 1); + private _tile = new Vec2(1, 1); /** * @zh 图块数。 @@ -141,7 +140,7 @@ export class LineComponent extends Component { } @property - private _offset = cc.v2(0, 0); + private _offset = new Vec2(0, 0); @property({ type: Vec2, @@ -187,7 +186,7 @@ export class LineComponent extends Component { * @ignore */ private _model: LineModel | null = null; - private _tile_offset: Vec4 = cc.v4(); + private _tile_offset: Vec4 = new Vec4(); constructor () { super(); diff --git a/cocos/renderer/models/line-model.ts b/cocos/particle/models/line-model.ts similarity index 95% rename from cocos/renderer/models/line-model.ts rename to cocos/particle/models/line-model.ts index 0349062f3a..e4acee8ff4 100644 --- a/cocos/renderer/models/line-model.ts +++ b/cocos/particle/models/line-model.ts @@ -2,14 +2,14 @@ * @hidden */ -import { IRenderingSubmesh } from '../../3d/assets/mesh'; -import CurveRange from '../../3d/framework/particle/animator/curve-range'; +import { IRenderingSubmesh } from '../../core/assets/mesh'; +import CurveRange from '../animator/curve-range'; import { Vec3 } from '../../core/math'; -import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; -import { Model } from '../scene/model'; -import { RenderScene } from '../scene/render-scene'; -import GradientRange from '../../3d/framework/particle/animator/gradient-range'; -import { GFX_DRAW_INFO_SIZE, IGFXIndirectBuffer, GFXBuffer } from '../../gfx/buffer'; +import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../core/gfx/define'; +import { Model } from '../../core/renderer/scene/model'; +import { RenderScene } from '../../core/renderer/scene/render-scene'; +import GradientRange from '../animator/gradient-range'; +import { GFX_DRAW_INFO_SIZE, IGFXIndirectBuffer, GFXBuffer } from '../../core/gfx/buffer'; import { INode } from '../../core/utils/interfaces'; const _vertex_attrs = [ @@ -19,8 +19,8 @@ const _vertex_attrs = [ { name: GFXAttributeName.ATTR_COLOR, format: GFXFormat.RGBA8, isNormalized: true }, ]; -const _temp_v1 = cc.v3(); -const _temp_v2 = cc.v3(); +const _temp_v1 = new Vec3(); +const _temp_v2 = new Vec3(); export class LineModel extends Model { diff --git a/cocos/renderer/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts similarity index 95% rename from cocos/renderer/models/particle-batch-model.ts rename to cocos/particle/models/particle-batch-model.ts index ec70904770..1cacb04acc 100644 --- a/cocos/renderer/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -27,15 +27,16 @@ * @hidden */ -import { Material } from '../../3d/assets/material'; -import { IRenderingSubmesh, Mesh } from '../../3d/assets/mesh'; -import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../gfx/buffer'; -import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, - GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; -import { IGFXAttribute } from '../../gfx/input-assembler'; -import { Node } from '../../scene-graph'; -import { Model } from '../scene/model'; -import { RenderScene } from '../scene/render-scene'; +import { Material } from '../../core/assets/material'; +import { IRenderingSubmesh, Mesh } from '../../core/assets/mesh'; +import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../core/gfx/buffer'; +import { GFXAttributeName, GFXBufferUsageBit, GFXFormatInfos, + GFXMemoryUsageBit, GFXPrimitiveMode } from '../../core/gfx/define'; +import { IGFXAttribute } from '../../core/gfx/input-assembler'; +import { Node } from '../../core/scene-graph'; +import { Model } from '../../core/renderer/scene/model'; +import { RenderScene } from '../../core/renderer/scene/render-scene'; +import { Color } from '../../core/math/color'; export default class ParticleBatchModel extends Model { @@ -141,7 +142,7 @@ export default class ParticleBatchModel extends Model { if (!this._mesh.copyAttribute(0, GFXAttributeName.ATTR_COLOR, vBuffer, this._vertSize, vOffset)) { // copy mesh color to ATTR_COLOR1 const vb = new Uint32Array(vBuffer); for (let iVertex = 0; iVertex < this._vertCount; ++iVertex) { - vb[iVertex * this._vertAttrsFloatCount + vOffset / 4] = cc.Color.WHITE._val; + vb[iVertex * this._vertAttrsFloatCount + vOffset / 4] = Color.WHITE._val; } } const vbFloatArray = new Float32Array(vBuffer); diff --git a/cocos/3d/framework/particle/particle-general-function.ts b/cocos/particle/particle-general-function.ts similarity index 97% rename from cocos/3d/framework/particle/particle-general-function.ts rename to cocos/particle/particle-general-function.ts index 93a645ed39..4bc5f01694 100644 --- a/cocos/3d/framework/particle/particle-general-function.ts +++ b/cocos/particle/particle-general-function.ts @@ -2,8 +2,8 @@ * @hidden */ -import { Mat4, Quat, random, randomRange, randomRangeInt, Vec2, Vec3 } from '../../../core/math'; -import { sign } from '../../../core/math/bits'; +import { Mat4, Quat, random, randomRange, randomRangeInt, Vec2, Vec3 } from '../core/math'; +import { sign } from '../core/math/bits'; import { Space } from './enum'; export const particleEmitZAxis = new Vec3(0, 0, -1); diff --git a/cocos/3d/framework/particle/particle-system-component.ts b/cocos/particle/particle-system-component.ts similarity index 98% rename from cocos/3d/framework/particle/particle-system-component.ts rename to cocos/particle/particle-system-component.ts index 63908dce61..dc318cc3bb 100644 --- a/cocos/3d/framework/particle/particle-system-component.ts +++ b/cocos/particle/particle-system-component.ts @@ -6,12 +6,12 @@ // tslint:disable: max-line-length -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Mat4, pseudoRandom, Quat, randomRangeInt, Vec2, Vec3 } from '../../../core/math'; -import { INT_MAX } from '../../../core/math/bits'; -import { Model } from '../../../renderer'; -import { Material } from '../../assets'; -import { RenderableComponent } from '../renderable-component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../core/data/class-decorator'; +import { Mat4, pseudoRandom, Quat, randomRangeInt, Vec2, Vec3 } from '../core/math'; +import { INT_MAX } from '../core/math/bits'; +import { Model } from '../core/renderer'; +import { Material } from '../core/assets/material'; +import { RenderableComponent } from '../core/3d/framework/renderable-component'; import ColorOverLifetimeModule from './animator/color-overtime'; import CurveRange, { Mode } from './animator/curve-range'; import ForceOvertimeModule from './animator/force-overtime'; diff --git a/cocos/3d/framework/particle/particle-utils.ts b/cocos/particle/particle-utils.ts similarity index 68% rename from cocos/3d/framework/particle/particle-utils.ts rename to cocos/particle/particle-utils.ts index 91c067c0d1..9d2b711172 100644 --- a/cocos/3d/framework/particle/particle-utils.ts +++ b/cocos/particle/particle-utils.ts @@ -2,10 +2,12 @@ * @hidden */ -import { ParticleSystemComponent } from '..'; -import { CCObject } from '../../../core/data/object'; -import { Node } from '../../../scene-graph'; -import { Pool } from '../../memop'; +import { ParticleSystemComponent } from './particle-system-component'; +import { CCObject } from '../core/data/object'; +import { Node } from '../core/scene-graph'; +import { Pool } from '../core/memop'; +import { Director, director } from '../core/director'; +import { instantiate } from '../core/data'; export class ParticleUtils { private static particleSystemPool: Map> = new Map>(); @@ -16,12 +18,12 @@ export class ParticleUtils { */ public static instantiate (prefab) { if (!this.registeredSceneEvent) { - cc.director.on(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, this.onSceneUnload, this); + director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, this.onSceneUnload, this); this.registeredSceneEvent = true; } if (!this.particleSystemPool.has(prefab._uuid)) { this.particleSystemPool.set(prefab._uuid, new Pool(() => { - return cc.instantiate(prefab); + return instantiate(prefab); }, 1)); } return this.particleSystemPool.get(prefab._uuid)!.alloc(); @@ -44,13 +46,13 @@ export class ParticleUtils { } public static play (rootNode: Node) { - for (const ps of rootNode.getComponentsInChildren(cc.ParticleSystemComponent)) { + for (const ps of rootNode.getComponentsInChildren(ParticleSystemComponent)) { (ps as ParticleSystemComponent).play(); } } public static stop (rootNode: Node) { - for (const ps of rootNode.getComponentsInChildren(cc.ParticleSystemComponent)) { + for (const ps of rootNode.getComponentsInChildren(ParticleSystemComponent)) { (ps as ParticleSystemComponent).stop(); } } diff --git a/cocos/3d/framework/particle/particle.ts b/cocos/particle/particle.ts similarity index 90% rename from cocos/3d/framework/particle/particle.ts rename to cocos/particle/particle.ts index 6f269cc213..b9ef3e628c 100644 --- a/cocos/3d/framework/particle/particle.ts +++ b/cocos/particle/particle.ts @@ -2,7 +2,7 @@ * @hidden */ -import { Color, Vec3 } from '../../../core/math'; +import { Color, Vec3 } from '../core/math'; import { ParticleSystemComponent } from './particle-system-component'; export default class Particle { @@ -36,8 +36,8 @@ export default class Particle { this.rotation = new Vec3(0, 0, 0); this.startSize = new Vec3(0, 0, 0); this.size = new Vec3(0, 0, 0); - this.startColor = cc.Color.WHITE.clone(); - this.color = cc.Color.WHITE.clone(); + this.startColor = Color.WHITE.clone(); + this.color = Color.WHITE.clone(); this.randomSeed = 0; // uint this.remainingLifetime = 0.0; this.startLifetime = 0.0; diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/particle/renderer/particle-system-renderer.ts similarity index 96% rename from cocos/3d/framework/particle/renderer/particle-system-renderer.ts rename to cocos/particle/renderer/particle-system-renderer.ts index 4aae63ec85..e0808816f9 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts +++ b/cocos/particle/renderer/particle-system-renderer.ts @@ -1,16 +1,16 @@ -import { Component } from '../../../../components'; -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { Mat4, Vec2, Vec3, Vec4 } from '../../../../core/math'; -import { GFXAttributeName, GFXFormat } from '../../../../gfx/define'; -import { IGFXAttribute } from '../../../../gfx/input-assembler'; -import { IDefineMap } from '../../../../renderer/core/pass'; -import ParticleBatchModel from '../../../../renderer/models/particle-batch-model'; -import { Mesh } from '../../../assets'; -import { Material } from '../../../assets/material'; -import { builtinResMgr } from '../../../builtin'; -import RecyclePool from '../../../memop/recycle-pool'; +import { Component } from '../../core/components'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { Mat4, Vec2, Vec3, Vec4 } from '../../core/math'; +import { GFXAttributeName, GFXFormat } from '../../core/gfx/define'; +import { IGFXAttribute } from '../../core/gfx/input-assembler'; +import { IDefineMap } from '../../core/renderer/core/pass'; +import ParticleBatchModel from '../models/particle-batch-model'; +import { Mesh, Material } from '../../core/assets'; +import { builtinResMgr } from '../../core/3d/builtin'; +import RecyclePool from '../../core/memop/recycle-pool'; import { RenderMode, Space } from '../enum'; import Particle from '../particle'; +import { ParticleSystemComponent } from '../particle-system-component'; const _tempAttribUV = new Vec3(); const _tempAttribUV0 = new Vec2(); @@ -136,7 +136,7 @@ export default class ParticleSystemRenderer { private _mesh: Mesh | null = null; @property({ - type: cc.ParticleSystemComponent, + type: ParticleSystemComponent, visible: false, }) private _particleSystem: any = null; diff --git a/cocos/3d/framework/particle/renderer/trail.ts b/cocos/particle/renderer/trail.ts similarity index 95% rename from cocos/3d/framework/particle/renderer/trail.ts rename to cocos/particle/renderer/trail.ts index 5c0ce8b536..88d45b3414 100644 --- a/cocos/3d/framework/particle/renderer/trail.ts +++ b/cocos/particle/renderer/trail.ts @@ -3,31 +3,33 @@ * @category particle */ -import { Color, Vec3 } from '../../../../core/math'; -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../../../gfx/buffer'; -import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../../../gfx/define'; -import { GFXDevice } from '../../../../gfx/device'; -import { IGFXAttribute } from '../../../../gfx/input-assembler'; -import { Model } from '../../../../renderer'; -import { Material } from '../../../assets'; -import { IRenderingSubmesh } from '../../../assets/mesh'; -import { Pool } from '../../../memop'; +import { Color, Vec3, Mat4, Quat } from '../../core/math'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../core/gfx/buffer'; +import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../core/gfx/define'; +import { GFXDevice } from '../../core/gfx/device'; +import { IGFXAttribute } from '../../core/gfx/input-assembler'; +import { Model } from '../../core/renderer'; +import { Material } from '../../core/assets/material'; +import { IRenderingSubmesh } from '../../core/assets/mesh'; +import { Pool } from '../../core/memop'; +import { director } from '../../core/director'; import CurveRange from '../animator/curve-range'; import GradientRange from '../animator/gradient-range'; import { Space, TextureMode, TrailMode } from '../enum'; import Particle from '../particle'; +import { ParticleSystemComponent } from '../particle-system-component'; // tslint:disable: max-line-length const PRE_TRIANGLE_INDEX = 1; const NEXT_TRIANGLE_INDEX = 1 << 2; -const _temp_trailEle = { position: cc.v3(), velocity: cc.v3() } as ITrailElement; -const _temp_quat = cc.quat(); -const _temp_xform = cc.mat4(); -const _temp_vec3 = cc.v3(); -const _temp_vec3_1 = cc.v3(); -const _temp_color = cc.color(); +const _temp_trailEle = { position: new Vec3(), velocity: new Vec3() } as ITrailElement; +const _temp_quat = new Quat(); +const _temp_xform = new Mat4(); +const _temp_vec3 = new Vec3(); +const _temp_vec3_1 = new Vec3(); +const _temp_color = new Color(); const barycentric = [1,0,0, 0,1,0, 0,0,1]; // let _bcIdx = 0; @@ -52,11 +54,11 @@ class TrailSegment { this.trailElements = []; while (maxTrailElementNum--) { this.trailElements.push({ - position: cc.v3(), + position: new Vec3(), lifetime: 0, width: 0, - velocity: cc.v3(), - color: cc.color(), + velocity: new Vec3(), + color: new Color(), }); } } @@ -268,7 +270,7 @@ export default class TrailModule { private _space = Space.World; @property({ - type: cc.ParticleSystemComponent, + type: ParticleSystemComponent, visible: false, }) private _particleSystem: any = null; @@ -527,7 +529,7 @@ export default class TrailModule { if (this._trailModel) { return; } - const device: GFXDevice = cc.director.root.device; + const device: GFXDevice = director.root!.device; const vertexBuffer = device.createBuffer({ usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, diff --git a/cocos/3d/physics/ammo-impl.ts b/cocos/physics/ammo-impl.ts similarity index 99% rename from cocos/3d/physics/ammo-impl.ts rename to cocos/physics/ammo-impl.ts index 95e2b0738a..e56cbe21d8 100644 --- a/cocos/3d/physics/ammo-impl.ts +++ b/cocos/physics/ammo-impl.ts @@ -3,8 +3,8 @@ */ import Ammo from 'ammo.js'; -import { Quat, Vec3 } from '../../core/math'; -import { Node } from '../../scene-graph'; +import { Quat, Vec3 } from '../core/math'; +import { Node } from '../core/scene-graph/node'; import { Debugger } from './ammo/debugger'; import { AfterStepCallback, BeforeStepCallback, BoxShapeBase, @@ -16,6 +16,7 @@ import { AfterStepCallback, BeforeStepCallback, IRaycastOptions, LockConstraintBase, PhysicsWorldBase, PointToPointConstraintBase, RigidBodyBase, ShapeBase, SphereShapeBase } from './api'; import { RaycastResult } from './raycast-result'; +import { director } from '../core/director'; export class CollisionEvent { get target () { @@ -189,7 +190,7 @@ export class AmmoWorld implements PhysicsWorldBase { this._callCustomAfterSteps(); if (!this._debugger.avaiable) { - const scene = cc.director.getScene(); + const scene = director.getScene(); if (scene) { const node = new Node('bullet-debugger'); scene.addChild(node); diff --git a/cocos/3d/physics/ammo/debugger.ts b/cocos/physics/ammo/debugger.ts similarity index 91% rename from cocos/3d/physics/ammo/debugger.ts rename to cocos/physics/ammo/debugger.ts index 203ea0c9b8..9088941c69 100644 --- a/cocos/3d/physics/ammo/debugger.ts +++ b/cocos/physics/ammo/debugger.ts @@ -1,13 +1,13 @@ import Ammo from 'ammo.js'; -import { Color, Vec3 } from '../../../core/math'; -import { GFXComparisonFunc, GFXPrimitiveMode } from '../../../gfx/define'; -import { Node } from '../../../scene-graph'; -import { Material } from '../../assets/material'; -import { Mesh } from '../../assets/mesh'; -import { ModelComponent } from '../../framework'; -import { createMesh } from '../../misc/utils'; -import { IGeometry } from '../../primitive/define'; +import { Color, Vec3 } from '../../core/math'; +import { GFXPrimitiveMode } from '../../core/gfx/define'; +import { Node } from '../../core/scene-graph'; +import { Material } from '../../core/assets/material'; +import { Mesh } from '../../core/assets/mesh'; +import { ModelComponent } from '../../core/3d/framework/model-component'; +import { createMesh } from '../../core/3d/misc/utils'; +import { IGeometry } from '../../core/primitive/define'; interface IDebugVertex { position: Vec3; @@ -62,7 +62,7 @@ export class Debugger implements Ammo.btIDebugDraw { USE_COLOR: true, }, states: { - primitive: cc.GFXPrimitiveMode.LINE_LIST, + primitive: GFXPrimitiveMode.LINE_LIST, // depthStencilState: { // depthFunc: GFXComparisonFunc.LESS_EQUAL, // }, diff --git a/cocos/3d/physics/api.ts b/cocos/physics/api.ts similarity index 99% rename from cocos/3d/physics/api.ts rename to cocos/physics/api.ts index 470146b293..c3d684d77c 100644 --- a/cocos/3d/physics/api.ts +++ b/cocos/physics/api.ts @@ -2,7 +2,7 @@ * @hidden */ -import { Mat4, Quat, Vec3 } from '../../core/math'; +import { Mat4, Quat, Vec3 } from '../core/math'; import { ERigidBodyType } from './physic-enum'; import { RaycastResult } from './raycast-result'; diff --git a/cocos/3d/assets/physics/material.ts b/cocos/physics/assets/material.ts similarity index 90% rename from cocos/3d/assets/physics/material.ts rename to cocos/physics/assets/material.ts index c3b986410b..82b7b00a00 100644 --- a/cocos/3d/assets/physics/material.ts +++ b/cocos/physics/assets/material.ts @@ -5,8 +5,8 @@ * @category physics */ -import { Asset } from '../../../assets/asset'; -import { ccclass, property } from '../../../core/data/class-decorator'; +import { Asset } from '../../core/assets/asset'; +import { ccclass, property } from '../../core/data/class-decorator'; @ccclass('cc.PhysicsMaterial') export class PhysicsMaterial extends Asset { diff --git a/cocos/3d/physics/cannon/cannon-body.ts b/cocos/physics/cannon/cannon-body.ts similarity index 99% rename from cocos/3d/physics/cannon/cannon-body.ts rename to cocos/physics/cannon/cannon-body.ts index bfa9dd4360..f758cdecb1 100644 --- a/cocos/3d/physics/cannon/cannon-body.ts +++ b/cocos/physics/cannon/cannon-body.ts @@ -1,5 +1,5 @@ import CANNON from 'cannon'; -import { Mat4, Quat, Vec3 } from '../../../core/math'; +import { Mat4, Quat, Vec3 } from '../../core/math'; import { ICollisionCallback, ICollisionEventType, ICreateBodyOptions, PhysicsWorldBase, RigidBodyBase, ShapeBase } from '../api'; import { ERigidBodyType } from '../physic-enum'; import { getWrap, setWrap, stringfyVec3 } from '../util'; diff --git a/cocos/3d/physics/cannon/cannon-const.ts b/cocos/physics/cannon/cannon-const.ts similarity index 100% rename from cocos/3d/physics/cannon/cannon-const.ts rename to cocos/physics/cannon/cannon-const.ts diff --git a/cocos/3d/physics/cannon/cannon-util.ts b/cocos/physics/cannon/cannon-util.ts similarity index 97% rename from cocos/3d/physics/cannon/cannon-util.ts rename to cocos/physics/cannon/cannon-util.ts index 73fb31424f..f31776f7a5 100644 --- a/cocos/3d/physics/cannon/cannon-util.ts +++ b/cocos/physics/cannon/cannon-util.ts @@ -1,5 +1,4 @@ import CANNON from 'cannon'; -import { Vec3 } from '../../../core/math'; import { IRaycastOptions, RigidBodyBase, ShapeBase } from '../api'; import { RaycastResult } from '../raycast-result'; import { getWrap } from '../util'; diff --git a/cocos/3d/physics/cannon/cannon-world.ts b/cocos/physics/cannon/cannon-world.ts similarity index 98% rename from cocos/3d/physics/cannon/cannon-world.ts rename to cocos/physics/cannon/cannon-world.ts index a40311067b..e4b8ffacae 100644 --- a/cocos/3d/physics/cannon/cannon-world.ts +++ b/cocos/physics/cannon/cannon-world.ts @@ -1,5 +1,5 @@ import CANNON from 'cannon'; -import { Vec3 } from '../../../core/math'; +import { Vec3 } from '../../core/math'; import { RaycastResult } from '../raycast-result'; import { setWrap } from '../util'; import { AfterStepCallback, BeforeStepCallback, IRaycastOptions, PhysicsWorldBase } from './../api'; diff --git a/cocos/3d/physics/cannon/constraint/cannon-constraint.ts b/cocos/physics/cannon/constraint/cannon-constraint.ts similarity index 100% rename from cocos/3d/physics/cannon/constraint/cannon-constraint.ts rename to cocos/physics/cannon/constraint/cannon-constraint.ts diff --git a/cocos/3d/physics/cannon/constraint/cannon-distance-constraint.ts b/cocos/physics/cannon/constraint/cannon-distance-constraint.ts similarity index 100% rename from cocos/3d/physics/cannon/constraint/cannon-distance-constraint.ts rename to cocos/physics/cannon/constraint/cannon-distance-constraint.ts diff --git a/cocos/3d/physics/cannon/constraint/cannon-lock-constraint.ts b/cocos/physics/cannon/constraint/cannon-lock-constraint.ts similarity index 100% rename from cocos/3d/physics/cannon/constraint/cannon-lock-constraint.ts rename to cocos/physics/cannon/constraint/cannon-lock-constraint.ts diff --git a/cocos/3d/physics/cannon/constraint/cannon-point-to-point-constraint.ts b/cocos/physics/cannon/constraint/cannon-point-to-point-constraint.ts similarity index 94% rename from cocos/3d/physics/cannon/constraint/cannon-point-to-point-constraint.ts rename to cocos/physics/cannon/constraint/cannon-point-to-point-constraint.ts index e60d55d6e2..3c2e369741 100644 --- a/cocos/3d/physics/cannon/constraint/cannon-point-to-point-constraint.ts +++ b/cocos/physics/cannon/constraint/cannon-point-to-point-constraint.ts @@ -1,5 +1,5 @@ import CANNON from 'cannon'; -import { Vec3 } from '../../../../core/math'; +import { Vec3 } from '../../../core/math'; import { IPointToPointConstraintOptions, PointToPointConstraintBase } from '../../api'; import { CannonRigidBody } from '../cannon-body'; import { CannonConstraint } from './cannon-constraint'; diff --git a/cocos/3d/physics/cannon/instantiate.ts b/cocos/physics/cannon/instantiate.ts similarity index 100% rename from cocos/3d/physics/cannon/instantiate.ts rename to cocos/physics/cannon/instantiate.ts diff --git a/cocos/3d/physics/cannon/shapes/cannon-box-shape.ts b/cocos/physics/cannon/shapes/cannon-box-shape.ts similarity index 98% rename from cocos/3d/physics/cannon/shapes/cannon-box-shape.ts rename to cocos/physics/cannon/shapes/cannon-box-shape.ts index 3dee2a0007..06c47a4202 100644 --- a/cocos/3d/physics/cannon/shapes/cannon-box-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-box-shape.ts @@ -1,5 +1,5 @@ import CANNON from 'cannon'; -import { Vec3 } from '../../../../core/math'; +import { Vec3 } from '../../../core/math'; import { BoxShapeBase, ShapeBase } from '../../api'; import { getWrap, setWrap, stringfyVec3 } from '../../util'; import { CannonRigidBody } from '../cannon-body'; diff --git a/cocos/3d/physics/cannon/shapes/cannon-shape.ts b/cocos/physics/cannon/shapes/cannon-shape.ts similarity index 95% rename from cocos/3d/physics/cannon/shapes/cannon-shape.ts rename to cocos/physics/cannon/shapes/cannon-shape.ts index 4fc43c17fd..17053aa099 100644 --- a/cocos/3d/physics/cannon/shapes/cannon-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-shape.ts @@ -1,6 +1,6 @@ import CANNON from 'cannon'; -import { Quat, Vec3 } from '../../../../core/math'; -import { ITriggerCallback, ITriggerEvent, ITriggerEventType, RigidBodyBase, ShapeBase } from '../../api'; +import { Quat, Vec3 } from '../../../core/math'; +import { ITriggerCallback, ITriggerEventType, ShapeBase } from '../../api'; import { getWrap, stringfyVec3 } from '../../util'; import { commitShapeUpdates } from '../cannon-util'; diff --git a/cocos/3d/physics/cannon/shapes/cannon-sphere-shape.ts b/cocos/physics/cannon/shapes/cannon-sphere-shape.ts similarity index 96% rename from cocos/3d/physics/cannon/shapes/cannon-sphere-shape.ts rename to cocos/physics/cannon/shapes/cannon-sphere-shape.ts index 71ce45909a..e9b6881d7f 100644 --- a/cocos/3d/physics/cannon/shapes/cannon-sphere-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-sphere-shape.ts @@ -1,5 +1,5 @@ import CANNON from 'cannon'; -import { Vec3 } from '../../../../core/math'; +import { Vec3 } from '../../../core/math'; import { ShapeBase, SphereShapeBase } from '../../api'; import { maxComponent, setWrap } from '../../util'; import { commitShapeUpdates } from '../cannon-util'; diff --git a/cocos/3d/physics/cocos/builtin-body.ts b/cocos/physics/cocos/builtin-body.ts similarity index 97% rename from cocos/3d/physics/cocos/builtin-body.ts rename to cocos/physics/cocos/builtin-body.ts index 078610fdea..777a16fcb4 100644 --- a/cocos/3d/physics/cocos/builtin-body.ts +++ b/cocos/physics/cocos/builtin-body.ts @@ -2,8 +2,8 @@ * @hidden */ -import { Mat4, Quat, Vec3 } from '../../../core/math'; -import { intersect } from '../../geom-utils'; +import { Mat4, Quat, Vec3 } from '../../core/math'; +import { intersect } from '../../core/geom-utils'; import { BuiltInRigidBodyBase, PhysicsWorldBase } from '../api'; import { ERigidBodyType } from '../physic-enum'; import { BuiltInWorld } from './builtin-world'; diff --git a/cocos/3d/physics/cocos/builtin-interface.ts b/cocos/physics/cocos/builtin-interface.ts similarity index 82% rename from cocos/3d/physics/cocos/builtin-interface.ts rename to cocos/physics/cocos/builtin-interface.ts index 42980ec64e..ac43400186 100644 --- a/cocos/3d/physics/cocos/builtin-interface.ts +++ b/cocos/physics/cocos/builtin-interface.ts @@ -2,7 +2,7 @@ * @hidden */ -import { Mat4, Quat, Vec3 } from '../../../core/math'; +import { Mat4, Quat, Vec3 } from '../../core/math'; /** * declare interface diff --git a/cocos/3d/physics/cocos/builtin-world.ts b/cocos/physics/cocos/builtin-world.ts similarity index 99% rename from cocos/3d/physics/cocos/builtin-world.ts rename to cocos/physics/cocos/builtin-world.ts index 5477b28dc9..03679a9101 100644 --- a/cocos/3d/physics/cocos/builtin-world.ts +++ b/cocos/physics/cocos/builtin-world.ts @@ -2,7 +2,7 @@ * @hidden */ -import { Vec3 } from '../../../core/math'; +import { Vec3 } from '../../core/math'; import { AfterStepCallback, BeforeStepCallback, BuiltInRigidBodyBase, BuiltInWorldBase, IRaycastOptions, ITriggerEventType, ShapeBase } from '../api'; import { RaycastResult } from '../raycast-result'; diff --git a/cocos/3d/physics/cocos/instantiate.ts b/cocos/physics/cocos/instantiate.ts similarity index 100% rename from cocos/3d/physics/cocos/instantiate.ts rename to cocos/physics/cocos/instantiate.ts diff --git a/cocos/3d/physics/cocos/object/builtin-object.ts b/cocos/physics/cocos/object/builtin-object.ts similarity index 100% rename from cocos/3d/physics/cocos/object/builtin-object.ts rename to cocos/physics/cocos/object/builtin-object.ts diff --git a/cocos/3d/physics/cocos/shapes/builtin-box-shape.ts b/cocos/physics/cocos/shapes/builtin-box-shape.ts similarity index 86% rename from cocos/3d/physics/cocos/shapes/builtin-box-shape.ts rename to cocos/physics/cocos/shapes/builtin-box-shape.ts index f3955d99ad..f7c8a77df4 100644 --- a/cocos/3d/physics/cocos/shapes/builtin-box-shape.ts +++ b/cocos/physics/cocos/shapes/builtin-box-shape.ts @@ -1,5 +1,5 @@ -import { Vec3 } from '../../../../core/math'; -import { obb } from '../../../geom-utils'; +import { Vec3 } from '../../../core/math'; +import { obb } from '../../../core/geom-utils'; import { BuiltinShape } from './builtin-shape'; export class BuiltinBoxShape extends BuiltinShape { diff --git a/cocos/3d/physics/cocos/shapes/builtin-shape.ts b/cocos/physics/cocos/shapes/builtin-shape.ts similarity index 97% rename from cocos/3d/physics/cocos/shapes/builtin-shape.ts rename to cocos/physics/cocos/shapes/builtin-shape.ts index 87a2fee379..033eca6b9f 100644 --- a/cocos/3d/physics/cocos/shapes/builtin-shape.ts +++ b/cocos/physics/cocos/shapes/builtin-shape.ts @@ -1,4 +1,4 @@ -import { Mat4, Quat, Vec3 } from '../../../../core/math'; +import { Mat4, Quat, Vec3 } from '../../../core/math'; import { ITriggerCallback, ITriggerEvent, ShapeBase } from '../../api'; import { BuiltInBody } from '../builtin-body'; import { IBuiltinShape } from '../builtin-interface'; diff --git a/cocos/3d/physics/cocos/shapes/builtin-sphere-shape.ts b/cocos/physics/cocos/shapes/builtin-sphere-shape.ts similarity index 92% rename from cocos/3d/physics/cocos/shapes/builtin-sphere-shape.ts rename to cocos/physics/cocos/shapes/builtin-sphere-shape.ts index b1d781fbf2..872e5befeb 100644 --- a/cocos/3d/physics/cocos/shapes/builtin-sphere-shape.ts +++ b/cocos/physics/cocos/shapes/builtin-sphere-shape.ts @@ -1,4 +1,4 @@ -import { sphere } from '../../../geom-utils'; +import { sphere } from '../../../core/geom-utils'; import { BuiltinShape } from './builtin-shape'; export class BuiltinSphereShape extends BuiltinShape { diff --git a/cocos/3d/physics/cocos/utils/array-collision-matrix.ts b/cocos/physics/cocos/utils/array-collision-matrix.ts similarity index 100% rename from cocos/3d/physics/cocos/utils/array-collision-matrix.ts rename to cocos/physics/cocos/utils/array-collision-matrix.ts diff --git a/cocos/3d/framework/physics/collider/box-collider-component.ts b/cocos/physics/components/collider/box-collider-component.ts similarity index 87% rename from cocos/3d/framework/physics/collider/box-collider-component.ts rename to cocos/physics/components/collider/box-collider-component.ts index 651fd5edfa..2584205fa8 100644 --- a/cocos/3d/framework/physics/collider/box-collider-component.ts +++ b/cocos/physics/components/collider/box-collider-component.ts @@ -8,10 +8,10 @@ import { executionOrder, menu, property, -} from '../../../../core/data/class-decorator'; -import { Vec3 } from '../../../../core/math'; -import { BoxShapeBase } from '../../../physics/api'; -import { createBoxShape } from '../../../physics/instance'; +} from '../../../core/data/class-decorator'; +import { Vec3 } from '../../../core/math'; +import { BoxShapeBase } from '../../api'; +import { createBoxShape } from '../../instance'; import { ColliderComponent } from './collider-component'; /** diff --git a/cocos/3d/framework/physics/collider/collider-component.ts b/cocos/physics/components/collider/collider-component.ts similarity index 93% rename from cocos/3d/framework/physics/collider/collider-component.ts rename to cocos/physics/components/collider/collider-component.ts index caad03d88b..f1a1ff2721 100644 --- a/cocos/3d/framework/physics/collider/collider-component.ts +++ b/cocos/physics/components/collider/collider-component.ts @@ -2,15 +2,15 @@ * @category physics */ -import { ccclass, property } from '../../../../core/data/class-decorator'; -import { EventTarget } from '../../../../core/event'; -import { CallbacksInvoker, ICallbackTable } from '../../../../core/event/callbacks-invoker'; -import { applyMixins, IEventTarget } from '../../../../core/event/event-target-factory'; -import { createMap } from '../../../../core/utils/js'; -import { Vec3 } from '../../../../core/math'; -import { ICollisionCallback, ICollisionEvent, ITriggerCallback, ITriggerEvent, RigidBodyBase, ShapeBase } from '../../../physics/api'; -import { CollisionCallback, CollisionEventType, TriggerCallback, TriggerEventType } from '../../../physics/export-api'; -import { ERigidBodyType, ETransformSource } from '../../../physics/physic-enum'; +import { ccclass, property } from '../../../core/data/class-decorator'; +import { EventTarget } from '../../../core/event'; +import { CallbacksInvoker, ICallbackTable } from '../../../core/event/callbacks-invoker'; +import { applyMixins, IEventTarget } from '../../../core/event/event-target-factory'; +import { createMap } from '../../../core/utils/js'; +import { Vec3 } from '../../../core/math'; +import { ICollisionCallback, ICollisionEvent, ITriggerCallback, ITriggerEvent, ShapeBase } from '../../api'; +import { CollisionCallback, CollisionEventType, TriggerCallback, TriggerEventType } from '../../export-api'; +import { ERigidBodyType } from '../../physic-enum'; import { PhysicsBasedComponent } from '../detail/physics-based-component'; import { RigidBodyComponent } from '../rigid-body-component'; diff --git a/cocos/3d/framework/physics/collider/sphere-collider-component.ts b/cocos/physics/components/collider/sphere-collider-component.ts similarity index 89% rename from cocos/3d/framework/physics/collider/sphere-collider-component.ts rename to cocos/physics/components/collider/sphere-collider-component.ts index b8e4a0ea97..8004849d06 100644 --- a/cocos/3d/framework/physics/collider/sphere-collider-component.ts +++ b/cocos/physics/components/collider/sphere-collider-component.ts @@ -8,9 +8,9 @@ import { executionOrder, menu, property, -} from '../../../../core/data/class-decorator'; -import { SphereShapeBase } from '../../../physics/api'; -import { createSphereShape } from '../../../physics/instance'; +} from '../../../core/data/class-decorator'; +import { SphereShapeBase } from '../../api'; +import { createSphereShape } from '../../instance'; import { ColliderComponent } from './collider-component'; /** diff --git a/cocos/3d/framework/physics/constant-force.ts b/cocos/physics/components/constant-force.ts similarity index 95% rename from cocos/3d/framework/physics/constant-force.ts rename to cocos/physics/components/constant-force.ts index 8dad849251..4404d1c3ad 100644 --- a/cocos/3d/framework/physics/constant-force.ts +++ b/cocos/physics/components/constant-force.ts @@ -10,10 +10,10 @@ import { property, requireComponent, disallowMultiple, -} from '../../../core/data/class-decorator'; -import { Component } from '../../../components'; +} from '../../core/data/class-decorator'; +import { Component } from '../../core/components/component'; import { RigidBodyComponent } from './rigid-body-component'; -import { Vec3 } from '../../../core'; +import { Vec3 } from '../../core/math/vec3'; /** * @zh diff --git a/cocos/3d/framework/physics/default-material.ts b/cocos/physics/components/default-material.ts similarity index 78% rename from cocos/3d/framework/physics/default-material.ts rename to cocos/physics/components/default-material.ts index 5f2b9bf7e0..69cd316fad 100644 --- a/cocos/3d/framework/physics/default-material.ts +++ b/cocos/physics/components/default-material.ts @@ -1,5 +1,5 @@ -import { PhysicsMaterial } from '../../assets/physics/material'; +import { PhysicsMaterial } from '../assets/material'; export const DefaultPhysicsMaterial: PhysicsMaterial = (() => { const result = new PhysicsMaterial(); diff --git a/cocos/3d/framework/physics/detail/physics-based-component.ts b/cocos/physics/components/detail/physics-based-component.ts similarity index 94% rename from cocos/3d/framework/physics/detail/physics-based-component.ts rename to cocos/physics/components/detail/physics-based-component.ts index 7fe0df3680..f5149a1f88 100644 --- a/cocos/3d/framework/physics/detail/physics-based-component.ts +++ b/cocos/physics/components/detail/physics-based-component.ts @@ -4,15 +4,16 @@ */ /** */ -import { Component } from '../../../../components/component'; -import { Mat4, Quat, Vec3 } from '../../../../core/math'; +import { Component } from '../../../core/components/component'; +import { Mat4, Quat, Vec3 } from '../../../core/math'; // tslint:disable-next-line:max-line-length -import { AfterStepCallback, BeforeStepCallback, PhysicsWorldBase, RigidBodyBase } from '../../../physics/api'; -import { createRigidBody } from '../../../physics/instance'; -import { ERigidBodyType, ETransformSource } from '../../../physics/physic-enum'; -import { INode } from '../../../../core/utils/interfaces'; -import { TransformDirtyBit } from '../../../../scene-graph/node-enum'; -import { error } from '../../../../core/platform/CCDebug'; +import { AfterStepCallback, BeforeStepCallback, PhysicsWorldBase, RigidBodyBase } from '../../api'; +import { createRigidBody } from '../../instance'; +import { ERigidBodyType, ETransformSource } from '../../physic-enum'; +import { INode } from '../../../core/utils/interfaces'; +import { TransformDirtyBit } from '../../../core/scene-graph/node-enum'; +import { error } from '../../../core/platform/debug'; +import { PhysicsSystem } from '../physics-system'; export class PhysicsBasedComponent extends Component { @@ -150,15 +151,15 @@ export class PhysicsBasedComponent extends Component { // if (rigidbody.sharedBody != null) { // sharedBody = rigidbody.sharedBody; // } else { - // sharedBody = new SharedRigidBody(rigidbody.node, rigidbody, cc.director._physicsSystem._world); + // sharedBody = new SharedRigidBody(rigidbody.node, rigidbody, director._physicsSystem._world); // } // } else { - // sharedBody = new SharedRigidBody(this.node, null, cc.director._physicsSystem._world); + // sharedBody = new SharedRigidBody(this.node, null, director._physicsSystem._world); // } // binding collider to self rigidybody, if it exist. const rigidbody = this.getComponent(cc.RigidBodyComponent); - sharedBody = new SharedRigidBody(this.node, rigidbody, cc.director._physicsSystem._world); + sharedBody = new SharedRigidBody(this.node, rigidbody, PhysicsSystem.instance._world); } sharedBody!.ref(); this._sharedBody = sharedBody!; diff --git a/cocos/3d/framework/physics/index.ts b/cocos/physics/components/index.ts similarity index 100% rename from cocos/3d/framework/physics/index.ts rename to cocos/physics/components/index.ts diff --git a/cocos/3d/framework/physics/physics-system.ts b/cocos/physics/components/physics-system.ts similarity index 81% rename from cocos/3d/framework/physics/physics-system.ts rename to cocos/physics/components/physics-system.ts index 9bccc5bf80..e30728fbad 100644 --- a/cocos/3d/framework/physics/physics-system.ts +++ b/cocos/physics/components/physics-system.ts @@ -2,15 +2,17 @@ * @category physics */ -import { Vec3 } from '../../../core/math'; -import { PhysicsWorldBase } from '../../physics/api'; -import { createPhysicsWorld } from '../../physics/instance'; +import { Vec3 } from '../../core/math'; +import { PhysicsWorldBase } from '../api'; +import { createPhysicsWorld } from '../instance'; +import { director, Director } from '../../core/director'; +import { System } from '../../core/components'; /** * @zh * 物理系统。 */ -export class PhysicsSystem { +export class PhysicsSystem extends System { /** * @zh @@ -19,7 +21,6 @@ export class PhysicsSystem { public get enable (): boolean { return this._enable; } - public set enable (value: boolean) { this._enable = value; } @@ -31,7 +32,6 @@ export class PhysicsSystem { public get allowSleep (): boolean { return this._allowSleep; } - public set allowSleep (v: boolean) { this._allowSleep = v; if (!CC_EDITOR) { @@ -50,7 +50,6 @@ export class PhysicsSystem { // public get singleStep () { // return this._singleStep; // } - // public set singleStep (b: boolean) { // this._singleStep = b; // } @@ -62,7 +61,6 @@ export class PhysicsSystem { public get maxSubStep () { return this._maxSubStep; } - public set maxSubStep (value: number) { this._maxSubStep = value; } @@ -74,7 +72,6 @@ export class PhysicsSystem { public get deltaTime () { return this._deltaTime; } - public set deltaTime (value: number) { this._deltaTime = value; } @@ -91,7 +88,6 @@ export class PhysicsSystem { } return this._gravity; } - public set gravity (gravity: Vec3) { this._gravity.x = gravity.x; this._gravity.y = gravity.y; @@ -115,17 +111,15 @@ export class PhysicsSystem { // public get frameRate () { // return this._frameRate; // } - // public set frameRate (value: number) { // this._frameRate = value; // this._deltaTime = 1 / this._frameRate; // } - public static get ins (): PhysicsSystem { - return cc.director._physicsSystem; - } + public static instance: PhysicsSystem; + public static ID: 'physics'; - private _world: PhysicsWorldBase; + public _world: PhysicsWorldBase; private _enable = true; private _deltaTime = 1.0 / 60.0; private _maxSubStep = 2; @@ -135,6 +129,7 @@ export class PhysicsSystem { private _gravity = new Vec3(0, -10, 0); constructor () { + super(); this._world = createPhysicsWorld(); this.gravity = this._gravity; this.allowSleep = this._allowSleep; @@ -145,17 +140,28 @@ export class PhysicsSystem { * 执行一次物理系统的模拟,目前将在每帧自动执行一次。 * @param deltaTime 与上一次执行相差的时间,目前为每帧消耗时间 */ - public update (deltaTime: number) { - if (CC_EDITOR) { + public postUpdate (deltaTime: number) { + if (CC_EDITOR && !this._executeInEditMode) { return; } if (!this._enable) { return; } + + director.emit(Director.EVENT_BEFORE_PHYSICS); + this._world.step(this._deltaTime, deltaTime, this._maxSubStep); // if (this._singleStep) { // this._enable = false; // } + + director.emit(Director.EVENT_AFTER_PHYSICS); } } cc.PhysicsSystem = PhysicsSystem; + +director.on(Director.EVENT_INIT, function () { + let sys = new PhysicsSystem(); + PhysicsSystem.instance = sys; + director.registerSystem(PhysicsSystem.ID, sys, 0); +}); \ No newline at end of file diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/physics/components/rigid-body-component.ts similarity index 99% rename from cocos/3d/framework/physics/rigid-body-component.ts rename to cocos/physics/components/rigid-body-component.ts index 15f8c6a350..a24ad7a1cd 100644 --- a/cocos/3d/framework/physics/rigid-body-component.ts +++ b/cocos/physics/components/rigid-body-component.ts @@ -10,8 +10,8 @@ import { menu, property, disallowMultiple, -} from '../../../core/data/class-decorator'; -import { Quat, Vec3 } from '../../../core/math'; +} from '../../core/data/class-decorator'; +import { Vec3 } from '../../core/math'; import { PhysicsBasedComponent } from './detail/physics-based-component'; const NonRigidBodyProperties = { diff --git a/cocos/3d/physics/export-api.ts b/cocos/physics/export-api.ts similarity index 93% rename from cocos/3d/physics/export-api.ts rename to cocos/physics/export-api.ts index 629380fd8a..ef6e9ce0da 100644 --- a/cocos/3d/physics/export-api.ts +++ b/cocos/physics/export-api.ts @@ -2,8 +2,8 @@ * @category physics */ -import { Vec3 } from '../../core/math'; -import { ColliderComponent } from '../framework/physics/collider/collider-component'; +import { Vec3 } from '../core/math'; +import { ColliderComponent } from './components/collider/collider-component'; /** * @zh diff --git a/cocos/3d/physics/impl-selector.ts b/cocos/physics/impl-selector.ts similarity index 100% rename from cocos/3d/physics/impl-selector.ts rename to cocos/physics/impl-selector.ts diff --git a/cocos/3d/physics/instance.ts b/cocos/physics/instance.ts similarity index 95% rename from cocos/3d/physics/instance.ts rename to cocos/physics/instance.ts index b3507324f7..135981b905 100644 --- a/cocos/3d/physics/instance.ts +++ b/cocos/physics/instance.ts @@ -2,7 +2,7 @@ * @hidden */ -import { Vec3 } from '../../core/math'; +import { Vec3 } from '../core/math'; import { BoxShapeBase, ICreateBodyOptions, PhysicsWorldBase, RigidBodyBase, SphereShapeBase } from './api'; import { BoxShape, PhysicsWorld, RigidBody, SphereShape } from './impl-selector'; import { RaycastResult } from './raycast-result'; diff --git a/cocos/3d/physics/physic-enum.ts b/cocos/physics/physic-enum.ts similarity index 100% rename from cocos/3d/physics/physic-enum.ts rename to cocos/physics/physic-enum.ts diff --git a/cocos/3d/physics/raycast-result.ts b/cocos/physics/raycast-result.ts similarity index 84% rename from cocos/3d/physics/raycast-result.ts rename to cocos/physics/raycast-result.ts index 4a075036ac..e174467b1c 100644 --- a/cocos/3d/physics/raycast-result.ts +++ b/cocos/physics/raycast-result.ts @@ -2,10 +2,10 @@ * @hidden */ -import { Component } from '../../components/component'; -import { Vec3 } from '../../core/math'; +import { Component } from '../core/components/component'; +import { Vec3 } from '../core/math'; import { RigidBodyBase, ShapeBase } from './api'; -import { INode } from '../../core/utils/interfaces'; +import { INode } from '../core/utils/interfaces'; export class RaycastResult { get hitPoint (): Vec3 { diff --git a/cocos/3d/physics/util.ts b/cocos/physics/util.ts similarity index 95% rename from cocos/3d/physics/util.ts rename to cocos/physics/util.ts index 82f2248d66..8b381fe386 100644 --- a/cocos/3d/physics/util.ts +++ b/cocos/physics/util.ts @@ -2,7 +2,7 @@ * @hidden */ -import { Quat, Vec3 } from '../../core/math'; +import { Quat, Vec3 } from '../core/math'; export function stringfyVec3 (value: {x: number; y: number; z: number}): string { if (Vec3.strictEquals(value, new Vec3())) { diff --git a/cocos/renderer/ui/ui-material.ts b/cocos/renderer/ui/ui-material.ts deleted file mode 100644 index 3e48b6b5d9..0000000000 --- a/cocos/renderer/ui/ui-material.ts +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @hidden - */ - -import { Material } from '../../3d/assets/material'; -import Pool from '../../3d/memop/pool'; -import { GFXPipelineState } from '../../gfx/pipeline-state'; -import { UBOGlobal } from '../../pipeline/define'; -import { Pass } from '../core/pass'; - -export interface IUIMaterialInfo { - material: Material; -} - -export class UIMaterial { - - public get material (): Material { - return this._material!; - } - - public get pass (): Pass { - return this._pass!; - } - - protected _material: Material | null = null; - protected _pass: Pass | null = null; - private _psos: Pool | null; - - constructor () { - this._psos = null; - } - - public initialize (info: IUIMaterialInfo): boolean { - - if (!info.material) { - return false; - } - - this._material = info.material; - - this._pass = this._material.passes[0]; - - this._psos = new Pool(() => { - const pso = this._pass!.createPipelineState()!; - return pso; - }, 1); - - return true; - } - - public getPipelineState (): GFXPipelineState { - return this._psos!.alloc(); - } - - public revertPipelineState (pso: GFXPipelineState) { - this._psos!.free(pso); - } - - public destroy () { - this._material = null; - if (this._psos) { - this._psos.clear((obj: GFXPipelineState) => { - this._pass!.destroyPipelineState(obj); - }); - } - } -} diff --git a/cocos/renderer/terrain/height-field.ts b/cocos/terrain/height-field.ts similarity index 97% rename from cocos/renderer/terrain/height-field.ts rename to cocos/terrain/height-field.ts index 56a9ab578d..ce80dc58ed 100644 --- a/cocos/renderer/terrain/height-field.ts +++ b/cocos/terrain/height-field.ts @@ -2,7 +2,7 @@ * @category terrain */ -import { clamp } from '../../core/math'; +import { clamp } from '../core/math'; export class HeightField { public data: Uint16Array = new Uint16Array(); diff --git a/cocos/terrain/index.ts b/cocos/terrain/index.ts new file mode 100644 index 0000000000..dee36b1602 --- /dev/null +++ b/cocos/terrain/index.ts @@ -0,0 +1,3 @@ + +export * from './height-field'; +export * from './terrain'; \ No newline at end of file diff --git a/cocos/renderer/terrain/terrain.ts b/cocos/terrain/terrain.ts similarity index 96% rename from cocos/renderer/terrain/terrain.ts rename to cocos/terrain/terrain.ts index d2b5f782be..e0ae17ab65 100644 --- a/cocos/renderer/terrain/terrain.ts +++ b/cocos/terrain/terrain.ts @@ -2,25 +2,24 @@ * @category terrain */ -import { EffectAsset } from '../../3d/assets/effect-asset'; -import { Material } from '../../3d/assets/material'; -import { IRenderingSubmesh } from '../../3d/assets/mesh'; -import { builtinResMgr } from '../../3d/builtin'; -import { RenderableComponent } from '../../3d/framework/renderable-component'; -import { Texture2D } from '../../assets'; -import { Filter, PixelFormat, WrapMode } from '../../assets/asset-enum'; -import { Component } from '../../components'; -import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; -import { clamp, Rect, Size, Vec2, Vec3, Vec4 } from '../../core/math'; -import { GFXBuffer } from '../../gfx/buffer'; -import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; -import { GFXDevice } from '../../gfx/device'; -import { IGFXAttribute } from '../../gfx/input-assembler'; -import { Model } from '../../renderer/scene/model'; -import { Node } from '../../scene-graph/node'; -import { PrivateNode } from '../../scene-graph/private-node'; -import { IDefineMap } from '../core/pass'; +import { Material } from '../core/assets/material'; +import { IRenderingSubmesh } from '../core/assets/mesh'; +import { builtinResMgr } from '../core/3d/builtin'; +import { RenderableComponent } from '../core/3d/framework/renderable-component'; +import { Texture2D, EffectAsset } from '../core/assets'; +import { Filter, PixelFormat, WrapMode } from '../core/assets/asset-enum'; +import { Component } from '../core/components'; +import { ccclass, executeInEditMode, menu, property } from '../core/data/class-decorator'; +import { clamp, Rect, Size, Vec2, Vec3, Vec4 } from '../core/math'; +import { GFXBuffer } from '../core/gfx/buffer'; +import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../core/gfx/define'; +import { GFXDevice } from '../core/gfx/device'; +import { IGFXAttribute } from '../core/gfx/input-assembler'; +import { Model } from '../core/renderer/scene/model'; +import { PrivateNode } from '../core/scene-graph/private-node'; +import { IDefineMap } from '../core/renderer/core/pass'; import { HeightField } from './height-field'; +import { director } from '../core/director'; export const TERRAIN_MAX_LEVELS = 4; export const TERRAIN_MAX_BLEND_LAYERS = 4; @@ -132,7 +131,7 @@ export class TerrainRenderable extends RenderableComponent { this._currentMaterial = new Material(); this._currentMaterial.initialize({ - effectAsset: cc.EffectAsset.get('builtin-terrain'), + effectAsset: EffectAsset.get('builtin-terrain'), defines: block._getMaterialDefines(nlayers), }); @@ -200,14 +199,16 @@ export class TerrainBlock { this._index[1] = j; this._node = new PrivateNode(''); - this._node.setParent(this._terrain.node as Node); + // @ts-ignore + this._node.setParent(this._terrain.node); + // @ts-ignore this._node._objFlags |= cc.Object.Flags.DontSave; this._renderable = this._node.addComponent(TerrainRenderable) as TerrainRenderable; } public build () { - const gfxDevice = cc.director.root.device as GFXDevice; + const gfxDevice = director.root!.device as GFXDevice; // vertex buffer const vertexData = new Float32Array(TERRAIN_BLOCK_VERTEX_SIZE * TERRAIN_BLOCK_VERTEX_COMPLEXITY * TERRAIN_BLOCK_VERTEX_COMPLEXITY); @@ -252,6 +253,7 @@ export class TerrainBlock { primitiveMode: GFXPrimitiveMode.TRIANGLE_LIST, }; + // @ts-ignore this._renderable._model = this._renderable._getRenderScene().createModel(Model, this._node); // reset weightmap @@ -300,7 +302,7 @@ export class TerrainBlock { mtl.setProperty('detailMap0', l0 != null ? l0.detailMap : null); } else { - mtl.setProperty('detailMap0', cc.builtinResMgr.get('default-texture')); + mtl.setProperty('detailMap0', builtinResMgr.get('default-texture')); } } else if (nlayers === 1) { @@ -674,7 +676,7 @@ export class Terrain extends Component { } public onLoad () { - const gfxDevice = cc.director.root.device as GFXDevice; + const gfxDevice = director.root!.device as GFXDevice; // initialize shared index buffer const indexData = new Uint16Array(TERRAIN_BLOCK_TILE_COMPLEXITY * TERRAIN_BLOCK_TILE_COMPLEXITY * 6); diff --git a/cocos/tween/deprecated.ts b/cocos/tween/deprecated.ts index 287eef7ad4..982fdb9209 100644 --- a/cocos/tween/deprecated.ts +++ b/cocos/tween/deprecated.ts @@ -3,9 +3,8 @@ */ // deprecated -import { Tween, tweenUtil } from './tween'; -import { warn } from '../core/platform/CCDebug'; -import { replaceProperty } from '../deprecated'; +import { Tween } from './tween'; +import { replaceProperty } from '../core/utils/deprecated'; /** * @zh diff --git a/cocos/tween/tween.ts b/cocos/tween/tween.ts index 98c407403e..27fab67599 100644 --- a/cocos/tween/tween.ts +++ b/cocos/tween/tween.ts @@ -6,6 +6,8 @@ import { TweenAction } from './tween-action'; import { TweenCommand } from './tween-command'; import { TweenUnion } from './tween-union'; import { ITweenOption, ITweenProp } from './export-api'; +import System from '../core/components/system'; +import { director, Director } from '../core/director'; /** * @en @@ -282,3 +284,20 @@ cc.tweenUtil = tweenUtil; * .repeat(1); * */ + +export class TweenSystem extends System { + public static ID = 'tween'; + public postUpdate (dt: number) { + if (!CC_EDITOR || this._executeInEditMode) { + if (cc.TWEEN) { + // Tween update + cc.TWEEN.update(performance.now()); + } + } + } +} + +director.on(Director.EVENT_INIT, function () { + let sys = new TweenSystem(); + director.registerSystem(TweenSystem.ID, sys, 100); +}); diff --git a/cocos/3d/ui/assembler/graphics/helper.ts b/cocos/ui/assembler/graphics/helper.ts similarity index 100% rename from cocos/3d/ui/assembler/graphics/helper.ts rename to cocos/ui/assembler/graphics/helper.ts diff --git a/cocos/3d/ui/assembler/graphics/index.ts b/cocos/ui/assembler/graphics/index.ts similarity index 100% rename from cocos/3d/ui/assembler/graphics/index.ts rename to cocos/ui/assembler/graphics/index.ts diff --git a/cocos/3d/ui/assembler/graphics/types.ts b/cocos/ui/assembler/graphics/types.ts similarity index 98% rename from cocos/3d/ui/assembler/graphics/types.ts rename to cocos/ui/assembler/graphics/types.ts index 46d920a5a5..9d6ada2d1f 100644 --- a/cocos/3d/ui/assembler/graphics/types.ts +++ b/cocos/ui/assembler/graphics/types.ts @@ -24,7 +24,7 @@ THE SOFTWARE. */ -import { ccenum } from '../../../../core/value-types/enum'; +import { ccenum } from '../../../core/value-types/enum'; /** * @en Enum for LineCap. diff --git a/cocos/3d/ui/assembler/graphics/webgl/earcut.ts b/cocos/ui/assembler/graphics/webgl/earcut.ts similarity index 100% rename from cocos/3d/ui/assembler/graphics/webgl/earcut.ts rename to cocos/ui/assembler/graphics/webgl/earcut.ts diff --git a/cocos/3d/ui/assembler/graphics/webgl/graphics-assembler.ts b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts similarity index 97% rename from cocos/3d/ui/assembler/graphics/webgl/graphics-assembler.ts rename to cocos/ui/assembler/graphics/webgl/graphics-assembler.ts index ec35bb51aa..ae463781e6 100644 --- a/cocos/3d/ui/assembler/graphics/webgl/graphics-assembler.ts +++ b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts @@ -27,19 +27,20 @@ * @category ui-assembler */ -import { Color, Vec2, Vec3 } from '../../../../../core/math'; -import { GFXPrimitiveMode } from '../../../../../gfx'; -import { Model } from '../../../../../renderer'; -import { RenderScene } from '../../../../../renderer/scene/render-scene'; -import { IARenderData } from '../../../../../renderer/ui/renderData'; -import { UI } from '../../../../../renderer/ui/ui'; -import { createMesh } from '../../../../misc/utils'; +import { Color, Vec3 } from '../../../../core/math'; +import { GFXPrimitiveMode } from '../../../../core/gfx'; +import { Model } from '../../../../core/renderer'; +import { RenderScene } from '../../../../core/renderer/scene/render-scene'; +import { IARenderData } from '../../../../core/renderer/ui/render-data'; +import { UI } from '../../../../core/renderer/ui/ui'; +import { createMesh } from '../../../../core/3d/misc/utils'; import { GraphicsComponent } from '../../../components'; -import { vfmt } from '../../../ui-vertex-format'; -import { IAssembler } from '../../base'; +import { vfmt } from '../../../../core/renderer/ui/ui-vertex-format'; +import { IAssembler } from '../../../../core/renderer/ui/base'; import { LineCap, LineJoin, PointFlags } from '../types'; import { earcut as Earcut } from './earcut'; import { Impl, Point } from './impl'; +import { director } from '../../../../core/director'; const MAX_VERTEX = 65535; const MAX_INDICE = MAX_VERTEX * 2; @@ -209,7 +210,7 @@ export const graphicsAssembler: IAssembler = { }, end (graphics: GraphicsComponent){ - const scene = cc.director.root.ui.renderScene as RenderScene; + const scene = director.root!.ui.renderScene as RenderScene; if (graphics.model){ graphics.model.destroy(); scene.destroyModel(graphics.model); diff --git a/cocos/3d/ui/assembler/graphics/webgl/impl.ts b/cocos/ui/assembler/graphics/webgl/impl.ts similarity index 92% rename from cocos/3d/ui/assembler/graphics/webgl/impl.ts rename to cocos/ui/assembler/graphics/webgl/impl.ts index 6fcace78c9..8c1c71d93e 100644 --- a/cocos/3d/ui/assembler/graphics/webgl/impl.ts +++ b/cocos/ui/assembler/graphics/webgl/impl.ts @@ -1,14 +1,9 @@ -// import { ccclass } from '../../../../../core/data/class-decorator'; -import { Color, Vec2 } from '../../../../../core/math'; -import { IARenderData } from '../../../../../renderer/ui/renderData'; -import RecyclePool from '../../../../memop/recycle-pool'; +import { Color, Vec2 } from '../../../../core/math'; +import { IARenderData } from '../../../../core/renderer/ui/render-data'; +import RecyclePool from '../../../../core/memop/recycle-pool'; import { arc, ellipse, roundRect, tesselateBezier } from '../helper'; import { LineCap, LineJoin, PointFlags} from '../types'; -// const renderer = require('../../../index'); -// const renderEngine = renderer.renderEngine; -// const IARenderData = renderEngine.IARenderData; -// const InputAssembler = renderEngine.InputAssembler; export class Point extends Vec2 { public dx = 0; diff --git a/cocos/3d/ui/assembler/graphics/webgl/index.ts b/cocos/ui/assembler/graphics/webgl/index.ts similarity index 95% rename from cocos/3d/ui/assembler/graphics/webgl/index.ts rename to cocos/ui/assembler/graphics/webgl/index.ts index 92e3abad36..943338be6d 100644 --- a/cocos/3d/ui/assembler/graphics/webgl/index.ts +++ b/cocos/ui/assembler/graphics/webgl/index.ts @@ -24,7 +24,7 @@ */ import { GraphicsComponent, UIRenderComponent } from '../../../components'; -import { IAssemblerManager } from '../../base'; +import { IAssemblerManager } from '../../../../core/renderer/ui/base'; import { graphicsAssembler as graphics } from './graphics-assembler'; const graphicsAssemblerManager: IAssemblerManager = { diff --git a/cocos/3d/ui/assembler/index.ts b/cocos/ui/assembler/index.ts similarity index 96% rename from cocos/3d/ui/assembler/index.ts rename to cocos/ui/assembler/index.ts index 3fd40624e9..415e8aa869 100644 --- a/cocos/3d/ui/assembler/index.ts +++ b/cocos/ui/assembler/index.ts @@ -33,4 +33,4 @@ export * from './label'; export * from './mask'; export * from './sprite'; -export * from './base'; +export * from '../../core/renderer/ui/base'; diff --git a/cocos/3d/ui/assembler/label/bmfont.ts b/cocos/ui/assembler/label/bmfont.ts similarity index 93% rename from cocos/3d/ui/assembler/label/bmfont.ts rename to cocos/ui/assembler/label/bmfont.ts index b8ebd3ed65..ee6c3a7e98 100644 --- a/cocos/3d/ui/assembler/label/bmfont.ts +++ b/cocos/ui/assembler/label/bmfont.ts @@ -27,12 +27,12 @@ * @category ui-assembler */ -import { SpriteFrame } from '../../../../assets/sprite-frame'; -import * as js from '../../../../core/utils/js'; -import { Rect } from '../../../../core/math'; -import { UI } from '../../../../renderer/ui/ui'; +import { SpriteFrame } from '../../../core/assets/sprite-frame'; +import * as js from '../../../core/utils/js'; +import { Rect } from '../../../core/math'; +import { UI } from '../../../core/renderer/ui/ui'; import { LabelComponent } from '../../components/label-component'; -import { IAssembler } from '../base'; +import { IAssembler } from '../../../core/renderer/ui/base'; import { fillMeshVertices3D } from '../utils'; import { bmfontUtils } from './bmfontUtils'; diff --git a/cocos/3d/ui/assembler/label/bmfontUtils.ts b/cocos/ui/assembler/label/bmfontUtils.ts similarity index 98% rename from cocos/3d/ui/assembler/label/bmfontUtils.ts rename to cocos/ui/assembler/label/bmfontUtils.ts index 738244c9b8..8b9b56b23c 100644 --- a/cocos/3d/ui/assembler/label/bmfontUtils.ts +++ b/cocos/ui/assembler/label/bmfontUtils.ts @@ -27,12 +27,13 @@ * @hidden */ -import { BitmapFont, IConfig } from '../../../../assets/bitmap-font'; -import { SpriteFrame } from '../../../../assets/sprite-frame'; -import { isUnicodeCJK, isUnicodeSpace } from '../../../../core/utils/text-utils'; -import { Rect, Size, Vec2 } from '../../../../core/math'; +import { BitmapFont, IConfig } from '../../../core/assets/bitmap-font'; +import { SpriteFrame } from '../../../core/assets/sprite-frame'; +import { isUnicodeCJK, isUnicodeSpace } from '../../../core/utils/text-utils'; +import { Rect, Size, Vec2 } from '../../../core/math'; import { HorizontalTextAlignment, VerticalTextAlignment } from '../../components/label-component'; import { LabelComponent, Overflow } from '../../components/label-component'; +import { js } from '../../../core/utils'; class FontLetterDefinition { public u = 0; @@ -68,7 +69,7 @@ export class FontAtlas { const copyLetterDefinitions: ILetterDefinition = {}; for (const key of Object.keys(this._letterDefinitions)) { const value = new FontLetterDefinition(); - cc.js.mixin(value, this._letterDefinitions[key]); + js.mixin(value, this._letterDefinitions[key]); copyLetterDefinitions[key] = value; } return copyLetterDefinitions; @@ -78,7 +79,7 @@ export class FontAtlas { for (const key of Object.keys(this._letterDefinitions)) { const newValue = letterDefinition[key]; const oldValue = this._letterDefinitions[key]; - cc.js.mixin(oldValue, newValue); + js.mixin(oldValue, newValue); } } diff --git a/cocos/3d/ui/assembler/label/font-utils.ts b/cocos/ui/assembler/label/font-utils.ts similarity index 100% rename from cocos/3d/ui/assembler/label/font-utils.ts rename to cocos/ui/assembler/label/font-utils.ts diff --git a/cocos/3d/ui/assembler/label/index.ts b/cocos/ui/assembler/label/index.ts similarity index 85% rename from cocos/3d/ui/assembler/label/index.ts rename to cocos/ui/assembler/label/index.ts index 5daeecdee2..2c2eee4612 100644 --- a/cocos/3d/ui/assembler/label/index.ts +++ b/cocos/ui/assembler/label/index.ts @@ -27,13 +27,15 @@ * @category ui-assembler */ -import { BitmapFont } from '../../../../assets'; +import { BitmapFont } from '../../../core/assets'; import { LabelComponent} from '../../components'; -import { IAssemblerManager } from '../base'; +import { IAssemblerManager } from '../../../core/renderer/ui/base'; import { bmfont } from './bmfont'; import { CanvasPool } from './font-utils'; import { letter } from './letter'; import { ttf } from './ttf'; +import sys from '../../../core/platform/sys'; +import { warn } from '../../../core/platform/debug'; const labelAssembler: IAssemblerManager = { getAssembler (comp: LabelComponent) { @@ -42,8 +44,8 @@ const labelAssembler: IAssemblerManager = { if (comp.font instanceof BitmapFont) { assembler = bmfont; }else if (comp.cacheMode === LabelComponent.CacheMode.CHAR){ - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB){ - cc.warn('sorry, subdomain does not support CHAR mode currently!'); + if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME_SUB){ + warn('sorry, subdomain does not support CHAR mode currently!'); } else { assembler = letter; } diff --git a/cocos/3d/ui/assembler/label/letter-font.ts b/cocos/ui/assembler/label/letter-font.ts similarity index 97% rename from cocos/3d/ui/assembler/label/letter-font.ts rename to cocos/ui/assembler/label/letter-font.ts index 6d10f98dea..a96c332cd6 100644 --- a/cocos/3d/ui/assembler/label/letter-font.ts +++ b/cocos/ui/assembler/label/letter-font.ts @@ -27,15 +27,16 @@ * @hidden */ -import { ImageAsset, SpriteFrame, Texture2D } from '../../../../assets'; -import { isUnicodeCJK, isUnicodeSpace, safeMeasureText} from '../../../../core/utils'; -import { mixin } from '../../../../core/utils/js'; -import { Color, Rect, Size, Vec2 } from '../../../../core/math'; -import { GFXBufferTextureCopy } from '../../../../gfx/define'; +import { ImageAsset, SpriteFrame, Texture2D } from '../../../core/assets'; +import { isUnicodeCJK, isUnicodeSpace, safeMeasureText} from '../../../core/utils'; +import { mixin } from '../../../core/utils/js'; +import { Color, Rect, Size, Vec2 } from '../../../core/math'; +import { GFXBufferTextureCopy } from '../../../core/gfx/define'; import { LabelComponent, LabelOutlineComponent } from '../../components'; -// import { UIComponent } from '../../components/ui-component'; import { ISharedLabelData } from './font-utils'; -import { PixelFormat } from '../../../../assets/asset-enum'; +import { PixelFormat } from '../../../core/assets/asset-enum'; +import { director, Director } from '../../../core/director'; +import { loader } from '../../../core/load-pipeline'; // const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutlineComponent, UIComponent); const Overflow = LabelComponent.Overflow; @@ -103,7 +104,7 @@ class LetterTexture { } public destroy () { - this.spriteframe!.destroy(); + // this.spriteframe!.destroy(); this.spriteframe = null; // LabelComponent._canvasPool.put(this._data); } @@ -120,7 +121,7 @@ class LetterTexture { this.height = this.labelInfo.fontSize; } - if (this.canvas.width !== this.width || CC_QQPLAY) { + if (this.canvas.width !== this.width) { this.canvas.width = this.width; } @@ -262,12 +263,12 @@ export class LetterAtlas { this._width = width; this._height = height; - cc.director.on(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); + director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); } public insertLetterTexture (letterTexture: LetterTexture) { const texture = letterTexture.spriteframe; - const device = cc.director.root.device; + const device = director.root!.device; if (!texture || !this.texture || !device || !texture._image) { return null; } @@ -532,7 +533,7 @@ export const letterFont = { } // outline - const outline = /*OUTLINE_SUPPORTED && */_comp.getComponent(LabelOutlineComponent); + const outline:LabelOutlineComponent|null = /*OUTLINE_SUPPORTED && */_comp.getComponent(LabelOutlineComponent); if (outline && outline.enabled) { _labelInfo.isOutlined = true; _labelInfo.margin = outline.width; @@ -561,9 +562,9 @@ export const letterFont = { _fontFamily = comp.font._nativeAsset; } else { - _fontFamily = cc.loader.getRes(comp.font.nativeUrl); + _fontFamily = loader.getRes(comp.font.nativeUrl) || ''; if (!_fontFamily) { - cc.loader.load(comp.font.nativeUrl, (err, fontFamily) => { + loader.load(comp.font.nativeUrl, (err, fontFamily) => { _fontFamily = fontFamily || 'Arial'; if (comp.font){ comp.font._nativeAsset = fontFamily; diff --git a/cocos/3d/ui/assembler/label/letter.ts b/cocos/ui/assembler/label/letter.ts similarity index 91% rename from cocos/3d/ui/assembler/label/letter.ts rename to cocos/ui/assembler/label/letter.ts index 7ce0286032..2137db59d6 100644 --- a/cocos/3d/ui/assembler/label/letter.ts +++ b/cocos/ui/assembler/label/letter.ts @@ -27,14 +27,15 @@ * @category ui-assembler */ -import { addon } from '../../../../core/utils/js'; -import { UI } from '../../../../renderer/ui/ui'; +import { addon } from '../../../core/utils/js'; +import { UI } from '../../../core/renderer/ui/ui'; import { LabelComponent } from '../../components/label-component'; import { fillMeshVertices3D } from '../utils'; import { bmfont } from './bmfont'; import { letterFont} from './letter-font'; +import { Color } from '../../../core/math/color'; -const WHITE = cc.color(255, 255, 255, 255); +const WHITE = new Color(255, 255, 255, 255); /** * letter 组装器 diff --git a/cocos/3d/ui/assembler/label/ttf.ts b/cocos/ui/assembler/label/ttf.ts similarity index 94% rename from cocos/3d/ui/assembler/label/ttf.ts rename to cocos/ui/assembler/label/ttf.ts index 24b6e2b016..983ed7956c 100644 --- a/cocos/3d/ui/assembler/label/ttf.ts +++ b/cocos/ui/assembler/label/ttf.ts @@ -28,13 +28,13 @@ * @category ui-assembler */ -import * as js from '../../../../core/utils/js'; -import { Color, Vec3 } from '../../../../core/math'; -import { UI } from '../../../../renderer/ui/ui'; +import * as js from '../../../core/utils/js'; +import { Color, Vec3 } from '../../../core/math'; +import { UI } from '../../../core/renderer/ui/ui'; import { LabelComponent } from '../../components/label-component'; -import { IAssembler} from '../base'; +import { IAssembler} from '../../../core/renderer/ui/base'; import { ttfUtils } from './ttfUtils'; -import { IRenderData } from '../../../../renderer/ui/renderData'; +import { IRenderData } from '../../../core/renderer/ui/render-data'; const WHITE = Color.WHITE.clone(); diff --git a/cocos/3d/ui/assembler/label/ttfUtils.ts b/cocos/ui/assembler/label/ttfUtils.ts similarity index 96% rename from cocos/3d/ui/assembler/label/ttfUtils.ts rename to cocos/ui/assembler/label/ttfUtils.ts index 2d3fc60acf..b6a83c9449 100644 --- a/cocos/3d/ui/assembler/label/ttfUtils.ts +++ b/cocos/ui/assembler/label/ttfUtils.ts @@ -27,17 +27,19 @@ * @hidden */ -import { SpriteFrame, Texture2D } from '../../../../assets'; -import { Component } from '../../../../components'; -import { fragmentText, safeMeasureText } from '../../../../core/utils'; -import { Color, Size } from '../../../../core/math'; +import { SpriteFrame, Texture2D } from '../../../core/assets'; +import { Component } from '../../../core/components/component'; +import { fragmentText, safeMeasureText, js } from '../../../core/utils'; +import { Color, Size, Vec2 } from '../../../core/math'; import { HorizontalTextAlignment, LabelComponent, LabelOutlineComponent, VerticalTextAlignment } from '../../components'; import { CanvasPool, ISharedLabelData } from './font-utils'; import { LetterRenderTexture } from './letter-font'; +import { loader } from '../../../core/load-pipeline'; +import { logID } from '../../../core/platform/debug'; const Overflow = LabelComponent.Overflow; const WHITE = Color.WHITE.clone(); -const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutlineComponent, Component); +const OUTLINE_SUPPORTED = js.isChildClassOf(LabelOutlineComponent, Component); let _context: CanvasRenderingContext2D | null = null; let _canvas: HTMLCanvasElement | null = null; @@ -128,7 +130,7 @@ export const ttfUtils = { _fontFamily = comp.font._nativeAsset; } else { - cc.loader.load(comp.font.nativeUrl, (err, fontFamily) => { + loader.load(comp.font.nativeUrl, (err, fontFamily) => { _fontFamily = fontFamily || 'Arial'; comp.updateRenderData(true); }); @@ -218,7 +220,7 @@ export const ttfUtils = { firstLinelabelY = _canvasSize.height - lineHeight * (lineCount - 1); } - return cc.v2(labelX, firstLinelabelY); + return new Vec2(labelX, firstLinelabelY); }, _updateTexture () { @@ -298,7 +300,7 @@ export const ttfUtils = { firstLinelabelY = _canvasSize.height - lineHeight * (lineCount - 1); } - return cc.v2(labelX, firstLinelabelY); + return new Vec2(labelX, firstLinelabelY); }, _updateLabelDimensions () { @@ -471,7 +473,7 @@ export const ttfUtils = { startShrinkFontSize = actualFontSize; } if (actualFontSize <= 0) { - cc.logID(4003); + logID(4003); break; } _fontSize = actualFontSize; diff --git a/cocos/3d/ui/assembler/mask/index.ts b/cocos/ui/assembler/mask/index.ts similarity index 66% rename from cocos/3d/ui/assembler/mask/index.ts rename to cocos/ui/assembler/mask/index.ts index e97790df54..5d8e192d9a 100644 --- a/cocos/3d/ui/assembler/mask/index.ts +++ b/cocos/ui/assembler/mask/index.ts @@ -3,10 +3,8 @@ */ import { maskAssembler as mask, maskEndAssembler as maskEnd } from './mask-assembler'; -import { StencilManager } from './stencil-manager'; export { mask, maskEnd, - StencilManager, }; diff --git a/cocos/3d/ui/assembler/mask/mask-assembler.ts b/cocos/ui/assembler/mask/mask-assembler.ts similarity index 90% rename from cocos/3d/ui/assembler/mask/mask-assembler.ts rename to cocos/ui/assembler/mask/mask-assembler.ts index b23f5f2a6c..c93912ead2 100644 --- a/cocos/3d/ui/assembler/mask/mask-assembler.ts +++ b/cocos/ui/assembler/mask/mask-assembler.ts @@ -27,11 +27,11 @@ * @category ui-assembler */ -import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; -import { UI } from '../../../../renderer/ui/ui'; -import { MaskComponent } from '../../components'; -import { IAssembler, IAssemblerManager } from '../base'; -import { StencilManager } from './stencil-manager'; +import { IRenderData, RenderData } from '../../../core/renderer/ui/render-data'; +import { UI } from '../../../core/renderer/ui/ui'; +import { MaskComponent } from '../../components/mask-component'; +import { IAssembler, IAssemblerManager } from '../../../core/renderer/ui/base'; +import { StencilManager } from '../../../core/renderer/ui/stencil-manager'; const _stencilManager = StencilManager.sharedManager!; diff --git a/cocos/3d/ui/assembler/sprite/bar-filled.ts b/cocos/ui/assembler/sprite/bar-filled.ts similarity index 96% rename from cocos/3d/ui/assembler/sprite/bar-filled.ts rename to cocos/ui/assembler/sprite/bar-filled.ts index 2cf128a70c..46b8a2df2a 100644 --- a/cocos/3d/ui/assembler/sprite/bar-filled.ts +++ b/cocos/ui/assembler/sprite/bar-filled.ts @@ -27,13 +27,13 @@ * @category ui-assembler */ -// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager'); -import { Mat4, Vec3 } from '../../../../core/math'; -import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; -import { UI } from '../../../../renderer/ui/ui'; +import { Mat4, Vec3 } from '../../../core/math'; +import { IRenderData, RenderData } from '../../../core/renderer/ui/render-data'; +import { UI } from '../../../core/renderer/ui/ui'; import { SpriteComponent } from '../../components'; -import { IAssembler } from '../base'; +import { IAssembler } from '../../../core/renderer/ui/base'; import { fillVerticesWithoutCalc3D } from '../utils'; +import { errorID } from '../../../core/platform/debug'; const FillType = SpriteComponent.FillType; const matrix = new Mat4(); @@ -167,7 +167,7 @@ export const barFilled: IAssembler = { datas[3].v = quadUV3 + (quadUV7 - quadUV3) * fillEnd; break; default: - cc.errorID(2626); + errorID(2626); break; } @@ -206,7 +206,7 @@ export const barFilled: IAssembler = { t = progressEnd; break; default: - cc.errorID(2626); + errorID(2626); break; } diff --git a/cocos/3d/ui/assembler/sprite/index.ts b/cocos/ui/assembler/sprite/index.ts similarity index 97% rename from cocos/3d/ui/assembler/sprite/index.ts rename to cocos/ui/assembler/sprite/index.ts index 30ecfc954a..effc70bbe8 100644 --- a/cocos/3d/ui/assembler/sprite/index.ts +++ b/cocos/ui/assembler/sprite/index.ts @@ -28,7 +28,7 @@ */ import { SpriteComponent, UIRenderComponent } from '../../components'; -import { IAssemblerManager } from '../base'; +import { IAssemblerManager } from '../../../core/renderer/ui/base'; import { barFilled } from './bar-filled'; import { radialFilled } from './radial-filled'; import { simple } from './simple'; diff --git a/cocos/3d/ui/assembler/sprite/mesh.js b/cocos/ui/assembler/sprite/mesh.js similarity index 98% rename from cocos/3d/ui/assembler/sprite/mesh.js rename to cocos/ui/assembler/sprite/mesh.js index 477915c2a3..6b722dce10 100644 --- a/cocos/3d/ui/assembler/sprite/mesh.js +++ b/cocos/ui/assembler/sprite/mesh.js @@ -23,8 +23,6 @@ THE SOFTWARE. */ -// const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); - let mesh = { useModel: false, diff --git a/cocos/3d/ui/assembler/sprite/radial-filled.ts b/cocos/ui/assembler/sprite/radial-filled.ts similarity index 97% rename from cocos/3d/ui/assembler/sprite/radial-filled.ts rename to cocos/ui/assembler/sprite/radial-filled.ts index 6d95961cf0..e32b3cf7ea 100644 --- a/cocos/3d/ui/assembler/sprite/radial-filled.ts +++ b/cocos/ui/assembler/sprite/radial-filled.ts @@ -27,13 +27,12 @@ * @category ui-assembler */ -// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager'); -import { SpriteFrame } from '../../../../assets'; -import { Mat4, Vec2, Vec3 } from '../../../../core/math'; -import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; -import { UI } from '../../../../renderer/ui/ui'; +import { SpriteFrame } from '../../../core/assets'; +import { Mat4, Vec2, Vec3 } from '../../../core/math'; +import { IRenderData, RenderData } from '../../../core/renderer/ui/render-data'; +import { UI } from '../../../core/renderer/ui/ui'; import { SpriteComponent } from '../../components'; -import { IAssembler } from '../base'; +import { IAssembler } from '../../../core/renderer/ui/base'; import { fillVertices3D } from '../utils'; const PI_2 = Math.PI * 2; diff --git a/cocos/3d/ui/assembler/sprite/simple.ts b/cocos/ui/assembler/sprite/simple.ts similarity index 97% rename from cocos/3d/ui/assembler/sprite/simple.ts rename to cocos/ui/assembler/sprite/simple.ts index d78afbc94d..c67500ae89 100644 --- a/cocos/3d/ui/assembler/sprite/simple.ts +++ b/cocos/ui/assembler/sprite/simple.ts @@ -28,11 +28,11 @@ * @category ui-assembler */ -import { Vec3 } from '../../../../core/math'; -import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; -import { UI } from '../../../../renderer/ui/ui'; +import { Vec3 } from '../../../core/math'; +import { IRenderData, RenderData } from '../../../core/renderer/ui/render-data'; +import { UI } from '../../../core/renderer/ui/ui'; import { SpriteComponent } from '../../components'; -import { IAssembler } from '../base'; +import { IAssembler } from '../../../core/renderer/ui/base'; const vec3_temps: Vec3[] = []; for (let i = 0; i < 4; i++) { vec3_temps.push(new Vec3()); diff --git a/cocos/3d/ui/assembler/sprite/sliced.ts b/cocos/ui/assembler/sprite/sliced.ts similarity index 95% rename from cocos/3d/ui/assembler/sprite/sliced.ts rename to cocos/ui/assembler/sprite/sliced.ts index c15bb35d3c..c23f13c714 100644 --- a/cocos/3d/ui/assembler/sprite/sliced.ts +++ b/cocos/ui/assembler/sprite/sliced.ts @@ -27,12 +27,12 @@ * @category ui-assembler */ -import { IUV, SpriteFrame } from '../../../../assets'; -import { Color, Mat4, Vec3 } from '../../../../core/math'; -import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; -import { UI } from '../../../../renderer/ui/ui'; +import { IUV, SpriteFrame } from '../../../core/assets'; +import { Color, Mat4, Vec3 } from '../../../core/math'; +import { IRenderData, RenderData } from '../../../core/renderer/ui/render-data'; +import { UI } from '../../../core/renderer/ui/ui'; import { SpriteComponent } from '../../components'; -import { IAssembler } from '../base'; +import { IAssembler } from '../../../core/renderer/ui/base'; const vec3_temp = new Vec3(); const matrix = new Mat4(); diff --git a/cocos/3d/ui/assembler/sprite/tiled.ts b/cocos/ui/assembler/sprite/tiled.ts similarity index 96% rename from cocos/3d/ui/assembler/sprite/tiled.ts rename to cocos/ui/assembler/sprite/tiled.ts index 165f2c6506..395194a74c 100644 --- a/cocos/3d/ui/assembler/sprite/tiled.ts +++ b/cocos/ui/assembler/sprite/tiled.ts @@ -23,13 +23,12 @@ THE SOFTWARE. */ -// const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); -import { Mat4, Vec3 } from '../../../../core/math'; -import { RenderData } from '../../../../renderer/ui/renderData'; -import { UI } from '../../../../renderer/ui/ui'; +import { Mat4, Vec3 } from '../../../core/math'; +import { RenderData } from '../../../core/renderer/ui/render-data'; +import { UI } from '../../../core/renderer/ui/ui'; import { SpriteComponent } from '../../components/sprite-component'; -import { UIRenderComponent } from '../../components/ui-render-component'; -import { IAssembler } from '../base'; +import { UIRenderComponent } from '../../../core/components/ui-base/ui-render-component'; +import { IAssembler } from '../../../core/renderer/ui/base'; const matrix = new Mat4(); diff --git a/cocos/3d/ui/assembler/utils.ts b/cocos/ui/assembler/utils.ts similarity index 95% rename from cocos/3d/ui/assembler/utils.ts rename to cocos/ui/assembler/utils.ts index 273d34cff7..086760b15d 100644 --- a/cocos/3d/ui/assembler/utils.ts +++ b/cocos/ui/assembler/utils.ts @@ -2,10 +2,10 @@ * @hidden */ -import { Color, Mat4, Vec3 } from '../../../core/math'; -import { RenderData } from '../../../renderer/ui/renderData'; -import { UI } from '../../../renderer/ui/ui'; -import { INode } from '../../../core/utils/interfaces'; +import { Color, Mat4, Vec3 } from '../../core/math'; +import { RenderData } from '../../core/renderer/ui/render-data'; +import { UI } from '../../core/renderer/ui/ui'; +import { INode } from '../../core/utils/interfaces'; const vec3_temp = new Vec3(); const _worldMatrix = new Mat4(); diff --git a/cocos/3d/ui/components/button-component.ts b/cocos/ui/components/button-component.ts similarity index 97% rename from cocos/3d/ui/components/button-component.ts rename to cocos/ui/components/button-component.ts index ecfa512310..c233ab3680 100644 --- a/cocos/3d/ui/components/button-component.ts +++ b/cocos/ui/components/button-component.ts @@ -29,17 +29,17 @@ * @category ui */ -import { SpriteFrame } from '../../../assets'; -import { Component, EventHandler as ComponentEventHandler } from '../../../components'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { EventMouse, EventTouch, SystemEventType } from '../../../core/platform'; -import { INode } from '../../../core/utils/interfaces'; -import { Color, Vec3 } from '../../../core/math'; -import { ccenum } from '../../../core/value-types/enum'; -import { lerp } from '../../../core/math/utils'; -import { Node } from '../../../scene-graph/node'; +import { SpriteFrame } from '../../core/assets'; +import { Component, EventHandler as ComponentEventHandler } from '../../core/components'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { EventMouse, EventTouch, SystemEventType } from '../../core/platform'; +import { INode } from '../../core/utils/interfaces'; +import { Color, Vec3 } from '../../core/math'; +import { ccenum } from '../../core/value-types/enum'; +import { lerp } from '../../core/math/utils'; +import { Node } from '../../core/scene-graph/node'; import { SpriteComponent } from './sprite-component'; -import { UIRenderComponent } from './ui-render-component'; +import { UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; /** * @zh diff --git a/cocos/3d/ui/components/editbox/edit-box-component.ts b/cocos/ui/components/editbox/edit-box-component.ts similarity index 96% rename from cocos/3d/ui/components/editbox/edit-box-component.ts rename to cocos/ui/components/editbox/edit-box-component.ts index 1c05da8226..8bbe330820 100644 --- a/cocos/3d/ui/components/editbox/edit-box-component.ts +++ b/cocos/ui/components/editbox/edit-box-component.ts @@ -28,21 +28,21 @@ * @category ui */ -import { SpriteFrame } from '../../../../assets/sprite-frame'; -import { Component } from '../../../../components/component'; -import { EventHandler as ComponentEventHandler } from '../../../../components/component-event-handler'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../../core/data/class-decorator'; -import { EventTouch } from '../../../../core/platform'; -import { SystemEventType } from '../../../../core/platform/event-manager/event-enum'; -import { Color, Size } from '../../../../core/math'; +import { SpriteFrame } from '../../../core/assets/sprite-frame'; +import { Component } from '../../../core/components/component'; +import { EventHandler as ComponentEventHandler } from '../../../core/components/component-event-handler'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { EventTouch } from '../../../core/platform'; +import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; +import { Color, Size } from '../../../core/math'; import { LabelComponent, VerticalTextAlignment } from '../label-component'; import { SpriteComponent } from '../sprite-component'; -import { UIRenderComponent } from '../ui-render-component'; -import { UITransformComponent } from '../ui-transfrom-component'; +import { UIRenderComponent } from '../../../core/components/ui-base/ui-render-component'; +import { UITransformComponent } from '../../../core/components/ui-base/ui-transfrom-component'; import { EditBoxImpl } from './edit-box-impl'; import { InputFlag, InputMode, KeyboardReturnType } from './types'; -import { INode } from '../../../../core/utils/interfaces'; -import { Node } from '../../../../scene-graph/node'; +import { INode } from '../../../core/utils/interfaces'; +import { Node } from '../../../core/scene-graph/node'; const LEFT_PADDING = 2; @@ -593,14 +593,14 @@ export class EditBoxComponent extends Component { public _createBackgroundSprite () { if (!this._background) { - this._background = this.node.getComponent(cc.SpriteComponent); + this._background = this.node.getComponent(SpriteComponent); if (!this._background) { - this._background = this.node.addComponent(cc.SpriteComponent); + this._background = this.node.addComponent(SpriteComponent); } } - this._background!.type = cc.SpriteComponent.Type.SLICED; + this._background!.type = SpriteComponent.Type.SLICED; this._background!.spriteFrame = this._backgroundImage; // let background = this._background; // if (!background) { diff --git a/cocos/3d/ui/components/editbox/edit-box-impl.ts b/cocos/ui/components/editbox/edit-box-impl.ts similarity index 88% rename from cocos/3d/ui/components/editbox/edit-box-impl.ts rename to cocos/ui/components/editbox/edit-box-impl.ts index 6aafe8f29e..85ad5936c7 100644 --- a/cocos/3d/ui/components/editbox/edit-box-impl.ts +++ b/cocos/ui/components/editbox/edit-box-impl.ts @@ -30,14 +30,20 @@ * @hidden */ -import { ccclass } from '../../../../core/data/class-decorator'; -import { macro } from '../../../../core/platform/CCMacro'; -import { INode } from '../../../../core/utils/interfaces'; -import { contains } from '../../../../core/utils/misc'; -import { Color, Mat4, Size, Vec3 } from '../../../../core/math'; -import { UIRenderComponent } from '../ui-render-component'; +import { ccclass } from '../../../core/data/class-decorator'; +import { macro } from '../../../core/platform/macro'; +import { INode } from '../../../core/utils/interfaces'; +import { contains } from '../../../core/utils/misc'; +import { Color, Mat4, Size, Vec3 } from '../../../core/math'; +import { UIRenderComponent } from '../../../core/components/ui-base/ui-render-component'; import { EditBoxComponent} from './edit-box-component'; import { InputFlag, InputMode, KeyboardReturnType } from './types'; +import { warnID } from '../../../core/platform/debug'; +import sys from '../../../core/platform/sys'; +import { view, screen } from '../../../core/platform'; +import { director } from '../../../core/director'; +import visibleRect from '../../../core/platform/visible-rect'; +import { game } from '../../../core/game'; // https://segmentfault.com/q/1010000002914610 const SCROLLY = 40; @@ -57,9 +63,9 @@ const polyfill = { zoomInvalid: false, }; -if (cc.sys.OS_ANDROID === cc.sys.os && - (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU || - cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) { +if (sys.OS_ANDROID === sys.os && + (sys.browserType === sys.BROWSER_TYPE_SOUGOU || + sys.browserType === sys.BROWSER_TYPE_360)) { polyfill.zoomInvalid = true; } @@ -90,7 +96,7 @@ export class EditBoxImpl { public _text = ''; public _placeholderText = ''; public _alwaysOnTop = false; - public _size: Size = cc.size(); + public _size: Size = new Size(); public _node: INode | null = null; public _editing = false; public __eventListeners: any = {}; @@ -175,7 +181,7 @@ export class EditBoxImpl { if (this._edTxt) { return document.activeElement === this._edTxt; } - cc.warnID(4700); + warnID(4700); return false; } @@ -309,7 +315,7 @@ export class EditBoxImpl { } public _beginEditing () { - if (cc.sys.isMobile && !this._editing) { + if (sys.isMobile && !this._editing) { // Pre adaptation this._beginEditingOnMobile(); } @@ -322,9 +328,9 @@ export class EditBoxImpl { if (this._edTxt) { this._edTxt.style.display = ''; - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { + if (sys.browserType === sys.BROWSER_TYPE_UC) { setTimeout(startFocus, FOCUS_DELAY_UC); - } else if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) { + } else if (sys.browserType === sys.BROWSER_TYPE_FIREFOX) { setTimeout(startFocus, FOCUS_DELAY_FIREFOX); } else { startFocus(); @@ -345,7 +351,7 @@ export class EditBoxImpl { } }; if (this._editing) { - if (cc.sys.isMobile) { + if (sys.isMobile) { // Delay end editing adaptation to ensure virtual keyboard is disapeared setTimeout(() => { self._endEditingOnMobile(); @@ -416,10 +422,10 @@ export class EditBoxImpl { if (!this._edTxt) { return; } const node = this._node; - let scaleX = cc.view._scaleX; - let scaleY = cc.view._scaleY; - const viewport = cc.view._viewportRect; - const dpr = cc.view._devicePixelRatio; + let scaleX = view.getScaleX(); + let scaleY = view.getScaleY(); + const viewport = view.getViewportRect(); + const dpr = view.getDevicePixelRatio(); node!.getWorldMatrix(_matrix); const transform = node!.uiTransfromComp; @@ -437,12 +443,12 @@ export class EditBoxImpl { // else { // camera = cc.Camera.findCamera(node); // } - const renderComp = node!.getComponent(UIRenderComponent); + const renderComp:UIRenderComponent = node!.getComponent(UIRenderComponent); if (!renderComp) { return false; } // let canvas = cc.CanvasComponent.findView(renderComp); - const canvas = cc.director.root.ui.getScreen(renderComp.visibility); + const canvas = director.root!.ui.getScreen(renderComp.visibility); if (!canvas) { return; } @@ -451,7 +457,7 @@ export class EditBoxImpl { canvas.node.getWorldRT(_matrix_temp); const m12 = _matrix_temp.m12; const m13 = _matrix_temp.m13; - const center = cc.visibleRect.center; + const center = visibleRect.center; _matrix_temp.m12 = center.x - (_matrix_temp.m00 * m12 + _matrix_temp.m04 * m13); _matrix_temp.m13 = center.y - (_matrix_temp.m01 * m12 + _matrix_temp.m05 * m13); @@ -460,15 +466,15 @@ export class EditBoxImpl { scaleX /= dpr; scaleY /= dpr; - const container = cc.game.container; + const container = game.container; let a = _matrix_temp.m00 * scaleX; const b = _matrix.m01; const c = _matrix.m04; let d = _matrix_temp.m05 * scaleY; - let offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft); + let offsetX = parseInt((container && container.style.paddingLeft) || '0'); offsetX += viewport.x / dpr; - let offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom); + let offsetY = parseInt((container && container.style.paddingBottom) || '0'); offsetY += viewport.y / dpr; const tx = _matrix_temp.m12 * scaleX + offsetX; const ty = _matrix_temp.m13 * scaleY + offsetY; @@ -489,8 +495,8 @@ export class EditBoxImpl { public _adjustEditBoxPosition () { this._node!.getWorldMatrix(_matrix); const y = _matrix.m13; - const windowHeight = cc.visibleRect.height; - const windowWidth = cc.visibleRect.width; + const windowHeight = visibleRect.height; + const windowWidth = visibleRect.width; let factor = 0.5; if (windowWidth > windowHeight) { factor = 0.7; @@ -523,29 +529,30 @@ export class EditBoxImpl { }; window.addEventListener('orientationchange', this.__orientationChanged); - if (cc.view.isAutoFullScreenEnabled()) { + if (view.isAutoFullScreenEnabled()) { this.__fullscreen = true; - cc.view.enableAutoFullScreen(false); - cc.screen.exitFullScreen(); + view.enableAutoFullScreen(false); + screen.exitFullScreen(); } else { this.__fullscreen = false; } - this.__autoResize = cc.view._resizeWithBrowserSize; - cc.view.resizeWithBrowserSize(false); + this.__autoResize = view._resizeWithBrowserSize; + view.resizeWithBrowserSize(false); _currentEditBoxImpl = this; } // Called after keyboard disappeared to readapte the game view public _endEditingOnMobile () { if (this.__rotateScreen) { - cc.game.container.style['-webkit-transform'] = 'rotate(90deg)'; - cc.game.container.style.transform = 'rotate(90deg)'; + if (game.container) { + game.container.style['-webkit-transform'] = 'rotate(90deg)'; + game.container.style.transform = 'rotate(90deg)'; + } - const view = cc.view; const width = view._originalDesignResolutionSize.width; const height = view._originalDesignResolutionSize.height; if (width > 0) { - view.setDesignResolutionSize(width, height, view._resolutionPolicy); + view.setDesignResolutionSize(width, height, view.getResolutionPolicy()); } this.__rotateScreen = false; } @@ -555,7 +562,7 @@ export class EditBoxImpl { } if (this.__fullscreen) { - cc.view.enableAutoFullScreen(true); + view.enableAutoFullScreen(true); } // In case focus on editBox A from editBox B @@ -563,7 +570,7 @@ export class EditBoxImpl { // whilte B enable resizeWithBrowserSize // Only _currentEditBoxImpl can enable resizeWithBrowserSize if (this.__autoResize && _currentEditBoxImpl === this) { - cc.view.resizeWithBrowserSize(true); + view.resizeWithBrowserSize(true); } } @@ -625,7 +632,9 @@ export class EditBoxImpl { } public _addDomToGameContainer () { - cc.game.container.appendChild(this._edTxt); + if (game.container && this._edTxt) { + game.container.appendChild(this._edTxt); + } } public removeDom () { @@ -646,9 +655,9 @@ export class EditBoxImpl { cbs.keypress = null; cbs.blur = null; - const hasChild = contains(cc.game.container, edTxt); - if (hasChild) { - cc.game.container.removeChild(edTxt); + const hasChild = contains(game.container, edTxt); + if (hasChild && game.container) { + game.container.removeChild(edTxt); } } this._edTxt = null; @@ -697,7 +706,7 @@ function registerInputEventListener (tmpEdTxt: HTMLInputElement | HTMLTextAreaEl editBoxImpl.editing = true; } - if (cc.sys.isMobile) { + if (sys.isMobile) { editBoxImpl._beginEditingOnMobile(); } @@ -718,7 +727,7 @@ function registerInputEventListener (tmpEdTxt: HTMLInputElement | HTMLTextAreaEl if (!isTextarea) { editBoxImpl.text = this.value; editBoxImpl._endEditing(); - cc.game.canvas.focus(); + game.canvas && game.canvas.focus(); } } }; diff --git a/cocos/3d/ui/components/editbox/types.ts b/cocos/ui/components/editbox/types.ts similarity index 98% rename from cocos/3d/ui/components/editbox/types.ts rename to cocos/ui/components/editbox/types.ts index 31b4ac50e8..b7403de073 100644 --- a/cocos/3d/ui/components/editbox/types.ts +++ b/cocos/ui/components/editbox/types.ts @@ -27,7 +27,7 @@ * @hidden */ -import { Enum } from '../../../../core/value-types'; +import { Enum } from '../../../core/value-types'; /** * 键盘的返回键类型。 * @readonly diff --git a/cocos/3d/ui/components/graphics-component.ts b/cocos/ui/components/graphics-component.ts similarity index 93% rename from cocos/3d/ui/components/graphics-component.ts rename to cocos/ui/components/graphics-component.ts index 4ccb6924ac..38fb38f060 100644 --- a/cocos/3d/ui/components/graphics-component.ts +++ b/cocos/ui/components/graphics-component.ts @@ -28,16 +28,18 @@ * @category ui */ -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Color } from '../../../core/math'; -import { Model } from '../../../renderer'; -import { UI } from '../../../renderer/ui/ui'; -import { Material } from '../../assets'; -import { RenderableComponent } from '../../framework/renderable-component'; -import { IAssembler } from '../assembler/base'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { Color } from '../../core/math'; +import { Model } from '../../core/renderer'; +import { UI } from '../../core/renderer/ui/ui'; +import { Material } from '../../core/assets/material'; +import { RenderableComponent } from '../../core/3d/framework/renderable-component'; +import { IAssembler } from '../../core/renderer/ui/base'; import { LineCap, LineJoin } from '../assembler/graphics/types'; import { Impl } from '../assembler/graphics/webgl/impl'; -import { InstanceMaterialType, UIRenderComponent } from '../components/ui-render-component'; +import { InstanceMaterialType, UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; +import { director } from '../../core/director'; +import { builtinResMgr } from '../../core/3d/builtin'; /** * @zh @@ -203,7 +205,7 @@ export class GraphicsComponent extends UIRenderComponent { } public onLoad (){ - this._sceneGetter = cc.director.root.ui.getRenderSceneGetter(); + this._sceneGetter = director.root!.ui.getRenderSceneGetter(); } public onEnable () { @@ -469,7 +471,7 @@ export class GraphicsComponent extends UIRenderComponent { if (this._sharedMaterial) { mat = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false); } else { - mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-base-material'), new RenderableComponent(), CC_EDITOR ? true : false); + mat = Material.getInstantiatedMaterial(builtinResMgr.get('ui-base-material'), new RenderableComponent(), CC_EDITOR ? true : false); mat.recompileShaders({ USE_LOCAL: true }); mat.onLoaded(); } diff --git a/cocos/3d/ui/components/index.ts b/cocos/ui/components/index.ts similarity index 85% rename from cocos/3d/ui/components/index.ts rename to cocos/ui/components/index.ts index b9d100aa9e..dee67a6804 100644 --- a/cocos/3d/ui/components/index.ts +++ b/cocos/ui/components/index.ts @@ -2,8 +2,6 @@ * @hidden */ -export { CanvasComponent } from './canvas-component'; -export { UIComponent } from './ui-component'; export { ButtonComponent } from './button-component'; export { EditBoxComponent } from './editbox/edit-box-component'; export * from './label-component'; @@ -18,8 +16,6 @@ export { SpriteComponent } from './sprite-component'; export { ToggleComponent } from './toggle-component'; export { ToggleContainerComponent } from './toggle-container-component'; export { UIModelComponent } from './ui-model-component'; -export { UIRenderComponent } from './ui-render-component'; -export { UITransformComponent } from './ui-transfrom-component'; export { ViewGroupComponent } from './view-group-component'; export { WebviewComponent } from './webview/webView-component'; export { WidgetComponent } from './widget-component'; diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/ui/components/label-component.ts similarity index 96% rename from cocos/3d/ui/components/label-component.ts rename to cocos/ui/components/label-component.ts index c7f743553f..621940eff7 100644 --- a/cocos/3d/ui/components/label-component.ts +++ b/cocos/ui/components/label-component.ts @@ -28,14 +28,16 @@ * @category ui */ -import { BitmapFont, Font, ImageAsset, SpriteFrame, Texture2D } from '../../../assets'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { ccenum } from '../../../core/value-types/enum'; -import { UI } from '../../../renderer/ui/ui'; +import { BitmapFont, Font, ImageAsset, SpriteFrame, Texture2D } from '../../core/assets'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { ccenum } from '../../core/value-types/enum'; +import { UI } from '../../core/renderer/ui/ui'; import { FontAtlas } from '../assembler/label/bmfontUtils'; import { CanvasPool, ISharedLabelData } from '../assembler/label/font-utils'; import { LetterRenderTexture } from '../assembler/label/letter-font'; -import { UIRenderComponent } from './ui-render-component'; +import { UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; +import { warnID } from '../../core/platform/debug'; +import sys from '../../core/platform/sys'; /** * @zh @@ -376,7 +378,7 @@ export class LabelComponent extends UIRenderComponent { // this._isSystemFontUsed = false; if (typeof value === 'string') { - cc.warnID(4000); + warnID(4000); } if (this._renderData) { @@ -641,7 +643,7 @@ export class LabelComponent extends UIRenderComponent { this._assemblerData = null; if (this._ttfSpriteFrame) { - this._ttfSpriteFrame.destroy(); + // this._ttfSpriteFrame.destroy(); this._ttfSpriteFrame = null; } @@ -736,7 +738,7 @@ export class LabelComponent extends UIRenderComponent { onBMFontTextureLoaded(); } } else { - if (this.cacheMode === CacheMode.CHAR && cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { + if (this.cacheMode === CacheMode.CHAR && sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME_SUB) { this._letterTexture = this._assembler!.getAssemblerData(); this._texture = this._letterTexture; } else if (!this._ttfSpriteFrame) { diff --git a/cocos/3d/ui/components/label-outline-component.ts b/cocos/ui/components/label-outline-component.ts similarity index 94% rename from cocos/3d/ui/components/label-outline-component.ts rename to cocos/ui/components/label-outline-component.ts index 92b269f46a..eb56b577d0 100644 --- a/cocos/3d/ui/components/label-outline-component.ts +++ b/cocos/ui/components/label-outline-component.ts @@ -28,9 +28,9 @@ * @category ui */ -import { Component } from '../../../components'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Color } from '../../../core/math'; +import { Component } from '../../core/components/component'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { Color } from '../../core/math'; import { LabelComponent } from './label-component'; /** diff --git a/cocos/3d/ui/components/layout-component.ts b/cocos/ui/components/layout-component.ts similarity index 98% rename from cocos/3d/ui/components/layout-component.ts rename to cocos/ui/components/layout-component.ts index 81a8606d82..d5a47ab875 100644 --- a/cocos/3d/ui/components/layout-component.ts +++ b/cocos/ui/components/layout-component.ts @@ -28,13 +28,14 @@ * @category ui */ -import { Component } from '../../../components/component'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Rect, Size, Vec2, Vec3 } from '../../../core/math'; -import { ccenum } from '../../../core/value-types/enum'; -import { UITransformComponent } from './ui-transfrom-component'; -import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; -import { INode } from '../../../core/utils/interfaces'; +import { Component } from '../../core/components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { Rect, Size, Vec2, Vec3 } from '../../core/math'; +import { ccenum } from '../../core/value-types/enum'; +import { UITransformComponent } from '../../core/components/ui-base/ui-transfrom-component'; +import { SystemEventType } from '../../core/platform/event-manager/event-enum'; +import { INode } from '../../core/utils/interfaces'; +import { director, Director } from '../../core/director'; const NodeEvent = SystemEventType; /** * @zh @@ -515,7 +516,7 @@ export class LayoutComponent extends Component { } private _addEventListeners () { - cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this); + director.on(Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this); this.node.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); this.node.on(NodeEvent.CHILD_ADDED, this._childAdded, this); @@ -525,7 +526,7 @@ export class LayoutComponent extends Component { } private _removeEventListeners () { - cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this); + director.off(Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this); this.node.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); this.node.off(NodeEvent.CHILD_ADDED, this._childAdded, this); diff --git a/cocos/3d/ui/components/mask-component.ts b/cocos/ui/components/mask-component.ts similarity index 93% rename from cocos/3d/ui/components/mask-component.ts rename to cocos/ui/components/mask-component.ts index f8e914daf7..8d58b2798a 100644 --- a/cocos/3d/ui/components/mask-component.ts +++ b/cocos/ui/components/mask-component.ts @@ -28,16 +28,17 @@ * @category ui */ -import { SpriteFrame } from '../../../assets'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; -import { clamp, Color, Mat4, Size, Vec2, Vec3 } from '../../../core/math'; -import { ccenum } from '../../../core/value-types/enum'; -import { UI } from '../../../renderer/ui/ui'; +import { SpriteFrame } from '../../core/assets'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { SystemEventType } from '../../core/platform/event-manager/event-enum'; +import { clamp, Color, Mat4, Vec2, Vec3 } from '../../core/math'; +import { ccenum } from '../../core/value-types/enum'; +import { UI } from '../../core/renderer/ui/ui'; import { GraphicsComponent } from './graphics-component'; -import { InstanceMaterialType, UIRenderComponent } from './ui-render-component'; -import { INode } from '../../../core/utils/interfaces'; -import { Node } from '../../../scene-graph'; +import { InstanceMaterialType, UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; +import { Node } from '../../core/scene-graph'; +import { view } from '../../core/platform'; +import visibleRect from '../../core/platform/visible-rect'; const _worldMatrix = new Mat4(); const _vec2_temp = new Vec2(); @@ -48,7 +49,7 @@ function _calculateCircle (center: Vec3, radius: Vec3, segements: number) { _circlepoints.length = 0; const anglePerStep = Math.PI * 2 / segements; for (let step = 0; step < segements; ++step) { - _circlepoints.push(cc.v3(radius.x * Math.cos(anglePerStep * step) + center.x, + _circlepoints.push(new Vec3(radius.x * Math.cos(anglePerStep * step) + center.x, radius.y * Math.sin(anglePerStep * step) + center.y, 0)); } @@ -316,14 +317,14 @@ export class MaskComponent extends UIRenderComponent { this._activateMaterial(); this.node.on(SystemEventType.TRANSFORM_CHANGED, this._nodeStateChange, this); - cc.view.on('design-resolution-changed', this._updateClearGraphics, this); + view.on('design-resolution-changed', this._updateClearGraphics, this); } public onDisable () { super.onDisable(); this._disableGraphics(); this.node.off(SystemEventType.TRANSFORM_CHANGED, this._nodeStateChange); - cc.view.off('design-resolution-changed', this._updateClearGraphics); + view.off('design-resolution-changed', this._updateClearGraphics); } public onDestroy () { @@ -500,7 +501,7 @@ export class MaskComponent extends UIRenderComponent { return; } console.log('resolution changed'); - const size = cc.visibleRect; + const size = visibleRect; this._clearGraphics.node.setWorldPosition(size.width / 2, size.height / 2, 0); this._clearGraphics.clear(); this._clearGraphics.rect(-size.width / 2, -size.height / 2, size.width, size.height); @@ -525,8 +526,8 @@ export class MaskComponent extends UIRenderComponent { if (this._type === MaskType.RECT) { graphics.rect(x, y, width, height); } else if (this._type === MaskType.ELLIPSE) { - const center = cc.v3(x + width / 2, y + height / 2, 0); - const radius = cc.v3(width / 2, height / 2, 0, + const center = new Vec3(x + width / 2, y + height / 2, 0); + const radius = new Vec3(width / 2, height / 2, 0, ); const points = _calculateCircle(center, radius, this._segments); for (let i = 0; i < points.length; ++i) { diff --git a/cocos/3d/ui/components/page-view-component.ts b/cocos/ui/components/page-view-component.ts similarity index 97% rename from cocos/3d/ui/components/page-view-component.ts rename to cocos/ui/components/page-view-component.ts index 546c17f382..1136d80dcd 100644 --- a/cocos/3d/ui/components/page-view-component.ts +++ b/cocos/ui/components/page-view-component.ts @@ -27,16 +27,17 @@ * @category ui */ -import { EventHandler as ComponentEventHandler } from '../../../components'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { EventTouch, SystemEventType } from '../../../core/platform'; -import { Vec2, Vec3 } from '../../../core/math'; -import { ccenum } from '../../../core/value-types/enum'; +import { EventHandler as ComponentEventHandler } from '../../core/components'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { EventTouch, SystemEventType } from '../../core/platform'; +import { Vec2, Vec3 } from '../../core/math'; +import { ccenum } from '../../core/value-types/enum'; import { LayoutComponent } from './layout-component'; import { PageViewIndicatorComponent } from './page-view-indicator-component'; import { ScrollViewComponent } from './scroll-view-component'; import { ScrollBarComponent } from './scroll-bar-component'; -import { INode } from '../../../core/utils/interfaces'; +import { INode } from '../../core/utils/interfaces'; +import { warnID } from '../../core/platform/debug'; const _temp_vec2 = new Vec2(); @@ -410,7 +411,7 @@ export class PageViewComponent extends ScrollViewComponent { if (!page || !this.content) { return; } const index = this._pages.indexOf(page); if (index === -1) { - cc.warnID(4300, page.name); + warnID(4300, page.name); return; } this.removePageAtIndex(index); diff --git a/cocos/3d/ui/components/page-view-indicator-component.ts b/cocos/ui/components/page-view-indicator-component.ts similarity index 93% rename from cocos/3d/ui/components/page-view-indicator-component.ts rename to cocos/ui/components/page-view-indicator-component.ts index d96bbb4481..b2a24b6c7d 100644 --- a/cocos/3d/ui/components/page-view-indicator-component.ts +++ b/cocos/ui/components/page-view-indicator-component.ts @@ -28,17 +28,16 @@ * @category ui */ -import { SpriteFrame } from '../../../assets'; -import { Component } from '../../../components'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Color, Size } from '../../../core/math'; -import { ccenum } from '../../../core/value-types/enum'; -import { Node } from '../../../scene-graph'; +import { SpriteFrame } from '../../core/assets'; +import { Component } from '../../core/components'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { Color, Size } from '../../core/math'; +import { ccenum } from '../../core/value-types/enum'; +import { Node } from '../../core/scene-graph'; import { LayoutComponent } from './layout-component'; import { PageViewComponent } from './page-view-component'; import { SpriteComponent } from './sprite-component'; -import { UIRenderComponent } from './ui-render-component'; -import { INode } from '../../../core/utils/interfaces'; +import { UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; const _color = new Color(); diff --git a/cocos/3d/ui/components/progress-bar-component.ts b/cocos/ui/components/progress-bar-component.ts similarity index 92% rename from cocos/3d/ui/components/progress-bar-component.ts rename to cocos/ui/components/progress-bar-component.ts index cdaf2eac45..15651fee14 100644 --- a/cocos/3d/ui/components/progress-bar-component.ts +++ b/cocos/ui/components/progress-bar-component.ts @@ -28,12 +28,13 @@ * @category ui */ -import { Component} from '../../../components'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Size, Vec2, Vec3 } from '../../../core/math'; -import { Enum } from '../../../core/value-types'; -import { clamp01 } from '../../../core/math/utils'; +import { Component} from '../../core/components'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { Size, Vec2, Vec3 } from '../../core/math'; +import { Enum } from '../../core/value-types'; +import { clamp01 } from '../../core/math/utils'; import { SpriteComponent } from './sprite-component'; +import { warn } from '../../core/platform/debug'; /** * @zh @@ -283,8 +284,8 @@ export class ProgressBarComponent extends Component { // handling filled mode if (this._mode === Mode.FILLED) { - if (this._barSprite.type !== cc.SpriteComponent.Type.FILLED) { - cc.warn('ProgressBar FILLED mode only works when barSprite\'s Type is FILLED!'); + if (this._barSprite.type !== SpriteComponent.Type.FILLED) { + warn('ProgressBar FILLED mode only works when barSprite\'s Type is FILLED!'); } else { if (this._reverse) { actualLenth = actualLenth * -1; @@ -292,7 +293,7 @@ export class ProgressBarComponent extends Component { this._barSprite.fillRange = actualLenth; } } else { - if (this._barSprite.type !== cc.SpriteComponent.Type.FILLED) { + if (this._barSprite.type !== SpriteComponent.Type.FILLED) { const anchorOffsetX = anchorPoint.x - entityAnchorPoint.x; const anchorOffsetY = anchorPoint.y - entityAnchorPoint.y; @@ -303,7 +304,7 @@ export class ProgressBarComponent extends Component { entity.setAnchorPoint(anchorPoint); entity.setContentSize(finalContentSize); } else { - cc.warn('ProgressBar non-FILLED mode only works when barSprite\'s Type is non-FILLED!'); + warn('ProgressBar non-FILLED mode only works when barSprite\'s Type is non-FILLED!'); } } } diff --git a/cocos/3d/ui/components/rich-text-component.ts b/cocos/ui/components/rich-text-component.ts similarity index 96% rename from cocos/3d/ui/components/rich-text-component.ts rename to cocos/ui/components/rich-text-component.ts index 95cc1e9fbd..0e68271088 100644 --- a/cocos/3d/ui/components/rich-text-component.ts +++ b/cocos/ui/components/rich-text-component.ts @@ -28,20 +28,22 @@ * @category ui */ -import { Font, SpriteAtlas, TTFFont } from '../../../assets'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { EventTouch } from '../../../core/platform'; -import { fragmentText, HtmlTextParser, IHtmlTextParserResultObj, IHtmlTextParserStack, isUnicodeCJK, isUnicodeSpace } from '../../../core/utils'; -import Pool from '../../../core/utils/pool'; -import { Color, Vec2 } from '../../../core/math'; -import { PrivateNode } from '../../../scene-graph'; +import { Font, SpriteAtlas, TTFFont } from '../../core/assets'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { EventTouch } from '../../core/platform'; +import { fragmentText, HtmlTextParser, IHtmlTextParserResultObj, IHtmlTextParserStack, isUnicodeCJK, isUnicodeSpace } from '../../core/utils'; +import Pool from '../../core/utils/pool'; +import { Color, Vec2 } from '../../core/math'; +import { PrivateNode, Node } from '../../core/scene-graph'; import { HorizontalTextAlignment, LabelComponent, VerticalTextAlignment } from './label-component'; import { LabelOutlineComponent } from './label-outline-component'; import { SpriteComponent } from './sprite-component'; -import { UIComponent } from './ui-component'; -import { UIRenderComponent } from './ui-render-component'; -import { UITransformComponent } from './ui-transfrom-component'; -import { INode } from '../../../core/utils/interfaces'; +import { UIComponent } from '../../core/components/ui-base/ui-component'; +import { UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; +import { UITransformComponent } from '../../core/components/ui-base/ui-transfrom-component'; +import { INode } from '../../core/utils/interfaces'; +import { assert, warnID } from '../../core/platform/debug'; +import { loader } from '../../core/load-pipeline'; const _htmlTextParser = new HtmlTextParser(); const RichTextChildName = 'RICHTEXT_CHILD'; @@ -79,7 +81,7 @@ const pool = new Pool((labelSeg: ILabelSegment) => { return false; } if (CC_DEV) { - cc.assert(!labelSeg.node.parent, 'Recycling node\'s parent should be null!'); + assert(!labelSeg.node.parent, 'Recycling node\'s parent should be null!'); } if (!cc.isValid(labelSeg.node)) { return false; @@ -417,11 +419,11 @@ export class RichTextComponent extends UIComponent { } private _addEventListeners () { - this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); + this.node.on(Node.EventType.TOUCH_END, this._onTouchEnded, this); } private _removeEventListeners () { - this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); + this.node.off(Node.EventType.TOUCH_END, this._onTouchEnded, this); } private _updateLabelSegmentTextAttributes () { @@ -443,7 +445,7 @@ export class RichTextComponent extends UIComponent { } else { const self = this; - cc.loader.load(this._font.nativeUrl, (err, fontFamily) => { + loader.load(this._font.nativeUrl, (err, fontFamily) => { self._layoutDirty = true; self._updateRichText(); }); @@ -699,8 +701,8 @@ export class RichTextComponent extends UIComponent { const spriteNode = new PrivateNode(RichTextChildImageName); const spriteComponent = spriteNode.addComponent(SpriteComponent); spriteNode.setAnchorPoint(0, 0); - spriteComponent!.type = cc.SpriteComponent.Type.SLICED; - spriteComponent!.sizeMode = cc.SpriteComponent.SizeMode.CUSTOM; + spriteComponent!.type = SpriteComponent.Type.SLICED; + spriteComponent!.sizeMode = SpriteComponent.SizeMode.CUSTOM; // @ts-ignore this.node.addChild(spriteNode); const obj: ILabelSegment = { @@ -759,7 +761,7 @@ export class RichTextComponent extends UIComponent { } } else { - cc.warnID(4400); + warnID(4400); } } diff --git a/cocos/3d/ui/components/scroll-bar-component.ts b/cocos/ui/components/scroll-bar-component.ts similarity index 97% rename from cocos/3d/ui/components/scroll-bar-component.ts rename to cocos/ui/components/scroll-bar-component.ts index 075067d17a..398b67f68b 100644 --- a/cocos/3d/ui/components/scroll-bar-component.ts +++ b/cocos/ui/components/scroll-bar-component.ts @@ -28,12 +28,12 @@ * @category ui */ -import { Component } from '../../../components'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { INode } from '../../../core/utils/interfaces'; -import { Color, Size, Vec2, Vec3 } from '../../../core/math'; -import { ccenum } from '../../../core/value-types/enum'; -import { clamp01 } from '../../../core/math/utils'; +import { Component } from '../../core/components'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { INode } from '../../core/utils/interfaces'; +import { Color, Size, Vec2, Vec3 } from '../../core/math'; +import { ccenum } from '../../core/value-types/enum'; +import { clamp01 } from '../../core/math/utils'; import { ScrollViewComponent } from './scroll-view-component'; import { SpriteComponent } from './sprite-component'; @@ -90,7 +90,7 @@ export class ScrollBarComponent extends Component { return; } this._handle = value; - this.onScroll(cc.v2(0, 0)); + this.onScroll(new Vec3(0, 0, 0)); } /** diff --git a/cocos/3d/ui/components/scroll-view-component.ts b/cocos/ui/components/scroll-view-component.ts similarity index 98% rename from cocos/3d/ui/components/scroll-view-component.ts rename to cocos/ui/components/scroll-view-component.ts index de707be8cc..8ab43a0088 100644 --- a/cocos/3d/ui/components/scroll-view-component.ts +++ b/cocos/ui/components/scroll-view-component.ts @@ -28,17 +28,18 @@ * @category ui */ -import { EventHandler as ComponentEventHandler } from '../../../components'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Event } from '../../../core/event'; -import { EventMouse, EventTouch, SystemEventType, Touch } from '../../../core/platform'; -import { Size, Vec2, Vec3 } from '../../../core/math'; -import { ccenum } from '../../../core/value-types/enum'; +import { EventHandler as ComponentEventHandler } from '../../core/components'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { Event } from '../../core/event'; +import { EventMouse, EventTouch, SystemEventType, Touch } from '../../core/platform'; +import { Size, Vec2, Vec3 } from '../../core/math'; +import { ccenum } from '../../core/value-types/enum'; import { LayoutComponent } from './layout-component'; import { ScrollBarComponent } from './scroll-bar-component'; import { ViewGroupComponent } from './view-group-component'; -import { INode } from '../../../core/utils/interfaces'; -import { Node } from '../../../scene-graph/node'; +import { INode } from '../../core/utils/interfaces'; +import { Node } from '../../core/scene-graph/node'; +import { director, Director } from '../../core/director'; const NodeEvent = SystemEventType; @@ -759,7 +760,7 @@ export class ScrollViewComponent extends ViewGroupComponent { // Because widget component will adjust content position and scrollview position is correct after visit // So this event could make sure the content is on the correct position after loading. if (this._content) { - cc.director.once(cc.Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this); + director.once(Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this); } } @@ -837,9 +838,6 @@ export class ScrollViewComponent extends ViewGroupComponent { let deltaMove = new Vec3(); let wheelPrecision = -0.1; - if (CC_JSB) { - wheelPrecision = -7; - } if (this.vertical) { deltaMove = new Vec3(0, event.getScrollY() * wheelPrecision, 0); } @@ -944,7 +942,7 @@ export class ScrollViewComponent extends ViewGroupComponent { protected _calculateBoundary () { if (this.content) { // refresh content size - const layout = this.content.getComponent(LayoutComponent); + const layout:LayoutComponent = this.content.getComponent(LayoutComponent); if (layout && layout.enabledInHierarchy) { layout.updateLayout(); } @@ -966,7 +964,7 @@ export class ScrollViewComponent extends ViewGroupComponent { // this is for nested scrollview protected _hasNestedViewGroup (event?: Event, captureListeners?: any) { - if (!event || event.eventPhase !== cc.Event.CAPTURING_PHASE) { + if (!event || event.eventPhase !== Event.CAPTURING_PHASE) { return; } @@ -1221,7 +1219,7 @@ export class ScrollViewComponent extends ViewGroupComponent { } } - cc.Component.EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]); + ComponentEventHandler.emitEvents(this.scrollEvents, this, eventMap[event]); this.node.emit(event, this); } @@ -1265,7 +1263,7 @@ export class ScrollViewComponent extends ViewGroupComponent { // This is for Scrollview as children of a Button protected _stopPropagationIfTargetIsMe (event?: Event) { - if (event && event.eventPhase === cc.Event.AT_TARGET && event.target === this.node) { + if (event && event.eventPhase === Event.AT_TARGET && event.target === this.node) { event.propagationStopped = true; } } diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/ui/components/slider-component.ts similarity index 93% rename from cocos/3d/ui/components/slider-component.ts rename to cocos/ui/components/slider-component.ts index ebd1d1cb8c..43785bf71e 100644 --- a/cocos/3d/ui/components/slider-component.ts +++ b/cocos/ui/components/slider-component.ts @@ -28,12 +28,12 @@ * @category ui */ -import { Component, EventHandler as ComponentEventHandler } from '../../../components'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { EventTouch, SystemEventType, Touch } from '../../../core/platform'; -import { Vec3 } from '../../../core/math'; -import { ccenum } from '../../../core/value-types/enum'; -import { clamp01 } from '../../../core/math/utils'; +import { Component, EventHandler } from '../../core/components'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { EventTouch, SystemEventType, Touch } from '../../core/platform'; +import { Vec3 } from '../../core/math'; +import { ccenum } from '../../core/value-types/enum'; +import { clamp01 } from '../../core/math/utils'; import { SpriteComponent } from './sprite-component'; const _tempPos = new Vec3(); @@ -136,9 +136,9 @@ export class SliderComponent extends Component { * 滑动器组件事件回调函数。 */ @property({ - type: ComponentEventHandler, + type: EventHandler, }) - public slideEvents: ComponentEventHandler[] = []; + public slideEvents: EventHandler[] = []; @property private _handle: SpriteComponent | null = null; @property @@ -223,7 +223,7 @@ export class SliderComponent extends Component { protected _onTouchEnded (event?: EventTouch) { this._dragging = false; this._touchHandle = false; - this._offset = cc.v2(); + this._offset = new Vec3(); if (event) { event.propagationStopped = true; @@ -243,7 +243,7 @@ export class SliderComponent extends Component { } protected _emitSlideEvent () { - cc.Component.EventHandler.emitEvents(this.slideEvents, this); + EventHandler.emitEvents(this.slideEvents, this); this.node.emit('slide', this); } diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/ui/components/sprite-component.ts similarity index 96% rename from cocos/3d/ui/components/sprite-component.ts rename to cocos/ui/components/sprite-component.ts index 2b90695999..3f1b9d5d39 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/ui/components/sprite-component.ts @@ -28,14 +28,14 @@ * @category ui */ -import { SpriteAtlas, SpriteFrame } from '../../../assets'; -import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; -import { Vec2 } from '../../../core/math'; -import { ccenum } from '../../../core/value-types/enum'; -import { clamp } from '../../../core/math/utils'; -import { UI } from '../../../renderer/ui/ui'; -import { UIRenderComponent } from './ui-render-component'; +import { SpriteAtlas, SpriteFrame, AssetLibrary } from '../../core/assets'; +import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { SystemEventType } from '../../core/platform/event-manager/event-enum'; +import { Vec2 } from '../../core/math'; +import { ccenum } from '../../core/value-types/enum'; +import { clamp } from '../../core/math/utils'; +import { UI } from '../../core/renderer/ui/ui'; +import { UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; /** * @zh @@ -575,7 +575,7 @@ export class SpriteComponent extends UIRenderComponent { if (spriteFrame.atlasUuid.length > 0) { if (!this._atlas || this._atlas._uuid !== spriteFrame.atlasUuid) { const self = this; - cc.AssetLibrary.loadAsset(spriteFrame.atlasUuid, (err, asset) => { + AssetLibrary.loadAsset(spriteFrame.atlasUuid, (err, asset) => { self._atlas = asset; }); } diff --git a/cocos/3d/ui/components/toggle-component.ts b/cocos/ui/components/toggle-component.ts similarity index 98% rename from cocos/3d/ui/components/toggle-component.ts rename to cocos/ui/components/toggle-component.ts index 66f3fa1bea..0b2f234800 100644 --- a/cocos/3d/ui/components/toggle-component.ts +++ b/cocos/ui/components/toggle-component.ts @@ -28,8 +28,8 @@ * @category ui */ -import { EventHandler as ComponentEventHandler } from '../../../components'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { EventHandler as ComponentEventHandler } from '../../core/components'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; import { ButtonComponent } from './button-component'; import { SpriteComponent } from './sprite-component'; import { ToggleContainerComponent } from './toggle-container-component'; diff --git a/cocos/3d/ui/components/toggle-container-component.ts b/cocos/ui/components/toggle-container-component.ts similarity index 98% rename from cocos/3d/ui/components/toggle-container-component.ts rename to cocos/ui/components/toggle-container-component.ts index db013cbdd6..787524eac9 100644 --- a/cocos/3d/ui/components/toggle-container-component.ts +++ b/cocos/ui/components/toggle-container-component.ts @@ -28,8 +28,8 @@ * @category ui */ -import { Component, EventHandler as ComponentEventHandler } from '../../../components'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { Component, EventHandler as ComponentEventHandler } from '../../core/components'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; import { ToggleComponent} from './toggle-component'; /** diff --git a/cocos/3d/ui/components/ui-model-component.ts b/cocos/ui/components/ui-model-component.ts similarity index 88% rename from cocos/3d/ui/components/ui-model-component.ts rename to cocos/ui/components/ui-model-component.ts index 31f5f53379..19d1b526c1 100644 --- a/cocos/3d/ui/components/ui-model-component.ts +++ b/cocos/ui/components/ui-model-component.ts @@ -28,12 +28,13 @@ * @category ui */ -import { ccclass, executionOrder, menu } from '../../../core/data/class-decorator'; -import { RenderPriority } from '../../../pipeline/define'; -import { UI } from '../../../renderer/ui/ui'; -import { Material } from '../../assets'; -import { RenderableComponent } from '../../framework/renderable-component'; -import { UIComponent } from './ui-component'; +import { ccclass, executionOrder, menu } from '../../core/data/class-decorator'; +import { RenderPriority } from '../../core/pipeline/define'; +import { UI } from '../../core/renderer/ui/ui'; +import { Material } from '../../core/assets'; +import { RenderableComponent } from '../../core/3d/framework/renderable-component'; +import { UIComponent } from '../../core/components/ui-base/ui-component'; +import { director } from '../../core/director'; /** * @zh @@ -58,7 +59,7 @@ export class UIModelComponent extends UIComponent { return; } - this._modelComponent._sceneGetter = cc.director.root.ui.getRenderSceneGetter(); + this._modelComponent._sceneGetter = director.root!.ui.getRenderSceneGetter(); this._modelComponent.recreateModel(); } diff --git a/cocos/3d/ui/components/ui-reorder-component.ts b/cocos/ui/components/ui-reorder-component.ts similarity index 92% rename from cocos/3d/ui/components/ui-reorder-component.ts rename to cocos/ui/components/ui-reorder-component.ts index 578edcf944..5c177a14c7 100644 --- a/cocos/3d/ui/components/ui-reorder-component.ts +++ b/cocos/ui/components/ui-reorder-component.ts @@ -27,8 +27,8 @@ * @category ui */ -import { ccclass, disallowMultiple, executeInEditMode, executionOrder, menu } from '../../../core/data/class-decorator'; -import { UIComponent } from './ui-component'; +import { ccclass, disallowMultiple, executeInEditMode, executionOrder, menu } from '../../core/data/class-decorator'; +import { UIComponent } from '../../core/components/ui-base/ui-component'; /** * @zh diff --git a/cocos/3d/ui/components/view-group-component.ts b/cocos/ui/components/view-group-component.ts similarity index 93% rename from cocos/3d/ui/components/view-group-component.ts rename to cocos/ui/components/view-group-component.ts index de2da935da..c970a5e4a0 100644 --- a/cocos/3d/ui/components/view-group-component.ts +++ b/cocos/ui/components/view-group-component.ts @@ -36,8 +36,8 @@ * 可通过 cc.ViewGroupComponent 获取该组件。 */ -import { Component } from '../../../components'; -import { ccclass, executionOrder } from '../../../core/data/class-decorator'; +import { Component } from '../../core/components'; +import { ccclass, executionOrder } from '../../core/data/class-decorator'; @ccclass('cc.ViewGroupComponent') @executionOrder(110) diff --git a/cocos/3d/ui/components/webview/webView-component.ts b/cocos/ui/components/webview/webView-component.ts similarity index 97% rename from cocos/3d/ui/components/webview/webView-component.ts rename to cocos/ui/components/webview/webView-component.ts index 5a1f0b8e82..b89573503a 100644 --- a/cocos/3d/ui/components/webview/webView-component.ts +++ b/cocos/ui/components/webview/webView-component.ts @@ -24,9 +24,9 @@ THE SOFTWARE. */ -import { EventHandler } from '../../../../components/component-event-handler'; -import { ccclass, executionOrder, menu, property } from '../../../../core/data/class-decorator'; -import { UIComponent } from '../ui-component'; +import { EventHandler } from '../../../core/components/component-event-handler'; +import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { UIComponent } from '../../../core/components/ui-base/ui-component'; import { WebViewEventType, WebViewImpl } from './webview-impl'; /** diff --git a/cocos/3d/ui/components/webview/webview-impl.ts b/cocos/ui/components/webview/webview-impl.ts similarity index 94% rename from cocos/3d/ui/components/webview/webview-impl.ts rename to cocos/ui/components/webview/webview-impl.ts index bb718518de..3a2e97dc06 100644 --- a/cocos/3d/ui/components/webview/webview-impl.ts +++ b/cocos/ui/components/webview/webview-impl.ts @@ -23,12 +23,14 @@ THE SOFTWARE. */ -import { ccclass } from '../../../../core/data/class-decorator'; -import sys from '../../../../core/platform/CCSys'; -import { misc } from '../../../../core/utils'; -import { INode } from '../../../../core/utils/interfaces'; -import { Mat4 } from '../../../../core/math'; -import { UIRenderComponent } from '../ui-render-component'; +import { ccclass } from '../../../core/data/class-decorator'; +import sys from '../../../core/platform/sys'; +import { misc } from '../../../core/utils'; +import { INode } from '../../../core/utils/interfaces'; +import { Mat4 } from '../../../core/math'; +import { UIRenderComponent } from '../../../core/components/ui-base/ui-render-component'; +import { logID, log } from '../../../core/platform/debug'; +import { view } from '../../../core/platform/view'; const _mat4_temp = new Mat4(); @@ -165,7 +167,7 @@ export class WebViewImpl { * Stop loading */ public stopLoading () { - cc.logID(7800); + logID(7800); } /** @@ -185,7 +187,7 @@ export class WebViewImpl { * Determine whether to go back */ public canGoBack () { - cc.logID(7801); + logID(7801); return true; } @@ -193,7 +195,7 @@ export class WebViewImpl { * Determine whether to go forward */ public canGoForward () { - cc.logID(7802); + logID(7802); return true; } @@ -203,7 +205,7 @@ export class WebViewImpl { public goBack () { try { if (WebViewImpl.Polyfill.closeHistory) { - return cc.logID(7803); + return logID(7803); } const iframe = this._iframe; if (iframe) { @@ -213,7 +215,7 @@ export class WebViewImpl { } } } catch (err) { - cc.log(err); + log(err); } } @@ -223,7 +225,7 @@ export class WebViewImpl { public goForward () { try { if (WebViewImpl.Polyfill.closeHistory) { - return cc.logID(7804); + return logID(7804); } const iframe = this._iframe; if (iframe) { @@ -233,7 +235,7 @@ export class WebViewImpl { } } } catch (err) { - cc.log(err); + log(err); } } @@ -260,7 +262,7 @@ export class WebViewImpl { * Limited scale */ public setScalesPageToFit () { - cc.logID(7805); + logID(7805); } /** @@ -327,9 +329,9 @@ export class WebViewImpl { this._w = contentSize.width; this._h = contentSize.height; - let scaleX = cc.view._scaleX; - let scaleY = cc.view._scaleY; - const dpr = cc.view._devicePixelRatio; + let scaleX = view.getScaleX(); + let scaleY = view.getScaleY(); + const dpr = view.getDevicePixelRatio(); scaleX /= dpr; scaleY /= dpr; diff --git a/cocos/3d/ui/components/widget-component.ts b/cocos/ui/components/widget-component.ts similarity index 92% rename from cocos/3d/ui/components/widget-component.ts rename to cocos/ui/components/widget-component.ts index 9f671826f2..d48d85dde4 100644 --- a/cocos/3d/ui/components/widget-component.ts +++ b/cocos/ui/components/widget-component.ts @@ -28,13 +28,16 @@ * @category ui */ -import { Component} from '../../../components'; -import { ccclass, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../../core/data/class-decorator'; -import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; -import { Size, Vec3 } from '../../../core/math'; -import { ccenum } from '../../../core/value-types/enum'; -import { INode } from '../../../core/utils/interfaces'; -import { UITransformComponent } from './ui-transfrom-component'; +import { Component} from '../../core/components'; +import { ccclass, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../core/data/class-decorator'; +import { SystemEventType } from '../../core/platform/event-manager/event-enum'; +import { Size, Vec3 } from '../../core/math'; +import { ccenum } from '../../core/value-types/enum'; +import { Node } from '../../core/scene-graph/node'; +import { UITransformComponent } from '../../core/components/ui-base/ui-transfrom-component'; +import { widgetManager } from './widget-manager'; +import { INode } from '../../core/utils/interfaces'; +import { errorID } from '../../core/platform/debug'; /** * @zh @@ -128,7 +131,7 @@ export class WidgetComponent extends Component { * 指定一个对齐目标,只能是当前节点的其中一个父节点,默认为空,为空时表示当前父节点。 */ @property({ - type: cc.Node, + type: Node, }) get target () { return this._target; @@ -144,7 +147,7 @@ export class WidgetComponent extends Component { this._registerTargetEvents(); if (CC_EDITOR /*&& !cc.engine._isPlaying*/ && this.node.parent) { // adjust the offsets to keep the size and position unchanged after target chagned - cc._widgetManager.updateOffsetsToStayPut(this); + widgetManager.updateOffsetsToStayPut(this); } this._validateTargetInDEV(); @@ -543,7 +546,7 @@ export class WidgetComponent extends Component { * ``` */ public updateAlignment () { - cc._widgetManager.updateAlignment(this.node); + widgetManager.updateAlignment(this.node as Node); } public _validateTargetInDEV () { @@ -555,7 +558,7 @@ export class WidgetComponent extends Component { if (target) { const isParent = this.node !== target && this.node.isChildOf(target); if (!isParent) { - cc.errorID(6500); + errorID(6500); this._target = null; } } @@ -572,7 +575,7 @@ export class WidgetComponent extends Component { public onEnable () { this.node.getPosition(this._lastPos); this.node.getContentSize(this._lastSize); - cc._widgetManager.add(this); + widgetManager.add(this); this._registerTargetEvents(); } @@ -588,7 +591,7 @@ export class WidgetComponent extends Component { } public onDisable () { - cc._widgetManager.remove(this); + widgetManager.remove(this); this._unregisterTargetEvents(); } @@ -673,7 +676,7 @@ export class WidgetComponent extends Component { if (CC_EDITOR && this.node.parent) { // adjust the offsets to keep the size and position unchanged after alignment chagned - cc._widgetManager.updateOffsetsToStayPut(this, flag); + widgetManager.updateOffsetsToStayPut(this, flag); } } else { if (isHorizontal) { @@ -704,30 +707,7 @@ export class WidgetComponent extends Component { } } +// @ts-ignore cc.WidgetComponent = WidgetComponent; -/** - * @zh - * 开启后仅会在 onEnable 的当帧结束时对齐一次,然后立刻禁用当前组件。 - * 这样便于脚本或动画继续控制当前节点。 - * 注意:onEnable 时所在的那一帧仍然会进行对齐。 - * @property {Boolean} isAlignOnce - * @default false - * @deprecated - */ -// Object.defineProperty(Widget.prototype, 'isAlignOnce', { -// get() { -// if (CC_DEBUG) { -// cc.warn('`widget.isAlignOnce` is deprecated, use `widget.alignMode === cc.Widget.AlignMode.ONCE` instead please.'); -// } -// return this.alignMode === AlignMode.ONCE; -// } -// set(value) { -// if (CC_DEBUG) { -// cc.warn('`widget.isAlignOnce` is deprecated, use `widget.alignMode = cc.Widget.AlignMode.*` instead please.'); -// } -// this.alignMode = value ? AlignMode.ONCE : AlignMode.ALWAYS; -// } -// }); - // cc.Widget = module.exports = Widget; diff --git a/cocos/3d/ui/components/widget-manager.ts b/cocos/ui/components/widget-manager.ts similarity index 90% rename from cocos/3d/ui/components/widget-manager.ts rename to cocos/ui/components/widget-manager.ts index 04c82718ce..d0382d339b 100644 --- a/cocos/3d/ui/components/widget-manager.ts +++ b/cocos/ui/components/widget-manager.ts @@ -28,13 +28,19 @@ * @hidden */ -import { SystemEventType } from '../../../core/platform/event-manager/event-enum'; -import { array } from '../../../core/utils/js'; -import { Vec2, Vec3 } from '../../../core/math'; -import { CanvasComponent } from './canvas-component'; -import { UIRenderComponent } from './ui-render-component'; +import { SystemEventType } from '../../core/platform/event-manager/event-enum'; +import { array } from '../../core/utils/js'; +import { Vec2, Vec3 } from '../../core/math'; +import { CanvasComponent } from '../../core/components/ui-base/canvas-component'; +import { UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; import { AlignFlags, AlignMode, WidgetComponent } from './widget-component'; -import { INode } from '../../../core/utils/interfaces'; +import { Node } from '../../core/scene-graph/node'; +import { Scene } from '../../core/scene-graph'; +import { Director, director } from '../../core/director'; +import { View } from '../../core/platform/view'; +import visibleRect from '../../core/platform/visible-rect'; +import sys from '../../core/platform/sys'; +import { INode } from '../../core/utils/interfaces'; const _tempPos = new Vec3(); const _zeroVec3 = new Vec3(); @@ -42,17 +48,18 @@ const _defaultAnchor = new Vec2(); // returns a readonly size of the node export function getReadonlyNodeSize (parent: INode) { - if (parent instanceof cc.Scene) { + if (parent instanceof Scene) { + // @ts-ignore if (CC_EDITOR) { // const canvasComp = parent.getComponentInChildren(CanvasComponent); - if (!cc.view) { + if (!View.instance) { throw new Error('cc.view uninitiated'); } - return cc.view.getDesignResolutionSize(); + return View.instance.getDesignResolutionSize(); } - return cc.visibleRect; + return visibleRect; } else { return parent.getContentSize(); } @@ -99,7 +106,7 @@ const tInverseTranslate = new Vec3(); const tInverseScale = new Vec3(1, 1, 1); // align to borders by adjusting node's position and size (ignore rotation) -function align (node: INode, widget: WidgetComponent) { +function align (node: Node, widget: WidgetComponent) { const hasTarget = widget.target; let target: any; const inverseTranslate = tInverseTranslate; @@ -108,14 +115,15 @@ function align (node: INode, widget: WidgetComponent) { target = hasTarget; // inverseTranslate = tInverseTranslate; // inverseScale = tInverseScale; - computeInverseTransForTarget(node, target, inverseTranslate, inverseScale); + computeInverseTransForTarget(node as INode, target, inverseTranslate, inverseScale); } else { target = node.parent; } const targetSize = getReadonlyNodeSize(target); - const isScene = target instanceof cc.Scene; + const isScene = target instanceof Scene; const targetAnchor = isScene ? _defaultAnchor : target.getAnchorPoint(); + // @ts-ignore const isRoot = !CC_EDITOR && isScene; node.getPosition(_tempPos); let x = _tempPos.x; @@ -128,8 +136,8 @@ function align (node: INode, widget: WidgetComponent) { let localRight = 0; const targetWidth = targetSize.width; if (isRoot) { - localLeft = cc.visibleRect.left.x; - localRight = cc.visibleRect.right.x; + localLeft = visibleRect.left.x; + localRight = visibleRect.right.x; } else { localLeft = -targetAnchor.x * targetWidth; localRight = localLeft + targetWidth; @@ -187,8 +195,8 @@ function align (node: INode, widget: WidgetComponent) { let localBottom = 0; const targetHeight = targetSize.height; if (isRoot) { - localBottom = cc.visibleRect.bottom.y; - localTop = cc.visibleRect.top.y; + localBottom = visibleRect.bottom.y; + localTop = visibleRect.top.y; } else { localBottom = -targetAnchor.y * targetHeight; localTop = localBottom + targetHeight; @@ -245,13 +253,15 @@ function align (node: INode, widget: WidgetComponent) { Vec3.set(widget._lastPos, x, y, _tempPos.z); } -function visitNode (node: INode) { +function visitNode (node: Node) { const widget = node.getComponent(WidgetComponent); if (widget) { + // @ts-ignore if (CC_DEV) { widget._validateTargetInDEV(); } align(node, widget); + // @ts-ignore if ((!CC_EDITOR || widgetManager.animationState!.animatedSinceLastFrame) && widget.alignMode !== AlignMode.ALWAYS) { widget.enabled = false; } else { @@ -308,7 +318,7 @@ function refreshScene () { // } // } - const scene = cc.director.getScene(); + const scene = director.getScene(); if (scene) { widgetManager.isAligning = true; if (widgetManager._nodesOrderDirty) { @@ -348,7 +358,7 @@ function refreshScene () { for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) { widget = activeWidgets[iterator.i]; if (widget._dirty) { - align(widget.node, widget); + align(widget.node as Node, widget); widget._dirty = false; } } @@ -379,13 +389,16 @@ function adjustWidgetToAllowMovingInEditor (this: WidgetComponent, eventType: Sy const delta = new Vec3(newPos); delta.subtract(oldPos); - let target = self.node.parent!; + let target = self.node.parent; const inverseScale = new Vec3(1, 1, 1); if (self.target) { - target = self.target; + target = self.target as INode; computeInverseTransForTarget(self.node, target, new Vec3(), inverseScale); } + if (!target) { + return; + } const targetSize = getReadonlyNodeSize(target); const deltaInPercent = new Vec3(); @@ -430,12 +443,15 @@ function adjustWidgetToAllowResizingInEditor (this: WidgetComponent/*, oldSize: const oldSize = this._lastSize; const delta = new Vec3(newSize.width - oldSize.width, newSize.height - oldSize.height, 0); - let target = self.node.parent!; + let target = self.node.parent; const inverseScale = new Vec3(1, 1, 1); if (self.target) { - target = self.target; + target = self.target as INode; computeInverseTransForTarget(self.node, target, new Vec3(), inverseScale); } + if (!target) { + return; + } const targetSize = getReadonlyNodeSize(target); const deltaInPercent = new Vec3(); @@ -467,9 +483,9 @@ function adjustWidgetToAnchorChanged (this: WidgetComponent) { const activeWidgets: WidgetComponent[] = []; // updateAlignment from scene to node recursively -function updateAlignment (node: INode) { +function updateAlignment (node: Node) { const parent = node.parent; - if (parent && cc.Node.isNode(parent)) { + if (parent && Node.isNode(parent)) { updateAlignment(parent); } @@ -494,26 +510,26 @@ export const widgetManager = cc._widgetManager = { } : null, init (director) { - director.on(cc.Director.EVENT_AFTER_UPDATE, refreshScene); + director.on(Director.EVENT_AFTER_UPDATE, refreshScene); if (CC_EDITOR /*&& cc.engine*/) { // cc.engien extends eventTarget // cc.engine.on('design-resolution-changed', this.onResized.bind(this)); } else { - if (cc.sys.isMobile) { + if (sys.isMobile) { window.addEventListener('resize', this.onResized.bind(this)); } else { - cc.view.on('design-resolution-changed', this.onResized, this); + View.instance.on('design-resolution-changed', this.onResized, this); } } }, add (widget: WidgetComponent) { this._nodesOrderDirty = true; // if (CC_EDITOR && !cc.engine.isPlaying) { - const renderComp = widget.node.getComponent(UIRenderComponent); + const renderComp:UIRenderComponent = widget.node.getComponent(UIRenderComponent); if (renderComp) { - const canvasComp = cc.director.root.ui.getScreen(renderComp.visibility); + const canvasComp = director.root!.ui.getScreen(renderComp.visibility); if (canvasComp && canvasList.indexOf(canvasComp) === -1) { canvasList.push(canvasComp); canvasComp.node.on('design-resolution-changed', this.onResized, this); @@ -533,13 +549,13 @@ export const widgetManager = cc._widgetManager = { // } }, onResized () { - const scene = cc.director.getScene(); + const scene = director.getScene(); if (scene) { this.refreshWidgetOnResized(scene); } }, - refreshWidgetOnResized (node: INode) { - if (cc.Node.isNode(node)){ + refreshWidgetOnResized (node: Node) { + if (Node.isNode(node)){ const widget = node.getComponent(WidgetComponent); // const widget: WidgetComponent | null = null; if (widget && widget.alignFlags === AlignMode.ALWAYS) { @@ -565,8 +581,8 @@ export const widgetManager = cc._widgetManager = { const zero = new Vec3(); const one = new Vec3(1, 1, 1); if (widget.target) { - widgetParent = widget.target; - computeInverseTransForTarget(widgetNode, widgetParent!, zero, one); + widgetParent = widget.target as INode; + computeInverseTransForTarget(widgetNode, widgetParent, zero, one); } if (!e) { @@ -637,3 +653,7 @@ export const widgetManager = cc._widgetManager = { AlignMode, AlignFlags, }; + +director.on(Director.EVENT_INIT, function () { + widgetManager.init(director); +}); \ No newline at end of file diff --git a/cocos/3d/ui/index.ts b/cocos/ui/index.ts similarity index 79% rename from cocos/3d/ui/index.ts rename to cocos/ui/index.ts index 97252fd02f..e2a16875c1 100644 --- a/cocos/3d/ui/index.ts +++ b/cocos/ui/index.ts @@ -16,11 +16,11 @@ import { simple, sliced, spriteAssembler, - StencilManager, ttf, } from './assembler'; -import { MeshBuffer } from './mesh-buffer'; -import * as UIVertexFormat from './ui-vertex-format'; +import { MeshBuffer } from '../core/renderer/ui/mesh-buffer'; +import * as UIVertexFormat from '../core/renderer/ui/ui-vertex-format'; +import { StencilManager } from '../core/renderer/ui/stencil-manager'; export * from './components'; diff --git a/exports/audio.ts b/exports/audio.ts index 890987c2f9..da6a6d73a8 100644 --- a/exports/audio.ts +++ b/exports/audio.ts @@ -2,9 +2,9 @@ * @hidden */ -export { AudioClip } from '../cocos/3d/assets/audio/clip'; +export { AudioClip } from '../cocos/audio/assets/clip'; -import { AudioSourceComponent } from '../cocos/3d/framework/audio-source-component'; +import { AudioSourceComponent } from '../cocos/audio/audio-source-component'; export { AudioSourceComponent }; cc.AudioSourceComponent = AudioSourceComponent; \ No newline at end of file diff --git a/exports/base.ts b/exports/base.ts index 6450b5bd29..261577632e 100644 --- a/exports/base.ts +++ b/exports/base.ts @@ -3,33 +3,22 @@ */ import '../predefine'; -import '../cocos/legacy'; +import '../cocos/core/legacy'; // LOAD ENGINE CORE -export * from '../cocos/scene-graph'; export * from '../cocos/core'; -import * as renderer from '../cocos/renderer'; +import * as renderer from '../cocos/core/renderer'; export { renderer }; cc.renderer = renderer; -export * from '../cocos/assets'; -export * from '../cocos/load-pipeline'; -export * from '../cocos/components'; -export * from '../cocos/3d'; -export * from '../cocos/gfx'; -import '../cocos/pipeline'; export * from '../extensions/ccpool/node-pool'; const cclegacy = cc; export { cclegacy }; -export * from '../cocos/deprecated'; -export { vmath } from '../cocos/vmath'; - -export * from '../cocos/animation'; - -import * as primitives from '../cocos/3d/primitive'; +import * as primitives from '../cocos/core/primitive'; export { primitives, }; -cc.primitives = primitives; \ No newline at end of file +cc.primitives = primitives; +export * from '../cocos/core/primitive/primitive'; \ No newline at end of file diff --git a/exports/gfx-webgl.ts b/exports/gfx-webgl.ts index 8379202dce..3644eb2053 100644 --- a/exports/gfx-webgl.ts +++ b/exports/gfx-webgl.ts @@ -2,5 +2,5 @@ * @hidden */ -import { WebGLGFXDevice } from '../cocos/gfx/webgl/webgl-device'; +import { WebGLGFXDevice } from '../cocos/core/gfx/webgl/webgl-device'; cc.WebGLGFXDevice = WebGLGFXDevice; diff --git a/exports/gfx-webgl2.ts b/exports/gfx-webgl2.ts index de4b1c4d4c..c259146ab2 100644 --- a/exports/gfx-webgl2.ts +++ b/exports/gfx-webgl2.ts @@ -2,5 +2,5 @@ * @hidden */ -import { WebGL2GFXDevice } from '../cocos/gfx/webgl2/webgl2-device'; +import { WebGL2GFXDevice } from '../cocos/core/gfx/webgl2/webgl2-device'; cc.WebGL2GFXDevice = WebGL2GFXDevice; diff --git a/exports/particle.ts b/exports/particle.ts new file mode 100644 index 0000000000..8ad1de84dd --- /dev/null +++ b/exports/particle.ts @@ -0,0 +1,5 @@ +/** + * @hidden + */ + +export * from '../cocos/particle'; \ No newline at end of file diff --git a/exports/physics-ammo.ts b/exports/physics-ammo.ts index 028a77dd9c..e9571cc66f 100644 --- a/exports/physics-ammo.ts +++ b/exports/physics-ammo.ts @@ -2,4 +2,4 @@ * @hidden */ -// import '../cocos/3d/physics/ammo/instantiate'; +// import '../physics/ammo/instantiate'; diff --git a/exports/physics-builtin.ts b/exports/physics-builtin.ts index 85d6c050fa..d159c2278e 100644 --- a/exports/physics-builtin.ts +++ b/exports/physics-builtin.ts @@ -2,5 +2,5 @@ * @hidden */ -import '../cocos/3d/physics/cocos/instantiate'; -export * from '../cocos/3d/physics/export-api'; +import '../cocos/physics/cocos/instantiate'; +export * from '../cocos/physics/export-api'; diff --git a/exports/physics-cannon.ts b/exports/physics-cannon.ts index 482e429eda..ab045dce28 100644 --- a/exports/physics-cannon.ts +++ b/exports/physics-cannon.ts @@ -2,5 +2,5 @@ * @hidden */ -import '../cocos/3d/physics/cannon/instantiate'; -export * from '../cocos/3d/physics/export-api'; +import '../cocos/physics/cannon/instantiate'; +export * from '../cocos/physics/export-api'; diff --git a/exports/physics-framework.ts b/exports/physics-framework.ts index 35032f2cbc..6f22c7abe5 100644 --- a/exports/physics-framework.ts +++ b/exports/physics-framework.ts @@ -2,12 +2,12 @@ * @hidden */ -import { BoxColliderComponent } from '../cocos/3d/framework/physics/collider/box-collider-component'; -import { ColliderComponent } from '../cocos/3d/framework/physics/collider/collider-component'; -import { SphereColliderComponent } from '../cocos/3d/framework/physics/collider/sphere-collider-component'; -import { RigidBodyComponent } from '../cocos/3d/framework/physics/rigid-body-component'; +import { BoxColliderComponent } from '../cocos/physics/components/collider/box-collider-component'; +import { ColliderComponent } from '../cocos/physics/components/collider/collider-component'; +import { SphereColliderComponent } from '../cocos/physics/components/collider/sphere-collider-component'; +import { RigidBodyComponent } from '../cocos/physics/components/rigid-body-component'; -export * from '../cocos/3d/framework/physics'; +export * from '../cocos/physics/components'; export { ColliderComponent, BoxColliderComponent, diff --git a/exports/terrain.ts b/exports/terrain.ts new file mode 100644 index 0000000000..763b689145 --- /dev/null +++ b/exports/terrain.ts @@ -0,0 +1,5 @@ +/** + * @hidden + */ + + export * from '../cocos/terrain'; \ No newline at end of file diff --git a/exports/ui.ts b/exports/ui.ts new file mode 100644 index 0000000000..30b1c4dd7f --- /dev/null +++ b/exports/ui.ts @@ -0,0 +1,5 @@ +/** + * @hidden + */ + +export * from '../cocos/ui'; \ No newline at end of file diff --git a/extensions/ccpool/node-pool.ts b/extensions/ccpool/node-pool.ts index a01ad2dd81..1d8622b5e2 100644 --- a/extensions/ccpool/node-pool.ts +++ b/extensions/ccpool/node-pool.ts @@ -2,8 +2,8 @@ * @hidden */ -import { Component } from '../../cocos/components/component'; -import { Node } from '../../cocos/scene-graph'; +import { Component } from '../../cocos/core/components/component'; +import { Node } from '../../cocos/core/scene-graph'; /**************************************************************************** Copyright (c) 2016 Chukong Technologies Inc. diff --git a/extensions/dragonbones/CCSlot.js b/extensions/dragonbones/CCSlot.js index ce59f5116b..44d39a3e9c 100644 --- a/extensions/dragonbones/CCSlot.js +++ b/extensions/dragonbones/CCSlot.js @@ -24,7 +24,7 @@ ****************************************************************************/ const math = require('../../cocos2d/core/renderer/render-engine').math; -const BlendFactor = require('../../cocos2d/core/platform/CCMacro'); +const BlendFactor = require('../../cocos2d/core/platform/macro'); const BinaryOffset = dragonBones.BinaryOffset; const BoneType = dragonBones.BoneType; diff --git a/extensions/videoplayer/video-player-impl.js b/extensions/videoplayer/video-player-impl.js index e9da47228c..16c7485f6a 100644 --- a/extensions/videoplayer/video-player-impl.js +++ b/extensions/videoplayer/video-player-impl.js @@ -24,7 +24,7 @@ ****************************************************************************/ const utils = require('../core/platform/utils'); -const sys = require('../core/platform/CCSys'); +const sys = require('../core/platform/sys'); const renderEngine = require('../core/renderer/render-engine'); const math = renderEngine.math; diff --git a/index.ts b/index.ts index 3f1973a676..de460dd67f 100644 --- a/index.ts +++ b/index.ts @@ -5,8 +5,11 @@ export * from './exports/base'; export * from './exports/gfx-webgl'; export * from './exports/gfx-webgl2'; +export * from './exports/audio'; +export * from './exports/particle'; +export * from './exports/ui'; export * from './exports/tween'; export * from './exports/physics-framework'; export * from './exports/physics-builtin'; export * from './exports/physics-cannon'; -export * from './exports/audio'; +export * from './exports/terrain'; diff --git a/predefine.js b/predefine.ts similarity index 97% rename from predefine.js rename to predefine.ts index 68221d81de..d18f88c8f8 100644 --- a/predefine.js +++ b/predefine.ts @@ -122,7 +122,8 @@ // PREDEFINE // window may be undefined when first load engine from editor -var _global = typeof window === 'undefined' ? global : window; +// @ts-ignore +const _global = typeof window === 'undefined' ? global : window; /** * !#en @@ -132,7 +133,7 @@ var _global = typeof window === 'undefined' ? global : window; * @module cc * @main cc */ -let cc = _global.cc = _global.cc || {}; +const cc = _global.cc = _global.cc || {}; // For internal usage cc.internal = cc.internal || {}; @@ -164,7 +165,6 @@ if (CC_BUILD) { _global.CC_DEV = CC_DEV; _global.CC_DEBUG = CC_DEBUG; _global.CC_JSB = CC_JSB; - _global.CC_WECHATGAME_SUB = CC_WECHATGAMESUB; _global.CC_WECHATGAME = CC_WECHATGAME; _global.CC_QQPLAY = CC_QQPLAY; _global.CC_RUNTIME = CC_RUNTIME; @@ -176,6 +176,7 @@ if (CC_BUILD) { else { // Defauled value for editor defineMacro('CC_TEST', defined('tap') || defined('QUnit')); + // @ts-ignore defineMacro('CC_EDITOR', defined('Editor') && defined('process') && ('electron' in process.versions)); defineMacro('CC_PREVIEW', !CC_EDITOR); defineMacro('CC_DEV', true); // (CC_EDITOR && !CC_BUILD) || CC_PREVIEW || CC_TEST @@ -184,6 +185,7 @@ else { defineMacro('CC_WECHATGAME_SUB', !!(defined('wx') && wx.getSharedCanvas)); defineMacro('CC_WECHATGAME', !!(defined('wx') && (wx.getSystemInfoSync || wx.getSharedCanvas))); defineMacro('CC_QQPLAY', defined('bk')); + // @ts-ignore defineMacro('CC_RUNTIME', 'function' === typeof loadRuntime); defineMacro('CC_SUPPORT_JIT', !(CC_WECHATGAME || CC_QQPLAY || CC_RUNTIME)); defineMacro('CC_PHYSICS_BUILT_IN', true); diff --git a/scripts/module-division/division-config.json b/scripts/module-division/division-config.json index 4d5b76f30e..8ea4b6453c 100644 --- a/scripts/module-division/division-config.json +++ b/scripts/module-division/division-config.json @@ -25,6 +25,18 @@ } ] }, + { + "text": "UI", + "description": "UI module", + "entry": "ui", + "default": true + }, + { + "text": "Particle System", + "description": "Particle system module", + "entry": "particle", + "default": true + }, { "text": "Physics", "description": "Physics(implementation).", @@ -57,6 +69,12 @@ "description": "Integrate tween.js in Creator 3D.", "entry": "tween", "default": true + }, + { + "text": "Terrain", + "description": "Integrate tween.js in Creator 3D.", + "entry": "terrain", + "default": true } ] } \ No newline at end of file diff --git a/tests/animation/test-animation-clip.js b/tests/animation/animation-clip.test.js similarity index 100% rename from tests/animation/test-animation-clip.js rename to tests/animation/animation-clip.test.js diff --git a/tests/animation/animation-curve.test.ts b/tests/animation/animation-curve.test.ts index 001115fde3..4f9774efe9 100644 --- a/tests/animation/animation-curve.test.ts +++ b/tests/animation/animation-curve.test.ts @@ -1,7 +1,7 @@ -import { AnimCurve, RatioSampler, sampleAnimationCurve } from '../../cocos/animation/animation-curve'; -import { BoundTarget, ComponentModifier, TargetModifier, HierachyModifier } from '../../cocos/animation/target-modifier'; -import { Node } from '../../cocos/scene-graph'; +import { AnimCurve, RatioSampler, sampleAnimationCurve } from '../../cocos/core/animation/animation-curve'; +import { BoundTarget, ComponentModifier, TargetModifier, HierachyModifier } from '../../cocos/core/animation/target-modifier'; +import { Node } from '../../cocos/core/scene-graph'; test('sample from animation curve', () => { const curve = new AnimCurve({ diff --git a/tests/animation/animation.test.js b/tests/animation/animation.test.js new file mode 100644 index 0000000000..b464c1aab9 --- /dev/null +++ b/tests/animation/animation.test.js @@ -0,0 +1,1432 @@ +import { Node } from '../../cocos/core/scene-graph/node'; +import { AnimationClip, AnimationState } from '../../cocos/core/animation'; + +test('curve types', function () { + var entity = new Node(); + + var clip = new AnimationClip(); + clip.duration = 3; + clip.sample = 10; + clip.curveDatas = { + '/' : { + props: { + 'position': { + keys: 0, + // easingMethod: "cubicInOut", + values: [ + { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + { + "__type__": "cc.Vec3", + "x": 100, + "y": 0, + "z": 0 + }, + { + "__type__": "cc.Vec3", + "x": 200, + "y": 0, + "z": 0 + }, + { + "__type__": "cc.Vec3", + "x": 300, + "y": 0, + "z": 0 + }, + ] + } + } + } + }; + clip.updateCurveDatas(); + + var state = new AnimationState(clip); + + state.update(0); + + state.update(0.2); + expect(entity.position.x).toBeCloseTo(0.2 * 100); + + state.update(1.2); + // expect(entity.position.x).toBeCloseTo([0, 0.5, 0.5, 1], 0.4) * 100 + 100, 0.0001, 'should wrap time by bezierByTime'); + + state.update(1.3); + // strictEqual(entity.x, 0.7 * 100 + 200, 'should wrap time by linear'); +}); + +// test('DynamicAnimCurve', function () { +// var DynamicAnimCurve = cc._Test.DynamicAnimCurve; +// var anim = new DynamicAnimCurve(); +// var target = { +// height: 1, +// position: v2(123, 456), +// foo: { +// bar: color(128, 128, 128, 128), +// } +// }; +// anim.target = target; +// anim.prop = 'height'; +// anim.values = [10, 100]; +// anim.ratios = [0.5, 1.0]; +// anim.sample(null, 0.1, null); + +// strictEqual(target.height, 10, 'The keyframe value whose ratio is out of ranges should just clamped'); + +// anim.prop = 'position'; +// anim.subProps = ['x']; +// anim.values = [50, 100]; +// anim.ratios = [0.0, 1.0]; +// anim.sample(null, 0.1, null); + +// deepEqual(target.position, v2(55, 456), 'The composed position should animated'); + +// anim.target = target; +// anim.prop = 'foo'; +// anim.subProps = ['bar', 'a']; +// anim.values = [128, 256]; +// anim.ratios = [0.0, 1.0]; +// anim.sample(null, 0.1, null); + +// deepEqual(target.foo, { bar: color(128, 128, 128, 140) }, 'The composed color should animated'); +// }); + +// test('AnimationState.getWrappedInfo', function () { +// var info; +// var animation = new cc.AnimationState(); + +// animation.duration = 2; +// animation.wrapMode = cc.WrapMode.PingPong; +// animation.repeatCount = Infinity; + +// function deepClose (actual, expected, maxDifference, message) { +// close(actual.time, expected.time, maxDifference, message + '[time]'); +// close(actual.ratio, expected.ratio, maxDifference, message + '[ratio]'); +// close(actual.direction, expected.direction, maxDifference, message + '[direction]'); +// close(actual.stopped, expected.stopped, maxDifference, message + '[stopped]'); +// close(actual.iterations, expected.iterations, maxDifference, message + '[iterations]'); +// } + +// info = animation.getWrappedInfo(0); +// deepClose(info, { +// time: 0, +// ratio: 0, +// direction: 1, +// stopped: false, +// iterations: 0 +// }, 0.00001, 'should start at time 0'); + +// info = animation.getWrappedInfo(2); +// deepClose(info, { +// time: 2, +// ratio: 1, +// direction: 1, +// stopped: false, +// iterations: 1 +// }, 0.00001, 'should at the end of first loop'); + +// info = animation.getWrappedInfo(2.1); +// deepClose(info, { +// time: 1.9, +// ratio: 0.95, +// direction: -1, +// stopped: false, +// iterations: 1.05 +// }, 0.00001, 'should at 2nd loop'); + +// info = animation.getWrappedInfo(4.0); +// deepClose(info, { +// time: 0, +// ratio: 0, +// direction: -1, +// stopped: false, +// iterations: 2 +// }, 0.00001, 'should at the end of second loop'); + +// info = animation.getWrappedInfo(4.2); +// deepClose(info, { +// time: 0.2, +// ratio: 0.1, +// direction: 1, +// stopped: false, +// iterations: 2.1 +// }, 0.00001, 'should at 3rd loop'); + +// }); + + +// test('createBatchedProperty', function () { +// var createBatchedProperty = cc._Test.createBatchedProperty; + +// function test(path, mainValue, animValue) { +// return createBatchedProperty(path, path.indexOf('.'), mainValue, animValue); +// } + +// var pos = v2(123, 456); +// var actual = test('position.y', pos, 321); +// ok(actual !== pos, 'should clone a new value'); +// deepEqual(actual, v2(123, 321), 'checking value x'); + +// actual = test('p.x', pos, 321); +// deepEqual(actual, v2(321, 456), 'checking value y'); + +// var MyValue = cc.Class({ +// extends: cc.ValueType, +// ctor: function () { +// this.abc = { +// def: { +// gh: arguments[0] +// } +// }; +// }, +// clone: function () { +// return new MyValue(this.abc.def.gh); +// } +// }); +// var myValue = new MyValue(520); +// actual = test('myValue.abc.def.gh', myValue, 521); +// strictEqual(actual.abc.def.gh, 521, 'checking value gh'); +// }); + +// test('initClipData', function () { +// var initClipData = cc._Test.initClipData; + +// var entity = new cc.Node(); +// entity.name = 'foo'; +// var renderer = entity.addComponent(cc.Sprite); +// renderer.testColor = Color.BLACK; + +// var childEntity = new cc.Node(); +// childEntity.name = 'bar'; +// var childRenderer = childEntity.addComponent(cc.Sprite); +// childRenderer.testColor = Color.BLACK; + +// entity.addChild(childEntity); + +// var clip = new cc.AnimationClip(); +// var state = new cc.AnimationState(clip); +// initClipData(entity, state); +// strictEqual(state.curves.length, 0, 'should create empty animation'); + +// clip = new cc.AnimationClip(); +// clip._duration = 10; +// clip.curveData = { +// props: { +// pos: [ +// { frame: 0, value: v2(50, 100) }, +// { frame: 5, value: v2(100, 75) }, +// { frame: 10, value: v2(100, 50) } +// ], +// 'scale.x': [ +// { frame: 0, value: 10 }, +// { frame: 10, value: 20 } +// ], +// 'scale.y': [ +// { frame: 0, value: 10 }, +// { frame: 5, value: 12 }, +// { frame: 10, value: 20 } +// ] +// }, + +// comps: { +// 'cc.Sprite': { +// 'testColor.a': [ +// { frame: 0, value: 1 }, +// { frame: 10, value: 0 } +// ] +// } +// }, + +// paths: { +// 'bar': { +// props: { +// pos: [ +// { frame: 0, value: v2(50, 100) }, +// { frame: 5, value: v2(100, 75) }, +// { frame: 10, value: v2(100, 50) }, +// ] +// }, + +// comps: { +// 'cc.Sprite': { +// 'testColor.a': [ +// { frame: 0, value: 1 }, +// { frame: 10, value: 0 } +// ] +// } +// } +// } +// } +// }; + +// state = new cc.AnimationState(clip); +// initClipData(entity, state); + +// var posCurve = state.curves[0]; +// var scaleCurveX = state.curves[1]; +// var scaleCurveY = state.curves[2]; +// var colorCurve = state.curves[3]; + +// strictEqual(state.curves.length, 6, 'should create 6 curve'); +// strictEqual(posCurve.target, entity, 'target of posCurve should be transform'); +// strictEqual(posCurve.prop, 'pos', 'propName of posCurve should be pos'); +// strictEqual(scaleCurveX.target, entity, 'target of scaleCurve should be transform'); +// strictEqual(scaleCurveX.prop, 'scale', 'propName of scaleCurve should be scale'); +// strictEqual(colorCurve.target, renderer, 'target of colorCurve should be sprite renderer'); +// strictEqual(colorCurve.prop, 'testColor', 'propName of colorCurve should be testColor'); + +// deepEqual(posCurve.values, [v2(50, 100), v2(100, 75), v2(100, 50)], 'values of posCurve should equals keyFrames'); + +// deepEqual(scaleCurveY.values, [10, 12, 20], 'values of scaleCurve should equals keyFrames'); + +// deepEqual(colorCurve.values, [1, 0], 'values of colorCurve should equals keyFrames'); + +// deepEqual(posCurve.ratios, [0, 0.5, 1], 'ratios of posCurve should equals keyFrames'); +// deepEqual(colorCurve.ratios, [0, 1], 'ratios of colorCurve should equals keyFrames'); +// }); + + +// test('Animation Component', function () { +// var entity = new cc.Node(); +// var animation = entity.addComponent(cc.Animation); + +// entity.x = 400; + +// cc.director.getScene().addChild(entity); + +// var clip = new cc.AnimationClip(); +// clip._duration = 10; +// clip._name = 'test'; +// clip.curveData = { +// props: { +// x: [ +// { frame: 0, value: 0 }, +// { frame: 5, value: 50 }, +// { frame: 10, value: 100 } +// ] +// } +// }; + +// animation.addClip(clip); + +// strictEqual(animation.getClips().length, 1, 'should add 1 clip'); + +// var state = animation.getAnimationState('test'); +// strictEqual(state.clip, clip, 'should create state with clip'); + +// strictEqual(state.duration, 10, 'should get state duration'); + +// animation.play('test'); +// animation.sample(); +// strictEqual(entity.x, 0, 'target property should equals value in frame 0s'); + +// animation.play('test', 5); +// animation.sample(); +// strictEqual(entity.x, 50, 'target property should equals value in frame 5s'); + +// animation.play('test', 10); +// animation.sample(); +// strictEqual(entity.x, 100, 'target property should equals value in frame 10s'); + +// animation.removeClip(clip, true); +// strictEqual(animation.getClips().length, 0, 'should remove clip'); +// strictEqual(animation.getAnimationState('test'), null, 'should remove state'); + +// animation.stop(); + +// animation.addClip(clip); +// animation.play('test'); +// cc.director.runSceneImmediate(new cc.Scene()); +// strictEqual(!!(animation._animator && animation._animator.isPlaying), false, 'animation should be stopped after load scene'); +// }); + + +// test('sampleMotionPaths', function () { +// var sampleMotionPaths = cc._Test.sampleMotionPaths; + +// var data = { +// prop: 'position', +// ratios: [ +// 0, +// 0.198, +// 1 +// ], +// values: [ +// [0, 480], +// [0, 0], +// [640, 480] +// ], +// types: [ +// null, +// null, +// null +// ] +// }; + +// var motionPaths = [ +// null, +// [[320, 240, 0, 240, 640, 240], [640, 0, 400, 0, 1000, 0]], +// null +// ]; + +// sampleMotionPaths(motionPaths, data, 2, 60); + +// var values = data.values; +// var ratios = data.ratios; + +// strictEqual(values.length, 120 + 1, 'motionPath length should be 121'); +// strictEqual(values[0] instanceof cc.Vec2, true, 'motionPath item should be cc.Vec2'); + +// close(values[0].x, 0, 0.0001, 'value[0].x should equal value'); +// close(values[0].y, 480, 0.0001, 'value[0].y should equal value'); + +// close(values[120].x, 640, 0.0001, 'value[119].x should equal value'); +// close(values[120].y, 480, 0.0001, 'value[119].x should equal value'); + +// var index = ( (0.198 / (1/120)) | 0 ) + 1; +// close(values[index].x, 0.1327874, 0.0001, 'value[index].x should equal value'); +// close(values[index].y, 3.8064457, 0.0001, 'value[index].x should equal value'); + +// var betweenRatio = 1 / (values.length - 1); + +// for (var i = 0; i < values.length - 1; i++) { +// close(ratios[i + 1] - ratios[i], betweenRatio, 0.0001, 'betweenRatio should be same'); +// } +// }); + +// test('SampledAnimCurve', function () { +// var initClipData = cc._Test.initClipData; + +// var entity = new cc.Node(); + +// var clip = new cc.AnimationClip(); +// clip._name = 'test'; +// clip._duration = 1; +// clip.sample = 60; +// clip.curveData = { +// props: { +// position: [ +// {frame: 0.2, value: [0, 0]}, +// {frame: 0.7, value: [100, 100]} +// ], +// test: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; + +// state = new cc.AnimationState(clip); +// initClipData(entity, state); + +// state.time = 0.2; +// state.sample(); + +// deepEqual(entity.position, v2(0, 0), 'entity position should be (0,0)'); + +// state.time = 0.7; +// state.sample(); + +// deepEqual(entity.position, v2(100, 100), 'entity position should be (100, 100)'); + +// state.time = 0.9; +// state.sample(); + +// deepEqual(entity.position, v2(100, 100), 'entity position should be (100, 100)'); +// }); + + +// test('EventAnimCurve', function () { +// var initClipData = cc._Test.initClipData; + +// var manager = cc.director.getAnimationManager(); + +// var calls = []; +// var state; + +// var MyComp = cc.Class({ +// name: 'MyComp', +// extends: cc.Component, + +// func1: function (arg1) { +// calls.push({ +// func: 'func1', +// args: [arg1] +// }); +// }, + +// func2: function (arg1, arg2) { +// calls.push({ +// func: 'func2', +// args: [arg1, arg2] +// }); +// }, + +// func3: function (arg1) { +// calls.push({ +// func: 'func3', +// args: [arg1] +// }); +// } +// }); + +// var entity = new cc.Node(); +// entity.addComponent(MyComp); + +// cc.director.getScene().addChild(entity); + +// var animation = entity.addComponent(cc.Animation); + +// var clip = new cc.AnimationClip(); +// clip._duration = 2; +// clip._name = 'test'; +// clip.sample = 10; +// clip.events = [ +// {frame: 0.2, func: 'func1', params: ['Frame 0 Event triggered']}, +// {frame: 0.4, func: 'func2', params: [1, 2]}, +// {frame: 0.4, func: 'func3', params: ['Second event on frame 0.4']}, +// {frame: 1, func: 'func1', params: ['Frame 2 Event triggered']}, +// {frame: 1.2, func: 'func1', params: ['Frame 3 Event triggered']}, +// {frame: 1.4, func: 'func1', params: ['Frame 4 Event triggered']}, +// {frame: 1.8, func: 'func1', params: ['Frame 5 Event triggered']} +// ]; + +// animation.addClip(clip); +// state = animation.getAnimationState('test'); + +// animation.play('test'); +// // play best first frame +// manager.update(0); +// manager.update(0.1); +// deepEqual(calls, [], 'should not triggered events'); + +// manager.update(0.1); +// deepEqual(calls, [{ +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// }], 'func1 should called with args'); + + +// calls = []; +// manager.update(0.1); +// deepEqual(calls, [], 'next event should not be triggered'); + +// manager.update(0.2); +// manager.update(0.2); +// deepEqual(calls, [ +// { +// func: 'func2', +// args: [1, 2] +// }, +// { +// func: 'func3', +// args: ['Second event on frame 0.4'] +// } +// ], 'next event should be triggered once'); + + +// calls = []; +// manager.update(1); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 2 Event triggered'] +// }, +// { +// func: 'func1', +// args: ['Frame 3 Event triggered'] +// }, +// { +// func: 'func1', +// args: ['Frame 4 Event triggered'] +// } +// ], 'should triggered frame 3 event in sequence'); + + +// calls = []; +// manager.update(10); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 5 Event triggered'] +// } +// ], 'should triggered last event once'); + + +// animation.stop('test'); +// animation.play('test'); +// state.wrapMode = cc.WrapMode.Loop; +// state.repeatCount = Infinity; +// manager.update(0); +// manager.update(1.7); +// calls = []; +// manager.update(0.3); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 5 Event triggered'] +// } +// ], 'should only triggered last event if wrapMode is Loop'); + +// calls = []; +// manager.update(0.1); +// deepEqual(calls, [], 'should not triggered event'); + + +// animation.stop('test'); +// animation.play('test'); +// state.wrapMode = cc.WrapMode.Loop; +// state.repeatCount = Infinity; +// manager.update(0); +// manager.update(1.7); +// calls = []; +// manager.update(0.5); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 5 Event triggered'] +// }, +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ], 'should triggered last and first event if wrapMode is Loop'); + + +// animation.stop('test'); +// animation.play('test'); +// state.wrapMode = cc.WrapMode.Reverse; +// state.repeatCount = 1; +// manager.update(0); +// calls = []; +// manager.update(0.1); +// deepEqual(calls, [], 'should triggered no events if wrapMode is Reverse'); + +// calls = []; +// manager.update(0.1); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 5 Event triggered'] +// } +// ], 'should triggered last event if wrapMode is Reverse'); + +// calls = []; +// manager.update(0.1); +// deepEqual(calls, [], 'should triggered no events if wrapMode is Reverse'); + +// calls = []; +// manager.update(1); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 4 Event triggered'] +// }, +// { +// func: 'func1', +// args: ['Frame 3 Event triggered'], +// }, +// { +// func: 'func1', +// args: ['Frame 2 Event triggered'], +// } +// ], 'should triggered no events if wrapMode is Reverse'); + +// calls = []; +// manager.update(10); +// deepEqual(calls, [ +// { +// func: 'func2', +// args: [1, 2], +// }, +// { +// func: 'func3', +// args: ['Second event on frame 0.4'] +// }, +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ], 'should triggered no events if wrapMode is Reverse'); + + +// animation.stop('test'); +// animation.play('test'); +// state.wrapMode = cc.WrapMode.PingPong; +// state.repeatCount = Infinity; +// manager.update(0); +// manager.update(1.7); +// calls = []; +// manager.update(0.5); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 5 Event triggered'] +// } +// ], 'should triggered frame 5 event once if wrapMode is PingPong'); + +// calls = []; +// manager.update(0.2); +// deepEqual(calls, [], 'should triggered no events if wrapMode is PingPong'); + +// calls = []; +// manager.update(0.3); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 4 Event triggered'] +// } +// ], 'should triggered frame 4 event once if wrapMode is PingPong'); + +// animation.stop('test'); +// animation.play('test'); +// state.wrapMode = cc.WrapMode.PingPongReverse; +// state.repeatCount = Infinity; +// manager.update(0); +// manager.update(1.7); +// calls = []; +// manager.update(0.5); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ], 'should triggered frame 0 event once if wrapMode is PingPongReverse'); + +// animation.stop('test'); +// animation.play('test'); +// state.speed = -1; +// state.wrapMode = cc.WrapMode.Normal; +// state.repeatCount = Infinity; +// manager.update(0); +// calls = []; +// manager.update(0.5); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 5 Event triggered'] +// } +// ], 'should triggered frame 5 event once if speed is -1'); + + + +// animation.stop('test'); +// animation.play('test'); +// state.speed = -1; +// state.wrapMode = cc.WrapMode.PingPongReverse; +// state.repeatCount = Infinity; +// manager.update(0); +// manager.update(1.7); +// calls = []; +// manager.update(0.5); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 5 Event triggered'] +// } +// ], 'should triggered frame 5 event once if speed is -1'); + + +// state.speed = 1; +// state.wrapMode = cc.WrapMode.Normal; +// animation.stop('test'); +// animation.play('test', 1.1); +// calls = []; +// manager.update(0); +// manager.update(1); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 3 Event triggered'] +// }, +// { +// func: 'func1', +// args: ['Frame 4 Event triggered'] +// }, +// { +// func: 'func1', +// args: ['Frame 5 Event triggered'] +// } +// ], 'should triggered from frame 3 to frame 5'); + + +// state.wrapMode = cc.WrapMode.Reverse; +// animation.stop('test'); +// animation.play('test', 1.1); +// calls = []; +// manager.update(0); +// manager.update(1); +// deepEqual(calls, [ +// { +// func: 'func2', +// args: [1,2] +// }, +// { +// func: 'func3', +// args: ['Second event on frame 0.4'] +// }, +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ], 'should triggered from frame 2 to frame 0'); + + +// // new clip +// clip = new cc.AnimationClip(); +// clip._duration = 2; +// clip._name = 'test'; +// clip.sample = 10; +// clip.events = [ +// {frame: 2, func: 'func1', params: ['Frame 0 Event triggered']}, +// ]; + +// animation.addClip(clip); +// state = animation.getAnimationState('test'); + +// // loop and single frame at last +// state.wrapMode = cc.WrapMode.Loop; +// state.repeatCount = Infinity; +// animation.play('test'); +// manager.update(0); + +// calls = []; +// manager.update(1); +// manager.update(2); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ]); + +// // pingpong and single frame at last +// animation.stop('test'); +// animation.play('test'); +// state.wrapMode = cc.WrapMode.PingPong; +// state.setTime(0); +// manager.update(0); +// calls = []; +// manager.update(1); +// manager.update(2); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ]); + +// calls = []; +// manager.update(2); +// deepEqual(calls, [ +// ]); + +// // loop reverse and single frame at last +// animation.stop('test'); +// animation.play('test'); +// state.wrapMode = cc.WrapMode.LoopReverse; +// state.setTime(0); +// calls = []; +// manager.update(0); +// manager.update(2); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ]); + +// calls = []; +// manager.update(2); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ]); + + +// // new clip +// clip = new cc.AnimationClip(); +// clip._duration = 1; +// clip._name = 'test'; +// clip.sample = 10; +// clip.events = [ +// {frame: 0, func: 'func1', params: ['Frame 0 Event triggered']}, +// ]; + +// animation.addClip(clip); +// state = animation.getAnimationState('test'); + +// // loop and single frame at 0 +// state.wrapMode = cc.WrapMode.Loop; +// state.repeatCount = Infinity; +// animation.play('test'); +// manager.update(0); +// manager.update(0.5); + +// calls = []; +// manager.update(1); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ]); + +// calls = []; +// manager.update(1); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ]); + + +// // new clip +// clip = new cc.AnimationClip(); +// clip._duration = 1; +// clip._name = 'test'; +// clip.sample = 10; +// clip.events = [ +// {frame: 0.5, func: 'func1', params: ['Frame 0 Event triggered']}, +// {frame: 1, func: 'func1', params: ['Frame 1 Event triggered']}, +// ]; + +// animation.addClip(clip); +// state = animation.getAnimationState('test'); + +// // loop and single frame at 0 +// state.wrapMode = cc.WrapMode.PingPong; +// state.repeatCount = Infinity; +// animation.play('test'); +// manager.update(0); + +// calls = []; +// manager.update(0.4); +// manager.update(0.4); +// manager.update(0.4); +// manager.update(0.4); +// manager.update(0.4); +// manager.update(0.4); +// manager.update(0.4); +// deepEqual(calls, [ +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// }, +// { +// func: 'func1', +// args: ['Frame 1 Event triggered'] +// }, +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// }, +// { +// func: 'func1', +// args: ['Frame 0 Event triggered'] +// } +// ]); + +// animation.stop(); +// }); + +// test('stop Animation', function () { +// var entity = new cc.Node(); +// var animation = entity.addComponent(cc.Animation); + +// cc.director.getScene().addChild(entity); + +// var clip = new cc.AnimationClip(); +// clip._name = 'test'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// x: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; + +// var animationManager = cc.director.getAnimationManager(); +// animationManager._anims.array.length = 0; + +// animation.addClip(clip); +// animation._init(); + +// animation.play('test'); + +// strictEqual(animationManager._anims.array.length, 1, 'playing animators should be 1'); +// strictEqual(animation._animator._anims.array.length, 1, 'playing anims should be 1'); + +// animationManager.update(0); +// animationManager.update(1); + +// strictEqual(animationManager._anims.array.length, 0, 'playing animators should be 0'); +// strictEqual(animation._animator._anims.array.length, 0, 'playing anims should be 0'); + +// animation.play('test'); +// animationManager.update(0.5); + +// strictEqual(animationManager._anims.array.length, 1, 'playing animators should be 1'); +// strictEqual(animation._animator._anims.array.length, 1, 'playing anims should be 1'); + +// animation.stop(); + +// strictEqual(animationManager._anims.array.length, 0, 'playing animators should be 0'); +// strictEqual(animation._animator._anims.array.length, 0, 'playing anims should be 0'); +// }); + +// test('play Animation', function () { +// var entity = new cc.Node(); +// var animation = entity.addComponent(cc.Animation); + +// var clip = new cc.AnimationClip(); +// clip._name = 'move'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// x: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; +// animation.addClip(clip); + +// clip = new cc.AnimationClip(); +// clip._name = 'rotate'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// rotation: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 90} +// ] +// } +// }; +// animation.addClip(clip); + +// clip = new cc.AnimationClip(); +// clip._name = 'scale'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// scaleX: [ +// {frame: 0, value: 1}, +// {frame: 1, value: 2} +// ] +// } +// }; +// animation.addClip(clip); + +// var moveState = animation.getAnimationState('move'); +// var rotateState = animation.getAnimationState('rotate'); + +// strictEqual(moveState.isPlaying, false, 'move animation state should not be playing'); +// strictEqual(rotateState.isPlaying, false, 'rotate animation state should not be playing'); + +// animation.play('move'); +// strictEqual(moveState.isPlaying, true, 'move animation state should be playing'); +// strictEqual(rotateState.isPlaying, false, 'rotate animation state should not be playing'); + +// animation.play('rotate'); +// strictEqual(moveState.isPlaying, false, 'move animation state should not be playing'); +// strictEqual(rotateState.isPlaying, true, 'rotate animation state should be playing'); + +// animation.playAdditive('move'); +// strictEqual(moveState.isPlaying, true, 'move animation state should be playing'); +// strictEqual(rotateState.isPlaying, true, 'rotate animation state should be playing'); + +// animation.play('scale'); +// strictEqual(moveState.isPlaying, false, 'move animation state should not be playing'); +// strictEqual(rotateState.isPlaying, false, 'rotate animation state should be playing'); + +// animation.stop(); +// }); + +// test('animation enabled/disabled', function () { +// var scene = cc.director.getScene(); +// var entity = new cc.Node(); +// var animation = entity.addComponent(cc.Animation); + +// entity.parent = scene; + +// var clip = new cc.AnimationClip(); +// clip._name = 'move'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// x: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; +// animation.addClip(clip); +// animation.play('move'); + +// animation.enabled = false; + +// strictEqual(animation._animator.isPlaying, true, 'move animation should be playing'); +// strictEqual(animation._animator.isPaused, true, 'move animation should be paused'); + +// animation.enabled = true; + +// strictEqual(animation._animator.isPlaying, true, 'move animation should be playing'); +// strictEqual(animation._animator.isPaused, false, 'move animation should be resumed'); + +// entity.parent = null; +// }); + +// test('animation removeClip', function () { +// var entity = new cc.Node(); +// var animation = entity.addComponent(cc.Animation); + +// var clip1 = new cc.AnimationClip(); +// clip1._name = 'clip1'; +// clip1._duration = 1; +// clip1.curveData = { +// props: { +// x: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; +// animation.addClip(clip1); +// animation._defaultClip = clip1; + +// var clip2 = new cc.AnimationClip(); +// clip2._name = 'clip2'; +// clip2._duration = 1; +// clip2.curveData = { +// props: { +// y: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; +// animation.addClip(clip2); + +// animation.removeClip(clip1); +// strictEqual(animation._clips.indexOf(clip1), 0, 'clip1 will not be removed since clip1 is defaultClip'); + +// animation.removeClip(clip1, true); +// strictEqual(animation._clips.indexOf(clip1), -1, 'clip1 will be removed even it\'t defaultClip if force is true'); +// strictEqual(animation.defaultClip, null, 'defaultClip will be reset to null'); + +// animation.play('clip2'); +// animation.removeClip(clip2); +// strictEqual(animation._clips.indexOf(clip2), 0, 'clip2 will not be removed since clip2 is playing'); + +// animation.removeClip(clip2, true); +// strictEqual(animation._clips.indexOf(clip2), -1, 'clip2 will be removed even clip2 is playing if force is true'); + +// animation.stop(); +// }); + +// test('animation callback', function () { +// var type; + +// function callback (t, state) { +// strictEqual(state instanceof cc.AnimationState, true); +// strictEqual(state.name === 'move', true); + +// type = t; +// } + +// var manager = cc.director.getAnimationManager(); + +// var entity = new cc.Node(); +// var animation = entity.addComponent(cc.Animation); + +// cc.director.getScene().addChild(entity); + +// var clip = new cc.AnimationClip(); +// clip._name = 'move'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// x: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; +// animation.addClip(clip); + +// var state = animation.getAnimationState('move'); + +// animation.on('play', callback); +// animation.on('pause', callback); +// animation.on('resume', callback); +// animation.on('stop', callback); + +// animation.play('move'); +// manager.update(0); +// strictEqual(type === 'play', true, 'should trigger play callback'); + +// animation.pause('move'); +// manager.update(0); +// strictEqual(type === 'pause', true, 'should trigger pause callback'); + +// animation.resume('move'); +// manager.update(0); +// strictEqual(type === 'resume', true, 'should trigger resume callback'); + +// manager.update(0); +// manager.update(1); +// strictEqual(type === 'stop', true, 'should trigger stop callback'); + +// type = ''; + +// animation.off('play', callback); + +// animation.play('move'); +// manager.update(0); +// strictEqual(type === '', true, 'should not trigger callback'); + +// animation.off('pause', callback); +// animation.off('resume', callback); + +// animation.pause('move'); +// manager.update(0); +// strictEqual(type === 'pause', false, 'should not trigger pause callback'); + +// animation.on('resume', callback); +// animation.resume('move'); +// manager.update(0); +// strictEqual(type === 'resume', true, 'should trigger resume callback'); + +// animation.on('finished', callback); +// manager.update(1); +// strictEqual(type === 'finished', true, 'should trigger finished callback'); + + +// clip = new cc.AnimationClip(); +// clip._name = 'move2'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// x: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; +// animation.addClip(clip); + +// var list = []; +// function callback2 (t, state) { +// list.push([state.name, t]); +// } + +// animation.play('move'); +// manager.update(0); + +// animation.on('play', callback2); +// animation.on('stop', callback2); + +// animation.play('move2'); +// manager.update(0); +// deepEqual(list, [['move2', 'play'], ['move', 'stop']]); + +// animation.stop(); +// }); + +// test('animation callback', function () { +// var entity = new cc.Node(); + +// var animation = entity.addComponent(cc.Animation); + +// clip = new cc.AnimationClip(); +// clip._name = 'test'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// x: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; + +// animation.addClip(clip); + +// animation.play('test'); +// animation.setCurrentTime(0.5,'test'); +// strictEqual(entity.x, 50, 'entity.x should be 50'); + +// animation.setCurrentTime(0.7); +// strictEqual(entity.x, 70, 'entity.x should be 70'); + +// animation.stop(); +// }); + +// test('animation delay', function () { +// var entity = new cc.Node(); + +// var animation = entity.addComponent(cc.Animation); + +// clip = new cc.AnimationClip(); +// clip._name = 'test'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// x: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; + +// animation.addClip(clip); + +// var state = animation.play('test'); + +// state.delay = 5; + +// strictEqual(state._delayTime, 5, 'delay time should be 5'); + +// state.update(3); +// strictEqual(state._delayTime, 2, 'delay time should be 2'); +// strictEqual(entity.x, 0, 'entity should not changed during delay'); + +// state.update(2); +// strictEqual(state._delayTime === 0, true, 'delay time should be 0'); + +// state.update(1); +// strictEqual(entity.x, 100, 'entity should move to end'); +// strictEqual(state.isPlaying, false, 'animation should end.'); + +// state = animation.play('test'); + +// strictEqual(state._delayTime, 5, 'delay time should reset when replay'); + +// animation.stop(); +// }); + +// test('animation pause/resume', function () { +// var entity = new cc.Node(); +// entity.parent = cc.director.getScene(); + +// var animation = entity.addComponent(cc.Animation); + +// clip = new cc.AnimationClip(); +// clip._name = 'test'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// x: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; + +// animation.addClip(clip); + +// animation.play('test'); + +// animation.pause(); +// strictEqual(animation._animator._isPaused, true, 'animation should be paused'); + +// entity.active = false; +// strictEqual(animation._animator._isPaused, true, 'animation should be paused'); + +// entity.active = true; +// strictEqual(animation._animator._isPaused, true, 'animation should be paused'); + +// animation.resume(); +// strictEqual(animation._animator._isPaused, false, 'animation should not be paused'); + +// entity.parent = null; +// }); + +// test('animation pause/resume should remove animation-actor from animation manager', function () { +// var entity = new cc.Node(); +// entity.parent = cc.director.getScene(); + +// var animation = entity.addComponent(cc.Animation); + +// clip = new cc.AnimationClip(); +// clip._name = 'test'; +// clip._duration = 1; +// clip.curveData = { +// props: { +// x: [ +// {frame: 0, value: 0}, +// {frame: 1, value: 100} +// ] +// } +// }; + +// animation.addClip(clip); + +// var manager = cc.director.getAnimationManager(); + +// var state = animation.play('test'); +// strictEqual(manager._anims.array.length, 1, 'should add 1 animation to animation manager'); + +// animation.pause(); +// strictEqual(manager._anims.array.length, 0, 'should remove animation from animation manager'); +// strictEqual(state.animator, null, 'should unbind animator to animation state when pause animation'); + +// animation.resume(); +// strictEqual(manager._anims.array.length, 1, 'should add 1 animation to animation manager'); +// strictEqual(state.animator, animation._animator, 'should rebind animator to animation state when pause animation'); + +// animation.stop(); +// strictEqual(manager._anims.array.length, 0, 'should remove animation from animation manager'); + +// // should not see error log in console +// animation.play('test'); +// animation.pause(); +// animation.stop(); + +// animation.play('test'); +// entity.parent = null; + +// strictEqual(manager._anims.array.length, 0, 'should remove animation from animation manager'); +// }); + + +// test('animation play on load', function () { +// var entity = new cc.Node(); + +// var animation = entity.addComponent(cc.Animation); +// animation.playOnLoad = true; + +// var clip1 = new cc.AnimationClip(); +// clip1._name = 'clip1'; +// clip1._duration = 1; + +// var clip2 = new cc.AnimationClip(); +// clip2._name = 'clip2'; +// clip2._duration = 1; + + +// animation.addClip(clip1); +// animation.addClip(clip2); + +// animation._defaultClip = clip1; + +// animation.play('clip2'); + +// entity.parent = cc.director.getScene(); +// animation.start(); + +// strictEqual(animation.getAnimationState('clip1').isPlaying, false, 'default clip should not be played if there is playing animation'); +// strictEqual(animation.getAnimationState('clip2').isPlaying, true, 'should play the specified animation'); + +// entity.parent = null; +// }); diff --git a/tests/animation/test-animation.js b/tests/animation/test-animation.js deleted file mode 100644 index e23b7939eb..0000000000 --- a/tests/animation/test-animation.js +++ /dev/null @@ -1,1412 +0,0 @@ -largeModule('Animation', SetupEngine); - -var color = cc.color; -var Color = cc.Color; -var v2 = cc.v2; - -test('curve types', function () { - var initClipData = cc._Test.initClipData; - var bezierByTime = cc._Test.bezierByTime; - - var entity = new cc.Node(); - - var clip = new cc.AnimationClip(); - clip._duration = 3; - clip.sample = 10; - clip.curveData = { - props: { - x: [ - {frame: 0, value: 0, curve: 'cubicInOut'}, - {frame: 1, value: 100, curve: [0, 0.5, 0.5, 1]}, - {frame: 2, value: 200}, - {frame: 3, value: 300} - ] - } - }; - - var state = new cc.AnimationState(clip); - initClipData(entity, state); - - state.update(0); - - state.update(0.2); - strictEqual(entity.x, cc.Easing.cubicInOut(0.2) * 100, 'should wrap time by cc.Easing.cubicInOut'); - - state.update(1.2); - close(entity.x, bezierByTime([0, 0.5, 0.5, 1], 0.4) * 100 + 100, 0.0001, 'should wrap time by bezierByTime'); - - state.update(1.3); - strictEqual(entity.x, 0.7 * 100 + 200, 'should wrap time by linear'); -}); - -test('DynamicAnimCurve', function () { - var DynamicAnimCurve = cc._Test.DynamicAnimCurve; - var anim = new DynamicAnimCurve(); - var target = { - height: 1, - position: v2(123, 456), - foo: { - bar: color(128, 128, 128, 128), - } - }; - anim.target = target; - anim.prop = 'height'; - anim.values = [10, 100]; - anim.ratios = [0.5, 1.0]; - anim.sample(null, 0.1, null); - - strictEqual(target.height, 10, 'The keyframe value whose ratio is out of ranges should just clamped'); - - anim.prop = 'position'; - anim.subProps = ['x']; - anim.values = [50, 100]; - anim.ratios = [0.0, 1.0]; - anim.sample(null, 0.1, null); - - deepEqual(target.position, v2(55, 456), 'The composed position should animated'); - - anim.target = target; - anim.prop = 'foo'; - anim.subProps = ['bar', 'a']; - anim.values = [128, 256]; - anim.ratios = [0.0, 1.0]; - anim.sample(null, 0.1, null); - - deepEqual(target.foo, { bar: color(128, 128, 128, 140) }, 'The composed color should animated'); -}); - -test('AnimationState.getWrappedInfo', function () { - var info; - var animation = new cc.AnimationState(); - - animation.duration = 2; - animation.wrapMode = cc.WrapMode.PingPong; - animation.repeatCount = Infinity; - - function deepClose (actual, expected, maxDifference, message) { - close(actual.time, expected.time, maxDifference, message + '[time]'); - close(actual.ratio, expected.ratio, maxDifference, message + '[ratio]'); - close(actual.direction, expected.direction, maxDifference, message + '[direction]'); - close(actual.stopped, expected.stopped, maxDifference, message + '[stopped]'); - close(actual.iterations, expected.iterations, maxDifference, message + '[iterations]'); - } - - info = animation.getWrappedInfo(0); - deepClose(info, { - time: 0, - ratio: 0, - direction: 1, - stopped: false, - iterations: 0 - }, 0.00001, 'should start at time 0'); - - info = animation.getWrappedInfo(2); - deepClose(info, { - time: 2, - ratio: 1, - direction: 1, - stopped: false, - iterations: 1 - }, 0.00001, 'should at the end of first loop'); - - info = animation.getWrappedInfo(2.1); - deepClose(info, { - time: 1.9, - ratio: 0.95, - direction: -1, - stopped: false, - iterations: 1.05 - }, 0.00001, 'should at 2nd loop'); - - info = animation.getWrappedInfo(4.0); - deepClose(info, { - time: 0, - ratio: 0, - direction: -1, - stopped: false, - iterations: 2 - }, 0.00001, 'should at the end of second loop'); - - info = animation.getWrappedInfo(4.2); - deepClose(info, { - time: 0.2, - ratio: 0.1, - direction: 1, - stopped: false, - iterations: 2.1 - }, 0.00001, 'should at 3rd loop'); - -}); - - -test('createBatchedProperty', function () { - var createBatchedProperty = cc._Test.createBatchedProperty; - - function test(path, mainValue, animValue) { - return createBatchedProperty(path, path.indexOf('.'), mainValue, animValue); - } - - var pos = v2(123, 456); - var actual = test('position.y', pos, 321); - ok(actual !== pos, 'should clone a new value'); - deepEqual(actual, v2(123, 321), 'checking value x'); - - actual = test('p.x', pos, 321); - deepEqual(actual, v2(321, 456), 'checking value y'); - - var MyValue = cc.Class({ - extends: cc.ValueType, - ctor: function () { - this.abc = { - def: { - gh: arguments[0] - } - }; - }, - clone: function () { - return new MyValue(this.abc.def.gh); - } - }); - var myValue = new MyValue(520); - actual = test('myValue.abc.def.gh', myValue, 521); - strictEqual(actual.abc.def.gh, 521, 'checking value gh'); -}); - -test('initClipData', function () { - var initClipData = cc._Test.initClipData; - - var entity = new cc.Node(); - entity.name = 'foo'; - var renderer = entity.addComponent(cc.Sprite); - renderer.testColor = Color.BLACK; - - var childEntity = new cc.Node(); - childEntity.name = 'bar'; - var childRenderer = childEntity.addComponent(cc.Sprite); - childRenderer.testColor = Color.BLACK; - - entity.addChild(childEntity); - - var clip = new cc.AnimationClip(); - var state = new cc.AnimationState(clip); - initClipData(entity, state); - strictEqual(state.curves.length, 0, 'should create empty animation'); - - clip = new cc.AnimationClip(); - clip._duration = 10; - clip.curveData = { - props: { - pos: [ - { frame: 0, value: v2(50, 100) }, - { frame: 5, value: v2(100, 75) }, - { frame: 10, value: v2(100, 50) } - ], - 'scale.x': [ - { frame: 0, value: 10 }, - { frame: 10, value: 20 } - ], - 'scale.y': [ - { frame: 0, value: 10 }, - { frame: 5, value: 12 }, - { frame: 10, value: 20 } - ] - }, - - comps: { - 'cc.Sprite': { - 'testColor.a': [ - { frame: 0, value: 1 }, - { frame: 10, value: 0 } - ] - } - }, - - paths: { - 'bar': { - props: { - pos: [ - { frame: 0, value: v2(50, 100) }, - { frame: 5, value: v2(100, 75) }, - { frame: 10, value: v2(100, 50) }, - ] - }, - - comps: { - 'cc.Sprite': { - 'testColor.a': [ - { frame: 0, value: 1 }, - { frame: 10, value: 0 } - ] - } - } - } - } - }; - - state = new cc.AnimationState(clip); - initClipData(entity, state); - - var posCurve = state.curves[0]; - var scaleCurveX = state.curves[1]; - var scaleCurveY = state.curves[2]; - var colorCurve = state.curves[3]; - - strictEqual(state.curves.length, 6, 'should create 6 curve'); - strictEqual(posCurve.target, entity, 'target of posCurve should be transform'); - strictEqual(posCurve.prop, 'pos', 'propName of posCurve should be pos'); - strictEqual(scaleCurveX.target, entity, 'target of scaleCurve should be transform'); - strictEqual(scaleCurveX.prop, 'scale', 'propName of scaleCurve should be scale'); - strictEqual(colorCurve.target, renderer, 'target of colorCurve should be sprite renderer'); - strictEqual(colorCurve.prop, 'testColor', 'propName of colorCurve should be testColor'); - - deepEqual(posCurve.values, [v2(50, 100), v2(100, 75), v2(100, 50)], 'values of posCurve should equals keyFrames'); - - deepEqual(scaleCurveY.values, [10, 12, 20], 'values of scaleCurve should equals keyFrames'); - - deepEqual(colorCurve.values, [1, 0], 'values of colorCurve should equals keyFrames'); - - deepEqual(posCurve.ratios, [0, 0.5, 1], 'ratios of posCurve should equals keyFrames'); - deepEqual(colorCurve.ratios, [0, 1], 'ratios of colorCurve should equals keyFrames'); -}); - - -test('Animation Component', function () { - var entity = new cc.Node(); - var animation = entity.addComponent(cc.Animation); - - entity.x = 400; - - cc.director.getScene().addChild(entity); - - var clip = new cc.AnimationClip(); - clip._duration = 10; - clip._name = 'test'; - clip.curveData = { - props: { - x: [ - { frame: 0, value: 0 }, - { frame: 5, value: 50 }, - { frame: 10, value: 100 } - ] - } - }; - - animation.addClip(clip); - - strictEqual(animation.getClips().length, 1, 'should add 1 clip'); - - var state = animation.getAnimationState('test'); - strictEqual(state.clip, clip, 'should create state with clip'); - - strictEqual(state.duration, 10, 'should get state duration'); - - animation.play('test'); - animation.sample(); - strictEqual(entity.x, 0, 'target property should equals value in frame 0s'); - - animation.play('test', 5); - animation.sample(); - strictEqual(entity.x, 50, 'target property should equals value in frame 5s'); - - animation.play('test', 10); - animation.sample(); - strictEqual(entity.x, 100, 'target property should equals value in frame 10s'); - - animation.removeClip(clip, true); - strictEqual(animation.getClips().length, 0, 'should remove clip'); - strictEqual(animation.getAnimationState('test'), null, 'should remove state'); - - animation.stop(); - - animation.addClip(clip); - animation.play('test'); - cc.director.runSceneImmediate(new cc.Scene()); - strictEqual(!!(animation._animator && animation._animator.isPlaying), false, 'animation should be stopped after load scene'); -}); - - -test('sampleMotionPaths', function () { - var sampleMotionPaths = cc._Test.sampleMotionPaths; - - var data = { - prop: 'position', - ratios: [ - 0, - 0.198, - 1 - ], - values: [ - [0, 480], - [0, 0], - [640, 480] - ], - types: [ - null, - null, - null - ] - }; - - var motionPaths = [ - null, - [[320, 240, 0, 240, 640, 240], [640, 0, 400, 0, 1000, 0]], - null - ]; - - sampleMotionPaths(motionPaths, data, 2, 60); - - var values = data.values; - var ratios = data.ratios; - - strictEqual(values.length, 120 + 1, 'motionPath length should be 121'); - strictEqual(values[0] instanceof cc.Vec2, true, 'motionPath item should be cc.Vec2'); - - close(values[0].x, 0, 0.0001, 'value[0].x should equal value'); - close(values[0].y, 480, 0.0001, 'value[0].y should equal value'); - - close(values[120].x, 640, 0.0001, 'value[119].x should equal value'); - close(values[120].y, 480, 0.0001, 'value[119].x should equal value'); - - var index = ( (0.198 / (1/120)) | 0 ) + 1; - close(values[index].x, 0.1327874, 0.0001, 'value[index].x should equal value'); - close(values[index].y, 3.8064457, 0.0001, 'value[index].x should equal value'); - - var betweenRatio = 1 / (values.length - 1); - - for (var i = 0; i < values.length - 1; i++) { - close(ratios[i + 1] - ratios[i], betweenRatio, 0.0001, 'betweenRatio should be same'); - } -}); - -test('SampledAnimCurve', function () { - var initClipData = cc._Test.initClipData; - - var entity = new cc.Node(); - - var clip = new cc.AnimationClip(); - clip._name = 'test'; - clip._duration = 1; - clip.sample = 60; - clip.curveData = { - props: { - position: [ - {frame: 0.2, value: [0, 0]}, - {frame: 0.7, value: [100, 100]} - ], - test: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - - state = new cc.AnimationState(clip); - initClipData(entity, state); - - state.time = 0.2; - state.sample(); - - deepEqual(entity.position, v2(0, 0), 'entity position should be (0,0)'); - - state.time = 0.7; - state.sample(); - - deepEqual(entity.position, v2(100, 100), 'entity position should be (100, 100)'); - - state.time = 0.9; - state.sample(); - - deepEqual(entity.position, v2(100, 100), 'entity position should be (100, 100)'); -}); - - -test('EventAnimCurve', function () { - var initClipData = cc._Test.initClipData; - - var manager = cc.director.getAnimationManager(); - - var calls = []; - var state; - - var MyComp = cc.Class({ - name: 'MyComp', - extends: cc.Component, - - func1: function (arg1) { - calls.push({ - func: 'func1', - args: [arg1] - }); - }, - - func2: function (arg1, arg2) { - calls.push({ - func: 'func2', - args: [arg1, arg2] - }); - }, - - func3: function (arg1) { - calls.push({ - func: 'func3', - args: [arg1] - }); - } - }); - - var entity = new cc.Node(); - entity.addComponent(MyComp); - - cc.director.getScene().addChild(entity); - - var animation = entity.addComponent(cc.Animation); - - var clip = new cc.AnimationClip(); - clip._duration = 2; - clip._name = 'test'; - clip.sample = 10; - clip.events = [ - {frame: 0.2, func: 'func1', params: ['Frame 0 Event triggered']}, - {frame: 0.4, func: 'func2', params: [1, 2]}, - {frame: 0.4, func: 'func3', params: ['Second event on frame 0.4']}, - {frame: 1, func: 'func1', params: ['Frame 2 Event triggered']}, - {frame: 1.2, func: 'func1', params: ['Frame 3 Event triggered']}, - {frame: 1.4, func: 'func1', params: ['Frame 4 Event triggered']}, - {frame: 1.8, func: 'func1', params: ['Frame 5 Event triggered']} - ]; - - animation.addClip(clip); - state = animation.getAnimationState('test'); - - animation.play('test'); - // play best first frame - manager.update(0); - manager.update(0.1); - deepEqual(calls, [], 'should not triggered events'); - - manager.update(0.1); - deepEqual(calls, [{ - func: 'func1', - args: ['Frame 0 Event triggered'] - }], 'func1 should called with args'); - - - calls = []; - manager.update(0.1); - deepEqual(calls, [], 'next event should not be triggered'); - - manager.update(0.2); - manager.update(0.2); - deepEqual(calls, [ - { - func: 'func2', - args: [1, 2] - }, - { - func: 'func3', - args: ['Second event on frame 0.4'] - } - ], 'next event should be triggered once'); - - - calls = []; - manager.update(1); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 2 Event triggered'] - }, - { - func: 'func1', - args: ['Frame 3 Event triggered'] - }, - { - func: 'func1', - args: ['Frame 4 Event triggered'] - } - ], 'should triggered frame 3 event in sequence'); - - - calls = []; - manager.update(10); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 5 Event triggered'] - } - ], 'should triggered last event once'); - - - animation.stop('test'); - animation.play('test'); - state.wrapMode = cc.WrapMode.Loop; - state.repeatCount = Infinity; - manager.update(0); - manager.update(1.7); - calls = []; - manager.update(0.3); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 5 Event triggered'] - } - ], 'should only triggered last event if wrapMode is Loop'); - - calls = []; - manager.update(0.1); - deepEqual(calls, [], 'should not triggered event'); - - - animation.stop('test'); - animation.play('test'); - state.wrapMode = cc.WrapMode.Loop; - state.repeatCount = Infinity; - manager.update(0); - manager.update(1.7); - calls = []; - manager.update(0.5); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 5 Event triggered'] - }, - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ], 'should triggered last and first event if wrapMode is Loop'); - - - animation.stop('test'); - animation.play('test'); - state.wrapMode = cc.WrapMode.Reverse; - state.repeatCount = 1; - manager.update(0); - calls = []; - manager.update(0.1); - deepEqual(calls, [], 'should triggered no events if wrapMode is Reverse'); - - calls = []; - manager.update(0.1); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 5 Event triggered'] - } - ], 'should triggered last event if wrapMode is Reverse'); - - calls = []; - manager.update(0.1); - deepEqual(calls, [], 'should triggered no events if wrapMode is Reverse'); - - calls = []; - manager.update(1); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 4 Event triggered'] - }, - { - func: 'func1', - args: ['Frame 3 Event triggered'], - }, - { - func: 'func1', - args: ['Frame 2 Event triggered'], - } - ], 'should triggered no events if wrapMode is Reverse'); - - calls = []; - manager.update(10); - deepEqual(calls, [ - { - func: 'func2', - args: [1, 2], - }, - { - func: 'func3', - args: ['Second event on frame 0.4'] - }, - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ], 'should triggered no events if wrapMode is Reverse'); - - - animation.stop('test'); - animation.play('test'); - state.wrapMode = cc.WrapMode.PingPong; - state.repeatCount = Infinity; - manager.update(0); - manager.update(1.7); - calls = []; - manager.update(0.5); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 5 Event triggered'] - } - ], 'should triggered frame 5 event once if wrapMode is PingPong'); - - calls = []; - manager.update(0.2); - deepEqual(calls, [], 'should triggered no events if wrapMode is PingPong'); - - calls = []; - manager.update(0.3); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 4 Event triggered'] - } - ], 'should triggered frame 4 event once if wrapMode is PingPong'); - - animation.stop('test'); - animation.play('test'); - state.wrapMode = cc.WrapMode.PingPongReverse; - state.repeatCount = Infinity; - manager.update(0); - manager.update(1.7); - calls = []; - manager.update(0.5); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ], 'should triggered frame 0 event once if wrapMode is PingPongReverse'); - - animation.stop('test'); - animation.play('test'); - state.speed = -1; - state.wrapMode = cc.WrapMode.Normal; - state.repeatCount = Infinity; - manager.update(0); - calls = []; - manager.update(0.5); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 5 Event triggered'] - } - ], 'should triggered frame 5 event once if speed is -1'); - - - - animation.stop('test'); - animation.play('test'); - state.speed = -1; - state.wrapMode = cc.WrapMode.PingPongReverse; - state.repeatCount = Infinity; - manager.update(0); - manager.update(1.7); - calls = []; - manager.update(0.5); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 5 Event triggered'] - } - ], 'should triggered frame 5 event once if speed is -1'); - - - state.speed = 1; - state.wrapMode = cc.WrapMode.Normal; - animation.stop('test'); - animation.play('test', 1.1); - calls = []; - manager.update(0); - manager.update(1); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 3 Event triggered'] - }, - { - func: 'func1', - args: ['Frame 4 Event triggered'] - }, - { - func: 'func1', - args: ['Frame 5 Event triggered'] - } - ], 'should triggered from frame 3 to frame 5'); - - - state.wrapMode = cc.WrapMode.Reverse; - animation.stop('test'); - animation.play('test', 1.1); - calls = []; - manager.update(0); - manager.update(1); - deepEqual(calls, [ - { - func: 'func2', - args: [1,2] - }, - { - func: 'func3', - args: ['Second event on frame 0.4'] - }, - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ], 'should triggered from frame 2 to frame 0'); - - - // new clip - clip = new cc.AnimationClip(); - clip._duration = 2; - clip._name = 'test'; - clip.sample = 10; - clip.events = [ - {frame: 2, func: 'func1', params: ['Frame 0 Event triggered']}, - ]; - - animation.addClip(clip); - state = animation.getAnimationState('test'); - - // loop and single frame at last - state.wrapMode = cc.WrapMode.Loop; - state.repeatCount = Infinity; - animation.play('test'); - manager.update(0); - - calls = []; - manager.update(1); - manager.update(2); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ]); - - // pingpong and single frame at last - animation.stop('test'); - animation.play('test'); - state.wrapMode = cc.WrapMode.PingPong; - state.setTime(0); - manager.update(0); - calls = []; - manager.update(1); - manager.update(2); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ]); - - calls = []; - manager.update(2); - deepEqual(calls, [ - ]); - - // loop reverse and single frame at last - animation.stop('test'); - animation.play('test'); - state.wrapMode = cc.WrapMode.LoopReverse; - state.setTime(0); - calls = []; - manager.update(0); - manager.update(2); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ]); - - calls = []; - manager.update(2); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ]); - - - // new clip - clip = new cc.AnimationClip(); - clip._duration = 1; - clip._name = 'test'; - clip.sample = 10; - clip.events = [ - {frame: 0, func: 'func1', params: ['Frame 0 Event triggered']}, - ]; - - animation.addClip(clip); - state = animation.getAnimationState('test'); - - // loop and single frame at 0 - state.wrapMode = cc.WrapMode.Loop; - state.repeatCount = Infinity; - animation.play('test'); - manager.update(0); - manager.update(0.5); - - calls = []; - manager.update(1); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ]); - - calls = []; - manager.update(1); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ]); - - - // new clip - clip = new cc.AnimationClip(); - clip._duration = 1; - clip._name = 'test'; - clip.sample = 10; - clip.events = [ - {frame: 0.5, func: 'func1', params: ['Frame 0 Event triggered']}, - {frame: 1, func: 'func1', params: ['Frame 1 Event triggered']}, - ]; - - animation.addClip(clip); - state = animation.getAnimationState('test'); - - // loop and single frame at 0 - state.wrapMode = cc.WrapMode.PingPong; - state.repeatCount = Infinity; - animation.play('test'); - manager.update(0); - - calls = []; - manager.update(0.4); - manager.update(0.4); - manager.update(0.4); - manager.update(0.4); - manager.update(0.4); - manager.update(0.4); - manager.update(0.4); - deepEqual(calls, [ - { - func: 'func1', - args: ['Frame 0 Event triggered'] - }, - { - func: 'func1', - args: ['Frame 1 Event triggered'] - }, - { - func: 'func1', - args: ['Frame 0 Event triggered'] - }, - { - func: 'func1', - args: ['Frame 0 Event triggered'] - } - ]); - - animation.stop(); -}); - -test('stop Animation', function () { - var entity = new cc.Node(); - var animation = entity.addComponent(cc.Animation); - - cc.director.getScene().addChild(entity); - - var clip = new cc.AnimationClip(); - clip._name = 'test'; - clip._duration = 1; - clip.curveData = { - props: { - x: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - - var animationManager = cc.director.getAnimationManager(); - animationManager._anims.array.length = 0; - - animation.addClip(clip); - animation._init(); - - animation.play('test'); - - strictEqual(animationManager._anims.array.length, 1, 'playing animators should be 1'); - strictEqual(animation._animator._anims.array.length, 1, 'playing anims should be 1'); - - animationManager.update(0); - animationManager.update(1); - - strictEqual(animationManager._anims.array.length, 0, 'playing animators should be 0'); - strictEqual(animation._animator._anims.array.length, 0, 'playing anims should be 0'); - - animation.play('test'); - animationManager.update(0.5); - - strictEqual(animationManager._anims.array.length, 1, 'playing animators should be 1'); - strictEqual(animation._animator._anims.array.length, 1, 'playing anims should be 1'); - - animation.stop(); - - strictEqual(animationManager._anims.array.length, 0, 'playing animators should be 0'); - strictEqual(animation._animator._anims.array.length, 0, 'playing anims should be 0'); -}); - -test('play Animation', function () { - var entity = new cc.Node(); - var animation = entity.addComponent(cc.Animation); - - var clip = new cc.AnimationClip(); - clip._name = 'move'; - clip._duration = 1; - clip.curveData = { - props: { - x: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - animation.addClip(clip); - - clip = new cc.AnimationClip(); - clip._name = 'rotate'; - clip._duration = 1; - clip.curveData = { - props: { - rotation: [ - {frame: 0, value: 0}, - {frame: 1, value: 90} - ] - } - }; - animation.addClip(clip); - - clip = new cc.AnimationClip(); - clip._name = 'scale'; - clip._duration = 1; - clip.curveData = { - props: { - scaleX: [ - {frame: 0, value: 1}, - {frame: 1, value: 2} - ] - } - }; - animation.addClip(clip); - - var moveState = animation.getAnimationState('move'); - var rotateState = animation.getAnimationState('rotate'); - - strictEqual(moveState.isPlaying, false, 'move animation state should not be playing'); - strictEqual(rotateState.isPlaying, false, 'rotate animation state should not be playing'); - - animation.play('move'); - strictEqual(moveState.isPlaying, true, 'move animation state should be playing'); - strictEqual(rotateState.isPlaying, false, 'rotate animation state should not be playing'); - - animation.play('rotate'); - strictEqual(moveState.isPlaying, false, 'move animation state should not be playing'); - strictEqual(rotateState.isPlaying, true, 'rotate animation state should be playing'); - - animation.playAdditive('move'); - strictEqual(moveState.isPlaying, true, 'move animation state should be playing'); - strictEqual(rotateState.isPlaying, true, 'rotate animation state should be playing'); - - animation.play('scale'); - strictEqual(moveState.isPlaying, false, 'move animation state should not be playing'); - strictEqual(rotateState.isPlaying, false, 'rotate animation state should be playing'); - - animation.stop(); -}); - -test('animation enabled/disabled', function () { - var scene = cc.director.getScene(); - var entity = new cc.Node(); - var animation = entity.addComponent(cc.Animation); - - entity.parent = scene; - - var clip = new cc.AnimationClip(); - clip._name = 'move'; - clip._duration = 1; - clip.curveData = { - props: { - x: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - animation.addClip(clip); - animation.play('move'); - - animation.enabled = false; - - strictEqual(animation._animator.isPlaying, true, 'move animation should be playing'); - strictEqual(animation._animator.isPaused, true, 'move animation should be paused'); - - animation.enabled = true; - - strictEqual(animation._animator.isPlaying, true, 'move animation should be playing'); - strictEqual(animation._animator.isPaused, false, 'move animation should be resumed'); - - entity.parent = null; -}); - -test('animation removeClip', function () { - var entity = new cc.Node(); - var animation = entity.addComponent(cc.Animation); - - var clip1 = new cc.AnimationClip(); - clip1._name = 'clip1'; - clip1._duration = 1; - clip1.curveData = { - props: { - x: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - animation.addClip(clip1); - animation._defaultClip = clip1; - - var clip2 = new cc.AnimationClip(); - clip2._name = 'clip2'; - clip2._duration = 1; - clip2.curveData = { - props: { - y: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - animation.addClip(clip2); - - animation.removeClip(clip1); - strictEqual(animation._clips.indexOf(clip1), 0, 'clip1 will not be removed since clip1 is defaultClip'); - - animation.removeClip(clip1, true); - strictEqual(animation._clips.indexOf(clip1), -1, 'clip1 will be removed even it\'t defaultClip if force is true'); - strictEqual(animation.defaultClip, null, 'defaultClip will be reset to null'); - - animation.play('clip2'); - animation.removeClip(clip2); - strictEqual(animation._clips.indexOf(clip2), 0, 'clip2 will not be removed since clip2 is playing'); - - animation.removeClip(clip2, true); - strictEqual(animation._clips.indexOf(clip2), -1, 'clip2 will be removed even clip2 is playing if force is true'); - - animation.stop(); -}); - -test('animation callback', function () { - var type; - - function callback (t, state) { - strictEqual(state instanceof cc.AnimationState, true); - strictEqual(state.name === 'move', true); - - type = t; - } - - var manager = cc.director.getAnimationManager(); - - var entity = new cc.Node(); - var animation = entity.addComponent(cc.Animation); - - cc.director.getScene().addChild(entity); - - var clip = new cc.AnimationClip(); - clip._name = 'move'; - clip._duration = 1; - clip.curveData = { - props: { - x: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - animation.addClip(clip); - - var state = animation.getAnimationState('move'); - - animation.on('play', callback); - animation.on('pause', callback); - animation.on('resume', callback); - animation.on('stop', callback); - - animation.play('move'); - manager.update(0); - strictEqual(type === 'play', true, 'should trigger play callback'); - - animation.pause('move'); - manager.update(0); - strictEqual(type === 'pause', true, 'should trigger pause callback'); - - animation.resume('move'); - manager.update(0); - strictEqual(type === 'resume', true, 'should trigger resume callback'); - - manager.update(0); - manager.update(1); - strictEqual(type === 'stop', true, 'should trigger stop callback'); - - type = ''; - - animation.off('play', callback); - - animation.play('move'); - manager.update(0); - strictEqual(type === '', true, 'should not trigger callback'); - - animation.off('pause', callback); - animation.off('resume', callback); - - animation.pause('move'); - manager.update(0); - strictEqual(type === 'pause', false, 'should not trigger pause callback'); - - animation.on('resume', callback); - animation.resume('move'); - manager.update(0); - strictEqual(type === 'resume', true, 'should trigger resume callback'); - - animation.on('finished', callback); - manager.update(1); - strictEqual(type === 'finished', true, 'should trigger finished callback'); - - - clip = new cc.AnimationClip(); - clip._name = 'move2'; - clip._duration = 1; - clip.curveData = { - props: { - x: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - animation.addClip(clip); - - var list = []; - function callback2 (t, state) { - list.push([state.name, t]); - } - - animation.play('move'); - manager.update(0); - - animation.on('play', callback2); - animation.on('stop', callback2); - - animation.play('move2'); - manager.update(0); - deepEqual(list, [['move2', 'play'], ['move', 'stop']]); - - animation.stop(); -}); - -test('animation callback', function () { - var entity = new cc.Node(); - - var animation = entity.addComponent(cc.Animation); - - clip = new cc.AnimationClip(); - clip._name = 'test'; - clip._duration = 1; - clip.curveData = { - props: { - x: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - - animation.addClip(clip); - - animation.play('test'); - animation.setCurrentTime(0.5,'test'); - strictEqual(entity.x, 50, 'entity.x should be 50'); - - animation.setCurrentTime(0.7); - strictEqual(entity.x, 70, 'entity.x should be 70'); - - animation.stop(); -}); - -test('animation delay', function () { - var entity = new cc.Node(); - - var animation = entity.addComponent(cc.Animation); - - clip = new cc.AnimationClip(); - clip._name = 'test'; - clip._duration = 1; - clip.curveData = { - props: { - x: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - - animation.addClip(clip); - - var state = animation.play('test'); - - state.delay = 5; - - strictEqual(state._delayTime, 5, 'delay time should be 5'); - - state.update(3); - strictEqual(state._delayTime, 2, 'delay time should be 2'); - strictEqual(entity.x, 0, 'entity should not changed during delay'); - - state.update(2); - strictEqual(state._delayTime === 0, true, 'delay time should be 0'); - - state.update(1); - strictEqual(entity.x, 100, 'entity should move to end'); - strictEqual(state.isPlaying, false, 'animation should end.'); - - state = animation.play('test'); - - strictEqual(state._delayTime, 5, 'delay time should reset when replay'); - - animation.stop(); -}); - -test('animation pause/resume', function () { - var entity = new cc.Node(); - entity.parent = cc.director.getScene(); - - var animation = entity.addComponent(cc.Animation); - - clip = new cc.AnimationClip(); - clip._name = 'test'; - clip._duration = 1; - clip.curveData = { - props: { - x: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - - animation.addClip(clip); - - animation.play('test'); - - animation.pause(); - strictEqual(animation._animator._isPaused, true, 'animation should be paused'); - - entity.active = false; - strictEqual(animation._animator._isPaused, true, 'animation should be paused'); - - entity.active = true; - strictEqual(animation._animator._isPaused, true, 'animation should be paused'); - - animation.resume(); - strictEqual(animation._animator._isPaused, false, 'animation should not be paused'); - - entity.parent = null; -}); - -test('animation pause/resume should remove animation-actor from animation manager', function () { - var entity = new cc.Node(); - entity.parent = cc.director.getScene(); - - var animation = entity.addComponent(cc.Animation); - - clip = new cc.AnimationClip(); - clip._name = 'test'; - clip._duration = 1; - clip.curveData = { - props: { - x: [ - {frame: 0, value: 0}, - {frame: 1, value: 100} - ] - } - }; - - animation.addClip(clip); - - var manager = cc.director.getAnimationManager(); - - var state = animation.play('test'); - strictEqual(manager._anims.array.length, 1, 'should add 1 animation to animation manager'); - - animation.pause(); - strictEqual(manager._anims.array.length, 0, 'should remove animation from animation manager'); - strictEqual(state.animator, null, 'should unbind animator to animation state when pause animation'); - - animation.resume(); - strictEqual(manager._anims.array.length, 1, 'should add 1 animation to animation manager'); - strictEqual(state.animator, animation._animator, 'should rebind animator to animation state when pause animation'); - - animation.stop(); - strictEqual(manager._anims.array.length, 0, 'should remove animation from animation manager'); - - // should not see error log in console - animation.play('test'); - animation.pause(); - animation.stop(); - - animation.play('test'); - entity.parent = null; - - strictEqual(manager._anims.array.length, 0, 'should remove animation from animation manager'); -}); - - -test('animation play on load', function () { - var entity = new cc.Node(); - - var animation = entity.addComponent(cc.Animation); - animation.playOnLoad = true; - - var clip1 = new cc.AnimationClip(); - clip1._name = 'clip1'; - clip1._duration = 1; - - var clip2 = new cc.AnimationClip(); - clip2._name = 'clip2'; - clip2._duration = 1; - - - animation.addClip(clip1); - animation.addClip(clip2); - - animation._defaultClip = clip1; - - animation.play('clip2'); - - entity.parent = cc.director.getScene(); - animation.start(); - - strictEqual(animation.getAnimationState('clip1').isPlaying, false, 'default clip should not be played if there is playing animation'); - strictEqual(animation.getAnimationState('clip2').isPlaying, true, 'should play the specified animation'); - - entity.parent = null; -}); diff --git a/tests/init.ts b/tests/init.ts index 7541dd8337..656f55cb2e 100644 --- a/tests/init.ts +++ b/tests/init.ts @@ -1,5 +1,5 @@ import '../exports/base'; -import { DebugMode } from "../cocos/core/platform/CCDebug"; +import { DebugMode } from "../cocos/core/platform/debug"; // @ts-ignore diff --git a/tests/page.html b/tests/page.html deleted file mode 100644 index ec64312b1d..0000000000 --- a/tests/page.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - -

Testing Cocos2d-JS

- - - - - diff --git a/tests/page.js b/tests/page.js deleted file mode 100644 index cea600dc8d..0000000000 --- a/tests/page.js +++ /dev/null @@ -1,31 +0,0 @@ -var Ipc = require('ipc'); - -describe('test cocos', function () { - var win; - - // close window afterward - after(function ( done ) { - win.close(); - win.nativeWin.on('closed', function () { - win.dispose(); - done(); - }); - }); - - // - it('running on page-level', function( done ) { - this.timeout(0); - Ipc.on('runner:end', function () { - done(); - }); - - win = new Editor.Window('main', { - title: 'Test Cocos', - width: 800, - height: 800, - show: true, - resizable: false, - }); - win.load('unpack://engine/test/page.html'); - }); -}); diff --git a/tsconfig.json b/tsconfig.json index b0b69d068b..8ede121d1a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -16,8 +16,8 @@ "./@types/globals", "./@types/ammo.js", "./@types/wx", - "./cocos/gfx/webgl/WebGL", - "./cocos/gfx/webgl2/WebGL2", + "./cocos/core/gfx/webgl/WebGL", + "./cocos/core/gfx/webgl2/WebGL2", "./node_modules/tween.js/TWEEN", "./node_modules/@types/jest/index" ],