Example #1
0
extern "C" size_t __cdecl _fwrite_nolock(
    void const* const buffer,
    size_t      const element_size,
    size_t      const element_count,
    FILE*       const public_stream
    )
{
    if (element_size == 0 || element_count == 0)
    {
        return 0;
    }

    __crt_stdio_stream const stream(public_stream);

    _VALIDATE_RETURN(stream.valid(),                             EINVAL, 0);
    _VALIDATE_RETURN(buffer != nullptr,                          EINVAL, 0);
    _VALIDATE_RETURN(element_count <= (SIZE_MAX / element_size), EINVAL, 0);

    // Figure out how big the buffer is; if the stream doesn't currently have a
    // buffer, we assume that we'll get one with the usual internal buffer size:
    unsigned stream_buffer_size = stream.has_any_buffer()
        ? stream->_bufsiz
        : _INTERNAL_BUFSIZ;

    // The total number of bytes to be written to the stream:
    size_t const total_bytes = element_size * element_count;

    char const* data = static_cast<char const*>(buffer);

    // Write blocks of data from the buffer until there is no more data left:
    size_t remaining_bytes = total_bytes;
    while (remaining_bytes != 0)
    {
        // If the buffer is big and is not full, copy data into the buffer:
        if (stream.has_big_buffer() && stream->_cnt != 0)
        {
            if (stream->_cnt < 0)
            {
                _ASSERTE(("Inconsistent Stream Count. Flush between consecutive read and write", stream->_cnt >= 0));
                stream.set_flags(_IOERROR);
                return (total_bytes - remaining_bytes) / element_size;
            }

            size_t const bytes_to_write = __min(remaining_bytes, static_cast<size_t>(stream->_cnt));

            memcpy(stream->_ptr, data, bytes_to_write);

            remaining_bytes -= bytes_to_write;
            stream->_cnt    -= static_cast<int>(bytes_to_write);
            stream->_ptr    += bytes_to_write;
            data            += bytes_to_write;
        }
        // If we have more than stream_buffer_size bytes to write, write data by
        // calling _write() with an integral number of stream_buffer_size blocks.
        else if (remaining_bytes >= stream_buffer_size)
        {
            // If we reach here and we have a big buffer, it must be full, so
            // flush it.  If the flush fails, there's nothing we can do to
            // recover:
            if (stream.has_big_buffer() && __acrt_stdio_flush_nolock(stream.public_stream()))
            {
                return (total_bytes - remaining_bytes) / element_size;
            }

            // Calculate the number of bytes to write.  The _write API takes a
            // 32-bit unsigned byte count, so clamp the value to UINT_MAX:
            size_t const max_bytes_to_write = stream_buffer_size > 0
                ? remaining_bytes - remaining_bytes % stream_buffer_size
                : remaining_bytes;

            unsigned const bytes_to_write = static_cast<unsigned>(__min(max_bytes_to_write, UINT_MAX));

            unsigned const bytes_actually_written = _write(_fileno(stream.public_stream()), data, bytes_to_write);
            if (bytes_actually_written == static_cast<unsigned>(-1))
            {
                stream.set_flags(_IOERROR);
                return (total_bytes - remaining_bytes) / element_size;
            }

            // VSWhidbey #326224:  _write can return more bytes than we requested
            // due to Unicode conversions in text files.  We do not care how many
            // bytes were written as long as the number is as least as large as we
            // requested:
            unsigned const bytes_written = bytes_actually_written > bytes_to_write
                ? bytes_to_write
                : bytes_actually_written;

            // Update the remaining bytes and data to reflect the write:
            remaining_bytes -= bytes_written;
            data            += bytes_written;

            if (bytes_actually_written < bytes_to_write)
            {
                stream.set_flags(_IOERROR);
                return (total_bytes - remaining_bytes) / element_size;
            }
        }
        // Otherwise, the stream does not have a buffer, or the buffer is full
        // and there are not enough characters to do a direct write, so use
        // __acrt_stdio_flush_and_write_narrow_nolock:
        else
        {
            // Write the first character.  If this fails, there is nothing we can
            // do.  (Note that if this fails, it will update the stream error state.)
            if (__acrt_stdio_flush_and_write_narrow_nolock(*data, stream.public_stream()) == EOF)
            {
                return (total_bytes - remaining_bytes) / element_size;
            }

            // Update the remaining bytes to account for the byte we just wrote:
            ++data;
            --remaining_bytes;

            stream_buffer_size = stream->_bufsiz > 0
                ? stream->_bufsiz
                : 1;
        }
    }

    return element_count; // Success!
}
Example #2
0
ERRORCODE TextFlow::adjust_words(DB_RECORD_NUMBER p_record,
					DB_RECORD_NUMBER f_record,
					CHARACTER_DELTA cdelta, WORD_DELTA_PTR wdelta)
{
	ParagraphPtr paragraph;
	W_INDEX w_index;
	TEXT_WORD_PTR wp;
	ERRORCODE error;

	/* Redisplay vars */
	LINE_PTR lp;
	FramePtr frame;
	PCOORD erase_xmin, erase_xmax;
	W_INDEX old_windex;
	L_INDEX l_index;
	BOOL deleted_something;

/*
// Initialize the word delta structure first.
*/

	wdelta->w_start = -1;
	wdelta->count = 0;

/* Make sure we avoid busy work. */

	if (cdelta.count == 0)
	{
		return ERRORCODE_None;
	}

/* Lock the paragraph so we can access it. */

	if ((paragraph = (ParagraphPtr)database->get_record(p_record, &error, RECORD_TYPE_Paragraph)) == NULL)
	{
		return error;
	}

/* Get the frame object. */

	if ((frame = (FramePtr)database->get_record(f_record, &error, RECORD_TYPE_Frame)) == NULL)
	{
		paragraph->release();
		return error;
	}

/*
// Run through the word array and update all words which need it.
// We must be careful using a pointer into the word array data since any
// deletions can cause the array data to change locations.
*/

	/* Initialize redisplay variables */
	deleted_something = FALSE;
	lp = NULL;
	old_windex = 0;
	l_index = frame->line_of_word(0, NULL);
	lp = (LINE_PTR)frame->line.get_element(l_index);

	for (wp = (TEXT_WORD_PTR)paragraph->word.get_element(0), w_index = 0;
							w_index < paragraph->word.count();
							old_windex++,
 							w_index++, wp++)
	{
		C_INDEX this_start;

		if ((this_start = wp->c_start) >= cdelta.c_start)
		{
		/* This has moved. Move it now. */
		/* If deleting, see if the array is still valid. */

			if ((this_start += cdelta.count) <= cdelta.c_start)
			{
				this_start = cdelta.c_start;
				if (!deleted_something)
				{
					deleted_something = TRUE;

					erase_xmin = wp->x_offset + wp->draw_left;
					erase_xmax = wp->x_offset + wp->draw_width;
				}

			/*
			// Update the word delta.
			// This makes the (valid) assumption that words which get
			// deleted are all contiguous.
			*/

				if (wdelta->w_start == -1)
				{
					wdelta->w_start = w_index;

					/* Start updating w1 (last word to erase) */
					l_index = frame->line_of_word(w_index, NULL);
					lp = (LINE_PTR)frame->line.get_element(l_index);

					erase_xmax = __max(erase_xmax, wp->x_offset + wp->draw_width);
					erase_xmin = __min(erase_xmin, wp->x_offset + wp->draw_left);
				}
				else
				{
				/* The previous word has vanished. Delete it now. */
					if (old_windex > lp->w_end)
					{
						/* That's all the words for this line.  Erase the words */
						add_width_refresh_extent(frame, lp,
									erase_xmin, erase_xmax, REFRESH_ERASE);

						/* Start a new line */
						erase_xmin = wp->x_offset + wp->draw_left;
						erase_xmax = wp->x_offset + wp->draw_width;
						lp++;
					}
					else
					{
						erase_xmax = __max(erase_xmax, wp->x_offset + wp->draw_width);
					}

					wdelta->count--;

				/* Do the actual delete. */

					paragraph->delete_word(--w_index);
					paragraph->modified();
#ifdef DEBUG_AW
					printf("Delete previous word (%d)\n", w_index);
#endif
				/* Recompute 'wp' in case 'word.data' changed. */

					wp = (TEXT_WORD_PTR)paragraph->word.get_element(w_index);
				}
			}

#ifdef DEBUG_AW
			printf("Bumped WORD %d from index %d to %d (", w_index, wp->c_start, this_start);
#endif

		/* Set the new start. */

			wp->c_start = this_start;

#ifdef DEBUG_AW
			dump_word(paragraph, wp);
			printf(")\n");
#endif
		}
		else
		{
			/* Advance the erase anchor point */
			erase_xmin = __min(erase_xmin, wp->x_offset + wp->draw_left);
		}
	}

	if (deleted_something)
	{
		/* Found at least one line to delete.  Delete the last line we found */
		add_width_refresh_extent(frame, lp,
			erase_xmin, erase_xmax, REFRESH_ERASE);
	}

/* Release the objects we got. */

	frame->release();
	paragraph->release();

	return ERRORCODE_None;
}
Example #3
0
VOID TextFlow::position_lines(FramePtr frame, VERT_ALIGN_TYPE align_type)
{
	PCOORD y_offset;
	L_INDEX l_index;
	LINE_PTR lp;
	PBOX refresh_offsets;
	PBOX bound = frame->get_bound();
	PCOORD baseline;

/*
// Compute the height of all the lines so we can know how to align them.
*/

	y_offset = 0;
	baseline = 0;

	SHORT line_count = frame->number_of_lines();

	if (line_count == 0)
	{
		refresh_offsets.x0 = 0;
		refresh_offsets.x1 = 0;
	}
	else
	{
		PCOORD xmin, xmax;
		xmin = 0x7fffffff;
		xmax = -xmin;

		for (lp = frame->get_line(0), l_index = 0; l_index < line_count; lp++, l_index++)
		{
			xmin = __min(xmin, lp->refresh_xmin);
			xmax = __max(xmax, lp->refresh_xmax);

			if (l_index == 0)
			{
				baseline = y_offset + lp->ascend;
			}
			else
			{
				baseline = y_offset + lp->line_spacing - lp->descend;
			}
			y_offset = baseline + lp->descend;
		}
		refresh_offsets.x0 = xmin;
		refresh_offsets.x1 = xmax;
	}

/*
// Compute the offset value from the height of the text and the frame height.
*/

	if ((y_offset = bound.y1 - bound.y0 - y_offset) > 0)
	{
		switch (align_type)
		{
			case ALIGN_top:
			{
				y_offset = 0;
				break;
			}
			case ALIGN_middle:
			{
				y_offset /= 2;
				break;
			}
			case ALIGN_bottom:
			default:
			{
				break;
			}
		}
	}
	else
	{
	/* Text too big for frame. Top align it. */
		y_offset = 0;
	}

	refresh_offsets.y0 = y_offset;

/*
// We have the amount to offset. Do the offset now.
*/

	for (lp = frame->get_line(0), l_index = 0; l_index < line_count; lp++, l_index++)
	{
		if (l_index == 0)
		{
			y_offset += lp->ascend;
		}
		else
		{
			y_offset += lp->line_spacing - lp->descend;
		}

		if (y_offset != lp->baseline)
		{
			if (lp->baseline != -1)
			{
				add_line_refresh_extent(frame, lp);
			}
			lp->baseline = y_offset;
			add_line_refresh_extent(frame, lp);
		}
		y_offset += lp->descend;
	}

	refresh_offsets.y1 = __min(y_offset, bound.y1 - bound.y0);

	frame->set_refresh_offsets(refresh_offsets);
}
Example #4
0
void    gml_hdref( const gmltag * entry )
{
    char    *   p;
    char    *   pa;
    char    *   pe;
    char    *   idp;
    char        quote;
    char        c;
    bool        idseen;
    bool        pageseen;
    bool        withpage;
    size_t      len;
    char        buf64[64];
    ref_entry   *   re;
    static char undefid[] = "\"Undefined Heading\" on page XXX";


    idseen = false;
    pageseen = false;
    withpage = false;
    p = scan_start;
    re = NULL;

    /***********************************************************************/
    /*  Scan attributes  for :HDREF                                        */
    /*  id=                                                                */
    /*  page=                                                              */
    /***********************************************************************/

    for( ;; ) {
        while( *p == ' ' ) {
            p++;
        }
        if( *p == '\0' || *p == '.'  ) {
            break;                      // tag end found
        }

        if( !strnicmp( "page=", p, 5 ) ) {
            p += 5;
            while( *p == ' ' ) {
                p++;
            }
            pa = p;
            if( !strnicmp( "yes", p, 3 ) ) {
                pageseen = true;
                withpage = true;
                p += 3;
            } else {
                if( !strnicmp( "no", p, 2 ) ) {
                    pageseen = true;
                    withpage = false;
                    p += 2;
                } else {
                   g_err( err_inv_att_val );
                   file_mac_info();
                   err_count++;
                   while( *p && (*p != '.') && (*p != ' ') ) p++;
                }
            }
            scan_start = p;
            continue;
        }

        if( !strnicmp( "refid=", p, 6 ) ) {
            p += 6;
            while( *p == ' ' ) {
                p++;
            }
            if( is_quote_char( *p ) ) {
                quote = *p;
                p++;
            } else {
                quote = '\0';
            }
            pa = p;
            while( *p && is_id_char( *p ) ) {
                p++;
            }
            len = __min( ID_LEN, p - pa );// restrict length as in ghx.c

            if( len > 0 ) {
                idseen = true;          // valid id attribute found
                pe = pa + len;
                c = *pe;
                *pe = '\0';
                re = find_refid( ref_dict, strlwr( pa ) );
                if( re != NULL ) {      // id found in ref dict
                    idp = mem_alloc( 4 + strlen( re->text_cap ) );
                    *idp = '"';         // decorate with quotes
                    strcpy( idp + 1, re->text_cap );
                    strcat( idp, "\"" );
                } else {
                    if( GlobalFlags.lastpass ) {
                        g_warn( wng_id_xxx, pa );
                        g_info( inf_id_unknown );
                        file_mac_info();
                        wng_count++;
                    }
                }
                *pe = c;
            }
            if( *p && (quote == *p) ) {
                p++;
            }

            scan_start = p;
            continue;
        }

        /*******************************************************************/
        /* no more valid attributes                                        */
        /*******************************************************************/
        break;
    }
    if( *p == '.' ) {                   // tag end ?
        p++;
    }
    if( idseen ) {                      // id attribute was specified
        bool concatsave = ProcFlags.concat;

        ProcFlags.concat = true;        // make process_text add to line
        if( re == NULL ) {              // undefined refid
            process_text( undefid, g_curr_font_num );
        } else {
            process_text( idp, g_curr_font_num );
            if( withpage || (!pageseen && (page != re->pageno)) ) {
                sprintf_s( buf64, sizeof( buf64 ), "on page %d", re->pageno );
                process_text( buf64, g_curr_font_num );
            }
            mem_free( idp );
        }
        ProcFlags.concat = concatsave;
    } else {
        g_err( err_att_missing );       // id attribute missing
        file_mac_info();
        err_count++;
    }

    scan_start = p;
    return;
}
Example #5
0
ERRORCODE TextFlow::rebuild_lines(FrameObjectPtr object, WORD_RANGE wrange)
{
	ERRORCODE error;

	DB_RECORD_NUMBER f_record = object->get_frame_record();
	FramePtr frame;
	DB_RECORD_NUMBER p_record;
	ParagraphPtr paragraph;

	W_INDEX w_index;
	TEXT_WORD_PTR wp;
	PCOORD line_top;
	LINE_PTR lp;
	L_INDEX l_index;
	PCOORD frame_extent, frame_left, tab_size;
	PCOORD baseline;
	BOOL use_white_space;
	FLAGS frame_flags;

	frame_object = object;

/*
// Text is flowed by placing text words into lines within a frame.
// Words are flowed until the end is reached and then until words stop moving.
*/

	if ((frame = (FramePtr)database->get_record(f_record, &error, RECORD_TYPE_Frame)) == NULL)
	{
		return error;
	}

	frame_flags = frame->get_flags();

/*
// See if we need to do any stretching.
*/
	
	if (frame_flags & (FRAME_FLAG_stretch_frame | FRAME_FLAG_stretch_text))
	{
		if (frame_flags & FRAME_FLAG_stretch_frame)
		{
			SHORT error;

		/* Stretch the frame before flowing. */

			if ((error = object->stretch_frame()) != 0)
			{
				frame->release();
				if (error > 0)
				{
					error = ERRORCODE_None;
				}
				return (ERRORCODE)error;
			}

		/* Frame did not change size. Flow normally. */
		}
#if 0
		else
#else
	/* Always check (or check, too). */
		if (frame_flags & FRAME_FLAG_stretch_text)
#endif
		{
		/* Stretch the text before flowing. */

			if ((error = frame->stretch_text()) != ERRORCODE_None)
			{
				frame->release();
				return error;
			}

		/* Flow all the text. */

			wrange.w_start = wrange.w_end = -1;
		}
	}

	p_record = frame->get_paragraph();

	if ((paragraph = (ParagraphPtr)database->get_record(p_record, &error, RECORD_TYPE_Paragraph)) == NULL)
	{
		frame->release();
		return error;
	}

/*
// Ascertain the true start and end of the text flow request.
*/

	SHORT word_count = paragraph->number_of_words();

	if (wrange.w_start < 0)
	{
		wrange.w_start = 0;
	}
	if (wrange.w_end < 0)
	{
		wrange.w_end = word_count-1;
	}

	if (wrange.w_start > wrange.w_end || wrange.w_end >= word_count)
	{
	/* Error of a parameter nature. */

		paragraph->release();
		frame->release();

		return ERRORCODE_BadParameter;
	}

/*
// Find the line where the desired word starts.
// If the word hasn't been flowed yet, it may be "between" existing lines.
// If a word is not in a line, we'll shove it into the line just following it.
// This should always be possible, because the EOP word should always be
// flowed and in a line (and no word should come after it).
//
// We can do this really easily by just checking the last word in the line.
// If we are before that line, we have our line.
*/

	SHORT line_count = frame->number_of_lines();

	for (lp = frame->get_line(0), l_index = 0;
									l_index < line_count;
									l_index++, lp++)
	{
		/* MH 4/25/93 this was "if (lp->w_end >= wrange.w_start)" */
		if (lp->w_end + 1 >= wrange.w_start)
		{
			break;
		}
	}

/*
// Adjust w_start to the start of the line or our word, whichever is first.
*/

	if (wrange.w_start > lp->w_start)
	{
		wrange.w_start = lp->w_start;
	}

#ifdef DEBUG_RL
	printf("Flow words from %d to %d @ line %d\n", wrange.w_start, wrange.w_end, l_index);
#endif

/*
// Now, we have the line (l_index) and the first word to flow (w_start) into
// it. Let's do some flowin'!
*/

/* Compute the flowable extent and the size of a tab. */

	TextStyleRef style = paragraph->get_style();
	PBOX bound = frame->get_bound();

	frame_left = style.get_left_margin();
	frame_extent = bound.x1 - bound.x0
				- (style.get_left_margin() + style.get_right_margin());
	use_white_space = frame_flags & FRAME_FLAG_use_white_space;

	if ((tab_size = frame_extent / 16) == 0)
	{
		tab_size = 1;
	}

/* Compute the current top of line. */

	baseline = lp->baseline;
	line_top = baseline - lp->ascend;
#ifdef DEBUG_RL
	printf("current baseline: %ld, ascend: %ld, line_top:%ld\n",
						baseline, lp->ascend, line_top);
#endif

	for (w_index = wrange.w_start, wp = paragraph->get_word(w_index);; )
	{
		PCOORD extent;					/* Horizontal extent. */
		PCOORD x_offset;				/* Horizontal position. */
		PCOORD solid_x_offset;
		LINE old_line;
		BOOL line_changed;

#ifdef DEBUG_RL
		printf("(flow next line)\n");
#endif

	/* Remember the old line so we can tell if it moved. */

		old_line = *lp;

	/* Start a new line. */

		lp->w_start = w_index;

	/* Initialize the horizontal extent. */

		extent = frame_extent;

	/* Plug in parameters for this line and update line_top. */

		lp->ascend = lp->descend = lp->line_spacing = 0;

		baseline = line_top;

	/* Start us at the left margin. */

		x_offset = 0;
		solid_x_offset = 0;

	/* Flow words into this line until done (possibly passing w_end). */

		while (w_index < word_count)
		{
			FLAGS flags = wp->flags;

		/* Calculate tab width if necessary. */

			if (wp->type == WORD_TYPE_tab)
			{
				wp->width = ((x_offset + tab_size)/tab_size)*tab_size - x_offset;
			}

		/* See if this word will fit in the row. */

#ifdef DEBUG_RL
			printf("flow word ");
			dump_word(paragraph, wp);
			printf("...");
#endif

			if (flags & WORD_FLAG_override)
			{
			/* Something is overridden. */

				wp->flags &= ~WORD_FLAG_override;

				if (flags & WORD_FLAG_override_flow)
				{
				/*
 				// A flow word!
				// Note that the flags have been cleared, so we won't keep
				// hitting this.
				*/
					break;
				}
			}
			else if (x_offset + wp->width > extent		/* doesn't fit */
						&& w_index != lp->w_start				/* not first word */
						&& !(wp->type == WORD_TYPE_space
									&& ((wp-1)->type == WORD_TYPE_solid
										 || (wp-1)->type == WORD_TYPE_macro))
						&& wp->width != 0)						/* real word */
			{
#ifdef DEBUG_RL
				printf(" Move word to next line\n");
#endif
				break;
			}

		/* Update the horizontal offsets. */

			x_offset += wp->width;
			if (use_white_space
				 || wp->type == WORD_TYPE_solid
				 || wp->type == WORD_TYPE_macro)
			{
				solid_x_offset = x_offset;
			}

			if (wp->ascend > lp->ascend)
			{
#ifdef DEBUG_RL
				printf("Expand ascend from %ld to %ld\n", lp->ascend, wp->ascend);
#endif
				baseline -= lp->ascend;
				baseline += (lp->ascend = wp->ascend);
#ifdef DEBUG_RL
				printf("Baseline moves to %ld\n", baseline);
#endif
			}

			if (wp->descend > lp->descend)
			{
#ifdef DEBUG_RL
				printf("Expand descend from %ld to %ld\n", lp->descend, wp->descend);
#endif
				lp->descend = wp->descend;
			}

			if (wp->line_spacing > lp->line_spacing)
			{
				lp->line_spacing = wp->line_spacing;
			}

		/* Add this word to the line. */

			lp->w_end = w_index++;

#ifdef DEBUG_RL
			printf(" Add word to line (x:%ld, w:%ld).\n", x_offset-wp->width, wp->width);
#endif

		/* If we just placed a break word, this line is done. */

			if (wp++->type == WORD_TYPE_break)
			{
			/*
			// If the previous word:
			// (a) was a "macro" word,
			// (b) started at the beginning of the line, and
			// (c) had zero width,
			// don't flow the break to the next line.
			*/
				BOOL fBreak = TRUE;
				if (w_index >= 2 && x_offset == 0)
				{
					TEXT_WORD_PTR wprev = wp-2;

					/* I make an assumption - x_offset == 0 --> width == 0. */
//					if (wprev->width == 0)
					{
						if (*(paragraph->get_character(wprev->c_start)) >= MACRO_CHARACTER)
						{
							fBreak = FALSE;
						}
					}
				}

				if (fBreak)
				{
#ifdef DEBUG_RL
					printf("(Breaking on BREAK word)\n");
#endif
				/* We need to break for this line. */
					break;
				}
			}
		}

#ifdef DEBUG_RL
		printf("[ line %d base:%ld, asc:%ld, dsc:%ld, w: %d to %d ]\n",
							l_index,
 							baseline, lp->ascend, lp->descend,
							lp->w_start, lp->w_end);
#endif
	/*
 	// We now know all the words in this line. Handle the placement.
 	*/

	/* First calculate the alignment offset. */

		if ((x_offset = extent - solid_x_offset) > 0)
		{
		/* Some space to distribute. */
			switch (style.get_line_alignment())
			{
				case ALIGN_center:
				{
					x_offset /= 2;
					break;
				}
				case ALIGN_left:
				{
					x_offset = 0;
					break;
				}
				default:
				{
					break;
				}
			}
		}
		else
		{
			x_offset = 0;
		}

	/* Now set the positions of the words in this line. */

		line_changed = FALSE;				/* Cross your fingers. */
		x_offset += style.get_left_margin();

		{
			W_INDEX w_index = lp->w_start, w_end = lp->w_end;
			TEXT_WORD_PTR wp = paragraph->get_word(w_index);

			/* Redisplay variables */
			TEXT_WORD_PTR first_word_change = NULL;
			TEXT_WORD_PTR last_word_change = NULL;
			PCOORD erase_xmin, erase_xmax;
			BOOL found_erase = FALSE;

			lp->refresh_xmin = 0x7fffffff;
			lp->refresh_xmax = -lp->refresh_xmin;

			while (w_index <= w_end)
			{
				if (x_offset != wp->x_offset || (wp->flags & WORD_FLAG_changed_size))
				{
				/* A word moved. */
#ifdef DEBUG_RL
					printf("word %d changed from %ld to %ld\n",
									w_index, wp->x_offset, x_offset);
#endif
					if (first_word_change == NULL)
					{
  						first_word_change = wp;
					}
					if (!found_erase && wp->x_offset != -1 &&
						w_index >= old_line.w_start && w_index <= old_line.w_end)
					{
						erase_xmin = wp->x_offset + wp->draw_left;
						erase_xmax = wp->x_offset + wp->draw_width;
  						found_erase = TRUE;
					}
					last_word_change = wp;
					if (wp->x_offset != -1 &&
						 w_index >= old_line.w_start && w_index <= old_line.w_end)
					{
						erase_xmin = __min(erase_xmin, wp->x_offset + wp->draw_left);
						erase_xmax = __max(erase_xmax, wp->x_offset + wp->draw_width);
					}


					wp->x_offset = x_offset;
//remove this to do word-wise refresh; restore it to do full line refresh
//					line_changed = TRUE;
				}
				wp->flags &= ~WORD_FLAG_changed_size;

				lp->refresh_xmin = __min(lp->refresh_xmin, wp->x_offset + wp->draw_left);
				lp->refresh_xmax = __max(lp->refresh_xmax, wp->x_offset + wp->draw_width);

				x_offset += wp++->width;
				w_index++;
			}

			if (first_word_change != NULL && old_line.baseline != -1)
			{
				/* Add a DRAW for every word that moved; erase moved words from
					their old positions. */

  				add_words_refresh_extent(frame, &old_line,
								first_word_change, last_word_change, REFRESH_DRAW);
				if (found_erase)
				{
	  				add_width_refresh_extent(frame, &old_line,
									erase_xmin, erase_xmax, REFRESH_ERASE);
				}
			}
		}

	/* See if the line changed. */

		if (!line_changed)
		{
		/* Words stayed the same. See if the line is different somehow. */
		/* Compare using the OLD_LINE structure. This allows us to ignore
			the changes in refresh_xmin, refresh_xmax. */

			line_changed = (memcmp(&old_line, lp, sizeof(OLD_LINE)) != 0);
			if (line_changed)
			{
				lp->baseline = -1;
			}
		}

		if (line_changed)
		{
#ifdef DEBUG_RL
			printf("Line %d changed\n", l_index);
			printf("old [%d to %d] vs. new [%d to %d]\n",
								old_line.w_start, old_line.w_end,
								lp->w_start, lp->w_end);
#endif
			if (old_line.baseline != -1)
			{
				add_line_refresh_extent(frame, &old_line);
			}
		}
		else
		{
#ifdef DEBUG_RL
			printf("Line %d stayed the same\n", l_index);
#endif
		/* We can end now! */
			if (w_index > wrange.w_end)
			{
				break;
			}
		}

	/* See if we're done. */

		if (w_index >= word_count)
		{
		/* Run out of words. Finished. */
			break;
		}

	/*
 	// Move to a new line.
	// Add one if there are no more left.
 	*/

		line_top = baseline + lp->descend;

		if (++l_index == frame->number_of_lines())
		{
		/* Create a new dummy line. */
			LINE line;
#ifdef DEBUG_RL
			printf("(Create a new line)\n");
#endif

			line.w_start = line.w_end = 0;			/* In case. */
			line.baseline = -1;
			frame->insert_line(l_index, &line);
			lp = frame->get_line(l_index);
		}
		else
		{
		/* Add a refresh extent for the old line in case it's changing. */
#ifdef DEBUG_RL
			printf("(Move onto existing line)\n");
#endif
			lp++;
		}
	}

#ifdef DEBUG_RL
	printf("Done (final l_index:%d, w_index:%d)...\n", l_index, w_index);
#endif

/* If we flowed all words, delete any trailing lines. */

	if (w_index == word_count)
	{
		if (++l_index < frame->number_of_lines())
		{
			while (l_index < frame->number_of_lines())
			{
#ifdef DEBUG_RL
				printf("{Delete line}");
#endif
				add_line_refresh_extent(frame, frame->get_line(l_index));
				frame->delete_line(l_index);
			}
#ifdef DEBUG_RL
			printf("\n");
#endif
		}
	}

	if (frame_flags & FRAME_FLAG_ystretch_frame)
	{
		position_lines(frame, style.get_vertical_alignment());
		object->ystretch_frame();
	}

	position_lines(frame, style.get_vertical_alignment());

/*
// Release our objects.
*/

	paragraph->release(TRUE);
	frame->release(TRUE);

	return ERRORCODE_None;
}
Example #6
0
//初始化函数
BOOL CGameFrameDlg::OnInitDialog()
{
	__super::OnInitDialog();

	//设置属性
	ModifyStyle(WS_CAPTION|WS_BORDER,0,0);

	//读取配置
	m_bAllowSound=AfxGetApp()->GetProfileInt(TEXT("GameOption"),TEXT("EnableSound"),TRUE)?true:false;

	//创建控制
	m_pGameFrameControl=new CGameFrameControl(this);
	if (m_pGameFrameControl==NULL) throw TEXT("游戏框架创建失败");

	//创建组件
	if (m_MessageProxyHelper.CreateInstance()==false) throw TEXT("信息组件创建失败");
	m_MessageProxyHelper->SetRichEditHwnd(&m_pGameFrameControl->m_ChatMessage);

	//设置界面
	m_VorSplitter.SetSplitterSink(this);

	//创建组件
	if (m_UserFaceResHelper.CreateInstance()==false) throw TEXT("头像组件加载失败");
	if (m_ClientKernelHelper.CreateInstance()==false) throw TEXT("游戏框架内核模块加载失败");

	//创建游戏视图
	CRect rcGameView(0,0,0,0);
	m_pGameFrameControl->Create(IDD_FRAME_CONTROL,this);
	if (m_pGameFrameControl->SetUserFaceRes(m_UserFaceResHelper.GetInterface())==false) throw TEXT("头像资源接口设置失败");
	m_pGameFrameView->Create(NULL,NULL,WS_VISIBLE|WS_CHILD|WS_CLIPSIBLINGS|WS_CLIPCHILDREN,rcGameView,this,10);
	if (m_pGameFrameView->SetUserFaceRes(m_UserFaceResHelper.GetInterface())==false) throw TEXT("头像资源接口设置失败");
	CVideoServiceManager * pVideoServiceManager=CVideoServiceManager::GetInstance();
	if (pVideoServiceManager!=NULL && pVideoServiceManager->SetUserFaceRes(m_UserFaceResHelper.GetInterface())==false) throw TEXT("头像资源接口设置失败");

	//初始化内核
	LPCTSTR lpszCmdLine=AfxGetApp()->m_lpCmdLine;
	bool bSuccess=m_ClientKernelHelper->InitClientKernel(lpszCmdLine,m_pKernelSink);
	if (bSuccess==false) throw TEXT("游戏框架逻辑模块初始化失败");
	bSuccess=m_ClientKernelHelper->SetMessageProxy(m_MessageProxyHelper.GetInterface());
	if (bSuccess==false) throw TEXT("获取消息输出模块失败");

	//初始化游戏
	m_pGameFrameControl->SetClientKernel(m_ClientKernelHelper.GetInterface());
	if (InitGameFrame()==false) throw TEXT("游戏框架初始化失败");

	//加载资源
	UpdateSkinResource();

	//移动窗口
	INT nXScreen=GetSystemMetrics(SM_CXSCREEN);
	INT nYScreen=GetSystemMetrics(SM_CYSCREEN);
	SetWindowPos(NULL,0,0,__min(nXScreen,1024),__min(nYScreen,730),SWP_NOZORDER|SWP_NOMOVE);

	//显示窗口
	m_bInitDialog=true;
	m_pGameFrameView->ShowWindow(SW_SHOW);
	m_pGameFrameControl->ShowWindow(SW_SHOW);

	//显示窗口
	CenterWindow();
	MaxSizeWindow();
	ShowWindow(SW_SHOW);
	
	return TRUE;
}
Example #7
0
LoadStatus_t GdbLoader::Load(void)
{
    m_cOrdinal = 0;
    SetProgress(g_hExp, "Loading...", 0);

    size_t cOffset = sizeof(g_pGdbSignature);
    size_t cFileSize = (size_t)GetFileSize();
    do {
        const size_t cEndOffset_tmp = __min(cOffset + sizeof(CGdbRecordHdr), cFileSize);
        const char * const pRecord_tmp = GetFilePart(cOffset, cEndOffset_tmp);
        if (pRecord_tmp == NULL)
            return lsFailed;
        const CGdbRecordHdr * const pHdr_tmp = reinterpret_cast<const CGdbRecordHdr *>(pRecord_tmp);
        size_t cNextOffset = __min(cOffset + sizeof(CGdbRecordHdr) + pHdr_tmp->dwLen, cFileSize);
        const char * const pRecord = GetFilePart (cOffset, cNextOffset);
        if (pRecord == NULL)
            return lsFailed;
        const CGdbRecordHdr * const pHdr = reinterpret_cast<const CGdbRecordHdr *>(pRecord);

        switch (pHdr->btType) {
        case 'D': { // GDB format version.
            const CGdbFormatVersion * const pVer = static_cast<const CGdbFormatVersion *>(pHdr);
            switch (pVer->wdVersion) {
            case 0x6B:
            case 0x6C:
            case 0x6D:
//						AddLog(g_hExp, "GDB Format version %d.", pVer->wdVersion - 0x6B + 1);
                break;
            default:
//						ReportText ("Format version: 0x%02X.", pVer->wdVersion);
                break;
            }
            m_b2ndVersion = pVer->wdVersion == 0x6C;
            m_b3rdVersion = pVer->wdVersion == 0x6D;
            if (pVer->wdVersion > 0x6D)
                AddLog(g_hExp, "File was created with an untested version of MapSource.", NULL);
            break;
        }
        case 'A': { // MapSource version.
            const CGdbMSVersion * const pVer = static_cast<const CGdbMSVersion *> (pHdr);

            const char * const pRecord = GetFilePart (cOffset, cNextOffset + 10);
            if (pRecord == NULL)
                return lsFailed;
            if (::_strnicmp (pRecord + (cNextOffset - cOffset), "MapSource", 10) == 0)
                cNextOffset += 10;
            break;
        }

        case 'W': { // Waypoint.
            const CGdbWaypointHdr * const pWP = static_cast<const CGdbWaypointHdr *> (pHdr);
            ParseWaypoint (pWP, cOffset, cNextOffset);
            break;
        }

        case 'T': { // Track.
            const CGdbTrackHdr * const pTrack = static_cast<const CGdbTrackHdr *> (pHdr);
            ParseTrack (pTrack, cOffset, cNextOffset, cFileSize, false);
            break;
        }

        case 'R': { // Route.
            const CGdbRouteHdr * const pRoute = static_cast<const CGdbRouteHdr *> (pHdr);
            ParseRoute (pRoute, cOffset, cNextOffset);
            break;
        }

        case 'L': { // Map reference.
            const CGdbMapHdr * const pMap = static_cast<const CGdbMapHdr *> (pHdr);
            break;
        }

        case 'V': {	// Tail mark and map set info.
            break;
        }
        }

        cOffset = cNextOffset;

        SetProgress(g_hExp, NULL, ::MulDiv(100, cOffset, cFileSize));
    } while (cOffset < cFileSize);

    return lsOK;
}
Example #8
0
/**
 * @brief This function learns the topics of words in a document and is the
 * main step of a Gibbs sampling iteration. The word topic counts and
 * corpus topic counts are passed to this function in the first call and
 * then transfered to the rest calls through args.mSysInfo->user_fctx for
 * efficiency. 
 * @param args[0]   The unique words in the documents
 * @param args[1]   The counts of each unique words
 * @param args[2]   The topic counts and topic assignments in the document
 * @param args[3]   The model (word topic counts and corpus topic
 *                  counts)
 * @param args[4]   The Dirichlet parameter for per-document topic
 *                  multinomial, i.e. alpha
 * @param args[5]   The Dirichlet parameter for per-topic word
 *                  multinomial, i.e. beta
 * @param args[6]   The size of vocabulary
 * @param args[7]   The number of topics
 * @param args[8]   The number of iterations (=1:training, >1:prediction)
 * @return          The updated topic counts and topic assignments for
 *                  the document
 **/
