====================
Exchange Integration
====================

Introduction
============

HOOPS Exchange is Tech Soft 3D's CAD data integration library and is the recommended way to get model data from a CAD file into HOOPS Visualize Desktop. Through Exchange, you can access assembly information, visualization data, and PMI annotations for inspection or manipulation within the context of a HOOPS Visualize Desktop scene graph. A detailed introduction to HOOPS Exchange can be found `here <http://www.techsoft3d.com/products/hoops-toolkits/hoops-exchange/>`_.

Any file that can be loaded by the HOOPS Exchange libraries can be loaded into HOOPS Visualize Desktop. The interface described in this section is 
the way to connect HOOPS Visualize Desktop with HOOPS Exchange, and is supported on Windows, Linux, OSX, iOS, and Android.


.. _cc_exchange:

Important Note for C# Programmers
---------------------------------

The Exchange integration has a few limitations when using C#. Functions which expect C++ pointers cannot be called directly from C#. Instead, an intermediate step using CLI (Common Language Infrastructure) is required. The HOOPS Visualize Desktop solution provides the *cc_exchange_lib_vc1x* project which demonstrates how the C++/CLI interface is set up, allowing the C# programmer to access specific Exchange functionality that is otherwise only available in C++.

The project can be found at *Applications > Demo > cc_exchange_lib_vc1x*, and when compiled, generates the CLI interface in the form of a DLL. The DLL needs to be added as a reference to the C# project that invokes it. You will also find a sister project called *Applications > Demo > cc_exchange_vc1x*. This project is a demonstration on how you would invoke the CLI to call from your C# application through to C++ using the interface generated by *cc_exchange_lib_vc1x*.


.. _android_support:

Important Note for Android Developers
-------------------------------------

The Exchange libraries do not ship with a *x86_64* binary.
As a result, HOOPS Visualize Desktop can't build the Android sprocket for *x86_64*.
To get around this, you can edit your *local.properties* file and add the following line to compile the only supported architecture:

.. code-block:: none

	ndk.abis=arm64-v8a


Prerequisites
=============

Steps for integrating HOOPS Visualize Desktop with Exchange are delineated below:


Step 1: Install Exchange
------------------------

Exchange can be downloaded from the Tech Soft 3D `Developer Zone <https://developer.techsoft3d.com/hoops/exchange/downloads/latest/>`_. If you don't already have Exchange installed, install it now. You do not have to generate a separate key to use the Exchange component. The key will be embedded with your HOOPS Visualize Desktop license key. Note the Exchange installation directory.


Step 2: Set Up the Environment
------------------------------

The Exchange DLLs must be in the system path so that they can be located when your program is executing. For example, assuming your platform is 64-bit Windows, and the installation is at *C:\\Program Files\\HOOPS_ExchangePublish*, the path should be set as *C:\\Program Files\\HOOPS_ExchangePublish\\bin\\win64;*.


Step 3: Include the Libraries In Your Project
---------------------------------------------

The HOOPS Visualize Desktop-Exchange integration library must be included as a dependency. C++ users will need to link to *hps_sprk_exchange.lib*. C# users need to add a Reference to the *hps_cs_sprk_exchange.dll* located in the *bin* directory. (If you're working in the :ref:`WPF Sandbox <general/sandboxes:WPF Sandbox>`, the "Copy Local" property for the Reference to *hps_cs_sprk_exchange.dll* should be set to ``False``).

Alternatively, you may specify the library directory by calling ``HPS::World::SetExchangeLibraryDirectory``.


Step 4: Include the Header File In Your Source (C++ Only)
---------------------------------------------------------

Your source files that use the HOOPS Visualize Desktop-Exchange integration must include *sprk_exchange.h*.


Step 5: Initialize the DLLs (Optional)
--------------------------------------

This step is only necessary if you need to call the HOOPS Exchange API directly in order to access functionality not provided by the HOOPS Visualize Desktop-Exchange integration.
If this is your intention, you must make an explicit call to ``A3DSDKLoadLibrary``.
See the |url_he_init| page of the HOOPS Exchange Programming Guide.
You should not call any other HOOPS Exchange initialization functions.

At this point, HOOPS Exchange is ready to use in your application.

.. _file_loading:

File Loading
============

