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

Standardize internal UV handling across WebGL geometry consumers

Open Srinidhi444 opened this issue 1 month ago • 10 comments

Increasing access

This improvement would make WebGL geometry behavior more consistent and predictable for users working with custom geometries, imported models, and textures.

Currently, different UV representations can lead to unexpected behavior in certain geometry operations. Handling these representations consistently would reduce confusing rendering and export issues, making it easier for beginners and experienced users to work with textured 3D models.

Most appropriate sub-area of p5.js?

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

Feature enhancement details

Problem

Currently, p5.Geometry UV coordinates can be represented in two different formats:

Flat UVs:

[0, 0, 1, 0, 1, 1, 0, 1]

Nested UV pairs:

[[0, 0], [1, 0], [1, 1], [0, 1]]

Although both representations are supported in parts of the rendering pipeline, not all internal consumers handle them consistently.

As discussed in #9288, computeNormals(SEGMENTED) previously assumed that UVs were always stored in a flat array. When geometries contained nested UV pairs, duplicating vertices could copy incorrect UV coordinates. This was fixed locally in the SEGMENTED implementation by flattening UVs before processing them.

However, this points to a broader inconsistency in how UV data is handled internally.

Current behavior

As @bhabishnu investigated, nested UVs appear in several p5-owned paths, including:

  • arc() and ellipse()
  • quad()
  • OBJ/STL loaders

Other geometry paths use flat UV arrays, and buildGeometry() can combine geometry data using both representations.

The renderer currently normalizes UVs before uploading them to the GPU using arr.flat():

https://github.com/processing/p5.js/blob/24a68d5c19eb70931c9a08c41b43a658978835f3/src/core/p5.Renderer3D.js#L302-L304

However, other consumers may access the original UV array without normalization. One example identified during the discussion is saveObj(), which can produce incorrect results when given nested UVs.

Proposed enhancement

Introduce a consistent internal way for geometry consumers to access normalized UV coordinates, regardless of how the UV data is originally stored.

One possible approach would be a shared internal helper that provides a flat representation when reading UVs:

const flatUVs = geometry.getFlatUVs();

This is only an illustrative API, not a finalized implementation proposal.

Internal consumers such as computeNormals(), saveObj(), and other geometry utilities could use this shared normalization path rather than implementing their own assumptions or conversions.

Backward compatibility

Changing every geometry producer to store flat UVs directly may break existing code that accesses nested UV pairs, for example:

model.uvs[i][1]

It may therefore be safer to preserve the existing stored representation while standardizing how internal consumers read UV data.

Areas to investigate

  • Identify internal consumers that assume UV coordinates are always flat.
  • Investigate and add regression coverage for saveObj() with nested UVs.
  • Evaluate a shared internal UV normalization helper.
  • Ensure flat, nested, and mixed UV representations are handled consistently.
  • Consider performance implications and backward compatibility.
  • Add appropriate unit tests.

References

Srinidhi444 avatar Oct 17 '26 05:10 Srinidhi444

Hey @bhabishnu, if you have any additional repros or technical details, please share them in the comments. They would really help me investigate the issue more thoroughly and work toward a fix.

Once I've investigated the issue and come up with a proposed approach, I'll share it with @davepagurek for feedback. If the approach looks good, I'll proceed with the implementation.

Srinidhi444 avatar Oct 17 '26 05:10 Srinidhi444

Hey @davepagurek, I've been investigating the inconsistent UV representations across WebGL geometry and wanted to share what I've found so far, along with a possible approach before starting implementation.

1. UV producers

I found that different parts of the codebase generate UV coordinates in different formats:

Flat UVs ([u, v, u, v, ...]):

  • triangle(), rect(), cylinder(), plane(), box(), ellipsoid()/sphere(), and torus() in 3d_primitives.js.
  • Immediate-mode geometry creation and tessellation in ShapeBuilder.js.
  • Glyph geometry in text.js.

Nested UVs ([[u, v], [u, v], ...]):

  • arc()/ellipse() and quad() in 3d_primitives.js.
  • OBJ and STL model loaders in loading.js.

Mixed UVs:

  • GeometryBuilder.addGeometry() copies UV entries directly without normalization, so combining geometries with different representations can produce arrays containing both scalar values and nested pairs.

2. UV consumers

I also checked how different parts of the codebase read and process UV coordinates.

Consumers that already normalize UVs:

  • p5.Renderer3D.js flattens UVs before uploading them to WebGL buffers.
  • computeTangents() flattens UVs before indexing individual coordinates.
  • flipU() and flipV() flatten UVs before modifying them.
  • computeNormals(SEGMENTED) flattens UVs before duplicating vertex attributes, following the fix in #9288.

Consumers that assume flat UVs:

  • saveObj() directly accesses this.uvs[i] and this.uvs[i + 1], advancing by two elements at a time.
  • Some UV processing paths in ShapeBuilder.js index UVs as scalar pairs. I haven't confirmed a failing case there yet.