AnyType lda_gibbs_sample::run(AnyType & args)
{
    ArrayHandle<int32_t> words = args[0].getAs<ArrayHandle<int32_t> >();
    ArrayHandle<int32_t> counts = args[1].getAs<ArrayHandle<int32_t> >();
    MutableArrayHandle<int32_t> doc_topic = args[2].getAs<MutableArrayHandle<int32_t> >();
    double alpha = args[4].getAs<double>();
    double beta = args[5].getAs<double>();
    int32_t voc_size = args[6].getAs<int32_t>();
    int32_t topic_num = args[7].getAs<int32_t>();
    int32_t iter_num = args[8].getAs<int32_t>();

    if(alpha <= 0)
        throw std::invalid_argument("invalid argument - alpha");
    if(beta <= 0)
        throw std::invalid_argument("invalid argument - beta");
    if(voc_size <= 0)
        throw std::invalid_argument(
            "invalid argument - voc_size");
    if(topic_num <= 0)
        throw std::invalid_argument(
            "invalid argument - topic_num");
    if(iter_num <= 0)
        throw std::invalid_argument(
            "invalid argument - iter_num");

    if(words.size() != counts.size())
        throw std::invalid_argument(
            "dimensions mismatch: words.size() != counts.size()");
    if(__min(words) < 0 || __max(words) >= voc_size)
        throw std::invalid_argument(
            "invalid values in words");
    if(__min(counts) <= 0)
        throw std::invalid_argument(
            "invalid values in counts");

    int32_t word_count = __sum(counts);
    if(doc_topic.size() != (size_t)(word_count + topic_num))
        throw std::invalid_argument(
            "invalid dimension - doc_topic.size() != word_count + topic_num");
    if(__min(doc_topic, 0, topic_num) < 0)
        throw std::invalid_argument("invalid values in topic_count");
    if(
        __min(doc_topic, topic_num, word_count) < 0 ||
        __max(doc_topic, topic_num, word_count) >= topic_num)
        throw std::invalid_argument( "invalid values in topic_assignment");

    if (!args.getUserFuncContext())
    {
        if(args[3].isNull())
            throw std::invalid_argument("invalid argument - the model \
            parameter should not be null for the first call");
        ArrayHandle<int64_t> model = args[3].getAs<ArrayHandle<int64_t> >();
        if(model.size() != (size_t)((voc_size + 1) * topic_num))
            throw std::invalid_argument(
                "invalid dimension - model.size() != (voc_size + 1) * topic_num");
        if(__min(model) < 0)
            throw std::invalid_argument("invalid topic counts in model");

        int64_t * state = 
            static_cast<int64_t *>(
                MemoryContextAllocZero(
                    args.getCacheMemoryContext(), 
                    model.size() * sizeof(int64_t)));
        memcpy(state, model.ptr(), model.size() * sizeof(int64_t));
        args.setUserFuncContext(state);
    }

    int64_t * state = static_cast<int64_t *>(args.getUserFuncContext());
    if(NULL == state){
        throw std::runtime_error("args.mSysInfo->user_fctx is null");
    }

    int32_t unique_word_count = static_cast<int32_t>(words.size());
    for(int32_t it = 0; it < iter_num; it++){
        int32_t word_index = topic_num;
        for(int32_t i = 0; i < unique_word_count; i++) {
            int32_t wordid = words[i];
            for(int32_t j = 0; j < counts[i]; j++){
                int32_t topic = doc_topic[word_index];
                int32_t retopic = __lda_gibbs_sample(
                    topic_num, topic, doc_topic.ptr(), 
                    state + wordid * topic_num, 
                    state + voc_size * topic_num, alpha, beta);
                doc_topic[word_index] = retopic;
                doc_topic[topic]--;
                doc_topic[retopic]++;

                if(iter_num == 1){
                    state[voc_size * topic_num + topic]--;
                    state[voc_size * topic_num + retopic]++;
                    state[wordid * topic_num + topic]--;
                    state[wordid * topic_num + retopic]++;
                }
                word_index++;
            }
        }
    }
    
    return doc_topic;
}
Example #9
0
/**
 * @brief This function is the sfunc for the aggregator computing the topic
 * counts. It scans the topic assignments in a document and updates the word
 * topic counts.
 * @param args[0]   The state variable, current topic counts
 * @param args[1]   The unique words in the document
 * @param args[2]   The counts of each unique word in the document
 * @param args[3]   The topic assignments in the document
 * @param args[4]   The size of vocabulary
 * @param args[5]   The number of topics 
 * @return          The updated state
 **/
