three#WebGLRenderer TypeScript Examples

The following examples show how to use three#WebGLRenderer. 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: App.ts    From codecity with Mozilla Public License 2.0 6 votes vote down vote up
static createRender() {
    let renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.outputEncoding = THREE.sRGBEncoding;
    renderer.shadowMap.enabled = true;
    renderer.xr.enabled = true;
    renderer.xr.setReferenceSpaceType( 'local' );
    renderer.xr.addEventListener( 'sessionstart', function ( event ) {
      App.controls.enabled = false;
    } );

    renderer.xr.addEventListener( 'sessionend', function ( event ) {
      App.controls.enabled = true;
    } );

    App.renderer = renderer;

    App.container.appendChild(renderer.domElement);
  }
Example #2
Source File: scene-helper.ts    From head-tracked-3d with MIT License 6 votes vote down vote up
export function loadEnvMap(renderer: WebGLRenderer, scene: Scene) {
  const pmremGenerator = new PMREMGenerator(renderer);
  pmremGenerator.compileEquirectangularShader();

  new RGBELoader()
    .setDataType(UnsignedByteType)
    .load("quarry_01_1k.hdr", function (texture) {
      const envMap = pmremGenerator.fromEquirectangular(texture).texture;

      scene.background = envMap;
      scene.environment = envMap;

      texture.dispose();
      pmremGenerator.dispose();
    });
}
Example #3
Source File: MapView.ts    From geo-three with MIT License 6 votes vote down vote up
/**
	 * Ajust node configuration depending on the camera distance.
	 *
	 * Called everytime before render.
	 */
	public onBeforeRender: (renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, material: Material, group: Group)=> void = (renderer, scene, camera, geometry, material, group) => 
	{
		this.lod.updateLOD(this, camera, renderer, scene);
	};
Example #4
Source File: LODFrustum.ts    From geo-three with MIT License 6 votes vote down vote up
public updateLOD(view: MapView, camera: Camera, renderer: WebGLRenderer, scene: Object3D): void
	{
		projection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
		frustum.setFromProjectionMatrix(projection);
		camera.getWorldPosition(pov);

		view.children[0].traverse((node: any) => 
		{
			node.getWorldPosition(position);
			let distance = pov.distanceTo(position);
			distance /= Math.pow(2, view.provider.maxZoom - node.level);

			const inFrustum = this.pointOnly ? frustum.containsPoint(position) : frustum.intersectsObject(node);

			if (distance < this.subdivideDistance && inFrustum) 
			{
				node.subdivide();
			}
			else if (distance > this.simplifyDistance && node.parentNode) 
			{
				node.parentNode.simplify();
			}
		});
	}
Example #5
Source File: LODRadial.ts    From geo-three with MIT License 6 votes vote down vote up
public updateLOD(view: MapView, camera: Camera, renderer: WebGLRenderer, scene: Object3D): void
	{
		camera.getWorldPosition(pov);

		view.children[0].traverse((node: any) =>
		{
			node.getWorldPosition(position);

			let distance = pov.distanceTo(position);
			distance /= Math.pow(2, view.provider.maxZoom - node.level);

			if (distance < this.subdivideDistance) 
			{
				node.subdivide();
			}
			else if (distance > this.simplifyDistance && node.parentNode) 
			{
				node.parentNode.simplify();
			}
		});
	}
