New sample renderer and UI (#10)

No changes to simulation
This commit is contained in:
Erin Catto 2026-06-06 10:06:05 -07:00 • committed by GitHub
commit 9e02b7f3b3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
196 changed files with 116992 additions and 29969 deletions

449
samples/host/camera.cpp Normal file
View file

@ -0,0 +1,449 @@
#include "camera.h"
#include "gfx/picking.h"
#include "box3d/math_functions.h"
#include "sokol_app.h"
#include <math.h>
static constexpr float HALF_PI = B3_PI * 0.5f;
static constexpr float DEG_TO_RAD = B3_PI / 180.0f;
static constexpr float ORBIT_SENS = 0.005f; // radians per pixel
static constexpr float FLY_LOOK_SENS = 0.005f; // radians per pixel
static constexpr float PAN_SENS = 0.005f; // meters per pixel per meter of radius
static constexpr float RADIAL_ZOOM_SENS = 0.02f; // meters per pixel (alt+right-drag)
static constexpr float FLY_SPEED_STEP = 1.0f; // m/s per scroll tick
static constexpr float ZOOM_STEP = 0.9f; // multiplier per scroll tick
static constexpr float MIN_DIST = 0.1f;
static constexpr float MAX_DIST = 1000.0f;
static constexpr float MIN_SPEED = 0.06f; // matches box3d's 0.001*60
static constexpr float MAX_SPEED = 30000.0f; // matches box3d's 500*60
static constexpr float PITCH_LIM = HALF_PI - 0.01f;
static constexpr float THIRD_PERSON_MIN_RADIUS = 0.25f; // matches box3d
// Build a reverse-Z RH projection and its inverse together by swapping the
// near/far args. mat4PerspectiveAndInverse normally puts ndc.z=0 at near, 1
// at far; with the arguments swapped you get 1 at near, 0 at far - what the
// project's pipeline expects (compare GREATER, far-clear 0). The inverse is
// closed-form from the same params so the un-project path stays accurate.
static void ReverseZPerspectiveAndInverse( Mat4* outProj, Mat4* outProjInv, float fov, float aspect, float n, float f )
{
MakePerspectiveAndInverse( outProj, outProjInv, fov, aspect, f, n );
}
// Yaw/pitch -> the "+view-Z" direction (pivot -> camera), matching Box3D's
// sample convention. The actual looking direction is -ForwardFromAngles.
static b3Vec3 ForwardFromAngles( float yaw, float pitch )
{
const float cp = cosf( pitch );
return b3Vec3{ sinf( yaw ) * cp, sinf( pitch ), cosf( yaw ) * cp };
}
// Refresh the world-space basis and the view / viewInv pair from yaw / pitch /
// pivot / radius. Called from every state mutator (SetOrbit, Frame, Update)
// so consumers can read m_view / m_viewInv without an inversion step.
static void RebuildBasisAndView( Camera& c )
{
const b3Vec3 forward = ForwardFromAngles( c.m_yaw, c.m_pitch );
const b3Vec3 worldUp = { 0.0f, 1.0f, 0.0f };
// up = worldUp re-orthogonalized against forward. right = up x forward.
// Matches Box3D's UpdateTransform; produces a right-handed view basis.
const b3Vec3 upUnnorm = b3Sub( worldUp, b3MulSV( b3Dot( worldUp, forward ), forward ) );
const b3Vec3 up = b3Normalize( upUnnorm );
const b3Vec3 right = b3Normalize( b3Cross( up, forward ) );
const b3Vec3 position = { c.m_pivot.x + forward.x * c.m_radius, c.m_pivot.y + forward.y * c.m_radius,
c.m_pivot.z + forward.z * c.m_radius };
c.m_position = position;
c.m_right = right;
c.m_up = up;
c.m_forward = forward;
MakeViewAndInverse( &c.m_view, &c.m_viewInv, right, up, forward, position );
}
Camera::Camera()
: m_pivot{ 0.0f, 0.0f, 0.0f }
, m_yaw( 35.0f * DEG_TO_RAD )
, m_pitch( -25.0f * DEG_TO_RAD )
, m_radius( 25.0f )
, m_fov( 60.0f * DEG_TO_RAD )
, m_near( 0.1f )
, m_far( 1000.0f )
, m_speed( 10.0f )
, m_width( 0 )
, m_height( 0 )
, m_thirdPerson( false )
, m_position{ 0.0f, 0.0f, 0.0f }
, m_right{ 1.0f, 0.0f, 0.0f }
, m_up{ 0.0f, 1.0f, 0.0f }
, m_forward{ 0.0f, 0.0f, 1.0f }
, m_view( MakeIdentity() )
, m_viewInv( MakeIdentity() )
, m_proj( MakeIdentity() )
, m_projInv( MakeIdentity() )
{
RebuildBasisAndView( *this );
RebuildProj( 1.0f );
}
void Camera::RebuildProj( float aspect )
{
if ( aspect <= 0.0f )
aspect = 1.0f;
ReverseZPerspectiveAndInverse( &m_proj, &m_projInv, m_fov, aspect, m_near, m_far );
}
void Camera::Frame( b3AABB aabb, float aspect, float padding )
{
if ( !b3IsValidAABB( aabb ) )
{
return;
}
b3Vec3 center = b3AABB_Center( aabb );
b3Vec3 ext = b3AABB_Extents( aabb ); // half-extents
float r = sqrtf( ext.x * ext.x + ext.y * ext.y + ext.z * ext.z );
m_pivot = center;
if ( r < 1.0e-6f )
{
// Point-like; preserve current radius, just retarget. The cached
// position/basis depend on m_pivot, so refresh them before returning.
RebuildBasisAndView( *this );
return;
}
if ( aspect <= 0.0f )
{
aspect = 1.0f;
}
float halfFovY = 0.5f * m_fov;
float invTan = 1.0f / tanf( halfFovY );
float distV = r * invTan;
float distH = r * invTan / aspect;
float d = ( distV > distH ) ? distV : distH;
d *= padding;
SetOrbit( m_yaw, m_pitch, d );
}
void Camera::SetOrbit( float yawRadians, float pitchRadians, float radius )
{
m_yaw = yawRadians;
if ( pitchRadians > PITCH_LIM )
pitchRadians = PITCH_LIM;
if ( pitchRadians < -PITCH_LIM )
pitchRadians = -PITCH_LIM;
m_pitch = pitchRadians;
if ( radius < MIN_DIST )
radius = MIN_DIST;
if ( radius > MAX_DIST )
radius = MAX_DIST;
m_radius = radius;
RebuildBasisAndView( *this );
}
void Camera::SetView( float yawDegrees, float pitchDegrees, float radius, b3Vec3 pivot )
{
// Box3D feeds degrees; render3d stores radians. Pivot first so SetOrbit's
// basis rebuild uses the new pivot.
SetPivot( pivot );
SetOrbit( yawDegrees * DEG_TO_RAD, pitchDegrees * DEG_TO_RAD, radius );
}
void Camera::UpdateTransform()
{
RebuildBasisAndView( *this );
}
b3Vec3 Camera::Position() const
{
return m_position;
}
PickRay Camera::BuildPickRay( float x, float y ) const
{
PickRay ray;
if ( !::BuildPickRay( x, y, &ray.origin, &ray.translation ) )
{
// Camera state not latched yet, or degenerate matrices: defined zero
// ray so callers never read uninitialized values.
ray.origin = m_position;
ray.translation = b3Vec3_zero;
}
return ray;
}
void Camera::OnEvent( const sapp_event* e )
{
uint32_t mods = e->modifiers & ( SAPP_MODIFIER_SHIFT | SAPP_MODIFIER_CTRL | SAPP_MODIFIER_ALT );
const bool canOrbit = mods == SAPP_MODIFIER_ALT;
switch ( e->type )
{
case SAPP_EVENTTYPE_MOUSE_DOWN:
if ( e->mouse_button == SAPP_MOUSEBUTTON_LEFT )
m_leftDown = true;
if ( e->mouse_button == SAPP_MOUSEBUTTON_RIGHT )
m_rightDown = true;
if ( e->mouse_button == SAPP_MOUSEBUTTON_MIDDLE )
m_middleDown = true;
break;
case SAPP_EVENTTYPE_MOUSE_UP:
if ( e->mouse_button == SAPP_MOUSEBUTTON_LEFT )
m_leftDown = false;
if ( e->mouse_button == SAPP_MOUSEBUTTON_RIGHT )
m_rightDown = false;
if ( e->mouse_button == SAPP_MOUSEBUTTON_MIDDLE )
m_middleDown = false;
break;
case SAPP_EVENTTYPE_MOUSE_MOVE:
if ( canOrbit && m_leftDown )
{
m_orbitDX += e->mouse_dx;
m_orbitDY += e->mouse_dy;
}
else if ( canOrbit && m_middleDown )
{
m_panDX += e->mouse_dx;
m_panDY += e->mouse_dy;
}
else if ( canOrbit && m_rightDown )
{
m_radialZoomDY += e->mouse_dy;
}
else if ( !canOrbit && m_rightDown )
{
// Fly-look: routed into the same orbit accumulators; Update
// interprets them differently when m_rightDown && !m_altDown.
m_orbitDX += e->mouse_dx;
m_orbitDY += e->mouse_dy;
}
break;
case SAPP_EVENTTYPE_MOUSE_SCROLL:
if ( !canOrbit && m_rightDown )
m_speedScrollAccum += e->scroll_y;
else
m_scrollAccum += e->scroll_y;
break;
case SAPP_EVENTTYPE_KEY_DOWN:
switch ( e->key_code )
{
case SAPP_KEYCODE_W:
m_wDown = true;
break;
case SAPP_KEYCODE_A:
m_aDown = true;
break;
case SAPP_KEYCODE_S:
m_sDown = true;
break;
case SAPP_KEYCODE_D:
m_dDown = true;
break;
case SAPP_KEYCODE_LEFT_ALT:
case SAPP_KEYCODE_RIGHT_ALT:
m_altDown = true;
break;
default:
break;
}
break;
case SAPP_EVENTTYPE_KEY_UP:
switch ( e->key_code )
{
case SAPP_KEYCODE_W:
m_wDown = false;
break;
case SAPP_KEYCODE_A:
m_aDown = false;
break;
case SAPP_KEYCODE_S:
m_sDown = false;
break;
case SAPP_KEYCODE_D:
m_dDown = false;
break;
case SAPP_KEYCODE_LEFT_ALT:
case SAPP_KEYCODE_RIGHT_ALT:
m_altDown = false;
break;
default:
break;
}
break;
case SAPP_EVENTTYPE_UNFOCUSED:
// Drop every held input on focus loss. Otherwise a drag or a held WASD
// key survives an alt-tab and the camera keeps moving.
m_leftDown = false;
m_rightDown = false;
m_middleDown = false;
m_wDown = false;
m_aDown = false;
m_sDown = false;
m_dDown = false;
m_altDown = false;
break;
default:
break;
}
}
void Camera::Update( float dt, int width, int height )
{
m_width = width;
m_height = height;
const float aspect = ( height > 0 ) ? (float)width / (float)height : 1.0f;
if ( m_thirdPerson )
{
// Follow cam: the sample drives m_pivot to the tracked body and calls
// UpdateTransform. The only camera input is wheel zoom on the radius.
if ( m_scrollAccum != 0.0f )
{
m_radius -= m_scrollAccum;
if ( m_radius < THIRD_PERSON_MIN_RADIUS )
m_radius = THIRD_PERSON_MIN_RADIUS;
}
// Drop the other accumulators so a return to orbit/fly starts clean.
m_orbitDX = 0.0f;
m_orbitDY = 0.0f;
m_panDX = 0.0f;
m_panDY = 0.0f;
m_radialZoomDY = 0.0f;
m_scrollAccum = 0.0f;
m_speedScrollAccum = 0.0f;
RebuildBasisAndView( *this );
RebuildProj( aspect );
return;
}
const bool flyMode = m_rightDown && !m_altDown;
if ( flyMode )
{
// Snapshot eye BEFORE rotating so yaw/pitch pivot around the eye
// (FPS) instead of around m_pivot (orbit). After rotation we
// back-derive m_pivot from this preserved eye so Position()
// returns the same point regardless of look angle.
const b3Vec3 eyeBefore = Position();
// FPS look: drag right -> yaw decreases (turn head right, scene
// shifts left); drag down -> pitch increases (look down). Box3D's
// signs - opposite of render3d's orbit pitch sign on purpose.
if ( m_orbitDX != 0.0f || m_orbitDY != 0.0f )
{
m_yaw -= m_orbitDX * FLY_LOOK_SENS;
m_pitch += m_orbitDY * FLY_LOOK_SENS;
if ( m_pitch > PITCH_LIM )
m_pitch = PITCH_LIM;
if ( m_pitch < -PITCH_LIM )
m_pitch = -PITCH_LIM;
}
const b3Vec3 forward = ForwardFromAngles( m_yaw, m_pitch );
float wasdF = 0.0f; // +forward = backwards, since forward = pivot->eye
float wasdR = 0.0f;
if ( m_wDown )
wasdF -= 1.0f;
if ( m_sDown )
wasdF += 1.0f;
if ( m_dDown )
wasdR += 1.0f;
if ( m_aDown )
wasdR -= 1.0f;
b3Vec3 eye = eyeBefore;
if ( wasdF != 0.0f || wasdR != 0.0f )
{
// Right = normalize(worldUp x forward), matching Box3D's
// UpdateTransform. worldUp = (0,1,0).
const b3Vec3 worldUp = { 0.0f, 1.0f, 0.0f };
b3Vec3 right = b3Cross( worldUp, forward );
const float rlen = sqrtf( right.x * right.x + right.y * right.y + right.z * right.z );
if ( rlen > 1.0e-6f )
{
right.x /= rlen;
right.y /= rlen;
right.z /= rlen;
}
const float step = m_speed * dt;
eye.x += forward.x * wasdF * step + right.x * wasdR * step;
eye.y += forward.y * wasdF * step + right.y * wasdR * step;
eye.z += forward.z * wasdF * step + right.z * wasdR * step;
}
// Back-derive the pivot so Position() stays consistent and a return
// to orbit mode preserves the current look direction.
m_pivot.x = eye.x - forward.x * m_radius;
m_pivot.y = eye.y - forward.y * m_radius;
m_pivot.z = eye.z - forward.z * m_radius;
if ( m_speedScrollAccum != 0.0f )
{
m_speed += m_speedScrollAccum * FLY_SPEED_STEP;
if ( m_speed < MIN_SPEED )
m_speed = MIN_SPEED;
if ( m_speed > MAX_SPEED )
m_speed = MAX_SPEED;
}
}
else
{
// Orbit mode.
if ( m_orbitDX != 0.0f || m_orbitDY != 0.0f )
{
m_yaw -= m_orbitDX * ORBIT_SENS;
m_pitch -= m_orbitDY * ORBIT_SENS;
if ( m_pitch > PITCH_LIM )
m_pitch = PITCH_LIM;
if ( m_pitch < -PITCH_LIM )
m_pitch = -PITCH_LIM;
}
if ( m_panDX != 0.0f || m_panDY != 0.0f )
{
// Move pivot along view-space right/up. m_right / m_up are still
// last frame's values (orbit yaw/pitch haven't been rebuilt yet),
// which matches the screen the user dragged against.
const float panScale = PAN_SENS * m_radius;
m_pivot.x -= m_right.x * m_panDX * panScale;
m_pivot.y -= m_right.y * m_panDX * panScale;
m_pivot.z -= m_right.z * m_panDX * panScale;
m_pivot.x += m_up.x * m_panDY * panScale;
m_pivot.y += m_up.y * m_panDY * panScale;
m_pivot.z += m_up.z * m_panDY * panScale;
}
if ( m_radialZoomDY != 0.0f )
{
// Drag down -> zoom in (radius shrinks). Matches Box3D.
m_radius -= RADIAL_ZOOM_SENS * m_radialZoomDY;
if ( m_radius < MIN_DIST )
m_radius = MIN_DIST;
if ( m_radius > MAX_DIST )
m_radius = MAX_DIST;
}
if ( m_scrollAccum != 0.0f )
{
m_radius *= powf( ZOOM_STEP, m_scrollAccum );
if ( m_radius < MIN_DIST )
m_radius = MIN_DIST;
if ( m_radius > MAX_DIST )
m_radius = MAX_DIST;
}
}
// Keep yaw bounded across long sessions. b3UnwindAngle wraps to (-pi, pi].
m_yaw = b3UnwindAngle( m_yaw );
m_orbitDX = 0.0f;
m_orbitDY = 0.0f;
m_panDX = 0.0f;
m_panDY = 0.0f;
m_radialZoomDY = 0.0f;
m_scrollAccum = 0.0f;
m_speedScrollAccum = 0.0f;
RebuildBasisAndView( *this );
RebuildProj( aspect );
}

198
samples/host/camera.h Normal file
View file

@ -0,0 +1,198 @@
// Orbit + fly camera, modeled after Box3D's sample camera.
//
// Two modes share one state. Sticky mouse-button + Alt-modifier flags
// select which mode each gesture drives:
//
// ORBIT (Alt held)
// Alt + left-drag : orbit (yaw/pitch around pivot)
// Alt + middle-drag : pan pivot in view-space XY
// Alt + right-drag-Y : radial zoom (adjust radius)
//
// FLY (right mouse held, no Alt)
// right-drag : FPS look (yaw/pitch the view direction)
// WASD : translate eye along view forward/right at m_speed
// scroll : tune m_speed
//
// Always
// bare scroll : multiplicative zoom on radius
//
// OnEvent accumulates input deltas; Update consumes them and folds them
// into the camera state. View / Proj produce the matrices the renderer
// consumes.
//
// m_pivot is the look-at pivot, m_radius the radial offset, m_yaw / m_pitch
// the spherical angles in radians. In fly mode the eye is the primary anchor
// and m_pivot is back-derived so re-entering orbit mode preserves the look
// direction. Box3D's sample camera keeps yaw/pitch in degrees, so SetView
// converts at the boundary.
#pragma once
#include "gfx/utility.h"
struct sapp_event;
// World-space ray from a screen pixel: origin sits on the near plane,
// translation spans near -> far. Feeds straight into b3World_CastRay*.
struct PickRay
{
b3Vec3 origin;
b3Vec3 translation;
};
class Camera
{
public:
Camera();
// Feed each sokol_app event here. Safe to call from event_cb at any
// time during the frame; deltas are summed and consumed by Update().
void OnEvent( const sapp_event* e );
// Width/height are the latched framebuffer pixels; aspect derives from
// them and they back BuildPickRay and ImGui bottom-anchored panels.
void Update( float dt, int width, int height );
Mat4 View() const
{
return m_view;
}
Mat4 ViewInverse() const
{
return m_viewInv;
}
Mat4 Proj() const
{
return m_proj;
}
Mat4 ProjInverse() const
{
return m_projInv;
}
b3Vec3 Position() const;
// Cached basis accessors (Box3D parity). Forward is +view-Z (pivot -> eye),
// so the look direction is -GetForward().
b3Vec3 GetPosition() const
{
return m_position;
}
b3Vec3 GetForward() const
{
return m_forward;
}
b3Vec3 GetRight() const
{
return m_right;
}
b3Vec3 GetUp() const
{
return m_up;
}
// Snap to a fixed orientation; used by scene init paths that frame
// the camera independently of mouse state.
void SetOrbit( float yawRadians, float pitchRadians, float radius );
// Box3D's sample signature: angles in degrees, pivot folded in. Mirrors
// the ~140 sample call sites exactly so they need no edits.
void SetView( float yawDegrees, float pitchDegrees, float radius, b3Vec3 pivot = b3Vec3_zero );
void SetPivot( b3Vec3 pivot )
{
m_pivot = pivot;
}
// Forwarder for existing render3d call sites.
void SetTarget( b3Vec3 target )
{
m_pivot = target;
}
// Frame an AABB: keep current yaw/pitch, move pivot to the AABB center,
// and refit radius so the AABB fits in view at the current FOV+aspect.
// `padding` (>= 1) scales the fit radius (1.2 leaves a small margin).
// A degenerate / invalid AABB is a no-op.
void Frame( b3AABB aabb, float aspect, float padding );
void SetFov( float fovRadians )
{
m_fov = fovRadians;
}
void SetClip( float near, float far )
{
m_near = near;
m_far = far;
}
// Recomputes the projection. Call after any SetFov / SetClip change, or
// when the target framebuffer aspect changes outside Update().
void RebuildProj( float aspect );
// Recompute the basis + view from yaw/pitch/pivot/radius. Public entry
// point for sample code that mutates m_pivot directly (third-person follow).
void UpdateTransform();
// World-space pick ray from a framebuffer-pixel coordinate, using the
// latched camera state. Wraps the free function in gfx/picking.h; hands
// back a zero-translation ray (origin at the eye) if that state is not
// ready yet, so callers never read uninitialized values.
PickRay BuildPickRay( float x, float y ) const;
b3Vec3 m_pivot;
float m_yaw; // radians, around Y
float m_pitch; // radians, around camera-frame X
float m_radius; // meters from pivot
float m_fov; // radians, vertical
float m_near;
float m_far;
// Fly-mode translation speed, m/s. Scroll-tunable while right-mouse held.
float m_speed;
// Latched framebuffer pixels, refreshed each Update. Sample UI anchors
// panels relative to m_height.
int m_width;
int m_height;
// Locks input to wheel-zoom; the sample drives m_pivot to a followed body
// and calls UpdateTransform. Eye placement stays the orbit formula.
bool m_thirdPerson;
// Cached basis (Box3D-style: forward is +view-Z, i.e. pivot->eye), refreshed
// alongside m_view / m_viewInv whenever yaw/pitch/pivot/radius change.
// These let consumers (picking, shadow frustum) skip re-inverting m_view.
b3Vec3 m_position;
b3Vec3 m_right;
b3Vec3 m_up;
b3Vec3 m_forward;
// All four matrices are produced together — view / viewInv from the basis,
// proj / projInv from fov/aspect/near/far — so the renderer never inverts
// at runtime.
Mat4 m_view;
Mat4 m_viewInv;
Mat4 m_proj;
Mat4 m_projInv;
// Per-frame input deltas accumulated by OnEvent and zeroed by Update.
// Routing into the right bucket happens in OnEvent based on which mouse
// buttons + Alt are held when the event arrives.
float m_orbitDX = 0.0f; // alt+left-drag, or right-drag (fly look)
float m_orbitDY = 0.0f;
float m_panDX = 0.0f; // alt+middle-drag
float m_panDY = 0.0f;
float m_radialZoomDY = 0.0f; // alt+right-drag, Y component
float m_scrollAccum = 0.0f; // bare scroll: orbit zoom
float m_speedScrollAccum = 0.0f; // scroll while right held (no alt): tune speed
// Sticky button/key state, toggled by MOUSE_DOWN/UP and KEY_DOWN/UP.
bool m_leftDown = false;
bool m_rightDown = false;
bool m_middleDown = false;
bool m_altDown = false;
bool m_wDown = false;
bool m_aDown = false;
bool m_sDown = false;
bool m_dDown = false;
};

402
samples/host/gui.cpp Normal file
View file

@ -0,0 +1,402 @@
// Dear ImGui shell - implementation.
//
// Owns the simgui setup and the ImGui pass, runs the app's UI draw callback
// (the menu bar, panels, and diagnostics drawn by DrawUI), and
// drains the in-world text overlay. Panels are anchored with BeginPanel /
// EndPanel; the menu bar and drawer the app draws itself.
//
// Render path: ImGui draws on a NEW swapchain pass opened in RenderUI,
// LOADed on top of the already-tonemapped swapchain image. The simgui
// pipeline therefore inherits the swapchain's color + depth format and
// sample_count=1.
#include "gui.h"
#include "gfx/draw.h"
#include "gfx/projection.h"
#include "gfx/renderer.h"
#include "gfx/text.h"
#include "imgui.h"
#include "implot.h"
#include "sokol_app.h"
#include "sokol_imgui.h"
#include "sokol_log.h"
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
static bool s_uiInitialized = false;
// Display scale (sapp_dpi_scale) latched once in InitUI. ImGui runs in
// physical framebuffer pixels, so panel code multiplies explicit pixel sizes
// by this; the font atlas and the rest of the style are pre-scaled by it too.
static float s_uiScale = 1.0f;
static DrawUiFcn* s_uiCallback;
// Restyle Dear ImGui away from the stock dark theme: a desaturated steel-blue
// accent over neutral charcoal, one consistent rounding system, and roomier
// padding. Sets base (unscaled) metrics - InitUI runs ScaleAllSizes after
// this on hi-DPI displays; colors are scale-independent so they need no pass.
static void guiApplyStyle( void )
{
ImGuiStyle& style = ImGui::GetStyle();
// Metrics: containers round at 4px, controls at 3px - one deliberate
// system instead of the stock mix. Padding gives rows room to breathe.
style.WindowPadding = ImVec2( 10.0f, 10.0f );
style.FramePadding = ImVec2( 8.0f, 4.0f );
style.CellPadding = ImVec2( 6.0f, 4.0f );
style.ItemSpacing = ImVec2( 8.0f, 7.0f );
style.ItemInnerSpacing = ImVec2( 7.0f, 4.0f );
style.IndentSpacing = 18.0f;
style.ScrollbarSize = 12.0f;
style.GrabMinSize = 10.0f;
style.WindowBorderSize = 1.0f;
style.FrameBorderSize = 0.0f;
style.PopupBorderSize = 1.0f;
style.TabBorderSize = 0.0f;
style.SeparatorTextBorderSize = 1.0f;
style.WindowRounding = 4.0f;
style.ChildRounding = 4.0f;
style.PopupRounding = 4.0f;
style.FrameRounding = 3.0f;
style.GrabRounding = 3.0f;
style.ScrollbarRounding = 3.0f;
style.TabRounding = 3.0f;
style.WindowTitleAlign = ImVec2( 0.0f, 0.5f );
// Palette: neutral charcoal surfaces, one steel-blue accent at three
// brightnesses. Replaces stock ImGui's saturated cornflower blue.
const ImVec4 accent = ImVec4( 0.28f, 0.48f, 0.66f, 1.00f );
const ImVec4 accentHi = ImVec4( 0.38f, 0.60f, 0.80f, 1.00f );
const ImVec4 accentLo = ImVec4( 0.22f, 0.36f, 0.50f, 1.00f );
ImVec4* c = style.Colors;
c[ImGuiCol_Text] = ImVec4( 0.90f, 0.91f, 0.93f, 1.00f );
c[ImGuiCol_TextDisabled] = ImVec4( 0.49f, 0.51f, 0.55f, 1.00f );
c[ImGuiCol_WindowBg] = ImVec4( 0.110f, 0.115f, 0.125f, 0.97f );
c[ImGuiCol_ChildBg] = ImVec4( 0.00f, 0.00f, 0.00f, 0.00f );
c[ImGuiCol_PopupBg] = ImVec4( 0.100f, 0.105f, 0.115f, 0.98f );
c[ImGuiCol_Border] = ImVec4( 0.00f, 0.00f, 0.00f, 0.45f );
c[ImGuiCol_BorderShadow] = ImVec4( 0.00f, 0.00f, 0.00f, 0.00f );
c[ImGuiCol_FrameBg] = ImVec4( 0.18f, 0.19f, 0.21f, 1.00f );
c[ImGuiCol_FrameBgHovered] = ImVec4( 0.24f, 0.26f, 0.29f, 1.00f );
c[ImGuiCol_FrameBgActive] = ImVec4( 0.29f, 0.32f, 0.36f, 1.00f );
c[ImGuiCol_TitleBg] = ImVec4( 0.090f, 0.095f, 0.105f, 1.00f );
c[ImGuiCol_TitleBgActive] = ImVec4( 0.14f, 0.16f, 0.19f, 1.00f );
c[ImGuiCol_TitleBgCollapsed] = ImVec4( 0.090f, 0.095f, 0.105f, 0.75f );
c[ImGuiCol_MenuBarBg] = ImVec4( 0.13f, 0.14f, 0.16f, 1.00f );
c[ImGuiCol_ScrollbarBg] = ImVec4( 0.06f, 0.06f, 0.07f, 0.55f );
c[ImGuiCol_ScrollbarGrab] = ImVec4( 0.28f, 0.30f, 0.33f, 1.00f );
c[ImGuiCol_ScrollbarGrabHovered] = ImVec4( 0.36f, 0.39f, 0.43f, 1.00f );
c[ImGuiCol_ScrollbarGrabActive] = accent;
c[ImGuiCol_CheckMark] = accentHi;
c[ImGuiCol_SliderGrab] = accent;
c[ImGuiCol_SliderGrabActive] = accentHi;
c[ImGuiCol_Button] = ImVec4( 0.22f, 0.24f, 0.27f, 1.00f );
c[ImGuiCol_ButtonHovered] = accentLo;
c[ImGuiCol_ButtonActive] = accent;
c[ImGuiCol_Header] = ImVec4( 0.19f, 0.21f, 0.24f, 1.00f );
c[ImGuiCol_HeaderHovered] = accentLo;
c[ImGuiCol_HeaderActive] = accent;
c[ImGuiCol_Separator] = ImVec4( 1.00f, 1.00f, 1.00f, 0.09f );
c[ImGuiCol_SeparatorHovered] = accentLo;
c[ImGuiCol_SeparatorActive] = accent;
c[ImGuiCol_ResizeGrip] = ImVec4( 1.00f, 1.00f, 1.00f, 0.06f );
c[ImGuiCol_ResizeGripHovered] = accentLo;
c[ImGuiCol_ResizeGripActive] = accent;
c[ImGuiCol_Tab] = ImVec4( 0.15f, 0.16f, 0.18f, 1.00f );
c[ImGuiCol_TabHovered] = accentLo;
c[ImGuiCol_TabSelected] = accent;
c[ImGuiCol_TabSelectedOverline] = accentHi;
c[ImGuiCol_TabDimmed] = ImVec4( 0.12f, 0.13f, 0.14f, 1.00f );
c[ImGuiCol_TabDimmedSelected] = accentLo;
c[ImGuiCol_TextSelectedBg] = ImVec4( accent.x, accent.y, accent.z, 0.40f );
c[ImGuiCol_DragDropTarget] = accentHi;
c[ImGuiCol_NavCursor] = accentHi;
c[ImGuiCol_PlotLines] = ImVec4( 0.70f, 0.72f, 0.75f, 1.00f );
c[ImGuiCol_PlotLinesHovered] = accentHi;
c[ImGuiCol_PlotHistogram] = accent;
c[ImGuiCol_PlotHistogramHovered] = accentHi;
}
void InitUI( const sg_environment* env, DrawUiFcn* drawGuiFcn )
{
s_uiCallback = drawGuiFcn;
simgui_desc_t desc = {};
desc.color_format = env->defaults.color_format;
desc.depth_format = env->defaults.depth_format;
desc.sample_count = env->defaults.sample_count;
desc.ini_filename = "imgui.ini";
desc.logger.func = slog_func;
// Skip ImGui's auto-pick so we always get the vector font we add below.
desc.no_default_font = true;
simgui_setup( &desc );
// simgui_setup creates the ImGui context, so ImPlot has to come after it.
ImPlot::CreateContext();
// DPI handling mirrors the Box2D sample app, which gets crisp text at
// fractional Windows display scales. ImGui runs in physical framebuffer
// pixels: StartUIFrame feeds simgui dpi_scale=1.0, so DisplaySize is the
// framebuffer size and DisplayFramebufferScale is 1.0. The display scale
// is then applied by hand - the font atlas is baked once at an integer
// pixel size and ScaleAllSizes scales the rest of the style. Drawing
// ImGui 1:1 against the framebuffer with an integer-sized atlas is what
// keeps glyphs sharp; letting sokol_imgui scale a logical-pixel UI up by
// a fractional factor instead leaves every glyph on a sub-pixel boundary.
s_uiScale = sapp_dpi_scale();
ImGuiIO& io = ImGui::GetIO();
io.Fonts->Clear();
// Restyle before the hi-DPI branch: guiApplyStyle sets base metrics, then
// ScaleAllSizes (below) multiplies them up. Colors are unscaled.
guiApplyStyle();
io.Fonts->AddFontDefaultVector();
ImGuiStyle& style = ImGui::GetStyle();
if ( s_uiScale != 1.0f )
{
style.ScaleAllSizes( s_uiScale );
}
// 13px base for the proportional UI font, scaled to a whole physical
// pixel. Rasterizer density is 1.0 (DisplayFramebufferScale 1.0), so the
// atlas bakes at exactly this - floorf keeps it on a whole-pixel size.
style.FontSizeBase = floorf( 13.0f * s_uiScale );
s_uiInitialized = true;
}
void ShutdownUI( void )
{
if ( !s_uiInitialized )
return;
ImPlot::DestroyContext();
simgui_shutdown();
s_uiInitialized = false;
}
bool HandleEvent( const sapp_event* e )
{
if ( !s_uiInitialized )
{
return false;
}
bool handled = simgui_handle_event( e );
const ImGuiIO& io = ImGui::GetIO();
if ( handled )
{
return true;
}
if ( e->type == SAPP_EVENTTYPE_KEY_DOWN || e->type == SAPP_EVENTTYPE_KEY_UP || e->type == SAPP_EVENTTYPE_CHAR )
{
return io.WantCaptureKeyboard;
}
if ( e->type == SAPP_EVENTTYPE_MOUSE_DOWN || e->type == SAPP_EVENTTYPE_MOUSE_UP || e->type == SAPP_EVENTTYPE_MOUSE_MOVE ||
e->type == SAPP_EVENTTYPE_MOUSE_SCROLL )
{
return io.WantCaptureMouse;
}
return false;
}
// Gap between a panel and the window edge
static const float PANEL_GAP = 5.0f;
// Running top Y for the next panel on each side, indexed by GuiPanelAnchor.
static float s_panelCursorY[2];
// Side of the panel currently open between guiBeginPanel and guiEndPanel.
static GuiPanelAnchor s_panelOpenSide;
static bool s_panelOpen = false;
static void ResetUIPanelLayout( void )
{
const ImGuiViewport* vp = ImGui::GetMainViewport();
// Clear the main menu bar. Without docking the bar does not shrink the
// viewport work area, so panels would otherwise start under it.
const float top = vp->WorkPos.y + ImGui::GetFrameHeight() + PANEL_GAP * s_uiScale;
s_panelCursorY[GUI_ANCHOR_LEFT] = top;
s_panelCursorY[GUI_ANCHOR_RIGHT] = top;
s_panelOpen = false;
}
bool BeginPanel( const char* name, GuiPanelAnchor anchor, float width )
{
ImGuiViewport* vp = ImGui::GetMainViewport();
float gap = PANEL_GAP * s_uiScale;
float w = width * s_uiScale;
float cursorY = s_panelCursorY[anchor];
// Left panels pin their top-left corner to the left edge; right panels
// pin their top-right corner to the right edge (pivot picks the corner).
float anchorX;
ImVec2 pivot;
if ( anchor == GUI_ANCHOR_RIGHT )
{
anchorX = vp->WorkPos.x + vp->WorkSize.x - gap;
pivot = ImVec2( 1.0f, 0.0f );
}
else
{
anchorX = vp->WorkPos.x + gap;
pivot = ImVec2( 0.0f, 0.0f );
}
ImGui::SetNextWindowPos( ImVec2( anchorX, cursorY ), ImGuiCond_Always, pivot );
// SetNextWindowSize y=0 auto-fits height to content; the constraint caps
// it so a tall panel can't run past the window's bottom edge (the panel
// gains a scrollbar past the cap). Width is locked to w by both calls.
float maxH = vp->WorkPos.y + vp->WorkSize.y - gap - cursorY;
if ( maxH < ImGui::GetFrameHeight() )
maxH = ImGui::GetFrameHeight();
ImGui::SetNextWindowSizeConstraints( ImVec2( w, 0.0f ), ImVec2( w, maxH ) );
ImGui::SetNextWindowSize( ImVec2( w, 0.0f ), ImGuiCond_Always );
s_panelOpenSide = anchor;
s_panelOpen = true;
return ImGui::Begin( name, nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize );
}
void EndPanel( void )
{
// Advance this side's cursor past the panel just drawn so the next panel
// stacks directly below it. GetWindowSize is valid here whether or not
// Begin returned true - a collapsed panel reports its title-bar height,
// so the next panel snugs up under the collapsed bar.
if ( s_panelOpen )
{
s_panelCursorY[s_panelOpenSide] += ImGui::GetWindowSize().y + PANEL_GAP * s_uiScale;
s_panelOpen = false;
}
ImGui::End();
}
// Text overlay. Drain the per-frame label arena (filled by DrawString /
// DrawScreenString and the Box3D adapter's DrawString callback). World
// entries project to screen pixels with the last rendered camera, screen
// entries pass through their pixel position, and both emit into ImGui's
// background draw list - labels sit on the scene but under any ImGui
// windows. The drain runs in StartUIFrame because the calling app
// guarantees RenderFrame already ran this frame, so GetCameraState
// returns the matrices the scene was actually rasterized with.
static void RenderText()
{
const int n = GetTextCount();
if ( n <= 0 )
return;
const CameraState cam = GetCameraState();
if ( cam.viewportW <= 0 || cam.viewportH <= 0 )
return;
// ImGui runs in physical framebuffer pixels (see InitUI), so the main
// viewport's Size matches cam.viewportW/H. Project against the viewport
// Size and offset by vp->Pos so this stays correct even if ImGui's space
// ever gains an origin offset. Aspect is encoded in cam.proj, so any
// width/height with the scene's ratio yields identical NDC.
ImGuiViewport* vp = ImGui::GetMainViewport();
const int vpW = (int)vp->Size.x;
const int vpH = (int)vp->Size.y;
if ( vpW <= 0 || vpH <= 0 )
return;
ImDrawList* dl = ImGui::GetBackgroundDrawList();
const ImVec2 origin = vp->Pos;
for ( int i = 0; i < n; ++i )
{
const TextEntry* e = GetTextAt( i );
float sx, sy;
if ( !ResolveTextScreenPos( e, cam.view, cam.proj, vpW, vpH, &sx, &sy ) )
{
continue;
}
// Linear-to-byte: pass straight through (no sRGB encode) - matches
// how Box3D's b3HexColor literals reach the Draw* path, so a label
// color reads the same as the SVG hex it came from.
const auto byte = []( float v ) -> uint32_t {
if ( v < 0.0f )
v = 0.0f;
if ( v > 1.0f )
v = 1.0f;
return (uint32_t)( v * 255.0f + 0.5f );
};
const uint32_t col = IM_COL32( byte( e->color.x ), byte( e->color.y ), byte( e->color.z ), byte( e->color.w ) );
dl->AddText( nullptr, 0.0f, ImVec2( origin.x + sx, origin.y + sy ), col, e->text );
}
}
void StartUIFrame( float dtSec )
{
if ( !s_uiInitialized )
{
return;
}
simgui_frame_desc_t fd = {};
fd.width = sapp_width();
fd.height = sapp_height();
// Clamp the delta we hand to ImGui to at least ~1ms. With swap_interval=0
// sokol_app can call OnFrame back-to-back fast enough that stm_laptime
// returns sub-microsecond deltas, and once cast to float ImGui's g.Time
// fails to advance. That breaks the per-frame reset of the BG/FG draw
// lists (their reset gate is `(float)BgFgDrawListsLastTimeActive !=
// (float)g.Time`), so subsequent AddText calls into the background draw
// list pile on top of the prior frame's vertices instead of replacing
// them - visible as in-world labels flickering bright/dim as overlapping
// copies alpha-blend over each other.
const float kMinDt = 1.0f / 1000.0f;
fd.delta_time = ( dtSec >= kMinDt ) ? (double)dtSec : (double)kMinDt;
// dpi_scale 1.0 on purpose: it keeps ImGui in physical framebuffer pixels
// (DisplaySize = framebuffer, DisplayFramebufferScale = 1.0). The display
// scale is baked into the font and style in InitUI instead. See there.
fd.dpi_scale = 1.0f;
simgui_new_frame( &fd );
// Reset the edge-anchor cursors before any panel opens - they accumulate
// per panel within this frame and must start fresh each frame.
ResetUIPanelLayout();
// The callback runs every frame; it branches on the sample context's showUI
// (full UI vs the minimal HUD) the way Box2D's DrawUI does.
if ( s_uiCallback != nullptr )
{
s_uiCallback();
}
RenderText();
}
void RenderUI( const sg_swapchain* swapchain )
{
if ( !s_uiInitialized )
{
return;
}
sg_pass pass = {};
pass.action.colors[0].load_action = SG_LOADACTION_LOAD; // sit on top of tonemap
pass.action.depth.load_action = SG_LOADACTION_DONTCARE;
pass.action.stencil.load_action = SG_LOADACTION_DONTCARE;
pass.swapchain = *swapchain;
pass.label = "imgui";
sg_begin_pass( &pass );
simgui_render();
sg_end_pass();
}

56
samples/host/gui.h Normal file
View file

@ -0,0 +1,56 @@
// Dear ImGui shell.
//
// Wraps sokol_imgui.h, runs the app's UI draw callback (the DrawUiFcn passed
// to InitUI) on top of the live scene, and drains the in-world text overlay.
// Used only by the renderer binary; the visual-test targets call
// RenderFrameOffscreen directly and never instantiate ImGui.
//
// Lifecycle from main.cpp's sapp callbacks:
//
// OnInit: InitRenderer(&env); InitUI(&env, DrawUI);
// OnEvent: if (HandleEvent(e)) return; // skip camera if ImGui ate it
// OnFrame: ResetFrameArena();
// scene draws...
// RenderFrame(&sc, &frame);
// StartUIFrame(dt); // runs the UI draw callback, drains in-world text
// RenderUI(&sc); // separate pass on the swapchain
// OnCleanup: ShutdownUI(); ShutdownRenderer();
//
// RenderUI opens its own swapchain pass with LOAD action so ImGui sits on
// top of the tonemapped scene without disturbing it. Single-threaded;
// render-thread only.
#pragma once
#include "sokol_app.h"
#include "sokol_gfx.h"
// Screen edge a panel anchors to. Panels sharing a side stack top-down in
// the order they call guiBeginPanel within a frame.
typedef enum GuiPanelAnchor
{
GUI_ANCHOR_LEFT = 0,
GUI_ANCHOR_RIGHT = 1,
} GuiPanelAnchor;
typedef void DrawUiFcn( void );
void InitUI( const sg_environment* env, DrawUiFcn* drawGuiFcn );
void ShutdownUI( void );
bool HandleEvent( const sapp_event* e );
void StartUIFrame( float dtSec );
void RenderUI( const sg_swapchain* swapchain );
// Begin an edge-anchored panel. A thin wrapper over ImGui::Begin. Pins the
// window flush against anchor's screen edge, stacked below any panel
// already opened on that side this frame, and re-anchors it there every
// frame so it tracks the edge when the window resizes (unlike a one-shot
// ImGuiCond_FirstUseEver position, which drifts off a shrinking window).
// width is in unscaled pixels. The UI DPI scale is applied internally.
// Height auto-fits the content, capped to the remaining viewport height
// (the panel gains a scrollbar past the cap). Returns ImGui::Begin's value;
// pair every call with EndPanel, including when it returns false.
bool BeginPanel( const char* name, GuiPanelAnchor anchor, float width );
void EndPanel( void );

View file

@ -0,0 +1,17 @@
// Single translation unit for sokol_imgui.h's implementation.
//
// Built as C++ so it can call into the C++ Dear ImGui API directly (the C
// path needs cimgui, which we don't pull in). Compiled as part of the
// renderer binary; not linked into tests, which never instantiate the GUI.
//
// The sokol_app/glue/time *_IMPL macros live in src/app/sokol_app_impl.c and
// sokol_gfx's SOKOL_IMPL lives in src/gfx/sokol_impl.c - we only enable
// SOKOL_IMGUI_IMPL here.
#include "imgui.h"
#include "sokol_gfx.h"
#include "sokol_app.h"
#define SOKOL_IMGUI_IMPL
#include "sokol_imgui.h"

View file

@ -0,0 +1,29 @@
// Single-TU build of sokol_app + sokol_glue + sokol_time.
//
// sokol_gfx's implementation lives in src/gfx/sokol_impl.c. We only include
// its header here (without SOKOL_IMPL) so that sokol_glue can see the
// sg_environment / sg_swapchain declarations it translates into.
//
// Backend macro (SOKOL_D3D11 / SOKOL_METAL / SOKOL_GLCORE) comes from the
// `sokol` INTERFACE target. On Apple this file is compiled as Objective-C
// with ARC (see src/app/CMakeLists.txt) so sokol_app's Cocoa backend builds.
//
// SOKOL_WIN32_FORCE_MAIN: sokol_app defaults to WinMain (subsystem:windows)
// on Windows. Our binaries are console-subsystem so the smoke test can
// surface stderr to ctest, so force the int main variant.
//
// _POSIX_C_SOURCE: glibc gates clock_gettime / CLOCK_MONOTONIC behind a
// POSIX feature-test macro under -std=c17. Define before any system headers.
#if defined(__linux__) && !defined(_POSIX_C_SOURCE)
#define _POSIX_C_SOURCE 200809L
#endif
#define SOKOL_APP_IMPL
#define SOKOL_GLUE_IMPL
#define SOKOL_LOG_IMPL
#define SOKOL_WIN32_FORCE_MAIN
#include "sokol_gfx.h"
#include "sokol_app.h"
#include "sokol_glue.h"
#include "sokol_log.h"