Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Metal line width

Tags:

ios

metal

I would like to set the width of a line that I'm drawing in Metal. I can set the size of a point with point_size as explained here:

https://developer.apple.com/library/prerelease/ios/documentation/Metal/Reference/MTLRenderCommandEncoder_Ref/index.html

But, I'm not sure how it works with lines.

like image 478
arthur Avatar asked Jan 29 '15 06:01

arthur


Video Answer


2 Answers

Short answer would be there is no way to control line width in the same way as a point size in Metal. Even in OpenGL graphics API, the function to do this (which used to exist as gllinewidth function) is now deprecated.

An option would be to draw the line as a quad (a box), with two triangles. This would let you control the width of the line.

If you want to stick to the line primitive itself, for some particular reason, the equivalent OpenGL question has been asked on StackOverflow already as seen here. The shader can be simple translated to Metal shading API.

like image 168
codingminion Avatar answered Oct 18 '22 19:10

codingminion


If you're dead set on using lines instead of drawing a 2D box with two rectangles you can draw multiple lines next to each other. You can do that by drawing the same two vertices multiple times with one drawPrimitives call, just increase the instanceCount to simulate the thickness and then in your vertex shader function you could use your vertex_id and a modulus operation or some other type of logic to translate the position of the line to simulate thickness. This will probably be a lot easier than trying to do something fancy in a fragment shader.

If you are drawing multiple lines, multiply your instanceCount by the thickness you want and adjust your vertex shader function logic to place those additional lines next to each other.

I experimented with this and found this to be a pretty cumbersome process. As you need additional math to position the extra lines to thicken correctly. For example if you're drawing a horizontal line and want to increase thickness by two you'd want to modify the y value, but if it's vertical you'd want to modify the x. Drawing at an angle gets more complicated. You'll also run into issues trying to match lengths with widths if you're attempting to draw shapes.

I think it's much better to just draw two triangles to make a rectangle to fake a line. The math will be much easier and simpler to understand.

In Geometry, Euclid's lines do not have any width, they only have length, the width they get during drawing is simply for representation. So while I think lines may be good for debugging and development, like for displaying vectors or creating a grid to see scale, they're not what you want if you're trying to style them to present them to users. In that case it's the wrong tool for the job.

like image 27
Bjorn Avatar answered Oct 18 '22 18:10

Bjorn