Skip to content

Instantly share code, notes, and snippets.

@elaughli elaughli/obj2usdz.mm
Created Dec 12, 2018

Embed
What would you like to do?
function to convert a saved obj file to USDZ in objective-c
// path to documents directory to save our usdc file
NSString* usdcPath = [documentsDirectory stringByAppendingPathComponent:@"usdcExample.usdc"];
NSURL *usdcUrl = [NSURL fileURLWithPath: usdcPath];
// path to documents directory to save our final usdz file
NSString* usdzPath = [documentsDirectory stringByAppendingPathComponent:@"usdzExample.usdz"];
NSURL *usdzUrl = [NSURL fileURLWithPath:usdzPath];
// load the .obj file at filePath as an MDLAsset
NSURL *url = [NSURL fileURLWithPath:filePath];
MDLAsset *asset = [[MDLAsset alloc]initWithURL:url];
// ensure the MDLAsset can write the desired extensions
// NOTE: including for example purposes.
// this is false, but ideally this would be true and would handle everything for us
if([MDLAsset canExportFileExtension:@"usdz"]){
NSLog(@"able to export as usdz");
} else {
NSLog(@"NOT able to export as usdz");
}
// usda is supported (USD ascii format)
if([MDLAsset canExportFileExtension:@"usda"]){
NSLog(@"able to export as usda");
}
// usdc is supported (USD binary format)
if([MDLAsset canExportFileExtension:@"usdc"]){
NSLog(@"able to export as usdc");
// save the usdc file
[asset exportAssetToURL:usdcUrl];
}
// rename the usdc to usdz because that's all it takes
NSError *renameErr;
NSFileManager *fm = [[NSFileManager alloc] init];
BOOL mvResult = [fm moveItemAtPath:usdcPath toPath:usdzPath error:& renameErr];
if(! mvResult){
NSLog(@"Error renaming usdz file: %@", [renameErr localizedDescription]);
}
@piemonte

This comment has been minimized.

Copy link

commented Dec 14, 2018

nice discovery! been needing to figure this out for a while. i made a swift version for your technique too.

📎 https://github.com/piemonte/obj2usdz/blob/master/Source/MDLAsset%2Busdz.swift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.