/* parse argument list. we assume that all unrecognized arguments are file names. */
void CommandLineInfo::ParseCommandLine(TCHAR *cmdLine)
{
    StrVec argList;
    ParseCmdLine(cmdLine, argList);
    size_t argCount = argList.Count();

#define is_arg(txt) str::EqI(_T(txt), argument)
#define is_arg_with_param(txt) (is_arg(txt) && param != NULL)
#define additional_param() argList.At(n + 1)
#define has_additional_param() ((argCount > n + 1) && ('-' != additional_param()[0]))

    for (size_t n = 1; n < argCount; n++) {
        TCHAR *argument = argList.At(n);
        TCHAR *param = NULL;
        if (argCount > n + 1)
            param = argList.At(n + 1);

        if (is_arg("-register-for-pdf")) {
            makeDefault = true;
            exitImmediately = true;
            return;
        }
        else if (is_arg("-silent")) {
            // silences errors happening during -print-to and -print-to-default
            silent = true;
        }
        else if (is_arg("-print-to-default")) {
            TCHAR *name = GetDefaultPrinterName();
            if (name) {
                str::ReplacePtr(&printerName, name);
                free(name);
            }
        }
        else if (is_arg_with_param("-print-to")) {
            str::ReplacePtr(&printerName, argList.At(++n));
        }
        else if (is_arg("-print-dialog")) {
            printDialog = true;
        }
        else if (is_arg_with_param("-print-settings")) {
            // argument is a comma separated list of page ranges and
            // advanced options [even|odd] and [noscale|shrink|fit]
            // e.g. -print-settings "1-3,5,10-8,odd,fit"
            str::ReplacePtr(&printSettings, argList.At(++n));
            str::RemoveChars(printSettings, _T(" "));
        }
        else if (is_arg("-exit-on-print")) {
            // only affects -print-dialog (-print-to and -print-to-default
            // always exit on print)
            exitOnPrint = true;
        }
        else if (is_arg_with_param("-bgcolor") || is_arg_with_param("-bg-color")) {
            // -bgcolor is for backwards compat (was used pre-1.3)
            // -bg-color is for consistency
            ParseColor(&bgColor, argList.At(++n));
        }
        else if (is_arg_with_param("-inverse-search")) {
            str::ReplacePtr(&inverseSearchCmdLine, argList.At(++n));
        }
        else if ((is_arg_with_param("-forward-search") ||
                  is_arg_with_param("-fwdsearch")) && argCount > n + 2) {
            // -forward-search is for consistency with -inverse-search
            // -fwdsearch is for consistency with -fwdsearch-*
            str::ReplacePtr(&forwardSearchOrigin, argList.At(++n));
            forwardSearchLine = _ttoi(argList.At(++n));
        }
        else if (is_arg_with_param("-fwdsearch-offset")) {
            fwdSearch.offset = _ttoi(argList.At(++n));
        }
        else if (is_arg_with_param("-fwdsearch-width")) {
            fwdSearch.width = _ttoi(argList.At(++n));
        }
        else if (is_arg_with_param("-fwdsearch-color")) {
            ParseColor(&fwdSearch.color, argList.At(++n));
        }
        else if (is_arg_with_param("-fwdsearch-permanent")) {
            fwdSearch.permanent = _ttoi(argList.At(++n));
        }
        else if (is_arg("-esc-to-exit")) {
            escToExit = true;
        }
        else if (is_arg("-reuse-instance")) {
            // find the window handle of a running instance of SumatraPDF
            // TODO: there should be a mutex here to reduce possibility of
            // race condition and having more than one copy launch because
            // FindWindow() in one process is called before a window is created
            // in another process
            reuseInstance = (FindWindow(FRAME_CLASS_NAME, 0) != NULL);
        }
        else if (is_arg_with_param("-lang")) {
            free(lang);
            lang = str::conv::ToAnsi(argList.At(++n));
        }
        else if (is_arg_with_param("-nameddest") || is_arg_with_param("-named-dest")) {
            // -nameddest is for backwards compat (was used pre-1.3)
            // -named-dest is for consistency
            str::ReplacePtr(&destName, argList.At(++n));
        }
        else if (is_arg_with_param("-page")) {
            pageNumber = _ttoi(argList.At(++n));
        }
        else if (is_arg("-restrict")) {
            restrictedUse = true;
        }
        // TODO: remove -invert-colors and -set-color-range in favor
        //       of the UI settable gGlobalPrefs.useSysColors(?)
        else if (is_arg("-invertcolors") || is_arg("-invert-colors")) {
            // -invertcolors is for backwards compat (was used pre-1.3)
            // -invert-colors is for consistency
            // -invert-colors is a shortcut for -set-color-range 0xFFFFFF 0x000000
            // (i.e. it sets white as foreground color and black as background color)
            colorRange[0] = WIN_COL_WHITE;
            colorRange[1] = WIN_COL_BLACK;
        }
        else if (is_arg("-set-color-range") && argCount > n + 2) {
            STATIC_ASSERT(sizeof(colorRange[0]) == sizeof(int), colorref_as_int);
            ParseColor((int *)&colorRange[0], argList.At(++n));
            ParseColor((int *)&colorRange[1], argList.At(++n));
        }
        else if (is_arg("-presentation")) {
            enterPresentation = true;
        }
        else if (is_arg("-fullscreen")) {
            enterFullscreen = true;
        }
        else if (is_arg_with_param("-view")) {
            ParseViewMode(&startView, argList.At(++n));
        }
        else if (is_arg_with_param("-zoom")) {
            ParseZoomValue(&startZoom, argList.At(++n));
        }
        else if (is_arg_with_param("-scroll")) {
            ParseScrollValue(&startScroll, argList.At(++n));
        }
        else if (is_arg("-console")) {
            showConsole = true;
        }
        else if (is_arg_with_param("-plugin")) {
            // -plugin [<URL>] <parent HWND>
            if (!str::IsDigit(*param) && has_additional_param())
                str::ReplacePtr(&pluginURL, argList.At(++n));
            // the argument is a (numeric) window handle to
            // become the parent of a frameless SumatraPDF
            // (used e.g. for embedding it into a browser plugin)
            hwndPluginParent = (HWND)_ttol(argList.At(++n));
        }
        else if (is_arg_with_param("-stress-test")) {
            // -stress-test <file or dir path> [<file filter>] [<page/file range(s)>] [<cycle count>x]
            // e.g. -stress-test file.pdf 25x  for rendering file.pdf 25 times
            //      -stress-test file.pdf 1-3  render only pages 1, 2 and 3 of file.pdf
            //      -stress-test dir 301- 2x   render all files in dir twice, skipping first 300
            //      -stress-test dir *.pdf;*.xps  render all files in dir that are either PDF or XPS
            str::ReplacePtr(&stressTestPath, argList.At(++n));
            int num;
            if (has_additional_param() && str::FindChar(additional_param(), '*')) {
                str::ReplacePtr(&stressTestFilter, additional_param());
                n++;
            }
            if (has_additional_param() && IsValidPageRange(additional_param())) {
                str::ReplacePtr(&stressTestRanges, additional_param());
                n++;
            }
            if (has_additional_param() && str::Parse(additional_param(), _T("%dx%$"), &num) && num > 0) {
                stressTestCycles = num;
                n++;
            }
        }
        else if (is_arg_with_param("-bench")) {
            TCHAR *s = str::Dup(argList.At(++n));
            pathsToBenchmark.Push(s);
            s = NULL;
            if (has_additional_param() && IsBenchPagesInfo(additional_param())) {
                s = str::Dup(additional_param());
                n++;
            }
            pathsToBenchmark.Push(s);
            exitImmediately = true;
        } else if (is_arg("-crash-on-open")) {
            // to make testing of crash reporting system in pre-release/release
            // builds possible
            crashOnOpen = true;
        } else if (is_arg_with_param("-manga-mode")) {
            // TODO: we should have a ui for this instead of remembering it globally
            // in prefs
            TCHAR *s = argList.At(++n);
            cbxR2L = str::EqI(_T("true"), s) || str::Eq(_T("1"), s);
        }
#ifdef DEBUG
        else if (is_arg("-enum-printers")) {
            EnumeratePrinters();
            /* this is for testing only, exit immediately */
            exitImmediately = true;
            return;
        }
#endif
        else {
            // Remember this argument as a filename to open
            TCHAR *filepath = NULL;
            if (str::EndsWithI(argList.At(n), _T(".lnk")))
                filepath = ResolveLnk(argList.At(n));
            if (!filepath)
                filepath = str::Dup(argList.At(n));
            fileNames.Push(filepath);
        }
    }
#undef is_arg
#undef is_arg_with_param
#undef additional_param
#undef has_additional_param
}
static void populate_key(struct brw_context *brw,
                         struct brw_ff_gs_prog_key *key)
{
   static const unsigned swizzle_for_offset[4] = {
      BRW_SWIZZLE4(0, 1, 2, 3),
      BRW_SWIZZLE4(1, 2, 3, 3),
      BRW_SWIZZLE4(2, 3, 3, 3),
      BRW_SWIZZLE4(3, 3, 3, 3)
   };

   struct gl_context *ctx = &brw->ctx;

   memset(key, 0, sizeof(*key));

   /* BRW_NEW_VS_PROG_DATA (part of VUE map) */
   key->attrs = brw->vs.prog_data->base.vue_map.slots_valid;

   /* BRW_NEW_PRIMITIVE */
   key->primitive = brw->primitive;

   /* _NEW_LIGHT */
   key->pv_first = (ctx->Light.ProvokingVertex == GL_FIRST_VERTEX_CONVENTION);
   if (key->primitive == _3DPRIM_QUADLIST && ctx->Light.ShadeModel != GL_FLAT) {
      /* Provide consistent primitive order with brw_set_prim's
       * optimization of single quads to trifans.
       */
      key->pv_first = true;
   }

   if (brw->gen >= 7) {
      /* On Gen7 and later, we don't use GS (yet). */
      key->need_gs_prog = false;
   } else if (brw->gen == 6) {
      /* On Gen6, GS is used for transform feedback. */
      /* BRW_NEW_TRANSFORM_FEEDBACK */
      if (_mesa_is_xfb_active_and_unpaused(ctx)) {
         const struct gl_shader_program *shaderprog =
            ctx->_Shader->CurrentProgram[MESA_SHADER_VERTEX];
         const struct gl_transform_feedback_info *linked_xfb_info =
            &shaderprog->LinkedTransformFeedback;
         int i;

         /* Make sure that the VUE slots won't overflow the unsigned chars in
          * key->transform_feedback_bindings[].
          */
         STATIC_ASSERT(BRW_VARYING_SLOT_COUNT <= 256);

         /* Make sure that we don't need more binding table entries than we've
          * set aside for use in transform feedback.  (We shouldn't, since we
          * set aside enough binding table entries to have one per component).
          */
         assert(linked_xfb_info->NumOutputs <= BRW_MAX_SOL_BINDINGS);

         key->need_gs_prog = true;
         key->num_transform_feedback_bindings = linked_xfb_info->NumOutputs;
         for (i = 0; i < key->num_transform_feedback_bindings; ++i) {
            key->transform_feedback_bindings[i] =
               linked_xfb_info->Outputs[i].OutputRegister;
            key->transform_feedback_swizzles[i] =
               swizzle_for_offset[linked_xfb_info->Outputs[i].ComponentOffset];
         }
      }
   } else {
      /* Pre-gen6, GS is used to transform QUADLIST, QUADSTRIP, and LINELOOP
       * into simpler primitives.
       */
      key->need_gs_prog = (brw->primitive == _3DPRIM_QUADLIST ||
                           brw->primitive == _3DPRIM_QUADSTRIP ||
                           brw->primitive == _3DPRIM_LINELOOP);
   }
}
Exemple #3
0
/**
 * Called by vbuf code when we're about to draw something.
 *
 * This function stores all dirty state in the current scene's display list
 * memory, via lp_scene_alloc().  We can not pass pointers of mutable state to
 * the JIT functions, as the JIT functions will be called later on, most likely
 * on a different thread.
 *
 * When processing dirty state it is imperative that we don't refer to any
 * pointers previously allocated with lp_scene_alloc() in this function (or any
 * function) as they may belong to a scene freed since then.
 */
static boolean
try_update_scene_state( struct lp_setup_context *setup )
{
   static const float fake_const_buf[4];
   boolean new_scene = (setup->fs.stored == NULL);
   struct lp_scene *scene = setup->scene;
   unsigned i;

   assert(scene);

   if (setup->dirty & LP_SETUP_NEW_VIEWPORTS) {
      /*
       * Record new depth range state for changes due to viewport updates.
       *
       * TODO: Collapse the existing viewport and depth range information
       *       into one structure, for access by JIT.
       */
      struct lp_jit_viewport *stored;

      stored = (struct lp_jit_viewport *)
         lp_scene_alloc(scene, sizeof setup->viewports);

      if (!stored) {
         assert(!new_scene);
         return FALSE;
      }

      memcpy(stored, setup->viewports, sizeof setup->viewports);

      setup->fs.current.jit_context.viewports = stored;
      setup->dirty |= LP_SETUP_NEW_FS;
   }

   if(setup->dirty & LP_SETUP_NEW_BLEND_COLOR) {
      uint8_t *stored;
      float* fstored;
      unsigned i, j;
      unsigned size;

      /* Alloc u8_blend_color (16 x i8) and f_blend_color (4 or 8 x f32) */
      size  = 4 * 16 * sizeof(uint8_t);
      size += (LP_MAX_VECTOR_LENGTH / 4) * sizeof(float);
      stored = lp_scene_alloc_aligned(scene, size, LP_MIN_VECTOR_ALIGN);

      if (!stored) {
         assert(!new_scene);
         return FALSE;
      }

      /* Store floating point colour */
      fstored = (float*)(stored + 4*16);
      for (i = 0; i < (LP_MAX_VECTOR_LENGTH / 4); ++i) {
         fstored[i] = setup->blend_color.current.color[i % 4];
      }

      /* smear each blend color component across 16 ubyte elements */
      for (i = 0; i < 4; ++i) {
         uint8_t c = float_to_ubyte(setup->blend_color.current.color[i]);
         for (j = 0; j < 16; ++j)
            stored[i*16 + j] = c;
      }

      setup->blend_color.stored = stored;
      setup->fs.current.jit_context.u8_blend_color = stored;
      setup->fs.current.jit_context.f_blend_color = fstored;
      setup->dirty |= LP_SETUP_NEW_FS;
   }

   if (setup->dirty & LP_SETUP_NEW_CONSTANTS) {
      for (i = 0; i < ARRAY_SIZE(setup->constants); ++i) {
         struct pipe_resource *buffer = setup->constants[i].current.buffer;
         const unsigned current_size = MIN2(setup->constants[i].current.buffer_size,
                                            LP_MAX_TGSI_CONST_BUFFER_SIZE);
         const ubyte *current_data = NULL;
         int num_constants;

         STATIC_ASSERT(DATA_BLOCK_SIZE >= LP_MAX_TGSI_CONST_BUFFER_SIZE);

         if (buffer) {
            /* resource buffer */
            current_data = (ubyte *) llvmpipe_resource_data(buffer);
         }
         else if (setup->constants[i].current.user_buffer) {
            /* user-space buffer */
            current_data = (ubyte *) setup->constants[i].current.user_buffer;
         }

         if (current_data) {
            current_data += setup->constants[i].current.buffer_offset;

            /* TODO: copy only the actually used constants? */

            if (setup->constants[i].stored_size != current_size ||
               !setup->constants[i].stored_data ||
               memcmp(setup->constants[i].stored_data,
                      current_data,
                      current_size) != 0) {
               void *stored;

               stored = lp_scene_alloc(scene, current_size);
               if (!stored) {
                  assert(!new_scene);
                  return FALSE;
               }

               memcpy(stored,
                      current_data,
                      current_size);
               setup->constants[i].stored_size = current_size;
               setup->constants[i].stored_data = stored;
            }
            setup->fs.current.jit_context.constants[i] =
               setup->constants[i].stored_data;
         }
         else {
            setup->constants[i].stored_size = 0;
            setup->constants[i].stored_data = NULL;
            setup->fs.current.jit_context.constants[i] = fake_const_buf;
         }

         num_constants =
            setup->constants[i].stored_size / (sizeof(float) * 4);
         setup->fs.current.jit_context.num_constants[i] = num_constants;
         setup->dirty |= LP_SETUP_NEW_FS;
      }
   }


   if (setup->dirty & LP_SETUP_NEW_FS) {
      if (!setup->fs.stored ||
          memcmp(setup->fs.stored,
                 &setup->fs.current,
                 sizeof setup->fs.current) != 0)
      {
         struct lp_rast_state *stored;
         
         /* The fs state that's been stored in the scene is different from
          * the new, current state.  So allocate a new lp_rast_state object
          * and append it to the bin's setup data buffer.
          */
         stored = (struct lp_rast_state *) lp_scene_alloc(scene, sizeof *stored);
         if (!stored) {
            assert(!new_scene);
            return FALSE;
         }

         memcpy(stored,
                &setup->fs.current,
                sizeof setup->fs.current);
         setup->fs.stored = stored;
         
         /* The scene now references the textures in the rasterization
          * state record.  Note that now.
          */
         for (i = 0; i < ARRAY_SIZE(setup->fs.current_tex); i++) {
            if (setup->fs.current_tex[i]) {
               if (!lp_scene_add_resource_reference(scene,
                                                    setup->fs.current_tex[i],
                                                    new_scene)) {
                  assert(!new_scene);
                  return FALSE;
               }
            }
         }
      }
   }

   if (setup->dirty & LP_SETUP_NEW_SCISSOR) {
      unsigned i;
      for (i = 0; i < PIPE_MAX_VIEWPORTS; ++i) {
         setup->draw_regions[i] = setup->framebuffer;
         if (setup->scissor_test) {
            u_rect_possible_intersection(&setup->scissors[i],
                                         &setup->draw_regions[i]);
         }
      }
   }

   setup->dirty = 0;

   assert(setup->fs.stored);
   return TRUE;
}
Exemple #4
0
/**
 * Compute the VUE map for vertex shader program.
 */
