Regression: Mesh method from_pydata in Python API does not work with quads and tris #111117

Closed
opened 2023-08-14 16:26:08 +02:00 by Alexander Milovsky · 5 comments

System Information
Operating system: Windows-10-10.0.22621-SP0 64 Bits
Graphics card: GeForce GTX 1050/PCIe/SSE2 NVIDIA Corporation 4.6.0 NVIDIA 442.19

Blender Version
Broken: version: 4.0.0 Alpha, branch: main, commit date: 2023-08-14 04:21, hash: deb4aa88b04a
Worked: 3.6.1

Caused by a280e8a68c

Short description of error
Mesh method from_pydata in Python API does not work on polygons with variable vertex count (quads and tris for example)

Exact steps for others to reproduce the error
Put this Python-code into the Console on the Scripting tab:

import bpy
vertices = [(0, 0, 0), (1, 0, 0), (2, 0, 0), (0, 1, 0), (1, 1, 0), (2, 1, 0)]
faces = [(0, 1, 4, 3), (1, 2, 5)]  # two polygons: quad and tris

mesh = bpy.data.meshes.new('test_mesh')
mesh.from_pydata(vertices, [], faces)  # produces error in Blender 4.0 Alpha
mesh.update()

obj = bpy.data.objects.new('test_obj', mesh)
bpy.context.scene.collection.objects.link(obj) 
**System Information** Operating system: Windows-10-10.0.22621-SP0 64 Bits Graphics card: GeForce GTX 1050/PCIe/SSE2 NVIDIA Corporation 4.6.0 NVIDIA 442.19 **Blender Version** Broken: version: 4.0.0 Alpha, branch: main, commit date: 2023-08-14 04:21, hash: `deb4aa88b04a` Worked: 3.6.1 Caused by a280e8a68c **Short description of error** Mesh method from_pydata in Python API does not work on polygons with variable vertex count (quads and tris for example) **Exact steps for others to reproduce the error** Put this Python-code into the Console on the Scripting tab: ```Py import bpy vertices = [(0, 0, 0), (1, 0, 0), (2, 0, 0), (0, 1, 0), (1, 1, 0), (2, 1, 0)] faces = [(0, 1, 4, 3), (1, 2, 5)] # two polygons: quad and tris mesh = bpy.data.meshes.new('test_mesh') mesh.from_pydata(vertices, [], faces) # produces error in Blender 4.0 Alpha mesh.update() obj = bpy.data.objects.new('test_obj', mesh) bpy.context.scene.collection.objects.link(obj) ```
Alexander Milovsky added the
Type
Report
Priority
Normal
Status
Needs Triage
labels 2023-08-14 16:26:08 +02:00
Iliya Katushenock added the
Interest
Modeling
Interest
Python API
labels 2023-08-14 16:28:28 +02:00
Iliya Katushenock changed title from Mesh method from_pydata in Python API does not work with quads and tris to Regression: Mesh method from_pydata in Python API does not work with quads and tris 2023-08-14 16:28:35 +02:00
Member

I think this may be the same issue as blender/blender-addons#104762.

I'm of the opinion this is a bug with Blender though:

The raised error is:

Error: Python: Traceback (most recent call last):
  File "\Text", line 85, in <module>
  File "D:\Downloads\temp\blender-4.0.0-alpha+main.aebc743bf1c7-windows.amd64-release\4.0\scripts\modules\bpy_types.py", line 627, in from_pydata
    self.polygons.foreach_set("vertices", vertex_indices)
TypeError: foreach_get(attr, sequence) sequence length mismatch given 7, needed 8

I copied the from_pydata function and added some print statements directly before the line that raises the TypeError.

    print(len(self.loops))
    print(loop_starts)
    for p in mesh.polygons:
        print(p.loop_total)
        print(len(p.vertices))
    self.polygons.foreach_set("vertices", vertex_indices)

This prints

7
(0, 4)
4
4
3
3

So individually, it seems to me that 7 is the length Blender should be checking for and that Blender saying it should be 8 is incorrect.

I guess the changes in a280e8a68c might have identified an issue with using foreach_set with MeshPolygon.vertices that has been present but unnoticed for some time.

