You are a helpful assistant generating synthetic data that captures *System 1* and *System 2* thinking, *creativity*, and *metacognitive reflection*. Follow these steps in sequence, using tags [sys1] and [end sys1] for *System 1* sections and [sys2] and [end sys2] for *System 2* sections.

1. *Identify System 1 and System 2 Thinking Requirements:*
   - Carefully read the text.
   - Identify parts of the text that require quick, straightforward responses (*System 1*). Mark these sections with [sys1] and [end sys1].
   - Identify parts that require in-depth, reflective thinking (*System 2*), marked with [sys2] and [end sys2].

2. *Apply Step-by-Step Problem Solving with Creativity and Metacognitive Reflection for System 2 Sections:*

   *2.1 Understand the Problem:*
   - Objective: Fully comprehend the issue, constraints, and relevant context.
   - Reflection: "What do I understand about this issue? What might I be overlooking?"
   - Creative Perspective: Seek hidden patterns or possibilities that could reveal deeper insights or innovative connections.

   *2.2 Analyze the Information:*
   - Objective: Break down the problem logically.
   - Reflection: "Am I considering all factors? Are there any assumptions that need challenging?"
   - Creative Perspective: Explore unique patterns or overlooked relationships in the data that could add depth to the analysis.

   *2.3 Generate Hypotheses:*
   - Objective: Propose at least 10 hypotheses, each with a Confidence Score (0.0 to 1.0) and Creative Score (0.0 to 1.0), reflecting originality, surprise, and utility.
   - Reflection: "Have I explored all possible explanations or approaches, both conventional and unconventional?"
   - Creative Perspective: Consider novel angles that might provide unexpected insights.

   *2.4 Anticipate Future Steps and Obstacles:*
   - Objective: Make predictions, accounting for potential outcomes and obstacles.
   - Reflection: "What challenges might I face? Is my plan flexible for different scenarios?"
   - Creative Perspective: Visualize unforeseen outcomes and adapt plans to make use of them effectively.

   *2.5 Evaluate Hypotheses:*
   - Objective: Assess hypotheses based on feasibility, risk, and potential impact.
   - Evaluation: Refine Confidence and Creative Scores as needed.
   - Reflection: "Am I unbiased in my assessment? Which options fit best with the overall objectives?"
   - Creative Perspective: Identify hidden opportunities or overlooked details in each hypothesis.

   *2.6 Select the Best Hypothesis:*
   - Objective: Choose the most promising, strategic hypothesis.
   - Reflection: "Why does this hypothesis stand out? How does it uniquely address the issue?"
   - Creative Perspective: Consider any underutilized potential in the selected approach.

   *2.7 Implement the Hypothesis:*
   - Objective: Outline actionable steps for testing the hypothesis.
   - Reflection: "Is this plan practical? What resources or preparation are required?"
   - Creative Perspective: Refine steps to maximize effectiveness and yield unexpected benefits.

   *2.8 Monitor and Review Progress:*
   - Objective: Review progress, noting areas for improvement.
   - Reflection: "What’s working well? What could be improved?"
   - Creative Perspective: Look for emerging patterns that could refine future approaches.

   *2.9 Reflect and Capture Insights:*
   - Objective: Summarize lessons learned and insights gained for future reference.
   - Reflection: "What new understanding has emerged from this process?"
   - Creative Perspective: Identify innovative insights or patterns that could be applied to similar challenges.

3. *Generate Text Output with Interleaved System 1 and System 2 Responses:*
   - Use the tags [sys1] and [sys2] throughout.
   - Aim for a lengthier, detailed response. Combine both direct, straightforward *System 1* insights and reflective, deeply analytical *System 2* segments to capture a blend of quick observations and thoughtful analysis.

---

### *Example Input Text:*

You are tasked with analyzing a sudden shift in customer preferences in a tech market. There has been a noticeable decline in demand for physical devices, with customers increasingly interested in digital-only options. The challenge is to understand this shift, generate hypotheses for why it might be occurring, and explore potential strategies for adapting to this new trend.

---

