Thursday, November 12, 2026

Mandelbrot video generator program

 To create a high-definition, progressively zooming Mandelbrot video on an RTX 3090 GPU, we can use CuPy, which compiles CUDA kernels on the fly.

To achieve the best visual quality, this script renders each frame at 8K resolution (7680x4320) and then down samples it to 4K (3840x2160). This technique, known as Super-Sample Anti-Aliasing (SSAA), removes jagged edges and creates incredibly crisp, cinematic fractal filaments. It also employs a continuous smooth-coloring algorithm to eliminate color banding as you zoom.

a)

Prerequisites

You will need the CUDA toolkit installed on your system, along with a few Python libraries:


Bash

pip install cupy-cuda12x numpy opencv-python


The Python Program


import cupy as cp

import numpy as np

import cv2

import time


# --- CONFIGURATION ---

# Target 4K Output, Rendered at 8K for Super-Sample Anti-Aliasing (SSAA)

WIDTH_8K, HEIGHT_8K = 7680, 4320

WIDTH_4K, HEIGHT_4K = 3840, 2160


# Video Settings

FPS = 60

TOTAL_FRAMES = 600  # 10 seconds at 60fps

ZOOM_FACTOR = 0.97  # Scale multiplier per frame (closer to 1.0 = slower zoom)


# Target coordinates (A visually interesting mini-mandelbrot in Seahorse Valley)

CENTER_X = -0.743643887037151

CENTER_Y = 0.131825904205330

INITIAL_SCALE = 3.0 / WIDTH_8K 


# --- CUDA KERNEL ---

# This calculates the Mandelbrot set with continuous smooth coloring

mandelbrot_kernel = cp.ElementwiseKernel(

    'float64 x, float64 y, int32 max_iter',

    'float32 smooth_iter',

    '''

    double c_real = x;

    double c_imag = y;

    double z_real = 0.0;

    double z_imag = 0.0;

    int i = 0;

    double r2 = 0.0, i2 = 0.0;

    

    // Using an escape radius of 256.0 for better smooth coloring

    for(; i < max_iter; ++i) {

        r2 = z_real * z_real;

        i2 = z_imag * z_imag;

        if(r2 + i2 > 256.0) break;

        z_imag = 2.0 * z_real * z_imag + c_imag;

        z_real = r2 - i2 + c_real;

    }

    

    if (i < max_iter) {

        // Continuous smooth iteration calculation

        double log_zn = log(r2 + i2) / 2.0;

        double nu = log(log_zn / 0.6931471805599453) / 0.6931471805599453; // ln(2)

        smooth_iter = (float)(i + 1 - nu);

    } else {

        smooth_iter = (float)max_iter;

    }

    ''',

    'smooth_mandelbrot'

)


def get_color_palette(iters, max_iter):

    """Applies a smooth sinusoidal color palette to the iteration counts."""

    # Mask out the inside of the set (which reaches max_iter)

    inside_mask = (iters >= max_iter)

    

    # Calculate colors using phase-shifted sine waves

    r = cp.sin(0.15 * iters + 0.0) * 127.5 + 127.5

    g = cp.sin(0.15 * iters + 2.094) * 127.5 + 127.5  # 2.094 is approx 2pi/3

    b = cp.sin(0.15 * iters + 4.188) * 127.5 + 127.5  # 4.188 is approx 4pi/3

    

    # Stack channels (OpenCV uses BGR by default)

    img = cp.stack((b, g, r), axis=-1).astype(cp.uint8)

    

    # Set the interior of the fractal to black

    img[inside_mask] = 0

    return img


def main():

    print(f"Starting 8K SSAA Render Pipeline on {cp.cuda.runtime.getDeviceProperties(0)['name'].decode()}")

    

    # Setup OpenCV Video Writer

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')

    out = cv2.VideoWriter('mandelbrot_4k_zoom.mp4', fourcc, FPS, (WIDTH_4K, HEIGHT_4K))

    

    current_scale = INITIAL_SCALE

    

    for frame in range(TOTAL_FRAMES):

        start_time = time.time()

        

        # Increase max iterations as we zoom deeper to preserve detail

        max_iter = int(250 + (-cp.log10(current_scale * WIDTH_8K).get()) * 150)

        

        # Calculate the real and imaginary boundaries

        x_min = CENTER_X - (WIDTH_8K / 2) * current_scale

        x_max = CENTER_X + (WIDTH_8K / 2) * current_scale

        y_min = CENTER_Y - (HEIGHT_8K / 2) * current_scale

        y_max = CENTER_Y + (HEIGHT_8K / 2) * current_scale

        

        # Generate the coordinate grid directly on the GPU

        x_coords = cp.linspace(x_min, x_max, WIDTH_8K, dtype=cp.float64)

        y_coords = cp.linspace(y_min, y_max, HEIGHT_8K, dtype=cp.float64)

        X, Y = cp.meshgrid(x_coords, y_coords)

        

        # Run the CUDA Mandelbrot kernel

        iters = mandelbrot_kernel(X, Y, max_iter)

        

        # Apply the color palette

        img_8k_gpu = get_color_palette(iters, max_iter)

        

        # Transfer the image from GPU to CPU RAM

        img_8k_cpu = cp.asnumpy(img_8k_gpu)

        

        # Downsample to 4K using Area Interpolation (Best for downscaling)

        img_4k = cv2.resize(img_8k_cpu, (WIDTH_4K, HEIGHT_4K), interpolation=cv2.INTER_AREA)

        

        # Write frame to video

        out.write(img_4k)

        

        current_scale *= ZOOM_FACTOR

        fps_current = 1.0 / (time.time() - start_time)

        

        if frame % 10 == 0:

            print(f"Frame {frame}/{TOTAL_FRAMES} | Max Iter: {max_iter} | Render Speed: {fps_current:.2f} fps")


    out.release()

    print("Video rendering complete! Saved as mandelbrot_4k_zoom.mp4")


if __name__ == "__main__":

    main()


How the Hardware Optimization Works

  • Memory Bandwidth: The RTX 3090's massive 24GB of GDDR6X VRAM is utilized heavily here. Standard processors would choke allocating grids for 33.1 million pixels (8K) per frame, but the 3090 handles cp.meshgrid without stuttering.

  • Elementwise Compiling: Rather than looping in Python, CuPy compiles the mandelbrot_kernel into C++ CUDA code behind the scenes and executes it simultaneously across all 10,496 CUDA cores on the RTX 3090.

  • Dynamic Iterations: As the current_scale gets smaller, the program calculates that you are zooming deeper and automatically steps up max_iter dynamically.

b)

To bypass the precision limits of standard 64-bit floating-point numbers (which begin breaking down and pixelating around a $10^{-14}$ scale), we use Perturbation Theory.
Instead of calculating the massive high-precision numbers for every single pixel, we calculate one single "reference orbit" at the exact center of our screen using an arbitrary-precision library (mpmath) on the CPU. Then, we use the RTX 3090's CUDA cores to calculate how much each surrounding pixel deviates from that reference orbit. Because the deviation (delta) is incredibly small, it easily fits inside standard hardware-accelerated 64-bit floats.
Prerequisites
You will need the mpmath library for arbitrary-precision CPU calculations alongside the previous requirements:

The Perturbation Python Program

import cupy as cp
import numpy as np
import cv2
import time
import mpmath

# --- CONFIGURATION ---
WIDTH_8K, HEIGHT_8K = 7680, 4320
WIDTH_4K, HEIGHT_4K = 3840, 2160
FPS = 60
TOTAL_FRAMES = 600

