<commit_before>#include	"FTGLTextureFont.h"
#include	"FTTextureGlyph.h"
#ifdef FTGL_DEBUG
	#include "mmgr.h"
#endif

using namespace std; // for memset

inline GLuint NextPowerOf2( GLuint in)
{
     in -= 1;

     in |= in >> 16;
     in |= in >> 8;
     in |= in >> 4;
     in |= in >> 2;
     in |= in >> 1;

     return in + 1;
}

FTGLTextureFont::FTGLTextureFont()
:	maxTextSize(0),
	textureWidth(0),
	textureHeight(0),
	numTextures(0),
	textMem(0),
	glyphHeight(0),
	glyphWidth(0),
	padding(1),
	remGlyphs(0),
	xOffset(0),
	yOffset(0)
{}

FTGLTextureFont::~FTGLTextureFont()
{
	glDeleteTextures( numTextures, (const GLuint*)glTextureID);
}

FTGlyph* FTGLTextureFont::MakeGlyph( unsigned int g)
{
	FT_Glyph* ftGlyph = face.Glyph( g, FT_LOAD_NO_HINTING);

	if( ftGlyph)
	{
		// Estimate the glyph size size - global bbox
		glyphHeight = ( charSize.Height());
		glyphWidth = ( charSize.Width());

		// Is there a current texture
		if( numTextures == 0)
		{
			glTextureID[0] = CreateTexture();
			xOffset = yOffset = padding;
			++numTextures;
		}

		// will it fit in the current texture
		if( xOffset > ( textureWidth - glyphWidth))
		{
			xOffset = padding;
			yOffset += glyphHeight;

			if( yOffset > ( textureHeight - glyphHeight))
			{
				// no - make a new texture
				glTextureID[numTextures] = CreateTexture();
				yOffset = padding;
				++numTextures;
			}
		}

		// yes - load the glyph
		FTTextureGlyph* tempGlyph = new FTTextureGlyph( *ftGlyph, glTextureID[numTextures - 1],
															xOffset, yOffset, textureWidth, textureHeight);

		xOffset += tempGlyph->BBox().x2 - tempGlyph->BBox().x1 + padding;

		--remGlyphs;
//                FT_Done_Glyph( *ftGlyph );
		return tempGlyph;
	}

	err = face.Error();
	return NULL;

}

bool FTGLTextureFont::MakeGlyphList()
{
	if( !maxTextSize)
		glGetIntegerv( GL_MAX_TEXTURE_SIZE, (GLint*)&maxTextSize);

	remGlyphs = numGlyphs;

	FTFont::MakeGlyphList();

	return !err; // FIXME what err?
}

void FTGLTextureFont::GetSize()
{
	//work out the max width. Most likely maxTextSize
	textureWidth = NextPowerOf2( (remGlyphs * glyphWidth) + padding * 2);
	if( textureWidth > maxTextSize)
	{
		textureWidth = maxTextSize;
	}

	int h = static_cast<int>( (textureWidth - padding * 2) / glyphWidth);

	textureHeight = NextPowerOf2( (( numGlyphs / h) + 1) * glyphHeight);
	textureHeight = textureHeight > maxTextSize ? maxTextSize : textureHeight;
}

int FTGLTextureFont::CreateTexture()
{
	// calc the size
	GetSize();

	// allocate some mem and clear it to black
	int totalMem = textureWidth * textureHeight;
	textMem = new unsigned char[totalMem]; // GL_ALPHA texture;
	memset( textMem, 0, totalMem);

	// Create the blank texture
	int textID;
	glGenTextures( 1, (GLuint*)&textID);

	glPixelStorei( GL_UNPACK_ALIGNMENT, 1); //What does this do exactly?
	glBindTexture( GL_TEXTURE_2D, textID);
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	glTexImage2D( GL_TEXTURE_2D, 0, GL_ALPHA, textureWidth, textureHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, textMem);

	delete [] textMem;

	return textID;
}

void FTGLTextureFont::render( const char* string)
{
	glPushAttrib( GL_ENABLE_BIT | GL_HINT_BIT | GL_LINE_BIT | GL_PIXEL_MODE_BIT);

	glEnable(GL_BLEND);
 	glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE

 	FTFont::render( string);

	glPopAttrib();
}

void FTGLTextureFont::render( const wchar_t* string)
{
	glPushAttrib( GL_ENABLE_BIT | GL_HINT_BIT | GL_LINE_BIT | GL_PIXEL_MODE_BIT);

	glEnable(GL_BLEND);
 	glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE

 	FTFont::render( string);

	glPopAttrib();
}

<commit_msg>Reformatted and merged with 1.32<commit_after>#include    "FTGLTextureFont.h"
#include    "FTTextureGlyph.h"
#ifdef FTGL_DEBUG
    #include "mmgr.h"
#endif

using namespace std; // for memset

inline GLuint NextPowerOf2( GLuint in)
{
     in -= 1;

     in |= in >> 16;
     in |= in >> 8;
     in |= in >> 4;
     in |= in >> 2;
     in |= in >> 1;

     return in + 1;
}

FTGLTextureFont::FTGLTextureFont()
:   maxTextSize(0),
    textureWidth(0),
    textureHeight(0),
    numTextures(0),
    textMem(0),
    glyphHeight(0),
    glyphWidth(0),
    padding(1),
    remGlyphs(0),
    xOffset(0),
    yOffset(0)
{}

FTGLTextureFont::~FTGLTextureFont()
{
    glDeleteTextures( numTextures, (const GLuint*)glTextureID);
}

FTGlyph* FTGLTextureFont::MakeGlyph( unsigned int g)
{
    FT_Glyph* ftGlyph = face.Glyph( g, FT_LOAD_NO_HINTING);

    if( ftGlyph)
    {
        // Estimate the glyph size size - global bbox
        glyphHeight = ( charSize.Height());
        glyphWidth = ( charSize.Width());

        // Is there a current texture
        if( numTextures == 0)
        {
            glTextureID[0] = CreateTexture();
            xOffset = yOffset = padding;
            ++numTextures;
        }

        // will it fit in the current texture
        if( xOffset > ( textureWidth - glyphWidth))
        {
            xOffset = padding;
            yOffset += glyphHeight;

            if( yOffset > ( textureHeight - glyphHeight))
            {
                // no - make a new texture
                glTextureID[numTextures] = CreateTexture();
                yOffset = padding;
                ++numTextures;
            }
        }

        // yes - load the glyph
        FTTextureGlyph* tempGlyph = new FTTextureGlyph( *ftGlyph, glTextureID[numTextures - 1],
                                                            xOffset, yOffset, textureWidth, textureHeight);

        // FIXME ceiling
        xOffset += tempGlyph->BBox().x2 - tempGlyph->BBox().x1 + padding;

        --remGlyphs;
//                FT_Done_Glyph( *ftGlyph );
        return tempGlyph;
    }

    err = face.Error();
    return NULL;

}

bool FTGLTextureFont::MakeGlyphList()
{
    if( !maxTextSize)
        glGetIntegerv( GL_MAX_TEXTURE_SIZE, (GLint*)&maxTextSize);

    remGlyphs = numGlyphs;

    FTFont::MakeGlyphList();

    return !err; // FIXME what err?
}

void FTGLTextureFont::GetSize()
{
    //work out the max width. Most likely maxTextSize
    textureWidth = NextPowerOf2( (remGlyphs * glyphWidth) + padding * 2);
    if( textureWidth > maxTextSize)
    {
        textureWidth = maxTextSize;
    }

    int h = static_cast<int>( (textureWidth - padding * 2) / glyphWidth);

    textureHeight = NextPowerOf2( (( numGlyphs / h) + 1) * glyphHeight);
    textureHeight = textureHeight > maxTextSize ? maxTextSize : textureHeight;
}

int FTGLTextureFont::CreateTexture()
{
    // calc the size
    GetSize();

    // allocate some mem and clear it to black
    int totalMem = textureWidth * textureHeight;
    textMem = new unsigned char[totalMem]; // GL_ALPHA texture;
    memset( textMem, 0, totalMem);

    // Create the blank texture
    int textID;
    glGenTextures( 1, (GLuint*)&textID);

    glPixelStorei( GL_UNPACK_ALIGNMENT, 1); //What does this do exactly?
    glBindTexture( GL_TEXTURE_2D, textID);
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    glTexImage2D( GL_TEXTURE_2D, 0, GL_ALPHA, textureWidth, textureHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, textMem);

    delete [] textMem;

    return textID;
}

void FTGLTextureFont::render( const char* string)
{
    glPushAttrib( GL_ENABLE_BIT | GL_HINT_BIT | GL_LINE_BIT | GL_PIXEL_MODE_BIT);

    glEnable(GL_BLEND);
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE

    FTFont::render( string);

    glPopAttrib();
}

void FTGLTextureFont::render( const wchar_t* string)
{
    glPushAttrib( GL_ENABLE_BIT | GL_HINT_BIT | GL_LINE_BIT | GL_PIXEL_MODE_BIT);

    glEnable(GL_BLEND);
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE

    FTFont::render( string);

    glPopAttrib();
}

<|endoftext|>


<commit_before>/* DO NOT INCLUDE THIS FILE DIRECTLY
*/

#include "Typedefs.h"
#include "MyLatticePointClass.cpp"

/*
 Assume ||p1|| > ||p2||
 */
template<class ET,int nfixed>
bool check2red (GaussSieve::FastAccess_Point<ET,false,nfixed> const &p1, GaussSieve::FastAccess_Point<ET,false,nfixed> const &p2, ET & scalar, Dimension<nfixed> n)
{

    ET sc_prod, abs_2scprod;
    sc_prod= compute_sc_product(p1, p2, n);
    abs_2scprod.mul_ui(sc_prod,2);
    abs_2scprod.abs(abs_2scprod);

    // check if |2 * <p1, p2>| <= |p2|^2. If yes, no reduction
    if (abs_2scprod <= p2.norm2)
        return false;

    //compute the multiple mult s.t. res = p1 \pm mult* p2;
    //mult = round ( <p1, p2> / ||p2||^2 )
    FP_NR<double> mult, tmp;
    mult.set_z(sc_prod); //conversions
    tmp.set_z(p2.norm2);

    mult.div(mult, tmp);
    mult.rnd(mult);

    scalar.set_f(mult); //convert back

    return true;

}

template<class ET,int nfixed>
GaussSieve::FastAccess_Point<ET,false,nfixed> perform2red (GaussSieve::FastAccess_Point<ET,false,nfixed> const &p1, GaussSieve::FastAccess_Point<ET,false,nfixed> const &p2, ET const scalar, Dimension<nfixed> n)
{
    GaussSieve::FastAccess_Point<ET,false,nfixed> res (n);
    res = scalar_mult<ET,nfixed>(p2, scalar, n);
    res = sub(p1, p2, n);
    return res;
}