void
brw_compute_vue_map(struct brw_context *brw, struct brw_vue_map *vue_map,
                    GLbitfield64 slots_valid)
{
   vue_map->slots_valid = slots_valid;
   int i;

   /* gl_Layer doesn't get its own varying slot--it's stored in the virst VUE
    * slot (VARYING_SLOT_PSIZ).
    */
   slots_valid &= ~VARYING_BIT_LAYER;

   /* Make sure that the values we store in vue_map->varying_to_slot and
    * vue_map->slot_to_varying won't overflow the signed chars that are used
    * to store them.  Note that since vue_map->slot_to_varying sometimes holds
    * values equal to BRW_VARYING_SLOT_COUNT, we need to ensure that
    * BRW_VARYING_SLOT_COUNT is <= 127, not 128.
    */
   STATIC_ASSERT(BRW_VARYING_SLOT_COUNT <= 127);

   vue_map->num_slots = 0;
   for (i = 0; i < BRW_VARYING_SLOT_COUNT; ++i) {
      vue_map->varying_to_slot[i] = -1;
      vue_map->slot_to_varying[i] = BRW_VARYING_SLOT_COUNT;
   }

   /* VUE header: format depends on chip generation and whether clipping is
    * enabled.
    */
   switch (brw->gen) {
   case 4:
   case 5:
      /* There are 8 dwords in VUE header pre-Ironlake:
       * dword 0-3 is indices, point width, clip flags.
       * dword 4-7 is ndc position
       * dword 8-11 is the first vertex data.
       *
       * On Ironlake the VUE header is nominally 20 dwords, but the hardware
       * will accept the same header layout as Gen4 [and should be a bit faster]
       */
      assign_vue_slot(vue_map, VARYING_SLOT_PSIZ);
      assign_vue_slot(vue_map, BRW_VARYING_SLOT_NDC);
      assign_vue_slot(vue_map, VARYING_SLOT_POS);
      break;
   case 6:
   case 7:
      /* There are 8 or 16 DWs (D0-D15) in VUE header on Sandybridge:
       * dword 0-3 of the header is indices, point width, clip flags.
       * dword 4-7 is the 4D space position
       * dword 8-15 of the vertex header is the user clip distance if
       * enabled.
       * dword 8-11 or 16-19 is the first vertex element data we fill.
       */
      assign_vue_slot(vue_map, VARYING_SLOT_PSIZ);
      assign_vue_slot(vue_map, VARYING_SLOT_POS);
      if (slots_valid & BITFIELD64_BIT(VARYING_SLOT_CLIP_DIST0))
         assign_vue_slot(vue_map, VARYING_SLOT_CLIP_DIST0);
      if (slots_valid & BITFIELD64_BIT(VARYING_SLOT_CLIP_DIST1))
         assign_vue_slot(vue_map, VARYING_SLOT_CLIP_DIST1);

      /* front and back colors need to be consecutive so that we can use
       * ATTRIBUTE_SWIZZLE_INPUTATTR_FACING to swizzle them when doing
       * two-sided color.
       */
      if (slots_valid & BITFIELD64_BIT(VARYING_SLOT_COL0))
         assign_vue_slot(vue_map, VARYING_SLOT_COL0);
      if (slots_valid & BITFIELD64_BIT(VARYING_SLOT_BFC0))
         assign_vue_slot(vue_map, VARYING_SLOT_BFC0);
      if (slots_valid & BITFIELD64_BIT(VARYING_SLOT_COL1))
         assign_vue_slot(vue_map, VARYING_SLOT_COL1);
      if (slots_valid & BITFIELD64_BIT(VARYING_SLOT_BFC1))
         assign_vue_slot(vue_map, VARYING_SLOT_BFC1);
      break;
   default:
      assert (!"VUE map not known for this chip generation");
      break;
   }

   /* The hardware doesn't care about the rest of the vertex outputs, so just
    * assign them contiguously.  Don't reassign outputs that already have a
    * slot.
    *
    * We generally don't need to assign a slot for VARYING_SLOT_CLIP_VERTEX,
    * since it's encoded as the clip distances by emit_clip_distances().
    * However, it may be output by transform feedback, and we'd rather not
    * recompute state when TF changes, so we just always include it.
    */
   for (int i = 0; i < VARYING_SLOT_MAX; ++i) {
      if ((slots_valid & BITFIELD64_BIT(i)) &&
          vue_map->varying_to_slot[i] == -1) {
         assign_vue_slot(vue_map, i);
      }
   }
}
Exemple #5
0
/**
 * Called via eglCreateWindowSurface(), drv->API.CreateWindowSurface().
 */
static _EGLSurface *
dri2_x11_create_surface(_EGLDriver *drv, _EGLDisplay *disp, EGLint type,
                        _EGLConfig *conf, void *native_surface,
                        const EGLint *attrib_list)
{
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
   struct dri2_egl_config *dri2_conf = dri2_egl_config(conf);
   struct dri2_egl_surface *dri2_surf;
   xcb_get_geometry_cookie_t cookie;
   xcb_get_geometry_reply_t *reply;
   xcb_generic_error_t *error;
   const __DRIconfig *config;

   (void) drv;

   dri2_surf = malloc(sizeof *dri2_surf);
   if (!dri2_surf) {
      _eglError(EGL_BAD_ALLOC, "dri2_create_surface");
      return NULL;
   }
   
   if (!dri2_init_surface(&dri2_surf->base, disp, type, conf, attrib_list,
                          false, native_surface))
      goto cleanup_surf;

   dri2_surf->region = XCB_NONE;
   if (type == EGL_PBUFFER_BIT) {
      dri2_surf->drawable = xcb_generate_id(dri2_dpy->conn);
      xcb_create_pixmap(dri2_dpy->conn, conf->BufferSize,
                       dri2_surf->drawable, dri2_dpy->screen->root,
			dri2_surf->base.Width, dri2_surf->base.Height);
   } else {
      STATIC_ASSERT(sizeof(uintptr_t) == sizeof(native_surface));
      dri2_surf->drawable = (uintptr_t) native_surface;
   }

   config = dri2_get_dri_config(dri2_conf, type,
                                dri2_surf->base.GLColorspace);

   if (!config) {
      _eglError(EGL_BAD_MATCH, "Unsupported surfacetype/colorspace configuration");
      goto cleanup_pixmap;
   }

   if (dri2_dpy->dri2) {
      dri2_surf->dri_drawable =
         dri2_dpy->dri2->createNewDrawable(dri2_dpy->dri_screen, config,
                                           dri2_surf);
   } else {
      assert(dri2_dpy->swrast);
      dri2_surf->dri_drawable = 
         dri2_dpy->swrast->createNewDrawable(dri2_dpy->dri_screen, config,
                                             dri2_surf);
   }

   if (dri2_surf->dri_drawable == NULL) {
      _eglError(EGL_BAD_ALLOC, "dri2->createNewDrawable");
      goto cleanup_pixmap;
   }

   if (type != EGL_PBUFFER_BIT) {
      cookie = xcb_get_geometry (dri2_dpy->conn, dri2_surf->drawable);
      reply = xcb_get_geometry_reply (dri2_dpy->conn, cookie, &error);
      if (error != NULL) {
         if (error->error_code == BadAlloc)
            _eglError(EGL_BAD_ALLOC, "xcb_get_geometry");
         else if (type == EGL_WINDOW_BIT)
            _eglError(EGL_BAD_NATIVE_WINDOW, "xcb_get_geometry");
         else
            _eglError(EGL_BAD_NATIVE_PIXMAP, "xcb_get_geometry");
         free(error);
         goto cleanup_dri_drawable;
      } else if (reply == NULL) {
         _eglError(EGL_BAD_ALLOC, "xcb_get_geometry");
         goto cleanup_dri_drawable;
      }

      dri2_surf->base.Width = reply->width;
      dri2_surf->base.Height = reply->height;
      dri2_surf->depth = reply->depth;
      free(reply);
   }

   if (dri2_dpy->dri2) {
      xcb_void_cookie_t cookie;
      int conn_error;

      cookie = xcb_dri2_create_drawable_checked(dri2_dpy->conn,
                                                dri2_surf->drawable);
      error = xcb_request_check(dri2_dpy->conn, cookie);
      conn_error = xcb_connection_has_error(dri2_dpy->conn);
      if (conn_error || error != NULL) {
         if (type == EGL_PBUFFER_BIT || conn_error || error->error_code == BadAlloc)
            _eglError(EGL_BAD_ALLOC, "xcb_dri2_create_drawable_checked");
         else if (type == EGL_WINDOW_BIT)
            _eglError(EGL_BAD_NATIVE_WINDOW,
                      "xcb_dri2_create_drawable_checked");
         else
            _eglError(EGL_BAD_NATIVE_PIXMAP,
                      "xcb_dri2_create_drawable_checked");
         free(error);
         goto cleanup_dri_drawable;
      }
   } else {
      if (type == EGL_PBUFFER_BIT) {
         dri2_surf->depth = _eglGetConfigKey(conf, EGL_BUFFER_SIZE);
      }
      swrastCreateDrawable(dri2_dpy, dri2_surf);
   }

   /* we always copy the back buffer to front */
   dri2_surf->base.PostSubBufferSupportedNV = EGL_TRUE;

   return &dri2_surf->base;

 cleanup_dri_drawable:
   dri2_dpy->core->destroyDrawable(dri2_surf->dri_drawable);
 cleanup_pixmap:
   if (type == EGL_PBUFFER_BIT)
      xcb_free_pixmap(dri2_dpy->conn, dri2_surf->drawable);
 cleanup_surf:
   free(dri2_surf);

   return NULL;
}
Exemple #6
0
static bool
raster_set_gen8_3DSTATE_RASTER(struct ilo_state_raster *rs,
                               const struct ilo_dev *dev,
                               const struct ilo_state_raster_info *info,
                               const struct ilo_state_raster_line_info *line)
{
   const struct ilo_state_raster_clip_info *clip = &info->clip;
   const struct ilo_state_raster_setup_info *setup = &info->setup;
   const struct ilo_state_raster_point_info *point = &info->point;
   const struct ilo_state_raster_tri_info *tri = &info->tri;
   const struct ilo_state_raster_params_info *params = &info->params;
   uint32_t dw1;

   ILO_DEV_ASSERT(dev, 8, 8);

   if (!raster_validate_gen8_raster(dev, info))
      return false;

   dw1 = tri->front_winding << GEN8_RASTER_DW1_FRONT_WINDING__SHIFT |
         tri->cull_mode << GEN8_RASTER_DW1_CULL_MODE__SHIFT |
         tri->fill_mode_front << GEN8_RASTER_DW1_FILL_MODE_FRONT__SHIFT |
         tri->fill_mode_back << GEN8_RASTER_DW1_FILL_MODE_BACK__SHIFT;

   if (point->aa_enable)
      dw1 |= GEN8_RASTER_DW1_SMOOTH_POINT_ENABLE;

   /* where should line_msaa_enable be set? */
   if (setup->msaa_enable)
      dw1 |= GEN8_RASTER_DW1_DX_MULTISAMPLE_ENABLE;

   if (tri->depth_offset_solid)
      dw1 |= GEN8_RASTER_DW1_DEPTH_OFFSET_SOLID;
   if (tri->depth_offset_wireframe)
      dw1 |= GEN8_RASTER_DW1_DEPTH_OFFSET_WIREFRAME;
   if (tri->depth_offset_point)
      dw1 |= GEN8_RASTER_DW1_DEPTH_OFFSET_POINT;

   if (line->aa_enable)
      dw1 |= GEN8_RASTER_DW1_AA_LINE_ENABLE;

   if (setup->scissor_enable)
      dw1 |= GEN8_RASTER_DW1_SCISSOR_ENABLE;

   if (ilo_dev_gen(dev) >= ILO_GEN(9)) {
      if (clip->z_far_enable)
         dw1 |= GEN9_RASTER_DW1_Z_TEST_FAR_ENABLE;
      if (clip->z_near_enable)
         dw1 |= GEN9_RASTER_DW1_Z_TEST_NEAR_ENABLE;
   } else {
      if (clip->z_near_enable)
         dw1 |= GEN8_RASTER_DW1_Z_TEST_ENABLE;
   }

   STATIC_ASSERT(ARRAY_SIZE(rs->raster) >= 4);
   rs->raster[0] = dw1;
   rs->raster[1] = fui(params->depth_offset_const);
   rs->raster[2] = fui(params->depth_offset_scale);
   rs->raster[3] = fui(params->depth_offset_clamp);

   rs->line_aa_enable = line->aa_enable;
   rs->line_giq_enable = line->giq_enable;

   return true;
}
Exemple #7
0
/**
 * Find the offset of the start of the free space on the device (or the size of the device if it is full).
 */
int flashfsIdentifyStartOfFreeSpace(void)
{
    /* Find the start of the free space on the device by examining the beginning of blocks with a binary search,
     * looking for ones that appear to be erased. We can achieve this with good accuracy because an erased block
     * is all bits set to 1, which pretty much never appears in reasonable size substrings of blackbox logs.
     *
     * To do better we might write a volume header instead, which would mark how much free space remains. But keeping
     * a header up to date while logging would incur more writes to the flash, which would consume precious write
     * bandwidth and block more often.
     */

    enum {
        /* We can choose whatever power of 2 size we like, which determines how much wastage of free space we'll have
         * at the end of the last written data. But smaller blocksizes will require more searching.
         */
        FREE_BLOCK_SIZE = 2048, // XXX This can't be smaller than page size for underlying flash device.

        /* We don't expect valid data to ever contain this many consecutive uint32_t's of all 1 bits: */
        FREE_BLOCK_TEST_SIZE_INTS = 4, // i.e. 16 bytes
        FREE_BLOCK_TEST_SIZE_BYTES = FREE_BLOCK_TEST_SIZE_INTS * sizeof(uint32_t)
    };

    STATIC_ASSERT(FREE_BLOCK_SIZE >= FLASH_MAX_PAGE_SIZE, FREE_BLOCK_SIZE_too_small);

    union {
        uint8_t bytes[FREE_BLOCK_TEST_SIZE_BYTES];
        uint32_t ints[FREE_BLOCK_TEST_SIZE_INTS];
    } testBuffer;

    int left = 0; // Smallest block index in the search region
    int right = flashfsGetSize() / FREE_BLOCK_SIZE; // One past the largest block index in the search region
    int mid;
    int result = right;
    int i;
    bool blockErased;

    while (left < right) {
        mid = (left + right) / 2;

        if (flashReadBytes(mid * FREE_BLOCK_SIZE, testBuffer.bytes, FREE_BLOCK_TEST_SIZE_BYTES) < FREE_BLOCK_TEST_SIZE_BYTES) {
            // Unexpected timeout from flash, so bail early (reporting the device fuller than it really is)
            break;
        }

        // Checking the buffer 4 bytes at a time like this is probably faster than byte-by-byte, but I didn't benchmark it :)
        blockErased = true;
        for (i = 0; i < FREE_BLOCK_TEST_SIZE_INTS; i++) {
            if (testBuffer.ints[i] != 0xFFFFFFFF) {
                blockErased = false;
                break;
            }
        }

        if (blockErased) {
            /* This erased block might be the leftmost erased block in the volume, but we'll need to continue the
             * search leftwards to find out:
             */
            result = mid;

            right = mid;
        } else {
            left = mid + 1;
        }
    }

    return result * FREE_BLOCK_SIZE;
}
Exemple #8
0
/**
 * Outputs the 3DSTATE_SO_DECL_LIST command.
 *
 * The data output is a series of 64-bit entries containing a SO_DECL per
 * stream.  We only have one stream of rendering coming out of the GS unit, so
 * we only emit stream 0 (low 16 bits) SO_DECLs.
 */
void
gen7_upload_3dstate_so_decl_list(struct brw_context *brw,
                                 const struct brw_vue_map *vue_map)
{
    struct gl_context *ctx = &brw->ctx;
    /* BRW_NEW_VERTEX_PROGRAM */
    const struct gl_shader_program *vs_prog =
            ctx->Shader.CurrentVertexProgram;
    /* BRW_NEW_TRANSFORM_FEEDBACK */
    const struct gl_transform_feedback_info *linked_xfb_info =
            &vs_prog->LinkedTransformFeedback;
    int i;
    uint16_t so_decl[128];
    int buffer_mask = 0;
    int next_offset[4] = {0, 0, 0, 0};

    STATIC_ASSERT(ARRAY_SIZE(so_decl) >= MAX_PROGRAM_OUTPUTS);

    /* Construct the list of SO_DECLs to be emitted.  The formatting of the
     * command is feels strange -- each dword pair contains a SO_DECL per stream.
     */
    for (i = 0; i < linked_xfb_info->NumOutputs; i++) {
        int buffer = linked_xfb_info->Outputs[i].OutputBuffer;
        uint16_t decl = 0;
        int varying = linked_xfb_info->Outputs[i].OutputRegister;
        unsigned component_mask =
            (1 << linked_xfb_info->Outputs[i].NumComponents) - 1;

        /* gl_PointSize is stored in VARYING_SLOT_PSIZ.w. */
        if (varying == VARYING_SLOT_PSIZ) {
            assert(linked_xfb_info->Outputs[i].NumComponents == 1);
            component_mask <<= 3;
        } else {
            component_mask <<= linked_xfb_info->Outputs[i].ComponentOffset;
        }

        buffer_mask |= 1 << buffer;

        decl |= buffer << SO_DECL_OUTPUT_BUFFER_SLOT_SHIFT;
        decl |= vue_map->varying_to_slot[varying] <<
                SO_DECL_REGISTER_INDEX_SHIFT;
        decl |= component_mask << SO_DECL_COMPONENT_MASK_SHIFT;

        /* This assert should be true until GL_ARB_transform_feedback_instanced
         * is added and we start using the hole flag.
         */
        assert(linked_xfb_info->Outputs[i].DstOffset == next_offset[buffer]);

        next_offset[buffer] += linked_xfb_info->Outputs[i].NumComponents;

        so_decl[i] = decl;
    }

    BEGIN_BATCH(linked_xfb_info->NumOutputs * 2 + 3);
    OUT_BATCH(_3DSTATE_SO_DECL_LIST << 16 |
              (linked_xfb_info->NumOutputs * 2 + 1));

    OUT_BATCH((buffer_mask << SO_STREAM_TO_BUFFER_SELECTS_0_SHIFT) |
              (0 << SO_STREAM_TO_BUFFER_SELECTS_1_SHIFT) |
              (0 << SO_STREAM_TO_BUFFER_SELECTS_2_SHIFT) |
              (0 << SO_STREAM_TO_BUFFER_SELECTS_3_SHIFT));

    OUT_BATCH((linked_xfb_info->NumOutputs << SO_NUM_ENTRIES_0_SHIFT) |
              (0 << SO_NUM_ENTRIES_1_SHIFT) |
              (0 << SO_NUM_ENTRIES_2_SHIFT) |
              (0 << SO_NUM_ENTRIES_3_SHIFT));

    for (i = 0; i < linked_xfb_info->NumOutputs; i++) {
        OUT_BATCH(so_decl[i]);
        OUT_BATCH(0);
    }

    ADVANCE_BATCH();
}
Exemple #9
0
/**
 * Return ARB_v/f_prog-style input attrib string.
 */
static const char *
arb_input_attrib_string(GLint index, GLenum progType)
{
   /*
    * These strings should match the VERT_ATTRIB_x and FRAG_ATTRIB_x tokens.
    */
   static const char *const vertAttribs[] = {
      "vertex.position",
      "vertex.weight",
      "vertex.normal",
      "vertex.color.primary",
      "vertex.color.secondary",
      "vertex.fogcoord",
      "vertex.(six)", /* VERT_ATTRIB_COLOR_INDEX */
      "vertex.(seven)", /* VERT_ATTRIB_EDGEFLAG */
      "vertex.texcoord[0]",
      "vertex.texcoord[1]",
      "vertex.texcoord[2]",
      "vertex.texcoord[3]",
      "vertex.texcoord[4]",
      "vertex.texcoord[5]",
      "vertex.texcoord[6]",
      "vertex.texcoord[7]",
      "vertex.(sixteen)", /* VERT_ATTRIB_POINT_SIZE */
      "vertex.attrib[0]",
      "vertex.attrib[1]",
      "vertex.attrib[2]",
      "vertex.attrib[3]",
      "vertex.attrib[4]",
      "vertex.attrib[5]",
      "vertex.attrib[6]",
      "vertex.attrib[7]",
      "vertex.attrib[8]",
      "vertex.attrib[9]",
      "vertex.attrib[10]",
      "vertex.attrib[11]",
      "vertex.attrib[12]",
      "vertex.attrib[13]",
      "vertex.attrib[14]",
      "vertex.attrib[15]" /* MAX_VARYING = 16 */
   };
   static const char *const fragAttribs[] = {
      "fragment.position",
      "fragment.color.primary",
      "fragment.color.secondary",
      "fragment.fogcoord",
      "fragment.texcoord[0]",
      "fragment.texcoord[1]",
      "fragment.texcoord[2]",
      "fragment.texcoord[3]",
      "fragment.texcoord[4]",
      "fragment.texcoord[5]",
      "fragment.texcoord[6]",
      "fragment.texcoord[7]",
      "fragment.(twelve)", /* FRAG_ATTRIB_FACE */
      "fragment.(thirteen)", /* FRAG_ATTRIB_PNTC */
      "fragment.(fourteen)", /* FRAG_ATTRIB_CLIP_DIST0 */
      "fragment.(fifteen)", /* FRAG_ATTRIB_CLIP_DIST1 */
      "fragment.varying[0]",
      "fragment.varying[1]",
      "fragment.varying[2]",
      "fragment.varying[3]",
      "fragment.varying[4]",
      "fragment.varying[5]",
      "fragment.varying[6]",
      "fragment.varying[7]",
      "fragment.varying[8]",
      "fragment.varying[9]",
      "fragment.varying[10]",
      "fragment.varying[11]",
      "fragment.varying[12]",
      "fragment.varying[13]",
      "fragment.varying[14]",
      "fragment.varying[15]" /* MAX_VARYING = 16 */
   };

   /* sanity checks */
   STATIC_ASSERT(Elements(vertAttribs) == VERT_ATTRIB_MAX);
   STATIC_ASSERT(Elements(fragAttribs) == FRAG_ATTRIB_MAX);
   assert(strcmp(vertAttribs[VERT_ATTRIB_TEX0], "vertex.texcoord[0]") == 0);
   assert(strcmp(vertAttribs[VERT_ATTRIB_GENERIC15], "vertex.attrib[15]") == 0);
   assert(strcmp(fragAttribs[FRAG_ATTRIB_TEX0], "fragment.texcoord[0]") == 0);
   assert(strcmp(fragAttribs[FRAG_ATTRIB_VAR0+15], "fragment.varying[15]") == 0);

   if (progType == GL_VERTEX_PROGRAM_ARB) {
      assert(index < Elements(vertAttribs));
      return vertAttribs[index];
   }
   else {
      assert(progType == GL_FRAGMENT_PROGRAM_ARB);
      assert(index < Elements(fragAttribs));
      return fragAttribs[index];
   }
}
Exemple #10
0
/** Draw the droids and structure positions on the radar. */
static void DrawRadarObjects()
{
	UBYTE				clan;
	PIELIGHT			playerCol;
	PIELIGHT			flashCol;
	int				x, y;

	/* Show droids on map - go through all players */
	for (clan = 0; clan < MAX_PLAYERS; clan++)
	{
		DROID		*psDroid;

		//see if have to draw enemy/ally color
		if (bEnemyAllyRadarColor)
		{
			if (clan == selectedPlayer)
			{
				playerCol = colRadarMe;
			}
			else
			{
				playerCol = (aiCheckAlliances(selectedPlayer, clan) ? colRadarAlly : colRadarEnemy);
			}
		}
		else
		{
			//original 8-color mode
			STATIC_ASSERT(MAX_PLAYERS <= ARRAY_SIZE(clanColours));
			playerCol = clanColours[getPlayerColour(clan)];
		}

		STATIC_ASSERT(MAX_PLAYERS <= ARRAY_SIZE(flashColours));
		flashCol = flashColours[getPlayerColour(clan)];

		/* Go through all droids */
		for (psDroid = apsDroidLists[clan]; psDroid != nullptr; psDroid = psDroid->psNext)
		{
			if (psDroid->pos.x < world_coord(scrollMinX) || psDroid->pos.y < world_coord(scrollMinY)
			    || psDroid->pos.x >= world_coord(scrollMaxX) || psDroid->pos.y >= world_coord(scrollMaxY))
			{
				continue;
			}
			if (psDroid->visible[selectedPlayer]
			    || (bMultiPlayer && alliancesSharedVision(game.alliance)
			        && aiCheckAlliances(selectedPlayer, psDroid->player)))
			{
				int	x = psDroid->pos.x / TILE_UNITS;
				int	y = psDroid->pos.y / TILE_UNITS;
				size_t	pos = (x - scrollMinX) + (y - scrollMinY) * radarTexWidth;

				ASSERT(pos * sizeof(*radarBuffer) < radarBufferSize, "Buffer overrun");
				if (clan == selectedPlayer && gameTime - psDroid->timeLastHit < HIT_NOTIFICATION)
				{
					radarBuffer[pos] = flashCol.rgba;
				}
				else
				{
					radarBuffer[pos] = playerCol.rgba;
				}
			}
		}
	}

	/* Do the same for structures */
	for (x = scrollMinX; x < scrollMaxX; x++)
	{
		for (y = scrollMinY; y < scrollMaxY; y++)
		{
			MAPTILE		*psTile = mapTile(x, y);
			STRUCTURE	*psStruct;
			size_t		pos = (x - scrollMinX) + (y - scrollMinY) * radarTexWidth;

			ASSERT(pos * sizeof(*radarBuffer) < radarBufferSize, "Buffer overrun");
			if (!TileHasStructure(psTile))
			{
				continue;
			}
			psStruct = (STRUCTURE *)psTile->psObject;
			clan = psStruct->player;

			//see if have to draw enemy/ally color
			if (bEnemyAllyRadarColor)
			{
				if (clan == selectedPlayer)
				{
					playerCol = colRadarMe;
				}
				else
				{
					playerCol = (aiCheckAlliances(selectedPlayer, clan) ? colRadarAlly : colRadarEnemy);
				}
			}
			else
			{
				//original 8-color mode
				playerCol = clanColours[getPlayerColour(clan)];
			}
			flashCol = flashColours[getPlayerColour(clan)];

			if (psStruct->visible[selectedPlayer]
			    || (bMultiPlayer && alliancesSharedVision(game.alliance)
			        && aiCheckAlliances(selectedPlayer, psStruct->player)))
			{
				if (clan == selectedPlayer && gameTime - psStruct->timeLastHit < HIT_NOTIFICATION)
				{
					radarBuffer[pos] = flashCol.rgba;
				}
				else
				{
					radarBuffer[pos] = playerCol.rgba;
				}
			}
		}
	}
}
static void UNUSED
static_asserts(void)
{
	STATIC_ASSERT(HWVULKAN_DISPATCH_MAGIC == ICD_LOADER_MAGIC);
}
Exemple #12
0
static long init_record(aSubRecord *prec, int pass)
{
    STATIC_ASSERT(sizeof(prec->onam)==sizeof(prec->snam));
    GENFUNCPTR     pfunc;
    long           status;
    int            i;

    status = 0;
    if (pass == 0) {
        /* Allocate memory for arrays */
        initFields(&prec->fta,  &prec->noa,  &prec->nea,  NULL,
            Ifldnames, &prec->a,    NULL);
        initFields(&prec->ftva, &prec->nova, &prec->neva, &prec->onva,
            Ofldnames, &prec->vala, &prec->ovla);
        return 0;
    }

    /* Initialize the Subroutine Name Link */
    switch (prec->subl.type) {
    case CONSTANT:
        recGblInitConstantLink(&prec->subl, DBF_STRING, prec->snam);
        break;

    case PV_LINK:
    case DB_LINK:
    case CA_LINK:
        break;

    default:
        recGblRecordError(S_db_badField, (void *)prec,
            "aSubRecord(init_record) Bad SUBL link type");
        return S_db_badField;
    }

    /* Initialize Input Links */
    for (i = 0; i < NUM_ARGS; i++) {
        struct link *plink = &(&prec->inpa)[i];
        switch (plink->type) {
        case CONSTANT:
            if ((&prec->noa)[i] < 2)
                recGblInitConstantLink(plink, (&prec->fta)[i], (&prec->a)[i]);
            break;

        case PV_LINK:
        case CA_LINK:
        case DB_LINK:
            break;

        default:
            recGblRecordError(S_db_badField, (void *)prec,
                "aSubRecord(init_record) Illegal INPUT LINK");
            status = S_db_badField;
            break;
        }
    }

    if (status)
        return status;

    /* Initialize Output Links */
    for (i = 0; i < NUM_ARGS; i++) {
        switch ((&prec->outa)[i].type) {
        case CONSTANT:
        case PV_LINK:
        case CA_LINK:
        case DB_LINK:
            break;

        default:
            recGblRecordError(S_db_badField, (void *)prec,
                "aSubRecord(init_record) Illegal OUTPUT LINK");
            status = S_db_badField;
        }
    }
    if (status)
        return status;

    /* Call the user initialization routine if there is one */
    if (prec->inam[0] != 0) {
        pfunc = (GENFUNCPTR)registryFunctionFind(prec->inam);
        if (pfunc) {
            pfunc(prec);
        } else {
            recGblRecordError(S_db_BadSub, (void *)prec,
                "aSubRecord::init_record - INAM subr not found");
            return S_db_BadSub;
        }
    }

    if (prec->lflg == aSubLFLG_IGNORE &&
        prec->snam[0] != 0) {
        pfunc = (GENFUNCPTR)registryFunctionFind(prec->snam);
        if (pfunc)
            prec->sadr = pfunc;
        else {
            recGblRecordError(S_db_BadSub, (void *)prec,
                "aSubRecord::init_record - SNAM subr not found");
            return S_db_BadSub;
        }
    }
    strcpy(prec->onam, prec->snam);
    prec->oval = prec->val;
    return 0;
}
Exemple #13
0
VAStatus
vlVaQuerySurfaceAttributes(VADriverContextP ctx, VAConfigID config_id,
                           VASurfaceAttrib *attrib_list, unsigned int *num_attribs)
{
   vlVaDriver *drv;
   vlVaConfig *config;
   VASurfaceAttrib *attribs;
   struct pipe_screen *pscreen;
   int i, j;

   STATIC_ASSERT(ARRAY_SIZE(vpp_surface_formats) <= VL_VA_MAX_IMAGE_FORMATS);

   if (config_id == VA_INVALID_ID)
      return VA_STATUS_ERROR_INVALID_CONFIG;

   if (!attrib_list && !num_attribs)
      return VA_STATUS_ERROR_INVALID_PARAMETER;

   if (!attrib_list) {
      *num_attribs = VL_VA_MAX_IMAGE_FORMATS + VASurfaceAttribCount;
      return VA_STATUS_SUCCESS;
   }

   if (!ctx)
      return VA_STATUS_ERROR_INVALID_CONTEXT;

   drv = VL_VA_DRIVER(ctx);

   if (!drv)
      return VA_STATUS_ERROR_INVALID_CONTEXT;

   pipe_mutex_lock(drv->mutex);
   config = handle_table_get(drv->htab, config_id);
   pipe_mutex_unlock(drv->mutex);

   if (!config)
      return VA_STATUS_ERROR_INVALID_CONFIG;

   pscreen = VL_VA_PSCREEN(ctx);

   if (!pscreen)
      return VA_STATUS_ERROR_INVALID_CONTEXT;

   attribs = CALLOC(VL_VA_MAX_IMAGE_FORMATS + VASurfaceAttribCount,
                    sizeof(VASurfaceAttrib));

   if (!attribs)
      return VA_STATUS_ERROR_ALLOCATION_FAILED;

   i = 0;

   /* vlVaCreateConfig returns PIPE_VIDEO_PROFILE_UNKNOWN
    * only for VAEntrypointVideoProc. */
   if (config->profile == PIPE_VIDEO_PROFILE_UNKNOWN) {
      for (j = 0; j < ARRAY_SIZE(vpp_surface_formats); ++j) {
         attribs[i].type = VASurfaceAttribPixelFormat;
         attribs[i].value.type = VAGenericValueTypeInteger;
         attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
         attribs[i].value.value.i = PipeFormatToVaFourcc(vpp_surface_formats[j]);
         i++;
      }
   } else {
      /* Assume VAEntrypointVLD for now. */
      attribs[i].type = VASurfaceAttribPixelFormat;
      attribs[i].value.type = VAGenericValueTypeInteger;
      attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
      attribs[i].value.value.i = VA_FOURCC_NV12;
      i++;
   }

   attribs[i].type = VASurfaceAttribMemoryType;
   attribs[i].value.type = VAGenericValueTypeInteger;
   attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE | VA_SURFACE_ATTRIB_SETTABLE;
   attribs[i].value.value.i = VA_SURFACE_ATTRIB_MEM_TYPE_VA |
         VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME;
   i++;

   attribs[i].type = VASurfaceAttribExternalBufferDescriptor;
   attribs[i].value.type = VAGenericValueTypePointer;
   attribs[i].flags = VA_SURFACE_ATTRIB_SETTABLE;
   attribs[i].value.value.p = NULL; /* ignore */
   i++;

   attribs[i].type = VASurfaceAttribMaxWidth;
   attribs[i].value.type = VAGenericValueTypeInteger;
   attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE;
   attribs[i].value.value.i = vl_video_buffer_max_size(pscreen);
   i++;

   attribs[i].type = VASurfaceAttribMaxHeight;
   attribs[i].value.type = VAGenericValueTypeInteger;
   attribs[i].flags = VA_SURFACE_ATTRIB_GETTABLE;
   attribs[i].value.value.i = vl_video_buffer_max_size(pscreen);
   i++;

   if (i > *num_attribs) {
      *num_attribs = i;
      FREE(attribs);
      return VA_STATUS_ERROR_MAX_NUM_EXCEEDED;
   }

   *num_attribs = i;
   memcpy(attrib_list, attribs, i * sizeof(VASurfaceAttrib));
   FREE(attribs);

   return VA_STATUS_SUCCESS;
}
Exemple #14
0
const char *
gl_varying_slot_name(gl_varying_slot slot)
{
   static const char *names[] = {
      ENUM(VARYING_SLOT_POS),
      ENUM(VARYING_SLOT_COL0),
      ENUM(VARYING_SLOT_COL1),
      ENUM(VARYING_SLOT_FOGC),
      ENUM(VARYING_SLOT_TEX0),
      ENUM(VARYING_SLOT_TEX1),
      ENUM(VARYING_SLOT_TEX2),
      ENUM(VARYING_SLOT_TEX3),
      ENUM(VARYING_SLOT_TEX4),
      ENUM(VARYING_SLOT_TEX5),
      ENUM(VARYING_SLOT_TEX6),
      ENUM(VARYING_SLOT_TEX7),
      ENUM(VARYING_SLOT_PSIZ),
      ENUM(VARYING_SLOT_BFC0),
      ENUM(VARYING_SLOT_BFC1),
      ENUM(VARYING_SLOT_EDGE),
      ENUM(VARYING_SLOT_CLIP_VERTEX),
      ENUM(VARYING_SLOT_CLIP_DIST0),
      ENUM(VARYING_SLOT_CLIP_DIST1),
      ENUM(VARYING_SLOT_CULL_DIST0),
      ENUM(VARYING_SLOT_CULL_DIST1),
      ENUM(VARYING_SLOT_PRIMITIVE_ID),
      ENUM(VARYING_SLOT_LAYER),
      ENUM(VARYING_SLOT_VIEWPORT),
      ENUM(VARYING_SLOT_FACE),
      ENUM(VARYING_SLOT_PNTC),
      ENUM(VARYING_SLOT_TESS_LEVEL_OUTER),
      ENUM(VARYING_SLOT_TESS_LEVEL_INNER),
      ENUM(VARYING_SLOT_BOUNDING_BOX0),
      ENUM(VARYING_SLOT_BOUNDING_BOX1),
      ENUM(VARYING_SLOT_VAR0),
      ENUM(VARYING_SLOT_VAR1),
      ENUM(VARYING_SLOT_VAR2),
      ENUM(VARYING_SLOT_VAR3),
      ENUM(VARYING_SLOT_VAR4),
      ENUM(VARYING_SLOT_VAR5),
      ENUM(VARYING_SLOT_VAR6),
      ENUM(VARYING_SLOT_VAR7),
      ENUM(VARYING_SLOT_VAR8),
      ENUM(VARYING_SLOT_VAR9),
      ENUM(VARYING_SLOT_VAR10),
      ENUM(VARYING_SLOT_VAR11),
      ENUM(VARYING_SLOT_VAR12),
      ENUM(VARYING_SLOT_VAR13),
      ENUM(VARYING_SLOT_VAR14),
      ENUM(VARYING_SLOT_VAR15),
      ENUM(VARYING_SLOT_VAR16),
      ENUM(VARYING_SLOT_VAR17),
      ENUM(VARYING_SLOT_VAR18),
      ENUM(VARYING_SLOT_VAR19),
      ENUM(VARYING_SLOT_VAR20),
      ENUM(VARYING_SLOT_VAR21),
      ENUM(VARYING_SLOT_VAR22),
      ENUM(VARYING_SLOT_VAR23),
      ENUM(VARYING_SLOT_VAR24),
      ENUM(VARYING_SLOT_VAR25),
      ENUM(VARYING_SLOT_VAR26),
      ENUM(VARYING_SLOT_VAR27),
      ENUM(VARYING_SLOT_VAR28),
      ENUM(VARYING_SLOT_VAR29),
      ENUM(VARYING_SLOT_VAR30),
      ENUM(VARYING_SLOT_VAR31),
   };
   STATIC_ASSERT(ARRAY_SIZE(names) == VARYING_SLOT_MAX);
   return NAME(slot);
}
Exemple #15
0
/*
 * \brief Initialzie page tables
 *
 * This includes setting up page tables for the init process.
 */