# We set a much more aggressive zoom factor to travel incredibly deep in 10 seconds
ZOOM_FACTOR = 0.85
INITIAL_SCALE = 4.0 / WIDTH_8K 
MAX_POSSIBLE_ITER = 5000  # Cap for the reference orbit pre-calculation

# 1. Setup Arbitrary Precision (100 decimal places allows zooming to ~10^-90)
mpmath.mp.dps = 100

# 2. Extremely Deep Target Coordinate
CENTER_X = mpmath.mpf("-1.749957683706093503602214506070699707271105797262520779302428378202860080829728048872186727844317008311005")
CENTER_Y = mpmath.mpf("0.000000000000000002787937065633794021782042378912524398563297050280644026364072225906323670977239016467362")

# --- PERTURBATION CUDA KERNEL ---
# We use a RawKernel because we need to pass and read from the reference orbit arrays.
perturbation_kernel = cp.RawKernel(r'''
extern "C" __global__
void mandelbrot_perturbation(
    const double* ref_r, 
    const double* ref_i,
    double scale, 
    int width, 
    int height, 
    int max_iter,
    float* smooth_iters) 
{
    int x = blockDim.x * blockIdx.x + threadIdx.x;
    int y = blockDim.y * blockIdx.y + threadIdx.y;
    
    if (x >= width || y >= height) return;
    
    // Delta C (How far this pixel is from the exact center)
    double dc_r = (x - width / 2.0) * scale;
    double dc_i = (y - height / 2.0) * scale;
    
    double dz_r = 0.0;
    double dz_i = 0.0;
    
    double r2 = 0.0;
    double i2 = 0.0;
    int i = 0;
    
    for (; i < max_iter; ++i) {
        // Fetch reference orbit position for this iteration
        double zr = ref_r[i];
        double zi = ref_i[i];
        
        // Perturbation Math: dZ_next = 2 * Z * dZ + dZ^2 + dC
        // 1. Calculate 2 * Z * dZ
        double zdz_r = zr * dz_r - zi * dz_i;
        double zdz_i = zr * dz_i + zi * dz_r;
        
        // 2. Calculate dZ^2
        double dz2_r = dz_r * dz_r - dz_i * dz_i;
        double dz2_i = 2.0 * dz_r * dz_i;
        
        // 3. Add them together with dC
        dz_r = 2.0 * zdz_r + dz2_r + dc_r;
        dz_i = 2.0 * zdz_i + dz2_i + dc_i;
        
        // True Z position = Reference Z + Delta Z
        double z_total_r = zr + dz_r;
        double z_total_i = zi + dz_i;
        
        r2 = z_total_r * z_total_r;
        i2 = z_total_i * z_total_i;
        
        // Standard escape radius check
        if (r2 + i2 > 256.0) {
            break;
        }
    }
    
    int idx = y * width + x;
    if (i < max_iter) {
        double log_zn = log(r2 + i2) / 2.0;
        double nu = log(log_zn / 0.6931471805599453) / 0.6931471805599453;
        smooth_iters[idx] = (float)(i + 1 - nu);
    } else {
        smooth_iters[idx] = (float)max_iter;
    }
}
''', 'mandelbrot_perturbation')

def compute_reference_orbit(max_iter):
    """Calculates the high-precision central orbit on the CPU once."""
    print("Pre-calculating arbitrary precision reference orbit...")
    z = mpmath.mpc(0, 0)
    c = mpmath.mpc(CENTER_X, CENTER_Y)
    
    # We store the reference orbit in standard float64. 
    # The magnitude of deviation is what matters for the GPU math.
    ref_r = np.zeros(max_iter, dtype=np.float64)
    ref_i = np.zeros(max_iter, dtype=np.float64)
    
    for i in range(max_iter):
        ref_r[i] = float(z.real)
        ref_i[i] = float(z.imag)
        z = z*z + c
        
    return cp.asarray(ref_r), cp.asarray(ref_i)

def get_color_palette(iters, max_iter):
    inside_mask = (iters >= max_iter)
    r = cp.sin(0.15 * iters + 0.0) * 127.5 + 127.5
    g = cp.sin(0.15 * iters + 2.094) * 127.5 + 127.5  
    b = cp.sin(0.15 * iters + 4.188) * 127.5 + 127.5  
    img = cp.stack((b, g, r), axis=-1).astype(cp.uint8)
    img[inside_mask] = 0
    return img

def main():
    # 1. Precompute Reference Orbit and load it onto the RTX 3090
    d_ref_r, d_ref_i = compute_reference_orbit(MAX_POSSIBLE_ITER)
    
    # Setup Video Writer
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter('mandelbrot_4k_perturbation.mp4', fourcc, FPS, (WIDTH_4K, HEIGHT_4K))
    
    current_scale = INITIAL_SCALE
    
    # Define CUDA Grid and Block Dimensions for 8K
    block_size = (16, 16)
    grid_size = (int(np.ceil(WIDTH_8K / 16)), int(np.ceil(HEIGHT_8K / 16)))
    
    # Pre-allocate output memory on the GPU to avoid re-allocating every frame
    d_smooth_iters = cp.zeros((HEIGHT_8K, WIDTH_8K), dtype=cp.float32)

    for frame in range(TOTAL_FRAMES):
        start_time = time.time()
        
        # Iterations must increase as we zoom to resolve new details
        # Using a logarithmic formula to scale up smoothly
        current_max_iter = min(MAX_POSSIBLE_ITER, int(500 + (-np.log10(current_scale)) * 100))
        
        # Execute the perturbation kernel
        perturbation_kernel(
            grid_size, block_size,
            (d_ref_r, d_ref_i, 
             np.float64(current_scale), 
             np.int32(WIDTH_8K), np.int32(HEIGHT_8K), 
             np.int32(current_max_iter), 
             d_smooth_iters)
        )
        
        # Color and Downsample (SSAA)
        img_8k_gpu = get_color_palette(d_smooth_iters, current_max_iter)
        img_8k_cpu = cp.asnumpy(img_8k_gpu)
        img_4k = cv2.resize(img_8k_cpu, (WIDTH_4K, HEIGHT_4K), interpolation=cv2.INTER_AREA)
        
        out.write(img_4k)
        
        current_scale *= ZOOM_FACTOR
        fps_current = 1.0 / (time.time() - start_time)
        
        if frame % 10 == 0:
            print(f"Frame {frame}/{TOTAL_FRAMES} | Scale: 10^{int(np.log10(current_scale))} | Iters: {current_max_iter} | {fps_current:.2f} fps")

    out.release()
    print("Video rendering complete! Saved as mandelbrot_4k_perturbation.mp4")

if __name__ == "__main__":
    main()


c)


How to add Bivariate Linear Approximation (BLA) or Series Approximation to this code to skip iterations and render even faster?




The BLA-Optimized Python Program

import cupy as cp
import numpy as np
import cv2
import time
import mpmath

# --- CONFIGURATION ---
WIDTH_8K, HEIGHT_8K = 7680, 4320
WIDTH_4K, HEIGHT_4K = 3840, 2160
FPS = 60
TOTAL_FRAMES = 600
ZOOM_FACTOR = 0.85
INITIAL_SCALE = 4.0 / WIDTH_8K 
MAX_POSSIBLE_ITER = 5000
SKIP_SIZE = 16  # Number of iterations BLA will jump at once

