Beispiel #1
0
// Initialize
void _Graphics::SetStaticUniforms() {
	SetProgram(Assets.Programs["ortho_pos"]);
	glUniformMatrix4fv(Assets.Programs["ortho_pos"]->ViewProjectionTransformID, 1, GL_FALSE, glm::value_ptr(Ortho));
	SetProgram(Assets.Programs["ortho_pos_uv"]);
	glUniformMatrix4fv(Assets.Programs["ortho_pos_uv"]->ViewProjectionTransformID, 1, GL_FALSE, glm::value_ptr(Ortho));
	SetProgram(Assets.Programs["text"]);
	glUniformMatrix4fv(Assets.Programs["text"]->ViewProjectionTransformID, 1, GL_FALSE, glm::value_ptr(Ortho));
}
Beispiel #2
0
void Meteor::OnCreate()
{
    SetTexture(MeteorTexture.Get(Scene.Get()->GetAssetManager()));
    if(!HasProgram())
        SetProgram(MeteorProgram.Get(Scene.Get()->GetAssetManager()));
    Sprite::OnCreate();
}
Beispiel #3
0
GNumericalExpression::GNumericalExpression(QObject *parent, QString uniqueIdentifierName)
	: GProgDevice(parent, uniqueIdentifierName)
	, m_ValueBucket("Result", this)
	, m_VariableBucket("Variables", this)
	, m_EnableEvaluation("EnableEvaluation", this)
	, m_Expression("Expression", this)
{
	// Expression Display Initialization
	m_ExpressionDisplay = new GExpressionDisplay(this);

	// Script Engine Initialization
	m_pScriptEngine = new GMathScriptEngine(this);
// 	m_ScriptEngineDebugger = new QScriptEngineDebugger;

	m_VariableBucket.AddExtraFieldString("symb");


	connect(&m_Expression, SIGNAL(ValueUpdated(QString)), m_pScriptEngine, SLOT(SetProgram(QString)));
	connect(&m_Expression, SIGNAL(ValueUpdated(QString)), m_pScriptEngine, SLOT(Evaluate()));
	connect(&m_VariableBucket, SIGNAL(BucketUpdatedValues(int)), this, SLOT(ReCalculate(int)));
	connect(m_pScriptEngine, SIGNAL(Evaluated(double)), &m_ValueBucket, SLOT(SetParamValue(double)));

	connect(&m_VariableBucket, SIGNAL(ParamAdded(GParam*)), this, SLOT(AddVariableFromParam(GParam*)), Qt::QueuedConnection);
	connect(&m_VariableBucket, SIGNAL(ParamRemoved(int, GParam*)), this, SLOT(RemoveVariableFromParam(int, GParam*)));
}
Beispiel #4
0
ES_InlineScriptThread::ES_InlineScriptThread(ES_Context *context, ES_Program *program,
                                             ES_SharedThreadInfo *shared)
	: ES_Thread(context, shared)
{
	OP_ASSERT(program);
	SetProgram(program);
}
Beispiel #5
0
	void CommandLine::InitFromArgv(const StringVector& argv) {
		argv_ = StringVector(1);
		switches_.clear();
		begin_args_ = 1;
		SetProgram(argv.empty() ? FilePath() : FilePath(argv[0]));
		AppendSwitchesAndArguments(*this, argv);
	}
Beispiel #6
0
void DeviceContext::Init() {
#ifndef CPU_ONLY
  if (backend_ == BACKEND_CUDA) {
#ifdef USE_CUDA
    workgroup_sizes_[0] = CAFFE_CUDA_NUM_THREADS;
#endif  // USE_CUDA
  } else {
#ifdef USE_GREENTEA
    viennacl::ocl::context &ctx = viennacl::ocl::get_context(id_);

    std::vector<size_t> temp(3);
    clGetDeviceInfo(ctx.devices()[0].id(),
    CL_DEVICE_MAX_WORK_ITEM_SIZES,
                    sizeof(size_t), &temp[0], NULL);
    workgroup_sizes_[0] = temp[0];
    workgroup_sizes_[1] = temp[1];
    workgroup_sizes_[2] = temp[2];

    SetProgram();

    for (int q = 0; q < GREENTEA_QUEUE_COUNT - 1; ++q) {
      ctx.add_queue(ctx.devices()[0]);
    }
#endif  // USE_GREENTEA
  }
#endif  // !CPU_ONLY
}
Beispiel #7
0
void CommandLine::AppendArguments(const CommandLine& other,
                                  bool include_program)
{
    if(include_program)
    {
        SetProgram(other.GetProgram());
    }
    AppendSwitchesAndArguments(*this, other.argv());
}
GEquationPayOff::GEquationPayOff( const GParamString & ProgramString, QObject *parent )
	: GPayOff(parent)
	, m_pEngine(0)
{
	m_pEngine = new GMathScriptEngine(this);
	m_pEngine->globalObject().setProperty("S", m_ScriptSpot);
	m_pEngine->SetProgram(ProgramString.StringValue());
	connect(&ProgramString, SIGNAL(ValueUpdated(QString)), m_pEngine, SLOT(SetProgram(QString)));
}
	cMaterial_BumpSpec2D::cMaterial_BumpSpec2D(const tString& asName,iLowLevelGraphics* apLowLevelGraphics,
		cImageManager* apImageManager, cTextureManager *apTextureManager,
		cRenderer2D* apRenderer, cGpuProgramManager* apProgramManager,
		eMaterialPicture aPicture, cRenderer3D *apRenderer3D)
	: iMaterial(asName,apLowLevelGraphics,apImageManager,apTextureManager,apRenderer,apProgramManager,
				aPicture,apRenderer3D)
	{
		mbIsTransperant = false;
		mbIsGlowing= false;
		mbUsesLights = true;

		mbHasSpecular = true;

		mType = eMaterialType_BumpSpec;

		if(mbHasSpecular)
		{
			//load the fragment program
			iGpuProgram* pFragProg = mpProgramManager->CreateProgram("BumpSpec2D_Light_fp.cg","main",
				eGpuProgramType_Fragment);
			SetProgram(pFragProg,eGpuProgramType_Fragment,0);


			//Load the vertex program
			iGpuProgram* pVtxProg = mpProgramManager->CreateProgram("BumpSpec2D_Light_vp.cg","main",
				eGpuProgramType_Vertex);
			SetProgram(pVtxProg,eGpuProgramType_Vertex,0);
		}
		else //Just use normal bump without specular
		{
			//load the fragment program
			iGpuProgram* pFragProg = mpProgramManager->CreateProgram("Bump2D_Light_fp.cg","main",
				eGpuProgramType_Fragment);
			SetProgram(pFragProg,eGpuProgramType_Fragment,0);


			//Load the vertex program
			iGpuProgram* pVtxProg = mpProgramManager->CreateProgram("Bump2D_Light_vp.cg","main",
				eGpuProgramType_Vertex);
			SetProgram(pVtxProg,eGpuProgramType_Vertex,0);
		}

	}