template<class ET, int nfixed> void Sieve<ET,false,nfixed>::sieve_2_iteration (GaussSieve::FastAccess_Point<ET,false,nfixed> &p) //note : Queue might output Approx ?
{
    int const n = get_ambient_dimension();

    if (p.get_norm2() == 0) return;
    bool loop = true;

    typename MainListType::Iterator it_comparison_flip=main_list.cend();

    ET target_scprod; //TODO: should be input to the function
    target_scprod=0.5;

    while (loop) {
        loop = false;

        typename MainListType::Iterator it =main_list.cbegin();
        for (it = main_list.cbegin(); it!=main_list.cend(); ++it)
        {
            if (p.get_norm2() < (*it).get_norm2())
            {
                it_comparison_flip = it;
                break;
            }

            ++number_of_total_scprods_level1;

            if (compare_abs_sc_product(p, *it, target_scprod, Dimension<nfixed>(n)))
            {
                ET scalar;
                if ( check2red(p, *it, scalar, Dimension<nfixed>(n)) )
                {
                         p = perform2red(p, *it, scalar, Dimension<nfixed>(n) );
                }

                loop = true;
                break;
            }

        }

    }

    if (p.get_norm2() == 0)
    {
        number_of_collisions++;
        return;
    }

    //convert to GaussList_StoredPoint first
    GaussSieve::GaussList_StoredPoint<ET, false, nfixed> p_converted (std::move(p));

    //insert the converted point into the main_list
    main_list.insert_before(it_comparison_flip, std::move(p_converted));
     ++current_list_size;

    if(update_shortest_vector_found(p))
    {
        if(verbosity>=2)
        {
            cout << "New shortest vector found. Norm2 = " << get_best_length2() << endl;
        }
    }

    for (typename MainListType::Iterator it =it_comparison_flip; it!=main_list.cend(); ++it)
    {
        if (compare_abs_sc_product(*it, p, target_scprod, Dimension<nfixed>(n)))
        {

        }

    }

    /*
    if (p.access_exact_point_r().norm2==0) return; //cerr << "Trying to reduce 0"; //TODO: Ensure sampler does not output 0 (currently, it happens).
    ApproximateLatticePoint<ET,nfixed> p_approx (p.access_approximation_r(), n); //makes a copy.
    ET p_exact_norm = p.get_exact_norm2();
    ExactLatticePoint<ET,nfixed> p_exact = p.get_exact_point();

    bool loop = true;

    ET scalar; //reduction multiple output by check2red_new

    typename MainListType::Iterator it_comparison_flip=main_list.cend(); //used to store the point where the list elements become larger than p.

    while (loop) //while p keeps changing
    {
        loop = false;
        for (auto it = main_list.cbegin(); it!=main_list.cend(); ++it)
        {
            if (p_exact_norm < it.get_true_norm2())
            {
                it_comparison_flip = it;
                break;
            }
        ++number_of_scprods;
        bool const predict =GaussSieve::compare_abs_approx_scalar_product(p_approx,*it,it->get_norm2_mantissa(), it->get_norm2_exponent() -1,n); //the -1 acts a a constant factor 1/2, related to our target scalar product.
//        bool predict = LatticeApproximations::Compare_Sc_Prod(p_approx,*it,it->get_approx_norm2(),2* it->get_length_exponent()-1,n   );
	    if(!predict) continue;

            ++number_of_exact_scprods;
            if ( GaussSieve::check2red_exact<ET,nfixed>(p_exact, it.dereference_exactly_r(), scalar) )
            {
                p = GaussSieve::perform2red_exact_to_compressed<ET,false,nfixed>(p_exact,it.dereference_exactly_r(),scalar);
                p_approx.replace_by(p.access_approximation_r(), n);
                p_exact  = p.get_exact_point();
                p_exact_norm = p_exact.norm2;
                //p = GaussSieve::perform2red(p, *(it.access_details()), scalar);
            //update the approximation of f
                //if (p.norm2!=0) p_approx = static_cast< ApproxLatticePoint<ET,false> >(p);
                loop = true;
                break;
            }
            else
            {
                ++number_of_mispredictions;
            }
        }
    }

    //p no longer changes. it_comparison_flip is iterator to first (shortest) element in the list that is longer than p.
    //If no such element exists, it_comparison_flip refers to after-the-end.

    if (p_exact_norm == 0) //essentially means that p was already inside the list.
	{
        //cout << "p has norm 2" << endl;
		number_of_collisions++;
		return;
	}

    //insert p into main_list;
    main_list.insert_before(it_comparison_flip,p.deep_copy_compressed_point()); //FIXME: This should cause an error without .deep_copy, but doesn't. Something is wrong!
    ++current_list_size;
    if(update_shortest_vector_found(p_exact))
    {
        if(verbosity>=2)
        {
            cout << "New shortest vector found. Norm2 = " << get_best_length2() << endl;
        }
    }

    for(auto it = it_comparison_flip; it!=main_list.cend(); ) //go through rest of the list.
                                                              //We know that every element current_list_point=*it is at least as long as p, so we reduce x using p.
    {
        ++number_of_scprods;
        bool const predict = GaussSieve::compare_abs_approx_scalar_product(p_approx,*it,p_approx.get_norm2_mantissa(),p_approx.get_norm2_exponent()-1,n);
        if(!predict){++it;continue;} //if prediction is bad, don't even bother to reduce.
        //We believe we can reduce *it
        ExactLatticePoint<ET,nfixed> current_list_point = it.dereference_exactly_r();
        ++number_of_exact_scprods;
        if (GaussSieve::check2red_exact(current_list_point, p_exact, scalar)) //We can reduce *it.
		{
			//create new list point
			CompressedPoint<ET,false,nfixed> reduced_point = GaussSieve::perform2red_exact_to_compressed<ET,false,nfixed>(current_list_point, p_exact, scalar);
			//if (!predict) cerr << "Misprediction 2" << endl;
			//cout << "v was found" <<  endl;

            if (reduced_point.get_exact_norm2() == 0) //Note : this cannot happen unless the list contains a non-trivial multiple of p (because the collision would have triggered before).
            {
                number_of_collisions++;
                ++it;
                continue; //was a break. Changed to ++it;continue; -- Gotti
            }

			main_queue.push(std::move(reduced_point));
			it = main_list.erase(it); //this also moves it forward
			--current_list_size;
		}
		else
		{
            ++number_of_mispredictions;
		//	prev = it1;
			++it;
		}
    }

    /* print for debugging */
    //for (it1 = main_list.begin(); it1!=main_list.end(); ++it1) {
    //	(*it1).printLatticePoint();
    //}
}
<commit_msg>convert double to ET<commit_after>/* DO NOT INCLUDE THIS FILE DIRECTLY
*/

#include "Typedefs.h"
#include "MyLatticePointClass.cpp"

/*
 Assume ||p1|| > ||p2||
 */
template<class ET,int nfixed>
bool check2red (GaussSieve::FastAccess_Point<ET,false,nfixed> const &p1, GaussSieve::FastAccess_Point<ET,false,nfixed> const &p2, ET & scalar, Dimension<nfixed> n)
{

    ET sc_prod, abs_2scprod;
    sc_prod= compute_sc_product(p1, p2, n);
    abs_2scprod.mul_ui(sc_prod,2);
    abs_2scprod.abs(abs_2scprod);

    // check if |2 * <p1, p2>| <= |p2|^2. If yes, no reduction
    if (abs_2scprod <= p2.norm2)
        return false;

    //compute the multiple mult s.t. res = p1 \pm mult* p2;
    //mult = round ( <p1, p2> / ||p2||^2 )
    FP_NR<double> mult, tmp;
    mult.set_z(sc_prod); //conversions
    tmp.set_z(p2.norm2);

    mult.div(mult, tmp);
    mult.rnd(mult);

    scalar.set_f(mult); //convert back

    return true;

}

template<class ET,int nfixed>
GaussSieve::FastAccess_Point<ET,false,nfixed> perform2red (GaussSieve::FastAccess_Point<ET,false,nfixed> const &p1, GaussSieve::FastAccess_Point<ET,false,nfixed> const &p2, ET const scalar, Dimension<nfixed> n)
{
    GaussSieve::FastAccess_Point<ET,false,nfixed> res (n);
    res = scalar_mult<ET,nfixed>(p2, scalar, n);
    res = sub(p1, p2, n);
    return res;
}

template<class ET, int nfixed> void Sieve<ET,false,nfixed>::sieve_2_iteration (GaussSieve::FastAccess_Point<ET,false,nfixed> &p) //note : Queue might output Approx ?
{
    int const n = get_ambient_dimension();

    if (p.get_norm2() == 0) return;
    bool loop = true;

    typename MainListType::Iterator it_comparison_flip=main_list.cend();

    ET target_scprod; //TODO: should be input to the function
    target_scprod=0.5;

    while (loop) {
        loop = false;

        typename MainListType::Iterator it =main_list.cbegin();
        for (it = main_list.cbegin(); it!=main_list.cend(); ++it)
        {
            if (p.get_norm2() < (*it).get_norm2())
            {
                it_comparison_flip = it;
                break;
            }

            ++number_of_total_scprods_level1;

            if (compare_abs_sc_product(p, *it, target_scprod, Dimension<nfixed>(n)))
            {
                ET scalar;
                if ( check2red(p, *it, scalar, Dimension<nfixed>(n)) )
                {
                         p = perform2red(p, *it, scalar, Dimension<nfixed>(n) );
                }

                loop = true;
                break;
            }

        }

    }

    if (p.get_norm2() == 0)
    {
        number_of_collisions++;
        return;
    }

    //convert to GaussList_StoredPoint first
    GaussSieve::GaussList_StoredPoint<ET, false, nfixed> p_converted (std::move(p));

    //insert the converted point into the main_list
    main_list.insert_before(it_comparison_flip, std::move(p_converted));
     ++current_list_size;

    if(update_shortest_vector_found(p))
    {
        if(verbosity>=2)
        {
            cout << "New shortest vector found. Norm2 = " << get_best_length2() << endl;
        }
    }

    for (typename MainListType::Iterator it =it_comparison_flip; it!=main_list.cend(); ++it)
    {

        ++number_of_total_scprods_level1;
        if (compare_abs_sc_product(*it, p, target_scprod, Dimension<nfixed>(n)))
        {
            ET scalar;
            if ( check2red(*it, p, scalar, Dimension<nfixed>(n)) )
            {
                GaussSieve::FastAccess_Point<ET,false,nfixed> v_new (n);
                v_new = perform2red(*it, p, scalar, Dimension<nfixed>(n) );

                if (v_new.get_norm2() == 0)
                {
                    number_of_collisions++;
                    ++it;
                    continue;
                }

                //TODO: Must convert to GaussQueue_DataType ??
                main_queue.push(std::move(v_new));
                it = main_list.erase(it);
                --current_list_size;
            }

        }

    }

    /*
    if (p.access_exact_point_r().norm2==0) return; //cerr << "Trying to reduce 0"; //TODO: Ensure sampler does not output 0 (currently, it happens).
    ApproximateLatticePoint<ET,nfixed> p_approx (p.access_approximation_r(), n); //makes a copy.
    ET p_exact_norm = p.get_exact_norm2();
    ExactLatticePoint<ET,nfixed> p_exact = p.get_exact_point();

    bool loop = true;

    ET scalar; //reduction multiple output by check2red_new

    typename MainListType::Iterator it_comparison_flip=main_list.cend(); //used to store the point where the list elements become larger than p.

    while (loop) //while p keeps changing
    {
        loop = false;
        for (auto it = main_list.cbegin(); it!=main_list.cend(); ++it)
        {
            if (p_exact_norm < it.get_true_norm2())
            {
                it_comparison_flip = it;
                break;
            }
        ++number_of_scprods;
        bool const predict =GaussSieve::compare_abs_approx_scalar_product(p_approx,*it,it->get_norm2_mantissa(), it->get_norm2_exponent() -1,n); //the -1 acts a a constant factor 1/2, related to our target scalar product.
//        bool predict = LatticeApproximations::Compare_Sc_Prod(p_approx,*it,it->get_approx_norm2(),2* it->get_length_exponent()-1,n   );
	    if(!predict) continue;

            ++number_of_exact_scprods;
            if ( GaussSieve::check2red_exact<ET,nfixed>(p_exact, it.dereference_exactly_r(), scalar) )
            {
                p = GaussSieve::perform2red_exact_to_compressed<ET,false,nfixed>(p_exact,it.dereference_exactly_r(),scalar);
                p_approx.replace_by(p.access_approximation_r(), n);
                p_exact  = p.get_exact_point();
                p_exact_norm = p_exact.norm2;
                //p = GaussSieve::perform2red(p, *(it.access_details()), scalar);
            //update the approximation of f
                //if (p.norm2!=0) p_approx = static_cast< ApproxLatticePoint<ET,false> >(p);
                loop = true;
                break;
            }
            else
            {
                ++number_of_mispredictions;
            }
        }
    }

    //p no longer changes. it_comparison_flip is iterator to first (shortest) element in the list that is longer than p.
    //If no such element exists, it_comparison_flip refers to after-the-end.

    if (p_exact_norm == 0) //essentially means that p was already inside the list.
	{
        //cout << "p has norm 2" << endl;
		number_of_collisions++;
		return;
	}

    //insert p into main_list;
    main_list.insert_before(it_comparison_flip,p.deep_copy_compressed_point()); //FIXME: This should cause an error without .deep_copy, but doesn't. Something is wrong!
    ++current_list_size;
    if(update_shortest_vector_found(p_exact))
    {
        if(verbosity>=2)
        {
            cout << "New shortest vector found. Norm2 = " << get_best_length2() << endl;
        }
    }

    for(auto it = it_comparison_flip; it!=main_list.cend(); ) //go through rest of the list.
                                                              //We know that every element current_list_point=*it is at least as long as p, so we reduce x using p.
    {
        ++number_of_scprods;
        bool const predict = GaussSieve::compare_abs_approx_scalar_product(p_approx,*it,p_approx.get_norm2_mantissa(),p_approx.get_norm2_exponent()-1,n);
        if(!predict){++it;continue;} //if prediction is bad, don't even bother to reduce.
        //We believe we can reduce *it
        ExactLatticePoint<ET,nfixed> current_list_point = it.dereference_exactly_r();
        ++number_of_exact_scprods;
        if (GaussSieve::check2red_exact(current_list_point, p_exact, scalar)) //We can reduce *it.
		{
			//create new list point
			CompressedPoint<ET,false,nfixed> reduced_point = GaussSieve::perform2red_exact_to_compressed<ET,false,nfixed>(current_list_point, p_exact, scalar);
			//if (!predict) cerr << "Misprediction 2" << endl;
			//cout << "v was found" <<  endl;

            if (reduced_point.get_exact_norm2() == 0) //Note : this cannot happen unless the list contains a non-trivial multiple of p (because the collision would have triggered before).
            {
                number_of_collisions++;
                ++it;
                continue; //was a break. Changed to ++it;continue; -- Gotti
            }

			main_queue.push(std::move(reduced_point));
			it = main_list.erase(it); //this also moves it forward
			--current_list_size;
		}
		else
		{
            ++number_of_mispredictions;
		//	prev = it1;
			++it;
		}
    }
     */
    // print for debugging
    //for (it1 = main_list.begin(); it1!=main_list.end(); ++it1) {
    //	(*it1).printLatticePoint();
    //}
}
<|endoftext|>


