Rendering .obj files with OpenGL - c++

I have been having problems rendering a model in opengl. I have made my own obj parser and a render function using glDrawElements but I can't see the problem. This is my parser function:
void load_obj(char *nom)
{
FILE *file = fopen(nom, "r");
int iv = 0, in = 0, it = 0, ifa = 0;
if(file != NULL)
{
while(1)
{
char lineHeader[128];
int res = fscanf(file, "%s", lineHeader);
if(res == EOF)
break;
if(strcmp(lineHeader, "v") == 0)
{
float vertex[3] = {0,0,0};
fscanf(file, "%f %f %f\n",
&vertex[0], &vertex[1], &vertex[2]);
vertices[iv] = vertex[0];
vertices[iv+1] = vertex[1];
vertices[iv+2] = vertex[2];
iv += 3;
}
else if(strcmp(lineHeader, "vt") == 0)
{
float tex_vert[2] = {0,0};
fscanf(file, "%f %f\n",
&tex_vert[0], &tex_vert[1]);
texturas[it] = tex_vert[0];
texturas[it+1] = tex_vert[1];
it += 2;
}
else if(strcmp(lineHeader, "vn") == 0)
{
float normal[3] = {0,0,0};
fscanf(file, "%f %f %f\n",
&normal[0], &normal[1], &normal[2]);
normales[in] = normal[0];
normales[in+1] = normal[1];
normales[in+2] = normal[2];
in += 3;
}
else if(strcmp(lineHeader, "f") == 0)
{
unsigned int vertexIndex[9] = {0,0,0,0,0,0,0,0,0};
fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n",
&vertexIndex[0], &vertexIndex[1], &vertexIndex[2],
&vertexIndex[3], &vertexIndex[4], &vertexIndex[5],
&vertexIndex[6], &vertexIndex[7], &vertexIndex[8]);
vertTriangulos[ifa] = vertexIndex[0];
vertTriangulos[ifa+1] = vertexIndex[1];
vertTriangulos[ifa+2] = vertexIndex[2];
vertTriangulos[ifa+3] = vertexIndex[3];
vertTriangulos[ifa+4] = vertexIndex[4];
vertTriangulos[ifa+5] = vertexIndex[5];
vertTriangulos[ifa+6] = vertexIndex[6];
vertTriangulos[ifa+7] = vertexIndex[7];
vertTriangulos[ifa+8] = vertexIndex[8];
ifa += 9;
nTriangulos++;
}
}
}
And this is my draw function:
void draw()
{
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glTexCoordPointer(2, GL_FLOAT, 0, texturas);
glNormalPointer(GL_FLOAT, 0, normales);
glDrawElements(GL_TRIANGLES, nTriangulos*9, GL_UNSIGNED_INT, vertTriangulos);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
}
Being the variables:
long nTriangulos;
float *vertices, *normales, *texturas;
unsigned int *vertTriangulos;
The obj file I'm using is a simple cube, but the mesh I'm rendering is a complete disaster.
EDIT:
I have changed my code and now the parser looks like this:
if(strcmp(lineHeader, "f") == 0)
{
unsigned int vertexIndex[9] = {0,0,0,0,0,0,0,0,0};
fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n",
&vertexIndex[0], &vertexIndex[1], &vertexIndex[2],
&vertexIndex[3], &vertexIndex[4], &vertexIndex[5],
&vertexIndex[6], &vertexIndex[7], &vertexIndex[8]);
for(int i = 0; i < 9; i += 3)
{
bool cierto = true;
int pos = 0;
if(indexbuff.size() > 0)
{
for(int i = 0; i < registro.size(); i++)
{
if(vertexIndex[0] == registro[i].in1
&& vertexIndex[1] == registro[i].in2
&& vertexIndex[2] == registro[i].in3)
{
cierto = false;
pos = i;
}
}
}
if(cierto)
{
verticebuff.push_back(vertices[vertexIndex[i]]);
verticebuff.push_back(vertices[vertexIndex[i]+1]);
verticebuff.push_back(vertices[vertexIndex[i]+2]);
textbuff.push_back(texturas[vertexIndex[i+1]]);
textbuff.push_back(texturas[vertexIndex[i+1]+1]);
normalbuff.push_back(normales[vertexIndex[i+2]]);
normalbuff.push_back(normales[vertexIndex[i+2]+1]);
normalbuff.push_back(normales[vertexIndex[i+2]+2]);
indexbuff.push_back(verticebuff.size()/3);
index3 indice;
indice.in1 = vertexIndex[i];
indice.in2 = vertexIndex[i+1];
indice.in3 = vertexIndex[i+2];
registro.push_back(indice);
}
else
{
indexbuff.push_back(i);
}
}
}
But it doesn't seem to work properly.

Classic obj to opengl buffer mistake, the element buffer index points to all attributes. In other words if opengl sees a 0 index it takes the first element out of all the enabled buffers and move on to the next index. There is no way to use the obj structure directly without duplication of the data as you are reading
you face code should be
if(/*vertexIndex[0..2] triplet has not been seen yet*/){
verticebuff.pushback(vertices[vertexIndex[0]]);
verticebuff.pushback(vertices[vertexIndex[0]+1]);
verticebuff.pushback(vertices[vertexIndex[0]+2]);
textbuff.pushback(texturas[vertexIndex[1]]);
textbuff.pushback(texturas[vertexIndex[1]+1]);
normalbuff.pushback(normales[vertexIndex[2]]);
normalbuff.pushback(normales[vertexIndex[2]+1]);
indexbuff.pushback(verticebuff.size()/3);
} else {
indexbuff.pushback(/*index of the seen triplet*/);
}
//repeat 3 times
then you can paint them with draw elements.

Related

