Three.js

Three.js

Текстуры

Текстура — растровое изображение, накладываемое на поверхность полигональной модели для придания ей цвета, окраски или иллюзии рельефа.
... читать далее
Приблизительно использование текстур можно легко представить как рисунок на поверхности скульптурного изображения. Использование текстур позволяет воспроизвести малые объекты поверхности, создание которых полигонами оказалось бы чрезмерно ресурсоёмким. Например, шрамы на коже, складки на одежде, мелкие камни и прочие предметы на поверхности стен и почвы.

Качество текстурированной поверхности определяется текселями — количеством пикселей на минимальную единицу текстуры. Так как сама по себе текстура является изображением, разрешение текстуры и её формат играют большую роль, которая впоследствии сказывается на общем впечатлении от качества графики в 3D-приложении.

Метод проецирования текстур для использования в трёхмерной графике впервые был предложен Эдвином Катмуллом в 1974 году[1].

Существует технология parallax mapping для создания трёхмерного описания текстурированной поверхности с использованием карт смещения.
https://ru.wikipedia.org/wiki/%D0%A2%D0%B5%D0%BA%D1%81%D1%82%D1%83%D1%80%D0%B0_(%D1%82%D1%80%D1%91%D1%85%D0%BC%D0%B5%D1%80%D0%BD%D0%B0%D1%8F_%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D0%BA%D0%B0)

Текстура — изображение, воспроизводящее визуальные свойства каких-либо поверхностей или объектов. В отличие от рисунка, к текстуре не применяются нормы и требования композиции, поскольку текстура сама по себе художественным произведением не является, хотя и может иногда выступать доминантой в художественном произведении.

Текстуру, окрестности всех точек которой визуально подобны друг другу, называют равномерной текстурой (гомогенной текстурой).

В компьютерной графике текстурами часто называют растровые цифровые изображения, содержащие текстурные элементы.

Текстуру часто ошибочно называют фоном. Понятие фона относится к перспективному месту на изображении, заднему плану. Текстура же в этом смысле — это изображение, визуально отображающее совокупность свойств поверхности какого-либо объекта — реального или вымышленного.

Понятия «текстура» и «фактура» применительно к свойствам какой-либо поверхности используются синонимично. Иногда словом "фактура" называют совокупность тактильных свойств, а текстурой — совокупность свойств визуальных. Однако за цифровым графическим изображением таких свойств закрепилось слово «текстура».
https://ru.wikipedia.org/wiki/%D0%A2%D0%B5%D0%BA%D1%81%D1%82%D1%83%D1%80%D0%B0_(%D0%B8%D0%B7%D0%BE%D0%B1%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5)
Texture →

CanvasTexture

Создает текстуру из элемента canvas.
Это фактически тоже самое, что и базовый класс Texture, за исключением того, что свойство needsUpdate сразу же устанавливается как true.

Конструктор

CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy )
canvas -- HTML элемент canvas, из которого загружается текстура.
[page:Constant mapping -- How the image is applied to the object. An object type of [page:Textures THREE.UVMapping. Другие варианты смотрите в константах картирования.
[page:Constant wrapS -- The default is [page:Textures THREE.ClampToEdgeWrapping. See [page:Textures wrap mode constants for other choices.
[page:Constant wrapT -- The default is [page:Textures THREE.ClampToEdgeWrapping. See [page:Textures wrap mode constants for other choices.
[page:Constant magFilter -- How the texture is sampled when a texel covers more than one pixel. The default is [page:Textures THREE.LinearFilter. See [page:Textures magnification filter constants for other choices.
[page:Constant minFilter -- How the texture is sampled when a texel covers less than one pixel. The default is [page:Textures THREE.LinearMipMapLinearFilter. See [page:Textures minification filter constants for other choices.
[page:Constant format -- The format used in the texture. See [page:Textures format constants for other choices.
[page:Constant type -- Default is [page:Textures THREE.UnsignedByteType. See [page:Textures type constants for other choices.
[page:Number anisotropy -- The number of samples taken along the axis through the pixel that has the highest density of texels.
By default, this value is 1. A higher value gives a less blurry result than a basic mipmap, at the cost of more texture samples being used.
Use [page:WebGLrenderer.getMaxAnisotropy renderer.getMaxAnisotropy() to find the maximum valid anisotropy value for the GPU; this value is usually a power of 2.

Свойства

Общие свойства смотрите в описании базового класса Texture.

.needsUpdate
Значением по умолчанию является true. Это необходимо для загрузки данных холста (canvas).

Методы

Общие методы смотрите в описании базового класса Texture.

Исходники



Texture →

CompressedTexture

Создает текстуру, основываясь на данных в сжатом виде.

Конструктор

CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy )
mipmaps - массив mipmap должен содержать объекты с данными, шириной и высотой. mipmaps должны быть правильного формата и типа.
https://ru.wikipedia.org/wiki/MIP-%D1%82%D0%B5%D0%BA%D1%81%D1%82%D1%83%D1%80%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5 mipmap - множественное отображение (последовательность текстур одного и того же изображения с уменьшающимся разрешением по мере удаления отображаемого объекта от наблюдателя)
width - ширина наибольшего mipmap
height - высота наибольшего mipmap
format - формат, используемый в mipmaps
type - тип, используемый в mipmaps
mapping -- How the image is applied to the object. An object type of THREE.UVMapping is the default, where the U,V coordinates are used to apply the map, and a single texture is expected. The other types are THREE.CubeReflectionMapping, for cube maps used as a reflection map; THREE.CubeRefractionMapping, refraction mapping; and THREE.SphericalReflectionMapping, a spherical reflection map projection.
wrapS -- The default is THREE.ClampToEdgeWrapping, where the edge is clamped to the outer edge texels. The other two choices are THREE.RepeatWrapping and THREE.MirroredRepeatWrapping.
wrapT -- The default is THREE.ClampToEdgeWrapping, where the edge is clamped to the outer edge texels. The other two choices are THREE.RepeatWrapping and THREE.MirroredRepeatWrapping.
magFilter -- How the texture is sampled when a texel covers more than one pixel. The default is THREE.LinearFilter, which takes the four closest texels and bilinearly interpolates among them. The other option is THREE.NearestFilter, which uses the value of the closest texels.
minFilter -- How the texture is sampled when a texel covers less than one pixel. The default is THREE.LinearMipMapLinearFilter, which uses mipmapping and a trilinear filter. Other choices are THREE.NearestFilter, THREE.NearestMipMapNearestFilter, THREE.NearestMipMapLinearFilter, THREE.LinearFilter, and THREE.LinearMipMapNearestFilter. These vary whether the nearest texel or nearest four texels are retrieved on the nearest mipmap or nearest two mipmaps. Interpolation occurs among the samples retrieved.
anisotropy -- The number of samples taken along the axis through the pixel that has the highest density of texels. By default, this value is 1. A higher value gives a less blurry result than a basic mipmap, at the cost of more texture samples being used. Use renderer.getMaxAnisotropy() to find the maximum valid anisotropy value for the GPU; this value is usually a power of 2.
This creates a texture from compressed data. This is mostly used in ImageUtils.loadCompressedTexture.

Свойства

Общие свойства смотрите в описании базового класса Texture.

.flipY
Значение по умолчанию равно false. Flipping textures does not work for compressed textures.
.generateMipmaps
Значение по умолчанию равно false. Mipmaps can't be generated for compressed textures.

Методы

Общие методы смотрите в описании базового класса Texture.

Исходники



Texture →

CubeTexture

Создает кубическую текстуру, состоящую из шести изображений.

Пример

var loader = new THREE.CubeTextureLoader();
loader.setPath( 'textures/cube/pisa/' );
var textureCube = loader.load( [ 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png' ] );
var material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );

Конструктор

CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy )
По функциональности и применению CubeTexture практически равна Texture. Отличие состоит только в том, что изображения представляют собой массив из 6 изображений, а не одно изображение, и and the mapping options are [page:Textures THREE.CubeReflectionMapping (default) or [page:Textures THREE.CubeRefractionMapping.

Свойства

Общие свойства смотрите в описании базового класса Texture.

Методы

Общие методы смотрите в описании базового класса Texture.

Исходники



Texture →

DataTexture

Создает текстуру непосредственно из необработанных данных (raw data), ширины и высоты.

Конструктор

DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy )
The data argument must be an ArrayBuffer or a typed array view. Further parameters correspond to the properties inherited from [page:Texture, where both magFilter and minFilter default to THREE.NearestFilter. The properties flipY and generateMipmaps are intially set to false.

The interpretation of the data depends on type and format: If the type is THREE.UnsignedByteType, a Uint8Array will be useful for addressing the texel data. If the format is THREE.RGBAFormat, data needs four values for one texel; Red, Green, Blue and Alpha (typically the opacity). Similarly, THREE.RGBFormat specifies a format where only three values are used for each texel.
For the packed types, THREE.UnsignedShort4444Type, THREE.UnsignedShort5551Type or THREE.UnsignedShort565Type, all color components of one texel can be addressed as bitfields within an integer element of a Uint16Array.
In order to use the types THREE.FloatType and THREE.HalfFloatType, the WebGL implementation must support the respective extensions OES_texture_float and OES_texture_half_float. In order to use THREE.LinearFilter for component-wise, bilinear interpolation of the texels based on these types, the WebGL extensions OES_texture_float_linear or OES_texture_half_float_linear must also be present.

Свойства


[property:Image image
Overridden with a record type holding data, width and height.

Методы



Исходники



Texture →

DepthTexture

Creates a texture for use as a Depth Texture. Require support for the WEBGL_depth_texture extension. According to WebGLStats, as of February 2016 around 85% of WebGL enabled devices support this.

Пример

[example:webgl_depth_texture depth / texture

Конструктор

DepthTexture( [page:Number width, [page:Number height, [page:Constant type, [page:Constant wrapS, [page:Constant wrapT, [page:Constant magFilter, [page:Constant minFilter, [page:Number anisotropy, [page:Constant format )
[page:Number width -- width of the texture.
[page:Number height -- height of the texture.
[page:Constant type -- Default is [page:Textures THREE.UnsignedShortType. See [page:Textures type constants for other choices.
[page:Constant mapping -- See [page:Textures type constants for details.
[page:Constant wrapS -- The default is [page:Textures THREE.ClampToEdgeWrapping. See [page:Textures wrap mode constants for other choices.
[page:Constant wrapT -- The default is [page:Textures THREE.ClampToEdgeWrapping. See [page:Textures wrap mode constants for other choices.
[page:Constant magFilter -- How the texture is sampled when a texel covers more than one pixel. The default is [page:Textures THREE.NearestFilter. See [page:Textures magnification filter constants for other choices.
[page:Constant minFilter -- How the texture is sampled when a texel covers less than one pixel. The default is [page:Textures THREE.NearestFilter. See [page:Textures minification filter constants for other choices.
[page:Number anisotropy -- The number of samples taken along the axis through the pixel that has the highest density of texels. By default, this value is 1. A higher value gives a less blurry result than a basic mipmap, at the cost of more texture samples being used. Use [page:WebGLrenderer.getMaxAnisotropy renderer.getMaxAnisotropy() to find the maximum valid anisotropy value for the GPU; this value is usually a power of 2.
[page:Constant format -- must be either [page:Textures DepthFormat (default) or [page:Textures DepthStencilFormat. See [page:Textures format constants for details.

Свойства

Общие методы смотрите в описании базового класса Texture. Свойства, приведенные ниже, также являются частью класса Texture, но имеют здесь другие значения по умолчанию. - the following are also part of the texture class, but have different defaults here.

[page:Texture.format .format
Either [page:Textures DepthFormat (default) or [page:Textures DepthStencilFormat. See [page:Textures format constants for details.

[page:Texture.type .type
Default is [page:Textures THREE.UnsignedShortType. See [page:Textures format constants for details.

[page:Texture.magFilter .magFilter
How the texture is sampled when a texel covers more than one pixel. The default is [page:Textures THREE.NearestFilter. See [page:Textures magnification filter constants for other choices.

[page:Texture.minFilter .minFilter
How the texture is sampled when a texel covers less than one pixel. The default is [page:Textures THREE.NearestFilter. See [page:Textures magnification filter constants for other choices.

[page:Texture.flipY .flipY
Depth textures do not need to be flipped so this is *false* by default.

[page:Texture.generateMipmaps .generateMipmaps
Depth textures do not use mipmaps.

Методы

Общие методы смотрите в описании базового класса Texture.

Исходники



Texture

Создает текстуру для применения к поверхности или в качестве карт отражения или преломления.

Пример

// load a texture, set wrap mode to repeat
// загрузка текстуры, установка режима оболочки для повторения
var texture = new THREE.TextureLoader().load( "textures/water.jpg" );
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set( 4, 4 );

Конструктор

Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy )

Свойства


.id
Уникальное число для данного экземпляра текстуры (только для чтения).

.image
An Image object, typically created using the ImageUtils or [page:ImageLoader ImageLoader classes. The Image object can include an image (e.g., PNG, JPG, GIF, DDS), video (e.g., MP4, OGG/OGV), or set of six images for a cube map. To use video as a texture you need to have a playing HTML5 video element as a source for your texture image and continuously update this texture as long as video is playing.

.mapping
How the image is applied to the object. An object type of THREE.UVMapping is the default, where the U,V coordinates are used to apply the map, and a single texture is expected. The other types are THREE.CubeReflectionMapping, for cube maps used as a reflection map; THREE.CubeRefractionMapping, refraction mapping; and THREE.SphericalReflectionMapping, a spherical reflection map projection.

.wrapS
The default is THREE.ClampToEdgeWrapping, where the edge is clamped to the outer edge texels. The other two choices are THREE.RepeatWrapping and THREE.MirroredRepeatWrapping.

.wrapT
The default is THREE.ClampToEdgeWrapping, where the edge is clamped to the outer edge texels. The other two choices are THREE.RepeatWrapping and THREE.MirroredRepeatWrapping.
Примечание: tiling of images in textures only functions if image dimensions are powers of two (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, ...) in terms of pixels. Individual dimensions need not be equal, but each must be a power of two. Это ограничение от WebGL, а не Three.js.

.magFilter
How the texture is sampled when a texel covers more than one pixel. The default is THREE.LinearFilter, which takes the four closest texels and bilinearly interpolates among them. The other option is THREE.NearestFilter, which uses the value of the closest texel.

.minFilter
How the texture is sampled when a texel covers less than one pixel. The default is THREE.LinearMipMapLinearFilter, which uses mipmapping and a trilinear filter. Other choices are THREE.NearestFilter, THREE.NearestMipMapNearestFilter, THREE.NearestMipMapLinearFilter, THREE.LinearFilter, and THREE.LinearMipMapNearestFilter. These vary whether the nearest texel or nearest four texels are retrieved on the nearest mipmap or nearest two mipmaps. Interpolation occurs among the samples retrieved.

.format
The default is THREE.RGBAFormat for the texture. Other formats are: THREE.AlphaFormat, THREE.RGBFormat, THREE.LuminanceFormat, and THREE.LuminanceAlphaFormat. There are also compressed texture formats, if the S3TC extension is supported: THREE.RGB_S3TC_DXT1_Format, THREE.RGBA_S3TC_DXT1_Format, THREE.RGBA_S3TC_DXT3_Format, and THREE.RGBA_S3TC_DXT5_Format.

.type
The default is THREE.UnsignedByteType. Other valid types (as WebGL allows) are THREE.ByteType, THREE.ShortType, THREE.UnsignedShortType, THREE.IntType, THREE.UnsignedIntType, THREE.FloatType, THREE.UnsignedShort4444Type, THREE.UnsignedShort5551Type, and THREE.UnsignedShort565Type.

.anisotropy
The number of samples taken along the axis through the pixel that has the highest density of texels. By default, this value is 1. A higher value gives a less blurry result than a basic mipmap, at the cost of more texture samples being used. Use renderer.getMaxAnisotropy() to find the maximum valid anisotropy value for the GPU; this value is usually a power of 2.

.needsUpdate
If a texture is changed after creation, set this flag to true so that the texture is properly set up. Particularly important for setting the wrap mode.

.repeat
How many times the texture is repeated across the surface, in each direction U and V.

.offset
How much a single repetition of the texture is offset from the beginning, in each direction U and V. Typical range is 0.0 to 1.0.

.name
Given name of the texture, empty string by default.

.generateMipmaps
Whether to generate mipmaps (if possible) for a texture. True by default.

.flipY
True by default. Flips the image's Y axis to match the WebGL texture coordinate space.

.mipmaps
Array of user-specified mipmaps (optional).

.unpackAlignment
4 by default. Specifies the alignment requirements for the start of each pixel row in memory. The allowable values are 1 (byte-alignment), 2 (rows aligned to even-numbered bytes), 4 (word-alignment), and 8 (rows start on double-word boundaries). See glPixelStorei for more information.

.premultiplyAlpha
False by default, which is the norm for PNG images. Set to true if the RGB values have been stored premultiplied by alpha.

.encoding
Set to THREE.LinearEncoding by default, but supports sRGB, RGBE, RGBM, RGBD, LogLuv and Gamma corrected encodings. IMPORTANT: If this value is changed on a texture after the material has been used, it is necessary to trigger a Material.needsUpdate for this value to be realized in the shader.

.onUpdate
A callback function, called when the texture is updated (e.g., when needsUpdate has been set to true and then the texture is used).

Методы

В этом классе доступны методы EventDispatcher.

.clone ( texture )
Make copy of the texture. Note this is not a "deep copy", the image is shared.

.dispose ()
Call EventDispatcher.dispatchEvent with a 'dispose' event type.

.toJSON ( meta )
meta -- объект, содержащий метаданные (дополнительный, необязательный параметр).
Convert the material to three.js JSON format.

.transformUv ( uv )
Transform the uv based on the value of this texture's .repeat, .offset, .wrapS, .wrapT and .flipY properties.

Исходники



Texture →

VideoTexture Creates a texture for use with a video texture.
This is almost the same as the base [page:Texture Texture class, except that it continuosly sets [page:Texture.needsUpdate needsUpdate to *true* (using requestAnimationFrame) so that the texture is updated as the video plays. Automatic creation of [page:Texture.mipmaps mipmaps is also disabled.

Пример

//assuming you have created a HTML video element with id="video"
var video = document.getElementById( 'video' );
var texture = new THREE.VideoTexture( video ); texture.minFilter = THREE.LinearFilter; texture.magFilter = THREE.LinearFilter; texture.format = THREE.RGBFormat;
Другие примеры
WebGL / materials / video

Конструктор

VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy )
video -- видеоэлемент для использования в качестве текстуры.
mapping -- How the image is applied to the object. An object type of [page:Textures THREE.UVMapping. See [page:Textures mapping constants for other choices.
wrapS -- The default is [page:Textures THREE.ClampToEdgeWrapping. See [page:Textures wrap mode constants for other choices.
wrapT -- The default is [page:Textures THREE.ClampToEdgeWrapping. See [page:Textures wrap mode constants for other choices.
magFilter -- способ выбора текстуры, если тексель занимает больше одного пикселя. Значением по умолчанию является THREE.LinearFilter. Другие возможные варианты смотрите в константах фильтров увеличения.
minFilter -- способ выбора текстуры, если тексель занимает менее одного пикселя. Значением по умолчанию является THREE.LinearMipMapLinearFilter. Другие возможные варианты смотрите в константах фильтров уменьшения.
format -- формат используемый в текстуре. Возможные варианты смотрите в константах форматов текстур.
type -- значением по умолчанию является THREE.UnsignedByteType. Другие возможные варианты смотрите в константах типов текстур.
anisotropy -- The number of samples taken along the axis through the pixel that has the highest density of texels. По умолчанию это значение равно 1. A higher value gives a less blurry result than a basic mipmap, at the cost of more texture samples being used. Используйте метод renderer.getMaxAnisotropy( ), чтобы найти максимальное допустимое значение анизотропии для графического процессора (GPU); это значение обычно является степенью двойки.

Свойства

Общие свойства смотрите в описании базового класса Texture.

.needsUpdate
Это свойство не нужно устанавливать вручную, поскольку оно автоматически обрабатывается методом update.

Методы

Общие методы смотрите в описании базового класса Texture.

.update()
Этот метод вызывается автоматически и устанавливает свойство needsUpdate как true каждый раз, когда доступен новый кадр (frame).

Исходники