static void init_page_tables(void)
{
    // Create page table for init
    if(hal_cpu_is_bsp()) {
        init_l1 =  (union arm_l1_entry *)local_phys_to_mem(bsp_alloc_phys_aligned(INIT_L1_BYTES, ARM_L1_ALIGN));
        memset(init_l1, 0, INIT_L1_BYTES);

        init_l2 = (union arm_l2_entry *)local_phys_to_mem(bsp_alloc_phys_aligned(INIT_L2_BYTES, ARM_L2_ALIGN));
        memset(init_l2, 0, INIT_L2_BYTES);
    } else {
        init_l1 =  (union arm_l1_entry *)local_phys_to_mem(app_alloc_phys_aligned(INIT_L1_BYTES, ARM_L1_ALIGN));
        memset(init_l1, 0, INIT_L1_BYTES);

        init_l2 = (union arm_l2_entry *)local_phys_to_mem(app_alloc_phys_aligned(INIT_L2_BYTES, ARM_L2_ALIGN));
        memset(init_l2, 0, INIT_L2_BYTES);
    }

    printf("init_page_tables done: init_l1=%p init_l2=%p\n",
           init_l1, init_l2);

    /* Map pagetables into page CN */
    int pagecn_pagemap = 0;

    /*
     * ARM has:
     *
     * L1 has 4096 entries (16KB).
     * L2 Coarse has 256 entries (256 * 4B = 1KB).
     *
     * CPU driver currently fakes having 1024 entries in L1 and
     * L2 with 1024 entries by treating a page as 4 consecutive
     * L2 tables and mapping this as a unit in L1.
     */
    caps_create_new(ObjType_VNode_ARM_l1,
                    mem_to_local_phys((lvaddr_t)init_l1),
                    vnode_objbits(ObjType_VNode_ARM_l1), 0,
                    caps_locate_slot(CNODE(spawn_state.pagecn), pagecn_pagemap++)
                   );

    //STARTUP_PROGRESS();

    // Map L2 into successive slots in pagecn
    size_t i;
    for (i = 0; i < INIT_L2_BYTES / BASE_PAGE_SIZE; i++) {
        size_t objbits_vnode = vnode_objbits(ObjType_VNode_ARM_l2);
        assert(objbits_vnode == BASE_PAGE_BITS);
        caps_create_new(
            ObjType_VNode_ARM_l2,
            mem_to_local_phys((lvaddr_t)init_l2) + (i << objbits_vnode),
            objbits_vnode, 0,
            caps_locate_slot(CNODE(spawn_state.pagecn), pagecn_pagemap++)
        );
    }

    /*
     * Initialize init page tables - this just wires the L1
     * entries through to the corresponding L2 entries.
     */
    STATIC_ASSERT(0 == (INIT_VBASE % ARM_L1_SECTION_BYTES), "");
    for (lvaddr_t vaddr = INIT_VBASE;
            vaddr < INIT_SPACE_LIMIT;
            vaddr += ARM_L1_SECTION_BYTES) {
        uintptr_t section = (vaddr - INIT_VBASE) / ARM_L1_SECTION_BYTES;
        uintptr_t l2_off = section * ARM_L2_TABLE_BYTES;
        lpaddr_t paddr = mem_to_local_phys((lvaddr_t)init_l2) + l2_off;
        paging_map_user_pages_l1((lvaddr_t)init_l1, vaddr, paddr);
    }

    printf("Calling paging_context_switch with address = %"PRIxLVADDR"\n",
           mem_to_local_phys((lvaddr_t) init_l1));
    paging_context_switch(mem_to_local_phys((lvaddr_t)init_l1));
}
void brw_init_state( struct brw_context *brw )
{
   struct gl_context *ctx = &brw->ctx;

   /* Force the first brw_select_pipeline to emit pipeline select */
   brw->last_pipeline = BRW_NUM_PIPELINES;

   STATIC_ASSERT(ARRAY_SIZE(gen4_atoms) <= ARRAY_SIZE(brw->render_atoms));
   STATIC_ASSERT(ARRAY_SIZE(gen6_atoms) <= ARRAY_SIZE(brw->render_atoms));
   STATIC_ASSERT(ARRAY_SIZE(gen7_render_atoms) <=
                 ARRAY_SIZE(brw->render_atoms));
   STATIC_ASSERT(ARRAY_SIZE(gen8_render_atoms) <=
                 ARRAY_SIZE(brw->render_atoms));
   STATIC_ASSERT(ARRAY_SIZE(gen7_compute_atoms) <=
                 ARRAY_SIZE(brw->compute_atoms));
   STATIC_ASSERT(ARRAY_SIZE(gen8_compute_atoms) <=
                 ARRAY_SIZE(brw->compute_atoms));

   brw_init_caches(brw);

   if (brw->gen >= 8) {
      brw_copy_pipeline_atoms(brw, BRW_RENDER_PIPELINE,
                              gen8_render_atoms,
                              ARRAY_SIZE(gen8_render_atoms));
      brw_copy_pipeline_atoms(brw, BRW_COMPUTE_PIPELINE,
                              gen8_compute_atoms,
                              ARRAY_SIZE(gen8_compute_atoms));
   } else if (brw->gen == 7) {
      brw_copy_pipeline_atoms(brw, BRW_RENDER_PIPELINE,
                              gen7_render_atoms,
                              ARRAY_SIZE(gen7_render_atoms));
      brw_copy_pipeline_atoms(brw, BRW_COMPUTE_PIPELINE,
                              gen7_compute_atoms,
                              ARRAY_SIZE(gen7_compute_atoms));
   } else if (brw->gen == 6) {
      brw_copy_pipeline_atoms(brw, BRW_RENDER_PIPELINE,
                              gen6_atoms, ARRAY_SIZE(gen6_atoms));
   } else {
      brw_copy_pipeline_atoms(brw, BRW_RENDER_PIPELINE,
                              gen4_atoms, ARRAY_SIZE(gen4_atoms));
   }

   brw_upload_initial_gpu_state(brw);

   brw->NewGLState = ~0;
   brw->ctx.NewDriverState = ~0ull;

   /* ~0 is a nonsensical value which won't match anything we program, so
    * the programming will take effect on the first time around.
    */
   brw->pma_stall_bits = ~0;

   /* Make sure that brw->ctx.NewDriverState has enough bits to hold all possible
    * dirty flags.
    */
   STATIC_ASSERT(BRW_NUM_STATE_BITS <= 8 * sizeof(brw->ctx.NewDriverState));

   ctx->DriverFlags.NewTransformFeedback = BRW_NEW_TRANSFORM_FEEDBACK;
   ctx->DriverFlags.NewTransformFeedbackProg = BRW_NEW_TRANSFORM_FEEDBACK;
   ctx->DriverFlags.NewRasterizerDiscard = BRW_NEW_RASTERIZER_DISCARD;
   ctx->DriverFlags.NewUniformBuffer = BRW_NEW_UNIFORM_BUFFER;
   ctx->DriverFlags.NewTextureBuffer = BRW_NEW_TEXTURE_BUFFER;
   ctx->DriverFlags.NewAtomicBuffer = BRW_NEW_ATOMIC_BUFFER;
}
Exemple #17
0
static bool
raster_set_gen7_3DSTATE_SF(struct ilo_state_raster *rs,
                           const struct ilo_dev *dev,
                           const struct ilo_state_raster_info *info,
                           const struct ilo_state_raster_line_info *line)
{
   const struct ilo_state_raster_clip_info *clip = &info->clip;
   const struct ilo_state_raster_setup_info *setup = &info->setup;
   const struct ilo_state_raster_point_info *point = &info->point;
   const struct ilo_state_raster_tri_info *tri = &info->tri;
   const struct ilo_state_raster_params_info *params = &info->params;
   const enum gen_msrast_mode msrast =
      raster_setup_get_gen6_msrast_mode(dev, setup);
   const int line_width = get_gen6_line_width(dev, params->line_width,
         line->aa_enable, line->giq_enable);
   const int point_width = get_gen6_point_width(dev, params->point_width);
   uint32_t dw1, dw2, dw3;

   ILO_DEV_ASSERT(dev, 6, 7.5);

   if (!raster_validate_gen8_raster(dev, info))
      return false;

   dw1 = tri->fill_mode_front << GEN7_SF_DW1_FILL_MODE_FRONT__SHIFT |
         tri->fill_mode_back << GEN7_SF_DW1_FILL_MODE_BACK__SHIFT |
         tri->front_winding << GEN7_SF_DW1_FRONT_WINDING__SHIFT;

   if (ilo_dev_gen(dev) >= ILO_GEN(7) && ilo_dev_gen(dev) <= ILO_GEN(7.5)) {
      enum gen_depth_format format;

      /* do it here as we want 0x0 to be valid */
      switch (tri->depth_offset_format) {
      case GEN6_ZFORMAT_D32_FLOAT_S8X24_UINT:
         format = GEN6_ZFORMAT_D32_FLOAT;
         break;
      case GEN6_ZFORMAT_D24_UNORM_S8_UINT:
         format = GEN6_ZFORMAT_D24_UNORM_X8_UINT;
         break;
      default:
         format = tri->depth_offset_format;
         break;
      }

      dw1 |= format << GEN7_SF_DW1_DEPTH_FORMAT__SHIFT;
   }

   /*
    * From the Sandy Bridge PRM, volume 2 part 1, page 248:
    *
    *     "This bit (Statistics Enable) should be set whenever clipping is
    *      enabled and the Statistics Enable bit is set in CLIP_STATE. It
    *      should be cleared if clipping is disabled or Statistics Enable in
    *      CLIP_STATE is clear."
    */
   if (clip->stats_enable && clip->clip_enable)
      dw1 |= GEN7_SF_DW1_STATISTICS;

   /*
    * From the Ivy Bridge PRM, volume 2 part 1, page 258:
    *
    *     "This bit (Legacy Global Depth Bias Enable, Global Depth Offset
    *      Enable Solid , Global Depth Offset Enable Wireframe, and Global
    *      Depth Offset Enable Point) should be set whenever non zero depth
    *      bias (Slope, Bias) values are used. Setting this bit may have some
    *      degradation of performance for some workloads."
    *
    * But it seems fine to ignore that.
    */
   if (tri->depth_offset_solid)
      dw1 |= GEN7_SF_DW1_DEPTH_OFFSET_SOLID;
   if (tri->depth_offset_wireframe)
      dw1 |= GEN7_SF_DW1_DEPTH_OFFSET_WIREFRAME;
   if (tri->depth_offset_point)
      dw1 |= GEN7_SF_DW1_DEPTH_OFFSET_POINT;

   if (setup->viewport_transform)
      dw1 |= GEN7_SF_DW1_VIEWPORT_TRANSFORM;

   dw2 = tri->cull_mode << GEN7_SF_DW2_CULL_MODE__SHIFT |
         line_width << GEN7_SF_DW2_LINE_WIDTH__SHIFT |
         GEN7_SF_DW2_AA_LINE_CAP_1_0 |
         msrast << GEN7_SF_DW2_MSRASTMODE__SHIFT;

   if (line->aa_enable)
      dw2 |= GEN7_SF_DW2_AA_LINE_ENABLE;

   if (ilo_dev_gen(dev) == ILO_GEN(7.5) && line->stipple_enable)
      dw2 |= GEN75_SF_DW2_LINE_STIPPLE_ENABLE;

   if (setup->scissor_enable)
      dw2 |= GEN7_SF_DW2_SCISSOR_ENABLE;

   dw3 = GEN7_SF_DW3_TRUE_AA_LINE_DISTANCE |
         GEN7_SF_DW3_SUBPIXEL_8BITS;

   /* this has no effect when line_width != 0 */
   if (line->giq_last_pixel)
      dw3 |= GEN7_SF_DW3_LINE_LAST_PIXEL_ENABLE;

   if (setup->first_vertex_provoking) {
      dw3 |= 0 << GEN7_SF_DW3_TRI_PROVOKE__SHIFT |
             0 << GEN7_SF_DW3_LINE_PROVOKE__SHIFT |
             1 << GEN7_SF_DW3_TRIFAN_PROVOKE__SHIFT;
   } else {
      dw3 |= 2 << GEN7_SF_DW3_TRI_PROVOKE__SHIFT |
             1 << GEN7_SF_DW3_LINE_PROVOKE__SHIFT |
             2 << GEN7_SF_DW3_TRIFAN_PROVOKE__SHIFT;
   }

   /* setup->point_aa_enable is ignored */
   if (!point->programmable_width) {
      dw3 |= GEN7_SF_DW3_USE_POINT_WIDTH |
             point_width << GEN7_SF_DW3_POINT_WIDTH__SHIFT;
   }

   STATIC_ASSERT(ARRAY_SIZE(rs->sf) >= 3);
   rs->sf[0] = dw1;
   rs->sf[1] = dw2;
   rs->sf[2] = dw3;

   STATIC_ASSERT(ARRAY_SIZE(rs->raster) >= 4);
   rs->raster[0] = 0;
   rs->raster[1] = fui(params->depth_offset_const);
   rs->raster[2] = fui(params->depth_offset_scale);
   rs->raster[3] = fui(params->depth_offset_clamp);

   rs->line_aa_enable = line->aa_enable;
   rs->line_giq_enable = line->giq_enable;

   return true;
}
static inline void
brw_upload_pipeline_state(struct brw_context *brw,
                          enum brw_pipeline pipeline)
{
   struct gl_context *ctx = &brw->ctx;
   int i;
   static int dirty_count = 0;
   struct brw_state_flags state = brw->state.pipelines[pipeline];