Beispiel #10
0
void Laser::OnCreate()
{
    if(!myTextureRef.Empty())
        myTexture = myTextureRef;

    //Debug("Set my program");
    FixedGeometry::OnCreate();
    if(!HasProgram())
        SetProgram(LaserProgram.Get(Scene.Get()->GetAssetManager()));
}
Beispiel #11
0
void CommandLine::ParseFromArgv(const ArgList& argv)
{
    if (argv.empty()) {
        return;
    }

    // Anyway, we start from scratch.
    argv_ = Argv(1);
    last_not_param_ = argv_.begin();
    switches_.clear();

    SetProgram(FilePath(argv[0]));
    AddArguments(this, argv);
}
Beispiel #12
0
    void Graphics::ResetCachedState()
    {
        Program::Clear();

        viewport_ = Recti(0);

        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &systemFbo_); // On IOS default FBO is not zero

        // Set up texture data read/write alignment
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

        VertexArrayObj::Clear();
        lastMesh_ = nullptr;
        lastProgram_ = nullptr;
        activeMesh_ = nullptr;
        activeWindow_ = nullptr;

        CHECK_GL_STATUS();

        SetClearColor(Color(0, 0, 0, 1));
        SetClearDepth(1);
        SetClearStencil(0);
        SetFrameBuffer(nullptr);
        SetStencilTest(DEFAULT_STENCIL_ENABLE, DEFAULT_STENCIL_WRITEMASK, DEFAULT_STENCIL_SFAIL,
                       DEFAULT_STENCIL_DPFAIL, DEFAULT_STENCIL_DPPASS, DEFAULT_STENCIL_FUNC, DEFAULT_STENCIL_REF, DEFAULT_STENCIL_COMPAREMASK);
        SetScissorTest();

        CHECK_GL_STATUS();

        SetColorMask(DEFAULT_COLOR_MASK);
        SetDepthMask(DEFAULT_DEPTH_MASK);
        SetDepthFunc(DepthFunc::LESS);
        SetStencilMask(DEFAULT_STENCIL_MASK);
        SetBlendModeTest(DEFAULT_BLEND_MODE);
        EnableDepthTest(DEFAULT_DEPTH_TEST_ENABLE);
        EnableCullFace(DEFAULT_CULL_FACE_ENABLE);
        SetCullFace(CullFaceMode::DEFAULT);
        SetFrontFace(FrontFaceMode::DEFAULT);
        CHECK_GL_STATUS();

        UnboundTextures();
        SetVertexArrayObj(nullptr);
        SetVertexBuffer(nullptr);
        SetIndexBuffer(nullptr);
        SetProgram(nullptr);
        SetSlopeScaledBias(0);

        CHECK_GL_STATUS();
    }
Beispiel #13
0
	inline void Renderer::m_RenderSprite(Camera* camera, Sprite* sprite, Transform* transform) {
		Material* material = sprite->material;
		if (material == NULL) return;
		
		CreateMaterial(material);
		CreateSpriteAttributes();
		SetProgram(material->GetOpenGLShader()->program);
		
		BindMaterial(material, camera->projection, camera->view, transform);
		BindSpriteAttributes(material);
		
		if (material->GetWireframe()) {
			glDrawArrays(GL_LINE_STRIP, 0, 4);
		} else {
			glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
		}
	}
