Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds geometry to downloadable obj files functionality #6812

Merged
merged 8 commits into from
Jun 23, 2024

Conversation

diyaayay
Copy link
Contributor

@diyaayay diyaayay commented Feb 15, 2024

Resolves #6769
Changes:
1- Added obj file support to save().
2- Created a method called geometryToObj() in p5.Geometry.js .

Screenshots of the change:
Sketch used:

let particles;
let button;

function setup() {
  createCanvas(400, 400, WEBGL); // Increase canvas size
  button = createButton('New');
  button.mousePressed(makeParticles);
  makeParticles();
  particles.geometryToObj();
}

function makeParticles() {
  if (particles) freeGeometry(particles);

  particles = buildGeometry(() => {
    for (let i = 0; i < 2; i++) {
      push();
      // Adjust translation values to fit within the canvas
      translate(
        randomGaussian(-50, 50),
        randomGaussian(-50, 50),
        randomGaussian(-50, 50)
      );
      sphere(5);
      pop();
    }
  });
}

Downloaded Obj File:
image

Sketch to check the downloaded obj file:

let octa;
function preload() {
 octa = loadModel('model.obj');
}
function setup() {
    createCanvas(400, 400, WEBGL);
}

function draw() {
 background(200);
   model(octa);
   }

Downloaded obj file on canvas:
image

PR Checklist

@diyaayay
Copy link
Contributor Author

@davepagurek Please take a look and let me know if this works and if further changes are needed, maybe unit tests, examples, or even how I've implemented this. Thanks.

Copy link
Contributor

@davepagurek davepagurek left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's looking good so far! Some user-facing documentation would be great.

For unit tests, some of our tests use this method to test downloads, maybe we can try using it too?

function testWithDownload(name, fn, asyncFn = false) {

an example of its usage:

testWithDownload(
'should download a file with expected contents (tsv)',
async function(blobContainer) {
myp5.saveTable(myTable, 'filename', 'tsv');
let myBlob = blobContainer.blob;
let text = await myBlob.text();
let myTableStr = myTable.columns.join('\t') + '\n';
for (let i = 0; i < myTable.rows.length; i++) {
myTableStr += myTable.rows[i].arr.join('\t') + '\n';
}
assert.strictEqual(text, myTableStr);
},
true
);



// Vertices
this.vertices.forEach(v => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work on this method, nice and concise!

objStr += `f ${faceStr}\n`;
});

save(objStr, fileName);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

save() is a user-facing function, so if this method uses it, users could also technically use it, but they would have to know to pass an obj string through here. Maybe instead we could use the internal downloadFile method?

p5.prototype.downloadFile(blob, filename, extension);

* @for p5.Geometry
*/

geometryToObj (fileName='model.obj'){
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can call this saveObj so users would call it like geom.saveObj() instead of geom.geometryToObj(), which feels a tad redundant?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

saveObj sounds much better :)

@diyaayay
Copy link
Contributor Author

@davepagurek made some changes, let me know if these work.Thanks.

Copy link
Contributor

@davepagurek davepagurek left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work on the writing for the documentation! I just have a few things left for the example.

I also thought of one more thing for the exporter itself about handling cases where we don't have either normals or texture coordinates.

* });
*
* octa = endGeometry();
* octa.saveObj();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we do this on button click maybe? I think going to the reference page and immediately having the file immediately download might be a bit jarring.