AnyType lda_count_topic_sfunc::run(AnyType & args)
{
    if(args[4].isNull() || args[5].isNull())
        throw std::invalid_argument("null parameter - voc_size and/or \
        topic_num is null");

    if(args[1].isNull() || args[2].isNull() || args[3].isNull()) 
        return args[0];

    int32_t voc_size = args[4].getAs<int32_t>();
    int32_t topic_num = args[5].getAs<int32_t>();
    if(voc_size <= 0)
        throw std::invalid_argument(
            "invalid argument - voc_size");
    if(topic_num <= 0)
        throw std::invalid_argument(
            "invalid argument - topic_num");

    ArrayHandle<int32_t> words = args[1].getAs<ArrayHandle<int32_t> >();
    ArrayHandle<int32_t> counts = args[2].getAs<ArrayHandle<int32_t> >();
    ArrayHandle<int32_t> topic_assignment = args[3].getAs<ArrayHandle<int32_t> >();
    if(words.size() != counts.size())
        throw std::invalid_argument(
            "dimensions mismatch - words.size() != counts.size()");
    if(__min(words) < 0 || __max(words) >= voc_size)
        throw std::invalid_argument(
            "invalid values in words");
    if(__min(counts) <= 0)
        throw std::invalid_argument(
            "invalid values in counts");
    if(__min(topic_assignment) < 0 || __max(topic_assignment) >= topic_num)
        throw std::invalid_argument("invalid values in topics");
    if((size_t)__sum(counts) != topic_assignment.size())
        throw std::invalid_argument(
            "dimension mismatch - sum(counts) != topic_assignment.size()");

    MutableArrayHandle<int64_t> state(NULL);
    if(args[0].isNull()){
        int dims[2] = {voc_size + 1, topic_num};
        int lbs[2] = {1, 1};
        state = madlib_construct_md_array(
            NULL, NULL, 2, dims, lbs, INT8TI.oid, INT8TI.len, INT8TI.byval,
            INT8TI.align);
    } else {
        state = args[0].getAs<MutableArrayHandle<int64_t> >();
    }

    int32_t unique_word_count = static_cast<int32_t>(words.size());
    int32_t word_index = 0;
    for(int32_t i = 0; i < unique_word_count; i++){
        int32_t wordid = words[i];
        for(int32_t j = 0; j < counts[i]; j++){
            int32_t topic = topic_assignment[word_index];
            state[wordid * topic_num + topic]++;
            state[voc_size * topic_num + topic]++;
            word_index++;
        }
    }

    return state;
}
Example #10
0
void PreprocessTransferFreenect(libusb_transfer* transfer, const int read)
{
	fnusb_isoc_stream* xferstrm = (fnusb_isoc_stream*)transfer->user_data;
	freenect_device* dev = xferstrm->parent->parent;
	packet_stream* pktstrm = (transfer->endpoint == 0x81) ? &dev->video : &dev->depth;

	// Kinect Camera Frame Packed Header:
	struct pkt_hdr
	{
		uint8_t magic[2];
		uint8_t pad;
		uint8_t flag;
		uint8_t unk1;
		uint8_t seq;
		uint8_t unk2;
		uint8_t unk3;
		uint32_t timestamp;
	};  // 12 bytes

	//packet sizes:
	//          first  middle  last
	// Bayer    1920    1920    24
	// IR       1920    1920  1180
	// YUV422   1920    1920    36
	// Depth    1760    1760  1144
	const unsigned int pktlen = sizeof(pkt_hdr) + pktstrm->pkt_size;
	const unsigned int pktend = sizeof(pkt_hdr) + pktstrm->last_pkt_size;

	unsigned int remaining (read);
	unsigned int leftover (transfer->length);
	unsigned char* pktbuffer (transfer->buffer);
	const int pkts (transfer->num_iso_packets);
	for (int i=0; i<pkts; ++i)
	{
		const pkt_hdr& header (*(pkt_hdr*)pktbuffer);
		libusb_iso_packet_descriptor& desc (transfer->iso_packet_desc[i]);
		if ((header.magic[0] == 'R') && (header.magic[1] == 'B'))
		{
			switch(header.flag & 0x0F)
			{
			case 0x01 : // begin
			case 0x02 : // middle
				desc.actual_length = __min(remaining, pktlen);
				break;
			case 0x05 : // final
				desc.actual_length = __min(remaining, pktend);
				break;
			default :
				fprintf(stdout, "0x%02X\n", header.flag);
				break;
			}
		}
		else
		{
			desc.actual_length = 0;
		}
		remaining -= desc.actual_length;
		pktbuffer += desc.length;   // a.k.a: += 1920
		leftover  -= desc.length;   // a.k.a: -= 1920
	}

	if (remaining > 0)
	{
		fprintf(stdout, "%d remaining out of %d\n", remaining, read);
		if (remaining == read)
		{
		}
	}
}
Example #11
0
/*
 *  lock - handle lock requests return errno to reply to client w/
 */
static int _iofunc_lock_scoid(iofunc_lock_list_t **plist, int scoid, int type, off64_t start, off64_t end) {
    iofunc_lock_list_t  *cl,    /*  current list item   */
						*pl,	/*  previous list item */
						*ol;
	int					ret;

	ol = cl = pl = NULL;

    /*
     *  Simple case, no existing locks, simply add new lock.
     */
    if((cl = *plist) == NULL) {
        return _iofunc_lock_add(plist, scoid, type, start, end);
	}

    /*
     *  Simple case, lock is before existing locks.
     *  Just insert at head of list (no possible overlap).
     */
    if(end < cl->start) {
		pl = *plist, *plist= NULL;
        if ((ret = _iofunc_lock_add(plist, scoid, type, start, end)) != EOK) {
			*plist = pl;
		}
		else {
			(*plist)->next = pl;
		}
		return ret;
	}

    /*
     *  Scan thru remaining locklist to find location for new request.
     */
    for(pl = NULL;cl != NULL; pl = cl, cl = cl->next) {
        /*
         *  If lock is owned by same process and overlaps, stop scan.
         *  If more locks in range, skip to next.
         *  Otherwise stop scan.
         */
        if(cl->scoid == scoid  &&  
		   OVERLAP(start, end, cl->start, cl->end)) {
			break;
        }
        else if(cl->start > start) {
			cl = pl;
            break;
		}
	}
	/*
	 *  Request is at end of list, so we can add the lock here.
	 */
	if(cl == NULL){
		return _iofunc_lock_add(&pl,scoid,type,start,end);
	}

    /*
     *  If we overlap & id's match
	 *   -And the types match, create a superblock
	 *   -And the types differ, split the block
     *  Otherwise add new entry
     */
    if(cl->scoid == scoid && OVERLAP(start, end, cl->start, cl->end)) {
        if(cl->type == type) {
			cl->end = __max(cl->end, end);
			cl->start = __min(cl->start, start);
			return EOK;
		}
        else if (!(cl = locksplit(plist, cl, scoid, type, start, end))) {
			return EINVAL;
		}
		//Otherwise go on an compact w/ cl
	}
    else {
		if((ret = _iofunc_lock_add(&cl, scoid, type, start, end))) {
			return ret;
		}
        cl = cl->next;
	}

/* 
 This compaction is not required, though it might optimize things 
 slightly if we were to join blocks together. (Check boundary
 conditions as well as overlap)
*/
#if 0
    /*
     *  Remember the new lock region for later
     */
    ol = cl;

    /*
     *  End point set above may overlap later entries.
     *  If so delete or modify them to perform the compaction.
     */
    while(nl = cl->next; cl && nl; cl = nl, nl = cl->next) {
        /*
         *  If the new range overlaps the first part of the next lock,
         *  if its the same type,
         *      take its end point and delete the next lock
         *  else
         *      move the start point (unlocking anyone waiting).
         *  We should be done.
         */
        if(cl->scoid == scoid) {
            if(end <= nl->end) {
                if(nl->type == type) {
                    ol->end = nl->end;
                    cl->next = nl->next;
                    _iofunc_lock_free(nl);
                }
                else {
                    nl->start = start;
                    if(nl->blocked) {
						printf("TODO: Wakup people! \n");
                        //wakeup(nl);
                    }
				}
                return EOK;
            }
            else {
                /*
                 *  the next lock is fully included in the new range
                 *  so it may be deleted
                 */
                cl->next = nl->next;
                _iofunc_lock_free(nl);
            }
		} 
		else {
            cl = nl;
		}
    }
#endif

    return EOK;
}
Example #12
0
void UPD765A::cmd_write_data()
{
	switch(phase) {
	case PHASE_IDLE:
		shift_to_cmd(8);
		break;
	case PHASE_CMD:
		get_sector_params();
		REGISTER_PHASE_EVENT_NEW(PHASE_EXEC, get_usec_to_exec_phase());
		break;
	case PHASE_EXEC:
#ifdef SDL
		if (force_ready && !disk[hdu & DRIVE_MASK]->inserted) {
			REGISTER_PHASE_EVENT(PHASE_EXEC, 1000000);
			break;
		}
#endif // SDL
		result = check_cond(true);
		if(result & ST1_MA) {
			REGISTER_PHASE_EVENT(PHASE_EXEC, 1000000);	// retry
			break;
		}
		if(!result) {
			result = find_id();
		}
		if(result) {
			shift_to_result7();
		} else {
			int length = 0x80 << (id[3] & 7);
			if(!(id[3] & 7)) {
				length = __min(dtl, 0x80);
				memset(buffer + length, 0, 0x80 - length);
			}
			shift_to_write(length);
		}
		break;
	case PHASE_WRITE:
		write_data((command & 0x1f) == 9);
		if(result) {
			shift_to_result7();
			break;
		}
		phase = PHASE_EXEC;
		if(!id_incr()) {
			REGISTER_PHASE_EVENT(PHASE_TIMER, 2000);
			break;
		}
		REGISTER_PHASE_EVENT_NEW(PHASE_EXEC, get_usec_to_exec_phase());
		break;
	case PHASE_TIMER:
//		result = ST0_AT | ST1_EN;
		result = ST1_EN;
		shift_to_result7();
		break;
	case PHASE_TC:
		CANCEL_EVENT();
		if(prevphase == PHASE_WRITE && bufptr != buffer) {
			// terminate while transfer ?
			memset(bufptr, 0, count);
			write_data((command & 0x1f) == 9);
		}
		shift_to_result7();
		break;
	}
}
Example #13
0
uint32 UPD765A::read_sector()
{
	int drv = hdu & DRIVE_MASK;
	int trk = fdc[drv].track;
	int side = (hdu >> 2) & 1;
	
	// get sector counts in the current track
	if(!disk[drv]->make_track(trk, side)) {
#ifdef _FDC_DEBUG_LOG
		emu->out_debug_log("FDC: TRACK NOT FOUND (TRK=%d SIDE=%d)\n", trk, side);
#endif
		return ST0_AT | ST1_MA;
	}
	int secnum = disk[drv]->sector_num.sd;
	if(!secnum) {
#ifdef _FDC_DEBUG_LOG
		emu->out_debug_log("FDC: NO SECTORS IN TRACK (TRK=%d SIDE=%d)\n", trk, side);
#endif
		return ST0_AT | ST1_MA;
	}
	int cy = -1;
	for(int i = 0; i < secnum; i++) {
		if(!disk[drv]->get_sector(trk, side, i)) {
			continue;
		}
		cy = disk[drv]->id[0];
#if 0
		if(disk[drv]->id[0] != id[0] || disk[drv]->id[1] != id[1] || disk[drv]->id[2] != id[2] /*|| disk[drv]->id[3] != id[3]*/) {
#else
		if(disk[drv]->id[0] != id[0] || disk[drv]->id[1] != id[1] || disk[drv]->id[2] != id[2] || disk[drv]->id[3] != id[3]) {
#endif
			continue;
		}
		// sector number is matched
		if(disk[drv]->invalid_format) {
			memset(buffer, disk[drv]->drive_mfm ? 0x4e : 0xff, sizeof(buffer));
			memcpy(buffer, disk[drv]->sector, disk[drv]->sector_size.sd);
		} else {
			memcpy(buffer, disk[drv]->track + disk[drv]->data_position[i], disk[drv]->get_track_size() - disk[drv]->data_position[i]);
			memcpy(buffer + disk[drv]->get_track_size() - disk[drv]->data_position[i], disk[drv]->track, disk[drv]->data_position[i]);
		}
		fdc[drv].next_trans_position = disk[drv]->data_position[i];
		
		if(disk[drv]->crc_error) {
			return ST0_AT | ST1_DE | ST2_DD;
		}
		if(disk[drv]->deleted) {
			return ST2_CM;
		}
		return 0;
	}
#ifdef _FDC_DEBUG_LOG
	emu->out_debug_log("FDC: SECTOR NOT FOUND (TRK=%d SIDE=%d ID=%2x,%2x,%2x,%2x)\n", trk, side, id[0], id[1], id[2], id[3]);
#endif
	if(cy != id[0] && cy != -1) {
		if(cy == 0xff) {
			return ST0_AT | ST1_ND | ST2_BC;
		} else {
			return ST0_AT | ST1_ND | ST2_NC;
		}
	}
	return ST0_AT | ST1_ND;
}

uint32 UPD765A::write_sector(bool deleted)
{
	int drv = hdu & DRIVE_MASK;
	int trk = fdc[drv].track;
	int side = (hdu >> 2) & 1;
	
	if(disk[drv]->write_protected) {
		return ST0_AT | ST1_NW;
	}
	// get sector counts in the current track
	if(!disk[drv]->get_track(trk, side)) {
		return ST0_AT | ST1_MA;
	}
	int secnum = disk[drv]->sector_num.sd;
	if(!secnum) {
		return ST0_AT | ST1_MA;
	}
	int cy = -1;
	for(int i = 0; i < secnum; i++) {
		if(!disk[drv]->get_sector(trk, side, i)) {
			continue;
		}
		cy = disk[drv]->id[0];
		if(disk[drv]->id[0] != id[0] || disk[drv]->id[1] != id[1] || disk[drv]->id[2] != id[2] /*|| disk[drv]->id[3] != id[3]*/) {
			continue;
		}
		// sector number is matched
		int size = 0x80 << (id[3] & 7);
		memcpy(disk[drv]->sector, buffer, __min(size, disk[drv]->sector_size.sd));
		disk[drv]->set_deleted(deleted);
		return 0;
	}
	if(cy != id[0] && cy != -1) {
		if(cy == 0xff) {
			return ST0_AT | ST1_ND | ST2_BC;
		} else {
			return ST0_AT | ST1_ND | ST2_NC;
		}
	}
	return ST0_AT | ST1_ND;
}
 inline void operator()(T val) const
 {
     static const int precision = 6;
     int zeroes = (val == 0.0f) ? 1 : -(int)floor(__min(0, log10(fabs(val))));
     std::cout << std::showpoint << std::setprecision(precision - zeroes) << (val < 0.0f ? "" : " ") << val << ", ";
 }
Example #15
0
BOOL CommonCmdHandler (
   IN  void                         *pvCmdBuf,          // Address of buffer contaiing command packet
   IN  size_t                       tCmdSize,           // Size of command packet
   OUT void                         *pvRspBuf,          // Address of buffer for response packet
   IN  size_t                       tRspSize            // Expected size of response packet
   )
{
   BOOL           bSucceeded = FALSE;     // Success indicator
   DWORD          dwCount;                // Count returned by WriteFile()/ReadFile()
   DWORD          dwStatus;               // Buffer for status codes
   int            iRetries;               // Retry counter

   // Obtain (thread) exclusive access to resources

   switch( WaitForSingleObject( hMutex, INFINITE ) )
   {
   case WAIT_ABANDONED:
   case WAIT_OBJECT_0:

      break;

   default:

      return( FALSE );
   }

   // Attach to HECI driver if we aren't already

   if( !bAttached && !AttachDriver() )
   {
      // Couldn't attach the driver...

      dwStatus = GetLastError();
   }
   else
   {
      // Attached; now have info to verify max command/response size...

      if( (tCmdSize > stProperties.minRxBufferSize) || (tRspSize > stProperties.minRxBufferSize) )
         dwStatus = ERROR_BAD_LENGTH;

      // Length ok, attempt communication...

      else
      {
         // Support retries during communication...

         for( iRetries = 0; iRetries < RETRY_COUNT; iRetries++ )
         {
            bReceivePosted = FALSE;

            // Post Receive Buffer if a response expected

            if( (tRspSize == 0) || PostReceive( pvBuffer, stProperties.minRxBufferSize ) )
            {
               // Send Command Packet

               if( DoSend( pvCmdBuf, tCmdSize ) )
               {
                  // If no response is desired, we're done!

                  if( tRspSize == 0 )
                  {
                     bSucceeded = TRUE;
                     break;
                  }

                  // Receive and process Response Packet

                  dwCount = CompleteReceive( TRUE );

                  if( dwCount )
                  {
                     // Have a response; verify it

                     if( (dwCount != tRspSize) && (CheckRspSuccess(pvBuffer)) )
                     {
                        // Data received is larger/smaller than expected

                        dwStatus = ERROR_BAD_LENGTH;
                     }
                     else
                     {
                        // Data received is right length (or QST rejected command)
                        // Place info available into caller's buffer

                        memcpy( pvRspBuf, pvBuffer, __min(dwCount, tRspSize) );
                        bSucceeded = TRUE;
                     }

                     // We're done!

                     break;
                  }
               }

               // Remember ccode from first failed operation...

               if( iRetries == 0 )
                  dwStatus = GetLastError();

               // Won't need the buffer we posted...

               if( tRspSize != 0 )
                  CancelReceive();
            }

            // A retry is necessary; recreate attachment to driver in case lost due to PM transition, etc.

            DetachDriver();

            if( !AttachDriver() )
               break;                           // Can't reattach, time to give up

            if( !AsyncDelay( RETRY_DELAY ) )    // Delay retry to give driver a break
               break;
         }
      }
   }

   ReleaseMutex( hMutex );

   if( !bSucceeded )
      SetLastError( dwStatus );       // Indicate why we're failing

   return (bSucceeded);
}
//------------------------------------------------------------------------------------------------
//  update the message from (x0,y0,plane) to the neighbors on the same plane
//    the encoding of the direction
//               2  |
//                   v
//    0 ------> <------- 1
//                   ^
//                3 |
//------------------------------------------------------------------------------------------------
void BPFlow::UpdateSpatialMessage(int x, int y, int plane, int direction)
{
	// eliminate impossible messages
	if (direction==0 && x==Width-1)
		return;
	if (direction==1 && x==0)
		return;
	if (direction==2 && y==Height-1)
		return;
	if (direction==3 && y==0)
		return;

	int offset=y*Width+x;
	int nStates=pWinSize[plane][offset]*2+1;

			

	T_message* message_org;
   	message_org=new T_message[nStates];

	int x1=x,y1=y; // get the destination
	switch(direction){
		case 0:
			x1++;
			s=Im_s.data()[offset*2+plane];
			d=Im_d.data()[offset*2+plane];
			break;
		case 1:
			x1--;
			s=Im_s.data()[(offset-1)*2+plane];
			d=Im_d.data()[(offset-1)*2+plane];
			break;
		case 2:
			y1++;
			s=Im_s.data()[offset*2+plane];
			d=Im_d.data()[offset*2+plane];
			break;
		case 3:
			y1--;
			s=Im_s.data()[(offset-Width)*2+plane];
			d=Im_d.data()[(offset-Width)*2+plane];
			break;
	}
	//s=m_s;
	//d=m_d;
	int offset1=y1*Width+x1;
	int nStates1=pWinSize[plane][offset1]*2+1; // get the number of states for the destination node
	int wsize=pWinSize[plane][offset];
	int wsize1=pWinSize[plane][offset1];

	T_message*& message=pSpatialMessage[plane][offset1*nNeighbors+direction].data();

	// initialize the message from the dual plane
	if(!IsTRW)
		memcpy(message_org,pDualMessage[plane][offset].data(),sizeof(T_message)*nStates);
	else
	{
		memset(message_org,0,sizeof(T_message)*nStates);
		Add2Message(message_org,pDualMessage[plane][offset].data(),nStates,CTRW);
	}

	// add the range term
	if(!IsTRW)
		Add2Message(message_org,pRangeTerm[plane][offset].data(),nStates);
	else
		Add2Message(message_org,pRangeTerm[plane][offset].data(),nStates,CTRW);
	
	// add spatial messages
	if(!IsTRW)
	{
		if(x>0 && direction!=1) // add left to right
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors].data(),nStates);
		if(x<Width-1 && direction!=0) // add right to left 
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+1].data(),nStates);
		if(y>0 && direction!=3) // add top down
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+2].data(),nStates);
		if(y<Height-1 && direction!=2) // add bottom up
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+3].data(),nStates);
	}
	else
	{
		if(x>0) // add left to right
			if(direction==1)
				Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors].data(),nStates,CTRW-1);
			else
				Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors].data(),nStates,CTRW);
		if(x<Width-1) // add right to left 
			if(direction==0)
				Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+1].data(),nStates,CTRW-1);
			else
				Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+1].data(),nStates,CTRW);
		if(y>0) // add top down
			if(direction==3)
				Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+2].data(),nStates,CTRW-1);
			else
				Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+2].data(),nStates,CTRW);
		if(y<Height-1) // add bottom up
			if(direction==2)
				Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+3].data(),nStates,CTRW-1);
			else
				Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+3].data(),nStates,CTRW);
	}
	// use distance transform function to impose smoothness compatibility
	T_message Min=CStochastic::Min(nStates,message_org)+d;
	for(ptrdiff_t l=1;l<nStates;l++)
		message_org[l]=__min(message_org[l],message_org[l-1]+s);
	for(ptrdiff_t l=nStates-2;l>=0;l--)
		message_org[l]=__min(message_org[l],message_org[l+1]+s);


	// transform the compatibility 
	int shift=pOffset[plane][offset1]-pOffset[plane][offset];
	if(abs(shift)>wsize+wsize1) // the shift is too big that there is no overlap
	{
		if(offset>0)
			for(ptrdiff_t l=0;l<nStates1;l++)
				message[l]=l*s;
		else
			for(ptrdiff_t l=0;l<nStates1;l++)
				message[l]=-l*s;
	}
	else
	{
		int start=__max(-wsize,shift-wsize1);
		int end=__min(wsize,shift+wsize1);
		for(ptrdiff_t i=start;i<=end;i++)
			message[i-shift+wsize1]=message_org[i+wsize];
		if(start-shift+wsize1>0)
			for(ptrdiff_t i=start-shift+wsize1-1;i>=0;i--)
				message[i]=message[i+1]+s;
		if(end-shift+wsize1<nStates1)
			for(ptrdiff_t i=end-shift+wsize1+1;i<nStates1;i++)
				message[i]=message[i-1]+s;
	}

	// put back the threshold
	for(ptrdiff_t l=0;l<nStates1;l++)
		message[l]=__min(message[l],Min);

	// normalize the message by subtracting the minimum value
	Min=CStochastic::Min(nStates1,message);
	for(ptrdiff_t l=0;l<nStates1;l++)
		message[l]-=Min;

	delete message_org;
}
Example #17
0
int main() {
    TCAS_pFile pFile;
    TCAS_pHeader pHeader;
    TCAS_pRawChunk pRawChunk;
    pFile = (TCAS_pFile)malloc(sizeof(TCAS_File));
    memset(pFile, 0, sizeof(TCAS_File));
    pFile->minTime = TCAS_INIT_MIN_TIME;
    pHeader = (TCAS_pHeader)malloc(sizeof(TCAS_Header));
    pRawChunk = (TCAS_pRawChunk)malloc(4 * sizeof(TCAS_RawChunk));
    pRawChunk[0].startTime = 0;
    pRawChunk[0].endTime = 100;
    pRawChunk[0].frameType = 0;
    pRawChunk[0].layer = 5;
    pRawChunk[0].posX = 100;
    pRawChunk[0].posY = 100;
    pRawChunk[0].r = (tcas_byte)1;
    pRawChunk[0].g = (tcas_byte)2;
    pRawChunk[0].b = (tcas_byte)3;
    pRawChunk[0].a = (tcas_byte)4;
    pFile->minTime = __min(pFile->minTime, pRawChunk[0].startTime);
    pFile->maxTime = __max(pFile->maxTime, pRawChunk[0].endTime);
    pFile->chunks ++;
    pRawChunk[1].startTime = 200;
    pRawChunk[1].endTime = 300;
    pRawChunk[1].frameType = 0;
    pRawChunk[1].layer = 1;
    pRawChunk[1].posX = 200;
    pRawChunk[1].posY = 100;
    pRawChunk[1].r = (tcas_byte)5;
    pRawChunk[1].g = (tcas_byte)6;
    pRawChunk[1].b = (tcas_byte)7;
    pRawChunk[1].a = (tcas_byte)8;
    pFile->minTime = __min(pFile->minTime, pRawChunk[1].startTime);
    pFile->maxTime = __max(pFile->maxTime, pRawChunk[1].endTime);
    pFile->chunks ++;
    pRawChunk[2].startTime = 400;
    pRawChunk[2].endTime = 500;
    pRawChunk[2].frameType = 0;
    pRawChunk[2].layer = 3;
    pRawChunk[2].posX = 100;
    pRawChunk[2].posY = 200;
    pRawChunk[2].r = (tcas_byte)1;
    pRawChunk[2].g = (tcas_byte)2;
    pRawChunk[2].b = (tcas_byte)3;
    pRawChunk[2].a = (tcas_byte)4;
    pFile->minTime = __min(pFile->minTime, pRawChunk[2].startTime);
    pFile->maxTime = __max(pFile->maxTime, pRawChunk[2].endTime);
    pFile->chunks ++;
    pRawChunk[3].startTime = 400;
    pRawChunk[3].endTime = 500;
    pRawChunk[3].frameType = 0;
    pRawChunk[3].layer = 3;
    pRawChunk[3].posX = 200;
    pRawChunk[3].posY = 200;
    pRawChunk[3].r = (tcas_byte)1;
    pRawChunk[3].g = (tcas_byte)2;
    pRawChunk[3].b = (tcas_byte)3;
    pRawChunk[3].a = (tcas_byte)4;
    pFile->minTime = __min(pFile->minTime, pRawChunk[3].startTime);
    pFile->maxTime = __max(pFile->maxTime, pRawChunk[3].endTime);
    pFile->chunks ++;
    libtcas_open_file(pFile, "test_raw.tcas", tcas_file_create_new);
    libtcas_set_file_position_indicator(pFile, tcas_fpi_header);
    libtcas_write_raw_chunks(pFile, pRawChunk, 4);
    libtcas_set_header(pHeader, TCAS_FILE_TYPE_RAW, 0, 640, 480, pFile->minTime, pFile->maxTime, pFile->chunks, 1, 1);
    libtcas_write_header(pFile, pHeader, tcas_false);
    libtcas_close_file(pFile);
    free(pRawChunk);
    free(pHeader);
    free(pFile);
    return 0;
}
//------------------------------------------------------------------------------------------------
// update dual message passing from one plane to the other
//------------------------------------------------------------------------------------------------
void BPFlow::UpdateDualMessage(int x, int y, int plane)
{
	int offset=y*Width+x;
	int offset1=offset;
	int wsize=pWinSize[plane][offset];
	int nStates=wsize*2+1;
	int wsize1=pWinSize[1-plane][offset];
	int nStates1=wsize1*2+1;

	s=Im_s.data()[offset*2+plane];
	d=Im_d.data()[offset*2+plane];
	//s=m_s;
	//d=m_d;

	T_message* message_org;
	message_org=new T_message[nStates];
	memset(message_org,0,sizeof(T_message)*nStates);
	
	// add the range term
	if(!IsTRW)
		Add2Message(message_org,pRangeTerm[plane][offset].data(),nStates);
	else
		Add2Message(message_org,pRangeTerm[plane][offset].data(),nStates,CTRW);

	// add spatial messages
	if(x>0)  //add left to right
	{
		if(!IsTRW)
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors].data(),nStates);
		else
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors].data(),nStates,CTRW);
	}
	if(x<Width-1) // add right to left
	{
		if(!IsTRW)
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+1].data(),nStates);
		else
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+1].data(),nStates,CTRW);
	}
	if(y>0) // add top down
	{
		if(!IsTRW)
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+2].data(),nStates);
		else
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+2].data(),nStates,CTRW);
	}
	if(y<Height-1) // add bottom up
	{
		if(!IsTRW)
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+3].data(),nStates);
		else
			Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+2].data(),nStates,CTRW);
	}

	if(IsTRW)
		Add2Message(message_org,pDualMessage[plane][offset1].data(),nStates,CTRW-1);

	T_message*& message=pDualMessage[1-plane][offset1].data();

	T_message Min;
	// use the data term
	if(plane==0) // from vx plane to vy plane
		for(size_t l=0;l<nStates1;l++)
			message[l]=CStochastic::Min(nStates,pDataTerm[offset].data()+l*nStates,message_org);
	else					// from vy plane to vx plane
		for(size_t l=0;l<nStates1;l++)
		{
			Min=message_org[0]+pDataTerm[offset].data()[l];
			for(size_t h=0;h<nStates;h++)
				Min=__min(Min,message_org[h]+pDataTerm[offset].data()[h*nStates1+l]);
			message[l]=Min;
		}

	// normalize the message
	Min=CStochastic::Min(nStates1,message);
	for(size_t l=0;l<nStates;l++)
		message[l]-=Min;

	delete message_org;
}
//游戏结束
bool __cdecl CTableFrameSink::OnEventGameEnd( WORD wChairID, IServerUserItem * pIServerUserItem, BYTE cbReason )
{
	switch ( cbReason )
	{
	case GER_DISMISS:		//游戏解散
		{
			//效验参数
			ASSERT( pIServerUserItem != NULL );
			ASSERT( wChairID < m_wPlayerCount );

			//构造数据
			CMD_S_GameEnd GameEnd;
			memset( &GameEnd, 0, sizeof( GameEnd ) );

			//剩余扑克
			BYTE bCardPos = 0;
			for ( WORD i = 0; i < m_wPlayerCount; i++ )
			{
				GameEnd.bCardCount[ i ] = m_bCardCount[ i ];
				CopyMemory( &GameEnd.bCardData[ bCardPos ], m_bHandCardData[ i ], m_bCardCount[ i ] * sizeof( BYTE ) );
				bCardPos += m_bCardCount[ i ];
			}

			//发送信息
			m_pITableFrame->SendTableData( INVALID_CHAIR, SUB_S_GAME_END, &GameEnd, sizeof( GameEnd ) );
			m_pITableFrame->SendLookonData( INVALID_CHAIR, SUB_S_GAME_END, &GameEnd, sizeof( GameEnd ) );

			//结束游戏
			m_pITableFrame->ConcludeGame();

			return true;
		}
	case GER_NORMAL:		//常规结束
		{
			//定义变量
			CMD_S_GameEnd GameEnd;
			ZeroMemory( &GameEnd, sizeof( GameEnd ) );

			//剩余扑克
			BYTE bCardPos = 0;
			for ( WORD i = 0; i < m_wPlayerCount; i++ )
			{
				GameEnd.bCardCount[ i ] = m_bCardCount[ i ];
				CopyMemory( &GameEnd.bCardData[ bCardPos ], m_bHandCardData[ i ], m_bCardCount[ i ] * sizeof( BYTE ) );
				bCardPos += m_bCardCount[ i ];
			}

			//变量定义
			LONG lCellScore = m_pGameServiceOption->lCellScore;
			bool bLandWin = ( m_bCardCount[ m_wBankerUser ] == 0 ) ? true : false;

			//春天判断
			if ( wChairID == m_wBankerUser )
			{
				WORD wUser1 = ( m_wBankerUser + 1 ) % GAME_PLAYER;
				WORD wUser2 = ( m_wBankerUser + 2 ) % GAME_PLAYER;
				if ( ( m_bOutCardCount[ wUser1 ] == 0 ) && ( m_bOutCardCount[ wUser2 ] == 0 ) ) m_wBombTime *= 2;
			}
			else
			{
				if ( m_bOutCardCount[ m_wBankerUser ] == 1 ) m_wBombTime *= 2;
			}

			//炸弹限制
			m_wBombTime = __min( m_wBombTime, 16 );
			
			//游戏积分
			LONG lScore=0;
			LONG lRevenue=0;
			enScoreKind ScoreKind;

			//统计积分
			for ( WORD i = 0; i < m_wPlayerCount; i++ )
			{

				lScore=0;
				lRevenue=0;

				//统计积分
				if ( i == m_wBankerUser )
				{
					lScore = m_wBombTime * m_bLandScore * lCellScore * ( ( bLandWin == true ) ? 2 : -2 );
					GameEnd.lGameScore[ i ] = m_wBombTime * m_bLandScore * lCellScore * ( ( bLandWin == true ) ? 2 : -2 );
				}
				else 
				{
					lScore = m_wBombTime * m_bLandScore * lCellScore * ( ( bLandWin == true ) ? -1 : 1 );
					GameEnd.lGameScore[ i ] = m_wBombTime * m_bLandScore * lCellScore * ( ( bLandWin == true ) ? -1 : 1 );
				}

				//胜利类型
				ScoreKind=(GameEnd.lGameScore[i]>0L)?enScoreKind_Win:enScoreKind_Lost;

				//计算税收
				if (m_pGameServiceOption->wServerType==GAME_GENRE_GOLD)
				{
					if (GameEnd.lGameScore[i]>=100L)
					{
						//计算税收
						GameEnd.lGameTax+= (GameEnd.lGameScore[i]*m_pGameServiceOption->wRevenue/1000L);
						lRevenue = (GameEnd.lGameScore[i]*m_pGameServiceOption->wRevenue/1000L);

						//积分调整
						lScore=lScore-lRevenue;
						GameEnd.lGameScore[i]=GameEnd.lGameScore[i]-lRevenue;
					}
				}

				//修改分数
				m_pITableFrame->WriteUserScore(i,lScore,lRevenue,ScoreKind);

				//历史积分
				m_HistoryScore.OnEventUserScore(i,GameEnd.lGameScore[i]);
			}

			//发送信息
			m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd));
			m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd));

			//切换用户
			m_wFirstUser=wChairID;

			//结束游戏
			m_pITableFrame->ConcludeGame();

			return true;
		}
	case GER_USER_LEFT:		//用户强退
		{
			//效验参数
			ASSERT(pIServerUserItem!=NULL);
			ASSERT(wChairID<m_wPlayerCount);

			//构造数据
			CMD_S_GameEnd GameEnd;
			ZeroMemory(&GameEnd,sizeof(GameEnd));

			//剩余扑克
			BYTE bCardPos=0;
			for (WORD i=0;i<m_wPlayerCount;i++)
			{
				GameEnd.bCardCount[i]=m_bCardCount[i];
				CopyMemory(&GameEnd.bCardData[bCardPos],m_bHandCardData[i],m_bCardCount[i]*sizeof(BYTE));
				bCardPos+=m_bCardCount[i];
			}

			//炸弹限制
			m_wBombTime=__min(m_wBombTime,16);
			m_bLandScore=__max(m_bLandScore,1);

			//修改积分
			for (WORD i=0;i<m_wPlayerCount;i++)
			{
				//游戏积分
				LONG lScore=0;
				LONG lRevenue=0;
				enScoreKind ScoreKind=enScoreKind_Draw;


				//构造变量
				if (i==wChairID)
				{
					ScoreKind=enScoreKind_Flee;
					lScore	 =-m_wBombTime*m_bLandScore*m_pGameServiceOption->lCellScore*2;
					GameEnd.lGameScore[i]=-m_wBombTime*m_bLandScore*m_pGameServiceOption->lCellScore*2;
				}
				else if (m_pGameServiceOption->wServerType==GAME_GENRE_GOLD)
				{
					//统计积分
					//ScoreKind=enScoreKind_Win;
					//lScore=(m_wBombTime*m_bLandScore*m_pGameServiceOption->lCellScore*4)/2;
					//GameEnd.lGameScore[i]=(m_wBombTime*m_bLandScore*m_pGameServiceOption->lCellScore*4)/2;

					////计算税收
					//if (lScore>=100L)
					//{
					//	//计算税收
					//	GameEnd.lGameTax+=GameEnd.lGameScore[i]*m_pGameServiceOption->cbRevenue/100L;
					//	lRevenue = GameEnd.lGameScore[i]*m_pGameServiceOption->cbRevenue/100L;

					//	//积分调整
					//	lScore=lScore-lRevenue ;
					//	GameEnd.lGameScore[i]=GameEnd.lGameScore[i]-lRevenue ;
					//}
				}

				//写入积分
				m_pITableFrame->WriteUserScore(i,lScore,lRevenue,ScoreKind);
				//历史积分
				m_HistoryScore.OnEventUserScore(i,GameEnd.lGameScore[i]);
			}

			//发送信息
			m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd));
			m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd));

			//结束游戏
			m_pITableFrame->ConcludeGame();

			return true;
		}
	}

	ASSERT(FALSE);

	return false;
}
Example #20
0
//------------------------------------------------------------------------------------------------
// function to compute data term
//------------------------------------------------------------------------------------------------
void BPFlow::ComputeDataTerm()
{
	// allocate the buffer for data term
	nTotalMatches = AllocateBuffer<PixelBuffer2D<T_message>, T_message>(pDataTerm, ptrDataTerm, WinSize);

    int XWinLength = WinSize * 2 + 1;
	T_message HistMin,HistMax;
	double HistInterval;
	double* pHistogramBuffer;
	int nBins=20000;
	int total=0; // total is the total number of plausible matches, used to normalize the histogram
	pHistogramBuffer=new double[nBins];
	memset(pHistogramBuffer,0,sizeof(double)*nBins);
	HistMin= 32767;
	HistMax=0;

	//--------------------------------------------------------------------------------------------------
	// step 1. the first sweep to compute the data term for the visible matches
	//--------------------------------------------------------------------------------------------------
    // accelerate here!
	for(ptrdiff_t i = 0; i < Height; i++)			// index over y
		for(ptrdiff_t j = 0; j < Width; j++)		// index over x
		{
			size_t index = i * Width + j;

			// loop over a local window
			for(ptrdiff_t k = -WinSize; k <= WinSize; k++)  // index over y
				for(ptrdiff_t l = -WinSize; l <= WinSize; l++)  // index over x
				{
					ptrdiff_t x = j + pOffset[0][index] + l;
					ptrdiff_t y = i + pOffset[1][index] + k;
                    ptrdiff_t index2 = y * Width2 + x;
					T_message foo = 0;
                    
					// if the point is outside the image boundary then continue
					if(!InsideImage(x, y)) continue;

                    // |S1(p) - S2(p + f(p))|
                    for(int n = 0; n < nChannels; n++)
                        foo += abs(pIm1[index * nChannels + n] - pIm2[index2 * nChannels + n]); // L1 norm
                    
					pDataTerm[index][(k + WinSize) * XWinLength + l + WinSize] = foo;
					HistMin=__min(HistMin,foo);
					HistMax=__max(HistMax,foo);
					total++;
				}
		}

	// compute the histogram info
	HistInterval=(double)(HistMax-HistMin)/nBins;

	//--------------------------------------------------------------------------------------------------
	// step 2. get the histogram of the matching
	//--------------------------------------------------------------------------------------------------
    // accelerate here!
	for(ptrdiff_t i=0;i<Height;i++)			// index over y
		for(ptrdiff_t j=0;j<Width;j++)		// index over x
		{
			size_t index=i*Width+j;

			// loop over a local window
			for(ptrdiff_t k = -WinSize; k <= WinSize; k++)  // index over y
				for(ptrdiff_t l = -WinSize; l <= WinSize; l++)  // index over x
				{
					ptrdiff_t x = j + pOffset[0][index] + l;
					ptrdiff_t y = i + pOffset[1][index] + k;

					// if the point is outside the image boundary then continue
					if(!InsideImage(x,y)) continue;
                    
					int foo = __min(pDataTerm[index][(k + WinSize) * XWinLength + l + WinSize] / HistInterval, nBins-1);
					pHistogramBuffer[foo]++;
				}
		}
    
	for(int i=0;i<nBins;i++) // normalize the histogram
		pHistogramBuffer[i] /= total;

	T_message DefaultMatchingScore;
	double Prob=0;
	for(int i=0;i<nBins;i++)
	{
		Prob+=pHistogramBuffer[i];

		if(Prob>=0.5)//(double)Area/nTotalMatches) // find the matching score
		{
			DefaultMatchingScore=__max(i,1)*HistInterval+HistMin; 
			break;
		}
	}

	if(IsDisplay)
#ifdef INTMESSAGE
		printf("Min: %d, Default: %d, Max: %d\n",HistMin,DefaultMatchingScore,HistMax);
#else
    printf("Min: %f, Default: %f, Max: %f\n",HistMin,DefaultMatchingScore,HistMax);
#endif

	//--------------------------------------------------------------------------------------------------
	// step 3. assigning the default matching score to the outside matches
	//--------------------------------------------------------------------------------------------------
    // accelerate here!
	for(ptrdiff_t i=0;i<Height;i++)			// index over y
		for(ptrdiff_t j=0;j<Width;j++)		// index over x
		{
			size_t index=i*Width+j;

			// loop over a local window
			for(ptrdiff_t k = -WinSize; k <= WinSize; k++)  // index over y
				for(ptrdiff_t l = -WinSize; l <= WinSize; l++)  // index over x
				{
					ptrdiff_t x = j + pOffset[0][index] + l;
					ptrdiff_t y = i + pOffset[1][index] + k;

                    int _ptr = (k + WinSize) * XWinLength + l + WinSize;

					// if the point is outside the image boundary then continue
					if(!InsideImage(x,y))
						pDataTerm[index][_ptr]=DefaultMatchingScore;
                    else if (IsDataTermTruncated) // put truncaitons to the data term
                        pDataTerm[index][_ptr]=__min(pDataTerm[index][_ptr],DefaultMatchingScore);
				}
		}

	delete pHistogramBuffer;
}
void CameraController::Update()
{
	if ( m_ZoomDirection == ZOOM_DIRECTION_NONE )
	{
		return;
	}

	float targetY = 0;
	float targetViewY = 0;

	switch ( m_ZoomStatus )
	{
		case ZOOM_STATUS_NEAREST:
			targetY = NEAREST_Y;
			targetViewY = NEAREST_VIEW_Y;
			break;
		case ZOOM_STATUS_DEGREE_1:
			targetY = DEGREE_1_Y;
			targetViewY = DEGREE_1_VIEW_Y;
			break;
		case ZOOM_STATUS_DEGREE_2:
			targetY = DEGREE_2_Y;
			targetViewY = DEGREE_2_VIEW_Y;
			break;
		case ZOOM_STATUS_DEGREE_3:
			targetY = DEGREE_3_Y;
			targetViewY = DEGREE_3_VIEW_Y;
			break;
		case ZOOM_STATUS_FARTHEST:
		default:
			targetY = FARTHEST_Y;
			targetViewY = FARTHEST_VIEW_Y;
			break;
	}

	float time = static_cast<float>( Timer::GetInstance()->GetElapsedTime() ) / 1000;
	float delta = time * 10.0f;

	D3DXVECTOR3 view = m_LookAtPoint - m_EyePoint;
	D3DXVec3Normalize( &view, &view );
	float	dotView = D3DXVec3Dot( &view, &( -m_UpVector ) );

	// Log( "%-8f도!!! %-8f \n", dotView, targetViewY );
	// Log( "목표 = %f, 현위치 = %f \n", targetY, m_EyePoint.y );

	// 카메라 업
	if ( m_ZoomDirection == ZOOM_DIRECTION_BACK )
	{
		if ( dotView < targetViewY )
		{
			RotateUp( delta * dotView / ( m_EyePoint.y / 10 ) );
		}

		MoveElevate( delta * 10 );
		MoveForward( -delta * 10, true );

		if ( targetY < m_EyePoint.y )
		{
			m_ZoomDirection = ZOOM_DIRECTION_NONE;
			return;
		}
	}
	// 카메라 다운
	else if ( m_ZoomDirection == ZOOM_DIRECTION_FOWARD )
	{
		if ( dotView > targetViewY )
		{
			RotateUp( -delta * dotView / ( m_EyePoint.y / 10 ) );
		}

		MoveElevate( -delta * 10 );
		MoveForward( delta * 10, true );

		if ( targetY > m_EyePoint.y )
		{
			m_ZoomDirection = ZOOM_DIRECTION_NONE;
			return;
		}
	}

	if ( m_ZoomPointX > 0 )
	{
		m_ZoomPointX = __min( m_ZoomPointX, 50 );
		m_ZoomPointX -= delta;
		MoveSide( delta );
	}
	else if ( m_ZoomPointX < 0 )
	{
		m_ZoomPointX = __max( m_ZoomPointX, -50 );
		m_ZoomPointX += delta;
		MoveSide( -delta );
	}

	if ( m_ZoomPointY > 0 )
	{
		m_ZoomPointY = __min( m_ZoomPointY, 50 );
		m_ZoomPointY -= delta;
		MoveForward( -delta );
	}
	else if ( m_ZoomPointY < 0 )
	{
		m_ZoomPointY = __max( m_ZoomPointY, -50 );
		m_ZoomPointY += delta;
		MoveForward( delta );
	}
}
Example #22
0
//------------------------------------------------------------------------------------------------
//  update the message from (x0,y0) to the neighbors
//    the encoding of the direction
//          2  |
//             v
//    0 ------> <------- 1
//             ^
//           3 |
//------------------------------------------------------------------------------------------------
void BPFlow::UpdateSpatialMessage(int x, int y, int direction)
{
	// eliminate impossible messages
	if (direction==0 && x==Width-1) return;
    
	if (direction==1 && x==0) return;
    
	if (direction==2 && y==Height-1) return;
    
	if (direction==3 && y==0) return;

	int p = y * Width + x;
    int WinLen = 2 * WinSize + 1;
	int nStates = WinLen * WinLen + 1;

	int x1 = x, y1 = y; // get the destination
	switch(direction)
    {
    case 0:
        x1++;
        break;
    case 1:
        x1--;
        break;
    case 2:
        y1++;
        break;
    case 3:
        y1--;
        break;
	}

	int q = y1 * Width + x1;

    if (!pMask1[q]) return;
    
    // init message
	T_message*& message = pSpatialMessage[q * nNeighbors + direction].data();
	T_message* message_org;
   	message_org = new T_message[nStates];

    // msg_org = dataTerm
    memset(message_org, 0, sizeof(T_message) * nStates);
    memcpy(message_org, pDataTerm[p].data(), sizeof(T_message) * (nStates - 1));

	// add the range term
    Add2Message(message_org, pRangeTerm[p].data(), nStates - 1);

	// add spatial messages
    // add m s->p where s != q 
    if(x > 0 && direction != 1 && pMask1[x - 1 + y * Width]) // add left to right
        Add2Message(message_org, pSpatialMessage[p * nNeighbors].data(), nStates);
        
    if(x < Width - 1 && direction != 0 && pMask1[x + 1 + y * Width]) // add right to left 
        Add2Message(message_org, pSpatialMessage[p * nNeighbors + 1].data(), nStates);
        
    if(y > 0 && direction != 3 && pMask1[x + (y - 1) * Width]) // add top to down
        Add2Message(message_org, pSpatialMessage[p * nNeighbors + 2].data(), nStates);
        
    if(y < Height - 1 && direction != 2 && pMask1[x + (y + 1) * Width]) // add bottom to up
        Add2Message(message_org, pSpatialMessage[p * nNeighbors + 3].data(), nStates);

    // msg_org = h(fp)
    // calculate min h(fp), fp is not empty
    T_message Min = CStochastic::Min(nStates - 1, message_org);

    // mahatton distance transformation
    // suitable for no predict flow
    int i, j, pInWin;

///*    // forward pass
    for (i = -WinSize; i <= WinSize; i++)
    {
        for (j = -WinSize; j <= WinSize; j++)
        {
            pInWin = i + WinSize + WinLen * (j + WinSize);
            if (i - 1 >= -WinSize)
            {
                message_org[pInWin] = __min(message_org[pInWin - 1] + s, message_org[pInWin]);
            }

            if (j - 1 >= -WinSize)
            {
                message_org[pInWin] = __min(message_org[pInWin - WinLen] + s, message_org[pInWin]);
            }
        }
    }

    // backward pass
    for (i = WinSize; i >= -WinSize; i--)
    {
        for (j = WinSize; j >= -WinSize; j--)
        {
            pInWin = i + WinSize + WinLen * (j + WinSize);
            if (i + 1 <= WinSize)
            {
                message_org[pInWin] = __min(message_org[pInWin + 1] + s, message_org[pInWin]);
            }

            if (j + 1 <= WinSize)
            {
                message_org[pInWin] = __min(message_org[pInWin + WinLen] + s, message_org[pInWin]);
            }
        }
    }

    for (i = 0; i < nStates - 1; i++)
    {
        message_org[i] = __min(message_org[i], Min + d);
    }
    
    memcpy(message, message_org, sizeof(T_message) * nStates);
//*/  
/*
    // brute force method for calculating min(s * |f(p) - f(q)|, d)
    T_message tmp;
    int k, l, qInWin;
    
    for (i = 0; i < nStates; i++)
        message[i] = -1;
    
    for (i = -WinSize; i <= WinSize; i++)
    {
        for (j = -WinSize; j <= WinSize; j++)
        {
            pInWin = i + WinSize + WinLen * (j + WinSize);
            for (k = -WinSize; k <= WinSize; k++)
            {
                for (l = -WinSize; l <= WinSize; l++)
                {
                    qInWin = k + WinSize + WinLen * (l + WinSize);

                    // use manhatton distance to metric distance between fp, fq
                    // min(s * (|u(p) - u(q)| + |v(p) - v(q)|), d)
                    tmp = __min((fabs(pOffset[0][p] + i - (k + pOffset[0][q])) + fabs(pOffset[1][p] + j - (l + pOffset[1][q]))) * s, d);

                    if (message[qInWin] == -1)
                        message[qInWin] = message_org[pInWin] + tmp;
                    else
                        message[qInWin] = __min(message[qInWin], message_org[pInWin] + tmp);
                }
            }
        }
    }
*/

    T_message Max = 0;
    T_message pEmpty = message_org[nStates - 1] + alphaD + alphaV;
    message[nStates - 1] = __min(Min + alphaV, pEmpty);

    for (i = 0; i < nStates - 1; i++)
        if (Max < message[i]) Max = message[i];

    // set all pixels out of mask message as maximum value
    for (int w = -WinSize; w <= WinSize; w++)
    {
        for (int h = -WinSize; h <= WinSize; h++)
        {
            int nx = x1 + w;
            int ny = y1 + h;
            int l = w + WinSize + (h + WinSize) * WinLen;
            message[l] = __min(message[l], pEmpty + pRangeTerm[p].data()[l]);
            
            if (!InsideImage(nx, ny)) continue;

            if (!pMask2[nx + ny * Width]) message[l] = Max + s * WinLen;
        }
    }
    
	// normalize the message by subtracting the minimum value
	Min = CStochastic::Min(nStates, message);
	for(int l = 0; l < nStates; l++)
		message[l] -= Min;

	delete message_org;
}
Example #23
0
BOOL bConvertOEMDevmode(
    PCOEMDEV    pOEMDevIn, 
    POEMDEV pOEMDevOut
    )