The :doc:` view hierarchy <0301_core>` that was introduced earlier is utilized when loading Exchange models. Specifically, HOOPS Visualize Desktop encapsulates Exchange models ``HPS::Model`` objects as part of the loading process. It can also create a ``HPS::View`` using the Exchange model's camera (where supported by the file format). In any case, the end goal is to create a view hierarchy. There are multiple ways to do this, as demonstrated in the code snippet, below:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_file_loading.cpp
		   :start-after: //! [load_file]
		   :end-before: //! [load_file]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_file_loading.cs
		   :start-after: //! [load_file]
		   :end-before: //! [load_file]
		   
This snippet demonstrates the importance of calling ``Wait()`` on your notifier object. Because all notifier classes do their I/O in a separate thread, the potential exists to use the object before it is done loading, especially if you try to interact with it immediately after you call ``Import()``. Calling ``Wait()`` ensures the I/O operation is complete before continuing. If you do not use ``Wait()``, you could end up with unexpected behavior.

In addition to waiting, the ``HPS::Exchange::ImportNotifier`` also can provide you with useful information about the status of the import. You can even use the notifier to cancel the import, if needed. All of the possible return values for the status are listed in the ``HPS::IOResult`` reference manual page.

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_file_loading.cpp
		   :start-after: //! [file_load_result]
		   :end-before: //! [file_load_result]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_file_loading.cs
		   :start-after: //! [file_load_result]
		   :end-before: //! [file_load_result]

After the model is loaded using Exchange, it can be manipulated like any other HOOPS Visualize Desktop model. The components of the model are translated from their native format into the HOOPS Visualize Desktop entities as discussed in the :ref:`data mapping section <prog_guide/0906_exchange_integration:Data mapping>`.

	**IMPORTANT:** When a CAD model is imported, memory is allocated which must eventually be released. Memory is allocated by Exchange to load Exchange entities, and additionally by HOOPS Visualize Desktop to create the scene graph. The way the data was imported will determine how memory cleanup should be handled.
	
	If you imported a CAD file using ``HPS::Exchange::File::Import`` with a path to a file, then the ``HPS::CADModel`` assumes "ownership" of the model file. In this case, calling ``Delete`` on the ``CADModel`` object is sufficient to delete all memory associated with the model.
	
	However, if you read the model a different way, then later imported it to HOOPS Visualize Desktop using the ``A3DAsmModelFile`` pointer (as opposed to providing a file path), then the ``HPS::CADModel`` is *not* considered the file owner. During cleanup, ``HPS::Component::Delete()`` should still be called, but doing so will not automatically free the underlying Exchange data. In this case, you also need to call the Exchange API directly and free the memory using ``A3DAsmModelFileDelete``.
	
	For more information, please see the API Reference entry for ``HPS::Component::Delete()``.
	

.. _options_for_loading:

Options for File Loading
------------------------

When loading a file, you can choose beforehand whether certain elements will be loaded. Default import options will be used for any import settings that are not set on the ``HPS::Stream::ImportOptionsKit`` passed to the ``HPS::Exchange::File::Import`` function. These defaults can be seen via ``HPS::ImportOptionsKit::GetDefault()``. The options specified during import will determine how long the import takes, the amount of memory used, and the size of exported files. Additionally, if data is not loaded during import, it will not be available afterwards without reimporting the data. It is important to keep these things in mind when selecting the import options. For example, if you have a file that contains PMI data, but know you will not be needing it, you can disable PMI as an import option:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_file_loading.cpp
		   :start-after: //! [pmi]
		   :end-before: //! [pmi]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_file_loading.cs
		   :start-after: //! [pmi]
		   :end-before: //! [pmi]

Additional options that can be controlled during import are B-rep data, solids, surfaces, and others.


.. _multiple-models:

Importing Multiple Models
-------------------------

Multiple CAD models may be imported into the same scene graph. To do this, set the destination of the model using ``HPS::Exchange::ImportOptionsKit::SetLocation`` or ``HPS::Exchange::ModelFileImportOptionsKit::SetLocation`` functions. These functions allow you to provide a ``HPS::ComponentPath`` with an optional ``HPS::MatrixKit``. ``HPS::ComponentPath`` describes the path within the component hierarchy where the new data should be inserted, scaled by the provided matrix.

If a location is not set, HOOPS Visualize Desktop will simply create a new ``HPS::CADModel``. If the location is set, HOOPS Visualize Desktop will create new ``HPS::Components`` and add them to the existing component hierarchy.


Configurations
--------------

