```python
import bpy
import math
import random

def setup_render_engine():
    """Sets up the render engine and resolution for high-quality Cycles rendering."""
    scene = bpy.context.scene
    scene.render.engine = 'CYCLES'
    scene.cycles.device = 'GPU'

    # Render settings
    scene.render.resolution_x = 1536
    scene.render.resolution_y = 1536
    scene.cycles.samples = 64
    scene.cycles.use_denoising = True

    # Color management
    scene.view_settings.view_transform = 'AgX'
    scene.view_settings.look = 'High Contrast'

def clean_scene():
    """Cleans up default scene objects."""
    bpy.ops.object.select_all(action='SELECT')
    bpy.ops.object.delete()

def create_materials():
    """Creates all stylized procedural materials for the scene."""
    materials = {}

    # 1. Corgi Tan Material
    mat_tan = bpy.data.materials.new(name="Corgi_Tan")
    mat_tan.use_nodes = True
    nodes = mat_tan.node_tree.nodes
    links = mat_tan.node_tree.links
    nodes.clear()

    out_node = nodes.new('ShaderNodeOutputMaterial')
    bsdf = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf.inputs['Base Color'].default_value = (0.84, 0.43, 0.18, 1.0) # Rich Tan/Orange
    bsdf.inputs['Roughness'].default_value = 0.85

    # Fuzzy bump map
    noise = nodes.new('ShaderNodeTexNoise')
    noise.inputs['Scale'].default_value = 120.0
    noise.inputs['Detail'].default_value = 4.0
    bump = nodes.new('ShaderNodeBump')
    bump.inputs['Strength'].default_value = 0.08

    links.new(noise.outputs['Factor'], bump.inputs['Height'])
    links.new(bump.outputs['Normal'], bsdf.inputs['Normal'])
    links.new(bsdf.outputs['BSDF'], out_node.inputs['Surface'])
    materials['Corgi_Tan'] = mat_tan

    # 2. Corgi White Material
    mat_white = bpy.data.materials.new(name="Corgi_White")
    mat_white.use_nodes = True
    nodes = mat_white.node_tree.nodes
    links = mat_white.node_tree.links
    nodes.clear()

    out_node = nodes.new('ShaderNodeOutputMaterial')
    bsdf = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf.inputs['Base Color'].default_value = (0.95, 0.95, 0.93, 1.0)
    bsdf.inputs['Roughness'].default_value = 0.85

    # Match the fuzzy bump
    noise = nodes.new('ShaderNodeTexNoise')
    noise.inputs['Scale'].default_value = 120.0
    noise.inputs['Detail'].default_value = 4.0
    bump = nodes.new('ShaderNodeBump')
    bump.inputs['Strength'].default_value = 0.08

    links.new(noise.outputs['Factor'], bump.inputs['Height'])
    links.new(bump.outputs['Normal'], bsdf.inputs['Normal'])
    links.new(bsdf.outputs['BSDF'], out_node.inputs['Surface'])
    materials['Corgi_White'] = mat_white

    # 3. Master Corgi Shader (Uses Vertex Painting to Mix Tan and White dynamically/softly)
    mat_corgi = bpy.data.materials.new(name="Corgi_Body")
    mat_corgi.use_nodes = True
    nodes = mat_corgi.node_tree.nodes
    links = mat_corgi.node_tree.links
    nodes.clear()

    out_node = nodes.new('ShaderNodeOutputMaterial')
    mix_shader = nodes.new('ShaderNodeMixShader')

    # Reuse node setups for clean code
    c_attr = nodes.new('ShaderNodeAttribute')
    c_attr.attribute_name = "CorgiColor"

    # We want a soft transition with some noise (fur edge effect)
    noise_trans = nodes.new('ShaderNodeTexNoise')
    noise_trans.inputs['Scale'].default_value = 40.0
    noise_trans.inputs['Detail'].default_value = 2.0

    mix_factor = nodes.new('ShaderNodeMix')
    mix_factor.data_type = 'FLOAT'
    mix_factor.blend_type = 'MIX'
    mix_factor.inputs[0].default_value = 0.4  # factor

    links.new(c_attr.outputs['Color'], mix_factor.inputs[4]) # Op B
    links.new(noise_trans.outputs['Factor'], mix_factor.inputs[3]) # Op A

    # Tan BSDF
    bsdf_tan = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf_tan.inputs['Base Color'].default_value = (0.84, 0.43, 0.18, 1.0)
    bsdf_tan.inputs['Roughness'].default_value = 0.85

    # White BSDF
    bsdf_white = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf_white.inputs['Base Color'].default_value = (0.95, 0.95, 0.93, 1.0)
    bsdf_white.inputs['Roughness'].default_value = 0.8

    # Universal bump for fur
    noise_fur = nodes.new('ShaderNodeTexNoise')
    noise_fur.inputs['Scale'].default_value = 150.0
    noise_fur.inputs['Detail'].default_value = 6.0
    bump_fur = nodes.new('ShaderNodeBump')
    bump_fur.inputs['Strength'].default_value = 0.15

    links.new(noise_fur.outputs['Factor'], bump_fur.inputs['Height'])
    links.new(bump_fur.outputs['Normal'], bsdf_tan.inputs['Normal'])
    links.new(bump_fur.outputs['Normal'], bsdf_white.inputs['Normal'])

    # Mix based on vertex attribute + noise
    links.new(c_attr.outputs['Color'], mix_shader.inputs['Factor'])
    links.new(bsdf_tan.outputs['BSDF'], mix_shader.inputs[1])
    links.new(bsdf_white.outputs['BSDF'], mix_shader.inputs[2])
    links.new(mix_shader.outputs['Shader'], out_node.inputs['Surface'])

    materials['Corgi_Body'] = mat_corgi

    # 4. Glossy Black (Eyes & Nose)
    mat_black = bpy.data.materials.new(name="Glossy_Black")
    mat_black.use_nodes = True
    nodes = mat_black.node_tree.nodes
    nodes.clear()
    out_node = nodes.new('ShaderNodeOutputMaterial')
    bsdf = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf.inputs['Base Color'].default_value = (0.02, 0.02, 0.02, 1.0)
    bsdf.inputs['Roughness'].default_value = 0.05
    nodes.node_tree.links.new(bsdf.outputs['BSDF'], out_node.inputs['Surface'])
    materials['Glossy_Black'] = mat_black

    # 5. Pink Mouth/Tongue
    mat_pink = bpy.data.materials.new(name="Mouth_Pink")
    mat_pink.use_nodes = True
    nodes = mat_pink.node_tree.nodes
    nodes.clear()
    out_node = nodes.new('ShaderNodeOutputMaterial')
    bsdf = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf.inputs['Base Color'].default_value = (0.95, 0.35, 0.45, 1.0)
    bsdf.inputs['Roughness'].default_value = 0.2
    nodes.node_tree.links.new(bsdf.outputs['BSDF'], out_node.inputs['Surface'])
    materials['Mouth_Pink'] = mat_pink

    # 6. Sand Material
    mat_sand = bpy.data.materials.new(name="Sand")
    mat_sand.use_nodes = True
    nodes = mat_sand.node_tree.nodes
    links = mat_sand.node_tree.links
    nodes.clear()

    out_node = nodes.new('ShaderNodeOutputMaterial')
    bsdf = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf.inputs['Base Color'].default_value = (0.92, 0.78, 0.61, 1.0)
    bsdf.inputs['Roughness'].default_value = 0.95

    # Sand texture detail
    noise_sand = nodes.new('ShaderNodeTexNoise')
    noise_sand.inputs['Scale'].default_value = 250.0
    noise_sand.inputs['Detail'].default_value = 8.0
    bump_sand = nodes.new('ShaderNodeBump')
    bump_sand.inputs['Strength'].default_value = 0.2

    links.new(noise_sand.outputs['Factor'], bump_sand.inputs['Height'])
    links.new(bump_sand.outputs['Normal'], bsdf.inputs['Normal'])
    links.new(bsdf.outputs['BSDF'], out_node.inputs['Surface'])
    materials['Sand'] = mat_sand

    # 7. Beach Ball Material (6-panel procedural Stripe)
    mat_ball = bpy.data.materials.new(name="Beach_Ball")
    mat_ball.use_nodes = True
    nodes = mat_ball.node_tree.nodes
    links = mat_ball.node_tree.links
    nodes.clear()

    out_node = nodes.new('ShaderNodeOutputMaterial')
    bsdf = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf.inputs['Roughness'].default_value = 0.15
    bsdf.inputs['Specular IOR Level'].default_value = 0.6

    # Texture Coordinates & Radial Gradient
    tex_coord = nodes.new('ShaderNodeTexCoord')
    grad = nodes.new('ShaderNodeTexGradient')
    grad.gradient_type = 'RADIAL'

    # ColorRamp for the 6 alternating panels
    ramp = nodes.new('ShaderNodeValToRGB')
    ramp.color_ramp.interpolation = 'CONSTANT'
    # Setup color bands: Red, White, Blue, White, Yellow, White
    elements = ramp.color_ramp.elements
    # Set existing elements
    elements[0].position = 0.0
    elements[0].color = (0.9, 0.1, 0.1, 1.0) # Red
    elements[1].position = 0.166
    elements[1].color = (0.95, 0.95, 0.95, 1.0) # White

    # Add remaining elements
    el2 = elements.new(0.333)
    el2.color = (0.1, 0.4, 0.9, 1.0) # Blue
    el3 = elements.new(0.5)
    el3.color = (0.95, 0.95, 0.95, 1.0) # White
    el4 = elements.new(0.666)
    el4.color = (0.95, 0.8, 0.05, 1.0) # Yellow
    el5 = elements.new(0.833)
    el5.color = (0.95, 0.95, 0.95, 1.0) # White

    # Let's add top/bottom white caps
    sep = nodes.new('ShaderNodeSeparateXYZ')
    abs_node = nodes.new('ShaderNodeMath')
    abs_node.operation = 'ABSOLUTE'
    cap_compare = nodes.new('ShaderNodeMath')
    cap_compare.operation = 'GREATER_THAN'
    cap_compare.inputs[1].default_value = 0.78  # threshold for caps

    mix_color = nodes.new('ShaderNodeMix')
    mix_color.data_type = 'RGBA'
    mix_color.blend_type = 'MIX'

    # Connect color bands and coordinate transforms to construct mapping
    links.new(tex_coord.outputs['Object'], grad.inputs['Vector'])
    links.new(grad.outputs['Factor'], ramp.inputs['Fac'])

    links.new(tex_coord.outputs['Object'], sep.inputs['Vector'])
    links.new(sep.outputs['Z'], abs_node.inputs[0])
    links.new(abs_node.outputs[0], cap_compare.inputs[0])

    # Compose final base color
    links.new(cap_compare.outputs[0], mix_color.inputs['Factor'])
    links.new(ramp.outputs['Color'], mix_color.inputs[4]) # Color A
    mix_color.inputs[5].default_value = (0.95, 0.95, 0.95, 1.0) # White cap color

    links.new(mix_color.outputs[2], bsdf.inputs['Base Color'])
    links.new(bsdf.outputs['BSDF'], out_node.inputs['Surface'])
    materials['Beach_Ball'] = mat_ball

    # 8. Bright Striped Towel Material
    mat_towel = bpy.data.materials.new(name="Towel")
    mat_towel.use_nodes = True
    nodes = mat_towel.node_tree.nodes
    links = mat_towel.node_tree.links
    nodes.clear()

    out_node = nodes.new('ShaderNodeOutputMaterial')
    bsdf = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf.inputs['Roughness'].default_value = 0.9

    tex_coord = nodes.new('ShaderNodeTexCoord')
    wave = nodes.new('ShaderNodeTexWave')
    wave.wave_type = 'BANDS'
    wave.inputs['Scale'].default_value = 1.5

    ramp = nodes.new('ShaderNodeValToRGB')
    ramp.color_ramp.interpolation = 'CONSTANT'
    elements = ramp.color_ramp.elements
    elements[0].position = 0.0
    elements[0].color = (0.05, 0.75, 0.85, 1.0) # Teal
    elements[1].position = 0.5
    elements[1].color = (0.95, 0.95, 0.95, 1.0) # White

    links.new(tex_coord.outputs['Object'], wave.inputs['Vector'])
    links.new(wave.outputs['Color'], ramp.inputs['Fac'])
    links.new(ramp.outputs['Color'], bsdf.inputs['Base Color'])
    links.new(bsdf.outputs['BSDF'], out_node.inputs['Surface'])
    materials['Towel'] = mat_towel

    # 9. Plastic Toy Material
    mat_plastic = bpy.data.materials.new(name="Bright_Plastic")
    mat_plastic.use_nodes = True
    nodes = mat_plastic.node_tree.nodes
    nodes.clear()
    out_node = nodes.new('ShaderNodeOutputMaterial')
    bsdf = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf.inputs['Base Color'].default_value = (0.95, 0.15, 0.1, 1.0) # Vibrant Red
    bsdf.inputs['Roughness'].default_value = 0.2
    nodes.node_tree.links.new(bsdf.outputs['BSDF'], out_node.inputs['Surface'])
    materials['Bright_Plastic'] = mat_plastic

    return materials

def build_corgi(materials):
    """Assembles and models the adorable Corgi, applies Voxel Remesh and paints its markings."""

    corgi_parts = []

    # Main Body Tube (Curved using multiple spheres)
    # Rear/Butt
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.55, location=(-0.5, 0, 0.2))
    butt = bpy.context.active_object
    butt.scale = (1.0, 1.0, 1.0)
    corgi_parts.append(butt)

    # Mid body
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.48, location=(0.0, 0, 0.15))
    mid = bpy.context.active_object
    mid.scale = (1.2, 0.95, 0.95)
    corgi_parts.append(mid)

    # Chest
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.54, location=(0.55, 0, 0.22))
    chest = bpy.context.active_object
    corgi_parts.append(chest)

    # Head
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.45, location=(1.15, 0, 0.65))
    head = bpy.context.active_object
    corgi_parts.append(head)

    # Fox-like Muzzle
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.25, location=(1.5, 0, 0.55))
    snout = bpy.context.active_object
    snout.scale = (1.4, 0.9, 0.8)
    corgi_parts.append(snout)

    # Lower Jaw (Slightly open mouth)
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.20, location=(1.45, 0, 0.38))
    jaw = bpy.context.active_object
    jaw.scale = (1.2, 0.8, 0.6)
    jaw.rotation_euler = (0, math.radians(-12), 0)
    corgi_parts.append(jaw)

    # Oversized Upright Ears (Flipped slightly back from momentum)
    # Left Ear
    bpy.ops.mesh.primitive_cone_add(radius1=0.22, depth=0.65, location=(1.05, 0.32, 1.0))
    rear_l = bpy.context.active_object
    rear_l.scale = (1.0, 0.45, 1.4)
    rear_l.rotation_euler = (math.radians(-15), math.radians(-25), math.radians(-10))
    corgi_parts.append(rear_l)

    # Right Ear
    bpy.ops.mesh.primitive_cone_add(radius1=0.22, depth=0.65, location=(1.05, -0.32, 1.0))
    rear_r = bpy.context.active_object
    rear_r.scale = (1.0, 0.45, 1.4)
    rear_r.rotation_euler = (math.radians(15), math.radians(-25), math.radians(10))
    corgi_parts.append(rear_r)

    # Comically Short Legs (Fully flying/extended)
    # Front Left Leg (reaching forward)
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.14, location=(0.95, 0.4, 0.15))
    f_leg_l = bpy.context.active_object
    f_leg_l.scale = (1.6, 1.0, 1.0)
    f_leg_l.rotation_euler = (0, math.radians(-20), math.radians(15))
    corgi_parts.append(f_leg_l)

    # Front Right Leg (reaching forward)
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.14, location=(0.95, -0.4, 0.15))
    f_leg_r = bpy.context.active_object
    f_leg_r.scale = (1.6, 1.0, 1.0)
    f_leg_r.rotation_euler = (0, math.radians(-20), math.radians(-15))
    corgi_parts.append(f_leg_r)

    # Thicker Rear Thighs (Stretched back)
    # Back Left Thigh
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.28, location=(-0.65, 0.48, 0.18))
    b_thigh_l = bpy.context.active_object
    b_thigh_l.scale = (1.5, 1.0, 1.0)
    b_thigh_l.rotation_euler = (0, math.radians(35), math.radians(-10))
    corgi_parts.append(b_thigh_l)

    # Back Right Thigh
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.28, location=(-0.65, -0.48, 0.18))
    b_thigh_r = bpy.context.active_object
    b_thigh_r.scale = (1.5, 1.0, 1.0)
    b_thigh_r.rotation_euler = (0, math.radians(35), math.radians(10))
    corgi_parts.append(b_thigh_r)

    # Back Left Foot/Sock
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.12, location=(-1.15, 0.48, -0.05))
    b_leg_l = bpy.context.active_object
    b_leg_l.scale = (1.4, 1.0, 1.0)
    corgi_parts.append(b_leg_l)

    # Back Right Foot/Sock
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.12, location=(-1.15, -0.48, -0.05))
    b_leg_r = bpy.context.active_object
    b_leg_r.scale = (1.4, 1.0, 1.0)
    corgi_parts.append(b_leg_r)

    # Iconic Tiny Corgi Butt Tail/Stub
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.10, location=(-1.05, 0.0, 0.38))
    tail_stub = bpy.context.active_object
    corgi_parts.append(tail_stub)

    # Join and Fuse all parts using Voxel Remesh for soft, organic silhouette-breaker
    # Select all parts
    for part in corgi_parts:
        part.select_set(True)
    bpy.context.view_layer.objects.active = butt
    bpy.ops.object.join()

    corgi_body = bpy.context.active_object
    corgi_body.name = "Corgi_Body_Seamless"

    # Add Remesh Modifier
    remesh_mod = corgi_body.modifiers.new(name="Fuse_Remesh", type='REMESH')
    remesh_mod.mode = 'VOXEL'
    remesh_mod.voxel_size = 0.038
    remesh_mod.use_smooth_shade = True

    # Add Smooth Modifier to make it incredibly soft and organic
    smooth_mod = corgi_body.modifiers.new(name="Fuse_Smooth", type='SMOOTH')
    smooth_mod.factor = 1.0
    smooth_mod.iterations = 12

    # Apply modifiers to prepare mesh for vertex writing
    bpy.ops.object.modifier_apply(modifier="Fuse_Remesh")
    bpy.ops.object.modifier_apply(modifier="Fuse_Smooth")

    # Add Subdivision Surface for render-time perfection
    subdiv_mod = corgi_body.modifiers.new(name="Render_Subdiv", type='SUBSURF')
    subdiv_mod.levels = 1
    subdiv_mod.render_levels = 2

    # Vertex Painting - Designing the classic Corgi White-and-Tan marking mask (0 = Tan, 1 = White)
    # Get mesh color attribute
    if not corgi_body.data.color_attributes:
        color_layer = corgi_body.data.color_attributes.new(name="CorgiColor", type='FLOAT_COLOR', domain='POINT')
    else:
        color_layer = corgi_body.data.color_attributes.active

    for i, vert in enumerate(corgi_body.data.vertices):
        co = vert.co
        is_white = False

        # 1. White Blaze (Up face center between eyes)
        if co.x > 0.95 and abs(co.y) < 0.075 and co.z > 0.45:
            is_white = True

        # 2. Chest & Underbelly
        if co.x > -0.2 and co.x < 1.0 and co.z < 0.16 and abs(co.y) < 0.45:
            is_white = True

        # 3. Muzzle chin (under part of face)
        if co.x >= 1.25 and co.z < 0.45:
            is_white = True

        # 4. Front white socks (paws)
        if co.x > 0.98 and abs(co.y) > 0.35 and co.z < 0.3:
            is_white = True

        # 5. Back white socks (paws)
        if co.x < -0.9 and abs(co.y) > 0.35 and co.z < 0.08:
            is_white = True

        color_layer.data[i].color = (1.0, 1.0, 1.0, 1.0) if is_white else (0.0, 0.0, 0.0, 1.0)

    # Assign Body Material
    corgi_body.data.materials.append(materials['Corgi_Body'])

    # Add Independent Face Elements (Nose, Eye Spheres, Tongue)
    # Nose
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.06, location=(1.65, 0.0, 0.57))
    nose = bpy.context.active_object
    nose.name = "Corgi_Nose"
    nose.scale = (0.7, 1.0, 0.6)
    nose.data.materials.append(materials['Glossy_Black'])

    # Left Eye
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.05, location=(1.35, 0.23, 0.72))
    eye_l = bpy.context.active_object
    eye_l.name = "Corgi_Eye_L"
    eye_l.data.materials.append(materials['Glossy_Black'])

    # Right Eye
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.05, location=(1.35, -0.23, 0.72))
    eye_r = bpy.context.active_object
    eye_r.name = "Corgi_Eye_R"
    eye_r.data.materials.append(materials['Glossy_Black'])

    # Wet, Floppy Pink Tongue hanging out mid-air (To-the-side joyful panic!)
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.07, location=(1.58, 0.12, 0.4))
    tongue = bpy.context.active_object
    tongue.name = "Corgi_Tongue"
    tongue.scale = (1.5, 1.1, 0.4)
    tongue.rotation_euler = (math.radians(-10), math.radians(25), math.radians(35))
    tongue.data.materials.append(materials['Mouth_Pink'])

    # Parent parts to the Corgi body for easy universal translation
    nose.parent = corgi_body
    eye_l.parent = corgi_body
    eye_r.parent = corgi_body
    tongue.parent = corgi_body

    return corgi_body

def build_beach_ball(materials):
    """Creates a slightly deformed, stylized beach ball floating in the air."""
    # Beach ball positioned right in front of the corgi's nose
    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.6, location=(2.6, 0.2, 0.95))
    ball = bpy.context.active_object
    ball.name = "Beach_Ball"

    # Slight dynamic squeeze to simulate visual motion/expansion/impact prep
    ball.scale = (1.08, 0.94, 0.94)
    ball.rotation_euler = (math.radians(20), math.radians(-35), math.radians(45))

    # Assign procedural multisegment material
    ball.data.materials.append(materials['Beach_Ball'])

    # Small valve nub
    bpy.ops.mesh.primitive_cylinder_add(radius=0.04, depth=0.03, location=(2.6, 0.18, 1.54))
    nub = bpy.context.active_object
    nub.name = "Beach_Ball_Valve"
    nub.data.materials.append(materials['Corgi_White'])
    nub.parent = ball

    # Smooth shade
    for face in ball.data.polygons:
        face.use_smooth = True
    for face in nub.data.polygons:
        face.use_smooth = True

    return ball

def build_environment(materials):
    """Sets up the beach stage terrain, detailed sea background, windblown towels, and splash details."""

    # Large sand floor
    bpy.ops.mesh.primitive_grid_add(x_subdivisions=50, y_subdivisions=50, size=24.0, location=(0, 0, -0.4))
    floor = bpy.context.active_object
    floor.name = "Sand_Floor"
    floor.data.materials.append(materials['Sand'])

    # Displace sand floor slightly for realistic dunes and dynamic tracks
    for v in floor.data.vertices:
        # Simple procedural dune displacement math
        v.co.z += (math.sin(v.co.x * 0.3) * math.cos(v.co.y * 0.3) * 0.1)

        # Deepen sand print impressions behind takeoff (around (-0.2, 0) and (-0.85, 0))
        dist_takeoff_1 = (v.co.x + 0.35)**2 + (v.co.y - 0.25)**2
        dist_takeoff_2 = (v.co.x + 0.35)**2 + (v.co.y + 0.25)**2
        if dist_takeoff_1 < 0.08:
            v.co.z -= 0.04
        if dist_takeoff_2 < 0.08:
            v.co.z -= 0.04

    # Smooth floor shading
    for face in floor.data.polygons:
        face.use_smooth = True

    # 2. Airborne Starfish/Coral Sandal Toy (tumbling mid-air detail)
    bpy.ops.mesh.primitive_cube_add(size=0.18, location=(1.5, -1.0, 0.45))
    toy = bpy.context.active_object
    toy.name = "Airborne_Toy"
    toy.scale = (1.5, 0.8, 0.3)
    toy.rotation_euler = (math.radians(35), math.radians(-50), math.radians(20))
    toy.data.materials.append(materials['Bright_Plastic'])
    # Strap for detail
    bpy.ops.mesh.primitive_torus_add(align='WORLD', location=(1.5, -1.0, 0.52), major_radius=0.06, minor_radius=0.015)
    strap = bpy.context.active_object
    strap.scale = (1.5, 1.0, 0.5)
    strap.rotation_euler = (math.radians(35), math.radians(-50), math.radians(20))
    strap.data.materials.append(materials['Corgi_White'])
    strap.parent = toy

    # 3. Tipped sand bucket spilling out sand
    bpy.ops.mesh.primitive_cone_add(radius1=0.2, radius2=0.28, depth=0.45, location=(-0.3, 1.6, -0.15))
    bucket = bpy.context.active_object
    bucket.name = "Beach_Bucket"
    bucket.rotation_euler = (math.radians(20), math.radians(75), math.radians(-10))
    bucket.data.materials.append(materials['Bright_Plastic'])
    for face in bucket.data.polygons:
        face.use_smooth = True

    # 4. Windblown towel (lifted corner from the takeoff gust)
    bpy.ops.mesh.primitive_grid_add(x_subdivisions=20, y_subdivisions=20, size=1.8, location=(-1.2, -1.3, -0.2))
    towel = bpy.context.active_object
    towel.name = "Beach_Towel"
    towel.scale = (1.2, 0.7, 1.0)
    towel.rotation_euler = (0, 0, math.radians(-15))
    towel.data.materials.append(materials['Towel'])

    # Displace towel vertices to create gorgeous organic folds & lifted takeoff corner
    for v in towel.data.vertices:
        # Wind drape effect
        v.co.z += math.sin(v.co.x * 2.0) * math.cos(v.co.y * 2.0) * 0.08
        # Lift up the front right corner dramatically from takeoff wind
        if v.co.x > 0.4 and v.co.y > 0.2:
            v.co.z += (v.co.x - 0.4) * (v.co.y - 0.2) * 1.8

    for face in towel.data.polygons:
        face.use_smooth = True

    # 5. Takeoff Sand Explosion Burst (Dynamic clumps caught mid-motion)
    for i in range(16):
        sz = random.uniform(0.02, 0.07)
        px = random.uniform(-0.6, -0.1)
        py = random.uniform(-0.4, 0.4)
        pz = random.uniform(-0.3, 0.5) # Some high up, escaping gravity

        bpy.ops.mesh.primitive_uv_sphere_add(radius=sz, location=(px, py, pz))
        clump = bpy.context.active_object
        clump.name = f"Sand_Clump_{i}"
        # Soft lighter-rough material
        clump.data.materials.append(materials['Sand'])
        for face in clump.data.polygons:
            face.use_smooth = True

def add_lighting_and_sky():
    """Builds vivid midday coastal sun and background sky setup."""
    # 1. Vibrant Golden Sun
    bpy.ops.object.light_add(type='SUN', radius=0.03, location=(5, -5, 12))
    sun = bpy.context.active_object
    sun.name = "Beach_Sun"
    sun.data.energy = 8.5
    sun.data.color = (1.0, 0.98, 0.92) # warm sunlight
    sun.data.shadow_soft_size = 0.015 # Sharp crisp beach shadows

    # 2. Soft Blue Sky/Ocean backdrop plane
    bpy.ops.mesh.primitive_grid_add(x_subdivisions=5, y_subdivisions=5, size=40.0, location=(0, 22.0, 5.0))
    sky = bpy.context.active_object
    sky.name = "SeaSky_Backdrop"
    sky.rotation_euler = (math.radians(90), 0, 0)

    # Backdrop Shader
    mat_sky = bpy.data.materials.new(name="Sea_Sky")
    mat_sky.use_nodes = True
    nodes = mat_sky.node_tree.nodes
    links = mat_sky.node_tree.links
    nodes.clear()

    out_node = nodes.new('ShaderNodeOutputMaterial')
    bsdf = nodes.new('ShaderNodeBsdfPrincipled')
    bsdf.inputs['Roughness'].default_value = 1.0

    # Blue/White tropical gradient backdrop
    tex_coord = nodes.new('ShaderNodeTexCoord')
    grad = nodes.new('ShaderNodeTexGradient')
    grad.gradient_type = 'LINEAR'
    grad_rot = nodes.new('ShaderNodeMapping')
    grad_rot.inputs['Rotation'].default_value[1] = math.radians(90) # Rotate to vertical

    ramp = nodes.new('ShaderNodeValToRGB')
    elements = ramp.color_ramp.elements
    elements[0].position = 0.0
    elements[0].color = (0.9, 0.95, 1.0, 1.0) # Light horizon haze
    elements[1].position = 0.7
    elements[1].color = (0.2, 0.55, 0.9, 1.0) # Sky blue

    links.new(tex_coord.outputs['Generated'], grad_rot.inputs['Vector'])
    links.new(grad_rot.outputs['Vector'], grad.inputs['Vector'])
    links.new(grad.outputs['Factor'], ramp.inputs['Fac'])
    links.new(ramp.outputs['Color'], bsdf.inputs['Base Color'])
    links.new(bsdf.outputs['BSDF'], out_node.inputs['Surface'])

    sky.data.materials.append(mat_sky)
    for face in sky.data.polygons:
        face.use_smooth = True

def setup_camera():
    """Sets up the low, eye-level perspective cinematic camera."""
    bpy.ops.object.camera_add(location=(3.4, -3.8, 0.45))
    camera = bpy.context.active_object
    camera.name = "Cinematic_Cam"

    # Point camera at the midpoint of key interaction (between dog's face and ball)
    camera.rotation_euler = (math.radians(82), 0, math.radians(39))

    # Camera settings
    camera.data.lens = 45 # Slightly wide-angle dramatic capture

    # Beautiful Depth of Field focused on Corgi's head
    camera.data.dof.use_dof = True
    camera.data.dof.aperture_fstop = 2.5 # Luscious blur for background
    camera.data.dof.focus_distance = 4.25

    bpy.context.scene.camera = camera

def main():
    """Executes the complete creation of the high-fidelity Corgi benchmark scene."""
    setup_render_engine()
    clean_scene()

    # Build parts sequentially
    materials = create_materials()
    corgi = build_corgi(materials)

    # Tilt the Corgi dynamically into flying space!
    corgi.location = (-0.2, -0.1, 0.3)
    corgi.rotation_euler = (math.radians(10), math.radians(-15), math.radians(30))

    ball = build_beach_ball(materials)
    build_environment(materials)
    add_lighting_and_sky()
    setup_camera()

if __name__ == "__main__":
    main()
```