Error when outputting the earth obj in OpenGl

I want to print out the earth obj, but it keeps printing strangely like a picture.
The vertexes are printed in an empty form in the middle.
_mesh = new Mesh("obj\\13902_Earth_v1_l3.obj", "obj\\Earth_diff.jpg");
First, enter the file name like this. Over there, _mesh is the object of the Mesh class that I created.
Mesh(char* obj, char* texture) {
open(obj);
loadTexture(texture, _textureIndex);
}
This is the constructor of the Mesh class. The Opne function outputs obj, and loadTexture reads the texture. just look at the Open function.
void Mesh::open(char* file)
{
FILE* fp;
char buffer[100] = { 0 };
Vec3<double> pos;
int index[3], tex[3], empty[3];
int id = 0;
_minBound.Set(1000000.0);
_maxBound.Set(-1000000.0);
fopen_s(&fp, file, "r");
while (fscanf(fp, "%s %lf %lf %lf", buffer, &pos[0], &pos[1], &pos[2]) != EOF)
{
// v 0.2 0.3 0.1
// vt
if (buffer[0] == 'v' && buffer[1] == NULL) {
for (int i = 0; i < 3; i++) {
if (_minBound[i] > pos[i]) _minBound[i] = pos[i];
if (_maxBound[i] < pos[i]) _maxBound[i] = pos[i];
}
_vertices.push_back(new Vertex(id, pos));
}
}
// read texture coordinate of vertics
id = 0;
fseek(fp, 0, SEEK_SET);
while (fscanf(fp, "%s %lf %lf", &buffer, &pos[0], &pos[1]) != EOF) {
if (!strcmp(buffer, "vt")) {
_textureCoords.push_back(new Texture(pos[0], 1.0 - pos[1], 0.0));
}
}
// read faces
id = 0;
fseek(fp, 0, SEEK_SET);
while (fscanf(fp, "%s %d/%d/%d %d/%d/%d %d/%d/%d", &buffer, &index[0], &tex[0], &empty[0], &index[1], &tex[1], &empty[1], &index[2], &tex[2], &empty[2]) != EOF) {
if (buffer[0] == 'f' && buffer[1] == NULL) {
auto v0 = _vertices[index[0] - 1];
auto v1 = _vertices[index[1] - 1];
auto v2 = _vertices[index[2] - 1];
_faces.push_back(new Face(id++, v0, v1, v2, tex[0] - 1, tex[1] - 1, tex[2] - 1));
//_faces.push_back(new Face(index++, _vertices[v_index[0] - 1], _vertices[v_index[1] - 1], _vertices[v_index[2] - 1]));
}
}
fclose(fp);
moveToCenter(10.0);
makeList();
computeNormal();
}
In the code, _vertices and _faces are class vectors that I've created. It's simply a text file in this format that's made vector computation.
And I didn't read the value of vn there, and I didn't read the third value of f. Then at least the vertex value would have been entered well, but why does it print out like that?
This is what it looks like when I don't put on textures.
All other sphere objects are printed in that form. How do we solve this?

What is causing VK_ERROR_DEVICE_LOST when calling vkQueueSubmit?