* let angleX = 0;
* let angleY = 0;
* function setup() {
* createCanvas(400, 400, WEBGL);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think we can make the canvas 100x100 (and scale accordingly in draw)? Right now it squishes the code:
image

// Faces
this.faces.forEach(face => {
// OBJ format uses 1-based indices
const faceStr = face.map(index => index + 1).join(' ');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we have normals and texture coordinates, I think we might have to use f 1/1/1 2/2/2 3/3/3 to specify that the face does in fact have vertices and faces? We read it out from the slashes here:

const vertParts = vertString.split('/');

It might take a few if statements to do e.g. f 1//1 2//2 3//3 if we have normals but no texture coordinates.

@davepagurek
Copy link
Contributor

Hi @diyaayay! I just wanted to check in to see whether you're still interested and have time to work on this? No problem at all of not, and would you be open to other contributors or myself continuing off of this branch to finish up the feature?

@diyaayay
Copy link
Contributor Author

Hi @diyaayay! I just wanted to check in to see whether you're still interested and have time to work on this? No problem at all of not, and would you be open to other contributors or myself continuing off of this branch to finish up the feature?

@davepagurek I've been a bit occupied lately with multiple stuff. I'm okay with any other contributors taking this up further and finishing the feature.

@davepagurek
Copy link
Contributor

No problem, thanks for the great foundation you've made for this feature so far 🙂 I hope GSoC is going well!

@dgrantham01
Copy link
Contributor

I've got a version of this that might work that can download both stl and obj filetypes, but I'm not sure how to submit it.

@davepagurek
Copy link
Contributor

Thanks @dgrantham01! How have you been working on it so far? Need any help making a PR?

@dgrantham01
Copy link
Contributor

dgrantham01 commented Jun 20, 2024

I made a little library type thing for my students to make generative sculptures last year and just modified it a bit to fit within the p5.Geometry class. It basically adds a save function to the class rather than going through the save function in the core library. I imagine that we could modify the save function in the core library similarly to the saveJson and saveStrings logic there.

This is the code though I haven't tested it in this context.

    save(filename = "model.obj", binary = false){
   let output;
   let nameAndExt = {
    "name": substring(0, filename.lastIndexOf(".")),
    "ext": filename.split('.').pop()
  }


  if(nameAndExt[1] === "stl"){
    faceNormals = [];
    for (let f of this.faces) {
      const U = p5.Vector.sub(this.vertices[f[1]], this.vertices[f[0]]);
      const V = p5.Vector.sub(this.vertices[f[2]], this.vertices[f[0]]);
      const nx = U.y * V.z - U.z * V.y;
      const ny = U.z * V.x - U.x * V.z;
      const nz = U.x * V.y - U.y * V.x;
      faceNormals.push(createVector(nx, ny, nz).normalize());
    }
    if(this.binary){
      let offset = 80;
      const bufferLength = this.faces.length * 2 + this.faces.length * 3 * 4 * 4 + 80 + 4;
      const arrayBuffer = new ArrayBuffer( bufferLength );
      output = new DataView( arrayBuffer );
      output.setUint32( offset, this.faces.length, true ); 
      offset += 4;

      for (const [key, f] of Object.entries(faces)){
        const normal = faceNormals[key];
        output.setFloat32(offset, normal.x, true ); 
        offset += 4;
        output.setFloat32(offset, normal.y, true ); 
        offset += 4;
        output.setFloat32(offset, normal.z, true ); 
        offset += 4;

        for (let vertexIndex of f) {
          const vertex = this.vertices[vertexIndex];
          output.setFloat32(offset, vertex.x, true ); 
          offset += 4;
          output.setFloat32(offset, vertex.y, true ); 
          offset += 4;
          output.setFloat32(offset, vertex.z, true ); 
          offset += 4;
        }
        output.setUint16(offset, 0, true ); 
        offset += 2;

      }  
    }
    else{
    output = ["solid " + nameAndExt[0]];
      // console.log(this.vertices)
    for (const [key, f] of Object.entries(faces)){
      const normal = faceNormals[key];
      output.push("facet normal " + normal.x + " " + normal.y + " " + normal.z);
      output.push(" outer loop");
      for (let vertexIndex of f) {
        const vertex = this.vertices[vertexIndex];
        output.push("vertex " + vertex.x + " " + vertex.y + " " + vertex.z);
      }
      output.push(" endloop");
      output.push("endfacet");

    }  
    output.push("endsolid " + nameAndExt[0] + "\n");
  }
  }
  else{
    output = []
    for (let v of this.vertices) {
      output.push("v " + v.x + " " + v.y + " " + v.z);
    }
    for(let uv of this.uvs){
      output.push("vt " + uv.x + " " + uv.y);
    }
    for(let vn of this.vertexNormals){
      output.push("vn " + vn.x + " " + vn.y + " " + vn.z);
    }
    for (let f of this.faces) {
      output.push("f " + f[0] + " " + f[1] + " " + f[2]);
    }
  }
  downloadFile(new Blob([output], {type: 'text/plain'}), filename);

}

@davepagurek
Copy link
Contributor

Nice! Are you able to clone this existing branch to add your STL exporter into the existing code, maybe by renaming the method to be format agnostic? Might be able to through here:
image

For the OBJ version, I wonder if we have to handle the same issue mentioned in this comment https://github.com/processing/p5.js/pull/6812/files#r1500085929 and make it output something like f 1/1/1 2/2/2 3/3/3 in order to add both normals and UVs to the face. If you're interested in modifying the existing OBJ export code here to add handling for that in that would be great!

@dgrantham01
Copy link
Contributor

I got it checked out. Never really contributed to this kind of thing before, but I'll see if I can get it all together.

One clarification about the Geometry data organization, are the indices of the vertexNormals and uvs the always the same as the vertices? The wiki on the obj format suggests that they could be different, but I just want to double check because I think that's not the case here.

@davepagurek
Copy link
Contributor

That's right, although in an arbitrary .obj file they might be different, in p5.Geometry's internals, there will always be a 1:1 mapping of vertices to UVs, per-vertex colors and normals (if they exist -- vertices will always exist but the others may just be empty.)

@dgrantham01
Copy link
Contributor

Ok. I fixed the obj and added stl and I think I committed it through the github online thing. Should be working. My test sketch was working and both stl and objs opened in blender no proble. A quick scan over the text inside looked like it was correct as well.

@davepagurek
Copy link
Contributor

ok nice! does it let you push the code to a new branch and make a PR? Also by online thing, is that Github Codespaces?

@dgrantham01
Copy link
Contributor

Yes. Codespaces is the online thing. I believe I managed to get it to commit and create a PR.

@davepagurek
Copy link
Contributor

I don't see it yet unfortunately, do you have a link to the PR?

@dgrantham01
Copy link
Contributor

I guess my commits aren't even going through because of a "husky" node version error, which I can't seem to resolve in codespaces, visualstudio, or github desktop. Here is a link to a forked version of the geometry file which should be correct.

https://github.com/dgrantham01/p5.js/blob/main/src/webgl/p5.Geometry.js

@davepagurek
Copy link
Contributor

Thanks! If getting it all working through GitHub is a problem, this weekend I can try to coalesce everything together into this PR to get both of your changes in.

dgrantham01 and others added 4 commits June 23, 2024 09:00
Fix obj export:
-included button in example to download the model instead of instantly downloading
-included vertexNormal and uv index inclusion in face output

added a saveStl function that saves an stl model
Copy link
Contributor

@davepagurek davepagurek left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your help everyone, I think this is good to go now!

@davepagurek davepagurek merged commit 263a652 into processing:main Jun 23, 2024
2 checks passed
@davepagurek
Copy link
Contributor

@all-contributors please add @diyaayay for code

Copy link
Contributor

@davepagurek

@diyaayay already contributed before to code

@davepagurek
Copy link
Contributor

@all-contributors please add @dgrantham01 for code

Copy link
Contributor

@davepagurek

I've put up a pull request to add @dgrantham01! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add Downloadable .obj File Support for p5.Geometry shapes
3 participants