   brw_select_pipeline(brw, pipeline);

   if (0) {
      /* Always re-emit all state. */
      brw->NewGLState = ~0;
      ctx->NewDriverState = ~0ull;
   }

   if (pipeline == BRW_RENDER_PIPELINE) {
      if (brw->fragment_program != ctx->FragmentProgram._Current) {
         brw->fragment_program = ctx->FragmentProgram._Current;
         brw->ctx.NewDriverState |= BRW_NEW_FRAGMENT_PROGRAM;
      }

      if (brw->geometry_program != ctx->GeometryProgram._Current) {
         brw->geometry_program = ctx->GeometryProgram._Current;
         brw->ctx.NewDriverState |= BRW_NEW_GEOMETRY_PROGRAM;
      }

      if (brw->vertex_program != ctx->VertexProgram._Current) {
         brw->vertex_program = ctx->VertexProgram._Current;
         brw->ctx.NewDriverState |= BRW_NEW_VERTEX_PROGRAM;
      }
   }

   if (brw->compute_program != ctx->ComputeProgram._Current) {
      brw->compute_program = ctx->ComputeProgram._Current;
      brw->ctx.NewDriverState |= BRW_NEW_COMPUTE_PROGRAM;
   }

   if (brw->meta_in_progress != _mesa_meta_in_progress(ctx)) {
      brw->meta_in_progress = _mesa_meta_in_progress(ctx);
      brw->ctx.NewDriverState |= BRW_NEW_META_IN_PROGRESS;
   }

   if (brw->num_samples != ctx->DrawBuffer->Visual.samples) {
      brw->num_samples = ctx->DrawBuffer->Visual.samples;
      brw->ctx.NewDriverState |= BRW_NEW_NUM_SAMPLES;
   }

   /* Exit early if no state is flagged as dirty */
   merge_ctx_state(brw, &state);
   if ((state.mesa | state.brw) == 0)
      return;

   /* Emit Sandybridge workaround flushes on every primitive, for safety. */
   if (brw->gen == 6)
      intel_emit_post_sync_nonzero_flush(brw);

   brw_upload_programs(brw, pipeline);
   merge_ctx_state(brw, &state);

   const struct brw_tracked_state *atoms =
      brw_get_pipeline_atoms(brw, pipeline);
   const int num_atoms = brw->num_atoms[pipeline];

   if (unlikely(INTEL_DEBUG)) {
      /* Debug version which enforces various sanity checks on the
       * state flags which are generated and checked to help ensure
       * state atoms are ordered correctly in the list.
       */
      struct brw_state_flags examined, prev;
      memset(&examined, 0, sizeof(examined));
      prev = state;

      for (i = 0; i < num_atoms; i++) {
	 const struct brw_tracked_state *atom = &atoms[i];
	 struct brw_state_flags generated;

         check_and_emit_atom(brw, &state, atom);

	 accumulate_state(&examined, &atom->dirty);

	 /* generated = (prev ^ state)
	  * if (examined & generated)
	  *     fail;
	  */
	 xor_states(&generated, &prev, &state);
	 assert(!check_state(&examined, &generated));
	 prev = state;
      }
   }
   else {
      for (i = 0; i < num_atoms; i++) {
	 const struct brw_tracked_state *atom = &atoms[i];

         check_and_emit_atom(brw, &state, atom);
      }
   }

   if (unlikely(INTEL_DEBUG & DEBUG_STATE)) {
      STATIC_ASSERT(ARRAY_SIZE(brw_bits) == BRW_NUM_STATE_BITS + 1);

      brw_update_dirty_count(mesa_bits, state.mesa);
      brw_update_dirty_count(brw_bits, state.brw);
      if (dirty_count++ % 1000 == 0) {
	 brw_print_dirty_count(mesa_bits);
	 brw_print_dirty_count(brw_bits);
	 fprintf(stderr, "\n");
      }
   }
}
Exemple #19
0
static bool
raster_set_gen6_3DSTATE_CLIP(struct ilo_state_raster *rs,
                             const struct ilo_dev *dev,
                             const struct ilo_state_raster_info *info)
{
   const struct ilo_state_raster_clip_info *clip = &info->clip;
   const struct ilo_state_raster_setup_info *setup = &info->setup;
   const struct ilo_state_raster_tri_info *tri = &info->tri;
   const struct ilo_state_raster_scan_info *scan = &info->scan;
   uint32_t dw1, dw2, dw3;

   ILO_DEV_ASSERT(dev, 6, 8);

   if (!raster_validate_gen6_clip(dev, info))
      return false;

   dw1 = clip->user_cull_enables << GEN6_CLIP_DW1_UCP_CULL_ENABLES__SHIFT;

   if (clip->stats_enable)
      dw1 |= GEN6_CLIP_DW1_STATISTICS;

   if (ilo_dev_gen(dev) >= ILO_GEN(7)) {
      /*
       * From the Ivy Bridge PRM, volume 2 part 1, page 219:
       *
       *     "Workaround : Due to Hardware issue "EarlyCull" needs to be
       *      enabled only for the cases where the incoming primitive topology
       *      into the clipper guaranteed to be Trilist."
       *
       * What does this mean?
       */
      dw1 |= GEN7_CLIP_DW1_SUBPIXEL_8BITS |
             GEN7_CLIP_DW1_EARLY_CULL_ENABLE;

      if (ilo_dev_gen(dev) <= ILO_GEN(7.5)) {
         dw1 |= tri->front_winding << GEN7_CLIP_DW1_FRONT_WINDING__SHIFT |
                tri->cull_mode << GEN7_CLIP_DW1_CULL_MODE__SHIFT;
      }
   }

   dw2 = clip->user_clip_enables << GEN6_CLIP_DW2_UCP_CLIP_ENABLES__SHIFT |
         GEN6_CLIPMODE_NORMAL << GEN6_CLIP_DW2_CLIP_MODE__SHIFT;

   if (clip->clip_enable)
      dw2 |= GEN6_CLIP_DW2_CLIP_ENABLE;

   if (clip->z_near_zero)
      dw2 |= GEN6_CLIP_DW2_APIMODE_D3D;
   else
      dw2 |= GEN6_CLIP_DW2_APIMODE_OGL;

   if (clip->xy_test_enable)
      dw2 |= GEN6_CLIP_DW2_XY_TEST_ENABLE;

   if (ilo_dev_gen(dev) < ILO_GEN(8) && clip->z_near_enable)
      dw2 |= GEN6_CLIP_DW2_Z_TEST_ENABLE;

   if (clip->gb_test_enable)
      dw2 |= GEN6_CLIP_DW2_GB_TEST_ENABLE;

   if (scan->barycentric_interps & (GEN6_INTERP_NONPERSPECTIVE_PIXEL |
                                    GEN6_INTERP_NONPERSPECTIVE_CENTROID |
                                    GEN6_INTERP_NONPERSPECTIVE_SAMPLE))
      dw2 |= GEN6_CLIP_DW2_NONPERSPECTIVE_BARYCENTRIC_ENABLE;

   if (setup->first_vertex_provoking) {
      dw2 |= 0 << GEN6_CLIP_DW2_TRI_PROVOKE__SHIFT |
             0 << GEN6_CLIP_DW2_LINE_PROVOKE__SHIFT |
             1 << GEN6_CLIP_DW2_TRIFAN_PROVOKE__SHIFT;
   } else {
      dw2 |= 2 << GEN6_CLIP_DW2_TRI_PROVOKE__SHIFT |
             1 << GEN6_CLIP_DW2_LINE_PROVOKE__SHIFT |
             2 << GEN6_CLIP_DW2_TRIFAN_PROVOKE__SHIFT;
   }

   dw3 = 0x1 << GEN6_CLIP_DW3_MIN_POINT_WIDTH__SHIFT |
         0x7ff << GEN6_CLIP_DW3_MAX_POINT_WIDTH__SHIFT |
         (clip->viewport_count - 1) << GEN6_CLIP_DW3_MAX_VPINDEX__SHIFT;

   if (clip->force_rtaindex_zero)
      dw3 |= GEN6_CLIP_DW3_FORCE_RTAINDEX_ZERO;

   STATIC_ASSERT(ARRAY_SIZE(rs->clip) >= 3);
   rs->clip[0] = dw1;
   rs->clip[1] = dw2;
   rs->clip[2] = dw3;

   return true;
}
Exemple #20
0
/*
 * __wt_curfile_create --
 *	Open a cursor for a given btree handle.
 */
int
__wt_curfile_create(WT_SESSION_IMPL *session,
    WT_CURSOR *owner, const char *cfg[], int bulk, int bitmap,
    WT_CURSOR **cursorp)
{
	WT_CURSOR_STATIC_INIT(iface,
	    NULL,			/* get-key */
	    NULL,			/* get-value */
	    NULL,			/* set-key */
	    NULL,			/* set-value */
	    __curfile_compare,		/* compare */
	    __curfile_next,		/* next */
	    __curfile_prev,		/* prev */
	    __curfile_reset,		/* reset */
	    __curfile_search,		/* search */
	    __curfile_search_near,	/* search-near */
	    __curfile_insert,		/* insert */
	    __curfile_update,		/* update */
	    __curfile_remove,		/* remove */
	    __curfile_close);		/* close */
	WT_BTREE *btree;
	WT_CONFIG_ITEM cval;
	WT_CURSOR *cursor;
	WT_CURSOR_BTREE *cbt;
	WT_DECL_RET;
	size_t csize;

	cbt = NULL;

	btree = session->btree;
	WT_ASSERT(session, btree != NULL);

	csize = bulk ? sizeof(WT_CURSOR_BULK) : sizeof(WT_CURSOR_BTREE);
	WT_RET(__wt_calloc(session, 1, csize, &cbt));

	cursor = &cbt->iface;
	*cursor = iface;
	cursor->session = &session->iface;
	cursor->uri = btree->name;
	cursor->key_format = btree->key_format;
	cursor->value_format = btree->value_format;

	cbt->btree = session->btree;
	if (bulk)
		WT_ERR(__wt_curbulk_init((WT_CURSOR_BULK *)cbt, bitmap));

	/*
	 * random_retrieval
	 * Random retrieval cursors only support next, reset and close.
	 */
	WT_ERR(__wt_config_gets_defno(session, cfg, "next_random", &cval));
	if (cval.val != 0) {
		__wt_cursor_set_notsup(cursor);
		cursor->next = __curfile_next_random;
		cursor->reset = __curfile_reset;
	}

	/* __wt_cursor_init is last so we don't have to clean up on error. */
	STATIC_ASSERT(offsetof(WT_CURSOR_BTREE, iface) == 0);
	WT_ERR(__wt_cursor_init(cursor, cursor->uri, owner, cfg, cursorp));

	if (0) {
err:		__wt_free(session, cbt);
	}

	return (ret);
}
Exemple #21
0
/*
 * __wt_open_session --
 *	Allocate a session handle.  The internal parameter is used for sessions
 *	opened by WiredTiger for its own use.
 */
int
__wt_open_session(WT_CONNECTION_IMPL *conn, int internal,
                  WT_EVENT_HANDLER *event_handler, const char *config,
                  WT_SESSION_IMPL **sessionp)
{
    static WT_SESSION stds = {
        NULL,
        __session_close,
        __session_open_cursor,
        __session_create,
        __session_drop,
        __session_rename,
        __session_salvage,
        __session_sync,
        __session_truncate,
        __session_upgrade,
        __session_verify,
        __session_begin_transaction,
        __session_commit_transaction,
        __session_rollback_transaction,
        __session_checkpoint,
        __session_dumpfile,
        __session_msg_printf
    };
    WT_SESSION_IMPL *session, *session_ret;
    uint32_t slot;
    int ret;

    WT_UNUSED(config);
    ret = 0;
    session = &conn->default_session;
    session_ret = NULL;

    __wt_spin_lock(session, &conn->spinlock);

    /* Check to see if there's an available session slot. */
    if (conn->session_cnt == conn->session_size - 1)
        WT_ERR_MSG(session, WT_ERROR,
                   "WiredTiger only configured to support %d thread contexts",
                   conn->session_size);

    /*
     * The session reference list is compact, the session array is not.
     * Find the first empty session slot.
     */
    for (slot = 0, session_ret = conn->session_array;
            session_ret->iface.connection != NULL;
            ++session_ret, ++slot)
        ;

    /* Session entries are re-used, clear the old contents. */
    WT_CLEAR(*session_ret);

    WT_ERR(__wt_cond_alloc(session, "session", 1, &session_ret->cond));
    session_ret->iface = stds;
    session_ret->iface.connection = &conn->iface;
    WT_ASSERT(session, session->event_handler != NULL);
    session_ret->event_handler = session->event_handler;
    session_ret->hazard = conn->hazard + slot * conn->hazard_size;

    TAILQ_INIT(&session_ret->cursors);
    TAILQ_INIT(&session_ret->btrees);
    if (event_handler != NULL)
        session_ret->event_handler = event_handler;

    /*
     * Public sessions are automatically closed during WT_CONNECTION->close.
     * If the session handles for internal threads were to go on the public
     * list, there would be complex ordering issues during close.  Set a
     * flag to avoid this: internal sessions are not closed automatically.
     */
    if (internal)
        F_SET(session_ret, WT_SESSION_INTERNAL);

    /*
     * Publish: make the entry visible to server threads.  There must be a
     * barrier to ensure the structure fields are set before any other
     * thread can see the session.
     */
    WT_PUBLISH(conn->sessions[conn->session_cnt++], session_ret);

    STATIC_ASSERT(offsetof(WT_CONNECTION_IMPL, iface) == 0);
    *sessionp = session_ret;

err:
    __wt_spin_unlock(session, &conn->spinlock);
    return (ret);
}
 BitMapView make_view(idx_t bits, bm_word_t value) {
   vmassert(BitMap::calc_size_in_words(bits) <= _words, "invalid request");
   STATIC_ASSERT(sizeof(bm_word_t) == sizeof(HeapWord));
   Copy::fill_to_aligned_words((HeapWord*)_memory, _words, value);
   return BitMapView(_memory, bits);
 }