Configurations are an important option that can be utilized for certain file formats. A *configuration* is a sub-model within a larger model - sometimes these files are also referred to as "multi-model" or "multi-entry" files. Only CATIAV4, SolidWorks, and IDEAS files support configurations. Some files can contain multiple configurations. If you do not specify a configuration to load, the default configuration will be loaded, if possible. Multi-model CATIA V4 files do not have a default configuration, so attempting to load such a file without specifying a configuration will cause the import to fail.

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_file_loading.cpp
		   :start-after: //! [configurations]
		   :end-before: //! [configurations]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_file_loading.cs
		   :start-after: //! [configurations]
		   :end-before: //! [configurations]


.. _incremental_loading:

Incremental Loading
===================

Loading a large, complex assembly can take a significant amount of time and memory. When working with large assemblies, sometimes it does not make sense to load the whole assembly if you are only interested in a single part. To solve this problem, parts of CAD models may be loaded individually. Incremental loading only works with certain formats - see "Limitations" at the end of this section for details.

To perform an incremental load, set the import mode to "incremental" before loading:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_incremental.cpp
		   :start-after: //! [incremental1]
		   :end-before: //! [incremental1]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_incremental.cs
		   :start-after: //! [incremental1]
		   :end-before: //! [incremental1]
		   
When this mode is enabled, only the structure of the CAD file will be imported. This means that no geometry is tessellated or displayed. Instead, you get the assembly tree structure, the product occurrences, with which you can the traverse the hierarchy and selectively load a part on demand. You do this by calling ``HPS::Exchange::ImportOptionsKit::SetIncrementalComponentPath`` (or ``SetIncrementalComponentPaths``) with the components you wish to load:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_incremental.cpp
		   :start-after: //! [incremental2]
		   :end-before: //! [incremental2]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_incremental.cs
		   :start-after: //! [incremental2]
		   :end-before: //! [incremental2]

At this point, the ``CADModel`` contains the loaded component path, along with the other product occurrences that have not been loaded. One can load another component path by repeating the same steps, or one can specify multiple ``ComponentPath`` objects to load simultaneously via the ``Exchange::ImportOptionsKit::SetIncrementalComponentPaths`` function. In any case, the load functionality happens at the level of a product occurrence, so that is what the leaf component in the incremental ``ComponentPath`` should be.


Unloading Product Occurrences and Querying Load Status
------------------------------------------------------

Another piece of the integration with incremental load is the ability to query a product occurrence for its load status and the ability to unload it. To this end, there is a new ``Exchange::ProductOccurrence`` class that provides an ``Unload`` and ``GetLoadStatus`` function.
 
Unloading a particular product occurrence from Exchange simply requires invoking the ``Unload`` function on an ``Exchange::ProductOccurrence``:
 
 .. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_incremental.cpp
		   :start-after: //! [incremental3]
		   :end-before: //! [incremental3]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_incremental.cs
		   :start-after: //! [incremental3]
		   :end-before: //! [incremental3]
		   
Whether or not the unload removes Component objects depends on the ``Exchange::UnloadMode`` value passed to ``Exchange::ProductOccurrence::Unload``. Passing ``Exchange::UnloadMode::ExchangeAndVisualization`` will result in Exchange data being unloaded and components being deleted, while passing ``Exchange::UnloadMode::ExchangeOnly`` will only unload the data from Exchange, but leave the component objects and their associated visualization data in memory.
 
An "Exchange only" unload is meant to allow memory savings by removing the Exchange data, but allow the visualization to remain. Some functionality may be lost with this type of unload, since it will generally no longer be possible to query the associated Exchange entity for things like its name or physical properties. Additionally, either form of unload will modify the underlying Exchange data, so operations performed on those underlying Exchange entities will similarly have unloaded entities, which will affect what gets exported for the various CAD exports or 3D PDF export.
 
It is possible to query the current load status of a product occurrence via ``Exchange::ProductOccurrence::GetLoadStatus``. This can be used to determine if a product occurrence has not been loaded, has been loaded, has only visualization data, or is partially loaded (i.e., a product occurrence contains other product occurrences, some of which are loaded, some of which are not).  This allows one to display special icons for the various load states in a model browser, or to determine what kind of load functionality to allow for a particular product occurrence, for example.
 
 
Incremental Loading Limitations
-------------------------------

