Code-Driven 3D Video Generation: From a Single Prompt to Modeling and Rendering

    This article explores how code-driven pipelines let developers generate short 3D videos from natural-language prompts by compiling creative intent into executable programs and rendering them through deterministic pipelines. It explains the technical workflow—from script and storyboard planning, parametric modeling, camera animation, and frame-by-frame rendering to audio synchronization and encoding—and offers engineering guidance on consistency, performance, human-in-the-loop review, and responsible content governance for scalable video production.

    1. Introduction: From Writing Animation Code to Generating Short Films from a Single Prompt

    Not long ago, producing even a short 3D clip—say, a few dozen seconds—meant going through script planning, storyboarding, 3D modeling, materials and lighting, character and camera animation, rendering, voiceover and music, and editing and compositing. It was typically a multi-person, weeks-long engineering effort.

    Over the past few months, a new approach has quietly gained traction in developer communities: letting capable large models write programs directly to generate video. Its evolution can be roughly divided into three stages:

    Stage 1: Code that draws animation frame by frame. Back in mid-September, a developer showcased an animation generated by a large model. The animation was rendered frame by frame through drawing code, without using any pre-built assets. Soon after, another developer used an AI coding tool to replicate a Risograph-style look:

    • Generating roughly 3,500 lines of 2D canvas drawing code;
    • Implementing 26 illustrated scenes within a single HTML file;
    • Synthesizing background music in real time using browser audio capabilities.

    In works like these, the “video” is essentially a continuously running drawing program.

    Stage 2: Open-ended requests produce a complete code-driven video. In late September, a version update to a coding-focused large model further fueled this wave of creation. A community creator gave the model a fairly open-ended request:

    Make a video about an ordinary workday. The mood should be eerie, and both the visuals and audio should be done through programming. You choose which tools to use.

    According to the author, the model completed this roughly one-minute surreal horror short—including final rendering—in about 45 minutes under a higher-intensity reasoning mode. The toolchain spanned numerical computation, vector drawing, speech synthesis, and video encoding. The model not only produced the visuals but also the sound, and autonomously selected the tools along the way.

    Stage 3: Toward finished 3D films. After that, this practice began extending from 2D illustration and abstract animation to 3D short films involving scene construction, camera movement, and materials and lighting. The boundary of “generating a short film from a single prompt” keeps expanding.

    Behind these cases lies a technical route distinct from the traditional “text/image-to-pixel” video generation. Its core logic can be summarized as:

    Compile creative intent into an executable program, then render frame by frame through a deterministic pipeline and assemble the final cut.

    Below, we start from the technical principles, break down the key stages of this pipeline, and offer practical engineering recommendations.

    2. Technical Principles: “Video Compilation” with Code as an Intermediate Representation

    Traditional text-to-video models output pixels or latent-space features directly, then decode them into images. Their strength is rich visual quality, but they also have clear limitations:

    • Weak controllability: To precisely adjust an object’s position or the camera angle, you can only tweak the prompt and regenerate;
    • Hard to guarantee consistency: Across different clips, character appearance and scene structure tend to drift;
    • Difficult to customize precisely: Cinematic language and physical behavior required in professional work often cannot be expressed accurately through prompts.

    The code-driven route turns the creative process into a kind of “compilation,” which can be roughly divided into four layers:

    1. Natural-language creative intent
    2. ↓ Large model: understanding, planning, and code generation
    3. Storyboard and scene script (shot duration, composition, camera movement, lighting)
    4. ↓ Render engine: deterministic execution
    5. Per-frame images + audio track
    6. ↓ Compositing pipeline: timeline alignment, encoding, packaging
    7. A playable, editable video file

    Among these, the storyboard script is the most critical intermediate representation. It is both a structured expression of the creator’s intent and the shared coordinate system that aligns the video and audio tracks. Around it, engineering practice typically adopts a “four-layer separation of responsibilities”:

    1. Director layer: Receives natural-language requirements, outputs a structured storyboard script, and decides “what story to tell and what shots to use”;
    2. Scene layer: Builds geometry, materials, and lighting, and decides “what is in the frame”;
    3. Presentation layer: Samples camera trajectories and animation curves, renders frame by frame, and adds post-production effects, deciding “how it is shot and presented”;
    4. Compositing layer: Generates or collects audio, mixes tracks along the timeline, and encodes and packages, deciding “how it sounds and plays.”

    The storyboard script can be described using structured formats such as JSON. An example is shown below:

    1. {
    2. "title": "An Ordinary Day",
    3. "fps": 24,
    4. "resolution": [1920, 1080],
    5. "duration": 6.0,
    6. "shots": [
    7. {
    8. "id": 1,
    9. "start": 0.0,
    10. "duration": 2.5,
    11. "scene": "office",
    12. "camera": {"start": [0, 1.6, -3.2], "end": [0, 1.6, -2.4], "target": [0, 1.0, 0]},
    13. "lighting": {"key_intensity": 1.8, "key_z": -2.0},
    14. "audio": {"voiceover": "shot1_vo", "sfx": ["hum", "keyboard"]},
    15. "post": ["vignette", "grain"]
    16. }
    17. ]
    18. }

    This layered structure brings three direct benefits:

    • Each layer can be swapped independently—for example, changing the render engine without touching the storyboard;
    • Every stage has inspectable intermediate artifacts, making it easier to locate problems;
    • The whole process is naturally parallelizable and cacheable, laying the foundation for later large-scale production.

    3. Why the Two Routes Are Starting to “Shake Hands”

    In fact, code-based animation and rendering have a long history:

    • Traditional 3D animation relies on modeling software, skeletal rigging, keyframes, and ray-traced rendering;
    • VFX has long used procedural methods to generate scene elements like buildings and vegetation in bulk;
    • Creative coding and generative art let artists draw graphics with algorithms;
    • Technical demo videos often use code to visualize abstract algorithms frame by frame.

    What large models change is not rendering technology itself, but that they dramatically lower the barrier to “translating ideas into code”:

    • From “people who can code making animation” to “people who can describe requirements making animation”;
    • From “hand-tuning parameters line by line” to “iterating directorial intent in natural language”;
    • From “scripting tools” to “end-to-end delivery of finished films”, because the model can plan, write, and debug the entire toolchain on its own.

    At the same time, pixel-level video generation models are also advancing rapidly. The two are not mutually exclusive: generation models excel at providing realistic textures, atmospheric quality, and complex natural phenomena, while the code route excels at precise control, logical consistency, and editability. They are more likely to be complementary.

    4. Full-Pipeline Breakdown: Six Stages from Modeling to Rendering

    4.1 Script and Storyboard: Turning Intent into an Executable Plan

    The first step in generating a video is not writing code, but breaking down the requirement. “Tell a story about an ordinary workday with an eerie mood” is a vague intent. The large model first needs to turn it into a concrete plan:

    • Story pacing (opening, development, turning point, ending);
    • The duration and shot size of each shot (long shot, medium shot, close-up, extreme close-up);
    • Visual elements and scene structure;
    • How emotion is conveyed through composition, lighting, and color.

    Engineering recommendations:

    • Adopt a two-step “plan first, code later” approach, separating storyboard planning from code generation to avoid the model overlooking the overall narrative when writing code directly;
    • Treat the planning output (shot list, camera list) as the shared contract for all subsequent stages;
    • If the plan is unsatisfactory, simply re-plan—no need to rewrite the code.

    4.2 3D Modeling: Building the “Digital Scene” with Parametric Geometry

    3D modeling determines the informational foundation of the image. What the model writes is usually not hand-crafted meshes, but parametric modeling code: using primitives like cubes, spheres, and cylinders, combined by size, position, and rotation to form tables, chairs, doors and windows, character silhouettes, and other objects.

    Taking a 3D sphere as an example, parametric mesh generation can be expressed in pseudocode:

    1. def build_sphere(radius, segments=32, rings=16):
    2. """Sample the sphere surface using parametric equations to generate vertices, normals, and triangle indices"""
    3. vertices, normals, indices = [], [], []
    4. for i in range(rings + 1):
    5. theta = pi * i / rings # polar angle
    6. for j in range(segments + 1):
    7. phi = 2 * pi * j / segments # azimuth angle
    8. x = radius * sin(theta) * cos(phi)
    9. y = radius * cos(theta)
    10. z = radius * sin(theta) * sin(phi)
    11. vertices.append((x, y, z))
    12. normals.append(normalize((x, y, z)))
    13. for i in range(rings):
    14. for j in range(segments):
    15. a = i * (segments + 1) + j
    16. b = a + segments + 1
    17. # Generate triangles with a fixed winding order to ensure consistent front-facing orientation and correct normals
    18. indices.extend([(a, b, a + 1), (b, b + 1, a + 1)])
    19. return Mesh(vertices, normals, indices)

    Combined with the classic “transform–project–rasterize” graphics pipeline (model transform, view transform, perspective projection, per-triangle rasterization), you can turn geometry into pixels on screen. This sample code is worth reading line by line, because it captures the core idea of parametric modeling: shape is determined by mathematical functions, and parameters are the “knobs” of creation.

    To lower the difficulty, practice often reuses off-the-shelf geometry primitives, material libraries, and lighting models:

    • Physically based rendering (PBR) materials;
    • Combinations of environment lighting and directional lights;
    • Point lights and spotlights to create local atmosphere;
    • Shadow maps or ray tracing to compute occlusion relationships.

    An “eerie” mood often does not come from complex models, but from precise control over lighting, composition, and color:

    • A hard light source on one side creates strong shadows;
    • Lower ambient light compresses tonal range;
    • Cool color tones and slightly distorted perspective create a sense of unease.

    4.3 Camera Movement: Designing a “Camera Trajectory” for Each Shot

    Camera movement is the skeleton of cinematic language and must answer four questions:

    1. Where is the camera (position);
    2. What is it looking at (orientation and target point);
    3. How long is the focal length or how wide is the field of view;
    4. How do these parameters change over time.

    Taking the common “slow push-in” as an example, it can be described in pseudocode:

    1. def push_in_shot(camera, t, duration, start_z, end_z, look_at):
    2. """Constant-speed push-in: camera moves along the z-axis toward the target, always facing the target point"""
    3. p = clamp(t / duration, 0.0, 1.0)
    4. z = lerp(start_z, end_z, p)
    5. camera.position = (0.0, 1.6, z)
    6. camera.look_at = look_at

    In actual works, movement rhythm is itself part of the narrative:

    • Constant-speed push-in: Slow and restrained, creating a sense of oppression and gaze;
    • Ease-in and ease-out: Soft starts and stops, close to real camera movement habits;
    • Step-like pauses: Sudden pauses during a push-in to heighten unease;
    • Subtle handheld shake: Overlaying small noise offsets to add immediacy.

    A few engineering lessons are worth noting:

    • Motion blur: Sample the camera position multiple times at adjacent moments and accumulate, or apply directional blur in post, to avoid strobing during fast motion;
    • Consistent focal length: If the image is stitched from multiple renders, unify focal length, resolution, and frame rate;
    • Smooth cutting: Lighting, color tone, and movement direction between adjacent shots should echo each other.

    4.4 Frame-by-Frame Rendering: Deterministic Pipelines and Layered Post

    Rendering is the process of turning the “digital scene” into “a series of images.” There are three mainstream strategies:

    1. Real-time rasterization: Fast, suitable for quick preview and iteration, sacrificing some realism;
    2. Ray tracing: Simulates light reflection, refraction, and shadows for a more realistic image, but at high computational cost;
    3. Hybrid rendering: Uses rasterization for the main pass and screen-space techniques or path tracing to supplement reflections and indirect light, balancing efficiency and quality.

    To create a filmic texture, layered post-processing is also needed:

    • Tone mapping and color grading;
    • Vignette;
    • Film grain;
    • Chromatic aberration;
    • Bloom.

    The 2D canvas route does not involve 3D geometry, but it is also “drawn” frame by frame. It uses gradients, semi-transparent overlays, noise textures, and overprint blending to simulate the misregistration and heavy grain of Risograph printing.

    Determinism is the prerequisite for engineering:

    • The rendering process should not depend on unpinned random numbers;
    • When jitter or noise is needed, use a pseudorandom number generator with a fixed seed;
    • The same script should produce exactly identical results in the same environment.

    Only when determinism is satisfied can you do result comparison, regression testing, and distributed parallel rendering.

    4.5 Audio and Audio-Visual Sync: Video Is More Than Images

    The open-ended requirement that “audio is also done through programming” means the pipeline includes an audio track as well:

    • Narration: Generated through a speech synthesis engine using parameters like text, voice, and speaking rate;
    • Ambient sound: Programmatically synthesized low-frequency hums, mechanical noise, and other atmospheric sounds;
    • Music: Generated programmatically as melody and rhythm, or synthesized in real time using browser audio capabilities.

    In eerie works, sound often creates unease more effectively than visuals: continuous low-frequency hums, intermittent rhythmic knocks, and sudden silence are all classic techniques.

    Audio-visual sync is a timeline design problem:

    • Use each shot’s start time as the baseline and compute the absolute time for each shot’s narration, sound effects, and music;
    • Narration duration may exceed the shot duration, so adjust speaking rate, compress silence, or split sentences;
    • When layering narration and music, duck the music to keep the voice clear.

    Sample code is shown below:

    1. def build_timeline(storyboard):
    2. timeline = []
    3. for shot in storyboard.shots:
    4. voice = tts.synthesize(shot.audio.voice_text, rate=shot.voice_rate)
    5. # Narration must not cross shot boundaries; increase speaking rate or split sentences if necessary
    6. assert voice.duration <= shot.duration + 0.1, "Narration too long, needs adjustment"
    7. timeline.append(track(shot.audio.voice, start=shot.start, gain=1.0))
    8. for sfx in shot.audio.sfx:
    9. timeline.append(track(sfx, start=shot.start + sfx.offset, gain=0.6))
    10. bgm = music.generate(storyboard.duration, mood=storyboard.mood)
    11. timeline.append(track(bgm, start=0.0, gain=-12.0, fade=(1.0, 2.0)))
    12. return mixdown(timeline, sample_rate=48000)

    4.6 Encoding and Muxing: From Images and Sound to the Final Cut

    The final compositing stage requires:

    1. Concatenating the video frames of each shot in order;
    2. Packaging the audio track and video with a unified time base;
    3. Completing encoding and compression.

    Sample code is shown below:

    1. def compose(storyboard, workdir):
    2. encoder = VideoEncoder(width=1920, height=1080, fps=24)
    3. for shot in storyboard.shots:
    4. shot_path = render_shot(shot, workdir) # returns the shot's video file
    5. encoder.append(shot_path)
    6. audio = build_timeline(storyboard) # returns the mixed audio track
    7. muxer = Muxer(video=encoder.output(), audio=audio)
    8. # Align keyframe interval with frame rate for easy scrubbing and precise editing
    9. muxer.gop = storyboard.fps * 2
    10. return muxer.write(workdir / "output.mp4")

    This step is often overlooked, yet it directly determines the final viewing experience:

    • Time base: Video frame rate and audio sample rate differ, so a unified time base must be used during muxing;
    • Keyframe interval: Affects scrubbing smoothness and secondary editing;
    • Bitrate and resolution: Relate to clarity and file size.

    Regardless of which rendering route is chosen, practical video generation usually follows a three-layer structure of “platform capabilities + scene orchestration + toolchain“:

    Layer Core responsibilities Foundational capabilities (general categories)
    Platform capability layer Model inference, numerical computation, speech synthesis, encoding/decoding, object storage AI coding tools, cloud inference resources
    Scene orchestration layer Storyboard planning, render scheduling, timeline mixing, caching and retries Message queues, container platforms, logging services, monitoring and alerting
    Toolchain layer Specialized programs for modeling, rendering, compositing, and preview Open-source graphics and multimedia tools, custom scripts

    5. Key Challenges and Engineering Countermeasures

    5.1 Long-Video Consistency

    The more shots there are, the more likely scene structure and character appearance drift. Three layers of constraints are recommended:

    1. Global scene description: Before storyboarding, define a “scene bible” (scene layout, character settings, color and lighting tone), and have every subsequent shot reference the same description;
    2. Reusable named assets: The same character or object across different shots should reference the same model definition and material parameters—no duplicate definitions;
    3. Anchor frame constraints: Once the first shot is settled, subsequent shots can reference the positions of key objects in the first frame to keep spatial relationships continuous.

    5.2 Loss of Complexity Control

    An “eerie workday” can easily balloon into dozens of shots and thousands of lines of code, making debugging difficult and render times unpredictable. Recommended practices:

    • Set budgets for lines of code per shot and number of scene objects;
    • Use reusable components (characters, furniture, lighting fixtures) rather than one-off scripts;
    • Create atmosphere primarily through “repetition + micro-variation” rather than stacking many unique elements.

    5.3 Performance and Cost

    • Fast preview: Render drafts at low resolution and low sampling first, then raise quality after confirming pacing;
    • Parallel rendering: Different shots are independent and can be processed in parallel;
    • Incremental caching: Reuse existing artifacts when visuals or audio have not changed;
    • Elastic scaling: Use container platform elastic scheduling to scale render resources dynamically based on workload, and release them promptly after tasks complete.

    Generation time needs to be viewed rationally. In the community case mentioned earlier, a roughly one-minute video included about 45 minutes of model inference and rendering time. This number depends on task complexity, inference intensity, hardware environment, and render quality settings, and should not be treated directly as an industry benchmark.

    Dimension Code-driven video generation Pixel-level video generation models
    Control precision High; shots and scenes can be specified precisely Depends on prompts; details are hard to control precisely
    Consistency Strong; reusing named assets maintains consistency Prone to drift across clips
    Editability Strong; change parameters and re-render Requires regeneration
    Visual realism Depends on modeling, materials, and render quality Usually more natural for complex textures and physical phenomena
    Explainability High; every step can be traced in code Low; the generation process is hard to intervene in step by step
    Suitable scenarios Data visualization, training, product demos, pre-visualization Live-action films, commercials, VFX shots

    5.4 Simulating Complex Phenomena

    Complex phenomena like fire, water, smoke, and crowds are extremely costly to describe with geometric modeling. Viable approaches include:

    • Approximate simulation using noise fields and particle systems;
    • In shots with high realism requirements, introducing image or video generation models to produce local assets, then compositing them with code-rendered images;
    • Being cautious with assets subject to copyright or likeness rights.

    This also shows that the code route is not a cure-all; reasonably assessing which content is suitable for programmatic generation is a prerequisite for project success.

    6. Practical Implementation: Building a Scalable Video Production Pipeline

    6.1 Introducing “Human-in-the-Loop” Checkpoints

    A fully “one-click” video generation is still hard to meet professional quality today. A more pragmatic approach is to set human confirmation at key nodes:

    1. Storyboard confirmation: The creator reviews the shot list and durations;
    2. Draft preview: Low-resolution quick preview of pacing and camera movement;
    3. Final review: Confirm image quality, audio-visual sync, and content compliance.

    6.2 Building a Reproducible and Observable Engineering System

    • Scripts as assets: Put storyboard scripts, scene definitions, and render configs under version control so every generation can be traced to a specific version and parameters;
    • Fixed random seeds: Ensure the same input produces the same output;
    • Layered caching: Cache intermediate artifacts separately by scene, shot, and audio;
    • Task visualization: Use logging services and monitoring/alerting to track per-stage time, failure rates, and resource usage;
    • Structured storage: Use object storage to save drafts, rendered frames, and final cuts, managing lifecycle by project layers;
    • Queue decoupling: Use message queues to decouple tasks from the request side, supporting queuing, prioritization, and failure retries.

    6.3 Human-Machine Collaboration Division

    In this production mode, the human role is changing:

    Traditional production Code-driven production
    Modelers, animators, lighting artists Prompt and storyboard designers
    Adjusting animation curves frame by frame Reviewing scripts and adjusting parameters and pacing
    Manual editing and compositing Defining render and compositing configurations
    Render farm operations Pipeline orchestration and quality review

    Creators can devote more energy to story structure and aesthetic judgment, while the model handles the heavy lifting of “turning ideas into reality.”

    7. Typical Application Scenarios

    1. Training and educational videos: Explain abstract processes and algorithm principles clearly with 3D animation; update content simply by changing the script;
    2. Product demos and launch materials: Quickly generate display clips with different color schemes and angles via parametric models;
    3. Data visualization and annual reports: Turn business data into dynamic chart animations; re-render whenever data updates;
    4. Film pre-visualization: Use low-cost animation to validate shot design and pacing before actual filming;
    5. Social media content: Batch-generate series of short films with consistent style, maintaining visual identity;
    6. Interactive web experiences: The drawing programs generated by models can be embedded directly in web pages, creating dynamic visuals that change in real time with user interaction.

    8. Risks and Governance: Boundaries Beyond Technology

    Code-driven video lowers the barrier to creation but also introduces new risks:

    • Content compliance: Generated content must comply with relevant laws, regulations, and platform rules; footage involving news or public issues should be handled cautiously;
    • Copyright and likeness rights: Imitating a specific artist’s style, using copyrighted assets, or cloning someone’s voice all require authorization;
    • Deepfakes: Realistic people and scenes could be used for misleading content; under applicable management requirements, AI-generated content should be marked with explicit and implicit labels;
    • Quality and review: Model-generated images may have proportion distortion, mesh clipping, unnatural lighting, and other issues; key content needs manual review.

    It is recommended to add content review nodes in the pipeline to check both scripts and final cuts in both directions.

    9. Outlook: From “Generating Video” to “Generating Editable Worlds”

    We can expect this route to continue evolving in three directions:

    1. Standardization of intermediate representations: Storyboard scripts and scene descriptions gradually form a common format, enabling seamless interoperability between different tools;
    2. Fusion of multiple routes: The precise control of code-driven generation and the realism of generation models deeply combine into a hybrid pipeline that is both “controllable + realistic”;
    3. Real-time interactivity: Video is no longer a file passively played after rendering, but an interactive world that can be computed in real time based on user actions.

    For developers, what is worth attention is the methodology itself: turning vague creative intent into a structured, executable, and verifiable engineering process. Whether generating a short film or a data animation, this approach applies equally well.