<commit_before>/*
 * Eos - A 3D Morphable Model fitting library written in modern C++11/14.
 *
 * File: examples/fit-model.cpp
 *
 * Copyright 2015 Patrik Huber
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "eos/core/Landmark.hpp"
#include "eos/core/LandmarkMapper.hpp"
#include "eos/fitting/affine_camera_estimation.hpp"
#include "eos/fitting/linear_shape_fitting.hpp"
#include "eos/render/utils.hpp"
#include "eos/render/texture_extraction.hpp"

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

#ifdef WIN32
	#define BOOST_ALL_DYN_LINK	// Link against the dynamic boost lib. Seems to be necessary because we use /MD, i.e. link to the dynamic CRT.
	#define BOOST_ALL_NO_LIB	// Don't use the automatic library linking by boost with VS2010 (#pragma ...). Instead, we specify everything in cmake.
#endif
#include "boost/program_options.hpp"
#include "boost/filesystem.hpp"

#include <vector>
#include <iostream>
#include <fstream>

using namespace eos;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
using eos::core::Landmark;
using eos::core::LandmarkCollection;
using cv::Mat;
using cv::Vec2f;
using cv::Vec3f;
using cv::Vec4f;
using std::cout;
using std::endl;
using std::vector;
using std::string;

/**
 * Reads an ibug .pts landmark file and returns an ordered vector with
 * the 68 2D landmark coordinates.
 *
 * @param[in] filename Path to a .pts file.
 * @return An ordered vector with the 68 ibug landmarks.
 */
LandmarkCollection<cv::Vec2f> read_pts_landmarks(std::string filename)
{
	using std::getline;
	using cv::Vec2f;
	using std::string;
	LandmarkCollection<Vec2f> landmarks;
	landmarks.reserve(68);

	std::ifstream file(filename);
	if (!file.is_open()) {
		throw std::runtime_error(string("Could not open landmark file: " + filename));
	}

	string line;
	// Skip the first 3 lines, they're header lines:
	getline(file, line); // 'version: 1'
	getline(file, line); // 'n_points : 68'
	getline(file, line); // '{'

	int ibugId = 1;
	while (getline(file, line))
	{
		if (line == "}") { // end of the file
			break;
		}
		std::stringstream lineStream(line);

		Landmark<Vec2f> landmark;
		landmark.name = std::to_string(ibugId);
		if (!(lineStream >> landmark.coordinates[0] >> landmark.coordinates[1])) {
			throw std::runtime_error(string("Landmark format error while parsing the line: " + line));
		}
		// From the iBug website:
		// "Please note that the re-annotated data for this challenge are saved in the Matlab convention of 1 being
		// the first index, i.e. the coordinates of the top left pixel in an image are x=1, y=1."
		// ==> So we shift every point by 1:
		landmark.coordinates[0] -= 1.0f;
		landmark.coordinates[1] -= 1.0f;
		landmarks.emplace_back(landmark);
		++ibugId;
	}
	return landmarks;
};

/**
 * This app demonstrates estimation of the camera and fitting of the shape
 * model of a 3D Morphable Model from an ibug LFPW image with its landmarks.
 *
 * First, the 68 ibug landmarks are loaded from the .pts file and converted
 * to vertex indices using the LandmarkMapper. Then, an affine camera matrix
 * is estimated, and then, using this camera matrix, the shape is fitted
 * to the landmarks.
 */
int main(int argc, char *argv[])
{
	fs::path modelfile, isomapfile, imagefile, landmarksfile, mappingsfile, outputfile;
	try {
		po::options_description desc("Allowed options");
		desc.add_options()
			("help,h",
				"display the help message")
			("model,m", po::value<fs::path>(&modelfile)->required(),
				"a Morphable Model stored as cereal BinaryArchive")
			("image,i", po::value<fs::path>(&imagefile)->required()->default_value("data/image_0001.png"),
				"an input image")
			("landmarks,l", po::value<fs::path>(&landmarksfile)->required()->default_value("data/image_0001.pts"),
				"2D landmarks for the image, in ibug .pts format")
			("mapping,p", po::value<fs::path>(&mappingsfile)->required()->default_value("../share/ibug2did.txt"),
				"landmark identifier to model vertex number mapping")
			("output,o", po::value<fs::path>(&outputfile)->required()->default_value("out"),
				"basename for the output rendering and obj files")
			;
		po::variables_map vm;
		po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
		if (vm.count("help")) {
			cout << "Usage: fit-model [options]" << endl;
			cout << desc;
			return EXIT_SUCCESS;
		}
		po::notify(vm);
	}
	catch (const po::error& e) {
		cout << "Error while parsing command-line arguments: " << e.what() << endl;
		cout << "Use --help to display a list of options." << endl;
		return EXIT_SUCCESS;
	}

	// Load the image, landmarks, LandmarkMapper and the Morphable Model:
	Mat image = cv::imread(imagefile.string());
	LandmarkCollection<cv::Vec2f> landmarks;
	try {
		landmarks = read_pts_landmarks(landmarksfile.string());
	}
	catch (const std::runtime_error& e) {
		cout << "Error reading the landmarks: " << e.what() << endl;
		return EXIT_FAILURE;
	}
	morphablemodel::MorphableModel morphable_model;
	try {
		morphable_model = morphablemodel::load_model(modelfile.string());
	}
	catch (const std::runtime_error& e) {
		cout << "Error loading the Morphable Model: " << e.what() << endl;
		return EXIT_FAILURE;
	}
	core::LandmarkMapper landmark_mapper = mappingsfile.empty() ? core::LandmarkMapper() : core::LandmarkMapper(mappingsfile);

	// Draw the loaded landmarks:
	Mat outimg = image.clone();
	for (auto&& lm : landmarks) {
		cv::rectangle(outimg, cv::Point2f(lm.coordinates[0] - 2.0f, lm.coordinates[1] - 2.0f), cv::Point2f(lm.coordinates[0] + 2.0f, lm.coordinates[1] + 2.0f), { 255, 0, 0 });
	}

	// These will be the final 2D and 3D points used for the fitting:
	vector<Vec4f> model_points; // the points in the 3D shape model
	vector<int> vertex_indices; // their vertex indices
	vector<Vec2f> image_points; // the corresponding 2D landmark points

	// Sub-select all the landmarks which we have a mapping for (i.e. that are defined in the 3DMM):
	//std::transform(begin(landmarks), end(landmarks), begin(landmarks), [&landmark_mapper](const Landmark<Vec2f>& lm) {  });
	for (int i = 0; i < landmarks.size(); ++i) {
		auto converted_name = landmark_mapper.convert(landmarks[i].name);
		if (!converted_name) { // no mapping defined for the current landmark
			continue;
		}
		int vertex_idx = std::stoi(converted_name.get());
		Vec4f vertex = morphable_model.get_shape_model().get_mean_at_point(vertex_idx);
		model_points.emplace_back(vertex);
		vertex_indices.emplace_back(vertex_idx);
		image_points.emplace_back(landmarks[i].coordinates);
	}

	// Estimate the camera from the 2D - 3D point correspondences
	Mat affine_cam = fitting::estimate_affine_camera(image_points, model_points);

	// Draw the mean-face landmarks projected using the estimated camera:
	for (auto&& vertex : model_points) {
		Vec2f screen_point(Mat(affine_cam * Mat(vertex)).at<float>(0), Mat(affine_cam * Mat(vertex)).at<float>(1));
		cv::circle(outimg, cv::Point2f(screen_point), 5, { 0.0f, 255.0f, 0.0f });
	}

	// Estimate the shape coefficients by fitting the shape to the landmarks:
	vector<float> fitted_coeffs = fitting::fit_shape_to_landmarks_linear(morphable_model, affine_cam, image_points, vertex_indices);

	// Obtain the full mesh and draw it using the estimated camera:
	render::Mesh mesh = morphable_model.draw_sample(fitted_coeffs, vector<float>());
	outputfile += fs::path(".obj");
	render::write_textured_obj(mesh, outputfile.string()); // save the mesh as obj

	// Draw the projected points again, this time using the fitted model shape:
	for (auto&& idx : vertex_indices) {
		Vec4f model_point(mesh.vertices[idx][0], mesh.vertices[idx][1], mesh.vertices[idx][2], mesh.vertices[idx][3]);
		Vec2f screen_point(Mat(affine_cam * Mat(model_point)).at<float>(0), Mat(affine_cam * Mat(model_point)).at<float>(1));
		cv::circle(outimg, cv::Point2f(screen_point), 3, { 0.0f, 0.0f, 255.0f });
	}

	// Save an output image with the landmarks from the different stages:
	//outputfile.replace_extension(".png");
	//cv::imwrite(outputfile.string(), outimg);
	outputfile.replace_extension(".png");
	cv::imwrite(outputfile.string(), outimg);

	// Extract the texture and save the extracted texture map (isomap):
	Mat isomap = render::extract_texture(mesh, affine_cam, image, render::TextureInterpolation::NearestNeighbour);
	outputfile.replace_extension(".isomap.png");
	cv::imwrite(outputfile.string(), isomap);

	cout << "Finished fitting and wrote result image and isomap " << outputfile.string() << "." << endl;

	return EXIT_SUCCESS;
}
<commit_msg>Cleaned up fit-model app: Removed the code that projects and draws the landmarks.<commit_after>/*
 * Eos - A 3D Morphable Model fitting library written in modern C++11/14.
 *
 * File: examples/fit-model.cpp
 *
 * Copyright 2015 Patrik Huber
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "eos/core/Landmark.hpp"
#include "eos/core/LandmarkMapper.hpp"
#include "eos/fitting/affine_camera_estimation.hpp"
#include "eos/fitting/linear_shape_fitting.hpp"
#include "eos/render/utils.hpp"
#include "eos/render/texture_extraction.hpp"

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

#ifdef WIN32
	#define BOOST_ALL_DYN_LINK	// Link against the dynamic boost lib. Seems to be necessary because we use /MD, i.e. link to the dynamic CRT.
	#define BOOST_ALL_NO_LIB	// Don't use the automatic library linking by boost with VS2010 (#pragma ...). Instead, we specify everything in cmake.
#endif
#include "boost/program_options.hpp"
#include "boost/filesystem.hpp"

#include <vector>
#include <iostream>
#include <fstream>

using namespace eos;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
using eos::core::Landmark;
using eos::core::LandmarkCollection;
using cv::Mat;
using cv::Vec2f;
using cv::Vec3f;
using cv::Vec4f;
using std::cout;
using std::endl;
using std::vector;
using std::string;

/**
 * Reads an ibug .pts landmark file and returns an ordered vector with
 * the 68 2D landmark coordinates.
 *
 * @param[in] filename Path to a .pts file.
 * @return An ordered vector with the 68 ibug landmarks.
 */
LandmarkCollection<cv::Vec2f> read_pts_landmarks(std::string filename)
{
	using std::getline;
	using cv::Vec2f;
	using std::string;
	LandmarkCollection<Vec2f> landmarks;
	landmarks.reserve(68);

	std::ifstream file(filename);
	if (!file.is_open()) {
		throw std::runtime_error(string("Could not open landmark file: " + filename));
	}

	string line;
	// Skip the first 3 lines, they're header lines:
	getline(file, line); // 'version: 1'
	getline(file, line); // 'n_points : 68'
	getline(file, line); // '{'

	int ibugId = 1;
	while (getline(file, line))
	{
		if (line == "}") { // end of the file
			break;
		}
		std::stringstream lineStream(line);

		Landmark<Vec2f> landmark;
		landmark.name = std::to_string(ibugId);
		if (!(lineStream >> landmark.coordinates[0] >> landmark.coordinates[1])) {
			throw std::runtime_error(string("Landmark format error while parsing the line: " + line));
		}
		// From the iBug website:
		// "Please note that the re-annotated data for this challenge are saved in the Matlab convention of 1 being
		// the first index, i.e. the coordinates of the top left pixel in an image are x=1, y=1."
		// ==> So we shift every point by 1:
		landmark.coordinates[0] -= 1.0f;
		landmark.coordinates[1] -= 1.0f;
		landmarks.emplace_back(landmark);
		++ibugId;
	}
	return landmarks;
};

/**
 * This app demonstrates estimation of the camera and fitting of the shape
 * model of a 3D Morphable Model from an ibug LFPW image with its landmarks.
 *
 * First, the 68 ibug landmarks are loaded from the .pts file and converted
 * to vertex indices using the LandmarkMapper. Then, an affine camera matrix
 * is estimated, and then, using this camera matrix, the shape is fitted
 * to the landmarks.
 */