I'm working on a voxel engine in C++ using Vulkan. Most of the boilerplate code is heavily based on vulkan-tutorial.com. I have a drawFrame function that looks like this...
void drawFrame(float dt) {
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
uint32_t imageIndex;
VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
updateUniformBuffer(imageIndex, dt);
if (result == VK_ERROR_OUT_OF_DATE_KHR) {
recreateSwapChain();
return;
} else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("failed to acquire swap chain image!");
}
// Check if a previous frame is using this image (i.e.there is its fence to wait on)
if (imagesInFlight[imageIndex] != VK_NULL_HANDLE) {
vkWaitForFences(device, 1, &imagesInFlight[imageIndex], VK_TRUE, UINT64_MAX);
}
// Mark the image as now being in use by this frame
imagesInFlight[imageIndex] = inFlightFences[currentFrame];
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] };
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] };
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
vkResetFences(device, 1, &inFlightFences[currentFrame]);
result = vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]);
if (result != VK_SUCCESS) {
throw std::runtime_error("failed to submit draw command buffer!");
}
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores;
VkSwapchainKHR swapChains[] = { swapChain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
presentInfo.pResults = nullptr; // Optional
result = vkQueuePresentKHR(presentQueue, &presentInfo);
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
framebufferResized = false;
recreateSwapChain();
} else if (result != VK_SUCCESS) {
throw std::runtime_error("failed to present swap chain image!");
}
// Increment the frame. By using the modulo(%) operator, we ensure that the frame index loops around after every MAX_FRAMES_IN_FLIGHT enqueued frames.
currentFrame = (currentFrame + 1) % config->maxFramesInFlight;
}
I'm passing in vertices like this...
void createVertexAndIndexBuffer() {
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 4; y++) {
for (size_t z = 0; z < 100; z++) {
// for each block in the world vector
auto blockId = world.getBlock(x, y, z);
if (blockId == BlockId::Air) {
continue;
}
Vec3 blockPosition = { x, y, z };
// get its data
auto verts = blockdb.blockDataFor(blockId).getVertices();
auto inds = blockdb.blockDataFor(blockId).getIndices();
// account for the block position and store the new verts for later
for (int i = 0; i < verts.size(); i++) {
Vertex v(verts[i]);
v.pos += blockPosition;
vertices.push_back(v);
}
// store the indices for later accounting for the offset into the verts vector
for (int i = 0; i < inds.size(); i++) {
int ind(inds[i] + vertices.size());
indices.push_back(ind);
}
}
}
}
// time to start creating the actual buffer
VkDeviceSize vertexBufferSize = sizeof(vertices[0]) * vertices.size();
VkBuffer vertexStagingBuffer;
VkDeviceMemory vertexStagingBufferMemory;
createBuffer(vertexBufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, vertexStagingBuffer, vertexStagingBufferMemory);
void* vertexData;
vkMapMemory(device, vertexStagingBufferMemory, 0, vertexBufferSize, 0, &vertexData);
memcpy(vertexData, vertices.data(), (size_t)vertexBufferSize);
vkUnmapMemory(device, vertexStagingBufferMemory);
createBuffer(vertexBufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory);
// use copyBuffer() to move the vertex data to the device local buffer
copyBuffer(vertexStagingBuffer, vertexBuffer, vertexBufferSize);
// After copying the data from the staging buffer to the device buffer, we should clean up the staging buffer since it is no longer needed.
vkDestroyBuffer(device, vertexStagingBuffer, nullptr);
vkFreeMemory(device, vertexStagingBufferMemory, nullptr);
// and do the same for the index buffer
VkDeviceSize indexBufferSize = sizeof(indices[0]) * indices.size();
VkBuffer indexStagingBuffer;
VkDeviceMemory indexStagingBufferMemory;
createBuffer(indexBufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, indexStagingBuffer, indexStagingBufferMemory);
void* indexData;
vkMapMemory(device, indexStagingBufferMemory, 0, indexBufferSize, 0, &indexData);
memcpy(indexData, indices.data(), (size_t)indexBufferSize);
vkUnmapMemory(device, indexStagingBufferMemory);
createBuffer(indexBufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory);
copyBuffer(indexStagingBuffer, indexBuffer, indexBufferSize);
vkDestroyBuffer(device, indexStagingBuffer, nullptr);
vkFreeMemory(device, indexStagingBufferMemory, nullptr);
}
Everything works fine like that but I need be able to render by chunk instead of by block in order to implement chunk geometry optimizations. This is my chunk.h and chunk.cpp...
#pragma once
#include "Layer.h"
class Chunk {
public:
Chunk() = default;
Chunk(World* _world, Vec2XZ pos);
~Chunk() {}
BlockId getBlock(int x, int y, int z);
bool setBlock(BlockId id, int x, int y, int z);
bool isBlockOutOfBounds(int x, int y, int z);
void generateVerticesAndIndices();
void load();
std::array<Layer, CHUNK_HEIGHT> layers;
const Vec2XZ position;
const World* world;
bool isLoaded = false;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
private:
};
#pragma once
#include "Chunk.h"
Chunk::Chunk(World* _world, Vec2XZ pos) :
position(pos),
world(_world) {
}
BlockId Chunk::getBlock(int x, int y, int z) {
if (isBlockOutOfBounds(x, y, z)) {
return BlockId::Air;
}
return layers[y].getBlock(x, z);
}
bool Chunk::setBlock(BlockId id, int x, int y, int z) {
if (!isBlockOutOfBounds(x, y, z)) {
if (layers[y].setBlock(id, x, z)) {
return true;
}
}
return false;
}
bool Chunk::isBlockOutOfBounds(int x, int y, int z) {
if (x >= CHUNK_WIDTH)
return true;
if (z >= CHUNK_WIDTH)
return true;
if (x < 0)
return true;
if (y < 0)
return true;
if (z < 0)
return true;
if (y >= CHUNK_HEIGHT) {
return true;
}
return false;
}
void Chunk::generateVerticesAndIndices() {
vertices.clear();
indices.clear();
for (int y = 0; y < CHUNK_HEIGHT; y++) {
for (int x = 0; x < CHUNK_WIDTH; x++) {
for (int z = 0; z < CHUNK_WIDTH; z++) {
// for each block in this chunk
auto blockId = getBlock(x, y, z);
if (blockId == BlockId::Air) {
continue; // dont render air
}
// infer the block position using its coordinates
Vec3 blockPosition = { x, y, z };
// get its data
auto verts = world->blockdb->blockDataFor(blockId).getVertices();
auto inds = world->blockdb->blockDataFor(blockId).getIndices();
// account for the block position and store the new verts
for (int i = 0; i < verts.size(); i++) {
Vertex v(verts[i]);
v.pos += blockPosition;
vertices.push_back(v);
}
// store the indices for later accounting for the offset into the verts vector
for (int i = 0; i < inds.size(); i++) {
int ind(inds[i] + vertices.size());
indices.push_back(ind);
}
}
}
}
}
void Chunk::load() {
if (isLoaded) {
return;
}
// todo: actual terrain generation
for (int y = 0; y < 4; y++) {
for (int x = 0; x < CHUNK_WIDTH; x++) {
for (int z = 0; z < CHUNK_WIDTH; z++) {
setBlock(BlockId::Grass, x, y, z);
}
}
}
isLoaded = true;
}
So I've basically migrated the top part of createVertexAndIndexBuffer() over to the chunk class. Then within createVertexAndIndexBuffer(), I iterate through the chunks around the player within render distance like this...
void createVertexAndIndexBuffer() {
// set bounds of how far out to render based on what chunk the player is in
Vec2XZ playerChunkCoords = { floor(player.position.x) / CHUNK_WIDTH, floor(player.position.z) / CHUNK_WIDTH };
Vec2XZ lowChunkXZ = { playerChunkCoords.x - renderDistance, playerChunkCoords.z - renderDistance };
Vec2XZ highChunkXZ = { playerChunkCoords.x + renderDistance, playerChunkCoords.z + renderDistance };
// for each chunk around the player within render distance
for (int x = lowChunkXZ.x; x < highChunkXZ.x; x++) {
for (int z = lowChunkXZ.z; z < highChunkXZ.z; z++) {
// get the chunk
Chunk* chunk = &world.getChunk(x, z);
// load it if it isnt already
if (!chunk->isLoaded) {
chunk->load();
}
// generate its geometry if it doesnt already exist
if (chunk->vertices.size() == 0 || chunk->indices.size() == 0) {
chunk->generateVerticesAndIndices();
}
auto verts = chunk->vertices;
auto inds = chunk->indices;
// account for the chunk position and store the new verts for later
for (int i = 0; i < verts.size(); i++) {
Vertex v(verts[i]);
v.pos.x += x * CHUNK_WIDTH;
v.pos.z += z * CHUNK_WIDTH;
vertices.push_back(v);
}
// store the indices for later accounting for the offset into the verts vector
for (int i = 0; i < inds.size(); i++) {
int ind(inds[i] + vertices.size());
indices.push_back(ind);
}
}
}
// time to start creating the actual buffer
VkDeviceSize vertexBufferSize = sizeof(vertices[0]) * vertices.size();
VkBuffer vertexStagingBuffer;
VkDeviceMemory vertexStagingBufferMemory;
createBuffer(vertexBufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, vertexStagingBuffer, vertexStagingBufferMemory);
void* vertexData;
vkMapMemory(device, vertexStagingBufferMemory, 0, vertexBufferSize, 0, &vertexData);
memcpy(vertexData, vertices.data(), (size_t)vertexBufferSize);
vkUnmapMemory(device, vertexStagingBufferMemory);
createBuffer(vertexBufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory);
// use copyBuffer() to move the vertex data to the device local buffer
copyBuffer(vertexStagingBuffer, vertexBuffer, vertexBufferSize);
// After copying the data from the staging buffer to the device buffer, we should clean up the staging buffer since it is no longer needed.
vkDestroyBuffer(device, vertexStagingBuffer, nullptr);
vkFreeMemory(device, vertexStagingBufferMemory, nullptr);
// and do the same for the index buffer
VkDeviceSize indexBufferSize = sizeof(indices[0]) * indices.size();
VkBuffer indexStagingBuffer;
VkDeviceMemory indexStagingBufferMemory;
createBuffer(indexBufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, indexStagingBuffer, indexStagingBufferMemory);
void* indexData;
vkMapMemory(device, indexStagingBufferMemory, 0, indexBufferSize, 0, &indexData);
memcpy(indexData, indices.data(), (size_t)indexBufferSize);
vkUnmapMemory(device, indexStagingBufferMemory);
createBuffer(indexBufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory);
copyBuffer(indexStagingBuffer, indexBuffer, indexBufferSize);
vkDestroyBuffer(device, indexStagingBuffer, nullptr);
vkFreeMemory(device, indexStagingBufferMemory, nullptr);
}
With this code, the engine starts up fine but the screen stays white and then after a few calls to vkQueueSubmit() within drawFrame(), vkQueueSubmit() returns VK_ERROR_DEVICE_LOST instead of VK_SUCCESS and then the app throws the corresponding runtime error, prints out the corresponding debug information "failed to submit draw command buffer!", waits for me to press a key, and then finally terminates with EXIT_FAILURE.
Why does pushing vertices from blocks directly work fine, but pushing them from chunks does not? I have checked the Vulkan specification and did a lot of googling but I just couldn't find much on what causes this error to be thrown. I want to know how to fix it and in turn, fix my engine.
I was assigning indices incorrectly and it was being caught by the graphics driver. There were indices that were larger than the vertex vector.

