Three.js

Three.js

Примеры

Контролы

      OrbitControls

Орбитальный контрол (элемент управления) позволяет камере вращаться вокруг цели.
Для его использования, как и всех файлов в директории /examples, нужно будет отдельно включить этот файл в HTML-код.

Пример

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
var controls = new THREE.OrbitControls( camera );
// controls.update() must be called after any manual changes to the camera's transform // после любых ручных изменений состояния камеры должен быть вызван controls.update() camera.position.set( 0, 20, 100 ); controls.update();
function animate() {
requestAnimationFrame( animate );
// required if controls.enableDamping or controls.autoRotate are set to true // если controls.enableDamping или controls.autoRotate установлен как true, необходимо controls.update();
renderer.render( scene, camera );
}
Другие примеры:
misc / controls / orbit

Конструктор

OrbitControls( 
object - объект')" onmouseout="hide()">object
, domElement )

object - объект')" onmouseout="hide()">object
- камера, которой нужно управлять (обязательный аргумент).
domElement - элемент HTML, используемый для прослушивателей (приемников) событий (дополнительный, необязательный аргумент). По умолчанию это весь документ целиком, однако, если нужно чтобы элементы управления (контролы) работали от какого-либо определенного элемента (например, <canvas> - холст), укажите его в этом аргументе.
Статья о DOM в Википедии.

Свойства


.autoRotate
Для автоматического вращения вокруг цели установите значение данного свойства как true.
Обратите внимание, если это свойство включено, в цикле анимации нужно вызывать метод update.

.autoRotateSpeed
Свойство определяет скорость вращения камеры вокруг цели, если свойство autoRotate установлено как true. Значение по умолчанию равно 2.0, что равно 30 секундам на один оборот при 60 кадрах в секунду.
Обратите внимание, если свойство autoRotate включено, в цикле анимации нужно вызывать метод update.

.dampingFactor
The damping inertia used if .enableDamping is set to true.
Обратите внимание, для работы этого свойства в цикле анимации нужно вызывать метод update.

.domElement
The HTMLDOMElement used to listen for mouse / touch events. This must be passed in the constructor; changing it here will not set up new event listeners.
Default is the whole document.

.enabled
Whether or not the controls are enabled.

.enableDamping
Set to true to enable damping (inertia), which can be used to give a sense of weight to the controls. Default is false.
Note that if this is enabled, you must call .update () in your animation loop.

.enableKeys
Enable or disable the use of keyboard controls.

.enablePan
Enable or disable camera panning. Default is true.

.enableRotate
Enable or disable horizontal and vertical rotation of the camera. Default is true.
Note that it is possible to disable a single axis by setting the min and max of the polar angle or azimuth angle to the same value, which will cause the vertical or horizontal rotation to be fixed at that value.

.enableZoom
Enable or disable zooming (dollying) of the camera.

.keyPanSpeed
How fast to pan the camera when the keyboard is used. Default is 7.0 pixels per keypress.

.keys
This object contains references to the keycodes for controlling camera panning. Default is the 4 arrow keys.
controls.keys = {
  LEFT: 37, //left arrow
  UP: 38, // up arrow
  RIGHT: 39, // right arrow
  BOTTOM: 40 // down arrow
}
See this page for a full list of keycodes.
.maxAzimuthAngle
How far you can orbit horizontally, upper limit. Range is - Math.PI to Math.PI ( or Infinity for no limit ) and default is Infinity;
.maxDistance
How far you can dolly out ( PerspectiveCamera only ). Default is Infinity.

.maxPolarAngle
How far you can orbit vertically, upper limit. Range is 0 to Math.PI radians, and default is Math.PI.

.maxZoom
How far you can zoom out ( OrthographicCamera only ). Default is Infinity.

.minAzimuthAngle
How far you can orbit horizontally, lower limit. Range is - Math.PI to Math.PI ( or - Infinity for no limit ) and default is - Infinity;

.minDistance
How far you can dolly in ( PerspectiveCamera only ). Default is 0.
.minPolarAngle
How far you can orbit vertically, lower limit. Range is 0 to Math.PI radians, and default is 0.

.minZoom
How far you can zoom in ( OrthographicCamera only ). Default is 0.

.mouseButtons
This object contains references to the mouse buttons used for the controls.
controls.mouseButtons = {
  ORBIT: THREE.MOUSE.LEFT,
  ZOOM: THREE.MOUSE.MIDDLE,
  PAN: THREE.MOUSE.RIGHT
}
.object
The camera ( or other object ) that is being controlled.

.position0
Used internally by the .saveState and .reset methods.

.rotateSpeed
Speed of rotation. Default is 1.

.target0
Used internally by the .saveState and .reset methods.

.target
The focus point of the controls, the .object orbits around this. It can be updated manually at any point to change the focus of the controls.

.zoom0
Used internally by the .saveState and .reset methods.

.zoomSpeed
Speed of zooming / dollying. Default is 1.

Методы


.dispose( )
Remove all the event listeners.

.getAzimuthalAngle( )
Get the current horizontal rotation, in radians.

.getPolarAngle( )
Get the current vertical rotation, in radians.

.reset( )
Reset the controls to their state from either the last time the .saveState was called, or the initial state.

.saveState( )
Save the current state of the controls. This can later be recovered with .reset.

.update( )
Update the controls. Must be called after any manual changes to the camera's transform, or in the update loop if .autoRotate or .enableDamping are set.

Исходники



Геометрические элементы

BufferGeometry →

      ConvexBufferGeometry

ConvexBufferGeometry can be used to generate a convex hull for a given array of 3D points. The average time complexity for this task is considered to be O(nlog(n)).

Пример

var geometry = new THREE.ConvexBufferGeometry( points );
var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
Другие примеры:
geometry / convex

Конструктор

ConvexBufferGeometry( points )
points — массив трехмерных векторов, that the resulting convex hull will contain.

Исходники



Geometry →

      ConvexGeometry

ConvexGeometry can be used to generate a convex hull for a given array of 3D points. The average time complexity for this task is considered to be O(nlog(n)).

Пример

var geometry = new THREE.ConvexGeometry( points );
var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );

Другие примеры:
geometry / convex

Конструктор