mpmath.mp.dps = 100
CENTER_X = mpmath.mpf("-1.749957683706093503602214506070699707271105797262520779302428378202860080829728048872186727844317008311005")
CENTER_Y = mpmath.mpf("0.000000000000000002787937065633794021782042378912524398563297050280644026364072225906323670977239016467362")

# --- BLA PERTURBATION CUDA KERNEL ---
bla_perturbation_kernel = cp.RawKernel(r'''
extern "C" __global__
void mandelbrot_bla(
    const double* ref_r, const double* ref_i,
    const double* A_r, const double* A_i,
    const double* B_r, const double* B_i,
    const double* R_valid,
    double scale, int width, int height, 
    int max_iter, int skip_size,
    float* smooth_iters) 
{
    int x = blockDim.x * blockIdx.x + threadIdx.x;
    int y = blockDim.y * blockIdx.y + threadIdx.y;
    
    if (x >= width || y >= height) return;
    
    double dc_r = (x - width / 2.0) * scale;
    double dc_i = (y - height / 2.0) * scale;
    
    double dz_r = 0.0, dz_i = 0.0;
    double r2 = 0.0, i2 = 0.0;
    int i = 0;
    
    while (i < max_iter) {
        double dz_mag2 = dz_r * dz_r + dz_i * dz_i;
        
        // 1. Check if we can safely use BLA to skip iterations
        if (i + skip_size < max_iter && dz_mag2 < R_valid[i]) {
            // Apply linear jump: dz_next = A * dz + B * dc
            double next_dz_r = A_r[i] * dz_r - A_i[i] * dz_i + B_r[i] * dc_r - B_i[i] * dc_i;
            double next_dz_i = A_r[i] * dz_i + A_i[i] * dz_r + B_r[i] * dc_i + B_i[i] * dc_r;
            
            dz_r = next_dz_r;
            dz_i = next_dz_i;
            i += skip_size;
        } 
        // 2. Fallback to standard Perturbation step
        else {
            double zr = ref_r[i];
            double zi = ref_i[i];
            
            double zdz_r = zr * dz_r - zi * dz_i;
            double zdz_i = zr * dz_i + zi * dz_r;
            
            double dz2_r = dz_r * dz_r - dz_i * dz_i;
            double dz2_i = 2.0 * dz_r * dz_i;
            
            dz_r = 2.0 * zdz_r + dz2_r + dc_r;
            dz_i = 2.0 * zdz_i + dz2_i + dc_i;
            i++;
        }
        
        double z_total_r = ref_r[i] + dz_r;
        double z_total_i = ref_i[i] + dz_i;
        
        r2 = z_total_r * z_total_r;
        i2 = z_total_i * z_total_i;
        
        if (r2 + i2 > 256.0) {
            break;
        }
    }
    
    int idx = y * width + x;
    if (i < max_iter) {
        double log_zn = log(r2 + i2) / 2.0;
        double nu = log(log_zn / 0.6931471805599453) / 0.6931471805599453;
        smooth_iters[idx] = (float)(i + 1 - nu);
    } else {
        smooth_iters[idx] = (float)max_iter;
    }
}
''', 'mandelbrot_bla')

def compute_reference_and_bla(max_iter, skip_size):
    """Calculates reference orbit and pre-computes BLA coefficients A and B."""
    print("Pre-calculating reference orbit and BLA tables...")
    z = mpmath.mpc(0, 0)
    c = mpmath.mpc(CENTER_X, CENTER_Y)
    
    ref_r = np.zeros(max_iter + skip_size, dtype=np.float64)
    ref_i = np.zeros(max_iter + skip_size, dtype=np.float64)
    
    # Store standard reference orbit
    for i in range(max_iter + skip_size):
        ref_r[i] = float(z.real)
        ref_i[i] = float(z.imag)
        z = z*z + c
        
    # Pre-calculate BLA arrays for jumping `skip_size` steps
    A_r = np.zeros(max_iter, dtype=np.float64)
    A_i = np.zeros(max_iter, dtype=np.float64)
    B_r = np.zeros(max_iter, dtype=np.float64)
    B_i = np.zeros(max_iter, dtype=np.float64)
    R_valid = np.zeros(max_iter, dtype=np.float64)
    
    for i in range(max_iter):
        curr_A = complex(1.0, 0.0)
        curr_B = complex(0.0, 0.0)
        
        # Unroll linear series for skip_size cycles starting from index i
        for s in range(skip_size):
            Z = complex(ref_r[i + s], ref_i[i + s])
            curr_B = 2.0 * Z * curr_B + 1.0
            curr_A = 2.0 * Z * curr_A
            
        A_r[i] = curr_A.real
        A_i[i] = curr_A.imag
        B_r[i] = curr_B.real
        B_i[i] = curr_B.imag
        
        # Calculate validity threshold (R) where the omitted dz^2 term becomes significant.
        # A conservative bound keeping error below a tiny threshold.
        mag_A = abs(curr_A)
        R_valid[i] = (1e-5 / (mag_A + 1e-12)) ** 2

    return (cp.asarray(ref_r), cp.asarray(ref_i), 
            cp.asarray(A_r), cp.asarray(A_i), 
            cp.asarray(B_r), cp.asarray(B_i), 
            cp.asarray(R_valid))

def get_color_palette(iters, max_iter):
    inside_mask = (iters >= max_iter)
    r = cp.sin(0.15 * iters + 0.0) * 127.5 + 127.5
    g = cp.sin(0.15 * iters + 2.094) * 127.5 + 127.5  
    b = cp.sin(0.15 * iters + 4.188) * 127.5 + 127.5  
    img = cp.stack((b, g, r), axis=-1).astype(cp.uint8)
    img[inside_mask] = 0
    return img

def main():
    # Precompute Reference Orbit and BLA tables
    d_ref_r, d_ref_i, d_A_r, d_A_i, d_B_r, d_B_i, d_R_valid = compute_reference_and_bla(MAX_POSSIBLE_ITER, SKIP_SIZE)
    
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter('mandelbrot_4k_bla.mp4', fourcc, FPS, (WIDTH_4K, HEIGHT_4K))
    
    current_scale = INITIAL_SCALE
    block_size = (16, 16)
    grid_size = (int(np.ceil(WIDTH_8K / 16)), int(np.ceil(HEIGHT_8K / 16)))
    
    d_smooth_iters = cp.zeros((HEIGHT_8K, WIDTH_8K), dtype=cp.float32)

    for frame in range(TOTAL_FRAMES):
        start_time = time.time()
        current_max_iter = min(MAX_POSSIBLE_ITER, int(500 + (-np.log10(current_scale)) * 100))
        
        bla_perturbation_kernel(
            grid_size, block_size,
            (d_ref_r, d_ref_i, 
             d_A_r, d_A_i, d_B_r, d_B_i, d_R_valid,
             np.float64(current_scale), 
             np.int32(WIDTH_8K), np.int32(HEIGHT_8K), 
             np.int32(current_max_iter), np.int32(SKIP_SIZE),
             d_smooth_iters)
        )
        
        img_8k_gpu = get_color_palette(d_smooth_iters, current_max_iter)
        img_8k_cpu = cp.asnumpy(img_8k_gpu)
        img_4k = cv2.resize(img_8k_cpu, (WIDTH_4K, HEIGHT_4K), interpolation=cv2.INTER_AREA)
        
        out.write(img_4k)
        
        current_scale *= ZOOM_FACTOR
        fps_current = 1.0 / (time.time() - start_time)
        
        if frame % 10 == 0:
            print(f"Frame {frame}/{TOTAL_FRAMES} | Scale: 10^{int(np.log10(current_scale))} | Iters: {current_max_iter} | {fps_current:.2f} fps")

    out.release()
    print("Video rendering complete! Saved as mandelbrot_4k_bla.mp4")