Exemple #23
0
static bool osdDrawSingleElement(uint8_t item)
{
    if (!VISIBLE(osdConfig()->item_pos[item]) || BLINK(item)) {
        return false;
    }

    uint8_t elemPosX = OSD_X(osdConfig()->item_pos[item]);
    uint8_t elemPosY = OSD_Y(osdConfig()->item_pos[item]);
    char buff[OSD_ELEMENT_BUFFER_LENGTH] = "";

    switch (item) {
    case OSD_RSSI_VALUE:
        {
            uint16_t osdRssi = getRssi() * 100 / 1024; // change range
            if (osdRssi >= 100)
                osdRssi = 99;

            tfp_sprintf(buff, "%c%2d", SYM_RSSI, osdRssi);
            break;
        }

    case OSD_MAIN_BATT_VOLTAGE:
        buff[0] = osdGetBatterySymbol(osdGetBatteryAverageCellVoltage());
        tfp_sprintf(buff + 1, "%2d.%1d%c", getBatteryVoltage() / 10, getBatteryVoltage() % 10, SYM_VOLT);
        break;

    case OSD_CURRENT_DRAW:
        {
            const int32_t amperage = getAmperage();
            tfp_sprintf(buff, "%3d.%02d%c", abs(amperage) / 100, abs(amperage) % 100, SYM_AMP);
            break;
        }

    case OSD_MAH_DRAWN:
        tfp_sprintf(buff, "%4d%c", getMAhDrawn(), SYM_MAH);
        break;

#ifdef USE_GPS
    case OSD_GPS_SATS:
        tfp_sprintf(buff, "%c%c%2d", SYM_SAT_L, SYM_SAT_R, gpsSol.numSat);
        break;

    case OSD_GPS_SPEED:
        // FIXME ideally we want to use SYM_KMH symbol but it's not in the font any more, so we use K (M for MPH)
        switch (osdConfig()->units) {
        case OSD_UNIT_IMPERIAL:
            tfp_sprintf(buff, "%3dM", CM_S_TO_MPH(gpsSol.groundSpeed));
            break;
        default:
            tfp_sprintf(buff, "%3dK", CM_S_TO_KM_H(gpsSol.groundSpeed));
            break;
        }
        break;

    case OSD_GPS_LAT:
        // The SYM_LAT symbol in the actual font contains only blank, so we use the SYM_ARROW_NORTH
        osdFormatCoordinate(buff, SYM_ARROW_NORTH, gpsSol.llh.lat);
        break;

    case OSD_GPS_LON:
        // The SYM_LON symbol in the actual font contains only blank, so we use the SYM_ARROW_EAST
        osdFormatCoordinate(buff, SYM_ARROW_EAST, gpsSol.llh.lon);
        break;

    case OSD_HOME_DIR:
        if (STATE(GPS_FIX) && STATE(GPS_FIX_HOME)) {
            if (GPS_distanceToHome > 0) {
                const int h = GPS_directionToHome - DECIDEGREES_TO_DEGREES(attitude.values.yaw);
                buff[0] = osdGetDirectionSymbolFromHeading(h);
            } else {
                // We don't have a HOME symbol in the font, by now we use this
                buff[0] = SYM_THR1;
            }

        } else {
            // We use this symbol when we don't have a FIX
            buff[0] = SYM_COLON;
        }

        buff[1] = 0;

        break;

    case OSD_HOME_DIST:
        if (STATE(GPS_FIX) && STATE(GPS_FIX_HOME)) {
            const int32_t distance = osdGetMetersToSelectedUnit(GPS_distanceToHome);
            tfp_sprintf(buff, "%d%c", distance, osdGetMetersToSelectedUnitSymbol());
        } else {
            // We use this symbol when we don't have a FIX
            buff[0] = SYM_COLON;
            // overwrite any previous distance with blanks
            memset(buff + 1, SYM_BLANK, 6);
            buff[7] = '\0';
        }
        break;

#endif // GPS

    case OSD_COMPASS_BAR:
        memcpy(buff, compassBar + osdGetHeadingIntoDiscreteDirections(DECIDEGREES_TO_DEGREES(attitude.values.yaw), 16), 9);
        buff[9] = 0;
        break;

    case OSD_ALTITUDE:
        osdFormatAltitudeString(buff, getEstimatedAltitude());
        break;

    case OSD_ITEM_TIMER_1:
    case OSD_ITEM_TIMER_2:
        osdFormatTimer(buff, true, true, item - OSD_ITEM_TIMER_1);
        break;

    case OSD_REMAINING_TIME_ESTIMATE:
        {
            const int mAhDrawn = getMAhDrawn();
            const int remaining_time = (int)((osdConfig()->cap_alarm - mAhDrawn) * ((float)flyTime) / mAhDrawn);

            if (mAhDrawn < 0.1 * osdConfig()->cap_alarm) {
                tfp_sprintf(buff, "--:--");
            } else if (mAhDrawn > osdConfig()->cap_alarm) {
                tfp_sprintf(buff, "00:00");
            } else {
                osdFormatTime(buff, OSD_TIMER_PREC_SECOND, remaining_time);
            }
            break;
        }

    case OSD_FLYMODE:
        {
            if (FLIGHT_MODE(FAILSAFE_MODE)) {
                strcpy(buff, "!FS!");
            } else if (FLIGHT_MODE(ANGLE_MODE)) {
                strcpy(buff, "STAB");
            } else if (FLIGHT_MODE(HORIZON_MODE)) {
                strcpy(buff, "HOR ");
            } else if (FLIGHT_MODE(GPS_RESCUE_MODE)) {
                strcpy(buff, "RESC");
            } else if (isAirmodeActive()) {
                strcpy(buff, "AIR ");
            } else {
                strcpy(buff, "ACRO");
            }

            break;
        }

    case OSD_ANTI_GRAVITY:
        {
            if (pidItermAccelerator() > 1.0f) {
                strcpy(buff, "AG");
            }

            break;
        }

    case OSD_CRAFT_NAME:
        // This does not strictly support iterative updating if the craft name changes at run time. But since the craft name is not supposed to be changing this should not matter, and blanking the entire length of the craft name string on update will make it impossible to configure elements to be displayed on the right hand side of the craft name.
        //TODO: When iterative updating is implemented, change this so the craft name is only printed once whenever the OSD 'flight' screen is entered.

        if (strlen(pilotConfig()->name) == 0) {
            strcpy(buff, "CRAFT_NAME");
        } else {
            unsigned i;
            for (i = 0; i < MAX_NAME_LENGTH; i++) {
                if (pilotConfig()->name[i]) {
                    buff[i] = toupper((unsigned char)pilotConfig()->name[i]);
                } else {
                    break;
                }    
            }    
            buff[i] = '\0';
        }

        break;

    case OSD_THROTTLE_POS:
        buff[0] = SYM_THR;
        buff[1] = SYM_THR1;
        tfp_sprintf(buff + 2, "%3d", (constrain(rcData[THROTTLE], PWM_RANGE_MIN, PWM_RANGE_MAX) - PWM_RANGE_MIN) * 100 / (PWM_RANGE_MAX - PWM_RANGE_MIN));
        break;

#if defined(USE_VTX_COMMON)
    case OSD_VTX_CHANNEL:
        {
            const char vtxBandLetter = vtx58BandLetter[vtxSettingsConfig()->band];
            const char *vtxChannelName = vtx58ChannelNames[vtxSettingsConfig()->channel];
            uint8_t vtxPower = vtxSettingsConfig()->power;
            const vtxDevice_t *vtxDevice = vtxCommonDevice();
            if (vtxDevice && vtxSettingsConfig()->lowPowerDisarm) {
                vtxCommonGetPowerIndex(vtxDevice, &vtxPower);
            }
            tfp_sprintf(buff, "%c:%s:%1d", vtxBandLetter, vtxChannelName, vtxPower);
            break;
        }
#endif

    case OSD_CROSSHAIRS:
        buff[0] = SYM_AH_CENTER_LINE;
        buff[1] = SYM_AH_CENTER;
        buff[2] = SYM_AH_CENTER_LINE_RIGHT;
        buff[3] = 0;
        break;

    case OSD_ARTIFICIAL_HORIZON:
        {
            // Get pitch and roll limits in tenths of degrees
            const int maxPitch = osdConfig()->ahMaxPitch * 10;
            const int maxRoll = osdConfig()->ahMaxRoll * 10;
            const int rollAngle = constrain(attitude.values.roll, -maxRoll, maxRoll);
            int pitchAngle = constrain(attitude.values.pitch, -maxPitch, maxPitch);
            // Convert pitchAngle to y compensation value
            // (maxPitch / 25) divisor matches previous settings of fixed divisor of 8 and fixed max AHI pitch angle of 20.0 degrees
            pitchAngle = ((pitchAngle * 25) / maxPitch) - 41; // 41 = 4 * AH_SYMBOL_COUNT + 5

            for (int x = -4; x <= 4; x++) {
                const int y = ((-rollAngle * x) / 64) - pitchAngle;
                if (y >= 0 && y <= 81) {
                    displayWriteChar(osdDisplayPort, elemPosX + x, elemPosY + (y / AH_SYMBOL_COUNT), (SYM_AH_BAR9_0 + (y % AH_SYMBOL_COUNT)));
                }
            }

            return true;
        }

    case OSD_HORIZON_SIDEBARS:
        {
            // Draw AH sides
            const int8_t hudwidth = AH_SIDEBAR_WIDTH_POS;
            const int8_t hudheight = AH_SIDEBAR_HEIGHT_POS;
            for (int y = -hudheight; y <= hudheight; y++) {
                displayWriteChar(osdDisplayPort, elemPosX - hudwidth, elemPosY + y, SYM_AH_DECORATION);
                displayWriteChar(osdDisplayPort, elemPosX + hudwidth, elemPosY + y, SYM_AH_DECORATION);
            }

            // AH level indicators
            displayWriteChar(osdDisplayPort, elemPosX - hudwidth + 1, elemPosY, SYM_AH_LEFT);
            displayWriteChar(osdDisplayPort, elemPosX + hudwidth - 1, elemPosY, SYM_AH_RIGHT);

            return true;
        }

    case OSD_ROLL_PIDS:
        osdFormatPID(buff, "ROL", &currentPidProfile->pid[PID_ROLL]);
        break;

    case OSD_PITCH_PIDS:
        osdFormatPID(buff, "PIT", &currentPidProfile->pid[PID_PITCH]);
        break;

    case OSD_YAW_PIDS:
        osdFormatPID(buff, "YAW", &currentPidProfile->pid[PID_YAW]);
        break;

    case OSD_POWER:
        tfp_sprintf(buff, "%4dW", getAmperage() * getBatteryVoltage() / 1000);
        break;

    case OSD_PIDRATE_PROFILE:
        tfp_sprintf(buff, "%d-%d", getCurrentPidProfileIndex() + 1, getCurrentControlRateProfileIndex() + 1);
        break;

    case OSD_WARNINGS:
        {

#define OSD_WARNINGS_MAX_SIZE 11
#define OSD_FORMAT_MESSAGE_BUFFER_SIZE (OSD_WARNINGS_MAX_SIZE + 1)

            STATIC_ASSERT(OSD_FORMAT_MESSAGE_BUFFER_SIZE <= sizeof(buff), osd_warnings_size_exceeds_buffer_size);

            const batteryState_e batteryState = getBatteryState();

            if (osdWarnGetState(OSD_WARNING_BATTERY_CRITICAL) && batteryState == BATTERY_CRITICAL) {
                osdFormatMessage(buff, OSD_FORMAT_MESSAGE_BUFFER_SIZE, " LAND NOW");
                break;
            }

#ifdef USE_ADC_INTERNAL
            uint8_t coreTemperature = getCoreTemperatureCelsius();
            if (osdWarnGetState(OSD_WARNING_CORE_TEMPERATURE) && coreTemperature >= osdConfig()->core_temp_alarm) {
                char coreTemperatureWarningMsg[OSD_FORMAT_MESSAGE_BUFFER_SIZE];
                tfp_sprintf(coreTemperatureWarningMsg, "CORE: %3d%c", osdConvertTemperatureToSelectedUnit(getCoreTemperatureCelsius() * 10) / 10, osdGetTemperatureSymbolForSelectedUnit());

                osdFormatMessage(buff, OSD_FORMAT_MESSAGE_BUFFER_SIZE, coreTemperatureWarningMsg);

                break;
            }
#endif

#ifdef USE_ESC_SENSOR
            // Show warning if we lose motor output, the ESC is overheating or excessive current draw
            if (feature(FEATURE_ESC_SENSOR) && osdWarnGetState(OSD_WARNING_ESC_FAIL)) {
                char escWarningMsg[OSD_FORMAT_MESSAGE_BUFFER_SIZE];
                unsigned pos = 0;
                
                const char *title = "ESC";

                // center justify message
                while (pos < (OSD_WARNINGS_MAX_SIZE - (strlen(title) + getMotorCount())) / 2) {
                    escWarningMsg[pos++] = ' ';
                }

                strcpy(escWarningMsg + pos, title);
                pos += strlen(title);

                unsigned i = 0;
                unsigned escWarningCount = 0;
                while (i < getMotorCount() && pos < OSD_FORMAT_MESSAGE_BUFFER_SIZE - 1) {
                    escSensorData_t *escData = getEscSensorData(i);
                    const char motorNumber = '1' + i;
                    // if everything is OK just display motor number else R, T or C
                    char warnFlag = motorNumber;
                    if (ARMING_FLAG(ARMED) && osdConfig()->esc_rpm_alarm != ESC_RPM_ALARM_OFF && calcEscRpm(escData->rpm) <= osdConfig()->esc_rpm_alarm) {
                        warnFlag = 'R';
                    }
                    if (osdConfig()->esc_temp_alarm != ESC_TEMP_ALARM_OFF && escData->temperature >= osdConfig()->esc_temp_alarm) {
                        warnFlag = 'T';
                    }
                    if (ARMING_FLAG(ARMED) && osdConfig()->esc_current_alarm != ESC_CURRENT_ALARM_OFF && escData->current >= osdConfig()->esc_current_alarm) {
                        warnFlag = 'C';
                    }

                    escWarningMsg[pos++] = warnFlag;

                    if (warnFlag != motorNumber) {
                        escWarningCount++;
                    }

                    i++;
                }

                escWarningMsg[pos] = '\0';

                if (escWarningCount > 0) {
                    osdFormatMessage(buff, OSD_FORMAT_MESSAGE_BUFFER_SIZE, escWarningMsg);
                }
                break;
            }
#endif

            // Warn when in flip over after crash mode
            if (osdWarnGetState(OSD_WARNING_CRASH_FLIP) && isFlipOverAfterCrashMode()) {
                osdFormatMessage(buff, OSD_FORMAT_MESSAGE_BUFFER_SIZE, "CRASH FLIP");
                break;
            }

            // Show most severe reason for arming being disabled
            if (osdWarnGetState(OSD_WARNING_ARMING_DISABLE) && IS_RC_MODE_ACTIVE(BOXARM) && isArmingDisabled()) {
                const armingDisableFlags_e flags = getArmingDisableFlags();
                for (int i = 0; i < ARMING_DISABLE_FLAGS_COUNT; i++) {
                    if (flags & (1 << i)) {
                        osdFormatMessage(buff, OSD_FORMAT_MESSAGE_BUFFER_SIZE, armingDisableFlagNames[i]);
                        break;
                    }
                }
                break;
            }

            if (osdWarnGetState(OSD_WARNING_BATTERY_WARNING) && batteryState == BATTERY_WARNING) {
                osdFormatMessage(buff, OSD_FORMAT_MESSAGE_BUFFER_SIZE, "LOW BATTERY");
                break;
            }

            // Show warning if battery is not fresh
            if (osdWarnGetState(OSD_WARNING_BATTERY_NOT_FULL) && !ARMING_FLAG(WAS_EVER_ARMED) && (getBatteryState() == BATTERY_OK)
                  && getBatteryAverageCellVoltage() < batteryConfig()->vbatfullcellvoltage) {
                osdFormatMessage(buff, OSD_FORMAT_MESSAGE_BUFFER_SIZE, "BATT < FULL");
                break;
            }

            // Visual beeper
            if (osdWarnGetState(OSD_WARNING_VISUAL_BEEPER) && showVisualBeeper) {
                osdFormatMessage(buff, OSD_FORMAT_MESSAGE_BUFFER_SIZE, "  * * * *");
                break;
            }

            osdFormatMessage(buff, OSD_FORMAT_MESSAGE_BUFFER_SIZE, NULL);
            break;
        }

    case OSD_AVG_CELL_VOLTAGE:
        {
            const int cellV = osdGetBatteryAverageCellVoltage();
            buff[0] = osdGetBatterySymbol(cellV);
            tfp_sprintf(buff + 1, "%d.%02d%c", cellV / 100, cellV % 100, SYM_VOLT);
            break;
        }

    case OSD_DEBUG:
        tfp_sprintf(buff, "DBG %5d %5d %5d %5d", debug[0], debug[1], debug[2], debug[3]);
        break;

    case OSD_PITCH_ANGLE:
    case OSD_ROLL_ANGLE:
        {
            const int angle = (item == OSD_PITCH_ANGLE) ? attitude.values.pitch : attitude.values.roll;
            tfp_sprintf(buff, "%c%02d.%01d", angle < 0 ? '-' : ' ', abs(angle / 10), abs(angle % 10));
            break;
        }

    case OSD_MAIN_BATT_USAGE:
        {
            // Set length of indicator bar
            #define MAIN_BATT_USAGE_STEPS 11 // Use an odd number so the bar can be centered.

            // Calculate constrained value
            const float value = constrain(batteryConfig()->batteryCapacity - getMAhDrawn(), 0, batteryConfig()->batteryCapacity);

            // Calculate mAh used progress
            const uint8_t mAhUsedProgress = ceilf((value / (batteryConfig()->batteryCapacity / MAIN_BATT_USAGE_STEPS)));

            // Create empty battery indicator bar
            buff[0] = SYM_PB_START;
            for (int i = 1; i <= MAIN_BATT_USAGE_STEPS; i++) {
                buff[i] = i <= mAhUsedProgress ? SYM_PB_FULL : SYM_PB_EMPTY;
            }
            buff[MAIN_BATT_USAGE_STEPS + 1] = SYM_PB_CLOSE;
            if (mAhUsedProgress > 0 && mAhUsedProgress < MAIN_BATT_USAGE_STEPS) {
                buff[1 + mAhUsedProgress] = SYM_PB_END;
            }
            buff[MAIN_BATT_USAGE_STEPS+2] = '\0';
            break;
        }

    case OSD_DISARMED:
        if (!ARMING_FLAG(ARMED)) {
            tfp_sprintf(buff, "DISARMED");
        } else {
            if (!lastArmState) {  // previously disarmed - blank out the message one time
                tfp_sprintf(buff, "        ");
            }
        }
        break;

    case OSD_NUMERICAL_HEADING:
        {
            const int heading = DECIDEGREES_TO_DEGREES(attitude.values.yaw);
            tfp_sprintf(buff, "%c%03d", osdGetDirectionSymbolFromHeading(heading), heading);
            break;
        }

    case OSD_NUMERICAL_VARIO:
        {
            const int verticalSpeed = osdGetMetersToSelectedUnit(getEstimatedVario());
            const char directionSymbol = verticalSpeed < 0 ? SYM_ARROW_SOUTH : SYM_ARROW_NORTH;
            tfp_sprintf(buff, "%c%01d.%01d", directionSymbol, abs(verticalSpeed / 100), abs((verticalSpeed % 100) / 10));
            break;
        }

#ifdef USE_ESC_SENSOR
    case OSD_ESC_TMP:
        if (feature(FEATURE_ESC_SENSOR)) {
            tfp_sprintf(buff, "%3d%c", osdConvertTemperatureToSelectedUnit(escDataCombined->temperature * 10) / 10, osdGetTemperatureSymbolForSelectedUnit());
        }
        break;

    case OSD_ESC_RPM:
        if (feature(FEATURE_ESC_SENSOR)) {
            tfp_sprintf(buff, "%5d", escDataCombined == NULL ? 0 : calcEscRpm(escDataCombined->rpm));
        }
        break;
#endif

#ifdef USE_RTC_TIME
    case OSD_RTC_DATETIME:
        osdFormatRtcDateTime(&buff[0]);
        break;
#endif

#ifdef USE_OSD_ADJUSTMENTS
    case OSD_ADJUSTMENT_RANGE:
        tfp_sprintf(buff, "%s: %3d", adjustmentRangeName, adjustmentRangeValue);
        break;
#endif

#ifdef USE_ADC_INTERNAL
    case OSD_CORE_TEMPERATURE:
        tfp_sprintf(buff, "%3d%c", osdConvertTemperatureToSelectedUnit(getCoreTemperatureCelsius() * 10) / 10, osdGetTemperatureSymbolForSelectedUnit());
        break;
#endif

    default:
        return false;
    }

    displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);

    return true;
}
static bool
thex_download_handle_hashtree(struct thex_download *ctx,
	const char *data, size_t size)
{
	bool success = FALSE;
	size_t n_nodes, n_leaves, n, start;
	unsigned good_depth;
	const struct tth *leaves;
	struct tth tth;

	if (size <= 0) {
		if (GNET_PROPERTY(tigertree_debug)) {
			g_debug("TTH hashtree record has no data");
		}
		goto finish;
	}
	if (size < TTH_RAW_SIZE) {
		if (GNET_PROPERTY(tigertree_debug)) {
			g_debug("TTH hashtree record is too small");
		}
		goto finish;
	}
	if (size % TTH_RAW_SIZE) {
		if (GNET_PROPERTY(tigertree_debug)) {
			g_debug("TTH hashtree has bad size");
		}
		goto finish;
	}
	memcpy(tth.data, data, TTH_RAW_SIZE);
	if (!tth_eq(&tth, ctx->tth)) {
		if (GNET_PROPERTY(tigertree_debug)) {
			g_debug("TTH hashtree has different root hash %s",
				tth_base32(&tth));
		}
		goto finish;
	}

	n_nodes = size / TTH_RAW_SIZE;
	n_leaves = tt_node_count_at_depth(ctx->filesize, ctx->depth);

	/* Shareaza uses a fixed depth of 9, allow one level less like others */
	good_depth = tt_good_depth(ctx->filesize);

	ctx->depth = MIN(ctx->depth, good_depth);
	if (n_nodes < n_leaves * 2 - 1) {
		ctx->depth = good_depth;
		n = tt_node_count_at_depth(ctx->filesize, ctx->depth);
		n = n * 2 - 1; /* All nodes, not just leaves */
		while (n > n_nodes) {
			n = (n + 1) / 2;
			ctx->depth--;
		}
		if (GNET_PROPERTY(tigertree_debug)) {
			g_debug("TTH calculated depth of hashtree: %u", ctx->depth);
		}
		n_leaves = tt_node_count_at_depth(ctx->filesize, ctx->depth);
	}

	if (ctx->depth < good_depth) {
		if (GNET_PROPERTY(tigertree_debug)) {
			g_debug("TTH tree depth (%u) is below the good depth (%u)",
				ctx->depth, good_depth);
		}
	}

	start = 0;
	n = n_leaves;
	while (n > 1) {
		n = (n + 1) / 2;
		start += n;
	}

	if (n_nodes < start + n_leaves) {
		if (GNET_PROPERTY(tigertree_debug)) {
			g_debug("TTH hashtree has too few nodes "
				"(filesize=%s depth=%u nodes=%zu expected=%zu)",
				filesize_to_string(ctx->filesize),
				ctx->depth, n_nodes, n_leaves * 2 - 1);
		}
		goto finish;
	}

	STATIC_ASSERT(TTH_RAW_SIZE == sizeof(struct tth));
	leaves = (const struct tth *) &data[start * TTH_RAW_SIZE];

	tth = tt_root_hash(leaves, n_leaves);
	if (!tth_eq(&tth, ctx->tth)) {
		if (GNET_PROPERTY(tigertree_debug)) {
			g_debug("TTH hashtree does not match root hash %s",
				tth_base32(&tth));
		}
		goto finish;
	}

	ctx->leaves = g_memdup(leaves, TTH_RAW_SIZE * n_leaves);
	ctx->num_leaves = n_leaves;
	success = TRUE;

finish:
	return success;
}
Exemple #25
0
/**
 * Creates a region containing the push constants for the CS on gen7+.
 *
 * Push constants are constant values (such as GLSL uniforms) that are
 * pre-loaded into a shader stage's register space at thread spawn time.
 *
 * For other stages, see brw_curbe.c:brw_upload_constant_buffer for the
 * equivalent gen4/5 code and gen6_vs_state.c:gen6_upload_push_constants for
 * gen6+.
 */
