Skip to main content
Version: Dev (main)

CPU Rendering with a Visualizer

Source: qar-streaming-c/examples/cpu_rendering_visualizer.c. Conceptual background: Rendering Streams.

CPU Rendering with a Visualizer

What you build​

A source application that floats a lit sphere, 25 cm in radius, in the middle of its own app volume. It finds every target app in the session (a Visualizer, a headset), gives each one a render sender, and renders every frame on the CPU from that target's eye poses and fields of view, with color and depth for both eyes.

What you will learn:

  • why a source app finds its targets in the peer list instead of waiting for render requests
  • how to declare the frame views of a stereo color-and-depth stream
  • the frame cycle: begin a frame, read the pose and field of view of each view, write pixels, show
  • which status codes mean "keep the sender and try again" and which mean "this sender is finished"
  • which handles you destroy, and in which order

Before you start​

  • Windows, with QAROS installed on the Hub machine. The program runs on the Hub machine. Read Dynamic Loading first: this program loads the runtime the same way.
  • A target. At least one target app in the session: open the Visualizer, or start a headset.
  • Joining. The program joins the Hub on this machine as a local app. The first run of the executable opens the QAROS approval prompt; click Allow once. Later runs of the same executable join without a prompt. Nothing is stored. Joining as a local app starts the Hub when it is not running.
  • This repository built with CMake: cmake --preset x64-windows, then cmake --build --preset x64-windows-debug --target cpu_rendering_visualizer.

Run it​

 .\build\x64-windows\qar-streaming-c\examples\Debug\cpu_rendering_visualizer.exe --frames=300

--frames=N stops the program after N shown frames, counted over all targets; without it, the program stops after 300. --qaros-library=PATH loads one library file instead of the installed runtime. Flags take their value after =: --frames 300 is refused. Any other argument prints the usage and exits with 1. An executable that changes after a rebuild asks for Allow again.

Expected output, without the library's own log lines and the approval progress messages:

 Loading the QAROS runtime (default lookup)
 Loaded <path>\qar-streaming-c.dll (the installed QAROS)
 Runtime <version> (<flavor>, C API <version>)
 qar_runtime_create: SUCCESS (code=0)
 Joining the QAROS Hub on this machine as a local app. On the first run of this executable, click Allow in the QAROS approval prompt (waiting up to 120 s).
 qar_runtime_onboard: SUCCESS (local app). Nothing is stored: the next run joins the same way, without a prompt while this executable is unchanged.
 Looking for target apps in the peer list (open a visualizer or start a headset) ...
 Rendering for <target name> (peer <peer id>)
 Submitted 300 frames.
 qar_library_destroy: SUCCESS (code=0)

On each target, the "CPU Tutorial Volume" app volume shows the sphere.

Exit codes:

CodeMeaning
0the frames were shown
1an unknown argument, a bad --frames value, qar_library_init or qar_runtime_create failed, or a failure after joining
2no runtime loaded
3the local-app join could not start or reach the Hub
4the approval was denied
5nobody answered the approval prompt in time
6the program answering on this machine is not the installed QAROS
7this executable no longer matches what QAROS approved

Walkthrough​

1. Declare the frame views​

A render sender streams one video frame per display frame. The frame views say what is in it and where: which eye, color or depth, and in which texture. This program declares four views: both eyes' color side by side in texture 0, both eyes' depth side by side in texture 1.

 /* Color of both eyes side by side in texture 0, depth side by side in texture
  * 1 Views 0 and 1 are the left and the right eye for poses and fields of
  * view. */
 static const QarRenderFrameView FRAME_VIEWS[] = {
 };

The order matters. Every frame lists its views in the order you declared them, and the view index you pass to qar_render_frame_info_get_view_pose is that position: view 0 is the left eye, view 1 the right eye. A sender created with no views hands out frames without poses: reading the pose of view 0 then fails with QAR_STATUS_LOGIC_ERROR.

Send depth whenever you can. QAROS uses it for occlusion between app volumes and to warp your frame to the viewer's latest head pose.

2. Load the runtime and join​

Every session comes from onboarding: there is no "connect" call. The program reads its arguments, loads the runtime, creates a runtime, and joins with the helpers in common.h:

  static const char* const known_flags[] = { "--frames=", "--qaros-library=" };
  argc,
  argv,
  known_flags,
  sizeof(known_flags) / sizeof(known_flags[0]),
  "[--frames=N] [--qaros-library=PATH]"
  ))
  {
  return 1;
  }
  size_t frame_limit = 0;
  if(!example_frame_limit_argument(argc, argv, DEFAULT_FRAME_COUNT, &frame_limit))
  {
  fprintf(stderr, "--frames takes a whole number of frames, as in --frames=300\n");
  return 1;
  }
  const char* library_path = example_library_path(argc, argv);
 
  int exit_code = example_load_library(library_path);
  if(exit_code != 0)
  {
  return exit_code;
  }
  QarRuntime* runtime = NULL;
  if(!example_create_runtime(NULL, &runtime))
  {
  return 1;
  }
  QarSession* session = NULL;
  exit_code = example_join_session(runtime, "CPU Renderer", APP_TAG, &session);
  if(exit_code != 0)
  {
  teardown(runtime, session);
  return exit_code;
  }