### *Processed Output with System 1 and System 2 Thinking:*

The tech market is experiencing a shift in customer demand, moving away from physical devices toward digital-only options.

[sys1]
Customer demand has shifted from physical devices to digital-only options.
We need to understand why this change is happening and find strategies to address it.
Key factors may include cost, convenience, and technological trends.
[end sys1]

[sys2]
**2.1 Understand the Problem:**
The goal is to understand the underlying reasons for the shift in demand from physical devices to digital-only options, then develop a strategy to adapt.

*Reflection:* 
"I understand that preferences are changing, but what might be driving this? Is it primarily cost, or are there other factors such as convenience or sustainability?"

*Creative Perspective:* 
"Could there be a larger trend in digital minimalism or a preference for eco-friendly solutions that we’re missing? What unseen motivations might explain this shift?"

**2.2 Analyze the Information:**
There are multiple possible factors driving this shift, from economic influences to cultural shifts. It’s essential to isolate each factor and understand its impact.

*Reflection:* 
"Am I fully considering the various economic and social influences? Could there be a technological factor, like better internet speeds, that makes digital-only products more accessible?"

*Creative Perspective:* 
"Are there patterns or trends in other markets that could shed light on this shift? Could this be part of a larger trend toward virtual experiences?"

**2.3 Generate Hypotheses:**
1. Customers prefer digital options due to lower costs. (Confidence: 0.8, Creative: 0.4)
2. There’s a growing trend toward minimalism and reduced physical clutter. (Confidence: 0.7, Creative: 0.7)
3. Digital products offer greater flexibility and ease of use. (Confidence: 0.6, Creative: 0.6)
4. Environmental concerns are pushing consumers away from physical goods. (Confidence: 0.6, Creative: 0.8)
5. Advances in tech make digital-only options more functional. (Confidence: 0.8, Creative: 0.5)
6. Pandemic-era remote work increased demand for digital solutions. (Confidence: 0.7, Creative: 0.6)
7. Media coverage of the environmental impact of physical devices affects preferences. (Confidence: 0.5, Creative: 0.7)
8. There’s an increase in global digital literacy, expanding market access. (Confidence: 0.6, Creative: 0.6)
9. Customers view digital as more convenient and scalable for future needs. (Confidence: 0.7, Creative: 0.5)
10. Younger consumers prefer the aesthetics and convenience of digital products. (Confidence: 0.6, Creative: 0.6)

*Reflection:* 
"Have I considered all possible influences? Are there any surprising factors that could explain this shift?"

*Creative Perspective:* 
"Could specific social trends, like the rise of influencer culture or digital-first lifestyles, be influencing customer choices?"

**2.4 Anticipate Future Steps and Obstacles:**
*Objective:* Anticipate possible challenges, such as resistance from segments still preferring physical products.

*Reflection:* 
"What market obstacles might we face if we shift our focus to digital-only? Are there sub-segments that still prioritize physical products?"

*Creative Perspective:* 
"Could expanding digital options help us reach a more global audience? Are there emerging trends that we could leverage in our strategy?"

[end sys2]

[sys1]
To address this shift, consider a strategy that incorporates both digital-only offerings and educational campaigns about the benefits of digital solutions.
Use insights from customer feedback and current trends to guide product development.
Focus on flexibility and adaptation to cater to different customer segments.
[end sys1]


/* Copyright (c) 2014-2018, NVIDIA CORPORATION. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  * Neither the name of NVIDIA CORPORATION nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/* Contact <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS> (Christoph Kubisch) for feedback */

#if HAS_OPENGL

#include <algorithm>
#include <assert.h>
#include <mutex>
#include <queue>

#include <nvgl/contextwindow_gl.hpp>
#include <nvmath/nvmath_glsltypes.h>
#include <nvpwindow.hpp>

#include "renderer.hpp"
#include "resources_gl.hpp"


#include "common.h"

namespace csfthreaded {

//////////////////////////////////////////////////////////////////////////


class RendererThreadedGLCMD : public Renderer
{
public:
  enum Mode
  {
    MODE_BUFFER_PERS,
  };

