S&box Wiki

Revision Difference

RenderEntity#560146

<cat>Code.Entity</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⤶ using Sandbox;⤶ // 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) return;⤶ ⤶ // Allow lights to affect the sprite⤶ Graphics.SetupLighting(obj);⤶ // Create the vertex buffer for the sprite⤶ var vb = new VertexBuffer();⤶ vb.Init(true);⤶ ⤶ // Vertex buffers are in local space, so we need the camera position in local space too⤶ var normal = Transform.PointToLocal(Camera.Position).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/sprites/glow.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.Attributes.Set` inside your `DoRender` method. The values you set will affect all subsequent draw calls in the method body.⤶ ⤶ ```csharp⤶ Graphics.Attributes.Set("rendercolor", Color.Red);⤶ ```⤶ ⤶ ## Limitations⤶ ⤶ Each vertex buffer 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).<cat>removed</cat>