int main(int argc, char *argv[])
{
	fs::path modelfile, isomapfile, imagefile, landmarksfile, mappingsfile, outputfile;
	try {
		po::options_description desc("Allowed options");
		desc.add_options()
			("help,h",
				"display the help message")
			("model,m", po::value<fs::path>(&modelfile)->required(),
				"a Morphable Model stored as cereal BinaryArchive")
			("image,i", po::value<fs::path>(&imagefile)->required()->default_value("data/image_0001.png"),
				"an input image")
			("landmarks,l", po::value<fs::path>(&landmarksfile)->required()->default_value("data/image_0001.pts"),
				"2D landmarks for the image, in ibug .pts format")
			("mapping,p", po::value<fs::path>(&mappingsfile)->required()->default_value("../share/ibug2did.txt"),
				"landmark identifier to model vertex number mapping")
			("output,o", po::value<fs::path>(&outputfile)->required()->default_value("out"),
				"basename for the output rendering and obj files")
			;
		po::variables_map vm;
		po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
		if (vm.count("help")) {
			cout << "Usage: fit-model [options]" << endl;
			cout << desc;
			return EXIT_SUCCESS;
		}
		po::notify(vm);
	}
	catch (const po::error& e) {
		cout << "Error while parsing command-line arguments: " << e.what() << endl;
		cout << "Use --help to display a list of options." << endl;
		return EXIT_SUCCESS;
	}

	// Load the image, landmarks, LandmarkMapper and the Morphable Model:
	Mat image = cv::imread(imagefile.string());
	LandmarkCollection<cv::Vec2f> landmarks;
	try {
		landmarks = read_pts_landmarks(landmarksfile.string());
	}
	catch (const std::runtime_error& e) {
		cout << "Error reading the landmarks: " << e.what() << endl;
		return EXIT_FAILURE;
	}
	morphablemodel::MorphableModel morphable_model;
	try {
		morphable_model = morphablemodel::load_model(modelfile.string());
	}
	catch (const std::runtime_error& e) {
		cout << "Error loading the Morphable Model: " << e.what() << endl;
		return EXIT_FAILURE;
	}
	core::LandmarkMapper landmark_mapper = mappingsfile.empty() ? core::LandmarkMapper() : core::LandmarkMapper(mappingsfile);

	// Draw the loaded landmarks:
	Mat outimg = image.clone();
	for (auto&& lm : landmarks) {
		cv::rectangle(outimg, cv::Point2f(lm.coordinates[0] - 2.0f, lm.coordinates[1] - 2.0f), cv::Point2f(lm.coordinates[0] + 2.0f, lm.coordinates[1] + 2.0f), { 255, 0, 0 });
	}

	// These will be the final 2D and 3D points used for the fitting:
	vector<Vec4f> model_points; // the points in the 3D shape model
	vector<int> vertex_indices; // their vertex indices
	vector<Vec2f> image_points; // the corresponding 2D landmark points

	// Sub-select all the landmarks which we have a mapping for (i.e. that are defined in the 3DMM):
	for (int i = 0; i < landmarks.size(); ++i) {
		auto converted_name = landmark_mapper.convert(landmarks[i].name);
		if (!converted_name) { // no mapping defined for the current landmark
			continue;
		}
		int vertex_idx = std::stoi(converted_name.get());
		Vec4f vertex = morphable_model.get_shape_model().get_mean_at_point(vertex_idx);
		model_points.emplace_back(vertex);
		vertex_indices.emplace_back(vertex_idx);
		image_points.emplace_back(landmarks[i].coordinates);
	}

	// Estimate the camera (pose) from the 2D - 3D point correspondences
	Mat affine_cam = fitting::estimate_affine_camera(image_points, model_points);

	// Estimate the shape coefficients by fitting the shape to the landmarks:
	vector<float> fitted_coeffs = fitting::fit_shape_to_landmarks_linear(morphable_model, affine_cam, image_points, vertex_indices);

	// Obtain the full mesh with the estimated coefficients:
	render::Mesh mesh = morphable_model.draw_sample(fitted_coeffs, vector<float>());

	// Extract the texture from the image using given mesh and camera parameters:
	Mat isomap = render::extract_texture(mesh, affine_cam, image);

	// Save the mesh as textured obj:
	outputfile += fs::path(".obj");
	render::write_textured_obj(mesh, outputfile.string());

	// And save the isomap:
	outputfile.replace_extension(".isomap.png");
	cv::imwrite(outputfile.string(), isomap);

	cout << "Finished fitting and wrote result mesh and isomap to files with basename " << outputfile.stem().stem() << "." << endl;

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if !defined(__LP64__)

#include <Carbon/Carbon.h>

#include "chrome/plugin/plugin_interpose_util_mac.h"
#include "ui/gfx/rect.h"
#include "webkit/plugins/npapi/carbon_plugin_window_tracker_mac.h"

#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

// Returns true if the given window is modal.
static bool IsModalWindow(WindowRef window) {
  WindowModality modality = kWindowModalityNone;
  WindowRef modal_target = NULL;
  OSStatus status = GetWindowModality(window, &modality, &modal_target);
  return (status == noErr) && (modality != kWindowModalityNone);
}

static bool IsContainingWindowActive(const OpaquePluginRef delegate) {
  return mac_plugin_interposing::GetPluginWindowHasFocus(delegate);
}

static CGRect CGRectForWindow(WindowRef window) {
  CGRect bounds = { { 0, 0 }, { 0, 0 } };
  HIWindowGetBounds(window, kWindowContentRgn, kHICoordSpace72DPIGlobal,
                    &bounds);
  return bounds;
}

struct WindowInfo {
  uint32 window_id;
  CGRect bounds;
  WindowInfo(WindowRef window) {
    window_id = HIWindowGetCGWindowID(window);
    bounds = CGRectForWindow(window);
  }
};

static void OnPluginWindowClosed(const WindowInfo& window_info) {
  mac_plugin_interposing::NotifyBrowserOfPluginHideWindow(window_info.window_id,
                                                          window_info.bounds);
}

static void OnPluginWindowShown(WindowRef window) {
  mac_plugin_interposing::NotifyBrowserOfPluginShowWindow(
      HIWindowGetCGWindowID(window), CGRectForWindow(window),
      IsModalWindow(window));
}

static void OnPluginWindowSelected(WindowRef window) {
  mac_plugin_interposing::NotifyBrowserOfPluginSelectWindow(
      HIWindowGetCGWindowID(window), CGRectForWindow(window),
      IsModalWindow(window));
}

#pragma mark -

static Boolean ChromePluginIsWindowActive(WindowRef window) {
  const OpaquePluginRef delegate =
      webkit::npapi::CarbonPluginWindowTracker::SharedInstance()->
          GetDelegateForDummyWindow(window);
  return delegate ? IsContainingWindowActive(delegate)
                  : IsWindowActive(window);
}

static Boolean ChromePluginIsWindowHilited(WindowRef window) {
  const OpaquePluginRef delegate =
      webkit::npapi::CarbonPluginWindowTracker::SharedInstance()->
          GetDelegateForDummyWindow(window);
  return delegate ? IsContainingWindowActive(delegate)
                  : IsWindowHilited(window);
}

static void ChromePluginSelectWindow(WindowRef window) {
  mac_plugin_interposing::SwitchToPluginProcess();
  SelectWindow(window);
  OnPluginWindowSelected(window);
}

static void ChromePluginShowWindow(WindowRef window) {
  mac_plugin_interposing::SwitchToPluginProcess();
  ShowWindow(window);
  OnPluginWindowShown(window);
}

static void ChromePluginDisposeWindow(WindowRef window) {
  WindowInfo window_info(window);
  DisposeWindow(window);
  OnPluginWindowClosed(window_info);
}

static void ChromePluginHideWindow(WindowRef window) {
  WindowInfo window_info(window);
  HideWindow(window);
  OnPluginWindowClosed(window_info);
}

static void ChromePluginShowHide(WindowRef window, Boolean show) {
  if (show) {
    mac_plugin_interposing::SwitchToPluginProcess();
    ShowHide(window, show);
    OnPluginWindowShown(window);
  } else {
    WindowInfo window_info(window);
    ShowHide(window, show);
    OnPluginWindowClosed(window_info);
  }
}

static void ChromePluginReleaseWindow(WindowRef window) {
  WindowInfo window_info(window);
  ReleaseWindow(window);
  OnPluginWindowClosed(window_info);
}

static void ChromePluginDisposeDialog(DialogRef dialog) {
  WindowRef window = GetDialogWindow(dialog);
  WindowInfo window_info(window);
  DisposeDialog(dialog);
  OnPluginWindowClosed(window_info);
}

static WindowPartCode ChromePluginFindWindow(Point point, WindowRef* window) {
  OpaquePluginRef delegate = mac_plugin_interposing::GetActiveDelegate();
  webkit::npapi::CarbonPluginWindowTracker* tracker =
      webkit::npapi::CarbonPluginWindowTracker::SharedInstance();
  WindowRef plugin_window = tracker->GetDummyWindowForDelegate(delegate);
  if (plugin_window) {
    // If plugin_window is non-NULL, then we are in the middle of routing an
    // event to the plugin, so we know it's destined for this window already,
    // so we don't have to worry that we'll be stealing an event meant for an
    // overlapping window.
    Rect window_bounds;
    GetWindowBounds(plugin_window, kWindowContentRgn, &window_bounds);
    if (PtInRect(point, &window_bounds)) {
      if (window)
        *window = plugin_window;
      return inContent;
    }
  }
  return FindWindow(point, window);
}

static OSStatus ChromePluginSetThemeCursor(ThemeCursor cursor) {
  OpaquePluginRef delegate = mac_plugin_interposing::GetActiveDelegate();
  if (delegate) {
    mac_plugin_interposing::NotifyPluginOfSetThemeCursor(delegate, cursor);
    return noErr;
  }
  return SetThemeCursor(cursor);
}

static void ChromePluginSetCursor(const Cursor* cursor) {
  OpaquePluginRef delegate = mac_plugin_interposing::GetActiveDelegate();
  if (delegate) {
    mac_plugin_interposing::NotifyPluginOfSetCursor(delegate, cursor);
    return;
  }
  return SetCursor(cursor);
}

#pragma mark -

struct interpose_substitution {
  const void* replacement;
  const void* original;
};

#define INTERPOSE_FUNCTION(function) \
    { reinterpret_cast<const void*>(ChromePlugin##function), \
      reinterpret_cast<const void*>(function) }

__attribute__((used)) static const interpose_substitution substitutions[]
    __attribute__((section("__DATA, __interpose"))) = {
  INTERPOSE_FUNCTION(IsWindowActive),
  INTERPOSE_FUNCTION(IsWindowHilited),
  INTERPOSE_FUNCTION(SelectWindow),
  INTERPOSE_FUNCTION(ShowWindow),
  INTERPOSE_FUNCTION(ShowHide),
  INTERPOSE_FUNCTION(DisposeWindow),
  INTERPOSE_FUNCTION(HideWindow),
  INTERPOSE_FUNCTION(ReleaseWindow),
  INTERPOSE_FUNCTION(DisposeDialog),
  INTERPOSE_FUNCTION(FindWindow),
  INTERPOSE_FUNCTION(SetThemeCursor),
  INTERPOSE_FUNCTION(SetCursor),
};

#endif  // !__LP64__
<commit_msg>Fix Mac build break<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if !defined(__LP64__)

#include <Carbon/Carbon.h>

#include "content/plugin/plugin_interpose_util_mac.h"
#include "ui/gfx/rect.h"
#include "webkit/plugins/npapi/carbon_plugin_window_tracker_mac.h"

#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

// Returns true if the given window is modal.
static bool IsModalWindow(WindowRef window) {
  WindowModality modality = kWindowModalityNone;
  WindowRef modal_target = NULL;
  OSStatus status = GetWindowModality(window, &modality, &modal_target);
  return (status == noErr) && (modality != kWindowModalityNone);
}

static bool IsContainingWindowActive(const OpaquePluginRef delegate) {
  return mac_plugin_interposing::GetPluginWindowHasFocus(delegate);
}

static CGRect CGRectForWindow(WindowRef window) {
  CGRect bounds = { { 0, 0 }, { 0, 0 } };
  HIWindowGetBounds(window, kWindowContentRgn, kHICoordSpace72DPIGlobal,
                    &bounds);
  return bounds;
}

struct WindowInfo {
  uint32 window_id;
  CGRect bounds;
  WindowInfo(WindowRef window) {
    window_id = HIWindowGetCGWindowID(window);
    bounds = CGRectForWindow(window);
  }
};

static void OnPluginWindowClosed(const WindowInfo& window_info) {
  mac_plugin_interposing::NotifyBrowserOfPluginHideWindow(window_info.window_id,
                                                          window_info.bounds);
}

static void OnPluginWindowShown(WindowRef window) {
  mac_plugin_interposing::NotifyBrowserOfPluginShowWindow(
      HIWindowGetCGWindowID(window), CGRectForWindow(window),
      IsModalWindow(window));
}

static void OnPluginWindowSelected(WindowRef window) {
  mac_plugin_interposing::NotifyBrowserOfPluginSelectWindow(
      HIWindowGetCGWindowID(window), CGRectForWindow(window),
      IsModalWindow(window));
}

#pragma mark -

static Boolean ChromePluginIsWindowActive(WindowRef window) {
  const OpaquePluginRef delegate =
      webkit::npapi::CarbonPluginWindowTracker::SharedInstance()->
          GetDelegateForDummyWindow(window);
  return delegate ? IsContainingWindowActive(delegate)
                  : IsWindowActive(window);
}

static Boolean ChromePluginIsWindowHilited(WindowRef window) {
  const OpaquePluginRef delegate =
      webkit::npapi::CarbonPluginWindowTracker::SharedInstance()->
          GetDelegateForDummyWindow(window);
  return delegate ? IsContainingWindowActive(delegate)
                  : IsWindowHilited(window);
}

static void ChromePluginSelectWindow(WindowRef window) {
  mac_plugin_interposing::SwitchToPluginProcess();
  SelectWindow(window);
  OnPluginWindowSelected(window);
}

static void ChromePluginShowWindow(WindowRef window) {
  mac_plugin_interposing::SwitchToPluginProcess();
  ShowWindow(window);
  OnPluginWindowShown(window);
}

static void ChromePluginDisposeWindow(WindowRef window) {
  WindowInfo window_info(window);
  DisposeWindow(window);
  OnPluginWindowClosed(window_info);
}

static void ChromePluginHideWindow(WindowRef window) {
  WindowInfo window_info(window);
  HideWindow(window);
  OnPluginWindowClosed(window_info);
}

static void ChromePluginShowHide(WindowRef window, Boolean show) {
  if (show) {
    mac_plugin_interposing::SwitchToPluginProcess();
    ShowHide(window, show);
    OnPluginWindowShown(window);
  } else {
    WindowInfo window_info(window);
    ShowHide(window, show);
    OnPluginWindowClosed(window_info);
  }
}

static void ChromePluginReleaseWindow(WindowRef window) {
  WindowInfo window_info(window);
  ReleaseWindow(window);
  OnPluginWindowClosed(window_info);
}

static void ChromePluginDisposeDialog(DialogRef dialog) {
  WindowRef window = GetDialogWindow(dialog);
  WindowInfo window_info(window);
  DisposeDialog(dialog);
  OnPluginWindowClosed(window_info);
}

static WindowPartCode ChromePluginFindWindow(Point point, WindowRef* window) {
  OpaquePluginRef delegate = mac_plugin_interposing::GetActiveDelegate();
  webkit::npapi::CarbonPluginWindowTracker* tracker =
      webkit::npapi::CarbonPluginWindowTracker::SharedInstance();
  WindowRef plugin_window = tracker->GetDummyWindowForDelegate(delegate);
  if (plugin_window) {
    // If plugin_window is non-NULL, then we are in the middle of routing an
    // event to the plugin, so we know it's destined for this window already,
    // so we don't have to worry that we'll be stealing an event meant for an
    // overlapping window.
    Rect window_bounds;
    GetWindowBounds(plugin_window, kWindowContentRgn, &window_bounds);
    if (PtInRect(point, &window_bounds)) {
      if (window)
        *window = plugin_window;
      return inContent;
    }
  }
  return FindWindow(point, window);
}

static OSStatus ChromePluginSetThemeCursor(ThemeCursor cursor) {
  OpaquePluginRef delegate = mac_plugin_interposing::GetActiveDelegate();
  if (delegate) {
    mac_plugin_interposing::NotifyPluginOfSetThemeCursor(delegate, cursor);
    return noErr;
  }
  return SetThemeCursor(cursor);
}

static void ChromePluginSetCursor(const Cursor* cursor) {
  OpaquePluginRef delegate = mac_plugin_interposing::GetActiveDelegate();
  if (delegate) {
    mac_plugin_interposing::NotifyPluginOfSetCursor(delegate, cursor);
    return;
  }
  return SetCursor(cursor);
}

#pragma mark -

struct interpose_substitution {
  const void* replacement;
  const void* original;
};

#define INTERPOSE_FUNCTION(function) \
    { reinterpret_cast<const void*>(ChromePlugin##function), \
      reinterpret_cast<const void*>(function) }

__attribute__((used)) static const interpose_substitution substitutions[]
    __attribute__((section("__DATA, __interpose"))) = {
  INTERPOSE_FUNCTION(IsWindowActive),
  INTERPOSE_FUNCTION(IsWindowHilited),
  INTERPOSE_FUNCTION(SelectWindow),
  INTERPOSE_FUNCTION(ShowWindow),
  INTERPOSE_FUNCTION(ShowHide),
  INTERPOSE_FUNCTION(DisposeWindow),
  INTERPOSE_FUNCTION(HideWindow),
  INTERPOSE_FUNCTION(ReleaseWindow),
  INTERPOSE_FUNCTION(DisposeDialog),
  INTERPOSE_FUNCTION(FindWindow),
  INTERPOSE_FUNCTION(SetThemeCursor),
  INTERPOSE_FUNCTION(SetCursor),
};

#endif  // !__LP64__
<|endoftext|>


<commit_before>#include "GenericSelector.h"
#include "Renderer.h"
#include "Color.h"
#include "SDL.h"
#include "TextEditor.h"
#include "Label.h"
#include "MessageBox.h"
#include <cstdio>
#include <cstring>
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>

GenericSelector::GenericSelector(EditorState& editorState)
	: Editor(editorState), mSelectedItem(0)
{
	mLabel = new Label(editorState);
	mLabel->setColor(Color(0, 0, 0));
	mLabel->setBackground(Color(255, 255, 255));
	addChild(mLabel, 0, 0, 100, 8);
	strcpy(mTitle, "");
}

GenericSelector::~GenericSelector()
{
	clearItems();
	delete mLabel;
}

void GenericSelector::selectItem(int index)
{
	mSelectedItem = index;

	if (mSelectedItem >= static_cast<int>(mItems.size()))
		mSelectedItem = static_cast<int>(mItems.size()) - 1;

	if (mSelectedItem < 0)
		mSelectedItem = 0;

	if (mItems.size() > 0)
	{
		onSelectItem(*mItems[mSelectedItem]);
	}

	setDirty(true);
}

void GenericSelector::setTitle(const char *title)
{
	strncpy(mTitle, title, titleSize);
	mLabel->setText(mTitle);
	setModal(NULL);
}

bool GenericSelector::onEvent(SDL_Event& event)
{
	if (mModal)
		return mModal->onEvent(event);

	switch (event.type)
	{
		case SDL_KEYDOWN:
			if (event.key.keysym.sym == SDLK_ESCAPE)
			{
				reject(true);
				return true;
			}

			if (event.key.keysym.sym == SDLK_RETURN)
			{
				accept(false);
				return true;
			}

			switch (event.key.keysym.sym)
			{
				case SDLK_UP:
					selectItem(mSelectedItem - 1);
					return true;

				case SDLK_DOWN:
					selectItem(mSelectedItem + 1);
					return true;
			}

			break;
	}

	return false;
}

void GenericSelector::onDraw(Renderer& renderer, const SDL_Rect& area)
{
	if (shouldRedrawBackground())
	{
		renderer.clearRect(area, Color(0, 0, 0));

		/*SDL_Rect fieldArea = { area.x, area.y + 8, area.w, renderer.getFontHeight() };

		renderer.clearRect(fieldArea, Color(255, 0, 0));*/
	}

	int countVisible = (area.h - 8 - 8 - 8) / 8;
	int firstVisible = mSelectedItem - countVisible / 2;

	if (firstVisible < 0)
	{
		firstVisible = 0;
	}

	int lastVisible = firstVisible + countVisible;

	if (lastVisible >= mItems.size())
	{
		lastVisible = mItems.size() - 1;
		firstVisible = lastVisible - countVisible;
		if (firstVisible < 0)
		{
			firstVisible = 0;
		}
	}

	for (int row = firstVisible ; row <= lastVisible ; ++row)
	{
		SDL_Rect textArea = {area.x, (row - firstVisible) * 8 + area.y + 16, area.w, 8};
		renderItem(renderer, textArea, *mItems[row], row == mSelectedItem);
	}
}

const GenericSelector::Item& GenericSelector::getSelectedItem() const
{
	return *mItems[mSelectedItem];
}

int GenericSelector::getId() const
{
	return mId;
}

void GenericSelector::setId(int id)
{
	mId = id;
}

void GenericSelector::addItem(GenericSelector::Item* newItem)
{
	mItems.push_back(newItem);
}

void GenericSelector::clearItems()
{
	mSelectedItem = 0;
	for (Item* item : mItems)
	{
		delete item;
	}
	mItems.clear();
}

void GenericSelector::sortItems(bool (*comparator)(const Item* a, const Item* b))
{
	std::sort(mItems.begin(), mItems.end(), comparator);
}

void GenericSelector::onAreaChanged(const SDL_Rect& area)
{
	SDL_Rect labelArea = mLabel->getArea();

	// Editor should handle the 2px modal margin
	labelArea.w = area.w - 4;

	mLabel->setArea(labelArea);
}
<commit_msg>Added scrollbar<commit_after>#include "GenericSelector.h"
#include "Renderer.h"
#include "Color.h"
#include "SDL.h"
#include "TextEditor.h"
#include "Label.h"
#include "MessageBox.h"
#include <cstdio>
#include <cstring>
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>

GenericSelector::GenericSelector(EditorState& editorState)
	: Editor(editorState), mSelectedItem(0)
{
	mLabel = new Label(editorState);
	mLabel->setColor(Color(0, 0, 0));
	mLabel->setBackground(Color(255, 255, 255));
	addChild(mLabel, 0, 0, 100, 8);
	strcpy(mTitle, "");
}

GenericSelector::~GenericSelector()
{
	clearItems();
	delete mLabel;
}

void GenericSelector::selectItem(int index)
{
	mSelectedItem = index;

	if (mSelectedItem >= static_cast<int>(mItems.size()))
		mSelectedItem = static_cast<int>(mItems.size()) - 1;

	if (mSelectedItem < 0)
		mSelectedItem = 0;

	if (mItems.size() > 0)
	{
		onSelectItem(*mItems[mSelectedItem]);
	}

	setDirty(true);
}

void GenericSelector::setTitle(const char *title)
{
	strncpy(mTitle, title, titleSize);
	mLabel->setText(mTitle);
	setModal(NULL);
}

bool GenericSelector::onEvent(SDL_Event& event)
{
	if (mModal)
		return mModal->onEvent(event);

	switch (event.type)
	{
		case SDL_KEYDOWN:
			if (event.key.keysym.sym == SDLK_ESCAPE)
			{
				reject(true);
				return true;
			}

			if (event.key.keysym.sym == SDLK_RETURN)
			{
				accept(false);
				return true;
			}

			switch (event.key.keysym.sym)
			{
				case SDLK_UP:
					selectItem(mSelectedItem - 1);
					return true;

				case SDLK_DOWN:
					selectItem(mSelectedItem + 1);
					return true;
			}

			break;
	}

	return false;
}

void GenericSelector::onDraw(Renderer& renderer, const SDL_Rect& area)
{
	if (shouldRedrawBackground())
	{
		renderer.clearRect(area, Color(0, 0, 0));

		/*SDL_Rect fieldArea = { area.x, area.y + 8, area.w, renderer.getFontHeight() };

		renderer.clearRect(fieldArea, Color(255, 0, 0));*/
	}

	int countVisible = (area.h - 8 - 8 - 8) / 8;
	int firstVisible = mSelectedItem - countVisible / 2;

	if (firstVisible < 0)
	{
		firstVisible = 0;
	}

	int lastVisible = firstVisible + countVisible;

	if (lastVisible >= mItems.size())
	{
		lastVisible = mItems.size() - 1;
		firstVisible = lastVisible - countVisible;
		if (firstVisible < 0)
		{
			firstVisible = 0;
		}
	}

	for (int row = firstVisible ; row <= lastVisible ; ++row)
	{
		SDL_Rect textArea = {area.x, (row - firstVisible) * 8 + area.y + 16, area.w - 4, 8};
		renderItem(renderer, textArea, *mItems[row], row == mSelectedItem);
	}

	int areaHeight = area.h - 8 - 8 - 4;
	int scrollbarTop = areaHeight * firstVisible / static_cast<int>(mItems.size());
	int scrollbarBottom = areaHeight * (lastVisible + 1) / static_cast<int>(mItems.size());
	SDL_Rect scrollbarArea = {area.x + area.w - 3, area.y + 16 + scrollbarTop, 2, scrollbarBottom - scrollbarTop};
	renderer.clearRect(scrollbarArea, Color());
}

const GenericSelector::Item& GenericSelector::getSelectedItem() const
{
	return *mItems[mSelectedItem];
}

int GenericSelector::getId() const
{
	return mId;
}

void GenericSelector::setId(int id)
{
	mId = id;
}

void GenericSelector::addItem(GenericSelector::Item* newItem)
{
	mItems.push_back(newItem);
}

void GenericSelector::clearItems()
{
	mSelectedItem = 0;
	for (Item* item : mItems)
	{
		delete item;
	}
	mItems.clear();
}

void GenericSelector::sortItems(bool (*comparator)(const Item* a, const Item* b))
{
	std::sort(mItems.begin(), mItems.end(), comparator);
}

void GenericSelector::onAreaChanged(const SDL_Rect& area)
{
	SDL_Rect labelArea = mLabel->getArea();

	// Editor should handle the 2px modal margin
	labelArea.w = area.w - 4;

	mLabel->setArea(labelArea);
}
<|endoftext|>


<commit_before>// water

#include "Water.h"
#include <math.h>
#include <string.h>

namespace tpx
{

static const double Tmn=273.16;
static const double Tmx=1600.0;
static const double M=18.016;
static const double Tc=647.286;
static const double Pc=22.089e6;
static const double Roc=317.0;
static const double To=273.16;
static const double R=461.51;
static const double E=4.8E-3;
static const double Ta=1000.0;
static const double tauc=1.544912;
static const double Tp=338.15;
static const double aww=0.01;
static const double Roa1=634.0;
static const double Roaj=1000.0;
static const double u0=2375470.875;
static const double s0=6697.356635;

static const double A[10][7]= {{
        2.9492937E-2,-5.1985860E-3,
        6.8335354E-3,-1.5641040E-4,
        -6.3972405E-3, -3.9661401E-3, -6.9048554E-4
    },
    {
        -1.3213917E-4,7.7779182E-6, -2.6149751E-5,-7.2546108E-7,
        2.6409282E-5, 1.5453061E-5,2.7407416E-6
    },
    {
        2.7464632E-7,-3.3301902E-8,6.5326396E-8,-9.2734289E-9,
        -4.7740374E-8,-2.9142470E-8,-5.1028070E-9
    },
    {
        -3.6093828E-10, -1.6254622E-11, -2.6181978E-11, 4.3125840E-12,
        5.6323130E-11, 2.9568796E-11,3.9636085E-12
    },
    {3.4218431E-13, -1.7731074E-13,0,0,0,0,0},
    {-2.4450042E-16, 1.2748742E-16,0,0,0,0,0},
    {1.5518535E-19, 1.3746153E-19,0,0,0,0,0},
    {5.9728487E-24,1.5597836E-22, 0,0,0,0,0},
    {
        -4.1030848E-1, 3.3731180E-1, -1.3746678E-1, 6.7874983E-3,
        1.3687317E-1, 7.984797E-2, 1.3041253E-2
    },
    {
        -4.1605860E-4, -2.0988866E-4,-7.3396848E-4,1.0401717E-5,
        6.4581880E-4, 3.9917570E-4, 7.1531353E-5
    }
};

static const double F[]= {-7.4192420, 2.9721E-1,-1.155286E-1,8.685635E-3,
                          1.0940980E-3, -4.39993E-3, 2.5206580E-3, -5.2186840E-4
                         };

static const double D[]= {3.6711257,-2.8512396E1,2.2265240E2,-8.8243852E2,
                          2.0002765E3,-2.6122557E3,1.8297674E3,-5.3350520E2
                         };

static const double G[]= {4.6E4,1.011249E3,8.3893E-1,-2.19989E-4,2.466619E-7,
                          -9.704700E-11
                         };

static const double taua[] = {1.544912, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5};

inline double water::C(int i)
{
    double tau = Ta/T;
    return (i == 0 ? R*T : R*T*(tau - tauc)*pow(tau - taua[i],i-1));
}

inline double water::Cprime(int i)
{
    double tau = Ta/T;
    return (i == 0 ? R : (i == 1 ? -R*tauc :
                          -R*pow(tau - taua[i],i-2)*(tauc*(tau - taua[i])
                                  + (i-1)*tau*(tau - tauc))));
}

inline double water::I(int j)
{
    double factor, sum, rho_aj;
    rho_aj = (j == 0 ? Roa1 : Roaj);
    sum = 0.0;
    factor = Rho - rho_aj;
    for (int i=7; i>0; i--) {
        sum += A[i][j];
        sum *= factor;
    }
    sum += A[0][j];
    sum += (exp(-E*Rho)*(A[8][j] + A[9][j]*Rho));
    return Rho*sum;
}

inline double water::H(int j)
{
    double factor, sum, rho_aj;
    rho_aj = (j == 0 ? Roa1 : Roaj);
    sum = 0.0;
    factor = Rho - rho_aj;
    for (int i=6; i>0; i--) {
        sum += (A[i][j] + Rho*(i+1)*A[i+1][j]);
        sum *= factor;
    }
    sum += (A[0][j] + Rho*A[1][j]);
    sum += (exp(-E*Rho)*((1.0 - Rho*E)*A[8][j]
                         + Rho*(2.0 - Rho*E)*A[9][j]));
    sum += A[7][j]*pow(factor,7);
    return Rho*Rho*sum;
}

double water::up()
{
    double sum = 0.0;
    int i;
    for (i=0; i<7; i++) {
        sum += (C(i) - T*Cprime(i))*I(i);
    }
    for (i=1; i<6; i++) {
        sum += G[i]*(pow(T,i) - pow(To,i))/double(i);
    }
    sum += G[0]*log(T/To) + u0;
    return sum + m_energy_offset;
}

double water::sp()
{
    double sum = 0.0;
    int i;
    for (i=2; i<6; i++) {
        sum += G[i]*(pow(T,i-1) - pow(To,i-1))/double(i-1);
    }
    sum += G[1]*log(T/To);
    sum -= G[0]*(1.0/T - 1.0/To);
    sum += s0 - R*log(Rho);
    for (i=0; i<7; i++) {
        sum -= Cprime(i)*I(i);
    }
    return sum + m_entropy_offset;
}

double water::Pp()
{
    double P = Rho*R*T;
    for (int i=0; i<7; i++) {
        P += C(i)*H(i);
    }
    return P;
}

double water::Psat()
{
    double log, sum=0,P;
    if ((T < Tmn) || (T > Tc)) {
        set_Err(TempError);    // Error("water::Psat",TempError,T);
    }
    for (int i=1; i<=8; i++) {
        sum += F[i-1]*pow(aww*(T-Tp),double(i-1));    // DGG mod
    }
    log = (Tc/T-1)*sum;
    P=exp(log)*Pc;
    return P;
}

/*
double water::dPsatdT(){
    double log, sum1=0, sum2=0;
        int i;
    if ((T < Tmn) || (T > Tc))
       set_Err(TempError); // Error("water::dPsatdT",TempError,T);
    for (i=1;i<=8;i++)
        sum1 += F[i-1]*pow(a*(T-Tp),double(i-1));
    for (i=2;i<=8;i++)
        sum2 += F[i-1]*a*(i-1)*pow(a*(T-Tp),double(i-2));
    log = (Tc/T-1)*sum2 - Tc*sum1/(T*T);
    return log*Psat();
}
*/

double water::ldens()
{
    double sum=0;
    int i;
    if ((T < Tmn) || (T >= Tc)) {
        set_Err(TempError);    // Error("water::ldens",TempError,T);
    }
    for (i=0; i<=8; i++) {
        sum+=D[i-1]*pow(1.0 - T/Tc, double(i)/3.0);
    }
    double density = Roc*(1+sum);
    return density;
}

double water::Tcrit()
{
    return Tc;
}
double water::Pcrit()
{
    return Pc;
}
double water::Vcrit()
{
    return 1.0/Roc;
}
double water::Tmin()
{
    return Tmn;
}
double water::Tmax()
{
    return Tmx;
}
char* water::name()
{
    return (char*) m_name.c_str();
}
char* water::formula()
{
    return (char*) m_formula.c_str();
}
double water::MolWt()
{
    return M;
}

}

<commit_msg>Fixed an array indexing error in tpx::Water::ldens<commit_after>// water

#include "Water.h"
#include <math.h>
#include <string.h>

namespace tpx
{

static const double Tmn=273.16;
static const double Tmx=1600.0;
static const double M=18.016;
static const double Tc=647.286;
static const double Pc=22.089e6;
static const double Roc=317.0;
static const double To=273.16;
static const double R=461.51;
static const double E=4.8E-3;
static const double Ta=1000.0;
static const double tauc=1.544912;
static const double Tp=338.15;
static const double aww=0.01;
static const double Roa1=634.0;
static const double Roaj=1000.0;
static const double u0=2375470.875;
static const double s0=6697.356635;

static const double A[10][7]= {{
        2.9492937E-2,-5.1985860E-3,
        6.8335354E-3,-1.5641040E-4,
        -6.3972405E-3, -3.9661401E-3, -6.9048554E-4
    },
    {
        -1.3213917E-4,7.7779182E-6, -2.6149751E-5,-7.2546108E-7,
        2.6409282E-5, 1.5453061E-5,2.7407416E-6
    },
    {
        2.7464632E-7,-3.3301902E-8,6.5326396E-8,-9.2734289E-9,
        -4.7740374E-8,-2.9142470E-8,-5.1028070E-9
    },
    {
        -3.6093828E-10, -1.6254622E-11, -2.6181978E-11, 4.3125840E-12,
        5.6323130E-11, 2.9568796E-11,3.9636085E-12
    },
    {3.4218431E-13, -1.7731074E-13,0,0,0,0,0},
    {-2.4450042E-16, 1.2748742E-16,0,0,0,0,0},
    {1.5518535E-19, 1.3746153E-19,0,0,0,0,0},
    {5.9728487E-24,1.5597836E-22, 0,0,0,0,0},
    {
        -4.1030848E-1, 3.3731180E-1, -1.3746678E-1, 6.7874983E-3,
        1.3687317E-1, 7.984797E-2, 1.3041253E-2
    },
    {
        -4.1605860E-4, -2.0988866E-4,-7.3396848E-4,1.0401717E-5,
        6.4581880E-4, 3.9917570E-4, 7.1531353E-5
    }
};

static const double F[]= {-7.4192420, 2.9721E-1,-1.155286E-1,8.685635E-3,
                          1.0940980E-3, -4.39993E-3, 2.5206580E-3, -5.2186840E-4
                         };

static const double D[]= {3.6711257,-2.8512396E1,2.2265240E2,-8.8243852E2,
                          2.0002765E3,-2.6122557E3,1.8297674E3,-5.3350520E2
                         };

static const double G[]= {4.6E4,1.011249E3,8.3893E-1,-2.19989E-4,2.466619E-7,
                          -9.704700E-11
                         };

static const double taua[] = {1.544912, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5};

inline double water::C(int i)
{
    double tau = Ta/T;
    return (i == 0 ? R*T : R*T*(tau - tauc)*pow(tau - taua[i],i-1));
}

inline double water::Cprime(int i)
{
    double tau = Ta/T;
    return (i == 0 ? R : (i == 1 ? -R*tauc :
                          -R*pow(tau - taua[i],i-2)*(tauc*(tau - taua[i])
                                  + (i-1)*tau*(tau - tauc))));
}

inline double water::I(int j)
{
    double factor, sum, rho_aj;
    rho_aj = (j == 0 ? Roa1 : Roaj);
    sum = 0.0;
    factor = Rho - rho_aj;
    for (int i=7; i>0; i--) {
        sum += A[i][j];
        sum *= factor;
    }
    sum += A[0][j];
    sum += (exp(-E*Rho)*(A[8][j] + A[9][j]*Rho));
    return Rho*sum;
}

inline double water::H(int j)
{
    double factor, sum, rho_aj;
    rho_aj = (j == 0 ? Roa1 : Roaj);
    sum = 0.0;
    factor = Rho - rho_aj;
    for (int i=6; i>0; i--) {
        sum += (A[i][j] + Rho*(i+1)*A[i+1][j]);
        sum *= factor;
    }
    sum += (A[0][j] + Rho*A[1][j]);
    sum += (exp(-E*Rho)*((1.0 - Rho*E)*A[8][j]
                         + Rho*(2.0 - Rho*E)*A[9][j]));
    sum += A[7][j]*pow(factor,7);
    return Rho*Rho*sum;
}

double water::up()
{
    double sum = 0.0;
    int i;
    for (i=0; i<7; i++) {
        sum += (C(i) - T*Cprime(i))*I(i);
    }
    for (i=1; i<6; i++) {
        sum += G[i]*(pow(T,i) - pow(To,i))/double(i);
    }
    sum += G[0]*log(T/To) + u0;
    return sum + m_energy_offset;
}

double water::sp()
{
    double sum = 0.0;
    int i;
    for (i=2; i<6; i++) {
        sum += G[i]*(pow(T,i-1) - pow(To,i-1))/double(i-1);
    }
    sum += G[1]*log(T/To);
    sum -= G[0]*(1.0/T - 1.0/To);
    sum += s0 - R*log(Rho);
    for (i=0; i<7; i++) {
        sum -= Cprime(i)*I(i);
    }
    return sum + m_entropy_offset;
}

double water::Pp()
{
    double P = Rho*R*T;
    for (int i=0; i<7; i++) {
        P += C(i)*H(i);
    }
    return P;
}

double water::Psat()
{
    double log, sum=0,P;
    if ((T < Tmn) || (T > Tc)) {
        set_Err(TempError);    // Error("water::Psat",TempError,T);
    }
    for (int i=1; i<=8; i++) {
        sum += F[i-1]*pow(aww*(T-Tp),double(i-1));    // DGG mod
    }
    log = (Tc/T-1)*sum;
    P=exp(log)*Pc;
    return P;
}

/*
double water::dPsatdT(){
    double log, sum1=0, sum2=0;
        int i;
    if ((T < Tmn) || (T > Tc))
       set_Err(TempError); // Error("water::dPsatdT",TempError,T);
    for (i=1;i<=8;i++)
        sum1 += F[i-1]*pow(a*(T-Tp),double(i-1));
    for (i=2;i<=8;i++)
        sum2 += F[i-1]*a*(i-1)*pow(a*(T-Tp),double(i-2));
    log = (Tc/T-1)*sum2 - Tc*sum1/(T*T);
    return log*Psat();
}
*/

double water::ldens()
{
    double sum=0;
    int i;
    if ((T < Tmn) || (T >= Tc)) {
        set_Err(TempError);    // Error("water::ldens",TempError,T);
    }
    for (i=0; i<8; i++) {
        sum+=D[i]*pow(1.0 - T/Tc, double(i+1)/3.0);
    }
    double density = Roc*(1+sum);
    return density;
}

double water::Tcrit()
{
    return Tc;
}
double water::Pcrit()
{
    return Pc;
}
double water::Vcrit()
{
    return 1.0/Roc;
}
double water::Tmin()
{
    return Tmn;
}
double water::Tmax()
{
    return Tmx;
}
char* water::name()
{
    return (char*) m_name.c_str();
}
char* water::formula()
{
    return (char*) m_formula.c_str();
}
double water::MolWt()
{
    return M;
}

}

<|endoftext|>


<commit_before><commit_msg>4 spaces<commit_after><|endoftext|>


<commit_before>// $Id$

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/// @file   AliHLTRCUAgent.cxx
/// @author Matthias Richter
/// @date
/// @brief  Agent of the libAliHLTRCU library
///

#include <cassert>
#include "AliHLTRCUAgent.h"
#include "AliHLTDAQ.h"

// header files of library components
#include "AliHLTAltroChannelSelectorComponent.h"
#include "AliHLTAltroTimebinAverageComponent.h"

/** global instance for agent registration */
AliHLTRCUAgent gAliHLTRCUAgent;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTRCUAgent)

AliHLTRCUAgent::AliHLTRCUAgent()
  : AliHLTModuleAgent("RCU")
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTRCUAgent::~AliHLTRCUAgent()
{
  // see header file for class documentation
}

int AliHLTRCUAgent::CreateConfigurations(AliHLTConfigurationHandler* handler,
					 AliRawReader* rawReader,
					 AliRunLoader* runloader) const
{
  // add configurations for the RCU library
  if (handler) {
    if (rawReader) {
      // AliSimulation: use the AliRawReaderPublisher if the raw reader is available
      // Alireconstruction: indicated by runloader==NULL, run always on raw data
      int iMinSlice=0;
      int iMaxSlice=35;
      int iMinPart=0;
      int iMaxPart=5;
      TString sinkChannelSelectors;
      for (int slice=iMinSlice; slice<=iMaxSlice; slice++) {
	for (int part=iMinPart; part<=iMaxPart; part++) {
	  TString arg, publisher, selector;

	  // publisher component
	  int ddlno=AliHLTDAQ::DdlIDOffset(3);
	  if (part>1) ddlno+=72+4*slice+(part-2);
	  else ddlno+=2*slice+part;

	  publisher.Form("RCU-DP_%02d_%d", slice, part);
	  arg.Form("-minid %d -datatype 'DDL_RAW ' 'TPC '  -dataspec %s -silent", ddlno, AliHLTDAQ::HLTSpecificationFromDdlID(ddlno).c_str());
	  handler->CreateConfiguration(publisher.Data(), "AliRawReaderPublisher", NULL , arg.Data());

	  // selector component
	  selector.Form("RCU-chselector_%02d_%d", slice, part);
	  arg="-signal-threshold 1";
	  handler->CreateConfiguration(selector.Data(), "AltroChannelSelector", publisher.Data(), arg.Data());

	  if (sinkChannelSelectors.Length()>0) sinkChannelSelectors+=" ";
	  sinkChannelSelectors+=selector;
	}
      }
      handler->CreateConfiguration("RCU-channelselect", "BlockFilter", sinkChannelSelectors.Data(), "");
    }
  }
  return 0;
}

const char* AliHLTRCUAgent::GetReconstructionChains(AliRawReader* /*rawReader*/,
						    AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  return NULL;
}

const char* AliHLTRCUAgent::GetRequiredComponentLibraries() const
{
  // see header file for class documentation
  return NULL;
}

int AliHLTRCUAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
  // see header file for class documentation
  assert(pHandler);
  if (!pHandler) return -EINVAL;
  pHandler->AddComponent(new AliHLTAltroChannelSelectorComponent);
  pHandler->AddComponent(new AliHLTAltroTimebinAverageComponent);
  return 0;
}
<commit_msg>commenting unused function argument<commit_after>// $Id$

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/// @file   AliHLTRCUAgent.cxx
/// @author Matthias Richter
/// @date
/// @brief  Agent of the libAliHLTRCU library
///

#include <cassert>
#include "AliHLTRCUAgent.h"
#include "AliHLTDAQ.h"

// header files of library components
#include "AliHLTAltroChannelSelectorComponent.h"
#include "AliHLTAltroTimebinAverageComponent.h"

/** global instance for agent registration */
AliHLTRCUAgent gAliHLTRCUAgent;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTRCUAgent)

