three#Quaternion TypeScript Examples

The following examples show how to use three#Quaternion. 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 almostEqualsQuaternion(
  epsilon: number,
  u: Quaternion,
  v: Quaternion
) {
  return (
    (Math.abs(u.x - v.x) < epsilon &&
      Math.abs(u.y - v.y) < epsilon &&
      Math.abs(u.z - v.z) < epsilon &&
      Math.abs(u.w - v.w) < epsilon) ||
    (Math.abs(u.x + v.x) < epsilon &&
      Math.abs(u.y + v.y) < epsilon &&
      Math.abs(u.z + v.z) < epsilon &&
      Math.abs(u.w + v.w) < epsilon)
  );
}
Example #2
Source File: utils.ts    From use-ammojs with MIT License 7 votes vote down vote up
export function toBtQuaternion(
  btQuat: Ammo.btQuaternion,
  quat: Quaternion | SerializedQuaternion
) {
  btQuat.setValue(
    (quat as Quaternion).x ?? (quat as SerializedQuaternion)._x,
    (quat as Quaternion).y ?? (quat as SerializedQuaternion)._y,
    (quat as Quaternion).z ?? (quat as SerializedQuaternion)._z,
    (quat as Quaternion).w ?? (quat as SerializedQuaternion)._w
  );
}
Example #3
Source File: utils.ts    From use-ammojs with MIT License 6 votes vote down vote up
export function fromBtQuaternion(btQuat: Ammo.btQuaternion) {
  return new Quaternion(btQuat.x(), btQuat.y(), btQuat.z(), btQuat.w());
}
Example #4
Source File: utils.ts    From use-ammojs with MIT License 6 votes vote down vote up
export function isQuaternion(q): q is Quaternion {
  return q && q.isQuaternion;
}
Example #5
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 #6
Source File: DisplayObject.ts    From FairyGUI-threejs with MIT License 5 votes vote down vote up
s_quaternion: Quaternion = new Quaternion()
Example #7
Source File: rigidbody-api.tsx    From use-ammojs with MIT License 5 votes vote down vote up
export function createRigidBodyApi(
  physicsContext: AmmoPhysicsContext,
  bodyUUID: UUID
) {
  return {
    updateBodyOptions(options: UpdateBodyOptions) {
      physicsContext.updateRigidBody(bodyUUID, options);
    },

    getPosition(): Vector3 {
      return physicsContext.object3Ds[bodyUUID].position;
    },

    setPosition(position: Vector3) {
      physicsContext.bodySetMotionState(bodyUUID, position);
    },

    getRotation(): Quaternion {
      return physicsContext.object3Ds[bodyUUID].quaternion;
    },

    setRotation(rotation: Quaternion) {
      physicsContext.bodySetMotionState(bodyUUID, undefined, rotation);
    },

    setMotionState(position: Vector3, rotation: Quaternion) {
      physicsContext.bodySetMotionState(bodyUUID, position, rotation);
    },

    setLinearVelocity(velocity: Vector3) {
      physicsContext.bodySetLinearVelocity(bodyUUID, velocity);
    },

    applyImpulse(impulse: Vector3, relativeOffset?: Vector3) {
      physicsContext.bodyApplyImpulse(bodyUUID, impulse, relativeOffset);
    },

    applyForce(force: Vector3, relativeOffset?: Vector3) {
      physicsContext.bodyApplyForce(bodyUUID, force, relativeOffset);
    },

    setShapesOffset(offset: Vector3) {
      physicsContext.bodySetShapesOffset(bodyUUID, offset);
    },
  };
}
Example #8
Source File: rigid-body.ts    From use-ammojs with MIT License 5 votes vote down vote up
quat = new Quaternion()
Example #9
Source File: rigid-body.ts    From use-ammojs with MIT License 5 votes vote down vote up
q = new Quaternion()
Example #10
Source File: index.ts    From use-ammojs with MIT License 5 votes vote down vote up
function finishCollisionShape(
  collisionShape: Ammo.btCollisionShape,
  options: ShapeConfig,
  scale?: Vector3
): FinalizedShape {
  collisionShape.setMargin(options.margin ?? 0);

  const localTransform = new Ammo.btTransform();
  const rotation = new Ammo.btQuaternion(0, 0, 0, 1);
  localTransform.setIdentity();

  if (options.offset) {
    localTransform
      .getOrigin()
      .setValue(-options.offset.x, -options.offset.y, -options.offset.z);
  }

  toBtQuaternion(rotation, options.orientation ?? new Quaternion());
  const invertedRotation = rotation.inverse();
  localTransform.setRotation(invertedRotation);

  Ammo.destroy(rotation);
  Ammo.destroy(invertedRotation);

  if (scale) {
    const localScale = new Ammo.btVector3(scale.x, scale.y, scale.z);
    collisionShape.setLocalScaling(localScale);
    Ammo.destroy(localScale);
  }

  return Object.assign(collisionShape, {
    type: options.type,
    localTransform,
    destroy() {
      const finalizedShape = collisionShape as FinalizedShape;

      for (let res of finalizedShape.resources || []) {
        Ammo.destroy(res);
      }

      if (finalizedShape.heightfieldData) {
        Ammo._free(finalizedShape.heightfieldData);
      }

      if (finalizedShape.shapes) {
        for (const shape of finalizedShape.shapes) {
          shape.destroy();
        }
      }

      Ammo.destroy(collisionShape);
    },
  });
}
Example #11
Source File: Player.tsx    From spacesvr with MIT License 4 votes vote down vote up
/**
 * Player represents a physics-enabled player in the environment, complete with a
 * control scheme and a physical representation that interacts with other physics-
 * enabled objects.
 *
 * There should only be one player per environment.
 *
 * @constructor
 */
export default function Player(
  props: { children: ReactNode[] | ReactNode } & PlayerProps
) {
  const { children, pos = [0, 1, 0], rot = 0, speed = SPEED, controls } = props;

  const camera = useThree((state) => state.camera);
  const gl = useThree((state) => state.gl);
  const defaultRaycaster = useThree((state) => state.raycaster);

  const { device } = useEnvironment();

  // physical body
  const [bodyRef, bodyApi] = useCapsuleCollider(pos);
  const { direction, updateVelocity } = useSpringVelocity(bodyApi, speed);

  // local state
  const position = useRef(new Vector3());
  const velocity = useRef(new Vector3());
  const lockControls = useRef(false);
  const raycaster = useMemo(
    () => new Raycaster(new Vector3(), new Vector3(), 0, 1.5),
    []
  );
  const { connected, frequency, sendEvent } = useSimulation();
  const simulationLimiter = useLimiter(frequency);

  // setup player
  useEffect(() => {
    // store position and velocity
    bodyApi.position.subscribe((p) => position.current.fromArray(p));
    bodyApi.velocity.subscribe((v) => velocity.current.fromArray(v));

    // rotation happens before position move
    camera.rotation.setFromQuaternion(
      new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), rot)
    );
  }, []);

  useFrame(({ clock }) => {
    const cam: Camera = device.xr ? gl.xr.getCamera(camera) : camera;

    // update raycaster
    if (device.desktop) {
      raycaster.ray.origin.copy(position.current);
      const lookAt = new Vector3(0, 0, -1);
      lookAt.applyQuaternion(cam.quaternion);
      raycaster.ray.direction.copy(lookAt);
    }

    // update camera position
    camera.position.copy(position.current);

    // update velocity
    if (!lockControls.current) {
      updateVelocity(cam, velocity.current);
    }

    // p2p stream position and rotation
    if (connected && simulationLimiter.isReady(clock)) {
      sendEvent(
        "player",
        JSON.stringify({
          position: camera.position
            .toArray()
            .map((p) => parseFloat(p.toPrecision(3))),
          rotation: camera.rotation
            .toArray()
            .slice(0, 3)
            .map((r) => parseFloat(r.toPrecision(3))),
        })
      );
    }
  });

  const state = createPlayerState(
    bodyApi,
    position,
    velocity,
    lockControls,
    device.mobile ? defaultRaycaster : raycaster
  );

  return (
    <PlayerContext.Provider value={state}>
      {device.mobile && (
        <>
          {controls?.disableGyro ? (
            <TouchFPSCamera />
          ) : (
            <GyroControls fallback={<TouchFPSCamera />} />
          )}
          <NippleMovement direction={direction} />
        </>
      )}
      {device.desktop && (
        <>
          <KeyboardMovement direction={direction} />
          <PointerLockControls />
        </>
      )}
      {device.xr && (
        <>
          <VRControllerMovement position={position} direction={direction} />
        </>
      )}
      <group name="player" ref={bodyRef}>
        {SHOW_PLAYER_HITBOX && <VisibleCapsuleCollider />}
      </group>
      {children}
    </PlayerContext.Provider>
  );
}