Skip to content

Add paints, materials and lights; remove sheen, shade_in_3d and background-image colouring - #5178

Open
behackl wants to merge 10 commits into
refactor/drawing-renderersfrom
refactor/paint-material
Open

behackl wants to merge 10 commits into
refactor/drawing-renderersfrom
refactor/paint-material

Conversation

@behackl

@behackl behackl commented Nov 23, 2026

Copy link
Copy Markdown
Member

Stacked on #5177.

Overview

One model for colour and lighting, shared by mobjects, snapshots and renderers:

  • Paints (manim.paint): a VMobject has a fill, a stroke and a background_stroke, each an immutable Solid, LinearGradient or ColorField.
  • Materials (manim.material): Unlit() or Pbr(roughness, metallic, emissive), on vector mobjects and meshes.
  • Lights (manim.light): PointLight mobjects that belong to the scene, plus scene.ambient_light.

set_fill, set_stroke, set_color, set_opacity, the getters and match_style work as before.

Breaking changes

Removed Use instead
fill_rgbas, stroke_rgbas, background_stroke_rgbas, get_fill_rgbas, get_stroke_rgbas, generate_rgbas_array, update_rgbas_array, align_rgbas mob.fill, mob.stroke, mob.background_stroke; get_fill_colors(), get_fill_opacities()
set_sheen, set_sheen_direction, rotate_sheen_direction, get_sheen_*, sheen_factor=, sheen_direction= LinearGradient(colors, direction=...)
color_using_background_image, match_background_image, get_background_image, background_image= on mobjects, StreamLines.get_colored_background_image ColorField
shade_in_3d=, set_shade_in_3d set_material(Pbr()) and set_sort_by_depth(True)
ThreeDCamera.light_source, light_source_start_point=, should_apply_shading=, shading_factor= scene.light, scene.ambient_light
get_gradient_start_and_end_points, utils.color.get_shaded_rgb, manim.mobject.three_d.three_d_utils none

Camera(background_image=...) is unchanged.

Visible changes

  • Surfaces are smooth, in one colour and without outlines by default. They had a blue checkerboard with grey outlines and were lit face by face. checkerboard_colors=[BLUE_D, BLUE_E], stroke_width=0.5 gives the old look.
  • set_fill_by_value colours the points of a smooth surface, so colours blend across faces.
  • Line3D is white by default, like Line and Arrow3D.
  • ThreeDAxes are drawn in their plain colours (they were shaded along their length, up to 31/255).
  • StreamLines keep their colours in place when the camera moves, and show them on OpenGL (they were one colour there).
  • Shading needs a light. A ThreeDScene has one, scene.light, where the camera's light was; it survives clear(). A plain Scene shows lit materials in their base colour.
  • Closed surfaces (torus, sphere) are lit without a visible seam on OpenGL.

Control data is regenerated for 19 Cairo tests with surfaces or 3D axes.

New

  • ColorField(grid, corners) and ColorField.from_function(...): colours that lie in the scene. A mobject painted with a field shows the field's colour where it is drawn.
  • PointLight(position, color, intensity): moves and animates like any mobject; up to 8 on OpenGL.
  • VMobject.material and set_material(): a flat path with Pbr() is lit in one colour.
  • VMobject.sort_by_depth and set_sort_by_depth(): painter ordering under a 3D camera.

Cairo and OpenGL approximate Pbr with Lambert diffuse and a Blinn-Phong highlight, using glTF's parameters and units.

Performance

Whole stack against main, 17 benchmark scenes at low quality (geometric mean of render time): Cairo −28 %, OpenGL −57 %.

Docs

  • New guide: Colours, materials and lights, with four rendered examples.
  • Upgrading guide: sections for paints, colour fields, lights and materials, and a table of all removed names. A test checks that the names in the table stay removed.

For reviewers

8 commits: paints, colour fields, lights, materials on vector mobjects, the guide, then three commits on surface defaults and mesh normals.

@behackl
behackl added this pull request to stack #5179 November 23, 2026 19:50
@behackl
behackl force-pushed the refactor/paint-material branch from 6458eea to c5c1e85 Compare November 23, 2026 21:06
A VMobject kept its colours in three arrays (fill_rgbas, stroke_rgbas,
background_stroke_rgbas) plus a sheen factor and direction that decided
how many colours there were and which way they ran. Every setter went
through generate_rgbas_array / update_rgbas_array, which stretched,
copied and partly overwrote those arrays, and alignment for transforms
changed both mobjects' arrays in place (align_rgbas).