This functionality is restricted to SolidWorks, NX (Unigraphics), Creo (Pro/E), JT, and CATIA V5 files. The API won't allow this functionality to be used for files that are not of those formats. Additionally, while native CATIA V5 assemblies will work with incremental load, V5 assemblies that contain or wrap V4 assemblies will not work. If incremental loading is attempted with an unsupported format, an exception will be thrown.
 
The ability to load and unload product occurrences in an assembly is only available if the file is originally loaded in incremental mode. The API does not allow the use of those functions for CADModel objects which were not loaded incrementally.
 
Incremental load will not work with parts in an assembly for which there is no corresponding file with BRep data. For instance, you can have a SolidWorks assembly and only a subset of the parts it references as files on disk.  If you perform a complete import of the assembly (calling ``Exchange::ImportOptionsKit::SetMode`` with ``Exchange::ImportMode::Complete``), geometry will still be inserted for those parts which don't have the corresponding part file if Exchange is able to extract the tessellation from the SolidWorks assembly. If you perform an incremental import of such an assembly (calling ``Exchange::ImportOptionsKit::SetMode`` with ``Exchange::ImportMode::Incremental``), it will not be possible to load those parts for which there is no part file on disk (trying to do so will simply result in nothing getting loaded for that part).  Rather, it will only be possible to load parts for which there is a part file. Similarly, using incremental load with a CATIA V5 assembly will only work for components corresponding to CATPart or CATProduct files.  Any components referring only to CGR files cannot be loaded incrementally.

Note that only the geometry on leaf product occurrences will be loaded.

For all formats, when a product occurrence is loaded, associated views are not loaded automatically.
For JT files, when a product occurrence is loaded, associated metadata are not loaded automatically.


.. _interaction:

Handling Views, Metadata, and Filters
=====================================

Handling views
--------------

In the first code snippet on this page, notice that ``ActivateDefaultCapture`` returns a ``HPS::View`` object. This is the same ``HPS::View`` discussed in :doc:`the view hierarchy section <0301_core>`. Some model formats include a view of a particular state of the model, and ``ActivateDefaultCapture`` will load that view. The view may include a camera, toggle visibility for cutting planes, PMI, and geometry with the scene. Additionally, it may apply transformations to some geometry, for example,  create an exploded view of an assembly. 

Certain model formats allow multiple views to be pre-defined, and you may be interested in loading some view other than the default. The code below demonstrates how to do this.

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_file_interaction.cpp
		   :start-after: //! [handling_views]
		   :end-before: //! [handling_views]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_file_interaction.cs
		   :start-after: //! [handling_views]
		   :end-before: //! [handling_views]
		   

Handling Metadata
-----------------

Metadata is additional non-geometric information that is associated with an ``HPS::Exchange::Component``. Each piece of metadata is a name-value pair, and the values can be strings, integers, unsigned integers, doubles, Booleans, or times. Any ``HPS::Exchange::Component`` can have metadata associated with it. During the import process, metadata is generally only imported if the ``HPS::Exchange::ImportOptionsKit::SetAttributes`` is set to ``true``. However, some metadata, such as faces, certain IDs, layers, and materials, are always imported even if ``HPS::ImportOptionsKit::SetAttributes`` is set to ``false``. A list of that metadata is as follows:

.. csv-table::
	:header: "Metadata name", "Type", "Description"
	
	"Name", "String", "Name of this component"
	"PersistentID", "non-zero unsigned int", ""
	"NonPersistentID", "non-zero unsigned int", ""
	"Layer", "unsigned int", "Layer number where this component is located"
	"Filename", "String", "File name of this model"
	"FileFormat", "String", "File format for this model"
	"IsAnnotationCapture", "Boolean", "Only available for components of type capture. Value is true if the capture is an annotation capture, false otherwise."
	"Units", "String", "The units of the model. Only available from the ``HPS::Exchange::CADModel``."
	"IsDefaultSheet", "Boolean", "Whether the sheet is the default sheet for a drawing. Only available for components of type ``HPS::Component::ComponentType::ExchangeDrawingSheet``."

Metadata can be embedded with a ``HPS::Exchange::Component`` in many different forms. The following example demonstrates how to get metadata associated with a ``HPS::Exchange::Component``:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_file_interaction.cpp
		   :start-after: //! [handling_metadata]
		   :end-before: //! [handling_metadata]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_file_interaction.cs
		   :start-after: //! [handling_metadata]
		   :end-before: //! [handling_metadata]
		   

