From 3ed9edfbc6d6caf95a96a083ceb2fd4e7c78cd15 Mon Sep 17 00:00:00 2001 From: Leslie Leigh Date: Thu, 27 Dec 2018 12:03:10 +0800 Subject: [PATCH] phy framework (#3644) * phy framework * phy mat * framework/index.ts * a node can have more than one collider * rename physical to physics * fix * fix * support mix ts js * fix * fix problems in issue * fix * remove RigidBodyType, add DataFlow * useGravity, freezeRotation, isKinematic * raycasts * fit buildin-world raycast options * add contact material * lint * add rigid-body-component.ts * some improvements * improvements * fix bug --- cocos/3d/assets/index.js | 4 +- cocos/3d/assets/physics/material.ts | 54 ++ cocos/3d/assets/utils/gltf-utils.js | 703 ------------------ cocos/3d/framework/camera-component.js | 12 + cocos/3d/framework/index.js | 7 + cocos/3d/framework/physics/body.ts | 420 +++++++++++ .../framework/physics/collider-component.ts | 121 +++ .../3d/framework/physics/contact-material.ts | 88 +++ .../physics/detail/physics-based-component.ts | 65 ++ cocos/3d/framework/physics/index.ts | 19 + cocos/3d/framework/physics/physics-system.ts | 17 + .../framework/physics/rigid-body-component.ts | 108 +++ cocos/3d/framework/physics/util.ts | 27 + cocos/3d/framework/physics/world.ts | 127 ++++ .../3d/framework/skinning-model-component.js | 1 - cocos/assets/texture-2d.js | 9 +- cocos/components/CCComponent.js | 2 +- cocos/core/CCDirector.js | 11 + cocos/scene-graph/base-node.js | 2 +- package.json | 17 +- rollup/babel-plugin-mix-ts-js.js | 31 + rollup/config.js | 103 ++- 22 files changed, 1189 insertions(+), 759 deletions(-) create mode 100644 cocos/3d/assets/physics/material.ts delete mode 100644 cocos/3d/assets/utils/gltf-utils.js create mode 100644 cocos/3d/framework/physics/body.ts create mode 100644 cocos/3d/framework/physics/collider-component.ts create mode 100644 cocos/3d/framework/physics/contact-material.ts create mode 100644 cocos/3d/framework/physics/detail/physics-based-component.ts create mode 100644 cocos/3d/framework/physics/index.ts create mode 100644 cocos/3d/framework/physics/physics-system.ts create mode 100644 cocos/3d/framework/physics/rigid-body-component.ts create mode 100644 cocos/3d/framework/physics/util.ts create mode 100644 cocos/3d/framework/physics/world.ts create mode 100644 rollup/babel-plugin-mix-ts-js.js diff --git a/cocos/3d/assets/index.js b/cocos/3d/assets/index.js index bab2bbae25..f44eda0443 100644 --- a/cocos/3d/assets/index.js +++ b/cocos/3d/assets/index.js @@ -34,4 +34,6 @@ import "./skeleton"; import "./sprite"; import "./web-audio-clip"; import "./wx-game-audio-clip"; -import "./utils/gltf-utils.js"; + +import { PhysicsMaterial } from './physics/material'; +cc.PhysicsMaterial = PhysicsMaterial; \ No newline at end of file diff --git a/cocos/3d/assets/physics/material.ts b/cocos/3d/assets/physics/material.ts new file mode 100644 index 0000000000..b44256eab7 --- /dev/null +++ b/cocos/3d/assets/physics/material.ts @@ -0,0 +1,54 @@ + +// @ts-check + +import CANNON from 'cannon'; +import Asset from '../../../assets/CCAsset'; +import { ccclass, property } from '../../../core/data/class-decorator'; + +@ccclass('cc.PhysicalMaterial') +export class PhysicsMaterial extends Asset { + @property + public _friction = -1; + + @property + public _restitution = -1; + + private _cannonMaterial: CANNON.Material; + + /** + * Friction for this material. + * If non-negative, it will be used instead of the friction given by ContactMaterials. + * If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used. + */ + get friction() { + return this._friction; + } + + set friction(value) { + this._friction = value; + this._cannonMaterial.friction = value; + } + + /** + * Restitution for this material. + * If non-negative, it will be used instead of the restitution given by ContactMaterials. + * If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used + */ + get restitution() { + return this._restitution; + } + + set restitution(value) { + this._restitution = value; + this._cannonMaterial.restitution = value; + } + + constructor() { + super(); + this._cannonMaterial = new CANNON.Material(''); + } + + public _getImpl() { + return this._cannonMaterial; + } +} diff --git a/cocos/3d/assets/utils/gltf-utils.js b/cocos/3d/assets/utils/gltf-utils.js deleted file mode 100644 index 21784e6e13..0000000000 --- a/cocos/3d/assets/utils/gltf-utils.js +++ /dev/null @@ -1,703 +0,0 @@ -// @ts-check -import gfx from "../../../renderer/gfx"; -import { enums as gfxEnums } from "../../../renderer/gfx/enums"; -import { vec3 } from "../../../core/vmath"; -import Node from "../../../scene-graph/node"; -import Texture from "../../../assets/texture-2d"; -import { WrapMode, Filter } from "../../../assets/texture-base"; -import Material from "../material"; -import Mesh, { Primitive, VertexBundle } from "../mesh"; -import BufferRange from "./buffer-range"; -import Skeleton from "../skeleton"; -import { Vec3, Mat4 } from "../../../core/value-types"; -import AnimationClip, { AnimationFrame, AnimationChannel } from "../animation-clip"; - -/** - * @typedef {import("../../../../types/glTF/glTF").GlTf} Gltf - * @typedef {import("../../../../types/glTF/glTF").Accessor} GltfAccessor - * @typedef {import("../../../../types/glTF/glTF").Buffer} GltfBuffer - * @typedef {import("../../../../types/glTF/glTF").BufferView} GltfBufferView - * @typedef {import("../../../../types/glTF/glTF").Node} GLTFNode - * @typedef {import("../../../../types/glTF/glTF").Sampler} GltfSampler - */ - -/** - * - * @param {GLTFNode} gltfNode - */ -export function createNode(gltfNode) { - let node = new Node(gltfNode.name); - - if (gltfNode.translation) { - node.setPosition( - gltfNode.translation[0], - gltfNode.translation[1], - gltfNode.translation[2] - ); - } - - if (gltfNode.rotation) { - node.setRotation( - gltfNode.rotation[0], - gltfNode.rotation[1], - gltfNode.rotation[2], - gltfNode.rotation[3] - ); - } - - if (gltfNode.scale) { - node.setScale( - gltfNode.scale[0], - gltfNode.scale[1], - gltfNode.scale[2] - ); - } - return node; -} - -class BufferBlob { - constructor() { - /** - * @type {ArrayBuffer[]} - */ - this._arrayByffers = []; - - this._length = 0; - } - - /** - * - * @param {ArrayBuffer} arrayBuffer - * @return {number} - */ - addBuffer(arrayBuffer) { - const result = this._length; - this._arrayByffers.push(arrayBuffer); - this._length += arrayBuffer.byteLength; - return result; - } - - getLength() { - return this._length; - } - - /** - * @return {ArrayBuffer} - */ - getCombined() { - let length = 0; - this._arrayByffers.forEach(arrayBuffer => length += arrayBuffer.byteLength); - const result = new Uint8Array(length); - let counter = 0; - this._arrayByffers.forEach(arrayBuffer => { - result.set(new Uint8Array(arrayBuffer), counter); - counter += arrayBuffer.byteLength; - }); - return result.buffer; - } -} - -export class GltfConverter { - /** - * - * @param {Gltf} gltf - * @param {Buffer[]} buffers - */ - constructor(gltf, buffers) { - /** - * @type {Gltf} - */ - this._gltf = gltf; - /** - * @type {Buffer[]} - */ - this._buffers = buffers; - } - - /** - * - * @param {number} index - * @return {{mesh: Mesh, buffer: ArrayBuffer}} - */ - createMesh(index) { - if (this._gltf.meshes === undefined || index >= this._gltf.meshes.length) { - return null; - } - - const gltfMesh = this._gltf.meshes[index]; - - const bufferBlob = new BufferBlob(); - - let minPosition = new Vec3(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); - let maxPosition = new Vec3(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); - - const vertexBundles = []; - const primitives = gltfMesh.primitives.map((gltfPrimitive, primitiveIndex) => { - const attributeNames = Object.getOwnPropertyNames(gltfPrimitive.attributes); - - let vertexBufferStride = 0; - let verticesCount = 0; - const formats = []; - - const attributeByteLengths = attributeNames.map((attributeName) => { - const attributeAccessor = this._requireGltfAccessor(gltfPrimitive.attributes[attributeName]); - const attributeByteLength = this._getBytesPerAttribute(attributeAccessor); - vertexBufferStride += attributeByteLength; - verticesCount = Math.max(verticesCount, attributeAccessor.count); - return attributeByteLength; - }); - - const vertexBuffer = new ArrayBuffer(vertexBufferStride * verticesCount); - - let currentByteOffset = 0; - attributeNames.forEach((attributeName, iAttribute) => { - const attributeAccessor = this._requireGltfAccessor(gltfPrimitive.attributes[attributeName]); - this._readAccessor(attributeAccessor, new DataView(vertexBuffer, currentByteOffset), vertexBufferStride); - currentByteOffset += attributeByteLengths[iAttribute]; - - if (attributeName === "POSITION") { - if (attributeAccessor.min) { - vec3.min(minPosition, minPosition, new vec3(attributeAccessor.min[0], attributeAccessor.min[1], attributeAccessor.min[2])); - } - if (attributeAccessor.max) { - vec3.max(maxPosition, maxPosition, new vec3(attributeAccessor.max[0], attributeAccessor.max[1], attributeAccessor.max[2])); - } - } - - formats.push({ - name: this._getGfxAttributeName(attributeName), - type: this._getGfxComponentType(attributeAccessor.componentType), - num: this._getComponentsPerAttribute(attributeAccessor.type) - }); - }); - - const vertexBundleRange = new BufferRange(bufferBlob.addBuffer(vertexBuffer), vertexBuffer.byteLength); - - const vertexBundle = new VertexBundle(); - vertexBundle._data = vertexBundleRange; - vertexBundle._verticesCount = verticesCount; - vertexBundle._formats = formats; - vertexBundles.push(vertexBundle); - - let indices = null; - let indexUnit = null; - if (gltfPrimitive.indices !== undefined) { - const indicesAccessor = this._requireGltfAccessor(gltfPrimitive.indices); - const indexStride = this._getBytesPerAttribute(indicesAccessor); - const indicesData = new ArrayBuffer(indexStride * indicesAccessor.count); - this._readAccessor(indicesAccessor, new DataView(indicesData)); - indices = new BufferRange(bufferBlob.addBuffer(indicesData), indicesData.byteLength); - indexUnit = this._getGfxIndexUnitType(indicesAccessor.componentType); - } - - const primitive = new Primitive(); - primitive._vertexBundelIndices = [primitiveIndex]; - primitive._topology = this._getTopology(gltfPrimitive.mode === undefined ? 4 : gltfPrimitive.mode); - primitive._indices = indices; - primitive._indexUnit = indexUnit; - return primitive; - }); - - const mesh = new Mesh(); - mesh.name = gltfMesh.name; - mesh._minPosition = minPosition; - mesh._maxPosition = maxPosition; - mesh._primitives = primitives; - mesh._vertexBundles = vertexBundles; - return { mesh, buffer: bufferBlob.getCombined() }; - } - - /** - * @param {number} index - * @param {string[]} nodePathTable - */ - createSkeleton(index, nodePathTable) { - if (this._gltf.skins === undefined || index >= this._gltf.skins.length) { - return null; - } - - const gltfSkin = this._gltf.skins[index]; - - const inverseBindMatrices = new Array(gltfSkin.joints.length); - if (gltfSkin.inverseBindMatrices === undefined) { - // The default is that each matrix is a 4x4 identity matrix, - // which implies that inverse-bind matrices were pre-applied. - for (let i = 0; i < inverseBindMatrices.length; ++i) { - inverseBindMatrices[i] = new Mat4( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ); - } - } else { - const inverseBindMatricesAccessor = this._requireGltfAccessor(gltfSkin.inverseBindMatrices); - if (inverseBindMatricesAccessor.componentType !== 5126 || - inverseBindMatricesAccessor.type !== "MAT4") { - throw `The inverse bind matrix should be floating-point 4x4 matrix.`; - } - const data = new Float32Array(inverseBindMatrices.length * 16); - this._readAccessor(inverseBindMatricesAccessor, new DataView(data.buffer)); - for (let i = 0; i < inverseBindMatrices.length; ++i) { - inverseBindMatrices[i] = new Mat4( - data[16 * i + 0], data[16 * i + 1], data[16 * i + 2], data[16 * i + 3], - data[16 * i + 4], data[16 * i + 5], data[16 * i + 6], data[16 * i + 7], - data[16 * i + 8], data[16 * i + 9], data[16 * i + 10], data[16 * i + 11], - data[16 * i + 12], data[16 * i + 13], data[16 * i + 14], data[16 * i + 15] - ); - } - } - - const skeleton = new Skeleton(); - skeleton.name = gltfSkin.name; - skeleton._joints = gltfSkin.joints.map(nodeIndex => nodePathTable[nodeIndex]); - skeleton._inverseBindMatrices = inverseBindMatrices; - - return skeleton; - } - - /** - * @param {number} index - * @param {string[]} nodePathTable - */ - createAnimation(index, nodePathTable) { - if (this._gltf.animations === undefined || index >= this._gltf.animations.length) { - return; - } - - let gltfAnimation = this._gltf.animations[index]; - - /** @type {AnimationFrame[]} */ - let frames = []; - let maxLength = 0; - - gltfAnimation.channels.forEach(gltfChannel => { - if (gltfChannel.target.node === undefined) { - // When node isn't defined, channel should be ignored. - return; - } - - const gltfSampler = gltfAnimation.samplers[gltfChannel.sampler]; - const inputAccessor = this._requireGltfAccessor(gltfSampler.input); - - // find frame by input name - /** @type {AnimationFrame} */ - let frame = frames.find((frame) => frame._name === inputAccessor.name); - - // if not found, create one - if (!frame) { - if (inputAccessor.componentType !== 5126 || - inputAccessor.type !== "SCALAR") { - throw `Input of an animation channel must be floating point scalars represent times.`; - } - const inputData = new Float32Array(inputAccessor.count); - this._readAccessor(inputAccessor, new DataView(inputData.buffer)); - - const times = new Array(inputData.length); - inputData.forEach((time, index) => { - times[index] = time; - }); - if (times.length > 0) { - maxLength = Math.max(maxLength, times[times.length - 1]); - } - - frame = new AnimationFrame(); - frame._name = inputAccessor.name; - frame._times = times; - frame._channels = []; - frames.push(frame); - } - - // find output frames by node id - /** @type {AnimationChannel} */ - let channel = frame._channels.find((channel) => channel.target === nodePathTable[gltfChannel.target.node]); - - // if not found, create one - if (!channel) { - channel = new AnimationChannel(); - channel.target = nodePathTable[gltfChannel.target.node]; - frame._channels.push(channel); - } - - const outputAccessor = this._requireGltfAccessor(gltfSampler.output); - if (outputAccessor.componentType !== 5126) { - throw `Output of an animation channel must be floating point values.`; - } - const outputData = new Float32Array(this._getComponentsPerAttribute(outputAccessor.type) * outputAccessor.count); - this._readAccessor(outputAccessor, new DataView(outputData.buffer)); - if (gltfChannel.target.path === 'translation') { - if (outputAccessor.type !== "VEC3") { - throw `Output of an animation channel targetting translation must be 3d vectors.`; - } - channel.positionCurve = new Array(outputAccessor.count); - for (let i = 0; i < outputAccessor.count; ++i) { - channel.positionCurve[i] = new cc.Vec3(outputData[3 * i + 0], outputData[3 * i + 1], outputData[3 * i + 2]); - } - } else if (gltfChannel.target.path === 'rotation') { - if (outputAccessor.type !== "VEC4") { - throw `Output of an animation channel targetting translation must be 4d vectors.`; - } - channel.rotationCurve = new Array(outputAccessor.count); - for (let i = 0; i < outputAccessor.count; ++i) { - channel.rotationCurve[i] = new cc.Quat(outputData[4 * i + 0], outputData[4 * i + 1], outputData[4 * i + 2], outputData[4 * i + 3]); - } - } else if (gltfChannel.target.path === 'scale') { - if (outputAccessor.type !== "VEC3") { - throw `Output of an animation channel targetting scale must be 3d vectors.`; - } - channel.scaleCurve = new Array(outputAccessor.count); - for (let i = 0; i < outputAccessor.count; ++i) { - channel.scaleCurve[i] = new cc.Vec3(outputData[3 * i + 0], outputData[3 * i + 1], outputData[3 * i + 2]); - } - } else { - throw `Unsupported channel target path.`; - } - }); - - const animationClip = new AnimationClip(); - animationClip.name = gltfAnimation.name; - animationClip._frames = frames; - animationClip._length = maxLength; - return animationClip; - } - - /** - * - * @param {number} index - * @param {Texture} textures - */ - createMaterial(index, textures) { - if (this._gltf.materials === undefined || index >= this._gltf.materials.length) { - return null; - } - - const gltfMaterial = this._gltf.materials[index]; - - const material = new Material(); - material.name = gltfMaterial.name; - material.effectName = "builtin-effect-unlit"; - if (gltfMaterial.pbrMetallicRoughness) { - const pbrMetallicRoughness = gltfMaterial.pbrMetallicRoughness; - if (pbrMetallicRoughness.baseColorTexture) { - material.define("USE_TEXTURE", true); - material.setProperty("mainTexture", textures[pbrMetallicRoughness.baseColorTexture.index]); - } else { - material.define("USE_COLOR", true); - let color = null; - if (pbrMetallicRoughness.baseColorFactor) { - const c = pbrMetallicRoughness.baseColorFactor; - color = new cc.Color(c[0] * 255, c[1] * 255, c[2] * 255, c[3] * 255); - } else { - color = new cc.Color(255, 255, 255, 255); - } - material.setProperty("color", color); - } - } - - return material; - } - - /** - * - * @param {number} index - */ - createTexture(index) { - if (this._gltf.textures === undefined || index >= this._gltf.textures.length) { - return null; - } - - const gltfTexture = this._gltf.textures[index]; - const texture = new Texture(); - texture.name = gltfTexture.name; - if (gltfTexture.sampler === undefined) { - texture.setWrapMode(WrapMode.REPEAT, WrapMode.REPEAT); - } else { - const gltfSampler = this._requireSampler(gltfTexture.sampler); - texture.setFilters( - gltfSampler.minFilter === undefined ? undefined : this._getFilter(gltfSampler.minFilter), - gltfSampler.magFilter === undefined ? undefined : this._getFilter(gltfSampler.magFilter) - ); - texture.setWrapMode( - this._getWrapMode(gltfSampler.wrapS === undefined ? 10497 : gltfSampler.wrapS), - this._getWrapMode(gltfSampler.wrapT === undefined ? 10497 : gltfSampler.wrapT), - ); - } - - return texture; - } - - createNodePathTable() { - if (this._gltf.nodes === undefined) { - return []; - } - - /** @type {string[]} */ - const result = new Array(this._gltf.nodes.length); - result.fill(""); - this._gltf.nodes.forEach((gltfNode, nodeIndex) => { - const myPath = result[nodeIndex] + gltfNode.name; - result[nodeIndex] = myPath; - if (gltfNode.children) { - gltfNode.children.forEach(childNodeIndex => { - const childPath = result[childNodeIndex]; - result[childNodeIndex] = `${myPath}/${childPath}`; - }); - } - }); - // Remove root segment - result.forEach((path, index) => { - let segments = path.split('/'); - segments.shift(); - result[index] = segments.join('/'); - }); - - return result; - } - - /** - * - * @param {GltfAccessor} gltfAccessor - * @param {DataView} outputBuffer - * @param {number} outputStride - */ - _readAccessor(gltfAccessor, outputBuffer, outputStride = 0) { - const gltfBufferView = this._requireGltfBufferView(gltfAccessor.bufferView); - - const componentsPerAttribute = this._getComponentsPerAttribute(gltfAccessor.type); - const bytesPerElement = this._getBytesPerComponent(gltfAccessor.componentType); - - if (outputStride === 0) { - outputStride = componentsPerAttribute * bytesPerElement; - } - - const inputStartOffset = - (gltfAccessor.byteOffset !== undefined ? gltfAccessor.byteOffset : 0) + - (gltfBufferView.byteOffset !== undefined ? gltfBufferView.byteOffset : 0); - - const inputBuffer = new DataView(this._buffers[gltfBufferView.buffer].buffer, inputStartOffset); - - const inputStride = gltfBufferView.byteStride !== undefined ? gltfBufferView.byteStride : componentsPerAttribute * bytesPerElement; - - const componentReader = this._getComponentReader(gltfAccessor.componentType); - const componentWriter = this._getComponentWriter(gltfAccessor.componentType); - - for (let iAttribute = 0; iAttribute < gltfAccessor.count; ++iAttribute) { - const i = new DataView(inputBuffer.buffer, inputBuffer.byteOffset + inputStride * iAttribute); - const o = new DataView(outputBuffer.buffer, outputBuffer.byteOffset + outputStride * iAttribute); - for (let iComponent = 0; iComponent < componentsPerAttribute; ++iComponent) { - const componentBytesOffset = bytesPerElement * iComponent; - const value = componentReader(i, componentBytesOffset); - componentWriter(o, componentBytesOffset, value); - } - } - } - - /** - * - * @param {number} mode - */ - _getTopology(mode) { - switch (mode) { - case 0: return gfxEnums.PT_POINTS; - case 1: return gfxEnums.PT_LINES; - case 2: return gfxEnums.PT_LINE_LOOP; - case 3: return gfxEnums.PT_LINE_STRIP; - case 4: return gfxEnums.PT_TRIANGLES; - case 5: return gfxEnums.PT_TRIANGLE_STRIP; - case 6: return gfxEnums.PT_TRIANGLE_FAN; - default: - throw `Unrecognized primitive mode: ${mode}.`; - } - } - - /** - * - * @param {number} componentType - */ - _getGfxIndexUnitType(componentType) { - return componentType; - } - - /** - * - * @param {number} componentType - */ - _getGfxComponentType(componentType) { - return componentType; - } - - /** - * - * @param {GltfAccessor} gltfAccessor - */ - _getBytesPerAttribute(gltfAccessor) { - return this._getBytesPerComponent(gltfAccessor.componentType) * this._getComponentsPerAttribute(gltfAccessor.type); - } - - /** - * - * @param {string} type - */ - _getComponentsPerAttribute(type) { - switch (type) { - case "SCALAR": return 1; - case "VEC2": return 2; - case "VEC3": return 3; - case "VEC4": case "MAT2": return 4; - case "MAT3": return 9; - case "MAT4": return 16; - default: - throw `Unrecognized attribute type: ${type}.`; - } - } - - /** - * - * @param {number} componentType - */ - _getBytesPerComponent(componentType) { - switch (componentType) { - case 5120: case 5121: return 1; - case 5122: case 5123: return 2; - case 5125: case 5126: return 4; - default: - throw `Unrecognized component type: ${componentType}`; - } - } - - /** - * - * @param {string} name - */ - _getGfxAttributeName(name) { - switch (name) { - case "POSITION": return gfx.ATTR_POSITION; - case "NORMAL": return gfx.ATTR_NORMAL; - case "TANGENT": return gfx.ATTR_TANGENT; - case "COLOR_0": return gfx.ATTR_COLOR0; - case "TEXCOORD_0": return gfx.ATTR_UV0; - case "TEXCOORD_1": return gfx.ATTR_UV1; - case "TEXCOORD_2": return gfx.ATTR_UV2; - case "TEXCOORD_3": return gfx.ATTR_UV3; - case "JOINTS_0": return gfx.ATTR_JOINTS; - case "WEIGHTS_0": return gfx.ATTR_WEIGHTS; - default: - throw `Unrecognized attribute type: ${name}`; - } - } - - /** - * - * @param {number} componentType - * @return {(buffer: DataView, offset: number) => number} - */ - _getComponentReader(componentType) { - switch (componentType) { - case 5120: return (buffer, offset) => buffer.getInt8(offset); - case 5121: return (buffer, offset) => buffer.getUint8(offset); - case 5122: return (buffer, offset) => buffer.getInt16(offset, true); - case 5123: return (buffer, offset) => buffer.getUint16(offset, true); - case 5125: return (buffer, offset) => buffer.getUint32(offset, true); - case 5126: return (buffer, offset) => buffer.getFloat32(offset, true); - default: - throw `Unrecognized component type: ${componentType}`; - } - } - - /** - * - * @param {number} componentType - * @return {(buffer: DataView, offset: number, value: number) => void} - */ - _getComponentWriter(componentType) { - switch (componentType) { - case 5120: return (buffer, offset, value) => buffer.setInt8(offset, value); - case 5121: return (buffer, offset, value) => buffer.setUint8(offset, value); - case 5122: return (buffer, offset, value) => buffer.setInt16(offset, value, true); - case 5123: return (buffer, offset, value) => buffer.setUint16(offset, value, true); - case 5125: return (buffer, offset, value) => buffer.setUint32(offset, value, true); - case 5126: return (buffer, offset, value) => buffer.setFloat32(offset, value, true); - default: - throw `Unrecognized component type: ${componentType}`; - } - } - - /** - * - * @param {number} filter - */ - _getFilter(filter) { - switch (filter) { - case 9728: - return Filter.NEAREST; - case 9729: - return Filter.LINEAR; - default: - throw `Unrecognized filter: ${filter}.`; - } - } - - /** - * - * @param {number} wrapMode - */ - _getWrapMode(wrapMode) { - switch (wrapMode) { - case 33071: - return WrapMode.CLAMP_TO_EDGE; - case 33648: - return WrapMode.MIRRORED_REPEAT; - case 10497: - return WrapMode.REPEAT; - default: - throw `Unrecognized wrapMode: ${wrapMode}.`; - } - } - - /** - * - * @param {number} index - * @return {GltfBuffer} - */ - _requireGltfBuffer(index) { - if (this._gltf.buffers === undefined) { - throw `Buffers is require but it do not exists.`; - } - return this._gltf.buffers[index]; - } - - /** - * @return {GltfBufferView} - * @param {number} index - */ - _requireGltfBufferView(index) { - if (this._gltf.bufferViews === undefined) { - throw `BufferViews is require but it do not exists.`; - } - return this._gltf.bufferViews[index]; - } - - /** - * - * @param {number} index - * @return {GltfAccessor} - */ - _requireGltfAccessor(index) { - if (this._gltf.accessors === undefined) { - throw `Accessors is require but it do not exists.`; - } - return this._gltf.accessors[index]; - } - - /** - * @param {number} index - * @return {GltfSampler} - * @private - */ - _requireSampler(index) { - if (this._gltf.samplers === undefined) { - throw `Samplers is require but it do not exists.`; - } - return this._gltf.samplers[index]; - } -} diff --git a/cocos/3d/framework/camera-component.js b/cocos/3d/framework/camera-component.js index 6504eaacee..c7cedc8479 100644 --- a/cocos/3d/framework/camera-component.js +++ b/cocos/3d/framework/camera-component.js @@ -328,4 +328,16 @@ export default class CameraComponent extends RenderSystemActor{ onDisable() { this.scene.removeCamera(this._camera); } + + /** + * transform a screen position to world space + * @param out the resulting vector + * @param screenPos the screen position to be transformed + * @param width framebuffer width + * @param height framebuffer height + * @returns the resulting vector + */ + screenToWorld(out, screenPos, width, height) { + return this._camera.screenToWorld(out, screenPos, width, height); + } } diff --git a/cocos/3d/framework/index.js b/cocos/3d/framework/index.js index b1ea92f6bc..9dac6884b1 100644 --- a/cocos/3d/framework/index.js +++ b/cocos/3d/framework/index.js @@ -30,6 +30,9 @@ import LightComponent from './light-component'; import ModelComponent from './model-component'; import SkinningModelComponent from './skinning-model-component'; import SkyboxComponent from './skybox-component'; +import { BoxColliderComponent, SphereColliderComponent } from './physics/collider-component'; +import { RigidBodyComponent } from './physics/rigid-body-component'; +import './physics/index'; cc.CameraComponent = CameraComponent; cc.AnimationComponent = AnimationComponent; @@ -37,3 +40,7 @@ cc.LightComponent = LightComponent; cc.ModelComponent = ModelComponent; cc.SkinningModelComponent = SkinningModelComponent; cc.SkyboxComponent = SkyboxComponent; + +cc.RigidBodyComponent = RigidBodyComponent; +cc.BoxColliderComponent = BoxColliderComponent; +cc.SphereColliderComponent = SphereColliderComponent; \ No newline at end of file diff --git a/cocos/3d/framework/physics/body.ts b/cocos/3d/framework/physics/body.ts new file mode 100644 index 0000000000..93203c8691 --- /dev/null +++ b/cocos/3d/framework/physics/body.ts @@ -0,0 +1,420 @@ +import CANNON from 'cannon'; +import Vec3 from '../../../core/value-types/vec3'; +import { vec3 } from '../../../core/vmath'; +import Node from '../../../scene-graph/node'; +import { PhysicsMaterial as PhysicsMaterial } from '../../assets/physics/material'; +import { setWrap, getWrap } from './util'; + +export enum DataFlow { + PUSHING, + PULLING, +} + +export class PhysicsBody { + private _node: Node | null = null; + + private _material: PhysicsMaterial | null = null; + + private _cannonBody: CANNON.Body; + + private _onCollidedListener: (event: CANNON.ICollisionEvent) => any; + + private _onWorldBeforeStepListener: ((event: CANNON.IEvent) => any) | null = null; + + private _onWorldPostStepListener: ((event: CANNON.IEvent) => any) | null = null; + + private _cancelGravityListener: ((event: CANNON.IEvent) => any); + + private _shapes: Set = new Set(); + + private _dataflow: DataFlow = DataFlow.PULLING; + + private _useGravity = true; + + constructor() { + const cannonBodyOptions: CANNON.IBodyOptions = { + mass: 0, + // material: new CANNON.Material(''), + }; + + this._cannonBody = new CANNON.Body(cannonBodyOptions); + setWrap(this._cannonBody, this); + + this._onCollidedListener = this._onCollided.bind(this); + this._cannonBody.addEventListener('collide', this._onCollidedListener); + + this._cancelGravityListener = (event) => { + const gravity = this._cannonBody.world.gravity; + vec3.scaleAndAdd(this._cannonBody.force, this._cannonBody.force, gravity, this.mass * -1); + }; + } + + public bind(node: Node) { + this._node = node; + } + + public destroy() { + this._cannonBody.removeEventListener('collide', this._onCollidedListener); + } + + public _onAdded() { + this._onWorldBeforeStepListener = this._onWorldBeforeStep.bind(this); + this._cannonBody.world.addEventListener('beforeStep', this._onWorldBeforeStepListener); + + this._onWorldPostStepListener = this._onWorldPostStep.bind(this); + this._cannonBody.world.addEventListener('postStep', this._onWorldPostStepListener); + } + + public _onRemoved() { + if (this._cannonBody.world) { + if (this._onWorldPostStepListener) { + this._cannonBody.world.removeEventListener('postStep', this._onWorldPostStepListener); + } + + if (this._onWorldBeforeStepListener) { + this._cannonBody.world.removeEventListener('beforeStep', this._onWorldBeforeStepListener); + } + + this._cannonBody.world.removeEventListener('beforeStep', this._cancelGravityListener); + } + } + + public _getCannonBody() { + return this._cannonBody; + } + + public addShape(shape: PhysicsShape) { + // if (this._node) { + // shape.__debugNodeName = this._node.name; + // } + if (this._node) { + shape.scale = this._node.getWorldScale(); + } + this._shapes.add(shape); + this._cannonBody.addShape(shape._getCannonShape()); + this.commitShapesUpdate(); + } + + public removeShape(shape: PhysicsShape) { + throw new Error(`not impl`); + } + + public getCenter(shape: PhysicsShape) { + const iShape = this._cannonBody.shapes.indexOf(shape._getCannonShape()); + if (iShape >= 0) { + const shapeOffset = this._cannonBody.shapeOffsets[iShape]; + return new Vec3(shapeOffset.x, shapeOffset.y, shapeOffset.z); + } + throw new Error(`shape not found.`); + } + + public setCenter(shape: PhysicsShape, center: Vec3) { + const iShape = this._cannonBody.shapes.indexOf(shape._getCannonShape()); + if (iShape >= 0) { + this._cannonBody.shapeOffsets[iShape].set(center.x, center.y, center.z); + } + } + + get velocity() { + return this._cannonBody.velocity; + } + + get force() { + return this._cannonBody.force; + } + + public applyForce(force: cc.Vec3, position?: cc.Vec3) { + if (!position) { + position = this._cannonBody.position; + } + this._cannonBody.applyForce(force, position); + } + + get material() { + return this._material; + } + + set material(value) { + this._material = value; + if (!this._material) { + return; + } + + this._cannonBody.material = this._material._getImpl(); + } + + get mass() { + return this._cannonBody.mass; + } + + set mass(value) { + this._cannonBody.mass = value; + this._cannonBody.updateMassProperties(); + if (this._cannonBody.type !== CANNON.Body.KINEMATIC) { + this._resetBodyTypeAccordingMess(); + this._onBodyTypeUpdated(); + } + } + + get isKinematic() { + return this._cannonBody.type === CANNON.Body.KINEMATIC; + } + + set isKinematic(value) { + if (value) { + this._cannonBody.type = CANNON.Body.KINEMATIC; + } else { + this._resetBodyTypeAccordingMess(); + } + this._onBodyTypeUpdated(); + } + + get useGravity() { + return this._useGravity; + } + + set useGravity(value) { + this._useGravity = value; + if (this._useGravity) { + this._cannonBody.world.removeEventListener('beforeStep', this._cancelGravityListener); + } else { + this._cannonBody.world.addEventListener('beforeStep', this._cancelGravityListener); + } + } + + get freezeRotation() { + return this._cannonBody.fixedRotation; + } + + set freezeRotation(value) { + this._cannonBody.fixedRotation = value; + this._cannonBody.updateMassProperties(); + } + + get linearDamping() { + return this._cannonBody.linearDamping; + } + + set linearDamping(value) { + this._cannonBody.linearDamping = value; + } + + get angularDamping() { + return this._cannonBody.angularDamping; + } + + set angularDamping(value) { + this._cannonBody.angularDamping = value; + } + + get isTrigger() { + return this._cannonBody.collisionResponse; + } + + set isTrigger(value) { + this._cannonBody.collisionResponse = value; + } + + get dataFlow() { + return this._dataflow; + } + + /** + * Set the collision filter of this body, remember that they are tested bitwise. + * @param {number} group The group which this body will be put into. + * @param {number} mask The groups which this body can collide with. + */ + public setCollisionFilter(group: number, mask: number) { + this._cannonBody.collisionFilterGroup = group; + this._cannonBody.collisionFilterMask = mask; + } + + public setWorldPosition(position: Vec3) { + this._cannonBody.position.set(position.x, position.y, position.z); + } + + /** + * Is this body currently in contact with the specified body? + * @param {CannonBody} body The body to test against. + */ + public isInContactWith(body: PhysicsBody) { + if (!this._cannonBody.world) { + return false; + } + + return this._cannonBody.world.collisionMatrix.get( + this._cannonBody.id, body._cannonBody.id) > 0; + } + + public commitShapesUpdate() { + this._cannonBody.updateBoundingRadius(); + } + + private _onCollided(event: CANNON.ICollisionEvent) { + // console.log(`Collided {${getWrap(event.body)._node.name}} and {${getWrap(event.target)._node.name}}.`); + } + + private _onWorldBeforeStep(event: CANNON.IEvent) { + if (this._dataflow === DataFlow.PULLING) { + this._pull(); + } + } + + private _onWorldPostStep(event: CANNON.IEvent) { + if (this._dataflow === DataFlow.PUSHING) { + this._push(); + } + } + + /** + * Pull node's transform information into rigidbody. + */ + private _pull() { + if (!this._node) { + return; + } + + if (!this._node._hasChanged) { + return; + } + + // @ts-nocheck + this._node.getWorldPosition(this._cannonBody.position); + // @ts-nocheck + this._node.getWorldRotation(this._cannonBody.quaternion); + const scale = this._node.getWorldScale(); + let shapeUpdated = false; + this._shapes.forEach((shape) => { + if (!vec3.exactEquals(scale, shape.scale)) { + shape.scale = scale; + shapeUpdated = true; + } + }); + if (shapeUpdated) { + this.commitShapesUpdate(); + } + } + + /** + * Push the rigidbody's transform information back to node. + */ + private _push() { + if (!this._node) { + return; + } + + const p = this._cannonBody.position; + this._node.setWorldPosition(p.x, p.y, p.z); + if (!this._cannonBody.fixedRotation) { + const q = this._cannonBody.quaternion; + this._node.setWorldRotation(q.x, q.y, q.z, q.w); + } + } + + private _resetBodyTypeAccordingMess() { + if (this.mass <= 0) { + this._cannonBody.type = CANNON.Body.STATIC; + } else { + this._cannonBody.type = CANNON.Body.DYNAMIC + } + } + + private _onBodyTypeUpdated() { + if (this._cannonBody.type !== CANNON.Body.STATIC) { + this._dataflow = DataFlow.PUSHING; + } else { + this._dataflow = DataFlow.PULLING; + } + } +} + +export class PhysicsShape { + // public __debugNodeName: string = ''; + + private _scale: cc.Vec3 = new cc.Vec3(1.0, 1.0, 1.0); + + constructor(private _cannonShape: CANNON.Shape) { + setWrap(this._cannonShape, this); + } + + public get scale() { + return this._scale; + } + + public set scale(value) { + vec3.copy(this._scale, value); + this._onShapeParamUpdated(); + } + + public _getCannonShape() { + return this._cannonShape as T; + } + + protected _onShapeParamUpdated() { + } +} + +export class PhysicsBoxShape extends PhysicsShape { + private _size: cc.Vec3; + + constructor(size: Vec3) { + super(new CANNON.Box(new CANNON.Vec3(size.x / 2, size.y / 2, size.z / 2))); + + this._size = new cc.Vec3(size.x, size.y, size.z); + } + + public get size() { + return this._size; + } + + public set size(value) { + vec3.copy(this._size, value); + this._onShapeParamUpdated(); + } + + protected _onShapeParamUpdated() { + const shape = this._getCannonShape(); + if (!shape.halfExtents) { + shape.halfExtents = new CANNON.Vec3(); + } + + const newHalfExtents = shape.halfExtents; + vec3.multiply(newHalfExtents, this._size, this.scale); + vec3.scale(newHalfExtents, newHalfExtents, 0.5); + // shape.updateBoundingSphereRadius(); + shape.updateConvexPolyhedronRepresentation(); + + // console.log(`Set ${this.__debugNodeName} halfExtents to ${shape.halfExtents.x}, ${shape.halfExtents.y},${shape.halfExtents.z}.`); + } +} + +export class PhysicsSphereShape extends PhysicsShape { + private _radius: number; + + constructor(radius: number) { + super(new CANNON.Sphere(radius)); + + this._radius = radius; + } + + public get radius() { + return this._radius; + } + + public set radius(value) { + this._radius = value; + this._onShapeParamUpdated(); + } + + protected _onShapeParamUpdated() { + const shape = this._getCannonShape(); + shape.radius = this._radius * maxComponent(this.scale); + // shape.updateBoundingSphereRadius(); + + // console.log(`Set ${this.__debugNodeName} radius to ${shape.radius}.`); + } +} + +function maxComponent(v: { x: number, y: number, z: number }) { + return Math.max(v.x, Math.max(v.y, v.z)); +} diff --git a/cocos/3d/framework/physics/collider-component.ts b/cocos/3d/framework/physics/collider-component.ts new file mode 100644 index 0000000000..06e6d1d527 --- /dev/null +++ b/cocos/3d/framework/physics/collider-component.ts @@ -0,0 +1,121 @@ + +import { + ccclass, + executeInEditMode, + executionOrder, + menu, + property +} from '../../../core/data/class-decorator'; +import Vec3 from '../../../core/value-types/vec3'; +import { PhysicsBoxShape, PhysicsShape, PhysicsSphereShape } from './body'; +import { PhysicsBasedComponent } from './detail/physics-based-component'; + +@ccclass('cc.ColliderComponentBase') +export class ColliderComponentBase extends PhysicsBasedComponent { + protected _shape: PhysicsShape; + + @property + private _center: Vec3 = new cc.Vec3(0, 0, 0); + + constructor(shape: PhysicsShape) { + super(); + this._center = new Vec3(0, 0, 0); + this._shape = shape; + } + + public get body() { + return this._body; + } + + public onLoad() { + super.onLoad(); + this.center = this._center; + } + + public onEnable() { + super.onEnable(); + this._body!.addShape(this._shape); + } + + public onDisable() { + super.onDisable(); + this._body!.removeShape(this._shape); + } + + @property(Vec3) + get center() { + return this._center; + } + + set center(value: Vec3) { + this._center = new Vec3(value.x, value.y, value.z); + if (this._body) { + this._body.setCenter(this._shape, this._center); + } + } +} + +@ccclass('cc.BoxColliderComponent') +@executionOrder(100) +@menu('Components/BoxColliderComponent') +@executeInEditMode +export class BoxColliderComponent extends ColliderComponentBase { + @property + private _size: Vec3 = new Vec3(0, 0, 0); + + constructor() { + super(new PhysicsBoxShape(new Vec3(0, 0, 0))); + } + + public onLoad() { + super.onLoad(); + this.size = this._size; + } + + @property(Vec3) + get size() { + return this._size; + } + + /** + * Note, shall not specify size with component 0 + */ + set size(value) { + this._size = value; + (this._shape as PhysicsBoxShape).size = this._size; + if (this._body) { + this._body.commitShapesUpdate(); + } + } +} + +@ccclass('cc.SphereColliderComponent') +@executionOrder(100) +@menu('Components/SphereColliderComponent') +@executeInEditMode +export class SphereColliderComponent extends ColliderComponentBase { + @property + private _radius: number = 0; + + constructor() { + super(new PhysicsSphereShape(0)); + } + + public onLoad() { + super.onLoad(); + this.radius = this._radius; + } + + @property + get radius() { + return this._radius; + } + + set radius(value) { + this._radius = value; + (this._shape as PhysicsSphereShape).radius = value; + if (this._body) { + this._body.commitShapesUpdate(); + } + } +} diff --git a/cocos/3d/framework/physics/contact-material.ts b/cocos/3d/framework/physics/contact-material.ts new file mode 100644 index 0000000000..de638104b4 --- /dev/null +++ b/cocos/3d/framework/physics/contact-material.ts @@ -0,0 +1,88 @@ +import CANNON from 'cannon'; +import { PhysicsMaterial } from '../../assets/physics/material'; + +export class ContactMaterial { + private _cannonContactMaterial: CANNON.ContactMaterial; + + constructor(lhs: PhysicsMaterial, rhs: PhysicsMaterial) { + const opts: CANNON.IContactMaterialOptions = { + friction: 0.3, + restitution: 0.3, + contactEquationStiffness: 1e7, + contactEquationRelaxation: 3, + frictionEquationStiffness: 1e7, + frictionEquationRelaxation: 3, + }; + this._cannonContactMaterial = new CANNON.ContactMaterial(lhs._getImpl(), rhs._getImpl(), opts); + } + + /** + * Friction coefficient. Default value 0.3. + */ + get friction() { + return this._cannonContactMaterial.friction; + } + + set friction(value) { + this._cannonContactMaterial.friction = value; + } + + /** + * Restitution coefficient. Default value 0.3. + */ + get restitution() { + return this._cannonContactMaterial.restitution; + } + + set restitution(value) { + this._cannonContactMaterial.restitution = value; + } + + /** + * Stiffness of the produced contact equations. Default value 1e7. + */ + get contactEquationStiffness() { + return this._cannonContactMaterial.contactEquationStiffness; + } + + set contactEquationStiffness(value) { + this._cannonContactMaterial.contactEquationStiffness = value; + } + + /** + * Relaxation time of the produced contact equations. Default value 0.3. + */ + get contactEquationRelaxation() { + return this._cannonContactMaterial.contactEquationRelaxation; + } + + set contactEquationRelaxation(value) { + this._cannonContactMaterial.contactEquationRelaxation = value; + } + + /** + * Stiffness of the produced friction equations. Default value 1e7. + */ + get frictionEquationStiffness() { + return this._cannonContactMaterial.frictionEquationStiffness; + } + + set frictionEquationStiffness(value) { + this._cannonContactMaterial.frictionEquationStiffness = value; + } + + /** + * Relaxation time of the produced friction equations. Default value 3. + */ + get frictionEquationRelaxation() { + return this._cannonContactMaterial.frictionEquationRelaxation; + } + + set frictionEquationRelaxation(value) { + this._cannonContactMaterial.frictionEquationRelaxation = value; + } + + public _getImpl() { + return this._cannonContactMaterial; + } +} \ No newline at end of file diff --git a/cocos/3d/framework/physics/detail/physics-based-component.ts b/cocos/3d/framework/physics/detail/physics-based-component.ts new file mode 100644 index 0000000000..5cfadbeb12 --- /dev/null +++ b/cocos/3d/framework/physics/detail/physics-based-component.ts @@ -0,0 +1,65 @@ + +import Component from '../../../../components/CCComponent'; +import { ccclass } from '../../../../core/data/class-decorator'; +import { PhysicsBody } from '../body'; + +@ccclass('cc.PhysicsBasedComponent') +export class PhysicsBasedComponent extends Component { + private _sharedBody: SharedRigidBody | null = null; + + constructor() { + super(); + } + + protected get _body() { + return this._sharedBody ? this._sharedBody.body : null; + } + + public onLoad() { + this._sharedBody = this._getSharedBody(); + this._sharedBody.body.bind(this.node); + } + + public onEnable() { + if (this._sharedBody!.enable()) { + cc.director._physicsSystem.world.addBody(this._body); + } + } + + public onDisable() { + if (this._sharedBody!.disable()) { + cc.director._physicsSystem.world.removeBody(this._body); + } + } + + private _getSharedBody() { + let component = this.getComponent(PhysicsBasedComponent) as (PhysicsBasedComponent | null); + if (!component) { + component = this; + } + if (!component._sharedBody) { + component._sharedBody = new SharedRigidBody(); + } + return component._sharedBody!; + } +} + +class SharedRigidBody { + public body: PhysicsBody; + + private _enableCount = 0; + + constructor() { + this.body = new PhysicsBody(); + } + + public enable() { + ++this._enableCount; + return this._enableCount === 1; + } + + public disable() { + --this._enableCount; + return this._enableCount === 0; + } +} diff --git a/cocos/3d/framework/physics/index.ts b/cocos/3d/framework/physics/index.ts new file mode 100644 index 0000000000..4f0901445c --- /dev/null +++ b/cocos/3d/framework/physics/index.ts @@ -0,0 +1,19 @@ +import { PhysicsBoxShape, PhysicsSphereShape, PhysicsBody } from './body'; +import { ContactMaterial } from './contact-material'; +import './physics-system'; +import './world'; + +// @ts-ignore +cc.PhysicsBody = PhysicsBody; +// @ts-ignore +cc.PhysicsBoxShape = PhysicsBoxShape; +// @ts-ignore +cc.PhysicsSphereShape = PhysicsSphereShape; +// @ts-ignore +cc.ContactMaterial = ContactMaterial; + +// namespace cc { +// export const PhysicalBody = PhysicalBody; +// export const PhysicalBoxShape = PhysicalBoxShape; +// export const PhysicalSphereShape = PhysicalSphereShape; +// } diff --git a/cocos/3d/framework/physics/physics-system.ts b/cocos/3d/framework/physics/physics-system.ts new file mode 100644 index 0000000000..1a818e85f0 --- /dev/null +++ b/cocos/3d/framework/physics/physics-system.ts @@ -0,0 +1,17 @@ +import { PhysicsWorld } from './world'; + +export class PhysicsSystem { + private _world: PhysicsWorld; + + constructor() { + this._world = new PhysicsWorld(); + } + + public update(deltaTime: number) { + this._world.step(deltaTime); + } + + get world() { + return this._world; + } +} \ No newline at end of file diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/3d/framework/physics/rigid-body-component.ts new file mode 100644 index 0000000000..0d5b1f8249 --- /dev/null +++ b/cocos/3d/framework/physics/rigid-body-component.ts @@ -0,0 +1,108 @@ + +import { + ccclass, + executeInEditMode, + executionOrder, + menu, + property +} from '../../../core/data/class-decorator'; +import { PhysicsMaterial } from '../../assets/physics/material'; +import { PhysicsBasedComponent } from './detail/physics-based-component'; + +@ccclass('cc.RigidBodyComponent') +@executionOrder(100) +@menu('Components/RigidBodyComponent') +@executeInEditMode +export class RigidBodyComponent extends PhysicsBasedComponent { + @property + private _material: PhysicsMaterial | null = null; + + @property + private _mass: number = NonRigidBodyProperties.mass; + + @property + private _linearDamping: number = NonRigidBodyProperties.linearDamping; + + @property + private _angularDamping: number = NonRigidBodyProperties.angularDamping; + + constructor() { + super(); + } + + public get body() { + return this._body; + } + + public onLoad() { + super.onLoad(); + } + + public onEnable() { + super.onEnable(); + this.mass = this._mass; + this.linearDamping = this._linearDamping; + this.angularDamping = this._angularDamping; + } + + public onDisable() { + super.onDisable(); + this.mass = NonRigidBodyProperties.mass; + this.linearDamping = NonRigidBodyProperties.linearDamping; + this.angularDamping = NonRigidBodyProperties.angularDamping; + } + + @property(PhysicsMaterial) + get material() { + return this._material; + } + + set material(value) { + this._material = value; + if (this._body) { + this._body.material = this._material; + } + } + + @property + get mass() { + return this._mass; + } + + set mass(value) { + this._mass = value; + if (this._body) { + this._body.mass = value; + } + } + + @property + get linearDamping() { + return this._linearDamping; + } + + set linearDamping(value) { + this._linearDamping = value; + if (this._body) { + this._body.linearDamping = value; + } + } + + @property + get angularDamping() { + return this._angularDamping; + } + + set angularDamping(value) { + this._angularDamping = value; + if (this._body) { + this._body.angularDamping = value; + } + } +} + +const NonRigidBodyProperties = { + mass: 0, + linearDamping: 0, + angularDamping: 0, +}; diff --git a/cocos/3d/framework/physics/util.ts b/cocos/3d/framework/physics/util.ts new file mode 100644 index 0000000000..09112cf72d --- /dev/null +++ b/cocos/3d/framework/physics/util.ts @@ -0,0 +1,27 @@ + +export interface IWrappedCANNON { + __cc_wrapper__: T; +} + +export function setWrap(cannonObject: any, wrapper: Wrapper) { + (cannonObject as unknown as IWrappedCANNON).__cc_wrapper__ = wrapper; +} + +export function getWrap(cannonObject: any) { + return (cannonObject as unknown as IWrappedCANNON).__cc_wrapper__; +} + +export function toCannonOptions(options: any, optionsRename?: { [x: string] : string; }) { + const result = {}; + for (const key in options) { + let destKey = key; + if (optionsRename) { + const rename = optionsRename[key]; + if (rename) { + destKey = rename; + } + } + result[destKey] = options[key]; + } + return result as T; +} \ No newline at end of file diff --git a/cocos/3d/framework/physics/world.ts b/cocos/3d/framework/physics/world.ts new file mode 100644 index 0000000000..6a034ebb8a --- /dev/null +++ b/cocos/3d/framework/physics/world.ts @@ -0,0 +1,127 @@ +import CANNON from 'cannon'; +import { PhysicsMaterial } from '../../assets/physics/material'; +import { DataFlow, PhysicsBody, PhysicsShape } from './body'; +import { ContactMaterial } from './contact-material'; +import { getWrap, setWrap, toCannonOptions } from './util'; + +export interface RaycastOptions { + collisionFilterMask?: number; + collisionFilterGroup?: number; + queryTriggerInteraction?: boolean; +} + +export class RaycastResult { + public _cannonResult: CANNON.RaycastResult = new CANNON.RaycastResult(); + + get hit() { + return this._cannonResult.hasHit; + } + + get hitPoint() { + return this._cannonResult.hitPointWorld; + } + + get distance() { + return this._cannonResult.distance; + } + + get shape() { + return getWrap(this._cannonResult.shape); + } + + get body() { + return getWrap(this._cannonResult.body); + } +} + +export class PhysicsWorld { + private _cannonWorld: CANNON.World; + private _defaultMaterial: PhysicsMaterial; + private _defaultContactMaterial: ContactMaterial; + private _bodys: Set; + private _beforeStepEvent: CANNON.IEvent = { + type: 'beforeStep', + }; + + constructor() { + this._defaultMaterial = new PhysicsMaterial(); + this._defaultContactMaterial = new ContactMaterial( + this._defaultMaterial, this._defaultMaterial, { friction: 0.3, restitution: 0.0 }); + + this._cannonWorld = new CANNON.World(); + setWrap(this._cannonWorld, this); + this._cannonWorld.gravity.set(0, -9.81, 0); + this._cannonWorld.broadphase = new CANNON.NaiveBroadphase(); + this._cannonWorld.defaultMaterial = this._defaultMaterial._getImpl(); + this._cannonWorld.defaultContactMaterial = this._defaultContactMaterial._getImpl(); + this._bodys = new Set(); + } + + get defaultContactMaterial() { + return this._defaultContactMaterial; + } + + public addBody(body: PhysicsBody) { + this._bodys.add(body); + this._cannonWorld.addBody(body._getCannonBody()); + body._onAdded(); + } + + public removeBody(body: PhysicsBody) { + body._onRemoved(); + this._cannonWorld.remove(body._getCannonBody()); + this._bodys.delete(body); + } + + public step(deltaTime: number) { + this._cannonWorld.dispatchEvent(this._beforeStepEvent); + this._cannonWorld.step(deltaTime); + } + + /** + * Ray cast, and return information of the closest hit. + * @return True if any body was hit. + */ + public raycastClosest(from: cc.Vec3, to: cc.Vec3, options: RaycastOptions, result: RaycastResult): boolean { + const hit = (this._cannonWorld as any).raycastClosest(from, to, toCannonRaycastOptions(options), result._cannonResult); + return hit; + } + + /** + * Ray cast, and stop at the first result. Note that the order is random - but the method is fast. + * @return True if any body was hit. + */ + public raycastAny(from: cc.Vec3, to: cc.Vec3, options: RaycastOptions, result: RaycastResult): boolean { + const hit = (this._cannonWorld as any).raycastAny(from, to, toCannonRaycastOptions(options), result._cannonResult); + return hit; + } + + /** + * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument. + * @return True if any body was hit. + */ + public raycastAll(from: cc.Vec3, to: cc.Vec3, options: RaycastOptions, callback: (result: RaycastResult) => void): boolean { + return (this._cannonWorld as any).raycastAll(from, to, toCannonRaycastOptions(options), (cannonResult: CANNON.RaycastResult) => { + const result = new RaycastResult(); + result._cannonResult = cannonResult; + callback(result); + }); + } + + public addContactMaterial(contactMaterial: ContactMaterial) { + this._cannonWorld.addContactMaterial(contactMaterial._getImpl()); + } +} + +interface CANNONRaycastOptions { + collisionFilterMask?: number; + collisionFilterGroup?: number; + checkCollisionResponse?: boolean; + skipBackfaces?: boolean; +} + +function toCannonRaycastOptions(options: RaycastOptions): CANNONRaycastOptions { + return toCannonOptions(options, { + queryTriggerInteraction: 'checkCollisionResponse', + }); +} diff --git a/cocos/3d/framework/skinning-model-component.js b/cocos/3d/framework/skinning-model-component.js index a6a1bf4804..5e903f5ec4 100644 --- a/cocos/3d/framework/skinning-model-component.js +++ b/cocos/3d/framework/skinning-model-component.js @@ -31,7 +31,6 @@ import { ccclass, property, executionOrder, menu,executeInEditMode } from '../.. import utils from '../misc/utils'; import Skeleton from '../assets/skeleton'; import Node from '../../scene-graph/node'; -import { createNode } from '../assets/utils/gltf-utils'; /** * @typedef {import("../framework/skeleton-instance").default} SkeletonInstance diff --git a/cocos/assets/texture-2d.js b/cocos/assets/texture-2d.js index ce429b9c26..a33d797260 100644 --- a/cocos/assets/texture-2d.js +++ b/cocos/assets/texture-2d.js @@ -255,10 +255,11 @@ export default class Texture2D extends TextureBase { height: 0 }); } else { + const level0 = this._mipmaps[0]; super.update({ - width: this._mipmaps[0].width, - height: this._mipmaps[0].height, - format: this._mipmaps[0]._format + width: level0.width, + height: level0.height, + format: level0._format }); } @@ -306,6 +307,8 @@ export default class Texture2D extends TextureBase { this._mipmaps = new Array(data.mipmaps.length); for (let i = 0; i < data.mipmaps.length; ++i) { + // Prevent resource load failed + this._mipmaps[i] = new ImageAsset(); const mipmapUUID = data.mipmaps[i]; handle.result.push(this._mipmaps, `${i}`, mipmapUUID); } diff --git a/cocos/components/CCComponent.js b/cocos/components/CCComponent.js index c3cd2cbd83..ad5e99f5c0 100644 --- a/cocos/components/CCComponent.js +++ b/cocos/components/CCComponent.js @@ -246,7 +246,7 @@ class Component extends CCObject { * * @method getComponent * @param {Function|String} typeOrClassName - * @return {Component} + * @return {Component | null} * @example * // get sprite component. * var sprite = node.getComponent(cc.Sprite); diff --git a/cocos/core/CCDirector.js b/cocos/core/CCDirector.js index f31485e2da..9fd24790a6 100644 --- a/cocos/core/CCDirector.js +++ b/cocos/core/CCDirector.js @@ -36,6 +36,7 @@ import NodeActivator from '../scene-graph/node-activator'; // import AnimationSystem from '../3d/framework/animation-system'; // import SkinningModelSystem from '../3d/framework/skinning-model-system'; import RenderSystem from '../3d/framework/render-system'; +import { PhysicsSystem } from '../3d/framework/physics/physics-system'; import { getClassByName } from './utils/js'; // const ComponentScheduler = require('./component-scheduler'); @@ -139,6 +140,11 @@ class Director extends EventTarget { // Action manager this._actionManager = null; + /** + * @type {PhysicsSystem} + */ + this._physicsSystem = null; + this._systems = []; var self = this; @@ -186,6 +192,10 @@ class Director extends EventTarget { }); } + { + this._physicsSystem = new PhysicsSystem(); + } + cc.loader.init(this); } @@ -890,6 +900,7 @@ class Director extends EventTarget { } // Render + this._physicsSystem.update(this._deltaTime); this.emit(cc.Director.EVENT_BEFORE_DRAW); this._renderSystem.update(this._deltaTime); // After draw diff --git a/cocos/scene-graph/base-node.js b/cocos/scene-graph/base-node.js index 734c0f0df4..181cf5aaab 100644 --- a/cocos/scene-graph/base-node.js +++ b/cocos/scene-graph/base-node.js @@ -786,7 +786,7 @@ export default class BaseNode extends CCObject { * 传入参数也可以是脚本的名称。 * @method getComponent * @param {Function|String} typeOrClassName - * @return {Component} + * @return {Component | null} * @example * // get sprite component. * var sprite = node.getComponent(cc.Sprite); diff --git a/package.json b/package.json index 59b7933793..47eab0d189 100644 --- a/package.json +++ b/package.json @@ -20,16 +20,17 @@ "url": "git+https://github.com/cocos-creator/engine.git" }, "devDependencies": { + "@babel/core": "^7.2.2", + "@babel/plugin-proposal-class-properties": "^7.2.1", + "@babel/plugin-proposal-decorators": "^7.2.2", + "@babel/preset-env": "^7.2.0", + "@babel/preset-typescript": "^7.1.0", + "@types/cannon": "^0.1.3", "aliasify": "^2.1.0", "async": "1.5.2", - "babel-plugin-parser-opts": "1.0.1", - "babel-plugin-transform-class-properties": "6.22.0", - "babel-plugin-transform-decorators-legacy": "^1.3.4", - "babel-plugin-transform-es2015-block-scoping": "6.22.0", - "babel-plugin-transform-es2015-shorthand-properties": "6.22.0", - "babel-plugin-transform-es2015-template-literals": "6.22.0", "babel-preset-env": "^1.2.2", "babelify": "7.3.0", + "cannon": "^0.6.2", "chalk": "1.1.0", "del": "1.2.0", "event-stream": "3.3.2", @@ -57,12 +58,12 @@ "persistify": "^1.1.1", "require-dir": "0.3.0", "rollup": "^0.65.2", - "rollup-plugin-babel": "^3.0.7", + "rollup-plugin-babel": "^4.1.0-1", "rollup-plugin-commonjs": "^9.1.6", "rollup-plugin-json": "^3.1.0", "rollup-plugin-node-resolve": "^3.4.0", "rollup-watch": "^4.3.1", - "uglify-es": "3.3.7", + "uglify-js": "^3.4.9", "vconsole": "^3.2.0", "vinyl": "1.1.0", "vinyl-buffer": "1.0.0", diff --git a/rollup/babel-plugin-mix-ts-js.js b/rollup/babel-plugin-mix-ts-js.js new file mode 100644 index 0000000000..730f4b4051 --- /dev/null +++ b/rollup/babel-plugin-mix-ts-js.js @@ -0,0 +1,31 @@ + +const fs = require('fs'); +const path = require('path'); + +Object.defineProperty(exports, "__esModule", { value: true }); + +exports.default = function(babel) { + return { + visitor: { + ImportDeclaration(babelPath, state) { + const currentFileName = state.filename; + const currentFileFolder = path.dirname(currentFileName); + + const source = babelPath.node.source; + const oldSourcePath = source.value; + + const destPath = path.resolve(currentFileFolder, oldSourcePath); + if (!fs.existsSync(`${destPath}.ts`)) { + return; + } + + const newSourcePath = `${oldSourcePath}.ts`; + const newSource = babel.types.stringLiteral(newSourcePath); + console.log(`Resolve ${oldSourcePath}(${currentFileName}) to ${newSourcePath}`); + + const newPath = babel.types.importDeclaration(babelPath.node.specifiers, newSource); + babelPath.replaceWith(newPath); + }, + } + }; +} \ No newline at end of file diff --git a/rollup/config.js b/rollup/config.js index 019eb1e362..fbead501ca 100644 --- a/rollup/config.js +++ b/rollup/config.js @@ -1,46 +1,67 @@ -'use strict'; +import * as fsJetpack from 'fs-jetpack'; +import babel from 'rollup-plugin-babel'; +import resolve from 'rollup-plugin-node-resolve'; +import json from 'rollup-plugin-json'; +import commonjs from 'rollup-plugin-commonjs'; -const fsJetpack = require('fs-jetpack'); -const commonjs = require('rollup-plugin-commonjs'); -const resolve = require('rollup-plugin-node-resolve'); -const babel = require('rollup-plugin-babel'); -const json = require('rollup-plugin-json'); - -let dest = './bin'; -let file = 'cocos-3d.dev'; -let moduleName = 'cocos3d'; +const dest = './bin'; +const file = 'cocos-3d.dev'; +const moduleName = 'cocos3d'; fsJetpack.dir(dest); -module.exports = { - input: './index.js', - output: [ - { - file: `${dest}/${file}.js`, - format: 'iife', - name: moduleName, - sourcemap: false, - }, - ], - plugins: [ - resolve({ - jsnext: true, - main: true, - }), - json({ - // for tree-shaking, properties will be declared as - // variables, using either `var` or `const` - preferConst: true, // Default: false - // ignores indent and generates the smallest code - compact: true, // Default: false - }), - babel({ - plugins: [ - "transform-decorators-legacy", - "transform-class-properties" - ], - exclude: 'node_modules/**' - }), - commonjs() - ], +export default { + input: './index.js', + + output: [{ + file: `${dest}/${file}.js`, + format: 'iife', + name: moduleName, + sourcemap: true + }], + + plugins: [ + resolve({ + jsnext: true, + + main: true, + + extensions: ['.js', '.ts', '.json'], + }), + + json({ + preferConst: true, + }), + + babel({ + highlightCode: true, + + extensions: ['.js', '.ts'], + + presets: [ + '@babel/preset-env', + '@babel/preset-typescript' + ], + + plugins: [ + //'./rollup/babel-plugin-mix-ts-js', + ['@babel/plugin-proposal-decorators', { + legacy: true + }], + ['@babel/plugin-proposal-class-properties', { + loose: true + }], + ], + + ignore: [ + 'node_modules/**' + ] + }), + + commonjs({ + namedExports: { + 'cannon': ['CANNON'] + } + }), + ] };