In this case, as a workaround, it works if I replace
self.polygons.foreach_set("vertices", vertex_indices)
with
self.loops.foreach_set("vertex_index", vertex_indices)
because polygons and loops (corners) are now always in the same order. So long as the mesh is valid (every loop belongs to exactly one polygon and every polygon's loop_start is in-bounds), MeshPolygon.vertices accessed through foreach_set is effectively a shortcut for iterating through the mesh's loops and setting each loop's vertex_index.

New script with comments:

import bpy
vertices = [(0, 0, 0), (1, 0, 0), (2, 0, 0), (0, 1, 0), (1, 1, 0), (2, 1, 0)]
faces = [(0, 1, 4, 3), (1, 2, 5)]  # two polygons: quad and tris


def from_pydata(self, vertices, edges, faces, shade_flat=True):
    from itertools import chain, islice, accumulate

    face_lengths = tuple(map(len, faces))

    # NOTE: check non-empty lists by length because of how `numpy` handles truth tests, see: #90268.
    vertices_len = len(vertices)
    edges_len = len(edges)
    faces_len = len(faces)

    self.vertices.add(vertices_len)
    self.edges.add(edges_len)
    self.loops.add(sum(face_lengths))
    self.polygons.add(faces_len)

    self.vertices.foreach_set("co", tuple(chain.from_iterable(vertices)))
    self.edges.foreach_set("vertices", tuple(chain.from_iterable(edges)))

    vertex_indices = tuple(chain.from_iterable(faces))
    loop_starts = tuple(islice(chain([0], accumulate(face_lengths)), faces_len))

    self.polygons.foreach_set("loop_start", loop_starts)
    
    print(len(self.loops))
    print(loop_starts)
    for p in self.polygons:
        print(p.loop_total)
        print(len(p.vertices))
    
    # Error occurs
    self.polygons.foreach_set("vertices", vertex_indices)
    # If the mesh is valid, using foreach_set with MeshPolygon.vertices is effectively the
    # same as using foreach_set with MeshLoop.vertex_index
    #self.loops.foreach_set("vertex_index", vertex_indices)

    if shade_flat:
        self.shade_flat()

    if edges_len or faces_len:
        self.update(
            # Needed to either:
            # - Calculate edges that don't exist for polygons.
            # - Assign edges to polygon loops.
            calc_edges=bool(faces_len),
            # Flag loose edges.
            calc_edges_loose=bool(edges_len),
        )


mesh = bpy.data.meshes.new('test_mesh')
from_pydata(mesh, vertices, [], faces)
I think this may be the same issue as https://projects.blender.org/blender/blender-addons/issues/104762. I'm of the opinion this is a bug with Blender though: The raised error is: ``` Error: Python: Traceback (most recent call last): File "\Text", line 85, in <module> File "D:\Downloads\temp\blender-4.0.0-alpha+main.aebc743bf1c7-windows.amd64-release\4.0\scripts\modules\bpy_types.py", line 627, in from_pydata self.polygons.foreach_set("vertices", vertex_indices) TypeError: foreach_get(attr, sequence) sequence length mismatch given 7, needed 8 ``` I copied the `from_pydata` function and added some print statements directly before the line that raises the `TypeError`. ```py print(len(self.loops)) print(loop_starts) for p in mesh.polygons: print(p.loop_total) print(len(p.vertices)) self.polygons.foreach_set("vertices", vertex_indices) ``` This prints ``` 7 (0, 4) 4 4 3 3 ``` So individually, it seems to me that 7 is the length Blender should be checking for and that Blender saying it should be 8 is incorrect. I guess the changes in https://projects.blender.org/blender/blender/commit/a280e8a68c15ee3ec0978fb594b29d083fd2bcd6 might have identified an issue with using `foreach_set` with `MeshPolygon.vertices` that has been present but unnoticed for some time. In this case, as a workaround, it works if I replace `self.polygons.foreach_set("vertices", vertex_indices)` with `self.loops.foreach_set("vertex_index", vertex_indices)` because polygons and loops (corners) are now always in the same order. So long as the mesh is valid (every loop belongs to exactly one polygon and every polygon's `loop_start` is in-bounds), `MeshPolygon.vertices` accessed through `foreach_set` is effectively a shortcut for iterating through the mesh's loops and setting each loop's `vertex_index`. New script with comments: ```py import bpy vertices = [(0, 0, 0), (1, 0, 0), (2, 0, 0), (0, 1, 0), (1, 1, 0), (2, 1, 0)] faces = [(0, 1, 4, 3), (1, 2, 5)] # two polygons: quad and tris def from_pydata(self, vertices, edges, faces, shade_flat=True): from itertools import chain, islice, accumulate face_lengths = tuple(map(len, faces)) # NOTE: check non-empty lists by length because of how `numpy` handles truth tests, see: #90268. vertices_len = len(vertices) edges_len = len(edges) faces_len = len(faces) self.vertices.add(vertices_len) self.edges.add(edges_len) self.loops.add(sum(face_lengths)) self.polygons.add(faces_len) self.vertices.foreach_set("co", tuple(chain.from_iterable(vertices))) self.edges.foreach_set("vertices", tuple(chain.from_iterable(edges))) vertex_indices = tuple(chain.from_iterable(faces)) loop_starts = tuple(islice(chain([0], accumulate(face_lengths)), faces_len)) self.polygons.foreach_set("loop_start", loop_starts) print(len(self.loops)) print(loop_starts) for p in self.polygons: print(p.loop_total) print(len(p.vertices)) # Error occurs self.polygons.foreach_set("vertices", vertex_indices) # If the mesh is valid, using foreach_set with MeshPolygon.vertices is effectively the # same as using foreach_set with MeshLoop.vertex_index #self.loops.foreach_set("vertex_index", vertex_indices) if shade_flat: self.shade_flat() if edges_len or faces_len: self.update( # Needed to either: # - Calculate edges that don't exist for polygons. # - Assign edges to polygon loops. calc_edges=bool(faces_len), # Flag loose edges. calc_edges_loose=bool(edges_len), ) mesh = bpy.data.meshes.new('test_mesh') from_pydata(mesh, vertices, [], faces) ```

I can confirm the problem, and indeed it is the same as blender/blender-addons#104762

However, since this report is in the repository that contains the affected code, I'm confirming it here.

It is caused by a280e8a68c. That commit does the size check based only on the size of the first element. So in the case of polygons in this report, the value will be 2 * 4 (number of faces multiplied by the number of vertices of the first face).

To fix the check, it would be necessary to sum the size of each individual element. But this can penalize the performance of the foreach function.

Maybe a280e8a68c has to be reverted for now :\

Cc @Baardaap, @lichtwerk

I can confirm the problem, and indeed it is the same as blender/blender-addons#104762 However, since this report is in the repository that contains the affected code, I'm confirming it here. It is caused by a280e8a68c. That commit does the size check based only on the size of the first element. So in the case of polygons in this report, the value will be 2 * 4 (number of faces multiplied by the number of vertices of the first face). To fix the check, it would be necessary to sum the size of each individual element. But this can penalize the performance of the `foreach` function. Maybe a280e8a68c has to be reverted for now :\ Cc @Baardaap, @lichtwerk
Member

Will summon reviewers of #109179 here to discuss...

CC @brecht
CC @HooglyBoogly

Will summon reviewers of https://projects.blender.org/blender/blender/pulls/109179 here to discuss... CC @brecht CC @HooglyBoogly
Member

The fix proposed of just setting the corner vertex indices seems right to me in theory, thanks for looking into this.

The fix proposed of just setting the corner vertex indices seems right to me in theory, thanks for looking into this.

I can maybe partially revert a280e8a68c. Just revert the check causing the problem and not the added code which is needed to fix #107416

I can maybe partially revert a280e8a68c. Just revert the check causing the problem and not the added code which is needed to fix #107416
Blender Bot added
Status
Resolved
and removed
Status
Confirmed
labels 2023-10-01 00:18:00 +02:00
Sign in to join this conversation.
No Label
Interest
Alembic
Interest
Animation & Rigging
Interest
Asset Browser
Interest
Asset Browser Project Overview
Interest
Audio
Interest
Automated Testing
Interest
Blender Asset Bundle
Interest
BlendFile
Interest
Collada
Interest
Compatibility
Interest
Compositing
Interest
Core
Interest
Cycles
Interest
Dependency Graph
Interest
Development Management
Interest
EEVEE
Interest
EEVEE & Viewport
Interest
Freestyle
Interest
Geometry Nodes
Interest
Grease Pencil
Interest
ID Management
Interest
Images & Movies
Interest
Import Export
Interest
Line Art
Interest
Masking
Interest
Metal
Interest
Modeling
Interest
Modifiers
Interest
Motion Tracking
Interest
Nodes & Physics
Interest
OpenGL
Interest
Overlay
Interest
Overrides
Interest
Performance
Interest
Physics
Interest
Pipeline, Assets & IO
Interest
Platforms, Builds & Tests
Interest
Python API
Interest
Render & Cycles
Interest
Render Pipeline
Interest
Sculpt, Paint & Texture
Interest
Text Editor
Interest
Translations
Interest
Triaging
Interest
Undo
Interest
USD
Interest
User Interface
Interest
UV Editing
Interest
VFX & Video
Interest
Video Sequencer
Interest
Virtual Reality
Interest
Vulkan
Interest
Wayland
Interest
Workbench
Interest: X11
Legacy
Blender 2.8 Project
Legacy
Milestone 1: Basic, Local Asset Browser
Legacy
OpenGL Error
Meta
Good First Issue
Meta
Papercut
Meta
Retrospective
Meta
Security
Module
Animation & Rigging
Module
Core
Module
Development Management
Module
EEVEE & Viewport
Module
Grease Pencil
Module
Modeling
Module
Nodes & Physics
Module
Pipeline, Assets & IO
Module
Platforms, Builds & Tests
Module
Python API
Module
Render & Cycles
Module
Sculpt, Paint & Texture
Module
Triaging
Module
User Interface
Module
VFX & Video
Platform
FreeBSD
Platform
Linux
Platform
macOS
Platform
Windows
Priority
High
Priority
Low
Priority
Normal
Priority
Unbreak Now!
Status
Archived
Status
Confirmed
Status
Duplicate
Status
Needs Info from Developers
Status
Needs Information from User
Status
Needs Triage
Status
Resolved
Type
Bug
Type
Design
Type
Known Issue
Type
Patch
Type
Report
Type
To Do
No Milestone
No project
No Assignees
6 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: blender/blender#111117
No description provided.