p5.js icon indicating copy to clipboard operation
p5.js copied to clipboard

[p5.js 2.0+ Bug Report]: Floats in strands shaders are always rounded to 4 decimals

Open davepagurek opened this issue 5 months ago • 19 comments

Most appropriate sub-area of p5.js?

  • [ ] Accessibility
  • [ ] Color
  • [ ] Core/Environment/Rendering
  • [ ] Data
  • [ ] DOM
  • [ ] Events
  • [ ] Image
  • [ ] IO
  • [ ] Math
  • [ ] Typography
  • [ ] Utilities
  • [x] WebGL
  • [x] WebGPU
  • [x] p5.strands
  • [ ] Build process
  • [ ] Unit testing
  • [ ] Internationalization
  • [ ] Friendly errors
  • [ ] Other (specify if possible)

p5.js version

2.3.0

Web browser and version

All

Operating system

All

Steps to reproduce this

In strands_glslBackend.js, we do this when converting number literals into shader code: https://github.com/processing/p5.js/blob/a5c9056fa2b3fb829a4e0187a9a9b1d7ad3700ab/src/webgl/strands_glslBackend.js#L273-L274

This means that if you include 0.00001 in your strands code, your shader code would be 0.0000. That seems like a problem. Is there any way we can do this in a more context-dependent way where we don't just add more decimals across the board for everything?

davepagurek avatar Jun 08 '26 17:06 davepagurek

happy to take this up @davepagurek !

harshiltewari2004 avatar Jun 08 '26 18:06 harshiltewari2004

Before actually writing code, do you have an idea for how to tackle this one?

davepagurek avatar Jun 08 '26 18:06 davepagurek

Took a look — the root cause is that float literals are serialized with node.value.toFixed(4) in both strands backends: strands_glslBackend.js (WebGL) and strands_wgslBackend.js (WebGPU), same line in each. So anything smaller than ~0.0001 collapses to 0.0000, and normal values get padded with trailing zeros. My thinking for a fix: instead of fixed-precision rounding, serialize the number in a way that preserves its actual value, then make sure the result still reads as a float literal (has a decimal point, or .0 for integer-valued floats). That avoids both the truncation and the padding, and doesn't bake in a fixed decimal count. The detail I'd want to get right is literal formatting per backend — e.g. whether exponent notation (1e-8) is acceptable in the GLSL version strands targets and in WGSL, or whether those need to be expanded. I'll confirm that against each backend rather than assume. Does that direction sound right to you, and do you want the fix to cover both backends in one PR, or keep them separate?

harshiltewari2004 avatar Jun 08 '26 18:06 harshiltewari2004

Right, I think the question is around how to do that serialization. I think if we can keep the method of serialization the same for each backend then that's ideal, less complexity to worry about

davepagurek avatar Jun 08 '26 18:06 davepagurek

Sounds good — keeping the serialization identical across both backends makes sense, I'll go that route. I'd like to take this one on if that works;I've got #8823 in review right now, so I'll start on this once that lands. happy to be assigned.

harshiltewari2004 avatar Jun 08 '26 18:06 harshiltewari2004

@davepagurek toFixed(4) cuts off small values. Instead, let JS decide the right precision with .toString(), and only add .0 if there's no decimal point for GLSL float typing. let s = node.value.toString(); if (!s.includes('.')) s += '.0'; If toString() returns something like 1e-7, use toFixed(10) and strip trailing zeros. GLSL doesn't do scientific notation. assign if valid

BHARATH0153 avatar Jun 11 '26 14:06 BHARATH0153

Hi @davepagurek — following up on this one. I think we'd settled the approach (value-preserving stringification, kept identical across both backends), with the one open detail being exponent-notation legality in GLSL ES 3.00 vs WGSL. Happy to dig into that and bring you a concrete proposal before writing any code — just wanted to confirm you're good with me picking it up once #8823 lands. Thank you!

harshiltewari2004 avatar Jun 13 '26 12:06 harshiltewari2004

Now that #8823 is merged, I'd like to pick this up. @davepagurek and I aligned on the approach earlier in this thread — replace the toFixed(4) literal serialization with a value-preserving stringification that still emits valid float-literal form, kept identical across the GLSL and WGSL backends. The one piece I want to settle before any code is the exact stringification that's valid in both targets — in particular whether exponent notation like 1e-8 is accepted by each. I'll investigate that and post a concrete proposal here for Dave to confirm. @ksen0 since strands is Dave's area and he's been away, would you be okay assigning this to me so I can get started on the investigation and proposal? Happy to hold for Dave's sign-off on the serialization specifics before writing anything.

harshiltewari2004 avatar Jun 19 '26 16:06 harshiltewari2004

Let's brainstorm a little more on the serialization method here before moving to a PR.

Based on the specs, it looks like exponent notation is allowed in both WGSL and GLSL, although it's worth confirming in WGSL that it is also accepted in practice -- I saw a github issue that was resolved in 2022 around whether or not you had to use e vs E, and whether or not a decimal is required before it. Whether or not that's valid would likely change the way we deal with parsing, so if someone has time to check and report back here, that'd be appreciated!

As for the input, when js numbers are converted to strings, MDN says:

Scientific notation is used if radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 10^21 or less than 10^-6.

The radix 10 thing is true by default unless specifically changed, so you can ignore that bit. One can call .toExponential() on a variable to normalize the input if that makes parsing easier. Some thoughts on that:

  • I'm not sure if its syntax for non-negative exponents, e.g. 1e+1 or 0e+0, is valid GLSL/WGSL -- it looks like they don't use the +.
  • Values like 0.123 become 1.23e-1, which I think would be valid, so we could leave it? Aesthetically it's not as concise, but correctness is probably the primary concern, so one possibility is to use exponential notation for now and maybe come back later to make the numbers more readable if it's not obvious when to use which.