Reference cannot be initialized/expression must have type class

I'm doing a quick binary tree program as a homework, but I am getting weird errors that I can't seem to figure out how to fix. Normally I'm programming in C#, and C is just slightly different but different enough for me to get confused.
Here is the code that is giving the error:
void SortArray() {//bubble sorting by float value of 'b'
int flag = 0;
do {
flag = 1;
for (int i = 0; i < arraySize - 1; i++)
{
if (stubList[i].b > stubList[i + 1].b) {
Swap(stubList[i], stubList[i + 1]);
flag = 0;
}
}
} while (flag == 0);
printf("Sorted by value of variable 'b'"); _getch(); _getch();
}
And here is the whole script:
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct stub
{
char crown[51];//some custom name - can be empty
float b;//comparable value for tree sort
int c;//limited by maxint
stub *l;//left node(normally smaller "b" value than this node)
stub *r;//right node(normally bigger "b" value than this node)
};
stub *stubList[255];//empty list of a stub array with a safe casual amount
int arraySize = 0;
stub *head = NULL;//main stub(first)
stub *latest = NULL;//latest stub
stub *st = NULL;//used for creating and checking
FILE *fs = NULL;
char fileName[255];
int maxint = 20;//for var 'c'
void BTreeNodeToArray(stub *s) {
stubList[arraySize] = s;
arraySize++;
}
void Swap(stub &s1, stub &s2) {
stub temp = s2;
s1 = s2;
s2 = temp;
}
int MaxMin(int num) {
int clampedInt = num;
if (num < 0) clampedInt = 0;
else if (num > maxint) clampedInt = maxint;
return clampedInt;
}
//Create a completely new stub with crown, b, and c variables being filled here
void CreateElement() {
st = new stub;
printf("Adding information for node:\n");
printf("Node name: "); gets_s(st->crown);
printf("\n");
float f;
printf("Node float value (B): "); scanf_s("%f", &f);
st->b = f;
printf("\n");
int d;
printf("Node integer value (C): "); scanf_s("%d", &d);
st->c = d;
printf("\n");
st->c = MaxMin(st->c);
st->l = NULL;
st->r = NULL;
}
//creates the very first stub(root/head)
void CreateFirst() {
printf("First in tree. Adding root node...\n");
CreateElement();
head = st;
latest = head;
BTreeNodeToArray(head);
printf("Added head stub\ncrown: %s\nValue: %f\nExtra: %d", head->crown, head->b, head->c);
getchar();
getchar();
}
void AddStub() {
if (head == NULL) {
CreateFirst();
}
else {
CreateElement();//create newest node
latest = st;
st = head;
int depth = 0;
while (1) {
if ((latest->b <= st->b)) {//choose left if true
printf("Went left\n");
depth++;
if (st->l == NULL) {//node free, assign here
printf("Node assigned at depth %d\n", depth);
st->l = latest;
BTreeNodeToArray(latest);
getchar();
getchar();
break;
}
else {//loop again with next node
//printf("New loop (left)\n");
st = st->l;
}
}
else {//choose right
printf("Went right\n");
depth++;
if (st->r == NULL) {//node free, assign here
printf("Node assigned at depth %d\n", depth);
st->r = latest;
BTreeNodeToArray(latest);
getchar();
getchar();
break;
}
else {//loop again with next node
//printf("New loop (right)\n");
st = st->r;
}
}
}
}
}
void ViewArray() {
for (int i = 0; i < arraySize; i++)
{
printf_s("Node [%d]:\n\tCrown: %s\n\tweight: %f\n\tExta value(0 - %d): %d\n", i, stubList[i]->crown, stubList[i]->b, maxint, stubList[i]->c);
}
getchar();
}
void SortArray() {//bubble sorting by float value of 'b'
int flag = 0;
do {
flag = 1;
for (int i = 0; i < arraySize - 1; i++)
{
if (stubList[i].b > stubList[i + 1].b) {
Swap(stubList[i], stubList[i + 1]);
flag = 0;
}
}
} while (flag == 0);
printf("Sorted by value of variable 'b'"); _getch(); _getch();
}
void ProcessArray() {
char c = ' ';
int found = 0;
printf("Process with character: \n"); c = _getch();
if (arraySize <= 0) {
printf("No List!");
return;
}
char chkstr[5];
for (short i = 0; i < 5; i++)//simple assign to a 'string' 5 times
{
chkstr[i] = c;
}
for (int i = 0; i < arraySize; i++)
{
if (strstr(stubList[i]->crown, chkstr) != NULL) {
// contains
printf("B = %f at [%d] \n", stubList[i]->b, i);
found++;
}
}
if (found > 0) {
printf("---Found: %d with character %c---", found, c);
}
else {
printf("No elements found with '%c'", c);
}
getchar();
}
void ExportArray() {
FILE *fs = NULL;
char fileName[255];
errno_t err;
printf("Save to file as: \n"); gets_s(fileName);
if (strlen(fileName) == 0) {
printf("Failed to create file. File name empty!");
_getch();
_getch();
}
err = fopen_s(&fs, fileName, "wb");
if (err != 0) {
printf("Failed to create file!!!");
_getch();
_getch();
return;
}
for (int i = 0; i < arraySize; i++)
{
int written = fwrite(&stubList[i], sizeof(stub), 1, fs);
//fwrite(&gr[i], sizeof(student), 1, fs);
}
int numclosed = _fcloseall();
printf("Exported to file: %s", fileName);
getchar();
}
void CleanReset() {//reset all values and release memory (function used for import)
for (int i = 0; i < arraySize; i++)
{
delete stubList[i];
}
arraySize = 0;
st = NULL;
head = NULL;
latest = NULL;
}
void ImportArray() {
FILE *fs = NULL;
char fname[255];
errno_t err;
printf("Open FIle: "); gets_s(fname);
err = fopen_s(&fs, fname, "rb");
if (err == 0) {
CleanReset();
fseek(fs, 0, SEEK_END);
long size = ftell(fs);
arraySize = size / sizeof(stub);//get amount of students saved
fseek(fs, 0, SEEK_SET);
int i = 0;
st = new stub;
fread_s(&st, sizeof(stub), sizeof(stub), 1, fs);
stubList[i] = st;
while (!feof(fs)) {
i++;
st = new stub;
fread_s(&st, sizeof(stub), sizeof(stub), 1, fs);
stubList[i] = st;
}
printf("File data imported. Size: %d", arraySize);
getchar();
return;
}
printf("Failed to import file!!!");
getchar();
}
void main()
{
system("chcp 65001");//use utf8
char izb = 'i';
while (izb != '0') {
system("cls");
printf_s("1. Add stub\n");
printf_s("2. View Array\n");
printf_s("3. Sort Array\n");
printf_s("4. Process\n");
printf_s("5. Export array to file\n");
printf_s("6. Import array from file\n");
printf_s("0. Exit\n\n");
printf_s("Choose action:\n"); izb = _getch();
switch (izb)
{
case '1':
AddStub();
break;
case '2':
ViewArray();
break;
case '3':
SortArray();
break;
case '4':
ProcessArray();
break;
case '5':
ExportArray();
break;
case '6':
ImportArray();
break;
case '0':
//Exit();
break;
}
}
}
The error is that you want to pass a stub * to a function that wants a stub &. The first one is a pointer, the second one is a reference.
You have two options.
First option (imho recommended):
Change your swap function to accept pointers instead of references.
void Swap(stub *s1, stub *s2) {
stub temp = *s2;
*s1 = *s2;
*s2 = temp;
}
Second option:
Dereference the parameters before passing to swap:
Swap(*(stubList[i]), *(stubList[i + 1]));
You have to undestand that the datatype in your list is a pointer to stub, the function Swap wants a reference, which are different things in C++.
For a better understanding I recommend reading this: https://www.geeksforgeeks.org/pointers-vs-references-cpp/

