Skip to content

Instantly share code, notes, and snippets.

@AaronMeyers
Created September 24, 2018 19:15
Show Gist options
  • Select an option

  • Save AaronMeyers/fe882ab6448ceaa182612b613bb4e120 to your computer and use it in GitHub Desktop.

Select an option

Save AaronMeyers/fe882ab6448ceaa182612b613bb4e120 to your computer and use it in GitHub Desktop.
using System.IO;
using UnityEditor;
using UnityEngine;
public class RoughnessHelper
{
[MenuItem("Assets/Convert Roughness Texture %#r")]
static void ConvertRoughnessTexture()
{
if ( Selection.objects.Length == 1 )
{
var texture = Selection.activeObject as Texture2D;
ConvertRoughnessTexture( texture );
}
else if ( Selection.objects.Length > 1 )
{
for ( int i=0; i<Selection.objects.Length; i++ )
{
var texture = Selection.objects[i] as Texture2D;
ConvertRoughnessTexture( texture );
}
}
}
static void ConvertRoughnessTexture( Texture2D texture )
{
if ( texture && texture.name.Contains( "Roughness" ) )
{
var path = AssetDatabase.GetAssetPath( texture.GetInstanceID() );
var fileName = Path.GetFileName( path );
var dirName = Path.GetDirectoryName( path );
var metallicTexture = AssetDatabase.LoadAssetAtPath<Texture2D>( dirName + '\\' + fileName.Replace( "Roughness", "Metallic" ) );
var output = new Texture2D( texture.width, texture.height, TextureFormat.ARGB32, false );
var roughnessPixels = texture.GetPixels( 0 );
var metallicPixels = metallicTexture ? metallicTexture.GetPixels() : null;
var pixels = new Color[texture.width * texture.height];
for ( int x = 0; x < texture.width; x++ )
{
for ( int y = 0; y < texture.height; y++ )
{
var index = x + y * texture.width;
var smoothness = 1.0f - roughnessPixels[index].r;
if ( metallicTexture )
{
var metallic = metallicPixels[index];
pixels[index] = new Color( metallic.r, metallic.g, metallic.b, smoothness );
}
else
{
pixels[index] = new Color( 0, 0, 0, smoothness );
}
}
}
output.SetPixels( pixels );
var png = output.EncodeToPNG();
var destinationPath = new DirectoryInfo( Application.dataPath ).Parent.FullName + '\\' + Path.GetDirectoryName( path );
var destinationFilename = fileName.Replace( "Roughness", "MetallicSmoothness" );
File.WriteAllBytes( destinationPath + '\\' + destinationFilename, png );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment