/** @brief A function used to generate input, set n unit points etc... */
void Safety1BPNGoAdapter::setPoint(Matrix<float>& m, int y, int value) const
{
	m.setValue(0, y*3, 0);
	m.setValue(0, y*3+1, 0);
	m.setValue(0, y*3+2, 0);
	if(value==ACT_OURCOLOUR)
		m.setValue(0, y*3, 1);
	else if(value==ACT_THEIRCOLOUR)
		m.setValue(0, y*3+1, 1);
	else if(value==ACT_EMPTY)
		m.setValue(0, y*3+2, 1);
}
OSG_BASE_DLLMAPPING bool MatrixLookAt(OSG::Matrix &result,
                                      OSG::Pnt3f   from, 
                                      OSG::Pnt3f   at, 
                                      OSG::Vec3f   up    )
{
    Vec3f view;
    Vec3f right;
    Vec3f newup;
    Vec3f tmp;

    view = from - at;
    view.normalize();

    right = up.cross(view);

    if(right.dot(right) < TypeTraits<Real>::getDefaultEps())
    {
        return true;
    }

    right.normalize();

    newup = view.cross(right);

    result.setIdentity ();
    result.setTranslate(from[0], from[1], from[2]);

    Matrix tmpm;

    tmpm.setValue(right, newup, view);

    result.mult(tmpm);

    return false;
}
void newBPN4GoAdapter::setLibertyNeurons(int base, const BoardStruct& board, int x, int y, Matrix<float>& input) const
{
	BoardStruct::constStringsIterator iter = board.getStringConst(x, y);
	if(iter==NULL)
		return;
	int libs = iter->getLibertyCount();
	// now set the appropriate marker neuron to 1
	if(libs>4)
		libs = 4;
	input.setValue(0, base+(libs-1), 1);
}
Example #4
0
bool BPN::DActivationFN(Matrix<float>& in, Matrix<float>& out, int layer) const
{
#ifdef _DEBUG
	if(in.width!=out.width || in.height!=out.height) return false;
#endif
	for(int y=0;y<in.height;y++)
	{
		for(int x=0;x<in.width;x++)
			out.setValue(x, y, DActivationFN(in.getValue(x, y), layer));
	}
	return true;
}
Example #5
0
int WarpVolume::JacobiRotationMatrix(float xx, float yy, float zz, Matrix& M)
{// (xx, yy, zz): the 3-D location 
 // return 1 : successful
 // return -1: failed
 // resulting matrix: M

  float Jab[9], ang, ox,oy,oz;
  Vector I(1,0,0), J(0,1,0), K(0,0,1), omega;
  	//cout <<" **111****" << endl;
  int res=Jacobi(xx,yy,zz, Jab);
  	//cout <<" **222****" << endl;

  if (res == -1)
	return -1;
 
  omega = -(I*Jab[5]) - (J*Jab[6]) - (K*Jab[1]);
	//cout <<endl <<"omega=>"; omega.outputs();
  omega.getXYZ(ox,oy,oz);
	//cout << endl << "omega <==" << endl;
  ang = omega.length(); 
     //cout << "omega & ang :" << endl;
     //omega.outputs(); cout << "ang = " << ang << endl;
  
  M.loadIdentity();
  M.setValue(0 , 0, ox*ox*(1-cos(ang)) +    cos(ang));
  M.setValue(0 , 1, ox*oy*(1-cos(ang)) - oz*sin(ang));
  M.setValue(0 , 2, ox*oz*(1-cos(ang)) + ox*sin(ang));
  M.setValue(1 , 0, ox*oy*(1-cos(ang)) + oz*sin(ang));
  M.setValue(1 , 1, oy*oy*(1-cos(ang)) +    cos(ang));
  M.setValue(1 , 2, oy*oz*(1-cos(ang)) - ox*sin(ang));
  M.setValue(2,  0, ox*oz*(1-cos(ang)) - oy*sin(ang));
  M.setValue(2 , 1, oy*oz*(1-cos(ang)) + ox*sin(ang));
  M.setValue(2 , 2, oz*oz*(1-cos(ang)) +    cos(ang));

  return 1;
}
Example #6
0
/** Set all weights in a layer to a random value between specified
bounds.
@param layer The layer of weights to set.
@param min The lower bound of allowed random numbers. 
@param max The upper bound of allowed random numbers. */
void BPN::randomizeLayerWeights(Matrix<float>& layer, float min, float max)
{
	int h = layer.getHeight();
	int w = layer.getWidth();
	float range = max-min;
	
	for(int i=0;i<h;i++)
	{
		for(int j=0;j<w;j++)
		{
			// generate random value
			layer.setValue(j, i, getRandom(min, max));
		}
	}
}
Example #7
0
    Matrix Matrix::operator*(const double num)
    {
        Matrix result;

        result.setSize(xSize, ySize);

        for (int x = 0; x < xSize; ++x)
        {
            for (int y = 0; y < ySize; ++y)
            {
                result.setValue(((mat[x])[y] * num), x, y);
            }
        }
        return result;
    }