Beispiel #14
0
	inline void Renderer::m_RenderMeshFilter(Camera* camera, MeshFilter* meshFilter, Transform* transform) {
		Mesh* mesh = meshFilter->mesh;
		Material* material = meshFilter->material;
		if (mesh == NULL || material == NULL) return;
		
		CreateMaterial(material);
		CreateMeshAttributes(mesh);
		SetProgram(material->GetOpenGLShader()->program);
		
		BindMaterial(material, camera->projection, camera->view, transform);
		BindMeshAttributes(material, mesh);
		
		if (material->GetWireframe()) {
			glDrawElements(GL_LINES, mesh->indices.Length(), GL_UNSIGNED_INT, BUFFER_OFFSET(0));
		} else {
			glDrawElements(GL_TRIANGLES, mesh->indices.Length(), GL_UNSIGNED_INT, BUFFER_OFFSET(0));
		}
	}
Beispiel #15
0
void MainHost::SetupGroupContainer()
{
    if(!groupContainer.isNull()) {
        mainContainer->ParkObject( groupContainer );
        groupContainer.clear();
        UpdateSolver(true);
        if(mainWindow)
            mainWindow->mySceneView->viewGroup->ClearViewPrograms();
    }

    ObjectInfo info;
    info.nodeType = NodeType::container;
    info.objType = ObjType::Container;
    info.name = "groupContainer";
    info.forcedObjId = FixedObjId::groupContainer;

    groupContainer = objFactory->NewObject(info).staticCast<Connectables::Container>();
    if(groupContainer.isNull())
        return;

    groupContainer->SetLoadingMode(true);

    groupContainer->LoadProgram(0);
    mainContainer->AddObject(groupContainer);

    QSharedPointer<Connectables::Object> bridge;

    //bridge in
    ObjectInfo in;
    in.name="in";
    in.nodeType = NodeType::bridge;
    in.objType = ObjType::BridgeIn;
    in.forcedObjId = FixedObjId::groupContainerIn;

    bridge = objFactory->NewObject(in);
    groupContainer->AddObject( bridge );
    bridge->SetBridgePinsInVisible(false);
    groupContainer->bridgeIn = bridge;

    //bridge out
    ObjectInfo out;
    out.name="out";
    out.nodeType = NodeType::bridge;
    out.objType = ObjType::BridgeOut;
    out.forcedObjId = FixedObjId::groupContainerOut;

    bridge = objFactory->NewObject(out);
    groupContainer->AddObject( bridge );
    bridge->SetBridgePinsOutVisible(false);
    groupContainer->bridgeOut = bridge;

    //connect with programContainer
    if(!programContainer.isNull()) {
        mainContainer->ConnectObjects(programContainer->bridgeSend, groupContainer->bridgeIn,true);
        mainContainer->ConnectObjects(groupContainer->bridgeOut, programContainer->bridgeReturn,true);
    }

    //bridge send
    ObjectInfo send;
    send.name="send";
    send.nodeType = NodeType::bridge;
    send.objType = ObjType::BridgeSend;
    send.forcedObjId = FixedObjId::groupContainerSend;

    bridge = objFactory->NewObject(send);
    groupContainer->AddObject( bridge );
    bridge->SetBridgePinsOutVisible(false);
    groupContainer->bridgeSend = bridge;

    //bridge return
    ObjectInfo retrn;
    retrn.name="return";
    retrn.nodeType = NodeType::bridge;
    retrn.objType = ObjType::BridgeReturn;
    retrn.forcedObjId = FixedObjId::groupContainerReturn;

    bridge = objFactory->NewObject(retrn);
    groupContainer->AddObject( bridge );
    bridge->SetBridgePinsInVisible(false);
    groupContainer->bridgeReturn = bridge;

    //connect with hostContainer
    if(!hostContainer.isNull()) {
        mainContainer->ConnectObjects(groupContainer->bridgeSend, hostContainer->bridgeIn,true);
        mainContainer->ConnectObjects(hostContainer->bridgeOut, groupContainer->bridgeReturn,true);
    }

    connect(programsModel, SIGNAL(GroupChanged(QModelIndex)),
            groupContainer.data(), SLOT(SetProgram(QModelIndex)));
    connect(programsModel, SIGNAL(GroupDelete(QModelIndex)),
            groupContainer.data(), SLOT(RemoveProgram(QModelIndex)));
    connect(this,SIGNAL(Rendered()),
            groupContainer.data(), SLOT(PostRender()));

    emit groupParkingModelChanged(&groupContainer->parkModel);

    if(projectContainer)
        projectContainer->childContainer=groupContainer;
    if(programContainer) {
        groupContainer->childContainer=programContainer;
        programContainer->parentContainer=groupContainer;
    }

    groupContainer->SetLoadingMode(false);
    groupContainer->UpdateModificationTime();
    SetSolverUpdateNeeded();
}
Beispiel #16
0
	//--
	CgShaderCelScreen::CgShaderCelScreen(CGcontext cgContext) : 
		CgShader(cgContext, CgShader::VertexFragment)
	{
		// [rad] This is vertex and fragment shader
	
		// [rad] Setup vertex shader:
		
		// [rad] Setup vertex shader entry point
		SetEntry(CgShader::Vertex, "main");

		static const std::string sProgramVertex = "							\
																			\
		void main(	float4 inPosition			: POSITION,					\
					float2 inTexCoord			: TEXCOORD0,				\
																			\
					out float4 outPosition		: POSITION,					\
					out float2 outTexCoord		: TEXCOORD0,				\
																			\
					uniform float4x4 uniModelViewProjMat)					\
		{																	\
			outPosition = mul(uniModelViewProjMat, inPosition);				\
			outTexCoord = inTexCoord;										\
		}																	";
		
		// [rad] Setup vertex shader program
		SetProgram(CgShader::Vertex, sProgramVertex);
		
		// [rad] Setup fragment shader:
		
		// [rad] Setup fragment shader entry point
		SetEntry(CgShader::Fragment, "main");
		
		static const std::string sProgramFragment = "							\
																				\
		void main(	float2 inTexCoord : TEXCOORD0,								\
																				\
					out float4 outColor : COLOR,								\
																				\
					uniform int2 uniTexSize,									\
					uniform sampler2D uniTexCel,								\
					uniform sampler2D uniTexOutline)							\
		{																		\
			float4 cel = tex2D(uniTexCel, inTexCoord);							\
			float4 outline = tex2D(uniTexOutline, inTexCoord);					\
																				\
			if(outline.x == 0)													\
			{																	\
				outColor = float4(0, 0, 0, 1);									\
			}																	\
			else																\
			{																	\
				outColor = cel;													\
			}																	\
		}																		";
		
		// [rad] Setup fragment shader program
		SetProgram(CgShader::Fragment, sProgramFragment);
		
		// [rad] Create shaders (both fragment and vertex)
		Create();
		
		// [rad] Set params 
		m_cgParamModelViewProjMatrix = cgGetNamedParameter(m_cgShaderVertex, "uniModelViewProjMat");	
		
		m_cgParamSamplerCel = cgGetNamedParameter(m_cgShaderFragment, "uniTexCel");	
		m_cgParamSamplerOutline = cgGetNamedParameter(m_cgShaderFragment, "uniTexOutline");
		
		m_cgParamSamplerSize = cgGetNamedParameter(m_cgShaderFragment, "uniTexSize");
	}
