three#Color JavaScript Examples

The following examples show how to use three#Color. 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: utilities.js    From 3DTilesRendererJS with Apache License 2.0 7 votes vote down vote up
// Return a consistant random color for an index
export function getIndexedRandomColor( index ) {

	if ( ! colors[ index ] ) {

		const h = Math.random();
		const s = 0.5 + Math.random() * 0.5;
		const l = 0.375 + Math.random() * 0.25;

		colors[ index ] = new Color().setHSL( h, s, l );

	}
	return colors[ index ];

}
Example #2
Source File: PlayerInInventory.js    From webmc with MIT License 6 votes vote down vote up
constructor (game) {
    this.game = game
    this.renderer = new WebGLRenderer({
      canvas: this.game.pcanvas,
      PixelRatio: window.devicePixelRatio
    })
    this.scene = new Scene()
    this.scene.background = new Color('black')
    const light = new AmbientLight(0xffffff)
    this.scene.add(light)
  }
Example #3
Source File: item.js    From architect3d with MIT License 6 votes vote down vote up
/** on is a bool */
	updateHighlight()
	{
		var on = this.hover || this.selected;
		this.highlighted = on;
		var hex = on ? this.emissiveColor : 0x000000;
		if(this.material)
		{
			if(this.material.length)
			{
				this.material.forEach((material) => {
					// TODO_Ekki emissive doesn't exist anymore?
					material.emissive.setHex(hex);
					this.material.emissive = new Color(hex);
				});
			}
			else
			{
				this.material.emissive.setHex(hex);
				this.material.emissive = new Color(hex);
			}
		}

	}
