Jump to content

Test: Difference between revisions

No edit summary
No edit summary
Line 17: Line 17:




<html>
<script type="module" src="https://cdn.jsdelivr.net/npm/@google/model-viewer@3.4.0/dist/model-viewer.min.js"></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/@google/model-viewer@3.4.0/dist/model-viewer.min.js"></script>


<div style="margin-bottom: 10px;">
<div style="margin-bottom: 10px; font-family: sans-serif;">
     <label for="bearTexture" style="font-weight: bold; margin-right: 10px;">Bear Type:</label>
     <label for="bearTexture" style="font-weight: bold; margin-right: 10px;">Bear Type:</label>
     <select id="bearTexture" style="padding: 5px; border: 1px solid #ccc; border-radius: 4px;">
     <select id="bearTexture" style="padding: 5px; border: 1px solid #ccc; border-radius: 4px;">
Line 28: Line 27:
</div>
</div>


<model-viewer  
<model-viewer
     id="bearModel"
     id="bearModelViewer"
     src="https://survivalcraft.wiki/content/Models/Bear.glb"
     src="https://survivalcraft.wiki/content/Models/Bear.glb"
     alt="3D Bear Model from Survivalcraft"
     alt="3D Bear Model from Survivalcraft"
     auto-rotate  
     auto-rotate
     camera-controls  
     camera-controls
     background-color="#f0f0f0"
     background-color="#f0f0f0"
     shadow-intensity="1"
     shadow-intensity="1"
Line 39: Line 38:
     exposure="1"
     exposure="1"
     style="width: 400px; height: 400px; border: 1px solid #ccc; border-radius: 8px;"
     style="width: 400px; height: 400px; border: 1px solid #ccc; border-radius: 8px;"
     loading="eager">
     loading="eager"
   
>
     <div slot="error" style="display: flex; align-items: center; justify-content: center; height: 100%; background: #ffe6e6; color: #d63031;">
     <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 console for details</small></p>
         <p>⚠️ Unable to load 3D model.<br><small>Check your browser console for details.</small></p>
     </div>
     </div>
</model-viewer>
</model-viewer>


<div id="loadingStatus" style="margin-top: 10px; font-size: 12px; color: #666;">
<div id="statusMessage" style="margin-top: 10px; font-size: 12px; color: #666; font-family: sans-serif;">
     Loading model...
     Loading model...
</div>
</div>


<div id="controlsInfo" style="margin-top: 10px; font-size: 12px; color: #666; display: none;">
<div id="controlsInfo" 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
     <strong>Controls:</strong> Click and drag to rotate • Scroll to zoom • Right-click and drag to pan
</div>
</div>


<script type="module"> // Added type="module" here as well
<script type="module">
const modelViewer = document.getElementById('bearModel');
    const modelViewer = document.getElementById('bearModelViewer');
const loadingStatus = document.getElementById('loadingStatus');
    const bearTextureSelector = document.getElementById('bearTexture');
const controlsInfo = document.getElementById('controlsInfo');
    const statusMessage = document.getElementById('statusMessage');
const bearTextureSelector = document.getElementById('bearTexture');
    const controlsInfo = document.getElementById('controlsInfo');


// Define texture URLs
    // Define texture URLs for different bear types
const textures = {
    const textures = {
    brown: 'https://survivalcraft.wiki/content/Textures/Creatures/Bear_Brown.png',
        brown: 'https://survivalcraft.wiki/content/Textures/Creatures/Bear_Brown.png',
    black: 'https://survivalcraft.wiki/content/Textures/Creatures/Bear_Black.png'
        black: 'https://survivalcraft.wiki/content/Textures/Creatures/Bear_Black.png'
};
    };


let currentMaterial = null; // To store a reference to the material we want to modify
    let mainModelMaterial = null; // We'll store a reference to the bear's main material here


// Track loading state
    // --- Event Listeners ---
modelViewer.addEventListener('load', async () => {
    console.log('Model loaded successfully');
    loadingStatus.textContent = 'Model loaded successfully!';
    controlsInfo.style.display = 'block';


     // Get the first material from the model
     // When the model is fully loaded and ready
    // Assuming your bear model has one main material that controls its color/texture
    modelViewer.addEventListener('load', async () => {
    // You might need to inspect your .glb file to find the correct material index or name
        console.log('3D model loaded successfully!');
    if (modelViewer.model && modelViewer.model.materials.length > 0) {
        statusMessage.textContent = 'Model loaded successfully!';
        currentMaterial = modelViewer.model.materials[0]; // Get the first material
        controlsInfo.style.display = 'block';
        console.log('Found model material:', currentMaterial);
 
        // Apply the initial texture
        // Attempt to get the first material from the loaded model.
        changeBearTexture();  
        // Most simple GLB models have a single primary material.
    } else {
        if (modelViewer.model && modelViewer.model.materials.length > 0) {
        console.warn('No materials found in the model.');
            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 for texture swap.';
            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';
    });


modelViewer.addEventListener('error', (event) => {
    // Update loading progress
    console.error('Model loading error:', event);
    modelViewer.addEventListener('progress', (event) => {
    loadingStatus.textContent = 'Error loading model. Check browser console.';
        const progress = event.detail.totalProgress;
    loadingStatus.style.color = '#d63031';
        statusMessage.textContent = `Loading model... ${Math.round(progress * 100)}%`;
});
    });


modelViewer.addEventListener('progress', (event) => {
    // Listen for changes in the bear type dropdown
    const progress = event.detail.totalProgress;
    bearTextureSelector.addEventListener('change', applyBearTexture);
    loadingStatus.textContent = `Loading model... ${Math.round(progress * 100)}%`;
});


// Event listener for texture selection change
    // --- Functions ---
bearTextureSelector.addEventListener('change', changeBearTexture);


async function changeBearTexture() {
    /**
    if (!currentMaterial) {
    * Applies the selected texture to the bear model.
        console.warn('Model material not yet available for texture change.');
    * Uses model-viewer's internal texture management.
        return;
    */
    }
    async function applyBearTexture() {
        if (!mainModelMaterial) {
            console.warn('Model material not yet available. Cannot change texture.');
            return; // Exit if material isn't ready
        }


    const selectedTexture = bearTextureSelector.value;
        const selectedTextureKey = bearTextureSelector.value;
    const textureUrl = textures[selectedTexture];
        const textureUrl = textures[selectedTextureKey];


    console.log('Attempting to change texture to:', selectedTexture, 'at URL:', textureUrl);
        if (!textureUrl) {
            console.warn(`No texture URL defined for "${selectedTextureKey}".`);
            return;
        }
 
        console.log(`Attempting to apply "${selectedTextureKey}" texture from: ${textureUrl}`);


    if (textureUrl) {
         try {
         try {
             // Create a new texture using model-viewer's createTexture method
             // 1. Create a new texture object using model-viewer's utility
             const texture = await modelViewer.createTexture(textureUrl);
             const newTexture = await modelViewer.createTexture(textureUrl);
           
 
             // Apply the new texture to the baseColorTexture of the material
             // 2. Apply this new texture to the material's baseColorTexture property.
             // This is the standard way to change the main color texture in glTF PBR materials
             // This is the primary texture that gives the model its color.
             currentMaterial.pbrMetallicRoughness.baseColorTexture.setTexture(texture);
             mainModelMaterial.pbrMetallicRoughness.baseColorTexture.setTexture(newTexture);
           
 
             console.log('Texture applied successfully:', selectedTexture);
             console.log(`Successfully applied ${selectedTextureKey} texture.`);
         } catch (error) {
         } catch (error) {
             console.error('Error creating or applying texture:', error);
             console.error(`Failed to apply ${selectedTextureKey} texture:`, error);
             // Optionally, revert to a default or show an error state
             statusMessage.textContent = `Error applying ${selectedTextureKey} texture.`;
            statusMessage.style.color = '#d63031';
         }
         }
    } else {
        console.warn('No texture URL found for:', selectedTexture);
     }
     }
}


// Debug: Log when everything is ready
    // --- Initial Checks (for debugging) ---
document.addEventListener('DOMContentLoaded', () => {
    document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM loaded, model-viewer should initialize');
        console.log('DOM fully loaded and parsed.');
   
 
    // Check if model-viewer is defined
        // Verify if the model-viewer custom element has been registered
    if (typeof customElements.get('model-viewer') === 'undefined') {
        if (typeof customElements.get('model-viewer') === 'undefined') {
        console.error('model-viewer component not loaded');
            console.error('The <model-viewer> component failed to load or register.');
        loadingStatus.textContent = 'Error: model-viewer component failed to load';
            statusMessage.textContent = 'Error: 3D viewer component not available.';
        loadingStatus.style.color = '#d63031';
            statusMessage.style.color = '#d63031';
    }
        }
});
    });
</script>
</script>
</html>