davepagurek avatar Jun 20 '26 16:06 davepagurek

Did some digging on the grammar — good news, GLSL ES 3.0 and WGSL line up and they're more permissive than we worried:

GLSL ES 3.0 WGSL
Exponent notation ✓ ✓
Decimal required before e No No
e / E both both
+ in exponent (1e+1) ✓ ✓
f/suffix required No No (abstract-float → f32)

Sources: GLSL ES 3.0 spec §4.1.4 — FLOATING_CONSTANT : Digit+ ExponentPart …, ExponentPart: [eE] [+-]? Digit+; and the WGSL decimal_float_literal rule [0-9]+ [eE][+-]?[0-9]+ [fh]? (as implemented in naga's number parser). So 5e-1 (no decimal) and 1e+1 (with the +) are both valid in each — meaning JS .toExponential() output is accepted as-is in both, no +-stripping or decimal fixup needed. On the in-practice question: naga (Firefox/wgpu) feeds the matched token to Rust's float parser, which accepts the +, and Tint (Chrome) follows the same spec grammar — happy to run a browser smoke test too if you'd like.

One gotcha for any approach: we have to keep integer-valued literals in float form — a bare 5 is an int literal, so it'd need 5.0 (the current toFixed(4) gets this from the padding).

Two options that both fix the precision loss and stay identical across backends:

  1. value.toExponential() for everything — uniform and correct, a bit verbose (0.5 → 5e-1).
  2. value.toString(), appending .0 when the result is a bare integer — same correctness, more readable (0.5 → 0.5, 0.123 → 0.123, 5 → 5.0); toString only switches to exponent form at extreme magnitudes, which we've confirmed is valid.

I lean (2) for readability, but (1) is the minimal version you floated. Either works for me — which do you prefer? I'll implement once we settle on one.

harshiltewari2004 avatar Jun 20 '26 17:06 harshiltewari2004

Hi @davepagurek — no urgency, just keeping this on your radar. It's only waiting on your pick between the two options above (uniform toExponential() vs. toString() with a float-form fixup for integers). Happy to go with whichever you prefer — I lean slightly toward (2) for readability if you don't have a strong preference — and I'll get the PR up as soon as you give the nod. Thanks!

harshiltewari2004 avatar Jun 27 '26 19:06 harshiltewari2004

Do we have a reliable way of detecting an integer in order to do option 2? e.g. if Number.isInteger works, then let's go with that. Otherwise, if it requires us to do some string parsing etc in order to tell if it's an integer, then it's maybe better to just go directly to toExponential.

davepagurek avatar Jul 13 '26 21:07 davepagurek

Number.isInteger is reliable (built-in, no parsing) — but I tested the edges and there's one trap: for integers ≥ 1e21, JS toString() itself switches to exponent form. So Number.isInteger(1e21) is true, but appending .0 to its string gives 1e+21.0, which is invalid in both GLSL and WGSL (exponent must come last).

value Number.isInteger toString() naive +'.0'
5 true 5 5.0 ✓
0.5 false 0.5 0.5 ✓
1e21 true 1e+21 1e+21.0 ✗ invalid

The condition that's actually correct isn't "is the value an integer" but "does the string already have a . or e":

const s = value.toString();
return /[.eE]/.test(s) ? s : s + '.0';

That's a single regex test on the output rather than any real parsing — but if that still counts as more string-inspection than you'd like, I'm equally happy to go with toExponential() for everything. Both handle all the cases above correctly; it's just readability vs. uniformity. Which would you like?

harshiltewari2004 avatar Jul 13 '26 22:07 harshiltewari2004

Hi @davepagurek !— no rush. This is down to a yes/no on the last comment: is the one-line regex check (/[.eE]/.test(s) ? s : s + '.0') acceptable, or would you rather I just go with toExponential() everywhere? Either is fine on my end — I'll open the PR the moment you pick one.

harshiltewari2004 avatar Jul 18 '26 20:07 harshiltewari2004

Following up on my own question — since Number.isInteger alone doesn't cover the ≥1e21 case (where toString() is already in exponent form), I'll take the fallback and go with toExponential() throughout, and put a PR up for it. Easy to switch to the more readable toString + ".0" form in review if you'd prefer.

harshiltewari2004 avatar Aug 31 '26 21:08 harshiltewari2004

Hi @davepagurek — the approach here is settled on my end; I'll go with toExponential(), the fallback you suggested above. Could you assign this one to me? I'd like the assignment in place before I open the PR so it isn't auto-closed as unassigned — happy to get it up quickly once it's mine.

harshiltewari2004 avatar Sep 27 '26 19:09 harshiltewari2004

building on @harshiltewari2004's option 2, i don't think the 1e21 case actually rules out Number.isInteger: Number.isInteger(v) ? v.toFixed(1) : String(v) avoids inspecting the string, since toFixed() already switches to exponent form there. the exponent forms i checked behaved fine on both backends.

also noticed raw numeric args take a separate path and can be emitted as bare integers, so abs(3000000000) differs between webgl and webgpu. might be worth routing both through one shared float-literal formatter.

bhabishnu avatar Nov 11 '26 11:11 bhabishnu

Sorry for the delay @harshiltewari2004, are you still interested in working on this? We can go with @bhabishnu's extension of your approach.

davepagurek avatar Nov 14 '26 16:11 davepagurek

I will be very happy to be assigned and will open a PR for it as soon as my open PRs get merged @davepagurek !

harshiltewari2004 avatar Nov 14 '26 17:11 harshiltewari2004