Jump to content

Template:ModelViewer: Difference between revisions

From Survivalcraft Wiki
Created page with "<script type="module" src="https://cdn.jsdelivr.net/npm/@google/model-viewer@3.4.0/dist/model-viewer.min.js"></script> <model-viewer id="bearModelViewer-{{PAGENAME}}" src="https://survivalcraft.wiki/content/Models/Bear.glb" alt="3D Bear Model from Survivalcraft" auto-rotate camera-controls background-color="#f0f0f0" shadow-intensity="1" environment-image="neutral" exposure="1" style="width: 400px; height: 400px; border: 1px solid..."
 
No edit summary
Line 1: Line 1:
<script type="module" src="https://cdn.jsdelivr.net/npm/@google/model-viewer@3.4.0/dist/model-viewer.min.js"></script>
<noinclude>
This template displays a 3D model using <code>&lt;model-viewer&gt;</code>.


=== Usage ===
<pre>
{{ModelViewer
|src=https://survivalcraft.wiki/content/Models/Bear_Brown.glb
|alt=Brown Bear
|width=200px
|height=200px
|cameraOrbit=165deg 75deg 4m
}}
</pre>
</noinclude>
<html>
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
<model-viewer
<model-viewer
     id="bearModelViewer-{{PAGENAME}}"
     id="modelViewer-{{PAGENAME}}"
     src="https://survivalcraft.wiki/content/Models/Bear.glb"
     src="{{{src}}}"
     alt="3D Bear Model from Survivalcraft"
     alt="{{{alt|3D model}}}"
    camera-orbit="{{{cameraOrbit|165deg 75deg 4m}}}"
     auto-rotate
     auto-rotate
     camera-controls
     camera-controls
     background-color="#f0f0f0"
     background-color="transparent"
     shadow-intensity="1"
     shadow-intensity="1"
     environment-image="neutral"
     environment-image="neutral"
     exposure="1"
     exposure="1"
     style="width: 400px; height: 400px; border: 1px solid #ccc; border-radius: 8px;"
     style="display: block; width: {{{width|200px}}}; height: {{{height|200px}}}; margin-left: auto; margin-right: auto;"
     loading="eager"
     loading="eager"
>
>
    <div slot="error" style="display: flex; align-items: center; justify-content: center; height: 100%; background: #ffe6e6; color: #d63031; font-family: sans-serif; text-align: center;">
        <p>⚠️ Unable to load 3D model.<br><small>Check your browser console for details.</small></p>
    </div>
</model-viewer>
</model-viewer>
 
</html>
<div id="statusMessage-{{PAGENAME}}" style="margin-top: 10px; font-size: 12px; color: #666; font-family: sans-serif;">
    Loading model...
</div>
 
<div id="controlsInfo-{{PAGENAME}}" style="margin-top: 10px; font-size: 12px; color: #666; font-family: sans-serif; display: none;">
    <strong>Controls:</strong> Click and drag to rotate • Scroll to zoom • Right-click and drag to pan
</div>
 
{{#tag:script|type="module"|
    const modelViewer = document.getElementById('bearModelViewer-{{PAGENAME}}');
    const statusMessage = document.getElementById('statusMessage-{{PAGENAME}}');
    const controlsInfo = document.getElementById('controlsInfo-{{PAGENAME}}');
 
    // Define the single texture URL for the brown bear
    const textureUrl = 'https://survivalcraft.wiki/content/Textures/Creatures/Bear_Brown.png';
 
    let mainModelMaterial = null; // We'll store a reference to the bear's main material here
 
    // --- Event Listeners ---
 
    // When the model is fully loaded and ready
    modelViewer.addEventListener('load', async () => {
        console.log('3D model loaded successfully!');
        statusMessage.textContent = 'Model loaded successfully!';
        controlsInfo.style.display = 'block';
 
        // Attempt to get the first material from the loaded model.
        if (modelViewer.model && modelViewer.model.materials.length > 0) {
            mainModelMaterial = modelViewer.model.materials[0];
            console.log('Identified main model material:', mainModelMaterial);
            // Apply the default (brown) texture right after the model loads
            await applyBearTexture();
        } else {
            console.warn('Could not find any materials in the loaded model. Texture changing might not work.');
            statusMessage.textContent = 'Model loaded, but materials not found.';
            statusMessage.style.color = '#d63031';
        }
    });
 
    // Handle any errors during model loading
    modelViewer.addEventListener('error', (event) => {
        console.error('Error loading 3D model:', event);
        statusMessage.textContent = 'Error loading model. Check your browser console.';
        statusMessage.style.color = '#d63031';
    });
 
    // Update loading progress
    modelViewer.addEventListener('progress', (event) => {
        const progress = event.detail.totalProgress;
        statusMessage.textContent = `Loading model... ${Math.round(progress * 100)}%`;
    });
 
    // --- Functions ---
 
    /**
    * Applies the single predefined texture to the bear model.
    */
    async function applyBearTexture() {
        if (!mainModelMaterial) {
            console.warn('Model material not yet available. Cannot apply texture.');
            return; // Exit if material isn't ready
        }
 
        console.log(`Attempting to apply texture from: ${textureUrl}`);
 
        try {
            // 1. Create a new texture object using model-viewer's utility
            const newTexture = await modelViewer.createTexture(textureUrl);
 
            // 2. Apply this new texture to the material's baseColorTexture property.
            mainModelMaterial.pbrMetallicRoughness.baseColorTexture.setTexture(newTexture);
 
            console.log('Successfully applied texture.');
        } catch (error) {
            console.error('Failed to apply texture:', error);
            statusMessage.textContent = 'Error applying texture.';
            statusMessage.style.color = '#d63031';
        }
    }
 
    // --- Initial Checks (for debugging) ---
    document.addEventListener('DOMContentLoaded', () => {
        console.log('DOM fully loaded and parsed.');
 
        // Verify if the model-viewer custom element has been registered
        if (typeof customElements.get('model-viewer') === 'undefined') {
            console.error('The <model-viewer> component failed to load or register.');
            statusMessage.textContent = 'Error: 3D viewer component not available.';
            statusMessage.style.color = '#d63031';
        }
    });
}}

Revision as of 19:20, 29 July 2025

This template displays a 3D model using <model-viewer>.

Usage

{{ModelViewer
 |src=https://survivalcraft.wiki/content/Models/Bear_Brown.glb
 |alt=Brown Bear
 |width=200px
 |height=200px
 |cameraOrbit=165deg 75deg 4m
}}