Activating Filters
------------------

Filters are found in some CAD files and provide the capability to show or hide certain pieces of geometry or objects that lie in certain layers. Filters can be toggled once a CAD file has been imported via the HOOPS Visualize Desktop-Exchange API. Filters may also be toggled when captures are activated. Note that a filter can be attached to any component of the model. You may use ``HPS::CADModel::GetAllFilters`` to get a list of all ``HPS::Filter`` objects in the ``HPS::CADModel``. The following code example shows how to activate a filter on a view:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_file_interaction.cpp
		   :start-after: //! [activating_filters]
		   :end-before: //! [activating_filters]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_file_interaction.cs
		   :start-after: //! [activating_filters]
		   :end-before: //! [activating_filters]

More than one filter may be active at a particular time. To activate or deactivate a filter, you first need to get a reference to it. You can get a list of all the active filters on a ``HPS::View`` by using this logic:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_file_interaction.cpp
		   :start-after: //! [deactivating_filters]
		   :end-before: //! [deactivating_filters]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_file_interaction.cs
		   :start-after: //! [deactivating_filters]
		   :end-before: //! [deactivating_filters]
		   

.. _exporting_files:

Exporting Files
===============

All file formats that Exchange can export are supported via the HOOPS Visualize Desktop-Exchange API (``Export3MF``, ``ExportACIS``, ``ExportFBX``, ``ExportGLTF``, ``ExportIGES``, ``ExportJT``, ``ExportOBJ``, ``ExportParasolid``, ``ExportPRC``, ``ExportSTEP``, ``ExportSTL``, ``ExportU3D``, ``ExportVRML``, and ``ExportXML``). All export formats have their own ``Export*OptionsKit`` (except for VRML which has no options). 

Writing a file through Exchange is an operation similar to reading:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_simple_export.cpp
		   :start-after: //! [exchange_simple_export]
		   :end-before: //! [exchange_simple_export]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_simple_export.cs
		   :start-after: //! [exchange_simple_export]
		   :end-before: //! [exchange_simple_export]
		   
Exchange can import many more file types than it can export. A list of supported file formats is located in |url_he_format| page.


Exporting HOOPS Visualize Desktop Scene Graph Data With an Exchange Model
----------------------------------------------------------

HOOPS Visualize Desktop does not use B-rep (boundary representation) calculations when rendering. All models are tessellated. However, models will be exported with B-rep if the original Exchange model was loaded with B-rep. If your application adds HOOPS Visualize Desktop scene graph data to the scene, and you have a need to export that data along with the Exchange data, the export process is more complex.

Exporting HOOPS Visualize Desktop data with Exchange data is possible using the ``ExportPRC`` function. As the name implies, PRC is the only format in which this operation is permitted. The general sequence is explained below: 

* Create a ``HPS::KeyPathArray`` containing the key paths to the HOOPS Visualize Desktop geometry you want to be part of the export.
* Set that key path on an ``HPS::ExportPRCOptionsKit`` using the ``SetAdditionalKeyPaths`` function.
* Call ``HPS::Exchange::File::ExportPRC``, passing it the ``HPS::CADModel``, the output file name, and the ``HPS::ExportPRCOptionsKit`` containing the extra key paths.

There exist overloads of the ``ExportPRC`` function which do not accept a ``HPS::CADModel``. These overloads will export everything which is pointed to by the key paths you pass to them, but in those cases you will only get tessellation - B-rep is not included.

If you need to export Exchange and HOOPS Visualize Desktop data to a non-PRC file format, we recommend you first export to PRC, then use Exchange to translate the file to the format of your choice.


.. _exchange_events:

Event Handling
==============

During the import process, Exchange will trigger events when it detects a problem or has information to give you. For example, if Exchange couldn't find a referenced subcomponent in an assembly, or if there was some sort of import failure, a warning or error could be triggered. It is the responsibility of your application to catch these events and respond appropriately.

The HOOPS Visualize Desktop-Exchange integration will capture all events and wrap them into one of three types: ``HPS::InformationEvent``, ``HPS::ErrorEvent``, or ``HPS::WarningEvent``. Each of these types derive from ``HPS::Event``, thus, handling them is identical to handling any other type of HOOPS Visualize Desktop event (event handling is discussed :doc:`here <1001_event_handling>`).

``WarningEvent`` and ``InformationEvent`` contain both a ``code`` and a ``message`` field that help to determine what caused the event.