Now a VMobject has three paint fields: fill, stroke and
background_stroke. A paint (manim.paint, exported from manim) is an
immutable value: Solid (one colour) or LinearGradient (evenly spaced
stops along a direction, UL by default, between the edges of the
mobject's own bounding box). Paints cannot be rebound or written to,
copy what they are given, are shared by copies, and hash by content for
the play cache. interpolate_paint returns the paints themselves at 0
and 1 and when both are the same paint, so a geometry-only transform
changes no paint version; otherwise it stretches the shorter list of
stops and interpolates colours and directions.

set_fill / set_stroke / set_color / set_opacity / fade, the getters and
match_style behave as before, and set_fill / set_stroke also take a
paint; get_style carries paints as values. fill_opacity,
stroke_opacity, background_stroke_color and background_stroke_opacity
are properties over the paints, so there is one stored value.
VMobject.rotate turns the direction of gradients only. Extraction makes
RSolid / RLinearGradient from the paints; snapshot types are unchanged.

Removed: fill_rgbas, stroke_rgbas, background_stroke_rgbas,
get_fill_rgbas, get_stroke_rgbas, generate_rgbas_array,
update_rgbas_array, align_rgbas, get_gradient_start_and_end_points, and
the sheen (set_sheen, set_sheen_direction, rotate_sheen_direction,
get_sheen_factor, get_sheen_direction, the sheen_factor and
sheen_direction arguments and style keys). The one user in manim, plots
coloured along x, gives its gradient direction RIGHT.

All graphical tests are pixel-identical; no control data changed. Bench
(bench2, Cairo, 2x3) against E: movie_low geomean 0.958, dry_run 0.858;
transforms that change colours 0.99-1.01, so no paint cache.

Tests: paints are immutable and copy their input; gradients default to
UL; interpolation keeps the paints themselves and stretches unequal
stops; a geometry-only transform changes no paint version; rotate turns
gradients and leaves solids; setters keep what they are not given and
take paints; match_style carries the paint; copies share paints; paint
hashes depend on content and are equal across processes. Each fails if
what it tests is removed. The upgrading guide lists the removals.
…image

color_using_background_image multiplied a path's colours with an image fixed
to the frame: a moving camera left the colours behind (StreamLines after a
pan: hue error 0.108 against the field they show), the OpenGL renderer drew
it in one colour, and Cairo needed a scratch target, a pixel mask and a rule
that kept runs of masked paths together for frame reuse. The snapshot carried
it as a provisional mask.

A third paint kind, manim.paint.ColorField(grid, corners, opacity), is a grid
of straight-alpha sRGB colours that lies in the scene: a mobject painted with
it shows the field's colour where it is drawn, so trimming, moving or
transforming it, or panning the camera, shows the field at its place. The
sampler is specified once (texel centres between the outer corners, clamped,
bilinear interpolation of premultiplied colours, times opacity;
ColorField.sample is the reference); from_function samples a function at the
texel centres (vectorized=True for array functions). set_stroke / set_fill
take a field; opacity changes, fades and set_opacity keep its grid; get_style
and match_style carry it as a value. Two fields on one grid interpolate their
opacity; any other pair with a field switches to the target at the end (so a
there_and_back returns to the start). The play cache hashes its content.

Renderers sample where they draw. Cairo uses the grid as a premultiplied
pattern placed in scene coordinates (made once per grid and corners) and
applies the opacity to the drawing as a whole; OpenGL samples it as a texture
in the stroke and winding-fill fragment shaders at each fragment's scene
position (through the target's view, so camera views are right), and keeps
paths with different fields in different draw groups. Both raise
CapabilityError for a field under a perspective camera, outside a plane
parallel to the frame, or on a mobject fixed in the frame or in orientation.
Coverage and alpha are exactly those of the same shapes in one colour.

StreamLines colour their lines with one field over the region the lines can
reach (seed ranges widened by padding, at a fifth of the pixel density); 3D
lines keep a colour list per line, named as an approximation. (No graphical
test covers StreamLines, so no control data changes.)

Removed: VMobject.color_using_background_image, match_background_image,
get_background_image, the background_image argument, field and style key,
StreamLines.get_colored_background_image and background_img, RPath.mask,
Cairo's masked-path drawing, scratch target and reusable_boundary, and the
tests of the mask. Camera(background_image=) is unchanged.

Tests on both renderers: a narrow band shows where it is for a full, trimmed
and panned stroke and a fill, with the coverage of a solid shape; the 2x2
sampler fixture against the reference sampler; several fields and a solid in
one frame; a camera view samples where it looks; field opacity and
translucent grids cover as a solid of the same alpha; unsupported cases
raise; an image stays valid after another. Paint tests: field interpolation,
there_and_back, opacity keeps the grid, match_style, content hashes,
from_function. Each fails if what it tests is removed.
The only light was the ThreeDCamera's (light_source, with
light_source_start_point, should_apply_shading and shading_factor), so a
light could not be animated as a mobject, a scene could not have two, and
the renderers read it from the camera state as a provisional value.

manim.light (exported from manim) adds PointLight(position, color,
intensity): a one-point mobject that draws nothing, with color and
intensity fields. It moves and animates like any mobject; a Transform
between lights interpolates colour and intensity (the end values at 1),
and FadeOut dims it to off before removing it. Scene.ambient_light (0.25,
the ambient of B) is the white light that reaches every surface.

A ThreeDScene has a light, scene.light, at the camera's former light
position with the same intensity. It is not in scene.mobjects (decided at
F.0): clear() and fading out every mobject leave it, updaters reach it, and
animating it does not add it to the mobjects. Lights added with add() are
ordinary mobjects of the scene. A frame without lights is not shaded at
all, so a plain Scene draws lit materials in their base colour.

RenderConfig carries lights (LightState: position, linear RGB, intensity)
and ambient (linear RGB); the FrameBuilder collects the scene's light and
the PointLights in the families of the scene's mobjects, and camera views
get the same. shade() takes the frame's lights and an RGB ambient; Cairo's
mesh faces use them, and the OpenGL mesh shader takes up to 8 lights in
uniform arrays (more raise CapabilityError). shade_in_3d paths (until F4)
are shaded towards the first light. The play cache hashes the ambient light
and the scene's light, which the hash of the mobjects does not reach.
The frame-reuse view key (renderer/_reuse.view_key) includes the frame's
lights and ambient light, so a change of light redraws the lit mobjects
instead of copying the previous frame's drawing.

Removed: ThreeDCamera.light_source, light_source_start_point,
should_apply_shading, shading_factor, and CameraState.light / shade_3d.
docs/examples: the light is moved with self.light.

All graphical tests are pixel-identical (same light, intensity and
ambient); no control data changed.

Tests: a light moves and animates, and FadeOut turns it off; the default
light survives clear() and stays apart from the mobjects when animated; a
moving light changes a lit mesh frame by frame, and without lights a Pbr
mesh looks as an Unlit one, on both renderers; added lights light the
scene; a second render after a change of the ambient light, the light's
position or its intensity does not reuse the cached play. A change of
the light's position, intensity or colour, an added light or a change of
the ambient light redraws a frame that copied its lit sphere, on both
renderers; the view key differs in every light field. Each fails if
what it tests is removed.
…de_in_3d

shade_in_3d meant two things: shade a path towards the camera's light (a
two-stop gradient between its first and last corner, get_shaded_rgb) and
sort it by depth under a 3D camera. The renderers carried the first as the
provisional LegacyShaded material.