AliHLTRCUAgent::AliHLTRCUAgent()
  : AliHLTModuleAgent("RCU")
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTRCUAgent::~AliHLTRCUAgent()
{
  // see header file for class documentation
}

int AliHLTRCUAgent::CreateConfigurations(AliHLTConfigurationHandler* handler,
					 AliRawReader* rawReader,
					 AliRunLoader* /*runloader*/) const
{
  // add configurations for the RCU library
  if (handler) {
    if (rawReader) {
      // AliSimulation: use the AliRawReaderPublisher if the raw reader is available
      // Alireconstruction: indicated by runloader==NULL, run always on raw data
      int iMinSlice=0;
      int iMaxSlice=35;
      int iMinPart=0;
      int iMaxPart=5;
      TString sinkChannelSelectors;
      for (int slice=iMinSlice; slice<=iMaxSlice; slice++) {
	for (int part=iMinPart; part<=iMaxPart; part++) {
	  TString arg, publisher, selector;

	  // publisher component
	  int ddlno=AliHLTDAQ::DdlIDOffset(3);
	  if (part>1) ddlno+=72+4*slice+(part-2);
	  else ddlno+=2*slice+part;

	  publisher.Form("RCU-DP_%02d_%d", slice, part);
	  arg.Form("-minid %d -datatype 'DDL_RAW ' 'TPC '  -dataspec %s -silent", ddlno, AliHLTDAQ::HLTSpecificationFromDdlID(ddlno).c_str());
	  handler->CreateConfiguration(publisher.Data(), "AliRawReaderPublisher", NULL , arg.Data());

	  // selector component
	  selector.Form("RCU-chselector_%02d_%d", slice, part);
	  arg="-signal-threshold 1";
	  handler->CreateConfiguration(selector.Data(), "AltroChannelSelector", publisher.Data(), arg.Data());

	  if (sinkChannelSelectors.Length()>0) sinkChannelSelectors+=" ";
	  sinkChannelSelectors+=selector;
	}
      }
      handler->CreateConfiguration("RCU-channelselect", "BlockFilter", sinkChannelSelectors.Data(), "");
    }
  }
  return 0;
}