/*++

Routine Description:

    Converts private DEVMODE members to the 
    current version.

Arguments:

    pOEMDevIn - pointer to OEM private devmode
    pOEMDevOut - pointer to OEM private devmode

Return Value:

    TRUE if successful, FALSE if there is an error

--*/

{
    VERBOSE("bConvertOEMDevmode entry.");
    
    if( (NULL == pOEMDevIn)
        ||
        (NULL == pOEMDevOut)
        )
    {
        ERR("ConvertOEMDevmode() invalid parameters.\r\n");
        return FALSE;
    }

    // Check OEM Signature, if it doesn't match ours,
    // then just assume DMIn is bad and use defaults.
    if(pOEMDevIn->dmOEMExtra.dwSignature == pOEMDevOut->dmOEMExtra.dwSignature)
    {
        VERBOSE("Converting private OEM Devmode.\r\n");

        // Set the devmode defaults so that anything the isn't copied over will
        // be set to the default value.
        pOEMDevOut->dwDriverData = 0;

        // Copy the old structure in to the new using which ever size is the smaller.
        // Devmode maybe from newer Devmode (not likely since there is only one), or
        // Devmode maybe a newer Devmode, in which case it maybe larger,
        // but the first part of the structure should be the same.

        // DESIGN ASSUMPTION: the private DEVMODE structure only gets added to;
        // the fields that are in the DEVMODE never change only new fields get added to the end.

        memcpy(pOEMDevOut, pOEMDevIn, __min(pOEMDevOut->dmOEMExtra.dwSize, pOEMDevIn->dmOEMExtra.dwSize));

        // Re-fill in the size and version fields to indicated 
        // that the DEVMODE is the current private DEVMODE version.
        pOEMDevOut->dmOEMExtra.dwSize       = sizeof(OEMDEV);
        pOEMDevOut->dmOEMExtra.dwVersion    = OEM_VERSION;
    }
    else
    {
        VERBOSE("Unknown DEVMODE signature, pOEMDMIn ignored.\r\n");

        // Don't know what the input DEVMODE is, so just use defaults.
        pOEMDevOut->dmOEMExtra.dwSize       = sizeof(OEMDEV);
        pOEMDevOut->dmOEMExtra.dwSignature  = OEM_SIGNATURE;
        pOEMDevOut->dmOEMExtra.dwVersion    = OEM_VERSION;
        pOEMDevOut->dwDriverData            = 0;
    }

    return TRUE;
}
Example #24
0
//------------------------------------------------------------------------------------------------
// function to get energy
//------------------------------------------------------------------------------------------------
double BPFlow::GetEnergy()
{
	double energy = 0;
    int p, q, emptyState, WinLen;
    int pXWinOffset, pYWinOffset, qXWinOffset, qYWinOffset;

    // min (a * |f(p) - f(q)|, d)
    WinLen = WinSize * 2 + 1;
    emptyState = WinLen * WinLen;
	for(int i = 0; i < Height; i++)
    {
		for(int j = 0; j < Width; j++)
		{
			p = i * Width + j;

            if (!pMask1[p]) continue;
            
            // calculate Vp,q
            if(j < Width-1)
            {
                q = p + 1;

                if (pMask1[q])
                {
                    // f(p) or f(q) is empty
                    if (pX[p] == emptyState || pX[q] == emptyState)
                        energy += alphaV;
                    else
                    {
                        pXWinOffset = pX[p] % WinLen + pOffset[0][p] - WinSize;
                        pYWinOffset = pX[p] / WinLen + pOffset[1][p] - WinSize;
                        qXWinOffset = pX[q] % WinLen + pOffset[0][q] - WinSize;
                        qYWinOffset = pX[q] / WinLen + pOffset[1][q] - WinSize;
                    
                        energy = energy + __min((fabs(pXWinOffset - qXWinOffset) + fabs(pYWinOffset - qYWinOffset)) * s, d);
                    }
                }
            }
                
            if(i<Height-1)
            {
                q = p + Width;

                if (pMask1[q])
                {
                    if (pX[p] == emptyState || pX[q] == emptyState)
                        energy += alphaV;
                    else
                    {
                        pXWinOffset = pX[p] % WinLen + pOffset[0][p] - WinSize;
                        pYWinOffset = pX[p] / WinLen + pOffset[1][p] - WinSize;
                        qXWinOffset = pX[q] % WinLen + pOffset[0][q] - WinSize;
                        qYWinOffset = pX[q] / WinLen + pOffset[1][q] - WinSize;
                    
                        energy = energy + __min((fabs(pXWinOffset - qXWinOffset) + fabs(pYWinOffset - qYWinOffset)) * s, d);
                    }
                }
            }
                
            if (pX[p] == emptyState) energy += alphaD;
            else
            {
                energy += pDataTerm[p].data()[pX[p]];
                energy += pRangeTerm[p].data()[pX[p]];
            }
		}
    }
    
	return energy;
}
Example #25
0
VOID near TextFlow::add_width_refresh_extent(
	FramePtr frame, LINE_PTR lp,
	PCOORD xmin, PCOORD xmax,
	REFRESH_TYPE refresh_type)
{
	if (want_refresh && database->can_refresh())
	{
		PBOX pbox, bound = frame->get_bound();
		PCOORD baseline;
		FLAGS object_flags = frame_object->get_flags();

		if (object_flags & OBJECT_FLAG_xflipped)
		{
			pbox.x0 = bound.x1 - xmax;
			pbox.x1 = bound.x1 - xmin;
		}
		else
		{
			pbox.x0 = bound.x0 + xmin;
			pbox.x1 = bound.x0 + xmax;
		}

		if (pbox.x0 >= pbox.x1)
		{
			/* Null box */
			return;
		}
#if 0
printf("WR: %c%ld %ld%c\n",
 refresh_type == REFRESH_ERASE ? '(' : '[',
 pbox.x0,
 pbox.x1,
 refresh_type == REFRESH_ERASE ? ')' : ']');
#endif
#if 0
	/* Allow for pixels added by hinting and by clear-out */
		pbox.x0 -= 2*redisplay_x_pixel;
		pbox.x1 += 2*redisplay_x_pixel;
#endif

		baseline = lp->baseline;

		pbox.y0 =  baseline - lp->ascend /*- 2*redisplay_y_pixel*/;
		pbox.y1 = baseline + lp->descend /*+ 2*redisplay_y_pixel*/;

		pbox.y0 = __max(pbox.y0, 0);
		pbox.y1 = __min(pbox.y1, bound.y1-bound.y0);

		if (object_flags & OBJECT_FLAG_yflipped)
		{
			PCOORD y0 = pbox.y0;
			pbox.y0 = bound.y1 - pbox.y1;
			pbox.y1 = bound.y1 - y0;
		}
		else
		{
			pbox.y0 += bound.y0;
			pbox.y1 += bound.y0;
		}

RECT rExtraPixels;
SetRect(&rExtraPixels, 2, 2, 2, 2);
		database->do_refresh_notify(&pbox, refresh_type, frame_object, &rExtraPixels);
	}
}
Example #26
0
void ARX_GLOBALMODS_Apply()
{
	if (EDITMODE) return;

	float baseinc = _framedelay;
	float incdiv1000 = _framedelay * DIV1000;

	if (desired.flags & GMOD_ZCLIP)
	{
		current.zclip = Approach(current.zclip, desired.zclip, baseinc * 2);
	}
	else // return to default...
	{
		desired.zclip = current.zclip = Approach(current.zclip, DEFAULT_ZCLIP, baseinc * 2);
	}

	// Now goes for RGB mods
	if (desired.flags & GMOD_DCOLOR)
	{
		current.depthcolor.r = Approach(current.depthcolor.r, desired.depthcolor.r, incdiv1000);
		current.depthcolor.g = Approach(current.depthcolor.g, desired.depthcolor.g, incdiv1000);
		current.depthcolor.b = Approach(current.depthcolor.b, desired.depthcolor.b, incdiv1000);
	}
	else
	{
		current.depthcolor.r = Approach(current.depthcolor.r, 0, incdiv1000);
		current.depthcolor.g = Approach(current.depthcolor.g, 0, incdiv1000);
		current.depthcolor.b = Approach(current.depthcolor.b, 0, incdiv1000);
	}

	ModeLight &= ~MODE_DEPTHCUEING;

	if (pMenuConfig)
	{
		float fZclipp = ((((float)pMenuConfig->iFogDistance) * 1.2f) * (DEFAULT_ZCLIP - DEFAULT_MINZCLIP) / 10.f) + DEFAULT_MINZCLIP;
		fZclipp += (ACTIVECAM->focal - 310.f) * 5.f;
		SetCameraDepth(__min(current.zclip, fZclipp));
	}
	else
	{
		SetCameraDepth(current.zclip);
	}

	if (USE_D3DFOG)
	{
		D3DDEVICEDESC7 d3dDeviceDesc;
		GDevice->GetCaps(&d3dDeviceDesc);
#define PERCENT_FOG (.6f)

		ulBKGColor = D3DRGB(current.depthcolor.r, current.depthcolor.g, current.depthcolor.b);
		
		//pour compatibilité ATI, etc...
		GDevice->SetRenderState(D3DRENDERSTATE_FOGCOLOR, ulBKGColor);
		float zval;

		zval = fZFogEnd;
		float zvalstart = fZFogStart;

		if ((!pMenuConfig->bATI) &&
		        (d3dDeviceDesc.dpcTriCaps.dwRasterCaps & D3DPRASTERCAPS_FOGTABLE))
		{
			GDevice->SetRenderState(D3DRENDERSTATE_FOGVERTEXMODE,  D3DFOG_NONE);
			GDevice->SetRenderState(D3DRENDERSTATE_FOGTABLEMODE, D3DFOG_LINEAR);
			bUSE_D3DFOG_INTER = true;

			//WORLD COORDINATE
			if (d3dDeviceDesc.dpcTriCaps.dwRasterCaps & D3DPRASTERCAPS_WFOG)
			{
				zval *= ACTIVECAM->cdepth;
				zvalstart *= ACTIVECAM->cdepth;
			}
		}
		else
		{
			zval *= ACTIVECAM->cdepth;
			zvalstart *= ACTIVECAM->cdepth;

			fZFogStartWorld = zvalstart;
			fZFogEndWorld = zval; 

			GDevice->SetRenderState(D3DRENDERSTATE_FOGVERTEXMODE,  D3DFOG_LINEAR);
			GDevice->SetRenderState(D3DRENDERSTATE_FOGTABLEMODE, D3DFOG_NONE);
			bUSE_D3DFOG_INTER = false;
		}

		GDevice->SetRenderState(D3DRENDERSTATE_FOGTABLEEND,    *((LPDWORD)(&zval)));
		GDevice->SetRenderState(D3DRENDERSTATE_FOGTABLESTART,  *((LPDWORD)(&zvalstart)));
	}
	else
	{
		GDevice->SetRenderState(D3DRENDERSTATE_FOGCOLOR, D3DRGB(current.depthcolor.r, current.depthcolor.g, current.depthcolor.b));
		GDevice->SetRenderState(D3DRENDERSTATE_FOGVERTEXMODE,  D3DFOG_NONE);
		GDevice->SetRenderState(D3DRENDERSTATE_FOGTABLEMODE, D3DFOG_NONE);
	}
}
Example #27
0
ERRORCODE TextFlow::rebuild_words(DB_RECORD_NUMBER p_record,
					DB_RECORD_NUMBER f_record,
					CHARACTER_RANGE crange,
					WORD_DELTA_PTR wdelta, WORD_RANGE_PTR wrange)
{
	ParagraphPtr paragraph;
	FramePtr frame;
	W_INDEX w_index, w_start, w_end;
	TEXT_WORD_PTR wp;
	C_INDEX c_index;
	CHARACTER_PTR cp;
	ERRORCODE error;

/*
// Initialize the word delta structure first.
*/

	wrange->w_start =
		wrange->w_end =
		wdelta->w_start = -1;
	wdelta->count = 0;

/* Get the paragraph so we can operate on it. */

	if ((paragraph = (ParagraphPtr)database->get_record(p_record, &error, RECORD_TYPE_Paragraph)) == NULL)
	{
	/* Error! */
		return error;
	}

/* See if there is any text. */

	SHORT text_count = paragraph->number_of_characters();

	if (text_count == 0)
	{
	/* No text! No words to form. */
		paragraph->release();
		return ERRORCODE_None;
	}

/* Figure out where to begin forming words. */

	if (crange.c_start < 0)
	{
		crange.c_start = 0;
	}
	if (crange.c_start >= text_count)
	{
		crange.c_start = text_count-1;
	}
	if (crange.c_end < 0 || crange.c_end >= text_count)
	{
		crange.c_end = text_count-1;
	}

	if (crange.c_start > crange.c_end)
	{
	/*
 	// Huh? Bad parameters!
	// We could adjust the parameters to full extent and continue, but then
	// we might not catch a bad programming case.
	// Let's just return an error for now.
 	*/
		od("rebuild_words: bad parameters\r\n");

		paragraph->release();

		return ERRORCODE_BadParameter;
	}

/*
// The first thing we need to do is go through and figure out which words
// are going to be rebuilt. The first word to be rebuilt is the word containing
// the start change (or the previous one if it's the first character of that
// word). The c_index where word forming starts is the first character of
// this word. The last word to be rebuilt is the word containing the end
// change. The c_index where word forming stops is the last character of this
// word. These words will be deleted and rebuilt from the c_index range
// generated.
*/

/*
// A paragraph should always have at least one word (the eop word).
// OK. Here's the first problem: what happens if c_start > word(eop).c_start?
// This means that the character indicies are inconsistent. This shouldn't
// happen, so let's see if we can detect it and flag an error.
*/

/*
// Look for the word containing the start offset.
*/

	SHORT word_count = paragraph->number_of_words();

	w_start = w_end = word_count;

	for (w_index = 0, wp = (TEXT_WORD_PTR)paragraph->word.get_element(0);
						w_index < word_count;
						wp++, w_index++)
	{
		if (wp->c_start >= crange.c_start)
		{
			w_start = w_index-1;
			break;
		}
	}

	if (w_start == word_count)
	{
	/* Couldn't find the c_index in our word array. Inconsistent. */
		paragraph->release();
		od("rebuild_words: start index inconsistent\r\n");
		return ERRORCODE_BadParameter;
	}
	else if (w_start < 0)
	{
	/* Means c_start is in first word. */
		w_start = 0;
	}

#ifdef DEBUG_RW
	printf("Found start offset %d in word %d (", crange.c_start, w_start);
	dump_word(paragraph, (TEXT_WORD_PTR)paragraph->word.data + w_start);
	printf(")\n");
#endif

/* Get the first index in this word. */

	wrange->w_start =
		wrange->w_end =
		wdelta->w_start = w_start;

	if ((c_index = paragraph->get_word(w_start)->c_start) < crange.c_start)
	{
	/* Move back to start of word. */
		crange.c_start = c_index;
		wdelta->w_start++;			/* First word stays put. */
	}

#ifdef DEBUG_RW
	printf("Start offset moves to %d\n", crange.c_start);
#endif

/*
// Look for the word containing the end offset.
*/

	for (; w_index < word_count; wp++, w_index++)
	{
		if (wp->c_start >= crange.c_end)
		{
			w_end = w_index;
			break;
		}
	}

	if (w_end == word_count)
	{
	/* Couldn't find the c_index in our word array. Inconsistent. */
		paragraph->release();

		od("rebuild_words: end index inconsistent\r\n");

		return ERRORCODE_IntError;
	}
	else if (w_end == word_count-1)
	{
	/* We ended up on the eop word. Move off of it. */
		w_end--;
	}

#ifdef DEBUG_RW
	printf("Found end offset %d in word %d (", crange.c_end, w_end);
	dump_word(paragraph, (TEXT_WORD_PTR)paragraph->word.data + w_end);
	printf(")\n");
#endif

/* Get the first index of the next word. */

	if ((c_index = paragraph->get_word(w_end+1)->c_start-1) > crange.c_end)
	{
	/* Move forward to end of word. */
		crange.c_end = c_index;
	}

#ifdef DEBUG_RW
	printf("End offset moves to %d\n", crange.c_end);
#endif

/*
// Delete the existing range if we have one.
// Perhaps this should be optimized someday to do all at once!
*/
	if (w_end >= w_start)
	{
		/* Redisplay variables */
		BOOL new_line = TRUE;
		L_INDEX l_index;
		LINE_PTR lp;
		TEXT_WORD_PTR wp0;
		PCOORD erase_xmin, erase_xmax;

		if ((frame = (FramePtr)database->get_record(f_record, &error, RECORD_TYPE_Frame)) == NULL)
		{
			paragraph->release();
			return error;
		}

		/* Get line pointer for redisplay purposes */

		l_index = frame->line_of_word(w_end, NULL);

		lp = frame->get_line(l_index);

		erase_xmin = 0x7fffffff;
		erase_xmax = -erase_xmin;

		wdelta->count = -(w_end - w_start + 1);
		while (w_end >= w_start)
		{
#ifdef DEBUG_RW
			printf("Delete word %d\n", w_end);
#endif
			wp0 = paragraph->get_word(w_end);
			if (!new_line && w_end < lp->w_start)
			{
				new_line = TRUE;
				add_width_refresh_extent(frame, lp,
					erase_xmin, erase_xmax, REFRESH_ERASE);
				lp--;
			}
			if (new_line)
			{
				new_line = FALSE;

				erase_xmin = wp0->x_offset + wp0->draw_left;
				erase_xmax = wp0->x_offset + wp0->draw_width;
			}
			else
			{
				erase_xmin = __min(erase_xmin, wp0->x_offset + wp0->draw_left);
				erase_xmax = __max(erase_xmax, wp0->x_offset + wp0->draw_width);
			}

			paragraph->delete_word(w_end--);
		}
		add_width_refresh_extent(frame, lp,
				erase_xmin, erase_xmax, REFRESH_ERASE);
		frame->release();
	}

/*
// Start forming new words.
*/

	for (w_index = w_start, c_index = crange.c_start,
 					cp = paragraph->get_character(c_index);
							c_index <= crange.c_end; )
	{
		TEXT_WORD word;

	/* Start this word. */

#ifdef DEBUG_RW
		printf(*cp < ' ' ? "[%d]" : "[%c]", *cp);
#endif

		word.type = character_type(*cp++);
		word.flags = WORD_FLAG_needs_sizing;
		word.c_start = c_index++;
		word.x_offset = -1;
		word.width = 0;

	/* Accumulate the rest of the word. */

		if (word.type == WORD_TYPE_solid)
		{
		/* Search for the next word start. */

			while (c_index <= crange.c_end && character_type(*cp) == word.type)
			{
#ifdef DEBUG_RW
				printf(*cp < ' ' ? "(%d)" : "(%c)", *cp);
#endif

				cp++;
				c_index++;
			}
		}

	/* This is a whole new word. */

#ifdef DEBUG_RW
		printf(" ADD word %d, type %d, c (%d to %d) \n", w_index, word.type, word.c_start, c_index-1);
#endif
		paragraph->insert_word(w_index++, &word);

	/* Another delta in the word array. */

		wdelta->count++;
		wrange->w_end++;
	}

/* Release the paragraph. */

	paragraph->release(TRUE);

	return ERRORCODE_None;
}
Example #28
0
    const Genome *