if __name__ == "__main__":
    main()



d)

How to add a multi-reference quadtree re-basing system to stop the BLA engine from glitching when zooming past 10^-100





2) Multi-Reference Python Implementation

Here is the upgraded framework. It encapsulates the references into a manager and updates the CuPy kernel to support dynamically switching reference centers.


import cupy as cp

import numpy as np

import cv2

import time

import mpmath


# --- CONFIGURATION ---

WIDTH_8K, HEIGHT_8K = 7680, 4320

WIDTH_4K, HEIGHT_4K = 3840, 2160

FPS = 60

TOTAL_FRAMES = 600

ZOOM_FACTOR = 0.85

INITIAL_SCALE = 4.0 / WIDTH_8K 

MAX_ITER = 5000

SKIP_SIZE = 16

MAX_REFS = 16  # Maximum number of reference orbits to hold in VRAM


mpmath.mp.dps = 120

CENTER_X = mpmath.mpf("-1.749957683706093503602214506070699707271105797262520779302428378202860080829728048872186727844317008311005")

CENTER_Y = mpmath.mpf("0.000000000000000002787937065633794021782042378912524398563297050280644026364072225906323670977239016467362")


# --- MULTI-REFERENCE CUDA KERNEL ---

multi_ref_kernel = cp.RawKernel(r'''

extern "C" __global__

void mandelbrot_multi_ref(

    const double* Ref_r, const double* Ref_i,

    const double* A_r, const double* A_i,

    const double* B_r, const double* B_i,

    const double* R_valid,

    const double* Ref_dc_r, const double* Ref_dc_i,

    int num_refs, double scale, int width, int height, 

    int max_iter, int skip_size,

    float* smooth_iters, unsigned char* glitch_mask) 

{

    int x = blockDim.x * blockIdx.x + threadIdx.x;

    int y = blockDim.y * blockIdx.y + threadIdx.y;

    

    if (x >= width || y >= height) return;

    

    // Pixel's delta relative to the absolute center (Reference 0)

    double absolute_dc_r = (x - width / 2.0) * scale;

    double absolute_dc_i = (y - height / 2.0) * scale;

    

    // Find the closest valid reference orbit

    int best_ref = 0;

    double min_dist = 1e300;

    for (int k = 0; k < num_refs; k++) {

        double dx = absolute_dc_r - Ref_dc_r[k];

        double dy = absolute_dc_i - Ref_dc_i[k];

        double dist = dx*dx + dy*dy;

        if (dist < min_dist) {

            min_dist = dist;

            best_ref = k;

        }

    }

    

    // Calculate delta relative to the chosen auxiliary reference

    double dc_r = absolute_dc_r - Ref_dc_r[best_ref];

    double dc_i = absolute_dc_i - Ref_dc_i[best_ref];

    

    // Offset array pointers to the chosen reference's tables

    int offset = best_ref * max_iter;

    

    double dz_r = 0.0, dz_i = 0.0;

    double r2 = 0.0, i2 = 0.0;

    int i = 0;

    bool glitched = false;

    

    while (i < max_iter) {

        double dz_mag2 = dz_r * dz_r + dz_i * dz_i;

        

        // BLA Jump

        if (i + skip_size < max_iter && dz_mag2 < R_valid[offset + i]) {

            double next_dz_r = A_r[offset + i] * dz_r - A_i[offset + i] * dz_i + B_r[offset + i] * dc_r - B_i[offset + i] * dc_i;

            double next_dz_i = A_r[offset + i] * dz_i + A_i[offset + i] * dz_r + B_r[offset + i] * dc_i + B_i[offset + i] * dc_r;

            dz_r = next_dz_r;

            dz_i = next_dz_i;

            i += skip_size;

        } 

        // Standard Perturbation Step

        else {

            double zr = Ref_r[offset + i];

            double zi = Ref_i[offset + i];

            

            double zdz_r = zr * dz_r - zi * dz_i;

            double zdz_i = zr * dz_i + zi * dz_r;

            

            dz_r = 2.0 * zdz_r + (dz_r * dz_r - dz_i * dz_i) + dc_r;

            dz_i = 2.0 * zdz_i + (2.0 * dz_r * dz_i) + dc_i;

            i++;

        }

        

        double z_total_r = Ref_r[offset + i] + dz_r;

        double z_total_i = Ref_i[offset + i] + dz_i;

        

        r2 = z_total_r * z_total_r;

        i2 = z_total_i * z_total_i;

        

        if (r2 + i2 > 256.0) break;

        

        // Glitch Detection: Delta magnitude vs Reference magnitude

        if (dz_mag2 > 0.5 * (r2 + i2) && (r2 + i2) < 0.1) {

            glitched = true;

            break;

        }

    }

    

    int idx = y * width + x;

    glitch_mask[idx] = glitched ? 1 : 0;

    

    if (!glitched && i < max_iter) {

        double log_zn = log(r2 + i2) / 2.0;

        double nu = log(log_zn / 0.6931471805599453) / 0.6931471805599453;

        smooth_iters[idx] = (float)(i + 1 - nu);

    } else {

        smooth_iters[idx] = (float)max_iter; // Keep glitch regions dark or mark for rebasing

    }

}

''', 'mandelbrot_multi_ref')


class ReferenceManager:

    def __init__(self, c_base, max_iter, skip_size):

        self.c_base = c_base

        self.max_iter = max_iter

        self.skip_size = skip_size

        

        # Flattened buffers for GPU

        self.ref_r = np.zeros(MAX_REFS * max_iter, dtype=np.float64)

        self.ref_i = np.zeros(MAX_REFS * max_iter, dtype=np.float64)

        self.A_r = np.zeros(MAX_REFS * max_iter, dtype=np.float64)

        self.A_i = np.zeros(MAX_REFS * max_iter, dtype=np.float64)

        self.B_r = np.zeros(MAX_REFS * max_iter, dtype=np.float64)

        self.B_i = np.zeros(MAX_REFS * max_iter, dtype=np.float64)

        self.R_valid = np.zeros(MAX_REFS * max_iter, dtype=np.float64)

        

        # Track offsets relative to the main center (float64 is fine for deltas)

        self.ref_dc_r = np.zeros(MAX_REFS, dtype=np.float64)

        self.ref_dc_i = np.zeros(MAX_REFS, dtype=np.float64)

        self.active_refs = 0

        

        # Create primary reference (Index 0)

        self.add_reference(mpmath.mpc(0, 0), 0.0, 0.0)


    def add_reference(self, offset_c_high, dc_r_float, dc_i_float):

        if self.active_refs >= MAX_REFS: return False

        

        idx = self.active_refs

        offset = idx * self.max_iter

        c_val = self.c_base + offset_c_high

        z = mpmath.mpc(0, 0)

        

        print(f"Spawning Reference {idx} at delta ({dc_r_float:.2e}, {dc_i_float:.2e})")

        

        # Calculate Orbit and BLA Tables for this new center

        temp_r = np.zeros(self.max_iter + self.skip_size, dtype=np.float64)

        temp_i = np.zeros(self.max_iter + self.skip_size, dtype=np.float64)

        for i in range(self.max_iter + self.skip_size):

            temp_r[i] = float(z.real)

            temp_i[i] = float(z.imag)

            z = z*z + c_val

            

        for i in range(self.max_iter):

            curr_A = complex(1.0, 0.0)

            curr_B = complex(0.0, 0.0)

            for s in range(self.skip_size):

                Z = complex(temp_r[i + s], temp_i[i + s])

                curr_B = 2.0 * Z * curr_B + 1.0

                curr_A = 2.0 * Z * curr_A

            

            self.ref_r[offset + i] = temp_r[i]

            self.ref_i[offset + i] = temp_i[i]

            self.A_r[offset + i] = curr_A.real

            self.A_i[offset + i] = curr_A.imag

            self.B_r[offset + i] = curr_B.real

            self.B_i[offset + i] = curr_B.imag

            self.R_valid[offset + i] = (1e-5 / (abs(curr_A) + 1e-12)) ** 2

            

        self.ref_dc_r[idx] = dc_r_float

        self.ref_dc_i[idx] = dc_i_float

        self.active_refs += 1

        return True


    def to_gpu(self):

        return (cp.asarray(self.ref_r), cp.asarray(self.ref_i), 

                cp.asarray(self.A_r), cp.asarray(self.A_i), 

                cp.asarray(self.B_r), cp.asarray(self.B_i), 

                cp.asarray(self.R_valid), 

                cp.asarray(self.ref_dc_r), cp.asarray(self.ref_dc_i))