The renderer handles flat, nested, and mixed UVs through normalization before buffer upload, but consumers accessing geometry.uvs directly don't necessarily have that protection.

3. Confirmed saveObj() bug

I added three local regression tests that capture the OBJ output and verify its vt records:

  • Flat UVs: Passed.
  • Nested UVs: Failed.
  • Mixed UVs: Failed.

For example, given:

[[0, 0], [1, 0], [0, 1]]

The expected output is:

vt 0 0
vt 1 0
vt 0 1

But saveObj() currently produces:

vt 0,0 1,0
vt 0,1 undefined

Mixed UVs also produce malformed vt records. This confirms an actual OBJ serialization issue rather than just an inconsistency in the internal representation.

4. Additional multipart UV issue

Thanks to @bhabishnu for sharing another reproduction involving single-material and multi-material OBJ files.

With a single-material model, flipU() and flipV() work correctly. With a multi-material model, the aggregate geometry.uvs changes, but the rendered texture doesn't flip because the UVs stored in geometry.parts remain unchanged.

I looked further into how material parts are constructed:

  • Single-material geometries: p5.Geometry._wrapInSinglePart() sets this.parts = [this], so the geometry and its rendered part are the same object.
  • Multi-material OBJ models: loading.js constructs separate GeometryPart instances with their own UV arrays and local vertex indices.
  • Multi-material buildGeometry() results: GeometryBuilder._addToCurrentPart() also constructs separate parts and copies UV entries into them.
  • Rendering: p5.Renderer3D.js draws the individual parts, rather than relying only on the aggregate geometry's UV data.

Currently, flipU() and flipV() update only this.uvs. This explains why they work on single-material geometry but can fail to affect rendering when separate material parts exist.

I also confirmed that GeometryPart is an independent class rather than a subclass of p5.Geometry, which is relevant when deciding where to place shared UV utilities.

5. Updated proposed approach

Based on these findings, I think we need to handle two related but separate concerns.

A. Consistent UV normalization for internal consumers

Introduce a small shared internal utility that returns flat UV coordinates regardless of whether the input is flat, nested, or mixed.

Conceptually:

function getFlatUVs(uvs) {
  return uvs.flat();
}

A standalone utility seems preferable to a method exclusively on p5.Geometry, since both p5.Geometry and GeometryPart can contain UV data.

Consumers such as saveObj(), computeTangents(), and computeNormals(SEGMENTED) could use this shared normalization path instead of duplicating conversion logic.

The helper would not mutate the original UV array, avoiding changes to the stored representation and preserving compatibility with existing code that accesses nested UV pairs.

B. Synchronizing UV modifications across material parts

For flipU() and flipV(), normalization alone isn't sufficient. These methods also need to update the UV coordinates of the parts actually used during rendering.

I'm considering a shared internal flip operation that updates the aggregate geometry and each distinct material part, while ensuring that single-material geometries (parts[0] === geometry) aren't transformed twice.

This should address the multipart reproduction without changing existing single-material behavior. I'll also verify how part-specific buffer updates are handled before implementation.

6. Next steps

I'm planning to start with the confirmed saveObj() issue and its regression tests, introduce the shared normalization utility, and then address multipart UV flipping with dedicated tests for single-material and multi-material models.

@davepagurek, does this updated approach sound reasonable to you? I'd appreciate your feedback before proceeding with the implementation.

Srinidhi444 avatar Oct 18 '26 05:10 Srinidhi444

@Srinidhi444 thanks for tagging me! I did find one more repro while going through the UV paths.

I attached the fixtures I used: one.obj is the single-material control, and two.obj is the same geometry split across two materials, both using the same quadrant texture.

multipart-uv-flip-repro.zip

With one.obj, flipU() / flipV() work as expected. With two.obj, the aggregate geometry.uvs changes, but the rendered result doesn’t because the UVs in geometry.parts stay unchanged.

Relevant paths: https://github.com/processing/p5.js/blob/24a68d5c19eb70931c9a08c41b43a658978835f3/src/webgl/p5.Geometry.js#L645-L652 https://github.com/processing/p5.js/blob/24a68d5c19eb70931c9a08c41b43a658978835f3/src/core/p5.Renderer3D.js#L611-L635

So the shared normalization helper looks good for read-side consumers, but flipU() / flipV() will still need to keep the part UVs in sync separately.

bhabishnu avatar Oct 18 '26 10:10 bhabishnu

5. @Srinidhi444 thanks for tagging me! I did find one more repro while going through the UV paths. I attached the fixtures I used: one.obj is the single-material control, and two.obj is the same geometry split across two materials, both using the same quadrant texture. multipart-uv-flip-repro.zip With one.obj, flipU() / flipV() work as expected. With two.obj, the aggregate geometry.uvs changes, but the rendered result doesn’t because the UVs in geometry.parts stay unchanged. Relevant paths: https://github.com/processing/p5.js/blob/24a68d5c19eb70931c9a08c41b43a658978835f3/src/webgl/p5.Geometry.js#L645-L652