Beispiel #17
0
	CommandLine::CommandLine(const FilePath& program)
		: argv_(1),
		begin_args_(1) {
			SetProgram(program);
	}
	iMaterial_Fallback01_BaseLight::iMaterial_Fallback01_BaseLight(
		bool abNormalMap, bool abSpecular,
		const tString& asName,iLowLevelGraphics* apLowLevelGraphics,
		cImageManager* apImageManager, cTextureManager *apTextureManager,
		cRenderer2D* apRenderer, cGpuProgramManager* apProgramManager,
		eMaterialPicture aPicture, cRenderer3D *apRenderer3D)
		: iMaterial(asName,apLowLevelGraphics,apImageManager,apTextureManager,apRenderer,apProgramManager,
					aPicture,apRenderer3D)
	{
		gDiffuseGLState.SetUp(mpLowLevelGraphics);
		gBumpGLState.SetUp(mpLowLevelGraphics);
		gSpotGLState.SetUp(mpLowLevelGraphics);
		if(mpLowLevelGraphics->GetCaps(eGraphicCaps_GL_ATIFragmentShader))
		{
			gATISpotGLState.SetUp(mpLowLevelGraphics);
			gATIBumpGLState.SetUp(mpLowLevelGraphics);
			gATIDiffuseGLState.SetUp(mpLowLevelGraphics);
		}

		mbUseNormalMap = abNormalMap;
		mbUseSpecular = abSpecular;

		mbIsTransperant = false;
		mbIsGlowing= false;
		mbUsesLights = true;

		tString asLightVertexProgram1 = "Fallback01_Diffuse_Light_p1_vp.cg";
		tString asLightVertexProgram2 = "Fallback01_Diffuse_Light_p2_vp.cg";

		tString asLightSpotVertexProgram1 = "Fallback01_Diffuse_Light_p1_vp.cg";
		tString asLightSpotVertexProgram2 = "Fallback01_Diffuse_Light_Spot_p2_vp.cg";

		for(int i=0; i<eBaseLightProgram_LastEnum; i++) {
			mvVtxPrograms[i] =NULL;
			mvFragPrograms[i] =NULL;
		}

		///////////////////////////////////////////
		//Load the light pass vertex program
		//Point
		mvVtxPrograms[eBaseLightProgram_Point1] = mpProgramManager->CreateProgram(asLightVertexProgram1,
													"main", eGpuProgramType_Vertex);
		mvVtxPrograms[eBaseLightProgram_Point2] = mpProgramManager->CreateProgram(asLightVertexProgram2,
													"main", eGpuProgramType_Vertex);
		mvVtxPrograms[eBaseLightProgram_Spot1] = mpProgramManager->CreateProgram(asLightSpotVertexProgram1,
													"main", eGpuProgramType_Vertex);
		mvVtxPrograms[eBaseLightProgram_Spot2] = mpProgramManager->CreateProgram(asLightSpotVertexProgram2,
													"main", eGpuProgramType_Vertex);

		///////////////////////////////////////////
		//Load the light pass fragment program
		//Point
		//mvFragPrograms[eBaseLightProgram_Point1] = mpProgramManager->CreateProgram("_Test_Diffuse_Light_fp.cg",
		//											"main",	eGpuProgramType_Fragment);
		if(mbUseNormalMap)
		{
			if(mpLowLevelGraphics->GetCaps(eGraphicCaps_GL_ATIFragmentShader))
			{
				mvFragPrograms[eBaseLightProgram_Point1] = &gATIBumpGLState;
				mvFragPrograms[eBaseLightProgram_Spot1] =  &gATIBumpGLState;
				
				mvFragPrograms[eBaseLightProgram_Spot2] =  &gATISpotGLState;
			}
			else
			{
				mvFragPrograms[eBaseLightProgram_Point1] = &gBumpGLState;
				mvFragPrograms[eBaseLightProgram_Spot1] =  &gBumpGLState;
				
				mvFragPrograms[eBaseLightProgram_Spot2] =  NULL;//hplNew( cGLState_Spot,(mpLowLevelGraphics) );
			}

			//mvFragPrograms[eBaseLightProgram_Spot2] =  hplNew( cGLState_Spot,(mpLowLevelGraphics) );
			//mvFragPrograms[eBaseLightProgram_Spot2] =  hplNew( cGLState_ATISpot, (mpLowLevelGraphics) );
			//mvFragPrograms[eBaseLightProgram_Spot2] = mpProgramManager->CreateProgram(
			//											"_Test_Diffuse_Light_fp.cg",
			//											"main", eGpuProgramType_Fragment);
		}
		else
		{
			if(mpLowLevelGraphics->GetCaps(eGraphicCaps_GL_ATIFragmentShader))
			{
				mvFragPrograms[eBaseLightProgram_Point1] = &gATIDiffuseGLState;
				mvFragPrograms[eBaseLightProgram_Spot1] =  &gATIDiffuseGLState;
				
				mvFragPrograms[eBaseLightProgram_Spot2] =  &gATISpotGLState;
			}
			else
			{
				mvFragPrograms[eBaseLightProgram_Point1] = &gDiffuseGLState;
				mvFragPrograms[eBaseLightProgram_Spot1] =  &gDiffuseGLState;
				
				mvFragPrograms[eBaseLightProgram_Spot2] =  NULL;//hplNew( cGLState_Spot, (mpLowLevelGraphics) );
			}

			//mvFragPrograms[eBaseLightProgram_Spot2] = mpProgramManager->CreateProgram(
			//											"_Test_Diffuse_Light_fp.cg",
			//											"main", eGpuProgramType_Fragment);
		}

		///////////////////////////////////////////
		//Load the Z pass vertex program
		iGpuProgram *pVtxProg = mpProgramManager->CreateProgram("Diffuse_Color_vp.cg","main",eGpuProgramType_Vertex);
		SetProgram(pVtxProg,eGpuProgramType_Vertex,1);

		mpNormalizationMap = mpTextureManager->CreateCubeMap("Normalization", false);
		mpNormalizationMap->SetWrapS(eTextureWrap_ClampToEdge);
		mpNormalizationMap->SetWrapT(eTextureWrap_ClampToEdge);

		mpSpotNegativeRejectMap = mpTextureManager->Create1D("core_spot_negative_reject",false);
		if(mpSpotNegativeRejectMap)
		{
			mpSpotNegativeRejectMap->SetWrapS(eTextureWrap_ClampToEdge);
			mpSpotNegativeRejectMap->SetWrapT(eTextureWrap_ClampToEdge);
		}
	}