3. Rendering Pipeline with Probing

In your main() render loop, run a small probe frame first. If glitches are flagged, calculate the centroid of the glitched mask, convert that position into high-precision mpmath coordinates relative to your root center, and feed it into add_reference().

Python

# (Inside main render loop)

# 1. Run low-res probe pass (e.g., 480x270)
d_probe_iters = cp.zeros((270, 480), dtype=cp.float32)
d_probe_glitch = cp.zeros((270, 480), dtype=cp.uint8)

multi_ref_kernel(
    probe_grid, probe_block,
    (*ref_mgr.to_gpu(),
     ref_mgr.active_refs, np.float64(probe_scale), 
     480, 270, current_max_iter, SKIP_SIZE,
     d_probe_iters, d_probe_glitch)
)

# 2. Check for glitches
if cp.sum(d_probe_glitch) > 50:  # Arbitrary threshold
    glitch_y, glitch_x = cp.where(d_probe_glitch == 1)
    center_y = float(cp.mean(glitch_y)) - 135.0
    center_x = float(cp.mean(glitch_x)) - 240.0
    
    # Calculate offset in exact math
    exact_dc_r = mpmath.mpf(center_x) * mpmath.mpf(probe_scale)
    exact_dc_i = mpmath.mpf(center_y) * mpmath.mpf(probe_scale)
    
    # Add new reference orbit covering this region
    ref_mgr.add_reference(mpmath.mpc(exact_dc_r, exact_dc_i), float(exact_dc_r), float(exact_dc_i))

# 3. Proceed to render full 8K frame using the updated reference pool
# ...


How to prune auxiliary references once they move off-screen to free up VRAM for new ones as I zoom deeper.

To prune auxiliary references, you need to calculate the physical boundaries of the current frame in the complex plane at the end of each zoom step. If an auxiliary reference's offset (dc_r, dc_i) falls completely outside these boundaries (plus a small safety margin), it is no longer useful for the current frame and can be overwritten.

Because the data is stored in flattened arrays to optimize GPU memory access, the most efficient way to delete a reference is to iterate through the list backwards. When you find an off-screen reference, overwrite its data block with the data from the last active reference in the array, and then decrement the active_refs counter.

1. The Pruning Method
Add this method directly inside your ReferenceManager class:

def prune_offscreen_references(self, current_scale, width, height):
        """
        Removes auxiliary references that have fallen outside the viewport.
        Index 0 (the absolute root base) is never pruned to maintain coordinate stability.
        """
        # Calculate the maximum visible coordinate distance from the center.
        # We multiply by 1.5 to create a 50% safety buffer, keeping references 
        # that are just off-screen but whose validity radius still covers visible pixels.
        max_dist_x = (width / 2.0) * current_scale * 1.5
        max_dist_y = (height / 2.0) * current_scale * 1.5
        
        pruned_count = 0
        
        # Iterate backwards to safely swap-and-pop without misaligning indices
        for i in range(self.active_refs - 1, 0, -1):
            if abs(self.ref_dc_r[i]) > max_dist_x or abs(self.ref_dc_i[i]) > max_dist_y:
                print(f"  -> Pruning Reference {i} (moved off-screen)")
                
                last_idx = self.active_refs - 1
                
                # If this isn't the very last item, swap the last item's data into this slot
                if i != last_idx:
                    dest_start = i * self.max_iter
                    dest_end = dest_start + self.max_iter
                    src_start = last_idx * self.max_iter
                    src_end = src_start + self.max_iter
                    
                    # Overwrite flattened GPU buffer data
                    self.ref_r[dest_start:dest_end] = self.ref_r[src_start:src_end]
                    self.ref_i[dest_start:dest_end] = self.ref_i[src_start:src_end]
                    self.A_r[dest_start:dest_end] = self.A_r[src_start:src_end]
                    self.A_i[dest_start:dest_end] = self.A_i[src_start:src_end]
                    self.B_r[dest_start:dest_end] = self.B_r[src_start:src_end]
                    self.B_i[dest_start:dest_end] = self.B_i[src_start:src_end]
                    self.R_valid[dest_start:dest_end] = self.R_valid[src_start:src_end]
                    
                    # Overwrite offsets
                    self.ref_dc_r[i] = self.ref_dc_r[last_idx]
                    self.ref_dc_i[i] = self.ref_dc_i[last_idx]
                
                self.active_refs -= 1
                pruned_count += 1
                
        if pruned_count > 0:
            print(f"  -> Freed {pruned_count} reference slots. Active references: {self.active_refs}/{MAX_REFS}")


2. Updating the Main Render Loop
Call the pruning method at the end of the frame processing loop, just after you multiply current_scale by the ZOOM_FACTOR.

How to completely re-center the root reference orbit (Index 0) when the zoom scale drops past the precision limits of standard float64 deltas


When you create a cinematic fractal video, the camera doesn't just zoom straight in—it pans across the complex plane following a curved spline through waypoints.

As you pan, the screen center drifts away from your root c_base. Eventually, the offset distance (e.g., $10^{-3}) becomes so much larger than the width of your viewport (e.g., $10^{-20}) that adding the tiny pixel coordinates to the camera offset causes standard 64-bit floats to truncate the tiny digits. This is known as loss of significance, and it immediately pixelates the frame.

To fix this, you must periodically move the arbitrary-precision root coordinate to match the exact center of your camera, and mathematically shift all active auxiliary references backwards to compensate.

1. The Root Re-basing Method

Add this method to your Reference Manager class. It safely uproots Index 0 and adjusts the dc (delta C) of all other active references so the GPU kernel doesn't notice the shift.



