Skip to main content

ZOS-API interface 2024 R1

Example 21 - 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);
// Add your custom code here...
// Create a new non-sequential file
TheSystem.New(false);
TheSystem.MakeNonSequential();
// Add new catalog MISC
TheSystem.SystemData.MaterialCatalogs.AddCatalog("MISC");
// Set Wave #1 to 0.47 micron
TheSystem.SystemData.Wavelengths.GetWavelength(1).Wavelength = 0.47;
// Use lumens as the source unit
TheSystem.SystemData.Units.SourceUnits = ZOSAPI.SystemData.ZemaxSourceUnits.Lumens;
// Add 4 more objects
INonSeqEditor TheNCE = TheSystem.NCE;
TheNCE.AddObject();
TheNCE.AddObject();
TheNCE.AddObject();
TheNCE.AddObject();
// Set 1st object as a Source File
INCERow Object_1 = TheNCE.GetObjectAt(1);
IObjectTypeSettings Typeset_SourceFile = Object_1.GetObjectTypeSettings(ObjectType.SourceFile);
Typeset_SourceFile.FileName1 = "RAYFILE_LB_T67C_100K_190608_ZEMAX.DAT";
Object_1.ChangeType(Typeset_SourceFile);
Object_1.GetObjectCell(ObjectColumn.Par2).IntegerValue = 1000;
Object_1.GetObjectCell(ObjectColumn.Par3).DoubleValue = 2.485572;
Object_1.GetObjectCell(ObjectColumn.Par8).DoubleValue = 0.47;
Object_1.GetObjectCell(ObjectColumn.Par9).DoubleValue = 0.47;
// Edit source data of object 1
// SourcesData includes all the settings in Object Properties > Sources
Object_1.SourcesData.PrePropagation = -0.2;
Object_1.SourcesData.ArrayType = ArrayMode.Rectangular;
Object_1.SourcesData.ArrayNumberX = 5;
Object_1.SourcesData.ArrayNumberY = 5;
// Set 2nd object as CAD Part: STEP/IGES/SAT
INCERow Object_2 = TheNCE.GetObjectAt(2);
IObjectTypeSettings Typeset_CADPartSTEPIGESSAT = Object_1.GetObjectTypeSettings(ObjectType.CADPartSTEPIGESSAT);
Typeset_CADPartSTEPIGESSAT.FileName1 = "LB_T67C_190608_GEOMETRY.STEP";
Object_2.ChangeType(Typeset_CADPartSTEPIGESSAT);
// Set Rays Ignore Object = Always for object 2
// TypeData includes all settings in Object Properties > Type
Object_2.TypeData.RaysIgnoreObject = RaysIgnoreObjectType.Always;
// Set 3rd object as Cylinder Volume
INCERow Object_3 = TheNCE.GetObjectAt(3);
IObjectTypeSettings Typeset_CylinderVolume = Object_3.GetObjectTypeSettings(ObjectType.CylinderVolume);
Object_3.ChangeType(Typeset_CylinderVolume);
// Set positions, material and parameters
Object_3.GetObjectCell(ObjectColumn.ZPosition).DoubleValue = 0.8;
Object_3.GetObjectCell(ObjectColumn.Material).Value = "PMMA";
Object_3.GetObjectCell(ObjectColumn.Par1).DoubleValue = 1.2;
Object_3.GetObjectCell(ObjectColumn.Par2).DoubleValue = 0.1;
Object_3.GetObjectCell(ObjectColumn.Par3).DoubleValue = 1.2;
// Make Face 1 of object 3 has Lambertian scattering properties
// To set scatter properties, you need to first create "ScatteringSettings" by "CreateScatterModelSettings()" method.
// And then assign is to object 3 by ChangeScatterModelSettings().
ScatType_Lam._S_Lambertian.ScatterFraction = 1;
// Make object 3 a volume scattering material
// VolumePhysicsData includes all settings in Object Properties > VolumePhysics.
// Use Photoluminescence model
Object_3.VolumePhysicsData.Model = VolumePhysicsModelType.PhotoluminescenceModel;
// Use Standard Model
Photo_setting.BasicAlgorithm = false;
// Set absorb, emission and quantum yield spectrum files
Photo_setting.AbsorptionFile = "_sample_3.ZAS";
Photo_setting.EmissionFile = "_sample_3.ZES";
Photo_setting.QuantumYield = "_sample_3.ZQE";
// Set efficiency spectrum to quantum yield
Photo_setting.EfficiencySpectrum = EfficiencySpectrumType.QuantumYield;
// Set photoluminescence parameters
Photo_setting.ExtinctionCoefficient = 1E+05;
Photo_setting.ExtinctionWavelength = 0.47;
Photo_setting.PLDensity = 3.1E+017;
// Set model to ignore mie scattering
Photo_setting.ConsiderMieScattering = false;
// Set 4th object as Standard Lens
INCERow Object_4 = TheNCE.GetObjectAt(4);
IObjectTypeSettings Typeset_StandardLens = Object_4.GetObjectTypeSettings(ObjectType.StandardLens);
Object_4.ChangeType(Typeset_StandardLens);
// Set positions
Object_4.GetObjectCell(ObjectColumn.ZPosition).DoubleValue = 0.9;
// To set solve for any cell, you need to first create a "ISolveData" by "CreateSolveType()" method.
// And then assign it to the cell.
ISolveData Solve_ObjPick = Object_4.GetObjectCell(ObjectColumn.Material).CreateSolveType(SolveType.ObjectPickup);
Solve_ObjPick._S_ObjectPickup.Object = 3;
// Set parameters
Object_4.GetObjectCell(ObjectColumn.Material).SetSolveData(Solve_ObjPick);
Object_4.GetObjectCell(ObjectColumn.Par3).DoubleValue = 1.2;
Object_4.GetObjectCell(ObjectColumn.Par4).DoubleValue = 1.2;
Object_4.GetObjectCell(ObjectColumn.Par5).DoubleValue = 1.2;
Object_4.GetObjectCell(ObjectColumn.Par6).DoubleValue = -1.2;
Object_4.GetObjectCell(ObjectColumn.Par8).DoubleValue = 1.2;
Object_4.GetObjectCell(ObjectColumn.Par9).DoubleValue = 1.2;
// Set 5th object as Detector Color
INCERow Object_5 = TheNCE.GetObjectAt(5);
IObjectTypeSettings Typeset_DetectorColor = Object_5.GetObjectTypeSettings(ObjectType.DetectorColor);
Object_5.ChangeType(Typeset_DetectorColor);
// Set positions, material and parameters
Object_5.GetObjectCell(ObjectColumn.ZPosition).DoubleValue = 7;
Object_5.GetObjectCell(ObjectColumn.Material).Value = "ABSORB";
Object_5.GetObjectCell(ObjectColumn.Par3).IntegerValue = 150;
Object_5.GetObjectCell(ObjectColumn.Par4).IntegerValue = 150;
// Open NSC Ray Trace tool and turn on Scatter NSC Rays and Ignore Errors
INSCRayTrace RayTraceControl = TheSystem.Tools.OpenNSCRayTrace();
RayTraceControl.SplitNSCRays = false;
RayTraceControl.ScatterNSCRays = true;
RayTraceControl.UsePolarization = false;
RayTraceControl.IgnoreErrors = true;
RayTraceControl.SaveRays = false;
// Trace rays and report the progress when it's running.
// Note that, instead an RunAndWaitCompletion(), Run() is used so that
// the code will just go on without waiting the tracing finishs.
// We will check the progress of tracing by a while loop.
// You can check the properties "Progress", which is percentage integer data (1-100)
Console.Write("Starting Tracing... ");
RayTraceControl.ClearDetectors(0);
RayTraceControl.Run();
while (RayTraceControl.Progress != 100)
{
System.Threading.Thread.Sleep(1000);
Console.Write("\b\b\b\b" + RayTraceControl.Progress.ToString("000") + "%");
}
RayTraceControl.Close();
Console.WriteLine("\nFinished!");
// Open two detector viewers for showing results in angle space and position space
// Detector Viewer has its own settings interface: IAS_DetectorViewer.
// Note that not all analyses have a specific settings interface.
I_Analyses TheAnalysis = TheSystem.Analyses;
IA_ Det1 = TheAnalysis.New_DetectorViewer();
Det_Set1.ShowAs = DetectorViewerShowAsTypes.TrueColor;
Det_Set1.Smoothing = 3;
IA_ Det2 = TheAnalysis.New_DetectorViewer();
Det_Set2.ShowAs = DetectorViewerShowAsTypes.TrueColor;
Det_Set2.Smoothing = 3;
Det_Set2.DataType = DetectorViewerShowDataTypes.AngleSpace;
TheSystem.SaveAs(TheApplication.SamplesDir + "\\API\\CS\\e21_White_LED_Phosphor.zos");
Console.Write("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
Methods and interfaces for opening, closing, and retrieving analyses. This interface can be accessed ...
Definition: I_Analyses.cs:784
IA_ New_DetectorViewer()
Open a new Detector Viewer window.
Base interface for all analysis windows. This interface can be accessed via the I_Analyses interface.
Definition: IA_Base.cs:29
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
double DoubleValue
Gets or sets the double precision value of this cell. Note that if DataType is not CellDataType....
Definition: InterfacesEditors.cs:340
string Value
Gets or sets the value of this cell. Note that this method can be used regardless of the DataType.
Definition: InterfacesEditors.cs:359
SolveStatus SetSolveData(ISolveData Data)
Updates the system with the new solve type settings (see also CreateSolveType and GetSolveData).
ISolveData CreateSolveType(SolveType type)
Creates the solve type settings for the specified solve type. Note that SetSolveData must be used to ...
int IntegerValue
Gets or sets the integer value of this cell. Note that if DataType is not CellDataType....
Definition: InterfacesEditors.cs:319
Base interface for all solve types. This interface can be accesed via the IEditorCell interface....
Definition: InterfacesEditors.cs:563
INCECoatScatterFaceData GetFaceData(int faceNumber)
Gets coat/scatter data for the specified face (0 to NumberOfFaces-1).
int NumberOfRays
Definition: InterfacesNCE.cs:6306
bool ChangeScatterModelSettings(IObjectScatteringSettings newSettings)
IObjectScatteringSettings CreateScatterModelSettings(ObjectScatteringTypes type)
All data for a Non-Sequential Component Editor object. This interface can be accessed via the INonSeq...
Definition: InterfacesNCE.cs:1198
INCEVolumePhysicsData VolumePhysicsData
Gets the object Volume Physics data.
Definition: InterfacesNCE.cs:1383
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...
IVolumePhysicsModelSettings ModelSettings
Gets the model settings for the current model type.
Definition: InterfacesNCE.cs:6573
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 AddObject()
Adds a new object as the last object in the system.
Scatter model settings for a specific face. This interface can be accessed via the INCECoatScatterFac...
Definition: InterfacesNCE.cs:6323
This interface is used for selecting any files required by a object, and for changing object types....
Definition: InterfacesNCE.cs:1110
Volume Physics Model - Phosphors and Fluorescence. This interface can be accessed via the INCEVolumeP...
Definition: InterfacesNCE.cs:6699
string QuantumYield
Definition: InterfacesNCE.cs:6717
IVMPS_PhotoluminscenceModel _S_PhotoluminescenceModel
Definition: InterfacesNCE.cs:6593
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
void New(bool saveIfNeeded)
Clears all data in the current system and resets it to a default state.
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
bool MakeNonSequential()
Makes the system non-sequential if it is not already. Note that any sequential data will be lost.
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
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 Run()
Start the tool. Note that for synchronous tools (see IsAsynchronous), this call will block until comp...
bool Close()
Closes this tool and frees up and associated resources.
int Progress
Gets the progress of the current tool, if supported.
Definition: Tools.cs:541
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: IAS_DetectorViewer.cs:6
Definition: IAS_FieldCurvatureAndDistortion.cs:5
DetectorViewerShowAsTypes
Definition: I_ShowAs.cs:34
DetectorViewerShowDataTypes
Definition: I_ShowAs.cs:56
Definition: InterfacesNCE.cs:19
VolumePhysicsModelType
Definition: InterfacesNCE.cs:6537
ObjectColumn
Definition: InterfacesNCE.cs:199
RaysIgnoreObjectType
Definition: InterfacesNCE.cs:5689
EfficiencySpectrumType
Definition: InterfacesNCE.cs:6673
ObjectScatteringTypes
Definition: InterfacesNCE.cs:6200
ObjectType
All supported non-sequential object types.
Definition: InterfacesNCE.cs:38
ArrayMode
Definition: InterfacesNCE.cs:5827
Definition: InterfacesEditors.cs:12
SolveType
All solve types available. Note that only a portion of the types are available for any given IEditorC...
Definition: InterfacesEditors.cs:483
Definition: InterfacesSE.cs:11
Definition: RayTrace.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