static void
brw_upload_cs_push_constants(struct brw_context *brw,
                             const struct gl_program *prog,
                             const struct brw_cs_prog_data *cs_prog_data,
                             struct brw_stage_state *stage_state,
                             enum aub_state_struct_type type)
{
   struct gl_context *ctx = &brw->ctx;
   const struct brw_stage_prog_data *prog_data =
      (struct brw_stage_prog_data*) cs_prog_data;

   /* Updates the ParamaterValues[i] pointers for all parameters of the
    * basic type of PROGRAM_STATE_VAR.
    */
   /* XXX: Should this happen somewhere before to get our state flag set? */
   _mesa_load_state_parameters(ctx, prog->Parameters);

   if (cs_prog_data->push.total.size == 0) {
      stage_state->push_const_size = 0;
      return;
   }


   gl_constant_value *param = (gl_constant_value*)
      brw_state_batch(brw, type, ALIGN(cs_prog_data->push.total.size, 64),
                      64, &stage_state->push_const_offset);
   assert(param);

   STATIC_ASSERT(sizeof(gl_constant_value) == sizeof(float));

   if (cs_prog_data->push.cross_thread.size > 0) {
      gl_constant_value *param_copy = param;
      assert(cs_prog_data->thread_local_id_index < 0 ||
             cs_prog_data->thread_local_id_index >=
                cs_prog_data->push.cross_thread.dwords);
      for (unsigned i = 0;
           i < cs_prog_data->push.cross_thread.dwords;
           i++) {
         param_copy[i] = *prog_data->param[i];
      }
   }

   gl_constant_value thread_id;
   if (cs_prog_data->push.per_thread.size > 0) {
      for (unsigned t = 0; t < cs_prog_data->threads; t++) {
         unsigned dst =
            8 * (cs_prog_data->push.per_thread.regs * t +
                 cs_prog_data->push.cross_thread.regs);
         unsigned src = cs_prog_data->push.cross_thread.dwords;
         for ( ; src < prog_data->nr_params; src++, dst++) {
            if (src != cs_prog_data->thread_local_id_index)
               param[dst] = *prog_data->param[src];
            else {
               thread_id.u = t * cs_prog_data->simd_size;
               param[dst] = thread_id;
            }
         }
      }
   }

   stage_state->push_const_size =
      cs_prog_data->push.cross_thread.regs +
      cs_prog_data->push.per_thread.regs;
}
/** Searches in the given search directory for files ending with the
 *  given extension. Then will create a window with buttons for each
 *  found file.
 *  \param searchDir the directory to search in
 *  \param fileExtension the extension files should end with, if the
 *         extension has a dot (.) then this dot _must_ be present as
 *         the first char in this parameter
 *  \param mode (purpose unknown)
 *  \param numPlayers (purpose unknown)
 */