const char* AliHLTRCUAgent::GetReconstructionChains(AliRawReader* /*rawReader*/,
						    AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  return NULL;
}

const char* AliHLTRCUAgent::GetRequiredComponentLibraries() const
{
  // see header file for class documentation
  return NULL;
}

int AliHLTRCUAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
  // see header file for class documentation
  assert(pHandler);
  if (!pHandler) return -EINVAL;
  pHandler->AddComponent(new AliHLTAltroChannelSelectorComponent);
  pHandler->AddComponent(new AliHLTAltroTimebinAverageComponent);
  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>
#include <vector>

#include "base/process.h"
#include "base/scoped_ptr.h"
#include "chrome/common/filter_policy.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/resource_dispatcher.h"

#include "testing/gtest/include/gtest/gtest.h"

using webkit_glue::ResourceLoaderBridge;

static const char test_page_url[] = "http://www.google.com/";
static const char test_page_headers[] =
  "HTTP/1.1 200 OK\nContent-Type:text/html\n\n";
static const char test_page_mime_type[] = "text/html";
static const char test_page_charset[] = "";
static const char test_page_contents[] =
  "<title>Google</title>
Google
";
static const int test_page_contents_len = arraysize(test_page_contents) - 1;

// Listens for request response data and stores it so that it can be compared
// to the reference data.
class TestRequestCallback : public ResourceLoaderBridge::Peer {
 public:
  TestRequestCallback() : complete_(false) {
  }

