Beispiel #1
0
	SphereExample(void)
	 : sphere_instr(make_sphere.Instructions())
	 , sphere_indices(make_sphere.Indices())
	 , hole_count(50)
	 , hole_diameter(0.30f)
	{
		// This shader will be used in transform fedback mode
		// to transform the vertices used to "cut out the holes"
		// the same way the sphere is transformed
		vs_tfb.Source(
			"#version 330\n"
			"uniform mat4 CameraMatrix, ModelMatrix;"
			"uniform float Diameter;"
			"in vec3 Hole;"
			"out vec3 vertTransfHole;"
			"void main(void)"
			"{"
			"	vertTransfHole = ("
			"		CameraMatrix *"
			"		ModelMatrix *"
			"		vec4(Hole * (1.0 + 0.5 * Diameter), 0.0)"
			"	).xyz;"
			"}"
		);
		// compile, setup transform feedback output variables
		// link and use the program
		vs_tfb.Compile();
		prog_tfb.AttachShader(vs_tfb);

		const GLchar* var_name = "vertTransfHole";
		prog_tfb.TransformFeedbackVaryings(
			1, &var_name,
			TransformFeedbackMode::InterleavedAttribs
		);
		prog_tfb.Link();
		prog_tfb.Use();

		Uniform<GLfloat> diameter(prog_tfb, "Diameter");
		diameter.Set(hole_diameter);

		// bind the VAO for the holes
		holes.Bind();

		// bind the VBO for the hole vertices
		hole_verts.Bind(Buffer::Target::Array);
		// and the VBO for the transformed hole vertices captured by tfb
		transf_hole_verts.Bind(Buffer::Target::TransformFeedback);
		{
			std::vector<GLfloat> data;
			make_hole_data(data, hole_count);
			Buffer::Data(Buffer::Target::TransformFeedback, data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexArrayAttrib attr(prog_tfb, "Hole");
			attr.Setup<Vec3f>();
			attr.Enable();
		}
		transf_hole_verts.BindBase(
			Buffer::IndexedTarget::TransformFeedback,
			0
		);

		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"out vec3 vertNormal;"
			"out vec3 vertLight;"
			"const vec3 LightPos = vec3(2.0, 3.0, 3.0);"
			"void main(void)"
			"{"
			"	gl_Position = ModelMatrix * Position;"
			"	vertNormal = mat3(ModelMatrix)*Normal;"
			"	vertLight = LightPos-gl_Position.xyz;"
			"	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"in vec3 vertNormal;"
			"in vec3 vertLight;"
			"out vec4 fragColor;"
			"const int HoleCount = 50;"
			"uniform vec3 TransfHole[50];"
			"uniform float Diameter;"
			"void main(void)"
			"{"
			"	int imax = 0;"
			"	float dmax = -1.0;"
			"	for(int i=0; i!=HoleCount; ++i)"
			"	{"
			"		float d = dot(vertNormal, TransfHole[i]);"
			"		if(dmax < d)"
			"		{"
			"			dmax = d;"
			"			imax = i;"
			"		}"
			"	}"
			"	float l = length(vertLight);"
			"	vec3 FragDiff = TransfHole[imax] - vertNormal;"
			"	vec3 FinalNormal = "
			"		length(FragDiff) > Diameter?"
			"		vertNormal:"
			"		normalize(FragDiff+vertNormal*Diameter);"
			"	float i = (l > 0.0) ? dot("
			"		FinalNormal, "
			"		normalize(vertLight)"
			"	) / l : 0.0;"
			"	i = 0.2+max(i*2.5, 0.0);"
			"	fragColor = vec4(i, i, i, 1.0);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		diameter.Set(hole_diameter);

		// bind the VAO for the sphere
		sphere.Bind();

		// bind the VBO for the sphere vertices
		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_sphere.Positions(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexArrayAttrib attr(prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// bind the VBO for the sphere normals
		normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_sphere.Normals(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexArrayAttrib attr(prog, "Normal");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);
	}
Beispiel #2
0
bool
FormProcGotoParse(Units *units, Function *fn, llvm::BasicBlock *block,
                  Node *node, bool get_address, bool prefixed_with_core,
                  ParseResult *pr)
{
    Context *ctx = units->top()->ctx;

    if (!ctx->er->assertArgNums("goto", node, 1, 1)) {
        return false;
    }

    std::vector<Node *> *lst = node->list;
    Node *label_node = (*lst)[1];

    if (!ctx->er->assertArgIsAtom("goto", label_node, "1")) {
        return false;
    }
    if (!ctx->er->assertAtomIsSymbol("goto", label_node, "1")) {
        return false;
    }

    const char *label_name = label_node->token->str_value.c_str();
    Label *label = fn->getLabel(label_name);

    if (!label) {
        /* If the label does not exist, then this goto becomes a
         * deferred goto. */

        DeferredGoto *dg = new DeferredGoto;
        dg->label_name.append(label_name);
        dg->ns = ctx->ns();
        dg->index = ctx->ns()->lv_index;
        dg->block_marker = block;

        Node *myn = new Node();
        node->copyTo(myn);
        dg->node = myn;

        if (block->size() == 0) {
            dg->marker = NULL;
        } else {
            llvm::Instruction *tinstr = &(block->back());
            dg->marker = tinstr;
        }

        fn->deferred_gotos.push_back(dg);

        /* Add a no-op instruction to the block, so that label parsing
         * does not add an implicit branch from the previous block to
         * the new block.  This will occur when the previous block
         * does not end with a terminator, which will be the case here
         * because the goto is deferred. */

        llvm::IRBuilder<> builder(block);
        builder.CreateBitCast(
            ctx->nt->getLLVMZero(),
            ctx->nt->getNativeIntType()
        );
    } else {
        /* Get all the variables that exist within the current scope
         * and have an index greater than the label's index.  Add a
         * Destruct call for each of these variables. */

        std::vector<Variable *> myvars;
        ctx->ns()->getVarsAfterIndex(label->index, &myvars);
        ParseResult destruct_pr;
        destruct_pr.block = block;
        destruct_pr.do_not_destruct = false;
        llvm::IRBuilder<> builder(destruct_pr.block);
        for (std::vector<Variable *>::iterator b = myvars.begin(),
                                               e = myvars.end();
                b != e;
                ++b) {
            builder.SetInsertPoint(destruct_pr.block);
            Variable *var = (*b);
            destruct_pr.type = var->type;
            llvm::Value *var_value = builder.CreateLoad(var->value);
            destruct_pr.value = var_value;

            Operation::Destruct(ctx, &destruct_pr, &destruct_pr);
        }

        block = destruct_pr.block;
        builder.SetInsertPoint(block);
        builder.CreateBr(label->block);
    }

    pr->set(block, ctx->tr->type_int, ctx->nt->getLLVMZero());
    if (!label) {
        pr->treat_as_terminator = true;
    }
    pr->do_not_copy_with_setf = true;

    return true;
}
Beispiel #3
0
// Mesh are not committed yet
int offline_regrid(Mesh &srcmesh, Mesh &dstmesh, Mesh &dstmeshcpy,
             int *regridConserve, int *regridMethod, 
             int *regridPoleType, int *regridPoleNPnts,
             char *srcGridFile, char *dstGridFile, char *wghtFile) {

  // Conflict management
  int regridScheme = ESMC_REGRID_SCHEME_FULL3D;
  int unmappedaction = ESMC_UNMAPPEDACTION_ERROR;

  IWeights wts;
  MEField<> *src_iwts, *dst_iwts, *dst_iwtscpy;

    switch (*regridConserve) {

    // Conservative regridding
    case (ESMC_REGRID_CONSERVE_ON): {

      // Add fields to mesh
      Context ctxt; ctxt.flip();
      src_iwts = srcmesh.RegisterField("iwts",
        MEFamilyStd::instance(), MeshObj::ELEMENT, ctxt, 1, true);

      dst_iwts = dstmesh.RegisterField("iwts",
        MEFamilyStd::instance(), MeshObj::ELEMENT, ctxt, 1, true);

      // generate integration weights on the copy
      // TODO: remove this (and the dstcpy mesh passed in) when the 
      //       write bug with pole assimilation is fixed.
      dst_iwtscpy = dstmeshcpy.RegisterField("iwts",
        MEFamilyStd::instance(), MeshObj::ELEMENT, ctxt, 1, true);
      dstmeshcpy.Commit();
      Integrate dig(dstmeshcpy);
      dig.clearWeights(dst_iwtscpy);
      if (regridScheme == ESMC_REGRID_SCHEME_FULL3D) {
        for (UInt i = 1; i <= 7; ++i)
          dig.AddPoleWeights(dstmeshcpy,i,dst_iwtscpy);
      }
      dig.intWeights(dst_iwtscpy);

      // Commit the meshes
      srcmesh.Commit();
      dstmesh.Commit();

      if (!csrv(srcmesh, dstmesh, wts, src_iwts, dst_iwts, regridMethod, &regridScheme,
                regridPoleType, regridPoleNPnts, &unmappedaction))
        Throw() << "Conservative regridding error" << std::endl;
    } break;

    // NON Conservative regridding
    case (ESMC_REGRID_CONSERVE_OFF): {

      // Commit the meshes
      srcmesh.Commit();
      dstmesh.Commit();
      dstmeshcpy.Commit();

      if (!regrid(srcmesh, dstmesh, wts, regridMethod, &regridScheme,
                  regridPoleType, regridPoleNPnts, &unmappedaction))
        Throw() << "Regridding error" << std::endl;

      // the mask
      MEField<> *mask = dstmesh.GetField("MASK_IO");
      ThrowRequire(mask);
      wts.Prune(dstmesh, mask);

    } break;

    default:
      Throw() << "Regridding method:" << *regridConserve << " is not implemented";
    }

    // Redistribute weights in an IO friendly decomposition
    if (Par::Rank() == 0) std::cout << "Writing weights to " << wghtFile << std::endl;
    GatherForWrite(wts);

    // Write the weights
    WriteNCMatFilePar(srcGridFile, dstGridFile, wghtFile,
                      wts, srcmesh, dstmesh, dstmeshcpy,
                      regridConserve, regridMethod, NCMATPAR_ORDER_SEQ);

  return 1;

}
    TessellationExample(void)
        : prog()
        , projection_matrix(prog, "ProjectionMatrix")
        , camera_matrix(prog, "CameraMatrix")
    {
        VertexShader vert(ObjectDesc("Vertex"));
        vert.Source(StrLit(
                        "#version 330\n"
                        "uniform mat4 CameraMatrix;"

                        "in vec4 Position;"
                        "out vec4 vertPosition;"

                        "void main(void)"
                        "{"
                        "	vertPosition = CameraMatrix * Position;"
                        "}"
                    ));
        vert.Compile();
        prog << vert;

        TessControlShader teco(ObjectDesc("TessControl"));
        teco.Source(StrLit(
                        "#version 330\n"
                        "#extension ARB_tessellation_shader: enable\n"
                        "layout(vertices = 16) out;"

                        "in vec4 vertPosition[];"
                        "patch out vec3 tecoPosition[16];"

                        "void main(void)"
                        "{"
                        "	if(gl_InvocationID == 0)"
                        "	{"
                        "		int tl = 1-int(100.0 / vertPosition[gl_InvocationID].z);"
                        "		gl_TessLevelInner[0] = tl;"
                        "		gl_TessLevelInner[1] = tl;"
                        "		gl_TessLevelOuter[0] = tl;"
                        "		gl_TessLevelOuter[1] = tl;"
                        "		gl_TessLevelOuter[2] = tl;"
                        "		gl_TessLevelOuter[3] = tl;"
                        "	}"
                        "	tecoPosition[gl_InvocationID] = "
                        "		vertPosition[gl_InvocationID].xyz;"
                        "}"
                    ));
        teco.Compile();
        prog << teco;

        TessEvaluationShader teev(ObjectDesc("TessEvaluation"));
        teev.Source(StrLit(
                        "#version 330\n"
                        "#extension ARB_tessellation_shader: enable\n"
                        "layout(quads, equal_spacing, ccw) in;"
                        "uniform mat4 ProjectionMatrix;"
                        "patch in vec3 tecoPosition[16];"

                        "const mat4 B = mat4("
                        "	-1, 3,-3, 1,"
                        "	 3,-6, 3, 0,"
                        "	-3, 3, 0, 0,"
                        "	 1, 0, 0, 0 "
                        ");"

                        "mat4 Px, Py, Pz;"

                        "void main(void)"
                        "{"
                        "	float u = gl_TessCoord.x, v = gl_TessCoord.y;"

                        "	for(int j=0; j!=4; ++j)"
                        "	for(int i=0; i!=4; ++i)"
                        "	{"
                        "		int k = j*4+i;"
                        "		Px[j][i] = tecoPosition[k].x;"
                        "		Py[j][i] = tecoPosition[k].y;"
                        "		Pz[j][i] = tecoPosition[k].z;"
                        "	}"

                        "	mat4 Cx = B * Px * B;"
                        "	mat4 Cy = B * Py * B;"
                        "	mat4 Cz = B * Pz * B;"

                        "	vec4 up = vec4(u*u*u, u*u, u, 1);"
                        "	vec4 vp = vec4(v*v*v, v*v, v, 1);"

                        "	vec4 tempPosition = vec4(dot(Cx * vp, up), dot(Cy * vp, up), dot(Cz * vp, up), 1.0);"

                        "	gl_Position = ProjectionMatrix * tempPosition;"
                        "}"
                    ));
        teev.Compile();
        prog << teev;

        FragmentShader frag(ObjectDesc("Fragment"));
        frag.Source(StrLit(
                        "#version 330\n"
                        "out vec3 fragColor;"
                        "void main(void)"
                        "{"
                        "	fragColor = vec3(0.1, 0.1, 0.1);"
                        "}"
                    ));
        frag.Compile();
        prog << frag;

        prog.Link();
        prog.Use();

        vao.Bind();

        GLfloat patch_cp_pos[16*3] = {
            -2.0f,  0.0f, -2.0f,
            -1.0f,  0.0f, -3.0f,
            1.0f,  0.0f, -5.0f,
            2.0f,  0.0f, -2.0f,
            -1.0f,  0.0f, -1.0f,
            0.0f,  4.0f, -1.0f,
            1.0f,  4.0f, -1.0f,
            3.0f,  0.0f, -1.0f,
            -1.0f,  0.0f,  1.0f,
            -1.0f,  4.0f,  1.0f,
            0.0f,  4.0f,  1.0f,
            1.0f,  0.0f,  1.0f,
            -2.0f,  0.0f,  2.0f,
            -1.0f,  0.0f,  5.0f,
            1.0f,  0.0f,  3.0f,
            2.0f,  0.0f,  2.0f
        };
        positions.Bind(Buffer::Target::Array);
        Buffer::Data(Buffer::Target::Array, 16*3, patch_cp_pos);
        VertexAttribArray position_attr(prog, "Position");
        position_attr.Setup<Vec3f>();
        position_attr.Enable();

        gl.ClearColor(0.9f, 0.9f, 0.9f, 0.0f);
        gl.ClearDepth(1.0f);
        gl.PolygonMode(PolygonMode::Line);
        gl.PatchParameter(PatchParameter::PatchVertices, 16);
    }
Beispiel #5
0
void JSONValue::AddResourceRef(const ResourceRef& value)
{
    Context* context = file_->GetContext();
    AddString(String(context->GetTypeName(value.type_)) + ";" + value.name_);
}
    PoolTilesExample()
      : make_plane(
          Vec3f(), Vec3f(7.0f, 0.0f, 0.0f), Vec3f(0.0f, 0.0f, -7.0f), 48, 48)
      , plane_instr(make_plane.Instructions())
      , plane_indices(make_plane.Indices())
      , make_shape()
      , shape_instr(make_shape.Instructions())
      , shape_indices(make_shape.Indices())
      , plane_vs(ObjectDesc("Plane vertex"))
      , shape_vs(ObjectDesc("Shape vertex"))
      , plane_fs(ObjectDesc("Plane fragment"))
      , shape_fs(ObjectDesc("Shape fragment"))
      , plane_camera_matrix(plane_prog, "CameraMatrix")
      , shape_camera_matrix(shape_prog, "CameraMatrix")
      , plane_camera_position(plane_prog, "CameraPosition")
      , width(800)
      , height(600)
      , refl_tex_side(width > height ? height : width)
      , tile_tex_side(64) {
        gl.RequireAtLeast(LimitQuery::MaxCombinedTextureImageUnits, 5);

        plane_vs.Source(
          "#version 140\n"
          "uniform vec3 LightPosition;"
          "uniform vec3 CameraPosition;"
          "uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
          "in vec4 Position;"
          "in vec2 TexCoord;"
          "out vec3 vertLightDir;"
          "out vec3 vertViewDir;"
          "out vec4 vertReflTexCoord;"
          "out vec2 vertTileTexCoord;"
          "void main()"
          "{"
          "	gl_Position = ModelMatrix* Position;"
          "	vertLightDir = normalize(LightPosition - gl_Position.xyz);"
          "	vertViewDir = normalize(CameraPosition - gl_Position.xyz);"
          "	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
          "	vertReflTexCoord = gl_Position;"
          "	vertTileTexCoord = TexCoord;"
          "}");
        plane_vs.Compile();

        plane_fs.Source(
          "#version 140\n"
          "uniform sampler2D RandTex, PictTex, TileTex, NormTex;"
          "uniform sampler2D ReflectTex;"
          "uniform uint TileCount;"
          "uniform float Aspect;"
          "in vec3 vertLightDir;"
          "in vec3 vertViewDir;"
          "in vec4 vertReflTexCoord;"
          "in vec2 vertTileTexCoord;"
          "out vec4 fragColor;"
          "void main()"
          "{"
          "	vec3 Normal = texture("
          "		NormTex, "
          "		vertTileTexCoord * TileCount"
          "	).rgb;"
          "	vec3 LightRefl = reflect("
          "		-normalize(vertLightDir),"
          "		normalize(Normal)"
          "	);"
          "	float Diffuse = max(dot("
          "		Normal, "
          "		vertLightDir"
          "	), 0.0);"
          "	float Specular = max(dot("
          "		LightRefl,"
          "		vertViewDir"
          "	), 0.0);"
          "	float PlasterLight = 0.3 + max(Diffuse, 0.0);"
          "	float TileLight = 0.3 + pow(Diffuse, 2.0)*0.9 + pow(Specular, "
          "4.0)*2.5;"
          "	vec2 ReflCoord = vertReflTexCoord.xy;"
          "	ReflCoord /= vertReflTexCoord.w;"
          "	ReflCoord *= 0.5;"
          "	ReflCoord += vec2(Aspect*0.5, 0.5);"
          "	ReflCoord += vec2(Normal.x, Normal.z)*0.5;"
          "	vec3 ReflColor = texture("
          "		ReflectTex, "
          "		ReflCoord"
          "	).rgb;"
          "	vec3 TileProps = texture("
          "		TileTex, "
          "		vertTileTexCoord * TileCount"
          "	).rgb;"
          "	float Pict = texture(PictTex, vertTileTexCoord).r;"
          "	float Rand = texture(RandTex, vertTileTexCoord).r;"
          "	float LightVsDark = "
          "		mix( 0.1, 0.9, Pict)+"
          "		mix(-0.1, 0.1, Rand);"
          "	vec3 TileColor = mix("
          "		vec3(0.1, 0.1, 0.5),"
          "		vec3(0.4, 0.4, 0.9),"
          "		LightVsDark "
          "	);"
          "	vec3 PlasterColor = vec3(0.9, 0.9, 0.9);"
          "	fragColor = vec4("
          "		mix("
          "			PlasterColor * PlasterLight,"
          "			TileColor * TileLight, "
          "			TileProps.b"
          "		) +"
          "		ReflColor * TileProps.g * 0.6,"
          "		1.0"
          "	);"
          "}");
        plane_fs.Compile();

        plane_prog.AttachShader(plane_vs);
        plane_prog.AttachShader(plane_fs);
        plane_prog.Link();
        plane_prog.Use();

        Vec3f lightPos(3.0f, 2.5f, 2.0f);
        Uniform<Vec3f>(plane_prog, "LightPosition").Set(lightPos);
        Uniform<GLuint>(plane_prog, "TileCount").Set(tile_tex_side);
        Uniform<Mat4f>(plane_prog, "ModelMatrix")
          .Set(ModelMatrixf::Translation(0.0f, -0.5f, 0.0f));

        std::vector<GLfloat> data;
        GLuint n_per_vertex;

        n_per_vertex = make_plane.Positions(data);
        plane_verts.Data(data);
        DSAVertexArrayAttribEXT(plane, plane_prog, "Position")
          .Setup<GLfloat>(plane_verts, n_per_vertex)
          .Enable();

        n_per_vertex = make_plane.TexCoordinates(data);
        plane_texcoords.Data(data);
        DSAVertexArrayAttribEXT(plane, plane_prog, "TexCoord")
          .Setup<GLfloat>(plane_texcoords, n_per_vertex)
          .Enable();

        //
        rand_tex.target = Texture::Target::_2D;
        rand_tex.Image2D(images::RandomRedUByte(tile_tex_side, tile_tex_side));
        rand_tex.Filter(TextureFilter::Nearest);
        rand_tex.Wrap(TextureWrap::Repeat);
        Texture::Active(0);
        UniformSampler(plane_prog, "RandTex").Set(0);
        rand_tex.Bind();

        //
        pict_tex.target = Texture::Target::_2D;
        pict_tex.Image2D(images::LoadTexture("pool_pictogram"));
        pict_tex.Filter(TextureFilter::Linear);
        pict_tex.Wrap(TextureWrap::Repeat);
        Texture::Active(1);
        UniformSampler(plane_prog, "PictTex").Set(1);
        pict_tex.Bind();
        //
        auto tile_image = images::LoadTexture("small_tile");
        //
        tile_tex.target = Texture::Target::_2D;
        tile_tex.Image2D(tile_image);
        tile_tex.MinFilter(TextureMinFilter::LinearMipmapLinear);
        tile_tex.MagFilter(TextureMagFilter::Linear);
        tile_tex.Wrap(TextureWrap::Repeat);
        tile_tex.GenerateMipmap();
        Texture::Active(2);
        UniformSampler(plane_prog, "TileTex").Set(2);
        tile_tex.Bind();
        //
        norm_tex.target = Texture::Target::_2D;
        norm_tex.Image2D(images::TransformComponents<GLfloat, 3>(
          images::NormalMap(tile_image),
          Mat4d(
            Vec4d(1.0, 0.0, 0.0, 0.0),
            Vec4d(0.0, 0.0, 1.0, 0.0),
            Vec4d(0.0, -1.0, 0.0, 0.0),
            Vec4d(0.0, 0.0, 0.0, 1.0))));
        norm_tex.MinFilter(TextureMinFilter::LinearMipmapLinear);
        norm_tex.MagFilter(TextureMagFilter::Linear);
        norm_tex.Wrap(TextureWrap::Repeat);
        norm_tex.GenerateMipmap();
        Texture::Active(3);
        UniformSampler(plane_prog, "NormTex").Set(3);
        norm_tex.Bind();
        //
        reflect_tex.target = Texture::Target::_2D;
        reflect_tex.Image2D(
          0,
          PixelDataInternalFormat::RGB,
          refl_tex_side,
          refl_tex_side,
          0,
          PixelDataFormat::RGB,
          PixelDataType::UnsignedByte,
          nullptr);
        reflect_tex.Filter(TextureFilter::Linear);
        reflect_tex.Wrap(TextureWrap::ClampToEdge);
        Texture::Active(4);
        UniformSampler(plane_prog, "ReflectTex").Set(4);
        reflect_tex.Bind();

        rbo.Storage(
          PixelDataInternalFormat::DepthComponent,
          refl_tex_side,
          refl_tex_side);
        fbo.target = Framebuffer::Target::Draw;
        fbo.AttachTexture(FramebufferAttachment::Color, reflect_tex, 0);
        fbo.AttachRenderbuffer(FramebufferAttachment::Depth, rbo);

        shape_vs.Source(
          "#version 140\n"
          "uniform vec3 LightPosition;"
          "uniform mat4 ProjectionMatrix, ModelMatrix, CameraMatrix;"
          "in vec4 Position;"
          "in vec3 Normal;"
          "out vec3 vertNormal;"
          "out vec3 vertLightDir;"
          "out vec3 vertLightRefl;"
          "out vec3 vertViewDir;"
          "out vec3 vertViewRefl;"
          "out vec3 vertColor;"
          "void main()"
          "{"
          "	gl_Position = "
          "		ModelMatrix *"
          "		Position;"
          "	vertLightDir = LightPosition - gl_Position.xyz;"
          "	vertNormal = mat3(ModelMatrix)*Normal;"
          "	vertLightRefl = reflect("
          "		-normalize(vertLightDir),"
          "		normalize(vertNormal)"
          "	);"
          "	vertViewDir = ("
          "		vec4(0.0, 0.0, 1.0, 1.0)*"
          "		CameraMatrix"
          "	).xyz;"
          "	vertViewRefl = reflect("
          "		-normalize(vertViewDir),"
          "		normalize(vertNormal)"
          "	);"
          "	vertColor = vec3(0.3, 0.3, 0.7);"
          "	gl_Position = "
          "		ProjectionMatrix *"
          "		CameraMatrix *"
          "		gl_Position;"
          "}");
        shape_vs.Compile();

        shape_fs.Source(
          "#version 140\n"
          "uniform sampler2D PictTex, TileTex;"
          "uniform uint TileCount;"
          "in vec3 vertNormal;"
          "in vec3 vertLightDir;"
          "in vec3 vertLightRefl;"
          "in vec3 vertViewDir;"
          "in vec3 vertViewRefl;"
          "in vec3 vertColor;"
          "out vec4 fragColor;"

          "void main()"
          "{"
          "	float LtDist = length(vertLightDir);"
          "	float Diffuse = dot("
          "		normalize(vertNormal), "
          "		normalize(vertLightDir)"
          "	) / LtDist;"
          "	float Specular = dot("
          "		normalize(vertLightRefl),"
          "		normalize(vertViewDir)"
          "	);"
          "	vec3 LightColor = vec3(1.0, 1.0, 1.0);"
          "	vec2 ReflTexCoord = -vec2("
          "		vertViewRefl.x,"
          "		vertViewRefl.z "
          "	);"
          "	ReflTexCoord *= 0.25;"
          "	ReflTexCoord += vec2(0.5, 0.5);"
          "	float Pict = texture(PictTex, ReflTexCoord).r;"
          "	float LightVsDark = mix( 0.1, 0.9, Pict);"
          "	vec3 TileColor = mix("
          "		vec3(0.2, 0.2, 0.6),"
          "		vec3(0.5, 0.5, 0.9),"
          "		LightVsDark"
          "	);"
          "	vec3 PlasterColor = vec3(0.7, 0.7, 0.7);"
          "	vec3 FloorColor = mix("
          "		PlasterColor, "
          "		TileColor, "
          "		texture(TileTex, ReflTexCoord*TileCount).b"
          "	);"
          "	vec3 ReflColor = mix("
          "		vec3(0.5, 0.5, 0.4), "
          "		FloorColor, "
          "		pow(max((-vertViewRefl.y-0.5)*2.0, 0.0), 2.0)"
          "	);"
          "	fragColor = vec4("
          "		vertColor * 0.4 + "
          "		ReflColor * 0.3 + "
          "		(LightColor + vertColor)*pow(max(2.5*Diffuse, 0.0), 3) + "
          "		LightColor * pow(max(Specular, 0.0), 64), "
          "		1.0"
          "	);"
          "}");
        shape_fs.Compile();

        shape_prog.AttachShader(shape_vs);
        shape_prog.AttachShader(shape_fs);
        shape_prog.Link();
        shape_prog.Use();

        Uniform<Vec3f>(shape_prog, "LightPosition").Set(lightPos);
        Uniform<Mat4f>(shape_prog, "ModelMatrix")
          .Set(ModelMatrixf::Translation(0.0f, 0.6f, 0.0f));
        UniformSampler(shape_prog, "PictTex").Set(0);
        UniformSampler(shape_prog, "TileTex").Set(1);
        Uniform<GLuint>(shape_prog, "TileCount").Set(tile_tex_side);

        n_per_vertex = make_shape.Positions(data);
        shape_verts.Data(data);
        DSAVertexArrayAttribEXT(shape, shape_prog, "Position")
          .Setup<GLfloat>(shape_verts, n_per_vertex)
          .Enable();

        n_per_vertex = make_shape.Normals(data);
        shape_normals.Data(data);
        DSAVertexArrayAttribEXT(shape, shape_prog, "Normal")
          .Setup<GLfloat>(shape_normals, n_per_vertex)
          .Enable();
        //
        gl.ClearColor(0.5f, 0.5f, 0.4f, 0.0f);
        gl.ClearDepth(1.0f);
        gl.Enable(Capability::DepthTest);
    }
Beispiel #7
0
	CubeExample(void)
	 : cube_instr(make_cube.Instructions())
	 , cube_indices(make_cube.Indices())
	 , projection_matrix(prog, "ProjectionMatrix")
	 , camera_matrix(prog, "CameraMatrix")
	{
		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix;"
			"in vec4 Position;"
			"out vec3 vertColor;"
			"void main(void)"
			"{"
			"	float angle = gl_InstanceID * 10 * 2 * 3.14159 / 360.0;"
			"	float cx = cos(angle);"
			"	float sx = sin(angle);"
			"	mat4 ModelMatrix = mat4("
			"		 cx, 0.0,  sx, 0.0,"
			"		0.0, 1.0, 0.0, 0.0,"
			"		-sx, 0.0,  cx, 0.0,"
			"		0.0, 0.0, 0.0, 1.0 "
			"	) * mat4("
			"		 1.0, 0.0, 0.0, 0.0,"
			"		 0.0, 1.0, 0.0, 0.0,"
			"		 0.0, 0.0, 1.0, 0.0,"
			"		12.0, 0.0, 0.0, 1.0 "
			"	);"
			"	gl_Position = "
			"		ProjectionMatrix *"
			"		CameraMatrix *"
			"		ModelMatrix *"
			"		Position;"
			"	vertColor = abs(normalize((ModelMatrix*Position).xyz));"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"in vec3 vertColor;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	fragColor = vec4(vertColor, 1.0);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the cube
		cube.Bind();

		// bind the VBO for the cube vertices
		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_cube.Positions(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexAttribArray attr(prog, "Position");
			attr.Setup(n_per_vertex, DataType::Float);
			attr.Enable();
		}

		//
		gl.ClearColor(0.9f, 0.9f, 0.9f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);
	}
Beispiel #8
0
	CubeMapExample(void)
	 : shape_instr(make_shape.Instructions())
	 , shape_indices(make_shape.Indices())
	 , projection_matrix(prog, "ProjectionMatrix")
	 , camera_matrix(prog, "CameraMatrix")
	 , model_matrix(prog, "ModelMatrix")
	{
		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"in vec2 TexCoord;"
			"out vec3 vertNormal;"
			"out vec3 vertLightDir;"
			"out vec3 vertLightRefl;"
			"out vec3 vertViewDir;"
			"out vec3 vertViewRefl;"
			"uniform vec3 LightPos;"
			"void main(void)"
			"{"
			"	gl_Position = ModelMatrix * Position;"
			"	vertNormal = mat3(ModelMatrix)*Normal;"
			"	vertLightDir = LightPos - gl_Position.xyz;"
			"	vertLightRefl = reflect("
			"		-normalize(vertLightDir),"
			"		normalize(vertNormal)"
			"	);"
			"	vertViewDir = ("
			"		vec4(0.0, 0.0, 1.0, 1.0)*"
			"		CameraMatrix"
			"	).xyz;"
			"	vertViewRefl = reflect("
			"		normalize(vertViewDir),"
			"		normalize(vertNormal)"
			"	);"
			"	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"uniform samplerCube TexUnit;"
			"in vec3 vertNormal;"
			"in vec3 vertLightDir;"
			"in vec3 vertLightRefl;"
			"in vec3 vertViewDir;"
			"in vec3 vertViewRefl;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	float l = length(vertLightDir);"
			"	float d = dot("
			"		normalize(vertNormal), "
			"		normalize(vertLightDir)"
			"	) / l;"
			"	float s = dot("
			"		normalize(vertLightRefl),"
			"		normalize(vertViewDir)"
			"	);"
			"	vec3 lt = vec3(1.0, 1.0, 1.0);"
			"	vec3 env = texture(TexUnit, vertViewRefl).rgb;"
			"	fragColor = vec4("
			"		env * 0.4 + "
			"		(lt + env) * 1.5 * max(d, 0.0) + "
			"		lt * pow(max(s, 0.0), 64), "
			"		1.0"
			"	);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the shape
		shape.Bind();

		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Positions(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexAttribArray attr(prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Normals(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexAttribArray attr(prog, "Normal");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// setup the texture
		{
			GLuint tex_side = 256;
			auto image = images::NewtonFractal(
				tex_side, tex_side,
				Vec3f(0.3f, 0.1f, 0.2f),
				Vec3f(1.0f, 0.8f, 0.9f),
				Vec2f(-1.0f, -1.0f),
				Vec2f( 1.0f,  1.0f),
				images::NewtonFractal::X4Minus1(),
				images::NewtonFractal::DefaultMixer()
			);
			auto tex_target = Texture::Target::CubeMap;
			// texture syntax sugar
			tex << tex_target;
			tex_target << TextureMinFilter::Linear;
			tex_target << TextureMagFilter::Linear;
			tex_target << TextureWrap::ClampToEdge;

			for(int i=0; i!=6; ++i)
			{
				Texture::CubeMapFace(i) << image;
			}
		}
		// typechecked uniform with the exact sampler type
		// on compilers supporting strongly typed enums
		// you can use:
		//Typechecked<Uniform<SLtoCpp<SLDataType::SamplerCube>>>(prog, "TexUnit").Set(0);
		// without strongly typed enums you need to do:
		typedef SLtoCpp<OGLPLUS_CONST_ENUM_VALUE(SLDataType::SamplerCube)> GLSLsamplerCube;
		Typechecked<Uniform<GLSLsamplerCube>>(prog, "TexUnit").Set(0);

		//
		Uniform<Vec3f>(prog, "LightPos").Set(Vec3f(3.0f, 5.0f, 4.0f));
		//
		gl.ClearColor(0.2f, 0.05f, 0.1f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);

		gl.Enable(Capability::CullFace);
		gl.FrontFace(make_shape.FaceWinding());
		gl.CullFace(Face::Back);
	}
   // ----------------------------------------------------------------------
   void
   DrawableNodeDefault::
   draw( cairo_t* cr, double t, const Context& C )
      const throw(std::runtime_error)
   {
      Drawable::draw(cr,t,C);
      if( visible() )
         {
            shawn::Vec pos = position(t);
            double size    = node_properties().size(t);
            
            shawn::Vec bg;

            shawn::ConstTagHandle rtag = node().find_tag( "red" );
            shawn::ConstTagHandle gtag = node().find_tag( "green" );
            shawn::ConstTagHandle btag = node().find_tag( "blue" );
            //if(rtag!=NULL && gtag!=NULL && btag!=NULL)
            //{
            //   double r = dynamic_cast<const shawn::DoubleTag*>( rtag.get() )->value();
            //   double g = dynamic_cast<const shawn::DoubleTag*>( gtag.get() )->value();
            //   double b = dynamic_cast<const shawn::DoubleTag*>( btag.get() )->value();
            //   
            //   bg = shawn::Vec(r,g,b);
            //}
            //else
            //{
               bg = node_properties().background(t);
            //}



			   int shape = node_properties().shape(t);

            cairo_save(cr);
            cairo_translate(cr,pos.x(),pos.y());
            cairo_set_line_width( cr, 0 );

			   switch(shape)
			   {
			   case 2:
				   cairo_rectangle(cr,-size,-size,size*2,size*2);
				   break;
			   default:
				   cairo_arc(cr,0.0,0.0,size,0,2.0*M_PI);
				   break;
			   }
            blend_set_color(cr,bg);
            cairo_fill(cr);

            if( C.draft_level()<2 ) {
               double lw      = node_properties().line_width(t);
               shawn::Vec fg  = node_properties().foreground(t);

               cairo_set_line_width( cr, lw );
               
               switch(shape)
			      {
				   case 2:
					   cairo_rectangle(cr,-size,-size,size*2,size*2);
				   break;
				   default:
					   cairo_arc(cr,0.0,0.0,size,0,2.0*M_PI);
				   break;
			      }
                  blend_set_color(cr,fg);
                  cairo_stroke(cr);
            }

            cairo_restore(cr);
         }
   }
Beispiel #10
0
void ContextTest::extensionsString() {
    std::vector<std::string> extensions = _context.extensionStrings();

    CORRADE_VERIFY(extensions.size() > 0);
}
int main(int argc, char* argv[])
{
    XnStatus nRetVal = XN_STATUS_OK;
    nRetVal = xnLogInitFromXmlFile(SAMPLE_XML_PATH);
    if (nRetVal != XN_STATUS_OK)
    {
        printf("Log couldn't be opened: %s. Running without log", xnGetStatusString(nRetVal));
    }
    if (argc < 3)
    {
        printf("usage: %s <inputFile> <outputFile>\n", argv[0]);
        return -1;
    }
    const char* strInputFile = argv[1];
    const char* strOutputFile = argv[2];
    Context context;
    nRetVal = context.Init();
    CHECK_RC(nRetVal, "Init");
    // open input file
    Player player;
    nRetVal = context.OpenFileRecording("/media/6B58CB581C0AACF6/7.oni", player);
    CHECK_RC(nRetVal, "Open input file");
    // Get depth node from recording
    DepthGenerator depth;
    nRetVal = context.FindExistingNode(XN_NODE_TYPE_DEPTH, depth);
    CHECK_RC(nRetVal, "Find depth generator");
    // Create mock node based on depth node from recording
    MockDepthGenerator mockDepth;
    nRetVal = mockDepth.CreateBasedOn(depth);
    CHECK_RC(nRetVal, "Create mock depth node");


    ImageGenerator image;
    nRetVal = context.FindExistingNode(XN_NODE_TYPE_IMAGE, image);
    CHECK_RC(nRetVal, "Find depth generator");
    // Create mock node based on depth node from recording
    MockImageGenerator mockImage;
    nRetVal = mockImage.CreateBasedOn(image);
    CHECK_RC(nRetVal, "Create mock depth node");
    // create recorder
    Recorder recorder;
    nRetVal = recorder.Create(context);
    CHECK_RC(nRetVal, "Create recorder");
    nRetVal = recorder.SetDestination(XN_RECORD_MEDIUM_FILE, "/home/shaghayegh/up.oni");
    CHECK_RC(nRetVal, "Set recorder destination file");
    // add depth node to recorder
    nRetVal = recorder.AddNodeToRecording(mockDepth);
    CHECK_RC(nRetVal, "Add node to recording");
    // nRetVal = recorder.AddNodeToRecording(mockImage);
    // CHECK_RC(nRetVal, "Add node to recording");

    nRetVal = player.SetRepeat(FALSE);
    XN_IS_STATUS_OK(nRetVal);
    XnUInt32 nNumFrames = 0;
    nRetVal = player.GetNumFrames(depth.GetName(), nNumFrames);
    CHECK_RC(nRetVal, "Get player number of frames");
    DepthMetaData depthMD;
    ImageMetaData imageMD;
    int frameNum = 0;
    String path = "/media/6B58CB581C0AACF6/ebook/Articles/activity_recognition/data1/0512164529/";
    while ((nRetVal = depth.WaitAndUpdateData()) != XN_STATUS_EOF)
    {
        ++frameNum;
        CHECK_RC(nRetVal, "Read next frame");
        // Get depth meta data
        depth.GetMetaData(depthMD);
        image.GetMetaData(imageMD);

        //-----------------------------------------------//
        // Transform depth! This is the interesting part //
        //-----------------------------------------------//
        /* Enable the depth data to be modified. This is done implicitly by depthMD.WritableDepthMap(),
but we're calling it just to be clear. */
        nRetVal = depthMD.MakeDataWritable();
        CHECK_RC(nRetVal, "Make depth data writable");

        // nRetVal = imageMD.MakeDataWritable();
        // CHECK_RC(nRetVal, "Make depth data writable");

        String ficheroActualRGB;
        // ficheroActualRGB = path  +"RGB_" + boost::to_string(frameNum) + ".png";
        String ficheroActualDepth = path +"Depth_"+ boost::to_string(frameNum) + ".png";

        // Mat matFrameImage = imread(ficheroActualRGB, 1);
        // resize(matFrameImage, matFrameImage, Size(640, 480), 0, 0, INTER_CUBIC);
        Mat matFrameDepth = imread(ficheroActualDepth,1);
        resize(matFrameDepth, matFrameDepth, Size(480, 640), 0, 0, INTER_CUBIC);

        transformDepthMD(matFrameDepth,depthMD);
        // transformImageMD(matFrameImage,imageMD);
//         Pass the transformed data to the mock depth generator
        nRetVal = mockDepth.SetData(depthMD);
        CHECK_RC(nRetVal, "Set mock node new data");

        // nRetVal = mockImage.SetData(imageMD);
        // CHECK_RC(nRetVal, "Set mock node new data");

        /* We need to call recorder.Record explicitly because we're not using WaitAndUpdateAll(). */
        nRetVal = recorder.Record();
        CHECK_RC(nRetVal, "Record");
        printf("Recorded: frame %u out of %u\r", depthMD.FrameID(), nNumFrames);
    }
    printf("\n");
    return 0;
}
Beispiel #12
0
std::unique_ptr<Value>
VariableValueNode::getValue(const Context& context) const {
    return context.getValue(_value);
}
//--------------------------------------------------------------
void testApp::update(){
	XnStatus rc = XN_STATUS_OK;
	
	// Read a new frame
	rc = g_context.WaitAnyUpdateAll();
	if (rc != XN_STATUS_OK)
	{
		printf("Read failed: %s\n", xnGetStatusString(rc));
		return;
	}
	
	g_depth.GetMetaData(g_depthMD);
	//g_image.GetMetaData(g_imageMD);
	
	const XnDepthPixel* pDepth = g_depthMD.Data();
	
	// Calculate the accumulative histogram (the yellow display...)
	xnOSMemSet(g_pDepthHist, 0, MAX_DEPTH*sizeof(float));
	
	unsigned int nNumberOfPoints = 0;
	for (XnUInt y = 0; y < g_depthMD.YRes(); ++y)
	{
		for (XnUInt x = 0; x < g_depthMD.XRes(); ++x, ++pDepth)
		{
			if (*pDepth != 0)
			{
				g_pDepthHist[*pDepth]++;
				nNumberOfPoints++;
			}
		}
	}
	for (int nIndex=1; nIndex<MAX_DEPTH; nIndex++)
	{
		g_pDepthHist[nIndex] += g_pDepthHist[nIndex-1];
	}
	if (nNumberOfPoints)
	{
		for (int nIndex=1; nIndex<MAX_DEPTH; nIndex++)
		{
			g_pDepthHist[nIndex] = (unsigned int)(256 * (1.0f - (g_pDepthHist[nIndex] / nNumberOfPoints)));
		}
	}
	
	xnOSMemSet(g_pTexMap, 0, g_nTexMapX*g_nTexMapY*sizeof(XnRGB24Pixel));
	
	// check if we need to draw depth frame to texture
	const XnDepthPixel* pDepthRow = g_depthMD.Data();
	XnRGB24Pixel* pTexRow = g_pTexMap + g_depthMD.YOffset() * g_nTexMapX;
	
	for (XnUInt y = 0; y < g_depthMD.YRes(); ++y)
	{
		const XnDepthPixel* pDepth = pDepthRow;
		XnRGB24Pixel* pTex = pTexRow + g_depthMD.XOffset();
		
		for (XnUInt x = 0; x < g_depthMD.XRes(); ++x, ++pDepth, ++pTex)
		{
			int idx = (x + y * g_depthMD.XRes()) * 3;
			if (*pDepth != 0)
			{
				int nHistValue = g_pDepthHist[*pDepth];
				
				pixels[idx] = nHistValue;
				pixels[idx+1] = nHistValue;
				pixels[idx+2] = nHistValue;
			}
			else
			{
				pixels[idx] = 0;
				pixels[idx+1] = 0;
				pixels[idx+2] = 0;
			}
		}
		
		pDepthRow += g_depthMD.XRes();
		pTexRow += g_nTexMapX;
	}
	
	tex.loadData(pixels, 640, 480, GL_RGB);
}
Beispiel #14
0
SkImageFilter::Context SkImageFilter::mapContext(const Context& ctx) const {
    SkIRect clipBounds = this->onFilterNodeBounds(ctx.clipBounds(), ctx.ctm(),
                                                  MapDirection::kReverse_MapDirection);
    return Context(ctx.ctm(), clipBounds, ctx.cache());
}
Beispiel #15
0
	void Render(double)
	{
		gl.DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
	}
Beispiel #16
0
void Ave::stop(Context &context) {
    variableNames.clear();
    context.removeSegment(targetSegment->getId());
}
Beispiel #17
0
	RectangleExample(void)
	 : vs(ShaderType::Vertex)
	 , fs(ShaderType::Fragment)
	{
		// this could be any istream
		std::stringstream vs_source(
			"#version 330\n"
			"in vec2 Position;"
			"in vec3 Color;"
			"out vec3 vertColor;"
			"void main(void)"
			"{"
			"	vertColor = Color;"
			"	gl_Position = vec4(Position, 0.0, 1.0);"
			"}"
		);
		// set the vertex shader source
		vs.Source(GLSLSource::FromStream(vs_source));
		// compile it
		vs.Compile();

		std::stringstream fs_source(
			"#version 330\n"
			"in vec3 vertColor;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	fragColor = vec4(vertColor, 1.0);"
			"}"
		);
		// set the fragment shader source
		fs.Source(GLSLSource::FromStream(fs_source));
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the rectangle
		rectangle.Bind();

		GLfloat rectangle_verts[8] = {
			-1.0f, -1.0f,
			-1.0f,  1.0f,
			 1.0f, -1.0f,
			 1.0f,  1.0f
		};
		// bind the VBO for the rectangle vertices
		verts.Bind(Buffer::Target::Array);
		// upload the data
		Buffer::Data(Buffer::Target::Array, 8, rectangle_verts);
		// setup the vertex attribs array for the vertices
		VertexAttribArray vert_attr(prog, "Position");
		vert_attr.Setup<Vec2f>().Enable();

		GLfloat rectangle_colors[12] = {
			1.0f, 1.0f, 1.0f,
			1.0f, 0.0f, 0.0f,
			0.0f, 1.0f, 0.0f,
			0.0f, 0.0f, 1.0f,
		};
		// bind the VBO for the rectangle colors
		colors.Bind(Buffer::Target::Array);
		// upload the data
		Buffer::Data(Buffer::Target::Array, 12, rectangle_colors);
		// setup the vertex attribs array for the vertices
		VertexAttribArray color_attr(prog, "Color");
		color_attr.Setup<Vec3f>().Enable();
		//
		gl.Disable(Capability::DepthTest);
	}
Beispiel #18
0
void Ave::process(Context &context) {
    using std::min;

    const long lastSourceL = context.getLastComputableL(*sourceSegment, *this);
    const long firstTargetL = context.getFirstComputableL(*targetSegment, *this);
    long lastTargetL = (lastSourceL - sourceSegment->getGrid().getMinL() + 1) / averagingFactor;
    if (lastSourceL < sourceSegment->getGrid().getMaxL()) {
        lastTargetL--;
    }
    lastTargetL = min(lastTargetL, context.getLastComputableL(*targetSegment, *this));

    context.getLogging().debug("Segment [" + targetSegment->toString() + "]: firstComputableL = " + lexical_cast<string>(firstTargetL), getId());
    context.getLogging().debug("Segment [" + targetSegment->toString() + "]: lastComputableL = " + lexical_cast<string>(lastTargetL), getId());

    averageVariables(context.getLogging(), firstTargetL, lastTargetL);

    context.setFirstRequiredL(*sourceSegment, *this, (lastTargetL + 1) * averagingFactor);

    // TODO - this is needed for synchronizing OLC and SYN_COLLOCATED segments, better unite both segments into one
    context.setFirstRequiredL(context.getSegment(Constants::SEGMENT_OLC), *this, (lastTargetL + 1) * averagingFactor);
    if (context.getSegment(Constants::SEGMENT_OLC_MIS).getGrid().getSizeL() > 1) {
        context.setFirstRequiredL(context.getSegment(Constants::SEGMENT_OLC_MIS), *this, (lastTargetL + 1) * averagingFactor);
    }

    context.setLastComputedL(*targetSegment, *this, lastTargetL);
}
Beispiel #19
0
int CmdDelete::execute (std::string& output)
{
  int rc = 0;
  int count = 0;

  // Apply filter.
  std::vector <Task> filtered;
  filter (filtered);
  if (filtered.size () == 0)
  {
    context.footnote (STRING_FEEDBACK_NO_TASKS_SP);
    return 1;
  }

  // Apply the command line modifications to the new task.
  A3 modifications = context.a3.extract_modifications ();

  // Accumulated project change notifications.
  std::map <std::string, std::string> projectChanges;

  std::vector <Task>::iterator task;
  for (task = filtered.begin (); task != filtered.end (); ++task)
  {
    Task before (*task);

    if (task->getStatus () == Task::pending   ||
        task->getStatus () == Task::completed ||
        task->getStatus () == Task::waiting)
    {
      // Delete the specified task.
      std::string question;
      if (task->id)
        question = format (STRING_CMD_DELETE_CONFIRM,
                           task->id,
                           task->get ("description"));
      else
        question = format (STRING_CMD_DELETE_CONFIRM,
                           task->get ("uuid"),
                           task->get ("description"));

      modify_task_annotate (*task, modifications);
      task->setStatus (Task::deleted);
      if (! task->has ("end"))
        task->setEnd ();

      if (permission (*task, question, filtered.size ()))
      {
        updateRecurrenceMask (*task);
        ++count;
        context.tdb2.modify (*task);
        feedback_affected (STRING_CMD_DELETE_TASK, *task);
        feedback_unblocked (*task);
        dependencyChainOnComplete (*task);
        if (context.verbose ("project"))
          projectChanges[task->get ("project")] = onProjectChange (*task, true);

        // Delete siblings.
        if (task->has ("parent"))
        {
          std::vector <Task> siblings = context.tdb2.siblings (*task);
          if (siblings.size () &&
              confirm (STRING_CMD_DELETE_CONFIRM_R))
          {
            std::vector <Task>::iterator sibling;
            for (sibling = siblings.begin (); sibling != siblings.end (); ++sibling)
            {
              modify_task_annotate (*sibling, modifications);
              sibling->setStatus (Task::deleted);
              if (! sibling->has ("end"))
                sibling->setEnd ();

              updateRecurrenceMask (*sibling);
              context.tdb2.modify (*sibling);
              feedback_affected (STRING_CMD_DELETE_TASK_R, *sibling);
              feedback_unblocked (*sibling);
              ++count;
            }

            // Delete the parent
            Task parent;
            context.tdb2.get (task->get ("parent"), parent);
            parent.setStatus (Task::deleted);
            if (! parent.has ("end"))
              parent.setEnd ();

            context.tdb2.modify (parent);
          }
        }
      }
      else
      {
        std::cout << STRING_CMD_DELETE_NO << "\n";
        rc  = 1;
      }
    }
    else
    {
      std::cout << format (STRING_CMD_DELETE_NOT_DEL,
                           task->id,
                           task->get ("description"))
          << "\n";
      rc = 1;
    }
  }

  // Now list the project changes.
  std::map <std::string, std::string>::iterator i;
  for (i = projectChanges.begin (); i != projectChanges.end (); ++i)
    if (i->first != "")
      context.footnote (i->second);

  context.tdb2.commit ();
  feedback_affected (count == 1 ? STRING_CMD_DELETE_1 : STRING_CMD_DELETE_N, count);
  return rc;
}
Beispiel #20
0
	TessellationExample(void)
	 : shape_instr(make_shape.Instructions(PrimitiveType::Patches))
	 , shape_indices(make_shape.Indices())
	 , vs(ObjectDesc("Vertex"))
	 , cs(ObjectDesc("Tessellation Control"))
	 , es(ObjectDesc("Tessellation Evaluation"))
	 , gs(ObjectDesc("Geometry"))
	 , fs(ObjectDesc("Fragment"))
	 , projection_matrix(prog, "ProjectionMatrix")
	 , camera_matrix(prog, "CameraMatrix")
	 , model_matrix(prog, "ModelMatrix")
	 , offset(prog, "Offset")
	 , view_position(prog, "ViewPosition")
	 , viewport_dimensions(prog, "ViewportDimensions")
	{
		vs.Source(
			"#version 410\n"

			"uniform vec3 ViewPosition;"

			"in vec3 Position;"

			"out vec3 vertPosition;"
			"out float vertDistance;"

			"void main(void)"
			"{"
			"	vertPosition = Position;"
			"	vertDistance = length(ViewPosition - vertPosition);"
			"}"
		);
		vs.Compile();

		cs.Source(
			"#version 410\n"

			"layout(vertices = 3) out;"

			"in vec3 vertPosition[];"
			"in float vertDistance[];"

			"out vec3 tecoPosition[];"

			"int tessLevel(float dist)"
			"{"
			"	return int(9.0 / sqrt(dist+0.1));"
			"}"

			"void main(void)"
			"{"
			"	tecoPosition[gl_InvocationID] ="
			"		vertPosition[gl_InvocationID];"

			"	if(gl_InvocationID == 0)"
			"	{"
			"		gl_TessLevelInner[0] = tessLevel(("
			"			vertDistance[0]+"
			"			vertDistance[1]+"
			"			vertDistance[2] "
			"		)*0.333);"
			"		gl_TessLevelOuter[0] = tessLevel(("
			"			vertDistance[1]+"
			"			vertDistance[2] "
			"		)*0.5);"
			"		gl_TessLevelOuter[1] = tessLevel(("
			"			vertDistance[2]+"
			"			vertDistance[0] "
			"		)*0.5);"
			"		gl_TessLevelOuter[2] = tessLevel(("
			"			vertDistance[0]+"
			"			vertDistance[1] "
			"		)*0.5);"
			"	}"
			"}"
		);
		cs.Compile();

		es.Source(
			"#version 410\n"

			"layout(triangles, equal_spacing, ccw) in;"

			"const vec3 LightPosition = vec3(12.0, 10.0, 7.0);"

			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"

			"in vec3 tecoPosition[];"

			"out vec3 teevNormal;"
			"out vec3 teevLightDir;"

			"void main(void)"
			"{"
			"	vec3 p0 = gl_TessCoord.x * tecoPosition[0];"
			"	vec3 p1 = gl_TessCoord.y * tecoPosition[1];"
			"	vec3 p2 = gl_TessCoord.z * tecoPosition[2];"

			"	vec4 tempPosition = vec4(normalize(p0+p1+p2), 0.0);"
			"	teevNormal = (ModelMatrix * tempPosition).xyz;"
			"	tempPosition.w = 1.0;"
			"	tempPosition = ModelMatrix * tempPosition;"
			"	teevLightDir = LightPosition - tempPosition.xyz;"
			"	gl_Position = "
			"		ProjectionMatrix *"
			"		CameraMatrix *"
			"		tempPosition;"
			"}"
		);
		es.Compile();

		gs.Source(
			"#version 410\n"
			"layout (triangles) in;"
			"layout (triangle_strip, max_vertices = 3) out;"

			"uniform vec3 Offset;"
			"uniform vec2 ViewportDimensions;"

			"in vec3 teevNormal[], teevLightDir[];"

			"noperspective out vec3 geomDist;"
			"flat out vec3 geomNormal;"
			"out vec3 geomColor;"
			"out vec3 geomLightDir;"

			"void main(void)"
			"{"
			"	geomNormal = normalize("
			"		teevNormal[0]+"
			"		teevNormal[1]+"
			"		teevNormal[2]"
			"	);"

			"	vec2 ScreenPos[3];"
			"	for(int i=0; i!=3; ++i)"
			"	{"
			"		ScreenPos[i] = "
			"			ViewportDimensions*"
			"			gl_in[i].gl_Position.xy/"
			"			gl_in[i].gl_Position.w;"
			"	}"

			"	vec2 TmpVect[3];"
			"	for(int i=0; i!=3; ++i)"
			"	{"
			"		TmpVect[i] = "
			"			ScreenPos[(i+2)%3]-"
			"			ScreenPos[(i+1)%3];"
			"	}"

			"	const vec3 EdgeMask[3] = vec3[3]("
			"		vec3(1.0, 0.0, 0.0),"
			"		vec3(0.0, 1.0, 0.0),"
			"		vec3(0.0, 0.0, 1.0) "
			"	);"

			"	for(int i=0; i!=3; ++i)"
			"	{"
			"		float Dist = abs("
			"			TmpVect[(i+1)%3].x*TmpVect[(i+2)%3].y-"
			"			TmpVect[(i+1)%3].y*TmpVect[(i+2)%3].x "
			"		) / length(TmpVect[i]);"
			"		vec3 DistVect = vec3(Dist, Dist, Dist);"

			"		gl_Position = gl_in[i].gl_Position;"
			"		geomColor = normalize(abs("
			"			vec3(2.0, 2.0, 2.0)-"
			"			teevNormal[i]-"
			"			Offset"
			"		));"
			"		geomLightDir = teevLightDir[i];"
			"		geomDist = EdgeMask[i] * DistVect;"
			"		EmitVertex();"
			"	}"
			"	EndPrimitive();"
			"}"
		);
		gs.Compile();

		fs.Source(
			"#version 410\n"

			"noperspective in vec3 geomDist;"
			"flat in vec3 geomNormal;"
			"in vec3 geomColor;"
			"in vec3 geomLightDir;"

			"out vec3 fragColor;"

			"void main(void)"
			"{"
			"	float MinDist = min(min(geomDist.x,geomDist.y),geomDist.z);"
			"	float EdgeAlpha = exp2(-pow(MinDist, 2.0));"

			"	const float Ambient = 0.8;"
			"	float Diffuse = max(dot("
			"		normalize(geomNormal),"
			"		normalize(geomLightDir)"
			"	), 0.0);"

			"	vec3 FaceColor = geomColor * (Diffuse + Ambient);"
			"	const vec3 EdgeColor = vec3(0.0, 0.0, 0.0);"

			"	fragColor = mix(FaceColor, EdgeColor, EdgeAlpha);"
			"}"
		);
		fs.Compile();

		prog.AttachShader(vs);
		prog.AttachShader(cs);
		prog.AttachShader(es);
		prog.AttachShader(gs);
		prog.AttachShader(fs);
		prog.Link();
		prog.Use();

		shape.Bind();

		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Positions(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexAttribArray attr(prog, "Position");
			attr.Setup(n_per_vertex, DataType::Float);
			attr.Enable();

			indices.Bind(Buffer::Target::ElementArray);
			Buffer::Data(Buffer::Target::ElementArray, shape_indices);
			shape_indices.clear();
		}

		//
		gl.ClearColor(0.8f, 0.8f, 0.8f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);

		prog.Use();
	}
/*
 * This one is specified in, and called from, AppleKeyPairGenContext
 */
void DSAKeyPairGenContext::generate(
	const Context 	&context,
	BinaryKey		&pubBinKey,	
	BinaryKey		&privBinKey,
	uint32			&keyBits)
{
	/* 
	 * These casts throw exceptions if the keys are of the 
	 * wrong classes, which would be a major bogon, since we created
	 * the keys in the above generate() function.
	 */
	DSABinaryKey &rPubBinKey = 
		dynamic_cast<DSABinaryKey &>(pubBinKey);
	DSABinaryKey &rPrivBinKey = 
		dynamic_cast<DSABinaryKey &>(privBinKey);

	/*
	 * Parameters from context: 
	 *   Key size in bits, required;
	 *   {p,q,g} from generateParams, optional
	 */
	keyBits = context.getInt(CSSM_ATTRIBUTE_KEY_LENGTH,
				CSSMERR_CSP_MISSING_ATTR_KEY_LENGTH);
	if(keyBits > DSA_MAX_KEY_SIZE) {
		CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_KEY_LENGTH);
	}
	CssmData *paramData = context.get<CssmData>(CSSM_ATTRIBUTE_ALG_PARAMS);

	NSS_DSAAlgParams algParams;
	SecNssCoder coder;			// generated algParams mallocd from here
	if(paramData != NULL) {
		/* this contains the DER encoding of a NSS_DSAAlgParams */
		CSSM_RETURN crtn = DSADecodeAlgParams(algParams, paramData->Data,
			(unsigned)paramData->Length, coder);
		if(crtn) {
			CssmError::throwMe(crtn);
		}
	}
	else {
		/* no alg params specified; generate them now using null (random) seed */
		dsaGenParams(keyBits, NULL, 0, algParams, coder);
	}
					
	/* create key, stuff params into it */
	rPrivBinKey.mDsaKey = DSA_new();
	if(rPrivBinKey.mDsaKey == NULL) {
		CssmError::throwMe(CSSMERR_CSP_MEMORY_ERROR);		
	}
	DSA *dsaKey = rPrivBinKey.mDsaKey;
	dsaKey->p = cssmDataToBn(algParams.p);
	dsaKey->q = cssmDataToBn(algParams.q);
	dsaKey->g = cssmDataToBn(algParams.g);
	
	/* generate the key (both public and private capabilities) */
	int irtn = DSA_generate_key(dsaKey);
	if(!irtn) {
		throwRsaDsa("DSA_generate_key");
	}
	
	/* public key is subset of private key */
	rPubBinKey.mDsaKey = DSA_new();
	if(rPrivBinKey.mDsaKey == NULL) {
		CssmError::throwMe(CSSMERR_CSP_MEMORY_ERROR);	
	}
	DSA *pub     = rPubBinKey.mDsaKey;
	DSA *priv    = rPrivBinKey.mDsaKey;
	pub->p       = BN_dup(priv->p);
	pub->q       = BN_dup(priv->q);
	pub->g       = BN_dup(priv->g);
	pub->pub_key = BN_dup(priv->pub_key);
	if((pub->p == NULL) || (pub->q == NULL) || (pub->g == NULL) ||
			(pub->pub_key == NULL)) {
		CssmError::throwMe(CSSMERR_CSP_MEMORY_ERROR);		
	}
}
Beispiel #22
0
int
Generator::run(std::vector<const char *> *file_paths,
               std::vector<const char *> *bc_file_paths,
               std::vector<const char *> *compile_lib_paths,
               std::vector<const char *> *include_paths,
               std::vector<const char *> *module_paths,
               std::vector<const char *> *static_module_names,
               std::vector<const char *> *cto_module_names,
               const char *module_name,
               int debug,
               int produce,
               int optlevel,
               int remove_macros,
               int no_common,
               int no_dale_stdlib,
               int static_mods_all,
               int enable_cto,
               std::vector<std::string> *shared_object_paths,
               FILE *output_file)
{
    if (!file_paths->size()) {
        return 0;
    }

    NativeTypes nt;
    TypeRegister tr;
    llvm::ExecutionEngine *ee = NULL;

    std::set<std::string> cto_modules;
    for (std::vector<const char*>::iterator
            b = cto_module_names->begin(),
            e = cto_module_names->end();
            b != e;
            ++b) {
        cto_modules.insert(std::string(*b));
    }

    /* On OS X, SYSTEM_PROCESSOR is i386 even when the underlying
     * processor is x86-64, hence the extra check here. */
    bool is_x86_64 =
        ((!strcmp(SYSTEM_PROCESSOR, "x86_64"))
         || ((!strcmp(SYSTEM_PROCESSOR, "amd64")))
         || ((!strcmp(SYSTEM_NAME, "Darwin"))
             && (sizeof(char *) == 8)));

    init_introspection_functions();

    llvm::Module *last_module = NULL;

    Module::Reader mr(module_paths, shared_object_paths, include_paths);
    for (std::vector<const char*>::iterator b = compile_lib_paths->begin(),
                                            e = compile_lib_paths->end();
            b != e;
            ++b) {
        mr.addDynamicLibrary((*b), false, false);
    }

    const char *libdrt_path = NULL;
    if (!no_dale_stdlib) {
        FILE *drt_file = NULL;
        if ((drt_file = fopen(DALE_LIBRARY_PATH "/libdrt.so", "r"))) {
            libdrt_path = DALE_LIBRARY_PATH "/libdrt.so";
        } else if ((drt_file = fopen("./libdrt.so", "r"))) {
            libdrt_path = "./libdrt.so";
        } else {
            error("unable to find libdrt.so");
        }
        mr.addDynamicLibrary(libdrt_path, false, false);
        int res = fclose(drt_file);
        if (res != 0) {
            error("unable to close %s", libdrt_path, true);
        }
    }
    if (!module_name && libdrt_path) {
        shared_object_paths->push_back(libdrt_path);
    }

    Units units(&mr);
    units.cto            = enable_cto;
    units.no_common      = no_common;
    units.no_dale_stdlib = no_dale_stdlib;

    Context *ctx         = NULL;
    llvm::Module *mod    = NULL;
    llvm::Linker *linker = NULL;

    ErrorReporter er("");
    if (module_name) {
        const char *last_slash = strrchr(module_name, '/');
        std::string bare_module_name;
        if (!last_slash) {
            last_slash = module_name;
            bare_module_name = std::string(last_slash);
        } else {
            bare_module_name = std::string(last_slash + 1);
        }
        if (bare_module_name.length() > 0) {
            if (!isValidModuleName(&bare_module_name)) {
                Error *e = new Error(
                    ErrorInst::InvalidModuleName, NULL,
                    bare_module_name.c_str()
                );
                er.addError(e);
                return 0;
            }
        }
        int diff = last_slash - module_name;
        units.module_name = std::string(module_name);
        units.module_name.replace(diff + 1, 0, "lib");
    }

    for (std::vector<const char*>::iterator b = file_paths->begin(),
                                            e = file_paths->end();
            b != e;
            ++b) {
        const char *filename = *b;
        assert(!units.size());

        Unit *unit = new Unit(filename, &units, &er, &nt, &tr, NULL, is_x86_64);
        units.push(unit);
        ctx    = unit->ctx;
        mod    = unit->module;
        linker = unit->linker;

        llvm::Triple triple(mod->getTargetTriple());
        if (triple.getTriple().empty()) {
            triple.setTriple(getTriple());
        }
        mod->setDataLayout((is_x86_64) ? x86_64_layout : x86_32_layout);

        llvm::EngineBuilder eb = llvm::EngineBuilder(mod);
        eb.setEngineKind(llvm::EngineKind::JIT);
        ee = eb.create();
        assert(ee);
        ee->InstallLazyFunctionCreator(&lazyFunctionCreator);

        unit->ee = ee;
        unit->mp->ee = ee;

        CommonDecl::addVarargsFunctions(unit);

        if (!no_common) {
            if (no_dale_stdlib) {
                unit->addCommonDeclarations();
            } else {
                std::vector<const char*> import_forms;
                mr.run(ctx, mod, nullNode(), "drt", &import_forms);
                units.top()->mp->setPoolfree();
            }
        }

        std::vector<Node*> nodes;
        for (;;) {
            int error_count = er.getErrorTypeCount(ErrorType::Error);
            Node *top = units.top()->parser->getNextList();
            if (top) {
                nodes.push_back(top);
            }

            if (er.getErrorTypeCount(ErrorType::Error) > error_count) {
                er.flush();
                continue;
            }
            if (!top) {
                er.flush();
                break;
            }

            if (!top->is_token && !top->is_list) {
                units.pop();
                if (!units.empty()) {
                    Unit *unit = units.top();
                    ctx    = unit->ctx;
                    mod    = unit->module;
                    linker = unit->linker;
                    continue;
                }
                break;
            }
            FormTopLevelInstParse(&units, top);
            er.flush();
        }

        if (remove_macros) {
            ctx->eraseLLVMMacros();
        }

        if (dale::pool_free_fptr) {
            ee->freeMachineCodeForFunction(dale::pool_free_fn);
        }

        if (last_module) {
            linkModule(linker, last_module);
        }

        last_module = mod;

        for (std::vector<Node *>::iterator b = nodes.begin(),
                                           e = nodes.end();
                b != e;
                ++b) {
            delete (*b);
        }
    }

    if (remove_macros) {
        ctx->eraseLLVMMacros();
    }

    if (er.getErrorTypeCount(ErrorType::Error)) {
        return 0;
    }

    if (bc_file_paths) {
        for (std::vector<const char*>::iterator b = bc_file_paths->begin(),
                                                e = bc_file_paths->end();
                b != e;
                ++b) {
            linkFile(linker, *b);
        }
    }

    /* At optlevel 3, things go quite awry when making libraries, due
     * to the argumentPromotionPass. So set it to 2, unless LTO has
     * also been requested (optlevel == 4). */
    bool lto = false;
    if (optlevel == 3) {
        optlevel = 2;
    } else if (optlevel == 4) {
        optlevel = 3;
        lto = true;
    }

    llvm::TargetMachine *target_machine = getTargetMachine(last_module);
    llvm::raw_fd_ostream ostream(fileno(output_file), false);

    llvm::PassManager pass_manager;
    addDataLayout(&pass_manager, mod);
    pass_manager.add(llvm::createPostDomTree());

    llvm::PassManagerBuilder pass_manager_builder;
    pass_manager_builder.OptLevel = optlevel;
    pass_manager_builder.DisableUnitAtATime = true;

    if (optlevel > 0) {
        if (lto) {
            pass_manager_builder.DisableUnitAtATime = false;
        }
        pass_manager_builder.populateModulePassManager(pass_manager);
        if (lto) {
            pass_manager_builder.populateLTOPassManager(pass_manager, true, true);
        }
    }

    if (units.module_name.size() > 0) {
        Module::Writer mw(units.module_name, ctx, mod, &pass_manager,
                          &(mr.included_once_tags), &(mr.included_modules),
                          units.cto);
        mw.run();
        return 1;
    }

    std::map<std::string, llvm::Module*> *dtm_modules = &(mr.dtm_modules);
    std::map<std::string, std::string> *dtm_nm_modules = &(mr.dtm_nm_modules);

    bool reget_pointers = true;
    std::map<std::string, llvm::Module *> static_dtm_modules;
    if (static_mods_all || (static_module_names->size() > 0)) {
        if (remove_macros) {
            for (std::map<std::string, std::string>::iterator
                    b = dtm_nm_modules->begin(),
                    e = dtm_nm_modules->end();
                    b != e; ++b) {
                static_dtm_modules.insert(
                    std::pair<std::string, llvm::Module*>(
                        b->first,
                        mr.loadModule(&(b->second))
                    )
                );
            }
        } else {
            static_dtm_modules = *dtm_modules;
        }
        reget_pointers = false;
    }

    if (static_mods_all) {
        for (std::map<std::string, llvm::Module *>::iterator
                b = static_dtm_modules.begin(),
                e = static_dtm_modules.end();
                b != e; ++b) {
            if (cto_modules.find(b->first) == cto_modules.end()) {
                linkModule(linker, b->second);
            }
        }
    } else if (static_module_names->size() > 0) {
        for (std::vector<const char *>::iterator b =
                    static_module_names->begin(), e =
                    static_module_names->end();
                b != e; ++b) {
            std::map<std::string, llvm::Module *>::iterator
            found = static_dtm_modules.find(std::string(*b));
            if (found != static_dtm_modules.end()) {
                linkModule(linker, found->second);
            }
        }
        reget_pointers = false;
    }

    if (reget_pointers) {
        ctx->regetPointers(mod);
    }
    if (remove_macros) {
        ctx->eraseLLVMMacrosAndCTOFunctions();
    }

    llvm::formatted_raw_ostream *ostream_formatted =
        new llvm::formatted_raw_ostream(
            ostream,
            llvm::formatted_raw_ostream::DELETE_STREAM
        );

    if (produce == IR) {
        addPrintModulePass(&pass_manager, &ostream);
    } else if (produce == ASM) {
        target_machine->setAsmVerbosityDefault(true);
        llvm::CodeGenOpt::Level level = llvm::CodeGenOpt::Default;
        bool res = target_machine->addPassesToEmitFile(
            pass_manager, *ostream_formatted,
            llvm::TargetMachine::CGFT_AssemblyFile,
            level, NULL);
        assert(!res && "unable to add passes to emit file");
        _unused(res);
    }

    if (debug) {
        mod->dump();
    }
    if (debug) {
        llvm::verifyModule(*mod);
    }
    pass_manager.run(*mod);

    if (produce == BitCode) {
        llvm::WriteBitcodeToFile(mod, ostream);
    }

    ostream_formatted->flush();
    ostream.flush();

    return 1;
}
Beispiel #23
0
void JSONValue::SetResourceRef(const String& name, const ResourceRef& value)
{
    Context* context = file_->GetContext();
    SetString(name, String(context->GetTypeName(value.type_)) + ";" + value.name_);
}
Beispiel #24
0
    TorusExample(void)
        : make_torus(1.0, 0.5, 18, 36)
        , torus_instr(make_torus.Instructions())
        , torus_indices(make_torus.Indices())
        , vs(ObjectDesc("Vertex"))
        , gs(ObjectDesc("Geometry"))
        , face_fs(ObjectDesc("Face fragment"))
        , frame_fs(ObjectDesc("Frame fragment"))
        , transf_prog(ObjectDesc("Transformation"))
        , face_prog(ObjectDesc("Face"))
        , frame_prog(ObjectDesc("Frame"))
        , projection_matrix(transf_prog, "ProjectionMatrix")
        , camera_matrix(transf_prog, "CameraMatrix")
        , model_matrix(transf_prog, "ModelMatrix")
        , transf_time(transf_prog, "Time")
    {
        vs.Source(
            "#version 330\n"
            "uniform mat4 ModelMatrix;"
            "in vec4 Position;"
            "in vec3 Normal;"
            "in vec2 TexCoord;"
            "out gl_PerVertex {"
            "	vec4 gl_Position;"
            "};"
            "out vec3 vertNormal;"
            "out vec2 vertTexCoord;"
            "void main(void)"
            "{"
            "	gl_Position = ModelMatrix * Position;"
            "	vertNormal = (ModelMatrix*vec4(Normal,0.0)).xyz;"
            "	vertTexCoord = TexCoord;"
            "}"
        );
        vs.Compile();

        gs.Source(
            "#version 330\n"
            "layout(triangles) in;"
            "layout(triangle_strip, max_vertices = 15) out;"
            "uniform mat4 CameraMatrix, ProjectionMatrix;"
            "uniform vec3 LightPos;"
            "uniform float Time;"
            "in gl_PerVertex {"
            "	vec4 gl_Position;"
            "} gl_in[];"
            "in vec3 vertNormal[];"
            "in vec2 vertTexCoord[];"
            "out gl_PerVertex {"
            "	vec4 gl_Position;"
            "};"
            "out vec3 geomNormal;"
            "out vec3 geomLight;"
            "out float geomGlow;"
            "flat out int geomTop;"
            "void main(void)"
            "{"
            "	vec3 FaceNormal = normalize("
            "		vertNormal[0]+"
            "		vertNormal[1]+"
            "		vertNormal[2] "
            "	);"
            "	vec2 FaceCoord = 0.33333 * ("
            "		vertTexCoord[0]+"
            "		vertTexCoord[1]+"
            "		vertTexCoord[2] "
            "	);"
            "	float Offs = (sin((FaceCoord.s + Time/10.0)* 3.14 * 2.0 * 10)*0.5 + 0.5)*0.4;"
            "	Offs *= cos(FaceCoord.t * 3.1415 * 2.0)*0.5 + 0.51;"

            "	vec3 pos[3], norm[3];"
            "	for(int i=0; i!=3; ++i)"
            "		pos[i] = gl_in[i].gl_Position.xyz;"
            "	for(int i=0; i!=3; ++i)"
            "		norm[i] = cross("
            "			FaceNormal, "
            "			normalize(pos[(i+1)%3] - pos[i])"
            "		);"
            "	vec3 pofs = FaceNormal * Offs;"

            "	geomTop = 0;"
            "	for(int i=0; i!=3; ++i)"
            "	{"
            "		geomNormal = norm[i];"
            "		for(int j=0; j!=2; ++j)"
            "		{"
            "			vec3 tpos = pos[(i+j)%3];"
            "			geomLight = LightPos-tpos;"
            "			geomGlow = 1.0;"
            "			gl_Position = "
            "				ProjectionMatrix *"
            "				CameraMatrix *"
            "				vec4(tpos, 1.0);"
            "			EmitVertex();"
            "			geomGlow = 0.7;"
            "			geomLight = LightPos-tpos+pofs;"
            "			gl_Position = "
            "				ProjectionMatrix *"
            "				CameraMatrix *"
            "				vec4(tpos + pofs, 1.0);"
            "			EmitVertex();"
            "		}"
            "		EndPrimitive();"
            "	}"

            "	geomGlow = 0.0;"
            "	geomTop = 1;"
            "	for(int i=0; i!=3; ++i)"
            "	{"
            "		geomLight = LightPos - (pos[i]+pofs);"
            "		geomNormal = vertNormal[i];"
            "		gl_Position = "
            "			ProjectionMatrix *"
            "			CameraMatrix *"
            "			vec4(pos[i] + pofs, 1.0);"
            "		EmitVertex();"
            "	}"
            "	EndPrimitive();"
            "}"
        );
        gs.Compile();

        transf_prog.AttachShader(vs);
        transf_prog.AttachShader(gs);
        transf_prog.MakeSeparable();
        transf_prog.Link();
        transf_prog.Use();

        ProgramUniform<Vec3f>(transf_prog, "LightPos").Set(4, 4, -8);

        torus.Bind();
        verts.Bind(Buffer::Target::Array);
        {
            std::vector<GLfloat> data;
            GLuint n_per_vertex = make_torus.Positions(data);
            Buffer::Data(Buffer::Target::Array, data);

            VertexAttribArray attr(transf_prog, "Position");
            attr.Setup<GLfloat>(n_per_vertex);
            attr.Enable();
        }

        normals.Bind(Buffer::Target::Array);
        {
            std::vector<GLfloat> data;
            GLuint n_per_vertex = make_torus.Normals(data);
            Buffer::Data(Buffer::Target::Array, data);

            VertexAttribArray attr(transf_prog, "Normal");
            attr.Setup<GLfloat>(n_per_vertex);
            attr.Enable();
        }

        texcoords.Bind(Buffer::Target::Array);
        {
            std::vector<GLfloat> data;
            GLuint n_per_vertex = make_torus.TexCoordinates(data);
            Buffer::Data(Buffer::Target::Array, data);

            VertexAttribArray attr(transf_prog, "TexCoord");
            attr.Setup<GLfloat>(n_per_vertex);
            attr.Enable();
        }

        face_fs.Source(
            "#version 330\n"
            "in vec3 geomNormal;"
            "in vec3 geomLight;"
            "in float geomGlow;"
            "flat in int geomTop;"
            "uniform vec3 TopColor, SideColor;"
            "const vec3 LightColor = vec3(1.0, 1.0, 1.0);"
            "out vec4 fragColor;"
            "void main(void)"
            "{"
            "	float d = max(dot("
            "		normalize(geomLight),"
            "		normalize(geomNormal)"
            "	), 0.0);"
            "	vec3 color;"
            "	if(geomTop != 0)"
            "	{"
            "		color = TopColor * d +"
            "			LightColor * pow(d, 8.0);"
            "	}"
            "	else"
            "	{"
            "		color = SideColor * geomGlow +"
            "			LightColor *"
            "			pow(d, 2.0) * 0.2;"
            "	}"
            "	fragColor = vec4(color, 1.0);"
            "}"
        );
        face_fs.Compile();

        face_prog.AttachShader(face_fs);
        face_prog.MakeSeparable();
        face_prog.Link();

        ProgramUniform<Vec3f>(face_prog, "TopColor").Set(0.2f, 0.2f, 0.2f);
        ProgramUniform<Vec3f>(face_prog, "SideColor").Set(0.9f, 0.9f, 0.2f);

        face_pp.Bind();
        face_prog.Use();
        face_pp.UseStages(transf_prog).Vertex().Geometry();
        face_pp.UseStages(face_prog).Fragment();


        frame_fs.Source(
            "#version 330\n"
            "out vec4 fragColor;"
            "void main(void)"
            "{"
            "	fragColor = vec4(0.2, 0.1, 0.0, 1.0);"
            "}"
        );
        frame_fs.Compile();

        frame_prog.AttachShader(frame_fs);
        frame_prog.MakeSeparable();
        frame_prog.Link();

        frame_pp.Bind();
        frame_prog.Use();
        frame_pp.UseStages(transf_prog).Vertex().Geometry();
        frame_pp.UseStages(frame_prog).Fragment();

        ProgramPipeline::Unbind();
        Program::UseNone();

        gl.ClearColor(0.7f, 0.6f, 0.5f, 0.0f);
        gl.ClearDepth(1.0f);
        gl.Enable(Capability::DepthTest);
        gl.DepthFunc(CompareFn::Less);
        gl.FrontFace(make_torus.FaceWinding());
    }
int recorder::record()
{
    Recording = true;
    qDebug("//////////////////////////////////////");
    qDebug("/// Welcome to the Kinect Recorder!///");
    qDebug("/// Press any key to STOP recording!//\n");

    bool record_rgb=true;

    //Metadata
    QFileInfo MetadataFile;
    MetadataFile.setFile(QDir::currentPath() + "/Metadata.txt");

    ofstream Metadata_file;

    if(MetadataFile.exists()){
        qDebug("Metadata File exists ");
        Metadata_file.open(MetadataFile.absoluteFilePath().toLocal8Bit(), ofstream::out | ofstream::app);
        Metadata_file.close();
    }
    else{
        qDebug("Metadata File doesn't exist ");
        Metadata_file.open(MetadataFile.absoluteFilePath().toLocal8Bit(), ofstream::out | ofstream::app);
        Metadata_file.close();
    }

    //Status variable
    XnStatus nRetVal = XN_STATUS_OK;

    //Context
    Context context;
    nRetVal = context.Init();

    //Vectors of Generators
    DepthGenerator DepthsGen[MAXGENERATORS];
    ImageGenerator ImagesGen[MAXGENERATORS];
    Recorder Recorders[MAXGENERATORS];

    //Node list.
    NodeInfoList node_info_list;
    NodeInfoList depth_nodes;
    NodeInfoList img_nodes;

    int nKinects = 0;
    int nDepths = 0;
    int nImg = 0;
    int Frames=0;

    //Enumeramos los nodos
    nRetVal = context.EnumerateProductionTrees(XN_NODE_TYPE_DEVICE, NULL,node_info_list);

    //Comprobamos la enumeración
    if(nRetVal != XN_STATUS_OK && node_info_list.Begin() != node_info_list.End()){
        qDebug ("Enumerating devices failed. Reason: %s", xnGetStatusString(nRetVal));
        return -1;
    }

    else if(node_info_list.Begin () == node_info_list.End()){
        qDebug("No devices found.\n");
        return -1;
    }

    for (xn::NodeInfoList::Iterator nodeIt = node_info_list.Begin(); nodeIt != node_info_list.End(); ++nodeIt){
        NodeInfo info = *nodeIt;
        const XnProductionNodeDescription& description = info.GetDescription();
        qDebug("Info: vendor %s name %s , instance %s",description.strVendor,description.strName, info.GetInstanceName());
    }

    //Count number of devices available for recording
    for (NodeInfoList::Iterator nodeIt = node_info_list.Begin(); nodeIt != node_info_list.End(); ++nodeIt){
        nKinects++;
    }
    qDebug("Number of Devices %d", nKinects);

    //Enumerate depth Devices
    nRetVal = context.EnumerateProductionTrees(XN_NODE_TYPE_DEPTH, NULL, depth_nodes, NULL);
    if (nRetVal != XN_STATUS_OK && depth_nodes.Begin () != depth_nodes.End ()) {
        qDebug ("Enumerating devices failed. Reason: %s", xnGetStatusString (nRetVal));
        return -1;
    }
    else if (depth_nodes.Begin () == depth_nodes.End ()) {
        qDebug("No devices found.\n");
        return -1;
    }

    //Enumerate RGB Devices
    if(record_rgb){
        //IMAGE devices
        nRetVal = context.EnumerateProductionTrees(XN_NODE_TYPE_IMAGE, NULL, img_nodes, NULL);
        if (nRetVal != XN_STATUS_OK && img_nodes.Begin () != img_nodes.End ()) {
            qDebug ("Enumerating devices failed. Reason: %s", xnGetStatusString (nRetVal));
            return -1;
        }
        else if (img_nodes.Begin () == img_nodes.End ()) {
            qDebug("No devices found.\n");
            return -1;
        }
    }

    //Show depth devices
    int i = 0;
    for (xn::NodeInfoList::Iterator nodeIt = depth_nodes.Begin(); nodeIt != depth_nodes.End(); ++nodeIt, i++) {
        NodeInfo info = *nodeIt;
        const XnProductionNodeDescription& description = info.GetDescription();
        qDebug("Depth: vendor %s name %s, instance %s",description.strVendor,description.strName, info.GetInstanceName());
        nDepths++;
    }

    //Show RGB Devices
    if(record_rgb){
        //RGB devices
        i = 0;
        for (xn::NodeInfoList::Iterator nodeIt = img_nodes.Begin(); nodeIt != img_nodes.End(); ++nodeIt, i++) {
            NodeInfo info = *nodeIt;
            const XnProductionNodeDescription& description = info.GetDescription();
            qDebug("RGB: vendor %s name %s, instance %s",description.strVendor,description.strName, info.GetInstanceName());
            nImg++;
        }

    }

    //Init everything
    i=0;
    char date[20];
    strcpy(date,QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss").toLocal8Bit());
    qDebug() << date;

    //Init depth devices & 'recorders'
    DepthGenerator depthaux[MAXGENERATORS];
    Recorder recorderaux[MAXGENERATORS];

    for (xn::NodeInfoList::Iterator nodeIt = depth_nodes.Begin(); nodeIt != depth_nodes.End(); ++nodeIt, i++) {
        //DepthGenerator depthaux;
        //Recorder recorderaux;
        XNFiles AuxFile;
        NodeInfo info = *nodeIt;
        const XnProductionNodeDescription& description = info.GetDescription();

        nRetVal = context.CreateProductionTree(info,depthaux[i]);
        nRetVal = info.GetInstance(depthaux[i]);
        qDebug("Instance Name %s",info.GetInstanceName());

        XnFieldOfView field;
        nRetVal= depthaux[i].GetFieldOfView(field);

        DepthsGen[i]=depthaux[i];
        qDebug("Depth Generator %i", i);

        Recorders[i]=recorderaux[i];
        nRetVal = Recorders[i].Create(context);

        XnChar recording_fileXnaux[300];
        strcpy(recording_fileXnaux,QDir::currentPath().toLocal8Bit());

        if(record_rgb)
            sprintf(recording_fileXnaux,"%s%s%s%d%s%s.oni",recording_fileXnaux,"/","DC-",i,"_",date);
        else
            sprintf(recording_fileXnaux,"%s%s%s%d%s%s.oni",recording_fileXnaux,"/","D-",i,"_",date);

        strcpy(AuxFile.name,recording_fileXnaux);
        qDebug(AuxFile.name);

        nRetVal = Recorders[i].SetDestination(XN_RECORD_MEDIUM_FILE,recording_fileXnaux);
        nRetVal = Recorders[i].AddNodeToRecording(DepthsGen[i], XN_CODEC_16Z_EMB_TABLES);
    }

    //Init RGB devices
    if(record_rgb){
        i=0;
        ImageGenerator imgaux[MAXGENERATORS];

        for (xn::NodeInfoList::Iterator nodeIt = img_nodes.Begin(); nodeIt != img_nodes.End(); ++nodeIt, i++) {
            //ImageGenerator imgaux;
            NodeInfo info = *nodeIt;
            const XnProductionNodeDescription& description = info.GetDescription();
            nRetVal = context.CreateProductionTree(info,imgaux[i]);
            nRetVal = info.GetInstance(imgaux[i]);
            qDebug("Instance Name %s",info.GetInstanceName());
            ImagesGen[i]=imgaux[i];
            qDebug("Image Generator %i", i);
            nRetVal = Recorders[i].AddNodeToRecording(ImagesGen[i],XN_CODEC_JPEG);
        }
    }

    XnMapOutputMode Mode;
    Mode.nFPS  = FPS;
    Mode.nXRes = RES_X;
    Mode.nYRes = RES_Y;

    if(record_rgb){
        if(nDepths==nImg ){

            for(int j=0;j<nDepths;j++){

                DepthsGen[j].SetMapOutputMode(Mode);
                CHECK_RC(nRetVal, "SetMap output for depth generator");
                ImagesGen[j].SetMapOutputMode(Mode);
                CHECK_RC(nRetVal, "SetMap output for image generator");

                if(DepthsGen[j].IsCapabilitySupported("AlternativeViewPoint")){
                    nRetVal = DepthsGen[j].GetAlternativeViewPointCap().SetViewPoint(ImagesGen[j]);
                    CHECK_RC(nRetVal, "SetViewPoint for depth generator");
                    qDebug("Alinged Depth and Image %d",j);
                }
            }
        }
    }

    // Context Generating all
    nRetVal = context.StartGeneratingAll();

    qDebug("Starting to record!");

    //For the first time
    qDebug() <<  MetadataFile.absoluteFilePath();
    write_metadata(MetadataFile.absoluteFilePath(),date,START);

    while(Recording){
        nRetVal = context.WaitAndUpdateAll();
        QCoreApplication::processEvents();
        Frames++;
        //if (Frames > 300) Recording = 0;
        //qDebug() << "Recording:" << Recording << "\tFrames:" <<Frames;
    }

    //last file
    char date_last[20];
    strcpy(date_last,QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss").toLocal8Bit());
    write_metadata(MetadataFile.absoluteFilePath(),date_last,STOP);

    //Liberamos
    context.Release();

    qDebug("Finished");
    return 0;
}
Beispiel #26
0
int main(int argc, char* argv[])
{
	XnStatus nRetVal = XN_STATUS_OK;
	nRetVal = xnLogInitFromXmlFile(SAMPLE_XML_PATH);
	if (nRetVal != XN_STATUS_OK)
	{
		printf("Log couldn't be opened: %s. Running without log", xnGetStatusString(nRetVal));
	}

	if (argc < 3)
	{
		printf("usage: %s <inputFile> <outputFile>\n", argv[0]);
		return -1;
	}

	const char* strInputFile = argv[1];
	const char* strOutputFile = argv[2];

	Context context;
	nRetVal = context.Init();
	CHECK_RC(nRetVal, "Init");

	// open input file
	Player player;
	nRetVal = context.OpenFileRecording(strInputFile, player);
	CHECK_RC(nRetVal, "Open input file");

	// Get depth node from recording
	DepthGenerator depth;
	nRetVal = context.FindExistingNode(XN_NODE_TYPE_DEPTH, depth);
	CHECK_RC(nRetVal, "Find depth generator");

	// Create mock node based on depth node from recording
	MockDepthGenerator mockDepth;
	nRetVal = mockDepth.CreateBasedOn(depth);
	CHECK_RC(nRetVal, "Create mock depth node");

	// create recorder
	Recorder recorder;

	nRetVal = recorder.Create(context);
	CHECK_RC(nRetVal, "Create recorder");

	nRetVal = recorder.SetDestination(XN_RECORD_MEDIUM_FILE, strOutputFile);
	CHECK_RC(nRetVal, "Set recorder destination file");

	// add depth node to recorder
	nRetVal = recorder.AddNodeToRecording(mockDepth);
	CHECK_RC(nRetVal, "Add node to recording");

	nRetVal = player.SetRepeat(FALSE);
	XN_IS_STATUS_OK(nRetVal);

	XnUInt32 nNumFrames = 0;

	nRetVal = player.GetNumFrames(depth.GetName(), nNumFrames);
	CHECK_RC(nRetVal, "Get player number of frames");

	DepthMetaData depthMD;

	while ((nRetVal = depth.WaitAndUpdateData()) != XN_STATUS_EOF)
	{
		CHECK_RC(nRetVal, "Read next frame");
		
		// Get depth meta data
		depth.GetMetaData(depthMD);

		//-----------------------------------------------//
		// Transform depth! This is the interesting part //
		//-----------------------------------------------//
		
		/* Enable the depth data to be modified. This is done implicitly by depthMD.WritableDepthMap(),
		   but we're calling it just to be clear. */
		nRetVal = depthMD.MakeDataWritable();
		CHECK_RC(nRetVal, "Make depth data writable");

		transformDepthMD(depthMD);

		// Pass the transformed data to the mock depth generator
		nRetVal = mockDepth.SetData(depthMD);
		CHECK_RC(nRetVal, "Set mock node new data");

		/* We need to call recorder.Record explicitly because we're not using WaitAndUpdateAll(). */
		nRetVal = recorder.Record();
		CHECK_RC(nRetVal, "Record");

		printf("Recorded: frame %u out of %u\r", depthMD.FrameID(), nNumFrames);
	}

	printf("\n");

	return 0;
}
Beispiel #27
0
/**
 * Evaluate
 *  left shift
 *  right shift
 *  binary and
 *  binary or
 *  binar xor
 */
RefPtr<Variant> BitExpr::eval_impl(Context& context)
{
    RefPtr<Variant> lval, rval;

    eval_operands(context, lval, rval);

    if (oper_ == LEFT_SHIFT || oper_ == RIGHT_SHIFT)
    {
        if (lval->type_tag() == Variant::VT_OBJECT)
        {
            try_overloaded_operator(context);
        }
        else if (rval->type_tag() == Variant::VT_OBJECT)
        {
            try_standalone_operator(context);
        }
    }

    // Bitwise operations make sense for integer types only
    if (!is_integer(*lval) || !is_integer(*rval))
    {
        throw_invalid_types();
    }

    // Determine the bit size of the result
    IntType& intType = interface_cast<IntType&>(*lhs()->type());
    size_t n = intType.bit_size();
    if (intType.is_signed() && (n % 2) == 0)
    {
        assert(n);
        --n;
    }
    assert(n);
    --n;
    // compute mask for clearing unused bytes:
    uint64_t mask = 1ULL << n;
    mask = ((mask - 1) << 1) | 1;
    //clog << __func__ << ": mask=" << hex << mask << dec << endl;

    uint64_t rbits = rval->bits();
    // warn if shift rbits is negative
    if (is_signed_int(*rval) && (rbits & 0x8000000000000000ULL))
    {
        context.notify_warning_event("Warning: negative shift count");
    }

    RefPtr<DataType> unsignedType;
    if (!is_signed_int(*lval)) unsignedType = lhs()->type();
    if (!is_signed_int(*rval)) unsignedType = rhs()->type();

    if (lval->size() >= sizeof(int32_t))
    {
        // return type is the type of lhs
        set_type(lhs()->type());

        uint64_t lbits = lval->bits() & mask;
        //clog << __func__ << ": LBITS=" << hex << lbits << dec << endl;

        switch (oper_)
        {
        case LEFT_SHIFT:  lbits <<= rbits; break;
        case RIGHT_SHIFT: lbits >>= rbits; break;
        case AND: lbits &= rbits; if (unsignedType) set_type(unsignedType); break;
        case OR:  lbits |= rbits; if (unsignedType) set_type(unsignedType); break;
        case XOR: lbits ^= rbits; if (unsignedType) set_type(unsignedType); break;
        }

        //clog << __func__ << ": lbits=" << hex << lbits << dec << endl;
        lval = new VariantImpl;
        variant_assign(*lval, *type(), lbits);
    }
Beispiel #28
0
	void Reshape(GLuint width, GLuint height)
	{
		gl.Viewport(width, height);
	}
Beispiel #29
0
bool
Layer_PasteCanvas::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
{
	Vector origin=param_origin.get(Vector());
	Vector focus=param_focus.get(Vector());
	Real zoom=param_zoom.get(Real());
	Real outline_grow=param_outline_grow.get(Real());
	Time time_offset=param_time_offset.get(Time());
	Time curr_time=param_curr_time.get(Time());

	if(cb && !cb->amount_complete(0,10000)) return false;

	if(depth==MAX_DEPTH)
		// if we are at the extent of our depth,
		// then we should just return whatever is under us.
		return context.accelerated_render(surface,quality,renddesc,cb);

	depth_counter counter(depth);

	if(!canvas || !get_amount())
		return context.accelerated_render(surface,quality,renddesc,cb);

	SuperCallback stageone(cb,0,4500,10000);
	SuperCallback stagetwo(cb,4500,9000,10000);
	SuperCallback stagethree(cb,9000,9999,10000);

	RendDesc desc(renddesc);
	Vector::value_type zoomfactor=1.0/exp(zoom);
	desc.clear_flags();
	desc.set_tl((desc.get_tl()-focus-origin)*zoomfactor+focus);
	desc.set_br((desc.get_br()-focus-origin)*zoomfactor+focus);
	desc.set_flags(RendDesc::PX_ASPECT);

	if (is_solid_color() || context->empty())
	{
		surface->set_wh(renddesc.get_w(),renddesc.get_h());
		surface->clear();
	}
	else if (!context.accelerated_render(surface,quality,renddesc,&stageone))
		return false;

	Real grow_value(get_parent_canvas_grow_value());
	canvas->set_grow_value(outline_grow+grow_value);

	if(muck_with_time_ && curr_time!=Time::begin() /*&& canvas->get_time()!=curr_time+time_offset*/)
		canvas->set_time(curr_time+time_offset);

	Color::BlendMethod blend_method(get_blend_method());
	const Rect full_bounding_rect(canvas->get_context(context).get_full_bounding_rect());

	bool blend_using_straight = false; // use 'straight' just for the central blit

	// sometimes the user changes the parameters while we're
	// rendering, causing our pasted canvas' bounding box to shrink
	// and no longer overlap with our tile.  if that has happened,
	// let's just stop now - we'll be refreshing soon anyway
	//! \todo shouldn't a mutex ensure this isn't needed?
	// http://synfig.org/images/d/d2/Bbox-change.sifz is an example
	// that shows this happening - open the encapsulation, select the
	// 'shade', and toggle the 'invert' parameter quickly.
	// Occasionally you'll see:
	//   error: Context::accelerated_render(): Layer "shade" threw a bad_alloc exception!
	// where the shade layer tries to allocate itself a canvas of
	// negative proportions, due to changing bounding boxes.
	if (!etl::intersect(desc.get_rect(), full_bounding_rect))
	{
		warning("%s:%d bounding box shrank while rendering?", __FILE__, __LINE__);
		return true;
	}

	// we have rendered what's under us, if necessary
	if(context->empty())
	{
		// if there's nothing under us, and we're blending 'onto', then we've finished
		if (Color::is_onto(blend_method)) return true;

		// there's nothing under us, so using straight blending is
		// faster than and equivalent to using composite, but we don't
		// want to blank the surrounding areas
		if (blend_method==Color::BLEND_COMPOSITE) blend_using_straight = true;
	}

	if (!etl::intersect(context.get_full_bounding_rect(),(full_bounding_rect-focus)*exp(zoom)+origin+focus))
	{
		// if there's no intersection between the context and our
		// surface, and we're rendering 'onto', then we're done
		if (Color::is_onto(blend_method) && !Color::is_straight(blend_method))
			return true;

		/* 'straight' is faster than 'composite' and has the same
		 * effect if the affected area of the lower layer is
		 * transparent;  however, if we're not clipping the blit to
		 * just the bounding rectangle, the affected area is the whole
		 * tile, so we can't use this optimisation.  if we are
		 * clipping, then we can use 'straight' to blit the clipped
		 * rectangle, but we shouldn't set blend_method to 'straight',
		 * or the surrounding areas will be blanked, which we don't
		 * want.
		 */
#ifdef SYNFIG_CLIP_PASTECANVAS
		if (blend_method==Color::BLEND_COMPOSITE) blend_using_straight = true;
#endif	// SYNFIG_CLIP_PASTECANVAS
	}

#ifdef SYNFIG_CLIP_PASTECANVAS
	Rect area(desc.get_rect() & full_bounding_rect);

	Point min(area.get_min());
	Point max(area.get_max());

	if (desc.get_tl()[0] > desc.get_br()[0]) swap(min[0], max[0]);
	if (desc.get_tl()[1] > desc.get_br()[1]) swap(min[1], max[1]);

	const int x(floor_to_int((min[0] - desc.get_tl()[0]) / desc.get_pw()));
	const int y(floor_to_int((min[1] - desc.get_tl()[1]) / desc.get_ph()));
	const int w( ceil_to_int((max[0] - desc.get_tl()[0]) / desc.get_pw()) - x);
	const int h( ceil_to_int((max[1] - desc.get_tl()[1]) / desc.get_ph()) - y);

	const int tw = desc.get_w();
	const int th = desc.get_h();

	desc.set_subwindow(x,y,w,h);

	// \todo this used to also have "area.area()<=0.000001 || " - is it useful?
	//		 it was causing bug #1809480 (Zoom in beyond 8.75 in nested canvases fails)
	if(desc.get_w()==0 || desc.get_h()==0)
	{
		if(cb && !cb->amount_complete(10000,10000)) return false;
		return true;
	}

	// SYNFIG_CLIP_PASTECANVAS is defined, so we are only touching the
	// pixels within the affected rectangle.  If the blend method is
	// 'straight', then we need to blend transparent pixels with the
	// clipped areas of this tile, because with the 'straight' blend
	// method, even transparent pixels have an effect on the layers below
	if (Color::is_straight(blend_method))
	{
		Surface clearsurface;

		Surface::alpha_pen apen(surface->begin());
		apen.set_alpha(get_amount());

		// the area we're about to blit is transparent, so it doesn't
		// matter whether we use 'straight' or 'straight onto' here
		if (blend_method == Color::BLEND_ALPHA_BRIGHTEN)
			apen.set_blend_method(blend_method);
		else
			apen.set_blend_method(Color::BLEND_STRAIGHT);

		/* This represents the area we're pasting into the tile,
		 * within the tile as a whole.	Areas (A), (B), (C) and (D)
		 * need blending with the underlying context if they're not
		 * zero-sized:
		 *
		 *		 0	   x		 x+w	  tw
		 *	 0	 +------------------------+
		 *		 |						  |
		 *		 |			(A)			  |
		 *		 |						  |
		 *	 y	 | - - +----------+ - - - |
		 *		 |	   |		  |		  |
		 *		 | (C) |  w by h  |	 (D)  |
		 *		 |	   |		  |		  |
		 *	 y+h | - - +----------+ - - - |
		 *		 |						  |
		 *		 |			(B)			  |
		 *		 |						  |
		 *	 tw	 +------------------------+
		 */

		if (y > 0)				// draw the full-width strip above the rectangle (A)
		{ apen.move_to(0,0);   clearsurface.set_wh(tw,y);        clearsurface.clear(); clearsurface.blit_to(apen); }
		if (y+h < th)			// draw the full-width strip below the rectangle (B)
		{ apen.move_to(0,y+h); clearsurface.set_wh(tw,th-(y+h)); clearsurface.clear(); clearsurface.blit_to(apen); }
		if (x > 0)				// draw the box directly left of the rectangle (C)
		{ apen.move_to(0,y);   clearsurface.set_wh(x,h);         clearsurface.clear(); clearsurface.blit_to(apen); }
		if (x+w < tw)			// draw the box directly right of the rectangle (D)
		{ apen.move_to(x+w,y); clearsurface.set_wh(tw-(x+w),h);  clearsurface.clear(); clearsurface.blit_to(apen); }
	}
#endif	// SYNFIG_CLIP_PASTECANVAS

	// render the canvas to be pasted onto pastesurface
	Surface pastesurface;
	if(!canvas->get_context(context).accelerated_render(&pastesurface,quality,desc,&stagetwo))
		return false;

#ifdef SYNFIG_CLIP_PASTECANVAS
	Surface::alpha_pen apen(surface->get_pen(x,y));
#else  // SYNFIG_CLIP_PASTECANVAS
	Surface::alpha_pen apen(surface->begin());
#endif	// SYNFIG_CLIP_PASTECANVAS

	apen.set_alpha(get_amount());
	apen.set_blend_method(blend_using_straight ? Color::BLEND_STRAIGHT : blend_method);
	pastesurface.blit_to(apen);

	if(cb && !cb->amount_complete(10000,10000)) return false;

	return true;
}
 void operator()(Iterator const&, Iterator const&
   , BOOST_SCOPED_ENUM(boost::spirit::lex::pass_flags)&
   , std::size_t&, Context& ctx) const
 {
     ctx.set_state_name(state.c_str());
 }