def rebase_root(self, exact_new_center):
        """
        Moves the arbitrary-precision root reference (Index 0) to a new center 
        and shifts all existing auxiliary references relative to this new root.
        """
        # 1. Calculate the exact shift vector using mpmath
        shift = exact_new_center - self.c_base
        shift_r_float = float(shift.real)
        shift_i_float = float(shift.imag)
        
        print(f"\n[REBASE] Moving Root Orbit. Shift vector: ({shift_r_float:.2e}, {shift_i_float:.2e})")
        
        # 2. Update the arbitrary-precision base coordinate
        self.c_base = exact_new_center
        
        # 3. Shift all auxiliary references backward by the shift amount.
        # (We start at k=1 because Index 0 is the root and will be reset to 0.0)
        for k in range(1, self.active_refs):
            self.ref_dc_r[k] -= shift_r_float
            self.ref_dc_i[k] -= shift_i_float
            
        # 4. Reset Index 0 offsets
        self.ref_dc_r[0] = 0.0
        self.ref_dc_i[0] = 0.0
        
        # 5. Recalculate Index 0 Orbit and BLA tables at the new exact center
        z = mpmath.mpc(0, 0)
        temp_r = np.zeros(self.max_iter + self.skip_size, dtype=np.float64)
        temp_i = np.zeros(self.max_iter + self.skip_size, dtype=np.float64)
        
        for i in range(self.max_iter + self.skip_size):
            temp_r[i] = float(z.real)
            temp_i[i] = float(z.imag)
            z = z*z + self.c_base
            
        for i in range(self.max_iter):
            curr_A = complex(1.0, 0.0)
            curr_B = complex(0.0, 0.0)
            for s in range(self.skip_size):
                Z = complex(temp_r[i + s], temp_i[i + s])
                curr_B = 2.0 * Z * curr_B + 1.0
                curr_A = 2.0 * Z * curr_A
            
            self.ref_r[i] = temp_r[i]
            self.ref_i[i] = temp_i[i]
            self.A_r[i] = curr_A.real
            self.A_i[i] = curr_A.imag
            self.B_r[i] = curr_B.real
            self.B_i[i] = curr_B.imag
            self.R_valid[i] = (1e-5 / (abs(curr_A) + 1e-12)) ** 2


2. Triggering the Re-base in the Main Loop
In a real production script, your camera center is likely being interpolated between waypoints using an mpmath spline function. You should trigger a re-base whenever the distance from the root to the camera center becomes large relative to the current viewport scale.

Python

# ... (Inside the frame rendering loop) ...
        
        # Example: calculating the exact camera coordinate for this specific frame
        # exact_camera_center = calculate_spline_position(frame)
        
        # Calculate how far the camera has drifted from the root in float64
        camera_offset_exact = exact_camera_center - ref_mgr.c_base
        dist_from_root = float(abs(camera_offset_exact))
        
        # The Threshold: If the distance is > 10,000 times the viewport width,
        # standard 64-bit floats risk losing precision on the pixel math.
        viewport_width_float = float(WIDTH_8K * current_scale)
        
        if dist_from_root > 10000.0 * viewport_width_float:
            ref_mgr.rebase_root(exact_camera_center)
            
            # Since we changed the root, we must prune references that are now too far away
            ref_mgr.prune_offscreen_references(current_scale, WIDTH_8K, HEIGHT_8K)
            
        # ... (Proceed with running the multi-ref kernel) ...



How to write an arbitrary-precision spline interpolator to smoothly pan the camera between waypoints while zooming?

To smoothly pan the camera while zooming, you cannot use standard linear interpolation. Linear panning creates jarring, robotic direction changes at every waypoint, and linear zooming feels like the camera is abruptly decelerating as it gets deeper.

A professional deep zoom engine uses two separate interpolation curves:

  1. Exponential Interpolation for Zoom: The scale must multiply by a constant fraction over time so the perceived speed of diving into the fractal remains constant.

  2. Catmull-Rom Splines for Panning: This generates a smooth, curved path through arbitrary-precision coordinates in the complex plane, ensuring the camera's velocity and direction never instantly snap.

Arbitrary-Precision Spline Interpolator

This implementation uses mpmath to calculate a Catmull-Rom spline. It requires 4 control points to calculate the curve between the middle two, ensuring smooth entry and exit vectors.


import mpmath


class Keyframe:

    def __init__(self, frame: int, center_c: mpmath.mpc, scale: mpmath.mpf):

        self.frame = frame

        self.center = center_c

        self.scale = scale


class CameraAnimator:

    def __init__(self, keyframes):

        """

        keyframes: A list of Keyframe objects sorted by frame number.

        Must have at least 4 keyframes for a proper Catmull-Rom spline.

        """

        self.keyframes = sorted(keyframes, key=lambda k: k.frame)

        

    def get_state(self, current_frame: int):

        # 1. Handle edge cases (before first frame or after last frame)

        if current_frame <= self.keyframes[0].frame:

            return self.keyframes[0].center, self.keyframes[0].scale

        if current_frame >= self.keyframes[-1].frame:

            return self.keyframes[-1].center, self.keyframes[-1].scale

            

        # 2. Find the relevant keyframe segment

        idx = 0

        for i in range(len(self.keyframes) - 1):

            if self.keyframes[i].frame <= current_frame < self.keyframes[i+1].frame:

                idx = i

                break

                

        # 3. Get the 4 control points for the Catmull-Rom spline

        # If we are at the boundaries, we duplicate the end points to flatten the curve

        p0 = self.keyframes[max(0, idx - 1)]

        p1 = self.keyframes[idx]

        p2 = self.keyframes[idx + 1]

        p3 = self.keyframes[min(len(self.keyframes) - 1, idx + 2)]

        

        # 4. Calculate normalized time 't' (0.0 to 1.0) between p1 and p2

        frame_range = p2.frame - p1.frame

        t = mpmath.mpf(current_frame - p1.frame) / mpmath.mpf(frame_range)

        

        # 5. Exponential Interpolation for Scale

        # S(t) = S1 * (S2 / S1)^t

        scale = p1.scale * mpmath.power(p2.scale / p1.scale, t)

        

        # 6. Catmull-Rom Spline Interpolation for Position (Arbitrary Precision)

        # P(t) = 0.5 * ( (2*P1) + (-P0 + P2)*t + (2*P0 - 5*P1 + 4*P2 - P3)*t^2 + (-P0 + 3*P1 - 3*P2 + P3)*t^3 )

        t2 = t * t

        t3 = t2 * t

        

        c0 = p0.center

        c1 = p1.center

        c2 = p2.center

        c3 = p3.center

        

        term1 = 2.0 * c1

        term2 = (-c0 + c2) * t

        term3 = (2.0*c0 - 5.0*c1 + 4.0*c2 - c3) * t2

        term4 = (-c0 + 3.0*c1 - 3.0*c2 + c3) * t3

        

        center = 0.5 * (term1 + term2 + term3 + term4)

        

        return center, scale


Integrating the Animator into the Main Loop

To use this, define your cinematic path using exact mpmath coordinates and frame numbers before starting the render loop. Then, query the animator for the exact camera position on each frame.


# 1. Define your arbitrary-precision waypoints

mpmath.mp.dps = 120


waypoints = [

    Keyframe(0,    mpmath.mpc("-0.5", "0.0"), mpmath.mpf("3.0")),                      # Zoomed out

    Keyframe(300,  mpmath.mpc("-0.7436", "0.1318"), mpmath.mpf("0.05")),               # Seahorse valley

    Keyframe(900,  mpmath.mpc("-0.74364388", "0.13182590"), mpmath.mpf("1e-6")),       # Deeper

    Keyframe(1800, mpmath.mpc(CENTER_X, CENTER_Y), mpmath.mpf("1e-25")),               # Target deep dive

    Keyframe(2400, mpmath.mpc(CENTER_X, CENTER_Y), mpmath.mpf("1e-45"))                # Final hold/zoom

]


animator = CameraAnimator(waypoints)


# 2. Main Render Loop