how to fill the "data field" of wavfile

Hi i am trying to record from a board and i have successfully record 4 seconds. Problem is when i try to record for more time, i got an error telling me that there not enough memory. my target is to record a 5 minutes file. Until now i have create a buffer named snIn[256] where are the samples. i send it to a big buffer of [16K * 4sec] and when it is full, i create the wav file.
#include "SAI_InOut.hpp"
#include "F746_GUI.hpp"
#include "Delay.hpp"
#include "WaveformDisplay.hpp"
#include "SDFileSystem.h"
#include "wavfile.h"
using namespace Mikami;
#define RES_STR_SIZE 0x20
#define WAVFILE_SAMPLES_PER_SECOND 16000
#define REC_TIME 4
//Create an SDFileSystem object
SDFileSystem sd("sd");
bool flag = 1;
int count = 0;
char *res_buf;
int rp = 0;
const int NUM_SAMPLES = WAVFILE_SAMPLES_PER_SECOND * REC_TIME;
Array<int16_t> my_buffer(NUM_SAMPLES);
int j = 0;
static const char *target_filename = "/sd/rectest.wav";
const int SEG_SIZE = 256;
int sent_array = 0;
int rec(const char *filename, Array<int16_t> my_buffer)
{
j = 0;
flag = 0;
sent_array = 0;
WavFileResult result;
wavfile_info_t info;
wavfile_data_t data;
WAVFILE_INFO_AUDIO_FORMAT(&info) = 1;
WAVFILE_INFO_NUM_CHANNELS(&info) = 1;
WAVFILE_INFO_SAMPLE_RATE(&info) = WAVFILE_SAMPLES_PER_SECOND;
WAVFILE_INFO_BITS_PER_SAMPLE(&info) = 16;
WAVFILE_INFO_BYTE_RATE(&info) = WAVFILE_INFO_NUM_CHANNELS(&info) * WAVFILE_INFO_SAMPLE_RATE(&info) * (WAVFILE_INFO_BITS_PER_SAMPLE(&info) / 8);
WAVFILE_INFO_BLOCK_ALIGN(&info) = 2;
WAVFILE *wf = wavfile_open(filename, WavFileModeWrite, &result);
if (result != WavFileResultOK) {
wavfile_result_string(result, res_buf, RES_STR_SIZE);
printf("%s", res_buf);
return result;
} else printf ("Open file success \r\n");
rp = 0;
WAVFILE_DATA_NUM_CHANNELS(&data) = 1;
result = wavfile_write_info(wf, &info);
if (result != WavFileResultOK) {
wavfile_result_string(result, res_buf, RES_STR_SIZE);
printf("%s", res_buf);
return result; } else printf ("Write info success \r\n");
while ( rp < NUM_SAMPLES ) {
WAVFILE_DATA_CHANNEL_DATA(&data, 0) = my_buffer[rp];
result = wavfile_write_data(wf, &data);
rp += 1;
}
if (result != WavFileResultOK) {
wavfile_result_string(result, res_buf, RES_STR_SIZE);
printf("%s", res_buf);
return result; } else printf ("Write Data file success \r\n");
result = wavfile_close(wf);
if (result != WavFileResultOK) {
wavfile_result_string(result, res_buf , RES_STR_SIZE);
printf("%s", res_buf);
return result; } else printf ("Close file success \r\n");
//UnMount the filesystem
sd.unmount();
printf("Success rec !\r\n");
return 0;
}
int main()
{
//Mount the filesystem
sd.mount();
const float MAX_DELAY = 0.5f; // 最大遅延,単位:秒
const int FS = I2S_AUDIOFREQ_16K; // 標本化周波数: 16 kHz
const uint32_t MAX_ARRAY_SIZE = (uint32_t)(MAX_DELAY*FS);
SaiIO mySai(SaiIO::BOTH, 256, FS, INPUT_DEVICE_DIGITAL_MICROPHONE_2);
Label myLabel(185, 10, "Delay System", Label::CENTER, Font16);
// ButtonGroup: "ON", "OFF"
const uint16_t BG_LEFT = 370;
const uint16_t BG_WIDTH = 100;
const uint16_t BG_HEIGHT = 45;
ButtonGroup onOff(BG_LEFT, 40, BG_WIDTH/2, BG_HEIGHT,
2, (string[]){"ON", "OFF"}, 0, 0, 2, 1);
const uint16_t SB_LEFT = BG_LEFT - 320;
const uint16_t SB_WIDTH = 270;
const uint16_t SB_Y0 = 240;
char str[20];
sprintf(str, " %3.1f [s]", MAX_DELAY);
SeekBar barDelay(SB_LEFT, SB_Y0, SB_WIDTH,
0, MAX_ARRAY_SIZE, 0, "0", "", str);
NumericLabel<float> labelDelay(SB_LEFT+SB_WIDTH/2, SB_Y0-40, "DELEY: %4.2f", 0, Label::CENTER);
DelaySystem delaySystem(MAX_ARRAY_SIZE);
WaveformDisplay displayIn(*GuiBase::GetLcdPtr(), SB_LEFT+7, 70, 256, 9,LCD_COLOR_WHITE, LCD_COLOR_CYAN,GuiBase::ENUM_BACK);
Label inLabel(SB_LEFT-30, 65, "IN");
WaveformDisplay displayOut(*GuiBase::GetLcdPtr(), SB_LEFT+7, 130, 256, 9,LCD_COLOR_WHITE, LCD_COLOR_CYAN,GuiBase::ENUM_BACK);
Label outLabel(SB_LEFT-30, 125, "OUT");
int runStop = 1;
Array<int16_t> snIn(mySai.GetLength());
Array<int16_t> snOut(mySai.GetLength());
mySai.RecordIn();
mySai.PlayOut();
mySai.PauseOut();
while (true)
{
// On/OFF
int num;
if (onOff.GetTouchedNumber(num))
if (runStop != num)
{
if (num == 0) mySai.ResumeOut();
else mySai.PauseOut();
runStop = num;
}
if (mySai.IsCompleted())
{
for (int n=0; n<mySai.GetLength() ; n++)
{
int16_t xL, xR;
mySai.Input(xL,xR);
int16_t xn = xL + xR;
snIn[n] = xn;
my_buffer[j] = xn;
j++;
if (j == NUM_SAMPLES && flag == 1) {
rec (target_filename , my_buffer); }
int16_t yn = delaySystem.Execute(xn);
mySai.Output(yn, yn);
snOut[n] = yn;
}
mySai.Reset();
displayIn.Execute(snIn);
}
}
}
I thought about a possible solution, to fill directly the "data field" of the wavefile with the snIn[256] buffer (instead of using my_buffer) again and again and at the end close the wavfile. Please let me know what you think about that and other solutions
things to note: 1) while a write operation is being performed, more data is still coming in.
At the very least I would double buffer that data, so can be writing one buffer while the other one fills.
Usually this means using an interrupt to collect the samples (into which ever buffer is currently being filed.)
the foreground program waits for the current buffer to be 'full', then initiates write operation.,
then waits again for a buffer to be 'full'
The interrupt function tracks which buffer is being filled and the current index into that buffer. When a buffer is full, set a 'global' status to let the foreground program know which buffer is ready to be written.
The foreground program writes the buffer, then resets the status for that buffer.

Some new version of opencv_performance for opencv_traincascade?

I have noted that the cascades trained with the program opencv_traincascade does not run with the current version of opencv_performance. I've tried to convert the old performance cpp file to load the new types of cascades, but without success. The code is here:
#include "cv.h"
#include "highgui.h"
#include <cstdio>
#include <cmath>
#include <ctime>
#include <math.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#ifndef PATH_MAX
#define PATH_MAX 512
#endif /* PATH_MAX */
/*typedef struct HidCascade {
int size;
int count;
} HidCascade;
*/
typedef struct ObjectPos {
float x;
float y;
float width;
int found; /* for reference */
int neghbors;
} ObjectPos;
using namespace std;
using namespace cv;
int main(int argc, char* argv[]) {
int i, j;
char* classifierdir = NULL;
//char* samplesdir = NULL;
int saveDetected = 1;
double scale_factor = 1.1;
float maxSizeDiff = 1.5F;
float maxPosDiff = 1.1F;
/* number of stages. if <=0 all stages are used */
//int nos = -1, nos0;
int width = 25;
int height = 15;
int rocsize;
FILE* info;
FILE* resultados;
char* infoname;
char fullname[PATH_MAX];
//char detfilename[PATH_MAX];
char* filename;
//char detname[] = "det-";
CascadeClassifier cascade;
double totaltime;
if (!(resultados = fopen("resultados.txt", "w"))) {
printf("Cannot create results file.\n");
exit(-1);
}
infoname = (char*) "";
rocsize = 20;
if (argc == 1) {
printf("Usage: %s\n -data <classifier_directory_name>\n"
" -info <collection_file_name>\n"
" [-maxSizeDiff <max_size_difference = %f>]\n"
" [-maxPosDiff <max_position_difference = %f>]\n"
" [-sf <scale_factor = %f>]\n"
" [-ni]\n"
" [-rs <roc_size = %d>]\n"
" [-w <sample_width = %d>]\n"
" [-h <sample_height = %d>]\n", argv[0], maxSizeDiff,
maxPosDiff, scale_factor, rocsize, width, height);
return 0;
}
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-data")) {
classifierdir = argv[++i];
} else if (!strcmp(argv[i], "-info")) {
infoname = argv[++i];
} else if (!strcmp(argv[i], "-maxSizeDiff")) {
maxSizeDiff = (float) atof(argv[++i]);
} else if (!strcmp(argv[i], "-maxPosDiff")) {
maxPosDiff = (float) atof(argv[++i]);
} else if (!strcmp(argv[i], "-sf")) {
scale_factor = atof(argv[++i]);
} else if (!strcmp(argv[i], "-ni")) {
saveDetected = 0;
} else if (!strcmp(argv[i], "-rs")) {
rocsize = atoi(argv[++i]);
} else if (!strcmp(argv[i], "-w")) {
width = atoi(argv[++i]);
} else if (!strcmp(argv[i], "-h")) {
height = atoi(argv[++i]);
}
}
if (!cascade.load(classifierdir)) {
printf("Unable to load classifier from %s\n", classifierdir);
return 1;
}
strcpy(fullname, infoname);
filename = strrchr(fullname, '\\');
if (filename == NULL) {
filename = strrchr(fullname, '/');
}
if (filename == NULL) {
filename = fullname;
} else {
filename++;
}
info = fopen(infoname, "r");
totaltime = 0.0;
if (info != NULL) {
int x, y, width, height;
Mat img;
int hits, missed, falseAlarms;
int totalHits, totalMissed, totalFalseAlarms;
int found;
float distance;
int refcount;
ObjectPos* ref;
int detcount;
ObjectPos* det;
int error = 0;
int* pos;
int* neg;
pos = (int*) cvAlloc(rocsize * sizeof(*pos));
neg = (int*) cvAlloc(rocsize * sizeof(*neg));
for (i = 0; i < rocsize; i++) {
pos[i] = neg[i] = 0;
}
printf("+================================+======+======+======+\n");
printf("| File Name | Hits |Missed| False|\n");
printf("+================================+======+======+======+\n");
fprintf(resultados,
"+================================+======+======+======+\n");
fprintf(resultados,
"| File Name | Hits |Missed| False|\n");
fprintf(resultados,
"+================================+======+======+======+\n");
//fprintf (resultados, "%d\n",framesCnt);
totalHits = totalMissed = totalFalseAlarms = 0;
while (!feof(info)) {
fscanf(info, "%s %d", filename, &refcount);
img = imread(fullname);
if (!img.data) {
cout << "ow" << endl;
return -1;
}
ref = (ObjectPos*) cvAlloc(refcount * sizeof(*ref));
for (i = 0; i < refcount; i++) {
error = (fscanf(info, "%d %d %d %d", &x, &y, &width, &height)
!= 4);
if (error)
break;
ref[i].x = 0.5F * width + x;
ref[i].y = 0.5F * height + y;
ref[i].width = sqrt(0.5F * (width * width + height * height));
ref[i].found = 0;
ref[i].neghbors = 0; //in the new cascade, where to get the neighbors?
}
vector<Rect> obj_detectados;
Rect retang;
if (!error) {
totaltime -= time(0);
cascade.detectMultiScale(img, obj_detectados, scale_factor, 4, 0
//|CV_HAAR_FIND_BIGGEST_OBJECT
// |CV_HAAR_DO_ROUGH_SEARCH
| CV_HAAR_SCALE_IMAGE, Size(25, 15));
totaltime += time(0);
if (obj_detectados.size() == 0) {
detcount = 0;
} else {
detcount = obj_detectados.size();
}
det = (detcount > 0) ?
((ObjectPos*) cvAlloc(detcount * sizeof(*det))) : NULL;
hits = missed = falseAlarms = 0;
for (vector<Rect>::const_iterator r = obj_detectados.begin();
r != obj_detectados.end(); r++, i++) {
Point r1, r2;
r1.x = (r->x);
r1.y = (r->y);
r2.x = (r->x + r->width);
r2.y = (r->y + r->height);
retang.x = r1.x;
retang.y = r1.y;
retang.width = abs(r2.x - r1.x);
retang.height = abs(r2.y - r1.y);
if (saveDetected) {
rectangle(img, retang, Scalar(0, 0, 255), 3, CV_AA);
}
det[i].x = 0.5F*r->width + r->x;
det[i].y = 0.5F*r->height + r->y;
det[i].width = sqrt(0.5F * (r->width * r->width
+ r->height * r->height));
det[i].neghbors = 1; // i don't know if it will work...
// det[i].neghbors = r.neighbors; --- how to do it in the new version??
found = 0;
for (j = 0; j < refcount; j++) {
distance = sqrtf( (det[i].x - ref[j].x) * (det[i].x - ref[j].x) +
(det[i].y - ref[j].y) * (det[i].y - ref[j].y) );
//cout << distance << endl;
if( (distance < ref[j].width * maxPosDiff) &&
(det[i].width > ref[j].width / maxSizeDiff) &&
(det[i].width < ref[j].width * maxSizeDiff) )
{
ref[j].found = 1;
ref[j].neghbors = MAX( ref[j].neghbors, det[i].neghbors );
found = 1;
}
}
if (!found) {
falseAlarms++;
neg[MIN(det[i].neghbors, rocsize - 1)]++;
//neg[MIN(0, rocsize - 1)]++;
}
}
//imshow("teste", img);
if (saveDetected) {
//strcpy(detfilename, detname);
//strcat(detfilename, filename);
//strcpy(filename, detfilename);
imwrite(fullname, img);
//cvvSaveImage(fullname, img);
}
for (j = 0; j < refcount; j++) {
if (ref[j].found) {
hits++;
//pos[MIN(0, rocsize - 1)]++;
pos[MIN(ref[j].neghbors, rocsize - 1)]++;
} else {
missed++;
}
}
totalHits += hits;
totalMissed += missed;
totalFalseAlarms += falseAlarms;
printf("|%32.64s|%6d|%6d|%6d|\n", filename, hits, missed,
falseAlarms);
//printf("+--------------------------------+------+------+------+\n");
fprintf(resultados, "|%32.64s|%6d|%6d|%6d|\n", filename, hits,
missed, falseAlarms);
//fprintf(resultados,
// "+--------------------------------+------+------+------+\n");
fflush(stdout);
if (det) {
cvFree( &det);
det = NULL;
}
} /* if( !error ) */
//char c = (char) waitKey(10);
// if (c == 27)
// exit(0);
cvFree( &ref);
}
fclose(info);
printf("|%32.32s|%6d|%6d|%6d|\n", "Total", totalHits, totalMissed,
totalFalseAlarms);
fprintf(resultados, "|%32.32s|%6d|%6d|%6d|\n", "Total", totalHits,
totalMissed, totalFalseAlarms);
printf("+================================+======+======+======+\n");
fprintf(resultados,
"+================================+======+======+======+\n");
//printf("Number of stages: %d\n", nos);
//printf("Number of weak classifiers: %d\n", numclassifiers[nos - 1]);
printf("Total time: %f\n", totaltime);
fprintf(resultados, "Total time: %f\n", totaltime);
/* print ROC to stdout */
for (i = rocsize - 1; i > 0; i--) {
pos[i - 1] += pos[i];
neg[i - 1] += neg[i];
}
//fprintf(stderr, "%d\n", nos);
for (i = 0; i < rocsize; i++) {
fprintf(stderr, "\t%d\t%d\t%f\t%f\n", pos[i], neg[i],
((float) pos[i]) / (totalHits + totalMissed),
((float) neg[i]) / (totalHits + totalMissed));
}
cvFree( &pos);
cvFree( &neg);
}
return 0;
}
My doubt is about the det[i].neghbors = r.neighbors; in the old performance.cpp. How I retrieve the neighbors in this new version?
Anyone could help me to convert opencv_performance to run the new cascades from opencv_traincascade?
Many thanks!