Genome::loadFromFile(const char *fileName, unsigned i_minOffset, unsigned length)
{    
    FILE *loadFile;
    unsigned nBases,nPieces;

    if (!openFileAndGetSizes(fileName,&loadFile,&nBases,&nPieces)) {
        //
        // It already printed an error.  Just fail.
        //
        return NULL;
    }

    if (0 == length) {
        length = nBases - i_minOffset;
    } else {
        //
        // Don't let length go beyond nBases.
        //
        length = __min(length,nBases - i_minOffset);
    }

    Genome *genome = new Genome(nBases,length);
   
    genome->nBases = nBases;
    genome->nPieces = genome->maxPieces = nPieces;
    genome->pieces = new Piece[nPieces];
    genome->minOffset = i_minOffset;
    if (i_minOffset >= nBases) {
        fprintf(stderr,"Genome::loadFromFile: specified minOffset %u >= nBases %u\n",i_minOffset,nBases);
    }

 

    genome->maxOffset = i_minOffset + length;

    static const unsigned pieceNameBufferSize = 512;
    char pieceNameBuffer[pieceNameBufferSize];
    unsigned n;
    size_t pieceSize;
    char *curName;
    for (unsigned i = 0; i < nPieces; i++) {
        if (NULL == fgets(pieceNameBuffer, pieceNameBufferSize, loadFile)){
	  
	  fprintf(stderr,"Unable to read piece description\n");
            delete genome;
            return NULL;
        }

	for (n = 0; n < pieceNameBufferSize; n++){
	  if (pieceNameBuffer[n] == ' ') {
	    pieceNameBuffer[n] = '\0'; 
	    break;
	  }
	}

    genome->pieces[i].beginningOffset = atoi(pieceNameBuffer);
	pieceNameBuffer[n] = ' '; 
	n++; // increment n so we start copying at the position after the space
	pieceSize = strlen(pieceNameBuffer + n) - 1; //don't include the final \n
        genome->pieces[i].name = new char[pieceSize + 1];
	curName = genome->pieces[i].name;
	for (unsigned pos = 0; pos < pieceSize; pos++) {
	  curName[pos] = pieceNameBuffer[pos + n];
	}
        curName[pieceSize] = '\0';
    }

    //
    // Skip over the miserable \n that gets left in the file.
    //
    /*  char newline;
    if (1 != fread(&newline,1,1,loadFile)) {
        fprintf(stderr,"Genome::loadFromFile: Unable to read expected newline\n");
        delete genome;
        return NULL;
    }

    if (newline != 10) {
        fprintf(stderr,"Genome::loadFromFile: Expected newline to be 0x0a, got 0x%02x\n",newline);
        delete genome;
        return NULL;
    }
    */

    if (0 != _fseek64bit(loadFile,i_minOffset,SEEK_CUR)) {
        fprintf(stderr,"Genome::loadFromFile: _fseek64bit failed\n");
        exit(1);
    }

    if (length != fread(genome->bases,1,length,loadFile)) {
        fprintf(stderr,"Genome::loadFromFile: fread of bases failed\n");
        fclose(loadFile);
        delete genome;
        return NULL;
    }

    fclose(loadFile);
    return genome;
}
Example #29
0
template<class T> static T __min(ArrayHandle<T> ah){
    return __min(ah, 0, ah.size());
}
Example #30
0
int
ipmi_tsol_main(struct ipmi_intf * intf, int argc, char ** argv)
{
	struct pollfd fds_wait[3], fds_data_wait[3], *fds;
	struct sockaddr_in sin, myaddr, *sa_in;
	socklen_t mylen;
	char *recvip = NULL;
	char out_buff[IPMI_BUF_SIZE * 8], in_buff[IPMI_BUF_SIZE];
	char buff[IPMI_BUF_SIZE + 4];
	int fd_socket, result, i;
	int out_buff_fill, in_buff_fill;
	int ip1, ip2, ip3, ip4;
	int read_only = 0, rows = 0, cols = 0;
	int port = IPMI_TSOL_DEF_PORT;

	if (strlen(intf->name) < 3 || strncmp(intf->name, "lan", 3) != 0) {
		lprintf(LOG_ERR, "Error: Tyan SOL is only available over lan interface");
		return -1;
	}

	for (i = 0; i<argc; i++) {
		if (sscanf(argv[i], "%d.%d.%d.%d", &ip1, &ip2, &ip3, &ip4) == 4) {
			/* not free'd ...*/
			/* recvip = strdup(argv[i]); */
			recvip = argv[i];
		} 
		else if (sscanf(argv[i], "port=%d", &ip1) == 1)
			port = ip1;
		else if (sscanf(argv[i], "rows=%d", &ip1) == 1)
			rows = ip1;
		else if (sscanf(argv[i], "cols=%d", &ip1) == 1)
			cols = ip1;
		else if (strlen(argv[i]) == 2 && strncmp(argv[i], "ro", 2) == 0)
			read_only = 1;
		else if (strlen(argv[i]) == 2 && strncmp(argv[i], "rw", 2) == 0)
			read_only = 0;
		else if (strlen(argv[i]) == 7 && strncmp(argv[i], "altterm", 7) == 0)
			_altterm = 1;
		else if (strlen(argv[i]) == 4 && strncmp(argv[i], "help", 4) == 0) {
			print_tsol_usage();
			return 0;
		}
		else {
			print_tsol_usage();
			return 0;
		}
	}

	/* create udp socket to receive the packet */
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port);

	sa_in = (struct sockaddr_in *)&intf->session->addr;
	result = inet_pton(AF_INET, (const char *)intf->session->hostname,
			   &sa_in->sin_addr);

	if (result <= 0) {
		struct hostent *host = gethostbyname((const char *)intf->session->hostname);
		if (host == NULL ) {
			lprintf(LOG_ERR, "Address lookup for %s failed",
				intf->session->hostname);
			return -1;
		}
		if (host->h_addrtype != AF_INET) {
			lprintf(LOG_ERR,
					"Address lookup for %s failed. Got %s, expected IPv4 address.",
					intf->session->hostname,
					(host->h_addrtype == AF_INET6) ? "IPv6" : "Unknown");
			return (-1);
		}
		sa_in->sin_family = host->h_addrtype;
		memcpy(&sa_in->sin_addr, host->h_addr, host->h_length);
	}

	fd_socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (fd_socket < 0) {
		lprintf(LOG_ERR, "Can't open port %d", port);
		return -1;
	}
	if (-1 == bind(fd_socket, (struct sockaddr *)&sin, sizeof(sin))) {
		lprintf(LOG_ERR, "Failed to bind socket.");
		close(fd_socket);
		return -1;
	}

	/*
	 * retrieve local IP address if not supplied on command line
	 */
	if (recvip == NULL) {
		result = intf->open(intf);	/* must connect first */
		if (result < 0) {
			close(fd_socket);
			return -1;
		}

		mylen = sizeof(myaddr);
		if (getsockname(intf->fd, (struct sockaddr *)&myaddr, &mylen) < 0) {
			lperror(LOG_ERR, "getsockname failed");
			close(fd_socket);
			return -1;
		}

		recvip = inet_ntoa(myaddr.sin_addr);
		if (recvip == NULL) {
			lprintf(LOG_ERR, "Unable to find local IP address");
			close(fd_socket);
			return -1;
		}
	}

	printf("[Starting %sSOL with receiving address %s:%d]\n",
	       read_only ? "Read-only " : "", recvip, port);

	set_terminal_size(rows, cols);
	enter_raw_mode();

	/*
	 * talk to smdc to start Console redirect - IP address and port as parameter
	 * ipmitool -I lan -H 192.168.168.227 -U Administrator raw 0x30 0x06 0xC0 0xA8 0xA8 0x78 0x1A 0x0A
	 */
	result = ipmi_tsol_start(intf, recvip, port);
        if (result < 0) {
		lprintf(LOG_ERR, "Error starting SOL");
		close(fd_socket);
                return -1;
        }

	printf("[SOL Session operational.  Use %c? for help]\n",
	       intf->session->sol_escape_char);

	gettimeofday(&_start_keepalive, 0);

	fds_wait[0].fd = fd_socket;
	fds_wait[0].events = POLLIN;
	fds_wait[0].revents = 0;
	fds_wait[1].fd = fileno(stdin);
	fds_wait[1].events = POLLIN;
	fds_wait[1].revents = 0;
	fds_wait[2].fd = -1;
	fds_wait[2].events = 0;
	fds_wait[2].revents = 0;

	fds_data_wait[0].fd = fd_socket;
	fds_data_wait[0].events = POLLIN | POLLOUT;
	fds_data_wait[0].revents = 0;
	fds_data_wait[1].fd = fileno(stdin);
	fds_data_wait[1].events = POLLIN;
	fds_data_wait[1].revents = 0;
	fds_data_wait[2].fd = fileno(stdout);
	fds_data_wait[2].events = POLLOUT;
	fds_data_wait[2].revents = 0;

	out_buff_fill = 0;
	in_buff_fill = 0;
	fds = fds_wait;

	for (;;) {
		result = poll(fds, 3, 15*1000);
		if (result < 0)
			break;

		/* send keepalive packet */
		tsol_keepalive(intf);

		if ((fds[0].revents & POLLIN) && (sizeof(out_buff) > out_buff_fill)){
			socklen_t sin_len = sizeof(sin);
			result = recvfrom(fd_socket, buff, sizeof(out_buff) - out_buff_fill + 4, 0,
					  (struct sockaddr *)&sin, &sin_len);

			/* read the data from udp socket, skip some bytes in the head */
			if((result - 4) > 0 ){
				int length = result - 4;
#if 1
		 		length = (unsigned char)buff[2] & 0xff;
			       	length *= 256;
				length += ((unsigned char)buff[3] & 0xff);
				if ((length <= 0) || (length > (result - 4)))
			              length = result - 4;
#endif
				memcpy(out_buff + out_buff_fill, buff + 4, length);
				out_buff_fill += length;
			}
		}
		if ((fds[1].revents & POLLIN) && (sizeof(in_buff) > in_buff_fill)) {
			result = read(fileno(stdin), in_buff + in_buff_fill,
				      sizeof(in_buff) - in_buff_fill); // read from keyboard
			if (result > 0) {
				int bytes;
				bytes = do_inbuf_actions(intf, in_buff + in_buff_fill, result);
				if(bytes < 0) {
					result = ipmi_tsol_stop(intf, recvip, port);
					do_terminal_cleanup();
					return result;
				}
				if (read_only)
					bytes = 0;
				in_buff_fill += bytes;
			}
		}
		if ((fds[2].revents & POLLOUT) && out_buff_fill) {
			result = write(fileno(stdout), out_buff, out_buff_fill); // to screen
			if (result > 0) {
				out_buff_fill -= result;
				if (out_buff_fill) {
					memmove(out_buff, out_buff + result, out_buff_fill);
				}
			}
		}
		if ((fds[0].revents & POLLOUT) && in_buff_fill) {
			/*
			 * translate key and send that to SMDC using IPMI
			 * ipmitool -I lan -H 192.168.168.227 -U Administrator raw 0x30 0x03 0x04 0x1B 0x5B 0x43
			 */
			result = ipmi_tsol_send_keystroke(intf, in_buff, __min(in_buff_fill,14));
			if (result > 0) {
				gettimeofday(&_start_keepalive, 0);
				in_buff_fill -= result;
				if (in_buff_fill) {
					memmove(in_buff, in_buff + result, in_buff_fill);
				}
			}
		}
		fds = (in_buff_fill || out_buff_fill )?
			fds_data_wait : fds_wait;
	}

	return 0;
}