Example #8
0
    Matrix Matrix::operator-(const Matrix &matr)
    {
        Matrix result;

        if (xSize != matr.xSize || ySize != matr.ySize) //Matrix sizes MUST match.
            return result;

        result.setSize(xSize, ySize);

        for (int x = 0; x < xSize; ++x)
            for (int y = 0; y < ySize; ++y)
                {
                    double sub = (mat[x])[y] - matr.getValue(x, y);
                    result.setValue(sub, x, y);
                }
        return result;
    }
void SkeletonBlendedGeometry::calculateJointTransform(void)
{
    //Precalculate the matrix for each joint
    Matrix m;
    for(UInt32 i(0) ; i<getNumJoints() ; ++i)
    {
        m.setValue(getBindTransformation());
        m.multLeft(getInternalJointInvBindTransformations(i));
        m.multLeft(getJoint(i)->getToWorld());

        if( m != _JointPoseTransforms[i])
        {
            _JointPoseTransforms[i].setValue(m);
            _NeedRecalc             = true;
        }
    }
}
// functions used to generate input, set 3 unit points etc...
void newBPN4GoAdapter::setPoint(Matrix<float>& m, int y, int value) const
{
	m.setValue(0, y*4, 0);
	m.setValue(0, y*4+1, 0);
	m.setValue(0, y*4+2, 0);
	m.setValue(0, y*4+3, 0);
	if(value==ACT_OURCOLOUR)
		m.setValue(0, y*4, 1);
	else if(value==ACT_THEIRCOLOUR)
		m.setValue(0, y*4+1, 1);
	else if(value==ACT_EMPTY)
		m.setValue(0, y*4+2, 1);
	else if(value==ACT_OFFBOARD)
		m.setValue(0, y*4+3, 1);
}
OSG_BASE_DLLMAPPING bool MatrixLookAt(OSG::Matrix &result,
                                      OSG::Real32  fromx,
                                      OSG::Real32  fromy,
                                      OSG::Real32  fromz,
                                      OSG::Real32  atx,
                                      OSG::Real32  aty,
                                      OSG::Real32  atz,
                                      OSG::Real32  upx,
                                      OSG::Real32  upy,
                                      OSG::Real32  upz)
{
    Vec3f view;
    Vec3f right;
    Vec3f newup;
    Vec3f up;

    view.setValues(fromx - atx , fromy - aty, fromz - atz);
    view.normalize();

    up.setValues(upx, upy, upz);

    right = up.cross(view);

    if(right.dot(right) < TypeTraits<Real>::getDefaultEps())
    {
        return true;
    }

    right.normalize();

    newup = view.cross(right);

    result.setIdentity ();
    result.setTranslate(fromx, fromy, fromz);

    Matrix tmpm;

    tmpm.setValue(right, newup, view);

    result.mult(tmpm);

    return false;
}
Example #12
0
    Matrix Matrix::operator*(const Matrix& matr)
    {
         Matrix result;

        //Perform rows vs column check
        if (ySize != matr.getXSize())
            return result;

        result.setSize(xSize, matr.getYSize());

        for (int y = 0; y != result.getXSize(); ++y)
        {
            for (int x = 0; x != result.getYSize(); x++)
            {
                double sum = 0;
                for (int i = 0; i != getYSize(); ++ i)
                    sum += getValue(i, y) * matr.getValue(x, i);
                result.setValue(sum, x, y);
            }
        }
        return result;
    }
Example #13
0
    /**
     * @brief Standard matrix multiplication.
     * @param matr Second matrix with same Y size as this matrix's X size.
     * @return Resultant matrix with X of the second matrix and Y of the first matrix.
     */
    Matrix Matrix::operator*(const Matrix& matr)
    {
        //Note: this algorithm assumes that this matrix is the matrix on the LEFT.
        Matrix result;

        //The columns of the first MUST match the rows of the second.
        if (getXSize() != matr.getYSize())
            return result;

        result.setSize(matr.getXSize(), getYSize()); //Size is equal to columns of the second by the rows of the first

        for (int iY = 0; iY < getYSize(); iY++) //Rows of the first
        {
            for (int iX = 0; iX < matr.getXSize(); iX++)
            {
                double sum = 0;
                for (int i = 0; i < getXSize(); i++)
                    sum += getValue(i, iY) * matr.getValue(iX, i);
                result.setValue(sum, iX, iY);
            }
        }

        return result;
    }
