language stringclasses 1
value | owner stringlengths 2 15 | repo stringlengths 2 21 | sha stringlengths 45 45 | message stringlengths 7 36.3k | path stringlengths 1 199 | patch stringlengths 15 102k | is_multipart bool 2
classes |
|---|---|---|---|---|---|---|---|
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-transparency.md | @@ -8,7 +8,7 @@ First we'll go over the easy part. Let's make a
scene with 8 cubes placed in a 2x2x2 grid.
We'll start with the example from
-[the article on rendering on demand](threejs-rendering-on-demand.md)
+[the article on rendering on demand](threejs-rendering-on-demand.html)
which had 3 cubes and modify it to have 8. First
let's change our `makeInstance` function to take
an x, y, and z | true |
Other | mrdoob | three.js | a43ab685966c758c6bb4284e9d9dddcd373b1abf.json | fix fixes from testing with check-all-the-errors | threejs/lessons/threejs-webvr-look-to-select.md | @@ -22,7 +22,7 @@ selected.
Let's implement "look to select"! We'll start with
[an example from the previous article](threejs-webvr.html)
and to do it we'll add the `PickHelper` we made in
-[the article on picking](threejs-picking). Here it is.
+[the article on picking](threejs-picking.html). Here it is.
```js
class PickHelper { | true |
Other | mrdoob | three.js | d0d0a944c1f0fe2f96328d92d1a59edf0f9f197a.json | fix voxel example for r112 | threejs/lessons/threejs-voxel-geometry.md | @@ -1123,36 +1123,25 @@ function updateCellGeometry(x, y, z) {
const cellZ = Math.floor(z / cellSize);
const cellId = world.computeCellId(x, y, z);
let mesh = cellIdToMesh[cellId];
- if (!mesh) {
- const geometry = new THREE.BufferGeometry();
- const positionNumComponents = 3;
- const normalNumComponents = 3;
- const uvNumComponents = 2;
-
- geometry.setAttribute(
- 'position',
- new THREE.BufferAttribute(new Float32Array(0), positionNumComponents));
- geometry.setAttribute(
- 'normal',
- new THREE.BufferAttribute(new Float32Array(0), normalNumComponents));
- geometry.setAttribute(
- 'uv',
- new THREE.BufferAttribute(new Float32Array(0), uvNumComponents));
+ const geometry = mesh ? mesh.geometry : new THREE.BufferGeometry();
+
+ const {positions, normals, uvs, indices} = world.generateGeometryDataForCell(cellX, cellY, cellZ);
+ const positionNumComponents = 3;
+ geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
+ const normalNumComponents = 3;
+ geometry.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
+ const uvNumComponents = 2;
+ geometry.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
+ geometry.setIndex(indices);
+ geometry.computeBoundingSphere();
+ if (!mesh) {
mesh = new THREE.Mesh(geometry, material);
mesh.name = cellId;
cellIdToMesh[cellId] = mesh;
scene.add(mesh);
mesh.position.set(cellX * cellSize, cellY * cellSize, cellZ * cellSize);
}
-
- const {positions, normals, uvs, indices} = world.generateGeometryDataForCell(cellX, cellY, cellZ);
- const geometry = mesh.geometry;
- geometry.getAttribute('position').setArray(new Float32Array(positions)).needsUpdate = true;
- geometry.getAttribute('normal').setArray(new Float32Array(normals)).needsUpdate = true;
- geometry.getAttribute('uv').setArray(new Float32Array(uvs)).needsUpdate = true;
- geometry.setIndex(indices);
- geometry.computeBoundingSphere();
}
```
| true |
Other | mrdoob | three.js | d0d0a944c1f0fe2f96328d92d1a59edf0f9f197a.json | fix voxel example for r112 | threejs/threejs-voxel-geometry-culled-faces-ui.html | @@ -396,36 +396,25 @@
const cellZ = Math.floor(z / cellSize);
const cellId = world.computeCellId(x, y, z);
let mesh = cellIdToMesh[cellId];
- if (!mesh) {
- const geometry = new THREE.BufferGeometry();
- const positionNumComponents = 3;
- const normalNumComponents = 3;
- const uvNumComponents = 2;
-
- geometry.setAttribute(
- 'position',
- new THREE.BufferAttribute(new Float32Array(0), positionNumComponents));
- geometry.setAttribute(
- 'normal',
- new THREE.BufferAttribute(new Float32Array(0), normalNumComponents));
- geometry.setAttribute(
- 'uv',
- new THREE.BufferAttribute(new Float32Array(0), uvNumComponents));
+ const geometry = mesh ? mesh.geometry : new THREE.BufferGeometry();
+
+ const {positions, normals, uvs, indices} = world.generateGeometryDataForCell(cellX, cellY, cellZ);
+ const positionNumComponents = 3;
+ geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
+ const normalNumComponents = 3;
+ geometry.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
+ const uvNumComponents = 2;
+ geometry.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
+ geometry.setIndex(indices);
+ geometry.computeBoundingSphere();
+ if (!mesh) {
mesh = new THREE.Mesh(geometry, material);
mesh.name = cellId;
cellIdToMesh[cellId] = mesh;
scene.add(mesh);
mesh.position.set(cellX * cellSize, cellY * cellSize, cellZ * cellSize);
}
-
- const {positions, normals, uvs, indices} = world.generateGeometryDataForCell(cellX, cellY, cellZ);
- const geometry = mesh.geometry;
- geometry.getAttribute('position').setArray(new Float32Array(positions)).needsUpdate = true;
- geometry.getAttribute('normal').setArray(new Float32Array(normals)).needsUpdate = true;
- geometry.getAttribute('uv').setArray(new Float32Array(uvs)).needsUpdate = true;
- geometry.setIndex(indices);
- geometry.computeBoundingSphere();
}
const neighborOffsets = [ | true |
Other | mrdoob | three.js | 58bee4c3b27a60c6e91836be76854c6fcc92e14a.json | use new lesson-builder | Gruntfile.js | @@ -134,7 +134,7 @@ module.exports = function(grunt) {
thumbnailBackground: 'threejsfundamentals-background.jpg',
text: [
{
- font: 'bold 100px sans-serif',
+ font: 'bold 100px lesson-font',
verticalSpacing: 100,
offset: [100, 120],
textAlign: 'left',
@@ -143,7 +143,7 @@ module.exports = function(grunt) {
textWrapWidth: 1000,
},
{
- font: 'bold 60px sans-serif',
+ font: 'bold 60px lesson-font',
text: 'threejsfundamentals.org',
verticalSpacing: 100,
offset: [-100, -90], | false |
Other | mrdoob | three.js | 729696c05eef07e5cafb0c76e73a677b959d9359.json | Update doc for Matrix4 | docs/api/en/math/Matrix4.html | @@ -88,7 +88,7 @@ <h2>Extracting position, rotation and scale</h2>
[page:Vector3.setFromMatrixScale]: can be used to extract the scale component.
</li>
<li>
- [page:Quaternion.setFromRotationMatrix], [page:Euler.setFromRotationMatrix] or [page:.extractRotation extractRotation] can be used to extract the rotation component.
+ [page:Quaternion.setFromRotationMatrix], [page:Euler.setFromRotationMatrix] or [page:.extractRotation extractRotation] can be used to extract the rotation component from a pure (unscaled) matrix.
</li>
<li>
[page:.decompose decompose] can be used to extract position, rotation and scale all at once. | false |
Other | mrdoob | three.js | 02c0511ad7bc9e79fedd2861b1ad346997f28dee.json | Add traversal note | docs/api/en/core/Object3D.html | @@ -413,15 +413,15 @@ <h3>[method:null traverse]( [param:Function callback] )</h3>
<p>
callback - A function with as first argument an object3D object.<br /><br />
- Executes the callback on this object and all descendants.
+ Executes the callback on this object and all descendants. <b>Warning:</b> Do not add, move, or remove the object or its descendants while traversing.
</p>
<h3>[method:null traverseVisible]( [param:Function callback] )</h3>
<p>
callback - A function with as first argument an object3D object.<br /><br />
Like traverse, but the callback will only be executed for visible objects.
- Descendants of invisible objects are not traversed.
+ Descendants of invisible objects are not traversed. <b>Warning:</b> Do not add, move, or remove the object or its descendants while traversing.
</p>
<h3>[method:null traverseAncestors]( [param:Function callback] )</h3> | false |
Other | mrdoob | three.js | cfa00dc9d45917ff27e0e2c0048d25823173a34a.json | add warnings for translations that need update | threejs/lessons/ru/threejs-fundamentals.md | @@ -2,6 +2,8 @@ Title: Основы Three.js
Description: Твой первый урок по Three.js начинаетсся с основ
TOC: Базовые принципы
+{{{warning msgId="updateNeeded"}}}
+
Это первая статья в серии статей о three.js.
[Three.js](http://threejs.org) это 3D-библиотека, которая максимально
упрощает создание 3D-контента на веб-странице. | true |
Other | mrdoob | three.js | cfa00dc9d45917ff27e0e2c0048d25823173a34a.json | add warnings for translations that need update | threejs/lessons/ru/threejs-optimize-lots-of-objects-animated.md | @@ -2,6 +2,8 @@ Title: Three.js Оптимизация большого количества а
Description: Анимированные объединенные объекты с морфтаргетами
TOC: Оптимизация множества анимированных объектов
+{{{warning msgId="updateNeeded"}}}
+
Эта статья является продолжением [статьи об оптимизации множества объектов
](threejs-optimize-lots-of-objects.html). Если вы еще не прочитали это, пожалуйста, прочитайте его, прежде чем продолжить.
| true |
Other | mrdoob | three.js | a2dfa80df8938398f1b303a83beefbaadea706ed.json | translate threejs-textures to zh-cn | threejs/lessons/zh_cn/threejs-textures.md | @@ -0,0 +1,517 @@
+Title: Three.js 纹理
+Description: 在three.js中使用纹理
+TOC: 纹理
+
+本文是关于 three.js 系列文章的一部分。第一篇文章是 [three.js 基础](threejs-fundamentals.html)。上一篇[文章](threejs-setup.html)是关于本文的环境搭建。如果你还没有读过它,建议先从那里开始。
+
+纹理是Three.js中的一种大话题,我还不能100%地确定在什么层面上解释它们,但我会试着去做它。这里面有很多主题,而且很多主题是相互关联的,所以很难一下子解释清楚。下面是本文的快速目录。
+
+<ul>
+<li><a href="#hello">你好,纹理</a></li>
+<li><a href="#six">6种纹理,在立方体的每个面上都有不同的纹理。</a></li>
+<li><a href="#loading">加载纹理</a></li>
+<ul>
+ <li><a href="#easy">简单的方法</a></li>
+ <li><a href="#wait1">等待一个纹理加载</a></li>
+ <li><a href="#waitmany">等待多个纹理加载</a></li>
+ <li><a href="#cors">从其他源加载纹理</a></li>
+</ul>
+<li><a href="#memory">内存使用</a></li>
+<li><a href="#format">JPG vs PNG</a></li>
+<li><a href="#filtering-and-mips">过滤和mips</a></li>
+<li><a href="#uvmanipulation">重复,偏移,旋转,包裹</a></li>
+</ul>
+
+## <a name="hello"></a> 你好,纹理
+
+纹理一般是指我们常见的在一些第三方程序中创建的图像,如Photoshop或GIMP。比如我们把这张图片放在立方体上。
+
+<div class="threejs_center">
+ <img src="../resources/images/wall.jpg" style="width: 600px;" class="border" >
+</div>
+
+我们将修改我们的第一个例子中的其中一个。我们需要做的就是创建一个`TextureLoader`。调用它的[`load`](TextureLoader.load)方法,同时传入图像的URL,并将材质的 `map` 属性设置为该方法的返回值,而不是设置它的 `color`属性。
+
+```js
++const loader = new THREE.TextureLoader();
+
+const material = new THREE.MeshBasicMaterial({
+- color: 0xFF8844,
++ map: loader.load('resources/images/wall.jpg'),
+});
+```
+注意,我们使用的是 `MeshBasicMaterial`, 所以没有必要增加光线
+
+{{{example url="../threejs-textured-cube.html" }}}
+
+## <a name="six"></a> 6种纹理,在立方体的每个面上都有不同的纹理。
+
+6个纹理,一个立方体的每个面都有一个,怎么样?
+
+<div class="threejs_center">
+ <div>
+ <img src="../resources/images/flower-1.jpg" style="width: 100px;" class="border" >
+ <img src="../resources/images/flower-2.jpg" style="width: 100px;" class="border" >
+ <img src="../resources/images/flower-3.jpg" style="width: 100px;" class="border" >
+ </div>
+ <div>
+ <img src="../resources/images/flower-4.jpg" style="width: 100px;" class="border" >
+ <img src="../resources/images/flower-5.jpg" style="width: 100px;" class="border" >
+ <img src="../resources/images/flower-6.jpg" style="width: 100px;" class="border" >
+ </div>
+</div>
+
+我们只需制作6种材料,并在创建 `Mesh` 时将它们作为一个数组传递给它们。
+
+```js
+const loader = new THREE.TextureLoader();
+
+-const material = new THREE.MeshBasicMaterial({
+- map: loader.load('resources/images/wall.jpg'),
+-});
++const materials = [
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-1.jpg')}),
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-2.jpg')}),
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-3.jpg')}),
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-4.jpg')}),
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-5.jpg')}),
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-6.jpg')}),
++];
+-const cube = new THREE.Mesh(geometry, material);
++const cube = new THREE.Mesh(geometry, materials);
+```
+
+有效果了!
+
+{{{example url="../threejs-textured-cube-6-textures.html" }}}
+
+但需要注意的是,并不是所有的几何体类型都支持多种材质。`BoxGeometry` 和 `BoxBufferGeometry` 可以使用6种材料,每个面一个。`ConeGeometry` 和 `ConeBufferGeometry` 可以使用2种材料,一种用于底部,一种用于侧面。 `CylinderGeometry` 和 `CylinderBufferGeometry` 可以使用3种材料,分别是底部、顶部和侧面。对于其他情况,你需要建立或加载自定义几何体和(或)修改纹理坐标。
+
+在其他3D引擎中,如果你想在一个几何体上使用多个图像,使用 [纹理图集(Texture Atlas)](https://en.wikipedia.org/wiki/Texture_atlas) 更为常见,性能也更高。纹理图集是将多个图像放在一个单一的纹理中,然后使用几何体顶点上的纹理坐标来选择在几何体的每个三角形上使用纹理的哪些部分。
+
+什么是纹理坐标?它们是添加到一块几何体的每个顶点上的数据,用于指定该顶点对应的纹理的哪个部分。当我们开始[构建自定义几何体时(building custom geometry)](threejs-custom-geometry.html),我们会介绍它们。
+
+## <a name="loading"></a> 加载纹理
+
+### <a name="easy"></a> 简单的方法
+
+本文的大部分代码都使用最简单的加载纹理的方法。我们创建一个 `TextureLoader` ,然后调用它的[`load`](TextureLoader.load)方法。
+这将返回一个 `Texture` 对象。
+
+```js
+const texture = loader.load('resources/images/flower-1.jpg');
+```
+
+需要注意的是,使用这个方法,我们的纹理将是透明的,直到图片被three.js异步加载完成,这时它将用下载的图片更新纹理。
+
+这有一个很大的好处,就是我们不必等待纹理加载,我们的页面会立即开始渲染。这对于很多用例来说可能都没问题,但如果我们想要的话,我们可以让three.js告诉我们何时纹理已经下载完毕。
+
+### <a name="wait1"></a> 等待一个纹理加载
+
+为了等待贴图加载,贴图加载器的 `load` 方法会在贴图加载完成后调用一个回调。回到上面的例子,我们可以在创建Mesh并将其添加到场景之前等待贴图加载,就像这样。
+
+```js
+const loader = new THREE.TextureLoader();
+loader.load('resources/images/wall.jpg', (texture) => {
+ const material = new THREE.MeshBasicMaterial({
+ map: texture,
+ });
+ const cube = new THREE.Mesh(geometry, material);
+ scene.add(cube);
+ cubes.push(cube); // 添加到我们要旋转的立方体数组中
+});
+```
+
+除非你清除你的浏览器的缓存并且连接缓慢,你不太可能看到任何差异,但放心,它正在等待纹理加载。
+
+{{{example url="../threejs-textured-cube-wait-for-texture.html" }}}
+
+### <a name="waitmany"></a> 等待多个纹理加载
+
+要等到所有纹理都加载完毕,你可以使用 `LoadingManager` 。创建一个并将其传递给 `TextureLoader`,然后将其[`onLoad`](LoadingManager.onLoad)属性设置为回调。
+
+```js
++const loadManager = new THREE.LoadingManager();
+*const loader = new THREE.TextureLoader(loadManager);
+
+const materials = [
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-1.jpg')}),
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-2.jpg')}),
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-3.jpg')}),
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-4.jpg')}),
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-5.jpg')}),
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-6.jpg')}),
+];
+
++loadManager.onLoad = () => {
++ const cube = new THREE.Mesh(geometry, materials);
++ scene.add(cube);
++ cubes.push(cube); // 添加到我们要旋转的立方体数组中
++};
+```
+
+`LoadingManager` 也有一个 [`onProgress`](LoadingManager.onProgress) 属性,我们可以设置为另一个回调来显示进度指示器。
+
+首先,我们在HTML中添加一个进度条
+
+```html
+<body>
+ <canvas id="c"></canvas>
++ <div id="loading">
++ <div class="progress"><div class="progressbar"></div></div>
++ </div>
+</body>
+```
+
+然后给它加上CSS
+
+```css
+#loading {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+}
+#loading .progress {
+ margin: 1.5em;
+ border: 1px solid white;
+ width: 50vw;
+}
+#loading .progressbar {
+ margin: 2px;
+ background: white;
+ height: 1em;
+ transform-origin: top left;
+ transform: scaleX(0);
+}
+```
+
+然后在代码中,我们将在 `onProgress` 回调中更新 `progressbar` 的比例。调用它有如下几个参数:最后加载的项目的URL,目前加载的项目数量,以及加载的项目总数。
+
+```js
++const loadingElem = document.querySelector('#loading');
++const progressBarElem = loadingElem.querySelector('.progressbar');
+
+loadManager.onLoad = () => {
++ loadingElem.style.display = 'none';
+ const cube = new THREE.Mesh(geometry, materials);
+ scene.add(cube);
+ cubes.push(cube); // 添加到我们要旋转的立方体数组中
+};
+
++loadManager.onProgress = (urlOfLastItemLoaded, itemsLoaded, itemsTotal) => {
++ const progress = itemsLoaded / itemsTotal;
++ progressBarElem.style.transform = `scaleX(${progress})`;
++};
+```
+除非你清除了你的缓存,而且连接速度很慢,否则你可能看不到加载栏。
+
+{{{example url="../threejs-textured-cube-wait-for-all-textures.html" }}}
+
+## <a name="cors"></a> 从其他源加载纹理
+
+要使用其他服务器上的图片,这些服务器需要发送正确的头文件。如果他们不发送,你就不能在three.js中使用这些图片,并且会得到一个错误。如果你运行提供图片的服务器,请确保它[发送正确的头文件](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).。如果你不控制托管图片的服务器,而且它没有发送权限头文件,那么你就不能使用该服务器上的图片。
+
+例如 [imgur](https://imgur.com)、[flickr](https://flickr.com) 和 [github](https://github.com) 都会发送头文件,允许你在 three.js 中使用他们服务器上托管的图片,使用 three.js。而其他大多数网站则不允许。
+
+## <a name="memory"></a> 内存管理
+
+纹理往往是three.js应用中使用内存最多的部分。重要的是要明白,*一般来说*,纹理会占用 `宽度 * 高度 * 4 * 1.33` 字节的内存。
+
+注意,这里没有提到任何关于压缩的问题。我可以做一个.jpg的图片,然后把它的压缩率设置的超级高。比如说我在做一个房子的场景。在房子里面有一张桌子,我决定在桌子的顶面放上这个木质的纹理
+
+<div class="threejs_center"><img class="border" src="resources/images/compressed-but-large-wood-texture.jpg" align="center" style="width: 300px"></div>
+
+那张图片只有157k,所以下载起来会比较快,但[实际上它的大小是3024×3761像素](resources/images/compressed-but-large-wood-texture.jpg).。按照上面的公式,那就是
+
+ 3024 * 3761 * 4 * 1.33 = 60505764.5
+
+在three.js中,这张图片会占用**60兆(meg)的内存!**。只要几个这样的纹理,你就会用完内存。
+
+我之所以提出这个问题,是因为要知道使用纹理是有隐性成本的。为了让three.js使用纹理,必须把纹理交给GPU,而GPU*一般*都要求纹理数据不被压缩。
+
+这个故事的寓意在于,不仅仅要让你的纹理的文件大小小,还得让你的纹理尺寸小。文件大小小=下载速度快。尺寸小=占用的内存少。你应该把它们做得多小?越小越好,而且看起来仍然是你需要的样子。
+
+## <a name="format"></a> JPG vs PNG
+
+这和普通的HTML差不多,JPG有损压缩,PNG有无损压缩,所以PNG的下载速度一般比较慢。但是,PNG支持透明度。PNG可能也适合作为非图像数据(non-image data)的格式,比如法线图,以及其他种类的非图像图,我们后面会介绍。
+
+请记住,在WebGL中JPG使用的内存并不比PNG少。参见上文。
+
+## <a name="filtering-and-mips"></a> 过滤和mips
+
+让我们把这个16x16的纹理应用到
+
+<div class="threejs_center"><img src="resources/images/mip-low-res-enlarged.png" class="nobg" align="center"></div>
+
+一个立方体上。
+
+<div class="spread"><div data-diagram="filterCube"></div></div>
+
+让我们把这个立方体画得非常小
+
+<div class="spread"><div data-diagram="filterCubeSmall"></div></div>
+
+嗯,我想这很难看得清楚。让我们把这个小方块放大
+
+<div class="spread"><div data-diagram="filterCubeSmallLowRes"></div></div>
+
+GPU怎么知道小立方体的每一个像素需要使用哪些颜色?如果立方体小到只有1、2个像素呢?
+
+这就是过滤(filtering)的意义所在。
+
+如果是Photoshop,Photoshop会把几乎所有的像素平均在一起,来计算出这1、2个像素的颜色。这将是一个非常缓慢的操作。GPU用mipmaps解决了这个问题。
+
+Mips 是纹理的副本,每一个都是前一个 mip 的一半宽和一半高,其中的像素已经被混合以制作下一个较小的 mip。Mips一直被创建,直到我们得到1x1像素的Mip。对于上面的图片,所有的Mip最终会变成这样的样子
+
+<div class="threejs_center"><img src="resources/images/mipmap-low-res-enlarged.png" class="nobg" align="center"></div>
+
+现在,当立方体被画得很小,只有1或2个像素大时,GPU可以选择只用最小或次小级别的mip来决定让小立方体变成什么颜色。
+
+在three.js中,当纹理绘制的尺寸大于其原始尺寸时,或者绘制的尺寸小于其原始尺寸时,你都可以做出相应的处理。
+
+当纹理绘制的尺寸大于其原始尺寸时,你可以将 [`texture.magFilter`](Texture.magFilter) 属性设置为 `THREE.NearestFilter` 或 `THREE.LinearFilter` 。`NearestFilter` 意味着只需从原始纹理中选取最接近的一个像素。对于低分辨率的纹理,这给你一个非常像素化的外观,就像Minecraft。
+
+`LinearFilter` 是指从纹理中选择离我们应该选择颜色的地方最近的4个像素,并根据实际点与4个像素的距离,以适当的比例进行混合。
+
+<div class="spread">
+ <div>
+ <div data-diagram="filterCubeMagNearest" style="height: 250px;"></div>
+ <div class="code">Nearest</div>
+ </div>
+ <div>
+ <div data-diagram="filterCubeMagLinear" style="height: 250px;"></div>
+ <div class="code">Linear</div>
+ </div>
+</div>
+
+为了在绘制的纹理小于其原始尺寸时设置过滤器,你可以将 [`texture.minFilter`](Texture.minFilter) 属性设置为下面6个值之一。
+
+* `THREE.NearestFilter`
+
+ 同上,在纹理中选择最近的像素。
+
+* `THREE.LinearFilter`
+
+ 和上面一样,从纹理中选择4个像素,然后混合它们
+
+* `THREE.NearestMipmapNearestFilter`
+
+ 选择合适的mip,然后选择一个像素。
+
+* `THREE.NearestMipmapLinearFilter`
+
+ 选择2个mips,从每个mips中选择一个像素,混合这2个像素。
+
+* `THREE.LinearMipmapNearestFilter`
+
+ 选择合适的mip,然后选择4个像素并将它们混合。
+
+* `THREE.LinearMipmapLinearFilter`
+
+ 选择2个mips,从每个mips中选择4个像素,然后将所有8个像素混合成1个像素。
+
+下面是一个分别使用上面6个设置的例子
+
+<div class="spread">
+ <div data-diagram="filterModes" style="
+ height: 450px;
+ position: relative;
+ ">
+ <div style="
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ ">
+ <div style="
+ background: rgba(255,0,0,.8);
+ color: white;
+ padding: .5em;
+ margin: 1em;
+ font-size: small;
+ border-radius: .5em;
+ line-height: 1.2;
+ user-select: none;"
+ >click to<br/>change<br/>texture</div>
+ </div>
+ <div class="filter-caption" style="left: 0.5em; top: 0.5em;">nearest</div>
+ <div class="filter-caption" style="width: 100%; text-align: center; top: 0.5em;">linear</div>
+ <div class="filter-caption" style="right: 0.5em; text-align: right; top: 0.5em;">nearest<br/>mipmap<br/>nearest</div>
+ <div class="filter-caption" style="left: 0.5em; text-align: left; bottom: 0.5em;">nearest<br/>mipmap<br/>linear</div>
+ <div class="filter-caption" style="width: 100%; text-align: center; bottom: 0.5em;">linear<br/>mipmap<br/>nearest</div>
+ <div class="filter-caption" style="right: 0.5em; text-align: right; bottom: 0.5em;">linear<br/>mipmap<br/>linear</div>
+ </div>
+</div>
+
+需要注意的是,使用 `NearestFilter` 和 `LinearFilter` 的左上方和中上方没有使用mips。正因为如此,它们在远处会闪烁,因为GPU是从原始纹理中挑选像素。左边只有一个像素被选取,中间有4个像素被选取并混合,但这还不足以得出一个好的代表颜色。其他4条做得比较好,右下角的`LinearMipmapLinearFilter`最好。
+
+如果你点击上面的图片,它将在我们上面一直使用的纹理和每一个mip级别都是不同颜色的纹理之间切换。
+
+<div class="threejs_center">
+ <div data-texture-diagram="differentColoredMips"></div>
+</div>
+
+这样就更清楚了。在左上角和中上角你可以看到第一个mip一直用到了远处。右上角和中下角你可以清楚地看到哪里使用了不同的mip。
+
+切换回原来的纹理,你可以看到右下角是最平滑的,质量最高的。你可能会问为什么不总是使用这种模式。最明显的原因是有时你希望东西是像素化的,以达到复古的效果或其他原因。其次最常见的原因是,读取8个像素并混合它们比读取1个像素并混合要慢。虽然单个纹理不太可能成为快和慢的区别,但随着我们在这些文章中的进一步深入,我们最终会有同时使用4或5个纹理的材料的情况。4个纹理*每个纹理8个像素,就是查找32个像素的永远渲染的像素。在移动设备上,这一嗲可能需要被重点考虑。
+
+## <a name="uvmanipulation"></a> 重复,偏移,旋转,包裹一个纹理
+
+纹理有重复、偏移和旋转纹理的设置。
+
+默认情况下,three.js中的纹理是不重复的。要设置纹理是否重复,有2个属性,[`wrapS`](Texture.wrapS) 用于水平包裹,[`wrapT`](Texture.wrapT) 用于垂直包裹。
+
+它们可以被设置为一下其中一个:
+
+* `THREE.ClampToEdgeWrapping`
+
+ 每条边上的最后一个像素无限重复。
+
+* `THREE.RepeatWrapping`
+
+ 纹理重复
+
+* `THREE.MirroredRepeatWrapping`
+
+ 在每次重复时将进行镜像
+
+比如说,要开启两个方向的包裹。
+
+```js
+someTexture.wrapS = THREE.RepeatWrapping;
+someTexture.wrapT = THREE.RepeatWrapping;
+```
+
+重复是用[repeat]重复属性设置的。
+
+```js
+const timesToRepeatHorizontally = 4;
+const timesToRepeatVertically = 2;
+someTexture.repeat.set(timesToRepeatHorizontally, timesToRepeatVertically);
+```
+
+纹理的偏移可以通过设置 `offset` 属性来完成。纹理的偏移是以单位为单位的,其中1个单位=1个纹理大小。换句话说,0 = 没有偏移,1 = 偏移一个完整的纹理数量。
+
+```js
+const xOffset = .5; // offset by half the texture
+const yOffset = .25; // offset by 1/4 the texture
+someTexture.offset.set(xOffset, yOffset);
+```
+
+通过设置以弧度为单位的 `rotation` 属性以及用于选择旋转中心的 `center` 属性,可以设置纹理的旋转。它的默认值是0,0,从左下角开始旋转。像偏移一样,这些单位是以纹理大小为单位的,所以将它们设置为 `.5`,`.5` 将会围绕纹理中心旋转。
+
+```js
+someTexture.center.set(.5, .5);
+someTexture.rotation = THREE.MathUtils.degToRad(45);
+```
+
+让我们修改一下上面的示例,来试试这些属性吧
+
+首先,我们要保留一个对纹理的引用,这样我们就可以对它进行操作。
+
+```js
++const texture = loader.load('resources/images/wall.jpg');
+const material = new THREE.MeshBasicMaterial({
+- map: loader.load('resources/images/wall.jpg');
++ map: texture,
+});
+```
+
+然后,我们会再次使用 [dat.GUI](https://github.com/dataarts/dat.gui) 来提供一个简单的界面。
+
+```js
+import {GUI} from '../3rdparty/dat.gui.module.js';
+```
+
+正如我们在之前的dat.GUI例子中所做的那样,我们将使用一个简单的类来给dat.GUI提供一个可以以度数为单位进行操作的对象,但它将以弧度为单位设置该属性。
+
+```js
+class DegRadHelper {
+ constructor(obj, prop) {
+ this.obj = obj;
+ this.prop = prop;
+ }
+ get value() {
+ return THREE.MathUtils.radToDeg(this.obj[this.prop]);
+ }
+ set value(v) {
+ this.obj[this.prop] = THREE.MathUtils.degToRad(v);
+ }
+}
+```
+
+我们还需要一个类,将 `"123"` 这样的字符串转换为 `123` 这样的数字,因为three.js的枚举设置需要数字,比如 `wrapS` 和 `wrapT`,但dat.GUI只使用字符串来设置枚举。
+
+```js
+class StringToNumberHelper {
+ constructor(obj, prop) {
+ this.obj = obj;
+ this.prop = prop;
+ }
+ get value() {
+ return this.obj[this.prop];
+ }
+ set value(v) {
+ this.obj[this.prop] = parseFloat(v);
+ }
+}
+```
+
+利用这些类,我们可以为上面的设置设置一个简单的GUI。
+
+```js
+const wrapModes = {
+ 'ClampToEdgeWrapping': THREE.ClampToEdgeWrapping,
+ 'RepeatWrapping': THREE.RepeatWrapping,
+ 'MirroredRepeatWrapping': THREE.MirroredRepeatWrapping,
+};
+
+function updateTexture() {
+ texture.needsUpdate = true;
+}
+
+const gui = new GUI();
+gui.add(new StringToNumberHelper(texture, 'wrapS'), 'value', wrapModes)
+ .name('texture.wrapS')
+ .onChange(updateTexture);
+gui.add(new StringToNumberHelper(texture, 'wrapT'), 'value', wrapModes)
+ .name('texture.wrapT')
+ .onChange(updateTexture);
+gui.add(texture.repeat, 'x', 0, 5, .01).name('texture.repeat.x');
+gui.add(texture.repeat, 'y', 0, 5, .01).name('texture.repeat.y');
+gui.add(texture.offset, 'x', -2, 2, .01).name('texture.offset.x');
+gui.add(texture.offset, 'y', -2, 2, .01).name('texture.offset.y');
+gui.add(texture.center, 'x', -.5, 1.5, .01).name('texture.center.x');
+gui.add(texture.center, 'y', -.5, 1.5, .01).name('texture.center.y');
+gui.add(new DegRadHelper(texture, 'rotation'), 'value', -360, 360)
+ .name('texture.rotation');
+```
+
+最后需要注意的是,如果你改变了纹理上的 `wrapS` 或 `wrapT`,你还必须设置 [`texture.needsUpdate`](Texture.needsUpdate),以便three.js知道并应用这些设置。其他的设置会自动应用。
+
+{{{example url="../threejs-textured-cube-adjust.html" }}}
+
+这只是进入纹理主题的一个步骤。在某些时候,我们将介绍纹理坐标以及其他9种可应用于材料的纹理类型。
+
+现在我们继续说说[灯光](threejs-lights.html)。
+
+<!--
+alpha
+ao
+env
+light
+specular
+bumpmap ?
+normalmap ?
+metalness
+roughness
+-->
+
+<link rel="stylesheet" href="resources/threejs-textures.css">
+<script type="module" src="resources/threejs-textures.js"></script> | false |
Other | mrdoob | three.js | 573635944d31d6ae28554f18eade8e5c0f8b449e.json | Improve diff of code snippet example (#163)
Co-authored-by: Torsten Knauf <Torsten.Knauf@maibornwolff.de> | threejs/lessons/threejs-scenegraph.md | @@ -209,6 +209,7 @@ Continuing that same pattern let's add a moon.
const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244});
const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial);
+-earthMesh.position.x = 10; // note that this offset is already set in its parent's THREE.Object3D object "earthOrbit"
-solarSystem.add(earthMesh);
+earthOrbit.add(earthMesh);
objects.push(earthMesh); | false |
Other | mrdoob | three.js | 8808b1cd0f11d9b33c977e9c6bad74c0baf158ba.json | fix zh_cn links | threejs/lessons/zh_cn/threejs-fundamentals.md | @@ -80,7 +80,7 @@ import * as THREE from './resources/threejs/r122/build/three.module.js';
</script>
```
-拿到canvas后我们需要创建一个[WebGL渲染器(`WebGLRenderer`)](WebGLRenderer)。渲染器负责将你提供的所有数据渲染绘制到canvas上。之前还有其他渲染器,比如[CSS渲染器(`CSSRenderer`)](CSSRenderer)、[Canvas渲染器(`CanvasRenderer`)](CanvasRenderer)。将来也可能会有[WebGL2渲染器(`WebGL2Renderer`)](WebGL2Renderer)或[WebGPU渲染器(`WebGPURenderer`)](WebGPURenderer)。目前的话是[WebGL渲染器(`WebGLRenderer`)](WebGLRenderer),它通过WebGL将三维空间渲染到canvas上。
+拿到canvas后我们需要创建一个[WebGL渲染器(`WebGLRenderer`)](WebGLRenderer)。渲染器负责将你提供的所有数据渲染绘制到canvas上。之前还有其他渲染器,比如CSS渲染器(`CSSRenderer`)、Canvas渲染器(`CanvasRenderer`)。将来也可能会有WebGL2渲染器(`WebGL2Renderer`)或WebGPU渲染器(`WebGPURenderer`)。目前的话是[WebGL渲染器(`WebGLRenderer`)](WebGLRenderer),它通过WebGL将三维空间渲染到canvas上。
注意这里有一些细节。如果你没有给three.js传canvas,three.js会自己创建一个 ,但是你必须手动把它添加到文档中。在哪里添加可能会不一样这取决你怎么使用, 我发现给three.js传一个canvas会更灵活一些。我可以将canvas放到任何地方, 代码都会找到它,假如我有一段代码是将canvas插入到文档中,那么当需求变化时, 我很可能必须去修改这段代码。
| false |
Other | mrdoob | three.js | a8be80b94fb5538c7107944fc44b97ec86cc4c27.json | fix zh_cn links | threejs/lessons/zh_cn/threejs-fundamentals.md | @@ -29,21 +29,21 @@ ES6的语法。[点击这里查看你需要提前掌握的东西](threejs-prereq
上图需要注意的事项:
-* 首先有一个[渲染器](`Renderer`)。这可以说是three.js的主要对象。你传入一个[场景](`Scene`)和一个[摄像机](`Camera`)到[渲染器](`Renderer`)中,然后它会将摄像机视椎体中的三维场景渲染成一个二维图片显示在画布上。
+* 首先有一个[渲染器(`Renderer`)](Renderer)。这可以说是three.js的主要对象。你传入一个[场景(`Scene`)](Scene)和一个[摄像机(`Camera`)](Camera)到[渲染器(`Renderer`)](Renderer)中,然后它会将摄像机视椎体中的三维场景渲染成一个二维图片显示在画布上。
-* 其次有一个[场景图](threejs-scenegraph.html) 它是一个树状结构,由很多对象组成,比如图中包含了一个[场景](`Scene`)对象 ,多个[网格](`Mesh`)对象,[光源](`Light`)对象,[群组](`Group`),[三维物体](`Object3D`),和[摄像机](`Camera`)对象。一个[场景](`Scene`)对象定义了场景图最基本的要素,并包了含背景色和雾等属性。这些对象通过一个层级关系明确的树状结构来展示出各自的位置和方向。子对象的位置和方向总是相对于父对象而言的。比如说汽车的轮子是汽车的子对象,这样移动和定位汽车时就会自动移动轮子。你可以在[场景图](threejs-scenegraph.html)的这篇文章中了解更多内容。
+* 其次有一个[场景图](threejs-scenegraph.html) 它是一个树状结构,由很多对象组成,比如图中包含了一个[场景(`Scene`)](Scene)对象 ,多个[网格(`Mesh`)](Mesh)对象,[光源(`Light`)](Light)对象,[群组(`Group`)](Group),[三维物体(`Object3D`)](Object3D),和[摄像机(`Camera`)](Camera)对象。一个[场景(`Scene`)](Scene)对象定义了场景图最基本的要素,并包了含背景色和雾等属性。这些对象通过一个层级关系明确的树状结构来展示出各自的位置和方向。子对象的位置和方向总是相对于父对象而言的。比如说汽车的轮子是汽车的子对象,这样移动和定位汽车时就会自动移动轮子。你可以在[场景图](threejs-scenegraph.html)的这篇文章中了解更多内容。
- 注意图中[摄像机](`Camera`)是一半在场景图中,一半在场景图外的。这表示在three.js中,[摄像机](`Camera`)和其他对象不同的是,它不一定要在场景图中才能起作用。相同的是,[摄像机](`Camera`)作为其他对象的子对象,同样会继承它父对象的位置和朝向。在[场景图](threejs-scenegraph.html)这篇文章的结尾部分有放置多个[摄像机](`Camera`)在一个场景中的例子。
+ 注意图中[摄像机(`Camera`)](Camera)是一半在场景图中,一半在场景图外的。这表示在three.js中,[摄像机(`Camera`)](Camera)和其他对象不同的是,它不一定要在场景图中才能起作用。相同的是,[摄像机(`Camera`)](Camera)作为其他对象的子对象,同样会继承它父对象的位置和朝向。在[场景图](threejs-scenegraph.html)这篇文章的结尾部分有放置多个[摄像机(`Camera`)](Camera)在一个场景中的例子。
-* [网格](`Mesh`)对象可以理解为用一种特定的[材质](`Material`)来绘制的一个特定的[几何体](`Geometry`)。[材质](`Material`)和[几何体](`Geometry`)可以被多个[网格](`Mesh`)对象使用。比如在不同的位置画两个蓝色立方体,我们会需要两个[网格](`Mesh`)对象来代表每一个立方体的位置和方向。但只需一个[几何体](`Geometry`)来存放立方体的顶点数据,和一种[材质](`Material`)来定义立方体的颜色为蓝色就可以了。两个[网格](`Mesh`)对象都引用了相同的[几何体](`Geometry`)和[材质](`Material`)。
+* [网格(`Mesh`)](Mesh)对象可以理解为用一种特定的[材质(`Material`)](Material)来绘制的一个特定的[几何体(`Geometry`)](Geometry)。[材质(`Material`)](Material)和[几何体(`Geometry`)](Geometry)可以被多个[网格(`Mesh`)](Mesh)对象使用。比如在不同的位置画两个蓝色立方体,我们会需要两个[网格(`Mesh`)](Mesh)对象来代表每一个立方体的位置和方向。但只需一个[几何体(`Geometry`)](Geometry)来存放立方体的顶点数据,和一种[材质(`Material`)](Material)来定义立方体的颜色为蓝色就可以了。两个[网格(`Mesh`)](Mesh)对象都引用了相同的[几何体(`Geometry`)](Geometry)和[材质(`Material`)](Material)。
-* [几何体](`Geometry`)对象顾名思义代表一些几何体,如球体、立方体、平面、狗、猫、人、树、建筑等物体的顶点信息。Three.js内置了许多[基本几何体](threejs-primitives.html) 。你也可以[创建自定义几何体](threejs-custom-geometry.html)或[从文件中加载几何体](threejs-load-obj.html)。
+* [几何体(`Geometry`)](Geometry)对象顾名思义代表一些几何体,如球体、立方体、平面、狗、猫、人、树、建筑等物体的顶点信息。Three.js内置了许多[基本几何体](threejs-primitives.html) 。你也可以[创建自定义几何体](threejs-custom-geometry.html)或[从文件中加载几何体](threejs-load-obj.html)。
-* [材质](`Material`)对象代表[绘制几何体的表面属性](threejs-materials.html),包括使用的颜色,和光亮程度。一个[材质](`Material`)可以引用一个或多个[纹理](`Texture`),这些纹理可以用来,打个比方,将图像包裹到几何体的表面。
+* [材质(`Material`)](Material)对象代表[绘制几何体的表面属性](threejs-materials.html),包括使用的颜色,和光亮程度。一个[材质(`Material`)](Material)可以引用一个或多个[纹理(`Texture`)](Texture),这些纹理可以用来,打个比方,将图像包裹到几何体的表面。
-* [纹理](`Texture`)对象通常表示一幅要么[从文件中加载](threejs-textures.html),要么[在画布上生成](threejs-canvas-textures.html),要么[由另一个场景渲染出](threejs-rendertargets.html)的图像。
+* [纹理(`Texture`)](Texture)对象通常表示一幅要么[从文件中加载](threejs-textures.html),要么[在画布上生成](threejs-canvas-textures.html),要么[由另一个场景渲染出](threejs-rendertargets.html)的图像。
-* [光源](`Light`)对象代表[不同种类的光](threejs-lights.html)。
+* [光源(`Light`)](Light)对象代表[不同种类的光](threejs-lights.html)。
有了以上基本概念,我们接下来就来画个下图所示的*"Hello Cube"*吧。
@@ -80,11 +80,11 @@ import * as THREE from './resources/threejs/r122/build/three.module.js';
</script>
```
-拿到canvas后我们需要创建一个[WebGL渲染器](`WebGLRenderer`)。渲染器负责将你提供的所有数据渲染绘制到canvas上。之前还有其他渲染器,比如[CSS渲染器](`CSSRenderer`)、[Canvas渲染器](`CanvasRenderer`)。将来也可能会有[WebGL2渲染器](`WebGL2Renderer`)或[WebGPU渲染器](`WebGPURenderer`)。目前的话是[WebGL渲染器](`WebGLRenderer`),它通过WebGL将三维空间渲染到canvas上。
+拿到canvas后我们需要创建一个[WebGL渲染器(`WebGLRenderer`)](WebGLRenderer)。渲染器负责将你提供的所有数据渲染绘制到canvas上。之前还有其他渲染器,比如[CSS渲染器(`CSSRenderer`)](CSSRenderer)、[Canvas渲染器(`CanvasRenderer`)](CanvasRenderer)。将来也可能会有[WebGL2渲染器(`WebGL2Renderer`)](WebGL2Renderer)或[WebGPU渲染器(`WebGPURenderer`)](WebGPURenderer)。目前的话是[WebGL渲染器(`WebGLRenderer`)](WebGLRenderer),它通过WebGL将三维空间渲染到canvas上。
注意这里有一些细节。如果你没有给three.js传canvas,three.js会自己创建一个 ,但是你必须手动把它添加到文档中。在哪里添加可能会不一样这取决你怎么使用, 我发现给three.js传一个canvas会更灵活一些。我可以将canvas放到任何地方, 代码都会找到它,假如我有一段代码是将canvas插入到文档中,那么当需求变化时, 我很可能必须去修改这段代码。
-接下来我们需要一个[透视摄像机](`PerspectiveCamera`)。
+接下来我们需要一个[透视摄像机(`PerspectiveCamera`)](PerspectiveCamera)。
```js
const fov = 75;
@@ -123,13 +123,13 @@ camera.position.z = 2;
我们能看到摄像机的位置在`z = 2`。它朝向Z轴负方向。我们的视椎体范围从摄像机前方0.1到5。因为这张图是俯视图,视野范围会受到宽高比的影响。画布的宽度是高度的两倍,所以水平视角会比我们设置的垂直视角75度要大。
-然后我们创建一个[场景](`Scene`)。[场景](`Scene`)是three.js的基本的组成部分。需要three.js绘制的东西都需要加入到scene中。 我们将会在[场景是如何工作的](threejs-scenegraph.html)一文中详细讨论。
+然后我们创建一个[场景(`Scene`)](Scene)。[场景(`Scene`)](Scene)是three.js的基本的组成部分。需要three.js绘制的东西都需要加入到scene中。 我们将会在[场景是如何工作的](threejs-scenegraph.html)一文中详细讨论。
```js
const scene = new THREE.Scene();
```
-然后创建一个包含盒子信息的[立方几何体](`BoxGeometry`)。几乎所有希望在three.js中显示的物体都需要一个包含了组成三维物体的顶点信息的几何体。
+然后创建一个包含盒子信息的[立方几何体(`BoxGeometry`)](BoxGeometry)。几乎所有希望在three.js中显示的物体都需要一个包含了组成三维物体的顶点信息的几何体。
```js
const boxWidth = 1;
@@ -144,10 +144,10 @@ const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
const material = new THREE.MeshBasicMaterial({color: 0x44aa88});
```
-再创建一个[网格](`Mesh`)对象,它包含了:
+再创建一个[网格(`Mesh`)](Mesh)对象,它包含了:
-1. [几何体](`Geometry`)(物体的形状)
-2. [材质](`Material`)(如何绘制物体,光滑还是平整,什么颜色,什么贴图等等)
+1. [几何体(`Geometry`)](Geometry)(物体的形状)
+2. [材质(`Material`)](Material)(如何绘制物体,光滑还是平整,什么颜色,什么贴图等等)
3. 对象在场景中相对于他父对象的位置、朝向、和缩放。下面的代码中父对象即为场景对象。
```js
@@ -290,7 +290,7 @@ function render(time) {
<div class="threejs_center"><img src="resources/images/threejs-3cubes-scene.svg" style="width: 610px;"></div>
-正如你看见的那样,我们有三个[网格](`Mesh`)引用了相同的[立方几何体](`BoxGeometry`)。每个[网格](`Mesh`)引用了一个单独的`MeshPhongMaterial`材质来显示不同的颜色。
+正如你看见的那样,我们有三个[网格(`Mesh`)](Mesh)引用了相同的[立方几何体(`BoxGeometry`)](BoxGeometry)。每个[网格(`Mesh`)](Mesh)引用了一个单独的`MeshPhongMaterial`材质来显示不同的颜色。
希望这个简短的介绍能帮助你起步。[接下来我们将介绍如何使我们的代码具有响应性,从而使其能够适应多种情况](threejs-responsive.html).
| false |
Other | mrdoob | three.js | aacfe246634d71c2e2ba181225d41577392a6ab5.json | fix links at build time instead of run time | Gruntfile.js | @@ -11,6 +11,14 @@ const path = require('path');
const semver = require('semver');
const liveEditor = require('@gfxfundamentals/live-editor');
const liveEditorPath = path.dirname(require.resolve('@gfxfundamentals/live-editor'));
+const jsdom = require('jsdom');
+const {JSDOM} = jsdom;
+
+// make a fake window because jquery sucks
+const dom = new JSDOM('');
+global.window = dom.window;
+global.document = global.window.document;
+const jquery = require('jquery');
module.exports = function(grunt) {
@@ -126,6 +134,337 @@ module.exports = function(grunt) {
onChange();
});
+ function fixThreeJSLinks(html) {
+ const supportedLangs = {
+ 'en': true,
+ 'zh': true,
+ };
+
+ /*
+ const dom = new JSDOM(html, {
+ //url: "https://example.org/",
+ //referrer: "https://example.com/",
+ //contentType: "text/html",
+ });
+ global.window = dom.window;
+ global.document = dom.window.document;f
+ */
+ global.document.open('text/html', 'replace');
+ global.document.write(html);
+ global.document.close();
+ const $ = jquery;
+
+ function insertLang(codeKeywordLinks) {
+ const lang = document.documentElement.lang.substr(0, 2).toLowerCase();
+ const langPart = `#api/${supportedLangs[lang] ? lang : 'en'}/`;
+ const langAddedLinks = {};
+ for (const [keyword, url] of Object.entries(codeKeywordLinks)) {
+ langAddedLinks[keyword] = url.replace('#api/', langPart);
+ }
+ return langAddedLinks;
+ }
+
+ const codeKeywordLinks = insertLang({
+ AnimationAction: 'https://threejs.org/docs/#api/animation/AnimationAction',
+ AnimationClip: 'https://threejs.org/docs/#api/animation/AnimationClip',
+ AnimationMixer: 'https://threejs.org/docs/#api/animation/AnimationMixer',
+ AnimationObjectGroup: 'https://threejs.org/docs/#api/animation/AnimationObjectGroup',
+ AnimationUtils: 'https://threejs.org/docs/#api/animation/AnimationUtils',
+ KeyframeTrack: 'https://threejs.org/docs/#api/animation/KeyframeTrack',
+ PropertyBinding: 'https://threejs.org/docs/#api/animation/PropertyBinding',
+ PropertyMixer: 'https://threejs.org/docs/#api/animation/PropertyMixer',
+ BooleanKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/BooleanKeyframeTrack',
+ ColorKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/ColorKeyframeTrack',
+ NumberKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/NumberKeyframeTrack',
+ QuaternionKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/QuaternionKeyframeTrack',
+ StringKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/StringKeyframeTrack',
+ VectorKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/VectorKeyframeTrack',
+ Audio: 'https://threejs.org/docs/#api/audio/Audio',
+ AudioAnalyser: 'https://threejs.org/docs/#api/audio/AudioAnalyser',
+ AudioContext: 'https://threejs.org/docs/#api/audio/AudioContext',
+ AudioListener: 'https://threejs.org/docs/#api/audio/AudioListener',
+ PositionalAudio: 'https://threejs.org/docs/#api/audio/PositionalAudio',
+ ArrayCamera: 'https://threejs.org/docs/#api/cameras/ArrayCamera',
+ Camera: 'https://threejs.org/docs/#api/cameras/Camera',
+ CubeCamera: 'https://threejs.org/docs/#api/cameras/CubeCamera',
+ OrthographicCamera: 'https://threejs.org/docs/#api/cameras/OrthographicCamera',
+ PerspectiveCamera: 'https://threejs.org/docs/#api/cameras/PerspectiveCamera',
+ StereoCamera: 'https://threejs.org/docs/#api/cameras/StereoCamera',
+ Animation: 'https://threejs.org/docs/#api/constants/Animation',
+ Core: 'https://threejs.org/docs/#api/constants/Core',
+ CustomBlendingEquation: 'https://threejs.org/docs/#api/constants/CustomBlendingEquations',
+ DrawModes: 'https://threejs.org/docs/#api/constants/DrawModes',
+ Materials: 'https://threejs.org/docs/#api/constants/Materials',
+ Renderer: 'https://threejs.org/docs/#api/constants/Renderer',
+ Textures: 'https://threejs.org/docs/#api/constants/Textures',
+ BufferAttribute: 'https://threejs.org/docs/#api/core/BufferAttribute',
+ BufferGeometry: 'https://threejs.org/docs/#api/core/BufferGeometry',
+ Clock: 'https://threejs.org/docs/#api/core/Clock',
+ DirectGeometry: 'https://threejs.org/docs/#api/core/DirectGeometry',
+ EventDispatcher: 'https://threejs.org/docs/#api/core/EventDispatcher',
+ Face3: 'https://threejs.org/docs/#api/core/Face3',
+ Geometry: 'https://threejs.org/docs/#api/core/Geometry',
+ InstancedBufferAttribute: 'https://threejs.org/docs/#api/core/InstancedBufferAttribute',
+ InstancedBufferGeometry: 'https://threejs.org/docs/#api/core/InstancedBufferGeometry',
+ InstancedInterleavedBuffer: 'https://threejs.org/docs/#api/core/InstancedInterleavedBuffer',
+ InterleavedBuffer: 'https://threejs.org/docs/#api/core/InterleavedBuffer',
+ InterleavedBufferAttribute: 'https://threejs.org/docs/#api/core/InterleavedBufferAttribute',
+ Layers: 'https://threejs.org/docs/#api/core/Layers',
+ Object3D: 'https://threejs.org/docs/#api/core/Object3D',
+ Raycaster: 'https://threejs.org/docs/#api/core/Raycaster',
+ Uniform: 'https://threejs.org/docs/#api/core/Uniform',
+ BufferAttributeTypes: 'https://threejs.org/docs/#api/core/bufferAttributeTypes/BufferAttributeTypes',
+ Earcut: 'https://threejs.org/docs/#api/extras/Earcut',
+ ShapeUtils: 'https://threejs.org/docs/#api/extras/ShapeUtils',
+ Curve: 'https://threejs.org/docs/#api/extras/core/Curve',
+ CurvePath: 'https://threejs.org/docs/#api/extras/core/CurvePath',
+ Font: 'https://threejs.org/docs/#api/extras/core/Font',
+ Interpolations: 'https://threejs.org/docs/#api/extras/core/Interpolations',
+ Path: 'https://threejs.org/docs/#api/extras/core/Path',
+ Shape: 'https://threejs.org/docs/#api/extras/core/Shape',
+ ShapePath: 'https://threejs.org/docs/#api/extras/core/ShapePath',
+ ArcCurve: 'https://threejs.org/docs/#api/extras/curves/ArcCurve',
+ CatmullRomCurve3: 'https://threejs.org/docs/#api/extras/curves/CatmullRomCurve3',
+ CubicBezierCurve: 'https://threejs.org/docs/#api/extras/curves/CubicBezierCurve',
+ CubicBezierCurve3: 'https://threejs.org/docs/#api/extras/curves/CubicBezierCurve3',
+ EllipseCurve: 'https://threejs.org/docs/#api/extras/curves/EllipseCurve',
+ LineCurve: 'https://threejs.org/docs/#api/extras/curves/LineCurve',
+ LineCurve3: 'https://threejs.org/docs/#api/extras/curves/LineCurve3',
+ QuadraticBezierCurve: 'https://threejs.org/docs/#api/extras/curves/QuadraticBezierCurve',
+ QuadraticBezierCurve3: 'https://threejs.org/docs/#api/extras/curves/QuadraticBezierCurve3',
+ SplineCurve: 'https://threejs.org/docs/#api/extras/curves/SplineCurve',
+ ImmediateRenderObject: 'https://threejs.org/docs/#api/extras/objects/ImmediateRenderObject',
+ BoxBufferGeometry: 'https://threejs.org/docs/#api/geometries/BoxBufferGeometry',
+ BoxGeometry: 'https://threejs.org/docs/#api/geometries/BoxGeometry',
+ CircleBufferGeometry: 'https://threejs.org/docs/#api/geometries/CircleBufferGeometry',
+ CircleGeometry: 'https://threejs.org/docs/#api/geometries/CircleGeometry',
+ ConeBufferGeometry: 'https://threejs.org/docs/#api/geometries/ConeBufferGeometry',
+ ConeGeometry: 'https://threejs.org/docs/#api/geometries/ConeGeometry',
+ CylinderBufferGeometry: 'https://threejs.org/docs/#api/geometries/CylinderBufferGeometry',
+ CylinderGeometry: 'https://threejs.org/docs/#api/geometries/CylinderGeometry',
+ DodecahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/DodecahedronBufferGeometry',
+ DodecahedronGeometry: 'https://threejs.org/docs/#api/geometries/DodecahedronGeometry',
+ EdgesGeometry: 'https://threejs.org/docs/#api/geometries/EdgesGeometry',
+ ExtrudeBufferGeometry: 'https://threejs.org/docs/#api/geometries/ExtrudeBufferGeometry',
+ ExtrudeGeometry: 'https://threejs.org/docs/#api/geometries/ExtrudeGeometry',
+ IcosahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/IcosahedronBufferGeometry',
+ IcosahedronGeometry: 'https://threejs.org/docs/#api/geometries/IcosahedronGeometry',
+ LatheBufferGeometry: 'https://threejs.org/docs/#api/geometries/LatheBufferGeometry',
+ LatheGeometry: 'https://threejs.org/docs/#api/geometries/LatheGeometry',
+ OctahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/OctahedronBufferGeometry',
+ OctahedronGeometry: 'https://threejs.org/docs/#api/geometries/OctahedronGeometry',
+ ParametricBufferGeometry: 'https://threejs.org/docs/#api/geometries/ParametricBufferGeometry',
+ ParametricGeometry: 'https://threejs.org/docs/#api/geometries/ParametricGeometry',
+ PlaneBufferGeometry: 'https://threejs.org/docs/#api/geometries/PlaneBufferGeometry',
+ PlaneGeometry: 'https://threejs.org/docs/#api/geometries/PlaneGeometry',
+ PolyhedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/PolyhedronBufferGeometry',
+ PolyhedronGeometry: 'https://threejs.org/docs/#api/geometries/PolyhedronGeometry',
+ RingBufferGeometry: 'https://threejs.org/docs/#api/geometries/RingBufferGeometry',
+ RingGeometry: 'https://threejs.org/docs/#api/geometries/RingGeometry',
+ ShapeBufferGeometry: 'https://threejs.org/docs/#api/geometries/ShapeBufferGeometry',
+ ShapeGeometry: 'https://threejs.org/docs/#api/geometries/ShapeGeometry',
+ SphereBufferGeometry: 'https://threejs.org/docs/#api/geometries/SphereBufferGeometry',
+ SphereGeometry: 'https://threejs.org/docs/#api/geometries/SphereGeometry',
+ TetrahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/TetrahedronBufferGeometry',
+ TetrahedronGeometry: 'https://threejs.org/docs/#api/geometries/TetrahedronGeometry',
+ TextBufferGeometry: 'https://threejs.org/docs/#api/geometries/TextBufferGeometry',
+ TextGeometry: 'https://threejs.org/docs/#api/geometries/TextGeometry',
+ TorusBufferGeometry: 'https://threejs.org/docs/#api/geometries/TorusBufferGeometry',
+ TorusGeometry: 'https://threejs.org/docs/#api/geometries/TorusGeometry',
+ TorusKnotBufferGeometry: 'https://threejs.org/docs/#api/geometries/TorusKnotBufferGeometry',
+ TorusKnotGeometry: 'https://threejs.org/docs/#api/geometries/TorusKnotGeometry',
+ TubeBufferGeometry: 'https://threejs.org/docs/#api/geometries/TubeBufferGeometry',
+ TubeGeometry: 'https://threejs.org/docs/#api/geometries/TubeGeometry',
+ WireframeGeometry: 'https://threejs.org/docs/#api/geometries/WireframeGeometry',
+ ArrowHelper: 'https://threejs.org/docs/#api/helpers/ArrowHelper',
+ AxesHelper: 'https://threejs.org/docs/#api/helpers/AxesHelper',
+ BoxHelper: 'https://threejs.org/docs/#api/helpers/BoxHelper',
+ Box3Helper: 'https://threejs.org/docs/#api/helpers/Box3Helper',
+ CameraHelper: 'https://threejs.org/docs/#api/helpers/CameraHelper',
+ DirectionalLightHelper: 'https://threejs.org/docs/#api/helpers/DirectionalLightHelper',
+ FaceNormalsHelper: 'https://threejs.org/docs/#api/helpers/FaceNormalsHelper',
+ GridHelper: 'https://threejs.org/docs/#api/helpers/GridHelper',
+ PolarGridHelper: 'https://threejs.org/docs/#api/helpers/PolarGridHelper',
+ HemisphereLightHelper: 'https://threejs.org/docs/#api/helpers/HemisphereLightHelper',
+ PlaneHelper: 'https://threejs.org/docs/#api/helpers/PlaneHelper',
+ PointLightHelper: 'https://threejs.org/docs/#api/helpers/PointLightHelper',
+ RectAreaLightHelper: 'https://threejs.org/docs/#api/helpers/RectAreaLightHelper',
+ SkeletonHelper: 'https://threejs.org/docs/#api/helpers/SkeletonHelper',
+ SpotLightHelper: 'https://threejs.org/docs/#api/helpers/SpotLightHelper',
+ VertexNormalsHelper: 'https://threejs.org/docs/#api/helpers/VertexNormalsHelper',
+ AmbientLight: 'https://threejs.org/docs/#api/lights/AmbientLight',
+ DirectionalLight: 'https://threejs.org/docs/#api/lights/DirectionalLight',
+ HemisphereLight: 'https://threejs.org/docs/#api/lights/HemisphereLight',
+ Light: 'https://threejs.org/docs/#api/lights/Light',
+ PointLight: 'https://threejs.org/docs/#api/lights/PointLight',
+ RectAreaLight: 'https://threejs.org/docs/#api/lights/RectAreaLight',
+ SpotLight: 'https://threejs.org/docs/#api/lights/SpotLight',
+ DirectionalLightShadow: 'https://threejs.org/docs/#api/lights/shadows/DirectionalLightShadow',
+ LightShadow: 'https://threejs.org/docs/#api/lights/shadows/LightShadow',
+ SpotLightShadow: 'https://threejs.org/docs/#api/lights/shadows/SpotLightShadow',
+ AnimationLoader: 'https://threejs.org/docs/#api/loaders/AnimationLoader',
+ AudioLoader: 'https://threejs.org/docs/#api/loaders/AudioLoader',
+ BufferGeometryLoader: 'https://threejs.org/docs/#api/loaders/BufferGeometryLoader',
+ Cache: 'https://threejs.org/docs/#api/loaders/Cache',
+ CompressedTextureLoader: 'https://threejs.org/docs/#api/loaders/CompressedTextureLoader',
+ CubeTextureLoader: 'https://threejs.org/docs/#api/loaders/CubeTextureLoader',
+ DataTextureLoader: 'https://threejs.org/docs/#api/loaders/DataTextureLoader',
+ FileLoader: 'https://threejs.org/docs/#api/loaders/FileLoader',
+ FontLoader: 'https://threejs.org/docs/#api/loaders/FontLoader',
+ ImageBitmapLoader: 'https://threejs.org/docs/#api/loaders/ImageBitmapLoader',
+ ImageLoader: 'https://threejs.org/docs/#api/loaders/ImageLoader',
+ JSONLoader: 'https://threejs.org/docs/#api/loaders/JSONLoader',
+ Loader: 'https://threejs.org/docs/#api/loaders/Loader',
+ LoaderUtils: 'https://threejs.org/docs/#api/loaders/LoaderUtils',
+ MaterialLoader: 'https://threejs.org/docs/#api/loaders/MaterialLoader',
+ ObjectLoader: 'https://threejs.org/docs/#api/loaders/ObjectLoader',
+ TextureLoader: 'https://threejs.org/docs/#api/loaders/TextureLoader',
+ DefaultLoadingManager: 'https://threejs.org/docs/#api/loaders/managers/DefaultLoadingManager',
+ LoadingManager: 'https://threejs.org/docs/#api/loaders/managers/LoadingManager',
+ LineBasicMaterial: 'https://threejs.org/docs/#api/materials/LineBasicMaterial',
+ LineDashedMaterial: 'https://threejs.org/docs/#api/materials/LineDashedMaterial',
+ Material: 'https://threejs.org/docs/#api/materials/Material',
+ MeshBasicMaterial: 'https://threejs.org/docs/#api/materials/MeshBasicMaterial',
+ MeshDepthMaterial: 'https://threejs.org/docs/#api/materials/MeshDepthMaterial',
+ MeshLambertMaterial: 'https://threejs.org/docs/#api/materials/MeshLambertMaterial',
+ MeshNormalMaterial: 'https://threejs.org/docs/#api/materials/MeshNormalMaterial',
+ MeshPhongMaterial: 'https://threejs.org/docs/#api/materials/MeshPhongMaterial',
+ MeshPhysicalMaterial: 'https://threejs.org/docs/#api/materials/MeshPhysicalMaterial',
+ MeshStandardMaterial: 'https://threejs.org/docs/#api/materials/MeshStandardMaterial',
+ MeshToonMaterial: 'https://threejs.org/docs/#api/materials/MeshToonMaterial',
+ PointsMaterial: 'https://threejs.org/docs/#api/materials/PointsMaterial',
+ RawShaderMaterial: 'https://threejs.org/docs/#api/materials/RawShaderMaterial',
+ ShaderMaterial: 'https://threejs.org/docs/#api/materials/ShaderMaterial',
+ ShadowMaterial: 'https://threejs.org/docs/#api/materials/ShadowMaterial',
+ SpriteMaterial: 'https://threejs.org/docs/#api/materials/SpriteMaterial',
+ Box2: 'https://threejs.org/docs/#api/math/Box2',
+ Box3: 'https://threejs.org/docs/#api/math/Box3',
+ Color: 'https://threejs.org/docs/#api/math/Color',
+ Cylindrical: 'https://threejs.org/docs/#api/math/Cylindrical',
+ Euler: 'https://threejs.org/docs/#api/math/Euler',
+ Frustum: 'https://threejs.org/docs/#api/math/Frustum',
+ Interpolant: 'https://threejs.org/docs/#api/math/Interpolant',
+ Line3: 'https://threejs.org/docs/#api/math/Line3',
+ Math: 'https://threejs.org/docs/#api/math/Math',
+ Matrix3: 'https://threejs.org/docs/#api/math/Matrix3',
+ Matrix4: 'https://threejs.org/docs/#api/math/Matrix4',
+ Plane: 'https://threejs.org/docs/#api/math/Plane',
+ Quaternion: 'https://threejs.org/docs/#api/math/Quaternion',
+ Ray: 'https://threejs.org/docs/#api/math/Ray',
+ Sphere: 'https://threejs.org/docs/#api/math/Sphere',
+ Spherical: 'https://threejs.org/docs/#api/math/Spherical',
+ Triangle: 'https://threejs.org/docs/#api/math/Triangle',
+ Vector2: 'https://threejs.org/docs/#api/math/Vector2',
+ Vector3: 'https://threejs.org/docs/#api/math/Vector3',
+ Vector4: 'https://threejs.org/docs/#api/math/Vector4',
+ CubicInterpolant: 'https://threejs.org/docs/#api/math/interpolants/CubicInterpolant',
+ DiscreteInterpolant: 'https://threejs.org/docs/#api/math/interpolants/DiscreteInterpolant',
+ LinearInterpolant: 'https://threejs.org/docs/#api/math/interpolants/LinearInterpolant',
+ QuaternionLinearInterpolant: 'https://threejs.org/docs/#api/math/interpolants/QuaternionLinearInterpolant',
+ Bone: 'https://threejs.org/docs/#api/objects/Bone',
+ Group: 'https://threejs.org/docs/#api/objects/Group',
+ Line: 'https://threejs.org/docs/#api/objects/Line',
+ LineLoop: 'https://threejs.org/docs/#api/objects/LineLoop',
+ LineSegments: 'https://threejs.org/docs/#api/objects/LineSegments',
+ LOD: 'https://threejs.org/docs/#api/objects/LOD',
+ Mesh: 'https://threejs.org/docs/#api/objects/Mesh',
+ Points: 'https://threejs.org/docs/#api/objects/Points',
+ Skeleton: 'https://threejs.org/docs/#api/objects/Skeleton',
+ SkinnedMesh: 'https://threejs.org/docs/#api/objects/SkinnedMesh',
+ Sprite: 'https://threejs.org/docs/#api/objects/Sprite',
+ WebGLRenderer: 'https://threejs.org/docs/#api/renderers/WebGLRenderer',
+ WebGLRenderTarget: 'https://threejs.org/docs/#api/renderers/WebGLRenderTarget',
+ WebGLCubeRenderTarget: 'https://threejs.org/docs/#api/renderers/WebGLCubeRenderTarget',
+ ShaderChunk: 'https://threejs.org/docs/#api/renderers/shaders/ShaderChunk',
+ ShaderLib: 'https://threejs.org/docs/#api/renderers/shaders/ShaderLib',
+ UniformsLib: 'https://threejs.org/docs/#api/renderers/shaders/UniformsLib',
+ UniformsUtils: 'https://threejs.org/docs/#api/renderers/shaders/UniformsUtils',
+ Fog: 'https://threejs.org/docs/#api/scenes/Fog',
+ FogExp2: 'https://threejs.org/docs/#api/scenes/FogExp2',
+ Scene: 'https://threejs.org/docs/#api/scenes/Scene',
+ CanvasTexture: 'https://threejs.org/docs/#api/textures/CanvasTexture',
+ CompressedTexture: 'https://threejs.org/docs/#api/textures/CompressedTexture',
+ CubeTexture: 'https://threejs.org/docs/#api/textures/CubeTexture',
+ DataTexture: 'https://threejs.org/docs/#api/textures/DataTexture',
+ DepthTexture: 'https://threejs.org/docs/#api/textures/DepthTexture',
+ Texture: 'https://threejs.org/docs/#api/textures/Texture',
+ VideoTexture: 'https://threejs.org/docs/#api/textures/VideoTexture',
+ CCDIKSolver: 'https://threejs.org/docs/#examples/animations/CCDIKSolver',
+ MMDAnimationHelper: 'https://threejs.org/docs/#examples/animations/MMDAnimationHelper',
+ MMDPhysics: 'https://threejs.org/docs/#examples/animations/MMDPhysics',
+ OrbitControls: 'https://threejs.org/docs/#examples/controls/OrbitControls',
+ ConvexBufferGeometry: 'https://threejs.org/docs/#examples/geometries/ConvexBufferGeometry',
+ ConvexGeometry: 'https://threejs.org/docs/#examples/geometries/ConvexGeometry',
+ DecalGeometry: 'https://threejs.org/docs/#examples/geometries/DecalGeometry',
+ BabylonLoader: 'https://threejs.org/docs/#examples/loaders/BabylonLoader',
+ GLTFLoader: 'https://threejs.org/docs/#examples/loaders/GLTFLoader',
+ MMDLoader: 'https://threejs.org/docs/#examples/loaders/MMDLoader',
+ MTLLoader: 'https://threejs.org/docs/#examples/loaders/MTLLoader',
+ OBJLoader: 'https://threejs.org/docs/#examples/loaders/OBJLoader',
+ OBJLoader2: 'https://threejs.org/docs/#examples/loaders/OBJLoader2',
+ LoaderSupport: 'https://threejs.org/docs/#examples/loaders/LoaderSupport',
+ PCDLoader: 'https://threejs.org/docs/#examples/loaders/PCDLoader',
+ PDBLoader: 'https://threejs.org/docs/#examples/loaders/PDBLoader',
+ SVGLoader: 'https://threejs.org/docs/#examples/loaders/SVGLoader',
+ TGALoader: 'https://threejs.org/docs/#examples/loaders/TGALoader',
+ PRWMLoader: 'https://threejs.org/docs/#examples/loaders/PRWMLoader',
+ Lensflare: 'https://threejs.org/docs/#examples/objects/Lensflare',
+ GLTFExporter: 'https://threejs.org/docs/#examples/exporters/GLTFExporter',
+ });
+
+ function getKeywordLink(keyword) {
+ const dotNdx = keyword.indexOf('.');
+ if (dotNdx) {
+ const before = keyword.substring(0, dotNdx);
+ const link = codeKeywordLinks[before];
+ if (link) {
+ return `${link}.${keyword.substr(dotNdx + 1)}`;
+ }
+ }
+ return keyword.startsWith('THREE.')
+ ? codeKeywordLinks[keyword.substring(6)]
+ : codeKeywordLinks[keyword];
+ }
+
+ $('code').filter(function() {
+ return getKeywordLink(this.textContent) &&
+ this.parentElement.nodeName !== 'A';
+ }).wrap(function() {
+ const a = document.createElement('a');
+ a.href = getKeywordLink(this.textContent);
+ return a;
+ });
+
+ const methodPropertyRE = /^(\w+)\.(\w+)$/;
+ const classRE = /^(\w+)$/;
+ $('a').each(function() {
+ const href = this.getAttribute('href');
+ if (!href) {
+ return;
+ }
+ const m = methodPropertyRE.exec(href);
+ if (m) {
+ const codeKeywordLink = getKeywordLink(m[1]);
+ if (codeKeywordLink) {
+ this.setAttribute('href', `${codeKeywordLink}#${m[2]}`);
+ }
+ } else if (classRE.test(href)) {
+ const codeKeywordLink = getKeywordLink(href);
+ if (codeKeywordLink) {
+ this.setAttribute('href', codeKeywordLink);
+ }
+ }
+ });
+
+ $('pre>code')
+ .unwrap()
+ .replaceWith(function() {
+ return $(`<pre class="prettyprint showlinemods notranslate ${this.className || ''}" translate="no">${this.innerHTML}</pre>`);
+ });
+
+ return dom.serialize();
+ }
+
const buildSettings = {
outDir: 'out',
baseUrl: 'https://threejsfundamentals.org',
@@ -161,6 +500,7 @@ module.exports = function(grunt) {
},
],
},
+ postHTMLFn: fixThreeJSLinks,
};
// just the hackiest way to get this working. | true |
Other | mrdoob | three.js | aacfe246634d71c2e2ba181225d41577392a6ab5.json | fix links at build time instead of run time | threejs/lessons/resources/lesson.js | @@ -38,345 +38,6 @@ function showContributors() {
showContributors();
$(document).ready(function($){
- const supportedLangs = {
- 'en': true,
- 'zh': true,
- };
-
- function insertLang(codeKeywordLinks) {
- const lang = document.documentElement.lang.substr(0, 2).toLowerCase();
- const langPart = `#api/${supportedLangs[lang] ? lang : 'en'}/`;
- const langAddedLinks = {};
- for (const [keyword, url] of Object.entries(codeKeywordLinks)) {
- langAddedLinks[keyword] = url.replace('#api/', langPart);
- }
- return langAddedLinks;
- }
-
- const codeKeywordLinks = insertLang({
- AnimationAction: 'https://threejs.org/docs/#api/animation/AnimationAction',
- AnimationClip: 'https://threejs.org/docs/#api/animation/AnimationClip',
- AnimationMixer: 'https://threejs.org/docs/#api/animation/AnimationMixer',
- AnimationObjectGroup: 'https://threejs.org/docs/#api/animation/AnimationObjectGroup',
- AnimationUtils: 'https://threejs.org/docs/#api/animation/AnimationUtils',
- KeyframeTrack: 'https://threejs.org/docs/#api/animation/KeyframeTrack',
- PropertyBinding: 'https://threejs.org/docs/#api/animation/PropertyBinding',
- PropertyMixer: 'https://threejs.org/docs/#api/animation/PropertyMixer',
- BooleanKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/BooleanKeyframeTrack',
- ColorKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/ColorKeyframeTrack',
- NumberKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/NumberKeyframeTrack',
- QuaternionKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/QuaternionKeyframeTrack',
- StringKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/StringKeyframeTrack',
- VectorKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/VectorKeyframeTrack',
- Audio: 'https://threejs.org/docs/#api/audio/Audio',
- AudioAnalyser: 'https://threejs.org/docs/#api/audio/AudioAnalyser',
- AudioContext: 'https://threejs.org/docs/#api/audio/AudioContext',
- AudioListener: 'https://threejs.org/docs/#api/audio/AudioListener',
- PositionalAudio: 'https://threejs.org/docs/#api/audio/PositionalAudio',
- ArrayCamera: 'https://threejs.org/docs/#api/cameras/ArrayCamera',
- Camera: 'https://threejs.org/docs/#api/cameras/Camera',
- CubeCamera: 'https://threejs.org/docs/#api/cameras/CubeCamera',
- OrthographicCamera: 'https://threejs.org/docs/#api/cameras/OrthographicCamera',
- PerspectiveCamera: 'https://threejs.org/docs/#api/cameras/PerspectiveCamera',
- StereoCamera: 'https://threejs.org/docs/#api/cameras/StereoCamera',
- Animation: 'https://threejs.org/docs/#api/constants/Animation',
- Core: 'https://threejs.org/docs/#api/constants/Core',
- CustomBlendingEquation: 'https://threejs.org/docs/#api/constants/CustomBlendingEquations',
- DrawModes: 'https://threejs.org/docs/#api/constants/DrawModes',
- Materials: 'https://threejs.org/docs/#api/constants/Materials',
- Renderer: 'https://threejs.org/docs/#api/constants/Renderer',
- Textures: 'https://threejs.org/docs/#api/constants/Textures',
- BufferAttribute: 'https://threejs.org/docs/#api/core/BufferAttribute',
- BufferGeometry: 'https://threejs.org/docs/#api/core/BufferGeometry',
- Clock: 'https://threejs.org/docs/#api/core/Clock',
- DirectGeometry: 'https://threejs.org/docs/#api/core/DirectGeometry',
- EventDispatcher: 'https://threejs.org/docs/#api/core/EventDispatcher',
- Face3: 'https://threejs.org/docs/#api/core/Face3',
- Geometry: 'https://threejs.org/docs/#api/core/Geometry',
- InstancedBufferAttribute: 'https://threejs.org/docs/#api/core/InstancedBufferAttribute',
- InstancedBufferGeometry: 'https://threejs.org/docs/#api/core/InstancedBufferGeometry',
- InstancedInterleavedBuffer: 'https://threejs.org/docs/#api/core/InstancedInterleavedBuffer',
- InterleavedBuffer: 'https://threejs.org/docs/#api/core/InterleavedBuffer',
- InterleavedBufferAttribute: 'https://threejs.org/docs/#api/core/InterleavedBufferAttribute',
- Layers: 'https://threejs.org/docs/#api/core/Layers',
- Object3D: 'https://threejs.org/docs/#api/core/Object3D',
- Raycaster: 'https://threejs.org/docs/#api/core/Raycaster',
- Uniform: 'https://threejs.org/docs/#api/core/Uniform',
- BufferAttributeTypes: 'https://threejs.org/docs/#api/core/bufferAttributeTypes/BufferAttributeTypes',
- Earcut: 'https://threejs.org/docs/#api/extras/Earcut',
- ShapeUtils: 'https://threejs.org/docs/#api/extras/ShapeUtils',
- Curve: 'https://threejs.org/docs/#api/extras/core/Curve',
- CurvePath: 'https://threejs.org/docs/#api/extras/core/CurvePath',
- Font: 'https://threejs.org/docs/#api/extras/core/Font',
- Interpolations: 'https://threejs.org/docs/#api/extras/core/Interpolations',
- Path: 'https://threejs.org/docs/#api/extras/core/Path',
- Shape: 'https://threejs.org/docs/#api/extras/core/Shape',
- ShapePath: 'https://threejs.org/docs/#api/extras/core/ShapePath',
- ArcCurve: 'https://threejs.org/docs/#api/extras/curves/ArcCurve',
- CatmullRomCurve3: 'https://threejs.org/docs/#api/extras/curves/CatmullRomCurve3',
- CubicBezierCurve: 'https://threejs.org/docs/#api/extras/curves/CubicBezierCurve',
- CubicBezierCurve3: 'https://threejs.org/docs/#api/extras/curves/CubicBezierCurve3',
- EllipseCurve: 'https://threejs.org/docs/#api/extras/curves/EllipseCurve',
- LineCurve: 'https://threejs.org/docs/#api/extras/curves/LineCurve',
- LineCurve3: 'https://threejs.org/docs/#api/extras/curves/LineCurve3',
- QuadraticBezierCurve: 'https://threejs.org/docs/#api/extras/curves/QuadraticBezierCurve',
- QuadraticBezierCurve3: 'https://threejs.org/docs/#api/extras/curves/QuadraticBezierCurve3',
- SplineCurve: 'https://threejs.org/docs/#api/extras/curves/SplineCurve',
- ImmediateRenderObject: 'https://threejs.org/docs/#api/extras/objects/ImmediateRenderObject',
- BoxBufferGeometry: 'https://threejs.org/docs/#api/geometries/BoxBufferGeometry',
- BoxGeometry: 'https://threejs.org/docs/#api/geometries/BoxGeometry',
- CircleBufferGeometry: 'https://threejs.org/docs/#api/geometries/CircleBufferGeometry',
- CircleGeometry: 'https://threejs.org/docs/#api/geometries/CircleGeometry',
- ConeBufferGeometry: 'https://threejs.org/docs/#api/geometries/ConeBufferGeometry',
- ConeGeometry: 'https://threejs.org/docs/#api/geometries/ConeGeometry',
- CylinderBufferGeometry: 'https://threejs.org/docs/#api/geometries/CylinderBufferGeometry',
- CylinderGeometry: 'https://threejs.org/docs/#api/geometries/CylinderGeometry',
- DodecahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/DodecahedronBufferGeometry',
- DodecahedronGeometry: 'https://threejs.org/docs/#api/geometries/DodecahedronGeometry',
- EdgesGeometry: 'https://threejs.org/docs/#api/geometries/EdgesGeometry',
- ExtrudeBufferGeometry: 'https://threejs.org/docs/#api/geometries/ExtrudeBufferGeometry',
- ExtrudeGeometry: 'https://threejs.org/docs/#api/geometries/ExtrudeGeometry',
- IcosahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/IcosahedronBufferGeometry',
- IcosahedronGeometry: 'https://threejs.org/docs/#api/geometries/IcosahedronGeometry',
- LatheBufferGeometry: 'https://threejs.org/docs/#api/geometries/LatheBufferGeometry',
- LatheGeometry: 'https://threejs.org/docs/#api/geometries/LatheGeometry',
- OctahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/OctahedronBufferGeometry',
- OctahedronGeometry: 'https://threejs.org/docs/#api/geometries/OctahedronGeometry',
- ParametricBufferGeometry: 'https://threejs.org/docs/#api/geometries/ParametricBufferGeometry',
- ParametricGeometry: 'https://threejs.org/docs/#api/geometries/ParametricGeometry',
- PlaneBufferGeometry: 'https://threejs.org/docs/#api/geometries/PlaneBufferGeometry',
- PlaneGeometry: 'https://threejs.org/docs/#api/geometries/PlaneGeometry',
- PolyhedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/PolyhedronBufferGeometry',
- PolyhedronGeometry: 'https://threejs.org/docs/#api/geometries/PolyhedronGeometry',
- RingBufferGeometry: 'https://threejs.org/docs/#api/geometries/RingBufferGeometry',
- RingGeometry: 'https://threejs.org/docs/#api/geometries/RingGeometry',
- ShapeBufferGeometry: 'https://threejs.org/docs/#api/geometries/ShapeBufferGeometry',
- ShapeGeometry: 'https://threejs.org/docs/#api/geometries/ShapeGeometry',
- SphereBufferGeometry: 'https://threejs.org/docs/#api/geometries/SphereBufferGeometry',
- SphereGeometry: 'https://threejs.org/docs/#api/geometries/SphereGeometry',
- TetrahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/TetrahedronBufferGeometry',
- TetrahedronGeometry: 'https://threejs.org/docs/#api/geometries/TetrahedronGeometry',
- TextBufferGeometry: 'https://threejs.org/docs/#api/geometries/TextBufferGeometry',
- TextGeometry: 'https://threejs.org/docs/#api/geometries/TextGeometry',
- TorusBufferGeometry: 'https://threejs.org/docs/#api/geometries/TorusBufferGeometry',
- TorusGeometry: 'https://threejs.org/docs/#api/geometries/TorusGeometry',
- TorusKnotBufferGeometry: 'https://threejs.org/docs/#api/geometries/TorusKnotBufferGeometry',
- TorusKnotGeometry: 'https://threejs.org/docs/#api/geometries/TorusKnotGeometry',
- TubeBufferGeometry: 'https://threejs.org/docs/#api/geometries/TubeBufferGeometry',
- TubeGeometry: 'https://threejs.org/docs/#api/geometries/TubeGeometry',
- WireframeGeometry: 'https://threejs.org/docs/#api/geometries/WireframeGeometry',
- ArrowHelper: 'https://threejs.org/docs/#api/helpers/ArrowHelper',
- AxesHelper: 'https://threejs.org/docs/#api/helpers/AxesHelper',
- BoxHelper: 'https://threejs.org/docs/#api/helpers/BoxHelper',
- Box3Helper: 'https://threejs.org/docs/#api/helpers/Box3Helper',
- CameraHelper: 'https://threejs.org/docs/#api/helpers/CameraHelper',
- DirectionalLightHelper: 'https://threejs.org/docs/#api/helpers/DirectionalLightHelper',
- FaceNormalsHelper: 'https://threejs.org/docs/#api/helpers/FaceNormalsHelper',
- GridHelper: 'https://threejs.org/docs/#api/helpers/GridHelper',
- PolarGridHelper: 'https://threejs.org/docs/#api/helpers/PolarGridHelper',
- HemisphereLightHelper: 'https://threejs.org/docs/#api/helpers/HemisphereLightHelper',
- PlaneHelper: 'https://threejs.org/docs/#api/helpers/PlaneHelper',
- PointLightHelper: 'https://threejs.org/docs/#api/helpers/PointLightHelper',
- RectAreaLightHelper: 'https://threejs.org/docs/#api/helpers/RectAreaLightHelper',
- SkeletonHelper: 'https://threejs.org/docs/#api/helpers/SkeletonHelper',
- SpotLightHelper: 'https://threejs.org/docs/#api/helpers/SpotLightHelper',
- VertexNormalsHelper: 'https://threejs.org/docs/#api/helpers/VertexNormalsHelper',
- AmbientLight: 'https://threejs.org/docs/#api/lights/AmbientLight',
- DirectionalLight: 'https://threejs.org/docs/#api/lights/DirectionalLight',
- HemisphereLight: 'https://threejs.org/docs/#api/lights/HemisphereLight',
- Light: 'https://threejs.org/docs/#api/lights/Light',
- PointLight: 'https://threejs.org/docs/#api/lights/PointLight',
- RectAreaLight: 'https://threejs.org/docs/#api/lights/RectAreaLight',
- SpotLight: 'https://threejs.org/docs/#api/lights/SpotLight',
- DirectionalLightShadow: 'https://threejs.org/docs/#api/lights/shadows/DirectionalLightShadow',
- LightShadow: 'https://threejs.org/docs/#api/lights/shadows/LightShadow',
- SpotLightShadow: 'https://threejs.org/docs/#api/lights/shadows/SpotLightShadow',
- AnimationLoader: 'https://threejs.org/docs/#api/loaders/AnimationLoader',
- AudioLoader: 'https://threejs.org/docs/#api/loaders/AudioLoader',
- BufferGeometryLoader: 'https://threejs.org/docs/#api/loaders/BufferGeometryLoader',
- Cache: 'https://threejs.org/docs/#api/loaders/Cache',
- CompressedTextureLoader: 'https://threejs.org/docs/#api/loaders/CompressedTextureLoader',
- CubeTextureLoader: 'https://threejs.org/docs/#api/loaders/CubeTextureLoader',
- DataTextureLoader: 'https://threejs.org/docs/#api/loaders/DataTextureLoader',
- FileLoader: 'https://threejs.org/docs/#api/loaders/FileLoader',
- FontLoader: 'https://threejs.org/docs/#api/loaders/FontLoader',
- ImageBitmapLoader: 'https://threejs.org/docs/#api/loaders/ImageBitmapLoader',
- ImageLoader: 'https://threejs.org/docs/#api/loaders/ImageLoader',
- JSONLoader: 'https://threejs.org/docs/#api/loaders/JSONLoader',
- Loader: 'https://threejs.org/docs/#api/loaders/Loader',
- LoaderUtils: 'https://threejs.org/docs/#api/loaders/LoaderUtils',
- MaterialLoader: 'https://threejs.org/docs/#api/loaders/MaterialLoader',
- ObjectLoader: 'https://threejs.org/docs/#api/loaders/ObjectLoader',
- TextureLoader: 'https://threejs.org/docs/#api/loaders/TextureLoader',
- DefaultLoadingManager: 'https://threejs.org/docs/#api/loaders/managers/DefaultLoadingManager',
- LoadingManager: 'https://threejs.org/docs/#api/loaders/managers/LoadingManager',
- LineBasicMaterial: 'https://threejs.org/docs/#api/materials/LineBasicMaterial',
- LineDashedMaterial: 'https://threejs.org/docs/#api/materials/LineDashedMaterial',
- Material: 'https://threejs.org/docs/#api/materials/Material',
- MeshBasicMaterial: 'https://threejs.org/docs/#api/materials/MeshBasicMaterial',
- MeshDepthMaterial: 'https://threejs.org/docs/#api/materials/MeshDepthMaterial',
- MeshLambertMaterial: 'https://threejs.org/docs/#api/materials/MeshLambertMaterial',
- MeshNormalMaterial: 'https://threejs.org/docs/#api/materials/MeshNormalMaterial',
- MeshPhongMaterial: 'https://threejs.org/docs/#api/materials/MeshPhongMaterial',
- MeshPhysicalMaterial: 'https://threejs.org/docs/#api/materials/MeshPhysicalMaterial',
- MeshStandardMaterial: 'https://threejs.org/docs/#api/materials/MeshStandardMaterial',
- MeshToonMaterial: 'https://threejs.org/docs/#api/materials/MeshToonMaterial',
- PointsMaterial: 'https://threejs.org/docs/#api/materials/PointsMaterial',
- RawShaderMaterial: 'https://threejs.org/docs/#api/materials/RawShaderMaterial',
- ShaderMaterial: 'https://threejs.org/docs/#api/materials/ShaderMaterial',
- ShadowMaterial: 'https://threejs.org/docs/#api/materials/ShadowMaterial',
- SpriteMaterial: 'https://threejs.org/docs/#api/materials/SpriteMaterial',
- Box2: 'https://threejs.org/docs/#api/math/Box2',
- Box3: 'https://threejs.org/docs/#api/math/Box3',
- Color: 'https://threejs.org/docs/#api/math/Color',
- Cylindrical: 'https://threejs.org/docs/#api/math/Cylindrical',
- Euler: 'https://threejs.org/docs/#api/math/Euler',
- Frustum: 'https://threejs.org/docs/#api/math/Frustum',
- Interpolant: 'https://threejs.org/docs/#api/math/Interpolant',
- Line3: 'https://threejs.org/docs/#api/math/Line3',
- Math: 'https://threejs.org/docs/#api/math/Math',
- Matrix3: 'https://threejs.org/docs/#api/math/Matrix3',
- Matrix4: 'https://threejs.org/docs/#api/math/Matrix4',
- Plane: 'https://threejs.org/docs/#api/math/Plane',
- Quaternion: 'https://threejs.org/docs/#api/math/Quaternion',
- Ray: 'https://threejs.org/docs/#api/math/Ray',
- Sphere: 'https://threejs.org/docs/#api/math/Sphere',
- Spherical: 'https://threejs.org/docs/#api/math/Spherical',
- Triangle: 'https://threejs.org/docs/#api/math/Triangle',
- Vector2: 'https://threejs.org/docs/#api/math/Vector2',
- Vector3: 'https://threejs.org/docs/#api/math/Vector3',
- Vector4: 'https://threejs.org/docs/#api/math/Vector4',
- CubicInterpolant: 'https://threejs.org/docs/#api/math/interpolants/CubicInterpolant',
- DiscreteInterpolant: 'https://threejs.org/docs/#api/math/interpolants/DiscreteInterpolant',
- LinearInterpolant: 'https://threejs.org/docs/#api/math/interpolants/LinearInterpolant',
- QuaternionLinearInterpolant: 'https://threejs.org/docs/#api/math/interpolants/QuaternionLinearInterpolant',
- Bone: 'https://threejs.org/docs/#api/objects/Bone',
- Group: 'https://threejs.org/docs/#api/objects/Group',
- Line: 'https://threejs.org/docs/#api/objects/Line',
- LineLoop: 'https://threejs.org/docs/#api/objects/LineLoop',
- LineSegments: 'https://threejs.org/docs/#api/objects/LineSegments',
- LOD: 'https://threejs.org/docs/#api/objects/LOD',
- Mesh: 'https://threejs.org/docs/#api/objects/Mesh',
- Points: 'https://threejs.org/docs/#api/objects/Points',
- Skeleton: 'https://threejs.org/docs/#api/objects/Skeleton',
- SkinnedMesh: 'https://threejs.org/docs/#api/objects/SkinnedMesh',
- Sprite: 'https://threejs.org/docs/#api/objects/Sprite',
- WebGLRenderer: 'https://threejs.org/docs/#api/renderers/WebGLRenderer',
- WebGLRenderTarget: 'https://threejs.org/docs/#api/renderers/WebGLRenderTarget',
- WebGLCubeRenderTarget: 'https://threejs.org/docs/#api/renderers/WebGLCubeRenderTarget',
- ShaderChunk: 'https://threejs.org/docs/#api/renderers/shaders/ShaderChunk',
- ShaderLib: 'https://threejs.org/docs/#api/renderers/shaders/ShaderLib',
- UniformsLib: 'https://threejs.org/docs/#api/renderers/shaders/UniformsLib',
- UniformsUtils: 'https://threejs.org/docs/#api/renderers/shaders/UniformsUtils',
- Fog: 'https://threejs.org/docs/#api/scenes/Fog',
- FogExp2: 'https://threejs.org/docs/#api/scenes/FogExp2',
- Scene: 'https://threejs.org/docs/#api/scenes/Scene',
- CanvasTexture: 'https://threejs.org/docs/#api/textures/CanvasTexture',
- CompressedTexture: 'https://threejs.org/docs/#api/textures/CompressedTexture',
- CubeTexture: 'https://threejs.org/docs/#api/textures/CubeTexture',
- DataTexture: 'https://threejs.org/docs/#api/textures/DataTexture',
- DepthTexture: 'https://threejs.org/docs/#api/textures/DepthTexture',
- Texture: 'https://threejs.org/docs/#api/textures/Texture',
- VideoTexture: 'https://threejs.org/docs/#api/textures/VideoTexture',
- CCDIKSolver: 'https://threejs.org/docs/#examples/animations/CCDIKSolver',
- MMDAnimationHelper: 'https://threejs.org/docs/#examples/animations/MMDAnimationHelper',
- MMDPhysics: 'https://threejs.org/docs/#examples/animations/MMDPhysics',
- OrbitControls: 'https://threejs.org/docs/#examples/controls/OrbitControls',
- ConvexBufferGeometry: 'https://threejs.org/docs/#examples/geometries/ConvexBufferGeometry',
- ConvexGeometry: 'https://threejs.org/docs/#examples/geometries/ConvexGeometry',
- DecalGeometry: 'https://threejs.org/docs/#examples/geometries/DecalGeometry',
- BabylonLoader: 'https://threejs.org/docs/#examples/loaders/BabylonLoader',
- GLTFLoader: 'https://threejs.org/docs/#examples/loaders/GLTFLoader',
- MMDLoader: 'https://threejs.org/docs/#examples/loaders/MMDLoader',
- MTLLoader: 'https://threejs.org/docs/#examples/loaders/MTLLoader',
- OBJLoader: 'https://threejs.org/docs/#examples/loaders/OBJLoader',
- OBJLoader2: 'https://threejs.org/docs/#examples/loaders/OBJLoader2',
- LoaderSupport: 'https://threejs.org/docs/#examples/loaders/LoaderSupport',
- PCDLoader: 'https://threejs.org/docs/#examples/loaders/PCDLoader',
- PDBLoader: 'https://threejs.org/docs/#examples/loaders/PDBLoader',
- SVGLoader: 'https://threejs.org/docs/#examples/loaders/SVGLoader',
- TGALoader: 'https://threejs.org/docs/#examples/loaders/TGALoader',
- PRWMLoader: 'https://threejs.org/docs/#examples/loaders/PRWMLoader',
- Lensflare: 'https://threejs.org/docs/#examples/objects/Lensflare',
- GLTFExporter: 'https://threejs.org/docs/#examples/exporters/GLTFExporter',
- });
-
- function getKeywordLink(keyword) {
- const dotNdx = keyword.indexOf('.');
- if (dotNdx) {
- const before = keyword.substring(0, dotNdx);
- const link = codeKeywordLinks[before];
- if (link) {
- return `${link}.${keyword.substr(dotNdx + 1)}`;
- }
- }
- return keyword.startsWith('THREE.')
- ? codeKeywordLinks[keyword.substring(6)]
- : codeKeywordLinks[keyword];
- }
-
- $('code').filter(function() {
- return getKeywordLink(this.textContent) &&
- this.parentElement.nodeName !== 'A';
- }).wrap(function() {
- const a = document.createElement('a');
- a.href = getKeywordLink(this.textContent);
- return a;
- });
-
- const methodPropertyRE = /^(\w+)\.(\w+)$/;
- const classRE = /^(\w+)$/;
- $('a').each(function() {
- const href = this.getAttribute('href');
- if (!href) {
- return;
- }
- const m = methodPropertyRE.exec(href);
- if (m) {
- const codeKeywordLink = getKeywordLink(m[1]);
- if (codeKeywordLink) {
- this.setAttribute('href', `${codeKeywordLink}#${m[2]}`);
- }
- } else if (classRE.test(href)) {
- const codeKeywordLink = getKeywordLink(href);
- if (codeKeywordLink) {
- this.setAttribute('href', codeKeywordLink);
- }
- }
- });
-
- const linkImgs = function(bigHref) {
- return function() {
- const a = document.createElement('a');
- a.href = bigHref;
- a.title = this.alt;
- a.className = this.className;
- a.setAttribute('align', this.align);
- this.setAttribute('align', '');
- this.className = '';
- this.style.border = '0px';
- return a;
- };
- };
- const linkSmallImgs = function(ext) {
- return function() {
- const src = this.src;
- return linkImgs(src.substr(0, src.length - 7) + ext);
- };
- };
- const linkBigImgs = function() {
- const src = $(this).attr('big');
- return linkImgs(src);
- };
- $('img[big$=".jpg"]').wrap(linkBigImgs);
- $('img[src$="-sm.jpg"]').wrap(linkSmallImgs('.jpg'));
- $('img[src$="-sm.gif"]').wrap(linkSmallImgs('.gif'));
- $('img[src$="-sm.png"]').wrap(linkSmallImgs('.png'));
- $('pre>code')
- .unwrap()
- .replaceWith(function() {
- return $('<pre class="prettyprint showlinemods notranslate" translate="no">' + this.innerHTML + '</pre>');
- });
if (window.prettyPrint) {
window.prettyPrint();
} | true |
Other | mrdoob | three.js | 745db1558d58eef42406e18d7be43e20a5746cac.json | add chinese font family
Change-Id: I0820dbe78552ddf50dde776ea19b207ef3a7ecaf | threejs/lessons/zh_cn/lang.css | @@ -0,0 +1,4 @@
+:root {
+ --article-font-family: "PingFang SC, Microsoft YaHei";
+ --headline-font-family: "PingFang SC, Microsoft YaHei";
+}
\ No newline at end of file | true |
Other | mrdoob | three.js | 745db1558d58eef42406e18d7be43e20a5746cac.json | add chinese font family
Change-Id: I0820dbe78552ddf50dde776ea19b207ef3a7ecaf | threejs/lessons/zh_cn/langinfo.hanson | @@ -1,7 +1,7 @@
{
language: '中文',
langCode: 'zh_cn', // if not specified will use folder
- defaultExampleCaption: "点击在新标签页中打开",
+ defaultExampleCaption: "点击此处在新标签页中打开",
title: 'Three.js 基础',
description: 'Three.js 基础学习',
link: 'http://threejsfundamentals.org/', | true |
Other | mrdoob | three.js | 2c8de4b6c9fd3ea8455e33cc549786d96213a497.json | Translate primitives to zh_cn (#153)
* Fix link error in ja/threejs-post-processing.md
* translate primitives to zh_cn
Co-authored-by: Evan <liuzhenqiang@ecityos.com> | threejs/lessons/zh_cn/langinfo.hanson | @@ -7,7 +7,7 @@
link: 'http://threejsfundamentals.org/',
commentSectionHeader: '<div>有问题? <a href="http://stackoverflow.com/questions/tagged/three.js">在 Stackoverflow 上提问</a>.</div>\n <div><a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=suggested+topic&template=suggest-topic.md&title=%5BSUGGESTION%5D">Suggestion</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=&template=request.md&title=">Request</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Issue</a>? <a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Bug</a>?</div>',
missing: "抱歉,还没有中文翻译哦。 [欢迎加入翻译](https://github.com/gfxfundamentals/threejsfundamentals)! 😄\n\n[英文原文链接]({{{origLink}}}).",
- toc: '内容列表',
+ toc: '目录',
categoryMapping: {
'basics': '基础',
'solutions': '解决方案', | true |
Other | mrdoob | three.js | 2c8de4b6c9fd3ea8455e33cc549786d96213a497.json | Translate primitives to zh_cn (#153)
* Fix link error in ja/threejs-post-processing.md
* translate primitives to zh_cn
Co-authored-by: Evan <liuzhenqiang@ecityos.com> | threejs/lessons/zh_cn/threejs-primitives.md | @@ -0,0 +1,321 @@
+Title: Three.js 图元
+Description: 关于 Three.js 图元
+TOC: 图元
+
+这篇文章是关于 Three.js 系列文章中的一篇。第一篇是 [基础](threejs-fundamentals.html)。
+如果你还没有阅读,建议从那里开始。
+
+Three.js 有很多图元。图元就是一些 3D 的形状,在运行时根据大量参数生成。
+
+使用图元是种很常见的做法,像使用球体作为地球,或者使用大量盒子来绘制 3D 图形。
+尤其是用来试验或者刚开始学习 3D。
+对大多数 3D 应用来说,更常见的做法是让美术在 3D 建模软件中创建 3D 模型,
+像 [Blender](https://blender.org),[Maya](https://www.autodesk.com/products/maya/)
+或者 [Cinema 4D](https://www.maxon.net/en-us/products/cinema-4d/)。
+之后在这个系列中,我们会涵盖到创建和加载来自 3D 建模软件的模型。
+现在,让我们仅使用可以获得的图元。
+
+下面的很多图元都有默认的部分或者全部参数,所以可以根据你的需要选择使用。
+
+
+<div id="Diagram-BoxBufferGeometry" data-primitive="BoxBufferGeometry">盒子</div>
+<div id="Diagram-CircleBufferGeometry" data-primitive="CircleBufferGeometry">平面圆</div>
+<div id="Diagram-ConeBufferGeometry" data-primitive="ConeBufferGeometry">锥形</div>
+<div id="Diagram-CylinderBufferGeometry" data-primitive="CylinderBufferGeometry">圆柱</div>
+<div id="Diagram-DodecahedronBufferGeometry" data-primitive="DodecahedronBufferGeometry">十二面体</div>
+<div id="Diagram-ExtrudeBufferGeometry" data-primitive="ExtrudeBufferGeometry">受挤压的 2D 形状,及可选的斜切。
+这里我们挤压了一个心型。注意,这分别是 <code>TextBufferGeometry</code> 和 <code>TextGeometry</code> 的基础。<div>
+<div id="Diagram-IcosahedronBufferGeometry" data-primitive="IcosahedronBufferGeometry">二十面体</div>
+<div id="Diagram-LatheBufferGeometry" data-primitive="LatheBufferGeometry">绕着一条线旋转形成的形状。例如:灯泡、保龄球瓶、蜡烛、蜡烛台、酒瓶、玻璃杯等。你提供一系列点作为 2D 轮廓,并告诉 Three.js 沿着某条轴旋转时需要将侧面分成多少块。</div>
+<div id="Diagram-OctahedronBufferGeometry" data-primitive="OctahedronBufferGeometry">八面体</div>
+<div id="Diagram-ParametricBufferGeometry" data-primitive="ParametricBufferGeometry">通过提供一个函数(将网格中 2D 的点转成对应的 3D 点)生成的表面。</div>
+<div id="Diagram-PlaneBufferGeometry" data-primitive="PlaneBufferGeometry">2D 平面</div>
+<div id="Diagram-PolyhedronBufferGeometry" data-primitive="PolyhedronBufferGeometry">将一些环绕着中心点的三角形投影到球体上</div>
+<div id="Diagram-RingBufferGeometry" data-primitive="RingBufferGeometry">中间有洞的 2D 圆盘</div>
+<div id="Diagram-ShapeBufferGeometry" data-primitive="ShapeBufferGeometry">2D 的三角轮廓</div>
+<div id="Diagram-SphereBufferGeometry" data-primitive="SphereBufferGeometry">球体</div>
+<div id="Diagram-TetrahedronBufferGeometry" data-primitive="TetrahedronBufferGeometry">四面体</div>
+<div id="Diagram-TextBufferGeometry" data-primitive="TextBufferGeometry">根据 3D 字体和字符串生成的 3D 文字</div>
+<div id="Diagram-TorusBufferGeometry" data-primitive="TorusBufferGeometry">圆环体(甜甜圈)</div>
+<div id="Diagram-TorusKnotBufferGeometry" data-primitive="TorusKnotBufferGeometry">环形节</div>
+<div id="Diagram-TubeBufferGeometry" data-primitive="TubeBufferGeometry">圆环沿着路径</div>
+<div id="Diagram-EdgesGeometry" data-primitive="EdgesGeometry">一个工具对象,将一个几何体作为输入,生成面夹角大于某个阈值的那条边。例如,你从顶上看一个盒子,你会看到有一条线穿过这个面,因为每个组成这个盒子的三角形都显示出来了。而如果使用 <code>EdgesGeometry</code> 中间的线就会被移除。调整下面的 thresholdAngle,你就会看到夹角小于这个值的边消失了。</div>
+<div id="Diagram-WireframeGeometry" data-primitive="WireframeGeometry">对于给定的几何体,生成每个边包含一个线段(2 个点)的几何体。如果不这样,通常缺边或者多边,因为 WebGL 中每条边通常需要 2 个点。例如,如果你只有一个三角形,就只有 3 个点 。如果你用 <code>wireframe: true</code> 的材质来绘制它,你只能得到一条线。将这个三角形几何体传给 <code>WireframeGeometry</code> 就能生成一个新的几何体,这个几何体用 6 个点组成 3 条线段。</div>
+
+你可能发现上面的大部分中,`Geometry` 和 `BufferGeometry` 是成对出现的。
+这两种类型的区别是高效灵活 vs 性能。
+
+基于 `BufferGeometry` 的图元是面向性能的类型。
+几何体的顶点是直接生成为一个高效的类型数组形式,可以被上传到 GPU 进行渲染。
+这意味着它们能更快的启动,占用更少的内存。但如果想修改数据,就需要复杂的编程。
+
+基于 `Geometry` 的图元更灵活、更易修改。
+它们根据 JavaScript 的类而来,像 `Vector3` 是 3D 的点,`Face3` 是三角形。
+它们需要更多的内存,在能够被渲染前,Three.js 会将它们转换成相应的 `BufferGeometry` 表现形式。
+
+如果你知道你不会操作图元,或者你擅长使用数学来操作它们,那么最好使用基于 `BufferGeometry` 的图元。
+但如果你想在渲染前修改一些东西,那么 `Geometry` 的图元会更好操作。
+
+举个简单的例子,`BufferGeometry` 不能轻松的添加新的顶点。
+使用顶点的数量在创建时就定好了,相应的创建存储,填充顶点数据。
+但用 `Geometry` 你就能随时添加顶点。
+
+我们会在 [另一篇文章](threejs-custom-geometry.html) 中来讲创建自定义几何体。
+现在,我们来为创建每一个图元作为例子。
+我们从 [上一篇文章的例子](threejs-responsive.html) 开始。
+
+在接近顶部的地方,先设置背景颜色:
+
+```js
+const scene = new THREE.Scene();
++scene.background = new THREE.Color(0xAAAAAA);
+```
+
+这告诉 Three.js 清除并设置成略浅的灰色。
+
+需要改变摄像机的位置,这样我们能看到所有物体。
+
+```js
+-const fov = 75;
++const fov = 40;
+const aspect = 2; // canvas 默认
+const near = 0.1;
+-const far = 5;
++const far = 1000;
+const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
+-camera.position.z = 2;
++camera.position.z = 120;
+```
+
+添加一个函数,`addObject`,传入位置 x、y 和一个 `Object3D`,将物体添加到场景中:
+
+```js
+const objects = [];
+const spread = 15;
+
+function addObject(x, y, obj) {
+ obj.position.x = x * spread;
+ obj.position.y = y * spread;
+
+ scene.add(obj);
+ objects.push(obj);
+}
+```
+
+同时,也创建一个函数,用于生成随机颜色的材质。
+我们会使用 `Color` 的一个特性,让你可以基于色调、饱和度、亮度来设置颜色。
+
+在色轮上,`hue` 值从 0 到 1,红色在 0 的位置,绿色在 .33 的位置,蓝色在 .66 的位置。
+`saturation` 值从 0 到 1,0 表示没有颜色,1 表示饱和度最高。
+`luminance` 值从 0 到 1,0 表示黑色,1 表示白色,0.5 表示最大数量的颜色。
+换句说话,`luminance` 从 0 到 0.5 表示颜色从黑到 `hue`,从 0.5 到 1.0 表示颜色从 `hue` 到白。
+
+```js
+function createMaterial() {
+ const material = new THREE.MeshPhongMaterial({
+ side: THREE.DoubleSide,
+ });
+
+ const hue = Math.random();
+ const saturation = 1;
+ const luminance = .5;
+ material.color.setHSL(hue, saturation, luminance);
+
+ return material;
+}
+```
+
+同时,我们将 `side: THREE.DoubleSide` 传给材质。这告诉 Three.js 绘制组成形状的三角形的两个面。
+对于实心的形状,像球体或立方体,通常不需要绘制三角形的背面,因为它们全部朝向内部。
+对于我们的情况,我们会绘制一些像 `PlaneBufferGeometry` 和 `ShapeBufferGeometry` 这样的二维图形,没有内部,
+如果不设置 `side: THREE.DoubleSide`,当从反面看时它们会消失。
+
+需要注意的是,如果 **不** 设置 `side: THREE.DoubleSide` 绘制会更快,所以最好只在需要的时候设置它。
+但现在我们不会绘制很多图形,所以没有必要太担心。
+
+接着,创建一个函数,`addSolidGeometry`,我们传入一个几何体,
+它通过 `createMaerial` 创建一个随机颜色的材质,通过 `addObject` 添加到场景中。
+
+```js
+function addSolidGeometry(x, y, geometry) {
+ const mesh = new THREE.Mesh(geometry, createMaterial());
+ addObject(x, y, mesh);
+}
+```
+
+现在,我们可以对我们创建的大多数图元使用它。
+比如创建一个盒子:
+
+```js
+{
+ const width = 8;
+ const height = 8;
+ const depth = 8;
+ addSolidGeometry(-2, -2, new THREE.BoxBufferGeometry(width, height, depth));
+}
+```
+
+如果你查看下面的代码,你会看到每个类型的几何体有相似的部分。
+
+这是结果:
+
+{{{example url="../threejs-primitives.html" }}}
+
+上面的模式有一些值得注意的例外。最大的可能就是 `TextBufferGeometry`。在为文字生成网格前需要先加载 3D 字体数据。
+数据的加载是异步的,所以在尝试创建几何体前需要等待。通过将字体加载 Promise 化,我们可以让这个过程更简单。
+我们创建一个 `FontLoader`,然后 `loadFont` 函数返回一个 `promise`,`promise` 的 `resolve` 会给我们字体。
+接着我们创建一个 `async` 函数 `doit`,使用 `await` 加载字体。最后创建几何体,调用 `addOjbect` 将它添加到场景中。
+
+```js
+{
+ const loader = new THREE.FontLoader();
+ // 将字体加载过程 promise 化
+ function loadFont(url) {
+ return new Promise((resolve, reject) => {
+ loader.load(url, resolve, undefined, reject);
+ });
+ }
+
+ async function doit() {
+ const font = await loadFont('resources/threejs/fonts/helvetiker_regular.typeface.json'); /* threejsfundamentals: url */
+ const geometry = new THREE.TextBufferGeometry('three.js', {
+ font: font,
+ size: 3.0,
+ height: .2,
+ curveSegments: 12,
+ bevelEnabled: true,
+ bevelThickness: 0.15,
+ bevelSize: .3,
+ bevelSegments: 5,
+ });
+ const mesh = new THREE.Mesh(geometry, createMaterial());
+ geometry.computeBoundingBox();
+ geometry.boundingBox.getCenter(mesh.position).multiplyScalar(-1);
+
+ const parent = new THREE.Object3D();
+ parent.add(mesh);
+
+ addObject(-1, -1, parent);
+ }
+ doit();
+}
+```
+
+还有一个其它的区别。我们想让文字绕着它的中心旋转,但默认的,Three.js 创建的文字的旋转中心在左边。
+变通的方法是要求 Three.js 计算几何体的边界框。然后我们可以对边界框调用 `getCenter`,将网格位置对象传给它。
+`getCenter` 将盒子的中心值复制进位置对象。
+同时它也返回位置对象,这样我们就可以调用 `multiplyScalar(-1)` 来放置整个对象,这样对象的旋转中心就是对象的中心了。
+
+如果我们像之前的例子一样接着调用 `addSolidGeometry`,它又会设置位置,这是不对的。
+在我们的例子中,我们创建了一个 `Object3D` 是 Three.js 场景图中的标准节点。
+`Mesh` 也是继承自 `Object3D` 的。我们会在 [另一篇文章中涉及场景图是如何工作的](threejs-scenegraph.html)。
+现在知道它们像 DOM 的节点就行了,子节点是相对与父节点绘制的。
+创建一个 `Object3D`,并将网格设置成它的子节点,我们就能将 `Object3D` 放置在任何位置,并保持我们之前设置的中心。
+
+如果不这么做,文字会偏离中心。
+
+{{{example url="../threejs-primitives-text.html" }}}
+
+注意,左边的没有绕着中心旋转,而右边的绕着中心旋转。
+
+其它的异常情况是,有 2 个线的例子,`EdgesGeometry` 和 `WireframeGeometry`。
+它们调用 `addLineGeometry` 而不是 `addSolidGeometry`,看起来像这样:
+
+```js
+function addLineGeometry(x, y, geometry) {
+ const material = new THREE.LineBasicMaterial({color: 0x000000});
+ const mesh = new THREE.LineSegments(geometry, material);
+ addObject(x, y, mesh);
+}
+```
+
+上面代码创建了一个黑色的 `LineBasicMaterial`,然后创建了一个 `LineSegments` 对象,它封装了 `Mesh`,
+好让 Three.js 知道你在渲染一个线段(每个段 2 个点)。
+
+每个图元都有多个参数可以在创建时传入,最好 [看文档](https://threejs.org/docs) 而不是在这里重复它们。
+你也可以点击上面每个形状边上的链接,查看对应的文档。
+
+有一对类并不和上面的模式匹配。它们是 `PointsMaterial` 和 `Points`。
+`Points` 和 `LineSegments` 类似,它需要一个 `Geometry` 或者 `BufferGeometry`,但每个顶点都绘制一次,而不是每条线。
+要使用,你需要传入 `PointsMaterial`,它需要一个代表点多大的 [`size`](PointsMaterial.size)。
+
+```js
+const radius = 7;
+const widthSegments = 12;
+const heightSegments = 8;
+const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
+const material = new THREE.PointsMaterial({
+ color: 'red',
+ size: 0.2, // in world units
+});
+const points = new THREE.Points(geometry, material);
+scene.add(points);
+```
+
+<div class="spread">
+<div data-diagram="Points"></div>
+</div>
+
+如果你想让点无视和摄像机的距离,始终保持相同大小,可以通过将 [`sizeAttenuation`](PointsMaterial.sizeAttenuation) 设置成 `false` 将其关闭。
+
+```js
+const material = new THREE.PointsMaterial({
+ color: 'red',
++ sizeAttenuation: false,
++ size: 3, // in pixels
+- size: 0.2, // in world units
+});
+...
+```
+
+<div class="spread">
+<div data-diagram="PointsUniformSize"></div>
+</div>
+
+还有一个重要的东西,就是所有形状都有多个设置来设置它们的细化程度。
+一个很好的例子就是球形几何体。它可以这些参数:一圈组成的片数、从上到下的数量等。例如:
+
+<div class="spread">
+<div data-diagram="SphereBufferGeometryLow"></div>
+<div data-diagram="SphereBufferGeometryMedium"></div>
+<div data-diagram="SphereBufferGeometryHigh"></div>
+</div>
+
+第一个球体一圈有 5 分片,高度为 3,一共 15 片,或者 30 个三角形。
+第二个球体一圈有 24 分片,高度为 10,一共 240 片,或者 480 个三角形。
+第三个球体一圈有 50 分片,高度为 50,一共 2500 片,或者 5000 个三角形。
+
+由你决定需要细分成多少。看起来你可能需要较多数量的分片,但去除线,设置平面着色,我们就得到了:
+
+<div class="spread">
+<div data-diagram="SphereBufferGeometryLowSmooth"></div>
+<div data-diagram="SphereBufferGeometryMediumSmooth"></div>
+<div data-diagram="SphereBufferGeometryHighSmooth"></div>
+</div>
+
+现在并不明显是否右边有 5000 个三角形的比中间只有 480 个三角形的好更多。
+如果你只是绘制少量球体,比如一个地球地图的球体,那么单个 10000 个三角形的球体就是个不错的选择。
+但如果你要画 1000 个球体,那么 1000 个球体 x 10000 个三角形就是一千万个三角形。
+想要动画流畅,你需要浏览器每秒绘制 60 帧,那么上面的场景就需要每秒绘制 6 亿个三角形。那是巨大的运算量。
+
+有时候很容易选择。例如你可以选择将平面细分。
+
+<div class="spread">
+<div data-diagram="PlaneBufferGeometryLow"></div>
+<div data-diagram="PlaneBufferGeometryHigh"></div>
+</div>
+
+左边的平面有 2 个三角形,右边的平面有 200 个三角形。不像球体,在多数平面的应用场景中,并没有什么折中的方法。
+你可能只在你想要修改或者在某些方面封装一下的时候才将平面细分。对于盒子也是一样。
+
+所以,选择适合你情况的方案。细分的越少,运行的越流畅,使用的内存也会更少。
+你需要根据你的具体情况选择合适的方案。
+
+如果上面的形状不符合你的使用需求,你可以从 [.obj 文件](threejs-load-obj.html) 或 [.gltf 文件](threejs-load-gltf.html) 加载几何体。
+你也可以创建 [自定义 Geometry](threejs-custom-geometry.html) 或 [自定义 BufferGeometry](threejs-custom-buffergeometry.html)。
+
+接下来是 [Three.js 的场景图是如何工作的及如何使用它](threejs-scenegraph.html)。
+
+<link rel="stylesheet" href="resources/threejs-primitives.css">
+<script type="module" src="resources/threejs-primitives.js"></script>
+ | true |
Other | mrdoob | three.js | 3dd0613be17b2f9f2dfe4f27b7be853dde30ff8f.json | use github actions | .github/workflows/deploy-to-gh-pages.yml | @@ -0,0 +1,30 @@
+name: Build and Deploy
+on:
+ push:
+ branches:
+ - master
+jobs:
+ build-and-deploy:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout 🍔🍟🥤
+ uses: actions/checkout@v2.3.1
+ with:
+ persist-credentials: false
+
+ - name: Use Node.js 😂
+ uses: actions/setup-node@v1
+ with:
+ node-version: '14.x'
+
+ - name: Install and Build 🏭
+ run: |
+ npm ci
+ npm run build-ci
+
+ - name: Deploy 📦
+ uses: JamesIves/github-pages-deploy-action@3.6.2
+ with:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ BRANCH: gh-pages
+ FOLDER: out
\ No newline at end of file | true |
Other | mrdoob | three.js | 3dd0613be17b2f9f2dfe4f27b7be853dde30ff8f.json | use github actions | .travis.yml | @@ -1,18 +0,0 @@
-language: node_js
-node_js:
- - "12.16.2"
-script:
- - npm run build-ci
-env:
- global:
- - COMMIT_AUTHOR_EMAIL: "github@greggman.com"
-
-deploy:
- provider: pages
- skip-cleanup: true
- github-token: $GITHUB_TOKEN # Set in the settings page of your repository, as a secure variable
- keep-history: true
- local-dir: out
- on:
- branch: master
- | true |
Other | mrdoob | three.js | b7e0b6de0f2ca3ac08591a3e567478378932dc46.json | update the chinese threejsfundamentals article | threejs/lessons/zh_cn/threejs-fundamentals.md | @@ -31,21 +31,35 @@ Three.js经常会和WebGL混淆,
* 有一个`Renderer`。这可以说是three.js的主要对象。你传入了一个`Scene`和一个`Camera`到`Renderer`里面,然后他来渲染 (画)出在相机视椎体中的3D场景,作为一个2D的图片在画布上。
-* 有一个[scenegraph](threejs-scenegraph.html) 它是一个类似结构的树,由很多对象组成,比如一个`Scene`对象 ,多个`Mesh`对象,`Light`对象,`Group`,`Object3D`,和`Camera`对象。一个`Scene`对象定义了场景图的根,并包含背景色和雾等属性。这些对象定义了一个分层的父/子树的结构,并且展现出对象出现的地方和他们的方向。子对象的位置和方向是相对于父对象而言的。比如说汽车的轮子是汽车的子对象,这样移动和定位汽车就会自动移动轮子。你可以了解更多在 [the article on scenegraphs](threejs-scenegraph.html) 中。
+* 有一个[场景图](threejs-scenegraph.html) 它是一个类似结构的树,由很多对象组成,比如一个`Scene`对象 ,多个`Mesh`对象,`Light`对象,`Group`,`Object3D`,和`Camera`对象。一个`Scene`对象定义了场景图最基本的要素,并包含背景色和雾等属性。这些对象定义了一个分层的父/子树的结构,并且展现出对象出现的地方和他们的方向。子对象的位置和方向是相对于父对象而言的。比如说汽车的轮子是汽车的子对象,这样移动和定位汽车就会自动移动轮子。你可以了解更多在[场景图的文章](threejs-scenegraph.html)中。
- 注意图中`Camera`是一半在场景图中,一半在场景图外的。这表示在three.js中,不像其他的对象一样,一个`Camera`不一定要在场景图中起作用。就像其他的对象一样,一个`Camera`,作为一些其他对象的子对象,将会相对他的父对象移动和朝向。这有一个例子,放置多个`Camera`对象在一个场景图中在 [the article on scenegraphs](threejs-scenegraph.html) 的结尾部分。
+ 注意图中`Camera`是一半在场景图中,一半在场景图外的。这表示在three.js中,不像其他的对象一样,一个`Camera`不一定要在场景图中起作用。就像其他的对象一样,一个`Camera`,作为一些其他对象的子对象,将会跟随他的父对象移动和朝向。这有一个例子,放置多个`Camera`对象在一个场景图中在[场景图的文章](threejs-scenegraph.html)的结尾部分。
* `Mesh`对象代表用一个特定的`Material`绘制一个特定的`Geometry`。`Material`对象和`Geometry`对象可以被多个`Mesh`对象使用。比如在不同的位置画两个蓝色立方体,我们会需要两个`Mesh`对象来代表每一个立方体的位置和方向。我们只需要一个`Geometry`来存放立方体的顶点数据,和一个`Material`来定义蓝色就可以了。两个`Mesh`对象都涉及到相同的`Geometry`对象和`Material`对象。
-* `Geometry`对象代表一些几何体,比如说球体、立方体、平面、狗、猫、人、树、建筑等的顶点信息。Three.js提供了多种内置的 [基本元素](threejs-primitives.html) 。你也可以 [create custom geometry](threejs-custom-geometry.html) 并且 [load geometry from files](threejs-load-obj.html)。
+* `Geometry`对象代表一些几何体,比如说球体、立方体、平面、狗、猫、人、树、建筑等的顶点信息。Three.js提供了多种内置的[基本元素](threejs-primitives.html) 。你也可以[创建自定义几何体](threejs-custom-geometry.html)并且[从文件中加载几何体](threejs-load-obj.html)。
-* `Material` objects represent
- [the surface properties used to draw geometry](threejs-materials.html)
- including things like the color to use and how shiny it is. A `Material` can also
- reference one or more `Texture` objects which can be used, for example,
- to wrap an image onto the surface of a geometry.
+* `Material`对象代表[绘制几何体的表面属性](threejs-materials.html),包括使用的颜色,和光亮程度。一个`Material`可以引用一个或多个`Texture`对象,这些对象可以用来,例如,将图像包裹到几何体的表面。
-首先我们需要一个canvas标签。
+* `Texture`对象通常代表图片要么[从图像文件中加载](threejs-textures.html),[在画布上形成](threejs-canvas-textures.html),要么 [由另一个场景渲染出](threejs-rendertargets.html)。
+
+* `Light`对象代表[不同种类的光](threejs-lights.html)。
+
+考虑以上所有注意事项,我们接下来要做一个最小的*"Hello Cube"* 设置,像下面这样
+
+<div class="threejs_center"><img src="resources/images/threejs-1cube-no-light-scene.svg" style="width: 500px;"></div>
+
+首先让我们先来加载three.js
+
+```html
+<script type="module">
+import * as THREE from './resources/threejs/r119/build/three.module.js';
+</script>
+```
+
+把`type="module"`放到script标签中很重要。这可以让我们使用`import`关键字加载three.js。还有其他的方法可以加载three.js,但是r106开始,推荐使用模块的方式。模块的优点是可以很方便地导入需要的其他模块。这样我们就不用再手动加载它们所依赖的额外脚本了。
+
+下一步我们需要一个`<canvas>`标签。
```html
<body>
@@ -59,10 +73,10 @@ Three.js将会使用这个canvas标签所以我们要先获取它然后传给thr
<script type="module">
import * as THREE from './resources/threejs/r119/build/three.module.js';
-function main() {
- const canvas = document.querySelector('#c');
- const renderer = new THREE.WebGLRenderer({canvas});
- ...
++function main() {
++ const canvas = document.querySelector('#c');
++ const renderer = new THREE.WebGLRenderer({canvas});
++ ...
</script>
```
@@ -95,9 +109,8 @@ canvas是300x150像素,所以aspect为300/150或者说2.。
`near`和`far`代表摄像机前方将要被渲染的空间。
任何在这个范围前面或者后面的物体都将被裁剪(不绘制)。
-这四个参数定义了一个*"frustum"*。一个*frustum*是指一个像被削去顶部
-的金字塔形状。换句话说把*"frustum"*想象成其他形状比如球体、
-立方体、棱柱体、截椎体。
+这四个参数定义了一个 *"frustum"*(译者注:视椎体)。 *frustum*是指一个像被削去顶部
+的金字塔形状。换句话说,可以把"frustum"想象成其他形状比如球体、立方体、棱柱体、截椎体。
<img src="resources/frustum-3d.svg" width="500" class="threejs_center"/>
@@ -117,10 +130,7 @@ camera.position.z = 2;
<img src="resources/scene-down.svg" width="500" class="threejs_center"/>
-上面的示意图中我们能看到摄像机的位置在`z = 2`。它朝向
-Z轴负方向。我们的截椎体从摄像机前方的0.1到5。因为这张图是俯视图,
-fov会受到aspect的影响。canvas的宽度是高度的两倍,
-所以水平视角会比我们设置的垂直视角75要大。
+上面的示意图中我们能看到摄像机的位置在`z = 2`。它朝向Z轴负方向。我们的截椎体从摄像机前方的0.1到5。因为这张图是俯视图,fov会受到aspect的影响。canvas的宽度是高度的两倍,所以水平视角会比我们设置的垂直视角75度要大。
然后我们创建一个`Scene`(场景)。`Scene`是three.js最基本的组成.
需要three.js绘制的东西都需要加入到scene中。 我们将会
@@ -147,9 +157,11 @@ const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
const material = new THREE.MeshBasicMaterial({color: 0x44aa88});
```
-然后创建一个`Mesh`. `Mesh`代表了`Geometry`(物体的形状)和`Material` (怎么
-绘制物体, 光滑还是平整, 什么颜色, 什么贴图等等)的组合,
-以及物体在场景中的位置、朝向、和缩放。
+然后创建一个`Mesh`。一个`Mesh`代表了三件事情的合集
+
+1. `Geometry`(物体的形状)
+2. `Material` (怎么绘制物体, 光滑还是平整, 什么颜色, 什么贴图等等)的组合
+3. 对象在场景中相对于他父对象的位置、朝向、和缩放。下面的代码父对象是场景。
```js
const cube = new THREE.Mesh(geometry, material);
@@ -161,8 +173,7 @@ const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
```
-然后我们通过将scene和camera传递给renderer的render方法
-来渲染整个场景。
+然后我们通过scene和camera传递给renderer的render方法来渲染整个场景。
```js
renderer.render(scene, camera);
@@ -244,6 +255,10 @@ requestAnimationFrame(render);
+const material = new THREE.MeshPhongMaterial({color: 0x44aa88}); // greenish blue
```
+这是我们新的项目结构
+
+<div class="threejs_center"><img src="resources/images/threejs-1cube-with-directionallight.svg" style="width: 500px;"></div>
+
下面开始生效了。
{{{example url="../threejs-fundamentals-with-light.html" }}}
@@ -309,6 +324,78 @@ function render(time) {
的立方体有一部分在我们的截椎体外面。他们大部分是被
包裹的,因为水平方向的视角非常大。
-希望这个简短的介绍能帮助你起步。 [Next up we'll cover
-making our code responsive so it is adaptable to multiple situations](threejs-responsive.html).
+我们的项目现在有了这样的结构
+
+<div class="threejs_center"><img src="resources/images/threejs-3cubes-scene.svg" style="width: 610px;"></div>
+
+正如你看见的那样,我们有三个`Mesh`引用了相同的`BoxGeometry`。每个`Mesh`引用了一个单独的
+`MeshPhongMaterial`来显示不同的颜色。
+
+希望这个简短的介绍能帮助你起步。[接下来我们将介绍如何使我们的代码具有响应性,从而使其能够适应多种情况](threejs-responsive.html).
+
+<div id="es6" class="threejs_bottombar">
+<h3>es6模块,three.js,和文件夹结构</h3>
+<p>从r106版本开始,使用three.js的首选方式是通过<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">es6模块</a>。</p>
+<p>
+在一个脚本中,es6模块可以通过<code>import</code>关键字加载或者通过<code><script type="module"></code>行内标签。这有一个两种方法都用的例子。
+</p>
+<pre class=prettyprint>
+<script type="module">
+import * as THREE from './resources/threejs/r119/build/three.module.js';
+...
+
+</script>
+</pre>
+<p>
+路径必须是绝对或相对的。相对路径通常由<code>./</code>或者<code>../</code>开头,和其他标签不同如<code><img></code>和<code><a></code>.
+</p>
+<p>
+只要它们的绝对路径完全相同,对同一脚本的引用将只被加载一次。对于three.js这意味着它需要你把所有的实例的库放在正确的文件夹结构中。
+</p>
+<pre class="dos">
+someFolder
+ |
+ ├-build
+ | |
+ | +-three.module.js
+ |
+ +-examples
+ |
+ +-jsm
+ |
+ +-controls
+ | |
+ | +-OrbitControls.js
+ | +-TrackballControls.js
+ | +-...
+ |
+ +-loaders
+ | |
+ | +-GLTFLoader.js
+ | +-...
+ |
+ ...
+</pre>
+<p>
+之所以需要这种文件夹结构,是因为像<a href="https://github.com/mrdoob/three.js/blob/master/examples/jsm/controls/OrbitControls.js"><code>OrbitControls.js</code></a>这样的示例中的脚本有一个复杂的相对路径,像下面这样
+</p>
+<pre class="prettyprint">
+import * as THREE from '../../../build/three.module.js';
+</pre>
+<p>
+使用相同的结构保证了当你导入three和任一示例库时,它们都会引用同一个three.module.js文件。
+</p>
+<pre class="prettyprint">
+import * as THREE from './someFolder/build/three.module.js';
+import {OrbitControls} from './someFolder/examples/jsm/controls/OrbitControls.js';
+</pre>
+<p>在使用CDN时,是同样的道理。确保<code>three.modules.js</code>的路径以
+<code>/build/three.modules.js</code>结尾,比如</p>
+<pre class="prettyprint">
+import * as THREE from 'https://unpkg.com/three@0.108.0/<b>build/three.module.js</b>';
+import {OrbitControls} from 'https://unpkg.com/three@0.108.0/examples/jsm/controls/OrbitControls.js';
+</pre>
+<p>如果你偏向于旧式的<code><script src="path/to/three.js"></script></code>样式,你可以查看<a href="https://r105.threejsfundamentals.org">这个网站的旧版本</a>。
+Three.js的政策是不担心向后的兼容性。他们希望你使用特定的版本,就像希望你下载代码并把它放在你的项目中一样。当升级到较新的版本时,你可以阅读 <a href="https://github.com/mrdoob/three.js/wiki/Migration-Guide">迁移指南</a> 看看你需要改变什么。如果要同时维护一个es6模块和一个类脚本版本的网站,那工作量就太大了,所以今后本网站将只显示es6模块样式。正如其他地方说过的那样,为了支持旧版浏览器,请考虑使用<a href="https://babeljs.io">转换器</a>。</p>
+</div>
\ No newline at end of file | false |
Other | mrdoob | three.js | 1a6d8e3e92155bdab876ab5b422df2646784185e.json | Extract light from control into light section | examples/webgl_geometry_convex.html | @@ -43,11 +43,13 @@
controls.minDistance = 20;
controls.maxDistance = 50;
controls.maxPolarAngle = Math.PI / 2;
-
+
+ // ambient light
+
scene.add( new THREE.AmbientLight( 0x222222 ) );
-
- // light
-
+
+ // point light
+
const light = new THREE.PointLight( 0xffffff, 1 );
camera.add( light );
| false |
Other | mrdoob | three.js | d33553080ed90db6ebb59da4f30c094f6ea8fd34.json | Update material properties for point clouds | examples/jsm/loaders/3DMLoader.js | @@ -428,13 +428,17 @@ Rhino3dmLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
case 'PointSet':
var geometry = loader.parse( obj.geometry );
- var _color = attributes.drawColor;
- var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
- var material = new PointsMaterial( { color: color, sizeAttenuation: false, size: 2 } );
+ var material = null;
if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
- material.vertexColors = true;
+ material = new PointsMaterial( { vertexColors: true, sizeAttenuation: false, size: 2 } );
+
+ } else {
+
+ var _color = attributes.drawColor;
+ var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
+ material = new PointsMaterial( { color: color, sizeAttenuation: false, size: 2 } );
}
| false |
Other | mrdoob | three.js | 418ccee35875f04d966af667fea66dad4781d70c.json | remove redundant brackets | src/core/Object3D.js | @@ -320,7 +320,7 @@ Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ),
}
- if ( ( object && object.isObject3D ) ) {
+ if ( object && object.isObject3D ) {
if ( object.parent !== null ) {
| true |
Other | mrdoob | three.js | 418ccee35875f04d966af667fea66dad4781d70c.json | remove redundant brackets | src/core/Raycaster.js | @@ -72,13 +72,13 @@ Object.assign( Raycaster.prototype, {
setFromCamera: function ( coords, camera ) {
- if ( ( camera && camera.isPerspectiveCamera ) ) {
+ if ( camera && camera.isPerspectiveCamera ) {
this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
this.camera = camera;
- } else if ( ( camera && camera.isOrthographicCamera ) ) {
+ } else if ( camera && camera.isOrthographicCamera ) {
this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/animations/MMDAnimationHelper.html | @@ -153,7 +153,7 @@ <h3>[method:MMDAnimationHelper remove]( [param:Object3D object] )</h3>
Remove an [page:SkinnedMesh], [page:Camera], or [page:Audio] from helper.
</p>
- <h3>[method:MMDAnimationHelper update]( [param:Nummber delta] )</h3>
+ <h3>[method:MMDAnimationHelper update]( [param:Number delta] )</h3>
<p>
[page:Number delta] — number in second<br />
</p> | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/animations/MMDPhysics.html | @@ -78,7 +78,7 @@ <h3>[method:MMDPhysicsHelper createHelper]()</h3>
<h3>[method:CCDIKSolver reset]()</h3>
<p>
- Resets Rigid bodies transorm to current bone's.
+ Resets Rigid bodies transform to current bone's.
</p>
<h3>[method:CCDIKSolver setGravity]( [param:Vector3 gravity] )</h3> | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/controls/FirstPersonControls.html | @@ -68,12 +68,12 @@ <h3>[property:Number heightCoef]</h3>
<h3>[property:Number heightMax]</h3>
<p>
- Upper camera height limit used for movement speed adjusment. Default is *1*.
+ Upper camera height limit used for movement speed adjustment. Default is *1*.
</p>
<h3>[property:Number heightMin]</h3>
<p>
- Lower camera height limit used for movement speed adjusment. Default is *0*.
+ Lower camera height limit used for movement speed adjustment. Default is *0*.
</p>
<h3>[property:Boolean heightSpeed]</h3> | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/controls/OrbitControls.html | @@ -13,7 +13,7 @@ <h1>[name]</h1>
Orbit controls allow the camera to orbit around a target.<br>
To use this, as with all files in the /examples directory, you will have to
- include the file seperately in your HTML.
+ include the file separately in your HTML.
</p>
| true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/controls/TransformControls.html | @@ -102,7 +102,7 @@ <h3>[property:Object3D object]</h3>
<h3>[property:Number rotationSnap]</h3>
<p>
- By default, 3D objects are continously rotated. If you set this property to a numeric value (radians), you can define in which
+ By default, 3D objects are continuously rotated. If you set this property to a numeric value (radians), you can define in which
steps the 3D object should be rotated. Deault is *null*.
</p>
@@ -133,7 +133,7 @@ <h3>[property:String space]</h3>
<h3>[property:Number translationSnap]</h3>
<p>
- By default, 3D objects are continously translated. If you set this property to a numeric value (world units), you can define in which
+ By default, 3D objects are continuously translated. If you set this property to a numeric value (world units), you can define in which
steps the 3D object should be translated. Deault is *null*.
</p>
| true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/exporters/ColladaExporter.html | @@ -57,7 +57,7 @@ <h3>[method:null parse]( [param:Object3D input], [param:Function onCompleted], [
// Collada file content
data: "",
- // List of referenced texures
+ // List of referenced textures
textures: [{
// File directory, name, and extension of the texture data | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/helpers/VertexNormalsHelper.html | @@ -55,7 +55,7 @@ <h2>Properties</h2>
<h3>[property:Object matrixAutoUpdate]</h3>
<p>
See [page:Object3D.matrixAutoUpdate]. Set to *false* here as the helper is using the
- objects's [page:Object3D.matrixWorld matrixWorld].
+ object's [page:Object3D.matrixWorld matrixWorld].
</p>
<h3>[property:Object3D object]</h3> | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/helpers/VertexTangentsHelper.html | @@ -54,7 +54,7 @@ <h2>Properties</h2>
<h3>[property:Object matrixAutoUpdate]</h3>
<p>
See [page:Object3D.matrixAutoUpdate]. Set to *false* here as the helper is using the
- objects's [page:Object3D.matrixWorld matrixWorld].
+ object's [page:Object3D.matrixWorld matrixWorld].
</p>
<h3>[property:Object3D object]</h3> | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/loaders/MMDLoader.html | @@ -91,7 +91,7 @@ <h3>[method:null loadAnimation]( [param:String url], [param:Object3D object], [p
[page:Function onError] — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.<br />
</p>
<p>
- Begin loading VMD motion file(s) from url(s) and fire the callback function with the parsed [page:AnimatioinClip].
+ Begin loading VMD motion file(s) from url(s) and fire the callback function with the parsed [page:AnimationClip].
</p>
<h3>[method:null loadWithAnimation]( [param:String modelUrl], [param:String vmdUrl], [param:Function onLoad], [param:Function onProgress], [param:Function onError] )</h3> | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/loaders/TGALoader.html | @@ -37,7 +37,7 @@ <h2>Code Example</h2>
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
- // called when the loading failes
+ // called when the loading fails
function ( error ) {
console.log( 'An error happened' ); | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/math/convexhull/ConvexHull.html | @@ -104,7 +104,7 @@ <h3>[method:ConvexHull compute]()</h3>
<h3>[method:Object computeExtremes]()</h3>
- <p>Computes the extremes values (min/max vectors) which will be used to compute the inital hull.</p>
+ <p>Computes the extremes values (min/max vectors) which will be used to compute the initial hull.</p>
<h3>[method:ConvexHull computeHorizon]( [param:Vector3 eyePoint], [param:HalfEdge crossEdge], [param:Face face], [param:Array horizon] )</h3>
<p> | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/math/convexhull/Face.html | @@ -10,7 +10,7 @@
<h1>[name]</h1>
<p class="desc">
- Represents a section bounded by a specific amount of half-edges. The current implmentation assumes that a face always consist of three edges.
+ Represents a section bounded by a specific amount of half-edges. The current implementation assumes that a face always consist of three edges.
</p>
| true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/math/convexhull/HalfEdge.html | @@ -55,7 +55,7 @@ <h3>[property:Face face]</h3>
<h2>Methods</h2>
<h3>[method:VertexNode head]()</h3>
- <p>Returns the destintation vertex.</p>
+ <p>Returns the destination vertex.</p>
<h3>[method:VertexNode tail]()</h3>
<p>Returns the origin vertex.</p> | true |
Other | mrdoob | three.js | b8c64be550e059a0af23fd65ecc6ef76b10983d3.json | Example documentation typos | docs/examples/en/postprocessing/EffectComposer.html | @@ -137,7 +137,7 @@ <h3>[method:void setPixelRatio]( [param:Float pixelRatio] )</h3>
<p>
pixelRatio -- The device pixel ratio.<br /><br />
- Sets device pixel ratio. This is usually used for HiDPI device to prevent bluring output.
+ Sets device pixel ratio. This is usually used for HiDPI device to prevent blurring output.
Thus, the semantic of the method is similar to [page:WebGLRenderer.setPixelRatio]().
</p>
| true |
Other | mrdoob | three.js | d9fa714202b9f9c687ffe848751e1565790adb56.json | Fix uniforms to support fog
Fixed uniforms of conditionalEdgeMaterial to support fog.
I think this is a bug, because its VertShader and FragShader is already support fog. | examples/js/loaders/LDrawLoader.js | @@ -998,14 +998,18 @@ THREE.LDrawLoader = ( function () {
edgeMaterial.userData.conditionalEdgeMaterial = new THREE.ShaderMaterial( {
vertexShader: conditionalLineVertShader,
fragmentShader: conditionalLineFragShader,
- uniforms: {
- diffuse: {
- value: new THREE.Color( edgeColour )
- },
- opacity: {
- value: alpha
+ uniforms: THREE.UniformsUtils.merge( [
+ THREE.UniformsLib.fog,
+ {
+ diffuse: {
+ value: new THREE.Color( edgeColour )
+ },
+ opacity: {
+ value: alpha
+ }
}
- },
+ ] ),
+ fog: true,
transparent: isTransparent,
depthWrite: ! isTransparent
} ); | false |
Other | mrdoob | three.js | 10710ebf2cbaee16d742094bf41d74a7c2304c91.json | Fix uniforms to support fog
Fixed uniforms of conditionalEdgeMaterial to support fog.
I think this is a bug, because its VertShader and FragShader are already support fog. | examples/jsm/loaders/LDrawLoader.js | @@ -13,6 +13,8 @@ import {
MeshPhongMaterial,
MeshStandardMaterial,
ShaderMaterial,
+ UniformsLib,
+ UniformsUtils,
Vector3
} from '../../../build/three.module.js';
@@ -1016,14 +1018,18 @@ var LDrawLoader = ( function () {
edgeMaterial.userData.conditionalEdgeMaterial = new ShaderMaterial( {
vertexShader: conditionalLineVertShader,
fragmentShader: conditionalLineFragShader,
- uniforms: {
- diffuse: {
- value: new Color( edgeColour )
- },
- opacity: {
- value: alpha
+ uniforms: UniformsUtils.merge( [
+ UniformsLib.fog,
+ {
+ diffuse: {
+ value: new Color( edgeColour )
+ },
+ opacity: {
+ value: alpha
+ }
}
- },
+ ] ),
+ fog: true,
transparent: isTransparent,
depthWrite: ! isTransparent
} ); | false |
Other | mrdoob | three.js | c9350382c50e549c0d2960041448ffe652bbbd9b.json | use ES6 default params to simplify code (#21662)
* use ES6 default params to simplify code
* simplify code | src/core/Clock.js | @@ -1,8 +1,8 @@
class Clock {
- constructor( autoStart ) {
+ constructor( autoStart = true ) {
- this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
+ this.autoStart = autoStart;
this.startTime = 0;
this.oldTime = 0; | true |
Other | mrdoob | three.js | c9350382c50e549c0d2960041448ffe652bbbd9b.json | use ES6 default params to simplify code (#21662)
* use ES6 default params to simplify code
* simplify code | src/extras/core/Curve.js | @@ -106,9 +106,7 @@ class Curve {
// Get list of cumulative segment lengths
- getLengths( divisions ) {
-
- if ( divisions === undefined ) divisions = this.arcLengthDivisions;
+ getLengths( divisions = this.arcLengthDivisions ) {
if ( this.cacheArcLengths &&
( this.cacheArcLengths.length === divisions + 1 ) && | true |
Other | mrdoob | three.js | 10a33e188b7f0fa85898bf8dba6253a52c994c7b.json | Use terser in test-treeshake command (#21650) | .gitignore | @@ -19,6 +19,7 @@ test/*
test/*.cmd
test/unit/build
test/treeshake/index.bundle.js
+test/treeshake/index.bundle.min.js
**/node_modules
\ No newline at end of file | true |
Other | mrdoob | three.js | 10a33e188b7f0fa85898bf8dba6253a52c994c7b.json | Use terser in test-treeshake command (#21650) | test/rollup.treeshake.config.js | @@ -1,18 +1,34 @@
import resolve from '@rollup/plugin-node-resolve';
import filesize from 'rollup-plugin-filesize';
+import { terser } from 'rollup-plugin-terser';
export default [
{
input: 'test/treeshake/index.js',
plugins: [
resolve(),
- filesize(),
],
output: [
{
format: 'esm',
file: 'test/treeshake/index.bundle.js'
}
]
+ },
+ {
+ input: 'test/treeshake/index.js',
+ plugins: [
+ resolve(),
+ terser(),
+ filesize( {
+ showMinifiedSize: false,
+ } ),
+ ],
+ output: [
+ {
+ format: 'esm',
+ file: 'test/treeshake/index.bundle.min.js'
+ }
+ ]
}
]; | true |
Other | mrdoob | three.js | 0d7fb8d74f3c4d4e465b5a92ada65e1c789708e1.json | Fix typo in TransformControls.html (#22840) | docs/examples/en/controls/TransformControls.html | @@ -103,7 +103,7 @@ <h3>[property:Object3D object]</h3>
<h3>[property:Number rotationSnap]</h3>
<p>
By default, 3D objects are continuously rotated. If you set this property to a numeric value (radians), you can define in which
- steps the 3D object should be rotated. Deault is *null*.
+ steps the 3D object should be rotated. Default is *null*.
</p>
<h3>[property:Boolean showX]</h3>
@@ -134,7 +134,7 @@ <h3>[property:String space]</h3>
<h3>[property:Number translationSnap]</h3>
<p>
By default, 3D objects are continuously translated. If you set this property to a numeric value (world units), you can define in which
- steps the 3D object should be translated. Deault is *null*.
+ steps the 3D object should be translated. Default is *null*.
</p>
<h2>Methods</h2> | false |
Other | mrdoob | three.js | b5c1e4d96e962e09646ab29e507a3bb1a2b23725.json | Use proper clearcoat variable (#22839) | src/renderers/shaders/ShaderLib/meshphysical.glsl.js | @@ -181,7 +181,7 @@ void main() {
vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
- outgoingLight = outgoingLight * ( 1.0 - clearcoat * Fcc ) + clearcoatSpecular * clearcoat;
+ outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;
#endif
| false |
Other | mrdoob | three.js | 904e56e78e4dd85e86bc36498e6a8a53bab6414d.json | Avoid clone() (#22830) | src/cameras/StereoCamera.js | @@ -4,6 +4,7 @@ import { PerspectiveCamera } from './PerspectiveCamera.js';
const _eyeRight = /*@__PURE__*/ new Matrix4();
const _eyeLeft = /*@__PURE__*/ new Matrix4();
+const _projectionMatrix = /*@__PURE__*/ new Matrix4();
class StereoCamera {
@@ -56,7 +57,7 @@ class StereoCamera {
// Off-axis stereoscopic effect based on
// http://paulbourke.net/stereographics/stereorender/
- const projectionMatrix = camera.projectionMatrix.clone();
+ _projectionMatrix.copy( camera.projectionMatrix );
const eyeSepHalf = cache.eyeSep / 2;
const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
const ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
@@ -72,20 +73,20 @@ class StereoCamera {
xmin = - ymax * cache.aspect + eyeSepOnProjection;
xmax = ymax * cache.aspect + eyeSepOnProjection;
- projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
- projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
+ _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
+ _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
- this.cameraL.projectionMatrix.copy( projectionMatrix );
+ this.cameraL.projectionMatrix.copy( _projectionMatrix );
// for right eye
xmin = - ymax * cache.aspect - eyeSepOnProjection;
xmax = ymax * cache.aspect - eyeSepOnProjection;
- projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
- projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
+ _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
+ _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
- this.cameraR.projectionMatrix.copy( projectionMatrix );
+ this.cameraR.projectionMatrix.copy( _projectionMatrix );
}
| false |
Other | mrdoob | three.js | 6258b52c8c962d2bd0d5f47290b19202f43468a2.json | Clarify .attach() limitations (#22821) | docs/api/en/core/Object3D.html | @@ -221,7 +221,9 @@ <h3>[method:this applyQuaternion]( [param:Quaternion quaternion] )</h3>
<p>Applies the rotation represented by the quaternion to the object.</p>
<h3>[method:this attach]( [param:Object3D object] )</h3>
- <p>Adds *object* as a child of this, while maintaining the object's world transform.</p>
+ <p>Adds *object* as a child of this, while maintaining the object's world transform.<br/><br/>
+ Note: This method does not support scene graphs having non-uniformly-scaled nodes(s).
+ </p>
<h3>[method:Object3D clone]( [param:Boolean recursive] )</h3>
<p> | true |
Other | mrdoob | three.js | 6258b52c8c962d2bd0d5f47290b19202f43468a2.json | Clarify .attach() limitations (#22821) | src/core/Object3D.js | @@ -405,6 +405,8 @@ class Object3D extends EventDispatcher {
// adds object as a child of this, while maintaining the object's world transform
+ // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
+
this.updateWorldMatrix( true, false );
_m1.copy( this.matrixWorld ).invert(); | true |
Other | mrdoob | three.js | 8bf2f2186eb3967b182b00910b5994112bae3dc3.json | Update SSAARenderPass.js (#22798)
Fix file references | examples/jsm/postprocessing/SSAARenderPass.js | @@ -7,7 +7,7 @@ import {
UniformsUtils,
WebGLRenderTarget
} from '../../../build/three.module.js';
-import { Pass, FullScreenQuad } from '../postprocessing/Pass.js';
+import { Pass, FullScreenQuad } from './Pass.js';
import { CopyShader } from '../shaders/CopyShader.js';
/** | false |
Other | mrdoob | three.js | b58c7cc9d42eeb0af2fd8b88a195c68db36f5f97.json | fix closingTag error in three-primitives on zh_cn | threejs/lessons/zh_cn/threejs-primitives.md | @@ -24,7 +24,7 @@ Three.js 有很多图元。图元就是一些 3D 的形状,在运行时根据
<div id="Diagram-CylinderGeometry" data-primitive="CylinderGeometry">圆柱</div>
<div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">十二面体</div>
<div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">受挤压的 2D 形状,及可选的斜切。
-这里我们挤压了一个心型。注意,这分别是 <code>TextGeometry</code> 和 <code>TextGeometry</code> 的基础。<div>
+这里我们挤压了一个心型。注意,这分别是 <code>TextGeometry</code> 和 <code>TextGeometry</code> 的基础。</div>
<div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">二十面体</div>
<div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">绕着一条线旋转形成的形状。例如:灯泡、保龄球瓶、蜡烛、蜡烛台、酒瓶、玻璃杯等。你提供一系列点作为 2D 轮廓,并告诉 Three.js 沿着某条轴旋转时需要将侧面分成多少块。</div>
<div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">八面体</div> | false |
Other | mrdoob | three.js | 26f7cb8be721cd0cb4d4bc4ab4b488d97c97fa3e.json | fix offscreen orbitcontrols | threejs/offscreencanvas-worker-orbitcontrols.js | @@ -7,13 +7,18 @@ function noop() {
class ElementProxyReceiver extends EventDispatcher {
constructor() {
super();
+ // because OrbitControls try to set style.touchAction;
+ this.style = {};
}
get clientWidth() {
return this.width;
}
get clientHeight() {
return this.height;
}
+ // OrbitControls call these as of r132. Maybe we should implement them
+ setPointerCapture() { }
+ releasePointerCapture() { }
getBoundingClientRect() {
return {
left: this.left, | false |
Other | mrdoob | three.js | 7ee89b908ee93833e6bd93de0db416f8f44135bb.json | add French translation | threejs/lessons/fr/threejs-fog.md | @@ -128,33 +128,26 @@ On peut l'ajouter comme ceci.
}
```
-The `near` and `far` parameters set the minimum and maximum values
-for adjusting the fog. They are set when we setup the camera.
+Les paramètres `near` et `far` définissent les valeurs minimales et maximales pour ajuster le brouillard. Ils sont définis lors de la configuration de la caméra.
-The `.listen()` at the end of the last 2 lines tells dat.GUI to *listen*
-for changes. That way when we change `near` because of an edit to `far`
-or we change `far` in response to an edit to `near` dat.GUI will update
-the other property's UI for us.
+Le `.listen()` à la fin des 2 lignes, dit à dat.GUI *d'écouter*
+les changements. Ainsi, que nous changions `near` ou `far`, dat.GUI mettra automatiquement à jour les deux propriétés pour nous.
-It might also be nice to be able to change the fog color but like was
-mentioned above we need to keep both the fog color and the background
-color in sync. So, let's add another *virtual* property to our helper
-that will set both colors when dat.GUI manipulates it.
+Il peut également être agréable de pouvoir changer la couleur du brouillard, mais comme mentionné ci-dessus, nous devons synchroniser la couleur du brouillard et la couleur de l'arrière-plan. Ajoutons donc une autre propriété *virtuelle* à notre helper qui définira les deux couleurs lorsque dat.GUI la manipule.
-dat.GUI can manipulate colors in 4 ways, as a CSS 6 digit hex string (eg: `#112233`). As an hue, saturation, value, object (eg: `{h: 60, s: 1, v: }`).
-As an RGB array (eg: `[255, 128, 64]`). Or, as an RGBA array (eg: `[127, 200, 75, 0.3]`).
+dat.GUI peut manipuler les couleurs de 4 façons différentes. Sous la forme d'une chaîne hexadécimale à 6 chiffres (ex : `#112233`). Sous la forme HSL (ex : `{h: 60, s: 1, v: }`).
+En tant que tableau RGB (ex : `[255, 128, 64]`). Ou, comme un tableau RGBA (ex : `[127, 200, 75, 0.3]`).
-It's easiest for our purpose to use the hex string version since that way
-dat.GUI is only manipulating a single value. Fortunately `THREE.Color`
-as a [`getHexString`](Color.getHexString) method
-we get use to easily get such a string, we just have to prepend a '#' to the front.
+Il est plus simple d'utiliser la première solution, la version chaîne hexadécimale, ainsi
+dat.GUI nemanipule qu'une seule valeur. Heureusement, `THREE.Color`
+a une méthode pour cela : [`getHexString`](Color.getHexString) qui permet d'obtenir une telle chaîne, il suffit juste d'ajouter un '#' au début.
```js
-// We use this class to pass to dat.gui
-// so when it manipulates near or far
-// near is never > far and far is never < near
-+// Also when dat.gui manipulates color we'll
-+// update both the fog and background colors.
+/// On utilise cette classe pour passer à dat.gui
+// donc quand il manipule near ou far
+// near n'est jamais > far et far n'est jamais < near
++// Aussi, lorsque dat.gui manipule la couleur, nous allons
++// mettre à jour les couleurs du brouillard et de l'arrière-plan.
class FogGUIHelper {
* constructor(fog, backgroundColor) {
this.fog = fog;
@@ -184,7 +177,7 @@ class FogGUIHelper {
}
```
-We then call `gui.addColor` to add a color UI for our helper's virtual property.
+Ensuite, nous appelons `gui.addColor` pour ajouter une couleur à notre propriété virtuelle.
```js
{
@@ -203,28 +196,11 @@ We then call `gui.addColor` to add a color UI for our helper's virtual property.
{{{example url="../threejs-fog-gui.html" }}}
-You can see setting `near` to like 1.9 and `far` to 2.0 gives
-a very sharp transition between un-fogged and completely fogged.
-where as `near` = 1.1 and `far` = 2.9 should just about be
-the smoothest given our cubes are spinning 2 units away from the camera.
-
-One last thing, there is a boolean [`fog`](Material.fog)
-property on a material for whether or not objects rendered
-with that material are affected by fog. It defaults to `true`
-for most materials. As an example of why you might want
-to turn the fog off, imagine you're making a 3D vehicle
-simulator with a view from the driver's seat or cockpit.
-You probably want the fog off for everything inside the vehicle when
-viewing from inside the vehicle.
-
-A better example might be a house
-and thick fog outside house. Let's say the fog is set to start
-2 meters away (near = 2) and completely fogged out at 4 meters (far = 4).
-Rooms are longer than 2 meters and the house is probably longer
-than 4 meters so you need to set the materials for the inside
-of the house to not apply fog otherwise when standing inside the
-house looking outside the wall at the far end of the room will look
-like it's in the fog.
+Vous pouvez voir qu'un réglage `near` à 1.9 et `far` à 2,0 donne une transition très nette entre non embué et complètement dans le brouillard. `near` = 1,1 et `far` = 2,9 devrait être la meilleure configuration étant donné que nos cubes tournent à 2 unités de la caméra.
+
+Une dernière chose, il existe une propriété [les matériaux](Material.fog) pour savoir si les objets rendus avec ce matériau sont affectés ou non par le brouillard. La valeur par défaut est `true` pour la plupart des matériaux. Pour illustrer pourquoi vous pourriez vouloir désactiver le brouillard, imaginez que vous créez un simulateur de véhicule 3D avec une vue depuis le siège du conducteur ou le cockpit. Vous voulez probablement que le brouillard se dissipe pour tout ce qui se trouve à l'intérieur du véhicule lorsque vous regardez de l'intérieur du véhicule.
+
+Prenons un autre exemple. Une maison avec un épais brouillard à l'extérieur. Disons que pour commencer, le brouillard est réglé pour commencer à 2 mètres (near = 2) et être complet à 4 mètres (far = 4). Les pièces et la maison faisant probablement plus de 4 mètres, il faudra donc définir les matériaux utilisés à l'intérieur de la maison pour qu'il n'y est pas de brouillard. Sinon, ça donnerait ceci.
<div class="spread">
<div>
@@ -233,8 +209,7 @@ like it's in the fog.
</div>
</div>
-Notice the walls and ceiling at the far end of the room are getting fog applied.
-By turning fog off on the materials for the house we can fix that issue.
+Remarquez que les murs et le plafond au fond de la pièce sont dans le brouillard. En désactivant le brouillard sur les matériaux de la maison, on résoud le problème.
<div class="spread">
<div> | false |
Other | mrdoob | three.js | 00933157822504e24b5138ae1351dde95fc57af2.json | add French Translation | threejs/lessons/fr/threejs-textures.md | @@ -1,5 +1,5 @@
-Title: Les textures dans Three.js
-Description: Comment utiliser les textures dans Three.js
+Title: Three.js Textures
+Description: Using textures in three.js
TOC: Textures
Cet article fait partie d'une série consacrée à Three.js. | false |
Other | mrdoob | three.js | 8b54e19b84b163a93c8f53c54de02eb18f2ff788.json | add French translation | threejs/lessons/fr/threejs-materials.md | @@ -1,6 +1,6 @@
-Title: Les Matériaux dans Three.js
-Description: Les Matériaux dans Three.js
-TOC: Matériaux
+Title: Les Materials de Three.js
+Description: Les Materials dans Three.js
+TOC: Materials
Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html). | false |
Other | mrdoob | three.js | 22b2790d70d50f08c73a94770630b4bc6a1734d2.json | add French translation | threejs/lessons/fr/threejs-scenegraph.md | @@ -1,12 +1,12 @@
-Title: Graphe de scène Three.js
-Description: What's a scene graph?
+Title: Graphique de scène de Three.js
+Description: Qu'est-ce qu'un graphique de scène ?
TOC: Scenegraph
Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
-Le coeurs de Three.js est sans aucun doute son graphique de scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
+Le coeurs de Three.js est sans aucun doute son graphique de scène. Un graphique de scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
<img src="resources/images/scenegraph-generic.svg" align="center">
| false |
Other | mrdoob | three.js | 98388fcc43b1e2eb9bd17ab352e85331f33e0a15.json | add French translation | threejs/lessons/fr/threejs-scenegraph.md | @@ -6,7 +6,7 @@ Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
-Le coeurs de Three.js est sans aucun doute son objet scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
+Le coeurs de Three.js est sans aucun doute son graphique de scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
<img src="resources/images/scenegraph-generic.svg" align="center">
@@ -176,31 +176,26 @@ objects.push(earthMesh);
+moonOrbit.add(moonMesh);
+objects.push(moonMesh);
```
-XXXXXXXXXXXXXXXX
-
-Again we added more invisible scene graph nodes. The first, an `Object3D` called `earthOrbit`
-and added both the `earthMesh` and the `moonOrbit` to it, also new. We then added the `moonMesh`
-to the `moonOrbit`. The new scene graph looks like this.
+Ajoutons à nouveau d'autres noeuds à notre scène. D'abord, un `Object3D` appelé `earthOrbit`
+ensuite ajoutons-lui un `earthMesh` et un `moonOrbit`. Finalement, ajoutons un `moonMesh`
+au `moonOrbit`. Notre scène devrait ressembler à ceci :
<img src="resources/images/scenegraph-sun-earth-moon.svg" align="center">
-and here's that
+et à ça :
{{{example url="../threejs-scenegraph-sun-earth-moon.html" }}}
-You can see the moon follows the spirograph pattern shown at the top
-of this article but we didn't have to manually compute it. We just
-setup our scene graph to do it for us.
+Vous pouvez voir que la lune suit le modèle de spirographe indiqué en haut de cet article, mais nous n'avons pas eu à le calculer manuellement. Nous venons de configurer notre graphe de scène pour le faire pour nous.
-It is often useful to draw something to visualize the nodes in the scene graph.
-Three.js has some helpful ummmm, helpers to ummm, ... help with this.
+Il est souvent utile de dessiner quelque chose pour visualiser les nœuds dans le graphe de scène.
+Three.js dispose pour cela de Helpers.
-One is called an `AxesHelper`. It draws 3 lines representing the local
+L'un d'entre eux s'appelle `AxesHelper`. Il dessine trois lignes représentant les axes
<span style="color:red">X</span>,
-<span style="color:green">Y</span>, and
-<span style="color:blue">Z</span> axes. Let's add one to every node we
-created.
+<span style="color:green">Y</span>, et
+<span style="color:blue">Z</span>. Ajoutons-en un à chacun de nos noeuds.
```js
// add an AxesHelper to each node
@@ -212,35 +207,20 @@ objects.forEach((node) => {
});
```
-On our case we want the axes to appear even though they are inside the spheres.
-To do this we set their material's `depthTest` to false which means they will
-not check to see if they are drawing behind something else. We also
-set their `renderOrder` to 1 (the default is 0) so that they get drawn after
-all the spheres. Otherwise a sphere might draw over them and cover them up.
+Dans notre cas, nous voulons que les axes apparaissent même s'ils sont à l'intérieur des sphères.
+Pour cela, nous définissons le `depthTest` de material à false, pour ne pas vérifier s'ils dessinent derrière quelque chose. Nous définissons également leur `renderOrder` sur 1 (la valeur par défaut est 0) afin qu'ils soient dessinés après toutes les sphères. Sinon, une sphère pourrait les recouvrir et les recouvrir.
{{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}}
-We can see the
-<span style="color:red">x (red)</span> and
-<span style="color:blue">z (blue)</span> axes. Since we are looking
-straight down and each of our objects is only rotating around its
-y axis we don't see much of the <span style="color:green">y (green)</span> axes.
+Vous pouvez voir les axes
+<span style="color:red">x (rouge)</span> et
+<span style="color:blue">z (bleu)</span>. Comme nous regardons vers le bas et que chacun de nos objets tourne autour de son axe y, nous ne voyons pas bien l'axe <span style="color:green">y (verte)</span>.
-It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the `sunMesh`
-and the `solarSystem` are at the same position. Similarly the `earthMesh` and
-`earthOrbit` are at the same position. Let's add some simple controls to allow us
-to turn them on/off for each node.
-While we're at it let's also add another helper called the `GridHelper`. It
-makes a 2D grid on the X,Z plane. By default the grid is 10x10 units.
+Il peut être difficile de voir certains d'entre eux car il y a 2 paires d'axes qui se chevauchent. Le `sunMesh` et le `solarSystem` sont tous les deux à la même position. De même, `earthMesh` et `earthOrbit` sont à la même position. Ajoutons quelques contrôles simples pour nous permettre de les activer/désactiver pour chaque nœud. Pendant que nous y sommes, ajoutons également un autre assistant appelé `GridHelper`. Il crée une grille 2D sur le plan X,Z. Par défaut, la grille est de 10x10 unités.
-We're also going to use [dat.GUI](https://github.com/dataarts/dat.gui) which is
-a UI library that is very popular with three.js projects. dat.GUI takes an
-object and a property name on that object and based on the type of the property
-automatically makes a UI to manipulate that property.
+Nous allons également utiliser [dat.GUI](https://github.com/dataarts/dat.gui), une librairie d'interface utilisateur très populaire pour les projets Three.js. dat.GUI prend un objet et un nom de propriété sur cet objet et, en fonction du type de la propriété, crée automatiquement une interface utilisateur pour manipuler cette propriété.
-We want to make both a `GridHelper` and an `AxesHelper` for each node. We need
-a label for each node so we'll get rid of the old loop and switch to calling
-some function to add the helpers for each node
+Nous voulons créer à la fois un `GridHelper` et un `AxesHelper` pour chaque nœud. Nous avons besoin d'un label pour chaque nœud, nous allons donc nous débarrasser de l'ancienne boucle et faire appel à une fonction pour ajouter les helpers pour chaque nœud.
```js
-// add an AxesHelper to each node
@@ -263,24 +243,14 @@ some function to add the helpers for each node
+makeAxisGrid(moonOrbit, 'moonOrbit');
+makeAxisGrid(moonMesh, 'moonMesh');
```
-
-`makeAxisGrid` makes an `AxisGridHelper` which is a class we'll create
-to make dat.GUI happy. Like it says above dat.GUI
-will automagically make a UI that manipulates the named property
-of some object. It will create a different UI depending on the type
-of property. We want it to create a checkbox so we need to specify
-a `bool` property. But, we want both the axes and the grid
-to appear/disappear based on a single property so we'll make a class
-that has a getter and setter for a property. That way we can let dat.GUI
-think it's manipulating a single property but internally we can set
-the visible property of both the `AxesHelper` and `GridHelper` for a node.
+`makeAxisGrid` crée un `AxisGridHelper` qui est une classe que nous allons créer pour rendre dat.GUI heureux. Comme il est dit ci-dessus, dat.GUI créera automatiquement une interface utilisateur qui manipule la propriété nommée d'un objet. Cela créera une interface utilisateur différente selon le type de propriété. Nous voulons qu'il crée une case à cocher, nous devons donc spécifier une propriété bool. Mais, nous voulons que les axes et la grille apparaissent/disparaissent en fonction d'une seule propriété, nous allons donc créer une classe qui a un getter et un setter pour une propriété. De cette façon, nous pouvons laisser dat.GUI penser qu'il manipule une seule propriété, mais en interne, nous pouvons définir la propriété visible de `AxesHelper` et `GridHelper` pour un nœud.
```js
-// Turns both axes and grid visible on/off
-// dat.GUI requires a property that returns a bool
-// to decide to make a checkbox so we make a setter
-// and getter for `visible` which we can tell dat.GUI
-// to look at.
+// Activer/désactiver les axes et la grille dat.GUI
+// nécessite une propriété qui renvoie un bool
+// pour décider de faire une case à cocher
+// afin que nous créions un setter et un getter pour `visible`
+// que nous pouvons dire à dat.GUI de regarder.
class AxisGridHelper {
constructor(node, units = 10) {
const axes = new THREE.AxesHelper();
@@ -308,57 +278,40 @@ class AxisGridHelper {
}
```
-One thing to notice is we set the `renderOrder` of the `AxesHelper`
-to 2 and for the `GridHelper` to 1 so that the axes get drawn after the grid.
-Otherwise the grid might overwrite the axes.
+Une chose à noter est que nous définissons le `renderOrder` de l'`AxesHelper` sur 2 et pour le `GridHelper` sur 1 afin que les axes soient dessinés après la grille. Sinon, la grille pourrait écraser les axes.
{{{example url="../threejs-scenegraph-sun-earth-moon-axes-grids.html" }}}
-Turn on the `solarSystem` and you'll see how the earth is exactly 10
-units out from the center just like we set above. You can see how the
-earth is in the *local space* of the `solarSystem`. Similarly if you
-turn on the `earthOrbit` you'll see how the moon is exactly 2 units
-from the center of the *local space* of the `earthOrbit`.
+Cliquez sur `solarSystem` et vous verrez que la terre est exactement à 10 unités du centre, comme nous l'avons défini ci-dessus. Vous pouvez voir que la terre est dans l'espace local du `solarSystem`. De même, si vous cliquez sur `earthOrbit`, vous verrez que la lune est exactement à 2 unités du centre de *l'espace local* de `earthOrbit`.
-A few more examples of scene graphs. An automobile in a simple game world might have a scene graph like this
+Un autre exemple de scène. Une automobile dans un jeu simple pourrait avoir un graphique de scène comme celui-ci
<img src="resources/images/scenegraph-car.svg" align="center">
-If you move the car's body all the wheels will move with it. If you wanted the body
-to bounce separate from the wheels you might parent the body and the wheels to a "frame" node
-that represents the car's frame.
+Si vous déplacez la carrosserie de la voiture, toutes les roues bougeront avec elle. Si vous vouliez que le corps rebondisse séparément des roues, vous pouvez lier le corps et les roues à un nœud "cadre" qui représente le cadre de la voiture.
-Another example is a human in a game world.
+Un autre exemple avec un humain dans un jeu vidéo.
<img src="resources/images/scenegraph-human.svg" align="center">
-You can see the scene graph gets pretty complex for a human. In fact
-that scene graph above is simplified. For example you might extend it
-to cover every finger (at least another 28 nodes) and every toe
-(yet another 28 nodes) plus ones for the face and jaw, the eyes and maybe more.
+Vous pouvez voir que le graphique de la scène devient assez complexe pour un humain. En fait, le graphe ci-dessus est simplifié. Par exemple, vous pouvez l'étendre pour couvrir chaque doigt (au moins 28 autres nœuds) et chaque orteil (encore 28 nœuds) plus ceux pour le visage et la mâchoire, les yeux et peut-être plus.
+
+Faisons un graphe semi-complexe. On va faire un char. Il aura 6 roues et une tourelle. Il pourra suivre un chemin. Il y aura une sphère qui se déplacera et le char ciblera la sphère.
Let's make one semi-complex scene graph. We'll make a tank. The tank will have
6 wheels and a turret. The tank will follow a path. There will be a sphere that
moves around and the tank will target the sphere.
-Here's the scene graph. The meshes are colored in green, the `Object3D`s in blue,
-the lights in gold, and the cameras in purple. One camera has not been added
-to the scene graph.
+Voici le graphique de la scène. Les maillages sont colorés en vert, les `Object3D` en bleu, les lumières en or et les caméras en violet. Une caméra n'a pas été ajoutée au graphique de la scène.
<div class="threejs_center"><img src="resources/images/scenegraph-tank.svg" style="width: 800px;"></div>
-Look in the code to see the setup of all of these nodes.
+Regardez dans le code pour voir la configuration de tous ces nœuds.
-For the target, the thing the tank is aiming at, there is a `targetOrbit`
-(`Object3D`) which just rotates similar to the `earthOrbit` above. A
-`targetElevation` (`Object3D`) which is a child of the `targetOrbit` provides an
-offset from the `targetOrbit` and a base elevation. Childed to that is another
-`Object3D` called `targetBob` which just bobs up and down relative to the
-`targetElevation`. Finally there's the `targetMesh` which is just a cube we
-rotate and change its colors
+Pour la cible, la chose que le char vise, il y a une `targetOrbit` (Object3D) qui tourne juste de la même manière que la `earthOrbit` ci-dessus. Une `targetElevation` (Object3D) qui est un enfant de `targetOrbit` fournit un décalage par rapport à `targetOrbit` et une élévation de base. Un autre `Object3D` appelé `targetBob` qui monte et descend par rapport à la `targetElevation`. Enfin, il y a le `targetMesh` qui est juste un cube que nous faisons pivoter et changeons ses couleurs.
```js
-// move target
+// mettre en mouvement la cible
targetOrbit.rotation.y = time * .27;
targetBob.position.y = Math.sin(time * 2) * 4;
targetMesh.rotation.x = time * 7;
@@ -367,71 +320,59 @@ targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25);
targetMaterial.color.setHSL(time * 10 % 1, 1, .25);
```
-For the tank there's an `Object3D` called `tank` which is used to move everything
-below it around. The code uses a `SplineCurve` which it can ask for positions
-along that curve. 0.0 is the start of the curve. 1.0 is the end of the curve. It
-asks for the current position where it puts the tank. It then asks for a
-position slightly further down the curve and uses that to point the tank in that
-direction using `Object3D.lookAt`.
+Pour le char, il y a un `Object3D` appelé `tank` qui est utilisé pour déplacer tout ce qui se trouve en dessous. Le code utilise une `SplineCurve` à laquelle il peut demander des positions le long de cette courbe. 0.0 est le début de la courbe. 1,0 est la fin de la courbe. Il demande la position actuelle où il met le réservoir. Il demande ensuite une position légèrement plus bas dans la courbe et l'utilise pour pointer le réservoir dans cette direction à l'aide de `Object3D.lookAt`.
```js
const tankPosition = new THREE.Vector2();
const tankTarget = new THREE.Vector2();
...
-// move tank
+// mettre en mouvement le char
const tankTime = time * .05;
curve.getPointAt(tankTime % 1, tankPosition);
curve.getPointAt((tankTime + 0.01) % 1, tankTarget);
tank.position.set(tankPosition.x, 0, tankPosition.y);
tank.lookAt(tankTarget.x, 0, tankTarget.y);
```
-The turret on top of the tank is moved automatically by being a child
-of the tank. To point it at the target we just ask for the target's world position
-and then again use `Object3D.lookAt`
+La tourelle sur le dessus du char est déplacée automatiquement en tant qu'enfant du char. Pour le pointer sur la cible, nous demandons simplement la position de la cible, puis utilisons à nouveau `Object3D.lookAt`.
```js
const targetPosition = new THREE.Vector3();
...
-// face turret at target
+// tourelle face à la cible
targetMesh.getWorldPosition(targetPosition);
turretPivot.lookAt(targetPosition);
```
-
-There's a `turretCamera` which is a child of the `turretMesh` so
-it will move up and down and rotate with the turret. We make that
-aim at the target.
+Il y a une `tourretCamera` qui est un enfant de `turretMesh` donc il se déplacera de haut en bas et tournera avec la tourelle. On la fait viser la cible.
```js
-// make the turretCamera look at target
+// la turretCamera regarde la cible
turretCamera.lookAt(targetPosition);
```
-
-There is also a `targetCameraPivot` which is a child of `targetBob` so it floats
-around with the target. We aim that back at the tank. Its purpose is to allow the
-`targetCamera` to be offset from the target itself. If we instead made the camera
-a child of `targetBob` and just aimed the camera itself it would be inside the
-target.
+Il y a aussi un `targetCameraPivot` qui est un enfant de `targetBob` donc il flotte
+autour de la cible. Nous le pointons vers le char. Son but est de permettre à la
+`targetCamera` d'être décalé par rapport à la cible elle-même. Si nous faisions de la caméra
+un enfant de `targetBob`, elle serait à l'intérieur de la cible.
```js
-// make the targetCameraPivot look at the tank
+// faire en sorte que la cibleCameraPivot regarde le char
tank.getWorldPosition(targetPosition);
targetCameraPivot.lookAt(targetPosition);
```
-Finally we rotate all the wheels
+Enfin on fait tourner toutes les roues
```js
wheelMeshes.forEach((obj) => {
obj.rotation.x = time * 3;
});
```
-For the cameras we setup an array of all 4 cameras at init time with descriptions.
+Pour les caméras, nous avons configuré un ensemble de 4 caméras au moment de l'initialisation avec des descriptions.
```js
const cameras = [
@@ -444,7 +385,7 @@ const cameras = [
const infoElem = document.querySelector('#info');
```
-and cycle through our cameras at render time.
+et nous parcourons chaque camera au moment du rendu
```js
const camera = cameras[time * .25 % cameras.length | 0];
@@ -453,11 +394,11 @@ infoElem.textContent = camera.desc;
{{{example url="../threejs-scenegraph-tank.html"}}}
-I hope this gives some idea of how scene graphs work and how you might use them.
-Making `Object3D` nodes and parenting things to them is an important step to using
-a 3D engine like three.js well. Often it might seem like some complex math is necessary
-to make something move and rotate the way you want. For example without a scene graph
-computing the motion of the moon or where to put the wheels of the car relative to its
-body would be very complicated but using a scene graph it becomes much easier.
+J'espère que cela donne une idée du fonctionnement des graphiques de scène et de la façon dont vous pouvez les utiliser.
+Faire des nœuds « Object3D » et leur attacher des choses est une étape importante pour utiliser
+un moteur 3D comme Three.js bien. Souvent, on pourrait penser que des mathématiques complexes soient nécessaires
+pour faire bouger quelque chose et faire pivoter comme vous le souhaitez. Par exemple sans graphique de scène
+calculer le mouvement de la lune, savoir où placer les roues de la voiture par rapport à son
+corps serait très compliqué, mais en utilisant un graphique de scène, cela devient beaucoup plus facile.
-[Next up we'll go over materials](threejs-materials.html).
+[Passons maintenant en revue les materials](threejs-materials.html). | false |
Other | mrdoob | three.js | bd8a2b9b140108e38a9c6844c53ab8ac669b5177.json | add French translation | threejs/lessons/fr/threejs-scenegraph.md | @@ -1,12 +1,12 @@
-Title: Graphique de scène de Three.js
-Description: Qu'est-ce qu'un graphique de scène ?
-TOC: Graphique de scène
+Title: Graphe de scène Three.js
+Description: What's a scene graph?
+TOC: Scenegraph
Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
-Le coeurs de Three.js est sans aucun doute son graphique de scène. Un graphique de scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
+Le coeurs de Three.js est sans aucun doute son objet scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
<img src="resources/images/scenegraph-generic.svg" align="center">
@@ -176,26 +176,31 @@ objects.push(earthMesh);
+moonOrbit.add(moonMesh);
+objects.push(moonMesh);
```
+XXXXXXXXXXXXXXXX
-Ajoutons à nouveau d'autres noeuds à notre scène. D'abord, un `Object3D` appelé `earthOrbit`
-ensuite ajoutons-lui un `earthMesh` et un `moonOrbit`. Finalement, ajoutons un `moonMesh`
-au `moonOrbit`. Notre scène devrait ressembler à ceci :
+
+Again we added more invisible scene graph nodes. The first, an `Object3D` called `earthOrbit`
+and added both the `earthMesh` and the `moonOrbit` to it, also new. We then added the `moonMesh`
+to the `moonOrbit`. The new scene graph looks like this.
<img src="resources/images/scenegraph-sun-earth-moon.svg" align="center">
-et à ça :
+and here's that
{{{example url="../threejs-scenegraph-sun-earth-moon.html" }}}
-Vous pouvez voir que la lune suit le modèle de spirographe indiqué en haut de cet article, mais nous n'avons pas eu à le calculer manuellement. Nous venons de configurer notre graphe de scène pour le faire pour nous.
+You can see the moon follows the spirograph pattern shown at the top
+of this article but we didn't have to manually compute it. We just
+setup our scene graph to do it for us.
-Il est souvent utile de dessiner quelque chose pour visualiser les nœuds dans le graphe de scène.
-Three.js dispose pour cela de Helpers.
+It is often useful to draw something to visualize the nodes in the scene graph.
+Three.js has some helpful ummmm, helpers to ummm, ... help with this.
-L'un d'entre eux s'appelle `AxesHelper`. Il dessine trois lignes représentant les axes
+One is called an `AxesHelper`. It draws 3 lines representing the local
<span style="color:red">X</span>,
-<span style="color:green">Y</span>, et
-<span style="color:blue">Z</span>. Ajoutons-en un à chacun de nos noeuds.
+<span style="color:green">Y</span>, and
+<span style="color:blue">Z</span> axes. Let's add one to every node we
+created.
```js
// add an AxesHelper to each node
@@ -207,20 +212,35 @@ objects.forEach((node) => {
});
```
-Dans notre cas, nous voulons que les axes apparaissent même s'ils sont à l'intérieur des sphères.
-Pour cela, nous définissons le `depthTest` de material à false, pour ne pas vérifier s'ils dessinent derrière quelque chose. Nous définissons également leur `renderOrder` sur 1 (la valeur par défaut est 0) afin qu'ils soient dessinés après toutes les sphères. Sinon, une sphère pourrait les recouvrir et les recouvrir.
+On our case we want the axes to appear even though they are inside the spheres.
+To do this we set their material's `depthTest` to false which means they will
+not check to see if they are drawing behind something else. We also
+set their `renderOrder` to 1 (the default is 0) so that they get drawn after
+all the spheres. Otherwise a sphere might draw over them and cover them up.
{{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}}
-Vous pouvez voir les axes
-<span style="color:red">x (rouge)</span> et
-<span style="color:blue">z (bleu)</span>. Comme nous regardons vers le bas et que chacun de nos objets tourne autour de son axe y, nous ne voyons pas bien l'axe <span style="color:green">y (verte)</span>.
+We can see the
+<span style="color:red">x (red)</span> and
+<span style="color:blue">z (blue)</span> axes. Since we are looking
+straight down and each of our objects is only rotating around its
+y axis we don't see much of the <span style="color:green">y (green)</span> axes.
-Il peut être difficile de voir certains d'entre eux car il y a 2 paires d'axes qui se chevauchent. Le `sunMesh` et le `solarSystem` sont tous les deux à la même position. De même, `earthMesh` et `earthOrbit` sont à la même position. Ajoutons quelques contrôles simples pour nous permettre de les activer/désactiver pour chaque nœud. Pendant que nous y sommes, ajoutons également un autre assistant appelé `GridHelper`. Il crée une grille 2D sur le plan X,Z. Par défaut, la grille est de 10x10 unités.
+It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the `sunMesh`
+and the `solarSystem` are at the same position. Similarly the `earthMesh` and
+`earthOrbit` are at the same position. Let's add some simple controls to allow us
+to turn them on/off for each node.
+While we're at it let's also add another helper called the `GridHelper`. It
+makes a 2D grid on the X,Z plane. By default the grid is 10x10 units.
-Nous allons également utiliser [dat.GUI](https://github.com/dataarts/dat.gui), une librairie d'interface utilisateur très populaire pour les projets Three.js. dat.GUI prend un objet et un nom de propriété sur cet objet et, en fonction du type de la propriété, crée automatiquement une interface utilisateur pour manipuler cette propriété.
+We're also going to use [dat.GUI](https://github.com/dataarts/dat.gui) which is
+a UI library that is very popular with three.js projects. dat.GUI takes an
+object and a property name on that object and based on the type of the property
+automatically makes a UI to manipulate that property.
-Nous voulons créer à la fois un `GridHelper` et un `AxesHelper` pour chaque nœud. Nous avons besoin d'un label pour chaque nœud, nous allons donc nous débarrasser de l'ancienne boucle et faire appel à une fonction pour ajouter les helpers pour chaque nœud.
+We want to make both a `GridHelper` and an `AxesHelper` for each node. We need
+a label for each node so we'll get rid of the old loop and switch to calling
+some function to add the helpers for each node
```js
-// add an AxesHelper to each node
@@ -243,14 +263,24 @@ Nous voulons créer à la fois un `GridHelper` et un `AxesHelper` pour chaque n
+makeAxisGrid(moonOrbit, 'moonOrbit');
+makeAxisGrid(moonMesh, 'moonMesh');
```
-`makeAxisGrid` crée un `AxisGridHelper` qui est une classe que nous allons créer pour rendre dat.GUI heureux. Comme il est dit ci-dessus, dat.GUI créera automatiquement une interface utilisateur qui manipule la propriété nommée d'un objet. Cela créera une interface utilisateur différente selon le type de propriété. Nous voulons qu'il crée une case à cocher, nous devons donc spécifier une propriété bool. Mais, nous voulons que les axes et la grille apparaissent/disparaissent en fonction d'une seule propriété, nous allons donc créer une classe qui a un getter et un setter pour une propriété. De cette façon, nous pouvons laisser dat.GUI penser qu'il manipule une seule propriété, mais en interne, nous pouvons définir la propriété visible de `AxesHelper` et `GridHelper` pour un nœud.
+
+`makeAxisGrid` makes an `AxisGridHelper` which is a class we'll create
+to make dat.GUI happy. Like it says above dat.GUI
+will automagically make a UI that manipulates the named property
+of some object. It will create a different UI depending on the type
+of property. We want it to create a checkbox so we need to specify
+a `bool` property. But, we want both the axes and the grid
+to appear/disappear based on a single property so we'll make a class
+that has a getter and setter for a property. That way we can let dat.GUI
+think it's manipulating a single property but internally we can set
+the visible property of both the `AxesHelper` and `GridHelper` for a node.
```js
-// Activer/désactiver les axes et la grille dat.GUI
-// nécessite une propriété qui renvoie un bool
-// pour décider de faire une case à cocher
-// afin que nous créions un setter et un getter pour `visible`
-// que nous pouvons dire à dat.GUI de regarder.
+// Turns both axes and grid visible on/off
+// dat.GUI requires a property that returns a bool
+// to decide to make a checkbox so we make a setter
+// and getter for `visible` which we can tell dat.GUI
+// to look at.
class AxisGridHelper {
constructor(node, units = 10) {
const axes = new THREE.AxesHelper();
@@ -278,40 +308,57 @@ class AxisGridHelper {
}
```
-Une chose à noter est que nous définissons le `renderOrder` de l'`AxesHelper` sur 2 et pour le `GridHelper` sur 1 afin que les axes soient dessinés après la grille. Sinon, la grille pourrait écraser les axes.
+One thing to notice is we set the `renderOrder` of the `AxesHelper`
+to 2 and for the `GridHelper` to 1 so that the axes get drawn after the grid.
+Otherwise the grid might overwrite the axes.
{{{example url="../threejs-scenegraph-sun-earth-moon-axes-grids.html" }}}
-Cliquez sur `solarSystem` et vous verrez que la terre est exactement à 10 unités du centre, comme nous l'avons défini ci-dessus. Vous pouvez voir que la terre est dans l'espace local du `solarSystem`. De même, si vous cliquez sur `earthOrbit`, vous verrez que la lune est exactement à 2 unités du centre de *l'espace local* de `earthOrbit`.
+Turn on the `solarSystem` and you'll see how the earth is exactly 10
+units out from the center just like we set above. You can see how the
+earth is in the *local space* of the `solarSystem`. Similarly if you
+turn on the `earthOrbit` you'll see how the moon is exactly 2 units
+from the center of the *local space* of the `earthOrbit`.
-Un autre exemple de scène. Une automobile dans un jeu simple pourrait avoir un graphique de scène comme celui-ci
+A few more examples of scene graphs. An automobile in a simple game world might have a scene graph like this
<img src="resources/images/scenegraph-car.svg" align="center">
-Si vous déplacez la carrosserie de la voiture, toutes les roues bougeront avec elle. Si vous vouliez que le corps rebondisse séparément des roues, vous pouvez lier le corps et les roues à un nœud "cadre" qui représente le cadre de la voiture.
+If you move the car's body all the wheels will move with it. If you wanted the body
+to bounce separate from the wheels you might parent the body and the wheels to a "frame" node
+that represents the car's frame.
-Un autre exemple avec un humain dans un jeu vidéo.
+Another example is a human in a game world.
<img src="resources/images/scenegraph-human.svg" align="center">
-Vous pouvez voir que le graphique de la scène devient assez complexe pour un humain. En fait, le graphe ci-dessus est simplifié. Par exemple, vous pouvez l'étendre pour couvrir chaque doigt (au moins 28 autres nœuds) et chaque orteil (encore 28 nœuds) plus ceux pour le visage et la mâchoire, les yeux et peut-être plus.
-
-Faisons un graphe semi-complexe. On va faire un char. Il aura 6 roues et une tourelle. Il pourra suivre un chemin. Il y aura une sphère qui se déplacera et le char ciblera la sphère.
+You can see the scene graph gets pretty complex for a human. In fact
+that scene graph above is simplified. For example you might extend it
+to cover every finger (at least another 28 nodes) and every toe
+(yet another 28 nodes) plus ones for the face and jaw, the eyes and maybe more.
Let's make one semi-complex scene graph. We'll make a tank. The tank will have
6 wheels and a turret. The tank will follow a path. There will be a sphere that
moves around and the tank will target the sphere.
-Voici le graphique de la scène. Les maillages sont colorés en vert, les `Object3D` en bleu, les lumières en or et les caméras en violet. Une caméra n'a pas été ajoutée au graphique de la scène.
+Here's the scene graph. The meshes are colored in green, the `Object3D`s in blue,
+the lights in gold, and the cameras in purple. One camera has not been added
+to the scene graph.
<div class="threejs_center"><img src="resources/images/scenegraph-tank.svg" style="width: 800px;"></div>
-Regardez dans le code pour voir la configuration de tous ces nœuds.
+Look in the code to see the setup of all of these nodes.
-Pour la cible, la chose que le char vise, il y a une `targetOrbit` (Object3D) qui tourne juste de la même manière que la `earthOrbit` ci-dessus. Une `targetElevation` (Object3D) qui est un enfant de `targetOrbit` fournit un décalage par rapport à `targetOrbit` et une élévation de base. Un autre `Object3D` appelé `targetBob` qui monte et descend par rapport à la `targetElevation`. Enfin, il y a le `targetMesh` qui est juste un cube que nous faisons pivoter et changeons ses couleurs.
+For the target, the thing the tank is aiming at, there is a `targetOrbit`
+(`Object3D`) which just rotates similar to the `earthOrbit` above. A
+`targetElevation` (`Object3D`) which is a child of the `targetOrbit` provides an
+offset from the `targetOrbit` and a base elevation. Childed to that is another
+`Object3D` called `targetBob` which just bobs up and down relative to the
+`targetElevation`. Finally there's the `targetMesh` which is just a cube we
+rotate and change its colors
```js
-// mettre en mouvement la cible
+// move target
targetOrbit.rotation.y = time * .27;
targetBob.position.y = Math.sin(time * 2) * 4;
targetMesh.rotation.x = time * 7;
@@ -320,59 +367,71 @@ targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25);
targetMaterial.color.setHSL(time * 10 % 1, 1, .25);
```
-Pour le char, il y a un `Object3D` appelé `tank` qui est utilisé pour déplacer tout ce qui se trouve en dessous. Le code utilise une `SplineCurve` à laquelle il peut demander des positions le long de cette courbe. 0.0 est le début de la courbe. 1,0 est la fin de la courbe. Il demande la position actuelle où il met le réservoir. Il demande ensuite une position légèrement plus bas dans la courbe et l'utilise pour pointer le réservoir dans cette direction à l'aide de `Object3D.lookAt`.
+For the tank there's an `Object3D` called `tank` which is used to move everything
+below it around. The code uses a `SplineCurve` which it can ask for positions
+along that curve. 0.0 is the start of the curve. 1.0 is the end of the curve. It
+asks for the current position where it puts the tank. It then asks for a
+position slightly further down the curve and uses that to point the tank in that
+direction using `Object3D.lookAt`.
```js
const tankPosition = new THREE.Vector2();
const tankTarget = new THREE.Vector2();
...
-// mettre en mouvement le char
+// move tank
const tankTime = time * .05;
curve.getPointAt(tankTime % 1, tankPosition);
curve.getPointAt((tankTime + 0.01) % 1, tankTarget);
tank.position.set(tankPosition.x, 0, tankPosition.y);
tank.lookAt(tankTarget.x, 0, tankTarget.y);
```
-La tourelle sur le dessus du char est déplacée automatiquement en tant qu'enfant du char. Pour le pointer sur la cible, nous demandons simplement la position de la cible, puis utilisons à nouveau `Object3D.lookAt`.
+The turret on top of the tank is moved automatically by being a child
+of the tank. To point it at the target we just ask for the target's world position
+and then again use `Object3D.lookAt`
```js
const targetPosition = new THREE.Vector3();
...
-// tourelle face à la cible
+// face turret at target
targetMesh.getWorldPosition(targetPosition);
turretPivot.lookAt(targetPosition);
```
-Il y a une `tourretCamera` qui est un enfant de `turretMesh` donc il se déplacera de haut en bas et tournera avec la tourelle. On la fait viser la cible.
+
+There's a `turretCamera` which is a child of the `turretMesh` so
+it will move up and down and rotate with the turret. We make that
+aim at the target.
```js
-// la turretCamera regarde la cible
+// make the turretCamera look at target
turretCamera.lookAt(targetPosition);
```
-Il y a aussi un `targetCameraPivot` qui est un enfant de `targetBob` donc il flotte
-autour de la cible. Nous le pointons vers le char. Son but est de permettre à la
-`targetCamera` d'être décalé par rapport à la cible elle-même. Si nous faisions de la caméra
-un enfant de `targetBob`, elle serait à l'intérieur de la cible.
+
+There is also a `targetCameraPivot` which is a child of `targetBob` so it floats
+around with the target. We aim that back at the tank. Its purpose is to allow the
+`targetCamera` to be offset from the target itself. If we instead made the camera
+a child of `targetBob` and just aimed the camera itself it would be inside the
+target.
```js
-// faire en sorte que la cibleCameraPivot regarde le char
+// make the targetCameraPivot look at the tank
tank.getWorldPosition(targetPosition);
targetCameraPivot.lookAt(targetPosition);
```
-Enfin on fait tourner toutes les roues
+Finally we rotate all the wheels
```js
wheelMeshes.forEach((obj) => {
obj.rotation.x = time * 3;
});
```
-Pour les caméras, nous avons configuré un ensemble de 4 caméras au moment de l'initialisation avec des descriptions.
+For the cameras we setup an array of all 4 cameras at init time with descriptions.
```js
const cameras = [
@@ -385,7 +444,7 @@ const cameras = [
const infoElem = document.querySelector('#info');
```
-et nous parcourons chaque camera au moment du rendu
+and cycle through our cameras at render time.
```js
const camera = cameras[time * .25 % cameras.length | 0];
@@ -394,11 +453,11 @@ infoElem.textContent = camera.desc;
{{{example url="../threejs-scenegraph-tank.html"}}}
-J'espère que cela donne une idée du fonctionnement des graphiques de scène et de la façon dont vous pouvez les utiliser.
-Faire des nœuds « Object3D » et leur attacher des choses est une étape importante pour utiliser
-un moteur 3D comme Three.js bien. Souvent, on pourrait penser que des mathématiques complexes soient nécessaires
-pour faire bouger quelque chose et faire pivoter comme vous le souhaitez. Par exemple sans graphique de scène
-calculer le mouvement de la lune, savoir où placer les roues de la voiture par rapport à son
-corps serait très compliqué, mais en utilisant un graphique de scène, cela devient beaucoup plus facile.
+I hope this gives some idea of how scene graphs work and how you might use them.
+Making `Object3D` nodes and parenting things to them is an important step to using
+a 3D engine like three.js well. Often it might seem like some complex math is necessary
+to make something move and rotate the way you want. For example without a scene graph
+computing the motion of the moon or where to put the wheels of the car relative to its
+body would be very complicated but using a scene graph it becomes much easier.
-[Passons maintenant en revue les materials](threejs-materials.html).
+[Next up we'll go over materials](threejs-materials.html). | false |
Other | mrdoob | three.js | 17bfe165606d65eaab1f3cb71dc40532b520dfd5.json | add French translation | threejs/lessons/fr/threejs-setup.md | @@ -1,6 +1,6 @@
-Title: Configuration de Three.js
+Title: Installation de Three.js
Description: Comment configurer votre environnement de développement pour Three.js
-TOC: Configuration
+TOC: Setup
Cette article fait parti d'une série consacrée à Three.js. Le premier article traité des [fondements de Three.js](threejs-fundamentals.html).
Si vous ne l'avez pas encore lu, vous devriez peut-être commencer par là. | false |
Other | mrdoob | three.js | 6281a9afcaf5c3d0a254e55fc49d6d2f7b0932f5.json | fix grammatical errors | threejs/lessons/fr/threejs-responsive.md | @@ -1,8 +1,8 @@
Title: Design réactif et Three.js
-Description: Comment rendre Three.js adaptable à des affichages de taille différente.
+Description: Comment rendre three.js adaptable à des affichages de taille différente.
TOC: Design réactif
-Ceci est le second article dans une série traitant de Three.js.
+Ceci est le second article dans une série traitant de three.js.
Le premier traitait [des principes de base](threejs-fundamentals.html).
Si vous ne l'avez pas encore lu, vous deviriez peut-être commencer par là.
@@ -17,18 +17,18 @@ Par exemple, un éditeur 3D avec des contrôles à gauche, droite, en haut ou
en bas est quelque chose que nous voudrions gérer. Un schéma interactif
au milieu d'un document en est un autre exemple.
-Le dernier exemple que nous avions utilisé est un canvas sans CSS et
+Le dernier exemple que nous avions utilisé est un canevas sans CSS et
sans taille :
```html
<canvas id="c"></canvas>
```
-Ce canvas a, par défaut, une taille de 300x150 pixels.
+Ce canevas a, par défaut, une taille de 300x150 pixels.
Dans le navigateur, la manière recommandée de fixer la taille
de quelque chose est d'utiliser CSS.
-Paramétrons le canvas pour occuper complètement la page en ajoutant
+Paramétrons le canevas pour occuper complètement la page en ajoutant
du CSS :
```html
@@ -54,15 +54,15 @@ Ensuite, nous faisons en sorte que l'élément `id=c` fasse
100% de la taille de son conteneur qui est, dans ce cas, la balise body.
Finalement, nous passons le mode `display` à `block`.
-Le mode d'affichage par défaut d'un canvas est `inline`, ce qui implique
+Le mode d'affichage par défaut d'un canevas est `inline`, ce qui implique
que des espaces peuvent être ajoutés à l'affichage.
-En passant le canvas à `block`, ce problème est supprimé.
+En passant le canevas à `block`, ce problème est supprimé.
Voici le résultat :
{{{example url="../threejs-responsive-no-resize.html" }}}
-Le canvas, comme nous le voyons, remplit maintenant la page mais il y a deux
+Le canevas, comme nous le voyons, remplit maintenant la page mais il y a deux
problèmes. Tout d'abord, nos cubes sont étirés et ressemblent à des boîtes trop
hautes et trop larges. Ouvrez l'exemple dans sa propre fenêtre et
redimensionnez la, vous verrez comment les cubes s'en trouvent déformés
@@ -78,8 +78,8 @@ pleinement le problème.
Tout d'abord, nous allons résoudre le problème d'étirement.
Pour cela, nous devons calquer l'aspect de la caméra sur celui
-de la taille d'affichage du canvas. Nous pouvons le faire
-en utilisant les propriétés `clientWidth` et `clientHeight` du canvas.
+de la taille d'affichage du canevas. Nous pouvons le faire
+en utilisant les propriétés `clientWidth` et `clientHeight` du canevas.
Nous mettons alors notre boucle de rendu comme cela :
@@ -108,8 +108,8 @@ Ils restent corrects quelque soit l'aspect de la taille de la fenêtre.
Maintenant résolvons le problème de la pixellisation.
Les éléments de type *canvas* ont deux tailles. La première
-est celle du canvas affiché dans la page. C'est ce que nous paramétrons avec le CSS.
-L'autre taille est le nombre de pixels dont est constitué le canvas lui-même.
+est celle du canevas affiché dans la page. C'est ce que nous paramétrons avec le CSS.
+L'autre taille est le nombre de pixels dont est constitué le canevas lui-même.
Ceci n'est pas différent d'une image.
Par exemple, nous pouvons avoir une image de taille 128x64 et, en utilisant le CSS,
nous pouvons l'afficher avec une taille de 400x200.
@@ -118,14 +118,14 @@ nous pouvons l'afficher avec une taille de 400x200.
<img src="some128x64image.jpg" style="width:400px; height:200px">
```
-La taille interne d'un canvas, sa résolution, est souvent appelée sa taille de tampon
+La taille interne d'un canevas, sa résolution, est souvent appelée sa taille de tampon
de dessin (*drawingbuffer*). Dans Three.js, nous pouvons ajuster la taille
-du canvas en appelant `renderer.setSize`.
+du canevas en appelant `renderer.setSize`.
Quelle taille devons nous choisir ? La réponse la plus évidente est "la même taille que
-celle du canvas". A nouveau, pour le faire, nous pouvons recourir
+celle du canevas". A nouveau, pour le faire, nous pouvons recourir
aux propriétés `clientWidth` et `clientHeight`.
-Ecrivons une fonction qui vérifie si le rendu du canvas a la bonne taille et l'ajuste en conséquence.
+Ecrivons une fonction qui vérifie si le rendu du canevas a la bonne taille et l'ajuste en conséquence.
```js
function resizeRendererToDisplaySize(renderer) {
@@ -140,21 +140,21 @@ function resizeRendererToDisplaySize(renderer) {
}
```
-Remarquez que nous vérifions si le canvas a réellement besoin d'être redimensionné.
-Le redimensionnement est une partie intéressante de la spécification du canvas
+Remarquez que nous vérifions si le canevas a réellement besoin d'être redimensionné.
+Le redimensionnement est une partie intéressante de la spécification du canevas
et il est mieux de ne pas lui donner à nouveau la même taille s'il est déjà
à la dimension que nous voulons.
Une fois que nous savons si le redimensionnement est nécessaire ou non, nous
appelons `renderer.setSize` et lui passons les nouvelles largeur et hauteur.
Il est important de passer `false` en troisième.
-`render.setSize` modifie par défaut la taille du canvas dans le CSS, mais ce n'est
+`render.setSize` modifie par défaut la taille du canevas dans le CSS, mais ce n'est
pas ce que nous voulons. Nous souhaitons que le navigateur continue à fonctionner
comme pour les autres éléments, en utilisant le CSS pour déterminer la
-taille d'affichage d'un élément. Nous ne voulons pas que les canvas utilisés
-par Three.js aient un comportement différent des autres éléments.
+taille d'affichage d'un élément. Nous ne voulons pas que les canevas utilisés
+par Three aient un comportement différent des autres éléments.
-Remarquez que notre fonction renvoie *true* si le canvas a été redimensionné.
+Remarquez que notre fonction renvoie *true* si le canevas a été redimensionné.
Nous pouvons l'utiliser pour vérifier si d'autre choses doivent être mises à jour.
Modifions à présent notre boucle de rendu pour utiliser la nouvelle fonction :
@@ -171,14 +171,14 @@ function render(time) {
...
```
-Puisque l'aspect ne change que si la taille d'affichage du canvas change,
+Puisque l'aspect ne change que si la taille d'affichage du canevas change,
nous ne modifions l'aspect de la caméra que si `resizeRendererToDisplaySize`
retourne `true`.
{{{example url="../threejs-responsive.html" }}}
Le rendu devrait à présent avoir une résolution correspondant à
-la taille d'affichage du canvas.
+la taille d'affichage du canevas.
Afin de comprendre pourquoi il faut laisser le CSS gérer le redimensionnement,
prenons notre code et mettons le dans un [fichier `.js` séparé](../threejs-responsive.js). Voici donc quelques autres exemples où nous avons laissé le CSS choisir la taille et remarquez que nous n'avons
@@ -242,7 +242,7 @@ utiliser la taille que vous avez demandé, multiplié par le
ratio que vous avez demandé.
**Ceci est fortement DÉCONSEILLÉ**. Voir ci-dessous.
-L'autre façon est de le faire par soi-même quand on redimensionne le canvas.
+L'autre façon est de le faire par soi-même quand on redimensionne le canevas.
```js
function resizeRendererToDisplaySize(renderer) {
@@ -261,10 +261,10 @@ L'autre façon est de le faire par soi-même quand on redimensionne le canvas.
Cette seconde façon est objectivement meilleure. Pourquoi ? Parce que cela signifie
que nous avons ce que nous avons demandé. Il y a plusieurs cas où,
quand on utilise Three.js, nous avons besoin de connaître la taille effective
-du tampon d'affichage du canvas. Par exemple, quand on réalise un filtre de
+du tampon d'affichage du canevas. Par exemple, quand on réalise un filtre de
post-processing, ou si nous faisons un *shader* qui accède à `gl_FragCoord`,
si nous sommes en train de faire une capture d'écran, ou en train de lire les pixels
-pour une sélection par GPU, pour dessiner dans un canvas 2D, etc...
+pour une sélection par GPU, pour dessiner dans un canevas 2D, etc...
Il y a plusieurs cas où, si nous utilisons `setPixelRatio` alors notre
taille effective est différente de la taille que nous avons demandé et nous
aurons alors à deviner quand utiliser la taille demandée ou la taille utilisée | false |
Other | mrdoob | three.js | c09aa7a83c2632309203a130362bf5c737a12e19.json | fix grammatical errors | threejs/lessons/fr/threejs-primitives.md | @@ -1,5 +1,5 @@
Title: Primitives de Three.js
-Description: Tour d'horizon des primitives de Three.js
+Description: Un tour des primitives de Three.js
TOC: Primitives
Cet article fait partie d'une série consacrée à Three.js. | false |
Other | mrdoob | three.js | 87c97f21ac72d78210b479809874b15cac4e2b6e.json | translate the description in French | threejs/lessons/fr/threejs-textures.md | @@ -1,5 +1,5 @@
-Title: Three.js Textures
-Description: Using textures in three.js
+Title: Les textures dans Three.js
+Description: Comment utiliser les textures dans Three.js
TOC: Textures
Cet article fait partie d'une série consacrée à Three.js. | false |
Other | mrdoob | three.js | 652a5b7b73fced3634804a8314c8f66d66620e6c.json | translate TOC in french | threejs/lessons/fr/threejs-shadows.md | @@ -1,6 +1,6 @@
Title: Les ombres dans Three.js
Description: Les ombres dans Three.js
-TOC: Shadows
+TOC: Ombres
Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html). | false |
Other | mrdoob | three.js | 60f310034a9a498ce9a9ac8ab60634ededfea592.json | Translate TOC in french | threejs/lessons/fr/threejs-scenegraph.md | @@ -1,6 +1,6 @@
Title: Graphique de scène de Three.js
Description: Qu'est-ce qu'un graphique de scène ?
-TOC: Scenegraph
+TOC: Graphique de scène
Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html). | false |
Other | mrdoob | three.js | d6706f5d06080158e79e92064ff65a3e3ae6ce8b.json | fix some translation errors | threejs/lessons/fr/threejs-materials.md | @@ -1,6 +1,6 @@
-Title: Les Materials de Three.js
-Description: Les Materials dans Three.js
-TOC: Materials
+Title: Les Matériaux dans Three.js
+Description: Les Matériaux dans Three.js
+TOC: Matériaux
Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html). | false |
Other | mrdoob | three.js | 889eeea46efb8fe9fefff9918b5e97a513997dcc.json | fix some errors in translation | threejs/lessons/fr/threejs-lights.md | @@ -1,6 +1,6 @@
Title: Lumières en Three.js
-Description: Configuration des mulières
-TOC: Lights
+Description: Configuration des lumières
+TOC: Lumières
Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html). Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là ou aussi voir l'article sur [la configuartion de votre environnement](threejs-setup.html). L' | false |
Other | mrdoob | three.js | b8bd0459204be4920198f893f48f88ea3c54cc47.json | translate the TOC in french | threejs/lessons/fr/threejs-cameras.md | @@ -1,6 +1,6 @@
Title: Caméras dans Three.js
Description: Comment utiliser les Cameras dans Three.js
-TOC: Cameras
+TOC: Caméras
Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html). | false |
Other | mrdoob | three.js | ff5d39ea9ebef3a6712fba62e65d7375e3568df0.json | add French translation | threejs/lessons/fr/threejs-shadows.md | @@ -0,0 +1,412 @@
+Title: Les ombres dans Three.js
+Description: Les ombres dans Three.js
+TOC: Shadows
+
+Cet article fait partie d'une série consacrée à Three.js.
+Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
+Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
+L'[article précédent qui s'intéressait caméras](threejs-cameras.html) est à lire ainsi que [celui à propos des lumières](threejs-lights.html) avant d'entamer cet article-ci.
+
+Les ombres peuvent être un sujet compliqué. Il existe différentes solutions et toutes ont des compromis, y compris les solutions disponibles dans Three.js.
+
+Three.js, par défaut, utilise des *shadow maps*. Comment ça marche ? *pour chaque lumière qui projette des ombres, tous les objets marqués pour projeter des ombres sont rendus du point de vue de la lumière*. **RELISEZ ENCORE UNE FOIS** pour que ça soit bien clair pour vous.
+
+En d'autres termes, si vous avez 20 objets et 5 lumières, et que les 20 objets projettent des ombres et que les 5 lumières projettent des ombres, toute votre scène sera dessinée 6 fois. Les 20 objets seront dessinés pour la lumière #1, puis les 20 objets seront dessinés pour la lumière #2, puis #3, et ainsi de suite. Enfin la scène sera dessinée en utilisant les données des 5 premiers rendus.
+
+C'est pire, si vous avez une 'pointLight' projetant des ombres, la scène devra être dessinée 6 fois juste pour cette lumière !
+
+Pour ces raisons, il est courant de trouver d'autres solutions que d'avoir un tas de lumières générant toutes des ombres. Une solution courante consiste à avoir plusieurs lumières mais une seule lumière directionnelle générant des ombres.
+
+Une autre solution consiste à utiliser des lightmaps et/ou des maps d'occlusion ambiante pour pré-calculer les effets de l'éclairage hors ligne. Cela se traduit par un éclairage statique ou des soupçons d'éclairage statique, mais au moins c'est rapide. Nous verrons cela dans un autre article.
+
+Une autre solution consiste à utiliser de fausses ombres. Créez un plan, placez une texture en niveaux de gris dans le plan qui se rapproche d'une ombre, dessinez-la au-dessus du sol sous votre objet.
+
+Par exemple, utilisons cette texture comme une fausse ombre.
+
+<div class="threejs_center"><img src="../resources/images/roundshadow.png"></div>
+
+Utilisons une partie du code de [l'article précédent](threejs-cameras.html).
+
+Réglons la couleur de fond sur blanc.
+
+```js
+const scene = new THREE.Scene();
++scene.background = new THREE.Color('white');
+```
+
+Ensuite, nous allons configurer le même sol en damier, mais cette fois, nous utilisons un [`MeshBasicMaterial`](https://threejs.org/docs/#api/en/materials/MeshBasicMaterial) car nous n'avons pas besoin d'éclairage pour le sol.
+
+```js
++const loader = new THREE.TextureLoader();
+
+{
+ const planeSize = 40;
+
+- const loader = new THREE.TextureLoader();
+ const texture = loader.load('resources/images/checker.png');
+ texture.wrapS = THREE.RepeatWrapping;
+ texture.wrapT = THREE.RepeatWrapping;
+ texture.magFilter = THREE.NearestFilter;
+ const repeats = planeSize / 2;
+ texture.repeat.set(repeats, repeats);
+
+ const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize);
+ const planeMat = new THREE.MeshBasicMaterial({
+ map: texture,
+ side: THREE.DoubleSide,
+ });
++ planeMat.color.setRGB(1.5, 1.5, 1.5);
+ const mesh = new THREE.Mesh(planeGeo, planeMat);
+ mesh.rotation.x = Math.PI * -.5;
+ scene.add(mesh);
+}
+```
+
+Notez que nous définissons la couleur sur `1.5, 1.5, 1.5`. Cela multipliera les couleurs de la texture du damier par 1,5, 1,5, 1,5. Puisque les couleurs de la texture sont 0x808080 et 0xC0C0C0, c'est-à-dire gris moyen et gris clair, les multiplier par 1,5 nous donnera un damier blanc et gris clair.
+
+Chargeons la texture de l'ombre
+
+```js
+const shadowTexture = loader.load('resources/images/roundshadow.png');
+```
+
+et créons un tableau pour mémoriser chaque sphère et les objets associés.
+
+```js
+const sphereShadowBases = [];
+```
+
+Ensuite, créons une sphère.
+
+```js
+const sphereRadius = 1;
+const sphereWidthDivisions = 32;
+const sphereHeightDivisions = 16;
+const sphereGeo = new THREE.SphereGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
+```
+
+Et un plan pour simuler l'ombre.
+
+```js
+const planeSize = 1;
+const shadowGeo = new THREE.PlaneGeometry(planeSize, planeSize);
+```
+
+Maintenant, nous allons faire un tas de sphères. Pour chaque sphère, nous allons créer une `base` `THREE.Object3D` et nous allons créer à la fois le maillage du plan d'ombre et le maillage de la sphère enfants de la base. De cette façon, si nous déplaçons la base, la sphère et l'ombre bougeront. Nous devons placer l'ombre légèrement au-dessus du sol pour éviter les combats en Z. Nous définissons également `depthWrite` sur false pour que les ombres ne se gâchent pas. Nous reviendrons sur ces deux problèmes dans un [autre article](threejs-transparency.html). L'ombre est un `MeshBasicMaterial` car elle n'a pas besoin d'éclairage.
+
+Nous donnons à chaque sphère une teinte différente, puis nous enregistrons la base, le maillage de la sphère, le maillage de l'ombre et la position y initiale de chaque sphère.
+
+```js
+const numSpheres = 15;
+for (let i = 0; i < numSpheres; ++i) {
+ // créer une base pour l'ombre et la sphère
+ // donc ils bougent ensemble.
+ const base = new THREE.Object3D();
+ scene.add(base);
+
+ // ajoute l'ombre à la base
+ // remarque : nous fabriquons un nouveau matériau pour chaque sphère
+ // afin que nous puissions définir la transparence matérielle de cette sphère
+ // séparément.
+ const shadowMat = new THREE.MeshBasicMaterial({
+ map: shadowTexture,
+ transparent: true, // pour que nous puissions voir le sol
+ depthWrite: false, // donc nous n'avons pas à trier
+ });
+ const shadowMesh = new THREE.Mesh(shadowGeo, shadowMat);
+ shadowMesh.position.y = 0.001; // donc nous sommes légèrement au-dessus du sol
+ shadowMesh.rotation.x = Math.PI * -.5;
+ const shadowSize = sphereRadius * 4;
+ shadowMesh.scale.set(shadowSize, shadowSize, shadowSize);
+ base.add(shadowMesh);
+
+ // ajouter la sphère à la base
+ const u = i / numSpheres; // passe de 0 à 1 au fur et à mesure que nous itérons les sphères.
+ const sphereMat = new THREE.MeshPhongMaterial();
+ sphereMat.color.setHSL(u, 1, .75);
+ const sphereMesh = new THREE.Mesh(sphereGeo, sphereMat);
+ sphereMesh.position.set(0, sphereRadius + 2, 0);
+ base.add(sphereMesh);
+
+ // rappelez-vous tous les 3 plus la position y
+ sphereShadowBases.push({base, sphereMesh, shadowMesh, y: sphereMesh.position.y});
+}
+```
+
+Nous avons installé 2 lumières. L'un est un [`HemisphereLight`](https://threejs.org/docs/#api/en/lights/HemisphereLight) avec une intensité réglée sur 2 pour vraiment illuminer les choses.
+
+```js
+{
+ const skyColor = 0xB1E1FF; // bleu
+ const groundColor = 0xB97A20; // orange brun
+ const intensity = 2;
+ const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
+ scene.add(light);
+}
+```
+
+L'autre est un `DirectionalLight` donc les sphères ont une définition
+
+```js
+{
+ const color = 0xFFFFFF;
+ const intensity = 1;
+ const light = new THREE.DirectionalLight(color, intensity);
+ light.position.set(0, 10, 5);
+ light.target.position.set(-5, 0, 0);
+ scene.add(light);
+ scene.add(light.target);
+}
+```
+
+Il rendrait tel quel mais animons les sphères. Pour chaque sphère, ombre, jeu de base, nous déplaçons la base dans le plan xz, nous déplaçons la sphère de haut en bas en utilisant [`Math.abs(Math.sin(time))`](https://threejs.org/docs/#api/en/math/Math.abs(Math.sin(time))) qui nous donne une animation rebondissante. Et, nous avons également défini l'opacité du matériau d'ombre de sorte qu'à mesure que chaque sphère monte, son ombre s'estompe.
+
+```js
+function render(time) {
+ time *= 0.001; // convertir en secondes
+
+ ...
+
+ sphereShadowBases.forEach((sphereShadowBase, ndx) => {
+ const {base, sphereMesh, shadowMesh, y} = sphereShadowBase;
+
+ // u est une valeur qui va de 0 à 1 au fur et à mesure que l'on itère les sphères
+ const u = ndx / sphereShadowBases.length;
+
+ // calculer une position pour la base. Cela va bouger
+ // à la fois la sphère et son ombre
+ const speed = time * .2;
+ const angle = speed + u * Math.PI * 2 * (ndx % 1 ? 1 : -1);
+ const radius = Math.sin(speed - ndx) * 10;
+ base.position.set(Math.cos(angle) * radius, 0, Math.sin(angle) * radius);
+
+ // yOff est une valeur allant de 0 à 1
+ const yOff = Math.abs(Math.sin(time * 2 + ndx));
+ // déplace la sphère de haut en bas
+ sphereMesh.position.y = y + THREE.MathUtils.lerp(-2, 2, yOff);
+ // estompe l'ombre au fur et à mesure que la sphère monte
+ shadowMesh.material.opacity = THREE.MathUtils.lerp(1, .25, yOff);
+ });
+
+ ...
+```
+
+Et voici 15 balles rebondissantes.
+
+{{{example url="../threejs-shadows-fake.html" }}}
+
+Dans certaines applications, il est courant d'utiliser une ombre ronde ou ovale pour tout, mais bien sûr, vous pouvez également utiliser différentes textures d'ombre de forme. Vous pouvez également donner à l'ombre un bord plus dur. Un bon exemple d'utilisation de ce type d'ombre est [Animal Crossing Pocket Camp](https://www.google.com/search?tbm=isch&q=animal+crossing+pocket+camp+screenshots) où vous pouvez voir que chaque personnage a une simple ombre ronde. C'est efficace et pas cher. [Monument Valley](https://www.google.com/search?q=monument+valley+screenshots&tbm=isch) semble également utiliser ce type d'ombre pour le personnage principal.
+
+Donc, en passant aux cartes d'ombre, il y a 3 lumières qui peuvent projeter des ombres. Le `DirectionalLight`, le `PointLight` et le `SpotLight`.
+
+Commençons avec la `DirectionalLight` avec l'aide de [l'article sur les lumières](threejs-lights.html).
+
+La première chose à faire est d'activer les ombres dans le renderer (moteur de rendu).
+
+```js
+const renderer = new THREE.WebGLRenderer({canvas});
++renderer.shadowMap.enabled = true;
+```
+
+Ensuite, nous devons également dire à la lumière de projeter une ombre.
+
+```js
+const light = new THREE.DirectionalLight(color, intensity);
++light.castShadow = true;
+```
+
+Nous devons également aller sur chaque maillage de la scène et décider s'il doit à la fois projeter des ombres et/ou recevoir des ombres.
+
+Faisons en sorte que le 'plane' (le sol) ne reçoive que des ombres car nous ne nous soucions pas vraiment de ce qui se passe en dessous.
+
+```js
+const mesh = new THREE.Mesh(planeGeo, planeMat);
+mesh.receiveShadow = true;
+```
+
+Pour le cube et la sphère faisons en sorte qu'ils reçoivent et projettent des ombres.
+
+```js
+const mesh = new THREE.Mesh(cubeGeo, cubeMat);
+mesh.castShadow = true;
+mesh.receiveShadow = true;
+
+...
+
+const mesh = new THREE.Mesh(sphereGeo, sphereMat);
+mesh.castShadow = true;
+mesh.receiveShadow = true;
+```
+
+Et puis nous l'exécutons.
+
+{{{example url="../threejs-shadows-directional-light.html" }}}
+
+Que s'est-il passé? Pourquoi des parties des ombres manquent-elles ?
+
+C'est parce que les shadow maps sont créées en rendant la scène du point de vue de la lumière. C'est comme si il y avait une caméra dans la [`DirectionalLight`](https://threejs.org/docs/#api/en/lights/DirectionalLight) qui regardait sa cible. Tout comme [la caméra de l'article précédent](threejs-cameras.html), la 'caméra de la lumière' définit une zone à l'intérieur de laquelle les ombres sont projetées. Dans l'exemple ci-dessus, cette zone est trop petite.
+
+Afin de bien visualiser cette zone, ajoutons un `CameraHelper` à la scène.
+
+```js
+const cameraHelper = new THREE.CameraHelper(light.shadow.camera);
+scene.add(cameraHelper);
+```
+
+Maintenant, on peut voir cette zone où les ombres sont projetés.
+
+{{{example url="../threejs-shadows-directional-light-with-camera-helper.html" }}}
+
+Ajustez la valeur x cible dans les deux sens et il devrait être assez clair que seul ce qui se trouve à l'intérieur de la boîte de la caméra d'ombre de la lumière est l'endroit où les ombres sont dessinées.
+
+Nous pouvons ajuster la taille de cette boîte en ajustant la caméra d'ombre de la lumière.
+
+Ajoutons quelques paramètres à dat.GUI pour ajuster les ombres. Étant donné qu'une [`DirectionalLight`](https://threejs.org/docs/#api/en/lights/DirectionalLight) représente la lumière allant dans une direction parallèle, la [`DirectionalLight`](https://threejs.org/docs/#api/en/lights/DirectionalLight) utilise une [`OrthographicCamera`](https://threejs.org/docs/#api/en/cameras/OrthographicCamera) pour sa caméra d'ombre. Nous avons expliqué le fonctionnement d'une caméra orthographique dans [l'article précédent sur les caméras](threejs-cameras.html).
+
+Pour rappel, une `OrthographicCamera` définit son *frustum* par ses propriètès `left`, `right`, `top`, `bottom`, `near`, `far` et `zoom`.
+
+Créons à nouveau un helper pour dat.GUI. Appelons-le `DimensionGUIHelper`
+et passons-lui un objet et 2 propriétés. Il dispose d'une propriété que dat.GUI peut ajuster et en réponse définit les deux propriétés, une positive et une négative.
+Nous pouvons l'utiliser pour définir `left` et `right` en tant que `width` et `up`, `down` en tant que `height`.
+
+```js
+class DimensionGUIHelper {
+ constructor(obj, minProp, maxProp) {
+ this.obj = obj;
+ this.minProp = minProp;
+ this.maxProp = maxProp;
+ }
+ get value() {
+ return this.obj[this.maxProp] * 2;
+ }
+ set value(v) {
+ this.obj[this.maxProp] = v / 2;
+ this.obj[this.minProp] = v / -2;
+ }
+}
+```
+
+Utilisons aussi le `MinMaxGUIHelper` que nous avons créé dans [l'article sur les caméra](threejs-cameras.html) pour paramètrer `near` et `far`.
+
+```js
+const gui = new GUI();
+gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
+gui.add(light, 'intensity', 0, 2, 0.01);
++{
++ const folder = gui.addFolder('Shadow Camera');
++ folder.open();
++ folder.add(new DimensionGUIHelper(light.shadow.camera, 'left', 'right'), 'value', 1, 100)
++ .name('width')
++ .onChange(updateCamera);
++ folder.add(new DimensionGUIHelper(light.shadow.camera, 'bottom', 'top'), 'value', 1, 100)
++ .name('height')
++ .onChange(updateCamera);
++ const minMaxGUIHelper = new MinMaxGUIHelper(light.shadow.camera, 'near', 'far', 0.1);
++ folder.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera);
++ folder.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far').onChange(updateCamera);
++ folder.add(light.shadow.camera, 'zoom', 0.01, 1.5, 0.01).onChange(updateCamera);
++}
+```
+
+Disons à dat.GUI d'appeler la fonction `updateCamera` à chaque changement.
+Écrivons cette fonction pour mettre à jour la lumière et son helper, la caméra d'ombre de la lumière et son helper.
+
+```js
+function updateCamera() {
+ // mettre à jour le MatrixWorld de la cible de lumière car il est requis par le helper
+ light.target.updateMatrixWorld();
+ helper.update();
+ // mettre à jour la matrice de projection de la caméra d'ombre de la lumière
+ light.shadow.camera.updateProjectionMatrix();
+ // et maintenant mettre à jour l'assistant de caméra que nous utilisons pour afficher la caméra d'ombre de la lumière
+ cameraHelper.update();
+}
+updateCamera();
+```
+
+Et maintenant que nous avons accès aux propriètès de la caméra d'ombre, jouons avec.
+
+{{{example url="../threejs-shadows-directional-light-with-camera-gui.html" }}}
+
+Réglez `width` et `height` sur 30 et vous verrez que les ombres sont correctement projetées.
+
+Mais cela soulève la question, pourquoi ne pas simplement définir `width` et `height` avec des chiffres plus grands ? Réglez la largeur et la hauteur sur 100 et vous pourriez voir quelque chose comme ceci.
+
+<div class="threejs_center"><img src="resources/images/low-res-shadow-map.png" style="width: 369px"></div>
+
+Que se passe-t-il avec ces ombres basse résolution ?!
+
+Ce problème est lié à un autre paramètres des ombres. Les textures d'ombre sont des textures dans lesquelles les ombres sont dessinées. Ces textures ont une taille. La zone de la caméra d'ombre que nous avons définie ci-dessus est étirée sur cette taille. Cela signifie que plus la zone que vous définissez est grande, plus vos ombres seront en blocs.
+
+Vous pouvez définir la résolution de la texture de l'ombre en définissant `light.shadow.mapSize.width` et `light.shadow.mapSize.height`. Ils sont par défaut à 512x512. Plus vous les agrandissez, plus ils prennent de mémoire et plus ils sont lents à s'afficher, vous voulez donc les définir aussi petits que possible tout en faisant fonctionner votre scène. La même chose est vraie avec la zone d'ombre. Plus petite signifie des ombres plus belles, alors réduisez la zone autant que possible tout en couvrant votre scène. Sachez que la machine de chaque utilisateur a une taille de texture maximale autorisée qui est disponible sur le renderer en tant que [`renderer.capabilities.maxTextureSize`](WebGLRenderer.capabilities).
+
+<!--
+Ok but what about `near` and `far` I hear you thinking. Can we set `near` to 0.00001 and far to `100000000`
+-->
+
+En passant à une `SpotLight` la caméra d'ombre devient une `PerspectiveCamera`. Contrairement à la caméra d'ombre de la `DirectionalLight` où nous pouvons régler manuellement la plupart de ses paramètres, celle de la `SpotLight`est auto-controlée. Le `fov` de la caméra d'ombre est directement connecté au réglage de l'`angle` de la `SpotLight`.
+L'`aspect` est directement définit en fonction de la taille de la zone d'ombre.
+
+```js
+-const light = new THREE.DirectionalLight(color, intensity);
++const light = new THREE.SpotLight(color, intensity);
+```
+
+Rajoutons les paramètres `penumbra` et `angle` vu dans [l'article sur les lumières](threejs-lights.html).
+
+{{{example url="../threejs-shadows-spot-light-with-camera-gui.html" }}}
+
+<!--
+You can notice, just like the last example if we set the angle high
+then the shadow map, the texture is spread over a very large area and
+the resolution of our shadows gets really low.
+
+div class="threejs_center"><img src="resources/images/low-res-shadow-map-spotlight.png" style="width: 344px"></div>
+
+You can increase the size of the shadow map as mentioned above. You can
+also blur the result
+
+{{{example url="../threejs-shadows-spot-light-with-shadow-radius" }}}
+-->
+
+
+Et enfin il y a les ombres avec un [`PointLight`](https://threejs.org/docs/#api/en/lights/PointLight). Étant donné qu'un [`PointLight`](https://threejs.org/docs/#api/en/lights/PointLight) brille dans toutes les directions, les seuls paramètres pertinents sont `near` et `far`. Sinon, l'ombre PointLight est effectivement constituée de 6 ombres [`SpotLight`](https://threejs.org/docs/#api/en/lights/SpotLight), chacune pointant vers la face d'un cube autour de la lumière. Cela signifie que les ombres [`PointLight`](https://threejs.org/docs/#api/en/lights/PointLight) sont beaucoup plus lentes car la scène entière doit être dessinée 6 fois, une pour chaque direction.
+
+Mettons un cadre autour de notre scène afin que nous puissions voir des ombres sur les murs et le plafond. Nous allons définir la propriété `side` du matériau sur `THREE.BackSide` afin de rendre l'intérieur de la boîte au lieu de l'extérieur. Comme le sol, nous ne le paramétrons pour recevoir des ombres. Nous allons également définir la position de la boîte de sorte que son fond soit légèrement en dessous du sol afin d'éviter un problème de z-fighting.
+
+```js
+{
+ const cubeSize = 30;
+ const cubeGeo = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
+ const cubeMat = new THREE.MeshPhongMaterial({
+ color: '#CCC',
+ side: THREE.BackSide,
+ });
+ const mesh = new THREE.Mesh(cubeGeo, cubeMat);
+ mesh.receiveShadow = true;
+ mesh.position.set(0, cubeSize / 2 - 0.1, 0);
+ scene.add(mesh);
+}
+```
+
+Et bien sûr, il faut passer la lumière en `PointLight`.
+
+```js
+-const light = new THREE.SpotLight(color, intensity);
++const light = new THREE.PointLight(color, intensity);
+
+....
+
+// afin que nous puissions facilement voir où se trouve la spotLight
++const helper = new THREE.PointLightHelper(light);
++scene.add(helper);
+```
+
+{{{example url="../threejs-shadows-point-light.html" }}}
+
+Utilisez les paramètres position de dat.GUI pour déplacer la lumière et vous verrez les ombres se projeter sur tous les murs. Vous pouvez également ajuster les paramètres near et far et voir comment les autres ombres se comportent.
+
+<!--
+self shadow, shadow acne
+-->
+ | false |
Other | mrdoob | three.js | dad28cd65720293e613cef6ae335c984b4ab53d5.json | add French translation | threejs/lessons/fr/threejs-cameras.md | @@ -0,0 +1,532 @@
+Title: Caméras dans Three.js
+Description: Comment utiliser les Cameras dans Three.js
+TOC: Cameras
+
+Cet article fait partie d'une série consacrée à Three.js.
+Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
+Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
+
+Parlons des caméras dans Three.js. Nous en avons déjà parlé dans [le premier article](threejs-fundamentals.html) mais ici nous allons entrer dans le détail.
+
+La caméra la plus courante dans Three.js et celle que nous avons utilisée jusqu'à présent, la [`PerspectiveCamera`](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera). Elle donne une vue 3D où les choses lointaines semblent plus petites que les plus proches.
+
+La `PerspectiveCamera` définit un *frustum*. [Un frustum (tronc) est une forme pyramidale solide dont la pointe est coupée](https://fr.wikipedia.org/wiki/Tronc_(g%C3%A9om%C3%A9trie)). Par nom de solide, j'entends par exemple un cube, un cône, une sphère, un cylindre et un frustum sont tous des noms de différents types de solides.
+
+<div class="spread">
+ <div><div data-diagram="shapeCube"></div><div>cube</div></div>
+ <div><div data-diagram="shapeCone"></div><div>cone</div></div>
+ <div><div data-diagram="shapeSphere"></div><div>sphere</div></div>
+ <div><div data-diagram="shapeCylinder"></div><div>cylinder</div></div>
+ <div><div data-diagram="shapeFrustum"></div><div>frustum</div></div>
+</div>
+
+Je le signale seulement parce que je ne le savais pas. Et quand je voyais le mot *frustum* dans un livre mes yeux buggaient. Comprendre que c'est le nom d'un type de forme solide a rendu ces descriptions soudainement plus logiques 😅
+
+Une `PerspectiveCamera` définit son frustum selon 4 propriétés. `near` définit l'endroit où commence l'avant du frustum. `far` où il finit. `fov`, le champ de vision, définit la hauteur de l'avant et de l'arrière du tronc en fonction de la propriété `near`. L'`aspect` se rapporte à la largeur de l'avant et de l'arrière du tronc. La largeur du tronc est juste la hauteur multipliée par l'aspect.
+
+<img src="resources/frustum-3d.svg" width="500" class="threejs_center"/>
+
+Utilisons la scène de [l'article précédent](threejs-lights.html) avec son plan, sa sphère et son cube, et faisons en sorte que nous puissions ajuster les paramètres de la caméra.
+
+Pour ce faire, nous allons créer un `MinMaxGUIHelper` pour les paramètres `near` et `far` où `far`
+est toujours supérieur `near`. Il aura des propriétés `min` et `max` que dat.GUI
+pourra ajuster. Une fois ajustés, ils définiront les 2 propriétés que nous spécifions.
+
+```js
+class MinMaxGUIHelper {
+ constructor(obj, minProp, maxProp, minDif) {
+ this.obj = obj;
+ this.minProp = minProp;
+ this.maxProp = maxProp;
+ this.minDif = minDif;
+ }
+ get min() {
+ return this.obj[this.minProp];
+ }
+ set min(v) {
+ this.obj[this.minProp] = v;
+ this.obj[this.maxProp] = Math.max(this.obj[this.maxProp], v + this.minDif);
+ }
+ get max() {
+ return this.obj[this.maxProp];
+ }
+ set max(v) {
+ this.obj[this.maxProp] = v;
+ this.min = this.min; // this will call the min setter
+ }
+}
+```
+
+Maintenant, nous pouvons configurer dat.GUI comme ça
+
+```js
+function updateCamera() {
+ camera.updateProjectionMatrix();
+}
+
+const gui = new GUI();
+gui.add(camera, 'fov', 1, 180).onChange(updateCamera);
+const minMaxGUIHelper = new MinMaxGUIHelper(camera, 'near', 'far', 0.1);
+gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera);
+gui.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far').onChange(updateCamera);
+```
+
+Chaque fois que les paramètres de la caméra changent, il faut appeler la fonction
+[`updateProjectionMatrix`](PerspectiveCamera.updateProjectionMatrix). Nous avons donc créé une fonction `updateCamera` transmise à dat.GUI pour l'appeler lorsque les choses changent.
+
+{{{example url="../threejs-cameras-perspective.html" }}}
+
+Vous pouvez ajuster les valeurs et voir comment elles fonctionnent. Notez que nous n'avons pas rendu `aspect` réglable car il est pris à partir de la taille de la fenêtre, donc si vous souhaitez ajuster l'aspect, ouvrez l'exemple dans une nouvelle fenêtre, puis redimensionnez la fenêtre.
+
+Néanmoins, je pense que c'est un peu difficile à voir, alors modifions l'exemple pour qu'il ait 2 caméras. L'un montrera notre scène telle que nous la voyons ci-dessus, l'autre montrera une autre caméra regardant la scène que la première caméra dessine et montrant le frustum de cette caméra.
+
+Pour ce faire, nous pouvons utiliser la fonction ciseaux de three.js. Modifions-le pour dessiner 2 scènes avec 2 caméras côte à côte en utilisant la fonction ciseaux.
+
+Tout d'abord, utilisons du HTML et du CSS pour définir 2 éléments côte à côte. Cela nous aidera également avec les événements afin que les deux caméras puissent facilement avoir leurs propres `OrbitControls`.
+
+```html
+<body>
+ <canvas id="c"></canvas>
++ <div class="split">
++ <div id="view1" tabindex="1"></div>
++ <div id="view2" tabindex="2"></div>
++ </div>
+</body>
+```
+
+Et le CSS qui fera apparaître ces 2 vues côte à côte sur le canevas
+
+```css
+.split {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ display: flex;
+}
+.split>div {
+ width: 100%;
+ height: 100%;
+}
+```
+
+Ensuite, ajoutons un `CameraHelper`. Un `CameraHelper` dessine le frustum d'une `Camera`.
+
+```js
+const cameraHelper = new THREE.CameraHelper(camera);
+
+...
+
+scene.add(cameraHelper);
+```
+
+Récupérons maintenant nos 2 éléments.
+
+```js
+const view1Elem = document.querySelector('#view1');
+const view2Elem = document.querySelector('#view2');
+```
+
+Et nous allons configurer nos `OrbitControls` pour qu'ils répondent uniquement au premier élément.
+
+```js
+-const controls = new OrbitControls(camera, canvas);
++const controls = new OrbitControls(camera, view1Elem);
+```
+
+Ajoutons une nouvelle `PerspectiveCamera` et un second `OrbitControls`.
+Le deuxième `OrbitControls` est lié à la deuxième caméra et reçoit view2Elem en paramètre.
+
+```js
+const camera2 = new THREE.PerspectiveCamera(
+ 60, // fov
+ 2, // aspect
+ 0.1, // near
+ 500, // far
+);
+camera2.position.set(40, 10, 30);
+camera2.lookAt(0, 5, 0);
+
+const controls2 = new OrbitControls(camera2, view2Elem);
+controls2.target.set(0, 5, 0);
+controls2.update();
+```
+
+Enfin, nous devons rendre la scène du point de vue de chaque caméra en utilisant la fonction `setScissor` pour ne rendre qu'une partie du canvas.
+
+Voici une fonction qui, étant donné un élément, calculera le rectangle de cet élément qui chevauche le canvas. Il définira ensuite les ciseaux et la fenêtre sur ce rectangle et renverra l'aspect pour cette taille.
+
+```js
+function setScissorForElement(elem) {
+ const canvasRect = canvas.getBoundingClientRect();
+ const elemRect = elem.getBoundingClientRect();
+
+ // calculer un rectangle relatif au canvas
+ const right = Math.min(elemRect.right, canvasRect.right) - canvasRect.left;
+ const left = Math.max(0, elemRect.left - canvasRect.left);
+ const bottom = Math.min(elemRect.bottom, canvasRect.bottom) - canvasRect.top;
+ const top = Math.max(0, elemRect.top - canvasRect.top);
+
+ const width = Math.min(canvasRect.width, right - left);
+ const height = Math.min(canvasRect.height, bottom - top);
+
+ // configurer les ciseaux pour ne rendre que cette partie du canvas
+ const positiveYUpBottom = canvasRect.height - bottom;
+ renderer.setScissor(left, positiveYUpBottom, width, height);
+ renderer.setViewport(left, positiveYUpBottom, width, height);
+
+ // retourne aspect
+ return width / height;
+}
+```
+
+Et maintenant, nous pouvons utiliser cette fonction pour dessiner la scène deux fois dans notre fonction `render`
+
+```js
+ function render() {
+
+- if (resizeRendererToDisplaySize(renderer)) {
+- const canvas = renderer.domElement;
+- camera.aspect = canvas.clientWidth / canvas.clientHeight;
+- camera.updateProjectionMatrix();
+- }
+
++ resizeRendererToDisplaySize(renderer);
++
++ // déclenche la fonction setScissorTest
++ renderer.setScissorTest(true);
++
++ // rend la vue originelle
++ {
++ const aspect = setScissorForElement(view1Elem);
++
++ // adjuste la caméra pour cet aspect
++ camera.aspect = aspect;
++ camera.updateProjectionMatrix();
++ cameraHelper.update();
++
++ // ne pas ajouter le camera helper dans la vue originelle
++ cameraHelper.visible = false;
++
++ scene.background.set(0x000000);
++
++ // rendu
++ renderer.render(scene, camera);
++ }
++
++ // rendu de la 2e caméra
++ {
++ const aspect = setScissorForElement(view2Elem);
++
++ // adjuste la caméra
++ camera2.aspect = aspect;
++ camera2.updateProjectionMatrix();
++
++ // camera helper dans la 2e vue
++ cameraHelper.visible = true;
++
++ scene.background.set(0x000040);
++
++ renderer.render(scene, camera2);
++ }
+
+- renderer.render(scene, camera);
+
+ requestAnimationFrame(render);
+ }
+
+ requestAnimationFrame(render);
+}
+```
+
+Le code ci-dessus définit la couleur d'arrière-plan de la scène lors du rendu de la deuxième vue en bleu foncé juste pour faciliter la distinction des deux vues.
+
+Nous pouvons également supprimer notre code `updateCamera` puisque nous mettons tout à jour dans la fonction `render`.
+
+```js
+-function updateCamera() {
+- camera.updateProjectionMatrix();
+-}
+
+const gui = new GUI();
+-gui.add(camera, 'fov', 1, 180).onChange(updateCamera);
++gui.add(camera, 'fov', 1, 180);
+const minMaxGUIHelper = new MinMaxGUIHelper(camera, 'near', 'far', 0.1);
+-gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera);
+-gui.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far').onChange(updateCamera);
++gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near');
++gui.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far');
+```
+
+Et maintenant, vous pouvez utiliser une vue pour voir le frustum de l'autre.
+
+{{{example url="../threejs-cameras-perspective-2-scenes.html" }}}
+
+Sur la gauche, vous pouvez voir la vue d'origine et sur la droite, vous pouvez voir une vue montrant le frustum sur la gauche. Lorsque vous ajustez `near`, `far`, `fov` et déplacez la caméra avec la souris, vous pouvez voir que seul ce qui se trouve à l'intérieur du frustum montré à droite apparaît dans la scène à gauche.
+
+Ajustez `near` d'environ 20 et vous verrez facilement le devant des objets disparaître car ils ne sont plus dans le tronc. Ajustez `far` en dessous de 35 et vous commencerez à voir le plan de masse disparaître car il n'est plus dans le tronc.
+
+Cela soulève la question, pourquoi ne pas simplement définir `near` de 0,0000000001 et `far` de 100000000000000 ou quelque chose comme ça pour que vous puissiez tout voir? Parce que votre GPU n'a qu'une précision limitée pour décider si quelque chose est devant ou derrière quelque chose d'autre. Cette précision se répartit entre `near` et `far`. Pire, par défaut la précision au plus près de la caméra est précise tandis que celle la plus lointaine de la caméra est grossière. Les unités commencent par `near` et s'étendent lentement à mesure qu'elles s'approchent de `far`.
+
+En commençant par l'exemple du haut, modifions le code pour insérer 20 sphères d'affilée.
+
+```js
+{
+ const sphereRadius = 3;
+ const sphereWidthDivisions = 32;
+ const sphereHeightDivisions = 16;
+ const sphereGeo = new THREE.SphereGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
+ const numSpheres = 20;
+ for (let i = 0; i < numSpheres; ++i) {
+ const sphereMat = new THREE.MeshPhongMaterial();
+ sphereMat.color.setHSL(i * .73, 1, 0.5);
+ const mesh = new THREE.Mesh(sphereGeo, sphereMat);
+ mesh.position.set(-sphereRadius - 1, sphereRadius + 2, i * sphereRadius * -2.2);
+ scene.add(mesh);
+ }
+}
+```
+
+et définissons `near` à 0.00001
+
+```js
+const fov = 45;
+const aspect = 2; // valeur par défaut
+-const near = 0.1;
++const near = 0.00001;
+const far = 100;
+const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
+```
+
+Nous devons également modifier un peu le code de dat.GUI pour autoriser 0,00001 si la valeur est modifiée.
+
+```js
+-gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera);
++gui.add(minMaxGUIHelper, 'min', 0.00001, 50, 0.00001).name('near').onChange(updateCamera);
+```
+
+Que pensez-vous qu'il va se passer ?
+
+{{{example url="../threejs-cameras-z-fighting.html" }}}
+
+Ceci est un exemple de *z fighting* où le GPU de votre ordinateur n'a pas assez de précision pour décider quels pixels sont devant et quels pixels sont derrière.
+
+Juste au cas où le problème ne s'afficherait pas sur votre machine, voici ce que je vois sur la mienne.
+
+<div class="threejs_center"><img src="resources/images/z-fighting.png" style="width: 570px;"></div>
+
+Une solution consiste à indiquer à Three.js d'utiliser une méthode différente pour calculer quels pixels sont devant et lesquels sont derrière. Nous pouvons le faire en activant `logarithmicDepthBuffer` lorsque nous créons le [`WebGLRenderer`](https://threejs.org/docs/#api/en/renderers/WebGLRenderer)
+
+```js
+-const renderer = new THREE.WebGLRenderer({canvas});
++const renderer = new THREE.WebGLRenderer({
++ canvas,
++ logarithmicDepthBuffer: true,
++});
+```
+
+et avec ça, ça devrait marcher.
+
+{{{example url="../threejs-cameras-logarithmic-depth-buffer.html" }}}
+
+Si cela n'a pas résolu le problème pour vous, vous avez rencontré une raison pour laquelle vous ne pouvez pas toujours utiliser cette solution. Cette raison est due au fait que seuls certains GPU le prennent en charge. En septembre 2018, presque aucun appareil mobile ne prenait en charge cette solution, contrairement à la plupart des ordinateurs de bureau.
+
+Une autre raison de ne pas choisir cette solution est qu'elle peut être nettement plus lente que la solution standard.
+
+Même avec cette solution, la résolution est encore limitée. Rendez `near` encore plus petit ou `far` plus grand et vous finirez par rencontrer les mêmes problèmes.
+
+Cela signifie que vous devez toujours faire un effort pour choisir un paramètre `near` et `far` qui correspond à votre cas d'utilisation. Placez `near` aussi loin que possible de la caméra et rien ne disparaîtra. Placez `far` aussi près que possible de la caméra et, de même, tout restera visible. Si vous essayez de dessiner une scène géante et de montrer en gros plan un visage de façon à voir ses cils, tandis qu'en arrière-plan il possible de voir les montagnes à 50 kilomètres de distance, vous devrez en trouver d'autres solutions créatives, nous-y reviendrons peut-être plus tard. Pour l'instant, sachez que vous devez prendre soin de choisir des valeurs proches et éloignées appropriées à vos besoins.
+
+La deuxième caméra la plus courante est l'[`OrthographicCamera`](https://threejs.org/docs/#api/en/cameras/OrthographicCamera). Plutôt que de définir un frustum, il spécifie une boîte avec les paramètres `left`, `right`, `top`, `bottom`, `near` et `far`. Comme elle projette une boîte, il n'y a pas de perspective.
+
+Changeons notre exemple précédent pour utiliser une `OrthographicCamera` dans la première vue.
+
+D'abord, paramétrons notre `OrthographicCamera`.
+
+```js
+const left = -1;
+const right = 1;
+const top = 1;
+const bottom = -1;
+const near = 5;
+const far = 50;
+const camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far);
+camera.zoom = 0.2;
+```
+
+Définissons `left` and `bottom` à -1 et `right` et `top` à 1. On devrait obtenir une boîte de 2 unités de large et 2 unités de haut, mais nous allons ajuster `left` et `top` en fonction de l'aspect du rectangle sur lequel nous dessinons. Nous utiliserons la propriété `zoom` pour faciliter le réglage du nombre d'unités réellement affichées par la caméra.
+
+Ajoutons un nouveau paramètre à dat.GUI pour le `zoom`.
+
+```js
+const gui = new GUI();
++gui.add(camera, 'zoom', 0.01, 1, 0.01).listen();
+```
+
+L'appel à `listen` dit à dat.GUI de surveiller les changements. Il faut faire cela parce que `OrbitControls` peut contrôler le zoom. Par exemple, la molette de défilement d'une souris zoomera via les `OrbitControls`.
+
+Enfin, nous avons juste besoin de changer la partie qui rend le côté gauche pour mettre à jour la `OrthographicCamera`.
+
+```js
+{
+ const aspect = setScissorForElement(view1Elem);
+
+ // mettre à jour la caméra pour cet aspect
+- camera.aspect = aspect;
++ camera.left = -aspect;
++ camera.right = aspect;
+ camera.updateProjectionMatrix();
+ cameraHelper.update();
+
+ // ne pas dessiner le camera helper dans la vue d'origine
+ cameraHelper.visible = false;
+
+ scene.background.set(0x000000);
+ renderer.render(scene, camera);
+}
+```
+
+et maintenant vous pouvez voir une `OrthographicCamera` au boulot.
+
+{{{example url="../threejs-cameras-orthographic-2-scenes.html" }}}
+
+Une `OrthographicCamera` est souvent utilisée pour dessiner des objets en 2D. Il faut décider du nombre d'unités que la caméra doit afficher. Par exemple, si vous voulez qu'un pixel du canvas corresponde à une unité de l'appareil photo, vous pouvez faire quelque chose comme.
+
+
+Pour mettre l'origine au centre et avoir 1 pixel = 1 unité three.js quelque chose comme
+
+```js
+camera.left = -canvas.width / 2;
+camera.right = canvas.width / 2;
+camera.top = canvas.height / 2;
+camera.bottom = -canvas.height / 2;
+camera.near = -1;
+camera.far = 1;
+camera.zoom = 1;
+```
+
+Ou si nous voulions que l'origine soit en haut à gauche comme un canvas 2D, nous pourrions utiliser ceci
+
+```js
+camera.left = 0;
+camera.right = canvas.width;
+camera.top = 0;
+camera.bottom = canvas.height;
+camera.near = -1;
+camera.far = 1;
+camera.zoom = 1;
+```
+
+Dans ce cas, le coin supérieur gauche serait à 0,0 tout comme un canvas 2D.
+
+Essayons! Commençons par installer la caméra.
+
+```js
+const left = 0;
+const right = 300; // taille par défaut
+const top = 0;
+const bottom = 150; // taille par défaut
+const near = -1;
+const far = 1;
+const camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far);
+camera.zoom = 1;
+```
+
+Chargeons ensuite 6 textures et créons 6 plans, un pour chaque texture. Nous allons associer chaque plan à un `THREE.Object3D` pour faciliter le décalage du plan afin que son centre semble être dans son coin supérieur gauche.
+
+Pour travailler en local sur votre machine, vous aurez besoin d'une [configuration spécifique](threejs-setup.html).
+Vous voudrez peut-être en savoir plus sur [l'utilisation des textures](threejs-textures.html).
+
+```js
+const loader = new THREE.TextureLoader();
+const textures = [
+ loader.load('resources/images/flower-1.jpg'),
+ loader.load('resources/images/flower-2.jpg'),
+ loader.load('resources/images/flower-3.jpg'),
+ loader.load('resources/images/flower-4.jpg'),
+ loader.load('resources/images/flower-5.jpg'),
+ loader.load('resources/images/flower-6.jpg'),
+];
+const planeSize = 256;
+const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize);
+const planes = textures.map((texture) => {
+ const planePivot = new THREE.Object3D();
+ scene.add(planePivot);
+ texture.magFilter = THREE.NearestFilter;
+ const planeMat = new THREE.MeshBasicMaterial({
+ map: texture,
+ side: THREE.DoubleSide,
+ });
+ const mesh = new THREE.Mesh(planeGeo, planeMat);
+ planePivot.add(mesh);
+ // déplacer le plan pour que le coin supérieur gauche soit l'origine
+ mesh.position.set(planeSize / 2, planeSize / 2, 0);
+ return planePivot;
+});
+```
+
+et nous devons mettre à jour la caméra si la taille de la toile change.
+
+```js
+function render() {
+
+ if (resizeRendererToDisplaySize(renderer)) {
+ camera.right = canvas.width;
+ camera.bottom = canvas.height;
+ camera.updateProjectionMatrix();
+ }
+
+ ...
+```
+
+`planes` est un tableau de `THREE.Mesh`.
+Déplaçons-les en fonction du temps.
+
+```js
+function render(time) {
+ time *= 0.001; // convertir en secondes;
+
+ ...
+
+ const distAcross = Math.max(20, canvas.width - planeSize);
+ const distDown = Math.max(20, canvas.height - planeSize);
+
+ // distance totale à parcourir
+ const xRange = distAcross * 2;
+ const yRange = distDown * 2;
+ const speed = 180;
+
+ planes.forEach((plane, ndx) => {
+ // calculer un temps unique pour chaque plan
+ const t = time * speed + ndx * 300;
+
+ // définir une valeur entre 0 et une plage
+ const xt = t % xRange;
+ const yt = t % yRange;
+
+ // définit notre position en avant si 0 à la moitié de la plage
+ // et vers l'arrière si la moitié de la plage à la plage
+ const x = xt < distAcross ? xt : xRange - xt;
+ const y = yt < distDown ? yt : yRange - yt;
+
+ plane.position.set(x, y, 0);
+ });
+
+ renderer.render(scene, camera);
+```
+
+Et vous pouvez voir les images rebondir parfaitement sur les bords de la toile en utilisant les mathématiques des pixels, tout comme une toile 2D.
+
+{{{example url="../threejs-cameras-orthographic-canvas-top-left-origin.html" }}}
+
+Une autre utilisation courante d'une caméra orthographique est de dessiner les vues haut, bas, gauche, droite, avant et arrière d'un programme de modélisation 3D ou d'un éditeur de moteur de jeu.
+
+<div class="threejs_center"><img src="resources/images/quad-viewport.png" style="width: 574px;"></div>
+
+Dans la capture d'écran ci-dessus, vous pouvez voir que 1 vue est une vue en perspective et 3 vues sont des vues orthogonales.
+
+C'est la base des caméras. Nous aborderons quelques façons courantes de déplacer les caméras dans d'autres articles. Pour l'instant passons aux [ombres](threejs-shadows.html).
+
+<canvas id="c"></canvas>
+<script type="module" src="resources/threejs-cameras.js"></script> | false |
Other | mrdoob | three.js | 5b618ac3f9f83c03eb9996e3bacf54c7933e5015.json | add French translation | threejs/lessons/fr/threejs-lights.md | @@ -0,0 +1,499 @@
+Title: Lumières en Three.js
+Description: Configuration des mulières
+TOC: Lights
+
+Cet article fait partie d'une série consacrée à Three.js.
+Le premier article s'intitule [Principes de base](threejs-fundamentals.html). Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là ou aussi voir l'article sur [la configuartion de votre environnement](threejs-setup.html). L'
+[article précédent](threejs-textures.html) parlait des textures.
+
+Voyons comment utiliser les différents types de lumières.
+
+En commençant par l'un de nos exemples précédents, mettons à jour la caméra. Nous allons régler le champ de vision à 45 degrés, le plan éloigné à 100 unités, et nous déplacerons la caméra de 10 unités vers le haut et 20 unités en arrière de l'origine.
+
+```js
+*const fov = 45;
+const aspect = 2; // the canvas default
+const near = 0.1;
+*const far = 100;
+const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
++camera.position.set(0, 10, 20);
+```
+
+Ajoutons ensuite `OrbitControls`. `OrbitControls` permet à l'utilisateur de tourner ou de mettre la caméra en *orbite* autour d'un certain point. Il s'agit d'une fonctionnalité facultative de Three.js, nous devons donc d'abord l'importer
+
+```js
+import * as THREE from './resources/three/r127/build/three.module.js';
++import {OrbitControls} from './resources/threejs/r127/examples/jsm/controls/OrbitControls.js';
+```
+
+Ensuite, nous pouvons l'utiliser. Nous passons à `OrbitControls` une caméra à contrôler et l'élément DOM à utiliser.
+
+```js
+const controls = new OrbitControls(camera, canvas);
+controls.target.set(0, 5, 0);
+controls.update();
+```
+
+Nous plaçons également la cible en orbite, 5 unités au-dessus de l'origine
+et appelons `controls.update` afin que les contrôles utilisent la nouvelle cible.
+
+Ensuite, créons des choses à éclairer. Nous allons d'abord faire un plan au sol. Nous allons appliquer une petite texture en damier de 2x2 pixels qui ressemble à ceci
+
+<div class="threejs_center">
+ <img src="../resources/images/checker.png" class="border" style="
+ image-rendering: pixelated;
+ width: 128px;
+ ">
+</div>
+
+Tout d'abord, chargeons la texture, définissons-la sur répétition, définissons le filtrage au plus proche et définissons le nombre de fois que nous voulons qu'elle se répète. Étant donné que la texture est un damier de 2x2 pixels, en répétant et en définissant la répétition à la moitié de la taille du plan, chaque case sur le damier aura exactement 1 unité de large ;
+
+```js
+const planeSize = 40;
+
+const loader = new THREE.TextureLoader();
+const texture = loader.load('resources/images/checker.png');
+texture.wrapS = THREE.RepeatWrapping;
+texture.wrapT = THREE.RepeatWrapping;
+texture.magFilter = THREE.NearestFilter;
+const repeats = planeSize / 2;
+texture.repeat.set(repeats, repeats);
+```
+
+Nous fabriquons ensuite une géométrie 'plane', un matériau et une 'mesh' pour l'insérer dans la scène. Les plans sont par défaut dans le plan XY, mais le sol est dans le plan XZ, nous le faisons donc pivoter.
+
+```js
+const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize);
+const planeMat = new THREE.MeshPhongMaterial({
+ map: texture,
+ side: THREE.DoubleSide,
+});
+const mesh = new THREE.Mesh(planeGeo, planeMat);
+mesh.rotation.x = Math.PI * -.5;
+scene.add(mesh);
+```
+
+Ajoutons un cube et une sphère, ainsi nous aurons 3 choses à éclairer dont le plan
+
+```js
+{
+ const cubeSize = 4;
+ const cubeGeo = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
+ const cubeMat = new THREE.MeshPhongMaterial({color: '#8AC'});
+ const mesh = new THREE.Mesh(cubeGeo, cubeMat);
+ mesh.position.set(cubeSize + 1, cubeSize / 2, 0);
+ scene.add(mesh);
+}
+{
+ const sphereRadius = 3;
+ const sphereWidthDivisions = 32;
+ const sphereHeightDivisions = 16;
+ const sphereGeo = new THREE.SphereGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
+ const sphereMat = new THREE.MeshPhongMaterial({color: '#CA8'});
+ const mesh = new THREE.Mesh(sphereGeo, sphereMat);
+ mesh.position.set(-sphereRadius - 1, sphereRadius + 2, 0);
+ scene.add(mesh);
+}
+```
+
+Maintenant que nous avons une scène à éclairer, ajoutons des lumières !
+
+## `AmbientLight`
+
+D'abord mettons en place une `AmbientLight`
+
+```js
+const color = 0xFFFFFF;
+const intensity = 1;
+const light = new THREE.AmbientLight(color, intensity);
+scene.add(light);
+```
+
+Faisons aussi en sorte que nous puissions ajuster les paramètres de la lumière.
+Utilisons à nouveau [dat.GUI](https://github.com/dataarts/dat.gui).
+Pour pouvoir ajuster la couleur via dat.GUI, nous avons besoin d'un petit 'helper' qui fournit à dat.GUI une couleur en hexadécimale (eg: `#FF8844`). Notre 'helper' obtiendra la couleur d'une propriété nommée, la convertira en une chaîne hexadécimale à offrir à dat.GUI. Lorsque dat.GUI essaie de définir la propriété de l'assistant, nous attribuons le résultat à la couleur de la lumière.
+
+Voici notre 'helper':
+
+```js
+class ColorGUIHelper {
+ constructor(object, prop) {
+ this.object = object;
+ this.prop = prop;
+ }
+ get value() {
+ return `#${this.object[this.prop].getHexString()}`;
+ }
+ set value(hexString) {
+ this.object[this.prop].set(hexString);
+ }
+}
+```
+
+Et voici le code de configuartion de dat.GUI
+
+```js
+const gui = new GUI();
+gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
+gui.add(light, 'intensity', 0, 2, 0.01);
+```
+
+Le résultat :
+
+{{{example url="../threejs-lights-ambient.html" }}}
+
+Cliquez/glissez pour mettre la caméra en *orbite*.
+
+Remarquez qu'il n'y a pas de définition. Les formes sont plates. L'`AmbientLight` multiplie simplement la couleur du matériau par la couleur de la lumière multipliée par l'intensité.
+
+ color = materialColor * light.color * light.intensity;
+
+C'est ça. Il n'a pas de direction. Ce style d'éclairage ambiant n'est en fait pas très utile en tant qu'éclairage, à part changer la couleur de toute la scène, ce n'est pas vraiment un éclairage, ça rend juste les ténèbres moins sombres.
+
+
+XXXXXXXXXXXXXXXXXXXXXXX
+
+## `HemisphereLight`
+
+Passons à une `HemisphereLight`. Une `HemisphereLight` prend une couleur de ciel et une couleur de sol et multiplie simplement la couleur du matériau entre ces 2 couleurs : la couleur du ciel si la surface de l'objet pointe vers le haut et la couleur du sol si la surface de l'objet pointe vers le bas.
+
+Voici le nouveau code
+
+```js
+-const color = 0xFFFFFF;
++const skyColor = 0xB1E1FF; // light blue
++const groundColor = 0xB97A20; // brownish orange
+const intensity = 1;
+-const light = new THREE.AmbientLight(color, intensity);
++const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
+scene.add(light);
+```
+
+Mettons aussi à jour le dat.GUI avec ces 2 couleurs
+
+```js
+const gui = new GUI();
+-gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
++gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('skyColor');
++gui.addColor(new ColorGUIHelper(light, 'groundColor'), 'value').name('groundColor');
+gui.add(light, 'intensity', 0, 2, 0.01);
+```
+
+Le resultat :
+
+{{{example url="../threejs-lights-hemisphere.html" }}}
+
+Remarquez encore une fois qu'il n'y a presque pas de définition, tout a l'air plutôt plat. L'`HemisphereLight` utilisée en combinaison avec une autre lumière peut aider à donner une belle sorte d'influence de la couleur du ciel et du sol. Retenez qu'il est préférable de l'utiliser en combinaison avec une autre lumière ou à la place d'une `AmbientLight`.
+
+## `DirectionalLight`
+
+Remplaçons le code par une `DirectionalLight`.
+Une `DirectionalLight` est souvent utiliser pour représenter la lumière du soleil.
+
+```js
+const color = 0xFFFFFF;
+const intensity = 1;
+const light = new THREE.DirectionalLight(color, intensity);
+light.position.set(0, 10, 0);
+light.target.position.set(-5, 0, 0);
+scene.add(light);
+scene.add(light.target);
+```
+
+Notez que nous avons dû ajouter une `light` et une `light.target`
+à la scéne. Une `DirectionalLight` doit illuminer une cible.
+
+Faisons en sorte que nous puissions déplacer la cible en l'ajoutant à dat.GUI.
+
+```js
+const gui = new GUI();
+gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
+gui.add(light, 'intensity', 0, 2, 0.01);
+gui.add(light.target.position, 'x', -10, 10);
+gui.add(light.target.position, 'z', -10, 10);
+gui.add(light.target.position, 'y', 0, 10);
+```
+
+{{{example url="../threejs-lights-directional.html" }}}
+
+C'est un peu difficile de voir ce qui se passe. Three.js a un tas de 'helper' que nous pouvons ajouter à la scène pour voir les objets invibles. Utilisons, dans ce cas,
+`DirectionalLightHelper` qui a représente la source de lumière en direction de sa cible. Il suffit de lui ajouter une lumière et de l'ajouter à la scène.
+
+```js
+const helper = new THREE.DirectionalLightHelper(light);
+scene.add(helper);
+```
+
+Pendant que nous y sommes, faisons en sorte que nous puissions définir à la fois la position de la lumière et la cible. Pour ce faire, nous allons créer une fonction qui, étant donné un `Vector3`, ajustera ses propriétés `x`, `y` et `z` à l'aide de `dat.GUI`.
+
+```js
+function makeXYZGUI(gui, vector3, name, onChangeFn) {
+ const folder = gui.addFolder(name);
+ folder.add(vector3, 'x', -10, 10).onChange(onChangeFn);
+ folder.add(vector3, 'y', 0, 10).onChange(onChangeFn);
+ folder.add(vector3, 'z', -10, 10).onChange(onChangeFn);
+ folder.open();
+}
+```
+
+Notez que nous devons appeler la fonction `update` du 'helper' à chaque fois que nous modifions quelque chose afin que l'assistant sache se mettre à jour. En tant que tel, nous passons une fonction `onChangeFn` pour être appelée à chaque fois que dat.GUI met à jour une valeur.
+
+Ensuite, nous pouvons l'utiliser à la fois pour la position de la lumière et la position de la cible comme ceci
+
+```js
++function updateLight() {
++ light.target.updateMatrixWorld();
++ helper.update();
++}
++updateLight();
+
+const gui = new GUI();
+gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
+gui.add(light, 'intensity', 0, 2, 0.01);
+
++makeXYZGUI(gui, light.position, 'position', updateLight);
++makeXYZGUI(gui, light.target.position, 'target', updateLight);
+```
+
+Maintenant, nous pouvons bouger la lumière, et sa cible.
+
+{{{example url="../threejs-lights-directional-w-helper.html" }}}
+
+Mettez la caméra en orbite et il devient plus facile de voir. Le plan représente une lumière directionnelle car une lumière directionnelle calcule la lumière venant dans une direction. Il n'y a aucun point d'où vient la lumière, c'est un plan de lumière infini qui projette des rayons de lumière parallèles.
+
+## `PointLight`
+
+Un `PointLight` est une lumière qui se trouve en un point et projette de la lumière dans toutes les directions à partir de ce point. Changeons le code.
+
+```js
+const color = 0xFFFFFF;
+const intensity = 1;
+-const light = new THREE.DirectionalLight(color, intensity);
++const light = new THREE.PointLight(color, intensity);
+light.position.set(0, 10, 0);
+-light.target.position.set(-5, 0, 0);
+scene.add(light);
+-scene.add(light.target);
+```
+
+Passons également à un `PointLightHelper`
+
+```js
+-const helper = new THREE.DirectionalLightHelper(light);
++const helper = new THREE.PointLightHelper(light);
+scene.add(helper);
+```
+
+et comme il n'y a pas de cible la fonction `onChange` peut être simplifiée.
+
+```js
+function updateLight() {
+- light.target.updateMatrixWorld();
+ helper.update();
+}
+-updateLight();
+```
+
+Notez qu'à un certain niveau, un `PointLightHelper` n'a pas de point. Il dessine juste un petit diamant filaire. Ou n'importe quelle autre forme que vous voulez, ajoutez simplement un maillage à la lumière elle-même.
+
+Une `PointLight` a une propriété supplémentaire, [`distance`](PointLight.distance).
+Si la `distance` est de 0, le `PointLight` brille à l'infini. Si la `distance` est supérieure à 0, la lumière brille de toute son intensité vers la lumière et s'estompe jusqu'à n'avoir aucune influence à des unités de `distance` de la lumière.
+
+Mettons à jour dat.GUI pour pouvoir modifier la distance.
+
+```js
+const gui = new GUI();
+gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
+gui.add(light, 'intensity', 0, 2, 0.01);
++gui.add(light, 'distance', 0, 40).onChange(updateLight);
+
+makeXYZGUI(gui, light.position, 'position', updateLight);
+-makeXYZGUI(gui, light.target.position, 'target', updateLight);
+```
+
+Et maintennat, testons.
+
+{{{example url="../threejs-lights-point.html" }}}
+
+Remarquez comment la lumière s'éteint lorsque la `distance` est > 0.
+
+## `SpotLight`
+
+La `SpotLight` (projecteur), c'est une lumière ponctuelle avec un cône attaché où la lumière ne brille qu'à l'intérieur du cône. Il y a en fait 2 cônes. Un cône extérieur et un cône intérieur. Entre le cône intérieur et le cône extérieur, la lumière passe de la pleine intensité à zéro.
+
+Pour utiliser une `SpotLight`, nous avons besoin d'une cible tout comme la lumière directionnelle. Le cône de lumière s'ouvrira vers la cible.
+
+Modifions notre `DirectionalLight` avec le 'helper' vu plus haut
+
+```js
+const color = 0xFFFFFF;
+const intensity = 1;
+-const light = new THREE.DirectionalLight(color, intensity);
++const light = new THREE.SpotLight(color, intensity);
+scene.add(light);
+scene.add(light.target);
+
+-const helper = new THREE.DirectionalLightHelper(light);
++const helper = new THREE.SpotLightHelper(light);
+scene.add(helper);
+```
+
+L'angle du cône de la `Spotlight` est défini avec la propriété [`angle`](SpotLight.angle)
+en radians. Utilisons notre `DegRadHelper` vu dans
+[l'article sur les textures](threejs-textures.html) pour modifier l'angle avec dat.GUI.
+
+```js
+gui.add(new DegRadHelper(light, 'angle'), 'value', 0, 90).name('angle').onChange(updateLight);
+```
+
+Le cône intérieur est défini en paramétrant la propriété [`penumbra`](SpotLight.penumbra) en pourcentage du cône extérieur. En d'autres termes, lorsque la pénombre est de 0, le cône intérieur a la même taille (0 = aucune différence) que le cône extérieur. Lorsque la pénombre est de 1, la lumière s'estompe en partant du centre du cône jusqu'au cône extérieur. Lorsque la pénombre est de 0,5, la lumière s'estompe à partir de 50 % entre le centre du cône extérieur.
+
+```js
+gui.add(light, 'penumbra', 0, 1, 0.01);
+```
+
+{{{example url="../threejs-lights-spot-w-helper.html" }}}
+
+Remarquez qu'avec la `penumbra` par défaut à 0, le projecteur a un bord très net alors que lorsque vous l'ajustez à 1, le bord devient flou.
+
+Il peut être difficile de voir le *cône* des spotlight. C'est parce qu'il se trouve sous le sol. Raccourcissez la distance à environ 5 et vous verrez l'extrémité ouverte du cône.
+
+## `RectAreaLight`
+
+Il existe un autre type de lumière, la [`RectAreaLight`](https://threejs.org/docs/#api/en/lights/RectAreaLight), qui ressemble à une zone de lumière rectangulaire comme une longue lampe fluorescente ou peut-être une lucarne dépolie dans un plafond.
+
+Le [`RectAreaLight`](https://threejs.org/docs/#api/en/lights/RectAreaLight) ne fonctionne qu'avec les [`MeshStandardMaterial`](https://threejs.org/docs/#api/en/materials/MeshStandardMaterial) et [`MeshPhysicalMaterial`](https://threejs.org/docs/#api/en/materials/MeshPhysicalMaterial) donc changeons tous nos matériaux en `MeshStandardMaterial`
+
+```js
+ ...
+
+ const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize);
+- const planeMat = new THREE.MeshPhongMaterial({
++ const planeMat = new THREE.MeshStandardMaterial({
+ map: texture,
+ side: THREE.DoubleSide,
+ });
+ const mesh = new THREE.Mesh(planeGeo, planeMat);
+ mesh.rotation.x = Math.PI * -.5;
+ scene.add(mesh);
+}
+{
+ const cubeSize = 4;
+ const cubeGeo = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
+- const cubeMat = new THREE.MeshPhongMaterial({color: '#8AC'});
++ const cubeMat = new THREE.MeshStandardMaterial({color: '#8AC'});
+ const mesh = new THREE.Mesh(cubeGeo, cubeMat);
+ mesh.position.set(cubeSize + 1, cubeSize / 2, 0);
+ scene.add(mesh);
+}
+{
+ const sphereRadius = 3;
+ const sphereWidthDivisions = 32;
+ const sphereHeightDivisions = 16;
+ const sphereGeo = new THREE.SphereGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
+- const sphereMat = new THREE.MeshPhongMaterial({color: '#CA8'});
++ const sphereMat = new THREE.MeshStandardMaterial({color: '#CA8'});
+ const mesh = new THREE.Mesh(sphereGeo, sphereMat);
+ mesh.position.set(-sphereRadius - 1, sphereRadius + 2, 0);
+ scene.add(mesh);
+}
+```
+
+Pour utiliser [`RectAreaLight`](https://threejs.org/docs/#api/en/lights/RectAreaLight) nous devons importer [`RectAreaLightHelper`](https://threejs.org/docs/#api/en/helpers/RectAreaLightHelper) pour nous aider à voir la lumière.
+
+```js
+import * as THREE from './resources/three/r127/build/three.module.js';
++import {RectAreaLightUniformsLib} from './resources/threejs/r127/examples/jsm/lights/RectAreaLightUniformsLib.js';
++import {RectAreaLightHelper} from './resources/threejs/r127/examples/jsm/helpers/RectAreaLightHelper.js';
+```
+
+et nous devons appeler `RectAreaLightUniformsLib.init`
+
+```js
+function main() {
+ const canvas = document.querySelector('#c');
+ const renderer = new THREE.WebGLRenderer({canvas});
++ RectAreaLightUniformsLib.init();
+```
+
+Si vous oubliez les données, la lumière fonctionnera toujours, mais ça pourrait paraître bizarre, alors n'oubliez pas d'inclure les données supplémentaires.
+
+Maintenant, nous pouvons créer la lumière
+
+```js
+const color = 0xFFFFFF;
+*const intensity = 5;
++const width = 12;
++const height = 4;
+*const light = new THREE.RectAreaLight(color, intensity, width, height);
+light.position.set(0, 10, 0);
++light.rotation.x = THREE.MathUtils.degToRad(-90);
+scene.add(light);
+
+*const helper = new RectAreaLightHelper(light);
+*light.add(helper);
+```
+
+Une chose à noter est que contrairement au [`DirectionalLight`](https://threejs.org/docs/#api/en/lights/DirectionalLight) et à la [`SpotLight`](https://threejs.org/docs/#api/en/lights/SpotLight), la [`RectAreaLight`](https://threejs.org/docs/#api/en/lights/RectAreaLight) n'utilise pas de cible. Elle utilise juste sa rotation. Une autre chose à noter est que le 'helper' doit être un enfant de la lumière. Ce n'est pas un enfant de la scène comme les autres 'helpers'.
+
+Ajustons-la également à dat.GUI. Nous allons le faire pour que nous puissions faire pivoter la lumière et ajuster sa `width` et sa `height`
+
+```js
+const gui = new GUI();
+gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
+gui.add(light, 'intensity', 0, 10, 0.01);
+gui.add(light, 'width', 0, 20);
+gui.add(light, 'height', 0, 20);
+gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation');
+gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation');
+gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation');
+
+makeXYZGUI(gui, light.position, 'position');
+```
+
+Et voici ce que ça donne.
+
+{{{example url="../threejs-lights-rectarea.html" }}}
+
+Une chose que nous n'avons pas vu, c'est qu'il existe un paramètre sur le [`WebGLRenderer`](https://threejs.org/docs/#api/en/renderers/WebGLRenderer) appelé `physicalCorrectLights`. Il affecte la façon dont la lumière tombe en tant que distance de la lumière. Cela n'affecte que [`PointLight`](https://threejs.org/docs/#api/en/lights/PointLight) et [`SpotLight`](https://threejs.org/docs/#api/en/lights/SpotLight). [`RectAreaLight`](https://threejs.org/docs/#api/en/lights/RectAreaLight) le fait automatiquement.
+
+Pour les lumières, l'idée de base est de ne pas définir de distance pour qu'elles s'éteignent, et vous ne définissez pas `intensity`. Au lieu de cela, vous définissez la [`power`](PointLight.power) de la lumière en lumens, puis three.js utilisera des calculs physiques comme de vraies lumières. Les unités de three.js dans ce cas sont des mètres et une ampoule de 60w aurait environ 800 lumens. Il y a aussi une propriété [`decay`](PointLight.decay). Elle doit être réglé sur 2 pour une apparence réaliste.
+
+Testons ça.
+
+D'abord, définissons `physicallyCorrectLights` sur true
+
+```js
+const renderer = new THREE.WebGLRenderer({canvas});
++renderer.physicallyCorrectLights = true;
+```
+
+Ensuite, réglons la `power` à 800 lumens, la `decay` à 2, et
+la `distance` sur `Infinity`.
+
+```js
+const color = 0xFFFFFF;
+const intensity = 1;
+const light = new THREE.PointLight(color, intensity);
+light.power = 800;
+light.decay = 2;
+light.distance = Infinity;
+```
+
+et mettons à jour dat.GUI pour pouvoir changer `power` et `decay`
+
+```js
+const gui = new GUI();
+gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
+gui.add(light, 'decay', 0, 4, 0.01);
+gui.add(light, 'power', 0, 2000);
+```
+
+{{{example url="../threejs-lights-point-physically-correct.html" }}}
+
+Il est important de noter que chaque lumière que vous ajoutez à la scène ralentit la vitesse à laquelle Three.js rend la scène, vous devez donc toujours essayer d'en utiliser le moins possible pour atteindre vos objectifs.
+
+Passons maintenant à [la gestion des caméras](threejs-cameras.html).
+
+<canvas id="c"></canvas>
+<script type="module" src="resources/threejs-lights.js"></script> | false |
Other | mrdoob | three.js | 6756b017b5baccc75e99c4069047918aa1a0ebf5.json | add French Translation | threejs/lessons/fr/threejs-textures.md | @@ -0,0 +1,533 @@
+Title: Three.js Textures
+Description: Using textures in three.js
+TOC: Textures
+
+Cet article fait partie d'une série consacrée à Three.js.
+Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
+L'[article précédent](threejs-setup.html) concerné la configuration nécessaire pour cet article.
+Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
+
+Les textures sont un gros sujet dans Three.js et je ne suis pas sûr de pouvoir les expliquer à 100% mais je vais essayer. Il y a de nombreuses choses à voir et beaucoup d'entre elles sont interdépendantes, il est donc difficile de les expliquer tous en même temps. Voici une table des matières rapide pour cet article.
+
+<ul>
+<li><a href="#hello">Hello Texture</a></li>
+<li><a href="#six">6 textures, une pour chaque face d'un cube</a></li>
+<li><a href="#loading">Téléchargement de textures</a></li>
+<ul>
+ <li><a href="#easy">La façon la plus simple</a></li>
+ <li><a href="#wait1">En attente du chargement d'une texture</a></li>
+ <li><a href="#waitmany">En attente du téléchargement de plusieurs textures</a></li>
+ <li><a href="#cors">Chargement de textures d'autres origines</a></li>
+</ul>
+<li><a href="#memory">Utilisation de la mémoire</a></li>
+<li><a href="#format">JPG ou PNG</a></li>
+<li><a href="#filtering-and-mips">Filtrage et mips</a></li>
+<li><a href="#uvmanipulation">Répétition, décalage, rotation, emballage</a></li>
+</ul>
+
+## <a name="hello"></a> Hello Texture
+
+Les textures sont *generallement* des images qui sont le plus souvent créées dans un programme tiers comme Photoshop ou GIMP. Par exemple, mettons cette image sur un cube.
+
+<div class="threejs_center">
+ <img src="../resources/images/wall.jpg" style="width: 600px;" class="border" >
+</div>
+
+Modifions l'un de nos premiers échantillons. Tout ce que nous avons à faire, c'est de créer un `TextureLoader`. Appelons-le avec sa méthode
+[`load`](TextureLoader.load) et l'URL d'une image définissons la propriété `map` du matériau sur le résultat au lieu de définir sa `color`.
+
+```js
++const loader = new THREE.TextureLoader();
+
+const material = new THREE.MeshBasicMaterial({
+- color: 0xFF8844,
++ map: loader.load('resources/images/wall.jpg'),
+});
+```
+
+Notez que nous utilisons un `MeshBasicMaterial`, donc pas besoin de lumières.
+
+{{{example url="../threejs-textured-cube.html" }}}
+
+## <a name="six"></a> 6 textures, une pour chaque face d'un cube
+
+Que diriez-vous de 6 textures, une sur chaque face d'un cube ?
+
+<div class="threejs_center">
+ <div>
+ <img src="../resources/images/flower-1.jpg" style="width: 100px;" class="border" >
+ <img src="../resources/images/flower-2.jpg" style="width: 100px;" class="border" >
+ <img src="../resources/images/flower-3.jpg" style="width: 100px;" class="border" >
+ </div>
+ <div>
+ <img src="../resources/images/flower-4.jpg" style="width: 100px;" class="border" >
+ <img src="../resources/images/flower-5.jpg" style="width: 100px;" class="border" >
+ <img src="../resources/images/flower-6.jpg" style="width: 100px;" class="border" >
+ </div>
+</div>
+
+Fabriquons juste 6 materiaux et passons-les sous forme de tableau lors de la création de la `Mesh`
+
+```js
+const loader = new THREE.TextureLoader();
+
+-const material = new THREE.MeshBasicMaterial({
+- map: loader.load('resources/images/wall.jpg'),
+-});
++const materials = [
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-1.jpg')}),
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-2.jpg')}),
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-3.jpg')}),
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-4.jpg')}),
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-5.jpg')}),
++ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-6.jpg')}),
++];
+-const cube = new THREE.Mesh(geometry, material);
++const cube = new THREE.Mesh(geometry, materials);
+```
+
+Ça marche !
+
+{{{example url="../threejs-textured-cube-6-textures.html" }}}
+
+Il convient de noter, cependant, que tous les types de géométries ne peuvent supporter la prise en charge de plusieurs matériaux. `BoxGeometry` ne peut utiliser que 6 materiaux, un pour chaque face.
+`ConeGeometry`, seulement 2, un pour la base et un pour le cône.
+`CylinderGeometry` peut recevoir 3 materiaux pour le bas, le haut et le côté.
+Dans les autres cas, vous devrez créer ou charger une géométrie personnalisée et/ou modifier les coordonnées de texture.
+
+Il est bien plus performant d'utiliser, comme dans bien d'autres moteurs 3D, un
+[atlas de texture](https://fr.wikipedia.org/wiki/Atlas_de_texture)
+si vous voulez utiliser plusieurs images sur une même géométrie. Un atlas de texture est l'endroit où vous placez plusieurs images dans une seule texture, puis utilisez les coordonnées de texture sur les sommets de votre géométrie pour sélectionner les parties d'une texture à utiliser sur chaque triangle de votre géométrie.
+
+Que sont les coordonnées de texture ? Ce sont des données ajoutées à chaque sommet d'un morceau de géométrie qui spécifient quelle partie de la texture correspond à ce sommet spécifique. Nous les examinerons lorsque nous commencerons à [créer une géométrie personnalisée](threejs-custom-buffergeometry.html).
+
+## <a name="loading"></a> Téléchargement de textures
+
+### <a name="easy"></a> La façon la plus simple
+
+La plupart du code de ce site utilise la méthode la plus simple pour charger les textures. Nous créons un `TextureLoader` puis appelons sa méthode de [`chargement`](TextureLoader.load).
+Cela renvoie un objet `Texture`.
+
+```js
+const texture = loader.load('resources/images/flower-1.jpg');
+```
+
+Il est important de noter qu'en utilisant cette méthode, notre texture sera transparente jusqu'à ce que l'image soit chargée de manière asynchrone par Three.js, auquel cas elle mettra à jour la texture avec l'image téléchargée.
+
+Le gros avantage, c'est que nous n'avons pas besoin d'attendre que la texture soit chargée pour que notre page s'affiche. C'est probablement correct pour un grand nombre de cas d'utilisation, mais si nous le voulons, nous pouvons demander à Three.js de nous dire quand le téléchargement de la texture est terminé.
+
+### <a name="wait1"></a> En attente du chargement d'une texture
+
+Pour attendre qu'une texture se charge, la méthode `load` du chargeur de texture prend une 'callback function' qui sera appelée lorsque la texture aura fini de se charger. Pour en revenir à notre meilleur exemple, nous pouvons attendre que la texture se charge avant de créer notre `Mesh` et de l'ajouter à une scène comme celle-ci
+
+```js
+const loader = new THREE.TextureLoader();
+loader.load('resources/images/wall.jpg', (texture) => {
+ const material = new THREE.MeshBasicMaterial({
+ map: texture,
+ });
+ const cube = new THREE.Mesh(geometry, material);
+ scene.add(cube);
+ cubes.push(cube); // add to our list of cubes to rotate
+});
+```
+
+À moins de vider le cache de votre navigateur et d'avoir une connexion lente, il est peu probable que vous voyiez la différence, mais soyez assuré qu'il attend le chargement de la texture.
+
+{{{example url="../threejs-textured-cube-wait-for-texture.html" }}}
+
+### <a name="waitmany"></a> En attente du chargement de plusieurs textures
+
+Pour attendre que toutes les textures soient chargées, vous pouvez utiliser un `LoadingManager`. Créez-en un et transmettez-le à `TextureLoader`, puis définissez sa propriété [`onLoad`](LoadingManager.onLoad) avec une 'callback function'.
+
+```js
++const loadManager = new THREE.LoadingManager();
+*const loader = new THREE.TextureLoader(loadManager);
+
+const materials = [
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-1.jpg')}),
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-2.jpg')}),
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-3.jpg')}),
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-4.jpg')}),
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-5.jpg')}),
+ new THREE.MeshBasicMaterial({map: loader.load('resources/images/flower-6.jpg')}),
+];
+
++loadManager.onLoad = () => {
++ const cube = new THREE.Mesh(geometry, materials);
++ scene.add(cube);
++ cubes.push(cube); // ajouter à la liste des cubes
++};
+```
+
+Le `LoadingManager` a également une propriété [`onProgress`](LoadingManager.onProgress) que nous pouvons définir sur une autre 'callback' pour afficher un indicateur de progression.
+
+Ajoutons d'abord une barre de progression en HTML
+
+```html
+<body>
+ <canvas id="c"></canvas>
++ <div id="loading">
++ <div class="progress"><div class="progressbar"></div></div>
++ </div>
+</body>
+```
+
+et un peu de CSS
+
+```css
+#loading {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+}
+#loading .progress {
+ margin: 1.5em;
+ border: 1px solid white;
+ width: 50vw;
+}
+#loading .progressbar {
+ margin: 2px;
+ background: white;
+ height: 1em;
+ transform-origin: top left;
+ transform: scaleX(0);
+}
+```
+
+Ensuite, dans le code, nous mettrons à jour la `progressbar` dans la 'callback function' `onProgress`. Elle est appelée avec l'URL du dernier élément chargé, le nombre d'éléments chargés jusqu'à présent et le nombre total d'éléments chargés.
+
+```js
++const loadingElem = document.querySelector('#loading');
++const progressBarElem = loadingElem.querySelector('.progressbar');
+
+loadManager.onLoad = () => {
++ loadingElem.style.display = 'none';
+ const cube = new THREE.Mesh(geometry, materials);
+ scene.add(cube);
+ cubes.push(cube); // ajouter à la liste des cubes
+};
+
++loadManager.onProgress = (urlOfLastItemLoaded, itemsLoaded, itemsTotal) => {
++ const progress = itemsLoaded / itemsTotal;
++ progressBarElem.style.transform = `scaleX(${progress})`;
++};
+```
+
+À moins que vous ne vidiez votre cache et que votre connexion soit lente, vous ne verrez peut-être pas la barre de chargement.
+
+{{{example url="../threejs-textured-cube-wait-for-all-textures.html" }}}
+
+## <a name="cors"></a> Chargement de textures d'autres origines
+
+Pour utiliser des images d'autres serveurs, ces serveurs doivent envoyer les en-têtes corrects. Si ce n'est pas le cas, vous ne pouvez pas utiliser les images dans Three.js et vous obtiendrez une erreur. Si vous utilisez un serveur distant, assurez-vous qu'il envoie [les bons en-têtes](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). Sinon, vous ne pourrez pas utiliser les images provenant de ce serveur.
+
+Par exemple [imgur](https://imgur.com), [flickr](https://flickr.com), et
+[github](https://github.com) envoient des en-têtes vous permettant d'utiliser des images hébergées sur leurs serveurs avec Three.js. La plupart des autres sites web ne le font pas.
+
+## <a name="memory"></a> Utilisation de la mémoire
+
+Les textures sont souvent la partie d'une application Three.js qui utilise le plus de mémoire. Il est important de comprendre qu'en *général*, textures prennent `width * height * 4 * 1.33` octets de mémoire.
+
+Remarquez que cela ne dit rien sur la compression. Je peux créer une image .jpg et régler sa compression à un niveau très élevé. Par exemple, disons que je souhaite créé une maison. A l'intérieur de la maison il y a une table et je décide de mettre cette texture de bois sur la surface supérieure de la table
+
+<div class="threejs_center"><img class="border" src="resources/images/compressed-but-large-wood-texture.jpg" align="center" style="width: 300px"></div>
+
+Cette image ne pèse que 157ko, elle sera donc téléchargée relativement vite mais [sa taill est en réalité de 3024 x 3761 pixels](resources/images/compressed-but-large-wood-texture.jpg).
+En suivant l'équation ci-dessous
+
+ 3024 * 3761 * 4 * 1.33 = 60505764.5
+
+Cette image prendra **60 MEGA de MEMOIRE!** dans Three.js.
+Encore quelques textures comme celle-la et vous serez à court de mémoire.
+
+J'en parle car il est important de savoir que l'utilisation de textures a un coût caché. Pour que Three.js utilise la texture, il doit la transmettre au GPU et le GPU *en général* nécessite que les données de texture soient décompressées.
+
+La morale de l'histoire, c'est d'utiliser des textures de petite taille, pas seulement petite en taille de fichier. Petit en taille de fichier = rapide à télécharger. Petit en dimensions = prend moins de mémoire. Quelle est la bonne taille ? Aussi petite que possible et toujours aussi belle que nécessaire.
+
+## <a name="format"></a> JPG ou PNG
+
+C'est à peu près la même chose qu'en HTML, en ce sens que les JPG ont une compression avec perte, les PNG ont une compression sans perte, donc les PNG sont généralement plus lents à télécharger. Mais, les PNG prennent en charge la transparence. Les PNG sont aussi probablement le format approprié pour les données non-image comme les normal maps, et d'autres types de map non-image que nous verrons plus tard.
+
+Il est important de se rappeler qu'un JPG n'utilise pas moins de mémoire qu'un PNG en WebGL. Voir au ci-dessus.
+
+## <a name="filtering-and-mips"></a> Filtrage et Mips
+
+Appliquons cette texture 16x16
+
+<div class="threejs_center"><img src="resources/images/mip-low-res-enlarged.png" class="nobg" align="center"></div>
+
+sur un cube
+
+<div class="spread"><div data-diagram="filterCube"></div></div>
+
+Rétrécissons-le au max
+
+<div class="spread"><div data-diagram="filterCubeSmall"></div></div>
+
+Hmmm, je suppose que c'est trop difficile à voir. Agrandissons-le un peu
+
+<div class="spread"><div data-diagram="filterCubeSmallLowRes"></div></div>
+
+Comment le GPU sait-il quelles couleurs créer pour chaque pixel qu'il dessine pour le petit cube ? Et si le cube était si petit qu'il ne faisait que 1 ou 2 pixels ?
+
+C'est à cela que sert le filtrage.
+
+S'il s'agissait de Photoshop, il ferait la moyenne de presque tous les pixels ensemble pour déterminer la couleur de ces 1 ou 2 pixels. Ce serait une opération très lente. Les GPU résolvent ce problème à l'aide de mipmaps.
+
+Le MIP mapping consiste à envoyer au processeur graphique (GPU) des échantillons de texture de résolutions décroissantes qui seront utilisés à la place de la texture originale, en fonction de la distance du point de vue à l'objet texturé et du niveau de détails nécessaire. Pour l'image précédente seront produites les mêmes images avec des résolutions inférieure jusqu'à obtenir 1 x 1 pixel.
+
+<div class="threejs_center"><img src="resources/images/mipmap-low-res-enlarged.png" class="nobg" align="center"></div>
+
+Désormais, lorsque le cube est dessiné si petit qu'il ne fait que 1 ou 2 pixels de large, le GPU peut choisir d'utiliser uniquement le plus petit ou le plus petit niveau de mip pour décider de la couleur du petit cube.
+
+Dans Three.js, vous pouvez choisir ce qui se passe à la fois lorsque la texture est dessinée plus grande que sa taille d'origine et ce qui se passe lorsqu'elle est dessinée plus petite que sa taille d'origine.
+
+Pour définir le filtre lorsque la texture est dessinée plus grande que sa taille d'origine, définissez la propriété [`texture.magFilter`](Texture.magFilter) sur `THREE.NearestFilter` ou
+ `THREE.LinearFilter`. `NearestFilter` signifie simplement choisir le pixel le plus proche dans la texture d'origine. Avec une texture basse résolution, cela vous donne un look très pixelisé comme Minecraft.
+
+`LinearFilter` signifie choisir les 4 pixels de la texture qui sont les plus proches de l'endroit où nous devrions choisir une couleur et les mélanger dans les proportions appropriées par rapport à la distance entre le point réel et chacun des 4 pixels.
+
+<div class="spread">
+ <div>
+ <div data-diagram="filterCubeMagNearest" style="height: 250px;"></div>
+ <div class="code">Nearest</div>
+ </div>
+ <div>
+ <div data-diagram="filterCubeMagLinear" style="height: 250px;"></div>
+ <div class="code">Linear</div>
+ </div>
+</div>
+
+Pour définir le filtre lorsque la texture est dessinée plus petite que sa taille d'origine, définissez la propriété [`texture.minFilter`](Texture.minFilter) sur l'une des 6 valeurs :
+
+* `THREE.NearestFilter`
+
+ comme ci-dessus, choisissez le pixel le plus proche dans la texture
+
+* `THREE.LinearFilter`
+
+ comme ci-dessus, choisissez 4 pixels dans la texture et mélangez-les
+
+* `THREE.NearestMipmapNearestFilter`
+
+ choisissez le mip approprié puis choisissez un pixe
+
+* `THREE.NearestMipmapLinearFilter`
+
+ choisissez 2 mips, choisissez un pixel de chacun, mélangez les 2 pixels
+
+* `THREE.LinearMipmapNearestFilter`
+
+ choisissez le mip approprié puis choisissez 4 pixels et mélangez-les
+
+* `THREE.LinearMipmapLinearFilter`
+
+ choisissez 2 mips, choisissez 4 pixels de chacun et mélangez les 8 en 1 pixel
+
+Voici un exemple montrant les 6 paramètres
+
+<div class="spread">
+ <div data-diagram="filterModes" style="
+ height: 450px;
+ position: relative;
+ ">
+ <div style="
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ ">
+ <div style="
+ background: rgba(255,0,0,.8);
+ color: white;
+ padding: .5em;
+ margin: 1em;
+ font-size: small;
+ border-radius: .5em;
+ line-height: 1.2;
+ user-select: none;"
+ >click to<br/>change<br/>texture</div>
+ </div>
+ <div class="filter-caption" style="left: 0.5em; top: 0.5em;">nearest</div>
+ <div class="filter-caption" style="width: 100%; text-align: center; top: 0.5em;">linear</div>
+ <div class="filter-caption" style="right: 0.5em; text-align: right; top: 0.5em;">nearest<br/>mipmap<br/>nearest</div>
+ <div class="filter-caption" style="left: 0.5em; text-align: left; bottom: 0.5em;">nearest<br/>mipmap<br/>linear</div>
+ <div class="filter-caption" style="width: 100%; text-align: center; bottom: 0.5em;">linear<br/>mipmap<br/>nearest</div>
+ <div class="filter-caption" style="right: 0.5em; text-align: right; bottom: 0.5em;">linear<br/>mipmap<br/>linear</div>
+ </div>
+</div>
+
+Une chose à noter est que la texture en haut/gauche et la haut/milieu utilisent NearestFilter et LinearFilter et pas les mips. À cause de cela, ils scintillent au loin car le GPU sélectionne les pixels de la texture d'origine. Sur la gauche, un seul pixel est choisi et au milieu, 4 sont choisis et mélangés, mais il ne suffit pas de proposer une bonne couleur représentative. Les 4 autres bandes font mieux avec le bas à droite, LinearMipmapLinearFilter étant le meilleur.
+
+Si vous cliquez sur l'image ci-dessus, elle basculera entre la texture que nous avons utilisée ci-dessus et une texture où chaque niveau de mip est d'une couleur différente.
+
+<div class="threejs_center">
+ <div data-texture-diagram="differentColoredMips"></div>
+</div>
+
+Cela clarifie les choses. Vous pouvez voir en haut à gauche et en haut au milieu que le premier mip est utilisé au loin. En haut à droite et en bas au milieu, vous pouvez clairement voir où un MIP différent est utilisé.
+
+En revenant à la texture d'origine, vous pouvez voir que celle en bas à droite est la plus douce et la plus haute qualité. Vous pourriez vous demander pourquoi ne pas toujours utiliser ce mode. La raison la plus évidente, c'est que parfois vous voulez que les choses soient pixelisées pour un look rétro ou pour une autre raison. La deuxième raison la plus courante, c' est que lire 8 pixels et les mélanger est plus lent que lire 1 pixel et mélanger. Bien qu'il soit peu probable qu'une seule texture fasse la différence entre rapide et lente à mesure que nous progressons dans ces articles, nous finirons par avoir des matériaux qui utilisent 4 ou 5 textures à la fois. 4 textures * 8 pixels par texture se transforment 32 pixels pour chaque pixel rendu. Cela peut être particulièrement important à considérer sur les appareils mobiles.
+
+## <a name="uvmanipulation"></a> Répétition, décalage, rotation, emballage d'une texture
+
+Les textures ont des paramètres pour la répétition, le décalage et la rotation d'une texture.
+
+Par défaut, les textures de three.js ne se répètent pas. Pour définir si une texture se répète ou non, il existe 2 propriétés, [`wrapS`](Texture.wrapS) pour un habillage horizontal et [`wrapT`](Texture.wrapT) pour un habillage vertical.
+
+Ils peuvent être définis sur l'un des éléments suivants :
+
+* `THREE.ClampToEdgeWrapping`
+
+ le dernier pixel de chaque bord est répété indéfiniment
+
+* `THREE.RepeatWrapping`
+
+ la texture est répétée
+
+* `THREE.MirroredRepeatWrapping`
+
+ la texture est reflétée et répétée
+
+Par exemple pour activer le wrapping dans les deux sens :
+
+```js
+someTexture.wrapS = THREE.RepeatWrapping;
+someTexture.wrapT = THREE.RepeatWrapping;
+```
+
+La répétition est définie avec la propriété [repeat].
+
+```js
+const timesToRepeatHorizontally = 4;
+const timesToRepeatVertically = 2;
+someTexture.repeat.set(timesToRepeatHorizontally, timesToRepeatVertically);
+```
+
+Le décalage de la texture peut être effectué en définissant la propriété `offset`. Les textures sont décalées avec des unités où 1 unité = 1 taille de texture. En d'autres termes 0 = aucun décalage et 1 = décalage d'une quantité de texture complète.
+
+```js
+const xOffset = .5; // décalage de la moitié de la texture
+const yOffset = .25; // décalage d'un quart
+someTexture.offset.set(xOffset, yOffset);
+```
+
+La rotation de la texture peut être définie en définissant la propriété `rotation` en radians ainsi que la propriété `center` pour choisir le centre de rotation. La valeur par défaut est 0,0 qui tourne à partir du coin inférieur gauche. Comme le décalage, ces unités ont une taille de texture, donc les régler sur `.5, .5` tournerait autour du centre de la texture.
+
+```js
+someTexture.center.set(.5, .5);
+someTexture.rotation = THREE.MathUtils.degToRad(45);
+```
+
+Modifions l'échantillon supérieur ci-dessus pour jouer avec ces valeurs.
+
+Tout d'abord, nous allons garder une référence à la texture afin que nous puissions la manipuler
+
+```js
++const texture = loader.load('resources/images/wall.jpg');
+const material = new THREE.MeshBasicMaterial({
+- map: loader.load('resources/images/wall.jpg');
++ map: texture,
+});
+```
+
+Ensuite, utilisons [dat.GUI](https://github.com/dataarts/dat.gui) pour fournir une interface simple.
+
+```js
+import {GUI} from '../3rdparty/dat.gui.module.js';
+```
+
+Comme nous l'avons fait dans les exemples précédents avec dat.GUI, nous utiliserons une classe simple pour donner à dat.GUI un objet qu'il peut manipuler en degrés mais qu'il définira en radians.
+
+```js
+class DegRadHelper {
+ constructor(obj, prop) {
+ this.obj = obj;
+ this.prop = prop;
+ }
+ get value() {
+ return THREE.MathUtils.radToDeg(this.obj[this.prop]);
+ }
+ set value(v) {
+ this.obj[this.prop] = THREE.MathUtils.degToRad(v);
+ }
+}
+```
+
+Nous avons également besoin d'une classe qui convertira une chaîne telle que `"123"` en un nombre tel que 123, car Three.js nécessite des nombres pour les paramètres d'énumération tels que `wrapS` et `wrapT`, mais dat.GUI n'utilise que des chaînes pour les énumérations.
+
+```js
+class StringToNumberHelper {
+ constructor(obj, prop) {
+ this.obj = obj;
+ this.prop = prop;
+ }
+ get value() {
+ return this.obj[this.prop];
+ }
+ set value(v) {
+ this.obj[this.prop] = parseFloat(v);
+ }
+}
+```
+
+En utilisant ces classes, nous pouvons configurer une interface graphique simple pour les paramètres ci-dessus
+
+```js
+const wrapModes = {
+ 'ClampToEdgeWrapping': THREE.ClampToEdgeWrapping,
+ 'RepeatWrapping': THREE.RepeatWrapping,
+ 'MirroredRepeatWrapping': THREE.MirroredRepeatWrapping,
+};
+
+function updateTexture() {
+ texture.needsUpdate = true;
+}
+
+const gui = new GUI();
+gui.add(new StringToNumberHelper(texture, 'wrapS'), 'value', wrapModes)
+ .name('texture.wrapS')
+ .onChange(updateTexture);
+gui.add(new StringToNumberHelper(texture, 'wrapT'), 'value', wrapModes)
+ .name('texture.wrapT')
+ .onChange(updateTexture);
+gui.add(texture.repeat, 'x', 0, 5, .01).name('texture.repeat.x');
+gui.add(texture.repeat, 'y', 0, 5, .01).name('texture.repeat.y');
+gui.add(texture.offset, 'x', -2, 2, .01).name('texture.offset.x');
+gui.add(texture.offset, 'y', -2, 2, .01).name('texture.offset.y');
+gui.add(texture.center, 'x', -.5, 1.5, .01).name('texture.center.x');
+gui.add(texture.center, 'y', -.5, 1.5, .01).name('texture.center.y');
+gui.add(new DegRadHelper(texture, 'rotation'), 'value', -360, 360)
+ .name('texture.rotation');
+```
+
+La dernière chose à noter à propos de l'exemple est que si vous modifiez `wrapS` ou `wrapT` sur la texture, vous devez également définir [`texture.needsUpdate`](Texture.needsUpdate)
+afin que three.js sache appliquer ces paramètres. Les autres paramètres sont automatiquement appliqués.
+
+{{{example url="../threejs-textured-cube-adjust.html" }}}
+
+Ce n'est qu'une étape dans le sujet des textures. À un moment donné, nous passerons en revue les coordonnées de texture ainsi que 9 autres types de textures pouvant être appliquées aux matériaux.
+
+Pour le moment, passons aux [lumières](threejs-lights.html).
+
+<!--
+alpha
+ao
+env
+light
+specular
+bumpmap ?
+normalmap ?
+metalness
+roughness
+-->
+
+<link rel="stylesheet" href="resources/threejs-textures.css">
+<script type="module" src="resources/threejs-textures.js"></script> | false |
Other | mrdoob | three.js | 2e640a4d6fa5d426f76cd0deba8106c8249bfa0e.json | add French translation | threejs/lessons/fr/threejs-materials.md | @@ -0,0 +1,262 @@
+Title: Les Materials de Three.js
+Description: Les Materials dans Three.js
+TOC: Materials
+
+Cet article fait partie d'une série consacrée à Three.js.
+Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
+Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
+
+Three.js fournit plusieurs types de matériaux.
+Ils définissent comment les objets apparaîtront dans la scène.
+Les matériaux que vous utilisez dépendent vraiment de ce que vous essayez d'accomplir.
+
+Il existe 2 façons de définir la plupart des propriétés des matériaux. A la création, comme nous l'avons déjà vu.
+
+```js
+const material = new THREE.MeshPhongMaterial({
+ color: 0xFF0000, // red (can also use a CSS color string here)
+ flatShading: true,
+});
+```
+
+Ou après la création.
+
+```js
+const material = new THREE.MeshPhongMaterial();
+material.color.setHSL(0, 1, .5); // red
+material.flatShading = true;
+```
+
+notez qu'il y a plusieurs façons de paramétrer la propriété `THREE.Color`.
+
+```js
+material.color.set(0x00FFFF); // same as CSS's #RRGGBB style
+material.color.set(cssString); // any CSS color, eg 'purple', '#F32',
+ // 'rgb(255, 127, 64)',
+ // 'hsl(180, 50%, 25%)'
+material.color.set(someColor) // some other THREE.Color
+material.color.setHSL(h, s, l) // where h, s, and l are 0 to 1
+material.color.setRGB(r, g, b) // where r, g, and b are 0 to 1
+```
+
+A la création, vous pouvez passer, soit un nombre héxadécimal ou une valeur entre guillemet comme en CSS.
+
+```js
+const m1 = new THREE.MeshBasicMaterial({color: 0xFF0000}); // rouge
+const m2 = new THREE.MeshBasicMaterial({color: 'red'}); // rouge
+const m3 = new THREE.MeshBasicMaterial({color: '#F00'}); // rouge
+const m4 = new THREE.MeshBasicMaterial({color: 'rgb(255,0,0)'}); // rouge
+const m5 = new THREE.MeshBasicMaterial({color: 'hsl(0,100%,50%)'); // rouge
+```
+
+Examinons l'ensemble des materials de Three.js
+
+Le `MeshBasicMaterial` n'est pas affecté par la lumière.
+Le `MeshLambertMaterial` calcul la lumière uniquement pour les sommets (vertices), par contre le `MeshPhongMaterial`, lui, calcule la lumière pour chaque pixel. Le `MeshPhongMaterial` prend en charge aussi les reflets spéculaires.
+
+<div class="spread">
+ <div>
+ <div data-diagram="MeshBasicMaterial" ></div>
+ <div class="code">Basic</div>
+ </div>
+ <div>
+ <div data-diagram="MeshLambertMaterial" ></div>
+ <div class="code">Lambert</div>
+ </div>
+ <div>
+ <div data-diagram="MeshPhongMaterial" ></div>
+ <div class="code">Phong</div>
+ </div>
+</div>
+<div class="spread">
+ <div>
+ <div data-diagram="MeshBasicMaterialLowPoly" ></div>
+ </div>
+ <div>
+ <div data-diagram="MeshLambertMaterialLowPoly" ></div>
+ </div>
+ <div>
+ <div data-diagram="MeshPhongMaterialLowPoly" ></div>
+ </div>
+</div>
+<div class="threejs_center code">modèles low-poly avec les mêmes materials</div>
+
+Le paramètre `shininess` du `MeshPhongMaterial` détermine la *brillance* de la surbrillance spéculaire. La valeur par défaut est 30.
+
+<div class="spread">
+ <div>
+ <div data-diagram="MeshPhongMaterialShininess0" ></div>
+ <div class="code">shininess: 0</div>
+ </div>
+ <div>
+ <div data-diagram="MeshPhongMaterialShininess30" ></div>
+ <div class="code">shininess: 30</div>
+ </div>
+ <div>
+ <div data-diagram="MeshPhongMaterialShininess150" ></div>
+ <div class="code">shininess: 150</div>
+ </div>
+</div>
+
+Notez que définir la propriété `émissive` sur une couleur sur un
+`MeshLambertMaterial` ou un `MeshPhongMaterial` et régler la `couleur` sur noir
+(et `shininess` à 0 pour phong) finit par ressembler au `MeshBasicMaterial`.
+
+<div class="spread">
+ <div>
+ <div data-diagram="MeshBasicMaterialCompare" ></div>
+ <div class="code">
+ <div>Basic</div>
+ <div>color: 'purple'</div>
+ </div>
+ </div>
+ <div>
+ <div data-diagram="MeshLambertMaterialCompare" ></div>
+ <div class="code">
+ <div>Lambert</div>
+ <div>color: 'black'</div>
+ <div>emissive: 'purple'</div>
+ </div>
+ </div>
+ <div>
+ <div data-diagram="MeshPhongMaterialCompare" ></div>
+ <div class="code">
+ <div>Phong</div>
+ <div>color: 'black'</div>
+ <div>emissive: 'purple'</div>
+ <div>shininess: 0</div>
+ </div>
+ </div>
+</div>
+
+Pourquoi avoir les 3, si `MeshPhongMaterial` peut faire les mêmes choses que `MeshBasicMaterial` et `MeshLambertMaterial` ? La raison est simple. Le materials le plus sophistiqué nécessite aussi plus de puissance de la part du GPU. Sur un GPU plus lent comme par exemple sur un téléphone mobile, vous souhaiterez peut-être réduire la puissance du GPU en utilisant l'un des materials les moins complexes. Il s'ensuit également que si vous n'avez pas besoin des fonctionnalités supplémentaires, utilisez le materials le plus simple. Si vous n'avez pas besoin de l'éclairage et de la surbrillance spéculaire, utilisez le `MeshBasicMaterial`.
+
+Le `MeshToonMaterial` est similaire au `MeshPhongMaterial`
+avec une grande différence. Plutôt que d'ombrager en douceur, il utilise une carte de dégradé (une texture X par 1) pour décider comment ombrager. La valeur par défaut utilise une carte de dégradé dont la luminosité est de 70 % pour les premiers 70 % et 100 % après, mais vous pouvez fournir votre propre carte de dégradé. Cela finit par donner un look 2 tons qui ressemble à un dessin animé.
+
+<div class="spread">
+ <div data-diagram="MeshToonMaterial"></div>
+</div>
+
+Ensuite, il y a 2 materials de *rendu physique*. Le rendu physique est souvent abrégé PBR.
+
+Les materials ci-dessus utilisent des mathématiques simples pour créer des materials qui semblent 3D, mais ne réagissent pas comme dans le monde réel. Les 2 materials PBR utilisent des mathématiques beaucoup plus complexes pour se rapprocher de ce qui se passe réellement dans le monde réel.
+
+Le premier est `MeshStandardMaterial`. La plus grande différence entre `MeshPhongMaterial` et `MeshStandardMaterial` est qu'il utilise des paramètres différents.
+`MeshPhongMaterial` a un paramètre `shininess`. `MeshStandardMaterial` a 2 paramètres `roughness` (rugosité) et `metalness` (metalique).
+
+Basiquement, [`roughness`](MeshStandardMaterial.roughness) est l'opposé de `shininess`.
+Quelque chose qui a une rugosité élevée, comme une balle de baseball, n'a pas de reflets durs alors que quelque chose qui n'est pas rugueux, comme une boule de billard, est très brillant. La rugosité va de 0 à 1.
+
+L'autre paramètre, [`metalness`](MeshStandardMaterial.metalness), indique
+à quel point le matériau est métallique. Les métaux se comportent différemment des non-métaux. 0
+pour le non-métal et 1 pour le métal.
+
+Voici quelques exemples de `MeshStandardMaterial` avec une `roughness` allant de 0 à 1
+sur la diagonale et une `metalness` allant de 0 à 1 en descendant.
+
+<div data-diagram="MeshStandardMaterial" style="min-height: 400px"></div>
+
+Le `MeshPhysicalMaterial` est le même que le `MeshStandardMaterial` mais il ajoute un paramètre `clearcoat` (vernis) qui va de 0 à 1 pour savoir quelle couche de brillance appliquée. Et un paramètre `clearCoatRoughness` qui spécifie à quel point la couche de brillance est rugueuse.
+
+Voici la même grille que ci-dessusmais avec les paramètres `clearcoat` et `clearCoatRoughness` en plus.
+
+<div data-diagram="MeshPhysicalMaterial" style="min-height: 400px"></div>
+
+Les divers matériaux standard progressent du plus rapide au plus lent
+`MeshBasicMaterial` ➡ `MeshLambertMaterial` ➡ `MeshPhongMaterial` ➡
+`MeshStandardMaterial` ➡ `MeshPhysicalMaterial`. Les matériaux les plus lents peuvent créer des scènes plus réalistes, mais vous devrez peut-être concevoir votre code pour utiliser les matériaux les plus rapides sur des machines mobiles ou de faible puissance.
+
+Il existe 3 matériaux qui ont des utilisations spéciales. `ShadowMaterial`
+est utilisé pour obtenir les données créées à partir des ombres. Nous n'avons pas encore couvert les ombres. Lorsque nous le ferons, nous utiliserons ce materiau pour jeter un œil à ce qui se passe dans les coulisses.
+
+The `MeshDepthMaterial` resttitue la profondeur de chaque pixel où les pixels
+négatifs [`near`](PerspectiveCamera.near) sont à 0 et les négatifs [`far`](PerspectiveCamera.far) sont à 1.
+Certains effets spéciaux peuvent utiliser ces données que nous aborderons plus tard.
+
+<div class="spread">
+ <div>
+ <div data-diagram="MeshDepthMaterial"></div>
+ </div>
+</div>
+
+Le `MeshNormalMaterial` vous montrera les *normals* de la geéometrie.
+Les *Normals* sont la direction d'un triangle ou d'un pixel particulier.
+`MeshNormalMaterial` dessine les normales de l'espace de vue (les normales par rapport à la caméra).
+
+<span style="background: red;" class="color">x rouge</span>,
+<span style="background: green;" class="dark-color">y est vert</span>, et
+<span style="background: blue;" class="dark-color">z est bleu</span> donc les choses tournés vers la droite seront <span style="background: #FF7F7F;" class="color">roses</span>,
+ceux vers la gauche seront <span style="background: #007F7F;" class="dark-color">aqua</span>,
+vers le haut <span style="background: #7FFF7F;" class="color">vert clair</span>,
+vers le bas <span style="background: #7F007F;" class="dark-color">violet</span>,
+et vers l'écran <span style="background: #7F7FFF;" class="color">lavande</span>.
+
+<div class="spread">
+ <div>
+ <div data-diagram="MeshNormalMaterial"></div>
+ </div>
+</div>
+
+`ShaderMaterial` permet de créer des matériaux personnalisés à l'aide du sytème de shader de Three.js. `RawShaderMaterial` permet de créer des shaders entièrement personnalisés sans l'aide de Three.js. Ces deux sujets sont vastes et seront traités plus tard.
+
+La plupart des matériaux partagent un ensemble de paramètres, tous définis par `Material`.
+[Voir la documentation](Material) pour chacun d'eux, mais passons en revue deux des propriétés les plus utilisées.
+
+[`flatShading`](Material.flatShading):
+si l'objet à l'air à facettes ou lisse. Par defaut = `false`.
+
+<div class="spread">
+ <div>
+ <div data-diagram="smoothShading"></div>
+ <div class="code">flatShading: false</div>
+ </div>
+ <div>
+ <div data-diagram="flatShading"></div>
+ <div class="code">flatShading: true</div>
+ </div>
+</div>
+
+[`side`](Material.side): quel côté montrer. La valeur par defaut est `THREE.FrontSide`.
+Les autres options sont `THREE.BackSide` et `THREE.DoubleSide` (des deux côtés).
+La plupart des objets 3D déssinés dans Three.js sont probablement des solides opaques, il n'est donc pas nécessaire de dessiner les faces arrières (c'est-à-dire les côtés tournés vers l'intérieur du solide). La raison la plus courante de définir le côté, est pour les plans et les objets non solides où il est courant de voir leurs faces arrières.
+
+Voici 6 plans dessinés avec `THREE.FrontSide` et `THREE.DoubleSide`.
+
+<div class="spread">
+ <div>
+ <div data-diagram="sideDefault" style="height: 250px;"></div>
+ <div class="code">side: THREE.FrontSide</div>
+ </div>
+ <div>
+ <div data-diagram="sideDouble" style="height: 250px;"></div>
+ <div class="code">side: THREE.DoubleSide</div>
+ </div>
+</div>
+
+Il y a vraiment beaucoup de choses à considérer avec les matériaux et il nous en reste encore beaucoup à faire. En particulier, nous avons principalement ignoré les textures qui ouvrent toute une série d'options. Avant de couvrir les textures, nous devons faire une pause et couvrir [la configuration de votre environnement de développement](threejs-setup.html)
+
+<div class="threejs_bottombar">
+<h3>material.needsUpdate</h3>
+<p>
+Ce sujet affecte rarement la plupart des applications Three.js, mais juste pour info...
+Three.js applique les paramètres de matériau lorsqu'un matériau est utilisé, où "utilisé" signifie "quelque chose est rendu qui utilise le matériau".
+Certains paramètres de matériau ne sont appliqués qu'une seule fois car leur modification nécessite beaucoup de travail de la part de Three.js.
+Dans ces cas, vous devez définir <code>material.needsUpdate = true</code> pour dire à Three.js d'appliquer vos modifications matérielles. Les paramètres les plus courants qui vous obligent à définir <code>needsUpdate</code> si vous modifiez les paramètres après avoir utilisé le matériau sont :
+</p>
+<ul>
+ <li><code>flatShading</code></li>
+ <li>ajouter ou supprimer une texture
+ <p>
+ Changer une texture est possible, mais si vous voulez passer de, aucune texture à l'utilisation d'une texture, ou l'inverse, vous devrez définir <code>needsUpdate = true</code>.
+ </p>
+ <p>Si vous souhaitez supprimer une texture, il est préférable de la remplacer par une texture blanche de 1 pixel de côté.</p>
+ </li>
+</ul>
+<p>Comme mentionné ci-dessus, la plupart des applications ne rencontrent jamais ces problèmes. La plupart des applications ne basculent pas entre l'ombrage plat et l'ombrage non plat. La plupart des applications utilisent également des textures ou une couleur unie pour un matériau donné, elles passent rarement de l'une à l'autre.
+</p>
+</div>
+
+<canvas id="c"></canvas>
+<script type="module" src="resources/threejs-materials.js"></script>
+ | false |
Other | mrdoob | three.js | 66495ff607512e0fd3e87a09af5f6be32e859185.json | add French translation | threejs/lessons/fr/threejs-scenegraph.md | @@ -1,12 +1,12 @@
-Title: Graphe de scène Three.js
-Description: What's a scene graph?
+Title: Graphique de scène de Three.js
+Description: Qu'est-ce qu'un graphique de scène ?
TOC: Scenegraph
Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
-Le coeurs de Three.js est sans aucun doute son graphique de scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
+Le coeurs de Three.js est sans aucun doute son graphique de scène. Un graphique de scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
<img src="resources/images/scenegraph-generic.svg" align="center">
| false |
Other | mrdoob | three.js | bf72b7a71c8578206217c150abb6973afbffd97c.json | add French translation | threejs/lessons/fr/threejs-scenegraph.md | @@ -6,7 +6,7 @@ Cet article fait partie d'une série consacrée à Three.js.
Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
-Le coeurs de Three.js est sans aucun doute son objet scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
+Le coeurs de Three.js est sans aucun doute son graphique de scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
<img src="resources/images/scenegraph-generic.svg" align="center">
@@ -176,31 +176,26 @@ objects.push(earthMesh);
+moonOrbit.add(moonMesh);
+objects.push(moonMesh);
```
-XXXXXXXXXXXXXXXX
-
-Again we added more invisible scene graph nodes. The first, an `Object3D` called `earthOrbit`
-and added both the `earthMesh` and the `moonOrbit` to it, also new. We then added the `moonMesh`
-to the `moonOrbit`. The new scene graph looks like this.
+Ajoutons à nouveau d'autres noeuds à notre scène. D'abord, un `Object3D` appelé `earthOrbit`
+ensuite ajoutons-lui un `earthMesh` et un `moonOrbit`. Finalement, ajoutons un `moonMesh`
+au `moonOrbit`. Notre scène devrait ressembler à ceci :
<img src="resources/images/scenegraph-sun-earth-moon.svg" align="center">
-and here's that
+et à ça :
{{{example url="../threejs-scenegraph-sun-earth-moon.html" }}}
-You can see the moon follows the spirograph pattern shown at the top
-of this article but we didn't have to manually compute it. We just
-setup our scene graph to do it for us.
+Vous pouvez voir que la lune suit le modèle de spirographe indiqué en haut de cet article, mais nous n'avons pas eu à le calculer manuellement. Nous venons de configurer notre graphe de scène pour le faire pour nous.
-It is often useful to draw something to visualize the nodes in the scene graph.
-Three.js has some helpful ummmm, helpers to ummm, ... help with this.
+Il est souvent utile de dessiner quelque chose pour visualiser les nœuds dans le graphe de scène.
+Three.js dispose pour cela de Helpers.
-One is called an `AxesHelper`. It draws 3 lines representing the local
+L'un d'entre eux s'appelle `AxesHelper`. Il dessine trois lignes représentant les axes
<span style="color:red">X</span>,
-<span style="color:green">Y</span>, and
-<span style="color:blue">Z</span> axes. Let's add one to every node we
-created.
+<span style="color:green">Y</span>, et
+<span style="color:blue">Z</span>. Ajoutons-en un à chacun de nos noeuds.
```js
// add an AxesHelper to each node
@@ -212,35 +207,20 @@ objects.forEach((node) => {
});
```
-On our case we want the axes to appear even though they are inside the spheres.
-To do this we set their material's `depthTest` to false which means they will
-not check to see if they are drawing behind something else. We also
-set their `renderOrder` to 1 (the default is 0) so that they get drawn after
-all the spheres. Otherwise a sphere might draw over them and cover them up.
+Dans notre cas, nous voulons que les axes apparaissent même s'ils sont à l'intérieur des sphères.
+Pour cela, nous définissons le `depthTest` de material à false, pour ne pas vérifier s'ils dessinent derrière quelque chose. Nous définissons également leur `renderOrder` sur 1 (la valeur par défaut est 0) afin qu'ils soient dessinés après toutes les sphères. Sinon, une sphère pourrait les recouvrir et les recouvrir.
{{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}}
-We can see the
-<span style="color:red">x (red)</span> and
-<span style="color:blue">z (blue)</span> axes. Since we are looking
-straight down and each of our objects is only rotating around its
-y axis we don't see much of the <span style="color:green">y (green)</span> axes.
+Vous pouvez voir les axes
+<span style="color:red">x (rouge)</span> et
+<span style="color:blue">z (bleu)</span>. Comme nous regardons vers le bas et que chacun de nos objets tourne autour de son axe y, nous ne voyons pas bien l'axe <span style="color:green">y (verte)</span>.
-It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the `sunMesh`
-and the `solarSystem` are at the same position. Similarly the `earthMesh` and
-`earthOrbit` are at the same position. Let's add some simple controls to allow us
-to turn them on/off for each node.
-While we're at it let's also add another helper called the `GridHelper`. It
-makes a 2D grid on the X,Z plane. By default the grid is 10x10 units.
+Il peut être difficile de voir certains d'entre eux car il y a 2 paires d'axes qui se chevauchent. Le `sunMesh` et le `solarSystem` sont tous les deux à la même position. De même, `earthMesh` et `earthOrbit` sont à la même position. Ajoutons quelques contrôles simples pour nous permettre de les activer/désactiver pour chaque nœud. Pendant que nous y sommes, ajoutons également un autre assistant appelé `GridHelper`. Il crée une grille 2D sur le plan X,Z. Par défaut, la grille est de 10x10 unités.
-We're also going to use [dat.GUI](https://github.com/dataarts/dat.gui) which is
-a UI library that is very popular with three.js projects. dat.GUI takes an
-object and a property name on that object and based on the type of the property
-automatically makes a UI to manipulate that property.
+Nous allons également utiliser [dat.GUI](https://github.com/dataarts/dat.gui), une librairie d'interface utilisateur très populaire pour les projets Three.js. dat.GUI prend un objet et un nom de propriété sur cet objet et, en fonction du type de la propriété, crée automatiquement une interface utilisateur pour manipuler cette propriété.
-We want to make both a `GridHelper` and an `AxesHelper` for each node. We need
-a label for each node so we'll get rid of the old loop and switch to calling
-some function to add the helpers for each node
+Nous voulons créer à la fois un `GridHelper` et un `AxesHelper` pour chaque nœud. Nous avons besoin d'un label pour chaque nœud, nous allons donc nous débarrasser de l'ancienne boucle et faire appel à une fonction pour ajouter les helpers pour chaque nœud.
```js
-// add an AxesHelper to each node
@@ -263,24 +243,14 @@ some function to add the helpers for each node
+makeAxisGrid(moonOrbit, 'moonOrbit');
+makeAxisGrid(moonMesh, 'moonMesh');
```
-
-`makeAxisGrid` makes an `AxisGridHelper` which is a class we'll create
-to make dat.GUI happy. Like it says above dat.GUI
-will automagically make a UI that manipulates the named property
-of some object. It will create a different UI depending on the type
-of property. We want it to create a checkbox so we need to specify
-a `bool` property. But, we want both the axes and the grid
-to appear/disappear based on a single property so we'll make a class
-that has a getter and setter for a property. That way we can let dat.GUI
-think it's manipulating a single property but internally we can set
-the visible property of both the `AxesHelper` and `GridHelper` for a node.
+`makeAxisGrid` crée un `AxisGridHelper` qui est une classe que nous allons créer pour rendre dat.GUI heureux. Comme il est dit ci-dessus, dat.GUI créera automatiquement une interface utilisateur qui manipule la propriété nommée d'un objet. Cela créera une interface utilisateur différente selon le type de propriété. Nous voulons qu'il crée une case à cocher, nous devons donc spécifier une propriété bool. Mais, nous voulons que les axes et la grille apparaissent/disparaissent en fonction d'une seule propriété, nous allons donc créer une classe qui a un getter et un setter pour une propriété. De cette façon, nous pouvons laisser dat.GUI penser qu'il manipule une seule propriété, mais en interne, nous pouvons définir la propriété visible de `AxesHelper` et `GridHelper` pour un nœud.
```js
-// Turns both axes and grid visible on/off
-// dat.GUI requires a property that returns a bool
-// to decide to make a checkbox so we make a setter
-// and getter for `visible` which we can tell dat.GUI
-// to look at.
+// Activer/désactiver les axes et la grille dat.GUI
+// nécessite une propriété qui renvoie un bool
+// pour décider de faire une case à cocher
+// afin que nous créions un setter et un getter pour `visible`
+// que nous pouvons dire à dat.GUI de regarder.
class AxisGridHelper {
constructor(node, units = 10) {
const axes = new THREE.AxesHelper();
@@ -308,57 +278,40 @@ class AxisGridHelper {
}
```
-One thing to notice is we set the `renderOrder` of the `AxesHelper`
-to 2 and for the `GridHelper` to 1 so that the axes get drawn after the grid.
-Otherwise the grid might overwrite the axes.
+Une chose à noter est que nous définissons le `renderOrder` de l'`AxesHelper` sur 2 et pour le `GridHelper` sur 1 afin que les axes soient dessinés après la grille. Sinon, la grille pourrait écraser les axes.
{{{example url="../threejs-scenegraph-sun-earth-moon-axes-grids.html" }}}
-Turn on the `solarSystem` and you'll see how the earth is exactly 10
-units out from the center just like we set above. You can see how the
-earth is in the *local space* of the `solarSystem`. Similarly if you
-turn on the `earthOrbit` you'll see how the moon is exactly 2 units
-from the center of the *local space* of the `earthOrbit`.
+Cliquez sur `solarSystem` et vous verrez que la terre est exactement à 10 unités du centre, comme nous l'avons défini ci-dessus. Vous pouvez voir que la terre est dans l'espace local du `solarSystem`. De même, si vous cliquez sur `earthOrbit`, vous verrez que la lune est exactement à 2 unités du centre de *l'espace local* de `earthOrbit`.
-A few more examples of scene graphs. An automobile in a simple game world might have a scene graph like this
+Un autre exemple de scène. Une automobile dans un jeu simple pourrait avoir un graphique de scène comme celui-ci
<img src="resources/images/scenegraph-car.svg" align="center">
-If you move the car's body all the wheels will move with it. If you wanted the body
-to bounce separate from the wheels you might parent the body and the wheels to a "frame" node
-that represents the car's frame.
+Si vous déplacez la carrosserie de la voiture, toutes les roues bougeront avec elle. Si vous vouliez que le corps rebondisse séparément des roues, vous pouvez lier le corps et les roues à un nœud "cadre" qui représente le cadre de la voiture.
-Another example is a human in a game world.
+Un autre exemple avec un humain dans un jeu vidéo.
<img src="resources/images/scenegraph-human.svg" align="center">
-You can see the scene graph gets pretty complex for a human. In fact
-that scene graph above is simplified. For example you might extend it
-to cover every finger (at least another 28 nodes) and every toe
-(yet another 28 nodes) plus ones for the face and jaw, the eyes and maybe more.
+Vous pouvez voir que le graphique de la scène devient assez complexe pour un humain. En fait, le graphe ci-dessus est simplifié. Par exemple, vous pouvez l'étendre pour couvrir chaque doigt (au moins 28 autres nœuds) et chaque orteil (encore 28 nœuds) plus ceux pour le visage et la mâchoire, les yeux et peut-être plus.
+
+Faisons un graphe semi-complexe. On va faire un char. Il aura 6 roues et une tourelle. Il pourra suivre un chemin. Il y aura une sphère qui se déplacera et le char ciblera la sphère.
Let's make one semi-complex scene graph. We'll make a tank. The tank will have
6 wheels and a turret. The tank will follow a path. There will be a sphere that
moves around and the tank will target the sphere.
-Here's the scene graph. The meshes are colored in green, the `Object3D`s in blue,
-the lights in gold, and the cameras in purple. One camera has not been added
-to the scene graph.
+Voici le graphique de la scène. Les maillages sont colorés en vert, les `Object3D` en bleu, les lumières en or et les caméras en violet. Une caméra n'a pas été ajoutée au graphique de la scène.
<div class="threejs_center"><img src="resources/images/scenegraph-tank.svg" style="width: 800px;"></div>
-Look in the code to see the setup of all of these nodes.
+Regardez dans le code pour voir la configuration de tous ces nœuds.
-For the target, the thing the tank is aiming at, there is a `targetOrbit`
-(`Object3D`) which just rotates similar to the `earthOrbit` above. A
-`targetElevation` (`Object3D`) which is a child of the `targetOrbit` provides an
-offset from the `targetOrbit` and a base elevation. Childed to that is another
-`Object3D` called `targetBob` which just bobs up and down relative to the
-`targetElevation`. Finally there's the `targetMesh` which is just a cube we
-rotate and change its colors
+Pour la cible, la chose que le char vise, il y a une `targetOrbit` (Object3D) qui tourne juste de la même manière que la `earthOrbit` ci-dessus. Une `targetElevation` (Object3D) qui est un enfant de `targetOrbit` fournit un décalage par rapport à `targetOrbit` et une élévation de base. Un autre `Object3D` appelé `targetBob` qui monte et descend par rapport à la `targetElevation`. Enfin, il y a le `targetMesh` qui est juste un cube que nous faisons pivoter et changeons ses couleurs.
```js
-// move target
+// mettre en mouvement la cible
targetOrbit.rotation.y = time * .27;
targetBob.position.y = Math.sin(time * 2) * 4;
targetMesh.rotation.x = time * 7;
@@ -367,71 +320,59 @@ targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25);
targetMaterial.color.setHSL(time * 10 % 1, 1, .25);
```
-For the tank there's an `Object3D` called `tank` which is used to move everything
-below it around. The code uses a `SplineCurve` which it can ask for positions
-along that curve. 0.0 is the start of the curve. 1.0 is the end of the curve. It
-asks for the current position where it puts the tank. It then asks for a
-position slightly further down the curve and uses that to point the tank in that
-direction using `Object3D.lookAt`.
+Pour le char, il y a un `Object3D` appelé `tank` qui est utilisé pour déplacer tout ce qui se trouve en dessous. Le code utilise une `SplineCurve` à laquelle il peut demander des positions le long de cette courbe. 0.0 est le début de la courbe. 1,0 est la fin de la courbe. Il demande la position actuelle où il met le réservoir. Il demande ensuite une position légèrement plus bas dans la courbe et l'utilise pour pointer le réservoir dans cette direction à l'aide de `Object3D.lookAt`.
```js
const tankPosition = new THREE.Vector2();
const tankTarget = new THREE.Vector2();
...
-// move tank
+// mettre en mouvement le char
const tankTime = time * .05;
curve.getPointAt(tankTime % 1, tankPosition);
curve.getPointAt((tankTime + 0.01) % 1, tankTarget);
tank.position.set(tankPosition.x, 0, tankPosition.y);
tank.lookAt(tankTarget.x, 0, tankTarget.y);
```
-The turret on top of the tank is moved automatically by being a child
-of the tank. To point it at the target we just ask for the target's world position
-and then again use `Object3D.lookAt`
+La tourelle sur le dessus du char est déplacée automatiquement en tant qu'enfant du char. Pour le pointer sur la cible, nous demandons simplement la position de la cible, puis utilisons à nouveau `Object3D.lookAt`.
```js
const targetPosition = new THREE.Vector3();
...
-// face turret at target
+// tourelle face à la cible
targetMesh.getWorldPosition(targetPosition);
turretPivot.lookAt(targetPosition);
```
-
-There's a `turretCamera` which is a child of the `turretMesh` so
-it will move up and down and rotate with the turret. We make that
-aim at the target.
+Il y a une `tourretCamera` qui est un enfant de `turretMesh` donc il se déplacera de haut en bas et tournera avec la tourelle. On la fait viser la cible.
```js
-// make the turretCamera look at target
+// la turretCamera regarde la cible
turretCamera.lookAt(targetPosition);
```
-
-There is also a `targetCameraPivot` which is a child of `targetBob` so it floats
-around with the target. We aim that back at the tank. Its purpose is to allow the
-`targetCamera` to be offset from the target itself. If we instead made the camera
-a child of `targetBob` and just aimed the camera itself it would be inside the
-target.
+Il y a aussi un `targetCameraPivot` qui est un enfant de `targetBob` donc il flotte
+autour de la cible. Nous le pointons vers le char. Son but est de permettre à la
+`targetCamera` d'être décalé par rapport à la cible elle-même. Si nous faisions de la caméra
+un enfant de `targetBob`, elle serait à l'intérieur de la cible.
```js
-// make the targetCameraPivot look at the tank
+// faire en sorte que la cibleCameraPivot regarde le char
tank.getWorldPosition(targetPosition);
targetCameraPivot.lookAt(targetPosition);
```
-Finally we rotate all the wheels
+Enfin on fait tourner toutes les roues
```js
wheelMeshes.forEach((obj) => {
obj.rotation.x = time * 3;
});
```
-For the cameras we setup an array of all 4 cameras at init time with descriptions.
+Pour les caméras, nous avons configuré un ensemble de 4 caméras au moment de l'initialisation avec des descriptions.
```js
const cameras = [
@@ -444,7 +385,7 @@ const cameras = [
const infoElem = document.querySelector('#info');
```
-and cycle through our cameras at render time.
+et nous parcourons chaque camera au moment du rendu
```js
const camera = cameras[time * .25 % cameras.length | 0];
@@ -453,11 +394,11 @@ infoElem.textContent = camera.desc;
{{{example url="../threejs-scenegraph-tank.html"}}}
-I hope this gives some idea of how scene graphs work and how you might use them.
-Making `Object3D` nodes and parenting things to them is an important step to using
-a 3D engine like three.js well. Often it might seem like some complex math is necessary
-to make something move and rotate the way you want. For example without a scene graph
-computing the motion of the moon or where to put the wheels of the car relative to its
-body would be very complicated but using a scene graph it becomes much easier.
+J'espère que cela donne une idée du fonctionnement des graphiques de scène et de la façon dont vous pouvez les utiliser.
+Faire des nœuds « Object3D » et leur attacher des choses est une étape importante pour utiliser
+un moteur 3D comme Three.js bien. Souvent, on pourrait penser que des mathématiques complexes soient nécessaires
+pour faire bouger quelque chose et faire pivoter comme vous le souhaitez. Par exemple sans graphique de scène
+calculer le mouvement de la lune, savoir où placer les roues de la voiture par rapport à son
+corps serait très compliqué, mais en utilisant un graphique de scène, cela devient beaucoup plus facile.
-[Next up we'll go over materials](threejs-materials.html).
+[Passons maintenant en revue les materials](threejs-materials.html). | false |
Other | mrdoob | three.js | 1339849911c6cba989c80c0b594a478aa50d928e.json | add French translation | threejs/lessons/fr/threejs-scenegraph.md | @@ -0,0 +1,463 @@
+Title: Graphe de scène Three.js
+Description: What's a scene graph?
+TOC: Scenegraph
+
+Cet article fait partie d'une série consacrée à Three.js.
+Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
+Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
+
+Le coeurs de Three.js est sans aucun doute son objet scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
+
+<img src="resources/images/scenegraph-generic.svg" align="center">
+
+C'est un peu abstrait, alors essayons de donner quelques exemples.
+
+On pourrait prendre comme exemple le système solaire, le soleil, la terre, la lune.
+
+<img src="resources/images/scenegraph-solarsystem.svg" align="center">
+
+La Terre tourne autour du Soleil. La Lune tourne autour de la Terre. La Lune se déplace en cercle autour de la Terre. Du point de vue de la Lune, elle tourne dans "l'espace local" de la Terre. Même si son mouvement par rapport au Soleil est une courbe folle comme un spirographe du point de vue de la Lune, il n'a qu'à se préoccuper de tourner autour de l'espace local de la Terre.
+
+{{{diagram url="resources/moon-orbit.html" }}}
+
+Pour le voir autrement, vous qui vivez sur Terre n'avez pas à penser à la rotation de la Terre sur son axe ni à sa rotation autour du Soleil. Vous marchez ou conduisez ou nagez ou courez comme si la Terre ne bougeait pas ou ne tournait pas du tout. Vous marchez, conduisez, nagez, courez et vivez dans "l'espace local" de la Terre même si par rapport au soleil, vous tournez autour de la terre à environ 1 600 km/h et autour du soleil à environ 107000km/h. Votre position dans le système solaire est similaire à celle de la lune au-dessus, mais vous n'avez pas à vous en préoccuper. Vous vous souciez simplement de votre position par rapport à la terre dans son "espace local".
+
+Allons-y une étape à la fois. Imaginez que nous voulions faire un diagramme du soleil, de la terre et de la lune. Nous allons commencer par le soleil en créant simplement une sphère et en la mettant à l'origine. Remarque : Nous utilisons le soleil, la terre et la lune comme démonstration de l'utilisation d'une scène. Bien sûr, le vrai soleil, la terre et la lune utilisent la physique, mais pour nos besoins, nous allons faire semblant.
+
+```js
+// un tableau d'objets dont la rotation à mettre à jour
+const objects = [];
+
+// utiliser une seule sphère pour tout
+const radius = 1;
+const widthSegments = 6;
+const heightSegments = 6;
+const sphereGeometry = new THREE.SphereGeometry(
+ radius, widthSegments, heightSegments);
+
+const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00});
+const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial);
+sunMesh.scale.set(5, 5, 5); // agrandir le soleil
+scene.add(sunMesh);
+objects.push(sunMesh);
+```
+
+Nous utilisons une sphère à très faible polygone. Seulement 6 segments autour de son équateur. C'est ainsi qu'il est facile de voir la rotation.
+
+Nous allons réutiliser la même sphère pour tout, nous allons juste grossir la `sunMesh` 5 fois.
+
+Nous avons également défini la propriété `emissive` du matériau phong sur jaune. La propriété émissive d'un matériau phong est essentiellement la couleur qui sera dessinée sans que la lumière ne frappe la surface. La lumière est ajoutée à cette couleur.
+
+Mettons également une 'point light' au centre de la scène. Nous entrerons dans les détails plus tard, mais pour l'instant, la version simple est une lumière qui émane d'un seul point.
+
+```js
+{
+ const color = 0xFFFFFF;
+ const intensity = 3;
+ const light = new THREE.PointLight(color, intensity);
+ scene.add(light);
+}
+```
+
+Pour faciliter la visualisation, nous allons placer la caméra directement au-dessus de l'origine en regardant vers le bas. Le moyen le plus simple de le faire est d'utiliser la fonction `lookAt`. Cette fonction oriente la caméra pour "regarder" vers la position que nous passons à `lookAt`. Avant de faire cela, nous devons cependant indiquer à la caméra dans quelle direction le haut de la caméra est orienté ou plutôt dans quelle direction est "vers le haut" pour la caméra. Pour la plupart des situations, un Y positif est suffisant, mais puisque nous regardons vers le bas, nous devons dire à la caméra que Z positif est levé.
+
+```js
+const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
+camera.position.set(0, 50, 0);
+camera.up.set(0, 0, 1);
+camera.lookAt(0, 0, 0);
+```
+
+Dans la boucle de rendu, issue des exemples précédents, nous faisons pivoter tous les objets de notre tableau `objects` avec ce code.
+
+```js
+objects.forEach((obj) => {
+ obj.rotation.y = time;
+});
+```
+
+Ajouter la `sunMesh` au tableau `objects`, la fait pivoter.
+
+{{{example url="../threejs-scenegraph-sun.html" }}}
+
+Ajoutons maintenant la terre.
+
+```js
+const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244});
+const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial);
+earthMesh.position.x = 10;
+scene.add(earthMesh);
+objects.push(earthMesh);
+```
+
+Nous fabriquons un matériau bleu mais nous lui donnons une petite quantité de bleu émissif pour qu'il apparaisse sur notre fond noir.
+
+Nous utilisons la même `sphereGeometry` avec notre nouveau `EarthMaterial` bleu pour faire une `earthMesh`.
+Nous positionnons ces 10 unités à gauche du soleil et l'ajoutons à la scène. L'ajouter à notre tableau `objects`, la met en mouvement également.
+
+{{{example url="../threejs-scenegraph-sun-earth.html" }}}
+
+Vous pouvez voir que le soleil et la terre tournent mais que la terre ne tourne pas autour du soleil. Faisons de la terre un enfant du soleil
+
+```js
+-scene.add(earthMesh);
++sunMesh.add(earthMesh);
+```
+
+et...
+
+{{{example url="../threejs-scenegraph-sun-earth-orbit.html" }}}
+
+Que s'est-il passé? Pourquoi la terre a-t-elle la même taille que le soleil et pourquoi est-elle si loin ? En fait, j'ai dû déplacer la caméra de 50 à 150 unités au-dessus pour voir la terre.
+
+Nous avons fait de `earthMesh` un enfant du `sunMesh`.
+La `sunMesh` a son échelle définie sur 5x grâce à `sunMesh.scale.set(5, 5, 5)`. Cela signifie que l'espace local sunMeshs est 5 fois plus grand.
+Tout ce qui est mis dans cet espace sera multiplié par 5. Cela signifie que la Terre est maintenant 5 fois plus grande et sa distance par rapport au soleil (`earthMesh.position.x = 10`) est également 5 fois plus grande.
+
+ Notre scène ressemble maintenant à celà
+
+<img src="resources/images/scenegraph-sun-earth.svg" align="center">
+
+Pour résoudre ce problème, ajoutons un nœud vide. Nous lions le soleil et la terre à ce nœud.
+
+```js
++const solarSystem = new THREE.Object3D();
++scene.add(solarSystem);
++objects.push(solarSystem);
+
+const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00});
+const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial);
+sunMesh.scale.set(5, 5, 5);
+-scene.add(sunMesh);
++solarSystem.add(sunMesh);
+objects.push(sunMesh);
+
+const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244});
+const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial);
+earthMesh.position.x = 10;
+-sunMesh.add(earthMesh);
++solarSystem.add(earthMesh);
+objects.push(earthMesh);
+```
+Ici, nous avons fait un `Object3D`. Comme une `Mesh`, c'est aussi un nœud, mais contrairement à une `Mesh`, il n'a ni matériau ni géométrie. Il ne représente qu'un espace local.
+
+Notre nouvelle scène ressemble à ceci :
+
+<img src="resources/images/scenegraph-sun-earth-fixed.svg" align="center">
+
+La `sunMesh` et la `earthMesh` sont tous les deux des enfants de `solarSystem`. Les trois sont en train de tournés, et comme `earthMesh` n'est pas un enfant de `sunMesh`, elle n'est plus mise à l'échelle.
+
+{{{example url="../threejs-scenegraph-sun-earth-orbit-fixed.html" }}}
+
+Encore mieux. La Terre est plus petite que le Soleil, elle tourne autour de lui et sur elle-même.
+
+Sur le même schéma, ajoutons une Lune.
+
+```js
++const earthOrbit = new THREE.Object3D();
++earthOrbit.position.x = 10;
++solarSystem.add(earthOrbit);
++objects.push(earthOrbit);
+
+const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244});
+const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial);
+-earthMesh.position.x = 10; // note that this offset is already set in its parent's THREE.Object3D object "earthOrbit"
+-solarSystem.add(earthMesh);
++earthOrbit.add(earthMesh);
+objects.push(earthMesh);
+
++const moonOrbit = new THREE.Object3D();
++moonOrbit.position.x = 2;
++earthOrbit.add(moonOrbit);
+
++const moonMaterial = new THREE.MeshPhongMaterial({color: 0x888888, emissive: 0x222222});
++const moonMesh = new THREE.Mesh(sphereGeometry, moonMaterial);
++moonMesh.scale.set(.5, .5, .5);
++moonOrbit.add(moonMesh);
++objects.push(moonMesh);
+```
+XXXXXXXXXXXXXXXX
+
+
+Again we added more invisible scene graph nodes. The first, an `Object3D` called `earthOrbit`
+and added both the `earthMesh` and the `moonOrbit` to it, also new. We then added the `moonMesh`
+to the `moonOrbit`. The new scene graph looks like this.
+
+<img src="resources/images/scenegraph-sun-earth-moon.svg" align="center">
+
+and here's that
+
+{{{example url="../threejs-scenegraph-sun-earth-moon.html" }}}
+
+You can see the moon follows the spirograph pattern shown at the top
+of this article but we didn't have to manually compute it. We just
+setup our scene graph to do it for us.
+
+It is often useful to draw something to visualize the nodes in the scene graph.
+Three.js has some helpful ummmm, helpers to ummm, ... help with this.
+
+One is called an `AxesHelper`. It draws 3 lines representing the local
+<span style="color:red">X</span>,
+<span style="color:green">Y</span>, and
+<span style="color:blue">Z</span> axes. Let's add one to every node we
+created.
+
+```js
+// add an AxesHelper to each node
+objects.forEach((node) => {
+ const axes = new THREE.AxesHelper();
+ axes.material.depthTest = false;
+ axes.renderOrder = 1;
+ node.add(axes);
+});
+```
+
+On our case we want the axes to appear even though they are inside the spheres.
+To do this we set their material's `depthTest` to false which means they will
+not check to see if they are drawing behind something else. We also
+set their `renderOrder` to 1 (the default is 0) so that they get drawn after
+all the spheres. Otherwise a sphere might draw over them and cover them up.
+
+{{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}}
+
+We can see the
+<span style="color:red">x (red)</span> and
+<span style="color:blue">z (blue)</span> axes. Since we are looking
+straight down and each of our objects is only rotating around its
+y axis we don't see much of the <span style="color:green">y (green)</span> axes.
+
+It might be hard to see some of them as there are 2 pairs of overlapping axes. Both the `sunMesh`
+and the `solarSystem` are at the same position. Similarly the `earthMesh` and
+`earthOrbit` are at the same position. Let's add some simple controls to allow us
+to turn them on/off for each node.
+While we're at it let's also add another helper called the `GridHelper`. It
+makes a 2D grid on the X,Z plane. By default the grid is 10x10 units.
+
+We're also going to use [dat.GUI](https://github.com/dataarts/dat.gui) which is
+a UI library that is very popular with three.js projects. dat.GUI takes an
+object and a property name on that object and based on the type of the property
+automatically makes a UI to manipulate that property.
+
+We want to make both a `GridHelper` and an `AxesHelper` for each node. We need
+a label for each node so we'll get rid of the old loop and switch to calling
+some function to add the helpers for each node
+
+```js
+-// add an AxesHelper to each node
+-objects.forEach((node) => {
+- const axes = new THREE.AxesHelper();
+- axes.material.depthTest = false;
+- axes.renderOrder = 1;
+- node.add(axes);
+-});
+
++function makeAxisGrid(node, label, units) {
++ const helper = new AxisGridHelper(node, units);
++ gui.add(helper, 'visible').name(label);
++}
++
++makeAxisGrid(solarSystem, 'solarSystem', 25);
++makeAxisGrid(sunMesh, 'sunMesh');
++makeAxisGrid(earthOrbit, 'earthOrbit');
++makeAxisGrid(earthMesh, 'earthMesh');
++makeAxisGrid(moonOrbit, 'moonOrbit');
++makeAxisGrid(moonMesh, 'moonMesh');
+```
+
+`makeAxisGrid` makes an `AxisGridHelper` which is a class we'll create
+to make dat.GUI happy. Like it says above dat.GUI
+will automagically make a UI that manipulates the named property
+of some object. It will create a different UI depending on the type
+of property. We want it to create a checkbox so we need to specify
+a `bool` property. But, we want both the axes and the grid
+to appear/disappear based on a single property so we'll make a class
+that has a getter and setter for a property. That way we can let dat.GUI
+think it's manipulating a single property but internally we can set
+the visible property of both the `AxesHelper` and `GridHelper` for a node.
+
+```js
+// Turns both axes and grid visible on/off
+// dat.GUI requires a property that returns a bool
+// to decide to make a checkbox so we make a setter
+// and getter for `visible` which we can tell dat.GUI
+// to look at.
+class AxisGridHelper {
+ constructor(node, units = 10) {
+ const axes = new THREE.AxesHelper();
+ axes.material.depthTest = false;
+ axes.renderOrder = 2; // after the grid
+ node.add(axes);
+
+ const grid = new THREE.GridHelper(units, units);
+ grid.material.depthTest = false;
+ grid.renderOrder = 1;
+ node.add(grid);
+
+ this.grid = grid;
+ this.axes = axes;
+ this.visible = false;
+ }
+ get visible() {
+ return this._visible;
+ }
+ set visible(v) {
+ this._visible = v;
+ this.grid.visible = v;
+ this.axes.visible = v;
+ }
+}
+```
+
+One thing to notice is we set the `renderOrder` of the `AxesHelper`
+to 2 and for the `GridHelper` to 1 so that the axes get drawn after the grid.
+Otherwise the grid might overwrite the axes.
+
+{{{example url="../threejs-scenegraph-sun-earth-moon-axes-grids.html" }}}
+
+Turn on the `solarSystem` and you'll see how the earth is exactly 10
+units out from the center just like we set above. You can see how the
+earth is in the *local space* of the `solarSystem`. Similarly if you
+turn on the `earthOrbit` you'll see how the moon is exactly 2 units
+from the center of the *local space* of the `earthOrbit`.
+
+A few more examples of scene graphs. An automobile in a simple game world might have a scene graph like this
+
+<img src="resources/images/scenegraph-car.svg" align="center">
+
+If you move the car's body all the wheels will move with it. If you wanted the body
+to bounce separate from the wheels you might parent the body and the wheels to a "frame" node
+that represents the car's frame.
+
+Another example is a human in a game world.
+
+<img src="resources/images/scenegraph-human.svg" align="center">
+
+You can see the scene graph gets pretty complex for a human. In fact
+that scene graph above is simplified. For example you might extend it
+to cover every finger (at least another 28 nodes) and every toe
+(yet another 28 nodes) plus ones for the face and jaw, the eyes and maybe more.
+
+Let's make one semi-complex scene graph. We'll make a tank. The tank will have
+6 wheels and a turret. The tank will follow a path. There will be a sphere that
+moves around and the tank will target the sphere.
+
+Here's the scene graph. The meshes are colored in green, the `Object3D`s in blue,
+the lights in gold, and the cameras in purple. One camera has not been added
+to the scene graph.
+
+<div class="threejs_center"><img src="resources/images/scenegraph-tank.svg" style="width: 800px;"></div>
+
+Look in the code to see the setup of all of these nodes.
+
+For the target, the thing the tank is aiming at, there is a `targetOrbit`
+(`Object3D`) which just rotates similar to the `earthOrbit` above. A
+`targetElevation` (`Object3D`) which is a child of the `targetOrbit` provides an
+offset from the `targetOrbit` and a base elevation. Childed to that is another
+`Object3D` called `targetBob` which just bobs up and down relative to the
+`targetElevation`. Finally there's the `targetMesh` which is just a cube we
+rotate and change its colors
+
+```js
+// move target
+targetOrbit.rotation.y = time * .27;
+targetBob.position.y = Math.sin(time * 2) * 4;
+targetMesh.rotation.x = time * 7;
+targetMesh.rotation.y = time * 13;
+targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25);
+targetMaterial.color.setHSL(time * 10 % 1, 1, .25);
+```
+
+For the tank there's an `Object3D` called `tank` which is used to move everything
+below it around. The code uses a `SplineCurve` which it can ask for positions
+along that curve. 0.0 is the start of the curve. 1.0 is the end of the curve. It
+asks for the current position where it puts the tank. It then asks for a
+position slightly further down the curve and uses that to point the tank in that
+direction using `Object3D.lookAt`.
+
+```js
+const tankPosition = new THREE.Vector2();
+const tankTarget = new THREE.Vector2();
+
+...
+
+// move tank
+const tankTime = time * .05;
+curve.getPointAt(tankTime % 1, tankPosition);
+curve.getPointAt((tankTime + 0.01) % 1, tankTarget);
+tank.position.set(tankPosition.x, 0, tankPosition.y);
+tank.lookAt(tankTarget.x, 0, tankTarget.y);
+```
+
+The turret on top of the tank is moved automatically by being a child
+of the tank. To point it at the target we just ask for the target's world position
+and then again use `Object3D.lookAt`
+
+```js
+const targetPosition = new THREE.Vector3();
+
+...
+
+// face turret at target
+targetMesh.getWorldPosition(targetPosition);
+turretPivot.lookAt(targetPosition);
+```
+
+There's a `turretCamera` which is a child of the `turretMesh` so
+it will move up and down and rotate with the turret. We make that
+aim at the target.
+
+```js
+// make the turretCamera look at target
+turretCamera.lookAt(targetPosition);
+```
+
+There is also a `targetCameraPivot` which is a child of `targetBob` so it floats
+around with the target. We aim that back at the tank. Its purpose is to allow the
+`targetCamera` to be offset from the target itself. If we instead made the camera
+a child of `targetBob` and just aimed the camera itself it would be inside the
+target.
+
+```js
+// make the targetCameraPivot look at the tank
+tank.getWorldPosition(targetPosition);
+targetCameraPivot.lookAt(targetPosition);
+```
+
+Finally we rotate all the wheels
+
+```js
+wheelMeshes.forEach((obj) => {
+ obj.rotation.x = time * 3;
+});
+```
+
+For the cameras we setup an array of all 4 cameras at init time with descriptions.
+
+```js
+const cameras = [
+ { cam: camera, desc: 'detached camera', },
+ { cam: turretCamera, desc: 'on turret looking at target', },
+ { cam: targetCamera, desc: 'near target looking at tank', },
+ { cam: tankCamera, desc: 'above back of tank', },
+];
+
+const infoElem = document.querySelector('#info');
+```
+
+and cycle through our cameras at render time.
+
+```js
+const camera = cameras[time * .25 % cameras.length | 0];
+infoElem.textContent = camera.desc;
+```
+
+{{{example url="../threejs-scenegraph-tank.html"}}}
+
+I hope this gives some idea of how scene graphs work and how you might use them.
+Making `Object3D` nodes and parenting things to them is an important step to using
+a 3D engine like three.js well. Often it might seem like some complex math is necessary
+to make something move and rotate the way you want. For example without a scene graph
+computing the motion of the moon or where to put the wheels of the car relative to its
+body would be very complicated but using a scene graph it becomes much easier.
+
+[Next up we'll go over materials](threejs-materials.html). | false |
Other | mrdoob | three.js | c7a72df0a8a34205964f77fd1325a38efe08408e.json | add French translation | threejs/lessons/fr/threejs-setup.md | @@ -0,0 +1,56 @@
+Title: Installation de Three.js
+Description: Comment configurer votre environnement de développement pour Three.js
+TOC: Setup
+
+Cette article fait parti d'une série consacrée à Three.js. Le premier article traité des [fondements de Three.js](threejs-fundamentals.html).
+Si vous ne l'avez pas encore lu, vous devriez peut-être commencer par là.
+
+Avant d'aller plus loin, parlons du paramètrage de votre environnement de travail. Pour des raisons de sécurité
+WebGL ne peut pas utiliser des images provenant de votre disque dur. Cela signifie qu'il faille utiliser
+un serveur web. Heureusement, ils sont très facile à utiliser.
+
+Tout d'abord, si vous le souhaitez, vous pouvez télécharger l'intégralité de ce site depuis [ce lien](https://github.com/gfxfundamentals/threejsfundamentals/archive/gh-pages.zip).
+Une fois téléchargé, dézippez le dossier.
+
+Ensuite, téléchargez l'un des web serveurs suivants.
+
+Si vous en préférez un avec une interface graphique, voici [Servez](https://greggman.github.io/servez)
+
+{{{image url="resources/servez.gif" className="border" }}}
+
+Pointez-le simplement sur le dossier où vous avez décompressé les fichiers, cliquez sur "Démarrer", puis accédez-y dans votre navigateur à l'adresse suivante [`http://localhost:8080/`](http://localhost:8080/) ou si vous voulez souhaitez parcourir les exemples, accédez à [`http://localhost:8080/threejs`](http://localhost:8080/threejs).
+
+Pour arrêter le serveur, cliquez sur stop ou quittez Servez.
+
+Si vous préférez la ligne de commande, une autre façon consiste à utiliser [node.js](https://nodejs.org).
+Téléchargez-le, installez-le, puis ouvrez une fenêtre d'invite de commande / console / terminal. Si vous êtes sous Windows, le programme d'installation ajoutera une "Invite de commande de nœud" spéciale, alors utilisez-la.
+
+Ensuite installez [`servez`](https://github.com/greggman/servez-cli) avec ces commandes
+
+ npm -g install servez
+
+Ou si vous êtes sous OSX
+
+ sudo npm -g install servez
+
+Une fois que c'est fait, tapez cette commande
+
+ servez path/to/folder/where/you/unzipped/files
+
+Ou si vous êtes comme moi
+
+ cd path/to/folder/where/you/unzipped/files
+ servez
+
+Il devrait imprimer quelque chose ça
+
+{{{image url="resources/servez-response.png" }}}
+
+Ensuite, ouvrez [`http://localhost:8080/`](http://localhost:8080/) dans votre navigateur.
+
+Si vous ne spécifiez pas de chemin, Servez choisira le dossier courant.
+
+Si ces options ne vous conviennent pas, vous pouvez choisir
+[d'autres alternatives](https://stackoverflow.com/questions/12905426/what-is-a-faster-alternative-to-pythons-servez-or-simplehttpserver).
+
+Maintenant que vous avez un serveur configuré, nous pouvons passer aux [textures](threejs-textures.html). | false |
Other | mrdoob | three.js | 936a77115e958ce9f0350a49136fc0b477855835.json | fix grammatical errors | threejs/lessons/fr/threejs-responsive.md | @@ -4,15 +4,15 @@ TOC: Design réactif
Ceci est le second article dans une série traitant de three.js.
Le premier traitait [des principes de base](threejs-fundamentals.html).
-Si vous ne l'avez pas encore lu, vous deviriez peut-être commencer par le lire.
+Si vous ne l'avez pas encore lu, vous deviriez peut-être commencer par là.
-Ce présent article explique comment rendre votre application three.js adaptable
+Cet article explique comment rendre votre application Three.js adaptable
à n'importe quelle situation. Rendre une page web adaptable (*responsive*)
se réfère généralement à faire en sorte que la page s'affiche de manière
-appropriée sur des affichages de taille différente, des ordinateurs de bureau
+appropriée sur des écrans de taille différente, des ordinateurs de bureau
aux *smart-phones*, en passant par les tablettes.
-Concernant three.js, il y a d'ailleurs davantage de situations à traiter.
+Concernant Three.js, il y a d'ailleurs davantage de situations à traiter.
Par exemple, un éditeur 3D avec des contrôles à gauche, droite, en haut ou
en bas est quelque chose que nous voudrions gérer. Un schéma interactif
au milieu d'un document en est un autre exemple.
@@ -24,7 +24,7 @@ sans taille :
<canvas id="c"></canvas>
```
-Ce canevas a par défaut une taille de 300x150 pixels CSS.
+Ce canevas a, par défaut, une taille de 300x150 pixels.
Dans le navigateur, la manière recommandée de fixer la taille
de quelque chose est d'utiliser CSS.
@@ -51,11 +51,11 @@ leur fait occuper toute la fenêtre. Sinon, ils ne sont seulement aussi large
que leur contenu.
Ensuite, nous faisons en sorte que l'élément `id=c` fasse
-100% de la taille de son conteneur qui, dans ce cas, est le corps du document.
+100% de la taille de son conteneur qui est, dans ce cas, la balise body.
-Finalement, nous le passons du mode `display` à celui de `block`.
-Le mode par défaut d'affichage d'un canevas est `inline`, ce qui implique
-que des espaces peuvent y être ajoutés à l'affichage.
+Finalement, nous passons le mode `display` à `block`.
+Le mode d'affichage par défaut d'un canevas est `inline`, ce qui implique
+que des espaces peuvent être ajoutés à l'affichage.
En passant le canevas à `block`, ce problème est supprimé.
Voici le résultat :
@@ -98,7 +98,7 @@ A présent les cubes ne devraient plus être déformés.
{{{example url="../threejs-responsive-update-camera.html" }}}
-Ouvrez l'exemple dans une fenêtre séparée et redimensionnez là.
+Ouvrez l'exemple dans une fenêtre séparée et redimensionnez la.
Vous devriez voir que les cubes ne sont plus étirés, que ce soit
en hauteur ou en largeur.
Ils restent corrects quelque soit l'aspect de la taille de la fenêtre.
@@ -119,14 +119,13 @@ nous pouvons l'afficher avec une taille de 400x200.
```
La taille interne d'un canevas, sa résolution, est souvent appelée sa taille de tampon
-de dessin (*drawingbuffer*). Dans three.js, nous pouvons ajuster cette taille
-de canevas en appelant `renderer.setSize`.
+de dessin (*drawingbuffer*). Dans Three.js, nous pouvons ajuster la taille
+du canevas en appelant `renderer.setSize`.
Quelle taille devons nous choisir ? La réponse la plus évidente est "la même taille que
-celle d'affichage du canevas". A nouveau, pour le faire, nous pouvons avoir recours
-au propriétés `clientWidth` et `clientHeight`.
+celle du canevas". A nouveau, pour le faire, nous pouvons recourir
+aux propriétés `clientWidth` et `clientHeight`.
-Ecrivons une fonction qui vérifie si le canevas du *renderer* est ou non à la taille
-qui est affichée et l'ajuste en conséquence.
+Ecrivons une fonction qui vérifie si le rendu du canevas a la bonne taille et l'ajuste en conséquence.
```js
function resizeRendererToDisplaySize(renderer) {
@@ -141,19 +140,19 @@ function resizeRendererToDisplaySize(renderer) {
}
```
-Remarquez que nous vérifions sur le canevas a réellement besoin d'être redimensionné.
+Remarquez que nous vérifions si le canevas a réellement besoin d'être redimensionné.
Le redimensionnement est une partie intéressante de la spécification du canevas
et il est mieux de ne pas lui donner à nouveau la même taille s'il est déjà
à la dimension que nous voulons.
Une fois que nous savons si le redimensionnement est nécessaire ou non, nous
appelons `renderer.setSize` et lui passons les nouvelles largeur et hauteur.
Il est important de passer `false` en troisième.
-`render.setSize` modifie par défaut la taille du canevas CSS, mais ce n'est
+`render.setSize` modifie par défaut la taille du canevas dans le CSS, mais ce n'est
pas ce que nous voulons. Nous souhaitons que le navigateur continue à fonctionner
-comme pour les autres éléments, qui est d'utiliser CSS pour déterminer la
+comme pour les autres éléments, en utilisant le CSS pour déterminer la
taille d'affichage d'un élément. Nous ne voulons pas que les canevas utilisés
-par three aient un comportement différent des autres éléments.
+par Three aient un comportement différent des autres éléments.
Remarquez que notre fonction renvoie *true* si le canevas a été redimensionné.
Nous pouvons l'utiliser pour vérifier si d'autre choses doivent être mises à jour.
@@ -178,21 +177,18 @@ retourne `true`.
{{{example url="../threejs-responsive.html" }}}
-Le rendu devrait à présent être avec une résolution qui correspond à
+Le rendu devrait à présent avoir une résolution correspondant à
la taille d'affichage du canevas.
-Afin de comprendre pourquoi il faut laisser CSS gérer le redimensionnement,
-prenons notre code et mettons le dans un [fichier `.js` séparé](../threejs-responsive.js).
-
-Voici donc quelques autres exemples où nous avons laissé CSS choisir la taille et remarquez que nous n'avons
+Afin de comprendre pourquoi il faut laisser le CSS gérer le redimensionnement,
+prenons notre code et mettons le dans un [fichier `.js` séparé](../threejs-responsive.js). Voici donc quelques autres exemples où nous avons laissé le CSS choisir la taille et remarquez que nous n'avons
eu aucun code à modifier pour qu'ils fonctionnent.
Mettons nos cubes au milieu d'un paragraphe de texte.
{{{example url="../threejs-responsive-paragraph.html" startPane="html" }}}
-et voici notre même code utilisé dans un éditeur
-où la zone de contrôle à droite peut être redimensionnée.
+et voici notre même code utilisé dans un éditeur où la zone de contrôle à droite peut être redimensionnée.
{{{example url="../threejs-responsive-editor.html" startPane="html" }}}
@@ -212,37 +208,37 @@ qui est supposée être la même quelque soit la résolution de
l'affichage. Le navigateur effectue le rendu du texte avec davantage
de détails mais la même taille physique.
-Il y a plusieurs façons de gérer les HD-DPI avec three.js.
+Il y a plusieurs façons de gérer les HD-DPI avec Three.js.
La première façon est de ne rien faire de spécial. Cela
est, de manière discutable, le plus commun. Effectuer le
-rendu de graphismes 3D prend beaucoup de puissance de calcul GPU
+rendu de graphismes 3D réclame beaucoup de puissance de calcul au GPU
(*Graphics Processing Units*, les processeurs dédiés de carte graphique).
-Les GPUs mobiles ont moins de puissance que les ordinateurs de bureau,
+Les GPUs des smartphones ont moins de puissance que ceux des ordinateurs de bureau,
du moins en 2018, et pourtant les téléphones mobiles ont des affichages
haute résolution. Le haut de gamme actuel pour les smartphones a un ratio
HD-DPI de 3x, ce qui signifie que pour chaque pixel d'un affichage non HD-DPI,
ces téléphones ont 9 pixels. Il y a donc 9 fois plus de travail
pour le rendu.
-Calculer pour 9 pixels nécessite des ressources donc, si
+Calculer pour 9 pixels nécessite des ressources. Donc, si
nous laissons le code comme cela, nous calculerons pour 1 pixel
et le navigateur le dessinera avec 3 fois sa taille (3 x 3 = 9 pixels).
-Pour toute application three.js lourde, c'est probablement ce que vous
+Pour toute application Three.js lourde, c'est probablement ce que vous
voulez sinon vous risquez d'avoir un taux de rafraîchissement faible (*framerate*).
Ceci étant dit, si vous préférez effectuer le rendu à la résolution de l'appareil,
-voici quelques façons de le faire en three.js.
+voici quelques façons de le faire en Three.js.
-La première est d'indiquer à three.js le facteur de multiplication de la résolution
+La première est d'indiquer à Three.js le facteur de multiplication de la résolution
en utilisant `renderer.setPixelRatio`. Nous pouvons demander au navigateur ce
-facteur entre les pixels CSS et les pixels du périphérique et les passer à three.js
+facteur entre les pixels CSS et les pixels du périphérique et les passer à Three.js
renderer.setPixelRatio(window.devicePixelRatio);
Après cela, tout appel à `renderer.setSize` va automatiquement
-utiliser la taille que vous avez demandée, multipliée par le
+utiliser la taille que vous avez demandé, multiplié par le
ratio que vous avez demandé.
**Ceci est fortement DÉCONSEILLÉ**. Voir ci-dessous.
@@ -264,15 +260,15 @@ L'autre façon est de le faire par soi-même quand on redimensionne le canevas.
Cette seconde façon est objectivement meilleure. Pourquoi ? Parce que cela signifie
que nous avons ce que nous avons demandé. Il y a plusieurs cas où,
-quand on utilise three.js, nous avons besoin de savoir la taille effective
+quand on utilise Three.js, nous avons besoin de connaître la taille effective
du tampon d'affichage du canevas. Par exemple, quand on réalise un filtre de
post-processing, ou si nous faisons un *shader* qui accède à `gl_FragCoord`,
si nous sommes en train de faire une capture d'écran, ou en train de lire les pixels
pour une sélection par GPU, pour dessiner dans un canevas 2D, etc...
Il y a plusieurs cas où, si nous utilisons `setPixelRatio` alors notre
taille effective est différente de la taille que nous avons demandé et nous
aurons alors à deviner quand utiliser la taille demandée ou la taille utilisée
-par three.js.
+par Three.js.
En le faisant par soi-même, nous savons toujours que la taille utilisée
est celle que nous avons demandé. Il n'y a aucun cas où cela se fait tout
seul autrement.
@@ -281,10 +277,10 @@ Voici un exemple utilisant le code vu plus haut.
{{{example url="../threejs-responsive-hd-dpi.html" }}}
-Cela devrait être difficile de voir la différence, mais si vous avez
+Il vous est peut-être difficile de voir la différence, mais si vous avez
un affichage HD-DPI et que vous comparez cet exemple aux autres plus
haut, vous devriez remarquer que les arêtes sont plus vives.
Cet article a couvert un sujet très basique mais fondamental.
-Ensuite, nous allons rapidement
-[passer en revue les primitives de base proposées par three.js](threejs-primitives.html).
+Dans l'article suivant, nous allons rapidement
+[passer en revue les primitives de base proposées par Three.js](threejs-primitives.html). | false |
Other | mrdoob | three.js | 50298e608076374ec72bae18ba4be8e3a7802aaf.json | fix grammatical errors | threejs/lessons/fr/threejs-primitives.md | @@ -1,9 +1,9 @@
Title: Primitives de Three.js
-Description: Un tour des primitives de three.js
+Description: Un tour des primitives de Three.js
TOC: Primitives
-Cet article fait partie d'une série consacrée à three.js.
-Le premier article est [Principes de base](threejs-fundamentals.html).
+Cet article fait partie d'une série consacrée à Three.js.
+Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
Three.js a un grand nombre de primitives. Les primitives
@@ -18,12 +18,12 @@ applications 3D, il est courant de demander à un artiste de faire des modèles
dans un programme de modélisation 3D comme [Blender](https://blender.org),
[Maya](https://www.autodesk.com/products/maya/) ou [Cinema 4D](https://www.maxon.net/en-us/products/cinema-4d/).
Plus tard dans cette série,
-nous aborderons la conception et le chargement de données de
+nous aborderons la conception et le chargement de données provenant de
plusieurs programme de modélisation 3D. Pour l'instant, passons
en revue certaines primitives disponibles.
La plupart des primitives ci-dessous ont des valeurs par défaut
-pour certains ou tous leurs paramètres. Vous pouvez donc les
+pour certain ou tous leurs paramètres. Vous pouvez donc les
utiliser en fonction de vos besoins.
<div id="Diagram-BoxGeometry" data-primitive="BoxGeometry">Une Boîte</div>
@@ -33,7 +33,7 @@ utiliser en fonction de vos besoins.
<div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">Un Dodécaèdre (12 côtés)</div>
<div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">Une forme 2D extrudée avec un biseautage optionnel. Ici, nous extrudons une forme de cœur. Notez qu'il s'agit du principe de fonctionnement pour les <code>TextGeometry</code> et les <code>TextGeometry</code>.</div>
<div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">Un Icosaèdre (20 côtés)</div>
-<div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">Une forme généré par la rotation d'une ligne pour, par exemple, dessiner une lampe, une quille, bougies, bougeoirs, verres à vin, verres à boire, etc. Vous fournissez une silhouette en deux dimensions comme une série de points et vous indiquez ensuite à three.js combien de subdivisions sont nécessaires en faisant tourner la silhouette autour d'un axe.</div>
+<div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">Une forme généré par la rotation d'une ligne pour, par exemple, dessiner une lampe, une quille, une bougie, un bougeoir, un verre à vin, etc. Vous fournissez une silhouette en deux dimensions comme une série de points et vous indiquez ensuite à Three.js combien de subdivisions sont nécessaires en faisant tourner la silhouette autour d'un axe.</div>
<div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">Un Octaèdre (8 côtés)</div>
<div id="Diagram-ParametricGeometry" data-primitive="ParametricGeometry">Une surface générée en fournissant à la fonction un point 2D d'une grille et retourne le point 3D correspondant.</div>
<div id="Diagram-PlaneGeometry" data-primitive="PlaneGeometry">Un plan 2D</div> | false |
Other | mrdoob | three.js | 9aa5627deae64ad66a4a227a3f0c4ddba0615603.json | fix grammatical errors | threejs/lessons/fr/threejs-fundamentals.md | @@ -2,15 +2,15 @@ Titre: Three.js, principes de base
Description: Votre première leçon sur Three.js, commençant par les principes de base
TOC: Principes de base
-Ceci est le premier article d'une série consacrée à three.js.
+Ceci est le premier article d'une série consacrée à Three.js.
[Three.js](https://threejs.org) est une bibliothèque 3D qui a pour objectif
de rendre aussi facile que possible l'inclusion de contenu 3D dans une page web.
Three.js est souvent confondu avec WebGL puisque la plupart du temps, mais
pas toujours, elle exploite WebGL pour dessiner en 3D.
[WebGL est un système très bas niveau qui ne dessine que des points, des lignes et des triangles](https://webglfundamentals.org).
Faire quelque chose d'exploitable avec WebGL requiert une certaine quantité de code
-et c'est là que three.js intervient. Elle prend en charge des choses
+et c'est là que Three.js intervient. Elle prend en charge des choses
telles que les scènes, lumières, ombres, matériaux, textures, mathématiques 3D, en bref,
tout ce que vous avez à écrire par vous même si vous aviez à utiliser WebGL directement.
@@ -23,23 +23,23 @@ donc la plupart des utilisateurs devraient être capables d'exécuter ce code.
Si vous souhaitez exécuter ce code sur un très vieux navigateur, nous vous recommandons
un transpileur tel que [Babel](https://babel.io).
Bien sûr, les utilisateurs exécutant de très vieux navigateurs ont probablement
-des machines incapables de faire tourner three.js.
+des machines incapables de faire tourner Three.js.
Lors de l'apprentissage de la plupart des langages de programmation,
la première tâche que les gens font est de faire afficher à l'ordinateur
`"Hello World!"`. Pour la programmation 3D, l'équivalent est de faire afficher
un cube en 3D. Donc, nous commencerons par "Hello Cube!".
Avant de débuter, nous allons tenter de vous donner un idée de la structure
-d'une application three.js. Elle requiert de créer un ensemble d'objets
+d'une application Three.js. Elle requiert de créer un ensemble d'objets
et de les connecter. Voici un diagramme qui représente une application
-three.js de petite taille:
+Three.js de petite taille:
<div class="threejs_center"><img src="resources/images/threejs-structure.svg" style="width: 768px;"></div>
Voici ce qui est à remarquer dans le diagramme ci-dessus :
-* Il y a un `Renderer`. C'est sans doute l'objet principal de three.js. Vous passez
+* Il y a un `Renderer`. C'est sans doute l'objet principal de Three.js. Vous passez
une `Scene` et une `Camera` à un `Renderer` et il effectue le rendu (dessine) de la
partie de la scène 3D qui est à l'intérieur de l'espace visible (en réalité une pyramide tronquée ou *frustum*)
de la caméra dans une image 2D affichée dans un canevas (*canvas*).
@@ -52,11 +52,11 @@ Voici ce qui est à remarquer dans le diagramme ci-dessus :
hiérarchique de type parent/enfant, arborescente, et indique où les objets apparaissent et
comment ils sont orientés. Les enfants sont positionnés et orientés par rapport à leur parent.
Par exemple, les roues d'une voiture sont les enfants du châssis impliquant que si l'on déplace
- ou oriente la voiture, les roues suiveront automatiquement son déplacement. Plus de
+ ou oriente la voiture, les roues suivront automatiquement son déplacement. Plus de
détails sont donnés dans [l'article sur les graphes de scène](threejs-scenegraph.html).
- Il est à noter sur que ce diagramme `Camera` est patiellement placée dans le graphe de scène.
- Cela permet d'attirer l'attention qu'en three.js, contrairement aux autres objets, une `Camera` ne doit
+ Il est à noter sur que ce diagramme `Camera` est patiellement placé dans le graphe de scène.
+ Cela permet d'attirer l'attention qu'en Three.js, contrairement aux autres objets, une `Camera` ne doit
pas forcément faire partie du graphe de scène pour être opérationnelle. Une `Camera`, de la même
façon que les autres objets, enfant d'un autre objet, se déplace et s'oriente par rapport à son
objet parent. A la fin de [l'article sur les graphes de scène](threejs-scenegraph.html), l'inclusion
@@ -80,29 +80,29 @@ Voici ce qui est à remarquer dans le diagramme ci-dessus :
[propriétés de surface utilisées pour dessiner la géométrie](threejs-materials.html)
telles que la couleur à utiliser ou le pouvoir réfléchissant (brillance). Un matériau (`Material`)
peut aussi se référer à un ou plusieurs objets `Texture` dont l'utilité est, par exemple, de plaquer
- une image sur la surface d'un géométrie.
+ une image sur la surface d'une géométrie.
* Les objets `Texture` représentent généralement des images soit [chargées de fichiers image](threejs-textures.html),
soit [générées par le biais d'un canevas](threejs-canvas-textures.html) ou
- [résultent du rendu d'une autre scène](threejs-rendertargets.html).
+ [résultant du rendu d'une autre scène](threejs-rendertargets.html).
* Les objets `Light` représentent [différentes sortent de lumière](threejs-lights.html).
Maintenant que tout cela a été défini, nous allons présenter un exemple de type *"Hello Cube"* utilisant un
-nombre minimum d'élements three.js :
+nombre minimum d'élements Three.js :
<div class="threejs_center"><img src="resources/images/threejs-1cube-no-light-scene.svg" style="width: 500px;"></div>
-Tout d'abord, chargeons three.js :
+Tout d'abord, chargeons Three.js :
```html
<script type="module">
-import * as THREE from './resources/threejs/r127/build/three.module.js';
+import * as THREE from './resources/threejs/r130/build/three.module.js';
</script>
```
Il est important d'écrire `type="module"` dans la balise script.
-Cela nous autorise l'utilisation du mot-clé `import` pour charger three.js.
+Cela nous autorise l'utilisation du mot-clé `import` pour charger Three.js.
Il y a d'autres manières de le réaliser, mais depuis la version 106 (r106),
l'utilisation des modules est recommandée. Ils ont l'avantage de pouvoir
facilement importer les autres modules dont ils ont besoin. Cela nous
@@ -116,7 +116,7 @@ Ensuite, nous avons besoin d'une balise `<canvas>` :
</body>
```
-Nous allons demander à three.js de dessiner dans ce canevas donc nous devons le rechercher
+Nous allons demander à Three.js de dessiner dans ce canevas donc nous devons le rechercher
dans le document html :
```html
@@ -138,14 +138,14 @@ dans le canevas. Par le passé, il y a eu aussi d'autre *renderers* tels que
qui utiliser WebGL pour effectuer une rendu 3D dans le canevas.
Notez qu'il y a quelques détails ésotériques ici. Si vous ne passez pas un
-canevas à three.js, il va en créer un pour vous mais vous aurez à l'ajouter
-au document. Où l'ajouter peut dépendre de contexte d'utilisation et vous aurez
-à modifier votre code en conséquence. Passer un canevas à three.js nous apparaît donc
+canevas à Three.js, il va en créer un pour vous mais vous aurez à l'ajouter
+au document. Où l'ajouter peut dépendre du contexte d'utilisation et vous aurez
+à modifier votre code en conséquence. Passer un canevas à Three.js nous apparaît donc
plus flexible. Nous pouvons mettre le canevas n'importe où et le code le retrouvera.
Dans le cas contraire, nous aurons à coder où insérer le canevas, ce qui amènera
probablement à changer le code si le contexte d'utilisation change.
-Ensuite, nous avons besoin d'une caméra. Nous créerons une `PerspectiveCamera`.
+Ensuite, nous avons besoin d'une caméra. Nous créons une `PerspectiveCamera`.
```js
const fov = 75;
@@ -157,7 +157,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
`fov` est le raccourci pour `field of view` ou champ de vision.
Dans ce cas, 75 degrés d'ouverture verticale. Il est à noter que
-la plupart des angles dans three.js sont exprimés en radians à l'exception
+la plupart des angles dans Three.js sont exprimés en radians à l'exception
de la caméra perspective.
`aspect` est l'aspect de l'affichage dans le canevas. Cela sera détaillé
@@ -175,7 +175,7 @@ cubes et prismes.
<img src="resources/frustum-3d.svg" width="500" class="threejs_center"/>
L'espacement entre les plans *near* et *far* est déterminé
-par le champ de vue. La largeur est fixée par le champ de vue et l'aspect.
+par le champ de vision. La largeur est fixée par le champ de vision et l'aspect.
Tout ce qui est dans le *frustum* est dessiné. Ce qui est à l'extérieur ne l'est pas.
@@ -191,15 +191,15 @@ Voici ce que nous voudrions voir :
<img src="resources/scene-down.svg" width="500" class="threejs_center"/>
-Dans le schéma ci-dessous, nous pouvons voir que notre caméra est placée
+Dans le schéma ci-dessus, nous pouvons voir que notre caméra est placée
en `z = 2`. Elle regarde le long de la direction -Z.
Notre *frustum* démarre à 0.1 unités de la caméra et s'étend jusqu'à 5 unités devant elle.
Comme le schéma est vu du haut, le champ de vue est affecté par l'aspect.
Notre canvas est deux fois plus large que haut donc le champ de vue horizontal
est plus grand que les 75 degrés spécifié pour le champ vertical.
-Ensuite, nous créons une `Scene`. Dans three.js, une `Scene` est la racine
-du graphe de scène. Tout ce que nous voulons que three.js dessine doit être ajouté
+Ensuite, nous créons une `Scene`. Dans Three.js, une `Scene` est la racine
+du graphe de scène. Tout ce que nous voulons que Three.js dessine doit être ajouté
à la scène. Cela sera davantage détaillé dans [un futur article sur le fonctionnement des scènes](threejs-scenegraph.html).
```js
@@ -216,14 +216,13 @@ const boxHeight = 1;
const boxDepth = 1;
const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
```
-Puis nous créons un matériau basique et fixons sa couleur.
-Elle peut être spécifiée au format hexadécimal (6 chiffres) du standard CSS.
+Puis nous créons un matériau basique et fixons sa couleur, qui peut être spécifiée au format hexadécimal (6 chiffres) du standard CSS.
```js
const material = new THREE.MeshBasicMaterial({color: 0x44aa88});
```
-Nous créons ensuite un maillage (`Mesh`). Dans three.js, il représente la combinaison
+Nous créons ensuite un maillage (`Mesh`). Dans Three.js, il représente la combinaison
d'une `Geometry` (forme de l'objet) et d'un matériau (`Material` - aspect
d'un objet, brillant ou plat, quelle couleur, quelle texture appliquer, etc.)
ainsi que la position, l'orientation et l'échelle de l'objet dans la scène.
@@ -238,7 +237,7 @@ Finalement, nous ajoutons le maillage à la scène.
scene.add(cube);
```
-Nous alors effectuer le rendu de la scène en appelant la fonction *render* du *renderer*
+Nous pouvons, maintenant, effectuer le rendu de la scène en appelant la fonction *render* du *renderer*
et en lui passant la scène et la caméra.
```js
@@ -250,10 +249,10 @@ Voici un exemple fonctionnel :
{{{example url="../threejs-fundamentals.html" }}}
Il est difficile de déterminer s'il s'agit d'un cube 3D puisque nous
-l'observons suivant l'axe -Z auquel le cube est lui même aligné.
+l'observons suivant l'axe -Z sur lequel le cube est lui même aligné.
Nous n'en voyons donc qu'une face.
-Nous nous proposons de l'animer en le faisant tourner et cela fera clairement
+Animons notre cube en le faisant tourner et cela fera clairement
apparaître qu'il est dessiné en 3D. Pour l'animation, nous effectuerons son rendu
dans une boucle de rendu en utilisant
[`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame).
@@ -278,7 +277,7 @@ requestAnimationFrame(render);
voulez animer quelque chose. Nous lui passons une fonction à appeler.
Dans notre cas, c'est la fonction `render`. Le navigateur appellera cette fonction
et, si nous mettons à jour l'affichage de la page, le navigateur refera le rendu
-de la page. Dans notre cas, nous appelons la fonction `renderer.render` de three
+de la page. Dans notre cas, nous appelons la fonction `renderer.render` de Three.js
qui dessinera notre scène.
`requestAnimationFrame` passe à notre fonction le temps depuis lequel la page est chargée.
@@ -287,8 +286,8 @@ avec des secondes. C'est pourquoi, nous l'avons converti.
A présent, nous appliquons sur le cube des rotations le long des axes X et Y en fonction du temps écoulé.
Les angles de rotation sont exprimés en [radians](https://en.wikipedia.org/wiki/Radian).
-Sachant que 2 pi radians fait faire un tour complet, notre cube effectuera une rotation complète
-sur chaque axe en à peu près 6.28 secondes.
+Sachant que 2 PI radians fait faire un tour complet, notre cube effectuera une rotation complète
+sur chaque axe en, à peu près, 6,28 secondes.
Nous effectuons alors le rendu de la scène et
demandons une autre image pour l'animation afin de poursuivre notre boucle.
@@ -338,9 +337,9 @@ Cela devrait à présent apparaître très clairement en 3D.
Pour le sport, ajoutons 2 cubes supplémentaires.
Nous partageons la même géométrie pour chaque cube mais un matériau différent par cube
-de sorte que chacun d'eux soit affecté d'une couleur différente.
+afin qu'ils aient une couleur différente.
-Tout d'abord, nous définissons une fonction qui crée une nouveau matériau
+Tout d'abord, nous définissons une fonction qui crée un nouveau matériau
avec la couleur spécifiée. Ensuite, elle créé un maillage à partir de la
géométrie spécifiée, l'ajoute à la scène et change sa position en X.
@@ -357,8 +356,8 @@ function makeInstance(geometry, color, x) {
}
```
-Ensuite, nous l'appellerons à 3 reprises avec 3 différentes couleurs
-et positions en X, puis nous conserverons ces instances de `Mesh` dans un tableau.
+Ensuite, nous l'appellons à 3 reprises avec 3 différentes couleurs
+et positions en X, puis nous conservons ces instances de `Mesh` dans un tableau.
```js
const cubes = [
@@ -368,7 +367,7 @@ const cubes = [
];
```
-Enfin, nous ferons tourner ces 3 cubes dans notre fonction de rendu.
+Enfin, nous faisons tourner ces 3 cubes dans notre fonction de rendu.
Nous calculons une rotation légèrement différente pour chacun d'eux.
```js
@@ -391,8 +390,8 @@ et voilà le résultat.
Si nous le comparons au schéma précédent, nous constatons qu'il
est conforme à nos attentes. Les cubes en X = -2 et X = +2
-sont partiellement en dehors du *frustum*. Ils sont également
-exagérément déformés puisque le champ de vue dépeint au travers du
+sont partiellement en dehors du *frustum*. Ils sont, de plus,
+exagérément déformés puisque le champ de vision dépeint au travers du
canevas est extrême.
A présent, notre programme est schématisé par la figure suivante :
@@ -407,8 +406,8 @@ Nous espérons que cette courte introduction vous aide à débuter.
[La prochaine étape consiste à rendre notre code réactif et donc adaptable à de multiples situations](threejs-responsive.html).
<div class="threejs_bottombar">
-<h3>es6 modules, three.js et structure de dossiers</h3>
-<p>Depuis la version 106 (r106), l'utilisation de three.js privilégie les <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">modules es6</a>.</p>
+<h3>es6 modules, Three.js et structure de dossiers</h3>
+<p>Depuis la version 106 (r106), l'utilisation de Three.js privilégie les <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">modules es6</a>.</p>
<p>
Ils sont chargés via le mot-clé <code>import</code> dans un script ou en ligne
par le biais d'une balise <code><script type="module"></code>. Voici un exemple d'utilisation avec les deux :
@@ -428,7 +427,7 @@ ce qui est différent des autres balises telles que <code><img></code> et
</p>
<p>
Les références à un même script ne seront chargées qu'une seule fois à partir du
-moment où leur chemin absolu est exactement identique. Pour three.js, cela veut
+moment où leur chemin absolu est exactement identique. Pour Three.js, cela veut
dire qu'il est nécessaire de mettre toutes les bibliothèques d'exemples dans une
structure correcte pour les dossiers :
</p>
@@ -466,7 +465,7 @@ import * as THREE from '../../../build/three.module.js';
</pre>
<p>
Utiliser la même structure permet de s'assurer, lors de l'importation de
-three et d'une autre bibliothèque d'exemple, qu'ils référenceront le même fichier
+Three.js et d'une autre bibliothèque d'exemple, qu'ils référenceront le même fichier
three.module.js.
</p>
<pre class="prettyprint">
@@ -483,7 +482,7 @@ import {OrbitControls} from 'https://unpkg.com/three@0.108.0/examples/jsm/contro
vous pouvez consulter <a href="https://r105.threejsfundamentals.org">une version plus ancienne de ce site</a>.
Three.js a pour politique de ne pas s'embarrasser avec la rétro compatibilité.
Cela suppose que vous utilisez une version spécifique de la bibliothèque que vous aurez téléchargé et
-incorporé à votre projet. Lors de la mise à jour vers une nouvelle version de three.js,
+incorporé à votre projet. Lors de la mise à jour vers une nouvelle version de Three.js,
vous pouvez lire le <a href="https://github.com/mrdoob/three.js/wiki/Migration-Guide">guide de migration</a>
pour voir ce que vous avez à changer. Cela nécessiterait beaucoup de travail de maintenir
à la fois une version de ce site avec les modules es6 et une autre avec le script global. | false |
Other | mrdoob | three.js | a06d6ec927b2aac9120d9a616b4933c3f5daa019.json | Fix typo if -> it | threejs/lessons/threejs-cameras.md | @@ -25,7 +25,7 @@ and a frustum are all names of different kinds of solids.
<div><div data-diagram="shapeFrustum"></div><div>frustum</div></div>
</div>
-I only point that out because I didn't know if for years. Some book or page would mention
+I only point that out because I didn't know it for years. Some book or page would mention
*frustum* and my eyes would glaze over. Understanding it's the name of a type of solid
shape made those descriptions suddenly make more sense 😅
| false |
Other | mrdoob | three.js | 676cf6d73749f9c89b7326f2f2b221fa19ee73c3.json | Fix typo in lesson ( code >> cone ). | threejs/lessons/threejs-lights.md | @@ -411,7 +411,7 @@ gui.add(new DegRadHelper(light, 'angle'), 'value', 0, 90).name('angle').onChange
The inner cone is defined by setting the [`penumbra`](SpotLight.penumbra) property
as a percentage from the outer cone. In other words when `penumbra` is 0 then the
-inner code is the same size (0 = no difference) from the outer cone. When the
+inner cone is the same size (0 = no difference) from the outer cone. When the
`penumbra` is 1 then the light fades starting in the center of the cone to the
outer cone. When `penumbra` is .5 then the light fades starting from 50% between
the center of the outer cone. | false |
Other | mrdoob | three.js | 0132df919c789b53bfd9d0418f97ebee96e9891e.json | add link to discussions | threejs/lessons/langinfo.hanson | @@ -7,6 +7,7 @@
link: 'http://threejsfundamentals.org/',
commentSectionHeader: `
<div>
+ <a href="https://github.com/gfxfundamentals/threejsfundamentals/discussions">Question</a>?
<a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=suggested+topic&template=suggest-topic.md&title=%5BSUGGESTION%5D">Suggestion</a>?
<a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=&template=request.md&title=">Request</a>?
<a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=bug+%2F+issue&template=bug-issue-report.md&title=">Issue</a>? | false |
Other | mrdoob | three.js | 34771f527b6ac72d6948623a23e2662a6bdb55b9.json | add Chinese version of chapter rendertargets | threejs/lessons/zh_cn/threejs-rendertargets.md | @@ -0,0 +1,148 @@
+Title: Three.js 渲染目标
+Description: 如何渲染到纹理
+TOC: 渲染目标
+
+在three.js中,渲染目标大体上指的是可以被渲染的纹理。当它被渲染之后,你可以像使用其他纹理一样使用它。
+
+让我们举个简单的例子。我们将从[the article on responsiveness](threejs-responsive.html)开始。
+
+渲染到渲染目标基本上跟通常的渲染一样。首先我们创建一个 `WebGLRenderTarget`。
+
+```js
+const rtWidth = 512;
+const rtHeight = 512;
+const renderTarget = new THREE.WebGLRenderTarget(rtWidth, rtHeight);
+```
+
+然后我们需要一个 `Camera` 和一个 `Scene`
+
+```js
+const rtFov = 75;
+const rtAspect = rtWidth / rtHeight;
+const rtNear = 0.1;
+const rtFar = 5;
+const rtCamera = new THREE.PerspectiveCamera(rtFov, rtAspect, rtNear, rtFar);
+rtCamera.position.z = 2;
+
+const rtScene = new THREE.Scene();
+rtScene.background = new THREE.Color('red');
+```
+
+注意我们设置长宽比(aspect)是相对渲染目标而言的,不是画布(canvas)。
+正确的长宽比取决于我们要渲染的对象。在本例,我们要将渲染目标的纹理用在方块的一个面,基于方块的面我们设置长宽比为1.0。
+
+我们将需要的东西添加到场景中。在本例我们使用灯光和三个方块[from the previous article](threejs-responsive.html)。
+
+```js
+{
+ const color = 0xFFFFFF;
+ const intensity = 1;
+ const light = new THREE.DirectionalLight(color, intensity);
+ light.position.set(-1, 2, 4);
+* rtScene.add(light);
+}
+
+const boxWidth = 1;
+const boxHeight = 1;
+const boxDepth = 1;
+const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
+
+function makeInstance(geometry, color, x) {
+ const material = new THREE.MeshPhongMaterial({color});
+
+ const cube = new THREE.Mesh(geometry, material);
+* rtScene.add(cube);
+
+ cube.position.x = x;
+
+ return cube;
+}
+
+*const rtCubes = [
+ makeInstance(geometry, 0x44aa88, 0),
+ makeInstance(geometry, 0x8844aa, -2),
+ makeInstance(geometry, 0xaa8844, 2),
+];
+```
+
+在上个例子中的 `Scene` 和 `Camera` 保持不变,我们将在画布中继续使用它们,只需要添加渲染的物体。
+
+让我们添加使用了渲染目标纹理的方块。
+
+```js
+const material = new THREE.MeshPhongMaterial({
+ map: renderTarget.texture,
+});
+const cube = new THREE.Mesh(geometry, material);
+scene.add(cube);
+```
+
+现在在渲染的时候,我们首先将渲染目标的场景(rtScene),渲染到渲染目标(注:这里有点绕,需要结合代码理解)。
+
+```js
+function render(time) {
+ time *= 0.001;
+
+ ...
+
+ // rotate all the cubes in the render target scene
+ rtCubes.forEach((cube, ndx) => {
+ const speed = 1 + ndx * .1;
+ const rot = time * speed;
+ cube.rotation.x = rot;
+ cube.rotation.y = rot;
+ });
+
+ // draw render target scene to render target
+ renderer.setRenderTarget(renderTarget);
+ renderer.render(rtScene, rtCamera);
+ renderer.setRenderTarget(null);
+```
+
+然后我们在画布中,渲染使用了渲染目标纹理的方块的场景。
+
+```js
+ // rotate the cube in the scene
+ cube.rotation.x = time;
+ cube.rotation.y = time * 1.1;
+
+ // render the scene to the canvas
+ renderer.render(scene, camera);
+```
+
+就是这样啦
+
+{{{example url="../threejs-render-target.html" }}}
+
+方块是红色的,这是因为我们设置了 `rtScene` 的 `background` 为红色,所以渲染目标的纹理所处的背景为红色。
+
+渲染目标可以用在各种各样的物体上。[Shadows](threejs-shadows.html)用了渲染目标,[Picking can use a render target](threejs-picking.html),多种效果[post processing effects](threejs-post-processing.html)需要用到渲染目标。
+渲染汽车的后视镜,或者3D场景中的监控实时画面,都可能用到渲染目标。
+
+关于 `WebGLRenderTarget` 的笔记。
+
+* 默认情况下 `WebGLRenderTarget` 会创建两个纹理。 颜色纹理和深度/模版纹理。如果你不需要深度或者模版纹理,你可以通过可选设置取消创建。例如:
+
+ ```js
+ const rt = new THREE.WebGLRenderTarget(width, height, {
+ depthBuffer: false,
+ stencilBuffer: false,
+ });
+ ```
+
+* 你可能需要改变渲染目标的尺寸
+
+ 在上面的例子,我们创建了固定尺寸512X512的渲染目标。对于像后处理,你通常需要创建跟画布一样尺寸的渲染目标。在我们的代码中意味着,当我们改变画布的尺寸,会同时更新渲染目标尺寸,和渲染目标中正在使用的摄像机。例如:
+
+ function render(time) {
+ time *= 0.001;
+
+ if (resizeRendererToDisplaySize(renderer)) {
+ const canvas = renderer.domElement;
+ camera.aspect = canvas.clientWidth / canvas.clientHeight;
+ camera.updateProjectionMatrix();
+
+ + renderTarget.setSize(canvas.width, canvas.height);
+ + rtCamera.aspect = camera.aspect;
+ + rtCamera.updateProjectionMatrix();
+ } | false |
Other | mrdoob | three.js | e5c645f8643ff3358309393f8e4852710a2ac97d.json | add Chinese version of the chapter Fog | threejs/lessons/zh_cn/threejs-fog.md | @@ -0,0 +1,214 @@
+Title: Three.js 雾
+Description: Three.js中的雾
+TOC: 雾
+
+本文是three.js系列文章的一部分。第一篇文章是[three.js 基础](threejs-fundamentals.html)。如果你是个新手,还没读过,请从那里开始。如果你还没读过有关摄像机的章节,请从[这篇文章](threejs-cameras.html)开始。
+
+在3D引擎里,雾通常是基于离摄像机的距离褪色至某种特定颜色的方式。在three.js中添加雾是通过创建 `Fog` 或者 `FogExp2` 实例并设定scene的[`fog`](Scene.fog) 属性。
+
+`Fog` 让你设定 `near` 和 `far` 属性,代表距离摄像机的距离。任何物体比 `near` 近不会受到影响,任何物体比 `far` 远则完全是雾的颜色。在 `near` 和 `far` 中间的物体,会从它们自身材料的颜色褪色到雾的颜色。
+
+`FogExp2` 会根据离摄像机的距离呈指数增长。
+
+选择其中一个类型,创建雾并设定到场景中如下:
+
+```js
+const scene = new THREE.Scene();
+{
+ const color = 0xFFFFFF; // white
+ const near = 10;
+ const far = 100;
+ scene.fog = new THREE.Fog(color, near, far);
+}
+```
+
+或者对于 `FogExp2` 会是:
+
+```js
+const scene = new THREE.Scene();
+{
+ const color = 0xFFFFFF;
+ const density = 0.1;
+ scene.fog = new THREE.FogExp2(color, density);
+}
+```
+
+`FogExp2` 比较接近现实效果,但是 `Fog` 使用的更加普遍,因为它支持设定影响区域,所以你可以设定一定距离内显示清晰的场景,过了这段距离再褪色到某种颜色。
+
+<div class="spread">
+ <div>
+ <div data-diagram="fog" style="height: 300px;"></div>
+ <div class="code">THREE.Fog</div>
+ </div>
+ <div>
+ <div data-diagram="fogExp2" style="height: 300px;"></div>
+ <div class="code">THREE.FogExp2</div>
+ </div>
+</div>
+
+需要注意的是雾是作用在 *渲染的物体* 上的,是物体颜色中每个像素计算的一部分。这意味着如果你想让你的场景褪色到某种颜色,你需要设定雾 **和** 场景的背景颜色为同一种颜色。背景颜色通过[`scene.background`](Scene.background)属性设置。你可以通过 `THREE.Color` 选择背景颜色设置。例如:
+
+```js
+scene.background = new THREE.Color('#F00'); // red
+```
+
+<div class="spread">
+ <div>
+ <div data-diagram="fogBlueBackgroundRed" style="height: 300px;" class="border"></div>
+ <div class="code">fog blue, background red</div>
+ </div>
+ <div>
+ <div data-diagram="fogBlueBackgroundBlue" style="height: 300px;" class="border"></div>
+ <div class="code">fog blue, background blue</div>
+ </div>
+</div>
+
+这是我们之前添加雾的例子。唯一的改动是在添加雾之后,我们设置了场景的背景颜色。
+
+```js
+const scene = new THREE.Scene();
+
++{
++ const near = 1;
++ const far = 2;
++ const color = 'lightblue';
++ scene.fog = new THREE.Fog(color, near, far);
++ scene.background = new THREE.Color(color);
++}
+```
+
+在下面的例子,摄像机的 `near` 是0.1, `far` 是5,位于 `z = 2`的位置。方块为单位大小,位于Z=0的位置。这意味着将雾设置为 `near = 1` 和 `far = 2` ,方块会在它的中间位置淡出。
+
+{{{example url="../threejs-fog.html" }}}
+
+让我们添加界面来调整雾。我们将再次使用[dat.GUI](https://github.com/dataarts/dat.gui)。dat.GUI接收对象和属性参数,并自动为其创建界面。我们能够简单地操纵雾的 `near` 和 `far` 属性,但是 `near` 数值大于 `far` 是无效的,所以我们创建助手(helper)来确保 `near` 和 `far` 属性,让 `near` 小于或等于 `far` , `far` 大于或等于 `near`。
+
+```js
+// We use this class to pass to dat.gui
+// so when it manipulates near or far
+// near is never > far and far is never < near
+class FogGUIHelper {
+ constructor(fog) {
+ this.fog = fog;
+ }
+ get near() {
+ return this.fog.near;
+ }
+ set near(v) {
+ this.fog.near = v;
+ this.fog.far = Math.max(this.fog.far, v);
+ }
+ get far() {
+ return this.fog.far;
+ }
+ set far(v) {
+ this.fog.far = v;
+ this.fog.near = Math.min(this.fog.near, v);
+ }
+}
+```
+
+之后我们可以像这样添加
+
+```js
+{
+ const near = 1;
+ const far = 2;
+ const color = 'lightblue';
+ scene.fog = new THREE.Fog(color, near, far);
+ scene.background = new THREE.Color(color);
++
++ const fogGUIHelper = new FogGUIHelper(scene.fog);
++ gui.add(fogGUIHelper, 'near', near, far).listen();
++ gui.add(fogGUIHelper, 'far', near, far).listen();
+}
+```
+
+当我们设置摄像机的时候,设置(助手的 `near` 和 `far` 以调节雾的最小值和最大值。
+
+最后两行调用 `.listen()` 告诉dat.GUI *监听* 变化。当我们编辑 `far` 改变了 `near` 或者编辑 `near` 改变了 `far` ,dat.GUI将会为我们更新其他属性的UI。
+
+或许能够改变雾的颜色是个不错的主意,但是如上面提到的,我们需要保持雾的颜色和背景颜色一致。所以,让我们在助手上添加另一个 *虚拟* 属性,当dat.GUI改变它时会设置这两个颜色。
+
+dat.GUI能够通过4种方式设置颜色。分别是6位hex字符串 (如: `#112233`),色相、饱和度、明度的对象 (如: `{h: 60, s: 1, v: }`),RGB数组 (如: `[255, 128, 64]`),或者RGBA数组 (如: `[127, 200, 75, 0.3]`)。
+
+对于我们的目的而言,最简单的是用hex字符串的方式,因为dat.GUI只修改单个数值。幸运的是通过 `THREE.Color` 的 [`getHexString`](Color.getHexString) 方法我们能轻松地获得这个字符串,只需要在其前面添加 '#' 。
+
+```js
+// We use this class to pass to dat.gui
+// so when it manipulates near or far
+// near is never > far and far is never < near
++// Also when dat.gui manipulates color we'll
++// update both the fog and background colors.
+class FogGUIHelper {
+* constructor(fog, backgroundColor) {
+ this.fog = fog;
++ this.backgroundColor = backgroundColor;
+ }
+ get near() {
+ return this.fog.near;
+ }
+ set near(v) {
+ this.fog.near = v;
+ this.fog.far = Math.max(this.fog.far, v);
+ }
+ get far() {
+ return this.fog.far;
+ }
+ set far(v) {
+ this.fog.far = v;
+ this.fog.near = Math.min(this.fog.near, v);
+ }
++ get color() {
++ return `#${this.fog.color.getHexString()}`;
++ }
++ set color(hexString) {
++ this.fog.color.set(hexString);
++ this.backgroundColor.set(hexString);
++ }
+}
+```
+
+然后我们调用 `gui.addColor` 来为我们的助手虚拟属性添加颜色界面。
+
+```js
+{
+ const near = 1;
+ const far = 2;
+ const color = 'lightblue';
+ scene.fog = new THREE.Fog(color, near, far);
+ scene.background = new THREE.Color(color);
+
+* const fogGUIHelper = new FogGUIHelper(scene.fog, scene.background);
+ gui.add(fogGUIHelper, 'near', near, far).listen();
+ gui.add(fogGUIHelper, 'far', near, far).listen();
++ gui.addColor(fogGUIHelper, 'color');
+}
+```
+
+{{{example url="../threejs-fog-gui.html" }}}
+
+你可以观察到,设置 `near` 如1.9, `far` 为2.0能在未雾化和完全雾化之间获得锐利的变化效果,而设置 `near` = 1.1, `far` = 2.9 会让我们旋转的方块在距离摄像机2个单位距离的位置获得最平滑的变化效果。
+
+最后, [`fog`](Material.fog) 在材料上有个布尔属性,用来设置渲染物体的材料是否会受到雾的影响。对于大多数材料而言默认设置为 `true` ,作为你可能想关掉雾生效的例子,设想下你正在制作一个3D车辆模拟器并处于驾驶员座位或座舱的视角,你很可能为了看清车内的物体将它们的是否受雾影响属性关闭。
+
+一个更好的例子会是一个外面弥漫浓雾的房子。让我们假设将雾设置在2米外 (near = 2) 并且在4米的地方完全进入雾中 (far = 4)。房间大于2米并且很可能大于4米,那么你需要将房子内的材质设置为不受雾的影响,否则当站在房子内尽头往墙壁外看会觉得房子是在雾里。
+
+<div class="spread">
+ <div>
+ <div data-diagram="fogHouseAll" style="height: 300px;" class="border"></div>
+ <div class="code">fog: true, all</div>
+ </div>
+</div>
+
+注意房间尽头的墙壁和天花板正受到雾的影响,当我们把房子材料上的是否受雾影响属性关闭可以解决这个问题。
+
+<div class="spread">
+ <div>
+ <div data-diagram="fogHouseInsideNoFog" style="height: 300px;" class="border"></div>
+ <div class="code">fog: true, only outside materials</div>
+ </div>
+</div>
+
+<canvas id="c"></canvas>
+<script type="module" src="resources/threejs-fog.js"></script> | false |
Other | mrdoob | three.js | 1c210f21e38aee732f8a5187e4239ed9127b027a.json | fix typo on text geometry primitive | threejs/lessons/threejs-primitives.md | @@ -31,7 +31,7 @@ parameters so you can use more or less depending on your needs.
<div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">A dodecahedron (12 sides)</div>
<div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">An extruded 2d shape with optional bevelling.
Here we are extruding a heart shape. Note this is the basis
-for <code>TextGeometry</code> and <code>TextGeometry</code> respectively.</div>
+for <code>TextGeometry</code>.</div>
<div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">An icosahedron (20 sides)</div>
<div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">A shape generated by spinning a line. Examples would be: lamps, bowling pins, candles, candle holders, wine glasses, drinking glasses, etc... You provide the 2d silhouette as series of points and then tell three.js how many subdivisions to make as it spins the silhouette around an axis.</div>
<div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">An Octahedron (8 sides)</div> | false |
Other | mrdoob | three.js | be001a3b6492255ee35c8c40d1ecd6398db8a88c.json | remove double reference | threejs/lessons/threejs-textures.md | @@ -97,9 +97,9 @@ It works!
{{{example url="../threejs-textured-cube-6-textures.html" }}}
It should be noted though that not all geometry types supports multiple
-materials. `BoxGeometry` and `BoxGeometry` can use 6 materials one for each face.
-`ConeGeometry` and `ConeGeometry` can use 2 materials, one for the bottom and one for the cone.
-`CylinderGeometry` and `CylinderGeometry` can use 3 materials, bottom, top, and side.
+materials. `BoxGeometry` can use 6 materials one for each face.
+`ConeGeometry` can use 2 materials, one for the bottom and one for the cone.
+`CylinderGeometry` can use 3 materials, bottom, top, and side.
For other cases you will need to build or load custom geometry and/or modify texture coordinates.
It's far more common in other 3D engines and far more performant to use a
@@ -340,7 +340,7 @@ Now, when the cube is drawn so small that it's only 1 or 2 pixels large the GPU
to use just the smallest or next to smallest mip level to decide what color to make the
tiny cube.
-In three you can choose what happens both when the texture is drawn
+In three.js you can choose what happens both when the texture is drawn
larger than its original size and what happens when it's drawn smaller than its
original size.
| false |
Other | mrdoob | three.js | 2db5c64849502534e2e96e7afb328e6b4b3839be.json | add more translation in fundamentals | threejs/lessons/tr/threejs-fundamentals.md | @@ -4,24 +4,19 @@ TOC: Temel Bilgiler
Bu three.js ile alakalı makale serisindeki ilk makaledir. [Three.js](https://threejs.org) bir web sayfasına 3D içerik sağlamayı mümkün olduğunca kolaylaştırmaya çalışan bir 3D kütüphanedir.
-Three.js sıklıkla WebGL ile karıştırılır fakat her zaman değil, three.js 3D çizim için WebGL kullanır.
+Three.js her zaman olmasa da öncesine göre daha sıklıkla WebGl ile karıştırılır, three.js 3D çizim için WebGL kullanır.
[WebGL yalnızca noktalar, çizgiler ve üçgenler çizen çok düşük seviyeli bir sistemdir](https://webglfundamentals.org).
WebGL ile herhangi yararlı bir şey yapmak birazcık kod gerektirir ve three.js burada devreye girer.
Sahneler, ışıklar, gölgeler, malzemeler, dokular, 3d matematik gibi şeyleri halleder, eğer direkt olarak WebGL kullansaydınız bunların hepsini kendiniz yazmak zorunda kalırdınız.
-These tutorials assume you already know JavaScript and, for the
-most part they will use ES6 style. [See here for a
-terse list of things you're expected to already know](threejs-prerequisites.html).
-Most browsers that support three.js are auto-updated so most users should
-be able to run this code. If you'd like to make this code run
-on really old browsers look into a transpiler like [Babel](https://babeljs.io).
-Of course users running really old browsers probably have machines
-that can't run three.js.
-
-When learning most programming languages the first thing people
-do is make the computer print `"Hello World!"`. For 3D one
-of the most common first things to do is to make a 3D cube.
-So let's start with "Hello Cube!"
+Bu dersler halihazırda Javascript bildiğinizi varsayar ve çoğu bölümünde ES6 stilini kullanacaklar. [Halihazırda bilmenizin beklendiği şeylerin kısa listesine buradan bakabilirsiniz](threejs-prerequisites.html).
+Three.js'i destekleyen çoğu tarayıcı otomatik olarak desteklendiğinden çoğu kullanıcı bu kodu çalıştırabilir. Eğer bu kodu gerçekten eski tarayıcılarda çalıştırmak istiyorsanız [Babel](https://babeljs.io) gibi bir aktarıcıya bakın.
+Elbette gerçekten eski tarayıcılarda çalışan kullanıcıların makineleri muhtemelen three.js'i çalıştırmayacaktır.
+
+Çoğu programlama dilini öğrenirken insanların ilk yaptığı şey
+bilgisayara `"Hello World!"` yazısını yazdırmaktır.
+3D için ise en yaygın olarak yapılan ilk şeylerden biri 3D bir küp yapmaktır.
+Öyleyse gelin "Hello Cube!" ile başlayalım!
Before we get started let's try to give you an idea of the structure
of a three.js app. A three.js app requires you to create a bunch of | false |
Other | mrdoob | three.js | ae864f9071aa67d640c8d43b82ed94241f32baa4.json | add fundamentals translation | threejs/lessons/tr/threejs-fundamentals.md | @@ -0,0 +1,488 @@
+Title: Three.js Temelleri
+Description: Temeller ile birlikte ilk Three.js dersiniz
+TOC: Temel Bilgiler
+
+Bu three.js ile alakalı makale serisindeki ilk makaledir. [Three.js](https://threejs.org) bir web sayfasına 3D içerik sağlamayı mümkün olduğunca kolaylaştırmaya çalışan bir 3D kütüphanedir.
+
+Three.js sıklıkla WebGL ile karıştırılır fakat her zaman değil, three.js 3D çizim için WebGL kullanır.
+[WebGL yalnızca noktalar, çizgiler ve üçgenler çizen çok düşük seviyeli bir sistemdir](https://webglfundamentals.org).
+WebGL ile herhangi yararlı bir şey yapmak birazcık kod gerektirir ve three.js burada devreye girer.
+Sahneler, ışıklar, gölgeler, malzemeler, dokular, 3d matematik gibi şeyleri halleder, eğer direkt olarak WebGL kullansaydınız bunların hepsini kendiniz yazmak zorunda kalırdınız.
+
+These tutorials assume you already know JavaScript and, for the
+most part they will use ES6 style. [See here for a
+terse list of things you're expected to already know](threejs-prerequisites.html).
+Most browsers that support three.js are auto-updated so most users should
+be able to run this code. If you'd like to make this code run
+on really old browsers look into a transpiler like [Babel](https://babeljs.io).
+Of course users running really old browsers probably have machines
+that can't run three.js.
+
+When learning most programming languages the first thing people
+do is make the computer print `"Hello World!"`. For 3D one
+of the most common first things to do is to make a 3D cube.
+So let's start with "Hello Cube!"
+
+Before we get started let's try to give you an idea of the structure
+of a three.js app. A three.js app requires you to create a bunch of
+objects and connect them together. Here's a diagram that represents
+a small three.js app
+
+<div class="threejs_center"><img src="resources/images/threejs-structure.svg" style="width: 768px;"></div>
+
+Things to notice about the diagram above.
+
+* There is a `Renderer`. This is arguably the main object of three.js. You pass a
+ `Scene` and a `Camera` to a `Renderer` and it renders (draws) the portion of
+ the 3D scene that is inside the *frustum* of the camera as a 2D image to a
+ canvas.
+
+* There is a [scenegraph](threejs-scenegraph.html) which is a tree like
+ structure, consisting of various objects like a `Scene` object, multiple
+ `Mesh` objects, `Light` objects, `Group`, `Object3D`, and `Camera` objects. A
+ `Scene` object defines the root of the scenegraph and contains properties like
+ the background color and fog. These objects define a hierarchical parent/child
+ tree like structure and represent where objects appear and how they are
+ oriented. Children are positioned and oriented relative to their parent. For
+ example the wheels on a car might be children of the car so that moving and
+ orienting the car's object automatically moves the wheels. You can read more
+ about this in [the article on scenegraphs](threejs-scenegraph.html).
+
+ Note in the diagram `Camera` is half in half out of the scenegraph. This is to
+ represent that in three.js, unlike the other objects, a `Camera` does not have
+ to be in the scenegraph to function. Just like other objects, a `Camera`, as a
+ child of some other object, will move and orient relative to its parent object.
+ There is an example of putting multiple `Camera` objects in a scenegraph at
+ the end of [the article on scenegraphs](threejs-scenegraph.html).
+
+* `Mesh` objects represent drawing a specific `Geometry` with a specific
+ `Material`. Both `Material` objects and `Geometry` objects can be used by
+ multiple `Mesh` objects. For example to draw two blue cubes in different
+ locations we could need two `Mesh` objects to represent the position and
+ orientation of each cube. We would only need one `Geometry` to hold the vertex
+ data for a cube and we would only need one `Material` to specify the color
+ blue. Both `Mesh` objects could reference the same `Geometry` object and the
+ same `Material` object.
+
+* `Geometry` objects represent the vertex data of some piece of geometry like
+ a sphere, cube, plane, dog, cat, human, tree, building, etc...
+ Three.js provides many kinds of built in
+ [geometry primitives](threejs-primitives.html). You can also
+ [create custom geometry](threejs-custom-buffergeometry.html) as well as
+ [load geometry from files](threejs-load-obj.html).
+
+* `Material` objects represent
+ [the surface properties used to draw geometry](threejs-materials.html)
+ including things like the color to use and how shiny it is. A `Material` can also
+ reference one or more `Texture` objects which can be used, for example,
+ to wrap an image onto the surface of a geometry.
+
+* `Texture` objects generally represent images either [loaded from image files](threejs-textures.html),
+ [generated from a canvas](threejs-canvas-textures.html) or [rendered from another scene](threejs-rendertargets.html).
+
+* `Light` objects represent [different kinds of lights](threejs-lights.html).
+
+Given all of that we're going to make the smallest *"Hello Cube"* setup
+that looks like this
+
+<div class="threejs_center"><img src="resources/images/threejs-1cube-no-light-scene.svg" style="width: 500px;"></div>
+
+First let's load three.js
+
+```html
+<script type="module">
+import * as THREE from './resources/threejs/r125/build/three.module.js';
+</script>
+```
+
+It's important you put `type="module"` in the script tag. This enables
+us to use the `import` keyword to load three.js. There are other ways
+to load three.js but as of r106 using modules is the recommended way.
+Modules have the advantage that they can easily import other modules
+they need. That saves us from having to manually load extra scripts
+they are dependent on.
+
+Next we need is a `<canvas>` tag so...
+
+```html
+<body>
+ <canvas id="c"></canvas>
+</body>
+```
+
+We will ask three.js to draw into that canvas so we need to look it up.
+
+```html
+<script type="module">
+import * as THREE from './resources/threejs/r125/build/three.module.js';
+
++function main() {
++ const canvas = document.querySelector('#c');
++ const renderer = new THREE.WebGLRenderer({canvas});
++ ...
+</script>
+```
+
+After we look up the canvas we create a `WebGLRenderer`. The renderer
+is the thing responsible for actually taking all the data you provide
+and rendering it to the canvas. In the past there have been other renderers
+like `CSSRenderer`, a `CanvasRenderer` and in the future there may be a
+`WebGL2Renderer` or `WebGPURenderer`. For now there's the `WebGLRenderer`
+that uses WebGL to render 3D to the canvas.
+
+Note there are some esoteric details here. If you don't pass a canvas
+into three.js it will create one for you but then you have to add it
+to your document. Where to add it may change depending on your use case
+and you'll have to change your code so I find that passing a canvas
+to three.js feels a little more flexible. I can put the canvas anywhere
+and the code will find it whereas if I had code to insert the canvas
+into to the document I'd likely have to change that code if my use case
+changed.
+
+Next up we need a camera. We'll create a `PerspectiveCamera`.
+
+```js
+const fov = 75;
+const aspect = 2; // the canvas default
+const near = 0.1;
+const far = 5;
+const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
+```
+
+`fov` is short for `field of view`. In this case 75 degrees in the vertical
+dimension. Note that most angles in three.js are in radians but for some
+reason the perspective camera takes degrees.
+
+`aspect` is the display aspect of the canvas. We'll go over the details
+[in another article](threejs-responsive.html) but by default a canvas is
+ 300x150 pixels which makes the aspect 300/150 or 2.
+
+`near` and `far` represent the space in front of the camera
+that will be rendered. Anything before that range or after that range
+will be clipped (not drawn).
+
+Those four settings define a *"frustum"*. A *frustum* is the name of
+a 3d shape that is like a pyramid with the tip sliced off. In other
+words think of the word "frustum" as another 3D shape like sphere,
+cube, prism, frustum.
+
+<img src="resources/frustum-3d.svg" width="500" class="threejs_center"/>
+
+The height of the near and far planes are determined by the field of view.
+The width of both planes is determined by the field of view and the aspect.
+
+Anything inside the defined frustum will be be drawn. Anything outside
+will not.
+
+The camera defaults to looking down the -Z axis with +Y up. We'll put our cube
+at the origin so we need to move the camera back a little from the origin
+in order to see anything.
+
+```js
+camera.position.z = 2;
+```
+
+Here's what we're aiming for.
+
+<img src="resources/scene-down.svg" width="500" class="threejs_center"/>
+
+In the diagram above we can see our camera is at `z = 2`. It's looking
+down the -Z axis. Our frustum starts 0.1 units from the front of the camera
+and goes to 5 units in front of the camera. Because in this diagram we are looking down,
+the field of view is affected by the aspect. Our canvas is twice as wide
+as it is tall so across the canvas the field of view will be much wider than
+our specified 75 degrees which is the vertical field of view.
+
+Next we make a `Scene`. A `Scene` in three.js is the root of a form of scene graph.
+Anything you want three.js to draw needs to be added to the scene. We'll
+cover more details of [how scenes work in a future article](threejs-scenegraph.html).
+
+```js
+const scene = new THREE.Scene();
+```
+
+Next up we create a `BoxGeometry` which contains the data for a box.
+Almost anything we want to display in Three.js needs geometry which defines
+the vertices that make up our 3D object.
+
+```js
+const boxWidth = 1;
+const boxHeight = 1;
+const boxDepth = 1;
+const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
+```
+
+We then create a basic material and set its color. Colors can
+be specified using standard CSS style 6 digit hex color values.
+
+```js
+const material = new THREE.MeshBasicMaterial({color: 0x44aa88});
+```
+
+We then create a `Mesh`. A `Mesh` in three represents the combination
+of a three things
+
+1. A `Geometry` (the shape of the object)
+2. A `Material` (how to draw the object, shiny or flat, what color, what texture(s) to apply. Etc.)
+3. The position, orientation, and scale of that object in the scene relative to its parent. In the code below that parent is the scene.
+
+```js
+const cube = new THREE.Mesh(geometry, material);
+```
+
+And finally we add that mesh to the scene
+
+```js
+scene.add(cube);
+```
+
+We can then render the scene by calling the renderer's render function
+and passing it the scene and the camera
+
+```js
+renderer.render(scene, camera);
+```
+
+Here's a working example
+
+{{{example url="../threejs-fundamentals.html" }}}
+
+It's kind of hard to tell that is a 3D cube since we're viewing
+it directly down the -Z axis and the cube itself is axis aligned
+so we're only seeing a single face.
+
+Let's animate it spinning and hopefully that will make
+it clear it's being drawn in 3D. To animate it we'll render inside a render loop using
+[`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame).
+
+Here's our loop
+
+```js
+function render(time) {
+ time *= 0.001; // convert time to seconds
+
+ cube.rotation.x = time;
+ cube.rotation.y = time;
+
+ renderer.render(scene, camera);
+
+ requestAnimationFrame(render);
+}
+requestAnimationFrame(render);
+```
+
+`requestAnimationFrame` is a request to the browser that you want to animate something.
+You pass it a function to be called. In our case that function is `render`. The browser
+will call your function and if you update anything related to the display of the
+page the browser will re-render the page. In our case we are calling three's
+`renderer.render` function which will draw our scene.
+
+`requestAnimationFrame` passes the time since the page loaded to
+our function. That time is passed in milliseconds. I find it's much
+easier to work with seconds so here we're converting that to seconds.
+
+We then set the cube's X and Y rotation to the current time. These rotations
+are in [radians](https://en.wikipedia.org/wiki/Radian). There are 2 pi radians
+in a circle so our cube should turn around once on each axis in about 6.28
+seconds.
+
+We then render the scene and request another animation frame to continue
+our loop.
+
+Outside the loop we call `requestAnimationFrame` one time to start the loop.
+
+{{{example url="../threejs-fundamentals-with-animation.html" }}}
+
+It's a little better but it's still hard to see the 3d. What would help is to
+add some lighting so let's add a light. There are many kinds of lights in
+three.js which we'll go over in [a future article](threejs-lights.html). For now let's create a directional light.
+
+```js
+{
+ const color = 0xFFFFFF;
+ const intensity = 1;
+ const light = new THREE.DirectionalLight(color, intensity);
+ light.position.set(-1, 2, 4);
+ scene.add(light);
+}
+```
+
+Directional lights have a position and a target. Both default to 0, 0, 0. In our
+case we're setting the light's position to -1, 2, 4 so it's slightly on the left,
+above, and behind our camera. The target is still 0, 0, 0 so it will shine
+toward the origin.
+
+We also need to change the material. The `MeshBasicMaterial` is not affected by
+lights. Let's change it to a `MeshPhongMaterial` which is affected by lights.
+
+```js
+-const material = new THREE.MeshBasicMaterial({color: 0x44aa88}); // greenish blue
++const material = new THREE.MeshPhongMaterial({color: 0x44aa88}); // greenish blue
+```
+
+Here is our new program structure
+
+<div class="threejs_center"><img src="resources/images/threejs-1cube-with-directionallight.svg" style="width: 500px;"></div>
+
+And here it is working.
+
+{{{example url="../threejs-fundamentals-with-light.html" }}}
+
+It should now be pretty clearly 3D.
+
+Just for the fun of it let's add 2 more cubes.
+
+We'll use the same geometry for each cube but make a different
+material so each cube can be a different color.
+
+First we'll make a function that creates a new material
+with the specified color. Then it creates a mesh using
+the specified geometry and adds it to the scene and
+sets its X position.
+
+```js
+function makeInstance(geometry, color, x) {
+ const material = new THREE.MeshPhongMaterial({color});
+
+ const cube = new THREE.Mesh(geometry, material);
+ scene.add(cube);
+
+ cube.position.x = x;
+
+ return cube;
+}
+```
+
+Then we'll call it 3 times with 3 different colors and X positions
+saving the `Mesh` instances in an array.
+
+```js
+const cubes = [
+ makeInstance(geometry, 0x44aa88, 0),
+ makeInstance(geometry, 0x8844aa, -2),
+ makeInstance(geometry, 0xaa8844, 2),
+];
+```
+
+Finally we'll spin all 3 cubes in our render function. We
+compute a slightly different rotation for each one.
+
+```js
+function render(time) {
+ time *= 0.001; // convert time to seconds
+
+ cubes.forEach((cube, ndx) => {
+ const speed = 1 + ndx * .1;
+ const rot = time * speed;
+ cube.rotation.x = rot;
+ cube.rotation.y = rot;
+ });
+
+ ...
+```
+
+and here's that.
+
+{{{example url="../threejs-fundamentals-3-cubes.html" }}}
+
+If you compare it to the top down diagram above you can see
+it matches our expectations. With cubes at X = -2 and X = +2
+they are partially outside our frustum. They are also
+somewhat exaggeratedly warped since the field of view
+across the canvas is so extreme.
+
+Our program now has this structure
+
+<div class="threejs_center"><img src="resources/images/threejs-3cubes-scene.svg" style="width: 610px;"></div>
+
+As you can see we have 3 `Mesh` objects each referencing the same `BoxGeometry`.
+Each `Mesh` references a unique `MeshPhongMaterial` so that each cube can have
+a different color.
+
+I hope this short intro helps to get things started. [Next up we'll cover
+making our code responsive so it is adaptable to multiple situations](threejs-responsive.html).
+
+<div id="es6" class="threejs_bottombar">
+<h3>es6 modules, three.js, and folder structure</h3>
+<p>As of version r106 the preferred way to use three.js is via <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">es6 modules</a>.</p>
+<p>
+es6 modules can be loaded via the <code>import</code> keyword in a script
+or inline via a <code><script type="module"></code> tag. Here's an example of
+both
+</p>
+<pre class=prettyprint>
+<script type="module">
+import * as THREE from './resources/threejs/r125/build/three.module.js';
+
+...
+
+</script>
+</pre>
+<p>
+Paths must be absolute or relative. Relative paths always start with <code>./</code> or <code>../</code>
+which is different than other tags like <code><img></code> and <code><a></code>.
+</p>
+<p>
+References to the same script will only be loaded once as long as their absolute paths
+are exactly the same. For three.js this means it's required that you put all the examples
+libraries in the correct folder structure
+</p>
+<pre class="dos">
+someFolder
+ |
+ ├-build
+ | |
+ | +-three.module.js
+ |
+ +-examples
+ |
+ +-jsm
+ |
+ +-controls
+ | |
+ | +-OrbitControls.js
+ | +-TrackballControls.js
+ | +-...
+ |
+ +-loaders
+ | |
+ | +-GLTFLoader.js
+ | +-...
+ |
+ ...
+</pre>
+<p>
+The reason this folder structure is required is because the scripts in the
+examples like <a href="https://github.com/mrdoob/three.js/blob/master/examples/jsm/controls/OrbitControls.js"><code>OrbitControls.js</code></a>
+have hard coded relative paths like
+</p>
+<pre class="prettyprint">
+import * as THREE from '../../../build/three.module.js';
+</pre>
+<p>
+Using the same structure assures then when you import both three and one of the example
+libraries they'll both reference the same <code>three.module.js</code> file.
+</p>
+<pre class="prettyprint">
+import * as THREE from './someFolder/build/three.module.js';
+import {OrbitControls} from './someFolder/examples/jsm/controls/OrbitControls.js';
+</pre>
+<p>This includes when using a CDN. Be sure your path to <code>three.module.js</code> ends with
+<code>/build/three.modules.js</code>. For example</p>
+<pre class="prettyprint">
+import * as THREE from 'https://unpkg.com/three@0.108.0<b>/build/three.module.js</b>';
+import {OrbitControls} from 'https://unpkg.com/three@0.108.0/examples/jsm/controls/OrbitControls.js';
+</pre>
+<p>If you'd prefer the old <code><script src="path/to/three.js"></script></code> style
+you can check out <a href="https://r105.threejsfundamentals.org">an older version of this site</a>.
+Three.js has a policy of not worrying about backward compatibility. They expect you to use a specific
+version, as in you're expected to download the code and put it in your project. When upgrading to a newer version
+you can read the <a href="https://github.com/mrdoob/three.js/wiki/Migration-Guide">migration guide</a> to
+see what you need to change. It would be too much work to maintain both an es6 module and a class script
+version of this site so going forward this site will only show es6 module style. As stated elsewhere,
+to support legacy browsers look into a <a href="https://babeljs.io">transpiler</a>.</p>
+</div>
+
+<!-- needed in English only to prevent warning from outdated translations -->
+<a href="threejs-geometry.html"></a>
+<a href="Geometry"></a>
\ No newline at end of file | false |
Other | mrdoob | three.js | 2fa471bcf7a5282f019ff7d0b2cd5fa655143c60.json | remove call to helper.update | threejs/lessons/ja/threejs-lights.md | @@ -478,13 +478,13 @@ GUIも調整してみましょう。
const gui = new GUI();
gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
gui.add(light, 'intensity', 0, 10, 0.01);
-gui.add(light, 'width', 0, 20).onChange(updateLight);
-gui.add(light, 'height', 0, 20).onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation').onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation').onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation').onChange(updateLight);
+gui.add(light, 'width', 0, 20);
+gui.add(light, 'height', 0, 20);
+gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation');
+gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation');
+gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation');
-makeXYZGUI(gui, light.position, 'position', updateLight);
+makeXYZGUI(gui, light.position, 'position');
```
そして、これが結果です。 | true |
Other | mrdoob | three.js | 2fa471bcf7a5282f019ff7d0b2cd5fa655143c60.json | remove call to helper.update | threejs/lessons/kr/threejs-lights.md | @@ -490,13 +490,13 @@ scene.add(light);
const gui = new GUI();
gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
gui.add(light, 'intensity', 0, 10, 0.01);
-gui.add(light, 'width', 0, 20).onChange(updateLight);
-gui.add(light, 'height', 0, 20).onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation').onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation').onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation').onChange(updateLight);
+gui.add(light, 'width', 0, 20);
+gui.add(light, 'height', 0, 20);
+gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation');
+gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation');
+gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation');
-makeXYZGUI(gui, light.position, 'position', updateLight);
+makeXYZGUI(gui, light.position, 'position');
```
{{{example url="../threejs-lights-rectarea.html" }}} | true |
Other | mrdoob | three.js | 2fa471bcf7a5282f019ff7d0b2cd5fa655143c60.json | remove call to helper.update | threejs/lessons/ru/threejs-lights.md | @@ -510,13 +510,13 @@ scene.add(helper);
const gui = new GUI();
gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
gui.add(light, 'intensity', 0, 10, 0.01);
-gui.add(light, 'width', 0, 20).onChange(updateLight);
-gui.add(light, 'height', 0, 20).onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation').onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation').onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation').onChange(updateLight);
+gui.add(light, 'width', 0, 20);
+gui.add(light, 'height', 0, 20);
+gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation');
+gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation');
+gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation');
-makeXYZGUI(gui, light.position, 'position', updateLight);
+makeXYZGUI(gui, light.position, 'position');
```
И вот что. | true |
Other | mrdoob | three.js | 2fa471bcf7a5282f019ff7d0b2cd5fa655143c60.json | remove call to helper.update | threejs/lessons/threejs-lights.md | @@ -522,13 +522,13 @@ its `width` and `height`
const gui = new GUI();
gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
gui.add(light, 'intensity', 0, 10, 0.01);
-gui.add(light, 'width', 0, 20).onChange(updateLight);
-gui.add(light, 'height', 0, 20).onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation').onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation').onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation').onChange(updateLight);
+gui.add(light, 'width', 0, 20);
+gui.add(light, 'height', 0, 20);
+gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation');
+gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation');
+gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation');
-makeXYZGUI(gui, light.position, 'position', updateLight);
+makeXYZGUI(gui, light.position, 'position');
```
And here is that. | true |
Other | mrdoob | three.js | 2fa471bcf7a5282f019ff7d0b2cd5fa655143c60.json | remove call to helper.update | threejs/lessons/zh_cn/threejs-lights.md | @@ -432,13 +432,13 @@ scene.add(light);
const gui = new GUI();
gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
gui.add(light, 'intensity', 0, 10, 0.01);
-gui.add(light, 'width', 0, 20).onChange(updateLight);
-gui.add(light, 'height', 0, 20).onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation').onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation').onChange(updateLight);
-gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation').onChange(updateLight);
+gui.add(light, 'width', 0, 20);
+gui.add(light, 'height', 0, 20);
+gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation');
+gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation');
+gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation');
-makeXYZGUI(gui, light.position, 'position', updateLight);
+makeXYZGUI(gui, light.position, 'position');
```
场景如下所示: | true |
Other | mrdoob | three.js | 2fa471bcf7a5282f019ff7d0b2cd5fa655143c60.json | remove call to helper.update | threejs/threejs-lights-rectarea.html | @@ -132,20 +132,16 @@
const helper = new RectAreaLightHelper(light);
light.add(helper);
- function updateLight() {
- helper.update();
- }
-
const gui = new GUI();
gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
gui.add(light, 'intensity', 0, 10, 0.01);
- gui.add(light, 'width', 0, 20).onChange(updateLight);
- gui.add(light, 'height', 0, 20).onChange(updateLight);
- gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation').onChange(updateLight);
- gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation').onChange(updateLight);
- gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation').onChange(updateLight);
+ gui.add(light, 'width', 0, 20);
+ gui.add(light, 'height', 0, 20);
+ gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation');
+ gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation');
+ gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation');
- makeXYZGUI(gui, light.position, 'position', updateLight);
+ makeXYZGUI(gui, light.position, 'position');
}
function resizeRendererToDisplaySize(renderer) { | true |
Other | mrdoob | three.js | 80d4d22e0bda20d6a2a5f6003b3237f34334d240.json | remove stackoverflow q? links | threejs/lessons/fr/langinfo.hanson | @@ -5,7 +5,9 @@
title: 'Three.js, notions de base',
description: 'Apprendre à utiliser Three.js.',
link: 'http://threejsfundamentals.org/',
- commentSectionHeader: '<div>Questions ? <a href="http://stackoverflow.com/questions/tagged/three.js">Les poser sur stackoverflow</a>.</div>\n <div>Problèmes / bug ? <a href="http://github.com/gfxfundamentals/threejsfundamentals/issues">Les reporter sur github</a>.</div>',
+ commentSectionHeader: `
+ <div>Problèmes / bug ? <a href="http://github.com/gfxfundamentals/threejsfundamentals/issues">Les reporter sur github</a>.</div>
+ `,
missing: "Désolé, cet article n'a pas encore été traduit. [Les traductions sont le bienvenue](https://github.com/gfxfundamentals/threejsfundamentals)! 😄\n\n[Voici l'article anglais originel pour le moment]({{{origLink}}}).",
toc: 'Table des matières',
categoryMapping: { | true |
Other | mrdoob | three.js | 80d4d22e0bda20d6a2a5f6003b3237f34334d240.json | remove stackoverflow q? links | threejs/lessons/ja/langinfo.hanson | @@ -5,7 +5,9 @@
title: 'Three Fundamentals',
description: 'Three.jsを学習する',
link: 'http://threejsfundamentals.org/threejs/lessons/ja',
- commentSectionHeader: '<div>質問はありますか? <a href="http://stackoverflow.com/questions/tagged/three.js">何かあればstackoverflowで尋ねて下さい</a>.</div>\n <div>Issue/Bug? <a href="http://github.com/greggman/threefundamentals/issues">またはgithubでissueを作って下さい</a>.</div>',
+ commentSectionHeader: `
+ <div>Issue/Bug? <a href="http://github.com/greggman/threefundamentals/issues">またはgithubでissueを作って下さい</a>.</div>
+ `,
missing: 'すいません、この記事はまだ翻訳してません. [Translations Welcome](https://github.com/gfxfundamentals/threejsfundamentals)! 😄\n\n[ここに元の英語の記事があります]({{{origLink}}}).',
toc: '目次',
categoryMapping: { | true |
Other | mrdoob | three.js | 80d4d22e0bda20d6a2a5f6003b3237f34334d240.json | remove stackoverflow q? links | threejs/lessons/kr/langinfo.hanson | @@ -7,8 +7,6 @@
link: 'http://threejsfundamentals.org/',
commentSectionHeader: `
<div>
- <a href="http://stackoverflow.com/questions/tagged/three.js">Stackoverflow</a>
- /
<a href="http://github.com/greggman/threefundamentals/issues">Github</a>
</div>
`, | true |
Other | mrdoob | three.js | 80d4d22e0bda20d6a2a5f6003b3237f34334d240.json | remove stackoverflow q? links | threejs/lessons/langinfo.hanson | @@ -6,7 +6,6 @@
description: 'Learn Three.js',
link: 'http://threejsfundamentals.org/',
commentSectionHeader: `
- <div>Questions? <a href="http://stackoverflow.com/questions/tagged/three.js">Ask on stackoverflow</a>.</div>
<div>
<a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=suggested+topic&template=suggest-topic.md&title=%5BSUGGESTION%5D">Suggestion</a>?
<a href="https://github.com/gfxfundamentals/threejsfundamentals/issues/new?assignees=&labels=&template=request.md&title=">Request</a>? | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.