three#Matrix4 TypeScript Examples

The following examples show how to use three#Matrix4. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From use-ammojs with MIT License 7 votes vote down vote up
export function fromBtTransform(btTransform: Ammo.btTransform): Transform {
  const matrix = new Matrix4();

  const position = toVector3(btTransform.getOrigin());
  const rotation = fromBtQuaternion(btTransform.getRotation());

  return {
    position,
    rotation,
  };
}
Example #2
Source File: MapSphereNode.ts    From geo-three with MIT License 6 votes vote down vote up
/** 
	 * Apply scale and offset position to the sphere node geometry.
	 */
	public applyScaleNode(): void
	{
		this.geometry.computeBoundingBox();
	
		const box = this.geometry.boundingBox.clone();
		const center = box.getCenter(new Vector3());
	
		const matrix = new Matrix4();
		matrix.compose(new Vector3(-center.x, -center.y, -center.z), new Quaternion(), new Vector3(UnitsUtils.EARTH_RADIUS, UnitsUtils.EARTH_RADIUS, UnitsUtils.EARTH_RADIUS));
		this.geometry.applyMatrix4(matrix);
	
		this.position.copy(center);
	
		this.updateMatrix();
		this.updateMatrixWorld();
	}
Example #3
Source File: DisplayObject.ts    From FairyGUI-threejs with MIT License 5 votes vote down vote up
s_mat: Matrix4 = new Matrix4()
Example #4
Source File: Stage.ts    From FairyGUI-threejs with MIT License 5 votes vote down vote up
function updateCanvasMatrix() {
    let offsetX: number = 0;
    let offsetY: number = 0;
    var element: HTMLElement = _canvas;
    var style = element.style;

    if(style.paddingTop)
        offsetY += parseInt(style.paddingTop,10);

    if(style.paddingLeft)
        offsetX += parseInt(style.paddingTop,10);
        
    do {
        offsetX += element.offsetLeft;
        offsetY += element.offsetTop;
        style = element.style;

        if(style.borderLeftWidth)
            offsetX += parseInt(style.borderLeftWidth, 10);

        if(style.borderTopWidth)
            offsetY += parseInt(style.borderTopWidth, 10);
    } while (element = <HTMLElement>element.offsetParent);

    _canvasTransform.identity();

    if (_screenMode == "horizontal") {
        if (_height > _width) {
            let tmp = _width;
            _width = _height;
            _height = tmp;
            _renderer.setSize(_width, _height);
            _canvas.style.transformOrigin = "0 0";
            _canvas.style.transform = "translate(" + _height + "px,0) rotate(90deg)";
            _canvasTransform.multiply(new Matrix4().makeTranslation(0, _height, 0))
                .multiply(new Matrix4().makeRotationZ(-Math.PI / 2));
        }
    }
    else if (_screenMode == "vertical") {
        if (_width > _height) {
            let tmp = _width;
            _width = _height;
            _height = tmp;
            _renderer.setSize(_width, _height);
            _canvas.style.transformOrigin = "0 0";
            _canvas.style.transform = "translate(0," + _width + "px) rotate(-90deg)";
            _canvasTransform.multiply(new Matrix4().makeTranslation(_width, 0, 0))
                .multiply(new Matrix4().makeRotationZ(Math.PI / 2));
        }
    }
    else
        _renderer.setSize(_width, _height);

    _canvasTransform.multiply(new Matrix4().makeTranslation(-offsetX, -offsetY, 0));
}
Example #5
Source File: Stage.ts    From FairyGUI-threejs with MIT License 5 votes vote down vote up
_canvasTransform: Matrix4 = new Matrix4()
Example #6
Source File: InputTextField.ts    From FairyGUI-threejs with MIT License 5 votes vote down vote up
s_mat: Matrix4 = new Matrix4()
Example #7
Source File: physics-update.tsx    From use-ammojs with MIT License 5 votes vote down vote up
transform = new Matrix4()
Example #8
Source File: physics-update.tsx    From use-ammojs with MIT License 5 votes vote down vote up
inverse = new Matrix4()
Example #9
Source File: physics-update.tsx    From use-ammojs with MIT License 5 votes vote down vote up
matrix = new Matrix4()
Example #10
Source File: rigid-body-manager.ts    From use-ammojs with MIT License 5 votes vote down vote up
function addBody({
  uuid,
  matrix,
  serializedMesh,
  shapeConfig,
  options,
}: {
  uuid: UUID;
  matrix: number[];
  serializedMesh?: SerializedMesh;
  shapeConfig: ShapeConfig;
  options: BodyConfig;
}) {
  if (freeIndex !== -1) {
    const nextFreeIndex = freeIndexArray[freeIndex];
    freeIndexArray[freeIndex] = -1;

    indexes[uuid] = freeIndex;
    uuids.push(uuid);
    const transform = new Matrix4();
    transform.fromArray(matrix);
    matrices[uuid] = transform;

    // sharedBuffers.rigidBodies.objectMatricesFloatArray.set(
    //   transform.elements,
    //   freeIndex * BUFFER_CONFIG.BODY_DATA_SIZE
    // );

    const physicsShape = createCollisionShapes(
      serializedMesh?.vertices,
      serializedMesh?.matrices,
      serializedMesh?.indexes,
      serializedMesh?.matrixWorld ?? IDENTITY_MATRIX,
      shapeConfig || { type: ShapeType.BOX }
    );

    if (!physicsShape) {
      console.error(
        "could not create physicsShape",
        shapeConfig,
        serializedMesh
      );
      throw new Error("could not create physicsShape");
    }

    bodies[uuid] = new RigidBody(options || {}, transform, physicsShape, world);
    const ptr = Ammo.getPointer(bodies[uuid].physicsBody);
    ptrToIndex[ptr] = freeIndex;
    ptrToRigidBody[ptr] = uuid;

    postMessage({
      type: ClientMessageType.RIGIDBODY_READY,
      uuid,
      index: freeIndex,
    });
    freeIndex = nextFreeIndex;
  }
}
Example #11
Source File: rigid-body-manager.ts    From use-ammojs with MIT License 5 votes vote down vote up
matrices: Record<UUID, Matrix4> = {}
Example #12
Source File: rigid-body.ts    From use-ammojs with MIT License 5 votes vote down vote up
constructor(
    bodyConfig: BodyConfig,
    matrix: Matrix4,
    physicsShape: FinalizedShape,
    world: World
  ) {
    this.loadedEvent = bodyConfig.loadedEvent ? bodyConfig.loadedEvent : "";
    this.mass = bodyConfig.mass ?? 1;
    const worldGravity = world.physicsWorld.getGravity();
    this.gravity = new Ammo.btVector3(
      worldGravity.x(),
      worldGravity.y(),
      worldGravity.z()
    );
    if (bodyConfig.gravity) {
      this.gravity.setValue(
        bodyConfig.gravity.x,
        bodyConfig.gravity.y,
        bodyConfig.gravity.z
      );
    }
    this.linearDamping = bodyConfig.linearDamping ?? 0.01;
    this.angularDamping = bodyConfig.angularDamping ?? 0.01;
    this.linearSleepingThreshold = bodyConfig.linearSleepingThreshold ?? 1.6;
    this.angularSleepingThreshold = bodyConfig.angularSleepingThreshold ?? 2.5;
    this.angularFactor = new Vector3(1, 1, 1);
    if (bodyConfig.angularFactor) {
      this.angularFactor.copy(bodyConfig.angularFactor);
    }
    this.activationState =
      bodyConfig.activationState ?? BodyActivationState.ACTIVE_TAG;
    this.type = bodyConfig.type ? bodyConfig.type : BodyType.DYNAMIC;
    this.emitCollisionEvents = bodyConfig.emitCollisionEvents ?? false;
    this.disableCollision = bodyConfig.disableCollision ?? false;
    this.collisionFilterGroup = bodyConfig.collisionFilterGroup ?? 1; //32-bit mask
    this.collisionFilterMask = bodyConfig.collisionFilterMask ?? 1; //32-bit mask
    this.scaleAutoUpdate = bodyConfig.scaleAutoUpdate ?? true;

    this.enableCCD = bodyConfig.enableCCD ?? false;
    this.ccdMotionThreshold = bodyConfig.ccdMotionThreshold ?? 1e-7;
    this.ccdSweptSphereRadius = bodyConfig.ccdSweptSphereRadius ?? 0.5;

    this.matrix = matrix;
    this.world = world;
    // this.shapes = [];

    this.tmpVec = new Ammo.btVector3();
    this.tmpTransform1 = new Ammo.btTransform();
    this.tmpTransform2 = new Ammo.btTransform();

    this.physicsShape = physicsShape;
    if (physicsShape.type === ShapeType.MESH && this.type !== BodyType.STATIC) {
      throw new Error("non-static mesh colliders not supported");
    }

    this.physicsBody = this._initBody();

    this.shapesChanged = true;
    this.updateShapes();
  }