https://github.com/processing/p5.js/blob/24a68d5c19eb70931c9a08c41b43a658978835f3/src/core/p5.Renderer3D.js#L611-L635

So the shared normalization helper looks good for read-side consumers, but `flipU()` / `flipV()` will still need to keep the part UVs in sync separately.

Hey @bhabishnu thanks for the help appreciate it

Srinidhi444 avatar Oct 21 '26 11:10 Srinidhi444

I think your approach makes sense. The fact that UVs could be on a single geometry or a part makes this a little more complicated, and I'm wondering if maybe we need a slight cleanup on Geometry/GeometryPart? Looking through the code:

This is less focused on just the uvs issue, but I wonder if possibly it'd make sense to do a slight refactor here to clean this up in the process. Here are my thoughts:

  • Maybe we put almost all geometry functionality in GeometryPart and Geometry extends GeometryPart mostly to add the this.parts array and the constructor callback function
  • Then we put any gating in the renderer inside the part loop instead of outside

davepagurek avatar Oct 21 '26 13:10 davepagurek

Hey @davepagurek, it took me a little time to understand the architecture, but I think your approach makes sense!

From what I understand, a Geometry can contain multiple GeometryPart objects, and both classes currently share much of the same geometry data and functionality. I agree that moving the common properties and methods into GeometryPart and having Geometry extend it would make the structure cleaner and reduce duplication.

Regarding the other points:

  • Edges: I noticed that edges are currently stored only on the top-level Geometry. Do you think we should move them into GeometryPart as part of the refactor, or keep them at the top level since strokes are handled separately?
  • Renderer gating: I agree that checking the top-level vertex count before rendering parts isn't ideal. Moving the vertex-count check inside the parts loop would allow each part to be evaluated independently, even if the parent geometry has no vertices.

Please let me know if I've misunderstood anything.

If we're aligned on this approach, I'd be happy to work on the cleanup first. Would you prefer that I open a separate issue and PR for the Geometry/GeometryPart refactor, then return to the UV normalization and multipart flipping fixes in #9304 once the cleanup is merged?

Srinidhi444 avatar Oct 21 '26 14:10 Srinidhi444

Hmm, right, for edges they do not currently go through the same part structure. I think this means that currently multipart geometry would not be able to work with edges unless all the edge vertices are present in the top-level geometry? So that seems worth correcting.

This does feel like a big enough task that we maybe want to make a new issue, tackle that first, and then hopefully that makes this one easier as a follow-up (or in the same PR if it looks like the incremental code for it would be fairly simple, either works!) If you make an issue for this I can assign it to you.

davepagurek avatar Oct 21 '26 14:10 davepagurek

9. Hmm, right, for edges they do not currently go through the same part structure. I think this means that currently multipart geometry would not be able to work with edges unless all the edge vertices are present in the top-level geometry? So that seems worth correcting. This does feel like a big enough task that we maybe want to make a new issue, tackle that first, and then hopefully that makes this one easier as a follow-up (or in the same PR if it looks like the incremental code for it would be fairly simple, either works!) If you make an issue for this I can assign it to you.

Hey @davepagurek, I've opened the new issue as discussed! I'll see if the UV fixes can be included in the same PR without making it too large. Otherwise, I'll handle them in a separate PR.

I do think the cleanup will make the overall architecture cleaner, although I'm not sure how much it will directly help with the UV representation inconsistencies, since those mainly come from how different functions produce and consume UVs. But let's see how things look once the refactor is done!

Srinidhi444 avatar Oct 21 '26 15:10 Srinidhi444

@Srinidhi444 I tested a few more things around this

flipU() / flipV() don't set dirtyFlags, so if the model was already drawn once the flip never shows on screen (works fine if you flip before the first draw). I checked this on WebGL, and flipU() on WebGPU too, so the fix here should mark the uvs dirty as well

saveObj() also breaks on any textured OBJ you load and re-save, not just hand made arrays, textured.obj gives vt 0,1 1,1

and on keeping nested uvs for back compat, flipU() already turns them flat (model.uvs[0] goes from [0,1] to 1)

cc @davepagurek

aashu2006 avatar Oct 21 '26 17:10 aashu2006

Thanks @aashu2006 for investigating this further! I hadn't considered the dirty-flag issue, so that's a really useful catch, especially since it also affects WebGPU.

I'll make sure we account for marking UV buffers dirty when implementing the flip fixes, including for individual material parts.

Good point about flipU() already converting nested UVs to flat arrays as well. Will make sure to keep that in mind during fixing.

Srinidhi444 avatar Oct 21 '26 18:10 Srinidhi444