Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read half precision floating point numbers from a Metal texture with Swift?

Tags:

ios

swift

metal

My Metal compute kernel writes to a texture with format MTLPixelFormat.RG16Float, half precision floating point numbers. This is because Metal does not support writing to 32 bits floating point textures.

I need to read these half precision numbers in my swift program? I have moved the texture into a Swift UInt8 array, but I cannot figure out how to convert the half precision floats into Swift floats.

like image 817
Hallgrim Avatar asked Oct 23 '14 07:10

Hallgrim


2 Answers

Actually @Muzza's answer is not correct. You could have read them from a float16_t pointer and cast them to a normal float32_t. No need to use external libraries. Just import the arm_neon header.

like image 138
aledalgrande Avatar answered Oct 28 '22 19:10

aledalgrande


EDIT: the below answer was written for Swift v1. Later versions of Swift added support via the float16_t type. Manual conversion may still be useful in some cases.


There is no built in method to interpret halfs as floats, you have to convert it yourself. The half datatype is a floating point format following IEEE 754. You can read the values in your swift program using UInt16 and then convert from this to a float value. I don't know of any conversion routines written in Swift, but here are two libraries written in C++ that could be converted easily enough:

http://mrob.com/pub/math/s10e5.h.txt

http://half.sourceforge.net/

In the first library it is the function operator float() that you need to convert, that takes the UInt16 member variable _h and outputs a float.

like image 38
Muzza Avatar answered Oct 28 '22 18:10

Muzza