void addMultiRequest(const char* searchDir, const char* fileExtension, UDWORD mode, UBYTE mapCam, UBYTE numPlayers)
{
	char**             fileList;
	char**             currFile;
	const unsigned int extensionLength = strlen(fileExtension);
	const unsigned int buttonsX = (mode == MULTIOP_MAP) ? 22 : 17;

	unsigned int       numButtons, count, butPerForm, i;

	static char		tips[NBTIPS][MAX_STR_LENGTH];


	context = mode;
	if(mode == MULTIOP_MAP)
	{	// only save these when they select MAP button
		current_tech = mapCam;
		current_numplayers = numPlayers;
	}
	fileList = PHYSFS_enumerateFiles(searchDir);
	if (!fileList)
	{
		debug(LOG_FATAL, "addMultiRequest: Out of memory");
		abort();
		return;
	}

	// Count number of required buttons
	numButtons = 0;
	for (currFile = fileList; *currFile != NULL; ++currFile)
	{
		const unsigned int fileNameLength = strlen(*currFile);

		// Check to see if this file matches the given extension
		if (fileNameLength > extensionLength
		 && strcmp(&(*currFile)[fileNameLength - extensionLength], fileExtension) == 0)
			++numButtons;
	}

	if(mode == MULTIOP_MAP)									// if its a map, also look in the predone stuff.
	{
		bool first = true;
		while (enumerateMultiMaps(first, mapCam, numPlayers) != NULL)
		{
			first = false;
			numButtons++;
		}
	}

	psRScreen = widgCreateScreen(); ///< move this to intinit or somewhere like that.. (close too.)
	widgSetTipFont(psRScreen,font_regular);

	/* Calculate how many buttons will go on a single form */
	butPerForm = ((M_REQUEST_W - 0 - 4) /
						(R_BUT_W +4)) *
				 ((M_REQUEST_H - 0- 4) /
						(R_BUT_H+ 4));

	/* add a form to place the tabbed form on */
	W_FORMINIT sFormInit;
	sFormInit.formID = 0;
	sFormInit.id = M_REQUEST;
	sFormInit.style = WFORM_PLAIN;
	sFormInit.x = (SWORD)(M_REQUEST_X+D_W);
	sFormInit.y = (SWORD)(M_REQUEST_Y+D_H);
	sFormInit.width = M_REQUEST_W;
	sFormInit.height = M_REQUEST_H;
	sFormInit.disableChildren = true;
	sFormInit.pDisplay = intOpenPlainForm;
	widgAddForm(psRScreen, &sFormInit);

	/* Add the tabs */
	sFormInit = W_FORMINIT();
	sFormInit.formID = M_REQUEST;
	sFormInit.id = M_REQUEST_TAB;
	sFormInit.style = WFORM_TABBED;
	sFormInit.x = 2;
	sFormInit.y = 2;
	sFormInit.width = M_REQUEST_W;
	sFormInit.height = M_REQUEST_H-4;

	sFormInit.numMajor = numForms(numButtons, butPerForm);

	sFormInit.majorPos = WFORM_TABTOP;
	sFormInit.minorPos = WFORM_TABNONE;
	sFormInit.majorSize = OBJ_TABWIDTH+2;
	sFormInit.majorOffset = OBJ_TABOFFSET;
	sFormInit.tabVertOffset = (OBJ_TABHEIGHT/2);
	sFormInit.tabMajorThickness = OBJ_TABHEIGHT;
	sFormInit.pUserData = &StandardTab;
	sFormInit.pTabDisplay = intDisplayTab;

	// TABFIXME: 
	// This appears to be the map pick screen, when we have lots of maps
	// this will need to change.
	if (sFormInit.numMajor > MAX_TAB_STD_SHOWN)
	{
		ASSERT(sFormInit.numMajor < MAX_TAB_SMALL_SHOWN,"Too many maps! Need scroll tabs here.");
		sFormInit.pUserData = &SmallTab;
		sFormInit.majorSize /= 2;
	}

	for (i = 0; i < sFormInit.numMajor; ++i)
	{
		sFormInit.aNumMinors[i] = 2;
	}
	widgAddForm(psRScreen, &sFormInit);

	// Add the close button.
	W_BUTINIT sButInit;
	sButInit.formID = M_REQUEST;
	sButInit.id = M_REQUEST_CLOSE;
	sButInit.x = M_REQUEST_W - CLOSE_WIDTH - 3;
	sButInit.y = 0;
	sButInit.width = CLOSE_WIDTH;
	sButInit.height = CLOSE_HEIGHT;
	sButInit.pTip = _("Close");
	sButInit.pDisplay = intDisplayImageHilight;
	sButInit.UserData = PACKDWORD_TRI(0,IMAGE_CLOSEHILIGHT , IMAGE_CLOSE);
	widgAddButton(psRScreen, &sButInit);

	/* Put the buttons on it *//* Set up the button struct */
	sButInit = W_BUTINIT();
	sButInit.formID		= M_REQUEST_TAB;
	sButInit.id		= M_REQUEST_BUT;
	sButInit.x		= buttonsX;
	sButInit.y		= 4;
	sButInit.width		= R_BUT_W;
	sButInit.height		= R_BUT_H;
	sButInit.pUserData	= NULL;
	sButInit.pDisplay	= displayRequestOption;

	for (currFile = fileList, count = 0; *currFile != NULL && count < (butPerForm * 4); ++currFile)
	{
		const unsigned int tip_index = check_tip_index(sButInit.id - M_REQUEST_BUT);
		const unsigned int fileNameLength = strlen(*currFile);
		const unsigned int tipStringLength = fileNameLength - extensionLength;

		// Check to see if this file matches the given extension
		if (!(fileNameLength > extensionLength)
		 || strcmp(&(*currFile)[fileNameLength - extensionLength], fileExtension) != 0)
			continue;

		// Set the tip and add the button

		// Copy all of the filename except for the extension into the tiptext string
		strlcpy(tips[tip_index], *currFile, MIN(tipStringLength + 1, sizeof(tips[tip_index])));

		sButInit.pTip		= tips[tip_index];
		sButInit.pText		= tips[tip_index];

		if(mode == MULTIOP_MAP)											// if its a map, set player flag.
		{
			ASSERT(false, "Confusing code, can we even get here?");

			const char* mapText;
			unsigned int mapTextLength;

			sButInit.UserData = (*currFile)[0] - '0';

			if( (*currFile)[1] != 'c')
			{
				continue;
			}

			// Chop off description
			mapText = strrchr(*currFile, '-') + 1;
			if (mapText - 1 == NULL)
				continue;

			mapTextLength = tipStringLength - (mapText - *currFile);
			strlcpy(tips[tip_index], mapText, MIN(mapTextLength + 1, sizeof(tips[tip_index])));
		}

		++count;
		widgAddButton(psRScreen, &sButInit);

		/* Update the init struct for the next button */
		sButInit.id += 1;
		sButInit.x = (SWORD)(sButInit.x + (R_BUT_W+ 4));
		if (sButInit.x + R_BUT_W+ 2 > M_REQUEST_W)
		{
			sButInit.x = buttonsX;
			sButInit.y = (SWORD)(sButInit.y +R_BUT_H + 4);
		}
		if (sButInit.y +R_BUT_H + 4 > M_REQUEST_H)
		{
			sButInit.y = 4;
			sButInit.majorID += 1;
		}
	}

	// Make sure to return memory back to PhyscisFS
	PHYSFS_freeList(fileList);

	if(mode == MULTIOP_MAP)
	{
		LEVEL_DATASET *mapData;
		bool first = true;
		while ((mapData = enumerateMultiMaps(first, mapCam, numPlayers)) != NULL)
		{
			first = false;

			unsigned int tip_index = check_tip_index(sButInit.id-M_REQUEST_BUT);

			// add number of players to string.
			sstrcpy(tips[tip_index], mapData->pName);

			sButInit.pTip = tips[tip_index];
			sButInit.pText = tips[tip_index];
			sButInit.pUserData = mapData;

			widgAddButton(psRScreen, &sButInit);

			sButInit.id += 1;
			sButInit.x = (SWORD)(sButInit.x + (R_BUT_W+ 4));
			if (sButInit.x + R_BUT_W+ 2 > M_REQUEST_W)
			{
				sButInit.x = buttonsX;
				sButInit.y = (SWORD)(sButInit.y +R_BUT_H + 4);
			}
			if (sButInit.y +R_BUT_H + 4 > M_REQUEST_H)
			{
				sButInit.y = 4;
				sButInit.majorID += 1;
			}
		}
	}
	multiRequestUp = true;
	hoverPreviewId = 0;


	// if it's map select then add the cam style buttons.
	if(mode == MULTIOP_MAP)
	{
		sButInit = W_BUTINIT();
		sButInit.formID		= M_REQUEST_TAB;
		sButInit.id		= M_REQUEST_C1;
		sButInit.x		= 1;
		sButInit.y		= 252;
		sButInit.width		= 17;
		sButInit.height		= 17;
		sButInit.UserData	= 1;
		sButInit.pTip		= _("Technology level 1");
		sButInit.pDisplay	= displayCamTypeBut;

		widgAddButton(psRScreen, &sButInit);

		sButInit.id		= M_REQUEST_C2;
		sButInit.y		+= 22;
		sButInit.UserData	= 2;
		sButInit.pTip		= _("Technology level 2");
		widgAddButton(psRScreen, &sButInit);

		sButInit.id		= M_REQUEST_C3;
		sButInit.y		+= 22;
		sButInit.UserData	= 3;
		sButInit.pTip		= _("Technology level 3");
		widgAddButton(psRScreen, &sButInit);

		sButInit.id		= M_REQUEST_AP;
		sButInit.y		= 17;
		sButInit.UserData	= 0;
		sButInit.pTip		= _("Any number of players");
		sButInit.pDisplay	= displayNumPlayersBut;
		widgAddButton(psRScreen, &sButInit);

		STATIC_ASSERT(MAX_PLAYERS_IN_GUI <= ARRAY_SIZE(M_REQUEST_NP) + 1);
		for (unsigned numPlayers = 2; numPlayers <= MAX_PLAYERS_IN_GUI; ++numPlayers)
		{
			static char ttip[MAX_PLAYERS_IN_GUI][20];
			sButInit.id             = M_REQUEST_NP[numPlayers - 2];
			sButInit.y		+= 22;
			sButInit.UserData	= numPlayers;
			ssprintf(ttip[numPlayers], ngettext("%d player", "%d players", numPlayers), numPlayers);
			sButInit.pTip		= (const char *)&ttip[numPlayers];
			widgAddButton(psRScreen, &sButInit);
		}
	}

}
Exemple #27
0
 concurrent_atomic_array() : m_index(UNASSIGNED) {
     STATIC_ASSERT((N & (N-1)) == 0, N_must_be_power_of_2);
 }
Exemple #28
0
/***********************************************************************
 * Emit all state:
 */
void brw_upload_state(struct brw_context *brw)
{
   struct gl_context *ctx = &brw->ctx;
   struct brw_state_flags *state = &brw->state.dirty;
   int i;
   static int dirty_count = 0;

   state->mesa |= brw->NewGLState;
   brw->NewGLState = 0;

   state->brw |= ctx->NewDriverState;
   ctx->NewDriverState = 0;

   if (0) {
      /* Always re-emit all state. */
      state->mesa |= ~0;
      state->brw |= ~0;
      state->cache |= ~0;
   }

   if (brw->fragment_program != ctx->FragmentProgram._Current) {
      brw->fragment_program = ctx->FragmentProgram._Current;
      brw->state.dirty.brw |= BRW_NEW_FRAGMENT_PROGRAM;
   }

   if (brw->geometry_program != ctx->GeometryProgram._Current) {
      brw->geometry_program = ctx->GeometryProgram._Current;
      brw->state.dirty.brw |= BRW_NEW_GEOMETRY_PROGRAM;
   }

   if (brw->vertex_program != ctx->VertexProgram._Current) {
      brw->vertex_program = ctx->VertexProgram._Current;
      brw->state.dirty.brw |= BRW_NEW_VERTEX_PROGRAM;
   }

   if (brw->meta_in_progress != _mesa_meta_in_progress(ctx)) {
      brw->meta_in_progress = _mesa_meta_in_progress(ctx);
      brw->state.dirty.brw |= BRW_NEW_META_IN_PROGRESS;
   }

   if ((state->mesa | state->cache | state->brw) == 0)
      return;

   intel_check_front_buffer_rendering(brw);

   if (unlikely(INTEL_DEBUG)) {
      /* Debug version which enforces various sanity checks on the
       * state flags which are generated and checked to help ensure
       * state atoms are ordered correctly in the list.
       */
      struct brw_state_flags examined, prev;      
      memset(&examined, 0, sizeof(examined));
      prev = *state;

      for (i = 0; i < brw->num_atoms; i++) {
	 const struct brw_tracked_state *atom = brw->atoms[i];
	 struct brw_state_flags generated;

	 if (check_state(state, &atom->dirty)) {
	    atom->emit(brw);
	 }

	 accumulate_state(&examined, &atom->dirty);

	 /* generated = (prev ^ state)
	  * if (examined & generated)
	  *     fail;
	  */
	 xor_states(&generated, &prev, state);
	 assert(!check_state(&examined, &generated));
	 prev = *state;
      }
   }
   else {
      for (i = 0; i < brw->num_atoms; i++) {
	 const struct brw_tracked_state *atom = brw->atoms[i];

	 if (check_state(state, &atom->dirty)) {
	    atom->emit(brw);
	 }
      }
   }

   if (unlikely(INTEL_DEBUG & DEBUG_STATE)) {
      STATIC_ASSERT(ARRAY_SIZE(brw_bits) == BRW_NUM_STATE_BITS + 1);
      STATIC_ASSERT(ARRAY_SIZE(cache_bits) == BRW_MAX_CACHE + 1);

      brw_update_dirty_count(mesa_bits, state->mesa);
      brw_update_dirty_count(brw_bits, state->brw);
      brw_update_dirty_count(cache_bits, state->cache);
      if (dirty_count++ % 1000 == 0) {
	 brw_print_dirty_count(mesa_bits);
	 brw_print_dirty_count(brw_bits);
	 brw_print_dirty_count(cache_bits);
	 fprintf(stderr, "\n");
      }
   }

   memset(state, 0, sizeof(*state));
}
/**
 * Return ARB_v/f_prog-style output attrib string.
 */
static const char *
arb_output_attrib_string(GLint index, GLenum progType)
{
   /*
    * These strings should match the VARYING_SLOT_x and FRAG_RESULT_x tokens.
    */
   static const char *const vertResults[] = {
      "result.position",
      "result.color.primary",
      "result.color.secondary",
      "result.fogcoord",
      "result.texcoord[0]",
      "result.texcoord[1]",
      "result.texcoord[2]",
      "result.texcoord[3]",
      "result.texcoord[4]",
      "result.texcoord[5]",
      "result.texcoord[6]",
      "result.texcoord[7]",
      "result.pointsize", /* VARYING_SLOT_PSIZ */
      "result.(thirteen)", /* VARYING_SLOT_BFC0 */
      "result.(fourteen)", /* VARYING_SLOT_BFC1 */
      "result.(fifteen)", /* VARYING_SLOT_EDGE */
      "result.(sixteen)", /* VARYING_SLOT_CLIP_VERTEX */
      "result.(seventeen)", /* VARYING_SLOT_CLIP_DIST0 */
      "result.(eighteen)", /* VARYING_SLOT_CLIP_DIST1 */
      "result.(nineteen)", /* VARYING_SLOT_PRIMITIVE_ID */
      "result.(twenty)", /* VARYING_SLOT_LAYER */
      "result.(twenty-one)", /* VARYING_SLOT_FACE */
      "result.(twenty-two)", /* VARYING_SLOT_PNTC */
      "result.varying[0]",
      "result.varying[1]",
      "result.varying[2]",
      "result.varying[3]",
      "result.varying[4]",
      "result.varying[5]",
      "result.varying[6]",
      "result.varying[7]",
      "result.varying[8]",
      "result.varying[9]",
      "result.varying[10]",
      "result.varying[11]",
      "result.varying[12]",
      "result.varying[13]",
      "result.varying[14]",
      "result.varying[15]",
      "result.varying[16]",
      "result.varying[17]",
      "result.varying[18]",
      "result.varying[19]",
      "result.varying[20]",
      "result.varying[21]",
      "result.varying[22]",
      "result.varying[23]",
      "result.varying[24]",
      "result.varying[25]",
      "result.varying[26]",
      "result.varying[27]",
      "result.varying[28]",
      "result.varying[29]",
      "result.varying[30]",
      "result.varying[31]", /* MAX_VARYING = 32 */
   };
   static const char *const fragResults[] = {
      "result.depth", /* FRAG_RESULT_DEPTH */
      "result.(one)", /* FRAG_RESULT_STENCIL */
      "result.color", /* FRAG_RESULT_COLOR */
      "result.samplemask", /* FRAG_RESULT_SAMPLE_MASK */
      "result.color[0]", /* FRAG_RESULT_DATA0 (named for GLSL's gl_FragData) */
      "result.color[1]",
      "result.color[2]",
      "result.color[3]",
      "result.color[4]",
      "result.color[5]",
      "result.color[6]",
      "result.color[7]" /* MAX_DRAW_BUFFERS = 8 */
   };

   /* sanity checks */
   STATIC_ASSERT(Elements(vertResults) == VARYING_SLOT_MAX);
   STATIC_ASSERT(Elements(fragResults) == FRAG_RESULT_MAX);
   assert(strcmp(vertResults[VARYING_SLOT_POS], "result.position") == 0);
   assert(strcmp(vertResults[VARYING_SLOT_VAR0], "result.varying[0]") == 0);
   assert(strcmp(fragResults[FRAG_RESULT_DATA0], "result.color[0]") == 0);

   if (progType == GL_VERTEX_PROGRAM_ARB) {
      assert(index < Elements(vertResults));
      return vertResults[index];
   }
   else {
      assert(progType == GL_FRAGMENT_PROGRAM_ARB);
      assert(index < Elements(fragResults));
      return fragResults[index];
   }
}
Exemple #30
0
/**
 * Create a security token from host address and port using specified key.
 *
 * Optionally, extra contextual data may be given (i.e. the token is not
 * only based on the address and port) to make the token more unique to
 * a specific context.
 *
 * @param stg		the security token generator
 * @param n			key index to use
 * @param tok		where security token is written
 * @param addr		address of the host for which we're generating a token
 * @param port		port of the host for which we're generating a token
 * @param data		optional contextual data
 * @param len		length of contextual data
 */
static void
sectoken_generate_n(sectoken_gen_t *stg, size_t n,
	sectoken_t *tok, host_addr_t addr, uint16 port,
	const void *data, size_t len)
{
	char block[8];
	char enc[8];
	char *p = block;

	sectoken_gen_check(stg);
	g_assert(tok != NULL);
	g_assert(size_is_non_negative(n));
	g_assert(n < stg->keycnt);
	g_assert((NULL != data) == (len != 0));

	switch (host_addr_net(addr)) {
	case NET_TYPE_IPV4:
		p = poke_be32(p, host_addr_ipv4(addr));
		break;
	case NET_TYPE_IPV6:
		{
			uint val;

			val = binary_hash(host_addr_ipv6(&addr), 16);
			p = poke_be32(p, val);
		}
		break;
	case NET_TYPE_LOCAL:
	case NET_TYPE_NONE:
		g_error("unexpected address for security token generation: %s",
			host_addr_to_string(addr));
	}

	p = poke_be16(p, port);
	p = poke_be16(p, 0);		/* Filler */

	g_assert(p == &block[8]);

	STATIC_ASSERT(sizeof(tok->v) == sizeof(uint32));
	STATIC_ASSERT(sizeof(block) == sizeof(enc));

	tea_encrypt(&stg->keys[n], enc, block, sizeof block);

	/*
	 * If they gave contextual data, encrypt them by block of TEA_BLOCK_SIZE
	 * bytes, filling the last partial block with zeroes if needed.
	 */

	if (data != NULL) {
		const void *q = data;
		size_t remain = len;
		char denc[8];

		STATIC_ASSERT(sizeof(denc) == sizeof(enc));

		while (remain != 0) {
			size_t fill = MIN(remain, TEA_BLOCK_SIZE);
			unsigned i;

			if (fill != TEA_BLOCK_SIZE)
				ZERO(&block);

			memcpy(block, q, fill);
			remain -= fill;
			q = const_ptr_add_offset(q, fill);

			/*
			 * Encrypt block of contextual data (possibly filled with trailing
			 * zeroes) and merge back the result into the main encryption
			 * output with XOR.
			 */

			tea_encrypt(&stg->keys[n], denc, block, sizeof block);

			for (i = 0; i < sizeof denc; i++)
				enc[i] ^= denc[i];
		}
	}

	poke_be32(tok->v, tea_squeeze(enc, sizeof enc));
}