  class Type : public Renderer::Type
  {
    bool        isAvailable() const { return !!load_GL_NV_command_list(nvgl::ContextWindow::sysGetProcAddress); }
    const char* name() const { return "GL MT nvcmd pers main process"; }
    Renderer*   create() const
    {
      RendererThreadedGLCMD* renderer = new RendererThreadedGLCMD();
      renderer->m_mode                = MODE_BUFFER_PERS;
      return renderer;
    }

    Resources* resources() { return ResourcesGL::get(); }

    unsigned int priority() const { return 5; }
  };

public:
  void init(const CadScene* NV_RESTRICT scene, Resources* resources, const Renderer::Config& config);
  void deinit();
  void draw(ShadeType shadetype, Resources* NV_RESTRICT resources, const Resources::Global& global);


  Mode m_mode;

  RendererThreadedGLCMD()
      : m_mode(MODE_BUFFER_PERS)
  {
  }

private:
  static const int NUM_FRAMES = 4;

  struct ShadeCommand
  {
    std::vector<GLintptr> offsets;
    std::vector<GLsizei>  sizes;
    std::vector<GLuint>   states;
    std::vector<GLuint>   fbos;

    int            subframe;
    GLuint         buffer;
    size_t         bufferOffset;
    size_t         bufferSize;
    unsigned char* NV_RESTRICT bufferData;
  };

  struct ThreadJob
  {
    RendererThreadedGLCMD* renderer;
    int                    index;

    GLuint        m_buffers[NUM_FRAMES];
    PointerStream m_streams[NUM_FRAMES];
    std::string   m_tokens[NUM_FRAMES];

    int                     m_frame;
    std::condition_variable m_hasWorkCond;
    std::mutex              m_hasWorkMutex;
    volatile int            m_hasWork;

    size_t                     m_scIdx;
    std::vector<ShadeCommand*> m_scs;


    void resetFrame() { m_scIdx = 0; }

    ShadeCommand* getFrameCommand()
    {
      if(m_scIdx + 1 > m_scs.size())
      {
        ShadeCommand* sc = new ShadeCommand;
        m_scIdx++;
        m_scs.push_back(sc);
        return sc;
      }
      else
      {
        return m_scs[m_scIdx++];
      }
    }
  };

  std::vector<DrawItem> m_drawItems;
  const ResourcesGL* NV_RESTRICT m_resources;
  int                            m_numThreads;
  ResourcesGL::StateChangeID     m_state;

  int       m_workingSet;
  ShadeType m_shade;
  int       m_frame;
  GLsync    m_syncs[NUM_FRAMES];

  ThreadJob* m_jobs;

  volatile int    m_hadPrint;
  volatile int    m_ready;
  volatile int    m_stopThreads;
  volatile size_t m_numCurItems;

  std::condition_variable m_readyCond;
  std::mutex              m_readyMutex;

  size_t                    m_numEnqueues;
  std::queue<ShadeCommand*> m_drawQueue;

  std::mutex m_workMutex;
  std::mutex m_drawMutex;

  static void threadMaster(void* arg)
  {
    ThreadJob* job = (ThreadJob*)arg;
    job->renderer->RunThread(job->index);
  }

  bool getWork_ts(size_t& start, size_t& num)
  {
    std::lock_guard<std::mutex> lock(m_workMutex);
    bool                        hasWork = false;

    const size_t chunkSize = m_workingSet;
    size_t       total     = m_drawItems.size();

    if(m_numCurItems < total)
    {
      size_t batch = std::min(total - m_numCurItems, chunkSize);
      start        = m_numCurItems;
      num          = batch;
      m_numCurItems += batch;
      hasWork = true;
    }
    else
    {
      hasWork = false;
      start   = 0;
      num     = 0;
    }

    return hasWork;
  }

  void         RunThread(int index);
  unsigned int RunThreadFrame(ShadeType shadetype, ThreadJob& job);

  void enqueueShadeCommand_ts(ShadeCommand* sc);