Example #13
Source File: rigid-body.ts    From use-ammojs with MIT License 5 votes vote down vote up
matrix: Matrix4;
Example #14
Source File: LODFrustum.ts    From geo-three with MIT License 5 votes vote down vote up
projection = new Matrix4()
Example #15
Source File: NMaterial.ts    From FairyGUI-threejs with MIT License 4 votes vote down vote up
public constructor() {
        super();

        let customUniforms = UniformsUtils.merge([
            ShaderLib.basic.uniforms,
            { _ColorMatrix: new Uniform(new Matrix4()) },
            { _ColorOffset: new Uniform(new Vector4()) },
            {
                diffuse: {
                    value: new Color(0xffffff)
                }
            }
        ]);

        this.uniforms = customUniforms;
        this.vertexShader = `
        #include <common>
        #include <uv_pars_vertex>
        #include <uv2_pars_vertex>
        #include <envmap_pars_vertex>
        varying vec4 vColor;
        attribute vec4 color;
        #include <fog_pars_vertex>
        #include <morphtarget_pars_vertex>
        #include <skinning_pars_vertex>
        #include <logdepthbuf_pars_vertex>
        #include <clipping_planes_pars_vertex>
        
        void main() {
        
            #include <uv_vertex>
            #include <uv2_vertex>

            vColor = color;

            #include <skinbase_vertex>
        
            #ifdef USE_ENVMAP
        
            #include <beginnormal_vertex>
            #include <morphnormal_vertex>
            #include <skinnormal_vertex>
            #include <defaultnormal_vertex>
        
            #endif
        
            #include <begin_vertex>
            #include <morphtarget_vertex>
            #include <skinning_vertex>
            #include <project_vertex>
            #include <logdepthbuf_vertex>
        
            #include <worldpos_vertex>
            #include <clipping_planes_vertex>
            #include <envmap_vertex>
            #include <fog_vertex>
        
        }
        `;

        this.fragmentShader = `
        uniform bool grayed;
        uniform bool colorFilter;
        uniform mat4 colorMatrix;
        uniform vec4 colorOffset;

        uniform vec3 diffuse;
        uniform float opacity;
        #ifndef FLAT_SHADED
            varying vec3 vNormal;
        #endif
        #include <common>
        #include <dithering_pars_fragment>

        varying vec4 vColor;

        #include <uv_pars_fragment>
        #include <uv2_pars_fragment>
        #include <map_pars_fragment>
        #include <alphamap_pars_fragment>
        #include <aomap_pars_fragment>
        #include <lightmap_pars_fragment>
        #include <envmap_common_pars_fragment>
        #include <envmap_pars_fragment>
        #include <cube_uv_reflection_fragment>
        #include <fog_pars_fragment>
        #include <specularmap_pars_fragment>
        #include <logdepthbuf_pars_fragment>
        #include <clipping_planes_pars_fragment>
        void main() {
            #include <clipping_planes_fragment>
            vec4 diffuseColor = vec4( diffuse, opacity );
            #include <logdepthbuf_fragment>
            #ifdef USE_MAP
                #ifdef TEXT
                    vec4 sampleColor = texture2D( map, vUv );
                    if(vColor.a<0.1)
                        diffuseColor.a *= sampleColor.r;
                    else if(vColor.a<0.4)
                        diffuseColor.a *= sampleColor.g;
                    else
                        diffuseColor.a *= sampleColor.b;
                #else
                    #include <map_fragment>
                #endif
            #endif

            #ifdef TEXT
            diffuseColor.rgb *= vColor.rgb;
            #else
            diffuseColor *= vColor;
            #endif

            #include <alphamap_fragment>
            #include <alphatest_fragment>
            #include <specularmap_fragment>
            ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
            // accumulation (baked indirect lighting only)
            #ifdef USE_LIGHTMAP
                vec4 lightMapTexel= texture2D( lightMap, vUv2 );
                reflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;
            #else
                reflectedLight.indirectDiffuse += vec3( 1.0 );
            #endif
            // modulation
            #include <aomap_fragment>
            reflectedLight.indirectDiffuse *= diffuseColor.rgb;
            vec3 outgoingLight = reflectedLight.indirectDiffuse;
            #include <envmap_fragment>
            gl_FragColor = vec4( outgoingLight, diffuseColor.a );
            #include <tonemapping_fragment>
            #include <encodings_fragment>
            #include <fog_fragment>
            #include <premultiplied_alpha_fragment>
            #include <dithering_fragment>

            #ifdef GRAYED
            float grey = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));
            gl_FragColor.rgb = vec3(grey, grey, grey);
            #endif

            #ifdef COLOR_FILTER
            vec4 col = gl_FragColor;
            gl_FragColor.r = dot(col, _ColorMatrix[0]) + _ColorOffset.x;
            gl_FragColor.g = dot(col, _ColorMatrix[1]) + _ColorOffset.y;
            gl_FragColor.b = dot(col, _ColorMatrix[2]) + _ColorOffset.z;
            gl_FragColor.a = dot(col, _ColorMatrix[3]) + _ColorOffset.w;
            #endif
        }
        `;

        this.name = "ui-material";
        this.lights = false;
        this.transparent = true;
        this.depthTest = false;
        this.side = DoubleSide;
        //this.wireframe = true;
        this["isMeshBasicMaterial"] = true;
    }