VMobject gets two fields instead:
- material (Unlit() by default; set_material(material, family=True), which
  also reaches meshes in a group). Pbr lights the path's fill in one colour:
  shade() at the center of its anchors with the normal of their plane
  (constant z fast path, else SVD, relative tolerance 1e-9), two-sided, with
  the frame's lights and ambient. Cairo and OpenGL both compute it on the
  CPU (_paint.lit_color), so they agree. Strokes, mobjects fixed in the
  frame and frames without lights are not lit. A lit path that is not flat
  or whose fill is not one colour raises CapabilityError.
- sort_by_depth (False by default; set_sort_by_depth): painter ordering by
  the center of the path's own points, not a depth test.
interpolate_color interpolates two Pbr materials and switches other
materials and sort_by_depth at the end (interpolate_material moved from
mesh.py to manim.material).

ThreeDVMobject: Pbr() and sort_by_depth. ThreeDAxes axes and the
ThreeDParametricSpring docs example: sort_by_depth, unlit.

Removed: VMobject(shade_in_3d=), set_shade_in_3d, LegacyShaded,
_view.shaded_rgbas, utils.color.get_shaded_rgb, the corner helpers of
_path_points, and mobject/three_d/three_d_utils.py (exported from manim,
used nowhere else). upgrading.rst: a section with the table.