Data Mapping
============

It is important for developers to be able to map objects within their HOOPS Visualize Desktop database to the corresponding entities as loaded by HOOPS Exchange. Exchange first maps all incoming CAD data to the industry standard 'PRC' format, which in turn is then mapped to the HOOPS Visualize Desktop scene graph. HOOPS Visualize Desktop interfaces to each Exchange entity through an ``HPS::Exchange::Component`` object. Using a ``HPS::Exchange::Component``, you can query the underlying PRC data for model information. Exchange objects are called *entities* and HOOPS Visualize Desktop objects are *components*. Here is an example of some basic Exchange interactions:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_file_interaction.cpp
		   :start-after: //! [exchange_data_mapping]
		   :end-before: //! [exchange_data_mapping]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_file_interaction.cs
		   :start-after: //! [exchange_data_mapping]
		   :end-before: //! [exchange_data_mapping]

At the end of the code snippet above, Exchange is integrated, and you can use then use the entity references to manipulate model 
data using the Exchange API.


Using Type Masks
----------------

Commonly, it is necessary to determine whether a component contains a certain type of entity. If you are only looking for a specific type, you can use ``HPS::Component::GetComponentType`` to test against the returned type. But some generalized entities can take many forms. For example, PMI can exist as plain text, rich text, or GD&T, among other things. Rather than checking against all types of PMI, you can use a PMI mask with the ``HasComponentType`` function. This operation will tell you whether the component contains any type of PMI.

Type masks also exist for topology and representation items. A usage example is as follows:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_component_mask.cpp
		   :start-after: //! [component_mask]
		   :end-before: //! [component_mask]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_component_mask.cs
		   :start-after: //! [component_mask]
		   :end-before: //! [component_mask]
		   

.. _synchronization:

Keeping HOOPS Visualize Desktop Synchronized With HOOPS Exchange
=================================================

When you make changes to a HOOPS Visualize Desktop scene graph which represents a HOOPS Exchange model, those changes affect the HOOPS Visualize Desktop scene graph only. Likewise, if you modify a model's PRC data using the HOOPS Exchange API, the corresponding HOOPS Visualize Desktop scene graph is unchanged. To ensure the PRC data and the HOOPS Visualize Desktop scene graph are synchronized, further action is necessary.

If your changes are relatively simple, such as a deleting a PRC entity, you can call ``HPS::Component::Delete`` on the corresponding ``HPS::Component`` to update the HOOPS Visualize Desktop scene graph. (For further details on the behavior of the ``HPS::Component::Delete`` function, please refer to the API Reference.)

However, if you have a need to make more substantive changes, first make the modification using the Exchange API. Next, call ``HPS::Exchange::Component::Reload`` to bring the scene graph and component hierarchy up to date. The reload should be invoked at or above the level where the changes were made, thus ensuring HOOPS Visualize Desktop doesn't try to access potentially deleted PRC entities. It is important to only call Reload() for components that have been changed, as reloading can be an expensive operation for complex models. Make use of a notifier if you need to determine when the reload is complete:

.. tabs::

	.. group-tab:: C++
	
		.. literalinclude:: ../../../internals/tests/docs/source/cpp/00700_exchange_file_interaction.cpp
		   :start-after: //! [exchange_component_reload]
		   :end-before: //! [exchange_component_reload]
		   
	.. group-tab:: C#

		.. literalinclude:: ../../../internals/tests/docs/source/cs/00700_exchange_file_interaction.cs
		   :start-after: //! [exchange_component_reload]
		   :end-before: //! [exchange_component_reload]
		   
Please note that the reload process rebuilds any prototypes and as a result, all existing Exchange pointers to the reloaded components will be invalidated.

It also is recommended that you re-activate a capture after a component reload completes. This will ensure that the visibility of components in the scene is correct, particularly for items whose visibility is conditional - for example, PMI. It is possible that a model may look correct without re-activating a capture, but to work in general, it is necessary to re-activate a capture after a reload. Be sure to keep a reference to the CAD model object to re-activate the capture (see previous sections for capture examples).


.. _copyto:

Implementing a Copy/Paste/Cut/Move Workflow
-------------------------------------------