Example #16
Source File: worker-helper.ts    From use-ammojs with MIT License 4 votes vote down vote up
export function WorkerHelpers(ammoWorker: Worker) {
  const transform = new Matrix4();
  const inverse = new Matrix4();

  let lastRequestId: number = 0;
  let requests: Record<WorkerRequestId, (data: any) => void> = {};

  return {
    initWorld(worldConfig: WorldConfig, sharedBuffers: SharedBuffers) {
      if (isSharedArrayBufferSupported) {
        ammoWorker.postMessage({
          type: MessageType.INIT,
          worldConfig,
          sharedBuffers,
          isSharedArrayBufferSupported,
        });
      } else {
        console.warn(
          "use-ammojs uses fallback to slower ArrayBuffers. To use the faster SharedArrayBuffers make sure that your environment is crossOriginIsolated. (see https://web.dev/coop-coep/)"
        );

        ammoWorker.postMessage(
          {
            type: MessageType.INIT,
            worldConfig,
            sharedBuffers,
            isSharedArrayBufferSupported,
          },
          [
            sharedBuffers.rigidBodies.headerIntArray.buffer,
            sharedBuffers.debug.vertexFloatArray.buffer,
            ...sharedBuffers.softBodies.map((sb) => sb.vertexFloatArray.buffer),
          ]
        );
      }
    },

    async makeAsyncRequest<T = any>(data): Promise<T> {
      return new Promise((resolve) => {
        const requestId = lastRequestId++;

        requests[requestId] = resolve;

        ammoWorker.postMessage({
          ...data,
          requestId,
        });
      });
    },

    resolveAsyncRequest(data) {
      if (requests[data.requestId]) {
        requests[data.requestId](data);
        delete requests[data.requestId];
      }
    },

    transferSharedBuffers(sharedBuffers: SharedBuffers) {
      ammoWorker.postMessage(
        { type: MessageType.TRANSFER_BUFFERS, sharedBuffers },
        [
          sharedBuffers.rigidBodies.headerIntArray.buffer,
          sharedBuffers.debug.vertexFloatArray.buffer,
          ...sharedBuffers.softBodies.map((sb) => sb.vertexFloatArray.buffer),
        ]
      );
    },

    addRigidBody(
      uuid: UUID,
      mesh: Object3D,
      shapeDescriptor: ShapeDescriptor,
      options: BodyConfig
    ) {
      let serializedMesh: SerializedMesh | undefined = undefined;

      if (shapeDescriptor.meshToUse) {
        inverse.copy(mesh.parent!.matrix).invert();
        transform.multiplyMatrices(inverse, mesh.parent!.matrix);
        const vertices: any[] = [];
        const matrices: any[] = [];
        const indexes: any[] = [];

        mesh.updateMatrixWorld(true);
        iterateGeometries(mesh, options, (vertexArray, matrix, index) => {
          vertices.push(vertexArray);
          matrices.push(matrix);
          indexes.push(index);
        });

        serializedMesh = {
          vertices,
          matrices,
          indexes,
          matrixWorld: mesh.matrixWorld.elements,
        };
      }

      inverse.copy(mesh.parent!.matrixWorld).invert();
      transform.multiplyMatrices(inverse, mesh.matrixWorld);
      ammoWorker.postMessage({
        type: MessageType.ADD_RIGIDBODY,
        uuid,
        matrix: transform.elements,
        serializedMesh,
        shapeConfig: shapeDescriptor.shapeConfig,
        options,
      });
    },

    updateRigidBody(uuid, options) {
      ammoWorker.postMessage({
        type: MessageType.UPDATE_RIGIDBODY,
        uuid,
        options,
      });
    },

    removeRigidBody(uuid) {
      ammoWorker.postMessage({
        type: MessageType.REMOVE_RIGIDBODY,
        uuid,
      });
    },

    addSoftBody(
      uuid: UUID,
      sharedSoftBodyBuffers: SharedSoftBodyBuffers,
      softBodyConfig: SoftBodyConfig
    ) {
      if (isSharedArrayBufferSupported) {
        ammoWorker.postMessage({
          type: MessageType.ADD_SOFTBODY,
          uuid,
          sharedSoftBodyBuffers,
          softBodyConfig,
        });
      } else {
        ammoWorker.postMessage(
          {
            type: MessageType.ADD_SOFTBODY,
            uuid,
            sharedSoftBodyBuffers,
            softBodyConfig,
          },
          [sharedSoftBodyBuffers.vertexFloatArray.buffer]
        );
      }
    },

    removeSoftBody(uuid: UUID) {
      ammoWorker.postMessage({
        type: MessageType.REMOVE_SOFTBODY,
        uuid,
      });
    },

    bodySetShapesOffset(bodyUuid, offset) {
      ammoWorker.postMessage({
        type: MessageType.SET_SHAPES_OFFSET,
        bodyUuid,
        offset,
      });
    },

    addConstraint(constraintId, bodyAUuid, bodyBUuid, options) {
      ammoWorker.postMessage({
        type: MessageType.ADD_CONSTRAINT,
        constraintId,
        bodyAUuid,
        bodyBUuid,
        options,
      });
    },

    updateConstraint(constraintId, options) {
      ammoWorker.postMessage({
        type: MessageType.UPDATE_CONSTRAINT,
        constraintId,
        options,
      });
    },

    removeConstraint(constraintId) {
      ammoWorker.postMessage({
        type: MessageType.REMOVE_CONSTRAINT,
        constraintId,
      });
    },

    enableDebug(enable, debugSharedArrayBuffer) {
      ammoWorker.postMessage({
        type: MessageType.ENABLE_DEBUG,
        enable,
        debugSharedArrayBuffer,
      });
    },

    resetDynamicBody(uuid) {
      ammoWorker.postMessage({
        type: MessageType.RESET_DYNAMIC_BODY,
        uuid,
      });
    },

    activateBody(uuid) {
      ammoWorker.postMessage({
        type: MessageType.ACTIVATE_BODY,
        uuid,
      });
    },

    bodySetMotionState(uuid, position, rotation) {
      ammoWorker.postMessage({
        type: MessageType.SET_MOTION_STATE,
        uuid,
        position,
        rotation,
      });
    },

    bodySetLinearVelocity(uuid, velocity) {
      ammoWorker.postMessage({
        type: MessageType.SET_LINEAR_VELOCITY,
        uuid,
        velocity,
      });
    },

    bodyApplyImpulse(uuid, impulse, relativeOffset) {
      if (!relativeOffset) {
        ammoWorker.postMessage({
          type: MessageType.APPLY_CENTRAL_IMPULSE,
          uuid,
          impulse,
        });
      } else {
        ammoWorker.postMessage({
          type: MessageType.APPLY_IMPULSE,
          uuid,
          impulse,
          relativeOffset,
        });
      }
    },

    bodyApplyForce(uuid, force, relativeOffset) {
      if (!relativeOffset) {
        ammoWorker.postMessage({
          type: MessageType.APPLY_CENTRAL_FORCE,
          uuid,
          force,
        });
      } else {
        ammoWorker.postMessage({
          type: MessageType.APPLY_FORCE,
          uuid,
          force,
          relativeOffset,
        });
      }
    },

    setSimulationSpeed(simulationSpeed: number) {
      ammoWorker.postMessage({
        type: MessageType.SET_SIMULATION_SPEED,
        simulationSpeed,
      });
    },
  };
}