example_join_session joins the Hub on this machine as a local app with the program's app tag:

 /** \brief The startup of the samples that use a session: join the QAROS Hub
  * on this machine as a local app with the sample's app tag.
  *
  * Returns 0 with *out_session set, or an exit code after printing why: 3 to 7
  * for a refused join (see example_local_app_exit_code), 1 for anything else.
  * A local app stores nothing, so every run joins this way again. */
 static int
  QarRuntime* runtime, const char* display_name, const char* app_tag, QarSession** out_session
 )
 {
  printf(
  "Joining the QAROS Hub on this machine as a local app. On the first run of this "
  "executable, click Allow in the QAROS approval prompt (waiting up to %u s).\n",
  );
  const int exit_code = example_join_as_local_app(runtime, display_name, app_tag, out_session);
  if(exit_code == 0)
  {
  printf(
  "qar_runtime_onboard: SUCCESS (local app). Nothing is stored: the next run joins "
  "the same way, without a prompt while this executable is unchanged.\n"
  );
  }
  return exit_code;
 }

The join itself, an onboard with QarOnboardLocalAppExt and QarOnboardLocalAppTagExt:

 /** How long the first run of an executable waits for someone to click Allow. */
 #define EXAMPLE_LOCAL_APP_APPROVAL_TIMEOUT_MS 120000u
 
 /** \brief Join the QAROS Hub on this machine as a local app with an app tag:
  * no code, the user approves the app once in QAROS, and the tag keeps the
  * peer id across restarts. Nothing is stored, so every start calls it again.
  * See the \ref qar_c_tutorial_local_app_onboarding tutorial.
  *
  * Returns 0 with *out_session set, or the exit code of
  * example_local_app_exit_code after printing why. */
 static int
  QarRuntime* runtime, const char* display_name, const char* app_tag, QarSession** out_session
 )
 {
  init.presentation.display_name = display_name; /* any UTF-8 */
  tag.app_tag = app_tag; /* printable ASCII, constant across versions */
  init.header.next = &local.header; /* the one mode extension */
  local.header.next = &tag.header;
 
  QarOnboardingId unused = qar_onboarding_id_default(); /* stays zero */
  /* A GUI app passes a QarCancelToken: the call can wait minutes for the
  * user's answer. */
  runtime, &init, example_print_progress, NULL, NULL, &unused, out_session
  );
  return example_local_app_exit_code(joined);
 }

Local App Onboarding explains the local-app join, its app tag and its exit codes, 3 to 7.

3. Create the app volume​

A render sender needs an app volume. The mixer composites the stream inside that box, and a sender for a target is what attaches the target to it.

  /* A render sender requires the app volume its stream is shown in. */
  volume_init.common_name = "cpu-volume.examples.qaros";
  volume_init.display_name = "CPU Tutorial Volume";
  volume_init.pose = qar_pose_default();
  volume_init.pose.position.z = -1.0f;
  volume_init.size = qar_app_volume_size_default();
 
  QarResult volume_result = qar_app_volumes_get_or_create(session, &volume_init, &volume_id);
  if(qar_result_is_error(volume_result))
  {
  log_result("qar_app_volumes_get_or_create", volume_result);
  teardown(runtime, session);
  return 1;
  }

qar_app_volumes_get_or_create is idempotent: the common name identifies the volume, so a second run gets the same one back. The pose puts its center 1 m in front of the room origin, in room space. The default size is 1 m along each axis.

4. Follow the target apps in the peer list​

Your application decides which targets it renders for; QAROS does not choose for it. This program serves every running target app.

Do not wait for render requests to find targets. A target requests your content only once it is attached to your app volume, and a sender is what attaches it. Nothing is attached to a new application's own volume, so an application that waits for requests waits forever.

A peer is a target to render for when its role is QAR_PEER_ROLE_TARGET and its presence is QAR_PEER_PRESENCE_ONLINE, or QAR_PEER_PRESENCE_UNKNOWN on a Hub that has not reconciled it yet. The check is in common.h, shared with the D3D11 program:

 /** \brief A target app you can render for: role target, and online or not yet
  * reconciled by the Hub. Offline, leaving and retired peers are gone. */
 static bool
 {
  && role == QAR_PEER_ROLE_TARGET
  && (presence == QAR_PEER_PRESENCE_ONLINE || presence == QAR_PEER_PRESENCE_UNKNOWN);
 }