Look: as approved at F.0 (f0/f4-sheet.png); the seven sheet scenes render
pixel-identical to the spike's on both renderers. Control data regenerated
(Cairo), only where axes are no longer shaded along their length:
threed/Axes, CameraMoveAxes, SurfaceColorscale, Y_Direction (max 31/255,
on the y axis drawn over the bright surface), plot/get_z_axis_label,
coordinate_system/plot_surface, plot_surface_colorscale (19-25/255).

Tests: defaults and set_material/set_sort_by_depth on a family; switching
at the end of a Transform and Pbr interpolation; a lit path is one colour
that follows its plane, alike on Cairo and OpenGL; strokes, fixed
mobjects and frames without lights are unlit; gradients and curved paths
raise, but not without lights; depth ordering puts the nearer path last.
Eight mutations caught.
The paints, colour fields, materials and lights of F1-F4 were documented
in their module docstrings and in the upgrading notes, but there was no
page that explains how they work together.

New guide docs/source/guides/colors_materials_lights.rst: paints (solid,
gradient with its UL default and rotate, colour fields and where the
renderers draw them), materials and the default rule (what has a surface
in space is lit, what is drawn is not; fixed mobjects never), depth
ordering (sort_by_depth is not a depth test), lights (the ThreeDScene
light outside scene.mobjects, ambient light, "without lights, nothing is
shaded") and what Cairo and OpenGL approximate (Lambert plus Blinn-Phong
for glTF's GGX, flat colour per Cairo face and per lit path, at most 8
OpenGL lights). Four rendered examples.

Also: manim.light and manim.paint in the reference index; the
manim.material docstring no longer says mobjects cannot have a material;
writing_a_renderer.rst describes the paints, materials and lights a
renderer is given; upgrading.rst lists z_index_group and
ThreeDAxes(light_source=), removed in A, and links the guide.

tests/module/test_removed_names.py checks that the removed names of the
upgrading table (attributes, arguments, exports, three_d_utils) stay gone;
four mutations that bring one back are caught.

Full docs build (all examples rendered, the four new ones included) adds no
warnings; remote suite 1963 passed.
A parametric surface whose grid closes on itself (a torus, a sphere, the
side of a cylinder) has vertices that sit at the same point but are
separate copies: the first and last rows and columns of the grid, and the
vertices at a sphere's poles. Their normals came from the triangles on one
side only, up to 16 degrees apart on a default torus, so a smooth surface
showed a lit seam.