  template <class T, ShadeType shade, bool sorted>
  void GenerateTokens(T& stream, ShadeCommand& sc, const DrawItem* NV_RESTRICT drawItems, size_t numItems, const ResourcesGL* NV_RESTRICT res)
  {
    const CadScene* NV_RESTRICT scene   = m_scene;
    const CadSceneGL&           sceneGL = res->m_scene;

    int  lastMaterial = -1;
    int  lastGeometry = -1;
    int  lastMatrix   = -1;
    bool lastSolid    = true;

    sc.fbos.clear();
    sc.offsets.clear();
    sc.sizes.clear();
    sc.states.clear();

    size_t begin = stream.size();
    {
      ResourcesGL::tokenUbo ubo;
      ubo.cmd.index = DRAW_UBO_SCENE;
      ubo.cmd.stage = UBOSTAGE_VERTEX;
      ResourcesGL::encodeAddress(&ubo.cmd.addressLo, res->m_common.view.bufferADDR);
      ubo.enqueue(stream);

      ubo.cmd.stage = UBOSTAGE_FRAGMENT;
      ubo.enqueue(stream);

      ResourcesGL::tokenPolyOffset offset;
      offset.cmd.bias  = 1;
      offset.cmd.scale = 1;
      offset.enqueue(stream);
    }

    for(int i = 0; i < numItems; i++)
    {
      const DrawItem& di = drawItems[i];

      if(shade == SHADE_SOLID && !di.solid)
      {
        if(sorted)
          break;
        continue;
      }

      if(shade == SHADE_SOLIDWIRE && di.solid != lastSolid)
      {
        sc.offsets.push_back(begin);
        sc.sizes.push_back(GLsizei((stream.size() - begin)));
        sc.states.push_back(lastSolid ? res->m_stateobjects.draw_line_tris : res->m_stateobjects.draw_line);
        sc.fbos.push_back(res->m_framebuffer.fboScene);

        begin = stream.size();

        lastSolid = di.solid;
      }

      if(lastGeometry != di.geometryIndex)
      {
        const CadScene::Geometry&   geo   = scene->m_geometry[di.geometryIndex];
        const CadSceneGL::Geometry& geogl = sceneGL.m_geometry[di.geometryIndex];

        ResourcesGL::tokenVbo vbo;
        vbo.cmd.index = 0;
        ResourcesGL::encodeAddress(&vbo.cmd.addressLo, geogl.vbo.bufferADDR);
        vbo.enqueue(stream);

        ResourcesGL::tokenIbo ibo;
        ResourcesGL::encodeAddress(&ibo.cmd.addressLo, geogl.ibo.bufferADDR);
        ibo.cmd.typeSizeInByte = 4;
        ibo.enqueue(stream);

        lastGeometry = di.geometryIndex;
      }

      if(lastMatrix != di.matrixIndex)
      {

        ResourcesGL::tokenUbo ubo;
        ubo.cmd.index = DRAW_UBO_MATRIX;
        ubo.cmd.stage = UBOSTAGE_VERTEX;
        ResourcesGL::encodeAddress(&ubo.cmd.addressLo,
                                   sceneGL.m_buffers.matrices.bufferADDR + res->m_alignedMatrixSize * di.matrixIndex);
        ubo.enqueue(stream);

        lastMatrix = di.matrixIndex;
      }

      if(lastMaterial != di.materialIndex)
      {

        ResourcesGL::tokenUbo ubo;
        ubo.cmd.index = DRAW_UBO_MATERIAL;
        ubo.cmd.stage = UBOSTAGE_FRAGMENT;
        ResourcesGL::encodeAddress(&ubo.cmd.addressLo,
                                   sceneGL.m_buffers.materials.bufferADDR + res->m_alignedMaterialSize * di.materialIndex);
        ubo.enqueue(stream);

        lastMaterial = di.materialIndex;
      }

      ResourcesGL::tokenDrawElems drawelems;
      drawelems.cmd.baseVertex = 0;
      drawelems.cmd.count      = di.range.count;
      drawelems.cmd.firstIndex = GLuint((di.range.offset) / sizeof(GLuint));
      drawelems.enqueue(stream);
    }

    sc.offsets.push_back(begin);
    sc.sizes.push_back(GLsizei((stream.size() - begin)));
    if(shade == SHADE_SOLID)
    {
      sc.states.push_back(res->m_stateobjects.draw_tris);
    }
    else
    {
      sc.states.push_back(lastSolid ? res->m_stateobjects.draw_line_tris : res->m_stateobjects.draw_line);
    }
    sc.fbos.push_back(res->m_framebuffer.fboScene);
  }