ConvexGeometry( points )
points — Array of [page:Vector3 Vector3s that the resulting convex hull will contain.

Исходники



BufferGeometry →

      DecalGeometry

DecalGeometry can be used to create a decal mesh that serves different kinds of purposes e.g. adding unique details to models, performing dynamic visual environmental changes or covering seams.

Пример

var geometry =  new THREE.DecalGeometry( mesh, position, orientation, size );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
Другие примеры:
decals

Конструктор

DecalGeometry( mesh, position, orientation, size )
mesh — Any mesh object.
position — Position of the decal projector.
orientation — Orientation of the decal projector.
size — Size of the decal projector.

Исходники



Загрузчики

      BabylonLoader

Загрузчик для загрузки ресурсов в формате .babylon
. Файловый формат babylon используется JavaScript'овским фреймворком Babylon.js.

Пример

// instantiate a loader (создаем экземпляр загрузчика)
var loader = new THREE.BabylonLoader();
// load a Babylon resource (загружаем Babylon ресурс) loader.load( // resource URL (URL-адрес ресурса) 'models/babylon/skull.babylon', // Function when resource is loaded (функция при загрузке ресурса) function ( object ) { scene.add( object ); }, // Function called when download progresses // функция, вызываемая в процессе загрузки function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // Function called when download errors // функция, вызываемая при ошибках загрузки function ( xhr ) { console.log( 'An error happened' ); } );
Другие примеры:
webgl_loader_babylon

Конструктор

BabylonLoader( 
manager - менеджер, управляющий')" onmouseout="hide()">manager
)

manager - менеджер, управляющий')" onmouseout="hide()">manager
— The [page:LoadingManager loadingManager for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager.
Создает новый BabylonLoader.

Свойства



Методы

.load( [page:String url, [page:Function onLoad, [page:Function onProgress, [page:Function onError )

- единообразный локатор (определитель
местонахождения) ресурса.')" onmouseout="hide()">url
— строка, содержащая путь/URL-адрес babylon-файла (обязательный аргумент).
[page:function onLoad — Will be called when load completes. The argument will be the loaded [page:Object3D.
[page:function onProgress — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total and .[page:Integer loaded bytes.
[page:function onError — Will be called when load errors.
Begin loading from url and call onLoad with the parsed response content.

[method:Object3D parse( [page:Object json )

[page:Object json — The JSON structure to parse.
Parse a JSON structure and return an [page:Object3D object or a [page:Scene scene.
Found objects are converted to [page:Mesh with a [page:BufferGeometry and a default [page:MeshPhongMaterial.
Lights are parsed accordingly.

Исходники



[page:Loader →

GLTFLoader

A loader for loading glTF 2.0 resource.
glTF (GL Transmission Format) is an open format specification for efficient delivery and loading of 3D content. Assets may be provided either in JSON (.gltf) or binary (.glb) format. External files store textures (.jpg, .png, ...) and additional binary data (.bin). A glTF asset may deliver one or more scenes, including meshes, materials, textures, skins, skeletons, morph targets, animations, lights, and/or cameras.

Расширения

GLTFLoader supports the following glTF extensions:
KHR_materials_pbrSpecularGlossiness
KHR_lights (experimental)

Example

// Instantiate a loader
	var loader = new THREE.GLTFLoader();

	// Load a glTF resource
	loader.load(
		// resource URL
		'models/gltf/duck/duck.gltf',
		// called when the resource is loaded
		function ( gltf ) {

			scene.add( gltf.scene );

			gltf.animations; // Array
			gltf.scene; // THREE.Scene
			gltf.scenes; // Array
			gltf.cameras; // Array

		},
		// called when loading is in progresses
		function ( xhr ) {

			console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );

		},
		// called when loading has errors
		function ( error ) {

			console.log( 'An error happened' );

		}
	);
Другие примеры:
webgl / loader / gltf

Совместимость с браузером

GLTFLoader relies on ES6 Promises, which are not supported in IE11. To use the loader in IE11, you must include a polyfill providing a Promise replacement.

Конструктор

GLTFLoader( manager )
manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.
Создает новый GLTFLoader.

Свойства



Методы

# .load ( url, onLoad, onProgress, onError ) url — A string containing the path/URL of the .gltf or .glb file. onLoad — A function to be called after the loading is successfully completed. The function receives the loaded JSON response returned from parse. onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, that contains .total and .loaded bytes. onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument. Begin loading from url and call the callback function with the parsed response content. # .setPath ( path ) path — Base path for loading additional resources e.g. textures and .bin data. Set the base path for additional resources. # .setCrossOrigin ( value ) value — The crossOrigin string to implement CORS for loading the url from a different domain that allows CORS. # .parse ( data, path, onLoad, onError ) data — glTF asset to parse, as an ArrayBuffer or JSON string. path — The base path from which to find subsequent glTF resources such as textures and .bin data files. onLoad — A function to be called when parse completes. onError — (optional) A function to be called if an error occurs during parsing. The function receives error as an argument. Parse a glTF-based ArrayBuffer or JSON String and fire onLoad callback when complete. The argument to onLoad will be an object that contains loaded parts: .scene, .scenes, .cameras, and .animations.

Исходники



MTLLoader

A loader for loading an .mtl resource, used internaly by [page:OBJMTLLoader and [page:UTF8Loader. A loader for loading an .mtl resource, used internaly by OBJLoader and UTF8Loader. The Material Template Library format (MTL) or .MTL File Format is a companion file format to .OBJ that describes surface shading (material) properties of objects within one or more .OBJ files.

Конструктор

MTLLoader( [page:LoadingManager loadingManager )

[page:LoadingManager loadingManager — LoadingManager to use. Defaults to [page:DefaultLoadingManager DefaultLoadingManager
Creates a new [name.

Методы

[method:null load( [page:String url, [page:Function onLoad, [page:Function onProgress, [page:Function onError )

[page:String url — required
[page:Function onLoad — Will be called when load completes. The argument will be the loaded [page:MTLLoaderMaterialCreator MTLLoader.MaterialCreator instance.
[page:Function onProgress — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total and .[page:Integer loaded bytes.
[page:Function onError — Will be called when load errors.
Begin loading from url and return the loaded material.

[method:null setPath( [page:String path )

[page:String path — required
Set base path for resolving references. If set this path will be prepended to each loaded and found reference.

[method:null setTexturePath( [page:String path )

[page:String path — required
Set base path for resolving texture references. If set this path will be prepended found texture reference. If not set and setPath is, it will be used as texture base path.

[method:null setCrossOrigin( [page:boolean useCrossOrigin )

[page:boolean useCrossOrigin — required
Set to true if you need to load textures from a different origin.

[method:null setMaterialOptions( [page:Object options )

[page:Object options — required
  • side: Which side to apply the material. THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  • wrap: What type of wrapping to apply for textures. THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  • normalizeRGB: RGBs need to be normalized to 0-1 from 0-255. Default: false, assumed to be already normalized
  • ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's. Default: false
Set of options on how to construct the materials

[method:MTLLoaderMaterialCreator parse( [page:String text )

[page:String text — The textual mtl structure to parse.
Parse a mtl text structure and return a [page:MTLLoaderMaterialCreator instance.

Исходники



OBJLoader

A loader for loading an .obj resource.

Пример

				// instantiate a loader
				var loader = new THREE.OBJLoader();

				// load a resource
				loader.load(
					// resource URL
					'models/monster.obj',
					// Function when resource is loaded
					function ( object ) {
						scene.add( object );
					}
				);
    
[example:webgl_loader_obj

Конструктор

OBJLoader( [page:LoadingManager manager )

[page:LoadingManager manager — The [page:LoadingManager loadingManager for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager.
Creates a new [name.

Свойства

Методы

[method:null load( [page:String url, [page:Function onLoad, [page:Function onProgress, [page:Function onError )

[page:String url — required
[page:Function onLoad — Will be called when load completes. The argument will be the loaded [page:Object3D.
[page:Function onProgress — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total and .[page:Integer loaded bytes.
[page:Function onError — Will be called when load errors.
Begin loading from url and call onLoad with the parsed response content.

[method:Object3D parse( [page:String text )

[page:String text — The textual obj structure to parse.
Returns an [page:Object3D. It contains the parsed meshes as [page:Mesh and lines as [page:LineSegments.
All geometry is created as [page:BufferGeometry. Default materials are created as [page:MeshPhongMaterial.
If an obj object or group uses multiple materials while declaring faces geometry groups and an array of materials are used.

Исходники



OBJLoader2

A loader for loading a .obj resource.
The OBJ file format is a simple data-format that represents 3D geometry in a human redeable format as, the position of each vertex, the UV position of each texture coordinate vertex, vertex normals, and the faces that make each polygon defined as a list of vertices, and texture vertices.

Пример

		// instantiate the loader
		var loader = new THREE.OBJLoader2();

		// function called on successful load
		var intergrateIntoScene = function ( object ) {
			scene.add( object );
		};

		// load a resource from provided URL
		loader.load( 'obj/female02/female02.obj', intergrateIntoScene );
  
[example:webgl_loader_obj2

Конструктор

OBJLoader2( [page:LoadingManager manager )

[page:LoadingManager manager — The [page:LoadingManager loadingManager for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager.
Use [name to load OBJ data from files or to parse OBJ data from arraybuffer or text.

Свойства

Методы

[method:null load( [page:String url, [page:Function onLoad, [page:Function onProgress, [page:Function onError, [page:Boolean useArrayBuffer )

[page:String url — URL of the file to load
[page:Function onLoad — Called after loading was successfully completed. The argument will be the loaded [page:Object3D.
[page:Function onProgress — Called to report progress of loading. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total and .[page:Integer loaded bytes.
[page:Function onError Called after an error occurred during loading.
[page:boolean useArrayBuffer — Set this to false to force string based parsing
Use this convenient method to load an OBJ file at the given URL. Per default the fileLoader uses an arraybuffer

[method:Object3D parse( [page:ArrayBuffer arrayBuffer )

[page:ArrayBuffer arrayBuffer — OBJ data as Uint8Array
Default parse function: Parses OBJ file content stored in arrayBuffer and returns the [page:Object3D sceneGraphBaseNode.

[method:Object3D parseText( [page:String test )

[page:String text — OBJ data as string
Legacy parse function: Parses OBJ file content stored in string and returns the [page:Object3D sceneGraphBaseNode.

[method:null setMaterials ( Array of [page:Material materials )

Array of [page:Material materials — Array of [page:Material Materials from MTLLoader
Set materials loaded by MTLLoader or any other supplier of an Array of [page:Material Materials.

[method:null setPath ( [page:String path )

[page:String path — The basePath
Base path to use.

[method:null setSceneGraphBaseNode ( [page:Object3D sceneGraphBaseNode )

[page:Object3D sceneGraphBaseNode — Scenegraph object where meshes will be attached
Set the node where the loaded objects will be attached.

[method:null setDebug( [page:Boolean parserDebug, [page:Boolean meshCreatorDebug )

[page:Boolean parserDebug — Internal Parser will produce debug output
[page:Boolean meshCreatorDebug — Internal MeshCreator will produce debug output
Allows to set debug mode for the parser and the meshCreator.

Исходники



LoaderSupport

Supporting classes for file loaders and web worker based loaders.

Sub-Classes

LoaderSupport.Builder
LoaderSupport.LoadedMeshUserOverride
LoaderSupport.WorkerSupport
LoaderSupport.WorkerRunnerRefImpl
LoaderSupport.WorkerDirector
LoaderSupport.PrepData
LoaderSupport.LoaderBase
LoaderSupport.Callbacks
LoaderSupport.Validator
LoaderSupport.ConsoleLogger

Пример

webgl_loader_obj2_meshspray - Example using LoaderSupport.LoaderWorkerDirector and LoaderSupport.LoaderWorkerSupport.

Builder

Конструктор

Builder() Builds one or many Mesh from one raw set of Arraybuffers, materialGroup descriptions and further parameters. Supports vertex, vertexColor, normal, uv and index buffers.

Методы

# .setMaterials ( Array of materials ) Array of materials - Array of Materials Set materials loaded by any supplier of an Array of Materials. # .processPayload ( Object payload ) payload - Raw Mesh or Material descriptions. Delegates processing of the payload (mesh building or material update) to the corresponding functions (BW-compatibility). # .buildMeshes ( Object meshPayload ) meshPayload - Raw mesh description (buffers, params, materials) used to build one to many meshes. Builds one or multiple meshes from the data described in the payload (buffers, params, material info). # .updateMaterials ( Object materialPayload ) materialPayload - Material update instructions Updates the materials with contained material objects (sync) or from alteration instructions (async). # .getMaterialsJSON () Returns the mapping object of material name and corresponding jsonified material. # .getMaterials () Returns the mapping object of material name and corresponding material.

LoadedMeshUserOverride

Конструктор

LoadedMeshUserOverride( disregardMesh, bufferGeometry ) disregardMesh - Tell implementation to completely disregard this mesh alteredMesh - Tell implementation that mesh(es) have been altered or added Object to return by callback onMeshAlter. Used to disregard a certain mesh or to return one to many meshes.

Методы

# .addMesh ( mesh ) mesh - Mesh Add a mesh created within callback. # .isDisregardMesh () Answers if mesh shall be disregarded completely. # .providesAlteredMeshes () Answers if new mesh(es) were created.

WorkerSupport

Конструктор

WorkerSupport( logger ) logger - logger to be used This class provides means to transform existing parser code into a web worker. It defines a simple communication protocol which allows to configure the worker and receive raw mesh data during execution.

Методы

# .validate ( functionCodeBuilder, Array of libLocations, libPath, runnerImpl ) functionCodeBuilder - Function that is invoked with funcBuildObject and funcBuildSingelton that allows stringification of objects and singletons. Array of libLocations - URL of libraries that shall be added to worker code relative to libPath. libPath - Base path used for loading libraries. runnerImpl - The default worker parser wrapper implementation (communication and execution). An extended class could be passed here. Validate the status of worker code and the derived worker. # .setTerminateRequested ( terminateRequested ) terminateRequested - True or false. Request termination of worker once parser is finished. # .setCallbacks ( builder, onLoad ) builder - The builder function. Default is LoaderSupport.Builder. onLoad - The function that is called when parsing is complete. Specify functions that should be build when new raw mesh data becomes available and when the parser is finished. # .run ( payload ) payload - Raw mesh description (buffers, params, materials) used to build one to many meshes. Runs the parser with the provided configuration.

WorkerRunnerRefImpl

Конструктор

WorkerRunnerRefImpl() Default implementation of the WorkerRunner responsible for creation and configuration of the parser within the worker.

Методы

# .applyProperties ( parser, params ) parser - The parser instance params - The parameter object Applies values from parameter object via set functions or via direct assignment. # .run ( payload ) payload - Raw mesh description (buffers, params, materials) used to build one to many meshes. Configures the Parser implementation according the supplied configuration object.

WorkerDirector

Конструктор

WorkerDirector( classDef, logger ) classDef - Class definition to be used for construction logger - logger to be used Orchestrate loading of multiple OBJ files/data from an instruction queue with a configurable amount of workers (1-16). - Workflow: - prepareWorkers - enqueueForRun - processQueue - tearDown

Методы

# .prepareWorkers ( globalCallbacks, maxQueueSize, maxWebWorkers ) globalCallbacks - Register global callbacks used by all web workers maxQueueSize - Set the maximum size of the instruction queue (1-1024) maxWebWorkers - Set the maximum amount of workers (1-16) Create or destroy workers according limits. Set the name and register callbacks for dynamically created web workers. # .enqueueForRun ( runParams ) runParams Store run instructions in internal instructionQueue. # .processQueue () Process the instructionQueue until it is depleted. # .tearDown ( callbackOnFinishedProcessing ) callbackOnFinishedProcessing - Function called once all workers finished processing. Terminate all workers. # .getMaxQueueSize () Returns the maximum length of the instruction queue. # .getMaxWebWorkers () Returns the maximum number of workers. # .isRunning () Returns if any workers are running. # .setCrossOrigin ( crossOrigin ) crossOrigin - CORS value Sets the CORS string to be used.

PrepData

Конструктор

PrepData( modelName ) modelName - Overall name of the model Configuration instructions to be used by run method.

Методы

# .setStreamMeshesTo ( streamMeshesTo ) streamMeshesTo - Object already attached to scenegraph where new meshes will be attached to Set the node where the loaded objects will be attached directly. # .setMaterialPerSmoothingGroup ( materialPerSmoothingGroup ) materialPerSmoothingGroup Tells whether a material shall be created per smoothing group. # .setUseIndices ( useIndices ) useIndices - Default is false Instructs loaders to create indexed BufferGeometry. # .setDisregardNormals ( disregardNormals ) disregardNormals Tells whether normals should be completely disregarded and regenerated. # .getCallbacks () Returns all callbacks as LoaderSupport.Callbacks. # .setCrossOrigin ( crossOrigin ) crossOrigin - CORS value Sets the CORS string to be used. # .addResource ( resource ) resource Add a resource description. # .setUseAsync ( useAsync ) useAsync If true uses async loading with worker, if false loads data synchronously.

LoaderBase

Конструктор

LoaderBase( manager, logger ) manager - The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager. logger - logger to be used Base class to be used by loaders.

Методы

# .getLogger () Returns LoaderSupport.ConsoleLogger. # .setModelName ( modelName ) modelName Set the name of the model. # .setPath ( path ) path - URL The URL of the base path. # .setStreamMeshesTo ( streamMeshesTo ) streamMeshesTo - Object already attached to scenegraph where new meshes will be attached to Set the node where the loaded objects will be attached directly. # .setMaterials ( Array of materials ) Array of materials - Array of Materials Set materials loaded by MTLLoader or any other supplier of an Array of Materials. # .setUseIndices ( useIndices ) useIndices Instructs loaders to create indexed BufferGeometry. # .setDisregardNormals ( disregardNormals ) disregardNormals Tells whether normals should be completely disregarded and regenerated. # .onProgress ( type, text, numericalValue ) type - The type of event text - Textual description of the event numericalValue - Numerical value describing the progress Announce feedback which is give to the registered LoaderSupport.Callbacks.

Callbacks

Конструктор

Callbacks() Callbacks utilized by loaders and builder.

Методы

# .setCallbackOnProgress ( callbackOnProgress ) callbackOnProgress - Callback function for described functionality Register callback function that is invoked by internal function "announceProgress" to print feedback. # .setCallbackOnMeshAlter ( callbackOnMeshAlter ) callbackOnMeshAlter - Callback function for described functionality Register callback function that is called every time a mesh was loaded. Use LoadedMeshUserOverride for alteration instructions (geometry, material or disregard mesh). # .setCallbackOnLoad ( callbackOnLoad ) callbackOnLoad - Callback function for described functionality Register callback function that is called once loading of the complete OBJ file is completed. # .setCallbackOnLoadMaterials ( callbackOnLoadMaterials ) callbackOnLoadMaterials - Callback function for described functionality Register callback function that is called when materials have been loaded.

Validator

Constructor

Validator() Validation functions.

Методы

# .isValid ( input ) input - Can be anything If given input is null or undefined, false is returned otherwise true. # .verifyInput ( input, defaultValue ) input - Can be anything defaultValue - Can be anything If given input is null or undefined, the defaultValue is returned otherwise the given input.

ConsoleLogger

Конструктор

ConsoleLogger( enabled, debug ) enabled - Tell if logger is enabled. debug - Toggle debug logging. Logging wrapper for console.

Методы

# .setDebug ( debug ) debug - True or False Enable or disable debug logging. # .isDebug () Returns if is enabled and debug. # .setEnabled ( enabled ) enabled - True or False Enable or disable info, debug and time logging. # .isEnabled () Returns if is enabled. # .logDebug ( message ) message - Message to log Log a debug message if enabled and debug is set. # .logInfo ( message ) message - Message to log Log an info message if enabled. # .logWarn ( message ) message - Message to log Log a warn message (always). # .logError ( message ) message - Message to log Log an error message (always). # .logTimeStart ( id ) id - Time identification Start time measurement with provided id. # .logTimeEnd ( id ) id - Time identification Stop time measurement started with provided id.

Исходники



PCDLoader

A loader for PCD files. Loads ascii and binary. Compressed binary files are not supported.

Пример

		// instantiate a loader
		var loader = new THREE.PCDLoader();

		// load a resource
		loader.load(
			// resource URL
			'pointcloud.pcd' ,
			// Function when resource is loaded
			function ( mesh ) {
				scene.add( mesh );
			}
		);
  
[example:webgl_loader_pcd

Конструктор

PCDLoader( [page:LoadingManager manager )

[page:LoadingManager manager — The [page:LoadingManager loadingManager for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager.
Creates a new [name.

Свойства

[page:Boolean littleEndian

Default value is true.

Методы

[method:null load( [page:String url, [page:Function onLoad, [page:Function onProgress, [page:Function onError )

[page:String url — required
[page:Function onLoad — Will be called when load completes. The argument will be the loaded [page:Object3D.
[page:Function onProgress — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total and .[page:Integer loaded bytes.
[page:Function onError — Will be called when load errors.
Begin loading from url and call onLoad with the parsed response content.

[method:Object3D parse( [page:Arraybuffer data,[page:String url )

[page:Arraybuffer data — The binary structure to parse.
[page:String url — The file name or file url.
Parse an pcd binary structure and return an [page:Object3D.
The object is converted to [page:Points with a [page:BufferGeometry and a [page:PointsMaterial.

Исходники



PDBLoader

A loader for loading a .pdb resource.
The Protein Data Bank file format is a textual file format describing the three-dimensional structures of molecules.

Пример

		// instantiate a loader
		var loader = new THREE.PDBLoader();

		// load a PDB resource
		loader.load(
			// resource URL
			'models/molecules/caffeine.pdb',
			// Function when resource is loaded
			function ( geometryAtoms, geometryBonds, json ) {
				console.log( 'This molecule has ' + json.atoms.length + ' atoms' );
			},
			// Function called when download progresses
			function ( xhr ) {
				console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
			},
			// Function called when download errors
			function ( xhr ) {
				console.log( 'An error happened' );
			}
		);
  
[example:webgl_loader_pdb

Конструктор

PDBLoader( [page:LoadingManager manager )

[page:LoadingManager manager — The [page:LoadingManager loadingManager for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager.
Creates a new PDBLoader.

Свойства

Методы

[method:null load( [page:String url, [page:Function onLoad, [page:Function onProgress, [page:Function onError )

[page:String url — required. URL to the .pdb file
[page:Function onLoad — Will be called when load completes. The arguments will be an [page:BufferGeometry geometryAtoms, [page:BufferGeometry geometryBonds and the [page:Object JSON structure.
[page:Function onProgress — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total and .[page:Integer loaded bytes.
[page:Function onError — Will be called when load errors.
Begin loading from url and call onLoad with the parsed response content.

[method:Object parsePDB( [page:String text )

[page:String text — The textual pdb structure to parse.
Parse a pdb text and return a JSON structure.

[method:null createModel( [page:Object json, [page:Function callback )

[page:Object json — The (JSON) pdb structure to parse.
[page:Function callback — Will be called when parse completes, with three arguments: [page:BufferGeometry geometryAtoms, [page:BufferGeometry geometryBonds and the original [page:Object json.
Parse a (JSON) pdb structure and return two [page:BufferGeometry: one for atoms, one for bonds.

Исходники



SVGLoader

Загрузчик для загрузки ресурса в формате .svg.

Конструктор

SVGLoader( manager )
manager — The [page:LoadingManager loadingManager for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager.
Создает новый SVGLoader.

Свойства


Методы


.load( url, onLoad, onProgress, onError )
url — обязательный параметр
onLoad — функция, которая должна быть вызвана по завершении загрузки. Её аргументом должен быть загруженный [page:SVGDocument.
onProgress — функция, которая будет вызвана во время хода процесса загрузки. Аргументом этой функции должен быть экземпляр XMLHttpRequest, which contains .[page:Integer total and .[page:Integer loaded bytes.
onError — функция, которая будет вызвана при ошибках загрузки.
Begin loading from url and call onLoad with the response content.

Исходники



TGALoader

Class for loading a .tga [page:DataTexture texture.

Пример

		// instantiate a loader
		var loader = new THREE.TGALoader();

		// load a resource
		var texture = loader.load(
			// resource URL
			'textures/crate_grey8.tga'
			// Function when resource is loaded
			function ( texture ) {
				console.log( 'Texture is loaded' );
			},
			// Function called when download progresses
			function ( xhr ) {
				console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
			},
			// Function called when download errors
			function ( xhr ) {
				console.log( 'An error happened' );
			}
		);

		var material = new THREE.MeshPhongMaterial( {
			color: 0xffffff,
			map: texture
		} );
  
[example:webgl_materials_texture_tga

Конструктор

TGALoader( [page:LoadingManager manager )

[page:LoadingManager manager — The [page:LoadingManager loadingManager for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager.
Creates a new TGALoader.

Методы

[method:DataTexture load( [page:String url, [page:Function onLoad, [page:Function onProgress, [page:Function onError )

[page:String url — required
[page:Function onLoad — Will be called when load completes. The argument will be the loaded [page:DataTexture.
[page:Function onProgress — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total and .[page:Integer loaded bytes.
[page:Function onError — Will be called when load errors.
Begin loading from url and pass the loaded [page:DataTexture texture to onLoad. The [page:DataTexture texture is also directly returned for immediate use (but may not be fully loaded).

Исходники



PRWMLoader

A loader for loading a .prwm resource. Packed Raw WebGL Model is an open-source binary file format for nD geometries specifically designed for JavaScript and WebGL with a strong focus on fast parsing (from 1ms to 0.1ms in Chrome 59 on a MBP Late 2013). The parsing of PRWM file is especially fast when the endianness of the file is the same as the endianness of the client platform. More information on this here.

Пример

// instantiate a loader var loader = new THREE.PRWMLoader(); // load a resource loader.load( // resource URL 'models/nefertiti.le.prwm', // called when resource is loaded function ( bufferGeometry ) { var object = new THREE.Mesh( bufferGeometry, new THREE.MeshNormalMaterial() ); scene.add( object ); }, // called when loading is in progresses function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } ); webgl_loader_prwm

Конструктор

PRWMLoader( manager ) manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager. Creates a new PRWMLoader.

Свойства



Методы

# .load ( url, onLoad, onProgress, onError ) url — A string containing the path/URL of the .prwm file. Any * character in the URL will be automatically replaced by le or be depending on the platform endianness. onLoad — (optional) A function to be called after the loading is successfully completed. The function receives the loaded BufferGeometry as an argument. onProgress — (optional) A function to be called while the loading is in progress. The function receives a XMLHttpRequest instance, which contains total and loaded bytes. onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument. Begin loading from url and call onLoad with the parsed response content. # .parse ( arrayBuffer ) arrayBuffer — ArrayBuffer containing the prwm data. Parse a prwm file passed as an ArrayBuffer and directly return an instance of BufferGeometry. PRWMLoader.isBigEndianPlatform( ) Return true if the endianness of the platform is Big Endian, false otherwise.

Исходники

Additional notes

This loader is additionally available on npm as three-prwm-loader.

Объекты

Mesh →

LensFlare

Создает имитацию блика объектива камеры, зависящего от направления освещения. Creates a simulated lens flare that tracks a light.
Примечание: Для работы LensFlare у WebGLRenderer аргумент alpha должен быть установлен как true.

Пример

[example:webgl_lensflares lensflares]

Конструктор

LensFlare( [page:Texture texture], [page:Float size], [page:Float distance], [page:Materials blending], [page:Color color] )
texture — THREE.Texture (optional)
size — size in pixels (-1 = use texture.width)
distance — (0-1) from light source (0 = at light source)
blending — [page:Materials Blending Mode] - Defaults to THREE.NormalBlending
color — The color of the lens flare.
Automatically adds a lens flare to the lensFlares array if a texture is set.

Свойства

[property:array lensFlares]
The array of flares as set by [page:LensFlare.add]
[property:Vector3 positionScreen]
The position of the lens flare on the screen.
[property:Function customUpdateCallback]
A custom update callback

Методы

[method:null add]( [page:Texture texture], [page:Float size], [page:Float distance], [page:Materials blending], [page:Color color] )
Adds a lens flare. See the constructor for details on the parameters.
[method:null updateLensFlares]()
Updates the lens flare based on the [page:LensFlare.positionScreen positionScreen] property.
[method:Lens Flare clone]()
Returns a clone of this LensFlare object and its descendants.

Исходники

[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]

Экспортеры

GLTFExporter

An exporter for glTF 2.0.
glTF (GL Transmission Format) is an open format specification for efficient delivery and loading of 3D content. Assets may be provided either in JSON (.gltf) or binary (.glb) format. External files store textures (.jpg, .png, ...) and additional binary data (.bin). A glTF asset may deliver one or more scenes, including meshes, materials, textures, skins, skeletons, morph targets, animations, lights, and/or cameras.

Пример

// Instantiate a exporter var exporter = new THREE.GLTFExporter( defaultOptions ); // Parse the input and generate the glTF output exporter.parse( scene, function ( gltf ) { console.log( gltf ); downloadJSON( gltf ); }, options ); misc_exporter_gltf

Конструктор

GLTFExporter( ) Creates a new GLTFExporter.

Методы

# .parse ( input, onCompleted, options ) input — Scenes or objects to export. Valid options: Export scenes exporter.parse( scene1, ...) exporter.parse( [ scene1, scene2 ], ...) Export objects (It will create a new Scene to hold all the objects) exporter.parse( object1, ...) exporter.parse( [ object1, object2 ], ...) Mix scenes and objects (It will export the scenes as usual but it will create a new scene to hold all the single objects). exporter.parse( [ scene1, object1, object2, scene2 ], ...) onCompleted — Will be called when the export completes. The argument will be the generated glTF JSON or binary ArrayBuffer. options - Export options trs - bool. Export position, rotation and scale instead of matrix per node. Default is false onlyVisible - bool. Export only visible objects. Default is true. truncateDrawRange - bool. Export just the attributes within the drawRange, if defined, instead of exporting the whole array. Default is true. binary - bool. Export in binary (.glb) format, returning an ArrayBuffer. Default is false. embedImages - bool. Export with images embedded into the glTF asset. Default is true. animations - Array. List of animations to be included in the export. Generates a .gltf (JSON) or .glb (binary) output from the input (Scene or Objects)

Исходники

examples/js/exporters/GLTFExporter.js

Плагины

Camera →

CombinedCamera

A general purpose camera, for setting FOV, Lens Focal Length, and switching between perspective and orthographic views easily. Use this only if you do not wish to manage both an Orthographic and Perspective Camera.

Примеры

[example:canvas_camera_orthographic2 camera / orthographic2
//Create combined camera - создаем комбинированную камеру
camera = new THREE.CombinedCamera( window.innerWidth / 2, window.innerHeight / 2, 70, 1, 1000, - 500, 1000 );

Конструктор

CombinedCamera(width, height, fov, near, far, orthoNear, orthoFar)
width — Camera frustum width.
height — Camera frustum height.
fov — Camera frustum vertical field of view in perspective view.
near — Camera frustum near plane in perspective view.
far — Camera frustum far plane in perspective view.
orthoNear — Camera frustum near plane in orthographic view.
orthoFar — Camera frustum far plane in orthographic view.
Creates a CombinedCamera. This initializes 2 cameras, an OrthographicCamera and a PerspectiveCamera. The default is the perspective Camera.

Свойства

.fov
Gets or sets the camera frustum vertical field of view in perspective view.
.left
Gets or sets the camera frustum left plane in orthographic view.
.right
Gets or sets the camera frustum right plane in orthographic view.
.top
Gets or sets the camera frustum top plane in orthographic view.
.bottom
Gets or sets the camera frustum bottom plane in orthographic view.
.zoom
Gets or sets the zoom factor of the camera.
.near
Gets camera frustum near plane.
.far
Gets camera frustum far plane.
[property:Matrix4 projectionMatrix
This is the matrix which contains the projection.
[property:OrthographicCamera cameraO
Gets or sets the internal OrthographicCamera used as camera.
[property:PerspectiveCamera cameraP
Gets or sets the internal PerspectiveCamera used as camera.
[property:boolean inOrthographicMode
Gets whether the combinedCamera is in Orthographic Mode.
[property:boolean inPerspectiveMode
Gets whether the combinedCamera is in Perspective Mode.

Методы

[method:null setFov([page:Number fov)
fov — Camera frustum vertical field of view in perspective view.
sets the camera frustum vertical field of view in perspective view.
[method:null setZoom([page:Number zoom)
zoom — The zoom factor.
Sets the zoomfactor.
[method:null setLens([page:number focalLength, [page:Number filmGauge)
focalLength — The focal length of a lens is defined as the distance from the optical center of a lens (or, the secondary principal point for a complex lens like a camera lens) to the focal point (sensor) when the lens is focused on an object at infinity.
filmGauge — the size of the frame in mm. (default is *35*)
Sets the fov based on lens data.
[method:null toFrontView()
Sets the camera to view the front of the target.
[method:null toBackView()
Sets the camera to view the back of the target.
[method:null toLeftView()
Sets the camera to view the left of the target.
[method:null toRightView()
Sets the camera to view the right of the target.
[method:null toTopView()
Sets the camera to view the top.
[method:null toBottomView()
Sets the camera to view the bottom.
[method:null setSize([page:Number width, [page:Number height)
width — The width of the orthographic view.
height — The height of the orthographic view.
Sets the size of the orthographic view.
[method:null toOrthographic()
Change the camera to orthographic view.
[method:null toPerspective()
Change the camera to Perspective view.
[method:null updateProjectionMatrix()
Updates the ProjectionMatrix.

Source


Lut

Represents a lookup table for colormaps. It is used to determine the color values from a range of data values.

Пример

var lut = new THREE.Lut( "rainbow", 512 );
var data = [0, 10.1, 4.2, 3.4, 63, 28;
lut.setMax(63);
color = lut.getColor(10);

Конструктор

Lut( colormap, numberOfColors )
colormap — optional argument that sets a colormap from predefined colormaps. Available colormaps are : "rainbow", "cooltowarm", "blackbody".
numberOfColors — optional argument that sets the number of colors used to represent the data array.

Свойства

[property:Float minV
The minimum value to be represented with the lookup table. Default is 0.
[property:Float maxV
The maximum value to be represented with the lookup table. Default is 1.
.[legend
The legend of the lookup table.

Методы

[method:null copy( [page:Lut lut ) [page:Lut this
color — Lut to copy.
Copies given lut.
.setLegendOn [parameters
parameters — { layout: value, position: { x: value, y: value, z: value }, dimensions: { width: value, height: value } } layout — Horizontal or vertical layout. Default is vertical.
position — The position x,y,z of the legend.
dimensions — The dimensions (width and height) of the legend.
Sets this Lut with the legend on.
.setLegendOff
Sets this Lut with the legend off.
.setLegendLabels [parameters, callback
parameters — { fontsize: value, fontface: value, title: value, um: value, ticks: value, decimal: value, notation: value } fontsize — Font size to be used for labels.
fontface — Font type to be used for labels.
title — The title of the legend.
um — The unit of measurements of the legend.
ticks — The number of ticks to be displayed.
decimal — The number of decimals to be used for legend values.
notation — Legend notation: standard (default) or scientific.
callback — An optional callback to be used to format the legend labels.
Sets the labels of the legend of this Lut.
[method:Lut setminV( [page:Float minV )
minV — The minimum value to be represented with the lookup table.
Sets this Lut with the minimum value to be represented.
[method:Lut setmaxV( [page:Float maxV )
maxV — The maximum value to be represented with the lookup table.
Sets this Lut with the maximum value to be represented.
[method:Lut changeNumberOfColors( [page:Float numberOfColors )
numberOfColors — The number of colors to be used to represent the data array.
Sets this Lut with the number of colors to be used.
[method:Lut changeColorMap( [page:Float colorMap )
colorMap — The name of the color map to be used to represent the data array.
Sets this Lut with the colormap to be used.
[method:Lut addColorMap( colorMapName, arrayOfColors )
Insert a new color map into the set of available color maps.
[method:Lut getColor( value ) [page:Lut this
value — the data value to be displayed as a color.
Returns a Three.Color.

Исходники

[link:https://github.com/mrdoob/three.js/blob/master/examples/js/math/[path.js examples/js/math/[path.js

Material →

SpriteCanvasMaterial

Create a material that can draw custom sprites using a 2d canvas.

Конструктор

SpriteCanvasMaterial( [page:Object parameters )
parameters is an object that can be used to set up the default properties
color — the color of the sprite
program — the program used to draw the sprite

Свойства

[property:Color color
The color of the sprite. The material will set up the color for the context before calling the material's program.

Методы

[method:null program([page:CanvasRenderingContext2D context, [page:Color color)
context — The canvas context
color — The color of the sprite
Define a program that will use the context to draw the sprite.

Исходники

[link:https://github.com/mrdoob/three.js/blob/master/examples/js/renderers/CanvasRenderer.js examples/js/renderers/CanvasRenderer.js

QuickHull

Face

Represents a section bounded by a specific amount of half-edges. The current implmentation assumes that a face always consist of three edges.

Конструктор

[name()

Свойства

[property:Vector3 normal

The normal vector of the face. Default is a [page:Vector3 at (0, 0, 0).

[property:Vector3 midpoint

The midpoint or centroid of the face. Default is a [page:Vector3 at (0, 0, 0).

[property:Float area

The area of the face. Default is 0.

[property:Float constant

Signed distance from face to the origin. Default is 0.

[property:VertexNode outside

Reference to a vertex in a vertex list this face can see. Default is null.

[property:Integer mark

Marks if a face is visible or deleted. Default is 'Visible'.

[property:HalfEdge edge

Reference to the base edge of a face. To retrieve all edges, you can use the 'next' reference of the current edge. Default is null.

Методы

[method:Face create( [page:VertexNode a, [page:VertexNode b, [page:VertexNode c )

[page:VertexNode a - First vertex of the face.

[page:VertexNode b - Second vertex of the face.

[page:VertexNode c - Third vertex of the face.

Creates a face.

[method:HalfEdge getEdge( [page:Integer i )

[page:Integer i - The index of the edge.

Returns an edge by the given index.

[method:Face compute ()

Computes all properties of the face.

[method:Float distanceToPoint( [page:Vector3 point )

[page:Vector3 point - Any point in 3D space.

Returns the signed distance from a given point to the plane representation of this face.

Source

[link:https://github.com/mrdoob/three.js/blob/master/examples/js/QuickHull.js examples/js/QuickHull.js

HalfEdge

The basis for a half-edge data structure, also known as doubly connected edge list (DCEL).

Конструктор

HalfEdge( [page:VertexNode vertex, [page:Face face )

[page:VertexNode vertex - [page:VertexNode A reference to its destination vertex.

[page:Face face - [page:Face A reference to its face.

Свойства

[property:VertexNode vertex

Reference to the destination vertex. The origin vertex can be obtained by querying the destination of its twin, or of the previous half-edge. Default is undefined.

[property:HalfEdge prev

Reference to the previous half-edge of the same face. Default is null.

[property:HalfEdge next

Reference to the next half-edge of the same face. Default is null.

[property:HalfEdge twin

Reference to the twin half-edge to reach the opposite face. Default is null.

[property:Face face

Each half-edge bounds a single face and thus has a reference to that face. Default is undefined.

Методы

[method:VertexNode head()

Returns the destintation vertex.

[method:VertexNode tail()

Returns the origin vertex.

[method:Float length()

Returns the [link:https://en.wikipedia.org/wiki/Euclidean_distance Euclidean length (straight-line length) of the edge.

[method:Float lengthSquared()

Returns the square of the [link:https://en.wikipedia.org/wiki/Euclidean_distance Euclidean length (straight-line length) of the edge.

[method:HalfEdge setTwin( [page:HalfEdge edge )

[page:HalfEdge edge - Any half-edge.

Sets the twin edge of this half-edge. It also ensures that the twin reference of the given half-edge is correctly set.

Source

[link:https://github.com/mrdoob/three.js/blob/master/examples/js/QuickHull.js examples/js/QuickHull.js

QuickHull

General information about the Quickhull algorithm: Dirk Gregorius. March 2014, Game Developers Conference: [link:http://media.steampowered.com/apps/valve/2014/DirkGregorius_ImplementingQuickHull.pdf Implementing QuickHull.

Конструктор

QuickHull()

Свойства

[property:Float tolerance

The epsilon value that is used for internal comparative operations. The calculation of this value depends on the size of the geometry. Default is -1.

[property:Array faces

The generated faces of the convex hull. Default is an empty array.

[property:Array newFaces

This array holds the faces that are generated within a single iteration. Default is an empty array.

[property:VertexList assigned

This [page:VertexList vertex list holds all vertices that are assigned to a face. Default is an empty vertex list.

[property:VertexList unassigned

This [page:VertexList vertex list holds all vertices that are not assigned to a face. Default is an empty vertex list.

[property:Array vertices

The internal representation of the given geometry data (an array of [page:VertexNode vertices).

Методы

[method:QuickHull setFromPoints( [page:Array points )

[page:Array points - Array of [page:Vector3 Vector3s that the resulting convex hull will contain.

Computes to convex hull for the given array of points.

[method:QuickHull setFromObject( [page:Object3D object )

[page:Object3D object - [page:Object3D to compute the convex hull of.

Computes the convex hull of an [page:Object3D (including its children), accounting for the world transforms of both the object and its childrens.

[method:QuickHull makeEmpty()

Makes this convex hull empty.

[method:QuickHull addVertexToFace( [page:VertexNode vertex, [page:Face face )

[page:VertexNodeNode vertex - The vetex to add.

[page:Face face - The target face.

Adds a vertex to the 'assigned' list of vertices and assigns it to the given face.

[method:QuickHull removeVertexFromFace( [page:VertexNode vertex, [page:Face face )

[page:VertexNode vertex - The vetex to remove.

[page:Face face - The target face.

Removes a vertex from the 'assigned' list of vertices and from the given face. It also makes sure that the link from 'face' to the first vertex it sees in 'assigned' is linked correctly after the removal.

[method:VertexNode removeAllVerticesFromFace( [page:Face face )

[page:Face face - The given face.

Removes all the visible vertices that a given face is able to see which are stored in the 'assigned' vertext list.

[method:QuickHull deleteFaceVertices( [page:Face face, [page:Face absorbingFace )

[page:Face face - The given face.

[page:Face absorbingFace - An optional face that tries to absorb the vertices of the first face.

Removes all the visible vertices that 'face' is able to see.
  • If 'absorbingFace' doesn't exist, then all the removed vertices will be added to the 'unassigned' vertex list.
  • If 'absorbingFace' exists, then this method will assign all the vertices of 'face' that can see 'absorbingFace'.
  • If a vertex cannot see 'absorbingFace', it's added to the 'unassigned' vertex list.

[method:QuickHull resolveUnassignedPoints( [page:Array newFaces )

[page:Face newFaces - An array of new faces.

Reassigns as many vertices as possible from the unassigned list to the new faces.

[method:Object computeExtremes()

Computes the extremes values (min/max vectors) which will be used to compute the inital hull.

[method:QuickHull computeInitialHull()

Computes the initial simplex assigning to its faces all the points that are candidates to form part of the hull.

[method:QuickHull reindexFaces()

Removes inactive (e.g. deleted) faces from the internal face list.

[method:VertexNode nextVertexToAdd()

Finds the next vertex to create faces with the current hull.
  • Let the initial face be the first face existing in the 'assigned' vertex list.
  • If a face doesn't exist then return since there're no vertices left.
  • Otherwise for each vertex that face sees find the one furthest away from it.

[method:QuickHull computeHorizon( [page:Vector3 eyePoint, [page:HalfEdge crossEdge, [page:Face face, [page:Array horizon )

[page:Vector3 eyePoint - The 3D-coordinates of a point.

[page:HalfEdge crossEdge - The edge used to jump to the current face.

[page:Face face - The current face being tested.

[page:Array horizon - The edges that form part of the horizon in CCW order.

Computes a chain of half edges in CCW order called the 'horizon'. For an edge to be part of the horizon it must join a face that can see 'eyePoint' and a face that cannot see 'eyePoint'.

[method:HalfEdge addAdjoiningFace( [page:VertexNode eyeVertex, [page:HalfEdge horizonEdge )

[page:VertexNode eyeVertex - The vertex that is added to the hull.

[page:HalfEdge horizonEdge - A single edge of the horizon.

Creates a face with the vertices 'eyeVertex.point', 'horizonEdge.tail' and 'horizonEdge.head' in CCW order. All the half edges are created in CCW order thus the face is always pointing outside the hull

[method:QuickHull addNewFaces( [page:VertexNode eyeVertex, [page:HalfEdge horizonEdge )

[page:VertexNode eyeVertex - The vertex that is added to the hull.

[page:HalfEdge horizon - An array of half-edges that form the horizon.

Adds 'horizon.length' faces to the hull, each face will be linked with the horizon opposite face and the face on the left/right.

[method:QuickHull addVertexToHull( [page:VertexNode eyeVertex )

[page:VertexNode eyeVertex - The vertex that is added to the hull.

Adds a vertex to the hull with the following algorithm
  • Compute the 'horizon' which is a chain of half edges. For an edge to belong to this group it must be the edge connecting a face that can see 'eyeVertex' and a face which cannot see 'eyeVertex'.
  • All the faces that can see 'eyeVertex' have its visible vertices removed from the assigned vertex list.
  • A new set of faces is created with each edge of the 'horizon' and 'eyeVertex'. Each face is connected with the opposite horizon face and the face on the left/right.
  • The vertices removed from all the visible faces are assigned to the new faces if possible.

[method:QuickHull cleanup()

Cleans up internal properties after computing the convex hull.

[method:QuickHull compute()

Starts the execution of the quick hull algorithm.

Source

[link:https://github.com/mrdoob/three.js/blob/master/examples/js/QuickHull.js examples/js/QuickHull.js

VertexNode

A vertex as a double linked list node.

Конструктор

VertexNode( [page:Vector3 point )

[page:Vector3 point - [page:Vector3 A point (x, y, z) in 3D space.

Свойства

[property:Vector3 point

A point (x, y, z) in 3D space. Default is undefined.

[property:VertexNode prev

Reference to the previous vertex in the double linked list. Default is null.

[property:VertexNode next

Reference to the next vertex in the double linked list. Default is null.

[property:Face face

Reference to the face that is able to see this vertex. Default is undefined.

Source

[link:https://github.com/mrdoob/three.js/blob/master/examples/js/QuickHull.js examples/js/QuickHull.js

VertexList

A doubly linked list of vertices.

Конструктор

VertexList()

Свойства

[property:VertexNode head

Reference to the first vertex of the linked list. Default is null.

[property:VertexNode tail

Reference to the last vertex of the linked list. Default is null.

Методы

[method:VertexNode first()

Returns the head reference.

[method:VertexNode last()

Returns the tail reference.

[method:VertexList clear()

Clears the linked list.

[method:VertexList insertBefore( [page:Vertex target, [page:Vertex vertex )

[page:Vertex target - The target vertex. It's assumed that this vertex belongs to the linked list.

[page:Vertex vertex - The vertex to insert.

Inserts a vertex before a target vertex.

[method:VertexList insertAfter( [page:Vertex target, [page:Vertex vertex )

[page:Vertex target - The target vertex. It's assumed that this vertex belongs to the linked list.

[page:Vertex vertex - The vertex to insert.

Inserts a vertex after a target vertex.

[method:VertexList append( [page:Vertex vertex )

[page:Vertex vertex - The vertex to append.

Appends a vertex to the end of the linked list.

[method:VertexList appendChain( [page:Vertex vertex )

[page:Vertex vertex - The head vertex of a chain of vertices.

Appends a chain of vertices where the given vertex is the head.

[method:VertexList remove( [page:Vertex vertex )

[page:Vertex vertex - The vertex to remove.

Removes a vertex from the linked list.

[method:VertexList removeSubList( [page:Vertex a, [page:Vertex b )

[page:Vertex a - The head of the sublist.

[page:Vertex b - The tail of the sublist.

Removes a sublist of vertices from the linked list.

[method:Boolean isEmpty()

Returns true if the linked list is empty.

Source

[link:https://github.com/mrdoob/three.js/blob/master/examples/js/QuickHull.js examples/js/QuickHull.js

Визуализаторы

CanvasRenderer

The Canvas renderer displays your beautifully crafted scenes not using WebGL, but draws it using the (slower) Canvas 2D Context API.

NOTE: The Canvas renderer has been deprecated and is no longer part of the three.js core. If you still need to use it you can find it here: [link:https://github.com/mrdoob/three.js/blob/master/examples/js/[path.js examples/js/[path.js.

This renderer can be a nice fallback from [page:WebGLRenderer for simple scenes:
			function webglAvailable() {
				try {
					var canvas = document.createElement( 'canvas' );
					return !!( window.WebGLRenderingContext && (
						canvas.getContext( 'webgl' ) ||
						canvas.getContext( 'experimental-webgl' ) )
					);
				} catch ( e ) {
					return false;
				}
			}

			if ( webglAvailable() ) {
				renderer = new THREE.WebGLRenderer();
			} else {
				renderer = new THREE.CanvasRenderer();
			}
   
Note: both WebGLRenderer and CanvasRenderer are embedded in the web page using an HTML5 <canvas> tag. The "Canvas" in CanvasRenderer means it uses Canvas 2D instead of WebGL.

Don't confuse either CanvasRenderer with the SoftwareRenderer example, which simulates a screen buffer in a Javascript array.

Конструктор

[name([page:object parameters)

parameters is an optional object with properties defining the renderer's behaviour. The constructor also accepts no parameters at all. In all cases, it will assume sane defaults when parameters are missing.
canvas — A [page:Canvas where the renderer draws its output.

Свойства

[property:Object info

An object with a series of statistical information about the graphics board memory and the rendering process. Useful for debugging or just for the sake of curiosity. The object contains the following fields:
  • render:
    • vertices
    • faces

[property:DOMElement domElement

A [page:Canvas where the renderer draws its output.
This is automatically created by the renderer in the constructor (if not provided already); you just need to add it to your page.

[property:Boolean autoClear

Defines whether the renderer should automatically clear its output before rendering.

[property:Boolean sortObjects

Defines whether the renderer should sort objects. Default is true.
Note: Sorting is used to attempt to properly render objects that have some degree of transparency. By definition, sorting objects may not work in all cases. Depending on the needs of application, it may be neccessary to turn off sorting and use other methods to deal with transparency rendering e.g. manually determining the object rendering order.

[property:boolean sortElements

Defines whether the renderer should sort the face of each object. Default is true.

Методы

[method:null render([page:Scene scene, [page:Camera camera)

scene -- The scene to render.
camera -- the camera to view the scene.
Render a scene using a camera.

[method:null clear()

Tells the renderer to clear its color drawing buffer with the clearcolor.

[method:null setClearColor([page:Color color, [page:number alpha)

color -- The color to clear the canvas with.
alpha -- The alpha channel to clear the canvas with.
This set the clearColor and the clearAlpha.

[method:null setSize([page:Number width, [page:Number height)

width -- The width of the drawing canvas.
height -- The height of the drawing canvas.
This set the size of the drawing canvas and if updateStyle is set, then the css of the canvas is updated too.

[method:null setClearColorHex([page:number hex, [page:number alpha)

hex -- The the hexadecimal value of the color to clear the canvas with.
alpha -- The alpha channel to clear the canvas with.
This set the clearColor and the clearAlpha.

[method:number getClearColorHex()

Returns the [page:number hex color.

[method:number getClearAlpha()

Returns the alpha value.

Empty Methods to Maintain Compatibility with [page:WebglRenderer

[method:null clearColor()
[method:null clearDepth()
[method:null clearStencil()
[method:null setFaceCulling()
[method:null supportsVertexTextures()
[method:number getMaxAnisotropy() - returns 1

Source

[link:https://github.com/mrdoob/three.js/blob/master/examples/js/[path.js examples/js/[path.js