Beispiel #19
0
/* virtual */
OP_STATUS
ES_JavascriptURLThread::EvaluateThread()
{
	OP_STATUS ret = OpStatus::OK;

	switch (eval_state)
	{
	case STATE_INITIAL:
		{
			eval_state = STATE_SET_PROGRAM;

#ifdef USER_JAVASCRIPT
			DOM_Environment *environment = scheduler->GetFramesDocument()->GetDOMEnvironment();

			RETURN_IF_ERROR(environment->HandleJavascriptURL(this));

			if (IsBlocked())
				return OpStatus::OK;
#endif // USER_JAVASCRIPT
		}
		// fall through

	case STATE_SET_PROGRAM:
		if (source)
		{
			ES_ProgramText program_text;

			program_text.program_text = source;
			program_text.program_text_length = uni_strlen(source);

			ES_Runtime *runtime = scheduler->GetRuntime();

			ES_Program *program;
			OP_STATUS status;

			ES_Runtime::CompileProgramOptions options;
			options.generate_result = TRUE;
			options.global_scope = FALSE;
			options.script_type = SCRIPT_TYPE_JAVASCRIPT_URL;
			options.when = UNI_L("while loading");
			options.script_url = &url;
#ifdef ECMASCRIPT_DEBUGGER
			options.reformat_source = g_ecmaManager->GetWantReformatScript(runtime);
#endif // ECMASCRIPT_DEBUGGER

			if (OpStatus::IsSuccess(status = runtime->CompileProgram(&program_text, 1, &program, options)))
				if (program)
					SetProgram(program);
				else
					status = OpStatus::ERR;

			if (OpStatus::IsMemoryError(status))
			{
				is_completed = is_failed = TRUE;
				return status;
			}
			else if (OpStatus::IsError(status))
			{
				is_completed = is_failed = TRUE;
				return OpStatus::OK;
			}
		}
		eval_state = STATE_EVALUATE;
		// fall through

	case STATE_EVALUATE:
		{
			ret = ES_Thread::EvaluateThread();
			if (OpStatus::IsError(ret))
			{
				eval_state = STATE_HANDLE_RESULT;
				is_completed = TRUE;
				break;
			}
			else if (IsCompleted())
			{
				if (IsFailed())
				{
					eval_state = STATE_DONE;
					break;
				}
				else
#ifdef USER_JAVASCRIPT
					eval_state = STATE_SEND_USER_JS_AFTER;
#else // USER_JAVASCRIPT
					eval_state = STATE_HANDLE_RESULT;
#endif // USER_JAVASCRIPT
			}
			else
				break;
		}
		// fall through

#ifdef USER_JAVASCRIPT
	case STATE_SEND_USER_JS_AFTER:
		{
			DOM_Environment *environment = scheduler->GetFramesDocument()->GetDOMEnvironment();

			RETURN_IF_ERROR(environment->HandleJavascriptURLFinished(this));

			eval_state = STATE_HANDLE_RESULT;

			if (IsBlocked())
			{
				is_completed = FALSE;
				break;
			}
		}
		// fall through
#endif // USER_JAVASCRIPT

	case STATE_HANDLE_RESULT:
		{
			is_completed = TRUE;
			const uni_char *use_result = NULL;

#ifdef USER_JAVASCRIPT
			if (has_result)
				use_result = result;
			else
#endif // USER_JAVASCRIPT
				if (ReturnedValue())
				{
					ES_Value return_value;

					RETURN_IF_ERROR(GetReturnedValue(&return_value));

					if (return_value.type == VALUE_STRING)
						use_result = return_value.value.string;
				}

			FramesDocument *frames_doc = GetFramesDocument();
			OP_ASSERT(frames_doc); // Since we're executing we must be in a document
			if (use_result)
			{
				if (write_result_to_document)
				{
					// The HTML5 spec says that we should load this data exactly as if it had come
					// from an HTTP connection with content type text/html and status 200. This
					// is a very bad approximation of that.
					BOOL is_busy = scheduler->IsDraining() || !frames_doc->IsCurrentDoc();
					write_result_to_document = FALSE; // Since it's enough to do it once
					frames_doc->SetWaitForJavascriptURL(FALSE);

					if (!is_busy)
						if (HLDocProfile *hld_profile = frames_doc->GetHLDocProfile())
							is_busy = hld_profile->GetESLoadManager()->GetScriptGeneratingDoc();

					if (!is_busy)
					{
						if (GetOriginInfo().open_in_new_window)
							RETURN_IF_ERROR(DOM_Environment::OpenWindowWithData(use_result, frames_doc, this, GetOriginInfo().is_user_requested));
						else
						{
							// The ESOpen()/ESClose() calls are just done in order to create an
							// empty document in The Right Way(tm) in order to parse some data
							// into it as if it had been loaded from a URL, and not to set up
							// a document.write call like they are usually used for.
							ESDocException doc_exception; // Ignored
							RETURN_IF_ERROR(frames_doc->ESOpen(scheduler->GetRuntime(), &url, is_reload, NULL, NULL, &doc_exception));

							FramesDocument *new_frames_doc = frames_doc->GetDocManager()->GetCurrentDoc();
							RETURN_IF_ERROR(new_frames_doc->ESClose(scheduler->GetRuntime()));

							SetBlockType(ES_BLOCK_NONE);

							if (frames_doc != new_frames_doc)
								RETURN_IF_ERROR(new_frames_doc->GetLogicalDocument()->ParseHtmlFromString(use_result, uni_strlen(use_result), FALSE, FALSE, FALSE));
							else
								OP_ASSERT(!"ESOpen might have failed, but if it didn't then we're stuck with a hung thread in a document and nothing will work");

							new_frames_doc->ESStoppedGeneratingDocument();
						}
					}
				}

				if (write_result_to_url)
				{
					if (want_utf8)
					{
						UTF16toUTF8Converter converter;

						unsigned length = uni_strlen(use_result) * sizeof source[0], needed = converter.BytesNeeded(use_result, length);
						converter.Reset();

						char *data;
						if (needed < g_memory_manager->GetTempBufLen())
							data = (char *) g_memory_manager->GetTempBuf();
						else
							data = OP_NEWA(char, needed);

						if (!data)
						{
							ret = OpStatus::ERR_NO_MEMORY;
							break;
						}
						else
						{
							int read, written = converter.Convert(use_result, length, data, needed, &read);

							url.WriteDocumentData(URL::KNormal, data, written);
							url.WriteDocumentDataFinished();

							if (data != g_memory_manager->GetTempBuf())
								OP_DELETEA(data);
						}
					}
					else
					{
						url.WriteDocumentData(URL::KNormal, use_result, uni_strlen(use_result));
						url.WriteDocumentDataFinished();
					}
				}
			}
			else if (write_result_to_document)
			{
				// The HTML5 spec says this should be handled as a HTTP status 204, NO_CONTENT
				frames_doc->GetMessageHandler()->PostMessage(MSG_URL_LOADING_FAILED, url.Id(), DH_ERRSTR(SI,ERR_HTTP_NO_CONTENT));
				frames_doc->SetWaitForJavascriptURL(FALSE);
				write_result_to_document = FALSE; // Since it's done and we don't want to do it again.
			}

			eval_state = STATE_DONE;
		}
Beispiel #20
0
bool CBotProgram::Compile(const std::string& program, std::vector<std::string>& externFunctions, void* pUser)
{
    // Cleanup the previously compiled program
    Stop();

    for (CBotClass* c : m_classes)
        c->Purge();      // purge the old definitions of classes
                         // but without destroying the object

    m_classes.clear();
    for (CBotFunction* f : m_functions) delete f;
    m_functions.clear();

    externFunctions.clear();
    m_error = CBotNoErr;

    // Step 1. Process the code into tokens
    auto tokens = CBotToken::CompileTokens(program);
    if (tokens == nullptr) return false;

    auto pStack = std::unique_ptr<CBotCStack>(new CBotCStack(nullptr));
    CBotToken* p = tokens.get()->GetNext();                 // skips the first token (separator)

    pStack->SetProgram(this);                               // defined used routines
    m_externalCalls->SetUserPtr(pUser);

    // Step 2. Find all function and class definitions
    while ( pStack->IsOk() && p != nullptr && p->GetType() != 0)
    {
        if ( IsOfType(p, ID_SEP) ) continue;                // semicolons lurking

        if ( p->GetType() == ID_CLASS ||
            ( p->GetType() == ID_PUBLIC && p->GetNext()->GetType() == ID_CLASS ))
        {
            m_classes.push_back(CBotClass::Compile1(p, pStack.get()));
        }
        else
        {
            m_functions.push_back(CBotFunction::Compile1(p, pStack.get(), nullptr));
        }
    }

    // Define fields and pre-compile methods for each class in this program
    if (pStack->IsOk()) CBotClass::DefineClasses(m_classes, pStack.get());

    if ( !pStack->IsOk() )
    {
        m_error = pStack->GetError(m_errorStart, m_errorEnd);
        for (CBotFunction* f : m_functions) delete f;
        m_functions.clear();
        return false;
    }

    // Step 3. Real compilation
    std::list<CBotFunction*>::iterator next = m_functions.begin();
    p  = tokens.get()->GetNext();                             // returns to the beginning
    while ( pStack->IsOk() && p != nullptr && p->GetType() != 0 )
    {
        if ( IsOfType(p, ID_SEP) ) continue;                // semicolons lurking

        if ( p->GetType() == ID_CLASS ||
            ( p->GetType() == ID_PUBLIC && p->GetNext()->GetType() == ID_CLASS ))
        {
            CBotClass::Compile(p, pStack.get());                  // completes the definition of the class
        }
        else
        {
            CBotFunction::Compile(p, pStack.get(), *next);
            if ((*next)->IsExtern()) externFunctions.push_back((*next)->GetName()/* + next->GetParams()*/);
            if ((*next)->IsPublic()) CBotFunction::AddPublic(*next);
            (*next)->m_pProg = this;                           // keeps pointers to the module
            ++next;
        }
    }

    if ( !pStack->IsOk() )
    {
        m_error = pStack->GetError(m_errorStart, m_errorEnd);
        for (CBotFunction* f : m_functions) delete f;
        m_functions.clear();
    }

    return !m_functions.empty();
}
Beispiel #21
0
	//--
	CgShaderCel::CgShaderCel(CGcontext cgContext) : 
		CgShader(cgContext, CgShader::VertexFragment)
	{
		// [rad] This is vertex and fragment shader
	
		// [rad] Setup vertex shader:
		
		// [rad] Setup vertex shader entry point
		SetEntry(CgShader::Vertex, "main");

		static const std::string sProgramVertex = "							\
																			\
		void main(	float4 inPosition			: POSITION,					\
					float4 inNormal				: NORMAL,					\
																			\
					out float4 outOPosition		: POSITION,					\
					out float4 outVPosition		: TEXCOORD0,				\
					out float4 outNormal		: TEXCOORD1,				\
																			\
					uniform float4x4 uniModelViewProjMat,					\
					uniform float4x4 uniModelViewITMat,						\
					uniform float4x4 uniModelViewMat)						\
		{																	\
			outOPosition = mul(uniModelViewProjMat, inPosition);			\
			outVPosition = mul(uniModelViewMat, inPosition);				\
																			\
			outNormal = mul(uniModelViewITMat, inNormal);					\
			outNormal.xyz = normalize(outNormal.xyz);						\
		}																	";
		
		// [rad] Setup vertex shader program
		SetProgram(CgShader::Vertex, sProgramVertex);
		
		// [rad] Setup fragment shader:
		
		// [rad] Setup fragment shader entry point
		SetEntry(CgShader::Fragment, "main");
		
		static const std::string sProgramFragment = "						\
																			\
		void main(															\
					float4 inPosition					: TEXCOORD0,		\
					float4 inNormal						: TEXCOORD1,		\
																			\
					out float4 outColor					: COLOR,			\
																			\
					uniform sampler1D uniTexDiffuse,						\
					uniform sampler1D uniTexSpecular,						\
					uniform sampler1D uniTexOutline,						\
																			\
					uniform float3 uniMatDiffuse,							\
					uniform float3 uniMatSpecular,							\
					uniform float3 uniLightColor,							\
					uniform float3 uniLightPosition,						\
					uniform float3 uniEyePosition,							\
					uniform float uniShininess,								\
																			\
					uniform int uniComputeOutline)							\
		{																	\
																			\
			float3 p = inPosition.xyz;										\
			float3 n = normalize(inNormal.xyz);								\
																			\
			float3 l = normalize(uniLightPosition - p);						\
			float diffuseL = max(dot(n, l), 0);								\
			diffuseL = tex1D(uniTexDiffuse, diffuseL).x;					\
			float3 diffuse = uniLightColor * diffuseL * uniMatDiffuse;		\
																			\
			float3 v = normalize(uniEyePosition - p);						\
			float3 h = normalize(l + v);									\
			float specularL = pow(max(dot(n, h), 0), uniShininess);			\
			if(diffuseL <= 0) specularL = 0;								\
			specularL = tex1D(uniTexSpecular, specularL).x;					\
			float3 specular = uniLightColor * specularL * uniMatSpecular;	\
																			\
			float edgeL = 1;												\
																			\
			if(uniComputeOutline)											\
			{																\
				edgeL = max(dot(n, v), 0);									\
				edgeL = tex1D(uniTexOutline, edgeL).x;						\
			}																\
																			\
			outColor.x = edgeL * (diffuse + specular);						\
			outColor.y = edgeL * (diffuse + specular);						\
			outColor.z = edgeL * (diffuse + specular);						\
			outColor.w = 1;													\
		}																	";

		// float3 diffuse = diffuseL * uniMatDiffuse;
		// float3 specular = specularL * uniMatSpecular;
		
		// [rad] Setup fragment shader program
		SetProgram(CgShader::Fragment, sProgramFragment);
		
		// [rad] Create shaders (both fragment and vertex)
		Create();
		
		// [rad] Set params - vertex shader
		m_cgParamModelViewProjMatrix = cgGetNamedParameter(m_cgShaderVertex, "uniModelViewProjMat");
		m_cgParamModelViewMatrix = cgGetNamedParameter(m_cgShaderVertex, "uniModelViewMat");
		m_cgParamModelViewITMatrix = cgGetNamedParameter(m_cgShaderVertex, "uniModelViewITMat");
		
		// [rad] Set params - fragment shader				
		m_cgParamLightColorVector = cgGetNamedParameter(m_cgShaderFragment, "uniLightColor");
		m_cgParamLightPositionVector = cgGetNamedParameter(m_cgShaderFragment, "uniLightPosition");	
		
		m_cgParamEyePositionVector = cgGetNamedParameter(m_cgShaderFragment, "uniEyePosition");	
		
		m_cgParamShininess = cgGetNamedParameter(m_cgShaderFragment, "uniShininess");	
		
		m_cgParamMatDiffuseVector = cgGetNamedParameter(m_cgShaderFragment, "uniMatDiffuse");	
		m_cgParamMatSpecularVector = cgGetNamedParameter(m_cgShaderFragment, "uniMatSpecular");
		
		m_cgParamSamplerDiffuse = cgGetNamedParameter(m_cgShaderFragment, "uniTexDiffuse");	
		m_cgParamSamplerSpecular = cgGetNamedParameter(m_cgShaderFragment, "uniTexSpecular");	
		m_cgParamSamplerOutline = cgGetNamedParameter(m_cgShaderFragment, "uniTexOutline");	
		
		m_cgParamComputeOutline = cgGetNamedParameter(m_cgShaderFragment, "uniComputeOutline");	
		
		// [rad] Manually assign other (material) related params
		cgSetParameter1f(m_cgParamShininess, 128.0f);
	
		static const float af3ColorDiffuse[3] = {0.8f, 0.8f, 0.8f};
		cgSetParameter3fv(m_cgParamMatDiffuseVector, af3ColorDiffuse); 
		
		static const float af3ColorSpecular[3] = {1.0f, 1.0f, 1.0f};
		cgSetParameter3fv(m_cgParamMatSpecularVector, af3ColorSpecular);
		
		static const float af3Color[3] = {1.0f, 1.0f, 1.0f};
		cgSetParameter3fv(m_cgParamLightColorVector, af3Color);
		
		// [rad] Set texture params
		GenerateTextures();
		
		cgGLSetTextureParameter(m_cgParamSamplerDiffuse, m_glIDTextureDiffuse);
		cgGLSetTextureParameter(m_cgParamSamplerSpecular, m_glIDTextureSpecular);
		cgGLSetTextureParameter(m_cgParamSamplerOutline, m_glIDTextureOutline);
		
	}
Beispiel #22
0
CommandLine::CommandLine(const FilePath& program)
    : argv_(1), last_not_param_(argv_.begin()), default_switch_prefix_({L"-"})
{
    SetProgram(program);
}