HOOPS Visualize Desktop offers several convenient functions to enable you to quickly adjust the position of components in the model tree. A common use for this functionality is a copy/paste/cut/move workflow. Although possible, it can be complicated to edit the PRC structure directly using HOOPS Exchange, since the management of the PRC model, links, and the associated HOOPS Visualize Desktop view require important expertise in both HOOPS Visualize Desktop scene graph and PRC management. For this reason, a high-level API is available to implement these common operations.

* **Copy/paste workflow:** The "copy/paste" workflow can be accomplished with the function ``HPS::Component::CopyTo(HPS::Component in_component, HPS::Component target_parent)``. This function creates a copy of the ``A3DEntity`` associated with the ``HPS::Component in_component``, and adds it under the ``A3DEntity`` associated with the ``HPS::Component target_parent`` in the PRC. It will then create a new ``HPS::Component``, associate it with the ``A3DEntity`` copied and then return this component. Following this function, you need to call ``HPS::Exchange::Component::Reload()`` from the returned component to create the subcomponent tree of this newly created component. You only need to call ``Reload()`` from this component, instead of having to call ``Reload()`` from the ``HPS::CADModel`` or the target component. For performance reasons, it is always a good idea to call ``Reload()`` from the lowest point of the tree possible. Lastly, you should check the type of the returned component to see if the function ran successfully (a component of type ``None`` means that the function failed).
    
* **Delete workflow:** The "delete" workflow is performed using the function ``HPS::Component::Delete`` with the option ``HPS::Component::DeleteMode::StandardAndExchange``. This function will remove the ``A3DEntity`` link to the component and clean up the link from and to that entity inside of the PRC, and then perform a standard delete on that component. This function does not require a reload to synchronize the HOOPS Visualize Desktop component tree and PRC entities structure.

* **Move workflow:** The "move" workflow can be done by combining the copy/paste workflow and the deletion workflow: you copy/paste the copied component under the new parent, and then delete the original component. This function requires a call to ``HPS::Component::Reload()`` to properly update the HOOPS Visualize Desktop component tree.

Please note that the implications of using ``CopyTo`` are slightly different depending on the type of entity you are operating on. Please see the Reference Manual for details.


.. _component-creation:

Component Creation Using a Custom Importer
==========================================

HOOPS Visualize Desktop takes care of all of the import logic for supported file formats, including HOOPS Exchange. In doing so, it creates an in-memory model structure which consists of the ``HPS::Component`` objects mentioned in the previous section. If you have a need to write your own importer, you will need a way to create these components as you parse the input file. HOOPS Visualize Desktop allows you to do this using its component creation API functions.

The first step in this process is to create the root component, which is the ``HPS::Exchange::CADModel``. This is the only object in the Exchange structure that has no owner. From this point, you can build the model structure as you parse it, using the ``HPS::Exchange::Factory`` static class to create each component.

.. tabs::

	.. group-tab:: C++
	
		.. code-block:: cpp
	
			// create the CAD model
			HPS::Exchange::CADModel cadModel = HPS::Exchange::Factory::CreateCADModel();
			 
			// ... parse file
			 
			// if your entity is a product occurrence
			HPS::Exchange::Component component = HPS::Exchange::Factory::CreateComponent
				(cadModel, HPS::Component::ComponentType::ExchangeProductOccurrence, myEntity);
		   
	.. group-tab:: C#
	
		.. code-block:: c#

			// create the CAD model
			HPS.Exchange.CADModel cadModel = HPS.Exchange.Factory.CreateCADModel();
			 
			// ... parse file
			 
			// if your entity is a product occurrence
			HPS.Exchange.Component component = HPS.Exchange.Factory.CreateComponent
				(cadModel, HPS.Component.ComponentType.ExchangeProductOccurrence, myEntity);

Additionally, see the reference manual entries for ``HPS::Component::AddKey``, ``HPS::Component::AddOwner``, and ``HPS::Component::AddReference``, which aid with component creation in certain situations. For example, to associate a geometry key will a component, use ``AddKey``.


General Exchange Limitations
============================

As Exchange itself is only implemented for Windows, Linux, OSX, iOS, and Android, the HOOPS Visualize Desktop-Exchange integration is not applicable to other 
operating systems.

It is also important to note that the HOOPS Visualize Desktop-Exchange integration ignores B-rep data and asks HOOPS Exchange to provide all data in tessellated form. 


Further Reading
===============

A further discussion on the inner workings of Exchange is beyond the scope of this manual.
However, the main source for Exchange documentation can be viewed in |url_he_docs|.
