Table of Contents

Adding a Texture at Runtime

This tutorial shows how to apply a texture to a 3D object at runtime. Using the toolkit's TextureLoader, you'll load an image file as a colour texture and assign it to a 3D entity (a cube).

What you'll learn

  • Load a texture from an image file at runtime.
  • Create and configure a MaterialDescriptor to apply the texture.
  • Create a 3D primitive (cube) and assign the material.

Code walkthrough

using Stride.CommunityToolkit.Bepu;
using Stride.CommunityToolkit.Engine;
using Stride.CommunityToolkit.Rendering;
using Stride.CommunityToolkit.Rendering.ProceduralModels;
using Stride.Core.Mathematics;
using Stride.Engine;
using Stride.Graphics;
using Stride.Rendering;
using Stride.Rendering.Materials;
using Stride.Rendering.Materials.ComputeColors;

using var game = new Game();

game.Run(new SceneSetup3D().UseBepu(), start: Start);

void Start(Scene scene)
{
    // Load the texture from a file as a colour: sRGB, premultiplied and mipmapped, the way the content
    // pipeline would have imported it
    var texture = new TextureLoader(game.GraphicsDevice).Color("Stride-logo.png");

    // Create a material descriptor and assign the loaded texture to it
    var materialDescriptor = new MaterialDescriptor
    {
        Attributes =
       new MaterialAttributes
       {
           Diffuse = new MaterialDiffuseMapFeature(new ComputeTextureColor(texture)),

           // Lambert shading, so lights shade the surface
           DiffuseModel = new MaterialDiffuseLambertModelFeature(),

           CullMode = CullMode.Back
       }
    };

    var material = Material.New(game.GraphicsDevice, materialDescriptor);

    // Create a 3D cube primitive and assign the material to it
    var entity = game.CreatePrimitive(Primitive3D.Cube(), new()
    {
        Material = material,
    });

    entity.Transform.Position = new Vector3(0, 8, 0);

    // Add the cube to the root scene
    entity.Scene = scene;
}

Running the code

When you run this code, you'll see a 3D cube with the specified texture applied. The cube starts 8 units above the ground and falls onto it.

Summary

  • Load a texture from an image file.
  • Create a material that uses the texture.
  • Apply the material to a 3D primitive and add it to the scene.

You can apply the same approach to other models and textures to change object appearance at runtime.