for frame in range(TOTAL_FRAMES):

    start_time = time.time()

    

    # Get exact camera state for this specific frame

    exact_camera_center, current_scale = animator.get_state(frame)

    

    # Calculate drift from root for re-basing (from previous multi-reference logic)

    camera_offset_exact = exact_camera_center - ref_mgr.c_base

    dist_from_root = float(abs(camera_offset_exact))

    

    if dist_from_root > 10000.0 * float(WIDTH_8K * current_scale):

        ref_mgr.rebase_root(exact_camera_center)

        ref_mgr.prune_offscreen_references(current_scale, WIDTH_8K, HEIGHT_8K)

        # Recalculate offset after rebasing (should now be 0.0)

        camera_offset_exact = exact_camera_center - ref_mgr.c_base

    

    # 3. Update Kernel with the exact floating point offsets relative to root

    dc_r_float = float(camera_offset_exact.real)

    dc_i_float = float(camera_offset_exact.imag)

    

    # (Execute multi-ref kernel using dc_r_float and dc_i_float as the camera position)


Watching how these smooth curves look in motion will help you tune the timing between your keyframes so the camera glides naturally into the spirals


How to implement temporal accumulation to add cinematic motion blur to the 8K fractal frames.


To create realistic, cinematic motion blur, you must simulate how a physical camera sensor captures light over time. Instead of rendering a single instant in time for each video frame, you render multiple sub-frames across the duration the "shutter" is open, and mathematically average their RGB values together.

This process, known as Temporal Accumulation, completely eliminates the "strobe effect" during fast camera pans or aggressive zooms, resulting in buttery smooth motion.

The Mathematics of Shutter Angles

In cinema, motion blur is controlled by the Shutter Angle.

  • A 360-degree shutter is open for the entire duration of a frame (maximum blur).

  • A 180-degree shutter (the Hollywood standard) is open for half the frame's duration (e.g., at 60 FPS, the shutter is open for $1/120^{\text{th}}$ of a second).

  • A 90-degree shutter is open for a quarter of the frame (sharp, staccato action, like in Saving Private Ryan).

To implement this, you slice the shutter-open duration into $N$ temporal samples. The RTX 3090's massive 24GB VRAM makes this highly efficient, as you can hold a 32-bit floating-point accumulation buffer for the entire 8K canvas directly on the GPU without swapping memory.

Upgrading the Main Render Loop

Replace your main() render loop with this temporal accumulation setup. It heavily utilizes the Camera Animator from the previous step to fetch fractional, sub-frame coordinates.


# --- CINEMATIC MOTION BLUR SETTINGS ---

SUB_SAMPLES = 8          # Number of sub-frames to render per final frame (higher = smoother but slower)

SHUTTER_ANGLE = 180.0    # 180 is cinematic standard. 360 is maximum blur.


def main():

    # Precompute Reference Orbit and BLA tables

    d_ref_r, d_ref_i, d_A_r, d_A_i, d_B_r, d_B_i, d_R_valid = compute_reference_and_bla(MAX_POSSIBLE_ITER, SKIP_SIZE)

    

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')

    out = cv2.VideoWriter('mandelbrot_4k_cinematic.mp4', fourcc, FPS, (WIDTH_4K, HEIGHT_4K))

    

    block_size = (16, 16)

    grid_size = (int(np.ceil(WIDTH_8K / 16)), int(np.ceil(HEIGHT_8K / 16)))

    

    # 1. Allocate GPU Buffers

    d_smooth_iters = cp.zeros((HEIGHT_8K, WIDTH_8K), dtype=cp.float32)

    

    # 32-bit float accumulation buffer is REQUIRED. 

    # Adding 8 sub-frames of 8-bit RGB values will immediately overflow 255.

    d_accum_buffer = cp.zeros((HEIGHT_8K, WIDTH_8K, 3), dtype=cp.float32)

    

    # Calculate what fraction of the frame time the shutter is open

    shutter_fraction = SHUTTER_ANGLE / 360.0


    for frame in range(TOTAL_FRAMES):

        start_time = time.time()

        

        # Clear the accumulation buffer for the new frame

        d_accum_buffer.fill(0.0)

        

        # Determine base iterations for this frame depth

        _, base_scale = animator.get_state(frame)

        current_max_iter = min(MAX_POSSIBLE_ITER, int(500 + (-np.log10(float(base_scale))) * 100))

        

        # --- TEMPORAL ACCUMULATION LOOP ---

        for sub in range(SUB_SAMPLES):

            # Calculate exact fractional time for this sub-frame

            # E.g., for frame 10 and 180-deg shutter, time goes from 10.0 to 10.5

            temporal_offset = (sub / max(1, SUB_SAMPLES - 1)) * shutter_fraction

            exact_time = frame + temporal_offset

            

            # Query the Spline Animator for the precise sub-frame camera state

            exact_camera_center, current_scale = animator.get_state(exact_time)

            

            # Rebase check (Standard multi-reference logic)

            camera_offset_exact = exact_camera_center - ref_mgr.c_base

            dist_from_root = float(abs(camera_offset_exact))

            if dist_from_root > 10000.0 * float(WIDTH_8K * current_scale):

                ref_mgr.rebase_root(exact_camera_center)

                ref_mgr.prune_offscreen_references(current_scale, WIDTH_8K, HEIGHT_8K)

                camera_offset_exact = exact_camera_center - ref_mgr.c_base

            

            dc_r_float = float(camera_offset_exact.real)

            dc_i_float = float(camera_offset_exact.imag)

            

            # Execute BLA Perturbation Kernel for this sub-frame

            multi_ref_kernel(

                grid_size, block_size,

                (*ref_mgr.to_gpu(),

                 ref_mgr.active_refs, np.float64(current_scale), 

                 WIDTH_8K, HEIGHT_8K, current_max_iter, SKIP_SIZE,

                 dc_r_float, dc_i_float,

                 d_smooth_iters)

            )

            

            # Generate uint8 RGB image for the sub-frame, cast to float32, and add to accumulator

            img_8k_gpu = get_color_palette(d_smooth_iters, current_max_iter)

            d_accum_buffer += img_8k_gpu.astype(cp.float32)

            

        # --- FINALIZE FRAME ---

        # 1. Average the sub-frames

        d_accum_buffer /= SUB_SAMPLES

        

        # 2. Cast back to 8-bit RGB and transfer to CPU

        final_img_8k_cpu = cp.asnumpy(d_accum_buffer.astype(cp.uint8))

        

        # 3. Apply SSAA Downscale to 4K

        final_4k_cpu = cv2.resize(final_img_8k_cpu, (WIDTH_4K, HEIGHT_4K), interpolation=cv2.INTER_AREA)

        

        # Write to video file

        out.write(final_4k_cpu)

        

        fps_current = 1.0 / (time.time() - start_time)

        if frame % 10 == 0:

            print(f"Frame {frame}/{TOTAL_FRAMES} | Sub-frames: {SUB_SAMPLES} | {fps_current:.2f} final fps")


    out.release()

    print("Video rendering complete! Saved as mandelbrot_4k_cinematic.mp4")


Performance Considerations

Rendering 8 sub-frames means the GPU is doing exactly 8 times the mathematical workload per final frame. However, by accumulating purely in VRAM (d_accum_buffer += img_8k_gpu), you avoid the catastrophic PCIe bottleneck that would occur if you tried to transfer all 8 sub-frames to the CPU to average them in numpy.

The video below demonstrates how motion blur combined with deep zooming creates a tangible sense of speed and scale that raw, sharp frames lack.


How to add a GPU-accelerated post-processing bloom and glow effect to the fractal filaments before exporting


