import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
export default class model3DLayer {
constructor(id,accessToken,opt) {
this.id = id;
this.type = 'custom';
this.renderingMode = '3d';
this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.01, 5 );
this.camera.position.set( 0.1, 0.05, 0.15 );
this.scene = new THREE.Scene();
this.modelURL = opt.modelURL == undefined ? "":opt.modelURL;
this.models = []; // 存储多个模型实例
this.modelPoints = opt.modelPoints; // 修改为多个点的数组
}
onAdd(map, gl) {
// create two three.js lights to illuminate the model
const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(0, -70, 100).normalize();
this.scene.add(directionalLight);
const directionalLight2 = new THREE.DirectionalLight(0x000000);
directionalLight2.position.set(0, 70, 100).normalize();
this.scene.add(directionalLight2);
// use the three.js GLTF loader to add the 3D model to the three.js scene
const loader = new GLTFLoader();
loader.load(
this.modelURL,
(gltf) => {
const model = gltf.scene;
// 遍历每个模型点
this.modelPoints.forEach((ev) => { // Use arrow function here
const modelClone = model.clone(); // 克隆模型
modelClone.traverse((child) => {
if (child.isMesh) {
const materials = Array.isArray(child.material) ? child.material : [child.material];
materials.forEach((material) => {
//material.color.set(0xff0000);
// 克隆材质,以便每个模型都有独立的材质
const newMaterial = material.clone(); // 完全克隆原始材质
It looks like the primary issue with your 3D model not displaying stems from the setup and synchronization between the Three.js camera and Mapbox's rendering system. Integrating Three.js with Mapbox GL JS requires careful alignment of the camera's projection matrix and the positioning of 3D objects within the map's coordinate system.
Below are detailed steps and code modifications to help you resolve the issue and ensure that your 3D models render correctly on the map.
1. Use THREE.Camera Instead of THREE.PerspectiveCamera
Mapbox GL JS provides its own projection matrix during rendering, which should be directly applied to a generic THREE.Camera. Using THREE.PerspectiveCamera can cause mismatches because it maintains its own projection properties that conflict with Mapbox's matrices.
Explanation: The generic THREE.Camera does not have its own projection matrix, allowing you to directly apply Mapbox's projection matrix during each render cycle.
2. Apply Mapbox’s Projection Matrix to the Three.js Camera
During each render cycle, Mapbox provides a projection matrix that must be applied to the Three.js camera. This ensures that the 3D scene aligns correctly with the 2D map.
Modification:
Before:
javascript
// Existing code that manipulates model matrices with the map's matrix
const m = new THREE.Matrix4().fromArray(matrix); // Map's projection matrix
// ... modelClone.matrix = m.clone().multiply(modelMatrix); ...
After:
javascript
render(gl, matrix) {
// Update the camera's projection matrix
this.camera.projectionMatrix = new THREE.Matrix4().fromArray(matrix);
// Update each model's position based on Mercator coordinates
this.models.forEach((modelClone, index) => {
const modelPoint = this.modelPoints[index];
const modelAsMercatorCoordinate = mapboxgl.MercatorCoordinate.fromLngLat(modelPoint.point);
// Apply translation, rotation, and scaling to the model
modelClone.position.set(
modelAsMercatorCoordinate.x,
modelAsMercatorCoordinate.y,
modelAsMercatorCoordinate.z
);
modelClone.rotation.set(
modelPoint.modelRotate[0],
modelPoint.modelRotate[1],
modelPoint.modelRotate[2]
);
modelClone.scale.set(
modelAsMercatorCoordinate.meterInMercatorCoordinateUnits() * modelPoint.scaleSize,
modelAsMercatorCoordinate.meterInMercatorCoordinateUnits() * modelPoint.scaleSize,
modelAsMercatorCoordinate.meterInMercatorCoordinateUnits() * modelPoint.scaleSize
);
});
// Render the scene with the updated camera
this.renderer.resetState();
this.renderer.render(this.scene, this.camera);
// Trigger a repaint for the map
this.map.triggerRepaint();
}
Explanation: Instead of modifying each model's matrix with the map's projection matrix, apply the projection matrix directly to the camera. Position, rotate, and scale the models based on their respective Mercator coordinates and orientation.
3. Correct Variable References in Event Handlers
In your handleClick method, ensure that you're referencing this.map instead of just map, as map is not defined within the scope of the handler.
Modification:
Before:
javascript
const rect = map.getCanvas().getBoundingClientRect();
After:
javascript
const rect = this.map.getCanvas().getBoundingClientRect();
Apply this change to all instances where map is used within class methods, replacing them with this.map.
4. Ensure mapboxgl Is Accessible
Make sure that mapboxgl is available within the scope of your class. If it's not globally available, you might need to pass it as an option or import it appropriately.
Example:
javascript
import mapboxgl from 'mapbox-gl';
export default class model3DLayer {
// ... existing code ...
}
Ensure that mapboxgl is correctly imported and accessible wherever it's used.
5. Verify Model Loading and Positions
Ensure that your models are loading correctly and are positioned within the visible range of the camera. You can add console logs to confirm that models are loaded and their positions are set as expected.
Example:
javascript
loader.load(
this.modelURL,
(gltf) => {
const model = gltf.scene;
console.info('Model loaded', model);
// ... existing cloning and material setup ...
modelClone.position.set(
modelAsMercatorCoordinate.x,
modelAsMercatorCoordinate.y,
modelAsMercatorCoordinate.z
);
console.info('Model position set to', modelClone.position);
this.models.push(modelClone);
this.scene.add(modelClone);
},
undefined,
(error) => {
console.error('Error loading model:', error);
}
);
Explanation: Adding console logs can help you verify that models are loading without errors and are correctly positioned in the scene.
6. Adjust Renderer Settings if Necessary
Ensure that the WebGL renderer is properly configured to handle the Three.js scene within Mapbox's context.
Modification:
javascript
this.renderer = new THREE.WebGLRenderer({
canvas: map.getCanvas(),
context: gl,
antialias: true,
alpha: true // Enable alpha if transparency is needed
});
this.renderer.autoClear = false;
this.renderer.setSize(map.getCanvas().clientWidth, map.getCanvas().clientHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
Explanation: Setting the size and pixel ratio ensures that the renderer matches the map's canvas properties, which is crucial for correct rendering.
7. Complete Revised Code Example
Here is a revised version of your class incorporating the suggested changes:
javascript
8. Additional Recommendations
Check Model URL: Ensure that opt.modelURL is a correct and accessible path to your GLTF model. You can add error handling in the GLTFLoader to log any loading issues.
Scale and Position: Verify that the modelPoint.scaleSize and modelPoint.point values correctly position your model within the map's view. Incorrect scaling or positioning can make models appear too small, too large, or off-screen.
Console Logs: Utilize console.log statements generously during development to trace the flow of data, especially after loading models and setting positions.
Mapbox GL JS Version: Ensure that you're using a compatible version of Mapbox GL JS with your Three.js integration. Compatibility issues can sometimes prevent proper rendering.
Three.js and Mapbox GL JS Updates: Both libraries are actively developed. Make sure you're using the latest stable versions and refer to their respective documentation for any recent changes that might affect integration.
By following these steps and ensuring that your camera and projection matrices are correctly aligned with Mapbox's rendering system, your 3D models should display correctly on the map. If you continue to experience issues, consider isolating parts of the code to identify whether the problem lies with model loading, positioning, or rendering configurations.
Not yet included in a published release.
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import mapboxgl from 'mapbox-gl'; // Ensure mapboxgl is imported
export default class model3DLayer {
constructor(id, accessToken, opt) {
this.id = id;
this.type = 'custom';
this.renderingMode = '3d';
this.camera = new THREE.Camera(); // Changed from PerspectiveCamera
this.scene = new THREE.Scene();
this.modelURL = opt.modelURL || "";
this.models = []; // To store multiple model instances
this.modelPoints = opt.modelPoints; // Array of points
}
onAdd(map, gl) {
this.map = map;
// Add lighting to the scene
const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(0, -70, 100).normalize();
this.scene.add(directionalLight);
const directionalLight2 = new THREE.DirectionalLight(0x000000);
directionalLight2.position.set(0, 70, 100).normalize();
this.scene.add(directionalLight2);
// Load the 3D model
const loader = new GLTFLoader();
loader.load(
this.modelURL,
(gltf) => {
const model = gltf.scene;
console.info('Model loaded:', model);
this.modelPoints.forEach((point, index) => {
const modelClone = model.clone();
// Update materials if needed
modelClone.traverse((child) => {
if (child.isMesh) {
const materials = Array.isArray(child.material) ? child.material : [child.material];
materials.forEach((material) => {
const newMaterial = material.clone();
// Apply any texture or customization here
newMaterial.transparent = false;
newMaterial.needsUpdate = true;
child.material = newMaterial;
});
}
});
// Convert geographic coordinates to Mercator
const mercatorCoord = mapboxgl.MercatorCoordinate.fromLngLat(point.point);
// Apply scale and position
modelClone.position.set(mercatorCoord.x, mercatorCoord.y, mercatorCoord.z);
modelClone.rotation.set(
point.modelRotate[0],
point.modelRotate[1],
point.modelRotate[2]
);
modelClone.scale.set(
mercatorCoord.meterInMercatorCoordinateUnits() * point.scaleSize,
mercatorCoord.meterInMercatorCoordinateUnits() * point.scaleSize,
mercatorCoord.meterInMercatorCoordinateUnits() * point.scaleSize
);
this.models.push(modelClone);
this.scene.add(modelClone);
console.info(`Model ${index} added at`, modelClone.position);
});
},
undefined,
(error) => {
console.error('Error loading GLTF model:', error);
}
);
// Initialize the renderer
this.renderer = new THREE.WebGLRenderer({
canvas: map.getCanvas(),
context: gl,
antialias: true,
alpha: true
});
this.renderer.autoClear = false;
this.renderer.setSize(map.getCanvas().clientWidth, map.getCanvas().clientHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
// Initialize Raycaster for interactions
this.raycaster = new THREE.Raycaster();
this.mouse = new THREE.Vector2();
this.selectedObject = null;
// Add event listener for clicks
this.map.getCanvas().addEventListener('click', (event) => {
this.handleClick(event);
});
}
render(gl, matrix) {
// Update the camera's projection matrix
this.camera.projectionMatrix = new THREE.Matrix4().fromArray(matrix);
// Render the scene
this.renderer.resetState();
this.renderer.render(this.scene, this.camera);
// Request a repaint
this.map.triggerRepaint();
}
handleClick(event) {
const rect = this.map.getCanvas().getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
if (mouseX >= 0 && mouseX <= rect.width && mouseY >= 0 && mouseY <= rect.height) {
this.mouse.x = (mouseX / rect.width) * 2 - 1;
this.mouse.y = - (mouseY / rect.height) * 2 + 1;
this.mouseClicked = true;
}
// Update the raycaster
this.raycaster.setFromCamera(this.mouse, this.camera);
// Determine objects intersected by the ray
const intersects = this.raycaster.intersectObjects(this.scene.children, true);
if (intersects.length > 0) {
const selectedModel = intersects[0].object;
console.log('Selected model:', selectedModel);
// Highlight the selected model
if (selectedModel && selectedModel.material) {
const highlightColor = 0xffff00; // Yellow
if (Array.isArray(selectedModel.material)) {
selectedModel.material.forEach(material => {
material.emissive.set(highlightColor);
material.color.set(highlightColor);
});
} else {
selectedModel.material.emissive.set(highlightColor);
selectedModel.material.color.set(highlightColor);
}
// Optional: Add outline or other effects
// const outlineMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });
// const outlineMesh = new THREE.Mesh(selectedModel.geometry, outlineMaterial);
// outlineMesh.scale.multiplyScalar(1.05);
// selectedModel.add(outlineMesh);
} else {
console.warn('Selected model does not have a material:', selectedModel);
}
} else {
console.warn('No intersections found.');
}
}
}