  virtual void OnReceivedRedirect(const GURL& new_url) {
  }

  virtual void OnReceivedResponse(
      const ResourceLoaderBridge::ResponseInfo& info,
      bool content_filtered) {
  }

  virtual void OnReceivedData(const char* data, int len) {
    EXPECT_FALSE(complete_);
    data_.append(data, len);
  }

  virtual void OnUploadProgress(uint64 position, uint64 size) {
  }

  virtual void OnCompletedRequest(const URLRequestStatus& status,
                                  const std::string& security_info) {
    EXPECT_FALSE(complete_);
    complete_ = true;
  }

  virtual std::string GetURLForDebugging() {
    return std::string();
  }

  const std::string& data() const {
    return data_;
  }
  const bool complete() const {
    return complete_;
  }

 private:
  bool complete_;
  std::string data_;
};

// Sets up the message sender override for the unit test
class ResourceDispatcherTest : public testing::Test,
                               public IPC::Message::Sender {
 public:
  // Emulates IPC send operations (IPC::Message::Sender) by adding
  // pending messages to the queue.
  virtual bool Send(IPC::Message* msg) {
    message_queue_.push_back(IPC::Message(*msg));
    delete msg;
    return true;
  }

  // Emulates the browser process and processes the pending IPC messages,
  // returning the hardcoded file contents.
  void ProcessMessages() {
    while (!message_queue_.empty()) {
      int request_id;
      ViewHostMsg_Resource_Request request;
      ASSERT_TRUE(ViewHostMsg_RequestResource::Read(
          &message_queue_[0], &request_id, &request));

      // check values
      EXPECT_EQ(test_page_url, request.url.spec());

      // received response message
      ResourceResponseHead response;
      std::string raw_headers(test_page_headers);
      std::replace(raw_headers.begin(), raw_headers.end(), '\n', '\0');
      response.headers = new net::HttpResponseHeaders(raw_headers);
      response.mime_type = test_page_mime_type;
      response.charset = test_page_charset;
      response.filter_policy = FilterPolicy::DONT_FILTER;
      dispatcher_->OnReceivedResponse(request_id, response);

      // received data message with the test contents
      base::SharedMemory shared_mem;
      EXPECT_TRUE(shared_mem.Create(std::wstring(),
          false, false, test_page_contents_len));
      EXPECT_TRUE(shared_mem.Map(test_page_contents_len));
      char* put_data_here = static_cast<char*>(shared_mem.memory());
      memcpy(put_data_here, test_page_contents, test_page_contents_len);
      base::SharedMemoryHandle dup_handle;
      EXPECT_TRUE(shared_mem.GiveToProcess(
          base::Process::Current().handle(), &dup_handle));
      dispatcher_->OnReceivedData(
          message_queue_[0], request_id, dup_handle, test_page_contents_len);

      message_queue_.erase(message_queue_.begin());

      // read the ack message.
      int request_ack = -1;
      ASSERT_TRUE(ViewHostMsg_DataReceived_ACK::Read(
          &message_queue_[0], &request_ack));

      ASSERT_EQ(request_ack, request_id);

      message_queue_.erase(message_queue_.begin());
    }
  }

 protected:
  static ResourceDispatcher* GetResourceDispatcher(WebFrame* unused) {
    return dispatcher_.get();
  }

  // testing::Test
  virtual void SetUp() {
    dispatcher_.reset(new ResourceDispatcher(this));
  }
  virtual void TearDown() {
    dispatcher_.reset();
  }

  std::vector<IPC::Message> message_queue_;
  static scoped_ptr<ResourceDispatcher> dispatcher_;
};

/*static*/
scoped_ptr<ResourceDispatcher> ResourceDispatcherTest::dispatcher_;

