S&box Wiki

Revision Difference

RenderEntity#544721

<cat>Code.Misc</cat>⤶ <title>RenderEntity</title>⤶ ⤶ `RenderEntity` is a clientside-only entity class that lets you draw simple meshes.⤶ The API is pretty simple and lets you provide dynamic vertex data on a per-frame basis.⤶ ⤶ ## Creating a basic sprite⤶ ⤶ For most use cases it's sufficient to just derive from the `RenderEntity` class and override the `DoRender` method:⤶ ⤶ ```csharp⤶ // It's just a square with a material slapped onto it.⤶ public class Sprite : RenderEntity⤶ {⤶ public Material SpriteMaterial { get; set; }⤶ ⤶ public float SpriteScale { get; set; } = 18f;⤶ ⤶ public bool Enabled { get; set; } = true;⤶ ⤶ public override void DoRender(SceneObject obj)⤶ {⤶ if (!Enabled || Local.Client.Camera is not Camera cam) return;⤶ ⤶ // Allow lights to affect the sprite⤶ Render.SetLighting(obj);⤶ // Create the vertex buffer for the sprite⤶ var vb = Render.GetDynamicVB();⤶ ⤶ // Vertex buffers are in local space, so we need the camera position in local space too⤶ var normal = Transform.PointToLocal(cam.Pos).Normal;⤶ var w = normal.Cross(Vector3.Down).Normal;⤶ var h = normal.Cross(w).Normal;⤶ float halfSpriteSize = SpriteScale / 2;⤶ ⤶ // Add a single quad to our vertex buffer⤶ vb.AddQuad(new Ray(default, normal), w * halfSpriteSize, h * halfSpriteSize);⤶ ⤶ // Draw the sprite⤶ vb.Draw(SpriteMaterial);⤶ }⤶ }⤶ ```⤶ ⤶ Then you can spawn them like this:⤶ ⤶ ```csharp⤶ // Somewhere in client code...⤶ var sprite = new Sprite⤶ {⤶ SpriteMaterial = Material.Load("materials/goatse.vmat"),⤶ SpriteScale = 24f⤶ };⤶ ```⤶ ⤶ Keep in mind that creating RenderEntities serverside does not work-- they simply won't spawn.⤶ ⤶ ## Dynamic expressions⤶ ⤶ If your materials have dynamic expressions, you can write to their variables by calling `Render.Set` inside your `DoRender` method. The values you set will affect all subsequent draw calls in the method body.⤶ ⤶ ```csharp⤶ Render.Set("rendercolor", Color.Red);⤶ ```⤶ ⤶ ## Limitations⤶ ⤶ Due to the large size of the `RenderEntity` vertex format, vertex buffers created with `Render.GetDynamicVB()` can only contain approximately 600 vertices. If you exceed this limit, you may experience crashes.⤶ ⤶ If you need more vertices, you can either use multiple vertex buffers or use the `Mesh` class instead (which allows you to use a custom vertex format).