Wednesday, March 22, 2023

doodle

Hi,

this is a c++ doodle that has a little bit on creating a vector (like a python list).  it also has an example of modifying a parameter passed into the method by passing it in as reference (i dont think python has this concept of referencing for parameters of methods).  it also shows an example of creating/calling a method of a struct (kindof like a container of data/methods).  the example translates vertices in x by a given amount.

#include <iostream>
//for writing to file
#include <fstream>
//for reading file
#include <sstream>
#include <vector> //for using std::vector

struct Vertex
{
public:
	double x,y,z;
	Vertex(double x1, double y1, double z1): x(x1),y(y1),z(z1){}
	//@param offset double amount to offset
	void offsetX( double offset )
	{
		std::cout<<"offsetX\n";
		x = x+offset;
	}
};

/*update data structure we can manipulate in c++ for a mesh
@param verts	a vector of structs where each struct is a vertex to be updated by method
@param filePath	full filePath of mesh vertices to read - each line 3 numbers - first row is for first vertex in Blender
*/
void getVerts( std::vector<Vertex> &verts, std::string filePath ) //passing verts by reference allows us to edit the parameter in the method
{
	//todo: check filePath exists
	std::string ivstr;
	std::ifstream ifile(filePath);
	double x,y,z;
	while(std::getline(ifile, ivstr))
	{
		std::istringstream iss(ivstr);
		iss>>x>>y>>z;
		std::cout<<x<<" "<<y<<" "<<z<<std::endl;
		verts.push_back( Vertex(x,y,z) ); //add vertex to our vector
	}
	
}

//@param verts a vector of structs where each struct is a vertex
void printVerts(std::vector<Vertex> &verts)
{
	for(int i=0; i<verts.size(); ++i)
	{
		std::cout<<verts[i].x<<" "<<verts[i].y<<" "<<verts[i].z<<std::endl;
	}
}

/*offset verts - in x axis by offset amount
@param verts a vector of structs where each struct is a vertex
@param offsetX	amount to offset in x axis
*/
void offsetVerts(std::vector<Vertex> &verts, double offsetX)
{
	for(int i=0; i<verts.size(); ++i)
	{
		verts[i].offsetX(offsetX);//offset the vertex using struct's method
	}
}


int main()
{
	std::cout<<"great!"<<std::endl;
	
	std::vector<Vertex> v;
	getVerts(v, "/Users/Nathaniel/Documents/src/c/snippets/meshOffset/vdat_in.txt"); //change path to one that exists
	//example for vdat_in.txt
	/*
	10 2 2
	5 0 3
	*/
	
	std::cout<<"read verts from external"<<std::endl;
	printVerts(v);
	
	//offset verts
	offsetVerts(v, 10);//offset by 10 units in x
	
	std::cout<<"after offset verts - ready for output"<<std::endl;
	printVerts(v);
	
	//todo: write out verts
	//std::string outFile = "/Users/Nathaniel/Documents/src/c/snippets/meshOffset/vdat_out.txt";
	
	return 0;	
}

//g++ -o prog cToBlender.cpp
//./prog

Happy Sketching!