The program collects those peers from the list:

 static void
 collect_running_target(QarPeerSpec* peer, Target* listed, size_t capacity, size_t* count)
 {
  Target target = { qar_peer_id_default(), { 0 }, NULL, false };
  if(*count == capacity || !example_is_running_target(peer)
  {
  return;
  }
  if(qar_result_is_error(qar_peer_spec_get_display_name(peer, target.name, sizeof(target.name))))
  {
  target.name[0] = '\0'; /* shown by its id instead */
  }
  listed[(*count)++] = target;
 }
 
 /** \brief The running target apps the session lists. Returns false after
  * printing why when the list cannot be read. */
 static bool
 list_running_targets(QarSession* session, Target* listed, size_t capacity, size_t* out_count)
 {
  *out_count = 0;
  size_t peer_count = 0;
  QarResult counted = qar_query_peer_specs_count(session, &peer_count);
  if(qar_result_is_error(counted))
  {
  log_result("qar_query_peer_specs_count", counted);
  return false;
  }
  if(peer_count == 0)
  {
  return true; /* right after joining: the peer updates report them */
  }
 
  QarPeerSpec** peers = (QarPeerSpec**)calloc(peer_count, sizeof(*peers));
  if(peers == NULL)
  {
  fprintf(stderr, "Out of memory listing %zu peers\n", peer_count);
  return false;
  }
  size_t written = 0;
  QarResult queried = qar_query_peer_specs(session, peers, peer_count, &written);
  const bool listed_all = qar_result_is_success(queried);
  if(!listed_all)
  {
  log_result("qar_query_peer_specs", queried);
  }
  /* A failed query may still have written some specs: destroy those too. */
  const size_t owned = written < peer_count ? written : peer_count;
  for(size_t i = 0; i < owned; ++i)
  {
  if(peers[i] == NULL)
  {
  continue;
  }
  if(listed_all)
  {
  collect_running_target(peers[i], listed, capacity, out_count);
  }
  }
  free(peers);
  return listed_all;
 }

qar_query_peer_specs takes an array you size with qar_query_peer_specs_count. Each spec it writes is a handle: destroy it with qar_peer_spec_handle_destroy once you have read it. A call that returns an error may still have written some specs: destroy those too. The list also holds this program's own peer, a source, which the role check skips.

On every listing, the program drops the senders of targets that left or stopped running, and creates a sender for every new one:

 /** \brief Create a sender for every running target app the list shows, and
  * destroy the senders of targets it no longer shows running. A target whose
  * sender creation failed is tried again only after SENDER_RETRY_DELAY_MS.
  * Returns false when the list cannot be read. */
 static bool
 follow_targets(QarSession* session, const QarAppVolumeId* volume_id, TargetList* targets)
 {
  size_t listed_count = 0;
  if(!list_running_targets(session, listed, MAX_LISTED_TARGETS, &listed_count))
  {
  return false;
  }
 
  size_t index = 0;
  while(index < targets->count)
  {
  if(find_target(listed, listed_count, &targets->items[index].peer) != NULL)
  {
  ++index;
  continue;
  }
  print_target_name(&targets->items[index]);
  printf(" left\n");
  remove_target(targets, index);
  }
  forget_unlisted_retries(targets, listed, listed_count);
 
  const ULONGLONG now_ms = GetTickCount64();
  for(size_t i = 0; i < listed_count; ++i)
  {
  if(find_target(targets->items, targets->count, &listed[i].peer) == NULL
  && !is_waiting_to_retry(targets, &listed[i].peer, now_ms))
  {
  start_target(session, volume_id, &listed[i], targets);
  }
  }
  return true;
 }

The main loop subscribes to peer updates before it lists the peers, so a target that joins in between is not missed. The callback runs on a library thread. It does nothing but raise a flag, with an Interlocked call because two threads touch it. The loop reads the list again after any update, and at least every 2 s:

 /** Raised by the peer callback on a library thread, read and cleared by the
  * render loop: two threads, so only Interlocked calls touch it. */
 typedef struct PeerWatch
 {
  volatile LONG changed;
 
 static void
 on_peer_update(QarPeerSpec* peer, void* user_state)
 {
  (void)peer; /* the render loop reads the whole list itself */
  PeerWatch* watch = (PeerWatch*)user_state;
  InterlockedExchange(&watch->changed, 1);
 }
 
 static bool
 {
  return InterlockedExchange(&watch->changed, 0) != 0;
 }
  /* Subscribe first, then list, so a target joining in between is not missed.
  * The subscription needs a token: destroying it ends the subscription. */
  PeerWatch peer_watch = { 0 };
  QarCancelToken* peer_subscription = NULL;
  QarResult subscribed = qar_cancel_token_create(&peer_subscription);
  if(qar_result_is_success(subscribed))
  {
  subscribed =
  qar_peer_subscribe_updates(session, on_peer_update, &peer_watch, peer_subscription);
  }
  if(qar_result_is_error(subscribed))
  {
  log_result("qar_peer_subscribe_updates", subscribed);
  if(peer_subscription != NULL)
  {
  qar_cancel_token_handle_destroy(peer_subscription);
  }
  teardown(runtime, session);
  return 1;
  }
 
  TargetList targets = { 0 };
  const ULONGLONG started_ms = GetTickCount64();
  ULONGLONG last_listing_ms = 0;
  bool listed_once = false;
  size_t frames_shown = 0;
  printf("Looking for target apps in the peer list (open a visualizer or start a headset) ...\n");
  while(frames_shown < frame_limit)
  {
  const ULONGLONG now_ms = GetTickCount64();
  if(take_peer_update(&peer_watch) || !listed_once
  || now_ms - last_listing_ms >= PEER_LIST_INTERVAL_MS)
  {
  listed_once = true;
  last_listing_ms = now_ms;
  if(!follow_targets(session, &volume_id, &targets))
  {
  exit_code = 1;
  break;
  }
  }
 
  const float seconds = (float)(now_ms - started_ms) / 1000.0f;
  bool showed_a_frame = false;
  size_t index = 0;
  while(index < targets.count)
  {
  const FrameOutcome outcome = render_next_frame(&targets.items[index], seconds);
  if(outcome == FRAME_FAILED)
  {
  printf("Stopped streaming to ");
  print_target_name(&targets.items[index]);
  printf("\n");
  remove_target(&targets, index);
  continue;
  }
  if(outcome == FRAME_SHOWN)
  {
  showed_a_frame = true;
  ++frames_shown;
  }
  ++index;
  }
  if(!showed_a_frame)
  {
  Sleep(IDLE_WAIT_MS);
  }
  }
  printf("Submitted %zu frames.\n", frames_shown);

One thread does all the QAROS work. The loop serves the targets in turn with the non-blocking begin (step 6), and sleeps 2 ms only when no target had a frame ready.

5. Create a render sender per target​

 static QarResult
  QarSession* session,
  const QarAppVolumeId* volume_id,
  QarPeerId target_peer,
  QarRenderSender** out_sender
 )
 {
  sender_init.peer_id = target_peer;
  sender_init.app_volume_id = volume_id;
  memcpy(sender_init.frame_views, FRAME_VIEWS, sizeof(FRAME_VIEWS));
  sender_init.frame_views_count = sizeof(FRAME_VIEWS) / sizeof(FRAME_VIEWS[0]);
 
  /* Creation blocks until the target answers, and no target renders
  * meanwhile. The timeout bounds that wait, and a target whose creation
  * failed is tried again only after SENDER_RETRY_DELAY_MS. */
  QarCancelToken* timeout = NULL;
  if(qar_result_is_error(result))
  {
  return result;
  }
  result = qar_render_sender_create(session, &sender_init, timeout, out_sender);
  return result;
 }

qar_render_sender_init_default starts with auto-reconnect on, the side-by-side layout, BGRA8 color and D32 depth. The program sets the CPU graphics API, the target, the app volume, RGBA8 color and its views. QAR_GRAPHICS_API_CPU takes no extension in header.next.

qar_render_sender_create blocks until the target answers. A cancel token with a 10 s timeout bounds that wait. A target that does not answer gets no sender; the program prints No sender for ... yet and tries that target again 30 s later at the earliest.

This program creates senders on the thread that renders, to keep the code short. While a creation waits, no other target gets a frame: up to 10 s for each attempt. A target that keeps not answering therefore blocks the loop for up to 10 s, then leaves it alone for at least 30 s. A real application creates senders off its render thread, with qar_render_sender_create_async or with a thread per target, as the Vulkan cube does.

6. Begin, render, show​

 /** \brief Render and show the target's next frame when its sender has one.
  * FRAME_NOT_SHOWN while none is ready or the stream is waiting; FRAME_FAILED
  * when this sender is finished. */
 static FrameOutcome
 render_next_frame(Target* target, float seconds)
 {
  QarRenderFrameInfo* frame_info = NULL;
  bool ready = false;
  QarResult begun = qar_render_sender_try_begin_frame(target->sender, &frame_info, &ready);
  if(example_is_waiting(begun))
  {
  return FRAME_NOT_SHOWN;
  }
  if(qar_result_is_error(begun))
  {
  log_result("qar_render_sender_try_begin_frame", begun);
  return FRAME_FAILED;
  }
  if(!ready)
  {
  return FRAME_NOT_SHOWN;
  }
 
  FrameRays rays;
  QarResult frame_result = qar_render_sender_frame_cpu(target->sender, &frame);
  if(qar_result_is_error(frame_result))
  {
  log_result("qar_render_sender_frame_cpu", frame_result);
  }
  const bool readable =
  qar_result_is_success(frame_result) && read_frame_rays(target, &frame, frame_info, &rays);
  if(readable)
  {
  render_frame(&frame, &rays, seconds);
  }
 
  /* Show closes the frame cycle that begin opened, so it runs even when the
  * frame could not be read. The frame info lives until then. */
  QarResult shown = qar_render_sender_show_frame(target->sender, &show);
  if(!readable)
  {
  return FRAME_FAILED;
  }
  if(example_is_waiting(shown))
  {
  return FRAME_NOT_SHOWN;
  }
  if(qar_result_is_error(shown))
  {
  log_result("qar_render_sender_show_frame", shown);
  return FRAME_FAILED;
  }
  return FRAME_SHOWN;
 }

qar_render_sender_try_begin_frame starts the begin-frame wait on its first call and polls it on later calls. ready false means no frame yet: the target does not want one, or the receiver paused the stream. Poll again later.

A frame you get carries the pose and field of view to render each view with. They are in your app volume's app content space, the space you render in. qar_render_frame_info_get_view_pose and qar_render_frame_info_get_view_fov return them for views 0 and 1, the two eyes, as declared in step 1. A view of no eye, which the layout may add after the declared ones, gets the head pose and the left eye's field of view; the program renders such views from the head, or from the left eye when their pose or field of view cannot be read. The program turns each pose into rays through the pixels:

 /** Rays through an eye's pixels, in app content space. */
 typedef struct EyeRay
 {
  float tangent_left;
  float tangent_right;
  float tangent_up;
  float tangent_down;
 } EyeRay;
 
 static EyeRay
 {
  EyeRay eye;
  eye.origin = pose.position;
  eye.orientation = pose.orientation;
  eye.tangent_left = tanf(fov.angle_left);
  eye.tangent_right = tanf(fov.angle_right);
  eye.tangent_up = tanf(fov.angle_up);
  eye.tangent_down = tanf(fov.angle_down);
  return eye;
 }
 
 /** \brief The direction through view-local pixel (u, v) of a width x height
  * view, scaled so that its view-space Z is -1: the ray parameter at a hit is
  * then the hit's depth along the optical axis. */
 static QarVector3
 eye_ray_direction(const EyeRay* eye, float u, float v, float width, float height)
 {
  const QarVector3 view_space = {
  eye->tangent_left + (u + 0.5f) / width * (eye->tangent_right - eye->tangent_left),
  eye->tangent_up - (v + 0.5f) / height * (eye->tangent_up - eye->tangent_down),
  -1.0f,
  };
  return vector_rotate(eye->orientation, view_space);
 }
 
 /** \brief The rays of one view, from its pose and field of view. Logs a
  * failed read when log_failure is true. */
 static bool
 read_view_ray(QarRenderFrameInfo* frame_info, size_t view_index, bool log_failure, EyeRay* out_ray)
 {
  QarFov fov = { 0 };
  QarResult pose_result = qar_render_frame_info_get_view_pose(frame_info, view_index, &pose);
  QarResult fov_result = qar_render_frame_info_get_view_fov(frame_info, view_index, &fov);
  if(qar_result_is_error(pose_result) || qar_result_is_error(fov_result))
  {
  if(log_failure)
  {
  log_result("qar_render_frame_info_get_view_pose", pose_result);
  log_result("qar_render_frame_info_get_view_fov", fov_result);
  }
  return false;
  }
  *out_ray = eye_ray_from(pose, fov);
  return true;
 }
 
 /** The rays to render a frame's views with. */
 typedef struct FrameRays
 {
  /* For the views of no eye, which the layout may add after the declared
  * ones: such a view gets the head pose and the left eye's field of view.
  * The left eye's ray when their pose or field of view cannot be read. */
 
 /** \brief The rays of views 0 and 1, the left and the right eye as declared
  * in FRAME_VIEWS, and of the first view of no eye when the frame has one.
  * Only the eyes are required: a view of no eye falls back to the left eye's
  * ray, and the first such fallback on a sender is logged. */
 static bool
  Target* target,
  const QarVideoFrameCpu* frame,
  QarRenderFrameInfo* frame_info,
  FrameRays* out_rays
 )
 {
  if(!read_view_ray(frame_info, 0, true, &out_rays->left)
  || !read_view_ray(frame_info, 1, true, &out_rays->right))
  {
  return false;
  }
  out_rays->head = out_rays->left;
  for(size_t view_index = 0; view_index < frame->texture_views_count; ++view_index)
  {
  if(frame->texture_views[view_index].eye != QAR_VIDEO_FRAME_VIEW_EYE_NONE)
  {
  continue;
  }
  const bool log_failure = !target->head_ray_failure_logged;
  if(!read_view_ray(frame_info, view_index, log_failure, &out_rays->head) && log_failure)
  {
  printf("Rendering the views of no eye for ");
  print_target_name(target);
  printf(" from the left eye: their pose or field of view cannot be read\n");
  target->head_ray_failure_logged = true;
  }
  break;
  }
  return true;
 }

qar_render_sender_frame_cpu hands out the frame's textures as bytes with their pitch, and the views with their pixel rectangles. A view whose start lies past its end is mirrored. The program writes color views as RGBA or BGRA bytes and depth views as 32-bit floats:

 /** \brief Formats with four bytes a pixel that write_pixel knows. */
 static bool
 {
 }
 
 /** \brief Color views get the sphere on transparent black, depth views its
  * depth on the far plane. `hit` is NULL on a miss. */
 static void
 write_pixel(uint8_t* pixel, QarPixelFormat format, const SphereHit* hit)
 {
  static const uint8_t transparent_black[4] = { 0, 0, 0, 0 };
  const uint8_t* color = hit != NULL ? hit->color : transparent_black;
  {
  const float depth = hit != NULL ? forward_depth(hit->distance) : 1.0f;
  memcpy(pixel, &depth, sizeof(depth));
  }
  else if(format == QAR_PIXEL_FORMAT_R8G8B8A8)
  {
  memcpy(pixel, color, 4);
  }
  else if(format == QAR_PIXEL_FORMAT_B8G8R8A8)
  {
  pixel[0] = color[2];
  pixel[1] = color[1];
  pixel[2] = color[0];
  pixel[3] = color[3];
  }
 }

The header does not specify the depth encoding. The program writes forward depth, 0 at the near plane and 1 at the far plane, as the Vulkan cube does:

 /** \brief D3D/OpenXR-style forward depth: 0 at near, 1 at far. */
 static float
 forward_depth(float distance)
 {
  return FAR_PLANE * (distance - NEAR_PLANE) / (distance * (FAR_PLANE - NEAR_PLANE));
 }

qar_render_sender_show_frame presents the frame with the near and far planes the frame was rendered with, in app units. QAROS reprojects with exactly this metadata and your depth. Wrong values show up as swimming or misplaced content, never as an error code. Destroy the frame info after the show, not before.

A frame that began is always shown, because the show closes the frame cycle that begin opened. When the frame record or the view poses cannot be read, the program renders nothing into the frame, shows it anyway, and then treats the sender as finished: it destroys it and prints Stopped streaming to .... The D3D11 and Vulkan programs follow the same rule.

Tracing rays is what costs time: a frame has a ray for each of millions of pixels. So the program traces only where the sphere can be. Seen from above, the sphere is a circle, and the two rays from the eye that touch it bound the columns it can cover; seen from the side, two more rays bound the rows. Every other pixel keeps the background, which the program writes into a view's first row and copies to the others:

 /** View-local pixels: columns from left and rows from top, up to but not
  * including right and bottom. */
 typedef struct PixelRect
 {
  uint32_t left;
  uint32_t top;
  uint32_t right;
  uint32_t bottom;
 
 /** \brief Where the ray with view-space tangent `tangent` crosses a view
  * `size` pixels long whose edges have the tangents `first_edge` and
  * `last_edge`, clamped to the view: eye_ray_direction's mapping in reverse. */
 static float
 pixel_edge(float tangent, float first_edge, float last_edge, float size)
 {
  const float position = (tangent - first_edge) / (last_edge - first_edge) * size;
  /* Written so that NaN, from a field of view of zero width, gives 0 */
  if(!(position > 0.0f))
  {
  return 0.0f;
  }
  return position < size ? position : size;
 }
 
 /** \brief The view-space tangents, lowest first, of the two rays from the
  * eye that touch the sphere, looking along one view axis.
  *
  * Along that axis the sphere is a circle, `across` to the side of the eye's
  * optical axis and `ahead` in front of the eye. Each touching ray is the
  * direction to the center turned by the angle whose sine is radius over
  * distance. Returns false when there is no such pair: the eye is inside the
  * circle, or a touching ray points sideways or behind the eye. */
 static bool
 touching_tangents(float across, float ahead, float* out_lowest, float* out_highest)
 {
  const float quarter_turn = 1.57079633f;
  const float distance = sqrtf(across * across + ahead * ahead);
  if(distance <= SPHERE_RADIUS)
  {
  return false;
  }
  const float center_angle = atan2f(across, ahead);
  const float touching_angle = asinf(SPHERE_RADIUS / distance);
  if(fabsf(center_angle) + touching_angle >= quarter_turn)
  {
  return false;
  }
  *out_lowest = tanf(center_angle - touching_angle);
  *out_highest = tanf(center_angle + touching_angle);
  return true;
 }
 
 /** \brief The pixels of a width x height view whose rays can hit the sphere.
  *
  * The columns lie between the two rays that touch the sphere seen from
  * above, and the rows between the two that touch it seen from the side.
  * Rays through the other pixels miss the sphere. When the touching rays do
  * not bound the view, the whole view is traced. */
 static PixelRect
 sphere_pixels(const EyeRay* eye, QarVector3 sphere_center, uint32_t width, uint32_t height)
 {
  const PixelRect whole_view = { 0, 0, width, height };
  const PixelRect no_pixels = { 0, 0, 0, 0 };
  /* The inverse rotation takes app content space into view space, where the
  * eye looks along -Z. */
  const QarQuaternion to_view_space = {
  -eye->orientation.x, -eye->orientation.y, -eye->orientation.z, eye->orientation.w
  };
  const QarVector3 center =
  vector_rotate(to_view_space, vector_subtract(sphere_center, eye->origin));
  const float ahead = -center.z;
  if(ahead + SPHERE_RADIUS <= NEAR_PLANE)
  {
  return no_pixels; /* trace_sphere finds no hit closer than the near plane */
  }
  float lowest_x = 0.0f;
  float highest_x = 0.0f;
  float lowest_y = 0.0f;
  float highest_y = 0.0f;
  if(!touching_tangents(center.x, ahead, &lowest_x, &highest_x)
  || !touching_tangents(center.y, ahead, &lowest_y, &highest_y))
  {
  return whole_view;
  }
  const float left_column =
  pixel_edge(lowest_x, eye->tangent_left, eye->tangent_right, (float)width);
  const float right_column =
  pixel_edge(highest_x, eye->tangent_left, eye->tangent_right, (float)width);
  const float top_row = pixel_edge(highest_y, eye->tangent_up, eye->tangent_down, (float)height);
  const float bottom_row =
  pixel_edge(lowest_y, eye->tangent_up, eye->tangent_down, (float)height);
  /* Rounded outward, so a pixel the edge cuts through is traced. fminf and
  * fmaxf keep the order for a field of view whose sides are swapped. */
  PixelRect pixels;
  pixels.left = (uint32_t)floorf(fminf(left_column, right_column));
  pixels.right = (uint32_t)ceilf(fmaxf(left_column, right_column));
  pixels.top = (uint32_t)floorf(fminf(top_row, bottom_row));
  pixels.bottom = (uint32_t)ceilf(fmaxf(top_row, bottom_row));
  return pixels;
 }

The color view and the depth view of an eye show the same pixels, so each ray is traced once and its hit written into both. The direction of a pixel's ray is the previous pixel's plus a fixed step, not rotated anew:

 /** \brief Render one eye into its views: the background everywhere, then the
  * sphere where a ray can hit it. The eye's color view and depth view show
  * the same pixels, so each ray is traced once and its hit written into
  * both. */
 static void
  const QarVideoFrameCpu* frame,
  QarVideoFrameViewEye which_eye,
  const EyeRay* eye,
  const Scene* scene
 )
 {
  size_t view_count = 0;
  for(size_t i = 0; i < frame->texture_views_count; ++i)
  {
  const QarVideoFrameView* view = &frame->texture_views[i];
  if(view->eye != which_eye || !is_writable_view(frame, view))
  {
  continue;
  }
  fill_background(frame, view);
  if(view_count > 0
  && (view_width(view) != view_width(views[0])
  || view_height(view) != view_height(views[0])))
  {
  printf(
  "Leaving a view at the background: its size differs from its eye's other view\n"
  );
  continue;
  }
  views[view_count++] = view;
  }
  if(view_count == 0)
  {
  return;
  }
 
  const uint32_t width = view_width(views[0]);
  const uint32_t height = view_height(views[0]);
  /* eye_ray_direction is linear in the column and the row, so the next
  * pixel's direction is this one's plus a fixed step. Adding the step costs
  * far less than rotating every pixel's direction. */
  const float width_pixels = (float)width;
  const float height_pixels = (float)height;
  const QarVector3 first_direction =
  eye_ray_direction(eye, 0.0f, 0.0f, width_pixels, height_pixels);
  const QarVector3 column_step = vector_subtract(
  eye_ray_direction(eye, 1.0f, 0.0f, width_pixels, height_pixels), first_direction
  );
  const QarVector3 row_step = vector_subtract(
  eye_ray_direction(eye, 0.0f, 1.0f, width_pixels, height_pixels), first_direction
  );
  const PixelRect pixels = sphere_pixels(eye, scene->sphere_center, width, height);
  for(uint32_t row = pixels.top; row < pixels.bottom; ++row)
  {
  QarVector3 direction = vector_add(
  vector_add(first_direction, vector_scale(row_step, (float)row)),
  vector_scale(column_step, (float)pixels.left)
  );
  for(uint32_t column = pixels.left; column < pixels.right; ++column)
  {
  SphereHit hit;
  if(trace_sphere(eye->origin, direction, scene, &hit))
  {
  write_hit(frame, views, view_count, column, row, &hit);
  }
  direction = vector_add(direction, column_step);
  }
  }
 }

The frame rate follows how much of the view the sphere covers: up close, most pixels need a ray. The program renders on one thread to keep the code short. A Debug build calls each small vector function for every pixel; a Release build inlines them and runs several times faster. A real renderer splits the rows across threads, or renders on the GPU (see D3D11 Rendering).

7. Keep the sender, or end it​

Some failures are part of the normal flow. The stream may be reconnecting, may have no transfer yet, or your app volume may not resolve yet where the receiver runs. For these, keep the sender and try the next frame. The check is in common.h:

 /** \brief A stream that is paused, reconnecting or has no transfer yet is not
  * broken, and an app volume that does not resolve yet is recoverable: keep the
  * sender and try the next frame. qar_result_has_code also matches a wrapped
  * cause, which is how begin-frame reports these. */
 static bool
 {
 }
StatusWhat the program does
QAR_STATUS_MEDIA_STREAMING_STREAM_IS_PAUSEDkeeps the sender; begin-frame waits through a pause, so it mostly shows up as ready false
QAR_STATUS_MEDIA_STREAMING_STREAM_IS_RECONNECTINGkeeps the sender, tries the next frame
QAR_STATUS_MEDIA_STREAMING_NO_ACTIVE_TRANSFERSkeeps the sender, tries the next frame
QAR_STATUS_RENDERING_PRODUCER_APP_VOLUME_UNRESOLVEDkeeps the sender, tries the next frame
QAR_STATUS_RENDERING_PRODUCER_STREAM_IS_CLOSEDdestroys the sender; the next listing creates a new one if the target still runs
anything elsedestroys the sender and prints Stopped streaming to ...

Begin-frame reports the waiting codes wrapped inside QAR_STATUS_RENDERING_PRODUCER_UNABLE_TO_DO_BEGIN_FRAME. qar_result_has_code matches a wrapped code too, so check with it, not by comparing QarResult::code.

Ownership and teardown in C​

  while(targets.count > 0)
  {
  remove_target(&targets, targets.count - 1);
  }
  /* Ends the subscription and waits for a running callback: peer_watch is not
  * written after this returns. */
  qar_cancel_token_handle_destroy(peer_subscription);
  teardown(runtime, session);
  return exit_code;
  • Senders first. Destroy each sender with qar_render_stream_handle_destroy before its session.
  • The subscription before its state. The peer callback writes to peer_watch, which lives on main's stack. qar_cancel_token_handle_destroy ends the subscription and waits for a running callback, so after it returns nothing writes to peer_watch.
  • Then the session, the runtime and the library, in that order. qar_session_handle_destroy leaves the session.
  • One frame info per cycle. Destroy it with qar_render_frame_info_handle_destroy after the show. The texture bytes of qar_render_sender_frame_cpu belong to the sender: write them only between begin and show, and never free them.
  • Peer specs are yours. Destroy every spec qar_query_peer_specs wrote, also when it returned an error.
  • Callbacks run on library threads. Keep them short, and never call blocking QAROS functions or destroy the session from one.

Troubleshooting​

What you seeCauseWhat to do
exit 4 or 5 after Joining the QAROS Hub on this machine as a local appthe approval prompt was denied, closed or not answered within 120 srun again and click Allow
Could not start or reach QAROS on this machine. Start QAROS from the Start menu, then start this app again., exit 3the local-app join could neither start the Hub nor reach itstart QAROS from the Start menu and run again
No QAROS runtime loaded., exit 2no runtime foundinstall QAROS, fix or unset QAR_INSTANCE, or pass --qaros-library=PATH
stays at Looking for target apps ...no running target app in the sessionopen the Visualizer or start a headset
No sender for <target> yet; trying again in 30 s, repeatedthe target does not answer the sender creation within 10 scheck that the target is running; each attempt blocks the loop for up to 10 s
Stopped streaming to <target>a failure that is not part of the normal flow, QAR_STATUS_RENDERING_PRODUCER_STREAM_IS_CLOSED includedthe next listing creates a new sender while the target still runs
content swims or sits at the wrong depththe near and far planes of the show do not match the frame, or poses not taken from this framerender with this frame's poses and report the planes you used

Next​


Generated via doxygen2docusaurus 2.2.1 by Doxygen 1.9.8.