Skip to main content

ZOS-API interface 2024 R1

Example 24 - C#

Last update: 17.07.2025

C#

using System;
using ZOSAPI;
namespace CSharpStandaloneApplication
{
class Program
{
static void Main(string[] args)
{
// Find the installed version of OpticStudio
bool isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize();
// Note -- uncomment the following line to use a custom initialization path
//bool isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize(@"C:\Program Files\OpticStudio\");
if (isInitialized)
{
LogInfo("Found OpticStudio at: " + ZOSAPI_NetHelper.ZOSAPI_Initializer.GetZemaxDirectory());
}
else
{
HandleError("Failed to locate OpticStudio!");
return;
}
BeginStandaloneApplication();
}
static void BeginStandaloneApplication()
{
// Create the initial connection class
ZOSAPI_Connection TheConnection = new ZOSAPI_Connection();
// Attempt to create a Standalone connection
IZOSAPI_Application TheApplication = TheConnection.CreateNewApplication();
if (TheApplication == null)
{
HandleError("An unknown connection error occurred!");
return;
}
// Check the connection status
if (!TheApplication.IsValidLicenseForAPI)
{
HandleError("Failed to connect to OpticStudio: " + TheApplication.LicenseStatus);
return;
}
if (TheApplication.Mode != ZOSAPI_Mode.Server)
{
HandleError("User plugin was started in the wrong mode: expected Server, found " + TheApplication.Mode.ToString());
return;
}
IOpticalSystem TheSystem = TheApplication.PrimarySystem;
// creates new directory
string strPath = System.IO.Path.Combine(TheApplication.SamplesDir, @"API\CS");
System.IO.Directory.CreateDirectory(strPath);
// Set up primary optical system
TheSystem = TheApplication.CreateNewSystem(ZOSAPI.SystemType.NonSequential);
TheSystem.SystemData.MaterialCatalogs.AddCatalog("Schott");
string sampleDir = TheApplication.SamplesDir;
// Initializes NCE and loads surfaces
// Inserts objects
for (int a = 1; a <= 4; a++) TheNCE.InsertNewObjectAt(a);
// Gets reference to specific object
INCERow o2 = TheNCE.GetObjectAt(2);
INCERow o3 = TheNCE.GetObjectAt(3);
INCERow o4 = TheNCE.GetObjectAt(4);
INCERow o5 = TheNCE.GetObjectAt(5);
// Changes Object Type
TheNCE.GetObjectAt(1).ChangeType(o1.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.SourceEllipse));
o2.ChangeType(o2.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.AsphericSurface2));
o3.ChangeType(o3.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.StandardLens));
o4.ChangeType(o4.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.DetectorColor));
o5.ChangeType(o5.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.DetectorRectangle));
// Sets positions & materials
TheNCE.GetObjectAt(2).XPosition = 1.5;
TheNCE.GetObjectAt(2).ZPosition = 9.99;
TheNCE.GetObjectAt(2).Material = "ABSORB";
o3.YPosition = 1.5;
o3.ZPosition = 8.99;
o3.Material = "N-BK7";
o4.ZPosition = 10;
o5.RefObject = 4;
o5.ZPosition = 1e-3;
// Sets layout rays based on parameter number
TheNCE.GetObjectAt(1).GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par1).IntegerValue = 100;
// Sets analysis rays based on object data column
sourcedata.NumberOfAnalysisRays = (int)1E6;
o1.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par10).DoubleValue = 50;
o1.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par11).DoubleValue = 50;
o2.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par3).DoubleValue = 0.5;
o2.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par4).DoubleValue = 1;
o2.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par9).IntegerValue = 1;
o4.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par1).DoubleValue = 8.223;
o4.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par2).DoubleValue = 2.565;
o4.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par3).IntegerValue = 200;
o4.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par4).IntegerValue = 150;
double o5_x = 10.0;
double o5_y = 12.23;
o5.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par1).DoubleValue = o5_x;
o5.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par2).DoubleValue = o5_y;
o5.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par3).IntegerValue = 100;
o5.GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par4).IntegerValue = 100;
// Changes face type and coating properties
TheNCE.GetObjectAt(3).CoatScatterData.GetFaceData(0).FaceIs = ZOSAPI.Editors.NCE.FaceIsType.Absorbing;
TheNCE.GetObjectAt(3).CoatScatterData.GetFaceData(1).FaceIs = ZOSAPI.Editors.NCE.FaceIsType.ObjectDefault;
// changes scatter profile on face
o3_Scatter._S_Lambertian.ScatterFraction = 0.5;
// Removes pixel interpolation for the detector
o4.TypeData.UsePixelInterpolation = false;
// Setup and run the ray trace
ZOSAPI.Tools.RayTrace.INSCRayTrace NSCRayTrace = TheSystem.Tools.OpenNSCRayTrace();
NSCRayTrace.SplitNSCRays = false;
NSCRayTrace.ScatterNSCRays = true;
NSCRayTrace.UsePolarization = false;
NSCRayTrace.IgnoreErrors = true;
NSCRayTrace.SaveRays = false;
NSCRayTrace.ClearDetectors(0);
NSCRayTrace.RunAndWaitForCompletion();
NSCRayTrace.Close();
// Reads in values from NCE for detector settings
int obj = 4;
double x_half = TheSystem.NCE.GetObjectAt(obj).GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par1).DoubleValue;
double y_half = TheSystem.NCE.GetObjectAt(obj).GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par2).DoubleValue;
double x_pixels = (double)TheSystem.NCE.GetObjectAt(obj).GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par3).IntegerValue;
double y_pixels = (double)TheSystem.NCE.GetObjectAt(obj).GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par4).IntegerValue;
// Creates a new detector viewer analysis reference
ZOSAPI.Analysis.IA_ d4 = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.DetectorViewer);
d4_settings.Detector.SetDetectorNumber(4);
d4_settings.ShowAs = ZOSAPI.Analysis.DetectorViewerShowAsTypes.TrueColor;
// Creates System.Single[] buffers to store pixel data
// Required any time Interface Documentation shows a Single[] or Double[] output
Single[] rData = new Single[(int)(x_pixels * y_pixels)];
Single[] gData = new Single[(int)(x_pixels * y_pixels)];
Single[] bData = new Single[(int)(x_pixels * y_pixels)];
// Reads values from detector color raw data
// Prints RGB data into single file
d4_raw.FillValues((uint)(x_pixels * y_pixels), rData, gData, bData);
System.Text.StringBuilder sbReport = new System.Text.StringBuilder();
sbReport.Append(string.Concat("Red: ", string.Join(", ", rData), "\nGreen: ", string.Join(", ", gData), "\nBlue: ", string.Join(", ", bData)));
string resFile = TheApplication.SamplesDir + "\\API\\CS\\e24_nsc_detector_rgb.txt";
System.IO.File.WriteAllText(resFile, sbReport.ToString());
// Changes default values for Detector Viewer
// Plots the Incoherent Irradiance in False Color
ZOSAPI.Analysis.IA_ d5 = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.DetectorViewer);
d5_set.ShowAs = ZOSAPI.Analysis.DetectorViewerShowAsTypes.FalseColor;
double[,] d5_values = d5_results.GetDataGrid(0).Values;
sbReport.Clear();
double max_value = 0.0;
for (int i = 0; i < d5_values.GetLength(0); i++)
{
for (int j = 0; j < d5_values.GetLength(1); j++)
{
if (d5_values[i, j] > max_value) max_value = d5_values[i, j];
sbReport.Append(d5_values[i, j] + "\t");
}
sbReport.AppendLine("");
}
resFile = TheApplication.SamplesDir + "\\API\\CS\\e24_nsc_detector_falsecolor.txt";
System.IO.File.WriteAllText(resFile, sbReport.ToString());
Console.WriteLine("The max value is {0:F2}", max_value);
// Saves current system in memory
TheSystem.SaveAs(TheApplication.SamplesDir + "\\API\\CS\\e24_nsc_detectors.zos");
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
// Clean up
FinishStandaloneApplication(TheApplication);
}
static void FinishStandaloneApplication(IZOSAPI_Application TheApplication)
{
// Note - TheApplication will close automatically when this application exits, so this isn't strictly necessary in most cases
if (TheApplication != null)
{
TheApplication.CloseApplication();
}
}
static void LogInfo(string message)
{
// TODO - add custom logging
Console.WriteLine(message);
}
static void HandleError(string errorMessage)
{
// TODO - add custom error handling
throw new Exception(errorMessage);
}
}
}
Definition: ZemaxService.cs:198
IZOSAPI_Application CreateNewApplication()
Attempts to launch a new instance of Optic Studio in 'headless' mode. Note that although the Optic St...
Definition: ZemaxService.cs:863
Definition: IAR_Base.cs:286
void FillValues(uint fullSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)][In][Out]float[] rData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)][In][Out]float[] gData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)][In][Out]float[] bData)
Retries all RGB data at once, into the specified buffers.
double[,] Values
Definition: IAR_Base.cs:229
Properties and methods for retrieving analysis window data. This interface can be accessed via the IA...
Definition: IAR_Base.cs:21
IAR_DataGridRgb GetDataGridRgb(int index)
IAR_DataGrid GetDataGrid(int index)
Base interface for all analysis windows. This interface can be accessed via the I_Analyses interface.
Definition: IA_Base.cs:29
IAR_ GetResults()
Gets the result data (if available) for the current analysis.
IAS_ GetSettings()
Gets the settings for the current analysis.
IMessage ApplyAndWaitForCompletion()
Re-runs the analysis with the current settings and waits for it to finish calculating.
Definition: IAS_DetectorViewer.cs:23
IAS_Detector Detector
Definition: IAS_DetectorViewer.cs:25
double DoubleValue
Gets or sets the double precision value of this cell. Note that if DataType is not CellDataType....
Definition: InterfacesEditors.cs:340
int IntegerValue
Gets or sets the integer value of this cell. Note that if DataType is not CellDataType....
Definition: InterfacesEditors.cs:319
INCECoatScatterFaceData GetFaceData(int faceNumber)
Gets coat/scatter data for the specified face (0 to NumberOfFaces-1).
int NumberOfRays
Definition: InterfacesNCE.cs:6306
FaceIsType FaceIs
Definition: InterfacesNCE.cs:6260
bool ChangeScatterModelSettings(IObjectScatteringSettings newSettings)
IObjectScatteringSettings CreateScatterModelSettings(ObjectScatteringTypes type)
string Coating
Definition: InterfacesNCE.cs:6273
All data for a Non-Sequential Component Editor object. This interface can be accessed via the INonSeq...
Definition: InterfacesNCE.cs:1198
double ZPosition
Definition: InterfacesNCE.cs:1464
double XPosition
Definition: InterfacesNCE.cs:1448
string Material
Definition: InterfacesNCE.cs:1484
INCECoatScatterData CoatScatterData
Gets the object Coat/Scatter data.
Definition: InterfacesNCE.cs:1355
bool ChangeType(IObjectTypeSettings settings)
Changes the current object to the specified type. Use GetObjectTypeSettings to get the relevant setti...
IEditorCell GetObjectCell(ObjectColumn Col)
Gets the specified object cell data.
IObjectTypeSettings GetObjectTypeSettings(ObjectType type)
Create the settings for the specified type. Use this method to specify any extra data required to cha...
This interface defines all properties and methods needed to interact with the Non-Sequential Componen...
Definition: InterfacesNCE.cs:363
INCERow GetObjectAt(int ObjectNumber)
Gets the object at the specified position.
INCERow InsertNewObjectAt(int ObjectNumber)
Inserts a new object at the specified position.
Scatter model settings for a specific face. This interface can be accessed via the INCECoatScatterFac...
Definition: InterfacesNCE.cs:6323
Definition: InterfacesNCE.cs:4809
Represent a complete optical system. A IOpticalSystem corresponds to a single .ZMX file....
Definition: Interfaces.cs:690
void SaveAs(string fileName)
Saves the current system to the specified file. All future calls to Save will use the same file.
ISystemData SystemData
Data for configuring everything in the System Explorer.
Definition: Interfaces.cs:848
I_Analyses Analyses
Gets the analyses for the current system.
Definition: Interfaces.cs:928
INonSeqEditor NCE
Gets the non-sequential component editor.
Definition: Interfaces.cs:887
IOpticalSystemTools Tools
Gets an interface used to run various tools on the optical system.
Definition: Interfaces.cs:935
This interface contains all information about the current ZOS-API connection, as well as methods for ...
Definition: Interfaces.cs:264
IOpticalSystem CreateNewSystem(SystemType mode)
Creates a new empty optical system, in the specified mode.
bool IsValidLicenseForAPI
Gets a value indicating whether this the API is currently useable.
Definition: Interfaces.cs:290
ZOSAPI_Mode Mode
Gets the current connetion mode. Use this to check if Optic Studio is expecting a user operand / anal...
Definition: Interfaces.cs:309
LicenseStatusType LicenseStatus
Gets the license status. Note that this displays the license edition if successful,...
Definition: Interfaces.cs:283
void CloseApplication()
Shut down the Optic Studio process.
IOpticalSystem PrimarySystem
Gets the primary system. When Mode is ZOSAPI_Mode.Server, this will initially be an empty sequential ...
Definition: Interfaces.cs:331
string SamplesDir
Gets the full path for the current user's samples directory (in the My Documents\Zemax\Samples\ folde...
Definition: Interfaces.cs:508
bool RunAndWaitForCompletion()
Sames as calling Run followed by WaitForCompletion.
bool Close()
Closes this tool and frees up and associated resources.
Interfaces and methods for running a non-sequential ray trace. This interface can be accessed via the...
Definition: RayTrace.cs:45
ErrorType ClearDetectors(int DetectorNumber)
Clears the specified detectors.
Definition: IAR_Base.cs:11
Definition: IAS_DetectorViewer.cs:6
Definition: IAS_FieldCurvatureAndDistortion.cs:5
Definition: IAS_FieldCurvatureAndDistortion.cs:5
Definition: InterfacesNCE.cs:19
Definition: InterfacesEditors.cs:12
The ZOSAPI namespace contains classes for initially connecting to zemax. See also ZOSAPI_Connection,...
Definition: IAS_FieldCurvatureAndDistortion.cs:5
ZOSAPI_Mode
Definition: Interfaces.cs:80

Connect with Ansys