Geometry and Texture Creation
Summary
In this section, we will learn how to create new geometry and textures from scratch and apply textures to a mesh.
Concepts
- Geometry creation
- Texture creation
- Applying textures to a mesh
Starting the Web Viewer with an empty model
The models we have been using up to this point in the tutorial do not have texture coordinates, so we will create our own geometry to apply textures to. Remove the endpointUri attribute from <hoops-web-viewer> in index.html so it starts with no model loaded:
<hoops-web-viewer id="viewer"></hoops-web-viewer>
Creating the cube mesh geometry
Now we will create the geometry of a cube to apply textures to. Add the createCubeMeshData method below to the MaterialManager class we created in Color and Transparency (in src/Material.ts):
createCubeMeshData(pos: Point3, size: number): MeshData {
const p0 = new Point3(pos.x, pos.y, pos.z);
const p1 = new Point3(pos.x + size, pos.y, pos.z);
const p2 = new Point3(pos.x + size, pos.y + size, pos.z);
const p3 = new Point3(pos.x, pos.y + size, pos.z);
const p4 = new Point3(pos.x, pos.y + size, pos.z + size);
const p5 = new Point3(pos.x + size, pos.y + size, pos.z + size);
const p6 = new Point3(pos.x + size, pos.y, pos.z + size);
const p7 = new Point3(pos.x, pos.y, pos.z + size);
const triangles = [p0, p2, p1, p0, p3, p2, p2, p3, p4, p2, p4, p5, p1, p2,
p5, p1, p5, p6, p0, p7, p4, p0, p4, p3, p5, p4, p7, p5, p7, p6, p0,
p6, p7, p0, p1, p6];
const positions: number[] = [];
triangles.forEach((point) => {
positions.push(point.x, point.y, point.z);
});
const uvs = [
0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0,
0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0,
0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1,
];
const normals = [
0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1,
0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,
1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,
0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, -1, 0, 0, -1,
0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,
];
const meshData = new MeshData();
meshData.addFaces(positions, normals, undefined, uvs);
meshData.setFaceWinding(FaceWinding.CounterClockwise);
return meshData;
}
Add the corresponding imports to the top of src/Material.ts:
import {
Color,
FaceWinding,
Matrix,
MeshData,
MeshInstanceData,
Point3,
type NodeId,
type WebViewer,
} from '@ts3d-hoops/web-viewer';
The function createCubeMeshData takes a position and size, and creates a MeshData object. This object stores the positions of the faces that make up the cube, the normal for the faces, and the UV texture mapping data.
The cube is made up of 6 sides, each side consisting of 2 triangles to make a square. p0 – p7 are the 8 vertices of the cube that we use to make each triangle. For readability, we first create an array called triangles which list each point, before adding the x, y, and z values into an array called positions.
The UV values correspond to the vertices that make up each triangle. For each vertex, there is a corresponding 2d coordinate. Ex (p0 -> (0,0), p2 -> (1,1), p1 -> (1,0), etc).
The normals correspond to the direction of the face of the cube that the vertices are on. For example, the first face of the cube is in the Z plane, and it’s normal is (0, 0, -1). Each vertex will have a corresponding normal.
The face winding depends on the order of the vertices that make up the triangles. In this example, the triangles are created using a counter-clockwise face winding.
Create a cube
Now, let’s add the following method to the same class:
async createCube(position: Point3, size: number, faceColor: Color): Promise<NodeId> {
const cubeMeshData = this.createCubeMeshData(position, size);
const meshId = await this._hwv.model.createMesh(cubeMeshData);
const meshInstanceData = new MeshInstanceData(
meshId, new Matrix(), 'texture-cube', faceColor,
);
return this._hwv.model.createMeshInstance(meshInstanceData);
}
The function createCube will create a new MeshInstanceData and render it to the scene. Let’s breakdown what this function is doing step-by-step.
First, we will call createCubeMeshData which returns a MeshData object. Then, we will use that MeshData object to create a mesh, which will return a MeshId. Once we have a MeshId, we will use it to create a MeshInstanceData object.
When we create our MeshInstanceData object, we will specify a mesh id, identity matrix, instance name, and face color.
The createMeshInstance function takes a MeshInstanceData object as a parameter and returns the new instance’s NodeId. We will call the function to create an instance of the cube in the scene.
The MeshInstanceData constructor takes the following optional parameters:
- meshId:
MeshIdof the mesh to instantiate - matrix: a
Matrixthat will be applied to this instance - instanceName: a name that will be visible when querying the model hierarchy
- faceColor: the
Colorfor faces of this instance - lineColor: the
Colorfor lines of this instance - pointColor: the
Colorfor points of this instance - creationFlags:
additional optionsthat can be used to alter the behavior of this instance
Creating multiple cubes
Now that we have functions to create the geometry, we need to call them. In src/main.ts, after the MaterialManager is created, add the following to the hwvModelStructureReady listener. When this event fires, it’s safe to create the geometry. The following code will create four cubes in red, green, blue, and yellow colors. It will then set the view orientation to ISO, which will change the camera to see all the geometry we created.
import { Color, Point3, ViewOrientation } from '@ts3d-hoops/web-viewer';
import { MaterialManager } from './Material';
let materialManager: MaterialManager;
viewerEl.addEventListener('hwvSceneReady', ({ detail: { hwv } }) => {
materialManager = new MaterialManager(hwv);
});
viewerEl.addEventListener('hwvModelStructureReady', async ({ detail: { hwv } }) => {
await materialManager.createCube(new Point3(0, 0, 0), 10, Color.red());
await materialManager.createCube(new Point3(10, 0, 0), 10, Color.green());
await materialManager.createCube(new Point3(0, 10, 0), 10, Color.blue());
await materialManager.createCube(new Point3(0, 0, 10), 10, Color.yellow());
await hwv.view.setViewOrientation(ViewOrientation.Iso);
materialManager.initializeTextures();
});
We’ll define initializeTextures() over the next few sections.
Loading images
Before we apply any textures, we first need to load the images. Add the loadImage() method to the MaterialManager class to load an image.
async loadImage(filename: string): Promise<ImageId> {
const p = new Promise<XMLHttpRequest>((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', filename, true);
request.responseType = 'arraybuffer';
request.onload = function () {
if (request.readyState === 4) {
if (request.status === 200) {
resolve(request);
}
}
};
request.onerror = function (event) {
reject(event);
};
request.send();
});
const request = await p;
const imageOptions = {
format: ImageFormat.Png,
data: new Uint8Array(request.response),
};
return this._hwv.model.createImage(imageOptions);
}
Add ImageFormat and ImageId to the import at the top of src/Material.ts:
import { ImageFormat, type ImageId } from '@ts3d-hoops/web-viewer';
The loadImage method makes an XMLHttpRequest to fetch the data for an image in an array buffer. The contents of the array buffer are then used to create a Uint8Array as part of an ImageOptions object, which also contains the image format. The ImageOptions object is then used as a parameter for the createImage() function, which returns an ImageId.
The returned ImageId can then be used to apply a texture to a part.
Setting textures
Now we will add the setNodeTexture() method to the MaterialManager class and use it to set the texture on a node.
setNodeTexture(nodeId: NodeId | null, imageId: ImageId) {
if (nodeId !== null) {
const textureOptions = {
imageId: imageId,
modifiers: TextureModifier.Decal,
};
this._hwv.model.setNodesTexture([nodeId], textureOptions);
}
}
Add TextureModifier to the import at the top of src/Material.ts:
import { TextureModifier } from '@ts3d-hoops/web-viewer';
The setNodeTexture() function takes a NodeId and an ImageId and calls the setNodesTexture function which takes an array of type NodeId and a TextureOptions object. There are two options we will set, imageId and modifiers.
We then call setNodesTexture with an array containing a single NodeId and our desired options. The texture will then be applied to the part.
Copying images
We will need some images to load as textures. Create an images folder at the top level of your application’s directory. Copy the images from the package at web_viewer/examples/images/textures to the new images folder. There should be three textures: bricks.png, nebula.png, and textured.png.
Creating the UI
Add the following HTML to index.html, alongside the color and opacity controls from the previous section. As with those controls, there’s no packaged component for this, so it stays hand-written HTML. We will use these images to set a texture on a selected node when the image is clicked.
<div id="textures">
<div>
Click an image to apply a texture to the cube:
<img id="bricks" src="images/bricks.png" width="100px" height="100px">
<img id="nebula" src="images/nebula.png" width="100px" height="100px">
<img id="textured" src="images/textured.png" width="100px" height="100px">
</div>
</div>
Connect UI to texture logic
Finally, add the initializeTextures() method we referenced earlier to the MaterialManager class. This loads the images and wires up each <img> element to apply the corresponding texture to the currently selected node when clicked.
async initializeTextures() {
const bricksImageId = await this.loadImage('images/bricks.png');
const nebulaImageId = await this.loadImage('images/nebula.png');
const texturedImageId = await this.loadImage('images/textured.png');
(document.getElementById('bricks') as HTMLImageElement).onclick = () => {
this.setNodeTexture(this.getSelectedNodeId(), bricksImageId);
};
(document.getElementById('nebula') as HTMLImageElement).onclick = () => {
this.setNodeTexture(this.getSelectedNodeId(), nebulaImageId);
};
(document.getElementById('textured') as HTMLImageElement).onclick = () => {
this.setNodeTexture(this.getSelectedNodeId(), texturedImageId);
};
}
This is the method we already called at the end of the hwvModelStructureReady listener in Creating multiple cubes - no further wiring is needed.
Loading the application
Load the application. Select a cube, then an image, and the selected texture will be applied.