Official Codebase of 3DCodeVerse
Python
graphics cookbooks: volume and physical-surface recipes; the SDF, sun, rain and sphere recipes fixed
gaoypeng7b63f83e79b5
diff --git a/harness/codeverse3d/prompts/glsl_shader/cookbook.md b/harness/codeverse3d/prompts/glsl_shader/cookbook.mdindex f015ee51..47de0974 100644--- a/harness/codeverse3d/prompts/glsl_shader/cookbook.md+++ b/harness/codeverse3d/prompts/glsl_shader/cookbook.md@@ -37,6 +37,62 @@ float warped(vec2 p, float t) {}```+## Volume lighting (smoke, clouds, fog)+These are transport helpers for a bounded raymarch, not a fluid simulation. Use world metres for+distance and inverse metres for extinction; density is a nonnegative multiplier. Accumulate front+to back as `colour += transmittance * (1.0-stepT) * litColour; transmittance *= stepT`, then composite+`colour + transmittance * background`. A light-direction density march supplies self-shadowing.+For `phaseHG`, cosTheta is the dot of the incoming and outgoing LIGHT TRAVEL directions; +1 is forward+scattering. If `rd` points from camera into the scene and `toSun` points toward the sun, use `dot(rd,toSun)`.+```glsl+float fbmVolume(vec3 p) {+ float value = 0.0, amplitude = 0.5;+ for (int i = 0; i < 5; i++) {+ value += amplitude * noise3(p);+ p = p.yzx * 2.03 + vec3(13.1, 7.7, 19.3); amplitude *= 0.5;+ }+ return value / 0.96875;+}+float beerTransmittance(float extinction, float distance) {+ return exp(-max(extinction, 0.0) * max(distance, 0.0));+}+float phaseHG(float cosTheta, float g) {+ g = clamp(g, -0.95, 0.95);+ float d = max(1.0 + g*g - 2.0*g*clamp(cosTheta, -1.0, 1.0), 1e-5);+ return (1.0-g*g) / (12.56637061 * d * sqrt(d));+}+```+The phase function integrates to one over the sphere. Do not silently omit its `1/(4*pi)` and then+compensate with exposure. See [PBRT's phase-function discussion](https://pbr-book.org/4ed/Volume_Scattering/Phase_Functions)+for direction conventions; this recipe uses travel directions, whereas PBRT's API uses two outward directions.++## Physical surface lighting (metal, dielectric, roughness)+Direct single-scattering GGX with correlated Smith visibility and Schlick Fresnel. Inputs are LINEAR;+`n`, `v` (toward camera) and `l` (toward light) are unit vectors in the same coordinate space. The+result includes the incident cosine. Supply actual light radiance; use an environment reflection for+indirect specular. This is a surface BRDF, without transmission, multiple scattering or area-light integration.+```glsl+vec3 fresnelSchlick(float cosine, vec3 f0) {+ return f0 + (vec3(1.0)-f0) * pow(1.0-clamp(cosine,0.0,1.0),5.0);+}+vec3 pbrDirect(vec3 albedo, float metallic, float roughness, vec3 n, vec3 v, vec3 l, vec3 radiance) {+ float nv = max(dot(n,v),0.0), nl = max(dot(n,l),0.0);+ if (nv <= 0.0 || nl <= 0.0) return vec3(0.0);+ vec3 h = normalize(v+l);+ float nh = max(dot(n,h),0.0), vh = max(dot(v,h),0.0);+ float a = pow(clamp(roughness,0.045,1.0),2.0), a2 = a*a;+ float d = nh*nh*(a2-1.0)+1.0;+ float distribution = a2 / max(3.14159265*d*d,1e-12);+ float visibility = 0.5 / max(nl*sqrt(nv*nv*(1.0-a2)+a2) + nv*sqrt(nl*nl*(1.0-a2)+a2),1e-7);+ metallic = clamp(metallic,0.0,1.0); albedo = clamp(albedo,0.0,1.0);+ vec3 f = fresnelSchlick(vh,mix(vec3(0.04),albedo,metallic));+ vec3 diffuse = (1.0-metallic)*(vec3(1.0)-f)*albedo/3.14159265;+ return (diffuse + f*distribution*visibility) * max(radiance,0.0) * nl;+}+```+Roughness changes the distribution and masking of microfacet reflections; a shiny colour alone cannot+replace it. See [PBRT's microfacet model](https://pbr-book.org/4ed/Reflection_Models/Roughness_Using_Microfacet_Theory).+## Palettes, tonemapping, grading```glslvec3 palette(float t, vec3 a, vec3 b, vec3 c, vec3 d) { return a + b * cos(6.28318 * (c * t + d)); }@@ -52,10 +108,21 @@ vec3 gamma(vec3 c) { return pow(max(c, 0.0), vec3(1.0 / 2.2)); }```glslfloat sdCircle(vec2 p, float r) { return length(p) - r; }float sdBox(vec2 p, vec2 b) { vec2 d = abs(p) - b; return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0); }-float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0); return length(pa - ba * h); }-float sdStar(vec2 p, float r, float n) { float a = atan(p.y, p.x), s = 6.28318 / n; a = mod(a + s * 0.5, s) - s * 0.5; return length(p) * cos(a) - r; }-float fill(float d) { return 1.0 - smoothstep(0.0, 1.5 / u_resolution.y, d); } // 1 px AA edge-float stroke(float d, float w) { return 1.0 - smoothstep(w, w + 1.5 / u_resolution.y, abs(d)); }+float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-12), 0.0, 1.0); return length(pa - ba * h); }+// A concave n-point star, outer radius r, inner radius 0.45*r; first tip points +x.+// Fold into one half-sector, then measure the actual outer-to-inner edge.+float sdStar(vec2 p, float r, float n) {+ if (r <= 0.0) return length(p);+ float halfSector = 3.14159265 / clamp(floor(n + 0.5), 2.0, 64.0);+ float angle = abs(mod(atan(p.y, p.x) + halfSector, 2.0 * halfSector) - halfSector);+ vec2 q = length(p) * vec2(cos(angle), sin(angle));+ vec2 a = vec2(r, 0.0), b = 0.45 * r * vec2(cos(halfSector), sin(halfSector));+ vec2 edge = b - a, fromTip = q - a;+ float side = edge.x * fromTip.y - edge.y * fromTip.x;+ return sdSegment(q, a, b) * (side >= 0.0 ? -1.0 : 1.0);+}+float fill(float d) { float aa = max(fwidth(d), 1e-6); return 1.0 - smoothstep(-0.5 * aa, 0.5 * aa, d); }+float stroke(float d, float w) { float aa = max(fwidth(d), 1e-6); return w <= 0.0 ? 0.0 : 1.0 - smoothstep(w - 0.5 * aa, w + 0.5 * aa, abs(d)); }float glow(float d, float k) { return exp(-k * max(d, 0.0)); }mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); }```@@ -65,7 +132,7 @@ mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); }float sdSphere(vec3 p, float r) { return length(p) - r; }float sdBox3(vec3 p, vec3 b) { vec3 q = abs(p) - b; return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0); }float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; }-float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); }+float smin(float a, float b, float k) { if (k <= 0.0) return min(a, b); float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); }float map(vec3 p) { // the scene: ground + bobbing blobsfloat ground = p.y + 1.0;vec3 q = p; q.xz = mod(q.xz + 2.0, 4.0) - 2.0; // repetition@@ -98,7 +165,7 @@ void mainImage(out vec4 fragColor, in vec2 fragCoord) {## Gradient sky, sun, stars, water```glslvec3 skyGrad(vec2 p) { return mix(vec3(0.95, 0.6, 0.35), vec3(0.1, 0.25, 0.6), smoothstep(-0.3, 0.6, p.y)); }-float sun(vec2 p, vec2 c, float r) { float d = length(p - c); return smoothstep(r, r * 0.8, d) + 0.3 * exp(-8.0 * d); }+float sun(vec2 p, vec2 c, float r) { float d = length(p - c); r = max(r, 1e-6); return 1.0 - smoothstep(r * 0.8, r, d) + 0.3 * exp(-8.0 * d); }// DENSE STARS: thousands of sub-pixel points, a few brighter; keep = fraction of cells that hold a star (0.2-0.3).// Two layers (density 160 and 70) read as a real sky; twenty twinkling sparkles do not (that version cost a run).float stars(vec2 p, float density, float keep) {@@ -109,21 +176,22 @@ float stars(vec2 p, float density, float keep) {return step(1.0 - keep, h) * exp(-d * d / (size * size)) * (0.35 + 0.65 * hash12(g + 9.0));}// usage: col += vec3(0.9, 0.95, 1.0) * (stars(p, 160.0, 0.22) * 0.55 + stars(p + 3.7, 70.0, 0.25) * 0.9);-float waterHeight(vec2 xz, float t) { return 0.05 * sin(xz.x * 4.0 + t * 1.5) + 0.03 * sin(xz.y * 6.0 - t * 1.1) + 0.04 * noise(xz * 3.0 + t * 0.4); }+float waterHeight(vec2 xz, float t) { return 0.05 * sin(xz.x * 4.0 + t * 1.5) + 0.03 * sin(xz.y * 6.0 - t * 1.1) + 0.04 * (noise(xz * 3.0 + t * 0.4) - 0.5); }// water colour: mix(deep, shallow, fresnel) + specular: pow(max(dot(reflect(-lig, n), -rd), 0.0), 64.0)```## Rain / drops on glass (grid cells + trails, refracted background)```glslvec2 dropsLayer(vec2 uv, float t, float scale) { // returns (mask, trail)- vec2 asp = vec2(2.0, 1.0); vec2 st = uv * scale * asp; vec2 id = floor(st);- float n = hash12(id); t += n * 6.28;- st.y += t * 0.25; id = floor(st); n = hash12(id); // scroll cells downward+ vec2 asp = vec2(2.0, 1.0); vec2 st = uv * scale * asp + vec2(0.0, t * 0.25);+ vec2 id = floor(st); float n = hash12(id); // identities move WITH the falling cellsvec2 f = fract(st) - 0.5;+ f.x += (hash12(id + 17.0) - 0.5) * 0.35;float w = sin(t + n * 6.28) * (0.5 - abs(f.y)) ; f.x += w * 0.3; // wobblevec2 d = f * vec2(1.0, 2.0);- float drop = smoothstep(0.1, 0.05, length(d));- float trail = smoothstep(0.1, 0.0, abs(f.x)) * smoothstep(0.5, -0.1, f.y) * step(0.0, f.y) * 0.5;+ float drop = 1.0 - smoothstep(0.05, 0.1, length(d));+ float trail = (1.0 - smoothstep(0.0, 0.1, abs(f.x))) *+ (1.0 - smoothstep(0.1, 0.5, f.y)) * smoothstep(0.02, 0.1, f.y) * 0.5;return vec2(drop, trail) * step(0.3, n);}// usage: vec2 dr = dropsLayer(uv, u_time, 8.0); vec2 off = dr.x * 0.03 * normalize(p + 1e-3); col = background(uv + off);@@ -144,7 +212,7 @@ vec3 bokehSoft(vec2 p, float t) {vec2 o = vec2(i, j); vec2 h = hash22(id + o); vec2 c = o + h - 0.5;float r = 0.12 + 0.12 * hash12(id + o + 7.0);float d = length(f - c);- float disc = exp(-d * d / (r * r)) * smoothstep(r * 1.6, r * 0.6, d); // soft core, soft rim+ float disc = exp(-d * d / (r * r)) * (1.0 - smoothstep(r * 0.6, r * 1.6, d)); // soft core, soft rimdisc *= 0.7 + 0.3 * sin(t * (0.5 + h.x) + h.y * 6.28); // gentle pulsingvec3 tint = mix(vec3(0.9, 0.6, 0.3), vec3(0.3, 0.6, 0.9), h.x) * (0.5 + 0.5 * h.y); // warm/cool, mutedacc += disc * tint * (0.28 + 0.18 * fl); // many small adds on a dark ground, never a flat filldiff --git a/harness/codeverse3d/prompts/opengl_python/cookbook.md b/harness/codeverse3d/prompts/opengl_python/cookbook.mdindex 38a6d561..50534065 100644--- a/harness/codeverse3d/prompts/opengl_python/cookbook.md+++ b/harness/codeverse3d/prompts/opengl_python/cookbook.md@@ -58,6 +58,9 @@ def look_at(eye, target, up=(0, 1, 0)):return mdef rot_y(a): c, s = math.cos(a), math.sin(a); return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]], dtype="f4")mvp = proj @ view @ model # then prog["u_mvp"].write(mvp.T.astype("f4").tobytes())+# With nonuniform scale, normals use inverse transpose, never mat3(model).+normal_matrix = np.linalg.inv(model[:3, :3]).T+prog["u_normal_matrix"].write(normal_matrix.T.astype("f4").tobytes())```## Textures (procedural data, noise, LUTs)@@ -99,6 +102,10 @@ void main() {Run horizontally (`u_dir = (1/w, 0)`) into FBO A, vertically (`(0, 1/h)`) into FBO B, at half resolution; composite `scene + k * blur`, tonemap `c/(1+c)`, gamma `pow(c, 1/2.2)`.## Lighting in GLSL (Blinn-Phong + rim + fog)+This short stylized lighting model is for sketches. For a realistic material, use the GGX+`pbrDirect` / `fresnelSchlick` functions in the GLSL cookbook's Physical surface lighting section;+keep all light and albedo inputs linear and tonemap once at the final output. Use the Volume+lighting helpers there for extinction and normalized phase functions in smoke/cloud raymarches.```glslvec3 n = normalize(v_normal); vec3 l = normalize(vec3(0.5, 0.9, 0.4)); vec3 v = normalize(u_cam - v_world);float diff = max(dot(n, l), 0.0); float spec = pow(max(dot(n, normalize(l + v)), 0.0), 48.0);@@ -127,7 +134,7 @@ def sphere_mesh(rings, sectors, r): # pos3 + normal3 interleaveddata += [r * n[0], r * n[1], r * n[2], *n]for j in range(rings):for i in range(sectors):- a = j * (sectors + 1) + i; idx += [a, a + sectors + 1, a + 1, a + 1, a + sectors + 1, a + sectors + 2]+ a = j * (sectors + 1) + i; idx += [a, a + 1, a + sectors + 1, a + 1, a + sectors + 2, a + sectors + 1]return np.array(data, dtype="f4"), np.array(idx, dtype="i4")```@@ -154,3 +161,6 @@ ctx.line_width = 1.0 # > 1 is unsupported on core profiles: draw quads for thi* Textures sampled with `texture()` need `.use(location=k)` every frame *and* `prog["u_tex"].value = k`.* Lines wider than 1 px and GL_QUADS do not exist in core profile; `ctx.wireframe = True` works for debugging only.* Half-float (`f2`) colour targets clip at ~65504 — tonemap before writing bright accumulations.+* When replacing resources, release each owned VAO, buffer, texture, framebuffer and program;+ a framebuffer does not own its attachments. The harness tears down the context at job end+ and has no `cleanup()` callback. Do not release its supplied context or final framebuffer.diff --git a/harness/codeverse3d/tracks/graphics.py b/harness/codeverse3d/tracks/graphics.pyindex de103c31..f485fe62 100644--- a/harness/codeverse3d/tracks/graphics.py+++ b/harness/codeverse3d/tracks/graphics.py@@ -86,6 +86,11 @@ PURPOSES: dict[str, str] = {"skyGrad": "dusk sky gradient by p.y", "sun": "sun disc with a soft halo","waterHeight": "water surface height (waves + noise) for reflections / normals","warped": "domain-warped fbm: billowy clouds, smoke, marble",+ "fbmVolume": "normalized five-octave 3D density field for bounded volumes",+ "beerTransmittance": "Beer extinction through a nonnegative distance; combine intervals multiplicatively",+ "phaseHG": "normalized Henyey-Greenstein phase; cosTheta uses light TRAVEL directions, +1 forward",+ "fresnelSchlick": "view-dependent RGB Fresnel reflectance from normal-incidence f0",+ "pbrDirect": "linear direct GGX surface lighting with correlated visibility, Fresnel and incident cosine","hash11": "1D hash 0..1", "hash12": "2D → float hash 0..1", "hash22": "2D → vec2 hash", "hash33": "3D → vec3 hash","noise": "smooth 2D value noise 0..1", "noise3": "3D value noise (volumes, time as z)","fbm": "6-octave rotated fbm", "ridged": "ridged fbm (mountains, veins)",diff --git a/harness/codeverse3d/tracks/prompting.py b/harness/codeverse3d/tracks/prompting.pyindex 7d3b2114..3dfe0d41 100644--- a/harness/codeverse3d/tracks/prompting.py+++ b/harness/codeverse3d/tracks/prompting.py@@ -174,7 +174,11 @@ COOKBOOK_SYNONYMS: dict[str, tuple[str, ...]] = {"galaxy": ("Gradient sky", "Light phenomena"), "nebula": ("Gradient sky", "Light phenomena"),"bokeh": ("Bokeh",), "city": ("Bokeh",), "neon": ("Bokeh",), "lights": ("Bokeh",),"rain": ("Rain",), "drops": ("Rain",), "glass": ("Rain",),- "cloud": ("Domain warping",), "clouds": ("Domain warping",), "smoke": ("Domain warping",),+ "cloud": ("Domain warping", "Volume lighting"), "clouds": ("Domain warping", "Volume lighting"),+ "smoke": ("Domain warping", "Volume lighting"), "fog": ("Volume lighting",),+ "volumetric": ("Volume lighting",), "metal": ("Physical surface lighting",),+ "metallic": ("Physical surface lighting",), "roughness": ("Physical surface lighting",),+ "pbr": ("Physical surface lighting",), "dielectric": ("Physical surface lighting",),"marble": ("Domain warping",),"tunnel": ("Raymarching",), "temple": ("Raymarching",), "corridor": ("Raymarching",), "3d": ("Raymarching",),"trail": ("Feedback",), "trails": ("Feedback",), "feedback": ("Feedback",),diff --git a/harness/tests/graphics/test_recipe_quality.py b/harness/tests/graphics/test_recipe_quality.pynew file mode 100644index 00000000..751c19df--- /dev/null+++ b/harness/tests/graphics/test_recipe_quality.py@@ -0,0 +1,86 @@+"""Executable numerical contracts for the recipes agents receive."""+from __future__ import annotations++import math+import re++import numpy as np+import pytest+from PIL import Image++from codeverse3d.languages.glsl_shader import compose+from codeverse3d.prompts import load_text+from codeverse3d.spatial.gl_render import GlHost, GlHostError+from codeverse3d.tracks.graphics import cookbook_functions, with_helpers++pytest.importorskip("moderngl")+++def test_sdf_transport_and_surface_response_on_real_gl(tmp_path):+ known = cookbook_functions(load_text("glsl_shader/cookbook.md"))+ requested = ("sdStar", "sdSegment", "sun", "dropsLayer", "bokehSoft", "beerTransmittance", "phaseHG", "pbrDirect")+ recipes = "\n\n".join(r.text for r in with_helpers([known[k] for k in requested], known))+ shader = """+void mainImage(out vec4 fragColor,in vec2 fragCoord) {+ float failures=0.0;+ float segment=sdSegment(vec2(.3,.4),vec2(0),vec2(0));+ if(isnan(segment)||abs(segment-.5)>1e-5) failures+=1.0;+ float halfSector=3.14159265/5.0;+ if(sdStar(.6*vec2(cos(halfSector),sin(halfSector)),1.0,5.0)<=0.0) failures+=1.0;+ if(abs(sdStar(vec2(0),1.0,5.0)+.45)>1e-5) failures+=1.0;+ if(abs(sdStar(vec2(2,0),1.0,5.0)-1.0)>1e-5) failures+=1.0;+ float a=beerTransmittance(.7,2.0),b=beerTransmittance(.7,3.0);+ if(abs(a*b-beerTransmittance(.7,5.0))>1e-6) failures+=1.0;+ if(beerTransmittance(.7,0.0)!=1.0) failures+=1.0;+ float phaseIntegral=0.0;+ for(int i=0;i<2048;i++) phaseIntegral+=phaseHG(-1.0+2.0*(float(i)+.5)/2048.0,.8)*12.56637061/2048.0;+ if(abs(phaseIntegral-1.0)>.002) failures+=1.0;+ if(phaseHG(1.0,.8)<=phaseHG(-1.0,.8)) failures+=1.0;+ vec3 n=vec3(0,0,1),v=normalize(vec3(.3,0,1)),l=normalize(vec3(-.2,.4,1));+ vec3 forward=pbrDirect(vec3(.7,.4,.2),.4,.35,n,v,l,vec3(1))/dot(n,l);+ vec3 reverse=pbrDirect(vec3(.7,.4,.2),.4,.35,n,l,v,vec3(1))/dot(n,v);+ if(length(forward-reverse)>1e-5) failures+=1.0;+ if(length(pbrDirect(vec3(1),0.0,.3,n,v,-n,vec3(1)))>0.0) failures+=1.0;+ vec3 integrated=vec3(0);+ for(int i=0;i<2048;i++) {+ float z=(float(i)+.5)/2048.0,angle=float(i)*2.39996323;+ vec3 light=vec3(sqrt(1.0-z*z)*vec2(cos(angle),sin(angle)),z);+ integrated+=pbrDirect(vec3(1),0.0,.5,n,n,light,vec3(1))*6.28318531/2048.0;+ }+ if(any(greaterThan(integrated,vec3(1.01)))||any(lessThan(integrated,vec3(.8)))) failures+=1.0;+ vec2 uv=fragCoord/u_resolution;+ vec2 rain=dropsLayer(uv,u_time,8.0);+ vec3 bokeh=bokehSoft(uv,u_time);+ float disc=sun(uv,vec2(.5),.1);+ if(any(isnan(rain))||any(isnan(bokeh))||isnan(disc)) failures+=1.0;+ if(any(lessThan(rain,vec2(0)))||any(greaterThan(rain,vec2(1)))) failures+=1.0;+ fragColor=vec4(min(failures,1.0),failures==0.0?1.0:0.0,failures/16.0,1.0);+}+"""+ try:+ result = GlHost(timeout_s=90).render_fragment_shader(+ compose(shader, recipes_src=recipes).source, tmp_path / "contracts",+ width=16, height=16, times=(0.0, 1.7))+ except GlHostError as exc:+ pytest.skip(f"OpenGL unavailable: {exc}")+ assert result.ok, result.error_message+ for frame in result.frames:+ assert frame.nan == frame.inf == 0+ pixels = np.asarray(Image.open(frame.path).convert("RGB"))+ assert np.all(pixels == [0, 255, 0]), pixels.max(axis=(0, 1)).tolist()+++def test_opengl_cookbook_sphere_winding_matches_its_outward_normals():+ text = load_text("opengl_python/cookbook.md")+ code = next(block for block in re.findall(r"```python\n(.*?)```", text, re.S)+ if "def sphere_mesh" in block)+ namespace = {"np": np, "math": math}+ exec(code, namespace)+ raw, indices = namespace["sphere_mesh"](12, 24, 2.0)+ vertices = raw.reshape(-1, 6)+ triangles = vertices[indices.reshape(-1, 3)]+ geometric = np.cross(triangles[:, 1, :3] - triangles[:, 0, :3],+ triangles[:, 2, :3] - triangles[:, 0, :3])+ nondegenerate = np.linalg.norm(geometric, axis=1) > 1e-6+ alignment = np.sum(geometric * triangles[:, :, 3:].mean(axis=1), axis=1)+ assert np.all(alignment[nondegenerate] > 0)