Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Modification of Cameron.'s code from http://forum.unity3d.com/threads/can-i-send-data-as-w-via-vertex-data.114111/#post-769621
- // by Alex May 2015
- // Packs a normalised direction vector into a single float
- float PackVector3(Vector3 vector3)
- {
- // Scale Bias values to 8 bit bytes in range of 0 to 255
- int x = PackFloat(vector3.x);
- int y = PackFloat(vector3.y);
- int z = PackFloat(vector3.z);
- uint packedByte = (uint)((x << 20) | (y << 10) | z);
- float packedFloat = (float)((double)packedByte / (double)(1<<30));
- return packedFloat;
- }
- // UnPack normal from float
- Vector3 UnPackVector3(float src)
- {
- Vector3 output = Vector3.zero;
- // Unpack to 0...1 range
- output.x = Frac(src);
- output.y = Frac(src * 1024.0f);
- output.z = Frac(src * 1048576.0f);
- // Bias to -1..1 range
- output = (output * 2f) - Vector3.one;
- return output;
- }
- void TestPackVector3(Vector3 normal)
- {
- normal.Normalize();
- float f = PackVector3(normal);
- Vector3 result = UnPackVector3(f).normalized;
- Vector3 error = normal - result;
- string s = "";
- s += "Testing: (" + normal.x + ", " + normal.y + ", " + normal.z + ")\n";
- s += "Result : (" + result.x + ", " + result.y + ", " + result.z + ")\n";
- s += "Error : (" + error.x + ", " + error.y + ", " + error.z + ")\n";
- Debug.Log(s);
- }
- // Helper method that converts a float in the
- // range(-1..1) to a 10 bit int in range(0..1023)
- int PackFloat(float x)
- {
- x = (x + 1.0f) * 0.5f; // Bias
- return (int)(x*1023.0f); // Scale
- }
- // Helper method to emulate CG's frac(x)
- float Frac(float x)
- {
- return x - Mathf.Floor(x);
- }
- /* Cg code for your shader
- inline float3 UnPackVector3(float src) {
- return (frac(float3(1.0f, 1024.0f, 1048576.0f) * src) * 2) - 1;
- }
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement