The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Implement vector fields and streamlines
apoogdkbf92167adc7d
diff --git a/rust/bridge/crates/manimgx-render/Cargo.toml b/rust/bridge/crates/manimgx-render/Cargo.tomlnew file mode 100644index 00000000..3787a396--- /dev/null+++ b/rust/bridge/crates/manimgx-render/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "manimgx-render"+version = "0.1.0"+edition = "2021"++[dependencies]+manimgx-core = { path = "../manimgx-core" }+manimgx-encode = { path = "../manimgx-encode" }+wgpu = "24"+bytemuck = { workspace = true }+glam = { workspace = true }+log = { workspace = true }+image = { version = "0.25", default-features = false, features = ["png"], optional = true }++[features]+time_profile = []+png_debug = ["image"]diff --git a/rust/bridge/crates/manimgx-render/src/gpu.rs b/rust/bridge/crates/manimgx-render/src/gpu.rsnew file mode 100644index 00000000..0fc8ae07--- /dev/null+++ b/rust/bridge/crates/manimgx-render/src/gpu.rs@@ -0,0 +1,67 @@+use std::pin::pin;+use std::task::{Context, Poll, Waker};++pub struct GpuContext {+ pub device: wgpu::Device,+ pub queue: wgpu::Queue,+}++/// Poll a future that is expected to resolve synchronously (wgpu native).+fn block_on<F: std::future::Future>(future: F) -> F::Output {+ let waker = Waker::noop();+ let mut cx = Context::from_waker(&waker);+ let mut future = pin!(future);+ match future.as_mut().poll(&mut cx) {+ Poll::Ready(v) => v,+ Poll::Pending => unreachable!("wgpu futures resolve synchronously on native"),+ }+}++impl Default for GpuContext {+ fn default() -> Self {+ Self::new()+ }+}++impl GpuContext {+ pub fn new() -> Self {+ Self::with_features(wgpu::Features::empty())+ }++ pub fn with_features(features: wgpu::Features) -> Self {+ block_on(Self::init(features))+ }++ async fn init(features: wgpu::Features) -> Self {+ let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {+ backends: wgpu::Backends::all(),+ ..Default::default()+ });++ let adapter = instance+ .request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::HighPerformance,+ compatible_surface: None,+ force_fallback_adapter: false,+ })+ .await+ .expect("Failed to find a suitable GPU adapter. Ensure you have a GPU with Vulkan/Metal/DX12 support.");++ let (device, queue) = adapter+ .request_device(+ &wgpu::DeviceDescriptor {+ label: Some("manimgx-device"),+ required_features: features,+ required_limits: wgpu::Limits::default(),+ ..Default::default()+ },+ None,+ )+ .await+ .expect("Failed to create GPU device");++ log::info!("GPU initialized: {:?}", adapter.get_info().name);++ Self { device, queue }+ }+}diff --git a/rust/bridge/crates/manimgx-render/src/lib.rs b/rust/bridge/crates/manimgx-render/src/lib.rsnew file mode 100644index 00000000..67d710e8--- /dev/null+++ b/rust/bridge/crates/manimgx-render/src/lib.rs@@ -0,0 +1,7 @@+pub mod gpu;+pub mod pipeline;+#[cfg(not(feature = "time_profile"))]+pub mod renderer;+#[cfg(feature = "time_profile")]+#[path = "renderer_profile.rs"]+pub mod renderer;diff --git a/rust/bridge/crates/manimgx-render/src/pipeline.rs b/rust/bridge/crates/manimgx-render/src/pipeline.rsnew file mode 100644index 00000000..813e6fbb--- /dev/null+++ b/rust/bridge/crates/manimgx-render/src/pipeline.rs@@ -0,0 +1,232 @@+use manimgx_core::vertex::Vertex;+use wgpu;++pub struct RenderPipelines {+ pub default: wgpu::RenderPipeline,+ pub flat_no_cull: wgpu::RenderPipeline,+ pub textured: wgpu::RenderPipeline,+ pub camera_bind_group_layout: wgpu::BindGroupLayout,+ pub model_bind_group_layout: wgpu::BindGroupLayout,+ pub texture_bind_group_layout: wgpu::BindGroupLayout,+}++impl RenderPipelines {+ pub fn new(+ device: &wgpu::Device,+ color_format: wgpu::TextureFormat,+ sample_count: u32,+ ) -> Self {+ let camera_bind_group_layout =+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("camera_bind_group_layout"),+ entries: &[wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ }],+ });++ let model_bind_group_layout =+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("model_bind_group_layout"),+ entries: &[wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: true,+ min_binding_size: None,+ },+ count: None,+ }],+ });++ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("render_pipeline_layout"),+ bind_group_layouts: &[&camera_bind_group_layout, &model_bind_group_layout],+ push_constant_ranges: &[],+ });++ let vertex_buffer_layout = wgpu::VertexBufferLayout {+ array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,+ step_mode: wgpu::VertexStepMode::Vertex,+ attributes: &[+ // position+ wgpu::VertexAttribute {+ offset: 0,+ shader_location: 0,+ format: wgpu::VertexFormat::Float32x3,+ },+ // normal+ wgpu::VertexAttribute {+ offset: 12,+ shader_location: 1,+ format: wgpu::VertexFormat::Float32x3,+ },+ // color+ wgpu::VertexAttribute {+ offset: 24,+ shader_location: 2,+ format: wgpu::VertexFormat::Float32x4,+ },+ ],+ };++ let default_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("default_shader"),+ source: wgpu::ShaderSource::Wgsl(include_str!("../../../shaders/default.wgsl").into()),+ });++ let flat_color_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("flat_color_shader"),+ source: wgpu::ShaderSource::Wgsl(+ include_str!("../../../shaders/flat_color.wgsl").into(),+ ),+ });++ let default = Self::create_pipeline(+ device,+ &pipeline_layout,+ &default_shader,+ &vertex_buffer_layout,+ color_format,+ wgpu::PrimitiveTopology::TriangleList,+ None,+ sample_count,+ );++ let flat_no_cull = Self::create_pipeline(+ device,+ &pipeline_layout,+ &flat_color_shader,+ &vertex_buffer_layout,+ color_format,+ wgpu::PrimitiveTopology::TriangleList,+ None,+ sample_count,+ );++ // --- Textured pipeline (for text rendering) ---++ let texture_bind_group_layout =+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("texture_bind_group_layout"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ ],+ });++ let textured_pipeline_layout =+ device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("textured_pipeline_layout"),+ bind_group_layouts: &[+ &camera_bind_group_layout,+ &model_bind_group_layout,+ &texture_bind_group_layout,+ ],+ push_constant_ranges: &[],+ });++ let text_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("text_shader"),+ source: wgpu::ShaderSource::Wgsl(include_str!("../../../shaders/text.wgsl").into()),+ });++ // Textured pipeline uses the same Vertex layout (UV packed into normal.xy)+ let textured = Self::create_pipeline(+ device,+ &textured_pipeline_layout,+ &text_shader,+ &vertex_buffer_layout,+ color_format,+ wgpu::PrimitiveTopology::TriangleList,+ None, // no culling for 2D text quads at z=0+ sample_count,+ );++ Self {+ default,+ flat_no_cull,+ textured,+ camera_bind_group_layout,+ model_bind_group_layout,+ texture_bind_group_layout,+ }+ }++ #[allow(clippy::too_many_arguments)]+ fn create_pipeline(+ device: &wgpu::Device,+ layout: &wgpu::PipelineLayout,+ shader: &wgpu::ShaderModule,+ vertex_buffer_layout: &wgpu::VertexBufferLayout,+ color_format: wgpu::TextureFormat,+ topology: wgpu::PrimitiveTopology,+ cull_mode: Option<wgpu::Face>,+ sample_count: u32,+ ) -> wgpu::RenderPipeline {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("render_pipeline"),+ layout: Some(layout),+ vertex: wgpu::VertexState {+ module: shader,+ entry_point: Some("vs_main"),+ buffers: std::slice::from_ref(vertex_buffer_layout),+ compilation_options: Default::default(),+ },+ fragment: Some(wgpu::FragmentState {+ module: shader,+ entry_point: Some("fs_main"),+ targets: &[Some(wgpu::ColorTargetState {+ format: color_format,+ blend: Some(wgpu::BlendState::ALPHA_BLENDING),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ compilation_options: Default::default(),+ }),+ primitive: wgpu::PrimitiveState {+ topology,+ strip_index_format: None,+ front_face: wgpu::FrontFace::Ccw,+ cull_mode,+ unclipped_depth: false,+ polygon_mode: wgpu::PolygonMode::Fill,+ conservative: false,+ },+ depth_stencil: Some(wgpu::DepthStencilState {+ format: wgpu::TextureFormat::Depth32Float,+ depth_write_enabled: true,+ depth_compare: wgpu::CompareFunction::Less,+ stencil: wgpu::StencilState::default(),+ bias: wgpu::DepthBiasState::default(),+ }),+ multisample: wgpu::MultisampleState {+ count: sample_count,+ mask: !0,+ alpha_to_coverage_enabled: false,+ },+ multiview: None,+ cache: None,+ })+ }+}diff --git a/rust/bridge/crates/manimgx-render/src/renderer.rs b/rust/bridge/crates/manimgx-render/src/renderer.rsnew file mode 100644index 00000000..463fb1e3--- /dev/null+++ b/rust/bridge/crates/manimgx-render/src/renderer.rs@@ -0,0 +1,1460 @@+use std::collections::HashMap;++use manimgx_core::color::srgb_to_linear;+use manimgx_core::scene::{ObjectId, RenderHint, Scene};+use manimgx_core::uniform::{CameraUniform, ObjectUniform};+use manimgx_core::vertex::Vertex;+use bytemuck;+use wgpu::util::DeviceExt;++use manimgx_core::encoder::FfmpegCodec;+use crate::gpu::GpuContext;+use crate::pipeline::RenderPipelines;+++/// Which encoder backend to use for video output.+pub enum EncoderBackend {+ /// GPU → staging → CPU readback → ffmpeg pipe (h264_videotoolbox or h264_vaapi)+ Ffmpeg(FfmpegCodec),+ /// GPU → NV12 compute → staging → CPU readback → in-process x264 FFI (no subprocess)+ X264,+}++/// Cached GPU buffers for a scene object (geometry never changes).+struct CachedObjectBuffers {+ vertex_buffer: wgpu::Buffer,+ index_buffer: wgpu::Buffer,+ index_count: u32,+}++/// Cached GPU texture resources for a textured object (uploaded once).+struct CachedTextureBindGroup {+ _texture: wgpu::Texture,+ _view: wgpu::TextureView,+ _sampler: wgpu::Sampler,+ bind_group: wgpu::BindGroup,+}++/// Draw command for one object in one frame.+struct DrawCmd {+ obj_idx: usize,+ uniform_slot: usize,+}++/// Pre-allocated GPU resources for rendering.+struct FrameResources {+ /// MSAA render target (only when sample_count > 1). Kept alive for msaa_view / nv12 bind group.+ _msaa_texture: Option<wgpu::Texture>,+ msaa_view: Option<wgpu::TextureView>,+ /// Output texture (sample_count=1) — copied to staging for readback.+ /// When MSAA is on, this is the resolve target. When off, this is the render target.+ output_texture: wgpu::Texture,+ output_view: wgpu::TextureView,+ _depth_texture: wgpu::Texture,+ depth_view: wgpu::TextureView,+ staging_buffer: wgpu::Buffer,+ padded_bytes_per_row: u32,+ unpadded_bytes_per_row: u32,+ pixel_size: usize,+ width: u32,+ height: u32,+ camera_buffer: wgpu::Buffer,+ camera_bind_group: wgpu::BindGroup,+ object_uniform_buffer: wgpu::Buffer,+ object_bind_group: wgpu::BindGroup,+ uniform_alignment: usize,+ /// CPU staging for object uniforms: max_objects * alignment bytes+ uniform_staging: Vec<u8>,+ rows_contiguous: bool,+ // NV12 compute conversion resources+ /// Kept alive to back nv12_bind_group+ _nv12_view: Option<wgpu::TextureView>,+ nv12_storage_buffer: Option<wgpu::Buffer>,+ nv12_staging_buffer: Option<wgpu::Buffer>,+ nv12_bind_group: Option<wgpu::BindGroup>,+ nv12_size: usize,+}++impl FrameResources {+ #[allow(clippy::too_many_arguments)]+ fn new(+ device: &wgpu::Device,+ width: u32,+ height: u32,+ color_format: wgpu::TextureFormat,+ camera_bgl: &wgpu::BindGroupLayout,+ object_bgl: &wgpu::BindGroupLayout,+ num_objects: usize,+ sample_count: u32,+ use_nv12: bool,+ nv12_bgl: Option<&wgpu::BindGroupLayout>,+ ) -> Self {+ // Non-sRGB view format for NV12 compute shader (keeps gamma-encoded values)+ let non_srgb_format = match color_format {+ wgpu::TextureFormat::Rgba8UnormSrgb => wgpu::TextureFormat::Rgba8Unorm,+ wgpu::TextureFormat::Bgra8UnormSrgb => wgpu::TextureFormat::Bgra8Unorm,+ other => other,+ };++ // MSAA render target (only when sample_count > 1)+ // Hardware MSAA resolve is essentially free (dedicated fixed-function silicon on tile flush).+ // The NV12 compute shader always reads the resolved 1x output_texture, not the MSAA texture.+ let (msaa_texture, msaa_view) = if sample_count > 1 {+ let tex = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("msaa_texture"),+ size: wgpu::Extent3d {+ width,+ height,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count,+ dimension: wgpu::TextureDimension::D2,+ format: color_format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,+ view_formats: &[],+ });+ let view = tex.create_view(&wgpu::TextureViewDescriptor::default());+ (Some(tex), Some(view))+ } else {+ (None, None)+ };++ // Output texture (1x) — resolve target when MSAA, or direct render target.+ // NV12 compute shader reads from this after hardware MSAA resolve.+ let mut output_usage =+ wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC;+ let mut output_view_formats: Vec<wgpu::TextureFormat> = vec![];+ if use_nv12 {+ output_usage |= wgpu::TextureUsages::TEXTURE_BINDING;+ output_view_formats.push(non_srgb_format);+ }+ let output_texture = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("output_texture"),+ size: wgpu::Extent3d {+ width,+ height,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: color_format,+ usage: output_usage,+ view_formats: &output_view_formats,+ });+ let output_view = output_texture.create_view(&wgpu::TextureViewDescriptor::default());++ // Depth buffer (must match sample_count)+ let depth_texture = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("depth_texture"),+ size: wgpu::Extent3d {+ width,+ height,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Depth32Float,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,+ view_formats: &[],+ });+ let depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default());++ let bytes_per_pixel = 4u32;+ let unpadded_bytes_per_row = width * bytes_per_pixel;+ let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;+ let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;+ let rows_contiguous = padded_bytes_per_row == unpadded_bytes_per_row;+ let pixel_size = (width * height * bytes_per_pixel) as usize;+ let staging_size = (padded_bytes_per_row * height) as u64;++ let staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("staging"),+ size: staging_size,+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ mapped_at_creation: false,+ });++ let cam_size = std::mem::size_of::<CameraUniform>() as u64;+ let camera_buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("camera"),+ size: cam_size,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("camera_bg"),+ layout: camera_bgl,+ entries: &[wgpu::BindGroupEntry {+ binding: 0,+ resource: camera_buffer.as_entire_binding(),+ }],+ });++ let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment as usize;+ let max_objects = num_objects.max(1);+ let buffer_size = (max_objects * uniform_alignment) as u64;++ let object_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("object_uniform_buffer"),+ size: buffer_size,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });++ let uniform_size = std::mem::size_of::<ObjectUniform>() as u64;+ let object_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("object_bind_group"),+ layout: object_bgl,+ entries: &[wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {+ buffer: &object_uniform_buffer,+ offset: 0,+ size: Some(std::num::NonZero::new(uniform_size).unwrap()),+ }),+ }],+ });++ let uniform_staging = vec![0u8; max_objects * uniform_alignment];++ // NV12 compute conversion resources+ let nv12_size = (width * height * 3 / 2) as usize;+ let (nv12_view, nv12_storage_buffer, nv12_staging_buffer, nv12_bind_group) = if use_nv12 {+ let bgl = nv12_bgl.expect("NV12 bind group layout required when use_nv12=true");++ // Non-sRGB view of the resolved 1x output_texture.+ // Hardware MSAA resolve writes here; compute shader reads raw gamma-encoded bytes.+ let nv12_view = output_texture.create_view(&wgpu::TextureViewDescriptor {+ format: Some(non_srgb_format),+ ..Default::default()+ });++ let storage_buf = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("nv12_storage"),+ size: nv12_size as u64,+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,+ mapped_at_creation: false,+ });++ let staging_buf = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("nv12_staging"),+ size: nv12_size as u64,+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });++ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("nv12_bg"),+ layout: bgl,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::TextureView(&nv12_view),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: storage_buf.as_entire_binding(),+ },+ ],+ });++ (+ Some(nv12_view),+ Some(storage_buf),+ Some(staging_buf),+ Some(bind_group),+ )+ } else {+ (None, None, None, None)+ };++ Self {+ _msaa_texture: msaa_texture,+ msaa_view,+ output_texture,+ output_view,+ _depth_texture: depth_texture,+ depth_view,+ staging_buffer,+ padded_bytes_per_row,+ unpadded_bytes_per_row,+ pixel_size,+ width,+ height,+ camera_buffer,+ camera_bind_group,+ object_uniform_buffer,+ object_bind_group,+ uniform_alignment,+ uniform_staging,+ rows_contiguous,+ _nv12_view: nv12_view,+ nv12_storage_buffer,+ nv12_staging_buffer,+ nv12_bind_group,+ nv12_size,+ }+ }++ /// Read pixels from the mapped staging buffer into a pre-allocated buffer.+ fn read_pixels_into(&self, dst: &mut Vec<u8>) {+ let data = self.staging_buffer.slice(..).get_mapped_range();++ if self.rows_contiguous {+ dst.clear();+ dst.extend_from_slice(&data[..self.pixel_size]);+ } else {+ dst.clear();+ dst.reserve(self.pixel_size);+ for row in 0..self.height {+ let start = (row * self.padded_bytes_per_row) as usize;+ let end = start + self.unpadded_bytes_per_row as usize;+ dst.extend_from_slice(&data[start..end]);+ }+ }++ drop(data);+ self.staging_buffer.unmap();+ }++ /// Read NV12 data from the mapped NV12 staging buffer (no row padding).+ fn read_nv12_into(&self, dst: &mut Vec<u8>) {+ let buf = self.nv12_staging_buffer.as_ref().unwrap();+ let data = buf.slice(..).get_mapped_range();+ dst.clear();+ dst.extend_from_slice(&data[..self.nv12_size]);+ drop(data);+ buf.unmap();+ }++ /// Read NV12 data from the mapped NV12 staging buffer into a pre-existing slice.+ fn read_nv12_into_slice(&self, dst: &mut [u8]) {+ let buf = self.nv12_staging_buffer.as_ref().unwrap();+ let data = buf.slice(..).get_mapped_range();+ dst[..self.nv12_size].copy_from_slice(&data[..self.nv12_size]);+ drop(data);+ buf.unmap();+ }+}++pub struct Renderer {+ pub gpu: GpuContext,+ pub pipelines: RenderPipelines,+ pub color_format: wgpu::TextureFormat,+ pub sample_count: u32,+ nv12_pipeline: wgpu::ComputePipeline,+ nv12_bind_group_layout: wgpu::BindGroupLayout,+}++/// Trait abstracting different frame encoding backends for the unified render loop.+pub trait FrameWriter {+ /// Write a rendered frame's pixel data to the encoder.+ fn write_frame(&mut self, pixels: &[u8]);+ /// Handle a duplicate frame (same scene state as previous).+ fn write_duplicate(&mut self);+ /// Finalize the writer (flush, join threads, etc).+ fn finish(&mut self);+}++/// Frame writer for ffmpeg-based encoding with a background writer thread and buffer pool.+pub struct FfmpegWriter {+ tx: Option<std::sync::mpsc::SyncSender<Option<Vec<u8>>>>,+ pool_rx: std::sync::mpsc::Receiver<Vec<u8>>,+ writer_handle: Option<std::thread::JoinHandle<()>>,+}++impl FfmpegWriter {+ pub fn new(encoder: manimgx_core::encoder::FfmpegEncoder, pixel_size: usize) -> Self {+ let pool_size = 4;+ let (tx, rx) = std::sync::mpsc::sync_channel::<Option<Vec<u8>>>(2);+ let (pool_tx, pool_rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(pool_size);++ for _ in 0..pool_size {+ pool_tx.send(vec![0u8; pixel_size]).unwrap();+ }++ let handle = std::thread::spawn(move || {+ let mut encoder = encoder;+ let mut last_written = vec![0u8; pixel_size];+ while let Ok(data) = rx.recv() {+ match data {+ Some(pixels) => {+ encoder.write_frame(&pixels);+ last_written.copy_from_slice(&pixels);+ let _ = pool_tx.send(pixels);+ }+ None => {+ encoder.write_frame(&last_written);+ }+ }+ }+ encoder.finish();+ });++ Self {+ tx: Some(tx),+ pool_rx,+ writer_handle: Some(handle),+ }+ }+}++impl FrameWriter for FfmpegWriter {+ fn write_frame(&mut self, pixels: &[u8]) {+ let mut buf = self.pool_rx.recv().unwrap();+ buf[..pixels.len()].copy_from_slice(pixels);+ self.tx.as_ref().unwrap().send(Some(buf)).unwrap();+ }++ fn write_duplicate(&mut self) {+ self.tx.as_ref().unwrap().send(None).unwrap();+ }++ fn finish(&mut self) {+ self.tx.take();+ if let Some(handle) = self.writer_handle.take() {+ handle.join().unwrap();+ }+ }+}++impl Renderer {+ pub fn new(sample_count: u32) -> Self {+ Self::new_with_format(sample_count, wgpu::TextureFormat::Rgba8UnormSrgb)+ }++ pub fn new_with_format(sample_count: u32, color_format: wgpu::TextureFormat) -> Self {+ let gpu = GpuContext::new();+ let pipelines = RenderPipelines::new(&gpu.device, color_format, sample_count);++ // NV12 compute pipeline — always reads the resolved 1x output_texture (non-MSAA).+ // Hardware MSAA resolve is free; manual resolve in compute shader is 10x slower.+ let nv12_shader_src = include_str!("../../../shaders/nv12_convert.wgsl");+ let nv12_shader = gpu+ .device+ .create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("nv12_convert_shader"),+ source: wgpu::ShaderSource::Wgsl(nv12_shader_src.into()),+ });++ let nv12_bind_group_layout =+ gpu.device+ .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("nv12_bgl"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: false },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Storage { read_only: false },+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ ],+ });++ let nv12_pipeline_layout =+ gpu.device+ .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("nv12_pipeline_layout"),+ bind_group_layouts: &[&nv12_bind_group_layout],+ push_constant_ranges: &[],+ });++ let nv12_pipeline =+ gpu.device+ .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {+ label: Some("nv12_pipeline"),+ layout: Some(&nv12_pipeline_layout),+ module: &nv12_shader,+ entry_point: Some("nv12_convert"),+ compilation_options: Default::default(),+ cache: None,+ });++ Self {+ gpu,+ pipelines,+ color_format,+ sample_count,+ nv12_pipeline,+ nv12_bind_group_layout,+ }+ }++ /// Get or create cached vertex/index buffers for an object.+ fn get_or_cache_buffers<'a>(+ &self,+ obj_id: ObjectId,+ vertices: &[Vertex],+ indices: &[u32],+ cache: &'a mut HashMap<ObjectId, CachedObjectBuffers>,+ ) -> &'a CachedObjectBuffers {+ cache.entry(obj_id).or_insert_with(|| {+ let vertex_buffer =+ self.gpu+ .device+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {+ label: Some("cached_vertex_buffer"),+ contents: bytemuck::cast_slice(vertices),+ usage: wgpu::BufferUsages::VERTEX,+ });+ let index_buffer =+ self.gpu+ .device+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {+ label: Some("cached_index_buffer"),+ contents: bytemuck::cast_slice(indices),+ usage: wgpu::BufferUsages::INDEX,+ });+ CachedObjectBuffers {+ vertex_buffer,+ index_buffer,+ index_count: indices.len() as u32,+ }+ })+ }++ /// Get or create cached texture bind group for a textured object (uploaded once).+ fn get_or_cache_texture<'a>(+ &self,+ obj_id: ObjectId,+ texture_data: &manimgx_core::scene::TextureData,+ cache: &'a mut HashMap<ObjectId, CachedTextureBindGroup>,+ ) -> &'a CachedTextureBindGroup {+ cache.entry(obj_id).or_insert_with(|| {+ let size = wgpu::Extent3d {+ width: texture_data.width,+ height: texture_data.height,+ depth_or_array_layers: 1,+ };+ let texture = self.gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: Some("text_texture"),+ size,+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Rgba8UnormSrgb,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ });+ self.gpu.queue.write_texture(+ wgpu::TexelCopyTextureInfo {+ texture: &texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ &texture_data.rgba,+ wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(4 * texture_data.width),+ rows_per_image: Some(texture_data.height),+ },+ size,+ );+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());+ let sampler = self.gpu.device.create_sampler(&wgpu::SamplerDescriptor {+ label: Some("text_sampler"),+ address_mode_u: wgpu::AddressMode::ClampToEdge,+ address_mode_v: wgpu::AddressMode::ClampToEdge,+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ ..Default::default()+ });+ let bind_group =+ self.gpu+ .device+ .create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("text_texture_bg"),+ layout: &self.pipelines.texture_bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::TextureView(&view),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::Sampler(&sampler),+ },+ ],+ });+ CachedTextureBindGroup {+ _texture: texture,+ _view: view,+ _sampler: sampler,+ bind_group,+ }+ })+ }++ fn wait_for_gpu(&self) {+ self.gpu.device.poll(wgpu::Maintain::Wait);+ }++ /// Encode a render pass into a command encoder.+ /// `output_view` is the resolve target (or direct render target if no MSAA).+ #[allow(clippy::too_many_arguments)]+ fn encode_render_pass(+ &self,+ cmd_encoder: &mut wgpu::CommandEncoder,+ res: &FrameResources,+ output_view: &wgpu::TextureView,+ draw_cmds: &[DrawCmd],+ scene: &Scene,+ object_cache: &mut HashMap<ObjectId, CachedObjectBuffers>,+ texture_cache: &mut HashMap<ObjectId, CachedTextureBindGroup>,+ clear_color: wgpu::Color,+ ) {+ let alignment = res.uniform_alignment;++ // Pre-cache textures for textured objects (must happen outside render pass borrow)+ for cmd in draw_cmds {+ let obj = &scene.objects[cmd.obj_idx];+ if let RenderHint::Textured = &obj.render_hint {+ if let Some(ref tex_data) = obj.texture_data {+ self.get_or_cache_texture(obj.id, tex_data, texture_cache);+ }+ }+ }++ // Always do hardware MSAA resolve — it's essentially free (dedicated fixed-function silicon).+ // NV12 compute shader reads the resolved 1x output_texture afterwards.+ let mut rp = cmd_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: None,+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: res.msaa_view.as_ref().unwrap_or(output_view),+ resolve_target: res.msaa_view.as_ref().map(|_| output_view),+ ops: wgpu::Operations {+ load: wgpu::LoadOp::Clear(clear_color),+ store: wgpu::StoreOp::Store,+ },+ })],+ depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {+ view: &res.depth_view,+ depth_ops: Some(wgpu::Operations {+ load: wgpu::LoadOp::Clear(1.0),+ store: wgpu::StoreOp::Store,+ }),+ stencil_ops: None,+ }),+ timestamp_writes: None,+ occlusion_query_set: None,+ });++ rp.set_bind_group(0, &res.camera_bind_group, &[]);++ for cmd in draw_cmds {+ let obj = &scene.objects[cmd.obj_idx];+ let is_textured = matches!(&obj.render_hint, RenderHint::Textured);+ let pipeline = match &obj.render_hint {+ RenderHint::Default => &self.pipelines.default,+ RenderHint::FlatUnlit => &self.pipelines.flat_no_cull,+ RenderHint::Textured => &self.pipelines.textured,+ };+ rp.set_pipeline(pipeline);+ let dynamic_offset = (cmd.uniform_slot * alignment) as u32;+ rp.set_bind_group(1, &res.object_bind_group, &[dynamic_offset]);++ if is_textured {+ if let Some(tex_cached) = texture_cache.get(&obj.id) {+ rp.set_bind_group(2, &tex_cached.bind_group, &[]);+ }+ }++ let cached =+ self.get_or_cache_buffers(obj.id, &obj.vertices, &obj.indices, object_cache);+ rp.set_vertex_buffer(0, cached.vertex_buffer.slice(..));+ rp.set_index_buffer(cached.index_buffer.slice(..), wgpu::IndexFormat::Uint32);+ rp.draw_indexed(0..cached.index_count, 0, 0..1);+ }+ }++ /// Encode render pass, copy to staging, submit, wait, readback into dst.+ fn render_and_readback(+ &self,+ res: &mut FrameResources,+ draw_cmds: &[DrawCmd],+ scene: &Scene,+ object_cache: &mut HashMap<ObjectId, CachedObjectBuffers>,+ texture_cache: &mut HashMap<ObjectId, CachedTextureBindGroup>,+ clear_color: wgpu::Color,+ dst: &mut Vec<u8>,+ ) {+ let mut cmd_encoder =+ self.gpu+ .device+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("frame_encoder"),+ });++ self.encode_render_pass(+ &mut cmd_encoder,+ res,+ &res.output_view,+ draw_cmds,+ scene,+ object_cache,+ texture_cache,+ clear_color,+ );++ cmd_encoder.copy_texture_to_buffer(+ wgpu::TexelCopyTextureInfo {+ texture: &res.output_texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ wgpu::TexelCopyBufferInfo {+ buffer: &res.staging_buffer,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(res.padded_bytes_per_row),+ rows_per_image: Some(res.height),+ },+ },+ wgpu::Extent3d {+ width: res.width,+ height: res.height,+ depth_or_array_layers: 1,+ },+ );++ self.gpu.queue.submit(std::iter::once(cmd_encoder.finish()));+ res.staging_buffer+ .slice(..)+ .map_async(wgpu::MapMode::Read, |_| {});+ self.wait_for_gpu();+ res.read_pixels_into(dst);+ }++ /// Print progress bar to stderr.+ fn print_progress(+ frame_idx: u32,+ total_frames: u32,+ render_start: &std::time::Instant,+ last_progress: &mut std::time::Instant,+ ) {+ if last_progress.elapsed().as_millis() >= 250 || frame_idx == total_frames - 1 {+ let done = frame_idx + 1;+ let elapsed = render_start.elapsed().as_secs_f64();+ let pct = done as f64 / total_frames as f64;+ let fps_now = if elapsed > 0.0 {+ done as f64 / elapsed+ } else {+ 0.0+ };+ let eta = if pct > 0.0 {+ elapsed / pct - elapsed+ } else {+ 0.0+ };+ let bar_width = 30;+ let filled = (pct * bar_width as f64) as usize;+ let bar: String = "█".repeat(filled) + &"░".repeat(bar_width - filled);+ eprint!(+ "\r [{}] {:>3.0}% | {}/{} | {:.1}s | ~{:.1}s left | {:.0} fps\x1b[K",+ bar,+ pct * 100.0,+ done,+ total_frames,+ elapsed,+ eta,+ fps_now,+ );+ *last_progress = std::time::Instant::now();+ }+ }++ /// Unified render loop with N-buffering and frame deduplication.+ ///+ /// With `n_buffers=1`: current synchronous behavior (render, readback, repeat).+ /// With `n_buffers=2+`: GPU render of frame K overlaps with staging readback of frame K-1.+ pub fn render_video<W: FrameWriter>(+ &self,+ scene: &mut Scene,+ timeline: &dyn manimgx_core::timeline_eval::TimelineEval,+ writer: &mut W,+ total_frames: u32,+ fps: u32,+ n_buffers: u32,+ use_nv12: bool,+ check_cancelled: &dyn Fn() -> bool,+ ) {+ if total_frames == 0 {+ return;+ }++ let effective_buffers = n_buffers.max(1) as usize;++ let nv12_bgl = if use_nv12 {+ Some(&self.nv12_bind_group_layout)+ } else {+ None+ };++ let resources: Vec<FrameResources> = (0..effective_buffers)+ .map(|_| {+ FrameResources::new(+ &self.gpu.device,+ scene.width,+ scene.height,+ self.color_format,+ &self.pipelines.camera_bind_group_layout,+ &self.pipelines.model_bind_group_layout,+ scene.objects.len(),+ self.sample_count,+ use_nv12,+ nv12_bgl,+ )+ })+ .collect();+ let mut object_cache: HashMap<ObjectId, CachedObjectBuffers> = HashMap::with_capacity(scene.objects.len());+ let mut texture_cache: HashMap<ObjectId, CachedTextureBindGroup> = HashMap::new();++ let alignment = resources[0].uniform_alignment;+ let uniform_size = std::mem::size_of::<ObjectUniform>();+ let cam_size = std::mem::size_of::<CameraUniform>();+ let pixel_size = if use_nv12 {+ resources[0].nv12_size+ } else {+ resources[0].pixel_size+ };++ let clear_color = wgpu::Color {+ r: srgb_to_linear(scene.background[0]) as f64,+ g: srgb_to_linear(scene.background[1]) as f64,+ b: srgb_to_linear(scene.background[2]) as f64,+ a: scene.background[3] as f64,+ };++ // CPU staging for uniform building and dedup comparison (shared across buffers)+ let mut uniform_staging = vec![0u8; resources[0].uniform_staging.len()];+ let mut prev_cam_bytes = vec![0u8; cam_size];+ let mut prev_uniform_bytes = vec![0u8; uniform_staging.len()];+ let mut prev_draw_count: usize = 0;+ let mut first_frame = true;+ let mut dup_count = 0u32;+ let mut render_count = 0usize;+ let mut pixel_buf = vec![0u8; pixel_size];++ // Pending readback queue: buffer indices with submitted but not-yet-read staging data+ let mut pending: std::collections::VecDeque<usize> = std::collections::VecDeque::new();++ // Pre-allocate draw command buffer (reused each frame)+ let mut draw_cmds: Vec<DrawCmd> = Vec::with_capacity(scene.objects.len());++ let render_start = std::time::Instant::now();+ let mut last_progress = std::time::Instant::now();++ for frame_idx in 0..total_frames {+ Self::print_progress(frame_idx, total_frames, &render_start, &mut last_progress);+ if check_cancelled() { eprintln!("\n Render interrupted at frame {}/{}", frame_idx, total_frames); break; }++ let time = frame_idx as f32 / fps as f32;+ timeline.evaluate(scene, time);++ let view_proj = scene.camera.view_projection_matrix(scene.aspect_ratio());+ let cam_uniform = CameraUniform {+ view_proj: view_proj.to_cols_array_2d(),+ };+ let cam_bytes = bytemuck::bytes_of(&cam_uniform);++ // Build draw commands + object uniforms into shared staging buffer+ draw_cmds.clear();+ for (obj_idx, obj) in scene.objects.iter().enumerate() {+ if obj.material.opacity <= 0.0 {+ continue;+ }+ let slot = draw_cmds.len();+ let byte_offset = slot * alignment;+ let mut material_color = obj.material.color;+ material_color[3] = obj.material.color[3] * obj.material.opacity;+ let uniform = ObjectUniform {+ model: obj.transform.to_matrix().to_cols_array_2d(),+ material_color,+ use_vertex_colors: if obj.material.use_vertex_colors { 1 } else { 0 },+ _pad: [0; 3],+ };+ uniform_staging[byte_offset..byte_offset + uniform_size]+ .copy_from_slice(bytemuck::bytes_of(&uniform));+ draw_cmds.push(DrawCmd {+ obj_idx,+ uniform_slot: slot,+ });+ }++ let total_uniform_bytes = draw_cmds.len() * alignment;++ // Frame deduplication: skip GPU render when scene state is unchanged+ let is_dup = !first_frame+ && draw_cmds.len() == prev_draw_count+ && cam_bytes == &prev_cam_bytes[..]+ && (total_uniform_bytes == 0+ || uniform_staging[..total_uniform_bytes]+ == prev_uniform_bytes[..total_uniform_bytes]);++ if is_dup {+ writer.write_duplicate();+ dup_count += 1;+ continue;+ }++ let buf_idx = render_count % effective_buffers;++ {+ // Staging readback path with N-buffering+ // Drain oldest pending readback if all buffers are in use+ if pending.len() >= effective_buffers {+ let drain_idx = pending.pop_front().unwrap();+ self.wait_for_gpu();+ if use_nv12 {+ resources[drain_idx].read_nv12_into(&mut pixel_buf);+ } else {+ resources[drain_idx].read_pixels_into(&mut pixel_buf);+ }+ writer.write_frame(&pixel_buf);+ }++ let res = &resources[buf_idx];+ self.gpu+ .queue+ .write_buffer(&res.camera_buffer, 0, cam_bytes);+ if total_uniform_bytes > 0 {+ self.gpu.queue.write_buffer(+ &res.object_uniform_buffer,+ 0,+ &uniform_staging[..total_uniform_bytes],+ );+ }++ // Encode render pass + copy to staging + submit (don't wait yet)+ let mut cmd_encoder =+ self.gpu+ .device+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("frame_encoder"),+ });+ self.encode_render_pass(+ &mut cmd_encoder,+ res,+ &res.output_view,+ &draw_cmds,+ scene,+ &mut object_cache,+ &mut texture_cache,+ clear_color,+ );++ if use_nv12 {+ // Compute pass: MSAA resolve + NV12 conversion+ {+ let mut cpass = cmd_encoder.begin_compute_pass(+ &wgpu::ComputePassDescriptor {+ label: Some("nv12_convert"),+ timestamp_writes: None,+ },+ );+ cpass.set_pipeline(&self.nv12_pipeline);+ cpass.set_bind_group(0, res.nv12_bind_group.as_ref().unwrap(), &[]);+ cpass.dispatch_workgroups(+ res.width.div_ceil(32),+ res.height.div_ceil(16),+ 1,+ );+ }+ // Copy storage → staging+ let nv12_sz = res.nv12_size as u64;+ cmd_encoder.copy_buffer_to_buffer(+ res.nv12_storage_buffer.as_ref().unwrap(),+ 0,+ res.nv12_staging_buffer.as_ref().unwrap(),+ 0,+ nv12_sz,+ );+ self.gpu.queue.submit(std::iter::once(cmd_encoder.finish()));+ res.nv12_staging_buffer+ .as_ref()+ .unwrap()+ .slice(..)+ .map_async(wgpu::MapMode::Read, |_| {});+ } else {+ cmd_encoder.copy_texture_to_buffer(+ wgpu::TexelCopyTextureInfo {+ texture: &res.output_texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ wgpu::TexelCopyBufferInfo {+ buffer: &res.staging_buffer,+ layout: wgpu::TexelCopyBufferLayout {+ offset: 0,+ bytes_per_row: Some(res.padded_bytes_per_row),+ rows_per_image: Some(res.height),+ },+ },+ wgpu::Extent3d {+ width: res.width,+ height: res.height,+ depth_or_array_layers: 1,+ },+ );+ self.gpu.queue.submit(std::iter::once(cmd_encoder.finish()));+ // Issue map_async immediately — overlap GPU work with CPU readback of previous frames+ res.staging_buffer+ .slice(..)+ .map_async(wgpu::MapMode::Read, |_| {});+ }+ pending.push_back(buf_idx);+ }++ // Update dedup state+ prev_cam_bytes.copy_from_slice(cam_bytes);+ if total_uniform_bytes > 0 {+ prev_uniform_bytes[..total_uniform_bytes]+ .copy_from_slice(&uniform_staging[..total_uniform_bytes]);+ }+ prev_draw_count = draw_cmds.len();+ first_frame = false;+ render_count += 1;+ }++ // Drain remaining pending readbacks+ while let Some(drain_idx) = pending.pop_front() {+ self.wait_for_gpu();+ if use_nv12 {+ resources[drain_idx].read_nv12_into(&mut pixel_buf);+ } else {+ resources[drain_idx].read_pixels_into(&mut pixel_buf);+ }+ writer.write_frame(&pixel_buf);+ }++ writer.finish();++ eprintln!();+ let rendered = total_frames - dup_count;+ eprintln!(+ " frames: {} rendered, {} duplicates skipped ({:.0}%)",+ rendered,+ dup_count,+ dup_count as f64 / total_frames as f64 * 100.0,+ );+ }++ /// Render video using in-process x264 encoding with CPU-side NV12 buffer pool.+ ///+ /// GPU renders → NV12 compute → staging readback → pool Vec<u8> → x264 encoder thread.+ /// No ffmpeg subprocess. Pool buffers are pinned (never reallocated) so raw pointers+ /// sent to the encoder thread remain valid.+ #[allow(clippy::too_many_arguments)]+ pub fn render_video_x264(+ &self,+ scene: &mut Scene,+ timeline: &dyn manimgx_core::timeline_eval::TimelineEval,+ output: &str,+ total_frames: u32,+ fps: u32,+ n_buffers: u32,+ preset: &str,+ crf: u32,+ muxer: &str,+ check_cancelled: &dyn Fn() -> bool,+ ) {+ use manimgx_encode::{X264FrameMsg, X264Writer};+ use std::collections::VecDeque;+ use std::sync::mpsc;++ if total_frames == 0 {+ return;+ }++ let n = n_buffers.max(1) as usize;+ let w = scene.width;+ let h = scene.height;+ let nv12_size = (w * h * 3 / 2) as usize;++ let nv12_bgl = Some(&self.nv12_bind_group_layout);++ let resources: Vec<FrameResources> = (0..n)+ .map(|_| {+ FrameResources::new(+ &self.gpu.device,+ w,+ h,+ self.color_format,+ &self.pipelines.camera_bind_group_layout,+ &self.pipelines.model_bind_group_layout,+ scene.objects.len(),+ self.sample_count,+ true,+ nv12_bgl,+ )+ })+ .collect();+ let mut object_cache: HashMap<ObjectId, CachedObjectBuffers> = HashMap::with_capacity(scene.objects.len());+ let mut texture_cache: HashMap<ObjectId, CachedTextureBindGroup> = HashMap::new();++ let alignment = resources[0].uniform_alignment;+ let uniform_size = std::mem::size_of::<ObjectUniform>();+ let cam_size = std::mem::size_of::<CameraUniform>();++ // CPU-side NV12 buffer pool (elastic, decoupled from GPU slots)+ let pool_count = 8usize;+ let (release_tx, release_rx) = mpsc::channel::<usize>();+ let mut pool_buffers: Vec<Vec<u8>> = (0..pool_count).map(|_| vec![0u8; nv12_size]).collect();+ let mut pool_available: VecDeque<usize> = (0..pool_count).collect();++ // In-process x264 encoder (spawns encoder thread)+ let writer = X264Writer::new(output, w, h, fps, preset, crf, release_tx, muxer);++ let clear_color = wgpu::Color {+ r: srgb_to_linear(scene.background[0]) as f64,+ g: srgb_to_linear(scene.background[1]) as f64,+ b: srgb_to_linear(scene.background[2]) as f64,+ a: scene.background[3] as f64,+ };++ // CPU staging for uniform building and dedup comparison+ let mut uniform_staging = vec![0u8; resources[0].uniform_staging.len()];+ let mut prev_cam_bytes = vec![0u8; cam_size];+ let mut prev_uniform_bytes = vec![0u8; uniform_staging.len()];+ let mut prev_draw_count: usize = 0;+ let mut first_frame = true;+ let mut dup_count = 0u32;+ let mut render_count = 0usize;++ // N-buffering: pending queue tracks (gpu_slot_idx, pool_buf_idx)+ let mut pending: VecDeque<(usize, usize)> = VecDeque::new();++ // Pre-allocate draw command buffer (reused each frame)+ let mut draw_cmds: Vec<DrawCmd> = Vec::with_capacity(scene.objects.len());++ let render_start = std::time::Instant::now();+ let mut last_progress = std::time::Instant::now();++ // Helper: acquire a pool buffer index+ let acquire_pool = |available: &mut VecDeque<usize>, rx: &mpsc::Receiver<usize>| -> usize {+ // Drain all released buffers (non-blocking)+ while let Ok(idx) = rx.try_recv() {+ available.push_back(idx);+ }+ if let Some(idx) = available.pop_front() {+ return idx;+ }+ // Pool exhausted — block until encoder releases one+ rx.recv().expect("x264 encoder thread died")+ };++ for frame_idx in 0..total_frames {+ Self::print_progress(frame_idx, total_frames, &render_start, &mut last_progress);+ if check_cancelled() {+ eprintln!("\n Render interrupted at frame {}/{}", frame_idx, total_frames);+ break;+ }++ let time = frame_idx as f32 / fps as f32;+ timeline.evaluate(scene, time);++ let view_proj = scene.camera.view_projection_matrix(scene.aspect_ratio());+ let cam_uniform = CameraUniform {+ view_proj: view_proj.to_cols_array_2d(),+ };+ let cam_bytes = bytemuck::bytes_of(&cam_uniform);++ // Build draw commands + object uniforms+ draw_cmds.clear();+ for (obj_idx, obj) in scene.objects.iter().enumerate() {+ if obj.material.opacity <= 0.0 {+ continue;+ }+ let slot = draw_cmds.len();+ let byte_offset = slot * alignment;+ let mut material_color = obj.material.color;+ material_color[3] = obj.material.color[3] * obj.material.opacity;+ let uniform = ObjectUniform {+ model: obj.transform.to_matrix().to_cols_array_2d(),+ material_color,+ use_vertex_colors: if obj.material.use_vertex_colors { 1 } else { 0 },+ _pad: [0; 3],+ };+ uniform_staging[byte_offset..byte_offset + uniform_size]+ .copy_from_slice(bytemuck::bytes_of(&uniform));+ draw_cmds.push(DrawCmd {+ obj_idx,+ uniform_slot: slot,+ });+ }++ let total_uniform_bytes = draw_cmds.len() * alignment;++ // Frame deduplication+ let is_dup = !first_frame+ && draw_cmds.len() == prev_draw_count+ && cam_bytes == &prev_cam_bytes[..]+ && (total_uniform_bytes == 0+ || uniform_staging[..total_uniform_bytes]+ == prev_uniform_bytes[..total_uniform_bytes]);++ if is_dup {+ // Drain ALL pending GPU slots before encoding dup+ while let Some((drain_slot, drain_buf)) = pending.pop_front() {+ self.wait_for_gpu();+ resources[drain_slot].read_nv12_into_slice(&mut pool_buffers[drain_buf]);++ writer.send(X264FrameMsg::Frame {+ ptr: pool_buffers[drain_buf].as_ptr(),+ len: nv12_size,+ pts: (frame_idx as i64) - (pending.len() as i64) - 1,+ buf_idx: drain_buf,+ });+ }++ writer.send(X264FrameMsg::Dup {+ pts: frame_idx as i64,+ });+ dup_count += 1;+ continue;+ }++ let slot_idx = render_count % n;++ // Drain oldest pending slot if all GPU slots are in use+ if pending.len() >= n {+ let (drain_slot, drain_buf) = pending.pop_front().unwrap();+ self.wait_for_gpu();+ resources[drain_slot].read_nv12_into_slice(&mut pool_buffers[drain_buf]);++ writer.send(X264FrameMsg::Frame {+ ptr: pool_buffers[drain_buf].as_ptr(),+ len: nv12_size,+ pts: (frame_idx as i64) - (n as i64),+ buf_idx: drain_buf,+ });+ }++ // Acquire a pool buffer for NV12 output+ let buf_idx = acquire_pool(&mut pool_available, &release_rx);++ // Write uniforms to GPU+ let res = &resources[slot_idx];+ self.gpu+ .queue+ .write_buffer(&res.camera_buffer, 0, cam_bytes);+ if total_uniform_bytes > 0 {+ self.gpu.queue.write_buffer(+ &res.object_uniform_buffer,+ 0,+ &uniform_staging[..total_uniform_bytes],+ );+ }++ // Encode render pass + NV12 compute + staging copy + submit+ let mut cmd_encoder =+ self.gpu+ .device+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("x264_frame"),+ });+ self.encode_render_pass(+ &mut cmd_encoder,+ res,+ &res.output_view,+ &draw_cmds,+ scene,+ &mut object_cache,+ &mut texture_cache,+ clear_color,+ );++ // NV12 compute pass+ {+ let mut cpass = cmd_encoder.begin_compute_pass(+ &wgpu::ComputePassDescriptor {+ label: Some("nv12_convert"),+ timestamp_writes: None,+ },+ );+ cpass.set_pipeline(&self.nv12_pipeline);+ cpass.set_bind_group(0, res.nv12_bind_group.as_ref().unwrap(), &[]);+ cpass.dispatch_workgroups(+ res.width.div_ceil(32),+ res.height.div_ceil(16),+ 1,+ );+ }+ // Copy storage → staging+ let nv12_sz = res.nv12_size as u64;+ cmd_encoder.copy_buffer_to_buffer(+ res.nv12_storage_buffer.as_ref().unwrap(),+ 0,+ res.nv12_staging_buffer.as_ref().unwrap(),+ 0,+ nv12_sz,+ );+ self.gpu.queue.submit(std::iter::once(cmd_encoder.finish()));+ res.nv12_staging_buffer+ .as_ref()+ .unwrap()+ .slice(..)+ .map_async(wgpu::MapMode::Read, |_| {});++ pending.push_back((slot_idx, buf_idx));++ // Update dedup state+ prev_cam_bytes.copy_from_slice(cam_bytes);+ if total_uniform_bytes > 0 {+ prev_uniform_bytes[..total_uniform_bytes]+ .copy_from_slice(&uniform_staging[..total_uniform_bytes]);+ }+ prev_draw_count = draw_cmds.len();+ first_frame = false;+ render_count += 1;+ }++ // Drain remaining pending slots+ let remaining = pending.len();+ let mut drain_count = 0;+ while let Some((drain_slot, drain_buf)) = pending.pop_front() {+ self.wait_for_gpu();+ resources[drain_slot].read_nv12_into_slice(&mut pool_buffers[drain_buf]);++ writer.send(X264FrameMsg::Frame {+ ptr: pool_buffers[drain_buf].as_ptr(),+ len: nv12_size,+ pts: (total_frames as i64) - (remaining as i64) + (drain_count as i64),+ buf_idx: drain_buf,+ });+ drain_count += 1;+ }++ // Flush encoder, join thread, finalize MP4+ writer.finish();++ eprintln!();+ let rendered = total_frames - dup_count;+ eprintln!(+ " frames: {} rendered, {} duplicates skipped ({:.0}%)",+ rendered,+ dup_count,+ dup_count as f64 / total_frames as f64 * 100.0,+ );+ }++ /// Render a single frame, returning RGBA pixel data (used for PNG export).+ pub fn render_frame(&self, scene: &Scene) -> Vec<u8> {+ let mut res = FrameResources::new(+ &self.gpu.device,+ scene.width,+ scene.height,+ self.color_format,+ &self.pipelines.camera_bind_group_layout,+ &self.pipelines.model_bind_group_layout,+ scene.objects.len(),+ self.sample_count,+ false,+ None,+ );+ let mut object_cache: HashMap<ObjectId, CachedObjectBuffers> = HashMap::with_capacity(scene.objects.len());+ let mut texture_cache: HashMap<ObjectId, CachedTextureBindGroup> = HashMap::new();++ // Camera+ let view_proj = scene.camera.view_projection_matrix(scene.aspect_ratio());+ let camera_uniform = CameraUniform {+ view_proj: view_proj.to_cols_array_2d(),+ };+ self.gpu.queue.write_buffer(+ &res.camera_buffer,+ 0,+ bytemuck::cast_slice(&[camera_uniform]),+ );++ // Object uniforms+ let alignment = res.uniform_alignment;+ let uniform_size = std::mem::size_of::<ObjectUniform>();+ let mut draw_cmds: Vec<DrawCmd> = Vec::with_capacity(scene.objects.len());++ for (obj_idx, obj) in scene.objects.iter().enumerate() {+ if obj.material.opacity <= 0.0 {+ continue;+ }+ let slot = draw_cmds.len();+ let offset = slot * alignment;+ let mut material_color = obj.material.color;+ material_color[3] = obj.material.color[3] * obj.material.opacity;+ let uniform = ObjectUniform {+ model: obj.transform.to_matrix().to_cols_array_2d(),+ material_color,+ use_vertex_colors: if obj.material.use_vertex_colors { 1 } else { 0 },+ _pad: [0; 3],+ };+ res.uniform_staging[offset..offset + uniform_size]+ .copy_from_slice(bytemuck::bytes_of(&uniform));+ draw_cmds.push(DrawCmd {+ obj_idx,+ uniform_slot: slot,+ });+ }++ if !draw_cmds.is_empty() {+ let total_bytes = draw_cmds.len() * alignment;+ self.gpu.queue.write_buffer(+ &res.object_uniform_buffer,+ 0,+ &res.uniform_staging[..total_bytes],+ );+ }++ let clear_color = wgpu::Color {+ r: srgb_to_linear(scene.background[0]) as f64,+ g: srgb_to_linear(scene.background[1]) as f64,+ b: srgb_to_linear(scene.background[2]) as f64,+ a: scene.background[3] as f64,+ };++ let mut pixels = Vec::with_capacity(res.pixel_size);+ self.render_and_readback(+ &mut res,+ &draw_cmds,+ scene,+ &mut object_cache,+ &mut texture_cache,+ clear_color,+ &mut pixels,+ );+ pixels+ }++ /// Render a single frame and save as PNG (requires `png_debug` feature).+ #[cfg(feature = "png_debug")]+ pub fn render_to_png(&self, scene: &Scene, path: &str) {+ let pixels = self.render_frame(scene);+ let img = image::RgbaImage::from_raw(scene.width, scene.height, pixels)+ .expect("Invalid image data");+ img.save(path).expect("Failed to save PNG");+ log::info!("Saved PNG: {}", path);+ }++ /// Stub when `png_debug` is not enabled — panics with a clear message.+ #[cfg(not(feature = "png_debug"))]+ pub fn render_to_png(&self, _scene: &Scene, _path: &str) {+ panic!("render_to_png requires the `png_debug` feature on manimgx-render");+ }+}diff --git a/src/manimgx/mobjects/plotting.py b/src/manimgx/mobjects/plotting.pyindex dfb14a24..c2f8516a 100644--- a/src/manimgx/mobjects/plotting.py+++ b/src/manimgx/mobjects/plotting.py@@ -7,6 +7,8 @@from __future__ import annotations+from warnings import deprecated+__all__ = ["Axes","BarChart",@@ -156,6 +158,7 @@ class _ScaleBase:def _inverse_function(self, value: float | np.ndarray) -> float | np.ndarray:raise NotImplementedError+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)def get_custom_labels(self, val_range: Iterable[float], unit_decimal_places: int = 0) -> list[Mobject]:@@ -280,6 +283,7 @@ class LogBase(_ScaleBase):return np.log(value) / np.log(self.base)return math.log(value, self.base)+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)def get_custom_labels(self,val_range: Iterable[float],@@ -293,7 +297,7 @@ class LogBase(_ScaleBase):Args:val_range: The numbers, all positive.unit_decimal_places: The decimal places the exponents are written with.- **base_config: [Number keywords][manimgx.mobjects.numbers.DecimalNumberOptions]+ **base_config: [Number keywords][manimgx.DecimalNumber]for the labels: each is an [Integer][manimgx.Integer], the base, withits exponent as its `unit`.@@ -363,9 +367,8 @@ class ParametricFunction(VMobject):an array, and checked against single calls; a function that does not take arraysis called once per value.- One-shot discontinuity iterators are retained as lists when point generation- consumes them. Their values are collected before range filtering, so copies and- regenerated curves keep all breaks. Repeatable iterables remain live inputs.+ The discontinuities are kept as the list they were when the curve was made, before+ range filtering, so copies and regenerated curves keep all its breaks.To graph a function on axes, in their coordinates, see [plot][manimgx.Axes.plot].@@ -434,7 +437,9 @@ class ParametricFunction(VMobject):t_range = (*t_range, 0.01)self.scaling = scalingself.dt = dt- self.discontinuities = discontinuities+ self.discontinuities = (+ None if discontinuities is None else list(discontinuities)+ )self.use_smoothing = use_smoothingself.use_vectorized = use_vectorizedself.t_min, self.t_max, self.t_step = t_range@@ -462,8 +467,6 @@ class ParametricFunction(VMobject):def generate_points(self) -> Self:if self.discontinuities is not None:values = self.discontinuities- if isinstance(values, Iterator):- self.discontinuities = values = list(values)discontinuities = filter(lambda t: self.t_min <= t <= self.t_max, values)discontinuities_array = np.array(list(discontinuities))boundary_times = np.array(@@ -717,7 +720,7 @@ class NumberLineOptions(Tipped, total=False):line_to_number_buff: float"""The gap between the line and its numbers, in scene units (default 0.25)."""decimal_number_config: DecimalNumberOptions | None- """[Number keywords][manimgx.mobjects.numbers.DecimalNumberOptions] for the+ """[Number keywords][manimgx.DecimalNumber] for thenumbers (default None: as many decimal places as the range's step has)."""numbers_to_exclude: Iterable[float] | None"""Numbers not to write, when the ticks are numbered (default None: none; an@@ -746,9 +749,8 @@ class NumberLine(Line):Initial length, rotation, tip dimensions and which ticks/numbers to draw areconstruction inputs, not retained attributes. The line keeps its drawing and- the defaults used by later tick and label methods. Single-use iterators for- exclusions or elongated ticks are consumed into lists at construction;- reusable inputs remain live defaults.+ the defaults used by later tick and label methods; the numbers to exclude and+ those with elongated ticks are kept as the lists they were when it was made.Args:x_range: The range, `[x_min, x_max, x_step]`, or `[x_min, x_max]` for a step of@@ -781,7 +783,7 @@ class NumberLine(Line):[LogBase][manimgx.LogBase] (its numbers are then written as powers).line_to_number_buff: The gap between the line and its numbers, in scene units.decimal_number_config: The numbers'- [number keywords][manimgx.mobjects.numbers.DecimalNumberOptions]; None+ [number keywords][manimgx.DecimalNumber]; Nonefor as many decimal places as `x_step` has.numbers_to_exclude: Numbers not to write, when the ticks are numbered; Nonefor none.@@ -846,14 +848,15 @@ class NumberLine(Line):numbers_to_include: Iterable[float] | None = None,**kwargs: Unpack[Tipped],):- if numbers_to_exclude is None:- numbers_to_exclude = []- elif isinstance(numbers_to_exclude, Iterator):- numbers_to_exclude = list(numbers_to_exclude)- if numbers_with_elongated_ticks is None:- numbers_with_elongated_ticks = []- elif isinstance(numbers_with_elongated_ticks, Iterator):- numbers_with_elongated_ticks = list(numbers_with_elongated_ticks)+ # values, as they are given: what the line keeps is its own+ numbers_to_exclude = (+ [] if numbers_to_exclude is None else list(numbers_to_exclude)+ )+ numbers_with_elongated_ticks = (+ []+ if numbers_with_elongated_ticks is None+ else list(numbers_with_elongated_ticks)+ )if x_range is None:x_range = [round(-config.frame_x_radius),@@ -946,6 +949,7 @@ class NumberLine(Line):"""return self.rotate(angle, axis, about_point=self.n2p(number))+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)def add_ticks(self) -> Self:"""Add the line's ticks: one at each number of its[tick range][manimgx.NumberLine.get_tick_range], across the line, those of@@ -968,6 +972,7 @@ class NumberLine(Line):self.ticks = ticksreturn self+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)def get_tick(self, x: float, size: float | None = None) -> Line:"""Make a tick for a number: a short line across the number line at thenumber's point, in the line's style.@@ -988,6 +993,7 @@ class NumberLine(Line):result.match_style(self)return result+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)def get_tick_range(self) -> np.ndarray:"""The numbers the line's ticks are at.@@ -1117,7 +1123,7 @@ class NumberLine(Line):buff: The gap between the line and the number, in scene units; None for theline's `line_to_number_buff`.label_constructor: The class it is typeset with; None for the line's.- **number_config: [Number keywords][manimgx.mobjects.numbers.DecimalNumberOptions],+ **number_config: [Number keywords][manimgx.DecimalNumber],over the line's.Returns:@@ -1154,7 +1160,7 @@ class NumberLine(Line):x_values: The numbers to write; None for the ticks' numbers.excluding: Numbers not to write; None for the line's `numbers_to_exclude`.label_constructor: The class they are typeset with; None for the line's.- **kwargs: [Number keywords][manimgx.mobjects.numbers.DecimalNumberOptions],+ **kwargs: [Number keywords][manimgx.DecimalNumber],over the line's: `font_size`, `num_decimal_places`, `color`, ….Examples:@@ -1292,7 +1298,7 @@ class UnitInterval(NumberLine):Its numbers, when it has them, have one decimal place.Args:- **kwargs: [Number line keywords][manimgx.mobjects.plotting.NumberLineOptions]:+ **kwargs: [Number line keywords][manimgx.NumberLine]:its range is always `[0, 1, 0.1]`, and its `unit_size`,`numbers_with_elongated_ticks` and `decimal_number_config` default to 10,[0, 1] and one decimal place.@@ -1318,9 +1324,9 @@ class UnitInterval(NumberLine):super().__init__(x_range=(0, 1, 0.1), **kwargs)-type Coordinates = float | Sequence[- float-] | np.ndarray # a number per axis, or arrays of them+type Coordinates = (+ float | Sequence[float] | np.ndarray+) # a number per axis, or arrays of them"""A coordinate on one axis: a number, or an array of numbers (of any shape) for many@@ -1329,10 +1335,11 @@ points at once."""def merged_axis_config(*configs: NumberLineOptions | None) -> NumberLineOptions:"""Merge axis configs: later ones win, key by key, and inside their- `decimal_number_config` too.+ `decimal_number_config` too. An iterator among the values is read into a list: the+ config is shared by every axis, and an iterator would give its numbers to the first.Args:- *configs: [Number line keywords][manimgx.mobjects.plotting.NumberLineOptions],+ *configs: [Number line keywords][manimgx.NumberLine],in order; None for none.Returns:@@ -1347,6 +1354,14 @@ def merged_axis_config(*configs: NumberLineOptions | None) -> NumberLineOptions:merged = merged | config_if numbers:merged["decimal_number_config"] = numbers+ for key in (+ "numbers_to_include",+ "numbers_to_exclude",+ "numbers_with_elongated_ticks",+ ):+ values = merged.get(key)+ if isinstance(values, Iterator):+ merged[key] = list(values)return merged@@ -1359,7 +1374,7 @@ class AxisLine(TypedDict, total=False):"""The class of the line (default [DashedLine][manimgx.DashedLine]; a[Line][manimgx.Line] is solid)."""line_config: DashedLineOptions | None- """[Dashed line keywords][manimgx.mobjects.shapes.DashedLineOptions] for the+ """[Dashed line keywords][manimgx.DashedLine] for theline, but its color and width, which `color` and `stroke_width` set (default None:none)."""color: ParsableManimColor | None@@ -1438,7 +1453,7 @@ class Axes(VGroup):less 2, rounded (12); None for `unit_size` (by default 1) per unit.y_length: The y-axis's length, in scene units: by default the frame's heightless 2, rounded (6); None for `unit_size` per unit.- axis_config: [Number line keywords][manimgx.mobjects.plotting.NumberLineOptions]+ axis_config: [Number line keywords][manimgx.NumberLine]for both axes: `include_numbers`, `font_size`, `color`, …; None for none.x_axis_config: Number line keywords for the x-axis, over `axis_config`'s; Nonefor none.@@ -1743,7 +1758,7 @@ class Axes(VGroup):) -> Mobject:label_mobject: Mobject = self.x_axis._create_label_tex(label)label_mobject.next_to(- axis.get_edge_center(edge), direction=direction, buff=buff+ axis.get_critical_point(edge), direction=direction, buff=buff)label_mobject.shift_onto_screen(buff=MED_SMALL_BUFF)return label_mobject@@ -1798,7 +1813,7 @@ class Axes(VGroup):Args:*axes_numbers: What to write on each axis, in order: None, values, orlabels by value; the axes past the last argument get nothing.- **kwargs: [Number keywords][manimgx.mobjects.numbers.DecimalNumberOptions]+ **kwargs: [Number keywords][manimgx.DecimalNumber]for the numbers: `font_size`, `num_decimal_places`, `color`, … (only`font_size`, for labels by value).@@ -1843,6 +1858,7 @@ class Axes(VGroup):self.coordinate_labels.add(labels)return self+ @deprecated("use get_vertical_line or get_horizontal_line", category=None)def get_line_from_axis_to_point(self,index: int,@@ -1860,7 +1876,7 @@ class Axes(VGroup):point: The point, in scene coordinates.line_func: The class of the line: [DashedLine][manimgx.DashedLine], or[Line][manimgx.Line] for a solid one, ….- line_config: [Dashed line keywords][manimgx.mobjects.shapes.DashedLineOptions]+ line_config: [Dashed line keywords][manimgx.DashedLine]for the line, but its color and width; None for none.color: The line's color; None for white.stroke_width: The line's width, in hundredths of a scene unit.@@ -2851,8 +2867,9 @@ class Axes(VGroup):self.play(m.Create(graph))```"""- xs, ys = np.array(list(x_values), dtype=float), np.array(- list(y_values), dtype=float+ xs, ys = (+ np.array(list(x_values), dtype=float),+ np.array(list(y_values), dtype=float),)zs = (np.zeros(xs.shape)@@ -2908,7 +2925,7 @@ class AxesOptions(Style, total=False):keywords."""axis_config: NumberLineOptions | None- """[Number line keywords][manimgx.mobjects.plotting.NumberLineOptions]+ """[Number line keywords][manimgx.NumberLine]for every axis: `include_numbers`, `font_size`, `color`, … (default None: none)."""x_axis_config: NumberLineOptions | None"""Number line keywords for the x-axis, over `axis_config`'s (default None:@@ -2958,7 +2975,7 @@ class ThreeDAxes(Axes):`unit_size` per unit.z_length: The z-axis's length, in scene units: by default the frame's heightless 1.5 (6.5); None for `unit_size` per unit.- z_axis_config: [Number line keywords][manimgx.mobjects.plotting.NumberLineOptions]+ z_axis_config: [Number line keywords][manimgx.NumberLine]for the z-axis, over `axis_config`'s; None for none.**kwargs: [Axes keywords][manimgx.mobjects.plotting.AxesOptions]:`axis_config`, `x_axis_config`, `y_axis_config`, `tips`.@@ -3266,9 +3283,11 @@ class NumberPlane(_Plane):Args:x_range: The x-axis's range, `[x_min, x_max, x_step]`: a vertical line of the- grid at every step. By default the frame's width, by 1.+ grid at every step. None for the frame's width when the plane is made, by+ 1.y_range: The y-axis's range, `[y_min, y_max, y_step]`: a horizontal line of- the grid at every step. By default the frame's height, by 1.+ the grid at every step. None for the frame's height when the plane is made,+ by 1.x_length: The x-axis's length, in scene units; None for one scene unit perunit.y_length: The y-axis's length, in scene units; None for one scene unit per@@ -3303,16 +3322,8 @@ class NumberPlane(_Plane):def __init__(self,- x_range: Sequence[float] | None = (- -config["frame_x_radius"],- config["frame_x_radius"],- 1,- ),- y_range: Sequence[float] | None = (- -config["frame_y_radius"],- config["frame_y_radius"],- 1,- ),+ x_range: Sequence[float] | None = None,+ y_range: Sequence[float] | None = None,x_length: float | None = None,y_length: float | None = None,background_line_style: Style | None = None,@@ -3334,6 +3345,11 @@ class NumberPlane(_Plane):kwargs["y_axis_config"] = merged_axis_config({"label_direction": DR}, kwargs.get("y_axis_config"))+ # the frame as it is now: a tall video's (9:16) is taller than a wide one's+ if x_range is None:+ x_range = (-config.frame_x_radius, config.frame_x_radius, 1)+ if y_range is None:+ y_range = (-config.frame_y_radius, config.frame_y_radius, 1)super().__init__(background_line_style=background_line_style,faded_line_style=faded_line_style,@@ -3373,10 +3389,10 @@ class NumberPlane(_Plane):x_min, x_max, _ = axis_perpendicular_to.x_rangeif axis_perpendicular_to.x_min > 0 and x_min < 0:x_min, x_max = (0, np.abs(x_min) + np.abs(x_max))- ranges = (+ ranges = ( # (short of the edges, which no rounding of the steps puts a line on)[0],- np.arange(step, min(x_max - x_min, x_max), step),- np.arange(-step, max(x_min - x_max, x_min), -step),+ np.arange(step, min(x_max - x_min, x_max) - step * 1e-06, step),+ np.arange(-step, max(x_min - x_max, x_min) + step * 1e-06, -step),)for inputs in ranges:for k, x in enumerate(inputs):@@ -3414,7 +3430,8 @@ class PolarPlane(_Plane):retains its drawn grid rather than those setup attributes.Args:- radius_max: The radius of the outer circle, in the plane's units.+ radius_max: The radius of the outer circle, in the plane's units; None for half+ the frame's short side when the plane is made (4).size: The plane's width, its diameter, in scene units; None for one scene unitper unit.radius_step: The distance between two circles, in the plane's units.@@ -3433,7 +3450,7 @@ class PolarPlane(_Plane):azimuth_label_buff: The gap between the outer circle and the angles' labels, inscene units.azimuth_label_font_size: The font size of the angles' labels.- radius_config: [Number line keywords][manimgx.mobjects.plotting.NumberLineOptions]+ radius_config: [Number line keywords][manimgx.NumberLine]for the radii's axes, over the plane's own (no ticks, no tips, 2 wide,font size 24, numbers below and to the left); None for none.background_line_style: [Style keywords][manimgx.drawing.paint.Style] for the@@ -3472,7 +3489,7 @@ class PolarPlane(_Plane):def __init__(self,- radius_max: float = config["frame_y_radius"],+ radius_max: float | None = None,size: float | None = None,radius_step: float = 1,azimuth_step: float | None = None,@@ -3489,6 +3506,11 @@ class PolarPlane(_Plane):**kwargs: Unpack[Style],):self.azimuth_units, self.azimuth_direction = azimuth_units, azimuth_direction+ radius = (+ min(config.frame_x_radius, config.frame_y_radius)+ if radius_max is None+ else radius_max+ )radius_config = merged_axis_config({"stroke_width": 2,@@ -3520,8 +3542,8 @@ class PolarPlane(_Plane):background_line_style=background_line_style,faded_line_style=faded_line_style,faded_line_ratio=faded_line_ratio,- x_range=(-radius_max, radius_max, radius_step),- y_range=(-radius_max, radius_max, radius_step),+ x_range=(-radius, radius, radius_step),+ y_range=(-radius, radius, radius_step),x_length=size,y_length=size,axis_config=radius_config,@@ -3537,7 +3559,11 @@ class PolarPlane(_Plane):parts1: list[VMobject] = []parts2: list[VMobject] = []unit_vector = self.x_axis.get_unit_vector()[0]- for k, x in enumerate(np.arange(0, self.x_axis.x_range[1] + rstep, rstep)):+ # (the circles to the radius, the lines short of a whole turn: no rounding of the+ # steps adds one beyond them)+ for k, x in enumerate(+ np.arange(0, self.x_axis.x_range[1] + rstep * 1e-06, rstep)+ ):(parts1 if k % ratio_faded_lines == 0 else parts2).append(Circle(radius=x * unit_vector))@@ -3545,7 +3571,7 @@ class PolarPlane(_Plane):alines2.add(*parts2)parts1, parts2 = [], []line = Line(center, self.get_x_axis().get_end())- for k, x in enumerate(np.arange(0, TAU, astep)):+ for k, x in enumerate(np.arange(0, TAU - astep * 1e-06, astep)):new_line = line.copy()new_line.rotate(x + self.azimuth_offset, about_point=center)(parts1 if k % ratio_faded_lines == 0 else parts2).append(new_line)@@ -3639,7 +3665,7 @@ class PolarPlane(_Plane):Args:number: The angle, as a fraction of a turn (0.375 for 3π/4).- **kwargs: [Math keywords][manimgx.mobjects.text.MathTexOptions]+ **kwargs: [Math keywords][manimgx.MathTex]for the label; its font size is 24 unless given.Returns:@@ -3741,7 +3767,7 @@ class ComplexPlane(NumberPlane):Args:*numbers: The numbers to label; none for the ticks of both axes, but 0.- **kwargs: [Number keywords][manimgx.mobjects.numbers.DecimalNumberOptions]+ **kwargs: [Number keywords][manimgx.DecimalNumber]for the labels: `font_size`, `num_decimal_places`, `color`, ….Returns:@@ -3772,7 +3798,7 @@ class ComplexPlane(NumberPlane):Args:*numbers: The numbers to label; none for the ticks of both axes, but 0.- **kwargs: [Number keywords][manimgx.mobjects.numbers.DecimalNumberOptions]+ **kwargs: [Number keywords][manimgx.DecimalNumber]for the labels: `font_size`, `num_decimal_places`, `color`, …."""self.add(self.get_coordinate_labels(*numbers, **kwargs))@@ -3782,8 +3808,8 @@ class ComplexPlane(NumberPlane):EPSILON = 0.0001-"""How far from 1 probabilities may sum before-[complete_p_list][manimgx.SampleSpace.complete_p_list] adds the rest as a part."""+"""How far from 1 probabilities may sum before a sample space adds the rest as a+part."""class SampleSpace(Rectangle):@@ -3839,6 +3865,7 @@ class SampleSpace(Rectangle):super().__init__(height=height, width=width, **kwargs)self.default_label_scale_val = default_label_scale_val+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)def complete_p_list(self, p_list: float | Iterable[float]) -> list[float]:"""The probabilities of a division, completed to sum to 1: the rest, 1 minustheir sum, is added as one more, unless it is within 0.0001 of 0.@@ -3872,8 +3899,8 @@ class SampleSpace(Rectangle):space itself.Args:- p_list: The probabilities, completed to sum to 1 (see- [complete_p_list][manimgx.SampleSpace.complete_p_list]).+ p_list: The probabilities: a part is added for the rest, if they sum to less+ than 1.dim: The dimension divided: 0 for the width, 1 for the height.colors: The colors, a gradient over the parts.vect: The direction the parts follow one another in.@@ -3882,7 +3909,7 @@ class SampleSpace(Rectangle):A new group of the parts, not added to the space."""p_list_complete = self.complete_p_list(p_list)- last_point = self.get_edge_center(-vect)+ last_point = self.get_critical_point(-vect)parts = VGroup()for factor, color in zip(p_list_complete, color_gradient(colors, len(p_list_complete)), strict=True@@ -3892,7 +3919,7 @@ class SampleSpace(Rectangle):part.replace(self, stretch=True)part.stretch(factor, dim)part.move_to(last_point, -vect)- last_point = part.get_edge_center(vect)+ last_point = part.get_critical_point(vect)parts.add(part)return partsdiff --git a/src/manimgx/mobjects/vector_field.py b/src/manimgx/mobjects/vector_field.pynew file mode 100644index 00000000..92551463--- /dev/null+++ b/src/manimgx/mobjects/vector_field.py@@ -0,0 +1,801 @@+# SPDX-FileCopyrightText: 2026 Academa, Inc.+# SPDX-FileCopyrightText: 2024 the Manim Community Developers+# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC+# SPDX-License-Identifier: MIT++"""Ported from Manim CE 0.21 (MIT)."""++from __future__ import annotations++__all__ = ["ArrowVectorField", "StreamLines", "VectorField"]+import itertools as it+import random+from collections.abc import Callable, Sequence+from math import ceil, floor+from typing import TYPE_CHECKING, Self, Unpack++import numpy as np++from manimgx.animation.easing import ease_out_sine, linear+from manimgx.animation.motion import Create, ShowPassingFlash, UpdateFromAlphaFunc+from manimgx.animation.timeline import (+ Animation,+ AnimationGroup,+ AnimationOptions,+ Succession,+ Untimed,+)+from manimgx.config import config+from manimgx.constants import OUT, RIGHT, UP+from manimgx.drawing.geometry import interpolate, inverse_interpolate, sigmoid+from manimgx.drawing.paint import (+ BLUE_E,+ GREEN,+ RED,+ YELLOW,+ Look,+ ManimColor,+ ParsableManimColor,+ StyleBase,+ color_to_rgb,+ rgb_to_color,+)+from manimgx.mobject import Mobject, VGroup, VMobject, flow+from manimgx.mobjects.plotting import Axes+from manimgx.mobjects.shapes import ArrowTips, Vector++if TYPE_CHECKING:+ from manimgx.typing import FloatRGB, FloatRGB_Array, Point3D, Vector3D++DEFAULT_SCALAR_FIELD_COLORS: list[ParsableManimColor] = [BLUE_E, GREEN, YELLOW, RED]+"""The colors a vector field takes by default, from its shortest vectors to its longest:+`BLUE_E`, `GREEN`, `YELLOW`, `RED`."""+type FieldFunction = Callable[[Point3D], Vector3D]+"""A vector field: a function from a point, an array of its three coordinates in scene+coordinates, to the field's vector there."""+++def _field_ranges(+ x_range: Sequence[float] | None,+ y_range: Sequence[float] | None,+ z_range: Sequence[float] | None,+ three_dimensions: bool,+) -> tuple[list[float], list[float], list[float]]:+ """Where a field is sampled, per axis: (start, stop past the end, step) — the frame by default,+ one layer in z unless three-dimensional."""+ xs: list[float] = (+ list(x_range)+ if x_range+ else [floor(-config.frame_width / 2), ceil(config.frame_width / 2)]+ )+ ys: list[float] = (+ list(y_range)+ if y_range+ else [floor(-config.frame_height / 2), ceil(config.frame_height / 2)]+ )+ zs: list[float] = (+ (list(z_range) if z_range else ys.copy())+ if three_dimensions or z_range+ else [0.0, 0.0]+ )+ for axis in (xs, ys, zs):+ if len(axis) == 2:+ axis.append(0.5)+ axis[1] += axis[2]+ return xs, ys, zs+++class VectorField(VGroup):+ """What the vector fields have in common: a function giving a vector at every point,+ colors by the vectors' lengths, and the tools to carry mobjects along the field.++ A field is drawn by its kinds: as arrows+ ([ArrowVectorField][manimgx.ArrowVectorField]) or as the lines that follow it+ ([StreamLines][manimgx.StreamLines]). Unless given one color, each part takes the+ field's color where it is: the vector's length there (or `color_scheme`'s value),+ between `min_color_scheme_value` and `max_color_scheme_value`, placed along+ `colors` and blended between them; values beyond take the first or the last color.+ [nudge][manimgx.VectorField.nudge] carries a mobject along the field, and+ [get_nudge_updater][manimgx.VectorField.get_nudge_updater] keeps it flowing.++ Args:+ func: The field: a function from a point (an array of its three coordinates, in+ scene coordinates) to the vector there.+ color: One color for the whole field; None to color it by its vectors.+ color_scheme: The value a vector is colored by, a function from the vector to a+ number; None for its length.+ min_color_scheme_value: The value that takes the first color.+ max_color_scheme_value: The value that takes the last color.+ colors: The colors, spread evenly from the first value to the last.+ **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the field's group+ itself: as it has no points, they do not restyle its parts.+ """++ def __init__(+ self,+ func: FieldFunction,+ color: ParsableManimColor | None = None,+ color_scheme: Callable[[Vector3D], float] | None = None,+ min_color_scheme_value: float = 0,+ max_color_scheme_value: float = 2,+ colors: Sequence[ParsableManimColor] = DEFAULT_SCALAR_FIELD_COLORS,+ **kwargs: Unpack[StyleBase],+ ):+ super().__init__(**kwargs)+ self.func = func+ """The field: its function, from a point to the vector there."""+ if color is None:+ self.single_color = False+ self.color_scheme: Callable[[Vector3D], float] = color_scheme or (+ lambda vec: float(np.linalg.norm(vec))+ )+ self.rgbs: FloatRGB_Array = np.array(list(map(color_to_rgb, colors)))++ self._color_range = (min_color_scheme_value, max_color_scheme_value)+ else:+ self.single_color = True+ self.color = ManimColor.parse(color)+ self.submob_movement_updater: Callable[[VectorField, float], object] | None = (+ None+ )++ def pos_to_rgb(self, pos: Point3D) -> FloatRGB:+ """The field's RGB color at a point, using its current function and palette."""+ if self.single_color:+ return self.color.to_rgb()+ low, high = self._color_range+ color_value = np.clip(self.color_scheme(self.func(pos)), low, high)+ alpha = inverse_interpolate(low, high, color_value)+ alpha *= len(self.rgbs) - 1+ c1: FloatRGB = self.rgbs[int(alpha)]+ c2: FloatRGB = self.rgbs[min(int(alpha + 1), len(self.rgbs) - 1)]+ return interpolate(c1, c2, alpha % 1)++ def pos_to_color(self, pos: Point3D) -> ManimColor:+ """The field's color at a point."""+ return rgb_to_color(self.pos_to_rgb(pos))++ @staticmethod+ def shift_func(func: FieldFunction, shift_vector: np.ndarray) -> FieldFunction:+ """Move a field: make the function of the field shifted by a vector.++ Args:+ func: The field's function.+ shift_vector: The vector to move it by, in scene units.++ Returns:+ A new function, which at a point p is `func(p - shift_vector)`.+ """+ return lambda p: func(p - shift_vector)++ @staticmethod+ def scale_func(func: FieldFunction, scalar: float) -> FieldFunction:+ """Rescale a field's pattern: make the function of the field whose vector at a+ point p is the old field's at p × `scalar`.++ A scalar below 1 spreads the pattern out, as if zoomed in; above 1, it draws it+ together. The vectors keep their lengths.++ Args:+ func: The field's function.+ scalar: The factor the points are multiplied by.++ Returns:+ A new function, which at a point p is `func(p * scalar)`.+ """+ return lambda p: func(p * scalar)++ def fit_to_coordinate_system(self, coordinate_system: Axes) -> Self:+ """Place the field on axes: move each point of its parts to the axes' point+ whose coordinates are the point's own.++ A field made in the axes' coordinates (its ranges theirs) lands on them, its+ arrows stretched with the axes' units.++ Args:+ coordinate_system: The axes.++ Examples:+ ```python+ import numpy as np++ import manimgx as m+++ class VectorFieldFitToCoordinateSystemExample(m.Scene):+ def construct(self) -> None:+ axes = m.Axes(+ x_range=[-2, 2], y_range=[-2, 2], x_length=7, y_length=7+ )+ field = m.ArrowVectorField(+ lambda p: np.array([-p[1], p[0], 0]) / 2,+ x_range=[-2, 2, 0.5],+ y_range=[-2, 2, 0.5],+ )+ self.add(axes, field.fit_to_coordinate_system(axes))+ ```+ """+ self.apply_function(lambda pos: coordinate_system.coords_to_point(*pos))+ return self++ def nudge(+ self, mob: Mobject, dt: float = 1, substeps: int = 1, pointwise: bool = False+ ) -> Self:+ """Carry a mobject along the field for a while, as a particle on its flow.++ The field's vectors are velocities: the mobject moves with the field at its+ center, or, with `pointwise`, each of its points moves with the field where it+ is, which bends it. Each step is a fourth-order Runge–Kutta step.++ Args:+ mob: The mobject to move.+ dt: How long it is carried, in the field's time; negative to carry it back.+ substeps: How many steps the time is divided into: more follow the field+ more closely.+ pointwise: Whether each point of the mobject moves on its own, rather than+ the whole mobject with its center.+ """++ def runge_kutta(p: Point3D, step_size: float) -> Vector3D:+ k_1 = self.func(p)+ k_2 = self.func(p + step_size * (k_1 * 0.5))+ k_3 = self.func(p + step_size * (k_2 * 0.5))+ k_4 = self.func(p + step_size * k_3)+ return step_size / 6.0 * (k_1 + 2.0 * k_2 + 2.0 * k_3 + k_4)++ step_size = dt / substeps+ for _ in range(substeps):+ if pointwise:+ mob.apply_function(lambda p: p + runge_kutta(p, step_size))+ else:+ mob.shift(runge_kutta(mob.get_center(), step_size))+ return self++ def nudge_submobjects(+ self, dt: float = 1, substeps: int = 1, pointwise: bool = False+ ) -> Self:+ """Carry each of the field's own parts along it for a while, as+ [nudge][manimgx.VectorField.nudge] carries a mobject.++ Args:+ dt: How long they are carried, in the field's time; negative to carry them+ back.+ substeps: How many steps the time is divided into.+ pointwise: Whether each point of a part moves on its own, rather than the+ whole part with its center.+ """+ for mob in self.submobjects:+ self.nudge(mob, dt, substeps, pointwise)+ return self++ def get_nudge_updater(+ self, speed: float = 1, pointwise: bool = False+ ) -> Callable[[Mobject, float], Mobject]:+ """Make an updater that carries a mobject along the field: added to a mobject,+ it moves it with the field every frame, by the time since the last.++ Args:+ speed: How fast the mobject is carried: the field's time per second.+ pointwise: Whether each point of the mobject moves on its own, rather than+ the whole mobject with its center.++ Returns:+ The updater, a function of the mobject and the time step, to give+ [add_updater][manimgx.Mobject.add_updater].++ Examples:+ ```python+ import numpy as np++ import manimgx as m+++ class VectorFieldGetNudgeUpdaterExample(m.Scene):+ def construct(self) -> None:+ def swirl(p: np.ndarray) -> np.ndarray:+ return np.sin(p[1] / 2) * m.RIGHT + np.cos(p[0] / 2) * m.UP++ field = m.ArrowVectorField(+ swirl, x_range=[-7, 7, 1], y_range=[-4, 4, 1]+ )+ circle = m.Circle(radius=1, color=m.YELLOW).shift(2 * m.LEFT)+ dot = m.Dot(2 * m.RIGHT, radius=0.15, color=m.RED)+ circle.add_updater(field.get_nudge_updater(pointwise=True))+ dot.add_updater(field.get_nudge_updater())+ self.add(field, circle, dot)+ self.wait(2.5)+ ```+ """+ return lambda mob, dt: self.nudge(mob, dt * speed, pointwise=pointwise)++ def start_submobject_movement(+ self, speed: float = 1, pointwise: bool = False+ ) -> Self:+ """Set the field's own parts moving along it: an updater carries them every+ frame, as [nudge_submobjects][manimgx.VectorField.nudge_submobjects] does.++ A movement already started is replaced.++ Args:+ speed: How fast they are carried: the field's time per second.+ pointwise: Whether each point of a part moves on its own, rather than the+ whole part with its center.+ """+ self.stop_submobject_movement()+ self.submob_movement_updater = lambda mob, dt: mob.nudge_submobjects(+ dt * speed, pointwise=pointwise+ )+ self.add_updater(self.submob_movement_updater)+ return self++ def stop_submobject_movement(self) -> Self:+ """Stop the movement+ [start_submobject_movement][manimgx.VectorField.start_submobject_movement]+ started, if any.+ """+ if self.submob_movement_updater is not None:+ self.remove_updater(self.submob_movement_updater)+ self.submob_movement_updater = None+ return self+++class ArrowVectorField(VectorField):+ """A vector field drawn as arrows: one at each point of a grid, from the point in+ the field's direction there; colored by the vectors' lengths, blue to red, unless+ given a color.++ The grid spans `x_range` and `y_range` — by default the frame, every half unit — in+ the plane z = 0, or through `z_range` too. Each arrow is as long as `length_func`+ makes of its vector's length: by default 0.45 × sigmoid(length), from 0.225 for the+ shortest vectors to 0.45 for the longest, so that neighbours do not overlap (a zero+ vector makes no arrow).++ Args:+ func: The field: a function from a point (an array of its three coordinates, in+ scene coordinates) to the vector there.+ color: One color for every arrow; None to color them by their vectors.+ color_scheme: The value a vector is colored by, a function from the vector to a+ number; None for its length.+ min_color_scheme_value: The value that takes the first color.+ max_color_scheme_value: The value that takes the last color.+ colors: The colors, spread evenly from the first value to the last.+ x_range: The grid's x values, `[x_min, x_max, x_step]` with both ends, or+ `[x_min, x_max]` for a step of 0.5; None for the frame's width, [-8, 8].+ y_range: The grid's y values, likewise; None for the frame's height, [-4, 4].+ z_range: The grid's z values, likewise; None for z = 0 alone, or the y values+ with `three_dimensions`.+ three_dimensions: Whether the grid spans z too: by `z_range`, or by the y+ values.+ length_func: The arrows' length, as a function of their vectors' length.+ opacity: The arrows' opacity, from 0 to 1.+ vector_config: [Arrow keywords][manimgx.mobjects.shapes.ArrowTips] for the+ arrows: their tips, `stroke_width`, …; None for none.+ **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the field's group+ itself: as it has no points, they do not restyle its arrows.++ Examples:+ ```python+ import numpy as np++ import manimgx as m+++ class ArrowVectorFieldExample(m.Scene):+ def construct(self) -> None:+ field = m.ArrowVectorField(lambda p: np.array([-p[1], p[0], 0]) / 2)+ self.add(field)+ ```+ """++ def __init__(+ self,+ func: FieldFunction,+ color: ParsableManimColor | None = None,+ color_scheme: Callable[[Vector3D], float] | None = None,+ min_color_scheme_value: float = 0,+ max_color_scheme_value: float = 2,+ colors: Sequence[ParsableManimColor] = DEFAULT_SCALAR_FIELD_COLORS,+ x_range: Sequence[float] | None = None,+ y_range: Sequence[float] | None = None,+ z_range: Sequence[float] | None = None,+ three_dimensions: bool = False,+ length_func: Callable[[float], float] = lambda norm: 0.45 * sigmoid(norm),+ opacity: float = 1.0,+ vector_config: ArrowTips | None = None,+ **kwargs: Unpack[StyleBase],+ ):+ x_range, y_range, z_range = _field_ranges(+ x_range, y_range, z_range, three_dimensions+ )+ super().__init__(+ func,+ color,+ color_scheme,+ min_color_scheme_value,+ max_color_scheme_value,+ colors,+ **kwargs,+ )+ self.length_func = length_func+ self.vector_config: ArrowTips = vector_config or {}+ grid = it.product(np.arange(*x_range), np.arange(*y_range), np.arange(*z_range))+ self.add(*(self.get_vector(x * RIGHT + y * UP + z * OUT) for x, y, z in grid))+ self.set_opacity(opacity)++ def get_vector(self, point: Point3D) -> Vector:+ """Make the field's arrow at a point: from the point, in the field's direction+ there, as long as `length_func` makes it, in the field's color there.++ Args:+ point: The point, in scene coordinates.++ Returns:+ A new [Vector][manimgx.Vector], not added to the field.+ """+ output = np.array(self.func(point), dtype=float)+ norm = np.linalg.norm(output)+ if norm != 0:+ output *= self.length_func(float(norm)) / norm+ vect = Vector(output, **self.vector_config)+ vect.shift(point)+ vect.set_color(self.color if self.single_color else self.pos_to_color(point))+ return vect+++class StreamLine(VMobject):+ """One stream line: how long it flows, and its animation while the field flows."""++ duration: float+ anim: Animation+ time: float+++class StreamLines(VectorField):+ """A vector field drawn as the lines that follow it: from points spread over a grid,+ the paths of particles the field carries; colored by the vectors' lengths, blue to+ red, unless given a color.++ The lines start at the points of a grid (`x_range`, `y_range`, `z_range`, as an+ [ArrowVectorField][manimgx.ArrowVectorField]'s), each moved a little at random —+ the same way every time — and `n_repeats` near each point. Each follows the field+ in steps of `dt` for `virtual_time`, and stops where it leaves the grid's box,+ widened by `padding`. A line takes the field's colors at its points, in a gradient+ from its start to its end. [create][manimgx.StreamLines.create] draws them in;+ [start_animation][manimgx.StreamLines.start_animation] sets them flowing, and+ [end_animation][manimgx.StreamLines.end_animation] ends the flow.++ Args:+ func: The field: a function from a point (an array of its three coordinates, in+ scene coordinates) to the vector there.+ color: One color for every line; None to color them by their vectors.+ color_scheme: The value a vector is colored by, a function from the vector to a+ number; None for its length.+ min_color_scheme_value: The value that takes the first color.+ max_color_scheme_value: The value that takes the last color.+ colors: The colors, spread evenly from the first value to the last.+ x_range: The x values of the lines' starts, `[x_min, x_max, x_step]` with both+ ends, or `[x_min, x_max]` for a step of 0.5; None for the frame's width,+ [-8, 8].+ y_range: The y values of the starts, likewise; None for the frame's height,+ [-4, 4].+ z_range: The z values of the starts, likewise; None for z = 0 alone, or the y+ values with `three_dimensions`.+ three_dimensions: Whether the starts span z too: by `z_range`, or by the y+ values.+ noise_factor: How far each start may be moved, in scene units: up to half of it+ either way, in each coordinate; None for half the y step.+ n_repeats: How many lines start near each point of the grid.+ dt: The time step the lines are traced with: smaller follows the field more+ closely.+ virtual_time: How long each line follows the field, in the field's time: longer+ makes longer lines.+ max_anchors_per_line: The most points a line is smoothed through.+ padding: How far beyond the grid the lines may go before they stop, in scene+ units.+ stroke_width: The lines' width, in hundredths of a scene unit.+ opacity: The lines' opacity, from 0 to 1.++ Examples:+ ```python+ import numpy as np++ import manimgx as m+++ class StreamLinesExample(m.Scene):+ def construct(self) -> None:+ def func(p: np.ndarray) -> np.ndarray:+ return np.sin(p[0] / 2) * m.UR + np.cos(p[1] / 2) * m.LEFT++ self.add(m.StreamLines(func, stroke_width=2, padding=1))+ ```+ """++ def __init__(+ self,+ func: FieldFunction,+ color: ParsableManimColor | None = None,+ color_scheme: Callable[[Vector3D], float] | None = None,+ min_color_scheme_value: float = 0,+ max_color_scheme_value: float = 2,+ colors: Sequence[ParsableManimColor] = DEFAULT_SCALAR_FIELD_COLORS,+ x_range: Sequence[float] | None = None,+ y_range: Sequence[float] | None = None,+ z_range: Sequence[float] | None = None,+ three_dimensions: bool = False,+ noise_factor: float | None = None,+ n_repeats: int = 1,+ dt: float = 0.05,+ virtual_time: float = 3,+ max_anchors_per_line: int = 100,+ padding: float = 3,+ stroke_width: float = 1,+ opacity: float = 1,+ **kwargs: Unpack[Look],+ ):+ x_range, y_range, z_range = _field_ranges(+ x_range, y_range, z_range, three_dimensions+ )+ super().__init__(+ func,+ color,+ color_scheme,+ min_color_scheme_value,+ max_color_scheme_value,+ colors,+ **kwargs,+ )+ noise_factor = noise_factor if noise_factor is not None else y_range[2] / 2+ self.virtual_time = virtual_time+ """How long each line follows the field, in the field's time."""+ self.stroke_width = stroke_width+ half_noise = noise_factor / 2+ rng = np.random.default_rng(0)+ start_points = np.array(+ [+ (x - half_noise) * RIGHT+ + (y - half_noise) * UP+ + (z - half_noise) * OUT+ + noise_factor * rng.random(3)+ for n in range(n_repeats)+ for x in np.arange(*x_range)+ for y in np.arange(*y_range)+ for z in np.arange(*z_range)+ ]+ )+ pad = padding+ (x0, x1, xs), (y0, y1, ys), (z0, z1, zs) = (+ x_range,+ y_range,+ z_range,+ )++ def outside_box(p: Point3D) -> bool:+ return bool(+ p[0] < x0 - pad+ or p[0] > x1 + pad - xs+ or p[1] < y0 - pad+ or p[1] > y1 + pad - ys+ or p[2] < z0 - pad+ or p[2] > z1 + pad - zs+ )++ max_steps = ceil(virtual_time / dt) + 1+ self.stream_lines: list[StreamLine] = []+ """The lines, in the order of their starts."""+ for point in start_points:+ points = [point]+ for _ in range(max_steps):+ new_point = points[-1] + dt * func(points[-1])+ if outside_box(new_point):+ break+ points.append(new_point)+ line = StreamLine()+ line.duration = max_steps * dt+ line.set_points_smoothly(+ points[:: max(1, int(len(points) / max_anchors_per_line))]+ )+ if self.single_color:+ line.set_stroke(+ color=self.color, width=self.stroke_width, opacity=opacity+ )+ else: # the field's color at each anchor, in order along the line: the gradient+ # runs from the line's start to its end (not across its box)+ line.set_stroke([self.pos_to_color(p) for p in line.get_anchors()])+ line.set_stroke(width=self.stroke_width, opacity=opacity)+ travel = np.sign(line.get_end() - line.get_start())+ if travel.any():+ line.set_sheen_direction(travel)+ self.add(line)+ self.stream_lines.append(line)+ self.flow_animation: Callable[[StreamLines, float], None] | None = None++ def create(self, **kwargs: Unpack[AnimationOptions]) -> AnimationGroup:+ """Make an animation that draws the lines in, one after another in a random+ order.++ Each line is drawn with [Create][manimgx.Create] over `run_time`, by default+ the field's `virtual_time`, each beginning `lag_ratio` of that after the one+ before: by default `run_time / 2` divided by the number of lines. The order is+ shuffled with Python's `random` (seed it for the same order every time).++ Args:+ **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions]+ for each line's animation, and `lag_ratio` for the whole.++ Returns:+ A new animation group.++ Examples:+ ```python+ import manimgx as m+++ class StreamLinesCreateExample(m.Scene):+ def construct(self) -> None:+ stream_lines = m.StreamLines(+ lambda p: (p[0] * m.UR + p[1] * m.LEFT) - p,+ color=m.YELLOW,+ x_range=[-7, 7, 1],+ y_range=[-4, 4, 1],+ stroke_width=3,+ virtual_time=1,+ max_anchors_per_line=6,+ )+ self.play(stream_lines.create())+ ```+ """+ run_time = kwargs.pop("run_time", self.virtual_time)+ lag_ratio = kwargs.pop("lag_ratio", run_time / 2 / len(self.submobjects))+ kwargs["run_time"] = run_time+ animations = [Create(line, **kwargs) for line in self.stream_lines]+ random.shuffle(animations)+ return AnimationGroup(*animations, lag_ratio=lag_ratio)++ def start_animation(+ self,+ warm_up: bool = True,+ flow_speed: float = 1,+ time_width: float = 0.3,+ line_animation_class: type[ShowPassingFlash] = ShowPassingFlash,+ **kwargs: Unpack[Untimed],+ ) -> Self:+ """Set the lines flowing: each flashes along itself, over and over, while the+ scene plays or waits.++ An updater plays each line's animation — by default a+ [ShowPassingFlash][manimgx.ShowPassingFlash] — along the line again and again,+ a cycle every `virtual_time / flow_speed` seconds, each line at a phase of its+ own, drawn with Python's `random`.+ [end_animation][manimgx.StreamLines.end_animation] ends the flow.++ Args:+ warm_up: Whether each line waits, empty, until its own time to begin,+ rather than all flowing from the start.+ flow_speed: How fast the lines flow: the field's time per second.+ time_width: The length of each flash, as a fraction of its line.+ line_animation_class: The animation played along each line: a+ ShowPassingFlash, or a class of its kind.+ **kwargs: [Animation options][manimgx.animation.timeline.Untimed] for each+ line's animation, but `run_time`; `rate_func` is `linear` unless given.++ Examples:+ ```python+ import numpy as np++ import manimgx as m+++ class StreamLinesStartAnimationExample(m.Scene):+ def construct(self) -> None:+ def func(p: np.ndarray) -> np.ndarray:+ return np.sin(p[0] / 2) * m.UR + np.cos(p[1] / 2) * m.LEFT++ stream_lines = m.StreamLines(+ func, stroke_width=3, max_anchors_per_line=7+ )+ self.add(stream_lines)+ stream_lines.start_animation(warm_up=False, flow_speed=1.5)+ self.wait(stream_lines.virtual_time / stream_lines.flow_speed)+ ```+ """+ kwargs.setdefault("rate_func", linear)+ for line in self.stream_lines:+ line.anim = line_animation_class(+ line,+ run_time=line.duration / flow_speed,+ time_width=time_width,+ **kwargs,+ )+ line.anim.begin()+ line.time = random.random() * self.virtual_time * (-1 if warm_up else 1)+ self.add(line.anim.mobject)++ def updater(mob: StreamLines, dt: float) -> None:+ for line in mob.stream_lines:+ line.time += dt * flow_speed+ if line.time >= mob.virtual_time:+ line.time -= mob.virtual_time+ line.anim.interpolate(+ float(np.clip(line.time / line.anim.run_time, 0, 1))+ )++ self.add_updater(flow(updater)) # each line at the time it has run+ self.flow_animation = updater+ self.flow_speed = flow_speed+ self.time_width = time_width+ return self++ def end_animation(self) -> AnimationGroup:+ """Make an animation that ends the flow: each line finishes its flash, then is+ drawn in with [Create][manimgx.Create], easing out.++ The flow's updater is removed at once, and a line still waiting to begin stays+ hidden until its time. Called before+ [start_animation][manimgx.StreamLines.start_animation], it raises a+ ValueError.++ Warning:+ The lines end hidden, not whole: a finished flash leaves its line trimmed+ past its end, and the Create that follows draws the line only as it finds+ it.++ Returns:+ A new animation group.+ """+ if self.flow_animation is None:+ raise ValueError("You have to start the animation before fading it out.")++ def hide_and_wait(mob: Mobject, alpha: float) -> None: # unseen until its turn+ mob.set_stroke(opacity=float(alpha >= 1))++ def finish_cycle(start: float) -> Callable[[StreamLine, float], None]:+ """The flow, on to the end of the line's cycle: its time at alpha (linear)."""++ def flow(line: StreamLine, alpha: float) -> None:+ line.time = start + alpha * (self.virtual_time - start)+ line.anim.interpolate(min(line.time / line.anim.run_time, 1))+ if alpha == 1:+ self.remove(line.anim.mobject)+ line.anim.finish()++ return flow++ max_run_time = self.virtual_time / self.flow_speed+ creation_rate_func = ease_out_sine+ creation_staring_speed = creation_rate_func(0.001) * 1000+ creation_run_time = (+ max_run_time / (1 + self.time_width) * creation_staring_speed+ )+ animations: list[Animation] = []+ self.remove_updater(self.flow_animation)+ self.flow_animation = None+ for line in self.stream_lines:+ create = Create(+ line, run_time=creation_run_time, rate_func=creation_rate_func+ )+ if line.time <= 0:+ animations.append(+ Succession(+ UpdateFromAlphaFunc(+ line, hide_and_wait, run_time=-line.time / self.flow_speed+ ),+ create,+ )+ )+ self.remove(line.anim.mobject)+ line.anim.finish()+ else:+ remaining_time = max_run_time - line.time / self.flow_speed+ animations.append(+ Succession(+ UpdateFromAlphaFunc(+ line,+ finish_cycle(line.time),+ run_time=remaining_time,+ rate_func=linear,+ ),+ create,+ )+ )+ return AnimationGroup(*animations)diff --git a/tests/unit/mobjects/test_vector_field.py b/tests/unit/mobjects/test_vector_field.pynew file mode 100644index 00000000..77a3ba30--- /dev/null+++ b/tests/unit/mobjects/test_vector_field.py@@ -0,0 +1,53 @@+"""A field's color queries follow its color: a uniform field answers with the color it is set+to. A stream line's colors run along it, from its start to its end."""++import numpy as np+import pytest++import manimgx as m+from manimgx.typing import Point3D+++def field(kind: str, color: m.ManimColor | None = None) -> m.VectorField:+ def function(point: Point3D) -> Point3D:+ return np.array([0.2, 0.3, 0.0])++ if kind == "plain":+ return m.VectorField(function, color=color, colors=[m.RED, m.BLUE])+ if kind == "arrows":+ return m.ArrowVectorField(+ function,+ color=color,+ colors=[m.RED, m.BLUE],+ x_range=[0, 0, 1],+ y_range=[0, 0, 1],+ )+ return m.StreamLines(+ function,+ color=color,+ colors=[m.RED, m.BLUE],+ x_range=[0, 0, 1],+ y_range=[0, 0, 1],+ noise_factor=0,+ virtual_time=0.2,+ )++[email protected]("kind", ["plain", "arrows", "lines"])+def test_uniform_field_color_queries_follow_its_current_color(kind: str) -> None:+ uniform = field(kind, m.RED)+ uniform.set_color(m.GREEN)+ np.testing.assert_array_equal(uniform.pos_to_rgb(np.zeros(3)), m.GREEN.to_rgb())+ assert uniform.pos_to_color(np.zeros(3)) == m.GREEN+++def test_a_stream_lines_colors_run_from_its_start_to_its_end() -> None:+ lines = m.StreamLines(+ lambda p: np.array([1.0, 0.5, 0]), x_range=[-2, 2, 1], y_range=[-2, 2, 1]+ )+ for line in lines.stream_lines: # straight: its ends are its box's corners+ np.testing.assert_allclose(+ line.get_gradient_start_and_end_points(),+ (line.get_start(), line.get_end()),+ atol=1e-9,+ )