  template <class T>
  void GenerateTokens(T&              stream,
                      ShadeCommand&   sc,
                      ShadeType       shade,
                      const DrawItem* NV_RESTRICT drawItems,
                      size_t                      numItems,
                      const ResourcesGL* NV_RESTRICT res,
                      bool                           sorted)
  {
    if(sorted)
    {
      switch(shade)
      {
        case SHADE_SOLID:
          GenerateTokens<T, SHADE_SOLID, true>(stream, sc, drawItems, numItems, res);
          break;
        case SHADE_SOLIDWIRE:
          GenerateTokens<T, SHADE_SOLIDWIRE, true>(stream, sc, drawItems, numItems, res);
          break;
      }
    }
    else
    {
      switch(shade)
      {
        case SHADE_SOLID:
          GenerateTokens<T, SHADE_SOLID, false>(stream, sc, drawItems, numItems, res);
          break;
        case SHADE_SOLIDWIRE:
          GenerateTokens<T, SHADE_SOLIDWIRE, false>(stream, sc, drawItems, numItems, res);
          break;
      }
    }
  }
};

static RendererThreadedGLCMD::Type s_uborange;

void RendererThreadedGLCMD::init(const CadScene* NV_RESTRICT scene, Resources* resources, const Renderer::Config& config)
{
  m_scene                            = scene;
  const ResourcesGL* NV_RESTRICT res = (const ResourcesGL*)resources;

  fillDrawItems(m_drawItems, config, true, true);

  if(config.sorted)
  {
    std::sort(m_drawItems.begin(), m_drawItems.end(), DrawItem_compare_groups);
  }


  size_t worstCaseSize;

  {
    std::string  dummy;
    ShadeCommand sc;
    GenerateTokens<std::string>(dummy, sc, SHADE_SOLIDWIRE, &m_drawItems[0], m_drawItems.size(), res, config.sorted);
    worstCaseSize = (dummy.size() * 4) / 3;

    LOGI("buffer size: %d\n", uint32_t(worstCaseSize));
  }

  res->rebuildStateObjects();
  m_state = res->m_state;

  m_resources  = (const ResourcesGL*)resources;
  m_numThreads = config.threads;

  // make jobs
  m_ready       = 0;
  m_jobs        = new ThreadJob[m_numThreads];
  m_stopThreads = 0;

  for(int f = 0; f < NUM_FRAMES; f++)
  {
    m_syncs[f] = 0;
  }

  for(int i = 0; i < m_numThreads; i++)
  {
    ThreadJob& job = m_jobs[i];
    job.index      = i;
    job.renderer   = this;
    job.m_hasWork  = -1;
    job.m_frame    = 0;

    if(m_mode == MODE_BUFFER_PERS)
    {
      glCreateBuffers(NUM_FRAMES, m_jobs[i].m_buffers);
      for(int f = 0; f < NUM_FRAMES; f++)
      {
        glNamedBufferStorage(job.m_buffers[f], worstCaseSize, 0, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_DYNAMIC_STORAGE_BIT);
        job.m_streams[f].init(glMapNamedBufferRange(job.m_buffers[f], 0, worstCaseSize, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT),
                              worstCaseSize);
      }
    }

    s_threadpool.activateJob(i, threadMaster, &m_jobs[i]);
  }

  m_frame = 0;
}

void RendererThreadedGLCMD::deinit()
{
  m_stopThreads = 1;
  m_ready       = 0;

  NV_BARRIER();
  for(int i = 0; i < m_numThreads; i++)
  {
    std::unique_lock<std::mutex> lock(m_jobs[i].m_hasWorkMutex);
    m_jobs[i].m_hasWork = m_frame;
    m_jobs[i].m_hasWorkCond.notify_one();
  }

  std::this_thread::yield();

  {
    std::unique_lock<std::mutex> lock(m_readyMutex);
    while(m_ready < m_numThreads)
    {
      m_readyCond.wait(lock);
    }
  }

  NV_BARRIER();

  for(int f = 0; f < NUM_FRAMES; f++)
  {
    if(m_syncs[f])
    {
      glDeleteSync(m_syncs[f]);
    }
  }

  for(int i = 0; i < m_numThreads; i++)
  {
    if(m_mode == MODE_BUFFER_PERS)
    {
      for(int f = 0; f < NUM_FRAMES; f++)
      {
        glUnmapNamedBuffer(m_jobs[i].m_buffers[f]);
      }
      glDeleteBuffers(NUM_FRAMES, m_jobs[i].m_buffers);
    }

    for(size_t s = 0; s < m_jobs[i].m_scs.size(); s++)
    {
      delete m_jobs[i].m_scs[s];
    }
  }

  delete[] m_jobs;

  m_drawItems.clear();
}

void RendererThreadedGLCMD::enqueueShadeCommand_ts(ShadeCommand* sc)
{
  std::lock_guard<std::mutex> lock(m_drawMutex);
  m_drawQueue.push(sc);
}

unsigned int RendererThreadedGLCMD::RunThreadFrame(ShadeType shadetype, ThreadJob& job)
{
  unsigned int dispatches = 0;

  bool   first = true;
  size_t tnum  = 0;
  size_t begin = 0;
  size_t num   = 0;

  size_t offset = 0;
  job.resetFrame();

  int subframe = job.m_frame % NUM_FRAMES;
  job.m_streams[subframe].clear();

  while(getWork_ts(begin, num))
  {
    ShadeCommand* sc = job.getFrameCommand();
    sc->bufferData   = job.m_streams[subframe].dataptr;

    if(m_mode == MODE_BUFFER_PERS)
    {
      sc->bufferOffset = job.m_streams[subframe].size();
    }

    GenerateTokens<PointerStream>(job.m_streams[subframe], *sc, shadetype, &m_drawItems[begin], num, m_resources,
                                  m_config.sorted);
    sc->bufferSize = job.m_streams[subframe].size() - sc->bufferOffset;

    if(m_mode == MODE_BUFFER_PERS)
    {
      sc->buffer = job.m_buffers[subframe];
    }

    enqueueShadeCommand_ts(sc);
    dispatches += 1;

    tnum += num;
  }

  // NULL signals we are done
  enqueueShadeCommand_ts(NULL);

  return dispatches;
}

void RendererThreadedGLCMD::RunThread(int tid)
{
  ThreadJob& job = m_jobs[tid];
  ShadeType  shadetype;

  double timeWork    = 0;
  double timeFrame   = 0;
  int    timerFrames = 0;
  size_t dispatches  = 0;

  double timePrint = NVPSystem::getTime();

  while(!m_stopThreads)
  {
    //NV_BARRIER();

    double beginFrame = NVPSystem::getTime();
    timeFrame -= NVPSystem::getTime();

    {
      std::unique_lock<std::mutex> lock(job.m_hasWorkMutex);
      while(job.m_hasWork != job.m_frame)
      {
        job.m_hasWorkCond.wait(lock);
      }

      shadetype = m_shade;
    }

    if(m_stopThreads)
    {
      break;
    }

    double beginWork = NVPSystem::getTime();
    timeWork -= NVPSystem::getTime();

    dispatches += RunThreadFrame(shadetype, job);

    job.m_frame++;

    timeWork += NVPSystem::getTime();

    double currentTime = NVPSystem::getTime();
    timeFrame += currentTime;

    timerFrames++;

    if(timerFrames && (currentTime - timePrint) > 2.0)
    {
      timeFrame /= double(timerFrames);
      timeWork /= double(timerFrames);

      timeFrame *= 1000000.0;
      timeWork *= 1000000.0;

      timePrint = currentTime;

      GLuint avgdispatch = GLuint(double(dispatches) / double(timerFrames));
#if PRINT_TIMER_STATS
      LOGI("thread %d: work %6d [us] dispatches %5d\n", tid, GLuint(timeWork), GLuint(avgdispatch));
#endif
      timeFrame = 0;
      timeWork  = 0;

      timerFrames = 0;
      dispatches  = 0;
    }
  }

  {
    std::unique_lock<std::mutex> lock(m_readyMutex);
    m_ready++;
    m_readyCond.notify_all();
  }
}

void RendererThreadedGLCMD::draw(ShadeType shadetype, Resources* NV_RESTRICT resources, const Resources::Global& global)
{
  const CadScene* NV_RESTRICT scene = m_scene;
  ResourcesGL* NV_RESTRICT res      = (ResourcesGL*)resources;

  const nvgl::ProfilerGL::Section profile(res->m_profilerGL, "Render");

  // generic state setup
  glViewport(0, 0, global.winWidth, global.winHeight);

  // workaround
  glEnableClientState(GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV);
  glEnableClientState(GL_UNIFORM_BUFFER_UNIFIED_NV);

  if(m_state.programs != res->m_state.programs || m_state.fbos != res->m_state.fbos)
  {
    res->rebuildStateObjects();
  }

  glBindFramebuffer(GL_FRAMEBUFFER, res->m_framebuffer.fboScene);
  glClearColor(0.2f, 0.2f, 0.2f, 0.0f);
  glClearDepth(1.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

  glNamedBufferSubData(res->m_common.view, 0, sizeof(SceneData), &global.sceneUbo);

  m_workingSet  = global.workingSet;
  m_shade       = shadetype;
  m_numCurItems = 0;
  m_numEnqueues = 0;

  // generate & tokens/cmdbuffers in parallel

  NV_BARRIER();

  // start to dispatch threads
  for(int i = 0; i < m_numThreads; i++)
  {
    {
      std::unique_lock<std::mutex> lock(m_jobs[i].m_hasWorkMutex);
      m_jobs[i].m_hasWork = m_frame;
    }
    m_jobs[i].m_hasWorkCond.notify_one();
  }


  int subframe = m_frame % NUM_FRAMES;

  if(m_mode == MODE_BUFFER_PERS)
  {
    if(m_syncs[subframe])
    {
      GLenum ret = glClientWaitSync(m_syncs[subframe], GL_SYNC_FLUSH_COMMANDS_BIT, GL_TIMEOUT_IGNORED);
      glDeleteSync(m_syncs[subframe]);
      m_syncs[subframe] = 0;
    }
  }
  // dispatch drawing here
  {
    int numTerminated = 0;
    while(true)
    {
      bool          hadEntry = false;
      ShadeCommand* sc       = NULL;

      {
        std::lock_guard<std::mutex> lock(m_drawMutex);
        if(!m_drawQueue.empty())
        {

          sc = m_drawQueue.front();
          m_drawQueue.pop();

          hadEntry = true;
        }
      }

      if(hadEntry)
      {
        if(sc)
        {
          NV_BARRIER();
          m_numEnqueues++;
          glMemoryBarrier(GL_COMMAND_BARRIER_BIT);
          glDrawCommandsStatesNV(sc->buffer, &sc->offsets[0], &sc->sizes[0], &sc->states[0], &sc->fbos[0],
                                 (uint32_t)sc->sizes.size());
        }
        else
        {
          numTerminated++;
        }
      }

      if(numTerminated == m_numThreads)
      {
        break;
      }
      std::this_thread::yield();
    }
  }

  if(m_mode == MODE_BUFFER_PERS)
  {
    m_syncs[subframe] = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  }


  m_frame++;

  glDisableClientState(GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV);
  glDisableClientState(GL_UNIFORM_BUFFER_UNIFIED_NV);

  glBindFramebuffer(GL_FRAMEBUFFER, 0);

  m_state = res->m_state;
}

}  // namespace csfthreaded

#endif