vertex_normals now adds up the normals of vertices at the same point (up
to 1e-6 of the mesh's size) before normalising, so the seams and the poles
are lit as the rest of the surface. Meshes whose faces have corners of
their own (checkerboard surfaces, the faces of solids: no vertex is used by
more than two triangles) keep their flat normals. Cairo lights faces, not
vertices, and does not change. No control data changed: the graphical
tests' surfaces have checkerboards.

Which vertices share a point does not change when a mesh only moves,
rotates or scales, so the renderer finds them once per triangles array
and keeps the result while the mesh is drawn; only new triangles or a
new number of points find them again. Without that, finding them every
frame made a scene of 60 spinning solids over a 200x200 terrain (720p,
600 frames) take 38 s instead of 27 s.

Tests: on a torus the seams' normals agree and the outer rim's point
outward; a sphere's pole vertices share the normal (0, 0, 1); checkerboard
surfaces and cube faces keep one normal per face; a rotating torus finds
its shared vertices once and gets the normals computed from scratch, and
new triangles find them again. Each fails when the welding is removed,
applied to flat meshes, never kept, or kept for new triangles.
… point

Surface (and Sphere, Dot3D, Torus, Cylinder, Line3D, Arrow3D,
plot_surface) defaulted to a [BLUE_D, BLUE_E] checkerboard with light grey
outlines of width 0.5. A checkerboard needs every face to have corners of
its own, so these surfaces were lit flat, face by face, even when given
one colour. With lighting and materials, the checkerboard and the grid
lines are not needed to read the shape.

- Surface defaults to checkerboard_colors=False and stroke_width=0: one
  colour (fill_color, BLUE_D), shared corners, lit smoothly. Checkerboards
  and outlines are opt-in (checkerboard_colors=[BLUE_D, BLUE_E],
  stroke_width=0.5 give the old look).
- set_fill_by_value colours the points of a smooth surface, so colours
  blend across faces on OpenGL; Cairo draws each face in the mean colour
  of its corners. Outlines still take the colour halfway around each face.
  On a surface with a checkerboard it colours each face, as before.
  A colourscale with several stops can show faint diamonds where a
  triangle spans a stop (the GPU blends colours, not values); fainter at
  higher resolutions (accepted; blending values is a later option).
- Line3D is white by default, as Line and Arrow3D are; it was the blue of
  the surface, which the checkerboard's grey outlines had mostly hidden.

The upgrading guide says so and no longer says surfaces are lit by the
ThreeDCamera's light.

Look approved from a contact sheet (Cairo and OpenGL, before/after).
Control data regenerated deliberately (Cairo): threed (Sphere, Dot3D,
Cone, Cylinder, Line3D, Arrow3D, Torus, SurfaceColorscale, Y_Direction),
coordinate_system (plot_surface, plot_surface_colorscale), polyhedra
(Tetrahedron, Octahedron, Icosahedron, Dodecahedron, ConvexHull3D: their
vertices are Dot3D spheres).

Tests: surfaces and the primitives built on them are smooth and without
outlines unless asked; a smooth surface coloured by value keeps its shared
corners, colours each point and each outline; Line3D is white unless given
a colour; checkered surfaces keep colouring faces. Five mutations caught.
A moving mesh (a spinning solid) gets new points every frame, so the
OpenGL renderer computed its vertex normals every frame with np.add.at
loops, weld included: in a scene of 60 spinning solids over a 200x200
terrain that was the largest single cost after drawing.

renderer/_mesh.py gets NormalAccumulator: made from a mesh's points and
triangles, it keeps which triangles each vertex is a corner of, with
vertices at the same point welded, as one sparse matrix (scipy is a
dependency already). Normals of new points of the same triangles are the
triangles' normals times that matrix, the same normals to 1e-12, about 3x
faster per mesh. vertex_normals and the weld moved from the OpenGL
package to _mesh.py, so the wgpu converter can use them too. The OpenGL
normal cache keeps one accumulator per mesh while its triangles and point
count stay; new triangles (a partial surface) make a new one.

Marked temporary in its docstring: once meshes have a transform, a moving
mesh keeps its points and renderers keep its normals instead.

Valley demo (OpenGL, 720p, 600 frames): 25-27 s before, 21-22 s after.
No control data changed.

Tests: accumulated normals equal those computed from scratch for smooth,
welded, checkered and flat meshes, rotated or not; a rotating mesh makes
its accumulator once, new triangles make a new one. Four mutations caught
(no weld, never kept, kept for new triangles, wrong cross product).

An accumulator welds the vertices that share a point when it is made.
fits() also checks that they still do: a mesh that is deformed so that
they move apart gets a new accumulator instead of normals from its old
welds. The class is not temporary: deforming meshes keep needing it.
…colour fields

Review of #5173, for the commits of this branch.
Fixes #5180: DrawBorderThenFill on a Label raised "BackgroundRectangle.
set_style() missing 1 required positional argument: 'fill_opacity'".
get_style() returns paints, which hold their opacities, and no longer a
fill_opacity, so match_style passed none. BackgroundRectangle.set_style
now takes the opacity from a fill_color paint when fill_opacity is not
given; its colours stay black. The background of a label fades in again
as on Manim 0.22 (opacity 0, 0.5, 1 at 1/4, 3/4 and the end).

The upgrading guide says that get_style returns paints, so that set_style
overrides must not require the opacities.
@nikolajmunk

Copy link
Copy Markdown
Contributor

I'm curious about the split between Material and Paint. In most rendering engines, a material would contain, roughly speaking, input values for all the exposed properties in its associated shader file – apart from uniforms, of course. So in addition to, say, information about roughness, metallicness and emissiveness, a material would likely also contain a value for its albedo (via a color value and/or a texture). In other words, the Paint information is usually part of the material.

Is there a particular reason to keep Paint as its own thing separately from Material? If I understand the pipeline correctly, the two get "joined" in the shader anyway, so it seems like it should be possible to keep color information inside the material as well. This would keep the semantics of shaders of materials more in line with how they're used in most other places. But maybe there's some insight I've missed! :)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants