raylib-go: UploadMesh() panics when calling C

Calling UploadMesh() causes a panic: “runtime error: cgo argument has Go pointer to unpinned Go pointer”, similar to issue #263

//in rmodels.go:

// UploadMesh - Upload vertex data into a VAO (if supported) and VBO
func UploadMesh(mesh *Mesh, dynamic bool) {
 	C.UploadMesh(mesh.cptr(), C.bool(dynamic)) // <-- panics at call to C.UploadMesh()
}

I was able to make it work by adding a C function that generates a mesh:

Mesh GenMeshCustom(Vector3* vertices, unsigned short* indices, int vertexCount, int triCount)
{
	int indexCount = triCount * 3;

	Mesh mesh = { 0 };

	mesh.vertexCount = vertexCount;
	mesh.triangleCount = triCount;

	mesh.vertices = (float*)malloc(sizeof(float) * vertexCount * 3);
	mesh.colors = (char*)malloc(sizeof(unsigned char) * vertexCount * 4);
	mesh.indices = (short*)malloc(sizeof(unsigned short) * indexCount);

	Color color = WHITE;

	for (size_t i = 0; i < vertexCount; i++)
	{
		size_t vIndex = i * 3;
		mesh.vertices[vIndex] = vertices[i].x;
		mesh.vertices[vIndex + 1] = vertices[i].y;
		mesh.vertices[vIndex + 2] = vertices[i].z;

		size_t cIndex = i * 4;
		mesh.colors[cIndex] = color.r;
		mesh.colors[cIndex + 1] = color.g;
		mesh.colors[cIndex + 2] = color.b;
		mesh.colors[cIndex + 3] = color.a;
	}

	for (size_t i = 0; i < indexCount; i++) {
		mesh.indices[i] = indices[i];
	}

	UploadMesh(&mesh, false);

	return mesh;
}

and calling it from this binding:

func GenMeshCustom(vertices []Vector3, indices []uint16) Mesh {
	cVertCount := (C.int)(len(vertices))
	cTriCount := (C.int)(len(indices) / 3)
	cVerts := (*C.Vector3)(unsafe.Pointer(&vertices[0]))
	cIndices := (*C.ushort)(unsafe.Pointer(&indices[0]))

	ret := C.GenMeshCustom(cVerts, cIndices, cVertCount, cTriCount)
	v := newMeshFromPointer(unsafe.Pointer(&ret))
	return v
}

This works for my purposes, but probably isn’t a great general solution since it adds functions that aren’t part of raylib originally. I can’t figure out what it is about UploadMesh() that doesn’t work for cgo. The other bindings that pass Meshes and Models such as LoadModelFromMesh() work just fine.

About this issue

  • Original URL
  • State: closed
  • Created 8 months ago
  • Comments: 23 (23 by maintainers)

Commits related to this issue

Most upvoted comments

@gen2brain Sounds good, posted PR #307 for it.

@JupiterRider GenMeshCube() calls UploadMesh() internally, so you don’t need to call Upload separately. You only need to use UploadMesh() if you created the Mesh struct manually in your go code.