Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

but its make my mesh elemnt displace and the texture is very bad, i need a real rock…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-7-sonnet-20250219-thinking-32k’s answer.
  1. User

    but its make my mesh elemnt displace and the texture is very bad, i need a real rock texture

  2. Gemini Assistant

    Okay, you're absolutely right! My previous attempt replaced the material entirely, which means all the nice PBR (Physically Based Rendering) properties like diffuse textures, normal maps, roughness maps, etc., that might have come with your GLB were lost. That's why it looked flat or "displaced" (visually, not geometrically).

    To get a "real rock texture" look and add a custom shader effect on top of it, the best approach in Three.js (and by extension, React Three Fiber) is to use onBeforeCompile on the model's existing MeshStandardMaterials. This allows you to inject custom GLSL code into the built-in PBR shader, keeping all its lighting, shadows, and existing texture mapping, while adding your own procedural flourishes.

    Here's how we can modify your RockStone component to achieve a more realistic stone shading by perturbing the existing material's color and roughness with procedural noise:

    import React, { useRef, useEffect } from 'react'
    import { useGLTF } from '@react-three/drei'
    import { useFrame } from '@react-three/fiber'
    import * as THREE from 'three'
    
    // Define the procedural noise functions in GLSL
    // These will be injected into the standard material's fragment shader
    const glslNoise = `
        // A simple hash function for pseudo-random numbers
        float rand(vec2 n) {
            return fract(sin(dot(n, vec2(12.9898, 78.233))) * 43758.5453);
        }
        
        // Perlin-like noise function
        float noise(vec2 p) {
            vec2 ip = floor(p);
            vec2 fp = fract(p);
            float a = rand(ip);
            float b = rand(ip + vec2(1.0, 0.0));
            float c = rand(ip + vec2(0.0, 1.0));
            float d = rand(ip + vec2(1.0, 1.0));
            vec2 u = fp * fp * (3.0 - 2.0 * fp); // Smooth interpolation
            return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
        }
        
        // Fractal Brownian Motion (FBM) for more organic noise
        float fbm(vec2 p) {
            float value = 0.0;
            float amplitude = 0.5;
            float frequency = 2.0;
            for (int i = 0; i < 4; i++) { // 4 octaves for detail
                value += amplitude * noise(p * frequency);
                amplitude *= 0.5;
                frequency *= 2.0;
            }
            return value;
        }
    `;
    
    export function RockStone(props) {
      const groupRef = useRef();
      // Load the entire scene from useGLTF for easier traversal and material modification
      const { scene } = useGLTF('/Rock-Product.glb');
    
      // Use useEffect to apply onBeforeCompile once when the component mounts
      useEffect(() => {
        // Traverse all children in the loaded scene
        scene.traverse((object) => {
          // We only want to modify MeshStandardMaterial or similar PBR materials
          // Check if it's a mesh and has a material, and that material is not already processed
          if (object.isMesh && object.material && !object.material._customShaderApplied) {
            // IMPORTANT: Clone the material to avoid modifying the original shared material from Drei's cache.
            // This ensures that if you load multiple instances of RockStone, they can have different shader effects
            // or just to be safe from modifying materials globally.
            const originalMaterial = object.material;
            object.material = originalMaterial.clone();
    
            // Mark it as processed to prevent re-applying the hook if traverse runs again (unlikely with useEffect)
            object.material._customShaderApplied = true;
    
            // The core of injecting custom shader code: onBeforeCompile
            object.material.onBeforeCompile = (shader) => {
              // Add custom uniforms that our shader will use
              shader.uniforms.uTime = { value: 0 };
              shader.uniforms.uNoiseScale = { value: 8.0 }; // Scale of the noise pattern (how "zoomed in" it is)
              shader.uniforms.uNoiseStrength = { value: 0.1 }; // Intensity of the noise effect on color/roughness
              shader.uniforms.uBaseColor = { value: new THREE.Color(0x8B8878) }; // A default light stone color
              shader.uniforms.uAccentColor = { value: new THREE.Color(0x5E5E5E) }; // A default darker accent color
    
              // Inject varying for world position into vertex shader
              // This allows us to use world coordinates for noise, making it appear consistent regardless of mesh UVs
              shader.vertexShader = `
                varying vec3 vWorldPosition; // Declare a varying to pass world position
                ${shader.vertexShader}
              `.replace(
                `#include <begin_vertex>`, // Find a good injection point (after position is transformed to clip space)
                `
                #include <begin_vertex>
                vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz; // Calculate world position
                `
              );
    
              // Inject noise functions and modify fragment shader
              shader.fragmentShader = `
                uniform float uTime;
                uniform float uNoiseScale;
                uniform float uNoiseStrength;
                uniform vec3 uBaseColor;
                uniform vec3 uAccentColor;
                varying vec3 vWorldPosition; // Receive world position from vertex shader
                ${glslNoise} // Include our noise functions here
                ${shader.fragmentShader}
              `.replace(
                `#include <map_fragment>`, // This include happens after diffuseColor (albedo) is sampled from map
                `
                #include <map_fragment>
    
                // Combine UVs and world position for a more robust noise coordinate
                // World position helps prevent visible seams if the model has disconnected parts
                vec2 noiseCoord = vUv * uNoiseScale + vWorldPosition.xz * 0.05; 
                float stoneNoise = fbm(noiseCoord + uTime * 0.005); // Animate the noise slowly
    
                // --- Apply procedural color variation ---
                // Blend the original diffuse color with a procedural color based on noise
                // This adds subtle discolouration, like natural mineral streaks or weathering
                vec3 proceduralColor = mix(uBaseColor, uAccentColor, stoneNoise);
                diffuseColor.rgb = mix(diffuseColor.rgb, proceduralColor, 0.3); // 0.3 is blend strength (adjust as needed)
    
                // --- Apply procedural roughness variation ---
                // Perturb the roughness factor based on noise.
                // This makes some areas appear rougher (like chipped bits or highly textured areas)
                // and others smoother, enhancing the rock feel.
                // Check if roughnessFactor exists (MeshStandardMaterial has it)
                #ifdef USE_ROUGHNESSMAP
                    // If there's an existing roughness map, combine with it
                    roughnessFactor *= (1.0 + stoneNoise * uNoiseStrength * 1.5); // Multiply for more impact
                #else
                    // If no roughness map, apply directly to the uniform roughness
                    roughnessFactor = clamp(roughnessFactor * (1.0 + stoneNoise * uNoiseStrength * 1.5), 0.0, 1.0);
                #endif
    
                // Optional: You could also perturb the normal using noise to simulate small bumps
                // This is more complex and requires more advanced normal mapping GLSL.
                // For now, varying color and roughness gives a good visual effect.
                `
              );
    
              // Store the shader reference on the material's userData for easy access in useFrame
              object.material.userData.shader = shader;
            };
    
            // Important: Force the material to recompile with the new onBeforeCompile hook
            object.material.needsUpdate = true;
          }
        });
      }, [scene]); // Re-run this effect only if the scene object reference changes (unlikely for a static GLB)
    
      // Use useFrame to update the `uTime` uniform for animation
      useFrame((state) => {
        // Traverse the scene again to find materials with our custom shader
        scene.traverse((object) => {
          if (object.isMesh && object.material && object.material.userData.shader) {
            object.material.userData.shader.uniforms.uTime.value = state.clock.elapsedTime;
          }
        });
      });
    
      return (
        <group ref={groupRef} {...props} dispose={null}>
          {/* Render the entire loaded scene. All its meshes will now have modified materials. */}
          <primitive object={scene} /> 
        </group>
      );
    }
    
    useGLTF.preload('/Rock-Product.glb');
    

    Explanation of Changes:

    1. glslNoise Constant:

      • I've moved the noise functions (Perlin-like noise and FBM) into a separate GLSL string constant. This makes it cleaner to inject them into the shader.
    2. useGLTF for scene:

      • Instead of destructuring nodes and materials, I now directly get the scene object: const { scene } = useGLTF('/Rock-Product.glb');. This is crucial because it allows us to easily traverse the entire model's hierarchy.
    3. useEffect for onBeforeCompile:

      • The material modification now happens inside a useEffect hook. This ensures it runs only once when the RockStone component mounts and the scene is loaded.
      • scene.traverse((object) => { ... }): This iterates over every object in your GLB's hierarchy.
      • if (object.isMesh && object.material && !object.material._customShaderApplied): We check if the object is a mesh and has a material. The _customShaderApplied flag (a custom property we add) prevents applying the onBeforeCompile hook multiple times to the same material if traverse is called more than once.
      • object.material = originalMaterial.clone();: This is extremely important! When you load a GLB, useGLTF often caches materials, and they might be shared across different meshes or even different instances of your RockStone component. By cloning the material, you ensure that your onBeforeCompile modifications only affect this specific instance of the material on this specific mesh, preventing unintended side effects.
      • object.material.onBeforeCompile = (shader) => { ... };: This is the core. This function is called by Three.js just before it compiles the shader program for this material. You get direct access to the shader object, which contains its vertexShader and fragmentShader strings.
      • shader.uniforms.uTime = { value: 0 }; etc.: Here, we add our custom uniforms (uTime, uNoiseScale, uNoiseStrength, uBaseColor, uAccentColor). These are variables that you can control from your JavaScript code and pass into the GLSL shader.
      • shader.vertexShader = ....replace(...): We inject vWorldPosition into the vertex shader. Calculating noise based on world position (rather than just UVs) often leads to more consistent and seamless procedural effects across different parts of a complex model.
      • shader.fragmentShader = ....replace(...):
        • We inject our glslNoise functions.
        • We then find the #include <map_fragment> line. This is a good injection point because it happens after the material's original texture (diffuse/albedo map) has been sampled and assigned to diffuseColor.rgb.
        • diffuseColor.rgb = mix(diffuseColor.rgb, proceduralColor, 0.3);: This is where the magic happens for color. mix linearly interpolates between two values. We're blending the original diffuseColor (from your GLB's texture) with a proceduralColor derived from our FBM noise. This adds subtle color variations on top of your existing texture.
        • roughnessFactor = clamp(roughnessFactor * (1.0 + stoneNoise * uNoiseStrength * 1.5), 0.0, 1.0);: Similarly, we perturb the roughnessFactor. If your original material has a roughness map, roughnessFactor will already contain its value. We then multiply it by (1.0 + stoneNoise * uNoiseStrength * 1.5) to make some areas rougher based on the noise, simulating small bumps, pits, or mineral variations in the stone. clamp ensures the value stays between 0 and 1.
      • object.material.userData.shader = shader;: We store a reference to the compiled shader on the material's userData. This makes it easy to access and update its uniforms later in useFrame.
      • object.material.needsUpdate = true;: This tells Three.js to recompile the material's shader with your new onBeforeCompile hook.
    4. useFrame for uTime Update:

      • The useFrame hook ensures that uTime uniform is updated every frame with state.clock.elapsedTime. This makes the procedural noise slowly "animate" or "flow," creating a subtle dynamic effect on the stone.
    5. return <primitive object={scene} />:

      • Instead of manually listing out every mesh as you had in the original component, we now just render the entire scene object received from useGLTF. Since we've already traversed and modified the materials on the scene object itself, all meshes within it will now use your enhanced materials.

    This approach gives you the best of both worlds: the realism of your GLB's baked PBR textures and lighting, combined with the artistic control and procedural generation capabilities of custom shaders.

    Remember to adjust uNoiseScale, uNoiseStrength, and the mix blend strengths (0.3 and 1.5 in the roughness calculation) to fine-tune the look of your stone!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.