Example #14
0
int main (int argc, char **argv) {

    Real32 ent, ex;
    int i;

    //Lines:

    const int nlines = 10;

    Line lines[nlines];
    Pnt3f pnts[nlines * 2] = {
                        Pnt3f(0,0,0), Pnt3f(0,1,0),
                        Pnt3f(0,0,0), Pnt3f(2,1,0),
                        Pnt3f(2,0,0), Pnt3f(2,1,0),
                        Pnt3f(-2,0,0), Pnt3f(0,2,0),
                        Pnt3f(-4,2,0), Pnt3f(0,2,0),
                        Pnt3f(-3,0,0), Pnt3f(-2,1,0),
                        Pnt3f(3,4,0), Pnt3f(1,3,0),
                        Pnt3f(-1,0,0), Pnt3f(-1,1,0),
                        Pnt3f(-4,0,0), Pnt3f(-3,1,0),
                        Pnt3f(-4,6,0), Pnt3f(0,6,0)
                        };

    for ( i = 0; i < nlines; i++ )
        lines[i].setValue( pnts[i*2], pnts[i*2+1] );


    BoxVolume b;

    float xmin, ymin, zmin, xmax, ymax, zmax;

    xmin = 0;
    ymin = 0.5;
    zmin = 0;
    xmax = 1;
    ymax = .5;
    zmax = 1;

    b.setBounds(xmin, ymin, zmin, xmax, ymax, zmax);

    std::cout << std::endl;
    b.dump();
    std::cout << std::endl;

    for ( i = 0 ; i < nlines; i++ )
    {
        std::cout << "Line: (" << lines[i].getPosition() << ") ("
             << lines[i].getDirection() << ")" << std::endl;

        bool res = lines[i].intersect( b, ent, ex );
        Pnt3f   ep = lines[i].getPosition() + ent * lines[i].getDirection(),
                xp = lines[i].getPosition() + ex * lines[i].getDirection();

        std::cout << "Result: " << res;

        if ( res )
        {
            std::cout << " enter " << ent << "=(" << ep << ") ";

            bool es = ( b.isOnSurface( ep ) || b.intersect( ep ) ),
                 xs = b.isOnSurface( xp );

            if ( ( res && es ) || !res )    std::cout << "ok";
            else                            std::cout << "**BAD**";

            std::cout << ";  exit " << ex << "=(" << xp << ") ";

            if ( ( res && xs ) || !res )    std::cout << "ok";
            else                            std::cout << "**BAD**";
        }

        std::cout << std::endl;
    }

    return 0;

    SphereVolume s;

    float radius;
    Vec3f center;

    center[0] = 0;
    center[1] = 0;
    center[2] = 0;

    radius = 1;

    s.setCenter(center);
    s.setRadius(radius);

    std::cout << std::endl;
    s.dump();
    std::cout << std::endl;


    for ( i = 0 ; i < nlines; i++ )
    {
        std::cout << "Line: (" << lines[i].getPosition() << ") ("
                  << lines[i].getDirection() << ")" << std::endl;

        bool res = lines[i].intersect( s, ent, ex );
        Pnt3f   ep = lines[i].getPosition() + ent * lines[i].getDirection(),
                xp = lines[i].getPosition() + ex * lines[i].getDirection();

        std::cout << "Result: " << res;

        if ( res )
        {
            std::cout << " enter " << ent << "=(" << ep << ") ";

            bool es = ( s.isOnSurface( ep ) || s.intersect( ep ) ),
                 xs = s.isOnSurface( xp );

            if ( ( res && es ) || !res )    std::cout << "ok";
            else                            std::cout << "**BAD**";

            std::cout << ";  exit " << ex << "=(" << xp << ") ";

            if ( ( res && xs ) || !res )    std::cout << "ok";
            else                            std::cout << "**BAD**";
        }

        std::cout << std::endl;
    }

//  Intersect the line with a cylinder.


    Pnt3f p;
    Vec3f d;
    float rad;

    p[0] = 0;
    p[1] = 1;
    p[2] = 0;

    d[0] = 0;
    d[1] = 4;
    d[2] = 0;

    rad = 2;

    CylinderVolume c;

    c.setValue(p, d, rad);

//  c.setAxis(p, d);
//  c.setRadius(rad);

    std::cout << std::endl;
    c.dump();
    std::cout << std::endl;


    for ( i = 0 ; i < nlines; i++ )
    {
        std::cout << "Line: (" << lines[i].getPosition() << ") ("
             << lines[i].getDirection() << ")" << std::endl;

        bool res = lines[i].intersect( c, ent, ex );
        Pnt3f   ep = lines[i].getPosition() + ent * lines[i].getDirection(),
                xp = lines[i].getPosition() + ex * lines[i].getDirection();

        std::cout << "Result: " << res;

        if ( res )
        {
            std::cout << " enter " << ent << "=(" << ep << ") ";

            bool es = ( c.isOnSurface( ep ) || c.intersect( ep ) ),
                 xs = c.isOnSurface( xp );

            if ( ( res && es ) || !res )    std::cout << "ok";
            else                            std::cout << "**BAD**";

            std::cout << ";  exit " << ex << "=(" << xp << ") ";

            if ( ( res && xs ) || !res )    std::cout << "ok";
            else                            std::cout << "**BAD**";
        }

        std::cout << std::endl;
    }

    //### volume intersection ##############################################


    std::cout << "### volume intersection test ###" << std::endl;

    BoxVolume box(-1,-1,-1,1,1,1);
    BoxVolume boxOut (5,5,5,10,10,10);
    BoxVolume boxIn(-1,-1,-1,2,2,2);

    SphereVolume sphere(Pnt3f(0,0,0),2);
    SphereVolume sphereOut(Pnt3f(2,2,2),1);
    SphereVolume sphereIn(Pnt3f(1,0,0),1);

    CylinderVolume cylinder(Pnt3f(0,0,0),Vec3f(1,1,1),1);
    CylinderVolume cylinderOut(Pnt3f(0,9,9),Vec3f(0,0,1),1);
    CylinderVolume cylinderIn(Pnt3f(1,0,0),Vec3f(0,1,0),1);


    // Frustum defined by normal vector and distance

    Plane pnear(Vec3f(0,0,-1),2);
    Plane pfar(Vec3f(0,0,1),7);
    Plane pright(Vec3f(-0.7071,0,-0.7071),0);
    Plane pleft(Vec3f(0.7071,0,-0.7071),0);
    Plane ptop(Vec3f(0,-0.7071,-0.7071),0);
    Plane pbottom(Vec3f(0,0.7071,-0.7071),0);

    FrustumVolume frustum(pnear, pfar, pleft, pright, ptop, pbottom);

    //Frustum defined by a clipMatrix

    Matrix matrix;
    matrix.setValue(0.7071,0,0,0,
            0,0.7071,0,0,
            0,0,-1.27,-3.959,
            0,0,-0.7071,0);

    FrustumVolume frustum1;
    frustum1.setPlanes(matrix);

    // Frustum defined by 8 points

    Pnt3f nlt(-2,2,-2);
    Pnt3f nlb(-2,-2,-2);
    Pnt3f nrt(2,2,-2);
    Pnt3f nrb(2,-2,-2);
    Pnt3f flt(-7,7,-7);
    Pnt3f flb(-7,-7,-7);
    Pnt3f frt(7,7,-7);
    Pnt3f frb(7,-7,-7);

    FrustumVolume frustum2;
    frustum2.setPlanes(nlt, nlb, nrt, nrb, flt, flb, frt, frb);


        //Tests

    std::cout << "Box/box outside test: " << std::flush;
    std::cout << (box.intersect(boxOut) ? "**BAD**" : "ok") << std::endl;

    std::cout << "Box/box inside test: " << std::flush;
    std::cout << (box.intersect(boxIn) ? "ok" : "**BAD**") << std::endl;

    std::cout << "Box/sphere outside test: " << std::flush;
    std::cout << (box.intersect(sphereOut) ? "**BAD**" : "ok") << std::endl;

    std::cout << "Box/sphere inside test: " << std::flush;
    std::cout << (box.intersect(sphereIn) ? "ok" : "**BAD**")<< std::endl;

    std::cout << "Sphere/sphere outside test: " << std::flush;
    std::cout << (sphere.intersect(sphereOut) ? "**BAD**" : "ok") << std::endl;

    std::cout << "Sphere/sphere inside test: " << std::flush;
    std::cout << (sphere.intersect(sphereIn) ? "ok" : "**BAD**") << std::endl;

    std::cout << "Box/cylinder outside test: " << std::flush;
    std::cout << (box.intersect(cylinderOut) ? "**BAD**" : "ok") << std::endl;

    std::cout << "Box/cylinder inside test: " << std::flush;
    std::cout << (box.intersect(cylinderIn) ? "ok" : "**BAD**") << std::endl;

    std::cout << "Sphere/cylinder outside test: " << std::flush;
    std::cout << (sphere.intersect(cylinderOut) ? "**BAD**" : "ok") << std::endl;

    std::cout << "Sphere/cylinder inside test: " << std::flush;
    std::cout << (sphere.intersect(cylinderIn) ? "ok" : " **BAD**") << std::endl;

    std::cout << "Cylinder/cylinder outside test: "<<std::flush;
    std::cout << (cylinder.intersect(cylinderOut) ? "**BAD**" : "ok")<<std::endl;

    std::cout << "Cylinder/cylinder inside test: "<<std::flush;
    std::cout << (cylinder.intersect(cylinderIn) ? "ok" : " **BAD** ")<<std::endl;

    std::cout << "Box/Frustum outside test : " << std::flush;
    std::cout << (boxOut.intersect(frustum) ? "**BAD**" : "ok") << std::endl;

    std::cout << "Box/Frustum inside test : " << std::flush;
    std::cout << (boxIn.intersect(frustum) ? "ok" : "**BAD**") << std::endl;

    std::cout << "Sphere/Frustum outside test : " << std::flush;
    std::cout << (sphereOut.intersect(frustum) ? "**BAD**" : "ok") << std::endl;

    std::cout << "Sphere/Frustum inside test : " << std::flush;
    std::cout << (sphereIn.intersect(frustum) ? "ok" : "**BAD**") << std::endl;


    std::cout << "Cylinder/Frustum outside test : " << std::flush;
    std::cout << (cylinderOut.intersect(frustum) ? "**BAD**" : "ok") << std::endl;

    std::cout << "Cylinder/Frustum inside test : " << std::flush;
    std::cout << (cylinderIn.intersect(frustum) ? "ok" : "**BAD**") << std::endl;

    std::cout << "Cylinder/Sphere outside test: " << std::flush;
    std::cout << (cylinderOut.intersect(sphere) ? "**BAD**" : "ok") << std::endl;

    //###VOLUME EXTENSION################################################

    std::cout << "### volume extension test ###" << std::endl;

    Pnt3f min,max;

    //Box extension

    extend(box, boxIn);
    box.getBounds(min,max);
    std::cout<< "min of the box : " <<min<<std::endl;
    std::cout<< "max of the box : " <<max<<std::endl;

    extend(box,sphere);
    box.getBounds(min,max);
    std::cout<< "min of the box : " <<min<<std::endl;
    std::cout<< "max of the box : " <<max<<std::endl;

    extend(box,cylinder);
    box.getBounds(min,max);
    std::cout<< "min of the box : " <<min<<std::endl;
    std::cout<< "max of the box : " <<max<<std::endl;

    //Sphere extension

    extend(sphere, box);
    std::cout<<"Center of the sphere : " <<sphere.getCenter()<<std::endl;
    std::cout<<"Radius of the sphere : " <<sphere.getRadius()<<std::endl;

    extend(sphere, sphereOut);
    std::cout<<"Center of the sphere : " <<sphere.getCenter()<<std::endl;
    std::cout<<"Radius of the sphere : " <<sphere.getRadius()<<std::endl;

    extend(sphere, cylinder);
    std::cout<<"Center of the sphere : " <<sphere.getCenter()<<std::endl;
    std::cout<<"Radius of the sphere : " <<sphere.getRadius()<<std::endl;

    //Cylinder extension

    extend (cylinder, box);
    cylinder.getBounds(min,max);
    std::cout<< "min of the cylinder : " <<min<<std::endl;
    std::cout<< "max of the cylinder : " <<max<<std::endl;

    extend (cylinder, sphere);
    cylinder.getBounds(min,max);
    std::cout<< "min of the cylinder : " <<min<<std::endl;
    std::cout<< "max of the cylinder : " <<max<<std::endl;

    extend (cylinder, cylinder);
    cylinder.getBounds(min,max);
    std::cout<< "min of the cylinder : " <<min<<std::endl;
    std::cout<< "max of the cylinder : " <<max<<std::endl;


    return 0;


}
void CSMTrackball::changed(ConstFieldMaskArg whichField, 
                           UInt32            origin,
                           BitVector         details)
{
    if(0x0000 != (whichField & MouseDataFieldMask))
    {
        const MouseData &mData = _sfMouseData.getValue();

        if((0x0000 != (mData.getModifier() & _sfModifierMask.getValue())) ||
           (_sfProcessing.getValue() == 0x01))
        {
            if(mData.getButton() != -1)
            {
                if(mData.getState() == Int32(MouseData::ButtonDown))
                {
                    switch(mData.getButton())
                    {
                        case MouseData::LeftButton :  
                            break;
                            
                        case MouseData::MiddleButton :
                            _oTrackball.setAutoPosition(true);
                            break;
                            
                        case MouseData::RightButton :     
                            _oTrackball.setAutoPositionNeg(true);
                            break;
                    }

                    _iMouseButtons |= 1 << mData.getButton();

                    editSFProcessing()->setValue(true);
                }
                else
                {
                    switch(mData.getButton())
                    {
                        case MouseData::LeftButton :  
                            break;
                            
                        case MouseData::MiddleButton :
                            _oTrackball.setAutoPosition(false);
                            break;
                            
                        case MouseData::RightButton :     
                            _oTrackball.setAutoPositionNeg(false);
                            break;
                    }       
                    
                    _iMouseButtons &= ~(1 << mData.getButton());

                    editSFProcessing()->setValue(false);
                }
            }
            else
            {
                if(_sfProcessing.getValue() == 0x01)
                {
                    Real32 a,b,c,d;

                    if(mData.getMode() == MouseData::RelValues)
                    {
                        a = 0.f;
                        b = 0.f;

                        c = mData.getX();
                        d = mData.getY();
                    }
                    else
                    {
                        Real32 w = mData.getWindow()->getWidth ();
                        Real32 h = mData.getWindow()->getHeight();

                        Real32 x = mData.getX();
                        Real32 y = mData.getY();
                    
                        a = -2.0 * (_iLastX / w - 0.5);
                        b = -2.0 * (0.5 - _iLastY / h);
                        c = -2.0 * (  x / w - 0.5   );
                        d = -2.0 * (0.5 - y / h     );
                    }

                    if(_iMouseButtons & (1 << MouseData::LeftButton))
                    {
                        _oTrackball.updateRotation(a, b, c, d);     
                    }
                    else if(_iMouseButtons & (1 << MouseData::MiddleButton))
                    {
                        _oTrackball.updatePosition(a, b, c, d);     
                    }
                    else if(_iMouseButtons & (1 << MouseData::RightButton))
                    {
                        _oTrackball.updatePositionNeg(a, b, c, d);  
                    }

                    editSFMatrixResult()->setValue(
                            _oTrackball.getFullTrackballMatrix());
                }
            }

            _iLastX = mData.getX();
            _iLastY = mData.getY();
        }
    }

    if(0x0000 != (whichField & ReferencePositionFieldMask))
    {
        _oTrackball.setStartPosition(_sfReferencePosition.getValue()[0],
                                     _sfReferencePosition.getValue()[1],
                                     _sfReferencePosition.getValue()[2], 
                                      true                             );

        editSFMatrixResult()->setValue(_oTrackball.getFullTrackballMatrix());
    }

    if(0x0000 != (whichField & ReferenceMatrixFieldMask))
    {
        Matrix m;
            
        m.setValue(&(_sfReferenceMatrix.getValue()[0][0]));
        
        Quaternion so;
        Vec3f      s;
        Vec3f      trans;
        Quaternion ro;
        Vec3f      cnt;
        
        cnt[0] = _sfTransformCenter.getValue()[0];
        cnt[1] = _sfTransformCenter.getValue()[1];
        cnt[2] = _sfTransformCenter.getValue()[2];
        
        m.getTransform(trans, ro, s, so, cnt);
        
        _oTrackball.setStartRotation(ro, true);
            
        ro.invert();
        ro.multVec(trans, trans);
        
        _oTrackball.setStartPosition(trans[0],
                                     trans[1],
                                     trans[2], 
                                     true);

        editSFMatrixResult()->setValue(_oTrackball.getFullTrackballMatrix());
    }

    if(0x0000 != (whichField & TransformCenterFieldMask))
    {
        _oTrackball.setRotationCenter(_sfTransformCenter.getValue());
    }

    if(0x0000 != (whichField & WorldDiagFieldMask))
    {
        _oTrackball.setTranslationScale(((_sfWorldDiag.getValue()[0] +
                                          _sfWorldDiag.getValue()[1] +
                                          _sfWorldDiag.getValue()[2]) / 5.f) *
                                        _sfTranslationScaleFactor.getValue());
    }

#if 0
    if(0x0000 != (whichField & ResetFieldMask))
    {
        _oTrackball.reset();

        VSC::beginEdit(this, MatrixResultFieldMask);
        {
            _sfMatrixResult.setValue(_oTrackball.getFullTrackballMatrix());
        }
        VSC::endEdit  (this, MatrixResultFieldMask);
    }
#endif

    Inherited::changed(whichField, origin, details);
}
/** Return a matrix containing appropriate representation of an area
of the board centred around the given move so it can be fed 
directly into a BPN network. The area size is determined by the
value of PATTERNWIDTH and PATTERNHEIGHT.
@param x The x coordinate to centre on.
@param y The y coordinate to centre on.
@param b The Board object from which to extract an area.
@param input A return parameter to store the converted, NN ready input matrix. 
@param colour The colour whose point of view we are creating this input pattern for. I.e. which colour
this move is being scored for. */
bool Safety1BPNGoAdapter::getInput(int x, int y, const BoardStruct& b, Matrix<float>& input, int colour) const
{

	/** @todo This is the old contents, needs to be rewritten for Safety1 design. */

	const BoardStruct::contentsType& t = b.getContents();
	float act = 0;

	// board contents should be rotated so that nearest two board edges
	// are the top and left, this gets rid of all rotational symmetry
	int width = t.getWidth();
	int height = t.getHeight();
	int leftdist = x;
	int rightdist = width-x-1; 
	int topdist = y;
	int bottomdist = height-y-1;

	bool topcloser = true;
	bool leftcloser = true;

	// top left sides always preferred if equidistant from two edges
	if(topdist>bottomdist)
		topcloser = false;
	if(leftdist>rightdist)
		leftcloser = false;

	// copy board into a matrix so we can rotate later
	BoardStruct::contentsType temp2(t);
	BoardStruct::contentsType temp(temp2.width, temp2.height);

	// if bottom right edges closer
	if(!topcloser && !leftcloser) {
		// rotate temp 180 clw
		temp2.doTransform(temp, Matrix_ROTATE180);
		// translate x and y now to match newly rotated board
		x = rightdist;
		y = bottomdist;
	}
	// if top right edges closer
	else if(topcloser && !leftcloser) {
		// rotate temp 270 clw
		temp2.doTransform(temp, Matrix_ROTATE270);
		x = topdist;
		y = rightdist;
	}
	// if bottom left edges closer
	else if(!topcloser && leftcloser) {
		// rotate temp 90 clw
		temp2.doTransform(temp, Matrix_ROTATE90);
		x = bottomdist;
		y = leftdist;
	}
	// no rotation
	else
		temp = temp2;

	// 3 units per point + 18 units for distance to nearest board edges
	input.resize(1, getBPN().getWeights()[0].getHeight());
	// now extract contents of board around this point

	// values to work around area centred on x,y
	// extending as PATTERNWIDTHxPATTERNHEIGHT
	int pWidth = getPatternWidth();
	int pHeight = getPatternHeight();
	int topleftx = x-(pWidth/2);
	int toplefty = y-(pHeight/2);

	int offsetx = 0;
	int offsety = 0;

	int count = 0;
	vector<SpecialPoint> points;
	getInputFieldPoints(temp, points, x, y);
	vector<SpecialPoint>::const_iterator citer = points.begin();
	for(;citer!=points.end();citer++) {
		if(citer->type==OFFBOARD)
			setPoint(input, count++, ACT_OFFBOARD);
		else
			setPoint(input, count++, getActivationValue(citer->type, colour));
	}
	
	// add distance to edge values for last 18 neurons
	// 9 neurons for top edge distance
	// 9 neurons for left edge distance
	// use binary type system
	// all off except the nth neuron indicating the distance

	// the distance to top and left edges (now the nearest after rotation)
	// should now be x, y

	// top distance
	for(int i=0;i<9;i++) {
		if((i+1)==x)
			input.setValue(0, (count*4)+i, 1);
		else
			input.setValue(0, (count*4)+i, 0);
	}

	// left distance
	for(i=0;i<9;i++) {
		if((i+1)==y)
			input.setValue(0, ((count*4)+9)+i, 1);
		else
			input.setValue(0, ((count*4)+9)+i, 0);
	}

	//input.setValue(0, count*3, x);
	//input.setValue(0, (count*3)+1, y);
	return true;
}
/** Return a matrix containing appropriate representation of an area
of the board centred around the given move so it can be fed 
directly into a BPN network. The area size is determined by the
value of PATTERNWIDTH and PATTERNHEIGHT.
@param x The x coordinate to centre on.
@param y The y coordinate to centre on.
@param b The Board object from which to extract an area.
@param input A return parameter to store the converted, NN ready input matrix. 
@param colour The colour whose point of view we are creating this input pattern for. I.e. which colour
this move is being scored for. */
bool newBPN4GoAdapter::getInput(int x, int y, const BoardStruct& b, Matrix<float>& input, int colour) const
{
	const BoardStruct::contentsType& t = b.getContents();
	float act = 0;

	// board contents should be rotated so that nearest two board edges
	// are the top and left, this gets rid of all rotational symmetry
	int width = t.getWidth();
	int height = t.getHeight();
	int leftdist = x;
	int rightdist = width-x-1; 
	int topdist = y;
	int bottomdist = height-y-1;

	bool topcloser = true;
	bool leftcloser = true;

	// top left sides always preferred if equidistant from two edges
	if(topdist>bottomdist)
		topcloser = false;
	if(leftdist>rightdist)
		leftcloser = false;

	// copy board into a matrix so we can rotate later
	BoardStruct::contentsType temp2(t);
	BoardStruct::contentsType temp(temp2.width, temp2.height);

	// if bottom right edges closer
	if(!topcloser && !leftcloser)
	{
		// rotate temp 180 clw
		temp2.doTransform(temp, Matrix_ROTATE180);
		// translate x and y now to match newly rotated board
		x = rightdist;
		y = bottomdist;
	}
	// if top right edges closer
	else if(topcloser && !leftcloser)
	{
		// rotate temp 270 clw
		temp2.doTransform(temp, Matrix_ROTATE270);
		x = topdist;
		y = rightdist;
	}
	// if bottom left edges closer
	else if(!topcloser && leftcloser)
	{
		// rotate temp 90 clw
		temp2.doTransform(temp, Matrix_ROTATE90);
		x = bottomdist;
		y = leftdist;
	}
	// no rotation
	else
		temp = temp2;

	// 3 units per point + 18 units for distance to nearest board edges
	input.resize(1, getBPN().getWeights()[0].getHeight());
	// now extract contents of board around this point

	// values to work around area centred on x,y
	// extending as PATTERNWIDTHxPATTERNHEIGHT
	int pWidth = getPatternWidth();
	int pHeight = getPatternHeight();
	int topleftx = x-(pWidth/2);
	int toplefty = y-(pHeight/2);

	int offsetx = 0;
	int offsety = 0;

	int count = 0;
	vector<SpecialPoint> points;
	getInputFieldPoints(temp, points, x, y);
	vector<SpecialPoint>::const_iterator citer = points.begin();
	for(;citer!=points.end();citer++)
	{
		if(citer->type==OFFBOARD)
			setPoint(input, count++, ACT_OFFBOARD);
		else
			setPoint(input, count++, getActivationValue(citer->type, colour));
	}
	
/*	// find equivalent input values
	for(int i=0;i<pHeight;i++)
	{
		offsety = i+toplefty;
		for(int j=0;j<pWidth;j++)
		{
			offsetx = j+topleftx;
			// check bounds	to see if this point is off the board
			if(offsetx<0 || offsety<0 || offsetx>=width || offsety>=height)
				setPoint(input, count, ACT_OFFBOARD);
			else
				setPoint(input, count, getActivationValue(temp.getValue(offsetx, offsety), colour));
			count++;
		} // end for j
	} // end for i
*/
	// add distance to edge values for last 18 neurons
	// 9 neurons for top edge distance
	// 9 neurons for left edge distance
	// use binary type system
	// all off except the nth neuron indicating the distance

	// the distance to top and left edges (now the nearest after rotation)
	// should now be x, y

	int base = count*4;

	// top distance
	for(int i=0;i<9;i++)
	{
		if((i+1)==x)
			input.setValue(0, base+i, 1);
		else
			input.setValue(0, base+i, 0);
	}

	base = (count*4)+9;

	// left distance
	for(i=0;i<9;i++)
	{
		if((i+1)==y)
			input.setValue(0, base+i, 1);
		else
			input.setValue(0, base+i, 0);
	}

	// liberties neurons, 4 for each north, south, east and west
	// indicating one of 1,2,3>=4 liberties for string in that direction
	base = (count*4)+18;

	for(i=0;i<16;i++)
		input.setValue(0, base+i, 0);

	// north
	if((y-1)>=0)
		setLibertyNeurons(base, b, x, y-1, input);
	// south
	if((y+1)<b.getSize())
		setLibertyNeurons(base+4, b, x, y+1, input);
	// east
	if((x+1)>=0)
		setLibertyNeurons(base+8, b, x+1, y, input);
	// west
	if((x-1)<b.getSize())
		setLibertyNeurons(base+12, b, x-1, y, input);

	return true;
}
Example #18
0
NodePtr PerformerLoader::traverse(pfNode *node)
{
    FINFO(("PfL:traverse: traversing \"%s\": %p (%s)\n", 
        node->getName()?node->getName():"Unnamed",
        node, pfGetTypeName(node)));    
    
    if(_nodes.find(node) != _nodes.end())
    {
        FINFO(("PfL:traverse: found in nodemap as %p.\n",
                _nodes[node].getCPtr()));    
        
        return cloneTree(_nodes[node]);
    }
    
    NodePtr n = Node::create();
    NodeCorePtr core = NullFC; 
    
    beginEditCP(n);
    
    setName(n, node->getName());
    
	if (node->getType()->isDerivedFrom(pfGroup::getClassType()))
	{
        pfGroup *group = dynamic_cast<pfGroup *>(node);
        
        int ind = 0;
        int num = group->getNumChildren();

	    if (node->getType()->isDerivedFrom(pfLOD::getClassType()))
	    {
            if(_highestLODOnly)
            {
                num = osgMin(num, 1);
                core = Group::create();
            }
            else
            {
                pfLOD *lod = dynamic_cast<pfLOD *>(node);

                DistanceLODPtr l = DistanceLOD::create();

                beginEditCP(l);

                for(int i = 0; i < lod->getNumRanges(); ++i)
                {
                    l->getRange().push_back(lod->getRange(i));
                }

                endEditCP(l);

                core = l;
            }
	    }
	    else if (node->getType()->isDerivedFrom(pfSCS::getClassType()))
	    {
            pfSCS *scs = dynamic_cast<pfSCS *>(node);
            
            if (node->getType()->isDerivedFrom(pfDCS::getClassType()))
            {
            }
            
            pfMatrix pmat;            
            scs->getMat(pmat);
            
            Matrix omat;
            
            omat.setValue( pmat[0][0], pmat[0][1], pmat[0][2], pmat[0][3], 
                           pmat[1][0], pmat[1][1], pmat[1][2], pmat[1][3], 
                           pmat[2][0], pmat[2][1], pmat[2][2], pmat[2][3], 
                           pmat[3][0], pmat[3][1], pmat[3][2], pmat[3][3]);
            
            omat.transpose();
            
            TransformPtr t = Transform::create();
            
            beginEditCP(t);
            t->setMatrix(omat);
            endEditCP(t);
            
            core = t;
	    }
	    else if (node->getType()->isDerivedFrom(pfScene::getClassType()))
	    {
            FWARNING(("PerformerLoader::traverse: encountered scene "
                      "group!\n"));
 	    }
	    else if (node->getType()->isDerivedFrom(pfLayer::getClassType()))
	    {
            FWARNING(("PerformerLoader::traverse: encountered layer "
                      "group!\n"));
	    }
        else if (node->getType() != pfGroup::getClassType())
        {
            FWARNING(("PerformerLoader::traverse: encountered unknown group"
                    " node of type %s\n", pfGetTypeName(node)));
            core = Group::create();
        }
        else
        {
            core = Group::create();
        }

	    for (;ind < num; ind++)
        {
            NodePtr cn = traverse(group->getChild(ind));
            if(cn != NullFC)
                n->addChild(cn);
        }
	}
	else if (node->getType()->isDerivedFrom(pfGeode::getClassType()))
	{
        pfGeode *geode = dynamic_cast<pfGeode *>(node);
        int num;
        
	    if (node->getType()->isDerivedFrom(pfBillboard::getClassType()))
	    {
		    num = geode->getNumGSets();
	    }
	    else if(node->getType()->isDerivedFrom(pfParaSurface::getClassType()))
	    {
            FWARNING(("PerformerLoader::traverse: encountered parametric"
                    " surface %s\n", pfGetTypeName(node)));
	    }
	    else
		    num = geode->getNumGSets();

        if(num == 1)
        {
            core = traverseGSet(n, geode->getGSet(0));
        }
        else
        {
            core = Group::create();
            
	        for (int i = 0; i < num; i++)
            {
		        GeometryPtr geo = traverseGSet(n, geode->getGSet(i));
                
                if(geo != NullFC)
                {
                    n->addChild(makeNodeFor(geo));
                }
            }
        }
	}
	else if (node->getType()->isDerivedFrom(pfLightSource::getClassType()))
	{
        FWARNING(("PerformerLoader::traverse: encountered light source!\n"));
        
	}
	else
	{
        FWARNING(("PerformerLoader::traverse: encountered unhandled node"
                " of type %s\n", pfGetTypeName(node)));
        return NullFC;
	}    
    
    if(core != NullFC)
    {
        n->setCore(core);
    }
    else
    {
        n->setCore(Group::create());
        FWARNING(("PerformerLoader::traverse: couldn't create core!\n"));
    }
    endEditCP(n);
    
    _nodes[node] = n;

    FINFO(("PfL:traverse: adding \"%s\": %p to nodelist using %p\n", 
        node->getName()?node->getName():"Unnamed",
        node, n.getCPtr()));    
    
    return n;
}