Modelling the eye II: The pupil
Part 2 of the WebGL eye series. We build a dynamic pupil, program the light reflex, and connect real eye-tracking hardware.
Published
In Part 1 we shaped the cornea, the fixed front lens of the eye. But a camera needs more than a lens: it needs an aperture, an adjustable hole that controls how much light gets in. In the eye that hole is the pupil, and the coloured ring around it, the iris, contains the muscles that open and close it.
Renaissance women used drops of deadly nightshade (Atropa belladonna, “beautiful lady”) to widen their pupils for cosmetic effect, often not knowing the plant was quietly poisoning them.
The pupil is not just a passive hole. It reacts to light in a fraction of a second, it trades sharpness against brightness, and it never sits perfectly still. In this part we model the iris, work out how pupil size sets the light reaching the retina, and simulate the reflex that drives it.
The Iris: A living aperture
The iris is what gives eyes their colour, but to an optical engineer it is an adjustable aperture, with apparent pupil diameters ranging roughly between wide (in bright light) and wide (in the dark). It does this with two opposing muscles:
- The sphincter is a ring of muscle around the pupil edge. When it contracts it makes the pupil smaller (constriction). It runs on the parasympathetic “rest and digest” nervous system.
- The dilator is a set of myoepithelial cells arranged like spokes, running outward from the pupil. When it contracts it pulls the pupil open (dilation). It runs on the sympathetic “fight or flight” system.
The front of the iris is split into two rings by a wavy ridge called the collarette: an inner pupillary zone around the pupil and an outer ciliary zone out toward the white of the eye. It is dotted with pits and folds called Fuchs crypts, Wölfflin nodules in the periphery, and the pupillary ruff at the margin, along with concentric contraction furrows in the outer zone. These anatomical features are what give every iris its unique, mesmerising texture.
There are two pupils to keep apart: the physical opening in the iris and its image seen through the cornea, the entrance pupil. The cornea usually makes that image appear larger and farther forward; the magnification depends on geometry and viewing angle. The exit pupil is the image of the opening through the optics behind it. This first demo represents the iris opening; its glassy cornea is an illustrative material, not a calibrated optical simulation.
To capture this biological complexity in our simulation, the model below builds the iris in 3D under a glassy cornea (although strictly speaking, the pupil is often slightly eccentric). The iris itself is drawn in a shader whose recipe is essentially two circles: throw away everything outside the iris, paint the hole in the middle black, and fill the ring between them with procedural noise to mimic the crypts and muscle fibres.
float dist = distance(uv, center); // distance from the pupil center
if (dist > irisRadius) discard; // outside the iris: nothing to draw
if (dist < pupilRadius) { // inside the pupil: the dark hole
gl_FragColor = vec4(0.01, 0.01, 0.02, 1.0);
return;
}
// in between: the colored iris, textured with layered noise (fbm)
Viewed from the side, the entrance pupil does not behave exactly like a flat disc: corneal refraction changes its apparent shape (Mathur et al., 2013). Orbiting this demo illustrates depth, not that experimental fit.
Drag the divider to reveal the red sphincter ring and blue radial dilator fibres. Open Settings in the caption to choose the starting diameter and pigment, or pause the illustrative light-response cycle. Drag elsewhere on the eye to orbit it.
Two muscles set the pupil size: a circular sphincter that closes it and radial dilator fibers that open it.
Settings
Pupil diameter in millimetres, chosen for this visualisation. It is independent of luminance here; no eye has been measured.
Drag the divider. Motion illustrates small fluctuations and a response to brighter light.
Calculating light
Why does pupil size matter so much? Because the amount of light reaching the retina depends on the area of the entrance pupil: the cornea’s image of the hole. Small changes in pupil size have a big effect: going from a pupil in sunlight to an pupil in the dark is a 4x change in diameter, but a 16x change in area. However, area is not the whole story. The Stiles-Crawford effect of the first kind (SCE-I) shows that light entering through the edge of a wide pupil is less effective than light entering through the centre, so the effective pupil area grows more slowly than the geometric area. This happens because the retina is not a flat, uniform sensor array; its cones are directionally sensitive. Their waveguide properties help explain why oblique light couples differently; they are not simply tiny ray-optical pipes. The Stiles-Crawford effect (Stiles & Crawford, 1933) is primarily associated with cone-mediated vision, so its influence is much less relevant under fully scotopic, rod-dominated conditions.
For these calculations, diameter means entrance-pupil diameter. A troland is a convenient way to combine brightness and aperture: , with in cd/m² and the entrance-pupil area in mm². It is not a measurement of power absorbed by the retina.
Beyond just letting light in, the pupil acts as the eye’s aperture for sharpness. The point spread function (PSF) describes how a point of light spreads into an image; the modulation transfer function (MTF) describes how much contrast survives at different detail sizes. Both depend on pupil diameter. If the pupil is too small, diffraction blurs the image; if it is too large, aberrations from the cornea and lens tend to reduce image quality. Pupil diameters around 3 to 4 mm often offer a useful balance between diffraction and aberrations, but the optimum depends on the eye and the visual task; resting size is not fixed.
One step further: phase and image quality
The aperture determines which light passes; the wavefront determines how it adds together. The generalised pupil is : is amplitude transmission, is wavefront error and is wavelength. In monochromatic scalar optics, the PSF is proportional to . The OTF adds phase to contrast: . Some aberrations produce contrast reversals, not just blur.
The quartic term in primary spherical aberration grows as ; this is not a scaling law for every Zernike coefficient. Partial compensation between cornea and lens does not fix a universal optimum diameter either. Metrics such as visual Strehl (VSX) weight the PSF by neural sensitivity; these demos do not calculate that retinal image quality (Thibos et al., 2004).
NOTE
Does iris colour affect how much light enters?
Yes. Iris pigmentation affects intraocular light scatter. Dark brown irises are packed with light-absorbing melanin. Lighter irises (like blue, green, or hazel) have less melanin, which can allow more light to scatter through iris tissue. This can contribute to straylight and glare, but iris colour alone does not predict an individual’s glare sensitivity (van den Berg et al., 1991).
How big should the pupil be at a given brightness? A useful rule of thumb gives a steady-state pupil diameter following a smooth curve of scene brightness, in the spirit of Moon and Spencer (1944). (For this visualisation we use a simplified luminance-only approximation inspired by established pupil-size models. Watson & Yellott’s (2012) unified model additionally accounts for factors such as age, field size and binocular viewing. Remember that these describe steady-state adaptation, not the transient reflex).
The term is a shift chosen for this demo, not the published Moon–Spencer conversion to cd/m². Watson & Yellott review that formula alongside the later Stanley–Davies and Barten models.
This gives an illustrative diameter in millimetres across dim to bright scenes, rather than an individual prediction. In code it is a one-liner:
function pupilFromLuminance(L) { // L = scene luminance (cd/m²)
const d = 4.9 - 3.0 * Math.tanh(0.4 * Math.log10(Math.max(0.0001, L)) + 0.4);
return Math.min(8, Math.max(2, d)); // clamp to 2-8 mm
}
In the model below you set the pupil size and the scene brightness by hand and read off the light reaching the retina: the geometric pupil area, the photopic retinal illuminance in trolands (Troland, 1917), and the SCE-weighted effective area. We use a simplified, centred Gaussian efficiency profile, , choosing and therefore . This is a conventional illustrative choice, not an individual constant; directionality varies with wavelength, retinal location and observer (Westheimer, 2008). Weighting changes the estimated visual effectiveness of the light, not the physical pupil size; the unweighted troland value remains luminance times geometric pupil area.
The SCE switch changes the readouts, not the iris colour. The second-kind effect (SCE-II) concerns changes in perceived colour with the light’s pupil-entry position, and is not simulated here.
Settings
Entrance-pupil diameter in mm: the corneal image of the iris opening. Used for area and trolands here; the 3D material is not a calibrated magnification model.
Scene luminance in cd/m² is an input to the demo, not a screen calibration or measurement. The reflex uses a simplified luminance-only relationship, not the full Watson–Yellott model.
Watson & Yellott (2012): fuller modelA centred Gaussian in entrance-pupil coordinates uses rho10 = 0.05 mm⁻² (rhoE ≈ 0.115 mm⁻²). This simplified SCE efficiency changes the effective area, not the physical pupil diameter.
Stiles & Crawford (1933)The light reflex
We know how the pupil size affects incoming light, but how does the body actually regulate this size to control light entering? Shine a light in someone’s eye and their pupil shrinks. That is the pupillary light reflex (PLR). It is a simple but critical feedback loop. Light information driving the pupillary light reflex comes from rods, cones, and melanopsin-expressing ipRGCs. Rods and cones provide rapid responses, while melanopsin provides a slower, sustained contribution to pupil control. The signal shoots up the optic nerve. Retinal signals reach the olivary pretectal nuclei (OPN) through the optic nerves and tracts, with partial crossing at the optic chiasm. Pretectal neurons project to both preganglionic Edinger-Westphal cell groups (EWpg), with crossed connections through the posterior commissure. This drives the consensual light reflex in the opposite eye. Finally, the Edinger-Westphal output travels with cranial nerve III to the ciliary ganglion, then postganglionic fibres travel through the short ciliary nerves to the sphincter pupillae. Constrict, then relax.
Because this neural circuit runs deep through the brainstem, it acts as a diagnostic window into the brain. If a patient has suffered a traumatic brain injury, a doctor will shine a light in their eyes; a pupil that remains fixed and dilated can indicate severe pressure on the brainstem. The reflex is also heavily influenced by drugs, which is why opiates cause pinpoint pupils and some stimulants can produce pupil dilation.
The loop is a feedback controller, and like any real controller it is not instant. The neural pathway of this reflex is a 3D circuit that crosses the brainstem:
- 1. Retina
- 2. Optic Chiasm
- 3. Olivary Pretectal Nucleus
- 4. Edinger-Westphal Nucleus
- 5. Ciliary Ganglion
Three things shape how the pupil actually moves:
- A delay. We approximate the neural latency of the pupillary light reflex as before the pupil begins responding. This latency varies with stimulus conditions, luminance, adaptation state, and age.
- Asymmetry. Constriction is generally faster than redilation. For this visualisation we choose time constants of and respectively; these are simulation parameters, not universal physiological constants.
- Pupillary unrest. Even under perfectly steady light the pupil quivers slightly. This small spontaneous fluctuation in pupil size is often called hippus and can occur physiologically.
The delay and the asymmetry give the reflex its character. For the visualisation, we approximate the more complex PLR dynamics (like Stark’s triple lag (Stark, 1959)) with asymmetric first-order responses. Each frame, the pupil eases toward the target diameter it was told to reach ago, using a simple first-order response that moves faster when closing than when opening:
const diff = targetDiameter - currentDiameter;
const tau = diff < 0 ? 0.12 : 0.65; // fast to constrict, slow to dilate
currentDiameter += diff * (1 - Math.exp(-dt / tau)); // stable first-order update
The model below pairs the pupil with an oscilloscope. The dashed line is the target the reflex is chasing; the solid line is where the pupil actually is. Switch the light from dark to bright and watch the lag and the asymmetry play out. Turn the latency off to compare the same model response without the delay.
Scene luminance in cd/m² is an input to the demo, not a screen calibration or measurement. The reflex uses a simplified luminance-only relationship, not the full Watson–Yellott model.
Watson & Yellott (2012): fuller modelThe 220 ms delay and unequal response time constants are simulation parameters. Actual PLR timing varies with stimulus, adaptation, age and other conditions.
Beyond light: Cognitive load and pupillometry
While the light reflex is the strongest driver of the pupil, it is not the only one. The pupil’s size is a continuous tug-of-war between two opposing nervous systems:
Swipe the table sideways to compare all columns.
| System | Muscle | Action | Common Triggers | Drug Effects |
|---|---|---|---|---|
| Parasympathetic (“Rest & Digest”) | Sphincter | Constricts (Miosis) | Bright light, focusing on near objects, relaxation | Opioids commonly cause miosis through central autonomic pathways. |
| Sympathetic (“Fight or Flight”) | Dilator | Dilates (Mydriasis) | Darkness, stress, arousal, cognitive load, adrenaline | Some stimulants can produce pupil dilation. |
The sympathetic route descends from the hypothalamus to the ciliospinal centre at C8–T2, relays in the superior cervical ganglion, and reaches the dilator mainly through the long ciliary nerves. Disruption can cause miosis and ptosis, as in Horner’s syndrome (Loewenfeld, 1993; McDougal & Gamlin, 2015).
Pupils often dilate during demanding cognitive tasks. Both sympathetic activity and reduced parasympathetic drive can contribute, with response size and timing depending on arousal, visual conditions, baseline pupil size and task structure (Beatty, 1982).
The locus coeruleus–noradrenaline system contributes to the link between arousal and pupil size, but pupil diameter is not a direct readout of its activity: several circuits contribute (Joshi & Gold, 2020).
UI designers, psychologists, and researchers use eye trackers to study pupil responses associated with cognitive demand. While some have proposed using pupillometry to monitor workplace fatigue or cognitive overload in high-stakes environments like surgical theatres or air traffic control, the reality is incredibly messy. The pupil light reflex is overwhelmingly stronger than cognitive responses. Separating tiny, task-evoked dilations (often just a fraction of a millimetre) from the massive fluctuations caused by ambient lighting changes, blinks, and screen glare in a real-world environment is exceptionally difficult. In controlled laboratory settings, however, by keeping lighting strictly constant and establishing a rigorous baseline, researchers can still reliably measure these subtle markers of mental effort.
The pupil also changes size when you focus on something close to your face. This is called the near triad: your eyes converge (turn inward), your lenses accommodate (bulge to focus), and your pupils constrict. The neural pathway for this bypasses the pretectal nucleus, traveling from the visual cortex to the supraoculomotor area. Constricting the pupil when looking at something close increases your depth of field, exactly like stopping down a macro lens on a camera.
The final simulator: Putting it together
Here is everything together. Slide the scene brightness and watch the reflex fire after its delay, hit the penlight button for a sudden flash, toggle the Stiles-Crawford effect to see how much the pupil edges really count, and switch the iris pigment between brown, hazel, blue, and albino.
Settings
Scene luminance in cd/m² is an input to the demo, not a screen calibration or measurement. The reflex uses a simplified luminance-only relationship, not the full Watson–Yellott model.
Watson & Yellott (2012): fuller modelAn additive diameter offset in millimetres demonstrates a non-light influence. It is not a calibrated measure of effort, arousal or cognitive load.
Beatty (1982)A centred Gaussian in entrance-pupil coordinates uses rho10 = 0.05 mm⁻² (rhoE ≈ 0.115 mm⁻²). This simplified SCE efficiency changes the effective area, not the physical pupil diameter.
Stiles & Crawford (1933)With the cornea shaped and the pupil now opening and closing on its own, our eye controls both how light is focused and how much of it gets in.
Real-Time Pupil Size with Neon
Since we are talking about pupils, why just simulate them when you can drive the 3D model with your actual eyes? If you have access to a pair of Pupil Labs Neon eye-tracking glasses, you can hook them up directly to this blog post!
Since the Neon Companion app bundles the Monitor app, we can fetch it and embed it in a hidden iframe whose lifetime we control. By quietly reading the gaze payload from its data stream, we have everything we need without complex integrations.
Here the convention changes: Pupil Labs describes Neon’s diameter as an estimate of physical pupil size in mm, not simply its apparent diameter in the video. We keep that estimate without adding a fixed corneal-magnification correction. The 3D image is illustrative; it does not calibrate apparent size or convert Neon measurements into trolands. See the official measurement definition.
In the documented Neon eye-state gaze payload, the left and right pupil diameters are big-endian Float32s at byte offsets 9 and 37. We locate the payload after the RTP header, validate both eyes, and plot the available measurements. The graph keeps the last 1000 samples; missing-eye values appear as gaps. The measurement stream can operate at 200 Hz, depending on the Companion device and conditions, while rendering follows the browser’s animation frames.
Make sure your computer or iPad is on the same Wi-Fi network as your eye tracker, enable Compute Eye State in Companion, enter its address, and click Connect. The browser will intercept the binary stream, parse the structs on the fly, and drive the 3D iris from the mean of the valid pupil measurements, using one eye when the other is unavailable.
WARNING
This experimental browser/WebGL demo fetches and patches the Companion Monitor bundle on your local network. The pupil packet format is documented, but bundle interception is intentionally fragile: Monitor updates or browser networking and security policies can break it. For production integrations, use Pupil Labs’ official Real-Time API and client.
Neon estimates physical left/right pupil diameters in millimetres, not simply apparent video diameters. Missing eyes remain gaps. Pausing offscreen drawing does not stop acquisition.
Pupil Labs: Neon real-time dataLive pupil data comes directly from Neon on your Wi-Fi. Click Connect and allow local-network access if your browser asks.
Connection help
Your browser asks permission to stop websites accessing devices on your network without your consent. This blog also uses HTTPS, while Companion’s local service uses unencrypted HTTP. That combination can be blocked as mixed content; the insecure-content exception permits that connection but does not encrypt it.
Chrome and supported Chromium browsers can ask for local-network permission. If you denied it, open the site controls beside the address and allow local-network access, then reconnect.
If it is still blocked in desktop Chrome or Edge:
- Open the controls beside the address → Site settings (or Permissions for this site).
- Set Insecure content to Allow, only for this trusted site.
- Reload the page and click Connect. You can revoke the exception afterwards.
Names and availability vary by browser. Safari/iPhone may not offer this exception; try a local HTTP preview. CORS, networking or the WebSocket connection may still block access. This page cannot change permissions for you.
Chrome local-network permissionsReferences
- Moon, P., & Spencer, D. (1944). On the Stiles-Crawford Effect. Journal of the Optical Society of America, 34(6), 319-329. DOI: 10.1364/JOSA.34.000319
- Watson, A. B., & Yellott, J. I. (2012). A unified formula for light-adapted pupil size. Journal of Vision, 12(10), 1-16. DOI: 10.1167/12.10.12
- Stiles, W. S., & Crawford, B. H. (1933). The luminous efficiency of rays entering the eye pupil at different points. Proceedings of the Royal Society of London B, 112(778), 428-450. DOI: 10.1098/rspb.1933.0019
- Loewenfeld, I. E. (1993). The Pupil: Anatomy, Physiology, and Clinical Applications. Wayne State University Press. A foundational medical text on autonomic tone and pupillary reflex pathways.
- Stark, L. (1959). Stability, oscillations, and noise in the human pupil servomechanism. Proceedings of the IRE, 47(11), 1925-1939. DOI: 10.1109/JRPROC.1959.287206. The seminal work on the non-linear dynamics and feedback control models of the pupillary light reflex.
- Beatty, J. (1982). Task-evoked pupillary responses, processing load, and the structure of information processing. Psychological Bulletin, 91(2), 276-292. DOI: 10.1037/0033-2909.91.2.276. A rigorous review of pupillometry for measuring cognitive workload and stress.
- Troland, L. T. (1917). On the measurement of visual stimulation intensities. Journal of Experimental Psychology, 2(1), 1-33. DOI: 10.1037/h0071652
- McDougal & Gamlin (2015). Autonomic control of the eye.
- van den Berg et al. (1991). Dependence of intraocular straylight on pigmentation and light transmission through the ocular wall.
- Pupil Labs. Under the Hood: decoding gaze data; Neon data streams.