Example #4
Source File: ColorifyShader.js    From Computer-Graphics with MIT License 6 votes vote down vote up
ColorifyShader = {

	uniforms: {

		'tDiffuse': { value: null },
		'color': { value: new Color( 0xffffff ) }

	},

	vertexShader: /* glsl */`

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,

	fragmentShader: /* glsl */`

		uniform vec3 color;
		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 texel = texture2D( tDiffuse, vUv );

			vec3 luma = vec3( 0.299, 0.587, 0.114 );
			float v = dot( texel.xyz, luma );

			gl_FragColor = vec4( v * color, texel.w );

		}`

}
Example #5
Source File: scene.js    From architect3d with MIT License 6 votes vote down vote up
/**
	 * Constructs a scene.
	 * @param model The associated model.
	 * @param textureDir The directory from which to load the textures.
	 */
	constructor(model, textureDir)
	{
		super();
		this.model = model;
		this.textureDir = textureDir;

//		var grid = new GridHelper(4000, 200);

		this.scene = new ThreeScene();
		this.scene.background = new Color(0xffffff);
//		this.scene.fog = new Fog(0xFAFAFA, 0.001, 6000);
		this.items = [];
		this.needsUpdate = false;
		// init item loader
		this.loader = new JSONLoader();
		this.loader.setCrossOrigin('');

		this.gltfloader = new GLTFLoader();
		this.objloader = new OBJLoader();
		this.gltfloader.setCrossOrigin('');

		this.itemLoadingCallbacks = null;
		this.itemLoadedCallbacks = null;
		this.itemRemovedCallbacks = null;
//		this.add(grid);

	}
Example #6
Source File: ClearPass.js    From Computer-Graphics with MIT License 6 votes vote down vote up
constructor( clearColor, clearAlpha ) {

		super();

		this.needsSwap = false;

		this.clearColor = ( clearColor !== undefined ) ? clearColor : 0x000000;
		this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
		this._oldClearColor = new Color();

	}
Example #7
Source File: font_kerning.js    From three-mesh-ui with MIT License 6 votes vote down vote up
//

function init() {

	scene = new THREE.Scene();
	scene.background = new THREE.Color( 0x505050 );

	camera = new THREE.PerspectiveCamera( 60, WIDTH / HEIGHT, 0.1, 100 );

	renderer = new THREE.WebGLRenderer( { antialias: true } );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( WIDTH, HEIGHT );
	renderer.xr.enabled = true;
	document.body.appendChild( VRButton.createButton( renderer ) );
	document.body.appendChild( renderer.domElement );

	controls = new OrbitControls( camera, renderer.domElement );
	camera.position.set( 0, 1.6, 0 );
	controls.target = new THREE.Vector3( 0, 1, -1.8 );
	controls.update();

	// ROOM

	const room = new THREE.LineSegments(
		new BoxLineGeometry( 6, 6, 6, 10, 10, 10 ).translate( 0, 3, 0 ),
		new THREE.LineBasicMaterial( { color: 0x808080 } )
	);

	scene.add( room );

	// TEXT PANEL

	makeTextPanel();

	//

	renderer.setAnimationLoop( loop );

}
Example #8
Source File: ShapeMarker.js    From BlueMapWeb with MIT License 6 votes vote down vote up
/**
     * @param shape {Shape}
     */
    constructor(shape) {
        let geometry = new LineGeometry();
        geometry.setPositions(ShapeMarkerBorder.createLinePoints(shape));

        let material = new LineMaterial({
            color: new Color(),
            opacity: 0,
            transparent: true,
            linewidth: 1,
            depthTest: true,
            vertexColors: false,
            dashed: false,
        });
        material.uniforms.fadeDistanceMin = { value: 0 };
        material.uniforms.fadeDistanceMax = { value: Number.MAX_VALUE };

        material.resolution.set(window.innerWidth, window.innerHeight);

        super(geometry, material);

        this.computeLineDistances();
    }
Example #9
Source File: letter_spacing.js    From three-mesh-ui with MIT License 6 votes vote down vote up
//

function init() {

	scene = new THREE.Scene();
	scene.background = new THREE.Color( 0x505050 );

	camera = new THREE.PerspectiveCamera( 60, WIDTH / HEIGHT, 0.1, 100 );

	renderer = new THREE.WebGLRenderer( { antialias: true } );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( WIDTH, HEIGHT );
	renderer.xr.enabled = true;
	document.body.appendChild( VRButton.createButton( renderer ) );
	document.body.appendChild( renderer.domElement );

	controls = new OrbitControls( camera, renderer.domElement );
	camera.position.set( 0, 1.6, 0 );
	controls.target = new THREE.Vector3( 0, 1, -1.8 );
	controls.update();

	// ROOM

	const room = new THREE.LineSegments( new BoxLineGeometry( 6, 6, 6, 10, 10, 10 ).translate( 0, 3, 0 ), new THREE.LineBasicMaterial( { color: 0x808080 } ) );

	scene.add( room );

	// TEXT PANEL

	makeTextPanel();

	//

	renderer.setAnimationLoop( loop );

}
Example #10
Source File: index.js    From THREE.BlurredLine with MIT License 5 votes vote down vote up
constructor(curve, material, resolution = 1) {
    super(undefined, material);

    this.type = 'BlurredLine';

    this._resolution = resolution;

    this.lineWidth = 1.0;
    this.blurWidth = 1.0;
    this.blur = true;
    this.color = new Color();
    this.opacity = 1.0;

    this.upVector = new Vector3(0.0, 0.0, 1.0);

    this.closed = false;

    this.angleBisection = false; // true: good for 2d

    this.lineShapeVertices = [[]];

    // this.calculateNormals = true;

    this.lineVertices = [];
    this.curve = curve; // curve to read vertices from

    for (let i = 0; i < this._resolution + 1; i++) {
      this.lineVertices[i] = new Vector3();
    }

    this.lineShapeVertices = [];
    for (let i = 0; i < this._resolution + 1; i++) {
      var vertices = [];
      vertices[LEFT_LINE] = new Vector3();
      vertices[RIGHT_LINE] = new Vector3();
      vertices[LEFT_SMOOTH_LINE] = new Vector3();
      vertices[RIGHT_SMOOTH_LINE] = new Vector3();
      this.lineShapeVertices[i] = vertices;
    }

    this.createGeometry();
  }
Example #11
Source File: SubsurfaceScatteringShader.js    From Computer-Graphics with MIT License 5 votes vote down vote up
SubsurfaceScatteringShader = {

	uniforms: UniformsUtils.merge( [
		ShaderLib[ 'phong' ].uniforms,
		{
			'thicknessMap': { value: null },
			'thicknessColor': { value: new Color( 0xffffff ) },
			'thicknessDistortion': { value: 0.1 },
			'thicknessAmbient': { value: 0.0 },
			'thicknessAttenuation': { value: 0.1 },
			'thicknessPower': { value: 2.0 },
			'thicknessScale': { value: 10.0 }
		}

	] ),

	vertexShader: [
		'#define USE_UV',
		ShaderChunk[ 'meshphong_vert' ],
	].join( '\n' ),

	fragmentShader: [
		'#define USE_UV',
		'#define SUBSURFACE',

		meshphong_frag_head,

		'uniform sampler2D thicknessMap;',
		'uniform float thicknessPower;',
		'uniform float thicknessScale;',
		'uniform float thicknessDistortion;',
		'uniform float thicknessAmbient;',
		'uniform float thicknessAttenuation;',
		'uniform vec3 thicknessColor;',

		'void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in GeometricContext geometry, inout ReflectedLight reflectedLight) {',
		'	vec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;',
		'	vec3 scatteringHalf = normalize(directLight.direction + (geometry.normal * thicknessDistortion));',
		'	float scatteringDot = pow(saturate(dot(geometry.viewDir, -scatteringHalf)), thicknessPower) * thicknessScale;',
		'	vec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;',
		'	reflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;',
		'}',

		meshphong_frag_body.replace( '#include <lights_fragment_begin>',

			replaceAll(
				ShaderChunk[ 'lights_fragment_begin' ],
				'RE_Direct( directLight, geometry, material, reflectedLight );',
				[
					'RE_Direct( directLight, geometry, material, reflectedLight );',

					'#if defined( SUBSURFACE ) && defined( USE_UV )',
					' RE_Direct_Scattering(directLight, vUv, geometry, reflectedLight);',
					'#endif',
				].join( '\n' )
			),

		),

	].join( '\n' ),

}
Example #12
Source File: Entities.js    From webmc with MIT License 5 votes vote down vote up
constructor (game) {
    this.game = game

    this.mobMaterial = new MeshStandardMaterial({
      color: new Color('red')
    })
    this.mobGeometry = new BoxGeometry(1, 1, 1)
    this.mobMaxCount = 1000
    this.mobMesh = new InstancedMesh(
      this.mobGeometry,
      this.mobMaterial,
      this.mobMaxCount
    )
    this.mobMesh.instanceMatrix.setUsage(DynamicDrawUsage)
    this.game.scene.add(this.mobMesh)

    this.playerMaterial = new MeshStandardMaterial({
      color: new Color('blue')
    })
    this.playerGeometry = new BoxGeometry(1, 1, 1)
    this.playerMaxCount = 1000
    this.playerMesh = new InstancedMesh(
      this.playerGeometry,
      this.playerMaterial,
      this.playerMaxCount
    )
    this.playerMesh.instanceMatrix.setUsage(DynamicDrawUsage)
    this.game.scene.add(this.playerMesh)

    this.objectMaterial = new MeshStandardMaterial({
      color: new Color('green')
    })
    this.objectGeometry = new BoxGeometry(0.25, 0.25, 0.25)
    this.objectMaxCount = 1000
    this.objectMesh = new InstancedMesh(
      this.objectGeometry,
      this.objectMaterial,
      this.objectMaxCount
    )
    this.objectMesh.instanceMatrix.setUsage(DynamicDrawUsage)
    this.game.scene.add(this.objectMesh)

    this.dummy = new Object3D()
  }
Example #13
Source File: BokehPass.js    From Computer-Graphics with MIT License 5 votes vote down vote up
constructor( scene, camera, params ) {

		super();

		this.scene = scene;
		this.camera = camera;

		const focus = ( params.focus !== undefined ) ? params.focus : 1.0;
		const aspect = ( params.aspect !== undefined ) ? params.aspect : camera.aspect;
		const aperture = ( params.aperture !== undefined ) ? params.aperture : 0.025;
		const maxblur = ( params.maxblur !== undefined ) ? params.maxblur : 1.0;

		// render targets

		const width = params.width || window.innerWidth || 1;
		const height = params.height || window.innerHeight || 1;

		this.renderTargetDepth = new WebGLRenderTarget( width, height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter
		} );

		this.renderTargetDepth.texture.name = 'BokehPass.depth';

		// depth material

		this.materialDepth = new MeshDepthMaterial();
		this.materialDepth.depthPacking = RGBADepthPacking;
		this.materialDepth.blending = NoBlending;

		// bokeh material

		if ( BokehShader === undefined ) {

			console.error( 'THREE.BokehPass relies on BokehShader' );

		}

		const bokehShader = BokehShader;
		const bokehUniforms = UniformsUtils.clone( bokehShader.uniforms );

		bokehUniforms[ 'tDepth' ].value = this.renderTargetDepth.texture;

		bokehUniforms[ 'focus' ].value = focus;
		bokehUniforms[ 'aspect' ].value = aspect;
		bokehUniforms[ 'aperture' ].value = aperture;
		bokehUniforms[ 'maxblur' ].value = maxblur;
		bokehUniforms[ 'nearClip' ].value = camera.near;
		bokehUniforms[ 'farClip' ].value = camera.far;

		this.materialBokeh = new ShaderMaterial( {
			defines: Object.assign( {}, bokehShader.defines ),
			uniforms: bokehUniforms,
			vertexShader: bokehShader.vertexShader,
			fragmentShader: bokehShader.fragmentShader
		} );

		this.uniforms = bokehUniforms;
		this.needsSwap = false;

		this.fsQuad = new FullScreenQuad( this.materialBokeh );

		this._oldClearColor = new Color();

	}
Example #14
Source File: font_kerning.js    From three-mesh-ui with MIT License 5 votes vote down vote up
function makeKernedContainer( kerning ) {

	const container = new ThreeMeshUI.Block( {
		width: 1.8,
		height: 0.12,
		padding: 0.05,
		contentDirection: "row",
		justifyContent: 'center',
		textAlign: 'left',
		fontFamily: FontJSON,
		fontTexture: FontImage,
		backgroundOpacity: 0
	} );

	const titleBox = new ThreeMeshUI.Block( {
		width: 0.8,
		height: 0.1,
		margin: 0.01,
		padding: 0.025,
		justifyContent: 'center',
		backgroundColor: new Color( 0xff9900 ),
		textAlign: 'left'
	} );

	const title = new ThreeMeshUI.Text( {
		content: `.set({fontKerning: "${kerning}"})`,
		fontSize: 0.055
	} );

	titleBox.add( title );

	const textBox = new ThreeMeshUI.Block( {
		width: 1.4,
		height: 0.1,
		margin: 0.01,
		padding: 0.02,
		justifyContent: 'center',
		fontSize: 0.055,
	} );

	textBox.add(
		new ThreeMeshUI.Text( {
			content: '"LYON F. to ATLANTA GA. Via ALTOONA PA."',
			fontKerning: kerning,
		} )
	);

	container.add( titleBox );
	container.add( textBox );

	return container;


}
Example #15
Source File: ToonShader.js    From Computer-Graphics with MIT License 5 votes vote down vote up
ToonShader1 = {

	uniforms: {

		'uDirLightPos': { value: new Vector3() },
		'uDirLightColor': { value: new Color( 0xeeeeee ) },

		'uAmbientLightColor': { value: new Color( 0x050505 ) },

		'uBaseColor': { value: new Color( 0xffffff ) }

	},

	vertexShader: /* glsl */`

		varying vec3 vNormal;
		varying vec3 vRefract;

		void main() {

			vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
			vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
			vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );

			vNormal = normalize( normalMatrix * normal );

			vec3 I = worldPosition.xyz - cameraPosition;
			vRefract = refract( normalize( I ), worldNormal, 1.02 );

			gl_Position = projectionMatrix * mvPosition;

		}`,

	fragmentShader: /* glsl */`

		uniform vec3 uBaseColor;

		uniform vec3 uDirLightPos;
		uniform vec3 uDirLightColor;

		uniform vec3 uAmbientLightColor;

		varying vec3 vNormal;

		varying vec3 vRefract;

		void main() {

			float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);
			vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;

			float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) );
			intensity += length(lightWeighting) * 0.2;

			float cameraWeighting = dot( normalize( vNormal ), vRefract );
			intensity += pow( 1.0 - length( cameraWeighting ), 6.0 );
			intensity = intensity * 0.2 + 0.3;

			if ( intensity < 0.50 ) {

				gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 );

			} else {

				gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 );

		}

		}`

}
Example #16
Source File: ClearPass.js    From three-viewer with MIT License 5 votes vote down vote up
/**
	 * Constructs a new clear pass.
	 *
	 * @param {Boolean} [color=true] - Determines whether the color buffer should be cleared.
	 * @param {Boolean} [depth=true] - Determines whether the depth buffer should be cleared.
	 * @param {Boolean} [stencil=false] - Determines whether the stencil buffer should be cleared.
	 */

	constructor(color = true, depth = true, stencil = false) {

		super("ClearPass", null, null);

		this.needsSwap = false;

		/**
		 * Indicates whether the color buffer should be cleared.
		 *
		 * @type {Boolean}
		 */

		this.color = color;

		/**
		 * Indicates whether the depth buffer should be cleared.
		 *
		 * @type {Boolean}
		 */

		this.depth = depth;

		/**
		 * Indicates whether the stencil buffer should be cleared.
		 *
		 * @type {Boolean}
		 */

		this.stencil = stencil;

		/**
		 * An override clear color.
		 *
		 * The default value is null.
		 *
		 * @type {Color}
		 */

		this.overrideClearColor = null;

		/**
		 * An override clear alpha.
		 *
		 * The default value is -1.
		 *
		 * @type {Number}
		 */

		this.overrideClearAlpha = -1.0;

	}
Example #17
Source File: Map.js    From BlueMapWeb with MIT License 5 votes vote down vote up
/**
	 * @param id {string}
	 * @param dataUrl {string}
	 * @param events {EventTarget}
	 */
	constructor(id, dataUrl, events = null) {
		Object.defineProperty( this, 'isMap', { value: true } );

		this.events = events;

		this.data = {
			id: id,
			sorting: 0,
			dataUrl: dataUrl,
			settingsUrl: dataUrl + "settings.json",
			texturesUrl: dataUrl + "textures.json",
			name: id,
			startPos: {x: 0, z: 0},
			skyColor: new Color(),
			ambientLight: 0,
			hires: {
				tileSize: {x: 32, z: 32},
				scale: {x: 1, z: 1},
				translate: {x: 2, z: 2}
			},
			lowres: {
				tileSize: {x: 32, z: 32},
				scale: {x: 1, z: 1},
				translate: {x: 2, z: 2}
			}
		};

		this.raycaster = new Raycaster();

		/** @type {ShaderMaterial[]} */
		this.hiresMaterial = null;
		/** @type {ShaderMaterial} */
		this.lowresMaterial = null;
		/** @type {Texture[]} */
		this.loadedTextures = [];

		/** @type {TileManager} */
		this.hiresTileManager = null;
		/** @type {TileManager} */
		this.lowresTileManager = null;
	}
Example #18
Source File: LuminosityHighPassShader.js    From AudioPlayer with MIT License 5 votes vote down vote up
LuminosityHighPassShader = {
  shaderID: "luminosityHighPass",

  uniforms: {
    tDiffuse: { value: null },
    luminosityThreshold: { value: 1.0 },
    smoothWidth: { value: 1.0 },
    defaultColor: { value: new Color(0x000000) },
    defaultOpacity: { value: 0.0 },
  },

  vertexShader: [
    "varying vec2 vUv;",

    "void main() {",

    "	vUv = uv;",

    "	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

    "}",
  ].join("\n"),

  fragmentShader: [
    "uniform sampler2D tDiffuse;",
    "uniform vec3 defaultColor;",
    "uniform float defaultOpacity;",
    "uniform float luminosityThreshold;",
    "uniform float smoothWidth;",

    "varying vec2 vUv;",

    "void main() {",

    "	vec4 texel = texture2D( tDiffuse, vUv );",

    "	vec3 luma = vec3( 0.299, 0.587, 0.114 );",

    "	float v = dot( texel.xyz, luma );",

    "	vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity );",

    "	float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v );",

    "	gl_FragColor = mix( outputColor, texel, alpha );",

    "}",
  ].join("\n"),
}
Example #19
Source File: main.js    From web-ifc-viewer with MIT License 5 votes vote down vote up
viewer = new IfcViewerAPI({ container, backgroundColor: new Color(255, 255, 255) })
Example #20
Source File: b3dmExample.js    From 3DTilesRendererJS with Apache License 2.0 5 votes vote down vote up
// Adjusts the three.js standard shader to include batchid highlight
function batchIdHighlightShaderMixin( shader ) {

	const newShader = { ...shader };
	newShader.uniforms = {
		highlightedBatchId: { value: - 1 },
		highlightColor: { value: new Color( 0xFFC107 ).convertSRGBToLinear() },
		...UniformsUtils.clone( shader.uniforms ),
	};
	newShader.extensions = {
		derivatives: true,
	};
	newShader.lights = true;
	newShader.vertexShader =
		`
			attribute float _batchid;
			varying float batchid;
		` +
		newShader.vertexShader.replace(
			/#include <uv_vertex>/,
			`
			#include <uv_vertex>
			batchid = _batchid;
			`
		);
	newShader.fragmentShader =
		`
			varying float batchid;
			uniform float highlightedBatchId;
			uniform vec3 highlightColor;
		` +
		newShader.fragmentShader.replace(
			/vec4 diffuseColor = vec4\( diffuse, opacity \);/,
			`
			vec4 diffuseColor =
				abs( batchid - highlightedBatchId ) < 0.5 ?
				vec4( highlightColor, opacity ) :
				vec4( diffuse, opacity );
			`
		);

	return newShader;

}
Example #21
Source File: index.js    From map33.js with MIT License 5 votes vote down vote up
scene.background = new Color(0x91abb5);
Example #22
Source File: VoxelLoader.js    From three-voxel-loader with MIT License 5 votes vote down vote up
/**
   * Generates a polygon mesh with cubes based on voxel data.
   * One cube for each voxel.
   * @param {PointOctree} octree Octree with voxel data stored as points in space.
   * @returns {Mesh} 3D mesh based on voxel data
   */
  generateMesh(octree) {

    let mergedGeometry = new Geometry();
    const material = this.material;

    for (const leaf of octree.leaves()) {
      if (leaf.points !== null) {
        const pos = new Vector3();
        var i;
        let min = { x: leaf.points[0].x, y: leaf.points[0].y, z: leaf.points[0].z };
        let max = { x: leaf.points[0].x, y: leaf.points[0].y, z: leaf.points[0].z };

        for (i = 0; i < leaf.points.length; i++) {
          const point = leaf.points[i];
          pos.add(point);
          min.x = Math.min(min.x, point.x);
          min.y = Math.min(min.y, point.y);
          min.z = Math.min(min.z, point.z);
          max.x = Math.max(max.x, point.x);
          max.y = Math.max(max.y, point.y);
          max.z = Math.max(max.z, point.z);
        }

        let width = Math.round((this.voxelSize + (max.x - min.x)) * 100) / 100;;
        let height = Math.round((this.voxelSize + (max.y - min.y)) * 100) / 100;;
        let depth = Math.round((this.voxelSize + (max.z - min.z)) * 100) / 100;

        let voxelGeometry = new BoxGeometry(width, height, depth);
        pos.divideScalar(i);

        const rgb = leaf.data[0].color;
        if (rgb != null) {
          const color = new Color().setRGB(rgb.r / 255, rgb.g / 255, rgb.b / 255);

          for (var i = 0; i < voxelGeometry.faces.length; i++) {
            let face = voxelGeometry.faces[i];
            face.color.set(color);
          }
        }

        voxelGeometry.translate(pos.x, pos.y, pos.z);
        mergedGeometry.merge(voxelGeometry);
        voxelGeometry.translate(-pos.x, -pos.y, -pos.z);
      }
    }

    let bufGeometry = new BufferGeometry().fromGeometry(mergedGeometry);
    bufGeometry.computeFaceNormals();
    bufGeometry.computeVertexNormals();

    var voxels = new Mesh(bufGeometry, material);

    return voxels;
  }
Example #23
Source File: skybox.js    From architect3d with MIT License 5 votes vote down vote up
constructor(scene, renderer)
	{
		super();
		
		this.defaultEnvironment = 'rooms/textures/envs/Garden.png';
		this.useEnvironment = false;
		this.topColor = 0x92b2ce;//0xe9e9e9; //0xf9f9f9;//0x565e63
		this.bottomColor = 0xffffff;//0xD8ECF9
		this.verticalOffset = 400;
		this.exponent = 0.5;
		
		var uniforms = {topColor: {type: 'c',value: new Color(this.topColor)},bottomColor: {type: 'c',value: new Color(this.bottomColor)},offset: {type: 'f',value: this.verticalOffset}, exponent: {type:'f', value: this.exponent}};
		
		this.scene = scene;
		this.renderer = renderer;
		
		this.sphereRadius = 4000;
		this.widthSegments = 32;
		this.heightSegments = 15;
		this.sky = null;

		this.plainVertexShader = ['varying vec3 vWorldPosition;','void main() {','vec4 worldPosition = modelMatrix * vec4( position, 1.0 );','vWorldPosition = worldPosition.xyz;','gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0 );','}'].join('\n');
		this.plainFragmentShader = ['uniform vec3 bottomColor;','uniform vec3 topColor;','uniform float offset;','uniform float exponent;','varying vec3 vWorldPosition;','void main() {',' float h = normalize( vWorldPosition + offset ).y;',' gl_FragColor = vec4( mix( bottomColor, topColor, max( pow( max(h, 0.0 ), exponent ), 0.0 ) ), 1.0 );','}'].join('\n');
		
		this.vertexShader = ['varying vec2 vUV;','void main() {','  vUV=uv;','  vec4 pos = vec4(position, 1.0);', '   gl_Position = projectionMatrix * modelViewMatrix * pos;','}'].join('\n');
		this.fragmentShader = ['uniform sampler2D texture;', 'varying vec2 vUV;', 'void main() {  ', 'vec4 sample = texture2D(texture, vUV);', 'gl_FragColor = vec4(sample.xyz, sample.w);' ,'}'].join('\n');
		
		this.texture = new TextureLoader();
		this.plainSkyMat = new ShaderMaterial({vertexShader: this.plainVertexShader,fragmentShader: this.plainFragmentShader,uniforms: uniforms, side: DoubleSide});
		this.skyMat = undefined;
		
		this.skyGeo = new SphereGeometry(this.sphereRadius, this.widthSegments, this.heightSegments);
		this.sky = new Mesh(this.skyGeo, this.skyMat);
//		this.sky.position.x += this.sphereRadius*0.5;
		
		
		var groundT = new TextureLoader().load('rooms/textures/Ground_4K.jpg', function(){});		
		groundT.wrapS = groundT.wrapT = RepeatWrapping;
		groundT.repeat.set(10,10);
		
//		var uniforms2 = {topColor: {type: 'c',value: new Color(0xFFFFFF)},bottomColor: {type: 'c',value: new Color(0x999999)},offset: {type: 'f',value: this.verticalOffset}, exponent: {type:'f', value: this.exponent}};
		this.groundGeo = new PlaneGeometry(10000, 10000, 10);
		this.groundMat = new MeshBasicMaterial({color: 0xEAEAEA, side: DoubleSide, map:groundT });
		this.ground = new Mesh(this.groundGeo, this.groundMat);
		this.ground.rotateX(-Math.PI * 0.5);
		this.ground.position.y = -1;
		
		this.groundSceneReflector = new GroundSceneReflector(this.ground, this.renderer, this.scene,{textureOne:'rooms/textures/Ground_4K.jpg', textureTwo:'rooms/textures/GroundRough.jpg', wrapOne:{x:40, y:40}, wrapTwo:{x:50, y:50}, textureWidth: 512, textureHeight: 512, intensity: 0.1, blendIntensity: 0.05});
		
		this.scene.add(this.sky);
		this.scene.add(this.ground);
		
		var axesHelper = new AxesHelper( 100 );
		this.scene.add( axesHelper );
		
		this.init();
	}
Example #24
Source File: MapViewer.js    From BlueMapWeb with MIT License 5 votes vote down vote up
/**
	 * @param element {Element}
	 * @param events {EventTarget}
	 */
	constructor(element, events = element) {
		Object.defineProperty( this, 'isMapViewer', { value: true } );

		this.rootElement = element;
		this.events = events;

		this.data = {
			map: null,
			camera: null,
			controlsManager: null,
			uniforms: {
				sunlightStrength: { value: 1 },
				ambientLight: { value: 0 },
				skyColor: { value: new Color(0.5, 0.5, 1) },
				hiresTileMap: {
					value: {
						map: null,
						size: TileManager.tileMapSize,
						scale: new Vector2(1, 1),
						translate: new Vector2(),
						pos: new Vector2(),
					}
				}
			},
			superSampling: 1,
			loadedCenter: new Vector2(0, 0),
			loadedHiresViewDistance: 200,
			loadedLowresViewDistance: 2000,
		}

		this.tileCacheHash = generateCacheHash();

		this.stats = new Stats();
		this.stats.hide();

		// renderer
		this.renderer = new WebGLRenderer({
			antialias: true,
			sortObjects: true,
			preserveDrawingBuffer: true,
			logarithmicDepthBuffer: true,
		});
		this.renderer.autoClear = false;
		this.renderer.uniforms = this.data.uniforms;

		// CSS2D renderer
		this.css2dRenderer = new CSS2DRenderer(this.events);

		this.skyboxScene = new SkyboxScene(this.data.uniforms);

		this.camera = new CombinedCamera(75, 1, 0.1, 10000, 0);
		this.skyboxCamera = new PerspectiveCamera(75, 1, 0.1, 10000);

		this.controlsManager = new ControlsManager(this, this.camera);

		this.raycaster = new Raycaster();
		this.raycaster.layers.enableAll();
		this.raycaster.params.Line2 = {threshold: 20}

		/** @type {Map} */
		this.map = null;

		this.markers = new MarkerSet("bm-root");

		this.lastFrame = 0;

		// initialize
		this.initializeRootElement();

		// handle window resizes
		window.addEventListener("resize", this.handleContainerResize);

		// start render-loop
		requestAnimationFrame(this.renderLoop);
	}
Example #25
Source File: SSAOPass.js    From Computer-Graphics with MIT License 4 votes vote down vote up
constructor( scene, camera, width, height ) {

		super();

		this.width = ( width !== undefined ) ? width : 512;
		this.height = ( height !== undefined ) ? height : 512;

		this.clear = true;

		this.camera = camera;
		this.scene = scene;

		this.kernelRadius = 8;
		this.kernelSize = 32;
		this.kernel = [];
		this.noiseTexture = null;
		this.output = 0;

		this.minDistance = 0.005;
		this.maxDistance = 0.1;

		this._visibilityCache = new Map();

		//

		this.generateSampleKernel();
		this.generateRandomKernelRotations();

		// beauty render target

		const depthTexture = new DepthTexture();
		depthTexture.format = DepthStencilFormat;
		depthTexture.type = UnsignedInt248Type;

		this.beautyRenderTarget = new WebGLRenderTarget( this.width, this.height );

		// normal render target with depth buffer

		this.normalRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			depthTexture: depthTexture
		} );

		// ssao render target

		this.ssaoRenderTarget = new WebGLRenderTarget( this.width, this.height );

		this.blurRenderTarget = this.ssaoRenderTarget.clone();

		// ssao material

		if ( SSAOShader === undefined ) {

			console.error( 'THREE.SSAOPass: The pass relies on SSAOShader.' );

		}

		this.ssaoMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSAOShader.defines ),
			uniforms: UniformsUtils.clone( SSAOShader.uniforms ),
			vertexShader: SSAOShader.vertexShader,
			fragmentShader: SSAOShader.fragmentShader,
			blending: NoBlending
		} );

		this.ssaoMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
		this.ssaoMaterial.uniforms[ 'tNormal' ].value = this.normalRenderTarget.texture;
		this.ssaoMaterial.uniforms[ 'tDepth' ].value = this.normalRenderTarget.depthTexture;
		this.ssaoMaterial.uniforms[ 'tNoise' ].value = this.noiseTexture;
		this.ssaoMaterial.uniforms[ 'kernel' ].value = this.kernel;
		this.ssaoMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
		this.ssaoMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
		this.ssaoMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
		this.ssaoMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
		this.ssaoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );

		// normal material

		this.normalMaterial = new MeshNormalMaterial();
		this.normalMaterial.blending = NoBlending;

		// blur material

		this.blurMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSAOBlurShader.defines ),
			uniforms: UniformsUtils.clone( SSAOBlurShader.uniforms ),
			vertexShader: SSAOBlurShader.vertexShader,
			fragmentShader: SSAOBlurShader.fragmentShader
		} );
		this.blurMaterial.uniforms[ 'tDiffuse' ].value = this.ssaoRenderTarget.texture;
		this.blurMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );

		// material for rendering the depth

		this.depthRenderMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSAODepthShader.defines ),
			uniforms: UniformsUtils.clone( SSAODepthShader.uniforms ),
			vertexShader: SSAODepthShader.vertexShader,
			fragmentShader: SSAODepthShader.fragmentShader,
			blending: NoBlending
		} );
		this.depthRenderMaterial.uniforms[ 'tDepth' ].value = this.normalRenderTarget.depthTexture;
		this.depthRenderMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
		this.depthRenderMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;

		// material for rendering the content of a render target

		this.copyMaterial = new ShaderMaterial( {
			uniforms: UniformsUtils.clone( CopyShader.uniforms ),
			vertexShader: CopyShader.vertexShader,
			fragmentShader: CopyShader.fragmentShader,
			transparent: true,
			depthTest: false,
			depthWrite: false,
			blendSrc: DstColorFactor,
			blendDst: ZeroFactor,
			blendEquation: AddEquation,
			blendSrcAlpha: DstAlphaFactor,
			blendDstAlpha: ZeroFactor,
			blendEquationAlpha: AddEquation
		} );

		this.fsQuad = new FullScreenQuad( null );

		this.originalClearColor = new Color();

	}
Example #26
Source File: Intro.jsx    From portfolio with MIT License 4 votes vote down vote up
export default function Intro({ darkTheme, active, setActivePage }) {

  // Use ref because need to directly manipulate DOM
  const mountRef = useRef(null);
  const [ requestId, setRequestId ] = useState(null)

  useEffect(() => {

    const curr = mountRef.current

    var startTime = Date.now();
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
    var renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setClearColor(darkTheme ? 0x000 : 0xf7f7f7,  1)

    renderer.setSize(window.innerWidth, window.innerHeight);
    mountRef.current.appendChild(renderer.domElement);


    let geometry, color1, color2
    let w = 12, h = 2
    if (darkTheme) {
      geometry = new THREE.PlaneGeometry(w, h, 70, 50);
      color2 = new Color(0x00d1ff)
      color1 = new Color(0x040b55)
    } else {
      geometry = new THREE.PlaneGeometry(w, h, 70, 50);
      color2 =  new Color(0x5233a8)
      color1 =  new Color(0x17a3db)
    }

    var material = new THREE.ShaderMaterial({
      glslVersion: THREE.GLSL1,
      wireframe: true,
      vertexShader: PerlinShader.vertexShader,
      fragmentShader: PerlinShader.fragmentShader,
      uniforms: {
        p: { value: PerlinShader.p },
        time: { value: 0 },
        color1: { value: new Vector4(color1.r, color1.g, color1.b, 1)},
        color2: { value: new Vector4(color2.r, color2.g, color2.b, 1)},
      }
    })

    var plane1 = new THREE.Mesh(geometry, material);
    plane1.rotateX(-1.1)
    plane1.position.z = 2
    plane1.position.y = -1.15
    scene.add(plane1)
    
    var plane2 = new THREE.Mesh(geometry, material);
    plane2.rotateX(1.1)
    plane2.position.z = 2
    plane2.position.y = 1.15
    scene.add(plane2)

    camera.position.z = 5

    var animate = function () {
      if (!active) { 
        cancelAnimationFrame(requestId)
        setRequestId(null)
        return
      }

      setRequestId(requestAnimationFrame(animate));

      var elapsedMilliseconds = Date.now() - startTime;
      plane1.material.uniforms.time.value = elapsedMilliseconds / 1000. / 2;
      plane1.material.uniforms.time.value %= 30;
      renderer.render(scene, camera);
    }

    let onWindowResize = function () {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    };

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

    animate()

    return () => curr.removeChild(renderer.domElement);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [darkTheme, active]);

  const updatePage = () => {
    const newActivePage = [false, false, false, false]
    newActivePage[1] = true
    setActivePage(newActivePage)
  }

  return (
    <div className='intro' id='intro'>

      <div id='c' ref={mountRef}></div>
      
      <div className='info'>
        <h1 className='blue'>Médéric Carriat</h1>
        <h4 className='blue'>Software Engineer looking for a 6-month internship</h4>
      </div>

      <div className='arrow-border'>
        <a 
          className='arrow-container'
          href='#experience'
          onClick={updatePage}
        >
          <span className='arrow'>
            <i class="fas fa-arrow-right blue"></i>
          </span>
        </a>
      </div>

    </div>
  )
}
Example #27
Source File: ToonShader.js    From Computer-Graphics with MIT License 4 votes vote down vote up
ToonShaderHatching = {

	uniforms: {

		'uDirLightPos':	{ value: new Vector3() },
		'uDirLightColor': { value: new Color( 0xeeeeee ) },

		'uAmbientLightColor': { value: new Color( 0x050505 ) },

		'uBaseColor': { value: new Color( 0xffffff ) },
		'uLineColor1': { value: new Color( 0x000000 ) },
		'uLineColor2': { value: new Color( 0x000000 ) },
		'uLineColor3': { value: new Color( 0x000000 ) },
		'uLineColor4': { value: new Color( 0x000000 ) }

	},

	vertexShader: /* glsl */`

		varying vec3 vNormal;

		void main() {

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
			vNormal = normalize( normalMatrix * normal );

		}`,

	fragmentShader: /* glsl */`

		uniform vec3 uBaseColor;
		uniform vec3 uLineColor1;
		uniform vec3 uLineColor2;
		uniform vec3 uLineColor3;
		uniform vec3 uLineColor4;

		uniform vec3 uDirLightPos;
		uniform vec3 uDirLightColor;

		uniform vec3 uAmbientLightColor;

		varying vec3 vNormal;

		void main() {

			float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);
			vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;

			gl_FragColor = vec4( uBaseColor, 1.0 );

			if ( length(lightWeighting) < 1.00 ) {

				if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) {

					gl_FragColor = vec4( uLineColor1, 1.0 );

				}

			}

			if ( length(lightWeighting) < 0.75 ) {

				if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) {

					gl_FragColor = vec4( uLineColor2, 1.0 );

				}

			}

			if ( length(lightWeighting) < 0.50 ) {

				if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) {

					gl_FragColor = vec4( uLineColor3, 1.0 );

				}

			}

			if ( length(lightWeighting) < 0.3465 ) {

				if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) {

					gl_FragColor = vec4( uLineColor4, 1.0 );

			}

			}

		}`

}
Example #28
Source File: 3MFLoader.js    From canvas with Apache License 2.0 4 votes vote down vote up
ThreeMFLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: ThreeMFLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;
		var loader = new FileLoader( scope.manager );
		loader.setPath( scope.path );
		loader.setResponseType( 'arraybuffer' );
		loader.load( url, function ( buffer ) {

			try {

				onLoad( scope.parse( buffer ) );

			} catch ( e ) {

				if ( onError ) {

					onError( e );

				} else {

					console.error( e );

				}

				scope.manager.itemError( url );

			}

		}, onProgress, onError );

	},

	parse: function ( data ) {

		var scope = this;
		var textureLoader = new TextureLoader( this.manager );

		function loadDocument( data ) {

			var zip = null;
			var file = null;

			var relsName;
			var modelRelsName;
			var modelPartNames = [];
			var printTicketPartNames = [];
			var texturesPartNames = [];
			var otherPartNames = [];

			var rels;
			var modelRels;
			var modelParts = {};
			var printTicketParts = {};
			var texturesParts = {};
			var otherParts = {};

			try {

				zip = new JSZip( data );

			} catch ( e ) {

				if ( e instanceof ReferenceError ) {

					console.error( 'THREE.3MFLoader: jszip missing and file is compressed.' );
					return null;

				}

			}

			for ( file in zip.files ) {

				if ( file.match( /\_rels\/.rels$/ ) ) {

					relsName = file;

				} else if ( file.match( /3D\/_rels\/.*\.model\.rels$/ ) ) {

					modelRelsName = file;

				} else if ( file.match( /^3D\/.*\.model$/ ) ) {

					modelPartNames.push( file );

				} else if ( file.match( /^3D\/Metadata\/.*\.xml$/ ) ) {

					printTicketPartNames.push( file );

				} else if ( file.match( /^3D\/Textures?\/.*/ ) ) {

					texturesPartNames.push( file );

				} else if ( file.match( /^3D\/Other\/.*/ ) ) {

					otherPartNames.push( file );

				}

			}

			//

			var relsView = new Uint8Array( zip.file( relsName ).asArrayBuffer() );
			var relsFileText = LoaderUtils.decodeText( relsView );
			rels = parseRelsXml( relsFileText );

			//

			if ( modelRelsName ) {

				var relsView = new Uint8Array( zip.file( modelRelsName ).asArrayBuffer() );
				var relsFileText = LoaderUtils.decodeText( relsView );
				modelRels = parseRelsXml( relsFileText );

			}

			//

			for ( var i = 0; i < modelPartNames.length; i ++ ) {

				var modelPart = modelPartNames[ i ];
				var view = new Uint8Array( zip.file( modelPart ).asArrayBuffer() );

				var fileText = LoaderUtils.decodeText( view );
				var xmlData = new DOMParser().parseFromString( fileText, 'application/xml' );

				if ( xmlData.documentElement.nodeName.toLowerCase() !== 'model' ) {

					console.error( 'THREE.3MFLoader: Error loading 3MF - no 3MF document found: ', modelPart );

				}

				var modelNode = xmlData.querySelector( 'model' );
				var extensions = {};

				for ( var i = 0; i < modelNode.attributes.length; i ++ ) {

					var attr = modelNode.attributes[ i ];
					if ( attr.name.match( /^xmlns:(.+)$/ ) ) {

						extensions[ attr.value ] = RegExp.$1;

					}

				}

				var modelData = parseModelNode( modelNode );
				modelData[ 'xml' ] = modelNode;

				if ( 0 < Object.keys( extensions ).length ) {

					modelData[ 'extensions' ] = extensions;

				}

				modelParts[ modelPart ] = modelData;

			}

			//

			for ( var i = 0; i < texturesPartNames.length; i ++ ) {

				var texturesPartName = texturesPartNames[ i ];
				texturesParts[ texturesPartName ] = zip.file( texturesPartName ).asArrayBuffer();

			}

			return {
				rels: rels,
				modelRels: modelRels,
				model: modelParts,
				printTicket: printTicketParts,
				texture: texturesParts,
				other: otherParts
			};

		}

		function parseRelsXml( relsFileText ) {

			var relationships = [];

			var relsXmlData = new DOMParser().parseFromString( relsFileText, 'application/xml' );

			var relsNodes = relsXmlData.querySelectorAll( 'Relationship' );

			for ( var i = 0; i < relsNodes.length; i ++ ) {

				var relsNode = relsNodes[ i ];

				var relationship = {
					target: relsNode.getAttribute( 'Target' ), //required
					id: relsNode.getAttribute( 'Id' ), //required
					type: relsNode.getAttribute( 'Type' ) //required
				};

				relationships.push( relationship );

			}

			return relationships;

		}

		function parseMetadataNodes( metadataNodes ) {

			var metadataData = {};

			for ( var i = 0; i < metadataNodes.length; i ++ ) {

				var metadataNode = metadataNodes[ i ];
				var name = metadataNode.getAttribute( 'name' );
				var validNames = [
					'Title',
					'Designer',
					'Description',
					'Copyright',
					'LicenseTerms',
					'Rating',
					'CreationDate',
					'ModificationDate'
				];

				if ( 0 <= validNames.indexOf( name ) ) {

					metadataData[ name ] = metadataNode.textContent;

				}

			}

			return metadataData;

		}

		function parseBasematerialsNode( basematerialsNode ) {

			var basematerialsData = {
				id: basematerialsNode.getAttribute( 'id' ), // required
				basematerials: []
			};

			var basematerialNodes = basematerialsNode.querySelectorAll( 'base' );

			for ( var i = 0; i < basematerialNodes.length; i ++ ) {

				var basematerialNode = basematerialNodes[ i ];
				var basematerialData = parseBasematerialNode( basematerialNode );
				basematerialData.index = i; // the order and count of the material nodes form an implicit 0-based index
				basematerialsData.basematerials.push( basematerialData );

			}

			return basematerialsData;

		}

		function parseTexture2DNode( texture2DNode ) {

			var texture2dData = {
				id: texture2DNode.getAttribute( 'id' ), // required
				path: texture2DNode.getAttribute( 'path' ), // required
				contenttype: texture2DNode.getAttribute( 'contenttype' ), // required
				tilestyleu: texture2DNode.getAttribute( 'tilestyleu' ),
				tilestylev: texture2DNode.getAttribute( 'tilestylev' ),
				filter: texture2DNode.getAttribute( 'filter' ),
			};

			return texture2dData;

		}

		function parseTextures2DGroupNode( texture2DGroupNode ) {

			var texture2DGroupData = {
				id: texture2DGroupNode.getAttribute( 'id' ), // required
				texid: texture2DGroupNode.getAttribute( 'texid' ), // required
				displaypropertiesid: texture2DGroupNode.getAttribute( 'displaypropertiesid' )
			};

			var tex2coordNodes = texture2DGroupNode.querySelectorAll( 'tex2coord' );

			var uvs = [];

			for ( var i = 0; i < tex2coordNodes.length; i ++ ) {

				var tex2coordNode = tex2coordNodes[ i ];
				var u = tex2coordNode.getAttribute( 'u' );
				var v = tex2coordNode.getAttribute( 'v' );

				uvs.push( parseFloat( u ), parseFloat( v ) );

			}

			texture2DGroupData[ 'uvs' ] = new Float32Array( uvs );

			return texture2DGroupData;

		}

		function parseColorGroupNode( colorGroupNode ) {

			var colorGroupData = {
				id: colorGroupNode.getAttribute( 'id' ), // required
				displaypropertiesid: colorGroupNode.getAttribute( 'displaypropertiesid' )
			};

			var colorNodes = colorGroupNode.querySelectorAll( 'color' );

			var colors = [];
			var colorObject = new Color();

			for ( var i = 0; i < colorNodes.length; i ++ ) {

				var colorNode = colorNodes[ i ];
				var color = colorNode.getAttribute( 'color' );

				colorObject.setStyle( color.substring( 0, 7 ) );
				colorObject.convertSRGBToLinear(); // color is in sRGB

				colors.push( colorObject.r, colorObject.g, colorObject.b );

			}

			colorGroupData[ 'colors' ] = new Float32Array( colors );

			return colorGroupData;

		}

		function parseMetallicDisplaypropertiesNode( metallicDisplaypropetiesNode ) {

			var metallicDisplaypropertiesData = {
				id: metallicDisplaypropetiesNode.getAttribute( 'id' ) // required
			};

			var metallicNodes = metallicDisplaypropetiesNode.querySelectorAll( 'pbmetallic' );

			var metallicData = [];

			for ( var i = 0; i < metallicNodes.length; i ++ ) {

				var metallicNode = metallicNodes[ i ];

				metallicData.push( {
					name: metallicNode.getAttribute( 'name' ), // required
					metallicness: parseFloat( metallicNode.getAttribute( 'metallicness' ) ), // required
					roughness: parseFloat( metallicNode.getAttribute( 'roughness' ) ) // required
				} );

			}

			metallicDisplaypropertiesData.data = metallicData;

			return metallicDisplaypropertiesData;

		}

		function parseBasematerialNode( basematerialNode ) {

			var basematerialData = {};

			basematerialData[ 'name' ] = basematerialNode.getAttribute( 'name' ); // required
			basematerialData[ 'displaycolor' ] = basematerialNode.getAttribute( 'displaycolor' ); // required
			basematerialData[ 'displaypropertiesid' ] = basematerialNode.getAttribute( 'displaypropertiesid' );

			return basematerialData;

		}

		function parseMeshNode( meshNode ) {

			var meshData = {};

			var vertices = [];
			var vertexNodes = meshNode.querySelectorAll( 'vertices vertex' );

			for ( var i = 0; i < vertexNodes.length; i ++ ) {

				var vertexNode = vertexNodes[ i ];
				var x = vertexNode.getAttribute( 'x' );
				var y = vertexNode.getAttribute( 'y' );
				var z = vertexNode.getAttribute( 'z' );

				vertices.push( parseFloat( x ), parseFloat( y ), parseFloat( z ) );

			}

			meshData[ 'vertices' ] = new Float32Array( vertices );

			var triangleProperties = [];
			var triangles = [];
			var triangleNodes = meshNode.querySelectorAll( 'triangles triangle' );

			for ( var i = 0; i < triangleNodes.length; i ++ ) {

				var triangleNode = triangleNodes[ i ];
				var v1 = triangleNode.getAttribute( 'v1' );
				var v2 = triangleNode.getAttribute( 'v2' );
				var v3 = triangleNode.getAttribute( 'v3' );
				var p1 = triangleNode.getAttribute( 'p1' );
				var p2 = triangleNode.getAttribute( 'p2' );
				var p3 = triangleNode.getAttribute( 'p3' );
				var pid = triangleNode.getAttribute( 'pid' );

				var triangleProperty = {};

				triangleProperty[ 'v1' ] = parseInt( v1, 10 );
				triangleProperty[ 'v2' ] = parseInt( v2, 10 );
				triangleProperty[ 'v3' ] = parseInt( v3, 10 );

				triangles.push( triangleProperty[ 'v1' ], triangleProperty[ 'v2' ], triangleProperty[ 'v3' ] );

				// optional

				if ( p1 ) {

					triangleProperty[ 'p1' ] = parseInt( p1, 10 );

				}

				if ( p2 ) {

					triangleProperty[ 'p2' ] = parseInt( p2, 10 );

				}

				if ( p3 ) {

					triangleProperty[ 'p3' ] = parseInt( p3, 10 );

				}

				if ( pid ) {

					triangleProperty[ 'pid' ] = pid;

				}

				if ( 0 < Object.keys( triangleProperty ).length ) {

					triangleProperties.push( triangleProperty );

				}

			}

			meshData[ 'triangleProperties' ] = triangleProperties;
			meshData[ 'triangles' ] = new Uint32Array( triangles );

			return meshData;

		}

		function parseComponentsNode( componentsNode ) {

			var components = [];

			var componentNodes = componentsNode.querySelectorAll( 'component' );

			for ( var i = 0; i < componentNodes.length; i ++ ) {

				var componentNode = componentNodes[ i ];
				var componentData = parseComponentNode( componentNode );
				components.push( componentData );

			}

			return components;

		}

		function parseComponentNode( componentNode ) {

			var componentData = {};

			componentData[ 'objectId' ] = componentNode.getAttribute( 'objectid' ); // required

			var transform = componentNode.getAttribute( 'transform' );

			if ( transform ) {

				componentData[ 'transform' ] = parseTransform( transform );

			}

			return componentData;

		}

		function parseTransform( transform ) {

			var t = [];
			transform.split( ' ' ).forEach( function ( s ) {

				t.push( parseFloat( s ) );

			} );

			var matrix = new Matrix4();
			matrix.set(
				t[ 0 ], t[ 3 ], t[ 6 ], t[ 9 ],
				t[ 1 ], t[ 4 ], t[ 7 ], t[ 10 ],
				t[ 2 ], t[ 5 ], t[ 8 ], t[ 11 ],
				 0.0, 0.0, 0.0, 1.0
			);

			return matrix;

		}

		function parseObjectNode( objectNode ) {

			var objectData = {
				type: objectNode.getAttribute( 'type' )
			};

			var id = objectNode.getAttribute( 'id' );

			if ( id ) {

				objectData[ 'id' ] = id;

			}

			var pid = objectNode.getAttribute( 'pid' );

			if ( pid ) {

				objectData[ 'pid' ] = pid;

			}

			var pindex = objectNode.getAttribute( 'pindex' );

			if ( pindex ) {

				objectData[ 'pindex' ] = pindex;

			}

			var thumbnail = objectNode.getAttribute( 'thumbnail' );

			if ( thumbnail ) {

				objectData[ 'thumbnail' ] = thumbnail;

			}

			var partnumber = objectNode.getAttribute( 'partnumber' );

			if ( partnumber ) {

				objectData[ 'partnumber' ] = partnumber;

			}

			var name = objectNode.getAttribute( 'name' );

			if ( name ) {

				objectData[ 'name' ] = name;

			}

			var meshNode = objectNode.querySelector( 'mesh' );

			if ( meshNode ) {

				objectData[ 'mesh' ] = parseMeshNode( meshNode );

			}

			var componentsNode = objectNode.querySelector( 'components' );

			if ( componentsNode ) {

				objectData[ 'components' ] = parseComponentsNode( componentsNode );

			}

			return objectData;

		}

		function parseResourcesNode( resourcesNode ) {

			var resourcesData = {};

			resourcesData[ 'basematerials' ] = {};
			var basematerialsNodes = resourcesNode.querySelectorAll( 'basematerials' );

			for ( var i = 0; i < basematerialsNodes.length; i ++ ) {

				var basematerialsNode = basematerialsNodes[ i ];
				var basematerialsData = parseBasematerialsNode( basematerialsNode );
				resourcesData[ 'basematerials' ][ basematerialsData[ 'id' ] ] = basematerialsData;

			}

			//

			resourcesData[ 'texture2d' ] = {};
			var textures2DNodes = resourcesNode.querySelectorAll( 'texture2d' );

			for ( var i = 0; i < textures2DNodes.length; i ++ ) {

				var textures2DNode = textures2DNodes[ i ];
				var texture2DData = parseTexture2DNode( textures2DNode );
				resourcesData[ 'texture2d' ][ texture2DData[ 'id' ] ] = texture2DData;

			}

			//

			resourcesData[ 'colorgroup' ] = {};
			var colorGroupNodes = resourcesNode.querySelectorAll( 'colorgroup' );

			for ( var i = 0; i < colorGroupNodes.length; i ++ ) {

				var colorGroupNode = colorGroupNodes[ i ];
				var colorGroupData = parseColorGroupNode( colorGroupNode );
				resourcesData[ 'colorgroup' ][ colorGroupData[ 'id' ] ] = colorGroupData;

			}

			//

			resourcesData[ 'pbmetallicdisplayproperties' ] = {};
			var pbmetallicdisplaypropertiesNodes = resourcesNode.querySelectorAll( 'pbmetallicdisplayproperties' );

			for ( var i = 0; i < pbmetallicdisplaypropertiesNodes.length; i ++ ) {

				var pbmetallicdisplaypropertiesNode = pbmetallicdisplaypropertiesNodes[ i ];
				var pbmetallicdisplaypropertiesData = parseMetallicDisplaypropertiesNode( pbmetallicdisplaypropertiesNode );
				resourcesData[ 'pbmetallicdisplayproperties' ][ pbmetallicdisplaypropertiesData[ 'id' ] ] = pbmetallicdisplaypropertiesData;

			}

			//

			resourcesData[ 'texture2dgroup' ] = {};
			var textures2DGroupNodes = resourcesNode.querySelectorAll( 'texture2dgroup' );

			for ( var i = 0; i < textures2DGroupNodes.length; i ++ ) {

				var textures2DGroupNode = textures2DGroupNodes[ i ];
				var textures2DGroupData = parseTextures2DGroupNode( textures2DGroupNode );
				resourcesData[ 'texture2dgroup' ][ textures2DGroupData[ 'id' ] ] = textures2DGroupData;

			}

			//

			resourcesData[ 'object' ] = {};
			var objectNodes = resourcesNode.querySelectorAll( 'object' );

			for ( var i = 0; i < objectNodes.length; i ++ ) {

				var objectNode = objectNodes[ i ];
				var objectData = parseObjectNode( objectNode );
				resourcesData[ 'object' ][ objectData[ 'id' ] ] = objectData;

			}

			return resourcesData;

		}

		function parseBuildNode( buildNode ) {

			var buildData = [];
			var itemNodes = buildNode.querySelectorAll( 'item' );

			for ( var i = 0; i < itemNodes.length; i ++ ) {

				var itemNode = itemNodes[ i ];
				var buildItem = {
					objectId: itemNode.getAttribute( 'objectid' )
				};
				var transform = itemNode.getAttribute( 'transform' );

				if ( transform ) {

					buildItem[ 'transform' ] = parseTransform( transform );

				}

				buildData.push( buildItem );

			}

			return buildData;

		}

		function parseModelNode( modelNode ) {

			var modelData = { unit: modelNode.getAttribute( 'unit' ) || 'millimeter' };
			var metadataNodes = modelNode.querySelectorAll( 'metadata' );

			if ( metadataNodes ) {

				modelData[ 'metadata' ] = parseMetadataNodes( metadataNodes );

			}

			var resourcesNode = modelNode.querySelector( 'resources' );

			if ( resourcesNode ) {

				modelData[ 'resources' ] = parseResourcesNode( resourcesNode );

			}

			var buildNode = modelNode.querySelector( 'build' );

			if ( buildNode ) {

				modelData[ 'build' ] = parseBuildNode( buildNode );

			}

			return modelData;

		}

		function buildTexture( texture2dgroup, objects, modelData, textureData ) {

			var texid = texture2dgroup.texid;
			var texture2ds = modelData.resources.texture2d;
			var texture2d = texture2ds[ texid ];

			if ( texture2d ) {

				var data = textureData[ texture2d.path ];
				var type = texture2d.contenttype;

				var blob = new Blob( [ data ], { type: type } );
				var sourceURI = URL.createObjectURL( blob );

				var texture = textureLoader.load( sourceURI, function () {

					URL.revokeObjectURL( sourceURI );

				} );

				texture.encoding = sRGBEncoding;

				// texture parameters

				switch ( texture2d.tilestyleu ) {

					case 'wrap':
						texture.wrapS = RepeatWrapping;
						break;

					case 'mirror':
						texture.wrapS = MirroredRepeatWrapping;
						break;

					case 'none':
					case 'clamp':
						texture.wrapS = ClampToEdgeWrapping;
						break;

					default:
						texture.wrapS = RepeatWrapping;

				}

				switch ( texture2d.tilestylev ) {

					case 'wrap':
						texture.wrapT = RepeatWrapping;
						break;

					case 'mirror':
						texture.wrapT = MirroredRepeatWrapping;
						break;

					case 'none':
					case 'clamp':
						texture.wrapT = ClampToEdgeWrapping;
						break;

					default:
						texture.wrapT = RepeatWrapping;

				}

				switch ( texture2d.filter ) {

					case 'auto':
						texture.magFilter = LinearFilter;
						texture.minFilter = LinearMipmapLinearFilter;
						break;

					case 'linear':
						texture.magFilter = LinearFilter;
						texture.minFilter = LinearFilter;
						break;

					case 'nearest':
						texture.magFilter = NearestFilter;
						texture.minFilter = NearestFilter;
						break;

					default:
						texture.magFilter = LinearFilter;
						texture.minFilter = LinearMipmapLinearFilter;

				}

				return texture;

			} else {

				return null;

			}

		}

		function buildBasematerialsMeshes( basematerials, triangleProperties, modelData, meshData, textureData, objectData ) {

			var objectPindex = objectData.pindex;

			var materialMap = {};

			for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) {

				var triangleProperty = triangleProperties[ i ];
				var pindex = ( triangleProperty.p1 !== undefined ) ? triangleProperty.p1 : objectPindex;

				if ( materialMap[ pindex ] === undefined ) materialMap[ pindex ] = [];

				materialMap[ pindex ].push( triangleProperty );

			}

			//

			var keys = Object.keys( materialMap );
			var meshes = [];

			for ( var i = 0, l = keys.length; i < l; i ++ ) {

				var materialIndex = keys[ i ];
				var trianglePropertiesProps = materialMap[ materialIndex ];
				var basematerialData = basematerials.basematerials[ materialIndex ];
				var material = getBuild( basematerialData, objects, modelData, textureData, objectData, buildBasematerial );

				//

				var geometry = new BufferGeometry();

				var positionData = [];

				var vertices = meshData.vertices;

				for ( var j = 0, jl = trianglePropertiesProps.length; j < jl; j ++ ) {

					var triangleProperty = trianglePropertiesProps[ j ];

					positionData.push( vertices[ ( triangleProperty.v1 * 3 ) + 0 ] );
					positionData.push( vertices[ ( triangleProperty.v1 * 3 ) + 1 ] );
					positionData.push( vertices[ ( triangleProperty.v1 * 3 ) + 2 ] );

					positionData.push( vertices[ ( triangleProperty.v2 * 3 ) + 0 ] );
					positionData.push( vertices[ ( triangleProperty.v2 * 3 ) + 1 ] );
					positionData.push( vertices[ ( triangleProperty.v2 * 3 ) + 2 ] );

					positionData.push( vertices[ ( triangleProperty.v3 * 3 ) + 0 ] );
					positionData.push( vertices[ ( triangleProperty.v3 * 3 ) + 1 ] );
					positionData.push( vertices[ ( triangleProperty.v3 * 3 ) + 2 ] );


				}

				geometry.setAttribute( 'position', new Float32BufferAttribute( positionData, 3 ) );

				//

				var mesh = new Mesh( geometry, material );
				meshes.push( mesh );

			}

			return meshes;

		}

		function buildTexturedMesh( texture2dgroup, triangleProperties, modelData, meshData, textureData, objectData ) {

			// geometry

			var geometry = new BufferGeometry();

			var positionData = [];
			var uvData = [];

			var vertices = meshData.vertices;
			var uvs = texture2dgroup.uvs;

			for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) {

				var triangleProperty = triangleProperties[ i ];

				positionData.push( vertices[ ( triangleProperty.v1 * 3 ) + 0 ] );
				positionData.push( vertices[ ( triangleProperty.v1 * 3 ) + 1 ] );
				positionData.push( vertices[ ( triangleProperty.v1 * 3 ) + 2 ] );

				positionData.push( vertices[ ( triangleProperty.v2 * 3 ) + 0 ] );
				positionData.push( vertices[ ( triangleProperty.v2 * 3 ) + 1 ] );
				positionData.push( vertices[ ( triangleProperty.v2 * 3 ) + 2 ] );

				positionData.push( vertices[ ( triangleProperty.v3 * 3 ) + 0 ] );
				positionData.push( vertices[ ( triangleProperty.v3 * 3 ) + 1 ] );
				positionData.push( vertices[ ( triangleProperty.v3 * 3 ) + 2 ] );

				//

				uvData.push( uvs[ ( triangleProperty.p1 * 2 ) + 0 ] );
				uvData.push( uvs[ ( triangleProperty.p1 * 2 ) + 1 ] );

				uvData.push( uvs[ ( triangleProperty.p2 * 2 ) + 0 ] );
				uvData.push( uvs[ ( triangleProperty.p2 * 2 ) + 1 ] );

				uvData.push( uvs[ ( triangleProperty.p3 * 2 ) + 0 ] );
				uvData.push( uvs[ ( triangleProperty.p3 * 2 ) + 1 ] );

			}

			geometry.setAttribute( 'position', new Float32BufferAttribute( positionData, 3 ) );
			geometry.setAttribute( 'uv', new Float32BufferAttribute( uvData, 2 ) );

			// material

			var texture = getBuild( texture2dgroup, objects, modelData, textureData, objectData, buildTexture );

			var material = new MeshPhongMaterial( { map: texture, flatShading: true } );

			// mesh

			var mesh = new Mesh( geometry, material );

			return mesh;

		}

		function buildVertexColorMesh( colorgroup, triangleProperties, modelData, meshData ) {

			// geometry

			var geometry = new BufferGeometry();

			var positionData = [];
			var colorData = [];

			var vertices = meshData.vertices;
			var colors = colorgroup.colors;

			for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) {

				var triangleProperty = triangleProperties[ i ];

				var v1 = triangleProperty.v1;
				var v2 = triangleProperty.v2;
				var v3 = triangleProperty.v3;

				positionData.push( vertices[ ( v1 * 3 ) + 0 ] );
				positionData.push( vertices[ ( v1 * 3 ) + 1 ] );
				positionData.push( vertices[ ( v1 * 3 ) + 2 ] );

				positionData.push( vertices[ ( v2 * 3 ) + 0 ] );
				positionData.push( vertices[ ( v2 * 3 ) + 1 ] );
				positionData.push( vertices[ ( v2 * 3 ) + 2 ] );

				positionData.push( vertices[ ( v3 * 3 ) + 0 ] );
				positionData.push( vertices[ ( v3 * 3 ) + 1 ] );
				positionData.push( vertices[ ( v3 * 3 ) + 2 ] );

				//

				var p1 = triangleProperty.p1;
				var p2 = triangleProperty.p2;
				var p3 = triangleProperty.p3;

				colorData.push( colors[ ( p1 * 3 ) + 0 ] );
				colorData.push( colors[ ( p1 * 3 ) + 1 ] );
				colorData.push( colors[ ( p1 * 3 ) + 2 ] );

				colorData.push( colors[ ( ( p2 || p1 ) * 3 ) + 0 ] );
				colorData.push( colors[ ( ( p2 || p1 ) * 3 ) + 1 ] );
				colorData.push( colors[ ( ( p2 || p1 ) * 3 ) + 2 ] );

				colorData.push( colors[ ( ( p3 || p1 ) * 3 ) + 0 ] );
				colorData.push( colors[ ( ( p3 || p1 ) * 3 ) + 1 ] );
				colorData.push( colors[ ( ( p3 || p1 ) * 3 ) + 2 ] );

			}

			geometry.setAttribute( 'position', new Float32BufferAttribute( positionData, 3 ) );
			geometry.setAttribute( 'color', new Float32BufferAttribute( colorData, 3 ) );

			// material

			var material = new MeshPhongMaterial( { vertexColors: true, flatShading: true } );

			// mesh

			var mesh = new Mesh( geometry, material );

			return mesh;

		}

		function buildDefaultMesh( meshData ) {

			var geometry = new BufferGeometry();
			geometry.setIndex( new BufferAttribute( meshData[ 'triangles' ], 1 ) );
			geometry.setAttribute( 'position', new BufferAttribute( meshData[ 'vertices' ], 3 ) );

			var material = new MeshPhongMaterial( { color: 0xaaaaff, flatShading: true } );

			var mesh = new Mesh( geometry, material );

			return mesh;

		}

		function buildMeshes( resourceMap, modelData, meshData, textureData, objectData ) {

			var keys = Object.keys( resourceMap );
			var meshes = [];

			for ( var i = 0, il = keys.length; i < il; i ++ ) {

				var resourceId = keys[ i ];
				var triangleProperties = resourceMap[ resourceId ];
				var resourceType = getResourceType( resourceId, modelData );

				switch ( resourceType ) {

					case 'material':
						var basematerials = modelData.resources.basematerials[ resourceId ];
						var newMeshes = buildBasematerialsMeshes( basematerials, triangleProperties, modelData, meshData, textureData, objectData );

						for ( var j = 0, jl = newMeshes.length; j < jl; j ++ ) {

							meshes.push( newMeshes[ j ] );

						}

						break;

					case 'texture':
						var texture2dgroup = modelData.resources.texture2dgroup[ resourceId ];
						meshes.push( buildTexturedMesh( texture2dgroup, triangleProperties, modelData, meshData, textureData, objectData ) );
						break;

					case 'vertexColors':
						var colorgroup = modelData.resources.colorgroup[ resourceId ];
						meshes.push( buildVertexColorMesh( colorgroup, triangleProperties, modelData, meshData ) );
						break;

					case 'default':
						meshes.push( buildDefaultMesh( meshData ) );
						break;

					default:
						console.error( 'THREE.3MFLoader: Unsupported resource type.' );

				}

			}

			return meshes;

		}

		function getResourceType( pid, modelData ) {

			if ( modelData.resources.texture2dgroup[ pid ] !== undefined ) {

				return 'texture';

			} else if ( modelData.resources.basematerials[ pid ] !== undefined ) {

				return 'material';

			} else if ( modelData.resources.colorgroup[ pid ] !== undefined ) {

				return 'vertexColors';

			} else if ( pid === 'default' ) {

				return 'default';

			} else {

				return undefined;

			}

		}

		function analyzeObject( modelData, meshData, objectData ) {

			var resourceMap = {};

			var triangleProperties = meshData[ 'triangleProperties' ];

			var objectPid = objectData.pid;

			for ( var i = 0, l = triangleProperties.length; i < l; i ++ ) {

				var triangleProperty = triangleProperties[ i ];
				var pid = ( triangleProperty.pid !== undefined ) ? triangleProperty.pid : objectPid;

				if ( pid === undefined ) pid = 'default';

				if ( resourceMap[ pid ] === undefined ) resourceMap[ pid ] = [];

				resourceMap[ pid ].push( triangleProperty );

			}

			return resourceMap;

		}

		function buildGroup( meshData, objects, modelData, textureData, objectData ) {

			var group = new Group();

			var resourceMap = analyzeObject( modelData, meshData, objectData );
			var meshes = buildMeshes( resourceMap, modelData, meshData, textureData, objectData );

			for ( var i = 0, l = meshes.length; i < l; i ++ ) {

				group.add( meshes[ i ] );

			}

			return group;

		}

		function applyExtensions( extensions, meshData, modelXml ) {

			if ( ! extensions ) {

				return;

			}

			var availableExtensions = [];
			var keys = Object.keys( extensions );

			for ( var i = 0; i < keys.length; i ++ ) {

				var ns = keys[ i ];

				for ( var j = 0; j < scope.availableExtensions.length; j ++ ) {

					var extension = scope.availableExtensions[ j ];

					if ( extension.ns === ns ) {

						availableExtensions.push( extension );

					}

				}

			}

			for ( var i = 0; i < availableExtensions.length; i ++ ) {

				var extension = availableExtensions[ i ];
				extension.apply( modelXml, extensions[ extension[ 'ns' ] ], meshData );

			}

		}

		function getBuild( data, objects, modelData, textureData, objectData, builder ) {

			if ( data.build !== undefined ) return data.build;

			data.build = builder( data, objects, modelData, textureData, objectData );

			return data.build;

		}

		function buildBasematerial( materialData, objects, modelData ) {

			var material;

			var displaypropertiesid = materialData.displaypropertiesid;
			var pbmetallicdisplayproperties = modelData.resources.pbmetallicdisplayproperties;

			if ( displaypropertiesid !== null && pbmetallicdisplayproperties[ displaypropertiesid ] !== undefined ) {

				// metallic display property, use StandardMaterial

				var pbmetallicdisplayproperty = pbmetallicdisplayproperties[ displaypropertiesid ];
				var metallicData = pbmetallicdisplayproperty.data[ materialData.index ];

				material = new MeshStandardMaterial( { flatShading: true, roughness: metallicData.roughness, metalness: metallicData.metallicness } );

			} else {

				// otherwise use PhongMaterial

				material = new MeshPhongMaterial( { flatShading: true } );

			}

			material.name = materialData.name;

			// displaycolor MUST be specified with a value of a 6 or 8 digit hexadecimal number, e.g. "#RRGGBB" or "#RRGGBBAA"

			var displaycolor = materialData.displaycolor;

			var color = displaycolor.substring( 0, 7 );
			material.color.setStyle( color );
			material.color.convertSRGBToLinear(); // displaycolor is in sRGB

			// process alpha if set

			if ( displaycolor.length === 9 ) {

				material.opacity = parseInt( displaycolor.charAt( 7 ) + displaycolor.charAt( 8 ), 16 ) / 255;

			}

			return material;

		}

		function buildComposite( compositeData, objects, modelData, textureData ) {

			var composite = new Group();

			for ( var j = 0; j < compositeData.length; j ++ ) {

				var component = compositeData[ j ];
				var build = objects[ component.objectId ];

				if ( build === undefined ) {

					buildObject( component.objectId, objects, modelData, textureData );
					build = objects[ component.objectId ];

				}

				var object3D = build.clone();

				// apply component transform

				var transform = component.transform;

				if ( transform ) {

					object3D.applyMatrix4( transform );

				}

				composite.add( object3D );

			}

			return composite;

		}

		function buildObject( objectId, objects, modelData, textureData ) {

			var objectData = modelData[ 'resources' ][ 'object' ][ objectId ];

			if ( objectData[ 'mesh' ] ) {

				var meshData = objectData[ 'mesh' ];

				var extensions = modelData[ 'extensions' ];
				var modelXml = modelData[ 'xml' ];

				applyExtensions( extensions, meshData, modelXml );

				objects[ objectData.id ] = getBuild( meshData, objects, modelData, textureData, objectData, buildGroup );

			} else {

				var compositeData = objectData[ 'components' ];

				objects[ objectData.id ] = getBuild( compositeData, objects, modelData, textureData, objectData, buildComposite );

			}

		}

		function buildObjects( data3mf ) {

			var modelsData = data3mf.model;
			var modelRels = data3mf.modelRels;
			var objects = {};
			var modelsKeys = Object.keys( modelsData );
			var textureData = {};

			// evaluate model relationships to textures

			if ( modelRels ) {

				for ( var i = 0, l = modelRels.length; i < l; i ++ ) {

					var modelRel = modelRels[ i ];
					var textureKey = modelRel.target.substring( 1 );

					if ( data3mf.texture[ textureKey ] ) {

						textureData[ modelRel.target ] = data3mf.texture[ textureKey ];

					}

				}

			}

			// start build

			for ( var i = 0; i < modelsKeys.length; i ++ ) {

				var modelsKey = modelsKeys[ i ];
				var modelData = modelsData[ modelsKey ];

				var objectIds = Object.keys( modelData[ 'resources' ][ 'object' ] );

				for ( var j = 0; j < objectIds.length; j ++ ) {

					var objectId = objectIds[ j ];

					buildObject( objectId, objects, modelData, textureData );

				}

			}

			return objects;

		}

		function build( objects, data3mf ) {

			var group = new Group();

			var relationship = data3mf[ 'rels' ][ 0 ];
			var buildData = data3mf.model[ relationship[ 'target' ].substring( 1 ) ][ 'build' ];

			for ( var i = 0; i < buildData.length; i ++ ) {

				var buildItem = buildData[ i ];
				var object3D = objects[ buildItem[ 'objectId' ] ];

				// apply transform

				var transform = buildItem[ 'transform' ];

				if ( transform ) {

					object3D.applyMatrix4( transform );

				}

				group.add( object3D );

			}

			return group;

		}

		var data3mf = loadDocument( data );
		var objects = buildObjects( data3mf );

		return build( objects, data3mf );

	},

	addExtension: function ( extension ) {

		this.availableExtensions.push( extension );

	}

} );
Example #29
Source File: SSRrPass.js    From Computer-Graphics with MIT License 4 votes vote down vote up
constructor( { renderer, scene, camera, width, height, selects } ) {

		super();

		this.width = ( width !== undefined ) ? width : 512;
		this.height = ( height !== undefined ) ? height : 512;

		this.clear = true;

		this.renderer = renderer;
		this.scene = scene;
		this.camera = camera;

		this.output = 0;
		// this.output = 1;

		this.ior = SSRrShader.uniforms.ior.value;
		this.maxDistance = SSRrShader.uniforms.maxDistance.value;
		this.surfDist = SSRrShader.uniforms.surfDist.value;

		this.tempColor = new Color();

		this.selects = selects;

		this._specular = SSRrShader.defines.SPECULAR;
		Object.defineProperty( this, 'specular', {
			get() {

				return this._specular;

			},
			set( val ) {

				if ( this._specular === val ) return;
				this._specular = val;
				this.ssrrMaterial.defines.SPECULAR = val;
				this.ssrrMaterial.needsUpdate = true;

			}
		} );

		this._fillHole = SSRrShader.defines.FILL_HOLE;
		Object.defineProperty( this, 'fillHole', {
			get() {

				return this._fillHole;

			},
			set( val ) {

				if ( this._fillHole === val ) return;
				this._fillHole = val;
				this.ssrrMaterial.defines.FILL_HOLE = val;
				this.ssrrMaterial.needsUpdate = true;

			}
		} );

		this._infiniteThick = SSRrShader.defines.INFINITE_THICK;
		Object.defineProperty( this, 'infiniteThick', {
			get() {

				return this._infiniteThick;

			},
			set( val ) {

				if ( this._infiniteThick === val ) return;
				this._infiniteThick = val;
				this.ssrrMaterial.defines.INFINITE_THICK = val;
				this.ssrrMaterial.needsUpdate = true;

			}
		} );

		// beauty render target with depth buffer

		const depthTexture = new DepthTexture();
		depthTexture.type = UnsignedShortType;
		depthTexture.minFilter = NearestFilter;
		depthTexture.magFilter = NearestFilter;

		this.beautyRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat,
			depthTexture: depthTexture,
			depthBuffer: true
		} );

		this.specularRenderTarget = new WebGLRenderTarget( this.width, this.height, { // TODO: Can merge with refractiveRenderTarget?
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat,
		} );

		// normalSelects render target

		const depthTextureSelects = new DepthTexture();
		depthTextureSelects.type = UnsignedShortType;
		depthTextureSelects.minFilter = NearestFilter;
		depthTextureSelects.magFilter = NearestFilter;

		this.normalSelectsRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat,
			type: HalfFloatType,
			depthTexture: depthTextureSelects,
			depthBuffer: true
		} );

		// refractive render target

		this.refractiveRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat
		} );

		// ssrr render target

		this.ssrrRenderTarget = new WebGLRenderTarget( this.width, this.height, {
			minFilter: NearestFilter,
			magFilter: NearestFilter,
			format: RGBAFormat
		} );

		// ssrr material

		if ( SSRrShader === undefined ) {

			console.error( 'THREE.SSRrPass: The pass relies on SSRrShader.' );

		}

		this.ssrrMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSRrShader.defines, {
				MAX_STEP: Math.sqrt( this.width * this.width + this.height * this.height )
			} ),
			uniforms: UniformsUtils.clone( SSRrShader.uniforms ),
			vertexShader: SSRrShader.vertexShader,
			fragmentShader: SSRrShader.fragmentShader,
			blending: NoBlending
		} );

		this.ssrrMaterial.uniforms[ 'tDiffuse' ].value = this.beautyRenderTarget.texture;
		this.ssrrMaterial.uniforms[ 'tSpecular' ].value = this.specularRenderTarget.texture;
		this.ssrrMaterial.uniforms[ 'tNormalSelects' ].value = this.normalSelectsRenderTarget.texture;
		this.ssrrMaterial.needsUpdate = true;
		this.ssrrMaterial.uniforms[ 'tRefractive' ].value = this.refractiveRenderTarget.texture;
		this.ssrrMaterial.uniforms[ 'tDepth' ].value = this.beautyRenderTarget.depthTexture;
		this.ssrrMaterial.uniforms[ 'tDepthSelects' ].value = this.normalSelectsRenderTarget.depthTexture;
		this.ssrrMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
		this.ssrrMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
		this.ssrrMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
		this.ssrrMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
		this.ssrrMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );

		// normal material

		this.normalMaterial = new MeshNormalMaterial();
		this.normalMaterial.blending = NoBlending;

		// refractiveOn material

		this.refractiveOnMaterial = new MeshBasicMaterial( {
			color: 'white'
		} );

		// refractiveOff material

		this.refractiveOffMaterial = new MeshBasicMaterial( {
			color: 'black'
		} );

		// specular material
		this.specularMaterial = new MeshStandardMaterial( {
			color: 'black',
			metalness: 0,
			roughness: .2,
		} );

		// material for rendering the depth

		this.depthRenderMaterial = new ShaderMaterial( {
			defines: Object.assign( {}, SSRrDepthShader.defines ),
			uniforms: UniformsUtils.clone( SSRrDepthShader.uniforms ),
			vertexShader: SSRrDepthShader.vertexShader,
			fragmentShader: SSRrDepthShader.fragmentShader,
			blending: NoBlending
		} );
		this.depthRenderMaterial.uniforms[ 'tDepth' ].value = this.beautyRenderTarget.depthTexture;
		this.depthRenderMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
		this.depthRenderMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;

		// material for rendering the content of a render target

		this.copyMaterial = new ShaderMaterial( {
			uniforms: UniformsUtils.clone( CopyShader.uniforms ),
			vertexShader: CopyShader.vertexShader,
			fragmentShader: CopyShader.fragmentShader,
			transparent: true,
			depthTest: false,
			depthWrite: false,
			blendSrc: SrcAlphaFactor,
			blendDst: OneMinusSrcAlphaFactor,
			blendEquation: AddEquation,
			blendSrcAlpha: SrcAlphaFactor,
			blendDstAlpha: OneMinusSrcAlphaFactor,
			blendEquationAlpha: AddEquation,
			// premultipliedAlpha:true,
		} );

		this.fsQuad = new FullScreenQuad( null );

		this.originalClearColor = new Color();

	}