// Does a simple request and tests that the correct data is received.
TEST_F(ResourceDispatcherTest, RoundTrip) {
  TestRequestCallback callback;
  ResourceLoaderBridge* bridge =
    dispatcher_->CreateBridge("GET", GURL(test_page_url), GURL(test_page_url),
                              GURL(), "null", "null", std::string(), 0, 0,
                              ResourceType::SUB_RESOURCE, 0,
                              MSG_ROUTING_CONTROL);

  bridge->Start(&callback);

  ProcessMessages();

  // FIXME(brettw) when the request complete messages are actually handledo
  // and dispatched, uncomment this.
  //EXPECT_TRUE(callback.complete());
  //EXPECT_STREQ(test_page_contents, callback.data().c_str());

  delete bridge;
}

// Tests that the request IDs are straight when there are multiple requests.
TEST_F(ResourceDispatcherTest, MultipleRequests) {
  // FIXME
}

// Tests that the cancel method prevents other messages from being received
TEST_F(ResourceDispatcherTest, Cancel) {
  // FIXME
}

TEST_F(ResourceDispatcherTest, Cookies) {
  // FIXME
}

TEST_F(ResourceDispatcherTest, SerializedPostData) {
  // FIXME
}
<commit_msg>Build fix.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>
#include <vector>

#include "base/process.h"
#include "base/scoped_ptr.h"
#include "chrome/common/filter_policy.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/resource_dispatcher.h"

#include "testing/gtest/include/gtest/gtest.h"

using webkit_glue::ResourceLoaderBridge;

static const char test_page_url[] = "http://www.google.com/";
static const char test_page_headers[] =
  "HTTP/1.1 200 OK\nContent-Type:text/html\n\n";
static const char test_page_mime_type[] = "text/html";
static const char test_page_charset[] = "";
static const char test_page_contents[] =
  "<title>Google</title>
Google
";
static const int test_page_contents_len = arraysize(test_page_contents) - 1;

// Listens for request response data and stores it so that it can be compared
// to the reference data.
class TestRequestCallback : public ResourceLoaderBridge::Peer {
 public:
  TestRequestCallback() : complete_(false) {
  }

  virtual void OnReceivedRedirect(const GURL& new_url) {
  }

  virtual void OnReceivedResponse(
      const ResourceLoaderBridge::ResponseInfo& info,
      bool content_filtered) {
  }

  virtual void OnReceivedData(const char* data, int len) {
    EXPECT_FALSE(complete_);
    data_.append(data, len);
  }

  virtual void OnUploadProgress(uint64 position, uint64 size) {
  }

  virtual void OnCompletedRequest(const URLRequestStatus& status,
                                  const std::string& security_info) {
    EXPECT_FALSE(complete_);
    complete_ = true;
  }

  virtual std::string GetURLForDebugging() {
    return std::string();
  }

  const std::string& data() const {
    return data_;
  }
  const bool complete() const {
    return complete_;
  }

 private:
  bool complete_;
  std::string data_;
};

// Sets up the message sender override for the unit test
class ResourceDispatcherTest : public testing::Test,
                               public IPC::Message::Sender {
 public:
  // Emulates IPC send operations (IPC::Message::Sender) by adding
  // pending messages to the queue.
  virtual bool Send(IPC::Message* msg) {
    message_queue_.push_back(IPC::Message(*msg));
    delete msg;
    return true;
  }

  // Emulates the browser process and processes the pending IPC messages,
  // returning the hardcoded file contents.
  void ProcessMessages() {
    while (!message_queue_.empty()) {
      int request_id;
      ViewHostMsg_Resource_Request request;
      ASSERT_TRUE(ViewHostMsg_RequestResource::Read(
          &message_queue_[0], &request_id, &request));

      // check values
      EXPECT_EQ(test_page_url, request.url.spec());

      // received response message
      ResourceResponseHead response;
      std::string raw_headers(test_page_headers);
      std::replace(raw_headers.begin(), raw_headers.end(), '\n', '\0');
      response.headers = new net::HttpResponseHeaders(raw_headers);
      response.mime_type = test_page_mime_type;
      response.charset = test_page_charset;
      response.filter_policy = FilterPolicy::DONT_FILTER;
      dispatcher_->OnReceivedResponse(request_id, response);

      // received data message with the test contents
      base::SharedMemory shared_mem;
      EXPECT_TRUE(shared_mem.Create(std::wstring(),
          false, false, test_page_contents_len));
      EXPECT_TRUE(shared_mem.Map(test_page_contents_len));
      char* put_data_here = static_cast<char*>(shared_mem.memory());
      memcpy(put_data_here, test_page_contents, test_page_contents_len);
      base::SharedMemoryHandle dup_handle;
      EXPECT_TRUE(shared_mem.GiveToProcess(
          base::Process::Current().handle(), &dup_handle));
      dispatcher_->OnReceivedData(
          message_queue_[0], request_id, dup_handle, test_page_contents_len);

      message_queue_.erase(message_queue_.begin());

      // read the ack message.
      int request_ack = -1;
      ASSERT_TRUE(ViewHostMsg_DataReceived_ACK::Read(
          &message_queue_[0], &request_ack));

      ASSERT_EQ(request_ack, request_id);

      message_queue_.erase(message_queue_.begin());
    }
  }

 protected:
  static ResourceDispatcher* GetResourceDispatcher(WebFrame* unused) {
    return dispatcher_.get();
  }

  // testing::Test
  virtual void SetUp() {
    dispatcher_.reset(new ResourceDispatcher(this));
  }
  virtual void TearDown() {
    dispatcher_.reset();
  }

  std::vector<IPC::Message> message_queue_;
  static scoped_ptr<ResourceDispatcher> dispatcher_;
};

/*static*/
scoped_ptr<ResourceDispatcher> ResourceDispatcherTest::dispatcher_;

// Does a simple request and tests that the correct data is received.
TEST_F(ResourceDispatcherTest, RoundTrip) {
  TestRequestCallback callback;
  ResourceLoaderBridge* bridge =
    dispatcher_->CreateBridge("GET", GURL(test_page_url), GURL(test_page_url),
                              GURL(), "null", "null", std::string(), "", 0, 0,
                              ResourceType::SUB_RESOURCE, 0,
                              MSG_ROUTING_CONTROL);

  bridge->Start(&callback);

  ProcessMessages();

  // FIXME(brettw) when the request complete messages are actually handledo
  // and dispatched, uncomment this.
  //EXPECT_TRUE(callback.complete());
  //EXPECT_STREQ(test_page_contents, callback.data().c_str());

  delete bridge;
}

// Tests that the request IDs are straight when there are multiple requests.
TEST_F(ResourceDispatcherTest, MultipleRequests) {
  // FIXME
}

// Tests that the cancel method prevents other messages from being received
TEST_F(ResourceDispatcherTest, Cancel) {
  // FIXME
}

TEST_F(ResourceDispatcherTest, Cookies) {
  // FIXME
}

TEST_F(ResourceDispatcherTest, SerializedPostData) {
  // FIXME
}
<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

#include <csignal>
#include <ctime>

#include <thread>

#include <osquery/core.h>
#include <osquery/database.h>
#include <osquery/flags.h>
#include <osquery/sql.h>

#include "osquery/core/json.h"
#include "osquery/core/process.h"
#include "osquery/tests/test_additional_util.h"
#include "osquery/tests/test_util.h"

namespace fs = boost::filesystem;

namespace osquery {

DECLARE_string(tls_hostname);
DECLARE_string(enroll_tls_endpoint);
DECLARE_string(tls_server_certs);
DECLARE_string(enroll_secret_path);
DECLARE_bool(disable_caching);

void TLSServerRunner::start() {
  auto& self = instance();
  if (self.server_ != nullptr) {
    return;
  }

  // Pick a port in an ephemeral range at random.
  self.port_ = std::to_string(rand() % 10000 + 20000);

  // Fork then exec a shell.
  auto python_server = (fs::path(kTestDataPath) / "test_http_server.py")
                           .make_preferred()
                           .string() +
                       " --tls " + self.port_;
  self.server_ = PlatformProcess::launchTestPythonScript(python_server);
  if (self.server_ == nullptr) {
    return;
  }

  size_t delay = 0;
  std::string query =
      "select pid from listening_ports where port = '" + self.port_ + "'";
  while (delay < 2 * 1000) {
    auto caching = FLAGS_disable_caching;
    FLAGS_disable_caching = true;
    auto results = SQL(query);
    FLAGS_disable_caching = caching;
    if (!results.rows().empty()) {
      self.server_.reset(
          new PlatformProcess(std::atoi(results.rows()[0].at("pid").c_str())));
      break;
    }

    sleepFor(100);
    delay += 100;
  }
}

void TLSServerRunner::setClientConfig() {
  auto& self = instance();

  self.tls_hostname_ = Flag::getValue("tls_hostname");
  Flag::updateValue("tls_hostname", "localhost:" + port());

  self.enroll_tls_endpoint_ = Flag::getValue("enroll_tls_endpoint");
  Flag::updateValue("enroll_tls_endpoint", "/enroll");

  self.tls_server_certs_ = Flag::getValue("tls_server_certs");
  Flag::updateValue("tls_server_certs",
                    (fs::path(kTestDataPath) / "test_server_ca.pem")
                        .make_preferred()
                        .string());

  self.enroll_secret_path_ = Flag::getValue("enroll_secret_path");
  Flag::updateValue("enroll_secret_path",
                    (fs::path(kTestDataPath) / "test_enroll_secret.txt")
                        .make_preferred()
                        .string());
}

void TLSServerRunner::unsetClientConfig() {
  auto& self = instance();
  Flag::updateValue("tls_hostname", self.tls_hostname_);
  Flag::updateValue("enroll_tls_endpoint", self.enroll_tls_endpoint_);
  Flag::updateValue("tls_server_certs", self.tls_server_certs_);
  Flag::updateValue("enroll_secret_path", self.enroll_secret_path_);
}

void TLSServerRunner::stop() {
  auto& self = instance();
  if (self.server_ != nullptr) {
    self.server_->kill();
    self.server_.reset();
  }
}
} // namespace osquery
<commit_msg>Fix random port problem<commit_after>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

#include <csignal>
#include <ctime>

#include <thread>

#include <osquery/core.h>
#include <osquery/database.h>
#include <osquery/flags.h>
#include <osquery/sql.h>

#include "osquery/core/json.h"
#include "osquery/core/process.h"
#include "osquery/tests/test_additional_util.h"
#include "osquery/tests/test_util.h"

namespace fs = boost::filesystem;

namespace osquery {

DECLARE_string(tls_hostname);
DECLARE_string(enroll_tls_endpoint);
DECLARE_string(tls_server_certs);
DECLARE_string(enroll_secret_path);
DECLARE_bool(disable_caching);

void TLSServerRunner::start() {
  auto& self = instance();
  if (self.server_ != nullptr) {
    return;
  }

  // Pick a port in an ephemeral range at random.
  self.port_ = std::to_string(getUnixTime() % 10000 + 20000);

  // Fork then exec a shell.
  auto python_server = (fs::path(kTestDataPath) / "test_http_server.py")
                           .make_preferred()
                           .string() +
                       " --tls " + self.port_;
  self.server_ = PlatformProcess::launchTestPythonScript(python_server);
  if (self.server_ == nullptr) {
    return;
  }

  size_t delay = 0;
  std::string query =
      "select pid from listening_ports where port = '" + self.port_ + "'";
  while (delay < 2 * 1000) {
    auto caching = FLAGS_disable_caching;
    FLAGS_disable_caching = true;
    auto results = SQL(query);
    FLAGS_disable_caching = caching;
    if (!results.rows().empty()) {
      self.server_.reset(
          new PlatformProcess(std::atoi(results.rows()[0].at("pid").c_str())));
      break;
    }

    sleepFor(100);
    delay += 100;
  }
}

void TLSServerRunner::setClientConfig() {
  auto& self = instance();

  self.tls_hostname_ = Flag::getValue("tls_hostname");
  Flag::updateValue("tls_hostname", "localhost:" + port());

  self.enroll_tls_endpoint_ = Flag::getValue("enroll_tls_endpoint");
  Flag::updateValue("enroll_tls_endpoint", "/enroll");

  self.tls_server_certs_ = Flag::getValue("tls_server_certs");
  Flag::updateValue("tls_server_certs",
                    (fs::path(kTestDataPath) / "test_server_ca.pem")
                        .make_preferred()
                        .string());

  self.enroll_secret_path_ = Flag::getValue("enroll_secret_path");
  Flag::updateValue("enroll_secret_path",
                    (fs::path(kTestDataPath) / "test_enroll_secret.txt")
                        .make_preferred()
                        .string());
}

void TLSServerRunner::unsetClientConfig() {
  auto& self = instance();
  Flag::updateValue("tls_hostname", self.tls_hostname_);
  Flag::updateValue("enroll_tls_endpoint", self.enroll_tls_endpoint_);
  Flag::updateValue("tls_server_certs", self.tls_server_certs_);
  Flag::updateValue("enroll_secret_path", self.enroll_secret_path_);
}

void TLSServerRunner::stop() {
  auto& self = instance();
  if (self.server_ != nullptr) {
    self.server_->kill();
    self.server_.reset();
  }
}
} // namespace osquery
<|endoftext|>