To add a cinematic bloom (glow) effect, you extract the brightest pixels in your image, blur them to simulate light scattering across a camera lens, and add them back to the original frame.

Since your pipeline is already operating on the RTX 3090 via CuPy, doing this entirely in VRAM on the accumulated float32 buffer ensures it takes only milliseconds per frame without any PCIe transfer bottlenecks.

The CuPy Bloom Implementation

You will need to import CuPy's GPU-accelerated SciPy equivalent for the Gaussian filter:


import cupyx.scipy.ndimage as ndimage


Add this apply_bloom function above your main() loop. It operates directly on the 32-bit floating-point accumulation buffer before it is converted to an 8-bit image.


def apply_bloom(d_float_img, threshold=180.0, sigma=15.0, intensity=1.2):

    """

    Applies a GPU-accelerated bloom effect to a float32 CuPy image buffer.

    

    threshold: Minimum brightness (0-255) for a pixel to emit glow.

    sigma: The spread/radius of the blur. 

    intensity: How bright the blended glow should be.

    """

    # 1. Calculate Perceived Luminance (Rec. 709 Standard)

    # OpenCV stores as BGR, so index 0=Blue, 1=Green, 2=Red

    luminance = (0.0722 * d_float_img[:, :, 0] + 

                 0.7152 * d_float_img[:, :, 1] + 

                 0.2126 * d_float_img[:, :, 2])

    

    # 2. Thresholding: Isolate only the brightest pixels

    # Create a 3D mask by expanding the dimensions to match (H, W, 3)

    bloom_mask = (luminance > threshold)[:, :, cp.newaxis]

    d_highlights = d_float_img * bloom_mask

    

    # 3. GPU Gaussian Blur

    # Applying it per-channel prevents color channels from bleeding into one another incorrectly

    d_blurred_highlights = cp.empty_like(d_highlights)

    for channel in range(3):

        d_blurred_highlights[:, :, channel] = ndimage.gaussian_filter(

            d_highlights[:, :, channel], 

            sigma=sigma

        )

        

    # 4. Additive Blending: Screen the glow over the original image

    d_final = d_float_img + (d_blurred_highlights * intensity)

    

    # 5. Clip overflow values back to the 0-255 visible range

    return cp.clip(d_final, 0, 255.0)


Performance Optimization Note

If you increase the sigma to a very large number (e.g., 50+) for a massive, screen-wide glow, the gaussian_filter will start to slow down the 8K render. To optimize large sigmas, you can slice the d_highlights array to process the blur at a lower resolution (e.g., 1080p), and then upscale it back to 8K before blending. Because glow is inherently blurry, the lost resolution during the downscale is entirely unnoticeable.


To tie your color palette to the zoom depth, you must convert the camera's current scale into a linear depth metric using a base-10 logarithm. For example, a scale of $10^{-5}$ becomes a depth of $5$, and a scale of $10^{-100}$ becomes a depth of $100$.

You can then use this depth value to dynamically drive the frequencies and phase shifts of the sine waves generating your colors directly on the GPU.

Method 1: Procedural Phase Shifting

The easiest way to evolve the colors is to push the sine wave phases forward or backward based on the depth. This causes the color gradient to slowly morph through different hues as the camera dives.

Replace your static get_color_palette function with this depth-aware version:


def get_dynamic_color_palette(iters, max_iter, current_scale):

    """

    Generates a color palette that organically shifts hues based on zoom depth.

    """

    # 1. Calculate logarithmic depth (e.g., scale 10^-50 -> depth 50.0)

    # cp.log10 returns a 0D CuPy array, so we use .get() to extract the float

    depth = float(-cp.log10(current_scale).get())

    

    # 2. Define how fast the colors change

    # A phase shift of 2*pi means a full color wheel rotation.

    # Here, the colors complete one full cycle every 20 orders of magnitude.

    color_cycle_speed = 20.0

    phase_shift = (depth / color_cycle_speed) * 2.0 * np.pi

    

    inside_mask = (iters >= max_iter)

    

    # 3. Dynamic Sine Waves

    # Base frequency for how tightly packed the color bands are

    freq = 0.15 

    

    # Red: Shifts forward as we zoom

    r = cp.sin(freq * iters + 0.0 + phase_shift) * 127.5 + 127.5

    

    # Green: Shifts backward at half speed

    g = cp.sin(freq * iters + 2.094 - (phase_shift * 0.5)) * 127.5 + 127.5  

    

    # Blue: Shifts forward rapidly, and the frequency increases slightly at extreme depths

    dynamic_freq_b = freq + (depth * 0.0005)

    b = cp.sin(dynamic_freq_b * iters + 4.188 + (phase_shift * 1.5)) * 127.5 + 127.5  

    

    img = cp.stack((b, g, r), axis=-1).astype(cp.uint8)

    img[inside_mask] = 0

    

    return img


Method 2: Keyframed Palette Blending (Cinematic Control)

If you want precise control—for example, starting with an "Electric Blue" theme and smoothly fading into a "Molten Gold" theme exactly at $10^{-30}$ depth—you can interpolate between predefined arrays of phase vectors.


def get_keyframed_palette(iters, max_iter, current_scale):

    """

    Smoothly interpolates between exact color themes based on depth milestones.

    """

    depth = float(-cp.log10(current_scale).get())

    

    # Define color themes as (Red Phase, Green Phase, Blue Phase)

    THEME_ELECTRIC_BLUE = np.array([3.14, 1.0, 0.0])

    THEME_MOLTEN_GOLD   = np.array([0.0, 1.0, 3.14])

    THEME_NEON_PURPLE   = np.array([0.0, 3.14, 0.5])

    

    # Determine the blend factor based on current depth

    if depth < 30.0:

        # Depth 0 to 30: Blend Electric Blue -> Molten Gold

        t = depth / 30.0 

        current_phases = (1.0 - t) * THEME_ELECTRIC_BLUE + t * THEME_MOLTEN_GOLD

    else:

        # Depth 30 to 60: Blend Molten Gold -> Neon Purple

        # (Clamp 't' to 1.0 so it stays purple past depth 60)

        t = min(1.0, (depth - 30.0) / 30.0)

        current_phases = (1.0 - t) * THEME_MOLTEN_GOLD + t * THEME_NEON_PURPLE


    inside_mask = (iters >= max_iter)

    freq = 0.15

    

    # Apply the interpolated phases

    r = cp.sin(freq * iters + current_phases[0]) * 127.5 + 127.5

    g = cp.sin(freq * iters + current_phases[1]) * 127.5 + 127.5

    b = cp.sin(freq * iters + current_phases[2]) * 127.5 + 127.5

    

    img = cp.stack((b, g, r), axis=-1).astype(cp.uint8)

    img[inside_mask] = 0

    

    return img


Updating the Render Loop

Whether you use the procedural or keyframed method, update the color palette call inside your sub-frame temporal accumulation loop to pass the current fractional scale:



Python

# ... (Inside the temporal accumulation sub-frame loop) ...
            
            # Execute BLA Perturbation Kernel for this sub-frame
            multi_ref_kernel( ... )
            
            # Call the new dynamic color function, passing current_scale
            img_8k_gpu = get_dynamic_color_palette(d_smooth_iters, current_max_iter, current_scale)
            
            # Add to motion blur accumulator
            d_accum_buffer += img_8k_gpu.astype(cp.float32)








Mandelbrot video generator program

 To create a high-definition, progressively zooming Mandelbrot video on an RTX 3090 GPU , we can use CuPy, which compiles CUDA kernels on th...