Example #6
Source File: Stage.ts    From FairyGUI-threejs with MIT License 5 votes vote down vote up
function init(renderer: Renderer, parameters?: StageInitParameters) {
    _renderer = renderer;
    if (parameters) {
        if (parameters.defaultLayer != null)
            UILayer = parameters.defaultLayer;
        if (parameters.screenMode)
            _screenMode = parameters.screenMode;
    }

    _canvas = renderer.domElement;
    _camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1000);
    _camera.layers.set(UILayer);

    _touchscreen = is_touch_enabled();
    if (renderer instanceof WebGLRenderer)
        _devicePixelRatio = renderer.getPixelRatio();

    _touches = [];
    for (let i = 0; i < 5; i++)
        _touches.push(new TouchInfo());
    if (!_touchscreen)
        _touches[0].touchId = 0;

    _touchCount = 0;
    _touchPos = new Vector2();

    if (_touchscreen) {
        document.addEventListener('touchstart', ev => handleTouch(ev, 0), { passive: false });
        document.addEventListener('touchend', ev => handleTouch(ev, 1), { passive: false });
        document.addEventListener('touchmove', ev => handleTouch(ev, 2), { passive: false });
        document.addEventListener('touchcancel', ev => handleTouch(ev, 3), { passive: false });
    }
    else {
        document.addEventListener('mousedown', ev => handleMouse(ev, 0), { passive: false });
        document.addEventListener('mouseup', ev => handleMouse(ev, 1), { passive: false });
        document.addEventListener('mousemove', ev => handleMouse(ev, 2), { passive: false });
    }
    document.addEventListener('wheel', ev => handleWheel(ev), { passive: false });

    window.addEventListener('resize', onWindowResize, false);

    onWindowResize();
}
Example #7
Source File: App.ts    From codecity with Mozilla Public License 2.0 5 votes vote down vote up
static renderer: WebGLRenderer;
Example #8
Source File: MapView.d.ts    From geo-three with MIT License 5 votes vote down vote up
onBeforeRender: (renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, material: Material, group: Group) => void;
Example #9
Source File: LODFrustum.d.ts    From geo-three with MIT License 5 votes vote down vote up
updateLOD(view: MapView, camera: Camera, renderer: WebGLRenderer, scene: Object3D): void;
Example #10
Source File: LODRadial.d.ts    From geo-three with MIT License 5 votes vote down vote up
updateLOD(view: MapView, camera: Camera, renderer: WebGLRenderer, scene: Object3D): void;
Example #11
Source File: LODRaycast.d.ts    From geo-three with MIT License 5 votes vote down vote up
updateLOD(view: MapView, camera: Camera, renderer: WebGLRenderer, scene: Object3D): void;
Example #12
Source File: LODRaycast.ts    From geo-three with MIT License 5 votes vote down vote up
public updateLOD(view: MapView, camera: Camera, renderer: WebGLRenderer, scene: Object3D): void
	{
		const intersects = [];

		for (let t = 0; t < this.subdivisionRays; t++) 
		{
			// Raycast from random point
			this.mouse.set(Math.random() * 2 - 1, Math.random() * 2 - 1);

			// Check intersection
			this.raycaster.setFromCamera(this.mouse, camera);
			this.raycaster.intersectObjects(view.children, true, intersects);
		}

		for (let i = 0; i < intersects.length; i++) 
		{
			const node = intersects[i].object;
			let distance = intersects[i].distance;

			if (this.powerDistance) 
			{
				distance = Math.pow(distance * 2, node.level);
			}

			if (this.scaleDistance) 
			{
				const matrix = node.matrixWorld.elements;
				const vector = new Vector3(matrix[0], matrix[1], matrix[2]);
				distance = vector.length() / distance;
			}

			if (distance > this.thresholdUp) 
			{
				node.subdivide();
				return;
			}
			else if (distance < this.thresholdDown) 
			{
				if (node.parentNode !== null) 
				{
					node.parentNode.simplify();
					return;
				}
			}
		}
	}
Example #13
Source File: useThree.ts    From trois with MIT License 4 votes vote down vote up
/**
 * Three.js helper
 */
export default function useThree(params: ThreeConfigInterface): ThreeInterface {
  // default config
  const config: ThreeConfigInterface = {
    antialias: true,
    alpha: false,
    autoClear: true,
    orbitCtrl: false,
    pointer: false,
    resize: false,
    width: 300,
    height: 150,
  }

  if (params) {
    Object.entries(params).forEach(([key, value]) => {
      config[key] = value
    })
  }

  // size
  const size: SizeInterface = {
    width: 1, height: 1,
    wWidth: 1, wHeight: 1,
    ratio: 1,
  }

  const beforeRenderCallbacks: {(): void}[] = []

  const intersectObjects: Object3D[] = []

  const renderer = createRenderer()

  // returned object
  const obj: ThreeInterface = {
    config,
    renderer,
    size,
    init,
    dispose,
    render,
    renderC,
    setSize,
    addIntersectObject, removeIntersectObject,
  }

  return obj

  /**
   * create WebGLRenderer
   */
  function createRenderer(): WebGLRenderer {
    const renderer = new WebGLRenderer({ canvas: config.canvas, antialias: config.antialias, alpha: config.alpha, ...config.params })
    renderer.autoClear = config.autoClear
    return renderer
  }

  /**
   * init three
   */
  function init() {
    if (!obj.scene) {
      console.error('Missing Scene')
      return false
    }

    if (!obj.camera) {
      console.error('Missing Camera')
      return false
    }

    if (config.resize) {
      onResize()
      window.addEventListener('resize', onResize)
    } else if (config.width && config.height) {
      setSize(config.width, config.height)
    }

    initPointer()

    if (config.orbitCtrl) {
      const cameraCtrl = new OrbitControls(obj.camera, obj.renderer.domElement)
      if (config.orbitCtrl instanceof Object) {
        Object.entries(config.orbitCtrl).forEach(([key, value]) => {
          // @ts-ignore
          cameraCtrl[key] = value
        })
      }
      onBeforeRender(() => { cameraCtrl.update() })
      obj.cameraCtrl = cameraCtrl
    }

    return true
  }

  /**
   * init pointer
   */
  function initPointer() {
    let pointerConf: PointerConfigInterface = {
      camera: obj.camera!,
      domElement: obj.renderer!.domElement,
      intersectObjects,
    }

    if (config.pointer && config.pointer instanceof Object) {
      pointerConf = { ...pointerConf, ...config.pointer }
    }

    const pointer = obj.pointer = usePointer(pointerConf)
    if (config.pointer || intersectObjects.length) {
      pointer.addListeners()
      if (pointerConf.intersectMode === 'frame') {
        onBeforeRender(pointer.intersect)
      }
    }
  }

  /**
   * add before render callback
   */
  function onBeforeRender(cb: {(): void}) {
    beforeRenderCallbacks.push(cb)
  }

  /**
   * default render
   */
  function render() {
    // if (obj.cameraCtrl) obj.cameraCtrl.update()
    beforeRenderCallbacks.forEach(c => c())
    obj.renderer!.render(obj.scene!, obj.camera!)
  }

  /**
   * composer render
   */
  function renderC() {
    // if (obj.cameraCtrl) obj.cameraCtrl.update()
    beforeRenderCallbacks.forEach(c => c())
    obj.composer!.render()
  }

  /**
   * add intersect object
   */
  function addIntersectObject(o: Object3D) {
    if (intersectObjects.indexOf(o) === -1) {
      intersectObjects.push(o)
    }
    // add listeners if needed
    if (obj.pointer && !obj.pointer.listeners) {
      obj.pointer.addListeners()
    }
  }

  /**
   * remove intersect object
   */
  function removeIntersectObject(o: Object3D) {
    const i = intersectObjects.indexOf(o)
    if (i !== -1) {
      intersectObjects.splice(i, 1)
    }
    // remove listeners if needed
    if (obj.pointer && !config.pointer && intersectObjects.length === 0) {
      obj.pointer.removeListeners()
    }
  }

  /**
   * remove listeners and dispose
   */
  function dispose() {
    // beforeRenderCallbacks = []
    window.removeEventListener('resize', onResize)
    if (obj.pointer) obj.pointer.removeListeners()
    if (obj.cameraCtrl) obj.cameraCtrl.dispose()
    if (obj.renderer) obj.renderer.dispose()
  }

  /**
   * resize listener
   */
  function onResize() {
    if (config.resize === 'window') {
      setSize(window.innerWidth, window.innerHeight)
    } else {
      const elt = obj.renderer!.domElement.parentNode as Element
      if (elt) setSize(elt.clientWidth, elt.clientHeight)
    }
    config.onResize?.(size)
  }

  /**
   * update renderer size and camera
   */
  function setSize(width: number, height: number) {
    size.width = width
    size.height = height
    size.ratio = width / height

    obj.renderer!.setSize(width, height, false)

    // already done in EffectComposer
    // if (obj.composer) {
    //   obj.composer.setSize(width, height)
    // }

    const camera = (<Camera>obj.camera!)
    if (camera.type === 'PerspectiveCamera') {
      const pCamera = (<PerspectiveCamera>camera)
      pCamera.aspect = size.ratio
      pCamera.updateProjectionMatrix()
    }

    if (camera.type === 'OrthographicCamera') {
      const oCamera = (<OrthographicCamera>camera)
      size.wWidth = oCamera.right - oCamera.left
      size.wHeight = oCamera.top - oCamera.bottom
    } else {
      const wsize = getCameraSize()
      size.wWidth = wsize[0]
      size.wHeight = wsize[1]
    }
  }

  /**
   * calculate camera visible area size
   */
  function getCameraSize() {
    const camera = (<PerspectiveCamera>obj.camera!)
    const vFOV = (camera.fov * Math.PI) / 180
    const h = 2 * Math.tan(vFOV / 2) * Math.abs(camera.position.z)
    const w = h * camera.aspect
    return [w, h]
  }
}