code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_BUILDER_H
#define COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_BUILDER_H
#include "compiler/depgraph/DependencyGraph.h"
//
// Creates a dependency graph of symbols, function calls, conditions etc. by traversing a
// intermediate tree.
//
class TDependencyGraphBuilder : public TIntermTraverser {
public:
static void build(TIntermNode* node, TDependencyGraph* graph);
virtual void visitSymbol(TIntermSymbol*);
virtual bool visitBinary(Visit visit, TIntermBinary*);
virtual bool visitSelection(Visit visit, TIntermSelection*);
virtual bool visitAggregate(Visit visit, TIntermAggregate*);
virtual bool visitLoop(Visit visit, TIntermLoop*);
private:
typedef std::stack<TGraphSymbol*> TSymbolStack;
typedef std::set<TGraphParentNode*> TParentNodeSet;
//
// For collecting the dependent nodes of assignments, conditions, etc.
// while traversing the intermediate tree.
//
// This data structure is stack of sets. Each set contains dependency graph parent nodes.
//
class TNodeSetStack {
public:
TNodeSetStack() {};
~TNodeSetStack() { clear(); }
// This should only be called after a pushSet.
// Returns NULL if the top set is empty.
TParentNodeSet* getTopSet() const
{
ASSERT(!nodeSets.empty());
TParentNodeSet* topSet = nodeSets.top();
return !topSet->empty() ? topSet : NULL;
}
void pushSet() { nodeSets.push(new TParentNodeSet()); }
void popSet()
{
ASSERT(!nodeSets.empty());
delete nodeSets.top();
nodeSets.pop();
}
// Pops the top set and adds its contents to the new top set.
// This should only be called after a pushSet.
// If there is no set below the top set, the top set is just deleted.
void popSetIntoNext()
{
ASSERT(!nodeSets.empty());
TParentNodeSet* oldTopSet = nodeSets.top();
nodeSets.pop();
if (!nodeSets.empty()) {
TParentNodeSet* newTopSet = nodeSets.top();
newTopSet->insert(oldTopSet->begin(), oldTopSet->end());
}
delete oldTopSet;
}
// Does nothing if there is no top set.
// This can be called when there is no top set if we are visiting
// symbols that are not under an assignment or condition.
// We don't need to track those symbols.
void insertIntoTopSet(TGraphParentNode* node)
{
if (nodeSets.empty())
return;
nodeSets.top()->insert(node);
}
void clear()
{
while (!nodeSets.empty())
popSet();
}
private:
typedef std::stack<TParentNodeSet*> TParentNodeSetStack;
TParentNodeSetStack nodeSets;
};
//
// An instance of this class pushes a new node set when instantiated.
// When the instance goes out of scope, it and pops the node set.
//
class TNodeSetMaintainer {
public:
TNodeSetMaintainer(TDependencyGraphBuilder* factory)
: sets(factory->mNodeSets) { sets.pushSet(); }
~TNodeSetMaintainer() { sets.popSet(); }
protected:
TNodeSetStack& sets;
};
//
// An instance of this class pushes a new node set when instantiated.
// When the instance goes out of scope, it and pops the top node set and adds its contents to
// the new top node set.
//
class TNodeSetPropagatingMaintainer {
public:
TNodeSetPropagatingMaintainer(TDependencyGraphBuilder* factory)
: sets(factory->mNodeSets) { sets.pushSet(); }
~TNodeSetPropagatingMaintainer() { sets.popSetIntoNext(); }
protected:
TNodeSetStack& sets;
};
//
// An instance of this class keeps track of the leftmost symbol while we're exploring an
// assignment.
// It will push the placeholder symbol kLeftSubtree when instantiated under a left subtree,
// and kRightSubtree under a right subtree.
// When it goes out of scope, it will pop the leftmost symbol at the top of the scope.
// During traversal, the TDependencyGraphBuilder will replace kLeftSubtree with a real symbol.
// kRightSubtree will never be replaced by a real symbol because we are tracking the leftmost
// symbol.
//
class TLeftmostSymbolMaintainer {
public:
TLeftmostSymbolMaintainer(TDependencyGraphBuilder* factory, TGraphSymbol& subtree)
: leftmostSymbols(factory->mLeftmostSymbols)
{
needsPlaceholderSymbol = leftmostSymbols.empty() || leftmostSymbols.top() != &subtree;
if (needsPlaceholderSymbol)
leftmostSymbols.push(&subtree);
}
~TLeftmostSymbolMaintainer()
{
if (needsPlaceholderSymbol)
leftmostSymbols.pop();
}
protected:
TSymbolStack& leftmostSymbols;
bool needsPlaceholderSymbol;
};
TDependencyGraphBuilder(TDependencyGraph* graph)
: TIntermTraverser(true, false, false)
, mLeftSubtree(NULL)
, mRightSubtree(NULL)
, mGraph(graph) {}
void build(TIntermNode* intermNode) { intermNode->traverse(this); }
void connectMultipleNodesToSingleNode(TParentNodeSet* nodes, TGraphNode* node) const;
void visitAssignment(TIntermBinary*);
void visitLogicalOp(TIntermBinary*);
void visitBinaryChildren(TIntermBinary*);
void visitFunctionDefinition(TIntermAggregate*);
void visitFunctionCall(TIntermAggregate* intermFunctionCall);
void visitAggregateChildren(TIntermAggregate*);
TGraphSymbol mLeftSubtree;
TGraphSymbol mRightSubtree;
TDependencyGraph* mGraph;
TNodeSetStack mNodeSets;
TSymbolStack mLeftmostSymbols;
};
#endif // COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_BUILDER_H
| 010smithzhang-ddd | src/compiler/depgraph/DependencyGraphBuilder.h | C++ | bsd | 6,123 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/depgraph/DependencyGraph.h"
// These methods do a breadth-first traversal through the graph and mark visited nodes.
void TGraphNode::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->markVisited(this);
}
void TGraphParentNode::traverse(TDependencyGraphTraverser* graphTraverser)
{
TGraphNode::traverse(graphTraverser);
graphTraverser->incrementDepth();
// Visit the parent node's children.
for (TGraphNodeSet::const_iterator iter = mDependentNodes.begin();
iter != mDependentNodes.end();
++iter)
{
TGraphNode* node = *iter;
if (!graphTraverser->isVisited(node))
node->traverse(graphTraverser);
}
graphTraverser->decrementDepth();
}
void TGraphArgument::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitArgument(this);
TGraphParentNode::traverse(graphTraverser);
}
void TGraphFunctionCall::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitFunctionCall(this);
TGraphParentNode::traverse(graphTraverser);
}
void TGraphSymbol::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitSymbol(this);
TGraphParentNode::traverse(graphTraverser);
}
void TGraphSelection::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitSelection(this);
TGraphNode::traverse(graphTraverser);
}
void TGraphLoop::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitLoop(this);
TGraphNode::traverse(graphTraverser);
}
void TGraphLogicalOp::traverse(TDependencyGraphTraverser* graphTraverser)
{
graphTraverser->visitLogicalOp(this);
TGraphNode::traverse(graphTraverser);
}
| 010smithzhang-ddd | src/compiler/depgraph/DependencyGraphTraverse.cpp | C++ | bsd | 1,920 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_H
#define COMPILER_DEPGRAPH_DEPENDENCY_GRAPH_H
#include "compiler/intermediate.h"
#include <set>
#include <stack>
class TGraphNode;
class TGraphParentNode;
class TGraphArgument;
class TGraphFunctionCall;
class TGraphSymbol;
class TGraphSelection;
class TGraphLoop;
class TGraphLogicalOp;
class TDependencyGraphTraverser;
class TDependencyGraphOutput;
typedef std::set<TGraphNode*> TGraphNodeSet;
typedef std::vector<TGraphNode*> TGraphNodeVector;
typedef std::vector<TGraphSymbol*> TGraphSymbolVector;
typedef std::vector<TGraphFunctionCall*> TFunctionCallVector;
//
// Base class for all dependency graph nodes.
//
class TGraphNode {
public:
TGraphNode(TIntermNode* node) : intermNode(node) {}
virtual ~TGraphNode() {}
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
protected:
TIntermNode* intermNode;
};
//
// Base class for dependency graph nodes that may have children.
//
class TGraphParentNode : public TGraphNode {
public:
TGraphParentNode(TIntermNode* node) : TGraphNode(node) {}
virtual ~TGraphParentNode() {}
void addDependentNode(TGraphNode* node) { if (node != this) mDependentNodes.insert(node); }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
private:
TGraphNodeSet mDependentNodes;
};
//
// Handle function call arguments.
//
class TGraphArgument : public TGraphParentNode {
public:
TGraphArgument(TIntermAggregate* intermFunctionCall, int argumentNumber)
: TGraphParentNode(intermFunctionCall)
, mArgumentNumber(argumentNumber) {}
virtual ~TGraphArgument() {}
const TIntermAggregate* getIntermFunctionCall() const { return intermNode->getAsAggregate(); }
int getArgumentNumber() const { return mArgumentNumber; }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
private:
int mArgumentNumber;
};
//
// Handle function calls.
//
class TGraphFunctionCall : public TGraphParentNode {
public:
TGraphFunctionCall(TIntermAggregate* intermFunctionCall)
: TGraphParentNode(intermFunctionCall) {}
virtual ~TGraphFunctionCall() {}
const TIntermAggregate* getIntermFunctionCall() const { return intermNode->getAsAggregate(); }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
};
//
// Handle symbols.
//
class TGraphSymbol : public TGraphParentNode {
public:
TGraphSymbol(TIntermSymbol* intermSymbol) : TGraphParentNode(intermSymbol) {}
virtual ~TGraphSymbol() {}
const TIntermSymbol* getIntermSymbol() const { return intermNode->getAsSymbolNode(); }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
};
//
// Handle if statements and ternary operators.
//
class TGraphSelection : public TGraphNode {
public:
TGraphSelection(TIntermSelection* intermSelection) : TGraphNode(intermSelection) {}
virtual ~TGraphSelection() {}
const TIntermSelection* getIntermSelection() const { return intermNode->getAsSelectionNode(); }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
};
//
// Handle for, do-while, and while loops.
//
class TGraphLoop : public TGraphNode {
public:
TGraphLoop(TIntermLoop* intermLoop) : TGraphNode(intermLoop) {}
virtual ~TGraphLoop() {}
const TIntermLoop* getIntermLoop() const { return intermNode->getAsLoopNode(); }
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
};
//
// Handle logical and, or.
//
class TGraphLogicalOp : public TGraphNode {
public:
TGraphLogicalOp(TIntermBinary* intermLogicalOp) : TGraphNode(intermLogicalOp) {}
virtual ~TGraphLogicalOp() {}
const TIntermBinary* getIntermLogicalOp() const { return intermNode->getAsBinaryNode(); }
const char* getOpString() const;
virtual void traverse(TDependencyGraphTraverser* graphTraverser);
};
//
// A dependency graph of symbols, function calls, conditions etc.
//
// This class provides an interface to the entry points of the dependency graph.
//
// Dependency graph nodes should be created by using one of the provided "create..." methods.
// This class (and nobody else) manages the memory of the created nodes.
// Nodes may not be removed after being added, so all created nodes will exist while the
// TDependencyGraph instance exists.
//
class TDependencyGraph {
public:
TDependencyGraph(TIntermNode* intermNode);
~TDependencyGraph();
TGraphNodeVector::const_iterator begin() const { return mAllNodes.begin(); }
TGraphNodeVector::const_iterator end() const { return mAllNodes.end(); }
TGraphSymbolVector::const_iterator beginSamplerSymbols() const
{
return mSamplerSymbols.begin();
}
TGraphSymbolVector::const_iterator endSamplerSymbols() const
{
return mSamplerSymbols.end();
}
TFunctionCallVector::const_iterator beginUserDefinedFunctionCalls() const
{
return mUserDefinedFunctionCalls.begin();
}
TFunctionCallVector::const_iterator endUserDefinedFunctionCalls() const
{
return mUserDefinedFunctionCalls.end();
}
TGraphArgument* createArgument(TIntermAggregate* intermFunctionCall, int argumentNumber);
TGraphFunctionCall* createFunctionCall(TIntermAggregate* intermFunctionCall);
TGraphSymbol* getOrCreateSymbol(TIntermSymbol* intermSymbol);
TGraphSelection* createSelection(TIntermSelection* intermSelection);
TGraphLoop* createLoop(TIntermLoop* intermLoop);
TGraphLogicalOp* createLogicalOp(TIntermBinary* intermLogicalOp);
private:
typedef TMap<int, TGraphSymbol*> TSymbolIdMap;
typedef std::pair<int, TGraphSymbol*> TSymbolIdPair;
TGraphNodeVector mAllNodes;
TGraphSymbolVector mSamplerSymbols;
TFunctionCallVector mUserDefinedFunctionCalls;
TSymbolIdMap mSymbolIdMap;
};
//
// For traversing the dependency graph. Users should derive from this,
// put their traversal specific data in it, and then pass it to a
// traverse method.
//
// When using this, just fill in the methods for nodes you want visited.
//
class TDependencyGraphTraverser {
public:
TDependencyGraphTraverser() : mDepth(0) {}
virtual void visitSymbol(TGraphSymbol* symbol) {};
virtual void visitArgument(TGraphArgument* selection) {};
virtual void visitFunctionCall(TGraphFunctionCall* functionCall) {};
virtual void visitSelection(TGraphSelection* selection) {};
virtual void visitLoop(TGraphLoop* loop) {};
virtual void visitLogicalOp(TGraphLogicalOp* logicalOp) {};
int getDepth() const { return mDepth; }
void incrementDepth() { ++mDepth; }
void decrementDepth() { --mDepth; }
void clearVisited() { mVisited.clear(); }
void markVisited(TGraphNode* node) { mVisited.insert(node); }
bool isVisited(TGraphNode* node) const { return mVisited.find(node) != mVisited.end(); }
private:
int mDepth;
TGraphNodeSet mVisited;
};
#endif
| 010smithzhang-ddd | src/compiler/depgraph/DependencyGraph.h | C++ | bsd | 7,043 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#pragma warning(disable: 4718)
#include "compiler/depgraph/DependencyGraph.h"
#include "compiler/depgraph/DependencyGraphBuilder.h"
TDependencyGraph::TDependencyGraph(TIntermNode* intermNode)
{
TDependencyGraphBuilder::build(intermNode, this);
}
TDependencyGraph::~TDependencyGraph()
{
for (TGraphNodeVector::const_iterator iter = mAllNodes.begin(); iter != mAllNodes.end(); ++iter)
{
TGraphNode* node = *iter;
delete node;
}
}
TGraphArgument* TDependencyGraph::createArgument(TIntermAggregate* intermFunctionCall,
int argumentNumber)
{
TGraphArgument* argument = new TGraphArgument(intermFunctionCall, argumentNumber);
mAllNodes.push_back(argument);
return argument;
}
TGraphFunctionCall* TDependencyGraph::createFunctionCall(TIntermAggregate* intermFunctionCall)
{
TGraphFunctionCall* functionCall = new TGraphFunctionCall(intermFunctionCall);
mAllNodes.push_back(functionCall);
if (functionCall->getIntermFunctionCall()->isUserDefined())
mUserDefinedFunctionCalls.push_back(functionCall);
return functionCall;
}
TGraphSymbol* TDependencyGraph::getOrCreateSymbol(TIntermSymbol* intermSymbol)
{
TSymbolIdMap::const_iterator iter = mSymbolIdMap.find(intermSymbol->getId());
TGraphSymbol* symbol = NULL;
if (iter != mSymbolIdMap.end()) {
TSymbolIdPair pair = *iter;
symbol = pair.second;
} else {
symbol = new TGraphSymbol(intermSymbol);
mAllNodes.push_back(symbol);
TSymbolIdPair pair(intermSymbol->getId(), symbol);
mSymbolIdMap.insert(pair);
// We save all sampler symbols in a collection, so we can start graph traversals from them quickly.
if (IsSampler(intermSymbol->getBasicType()))
mSamplerSymbols.push_back(symbol);
}
return symbol;
}
TGraphSelection* TDependencyGraph::createSelection(TIntermSelection* intermSelection)
{
TGraphSelection* selection = new TGraphSelection(intermSelection);
mAllNodes.push_back(selection);
return selection;
}
TGraphLoop* TDependencyGraph::createLoop(TIntermLoop* intermLoop)
{
TGraphLoop* loop = new TGraphLoop(intermLoop);
mAllNodes.push_back(loop);
return loop;
}
TGraphLogicalOp* TDependencyGraph::createLogicalOp(TIntermBinary* intermLogicalOp)
{
TGraphLogicalOp* logicalOp = new TGraphLogicalOp(intermLogicalOp);
mAllNodes.push_back(logicalOp);
return logicalOp;
}
const char* TGraphLogicalOp::getOpString() const
{
const char* opString = NULL;
switch (getIntermLogicalOp()->getOp()) {
case EOpLogicalAnd: opString = "and"; break;
case EOpLogicalOr: opString = "or"; break;
default: opString = "unknown"; break;
}
return opString;
}
| 010smithzhang-ddd | src/compiler/depgraph/DependencyGraph.cpp | C++ | bsd | 2,968 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/InitializeDll.h"
#include "compiler/InitializeGlobals.h"
#include "compiler/InitializeParseContext.h"
#include "compiler/osinclude.h"
OS_TLSIndex ThreadInitializeIndex = OS_INVALID_TLS_INDEX;
bool InitProcess()
{
if (ThreadInitializeIndex != OS_INVALID_TLS_INDEX) {
//
// Function is re-entrant.
//
return true;
}
ThreadInitializeIndex = OS_AllocTLSIndex();
if (ThreadInitializeIndex == OS_INVALID_TLS_INDEX) {
assert(0 && "InitProcess(): Failed to allocate TLS area for init flag");
return false;
}
if (!InitializePoolIndex()) {
assert(0 && "InitProcess(): Failed to initalize global pool");
return false;
}
if (!InitializeParseContextIndex()) {
assert(0 && "InitProcess(): Failed to initalize parse context");
return false;
}
return InitThread();
}
bool DetachProcess()
{
bool success = true;
if (ThreadInitializeIndex == OS_INVALID_TLS_INDEX)
return true;
success = DetachThread();
if (!FreeParseContextIndex())
success = false;
FreePoolIndex();
OS_FreeTLSIndex(ThreadInitializeIndex);
ThreadInitializeIndex = OS_INVALID_TLS_INDEX;
return success;
}
bool InitThread()
{
//
// This function is re-entrant
//
if (ThreadInitializeIndex == OS_INVALID_TLS_INDEX) {
assert(0 && "InitThread(): Process hasn't been initalised.");
return false;
}
if (OS_GetTLSValue(ThreadInitializeIndex) != 0)
return true;
InitializeGlobalPools();
if (!InitializeGlobalParseContext())
return false;
if (!OS_SetTLSValue(ThreadInitializeIndex, (void *)1)) {
assert(0 && "InitThread(): Unable to set init flag.");
return false;
}
return true;
}
bool DetachThread()
{
bool success = true;
if (ThreadInitializeIndex == OS_INVALID_TLS_INDEX)
return true;
//
// Function is re-entrant and this thread may not have been initalised.
//
if (OS_GetTLSValue(ThreadInitializeIndex) != 0) {
if (!OS_SetTLSValue(ThreadInitializeIndex, (void *)0)) {
assert(0 && "DetachThread(): Unable to clear init flag.");
success = false;
}
if (!FreeParseContext())
success = false;
FreeGlobalPools();
}
return success;
}
| 010smithzhang-ddd | src/compiler/InitializeDll.cpp | C++ | bsd | 2,574 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/InfoSink.h"
void TInfoSinkBase::prefix(TPrefixType p) {
switch(p) {
case EPrefixNone:
break;
case EPrefixWarning:
sink.append("WARNING: ");
break;
case EPrefixError:
sink.append("ERROR: ");
break;
case EPrefixInternalError:
sink.append("INTERNAL ERROR: ");
break;
case EPrefixUnimplemented:
sink.append("UNIMPLEMENTED: ");
break;
case EPrefixNote:
sink.append("NOTE: ");
break;
default:
sink.append("UNKOWN ERROR: ");
break;
}
}
void TInfoSinkBase::location(int file, int line) {
TPersistStringStream stream;
if (line)
stream << file << ":" << line;
else
stream << file << ":? ";
stream << ": ";
sink.append(stream.str());
}
void TInfoSinkBase::location(const TSourceLoc& loc) {
location(loc.first_file, loc.first_line);
}
void TInfoSinkBase::message(TPrefixType p, const TSourceLoc& loc, const char* m) {
prefix(p);
location(loc);
sink.append(m);
sink.append("\n");
}
| 010smithzhang-ddd | src/compiler/InfoSink.cpp | C++ | bsd | 1,355 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef _VARIABLEPACKER_INCLUDED_
#define _VARIABLEPACKER_INCLUDED_
#include <vector>
#include "compiler/ShHandle.h"
class VariablePacker {
public:
// Returns true if the passed in variables pack in maxVectors following
// the packing rules from the GLSL 1.017 spec, Appendix A, section 7.
bool CheckVariablesWithinPackingLimits(
int maxVectors,
const TVariableInfoList& in_variables);
// Gets how many components in a row a data type takes.
static int GetNumComponentsPerRow(ShDataType type);
// Gets how many rows a data type takes.
static int GetNumRows(ShDataType type);
private:
static const int kNumColumns = 4;
static const unsigned kColumnMask = (1 << kNumColumns) - 1;
unsigned makeColumnFlags(int column, int numComponentsPerRow);
void fillColumns(int topRow, int numRows, int column, int numComponentsPerRow);
bool searchColumn(int column, int numRows, int* destRow, int* destSize);
int topNonFullRow_;
int bottomNonFullRow_;
int maxRows_;
std::vector<unsigned> rows_;
};
#endif // _VARIABLEPACKER_INCLUDED_
| 010smithzhang-ddd | src/compiler/VariablePacker.h | C++ | bsd | 1,295 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef __INITIALIZE_PARSE_CONTEXT_INCLUDED_
#define __INITIALIZE_PARSE_CONTEXT_INCLUDED_
bool InitializeParseContextIndex();
bool FreeParseContextIndex();
bool InitializeGlobalParseContext();
bool FreeParseContext();
struct TParseContext;
typedef TParseContext* TParseContextPointer;
extern TParseContextPointer& GetGlobalParseContext();
#define GlobalParseContext GetGlobalParseContext()
typedef struct TThreadParseContextRec
{
TParseContext *lpGlobalParseContext;
} TThreadParseContext;
#endif // __INITIALIZE_PARSE_CONTEXT_INCLUDED_
| 010smithzhang-ddd | src/compiler/InitializeParseContext.h | C | bsd | 732 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef COMPILER_TRANSLATORGLSL_H_
#define COMPILER_TRANSLATORGLSL_H_
#include "compiler/ShHandle.h"
class TranslatorGLSL : public TCompiler {
public:
TranslatorGLSL(ShShaderType type, ShShaderSpec spec);
protected:
virtual void translate(TIntermNode* root);
};
#endif // COMPILER_TRANSLATORGLSL_H_
| 010smithzhang-ddd | src/compiler/TranslatorGLSL.h | C++ | bsd | 498 |
//
// Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/DetectCallDepth.h"
#include "compiler/InfoSink.h"
DetectCallDepth::FunctionNode::FunctionNode(const TString& fname)
: name(fname),
visit(PreVisit)
{
}
const TString& DetectCallDepth::FunctionNode::getName() const
{
return name;
}
void DetectCallDepth::FunctionNode::addCallee(
DetectCallDepth::FunctionNode* callee)
{
for (size_t i = 0; i < callees.size(); ++i) {
if (callees[i] == callee)
return;
}
callees.push_back(callee);
}
int DetectCallDepth::FunctionNode::detectCallDepth(DetectCallDepth* detectCallDepth, int depth)
{
ASSERT(visit == PreVisit);
ASSERT(detectCallDepth);
int maxDepth = depth;
visit = InVisit;
for (size_t i = 0; i < callees.size(); ++i) {
switch (callees[i]->visit) {
case InVisit:
// cycle detected, i.e., recursion detected.
return kInfiniteCallDepth;
case PostVisit:
break;
case PreVisit: {
// Check before we recurse so we don't go too depth
if (detectCallDepth->checkExceedsMaxDepth(depth))
return depth;
int callDepth = callees[i]->detectCallDepth(detectCallDepth, depth + 1);
// Check after we recurse so we can exit immediately and provide info.
if (detectCallDepth->checkExceedsMaxDepth(callDepth)) {
detectCallDepth->getInfoSink().info << "<-" << callees[i]->getName();
return callDepth;
}
maxDepth = std::max(callDepth, maxDepth);
break;
}
default:
UNREACHABLE();
break;
}
}
visit = PostVisit;
return maxDepth;
}
void DetectCallDepth::FunctionNode::reset()
{
visit = PreVisit;
}
DetectCallDepth::DetectCallDepth(TInfoSink& infoSink, bool limitCallStackDepth, int maxCallStackDepth)
: TIntermTraverser(true, false, true, false),
currentFunction(NULL),
infoSink(infoSink),
maxDepth(limitCallStackDepth ? maxCallStackDepth : FunctionNode::kInfiniteCallDepth)
{
}
DetectCallDepth::~DetectCallDepth()
{
for (size_t i = 0; i < functions.size(); ++i)
delete functions[i];
}
bool DetectCallDepth::visitAggregate(Visit visit, TIntermAggregate* node)
{
switch (node->getOp())
{
case EOpPrototype:
// Function declaration.
// Don't add FunctionNode here because node->getName() is the
// unmangled function name.
break;
case EOpFunction: {
// Function definition.
if (visit == PreVisit) {
currentFunction = findFunctionByName(node->getName());
if (currentFunction == NULL) {
currentFunction = new FunctionNode(node->getName());
functions.push_back(currentFunction);
}
} else if (visit == PostVisit) {
currentFunction = NULL;
}
break;
}
case EOpFunctionCall: {
// Function call.
if (visit == PreVisit) {
FunctionNode* func = findFunctionByName(node->getName());
if (func == NULL) {
func = new FunctionNode(node->getName());
functions.push_back(func);
}
if (currentFunction)
currentFunction->addCallee(func);
}
break;
}
default:
break;
}
return true;
}
bool DetectCallDepth::checkExceedsMaxDepth(int depth)
{
return depth >= maxDepth;
}
void DetectCallDepth::resetFunctionNodes()
{
for (size_t i = 0; i < functions.size(); ++i) {
functions[i]->reset();
}
}
DetectCallDepth::ErrorCode DetectCallDepth::detectCallDepthForFunction(FunctionNode* func)
{
currentFunction = NULL;
resetFunctionNodes();
int maxCallDepth = func->detectCallDepth(this, 1);
if (maxCallDepth == FunctionNode::kInfiniteCallDepth)
return kErrorRecursion;
if (maxCallDepth >= maxDepth)
return kErrorMaxDepthExceeded;
return kErrorNone;
}
DetectCallDepth::ErrorCode DetectCallDepth::detectCallDepth()
{
if (maxDepth != FunctionNode::kInfiniteCallDepth) {
// Check all functions because the driver may fail on them
// TODO: Before detectingRecursion, strip unused functions.
for (size_t i = 0; i < functions.size(); ++i) {
ErrorCode error = detectCallDepthForFunction(functions[i]);
if (error != kErrorNone)
return error;
}
} else {
FunctionNode* main = findFunctionByName("main(");
if (main == NULL)
return kErrorMissingMain;
return detectCallDepthForFunction(main);
}
return kErrorNone;
}
DetectCallDepth::FunctionNode* DetectCallDepth::findFunctionByName(
const TString& name)
{
for (size_t i = 0; i < functions.size(); ++i) {
if (functions[i]->getName() == name)
return functions[i];
}
return NULL;
}
| 010smithzhang-ddd | src/compiler/DetectCallDepth.cpp | C++ | bsd | 5,365 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/MapLongVariableNames.h"
namespace {
TString mapLongName(size_t id, const TString& name, bool isGlobal)
{
ASSERT(name.size() > MAX_SHORTENED_IDENTIFIER_SIZE);
TStringStream stream;
stream << "webgl_";
if (isGlobal)
stream << "g";
stream << id;
if (name[0] != '_')
stream << "_";
stream << name.substr(0, MAX_SHORTENED_IDENTIFIER_SIZE - stream.str().size());
return stream.str();
}
LongNameMap* gLongNameMapInstance = NULL;
} // anonymous namespace
LongNameMap::LongNameMap()
: refCount(0)
{
}
LongNameMap::~LongNameMap()
{
}
// static
LongNameMap* LongNameMap::GetInstance()
{
if (gLongNameMapInstance == NULL)
gLongNameMapInstance = new LongNameMap;
gLongNameMapInstance->refCount++;
return gLongNameMapInstance;
}
void LongNameMap::Release()
{
ASSERT(gLongNameMapInstance == this);
ASSERT(refCount > 0);
refCount--;
if (refCount == 0) {
delete gLongNameMapInstance;
gLongNameMapInstance = NULL;
}
}
const char* LongNameMap::Find(const char* originalName) const
{
std::map<std::string, std::string>::const_iterator it = mLongNameMap.find(
originalName);
if (it != mLongNameMap.end())
return (*it).second.c_str();
return NULL;
}
void LongNameMap::Insert(const char* originalName, const char* mappedName)
{
mLongNameMap.insert(std::map<std::string, std::string>::value_type(
originalName, mappedName));
}
size_t LongNameMap::Size() const
{
return mLongNameMap.size();
}
MapLongVariableNames::MapLongVariableNames(LongNameMap* globalMap)
{
ASSERT(globalMap);
mGlobalMap = globalMap;
}
void MapLongVariableNames::visitSymbol(TIntermSymbol* symbol)
{
ASSERT(symbol != NULL);
if (symbol->getSymbol().size() > MAX_SHORTENED_IDENTIFIER_SIZE) {
switch (symbol->getQualifier()) {
case EvqVaryingIn:
case EvqVaryingOut:
case EvqInvariantVaryingIn:
case EvqInvariantVaryingOut:
case EvqUniform:
symbol->setSymbol(
mapGlobalLongName(symbol->getSymbol()));
break;
default:
symbol->setSymbol(
mapLongName(symbol->getId(), symbol->getSymbol(), false));
break;
};
}
}
bool MapLongVariableNames::visitLoop(Visit, TIntermLoop* node)
{
if (node->getInit())
node->getInit()->traverse(this);
return true;
}
TString MapLongVariableNames::mapGlobalLongName(const TString& name)
{
ASSERT(mGlobalMap);
const char* mappedName = mGlobalMap->Find(name.c_str());
if (mappedName != NULL)
return mappedName;
size_t id = mGlobalMap->Size();
TString rt = mapLongName(id, name, true);
mGlobalMap->Insert(name.c_str(), rt.c_str());
return rt;
}
| 010smithzhang-ddd | src/compiler/MapLongVariableNames.cpp | C++ | bsd | 3,010 |
# Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'build_angle.gypi',
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| 010smithzhang-ddd | src/build_angle.gyp | Python | bsd | 330 |
# Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'angle_code': 1,
},
'target_defaults': {
'defines': [
'ANGLE_DISABLE_TRACE',
'ANGLE_COMPILE_OPTIMIZATION_LEVEL=D3DCOMPILE_OPTIMIZATION_LEVEL1',
'ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES={ TEXT("d3dcompiler_46.dll"), TEXT("d3dcompiler_43.dll") }',
],
},
'targets': [
{
'target_name': 'preprocessor',
'type': 'static_library',
'include_dirs': [
],
'sources': [
'compiler/preprocessor/DiagnosticsBase.cpp',
'compiler/preprocessor/DiagnosticsBase.h',
'compiler/preprocessor/DirectiveHandlerBase.cpp',
'compiler/preprocessor/DirectiveHandlerBase.h',
'compiler/preprocessor/DirectiveParser.cpp',
'compiler/preprocessor/DirectiveParser.h',
'compiler/preprocessor/ExpressionParser.cpp',
'compiler/preprocessor/ExpressionParser.h',
'compiler/preprocessor/Input.cpp',
'compiler/preprocessor/Input.h',
'compiler/preprocessor/length_limits.h',
'compiler/preprocessor/Lexer.cpp',
'compiler/preprocessor/Lexer.h',
'compiler/preprocessor/Macro.cpp',
'compiler/preprocessor/Macro.h',
'compiler/preprocessor/MacroExpander.cpp',
'compiler/preprocessor/MacroExpander.h',
'compiler/preprocessor/numeric_lex.h',
'compiler/preprocessor/pp_utils.h',
'compiler/preprocessor/Preprocessor.cpp',
'compiler/preprocessor/Preprocessor.h',
'compiler/preprocessor/SourceLocation.h',
'compiler/preprocessor/Token.cpp',
'compiler/preprocessor/Token.h',
'compiler/preprocessor/Tokenizer.cpp',
'compiler/preprocessor/Tokenizer.h',
],
# TODO(jschuh): http://crbug.com/167187
'msvs_disabled_warnings': [
4267,
],
},
{
'target_name': 'translator_common',
'type': 'static_library',
'dependencies': ['preprocessor'],
'include_dirs': [
'.',
'../include',
],
'defines': [
'COMPILER_IMPLEMENTATION',
],
'sources': [
'compiler/BaseTypes.h',
'compiler/BuiltInFunctionEmulator.cpp',
'compiler/BuiltInFunctionEmulator.h',
'compiler/Common.h',
'compiler/Compiler.cpp',
'compiler/ConstantUnion.h',
'compiler/debug.cpp',
'compiler/debug.h',
'compiler/DetectCallDepth.cpp',
'compiler/DetectCallDepth.h',
'compiler/Diagnostics.h',
'compiler/Diagnostics.cpp',
'compiler/DirectiveHandler.h',
'compiler/DirectiveHandler.cpp',
'compiler/ExtensionBehavior.h',
'compiler/ForLoopUnroll.cpp',
'compiler/ForLoopUnroll.h',
'compiler/glslang.h',
'compiler/glslang_lex.cpp',
'compiler/glslang_tab.cpp',
'compiler/glslang_tab.h',
'compiler/HashNames.h',
'compiler/InfoSink.cpp',
'compiler/InfoSink.h',
'compiler/Initialize.cpp',
'compiler/Initialize.h',
'compiler/InitializeDll.cpp',
'compiler/InitializeDll.h',
'compiler/InitializeGlobals.h',
'compiler/InitializeParseContext.cpp',
'compiler/InitializeParseContext.h',
'compiler/Intermediate.cpp',
'compiler/intermediate.h',
'compiler/intermOut.cpp',
'compiler/IntermTraverse.cpp',
'compiler/localintermediate.h',
'compiler/MapLongVariableNames.cpp',
'compiler/MapLongVariableNames.h',
'compiler/MMap.h',
'compiler/osinclude.h',
'compiler/parseConst.cpp',
'compiler/ParseHelper.cpp',
'compiler/ParseHelper.h',
'compiler/PoolAlloc.cpp',
'compiler/PoolAlloc.h',
'compiler/QualifierAlive.cpp',
'compiler/QualifierAlive.h',
'compiler/RemoveTree.cpp',
'compiler/RemoveTree.h',
'compiler/RenameFunction.h',
'compiler/ShHandle.h',
'compiler/SymbolTable.cpp',
'compiler/SymbolTable.h',
'compiler/Types.h',
'compiler/Uniform.cpp',
'compiler/Uniform.h',
'compiler/util.cpp',
'compiler/util.h',
'compiler/ValidateLimitations.cpp',
'compiler/ValidateLimitations.h',
'compiler/VariableInfo.cpp',
'compiler/VariableInfo.h',
'compiler/VariablePacker.cpp',
'compiler/VariablePacker.h',
# Dependency graph
'compiler/depgraph/DependencyGraph.cpp',
'compiler/depgraph/DependencyGraph.h',
'compiler/depgraph/DependencyGraphBuilder.cpp',
'compiler/depgraph/DependencyGraphBuilder.h',
'compiler/depgraph/DependencyGraphOutput.cpp',
'compiler/depgraph/DependencyGraphOutput.h',
'compiler/depgraph/DependencyGraphTraverse.cpp',
# Timing restrictions
'compiler/timing/RestrictFragmentShaderTiming.cpp',
'compiler/timing/RestrictFragmentShaderTiming.h',
'compiler/timing/RestrictVertexShaderTiming.cpp',
'compiler/timing/RestrictVertexShaderTiming.h',
'third_party/compiler/ArrayBoundsClamper.cpp',
'third_party/compiler/ArrayBoundsClamper.h',
],
'conditions': [
['OS=="win"', {
# TODO(jschuh): http://crbug.com/167187 size_t -> int
'msvs_disabled_warnings': [ 4267 ],
'sources': ['compiler/ossource_win.cpp'],
}, { # else: posix
'sources': ['compiler/ossource_posix.cpp'],
}],
],
},
{
'target_name': 'translator_glsl',
'type': '<(component)',
'dependencies': ['translator_common'],
'include_dirs': [
'.',
'../include',
],
'defines': [
'COMPILER_IMPLEMENTATION',
],
'sources': [
'compiler/CodeGenGLSL.cpp',
'compiler/OutputESSL.cpp',
'compiler/OutputESSL.h',
'compiler/OutputGLSLBase.cpp',
'compiler/OutputGLSLBase.h',
'compiler/OutputGLSL.cpp',
'compiler/OutputGLSL.h',
'compiler/ShaderLang.cpp',
'compiler/TranslatorESSL.cpp',
'compiler/TranslatorESSL.h',
'compiler/TranslatorGLSL.cpp',
'compiler/TranslatorGLSL.h',
'compiler/VersionGLSL.cpp',
'compiler/VersionGLSL.h',
],
# TODO(jschuh): http://crbug.com/167187 size_t -> int
'msvs_disabled_warnings': [ 4267 ],
},
],
'conditions': [
['OS=="win"', {
'targets': [
{
'target_name': 'translator_hlsl',
'type': '<(component)',
'dependencies': ['translator_common'],
'include_dirs': [
'.',
'../include',
],
'defines': [
'COMPILER_IMPLEMENTATION',
],
'sources': [
'compiler/ShaderLang.cpp',
'compiler/DetectDiscontinuity.cpp',
'compiler/DetectDiscontinuity.h',
'compiler/CodeGenHLSL.cpp',
'compiler/OutputHLSL.cpp',
'compiler/OutputHLSL.h',
'compiler/TranslatorHLSL.cpp',
'compiler/TranslatorHLSL.h',
'compiler/UnfoldShortCircuit.cpp',
'compiler/UnfoldShortCircuit.h',
'compiler/SearchSymbol.cpp',
'compiler/SearchSymbol.h',
],
# TODO(jschuh): http://crbug.com/167187 size_t -> int
'msvs_disabled_warnings': [ 4267 ],
},
{
'target_name': 'libGLESv2',
'type': 'shared_library',
'dependencies': ['translator_hlsl'],
'include_dirs': [
'.',
'../include',
'libGLESv2',
],
'sources': [
'third_party/murmurhash/MurmurHash3.h',
'third_party/murmurhash/MurmurHash3.cpp',
'common/angleutils.h',
'common/debug.cpp',
'common/debug.h',
'common/RefCountObject.cpp',
'common/RefCountObject.h',
'common/version.h',
'libGLESv2/precompiled.h',
'libGLESv2/precompiled.cpp',
'libGLESv2/BinaryStream.h',
'libGLESv2/Buffer.cpp',
'libGLESv2/Buffer.h',
'libGLESv2/constants.h',
'libGLESv2/Context.cpp',
'libGLESv2/Context.h',
'libGLESv2/angletypes.h',
'libGLESv2/Fence.cpp',
'libGLESv2/Fence.h',
'libGLESv2/Float16ToFloat32.cpp',
'libGLESv2/Framebuffer.cpp',
'libGLESv2/Framebuffer.h',
'libGLESv2/HandleAllocator.cpp',
'libGLESv2/HandleAllocator.h',
'libGLESv2/libGLESv2.cpp',
'libGLESv2/libGLESv2.def',
'libGLESv2/libGLESv2.rc',
'libGLESv2/main.cpp',
'libGLESv2/main.h',
'libGLESv2/mathutil.h',
'libGLESv2/Program.cpp',
'libGLESv2/Program.h',
'libGLESv2/ProgramBinary.cpp',
'libGLESv2/ProgramBinary.h',
'libGLESv2/Query.h',
'libGLESv2/Query.cpp',
'libGLESv2/Renderbuffer.cpp',
'libGLESv2/Renderbuffer.h',
'libGLESv2/renderer/Blit.cpp',
'libGLESv2/renderer/Blit.h',
'libGLESv2/renderer/BufferStorage.h',
'libGLESv2/renderer/BufferStorage.cpp',
'libGLESv2/renderer/BufferStorage9.cpp',
'libGLESv2/renderer/BufferStorage9.h',
'libGLESv2/renderer/BufferStorage11.cpp',
'libGLESv2/renderer/BufferStorage11.h',
'libGLESv2/renderer/FenceImpl.h',
'libGLESv2/renderer/Fence9.cpp',
'libGLESv2/renderer/Fence9.h',
'libGLESv2/renderer/Fence11.cpp',
'libGLESv2/renderer/Fence11.h',
'libGLESv2/renderer/generatemip.h',
'libGLESv2/renderer/Image.cpp',
'libGLESv2/renderer/Image.h',
'libGLESv2/renderer/Image11.cpp',
'libGLESv2/renderer/Image11.h',
'libGLESv2/renderer/Image9.cpp',
'libGLESv2/renderer/Image9.h',
'libGLESv2/renderer/ImageSSE2.cpp',
'libGLESv2/renderer/IndexBuffer.cpp',
'libGLESv2/renderer/IndexBuffer.h',
'libGLESv2/renderer/IndexBuffer9.cpp',
'libGLESv2/renderer/IndexBuffer9.h',
'libGLESv2/renderer/IndexBuffer11.cpp',
'libGLESv2/renderer/IndexBuffer11.h',
'libGLESv2/renderer/IndexDataManager.cpp',
'libGLESv2/renderer/IndexDataManager.h',
'libGLESv2/renderer/InputLayoutCache.cpp',
'libGLESv2/renderer/InputLayoutCache.h',
'libGLESv2/renderer/QueryImpl.h',
'libGLESv2/renderer/Query9.cpp',
'libGLESv2/renderer/Query9.h',
'libGLESv2/renderer/Query11.cpp',
'libGLESv2/renderer/Query11.h',
'libGLESv2/renderer/Renderer.cpp',
'libGLESv2/renderer/Renderer.h',
'libGLESv2/renderer/Renderer11.cpp',
'libGLESv2/renderer/Renderer11.h',
'libGLESv2/renderer/renderer11_utils.cpp',
'libGLESv2/renderer/renderer11_utils.h',
'libGLESv2/renderer/Renderer9.cpp',
'libGLESv2/renderer/Renderer9.h',
'libGLESv2/renderer/renderer9_utils.cpp',
'libGLESv2/renderer/renderer9_utils.h',
'libGLESv2/renderer/RenderStateCache.cpp',
'libGLESv2/renderer/RenderStateCache.h',
'libGLESv2/renderer/RenderTarget.h',
'libGLESv2/renderer/RenderTarget11.h',
'libGLESv2/renderer/RenderTarget11.cpp',
'libGLESv2/renderer/RenderTarget9.h',
'libGLESv2/renderer/RenderTarget9.cpp',
'libGLESv2/renderer/ShaderCache.h',
'libGLESv2/renderer/ShaderExecutable.h',
'libGLESv2/renderer/ShaderExecutable9.cpp',
'libGLESv2/renderer/ShaderExecutable9.h',
'libGLESv2/renderer/ShaderExecutable11.cpp',
'libGLESv2/renderer/ShaderExecutable11.h',
'libGLESv2/renderer/SwapChain.h',
'libGLESv2/renderer/SwapChain9.cpp',
'libGLESv2/renderer/SwapChain9.h',
'libGLESv2/renderer/SwapChain11.cpp',
'libGLESv2/renderer/SwapChain11.h',
'libGLESv2/renderer/TextureStorage.cpp',
'libGLESv2/renderer/TextureStorage.h',
'libGLESv2/renderer/TextureStorage11.cpp',
'libGLESv2/renderer/TextureStorage11.h',
'libGLESv2/renderer/TextureStorage9.cpp',
'libGLESv2/renderer/TextureStorage9.h',
'libGLESv2/renderer/VertexBuffer.cpp',
'libGLESv2/renderer/VertexBuffer.h',
'libGLESv2/renderer/VertexBuffer9.cpp',
'libGLESv2/renderer/VertexBuffer9.h',
'libGLESv2/renderer/VertexBuffer11.cpp',
'libGLESv2/renderer/VertexBuffer11.h',
'libGLESv2/renderer/vertexconversion.h',
'libGLESv2/renderer/VertexDataManager.cpp',
'libGLESv2/renderer/VertexDataManager.h',
'libGLESv2/renderer/VertexDeclarationCache.cpp',
'libGLESv2/renderer/VertexDeclarationCache.h',
'libGLESv2/ResourceManager.cpp',
'libGLESv2/ResourceManager.h',
'libGLESv2/Shader.cpp',
'libGLESv2/Shader.h',
'libGLESv2/Texture.cpp',
'libGLESv2/Texture.h',
'libGLESv2/Uniform.cpp',
'libGLESv2/Uniform.h',
'libGLESv2/utilities.cpp',
'libGLESv2/utilities.h',
],
# TODO(jschuh): http://crbug.com/167187 size_t -> int
'msvs_disabled_warnings': [ 4267 ],
'msvs_settings': {
'VCLinkerTool': {
'AdditionalDependencies': [
'd3d9.lib',
'dxguid.lib',
],
}
},
},
{
'target_name': 'libEGL',
'type': 'shared_library',
'dependencies': ['libGLESv2'],
'include_dirs': [
'.',
'../include',
'libGLESv2',
],
'sources': [
'common/angleutils.h',
'common/debug.cpp',
'common/debug.h',
'common/RefCountObject.cpp',
'common/RefCountObject.h',
'common/version.h',
'libEGL/Config.cpp',
'libEGL/Config.h',
'libEGL/Display.cpp',
'libEGL/Display.h',
'libEGL/libEGL.cpp',
'libEGL/libEGL.def',
'libEGL/libEGL.rc',
'libEGL/main.cpp',
'libEGL/main.h',
'libEGL/Surface.cpp',
'libEGL/Surface.h',
],
# TODO(jschuh): http://crbug.com/167187 size_t -> int
'msvs_disabled_warnings': [ 4267 ],
'msvs_settings': {
'VCLinkerTool': {
'AdditionalDependencies': [
'd3d9.lib',
],
}
},
},
],
}],
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
# Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
| 010smithzhang-ddd | src/build_angle.gypi | Python | bsd | 15,485 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Config.h: Defines the egl::Config class, describing the format, type
// and size for an egl::Surface. Implements EGLConfig and related functionality.
// [EGL 1.4] section 3.4 page 15.
#ifndef INCLUDE_CONFIG_H_
#define INCLUDE_CONFIG_H_
#define EGLAPI
#include <EGL/egl.h>
#include <set>
#include "libGLESv2/renderer/Renderer.h"
#include "common/angleutils.h"
namespace egl
{
class Display;
class Config
{
public:
Config(rx::ConfigDesc desc, EGLint minSwapInterval, EGLint maxSwapInterval, EGLint texWidth, EGLint texHeight);
EGLConfig getHandle() const;
const GLenum mRenderTargetFormat;
const GLenum mDepthStencilFormat;
const GLint mMultiSample;
EGLint mBufferSize; // Depth of the color buffer
EGLint mRedSize; // Bits of Red in the color buffer
EGLint mGreenSize; // Bits of Green in the color buffer
EGLint mBlueSize; // Bits of Blue in the color buffer
EGLint mLuminanceSize; // Bits of Luminance in the color buffer
EGLint mAlphaSize; // Bits of Alpha in the color buffer
EGLint mAlphaMaskSize; // Bits of Alpha Mask in the mask buffer
EGLBoolean mBindToTextureRGB; // True if bindable to RGB textures.
EGLBoolean mBindToTextureRGBA; // True if bindable to RGBA textures.
EGLenum mColorBufferType; // Color buffer type
EGLenum mConfigCaveat; // Any caveats for the configuration
EGLint mConfigID; // Unique EGLConfig identifier
EGLint mConformant; // Whether contexts created with this config are conformant
EGLint mDepthSize; // Bits of Z in the depth buffer
EGLint mLevel; // Frame buffer level
EGLBoolean mMatchNativePixmap; // Match the native pixmap format
EGLint mMaxPBufferWidth; // Maximum width of pbuffer
EGLint mMaxPBufferHeight; // Maximum height of pbuffer
EGLint mMaxPBufferPixels; // Maximum size of pbuffer
EGLint mMaxSwapInterval; // Maximum swap interval
EGLint mMinSwapInterval; // Minimum swap interval
EGLBoolean mNativeRenderable; // EGL_TRUE if native rendering APIs can render to surface
EGLint mNativeVisualID; // Handle of corresponding native visual
EGLint mNativeVisualType; // Native visual type of the associated visual
EGLint mRenderableType; // Which client rendering APIs are supported.
EGLint mSampleBuffers; // Number of multisample buffers
EGLint mSamples; // Number of samples per pixel
EGLint mStencilSize; // Bits of Stencil in the stencil buffer
EGLint mSurfaceType; // Which types of EGL surfaces are supported.
EGLenum mTransparentType; // Type of transparency supported
EGLint mTransparentRedValue; // Transparent red value
EGLint mTransparentGreenValue; // Transparent green value
EGLint mTransparentBlueValue; // Transparent blue value
};
// Function object used by STL sorting routines for ordering Configs according to [EGL] section 3.4.1 page 24.
class SortConfig
{
public:
explicit SortConfig(const EGLint *attribList);
bool operator()(const Config *x, const Config *y) const;
bool operator()(const Config &x, const Config &y) const;
private:
void scanForWantedComponents(const EGLint *attribList);
EGLint wantedComponentsSize(const Config &config) const;
bool mWantRed;
bool mWantGreen;
bool mWantBlue;
bool mWantAlpha;
bool mWantLuminance;
};
class ConfigSet
{
friend Display;
public:
ConfigSet();
void add(rx::ConfigDesc desc, EGLint minSwapInterval, EGLint maxSwapInterval, EGLint texWidth, EGLint texHeight);
size_t size() const;
bool getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig);
const egl::Config *get(EGLConfig configHandle);
private:
DISALLOW_COPY_AND_ASSIGN(ConfigSet);
typedef std::set<Config, SortConfig> Set;
typedef Set::iterator Iterator;
Set mSet;
static const EGLint mSortAttribs[];
};
}
#endif // INCLUDE_CONFIG_H_
| 010smithzhang-ddd | src/libEGL/Config.h | C++ | bsd | 4,404 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Display.h: Defines the egl::Display class, representing the abstract
// display on which graphics are drawn. Implements EGLDisplay.
// [EGL 1.4] section 2.1.2 page 3.
#ifndef LIBEGL_DISPLAY_H_
#define LIBEGL_DISPLAY_H_
#include "common/system.h"
#include <set>
#include <vector>
#include "libEGL/Config.h"
namespace gl
{
class Context;
}
namespace egl
{
class Surface;
class Display
{
public:
~Display();
bool initialize();
void terminate();
static egl::Display *getDisplay(EGLNativeDisplayType displayId);
bool getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig);
bool getConfigAttrib(EGLConfig config, EGLint attribute, EGLint *value);
EGLSurface createWindowSurface(HWND window, EGLConfig config, const EGLint *attribList);
EGLSurface createOffscreenSurface(EGLConfig config, HANDLE shareHandle, const EGLint *attribList);
EGLContext createContext(EGLConfig configHandle, const gl::Context *shareContext, bool notifyResets, bool robustAccess);
void destroySurface(egl::Surface *surface);
void destroyContext(gl::Context *context);
bool isInitialized() const;
bool isValidConfig(EGLConfig config);
bool isValidContext(gl::Context *context);
bool isValidSurface(egl::Surface *surface);
bool hasExistingWindowSurface(HWND window);
rx::Renderer *getRenderer() { return mRenderer; };
// exported methods must be virtual
virtual void notifyDeviceLost();
virtual void recreateSwapChains();
const char *getExtensionString() const;
const char *getVendorString() const;
private:
DISALLOW_COPY_AND_ASSIGN(Display);
Display(EGLNativeDisplayType displayId, HDC deviceContext);
bool restoreLostDevice();
EGLNativeDisplayType mDisplayId;
const HDC mDc;
bool mSoftwareDevice;
typedef std::set<Surface*> SurfaceSet;
SurfaceSet mSurfaceSet;
ConfigSet mConfigSet;
typedef std::set<gl::Context*> ContextSet;
ContextSet mContextSet;
rx::Renderer *mRenderer;
void initExtensionString();
void initVendorString();
std::string mExtensionString;
std::string mVendorString;
};
}
#endif // LIBEGL_DISPLAY_H_
| 010smithzhang-ddd | src/libEGL/Display.h | C++ | bsd | 2,404 |
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by libEGL.rc
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 010smithzhang-ddd | src/libEGL/resource.h | C | bsd | 386 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Display.cpp: Implements the egl::Display class, representing the abstract
// display on which graphics are drawn. Implements EGLDisplay.
// [EGL 1.4] section 2.1.2 page 3.
#include "libEGL/Display.h"
#include <algorithm>
#include <map>
#include <vector>
#include "common/debug.h"
#include "libGLESv2/mathutil.h"
#include "libGLESv2/main.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/renderer/SwapChain.h"
#include "libEGL/main.h"
#include "libEGL/Surface.h"
namespace egl
{
namespace
{
typedef std::map<EGLNativeDisplayType, Display*> DisplayMap;
DisplayMap displays;
}
egl::Display *Display::getDisplay(EGLNativeDisplayType displayId)
{
if (displays.find(displayId) != displays.end())
{
return displays[displayId];
}
// FIXME: Check if displayId is a valid display device context
egl::Display *display = new egl::Display(displayId, (HDC)displayId);
displays[displayId] = display;
return display;
}
Display::Display(EGLNativeDisplayType displayId, HDC deviceContext) : mDc(deviceContext)
{
mDisplayId = displayId;
mRenderer = NULL;
}
Display::~Display()
{
terminate();
DisplayMap::iterator thisDisplay = displays.find(mDisplayId);
if (thisDisplay != displays.end())
{
displays.erase(thisDisplay);
}
}
bool Display::initialize()
{
if (isInitialized())
{
return true;
}
mRenderer = glCreateRenderer(this, mDc, mDisplayId);
if (!mRenderer)
{
terminate();
return error(EGL_NOT_INITIALIZED, false);
}
EGLint minSwapInterval = mRenderer->getMinSwapInterval();
EGLint maxSwapInterval = mRenderer->getMaxSwapInterval();
EGLint maxTextureWidth = mRenderer->getMaxTextureWidth();
EGLint maxTextureHeight = mRenderer->getMaxTextureHeight();
rx::ConfigDesc *descList;
int numConfigs = mRenderer->generateConfigs(&descList);
ConfigSet configSet;
for (int i = 0; i < numConfigs; ++i)
configSet.add(descList[i], minSwapInterval, maxSwapInterval,
maxTextureWidth, maxTextureHeight);
// Give the sorted configs a unique ID and store them internally
EGLint index = 1;
for (ConfigSet::Iterator config = configSet.mSet.begin(); config != configSet.mSet.end(); config++)
{
Config configuration = *config;
configuration.mConfigID = index;
index++;
mConfigSet.mSet.insert(configuration);
}
mRenderer->deleteConfigs(descList);
descList = NULL;
if (!isInitialized())
{
terminate();
return false;
}
initExtensionString();
initVendorString();
return true;
}
void Display::terminate()
{
while (!mSurfaceSet.empty())
{
destroySurface(*mSurfaceSet.begin());
}
while (!mContextSet.empty())
{
destroyContext(*mContextSet.begin());
}
glDestroyRenderer(mRenderer);
mRenderer = NULL;
}
bool Display::getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig)
{
return mConfigSet.getConfigs(configs, attribList, configSize, numConfig);
}
bool Display::getConfigAttrib(EGLConfig config, EGLint attribute, EGLint *value)
{
const egl::Config *configuration = mConfigSet.get(config);
switch (attribute)
{
case EGL_BUFFER_SIZE: *value = configuration->mBufferSize; break;
case EGL_ALPHA_SIZE: *value = configuration->mAlphaSize; break;
case EGL_BLUE_SIZE: *value = configuration->mBlueSize; break;
case EGL_GREEN_SIZE: *value = configuration->mGreenSize; break;
case EGL_RED_SIZE: *value = configuration->mRedSize; break;
case EGL_DEPTH_SIZE: *value = configuration->mDepthSize; break;
case EGL_STENCIL_SIZE: *value = configuration->mStencilSize; break;
case EGL_CONFIG_CAVEAT: *value = configuration->mConfigCaveat; break;
case EGL_CONFIG_ID: *value = configuration->mConfigID; break;
case EGL_LEVEL: *value = configuration->mLevel; break;
case EGL_NATIVE_RENDERABLE: *value = configuration->mNativeRenderable; break;
case EGL_NATIVE_VISUAL_TYPE: *value = configuration->mNativeVisualType; break;
case EGL_SAMPLES: *value = configuration->mSamples; break;
case EGL_SAMPLE_BUFFERS: *value = configuration->mSampleBuffers; break;
case EGL_SURFACE_TYPE: *value = configuration->mSurfaceType; break;
case EGL_TRANSPARENT_TYPE: *value = configuration->mTransparentType; break;
case EGL_TRANSPARENT_BLUE_VALUE: *value = configuration->mTransparentBlueValue; break;
case EGL_TRANSPARENT_GREEN_VALUE: *value = configuration->mTransparentGreenValue; break;
case EGL_TRANSPARENT_RED_VALUE: *value = configuration->mTransparentRedValue; break;
case EGL_BIND_TO_TEXTURE_RGB: *value = configuration->mBindToTextureRGB; break;
case EGL_BIND_TO_TEXTURE_RGBA: *value = configuration->mBindToTextureRGBA; break;
case EGL_MIN_SWAP_INTERVAL: *value = configuration->mMinSwapInterval; break;
case EGL_MAX_SWAP_INTERVAL: *value = configuration->mMaxSwapInterval; break;
case EGL_LUMINANCE_SIZE: *value = configuration->mLuminanceSize; break;
case EGL_ALPHA_MASK_SIZE: *value = configuration->mAlphaMaskSize; break;
case EGL_COLOR_BUFFER_TYPE: *value = configuration->mColorBufferType; break;
case EGL_RENDERABLE_TYPE: *value = configuration->mRenderableType; break;
case EGL_MATCH_NATIVE_PIXMAP: *value = false; UNIMPLEMENTED(); break;
case EGL_CONFORMANT: *value = configuration->mConformant; break;
case EGL_MAX_PBUFFER_WIDTH: *value = configuration->mMaxPBufferWidth; break;
case EGL_MAX_PBUFFER_HEIGHT: *value = configuration->mMaxPBufferHeight; break;
case EGL_MAX_PBUFFER_PIXELS: *value = configuration->mMaxPBufferPixels; break;
default:
return false;
}
return true;
}
EGLSurface Display::createWindowSurface(HWND window, EGLConfig config, const EGLint *attribList)
{
const Config *configuration = mConfigSet.get(config);
EGLint postSubBufferSupported = EGL_FALSE;
if (attribList)
{
while (*attribList != EGL_NONE)
{
switch (attribList[0])
{
case EGL_RENDER_BUFFER:
switch (attribList[1])
{
case EGL_BACK_BUFFER:
break;
case EGL_SINGLE_BUFFER:
return error(EGL_BAD_MATCH, EGL_NO_SURFACE); // Rendering directly to front buffer not supported
default:
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
break;
case EGL_POST_SUB_BUFFER_SUPPORTED_NV:
postSubBufferSupported = attribList[1];
break;
case EGL_VG_COLORSPACE:
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
case EGL_VG_ALPHA_FORMAT:
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
default:
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
attribList += 2;
}
}
if (hasExistingWindowSurface(window))
{
return error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
if (mRenderer->testDeviceLost(false))
{
if (!restoreLostDevice())
return EGL_NO_SURFACE;
}
Surface *surface = new Surface(this, configuration, window, postSubBufferSupported);
if (!surface->initialize())
{
delete surface;
return EGL_NO_SURFACE;
}
mSurfaceSet.insert(surface);
return success(surface);
}
EGLSurface Display::createOffscreenSurface(EGLConfig config, HANDLE shareHandle, const EGLint *attribList)
{
EGLint width = 0, height = 0;
EGLenum textureFormat = EGL_NO_TEXTURE;
EGLenum textureTarget = EGL_NO_TEXTURE;
const Config *configuration = mConfigSet.get(config);
if (attribList)
{
while (*attribList != EGL_NONE)
{
switch (attribList[0])
{
case EGL_WIDTH:
width = attribList[1];
break;
case EGL_HEIGHT:
height = attribList[1];
break;
case EGL_LARGEST_PBUFFER:
if (attribList[1] != EGL_FALSE)
UNIMPLEMENTED(); // FIXME
break;
case EGL_TEXTURE_FORMAT:
switch (attribList[1])
{
case EGL_NO_TEXTURE:
case EGL_TEXTURE_RGB:
case EGL_TEXTURE_RGBA:
textureFormat = attribList[1];
break;
default:
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
break;
case EGL_TEXTURE_TARGET:
switch (attribList[1])
{
case EGL_NO_TEXTURE:
case EGL_TEXTURE_2D:
textureTarget = attribList[1];
break;
default:
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
break;
case EGL_MIPMAP_TEXTURE:
if (attribList[1] != EGL_FALSE)
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
break;
case EGL_VG_COLORSPACE:
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
case EGL_VG_ALPHA_FORMAT:
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
default:
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
attribList += 2;
}
}
if (width < 0 || height < 0)
{
return error(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
}
if (width == 0 || height == 0)
{
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
if (textureFormat != EGL_NO_TEXTURE && !mRenderer->getNonPower2TextureSupport() && (!gl::isPow2(width) || !gl::isPow2(height)))
{
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
}
if ((textureFormat != EGL_NO_TEXTURE && textureTarget == EGL_NO_TEXTURE) ||
(textureFormat == EGL_NO_TEXTURE && textureTarget != EGL_NO_TEXTURE))
{
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
}
if (!(configuration->mSurfaceType & EGL_PBUFFER_BIT))
{
return error(EGL_BAD_MATCH, EGL_NO_SURFACE);
}
if ((textureFormat == EGL_TEXTURE_RGB && configuration->mBindToTextureRGB != EGL_TRUE) ||
(textureFormat == EGL_TEXTURE_RGBA && configuration->mBindToTextureRGBA != EGL_TRUE))
{
return error(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
}
if (mRenderer->testDeviceLost(false))
{
if (!restoreLostDevice())
return EGL_NO_SURFACE;
}
Surface *surface = new Surface(this, configuration, shareHandle, width, height, textureFormat, textureTarget);
if (!surface->initialize())
{
delete surface;
return EGL_NO_SURFACE;
}
mSurfaceSet.insert(surface);
return success(surface);
}
EGLContext Display::createContext(EGLConfig configHandle, const gl::Context *shareContext, bool notifyResets, bool robustAccess)
{
if (!mRenderer)
{
return NULL;
}
else if (mRenderer->testDeviceLost(false)) // Lost device
{
if (!restoreLostDevice())
return NULL;
}
gl::Context *context = glCreateContext(shareContext, mRenderer, notifyResets, robustAccess);
mContextSet.insert(context);
return context;
}
bool Display::restoreLostDevice()
{
for (ContextSet::iterator ctx = mContextSet.begin(); ctx != mContextSet.end(); ctx++)
{
if ((*ctx)->isResetNotificationEnabled())
return false; // If reset notifications have been requested, application must delete all contexts first
}
// Release surface resources to make the Reset() succeed
for (SurfaceSet::iterator surface = mSurfaceSet.begin(); surface != mSurfaceSet.end(); surface++)
{
(*surface)->release();
}
if (!mRenderer->resetDevice())
{
return error(EGL_BAD_ALLOC, false);
}
// Restore any surfaces that may have been lost
for (SurfaceSet::iterator surface = mSurfaceSet.begin(); surface != mSurfaceSet.end(); surface++)
{
(*surface)->resetSwapChain();
}
return true;
}
void Display::destroySurface(egl::Surface *surface)
{
delete surface;
mSurfaceSet.erase(surface);
}
void Display::destroyContext(gl::Context *context)
{
glDestroyContext(context);
mContextSet.erase(context);
}
void Display::notifyDeviceLost()
{
for (ContextSet::iterator context = mContextSet.begin(); context != mContextSet.end(); context++)
{
(*context)->markContextLost();
}
egl::error(EGL_CONTEXT_LOST);
}
void Display::recreateSwapChains()
{
for (SurfaceSet::iterator surface = mSurfaceSet.begin(); surface != mSurfaceSet.end(); surface++)
{
(*surface)->getSwapChain()->recreate();
}
}
bool Display::isInitialized() const
{
return mRenderer != NULL && mConfigSet.size() > 0;
}
bool Display::isValidConfig(EGLConfig config)
{
return mConfigSet.get(config) != NULL;
}
bool Display::isValidContext(gl::Context *context)
{
return mContextSet.find(context) != mContextSet.end();
}
bool Display::isValidSurface(egl::Surface *surface)
{
return mSurfaceSet.find(surface) != mSurfaceSet.end();
}
bool Display::hasExistingWindowSurface(HWND window)
{
for (SurfaceSet::iterator surface = mSurfaceSet.begin(); surface != mSurfaceSet.end(); surface++)
{
if ((*surface)->getWindowHandle() == window)
{
return true;
}
}
return false;
}
void Display::initExtensionString()
{
HMODULE swiftShader = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
bool shareHandleSupported = mRenderer->getShareHandleSupport();
mExtensionString = "";
// Multi-vendor (EXT) extensions
mExtensionString += "EGL_EXT_create_context_robustness ";
// ANGLE-specific extensions
if (shareHandleSupported)
{
mExtensionString += "EGL_ANGLE_d3d_share_handle_client_buffer ";
}
mExtensionString += "EGL_ANGLE_query_surface_pointer ";
if (swiftShader)
{
mExtensionString += "EGL_ANGLE_software_display ";
}
if (shareHandleSupported)
{
mExtensionString += "EGL_ANGLE_surface_d3d_texture_2d_share_handle ";
}
if (mRenderer->getPostSubBufferSupport())
{
mExtensionString += "EGL_NV_post_sub_buffer";
}
std::string::size_type end = mExtensionString.find_last_not_of(' ');
if (end != std::string::npos)
{
mExtensionString.resize(end+1);
}
}
const char *Display::getExtensionString() const
{
return mExtensionString.c_str();
}
void Display::initVendorString()
{
mVendorString = "Google Inc.";
LUID adapterLuid = {0};
if (mRenderer && mRenderer->getLUID(&adapterLuid))
{
char adapterLuidString[64];
sprintf_s(adapterLuidString, sizeof(adapterLuidString), " (adapter LUID: %08x%08x)", adapterLuid.HighPart, adapterLuid.LowPart);
mVendorString += adapterLuidString;
}
}
const char *Display::getVendorString() const
{
return mVendorString.c_str();
}
}
| 010smithzhang-ddd | src/libEGL/Display.cpp | C++ | bsd | 16,219 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// main.cpp: DLL entry point and management of thread-local data.
#include "libEGL/main.h"
#include "common/debug.h"
static DWORD currentTLS = TLS_OUT_OF_INDEXES;
extern "C" BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved)
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
{
#if !defined(ANGLE_DISABLE_TRACE)
FILE *debug = fopen(TRACE_OUTPUT_FILE, "rt");
if (debug)
{
fclose(debug);
debug = fopen(TRACE_OUTPUT_FILE, "wt"); // Erase
if (debug)
{
fclose(debug);
}
}
#endif
currentTLS = TlsAlloc();
if (currentTLS == TLS_OUT_OF_INDEXES)
{
return FALSE;
}
}
// Fall throught to initialize index
case DLL_THREAD_ATTACH:
{
egl::Current *current = (egl::Current*)LocalAlloc(LPTR, sizeof(egl::Current));
if (current)
{
TlsSetValue(currentTLS, current);
current->error = EGL_SUCCESS;
current->API = EGL_OPENGL_ES_API;
current->display = EGL_NO_DISPLAY;
current->drawSurface = EGL_NO_SURFACE;
current->readSurface = EGL_NO_SURFACE;
}
}
break;
case DLL_THREAD_DETACH:
{
void *current = TlsGetValue(currentTLS);
if (current)
{
LocalFree((HLOCAL)current);
}
}
break;
case DLL_PROCESS_DETACH:
{
void *current = TlsGetValue(currentTLS);
if (current)
{
LocalFree((HLOCAL)current);
}
TlsFree(currentTLS);
}
break;
default:
break;
}
return TRUE;
}
namespace egl
{
void setCurrentError(EGLint error)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->error = error;
}
EGLint getCurrentError()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->error;
}
void setCurrentAPI(EGLenum API)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->API = API;
}
EGLenum getCurrentAPI()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->API;
}
void setCurrentDisplay(EGLDisplay dpy)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->display = dpy;
}
EGLDisplay getCurrentDisplay()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->display;
}
void setCurrentDrawSurface(EGLSurface surface)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->drawSurface = surface;
}
EGLSurface getCurrentDrawSurface()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->drawSurface;
}
void setCurrentReadSurface(EGLSurface surface)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->readSurface = surface;
}
EGLSurface getCurrentReadSurface()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->readSurface;
}
void error(EGLint errorCode)
{
egl::setCurrentError(errorCode);
}
}
| 010smithzhang-ddd | src/libEGL/main.cpp | C++ | bsd | 3,490 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// main.h: Management of thread-local data.
#ifndef LIBEGL_MAIN_H_
#define LIBEGL_MAIN_H_
#define EGLAPI
#include <EGL/egl.h>
#include <EGL/eglext.h>
namespace egl
{
struct Current
{
EGLint error;
EGLenum API;
EGLDisplay display;
EGLSurface drawSurface;
EGLSurface readSurface;
};
void setCurrentError(EGLint error);
EGLint getCurrentError();
void setCurrentAPI(EGLenum API);
EGLenum getCurrentAPI();
void setCurrentDisplay(EGLDisplay dpy);
EGLDisplay getCurrentDisplay();
void setCurrentDrawSurface(EGLSurface surface);
EGLSurface getCurrentDrawSurface();
void setCurrentReadSurface(EGLSurface surface);
EGLSurface getCurrentReadSurface();
void error(EGLint errorCode);
template<class T>
const T &error(EGLint errorCode, const T &returnValue)
{
error(errorCode);
return returnValue;
}
template<class T>
const T &success(const T &returnValue)
{
egl::setCurrentError(EGL_SUCCESS);
return returnValue;
}
}
#endif // LIBEGL_MAIN_H_
| 010smithzhang-ddd | src/libEGL/main.h | C++ | bsd | 1,167 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Surface.cpp: Implements the egl::Surface class, representing a drawing surface
// such as the client area of a window, including any back buffers.
// Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.
#include <tchar.h>
#include "libEGL/Surface.h"
#include "common/debug.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/renderer/SwapChain.h"
#include "libGLESv2/main.h"
#include "libEGL/main.h"
#include "libEGL/Display.h"
namespace egl
{
Surface::Surface(Display *display, const Config *config, HWND window, EGLint postSubBufferSupported)
: mDisplay(display), mConfig(config), mWindow(window), mPostSubBufferSupported(postSubBufferSupported)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mShareHandle = NULL;
mTexture = NULL;
mTextureFormat = EGL_NO_TEXTURE;
mTextureTarget = EGL_NO_TEXTURE;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
mWidth = -1;
mHeight = -1;
setSwapInterval(1);
subclassWindow();
}
Surface::Surface(Display *display, const Config *config, HANDLE shareHandle, EGLint width, EGLint height, EGLenum textureFormat, EGLenum textureType)
: mDisplay(display), mWindow(NULL), mConfig(config), mShareHandle(shareHandle), mWidth(width), mHeight(height), mPostSubBufferSupported(EGL_FALSE)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mWindowSubclassed = false;
mTexture = NULL;
mTextureFormat = textureFormat;
mTextureTarget = textureType;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
setSwapInterval(1);
}
Surface::~Surface()
{
unsubclassWindow();
release();
}
bool Surface::initialize()
{
if (!resetSwapChain())
return false;
return true;
}
void Surface::release()
{
delete mSwapChain;
mSwapChain = NULL;
if (mTexture)
{
mTexture->releaseTexImage();
mTexture = NULL;
}
}
bool Surface::resetSwapChain()
{
ASSERT(!mSwapChain);
int width;
int height;
if (mWindow)
{
RECT windowRect;
if (!GetClientRect(getWindowHandle(), &windowRect))
{
ASSERT(false);
ERR("Could not retrieve the window dimensions");
return error(EGL_BAD_SURFACE, false);
}
width = windowRect.right - windowRect.left;
height = windowRect.bottom - windowRect.top;
}
else
{
// non-window surface - size is determined at creation
width = mWidth;
height = mHeight;
}
mSwapChain = mRenderer->createSwapChain(mWindow, mShareHandle,
mConfig->mRenderTargetFormat,
mConfig->mDepthStencilFormat);
if (!mSwapChain)
{
return error(EGL_BAD_ALLOC, false);
}
if (!resetSwapChain(width, height))
{
delete mSwapChain;
mSwapChain = NULL;
return false;
}
return true;
}
bool Surface::resizeSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->resize(backbufferWidth, backbufferHeight);
if (status == EGL_CONTEXT_LOST)
{
mDisplay->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
return true;
}
bool Surface::resetSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->reset(backbufferWidth, backbufferHeight, mSwapInterval);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
mSwapIntervalDirty = false;
return true;
}
bool Surface::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mSwapChain)
{
return true;
}
if (x + width > mWidth)
{
width = mWidth - x;
}
if (y + height > mHeight)
{
height = mHeight - y;
}
if (width == 0 || height == 0)
{
return true;
}
EGLint status = mSwapChain->swapRect(x, y, width, height);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
checkForOutOfDateSwapChain();
return true;
}
HWND Surface::getWindowHandle()
{
return mWindow;
}
#define kSurfaceProperty _TEXT("Egl::SurfaceOwner")
#define kParentWndProc _TEXT("Egl::SurfaceParentWndProc")
static LRESULT CALLBACK SurfaceWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
if (message == WM_SIZE)
{
Surface* surf = reinterpret_cast<Surface*>(GetProp(hwnd, kSurfaceProperty));
if(surf)
{
surf->checkForOutOfDateSwapChain();
}
}
WNDPROC prevWndFunc = reinterpret_cast<WNDPROC >(GetProp(hwnd, kParentWndProc));
return CallWindowProc(prevWndFunc, hwnd, message, wparam, lparam);
}
void Surface::subclassWindow()
{
if (!mWindow)
{
return;
}
DWORD processId;
DWORD threadId = GetWindowThreadProcessId(mWindow, &processId);
if (processId != GetCurrentProcessId() || threadId != GetCurrentThreadId())
{
return;
}
SetLastError(0);
LONG_PTR oldWndProc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
if(oldWndProc == 0 && GetLastError() != ERROR_SUCCESS)
{
mWindowSubclassed = false;
return;
}
SetProp(mWindow, kSurfaceProperty, reinterpret_cast<HANDLE>(this));
SetProp(mWindow, kParentWndProc, reinterpret_cast<HANDLE>(oldWndProc));
mWindowSubclassed = true;
}
void Surface::unsubclassWindow()
{
if(!mWindowSubclassed)
{
return;
}
// un-subclass
LONG_PTR parentWndFunc = reinterpret_cast<LONG_PTR>(GetProp(mWindow, kParentWndProc));
// Check the windowproc is still SurfaceWindowProc.
// If this assert fails, then it is likely the application has subclassed the
// hwnd as well and did not unsubclass before destroying its EGL context. The
// application should be modified to either subclass before initializing the
// EGL context, or to unsubclass before destroying the EGL context.
if(parentWndFunc)
{
LONG_PTR prevWndFunc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, parentWndFunc);
ASSERT(prevWndFunc == reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
}
RemoveProp(mWindow, kSurfaceProperty);
RemoveProp(mWindow, kParentWndProc);
mWindowSubclassed = false;
}
bool Surface::checkForOutOfDateSwapChain()
{
RECT client;
if (!GetClientRect(getWindowHandle(), &client))
{
ASSERT(false);
return false;
}
// Grow the buffer now, if the window has grown. We need to grow now to avoid losing information.
int clientWidth = client.right - client.left;
int clientHeight = client.bottom - client.top;
bool sizeDirty = clientWidth != getWidth() || clientHeight != getHeight();
if (mSwapIntervalDirty)
{
resetSwapChain(clientWidth, clientHeight);
}
else if (sizeDirty)
{
resizeSwapChain(clientWidth, clientHeight);
}
if (mSwapIntervalDirty || sizeDirty)
{
if (static_cast<egl::Surface*>(getCurrentDrawSurface()) == this)
{
glMakeCurrent(glGetCurrentContext(), static_cast<egl::Display*>(getCurrentDisplay()), this);
}
return true;
}
return false;
}
bool Surface::swap()
{
return swapRect(0, 0, mWidth, mHeight);
}
bool Surface::postSubBuffer(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mPostSubBufferSupported)
{
// Spec is not clear about how this should be handled.
return true;
}
return swapRect(x, y, width, height);
}
EGLint Surface::getWidth() const
{
return mWidth;
}
EGLint Surface::getHeight() const
{
return mHeight;
}
EGLint Surface::isPostSubBufferSupported() const
{
return mPostSubBufferSupported;
}
rx::SwapChain *Surface::getSwapChain() const
{
return mSwapChain;
}
void Surface::setSwapInterval(EGLint interval)
{
if (mSwapInterval == interval)
{
return;
}
mSwapInterval = interval;
mSwapInterval = std::max(mSwapInterval, mRenderer->getMinSwapInterval());
mSwapInterval = std::min(mSwapInterval, mRenderer->getMaxSwapInterval());
mSwapIntervalDirty = true;
}
EGLenum Surface::getTextureFormat() const
{
return mTextureFormat;
}
EGLenum Surface::getTextureTarget() const
{
return mTextureTarget;
}
void Surface::setBoundTexture(gl::Texture2D *texture)
{
mTexture = texture;
}
gl::Texture2D *Surface::getBoundTexture() const
{
return mTexture;
}
EGLenum Surface::getFormat() const
{
return mConfig->mRenderTargetFormat;
}
}
| 010smithzhang-ddd | src/libEGL/Surface.cpp | C++ | bsd | 9,680 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Surface.h: Defines the egl::Surface class, representing a drawing surface
// such as the client area of a window, including any back buffers.
// Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.
#ifndef LIBEGL_SURFACE_H_
#define LIBEGL_SURFACE_H_
#define EGLAPI
#include <EGL/egl.h>
#include "common/angleutils.h"
namespace gl
{
class Texture2D;
}
namespace rx
{
class Renderer;
class SwapChain;
}
namespace egl
{
class Display;
class Config;
class Surface
{
public:
Surface(Display *display, const egl::Config *config, HWND window, EGLint postSubBufferSupported);
Surface(Display *display, const egl::Config *config, HANDLE shareHandle, EGLint width, EGLint height, EGLenum textureFormat, EGLenum textureTarget);
~Surface();
bool initialize();
void release();
bool resetSwapChain();
HWND getWindowHandle();
bool swap();
bool postSubBuffer(EGLint x, EGLint y, EGLint width, EGLint height);
virtual EGLint getWidth() const;
virtual EGLint getHeight() const;
virtual EGLint isPostSubBufferSupported() const;
virtual rx::SwapChain *getSwapChain() const;
void setSwapInterval(EGLint interval);
bool checkForOutOfDateSwapChain(); // Returns true if swapchain changed due to resize or interval update
virtual EGLenum getTextureFormat() const;
virtual EGLenum getTextureTarget() const;
virtual EGLenum getFormat() const;
virtual void setBoundTexture(gl::Texture2D *texture);
virtual gl::Texture2D *getBoundTexture() const;
private:
DISALLOW_COPY_AND_ASSIGN(Surface);
Display *const mDisplay;
rx::Renderer *mRenderer;
HANDLE mShareHandle;
rx::SwapChain *mSwapChain;
void subclassWindow();
void unsubclassWindow();
bool resizeSwapChain(int backbufferWidth, int backbufferHeight);
bool resetSwapChain(int backbufferWidth, int backbufferHeight);
bool swapRect(EGLint x, EGLint y, EGLint width, EGLint height);
const HWND mWindow; // Window that the surface is created for.
bool mWindowSubclassed; // Indicates whether we successfully subclassed mWindow for WM_RESIZE hooking
const egl::Config *mConfig; // EGL config surface was created with
EGLint mHeight; // Height of surface
EGLint mWidth; // Width of surface
// EGLint horizontalResolution; // Horizontal dot pitch
// EGLint verticalResolution; // Vertical dot pitch
// EGLBoolean largestPBuffer; // If true, create largest pbuffer possible
// EGLBoolean mipmapTexture; // True if texture has mipmaps
// EGLint mipmapLevel; // Mipmap level to render to
// EGLenum multisampleResolve; // Multisample resolve behavior
EGLint mPixelAspectRatio; // Display aspect ratio
EGLenum mRenderBuffer; // Render buffer
EGLenum mSwapBehavior; // Buffer swap behavior
EGLenum mTextureFormat; // Format of texture: RGB, RGBA, or no texture
EGLenum mTextureTarget; // Type of texture: 2D or no texture
// EGLenum vgAlphaFormat; // Alpha format for OpenVG
// EGLenum vgColorSpace; // Color space for OpenVG
EGLint mSwapInterval;
EGLint mPostSubBufferSupported;
bool mSwapIntervalDirty;
gl::Texture2D *mTexture;
};
}
#endif // LIBEGL_SURFACE_H_
| 010smithzhang-ddd | src/libEGL/Surface.h | C++ | bsd | 3,537 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Config.cpp: Implements the egl::Config class, describing the format, type
// and size for an egl::Surface. Implements EGLConfig and related functionality.
// [EGL 1.4] section 3.4 page 15.
#include "libEGL/Config.h"
#include <algorithm>
#include <vector>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include "common/debug.h"
using namespace std;
namespace egl
{
Config::Config(rx::ConfigDesc desc, EGLint minInterval, EGLint maxInterval, EGLint texWidth, EGLint texHeight)
: mRenderTargetFormat(desc.renderTargetFormat), mDepthStencilFormat(desc.depthStencilFormat), mMultiSample(desc.multiSample)
{
mBindToTextureRGB = EGL_FALSE;
mBindToTextureRGBA = EGL_FALSE;
switch (desc.renderTargetFormat)
{
case GL_RGB5_A1:
mBufferSize = 16;
mRedSize = 5;
mGreenSize = 5;
mBlueSize = 5;
mAlphaSize = 1;
break;
case GL_RGBA8_OES:
mBufferSize = 32;
mRedSize = 8;
mGreenSize = 8;
mBlueSize = 8;
mAlphaSize = 8;
mBindToTextureRGBA = true;
break;
case GL_RGB565:
mBufferSize = 16;
mRedSize = 5;
mGreenSize = 6;
mBlueSize = 5;
mAlphaSize = 0;
break;
case GL_RGB8_OES:
mBufferSize = 32;
mRedSize = 8;
mGreenSize = 8;
mBlueSize = 8;
mAlphaSize = 0;
mBindToTextureRGB = true;
break;
case GL_BGRA8_EXT:
mBufferSize = 32;
mRedSize = 8;
mGreenSize = 8;
mBlueSize = 8;
mAlphaSize = 8;
mBindToTextureRGBA = true;
break;
default:
UNREACHABLE(); // Other formats should not be valid
}
mLuminanceSize = 0;
mAlphaMaskSize = 0;
mColorBufferType = EGL_RGB_BUFFER;
mConfigCaveat = (desc.fastConfig) ? EGL_NONE : EGL_SLOW_CONFIG;
mConfigID = 0;
mConformant = EGL_OPENGL_ES2_BIT;
switch (desc.depthStencilFormat)
{
case GL_NONE:
mDepthSize = 0;
mStencilSize = 0;
break;
case GL_DEPTH_COMPONENT32_OES:
mDepthSize = 32;
mStencilSize = 0;
break;
case GL_DEPTH24_STENCIL8_OES:
mDepthSize = 24;
mStencilSize = 8;
break;
case GL_DEPTH_COMPONENT24_OES:
mDepthSize = 24;
mStencilSize = 0;
break;
case GL_DEPTH_COMPONENT16:
mDepthSize = 16;
mStencilSize = 0;
break;
default:
UNREACHABLE();
}
mLevel = 0;
mMatchNativePixmap = EGL_NONE;
mMaxPBufferWidth = texWidth;
mMaxPBufferHeight = texHeight;
mMaxPBufferPixels = texWidth*texHeight;
mMaxSwapInterval = maxInterval;
mMinSwapInterval = minInterval;
mNativeRenderable = EGL_FALSE;
mNativeVisualID = 0;
mNativeVisualType = 0;
mRenderableType = EGL_OPENGL_ES2_BIT;
mSampleBuffers = desc.multiSample ? 1 : 0;
mSamples = desc.multiSample;
mSurfaceType = EGL_PBUFFER_BIT | EGL_WINDOW_BIT | EGL_SWAP_BEHAVIOR_PRESERVED_BIT;
mTransparentType = EGL_NONE;
mTransparentRedValue = 0;
mTransparentGreenValue = 0;
mTransparentBlueValue = 0;
}
EGLConfig Config::getHandle() const
{
return (EGLConfig)(size_t)mConfigID;
}
SortConfig::SortConfig(const EGLint *attribList)
: mWantRed(false), mWantGreen(false), mWantBlue(false), mWantAlpha(false), mWantLuminance(false)
{
scanForWantedComponents(attribList);
}
void SortConfig::scanForWantedComponents(const EGLint *attribList)
{
// [EGL] section 3.4.1 page 24
// Sorting rule #3: by larger total number of color bits, not considering
// components that are 0 or don't-care.
for (const EGLint *attr = attribList; attr[0] != EGL_NONE; attr += 2)
{
if (attr[1] != 0 && attr[1] != EGL_DONT_CARE)
{
switch (attr[0])
{
case EGL_RED_SIZE: mWantRed = true; break;
case EGL_GREEN_SIZE: mWantGreen = true; break;
case EGL_BLUE_SIZE: mWantBlue = true; break;
case EGL_ALPHA_SIZE: mWantAlpha = true; break;
case EGL_LUMINANCE_SIZE: mWantLuminance = true; break;
}
}
}
}
EGLint SortConfig::wantedComponentsSize(const Config &config) const
{
EGLint total = 0;
if (mWantRed) total += config.mRedSize;
if (mWantGreen) total += config.mGreenSize;
if (mWantBlue) total += config.mBlueSize;
if (mWantAlpha) total += config.mAlphaSize;
if (mWantLuminance) total += config.mLuminanceSize;
return total;
}
bool SortConfig::operator()(const Config *x, const Config *y) const
{
return (*this)(*x, *y);
}
bool SortConfig::operator()(const Config &x, const Config &y) const
{
#define SORT(attribute) \
if (x.attribute != y.attribute) \
{ \
return x.attribute < y.attribute; \
}
META_ASSERT(EGL_NONE < EGL_SLOW_CONFIG && EGL_SLOW_CONFIG < EGL_NON_CONFORMANT_CONFIG);
SORT(mConfigCaveat);
META_ASSERT(EGL_RGB_BUFFER < EGL_LUMINANCE_BUFFER);
SORT(mColorBufferType);
// By larger total number of color bits, only considering those that are requested to be > 0.
EGLint xComponentsSize = wantedComponentsSize(x);
EGLint yComponentsSize = wantedComponentsSize(y);
if (xComponentsSize != yComponentsSize)
{
return xComponentsSize > yComponentsSize;
}
SORT(mBufferSize);
SORT(mSampleBuffers);
SORT(mSamples);
SORT(mDepthSize);
SORT(mStencilSize);
SORT(mAlphaMaskSize);
SORT(mNativeVisualType);
SORT(mConfigID);
#undef SORT
return false;
}
// We'd like to use SortConfig to also eliminate duplicate configs.
// This works as long as we never have two configs with different per-RGB-component layouts,
// but the same total.
// 5551 and 565 are different because R+G+B is different.
// 5551 and 555 are different because bufferSize is different.
const EGLint ConfigSet::mSortAttribs[] =
{
EGL_RED_SIZE, 1,
EGL_GREEN_SIZE, 1,
EGL_BLUE_SIZE, 1,
EGL_LUMINANCE_SIZE, 1,
// BUT NOT ALPHA
EGL_NONE
};
ConfigSet::ConfigSet()
: mSet(SortConfig(mSortAttribs))
{
}
void ConfigSet::add(rx::ConfigDesc desc, EGLint minSwapInterval, EGLint maxSwapInterval, EGLint texWidth, EGLint texHeight)
{
Config config(desc, minSwapInterval, maxSwapInterval, texWidth, texHeight);
mSet.insert(config);
}
size_t ConfigSet::size() const
{
return mSet.size();
}
bool ConfigSet::getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig)
{
vector<const Config*> passed;
passed.reserve(mSet.size());
for (Iterator config = mSet.begin(); config != mSet.end(); config++)
{
bool match = true;
const EGLint *attribute = attribList;
while (attribute[0] != EGL_NONE)
{
switch (attribute[0])
{
case EGL_BUFFER_SIZE: match = config->mBufferSize >= attribute[1]; break;
case EGL_ALPHA_SIZE: match = config->mAlphaSize >= attribute[1]; break;
case EGL_BLUE_SIZE: match = config->mBlueSize >= attribute[1]; break;
case EGL_GREEN_SIZE: match = config->mGreenSize >= attribute[1]; break;
case EGL_RED_SIZE: match = config->mRedSize >= attribute[1]; break;
case EGL_DEPTH_SIZE: match = config->mDepthSize >= attribute[1]; break;
case EGL_STENCIL_SIZE: match = config->mStencilSize >= attribute[1]; break;
case EGL_CONFIG_CAVEAT: match = config->mConfigCaveat == (EGLenum) attribute[1]; break;
case EGL_CONFIG_ID: match = config->mConfigID == attribute[1]; break;
case EGL_LEVEL: match = config->mLevel >= attribute[1]; break;
case EGL_NATIVE_RENDERABLE: match = config->mNativeRenderable == (EGLBoolean) attribute[1]; break;
case EGL_NATIVE_VISUAL_TYPE: match = config->mNativeVisualType == attribute[1]; break;
case EGL_SAMPLES: match = config->mSamples >= attribute[1]; break;
case EGL_SAMPLE_BUFFERS: match = config->mSampleBuffers >= attribute[1]; break;
case EGL_SURFACE_TYPE: match = (config->mSurfaceType & attribute[1]) == attribute[1]; break;
case EGL_TRANSPARENT_TYPE: match = config->mTransparentType == (EGLenum) attribute[1]; break;
case EGL_TRANSPARENT_BLUE_VALUE: match = config->mTransparentBlueValue == attribute[1]; break;
case EGL_TRANSPARENT_GREEN_VALUE: match = config->mTransparentGreenValue == attribute[1]; break;
case EGL_TRANSPARENT_RED_VALUE: match = config->mTransparentRedValue == attribute[1]; break;
case EGL_BIND_TO_TEXTURE_RGB: match = config->mBindToTextureRGB == (EGLBoolean) attribute[1]; break;
case EGL_BIND_TO_TEXTURE_RGBA: match = config->mBindToTextureRGBA == (EGLBoolean) attribute[1]; break;
case EGL_MIN_SWAP_INTERVAL: match = config->mMinSwapInterval == attribute[1]; break;
case EGL_MAX_SWAP_INTERVAL: match = config->mMaxSwapInterval == attribute[1]; break;
case EGL_LUMINANCE_SIZE: match = config->mLuminanceSize >= attribute[1]; break;
case EGL_ALPHA_MASK_SIZE: match = config->mAlphaMaskSize >= attribute[1]; break;
case EGL_COLOR_BUFFER_TYPE: match = config->mColorBufferType == (EGLenum) attribute[1]; break;
case EGL_RENDERABLE_TYPE: match = (config->mRenderableType & attribute[1]) == attribute[1]; break;
case EGL_MATCH_NATIVE_PIXMAP: match = false; UNIMPLEMENTED(); break;
case EGL_CONFORMANT: match = (config->mConformant & attribute[1]) == attribute[1]; break;
case EGL_MAX_PBUFFER_WIDTH: match = config->mMaxPBufferWidth >= attribute[1]; break;
case EGL_MAX_PBUFFER_HEIGHT: match = config->mMaxPBufferHeight >= attribute[1]; break;
case EGL_MAX_PBUFFER_PIXELS: match = config->mMaxPBufferPixels >= attribute[1]; break;
default:
return false;
}
if (!match)
{
break;
}
attribute += 2;
}
if (match)
{
passed.push_back(&*config);
}
}
if (configs)
{
sort(passed.begin(), passed.end(), SortConfig(attribList));
EGLint index;
for (index = 0; index < configSize && index < static_cast<EGLint>(passed.size()); index++)
{
configs[index] = passed[index]->getHandle();
}
*numConfig = index;
}
else
{
*numConfig = passed.size();
}
return true;
}
const egl::Config *ConfigSet::get(EGLConfig configHandle)
{
for (Iterator config = mSet.begin(); config != mSet.end(); config++)
{
if (config->getHandle() == configHandle)
{
return &(*config);
}
}
return NULL;
}
}
| 010smithzhang-ddd | src/libEGL/Config.cpp | C++ | bsd | 12,060 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// libEGL.cpp: Implements the exported EGL functions.
#include <exception>
#include "common/debug.h"
#include "common/version.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/SwapChain.h"
#include "libEGL/main.h"
#include "libEGL/Display.h"
#include "libEGL/Surface.h"
bool validateDisplay(egl::Display *display)
{
if (display == EGL_NO_DISPLAY)
{
return egl::error(EGL_BAD_DISPLAY, false);
}
if (!display->isInitialized())
{
return egl::error(EGL_NOT_INITIALIZED, false);
}
return true;
}
bool validateConfig(egl::Display *display, EGLConfig config)
{
if (!validateDisplay(display))
{
return false;
}
if (!display->isValidConfig(config))
{
return egl::error(EGL_BAD_CONFIG, false);
}
return true;
}
bool validateContext(egl::Display *display, gl::Context *context)
{
if (!validateDisplay(display))
{
return false;
}
if (!display->isValidContext(context))
{
return egl::error(EGL_BAD_CONTEXT, false);
}
return true;
}
bool validateSurface(egl::Display *display, egl::Surface *surface)
{
if (!validateDisplay(display))
{
return false;
}
if (!display->isValidSurface(surface))
{
return egl::error(EGL_BAD_SURFACE, false);
}
return true;
}
extern "C"
{
EGLint __stdcall eglGetError(void)
{
EVENT("()");
EGLint error = egl::getCurrentError();
if (error != EGL_SUCCESS)
{
egl::setCurrentError(EGL_SUCCESS);
}
return error;
}
EGLDisplay __stdcall eglGetDisplay(EGLNativeDisplayType display_id)
{
EVENT("(EGLNativeDisplayType display_id = 0x%0.8p)", display_id);
try
{
return egl::Display::getDisplay(display_id);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_DISPLAY);
}
}
EGLBoolean __stdcall eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLint *major = 0x%0.8p, EGLint *minor = 0x%0.8p)",
dpy, major, minor);
try
{
if (dpy == EGL_NO_DISPLAY)
{
return egl::error(EGL_BAD_DISPLAY, EGL_FALSE);
}
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!display->initialize())
{
return egl::error(EGL_NOT_INITIALIZED, EGL_FALSE);
}
if (major) *major = 1;
if (minor) *minor = 4;
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglTerminate(EGLDisplay dpy)
{
EVENT("(EGLDisplay dpy = 0x%0.8p)", dpy);
try
{
if (dpy == EGL_NO_DISPLAY)
{
return egl::error(EGL_BAD_DISPLAY, EGL_FALSE);
}
egl::Display *display = static_cast<egl::Display*>(dpy);
display->terminate();
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
const char *__stdcall eglQueryString(EGLDisplay dpy, EGLint name)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLint name = %d)", dpy, name);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateDisplay(display))
{
return NULL;
}
switch (name)
{
case EGL_CLIENT_APIS:
return egl::success("OpenGL_ES");
case EGL_EXTENSIONS:
return egl::success(display->getExtensionString());
case EGL_VENDOR:
return egl::success(display->getVendorString());
case EGL_VERSION:
return egl::success("1.4 (ANGLE " VERSION_STRING ")");
}
return egl::error(EGL_BAD_PARAMETER, (const char*)NULL);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, (const char*)NULL);
}
}
EGLBoolean __stdcall eglGetConfigs(EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig *configs = 0x%0.8p, "
"EGLint config_size = %d, EGLint *num_config = 0x%0.8p)",
dpy, configs, config_size, num_config);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateDisplay(display))
{
return EGL_FALSE;
}
if (!num_config)
{
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
const EGLint attribList[] = {EGL_NONE};
if (!display->getConfigs(configs, attribList, config_size, num_config))
{
return egl::error(EGL_BAD_ATTRIBUTE, EGL_FALSE);
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, const EGLint *attrib_list = 0x%0.8p, "
"EGLConfig *configs = 0x%0.8p, EGLint config_size = %d, EGLint *num_config = 0x%0.8p)",
dpy, attrib_list, configs, config_size, num_config);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateDisplay(display))
{
return EGL_FALSE;
}
if (!num_config)
{
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
const EGLint attribList[] = {EGL_NONE};
if (!attrib_list)
{
attrib_list = attribList;
}
display->getConfigs(configs, attrib_list, config_size, num_config);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig config = 0x%0.8p, EGLint attribute = %d, EGLint *value = 0x%0.8p)",
dpy, config, attribute, value);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_FALSE;
}
if (!display->getConfigAttrib(config, attribute, value))
{
return egl::error(EGL_BAD_ATTRIBUTE, EGL_FALSE);
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLSurface __stdcall eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig config = 0x%0.8p, EGLNativeWindowType win = 0x%0.8p, "
"const EGLint *attrib_list = 0x%0.8p)", dpy, config, win, attrib_list);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_NO_SURFACE;
}
HWND window = (HWND)win;
if (!IsWindow(window))
{
return egl::error(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
}
return display->createWindowSurface(window, config, attrib_list);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
}
EGLSurface __stdcall eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig config = 0x%0.8p, const EGLint *attrib_list = 0x%0.8p)",
dpy, config, attrib_list);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_NO_SURFACE;
}
return display->createOffscreenSurface(config, NULL, attrib_list);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
}
EGLSurface __stdcall eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig config = 0x%0.8p, EGLNativePixmapType pixmap = 0x%0.8p, "
"const EGLint *attrib_list = 0x%0.8p)", dpy, config, pixmap, attrib_list);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_NO_SURFACE;
}
UNIMPLEMENTED(); // FIXME
return egl::success(EGL_NO_SURFACE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
}
EGLBoolean __stdcall eglDestroySurface(EGLDisplay dpy, EGLSurface surface)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p)", dpy, surface);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (surface == EGL_NO_SURFACE)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
display->destroySurface((egl::Surface*)surface);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglQuerySurface(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint attribute = %d, EGLint *value = 0x%0.8p)",
dpy, surface, attribute, value);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = (egl::Surface*)surface;
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (surface == EGL_NO_SURFACE)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
switch (attribute)
{
case EGL_VG_ALPHA_FORMAT:
UNIMPLEMENTED(); // FIXME
break;
case EGL_VG_COLORSPACE:
UNIMPLEMENTED(); // FIXME
break;
case EGL_CONFIG_ID:
UNIMPLEMENTED(); // FIXME
break;
case EGL_HEIGHT:
*value = eglSurface->getHeight();
break;
case EGL_HORIZONTAL_RESOLUTION:
UNIMPLEMENTED(); // FIXME
break;
case EGL_LARGEST_PBUFFER:
UNIMPLEMENTED(); // FIXME
break;
case EGL_MIPMAP_TEXTURE:
UNIMPLEMENTED(); // FIXME
break;
case EGL_MIPMAP_LEVEL:
UNIMPLEMENTED(); // FIXME
break;
case EGL_MULTISAMPLE_RESOLVE:
UNIMPLEMENTED(); // FIXME
break;
case EGL_PIXEL_ASPECT_RATIO:
UNIMPLEMENTED(); // FIXME
break;
case EGL_RENDER_BUFFER:
UNIMPLEMENTED(); // FIXME
break;
case EGL_SWAP_BEHAVIOR:
UNIMPLEMENTED(); // FIXME
break;
case EGL_TEXTURE_FORMAT:
UNIMPLEMENTED(); // FIXME
break;
case EGL_TEXTURE_TARGET:
UNIMPLEMENTED(); // FIXME
break;
case EGL_VERTICAL_RESOLUTION:
UNIMPLEMENTED(); // FIXME
break;
case EGL_WIDTH:
*value = eglSurface->getWidth();
break;
case EGL_POST_SUB_BUFFER_SUPPORTED_NV:
*value = eglSurface->isPostSubBufferSupported();
break;
default:
return egl::error(EGL_BAD_ATTRIBUTE, EGL_FALSE);
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglQuerySurfacePointerANGLE(EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value)
{
TRACE("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint attribute = %d, void **value = 0x%0.8p)",
dpy, surface, attribute, value);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = (egl::Surface*)surface;
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (surface == EGL_NO_SURFACE)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
switch (attribute)
{
case EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE:
{
rx::SwapChain *swapchain = eglSurface->getSwapChain();
*value = (void*) (swapchain ? swapchain->getShareHandle() : NULL);
}
break;
default:
return egl::error(EGL_BAD_ATTRIBUTE, EGL_FALSE);
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglBindAPI(EGLenum api)
{
EVENT("(EGLenum api = 0x%X)", api);
try
{
switch (api)
{
case EGL_OPENGL_API:
case EGL_OPENVG_API:
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE); // Not supported by this implementation
case EGL_OPENGL_ES_API:
break;
default:
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
egl::setCurrentAPI(api);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLenum __stdcall eglQueryAPI(void)
{
EVENT("()");
try
{
EGLenum API = egl::getCurrentAPI();
return egl::success(API);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglWaitClient(void)
{
EVENT("()");
try
{
UNIMPLEMENTED(); // FIXME
return egl::success(0);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglReleaseThread(void)
{
EVENT("()");
try
{
eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_CONTEXT, EGL_NO_SURFACE, EGL_NO_SURFACE);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLSurface __stdcall eglCreatePbufferFromClientBuffer(EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLenum buftype = 0x%X, EGLClientBuffer buffer = 0x%0.8p, "
"EGLConfig config = 0x%0.8p, const EGLint *attrib_list = 0x%0.8p)",
dpy, buftype, buffer, config, attrib_list);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_NO_SURFACE;
}
if (buftype != EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE || !buffer)
{
return egl::error(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
}
return display->createOffscreenSurface(config, (HANDLE)buffer, attrib_list);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
}
EGLBoolean __stdcall eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint attribute = %d, EGLint value = %d)",
dpy, surface, attribute, value);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
UNIMPLEMENTED(); // FIXME
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglBindTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint buffer = %d)", dpy, surface, buffer);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (buffer != EGL_BACK_BUFFER)
{
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
if (surface == EGL_NO_SURFACE || eglSurface->getWindowHandle())
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
if (eglSurface->getBoundTexture())
{
return egl::error(EGL_BAD_ACCESS, EGL_FALSE);
}
if (eglSurface->getTextureFormat() == EGL_NO_TEXTURE)
{
return egl::error(EGL_BAD_MATCH, EGL_FALSE);
}
if (!glBindTexImage(eglSurface))
{
return egl::error(EGL_BAD_MATCH, EGL_FALSE);
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglReleaseTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint buffer = %d)", dpy, surface, buffer);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (buffer != EGL_BACK_BUFFER)
{
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
if (surface == EGL_NO_SURFACE || eglSurface->getWindowHandle())
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
if (eglSurface->getTextureFormat() == EGL_NO_TEXTURE)
{
return egl::error(EGL_BAD_MATCH, EGL_FALSE);
}
gl::Texture2D *texture = eglSurface->getBoundTexture();
if (texture)
{
texture->releaseTexImage();
}
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglSwapInterval(EGLDisplay dpy, EGLint interval)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLint interval = %d)", dpy, interval);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateDisplay(display))
{
return EGL_FALSE;
}
egl::Surface *draw_surface = static_cast<egl::Surface*>(egl::getCurrentDrawSurface());
if (draw_surface == NULL)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
draw_surface->setSwapInterval(interval);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLContext __stdcall eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLConfig config = 0x%0.8p, EGLContext share_context = 0x%0.8p, "
"const EGLint *attrib_list = 0x%0.8p)", dpy, config, share_context, attrib_list);
try
{
// Get the requested client version (default is 1) and check it is two.
EGLint client_version = 1;
bool reset_notification = false;
bool robust_access = false;
if (attrib_list)
{
for (const EGLint* attribute = attrib_list; attribute[0] != EGL_NONE; attribute += 2)
{
switch (attribute[0])
{
case EGL_CONTEXT_CLIENT_VERSION:
client_version = attribute[1];
break;
case EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT:
if (attribute[1] == EGL_TRUE)
{
return egl::error(EGL_BAD_CONFIG, EGL_NO_CONTEXT); // Unimplemented
// robust_access = true;
}
else if (attribute[1] != EGL_FALSE)
return egl::error(EGL_BAD_ATTRIBUTE, EGL_NO_CONTEXT);
break;
case EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT:
if (attribute[1] == EGL_LOSE_CONTEXT_ON_RESET_EXT)
reset_notification = true;
else if (attribute[1] != EGL_NO_RESET_NOTIFICATION_EXT)
return egl::error(EGL_BAD_ATTRIBUTE, EGL_NO_CONTEXT);
break;
default:
return egl::error(EGL_BAD_ATTRIBUTE, EGL_NO_CONTEXT);
}
}
}
if (client_version != 2)
{
return egl::error(EGL_BAD_CONFIG, EGL_NO_CONTEXT);
}
if (share_context && static_cast<gl::Context*>(share_context)->isResetNotificationEnabled() != reset_notification)
{
return egl::error(EGL_BAD_MATCH, EGL_NO_CONTEXT);
}
egl::Display *display = static_cast<egl::Display*>(dpy);
if (!validateConfig(display, config))
{
return EGL_NO_CONTEXT;
}
EGLContext context = display->createContext(config, static_cast<gl::Context*>(share_context), reset_notification, robust_access);
if (context)
return egl::success(context);
else
return egl::error(EGL_CONTEXT_LOST, EGL_NO_CONTEXT);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
}
}
EGLBoolean __stdcall eglDestroyContext(EGLDisplay dpy, EGLContext ctx)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLContext ctx = 0x%0.8p)", dpy, ctx);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
gl::Context *context = static_cast<gl::Context*>(ctx);
if (!validateContext(display, context))
{
return EGL_FALSE;
}
if (ctx == EGL_NO_CONTEXT)
{
return egl::error(EGL_BAD_CONTEXT, EGL_FALSE);
}
display->destroyContext(context);
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface draw = 0x%0.8p, EGLSurface read = 0x%0.8p, EGLContext ctx = 0x%0.8p)",
dpy, draw, read, ctx);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
gl::Context *context = static_cast<gl::Context*>(ctx);
if (ctx != EGL_NO_CONTEXT && !validateContext(display, context))
{
return EGL_FALSE;
}
rx::Renderer *renderer = display->getRenderer();
if (renderer->testDeviceLost(true))
{
return EGL_FALSE;
}
if (renderer->isDeviceLost())
{
return egl::error(EGL_CONTEXT_LOST, EGL_FALSE);
}
if ((draw != EGL_NO_SURFACE && !validateSurface(display, static_cast<egl::Surface*>(draw))) ||
(read != EGL_NO_SURFACE && !validateSurface(display, static_cast<egl::Surface*>(read))))
{
return EGL_FALSE;
}
if (draw != read)
{
UNIMPLEMENTED(); // FIXME
}
egl::setCurrentDisplay(dpy);
egl::setCurrentDrawSurface(draw);
egl::setCurrentReadSurface(read);
glMakeCurrent(context, display, static_cast<egl::Surface*>(draw));
return egl::success(EGL_TRUE);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLContext __stdcall eglGetCurrentContext(void)
{
EVENT("()");
try
{
EGLContext context = glGetCurrentContext();
return egl::success(context);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
}
}
EGLSurface __stdcall eglGetCurrentSurface(EGLint readdraw)
{
EVENT("(EGLint readdraw = %d)", readdraw);
try
{
if (readdraw == EGL_READ)
{
EGLSurface read = egl::getCurrentReadSurface();
return egl::success(read);
}
else if (readdraw == EGL_DRAW)
{
EGLSurface draw = egl::getCurrentDrawSurface();
return egl::success(draw);
}
else
{
return egl::error(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
}
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_SURFACE);
}
}
EGLDisplay __stdcall eglGetCurrentDisplay(void)
{
EVENT("()");
try
{
EGLDisplay dpy = egl::getCurrentDisplay();
return egl::success(dpy);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_NO_DISPLAY);
}
}
EGLBoolean __stdcall eglQueryContext(EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint *value)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLContext ctx = 0x%0.8p, EGLint attribute = %d, EGLint *value = 0x%0.8p)",
dpy, ctx, attribute, value);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
gl::Context *context = static_cast<gl::Context*>(ctx);
if (!validateContext(display, context))
{
return EGL_FALSE;
}
UNIMPLEMENTED(); // FIXME
return egl::success(0);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglWaitGL(void)
{
EVENT("()");
try
{
UNIMPLEMENTED(); // FIXME
return egl::success(0);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglWaitNative(EGLint engine)
{
EVENT("(EGLint engine = %d)", engine);
try
{
UNIMPLEMENTED(); // FIXME
return egl::success(0);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglSwapBuffers(EGLDisplay dpy, EGLSurface surface)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p)", dpy, surface);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = (egl::Surface*)surface;
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (display->getRenderer()->isDeviceLost())
{
return egl::error(EGL_CONTEXT_LOST, EGL_FALSE);
}
if (surface == EGL_NO_SURFACE)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
if (eglSurface->swap())
{
return egl::success(EGL_TRUE);
}
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
return EGL_FALSE;
}
EGLBoolean __stdcall eglCopyBuffers(EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLNativePixmapType target = 0x%0.8p)", dpy, surface, target);
try
{
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (display->getRenderer()->isDeviceLost())
{
return egl::error(EGL_CONTEXT_LOST, EGL_FALSE);
}
UNIMPLEMENTED(); // FIXME
return egl::success(0);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
}
EGLBoolean __stdcall eglPostSubBufferNV(EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height)
{
EVENT("(EGLDisplay dpy = 0x%0.8p, EGLSurface surface = 0x%0.8p, EGLint x = %d, EGLint y = %d, EGLint width = %d, EGLint height = %d)", dpy, surface, x, y, width, height);
try
{
if (x < 0 || y < 0 || width < 0 || height < 0)
{
return egl::error(EGL_BAD_PARAMETER, EGL_FALSE);
}
egl::Display *display = static_cast<egl::Display*>(dpy);
egl::Surface *eglSurface = static_cast<egl::Surface*>(surface);
if (!validateSurface(display, eglSurface))
{
return EGL_FALSE;
}
if (display->getRenderer()->isDeviceLost())
{
return egl::error(EGL_CONTEXT_LOST, EGL_FALSE);
}
if (surface == EGL_NO_SURFACE)
{
return egl::error(EGL_BAD_SURFACE, EGL_FALSE);
}
if (eglSurface->postSubBuffer(x, y, width, height))
{
return egl::success(EGL_TRUE);
}
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, EGL_FALSE);
}
return EGL_FALSE;
}
__eglMustCastToProperFunctionPointerType __stdcall eglGetProcAddress(const char *procname)
{
EVENT("(const char *procname = \"%s\")", procname);
try
{
struct Extension
{
const char *name;
__eglMustCastToProperFunctionPointerType address;
};
static const Extension eglExtensions[] =
{
{"eglQuerySurfacePointerANGLE", (__eglMustCastToProperFunctionPointerType)eglQuerySurfacePointerANGLE},
{"eglPostSubBufferNV", (__eglMustCastToProperFunctionPointerType)eglPostSubBufferNV},
{"", NULL},
};
for (unsigned int ext = 0; ext < ArraySize(eglExtensions); ext++)
{
if (strcmp(procname, eglExtensions[ext].name) == 0)
{
return (__eglMustCastToProperFunctionPointerType)eglExtensions[ext].address;
}
}
return glGetProcAddress(procname);
}
catch(std::bad_alloc&)
{
return egl::error(EGL_BAD_ALLOC, (__eglMustCastToProperFunctionPointerType)NULL);
}
}
}
| 010smithzhang-ddd | src/libEGL/libEGL.cpp | C++ | bsd | 30,822 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// RefCountObject.h: Defines the gl::RefCountObject base class that provides
// lifecycle support for GL objects using the traditional BindObject scheme, but
// that need to be reference counted for correct cross-context deletion.
// (Concretely, textures, buffers and renderbuffers.)
#ifndef COMMON_REFCOUNTOBJECT_H_
#define COMMON_REFCOUNTOBJECT_H_
#include <cstddef>
#define GL_APICALL
#include <GLES2/gl2.h>
#include "common/debug.h"
class RefCountObject
{
public:
explicit RefCountObject(GLuint id);
virtual ~RefCountObject();
virtual void addRef() const;
virtual void release() const;
GLuint id() const { return mId; }
private:
GLuint mId;
mutable std::size_t mRefCount;
};
class RefCountObjectBindingPointer
{
protected:
RefCountObjectBindingPointer() : mObject(NULL) { }
~RefCountObjectBindingPointer() { ASSERT(mObject == NULL); } // Objects have to be released before the resource manager is destroyed, so they must be explicitly cleaned up.
void set(RefCountObject *newObject);
RefCountObject *get() const { return mObject; }
public:
GLuint id() const { return (mObject != NULL) ? mObject->id() : 0; }
bool operator ! () const { return (get() == NULL); }
private:
RefCountObject *mObject;
};
template <class ObjectType>
class BindingPointer : public RefCountObjectBindingPointer
{
public:
void set(ObjectType *newObject) { RefCountObjectBindingPointer::set(newObject); }
ObjectType *get() const { return static_cast<ObjectType*>(RefCountObjectBindingPointer::get()); }
ObjectType *operator -> () const { return get(); }
};
#endif // COMMON_REFCOUNTOBJECT_H_
| 010smithzhang-ddd | src/common/RefCountObject.h | C++ | bsd | 1,856 |
#define MAJOR_VERSION 1
#define MINOR_VERSION 2
#define BUILD_VERSION 0
#define BUILD_REVISION 2423
#define STRINGIFY(x) #x
#define MACRO_STRINGIFY(x) STRINGIFY(x)
#define REVISION_STRING MACRO_STRINGIFY(BUILD_REVISION)
#define VERSION_STRING MACRO_STRINGIFY(MAJOR_VERSION) "." MACRO_STRINGIFY(MINOR_VERSION) "." MACRO_STRINGIFY(BUILD_VERSION) "." MACRO_STRINGIFY(BUILD_REVISION)
#define VERSION_DWORD ((MAJOR_VERSION << 24) | (MINOR_VERSION << 16) | BUILD_REVISION)
| 010smithzhang-ddd | src/common/version.h | C | bsd | 470 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// system.h: Includes Windows system headers and undefines macros that conflict.
#ifndef COMMON_SYSTEM_H
#define COMMON_SYSTEM_H
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#if defined(min)
#undef min
#endif
#if defined(max)
#undef max
#endif
#endif // COMMON_SYSTEM_H
| 010smithzhang-ddd | src/common/system.h | C | bsd | 509 |
#include "precompiled.h"
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// RefCountObject.cpp: Defines the gl::RefCountObject base class that provides
// lifecycle support for GL objects using the traditional BindObject scheme, but
// that need to be reference counted for correct cross-context deletion.
// (Concretely, textures, buffers and renderbuffers.)
#include "RefCountObject.h"
RefCountObject::RefCountObject(GLuint id)
{
mId = id;
mRefCount = 0;
}
RefCountObject::~RefCountObject()
{
ASSERT(mRefCount == 0);
}
void RefCountObject::addRef() const
{
mRefCount++;
}
void RefCountObject::release() const
{
ASSERT(mRefCount > 0);
if (--mRefCount == 0)
{
delete this;
}
}
void RefCountObjectBindingPointer::set(RefCountObject *newObject)
{
// addRef first in case newObject == mObject and this is the last reference to it.
if (newObject != NULL) newObject->addRef();
if (mObject != NULL) mObject->release();
mObject = newObject;
}
| 010smithzhang-ddd | src/common/RefCountObject.cpp | C++ | bsd | 1,138 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// debug.cpp: Debugging utilities.
#include "common/debug.h"
#include "common/system.h"
#include <d3d9.h>
namespace gl
{
typedef void (WINAPI *PerfOutputFunction)(D3DCOLOR, LPCWSTR);
static void output(bool traceFileDebugOnly, PerfOutputFunction perfFunc, const char *format, va_list vararg)
{
#if !defined(ANGLE_DISABLE_PERF)
if (perfActive())
{
char message[32768];
int len = vsprintf_s(message, format, vararg);
if (len < 0)
{
return;
}
// There are no ASCII variants of these D3DPERF functions.
wchar_t wideMessage[32768];
for (int i = 0; i < len; ++i)
{
wideMessage[i] = message[i];
}
wideMessage[len] = 0;
perfFunc(0, wideMessage);
}
#endif
#if !defined(ANGLE_DISABLE_TRACE)
#if defined(NDEBUG)
if (traceFileDebugOnly)
{
return;
}
#endif
FILE* file = fopen(TRACE_OUTPUT_FILE, "a");
if (file)
{
vfprintf(file, format, vararg);
fclose(file);
}
#endif
}
void trace(bool traceFileDebugOnly, const char *format, ...)
{
va_list vararg;
va_start(vararg, format);
#if defined(ANGLE_DISABLE_PERF)
output(traceFileDebugOnly, NULL, format, vararg);
#else
output(traceFileDebugOnly, D3DPERF_SetMarker, format, vararg);
#endif
va_end(vararg);
}
bool perfActive()
{
#if defined(ANGLE_DISABLE_PERF)
return false;
#else
static bool active = D3DPERF_GetStatus() != 0;
return active;
#endif
}
ScopedPerfEventHelper::ScopedPerfEventHelper(const char* format, ...)
{
#if !defined(ANGLE_DISABLE_PERF)
#if defined(ANGLE_DISABLE_TRACE)
if (!perfActive())
{
return;
}
#endif
va_list vararg;
va_start(vararg, format);
output(true, reinterpret_cast<PerfOutputFunction>(D3DPERF_BeginEvent), format, vararg);
va_end(vararg);
#endif
}
ScopedPerfEventHelper::~ScopedPerfEventHelper()
{
#if !defined(ANGLE_DISABLE_PERF)
if (perfActive())
{
D3DPERF_EndEvent();
}
#endif
}
}
| 010smithzhang-ddd | src/common/debug.cpp | C++ | bsd | 2,218 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// angleutils.h: Common ANGLE utilities.
#ifndef COMMON_ANGLEUTILS_H_
#define COMMON_ANGLEUTILS_H_
#include <stddef.h>
// A macro to disallow the copy constructor and operator= functions
// This must be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
template <typename T, unsigned int N>
inline unsigned int ArraySize(T(&)[N])
{
return N;
}
template <typename T, unsigned int N>
void SafeRelease(T (&resourceBlock)[N])
{
for (unsigned int i = 0; i < N; i++)
{
SafeRelease(resourceBlock[i]);
}
}
template <typename T>
void SafeRelease(T& resource)
{
if (resource)
{
resource->Release();
resource = NULL;
}
}
#if defined(_MSC_VER)
#define snprintf _snprintf
#endif
#define VENDOR_ID_AMD 0x1002
#define VENDOR_ID_INTEL 0x8086
#define VENDOR_ID_NVIDIA 0x10DE
#define GL_BGRA4_ANGLEX 0x6ABC
#define GL_BGR5_A1_ANGLEX 0x6ABD
#endif // COMMON_ANGLEUTILS_H_
| 010smithzhang-ddd | src/common/angleutils.h | C++ | bsd | 1,221 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// debug.h: Debugging utilities.
#ifndef COMMON_DEBUG_H_
#define COMMON_DEBUG_H_
#include <stdio.h>
#include <assert.h>
#include "common/angleutils.h"
#if !defined(TRACE_OUTPUT_FILE)
#define TRACE_OUTPUT_FILE "debug.txt"
#endif
namespace gl
{
// Outputs text to the debugging log
void trace(bool traceFileDebugOnly, const char *format, ...);
// Returns whether D3DPERF is active.
bool perfActive();
// Pairs a D3D begin event with an end event.
class ScopedPerfEventHelper
{
public:
ScopedPerfEventHelper(const char* format, ...);
~ScopedPerfEventHelper();
private:
DISALLOW_COPY_AND_ASSIGN(ScopedPerfEventHelper);
};
}
// A macro to output a trace of a function call and its arguments to the debugging log
#if defined(ANGLE_DISABLE_TRACE) && defined(ANGLE_DISABLE_PERF)
#define TRACE(message, ...) (void(0))
#else
#define TRACE(message, ...) gl::trace(true, "trace: %s(%d): " message "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#endif
// A macro to output a function call and its arguments to the debugging log, to denote an item in need of fixing.
#if defined(ANGLE_DISABLE_TRACE) && defined(ANGLE_DISABLE_PERF)
#define FIXME(message, ...) (void(0))
#else
#define FIXME(message, ...) gl::trace(false, "fixme: %s(%d): " message "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#endif
// A macro to output a function call and its arguments to the debugging log, in case of error.
#if defined(ANGLE_DISABLE_TRACE) && defined(ANGLE_DISABLE_PERF)
#define ERR(message, ...) (void(0))
#else
#define ERR(message, ...) gl::trace(false, "err: %s(%d): " message "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#endif
// A macro to log a performance event around a scope.
#if defined(ANGLE_DISABLE_TRACE) && defined(ANGLE_DISABLE_PERF)
#define EVENT(message, ...) (void(0))
#elif defined(_MSC_VER)
#define EVENT(message, ...) gl::ScopedPerfEventHelper scopedPerfEventHelper ## __LINE__(__FUNCTION__ message "\n", __VA_ARGS__);
#else
#define EVENT(message, ...) gl::ScopedPerfEventHelper scopedPerfEventHelper(message "\n", ##__VA_ARGS__);
#endif
// A macro asserting a condition and outputting failures to the debug log
#if !defined(NDEBUG)
#define ASSERT(expression) do { \
if(!(expression)) \
ERR("\t! Assert failed in %s(%d): "#expression"\n", __FUNCTION__, __LINE__); \
assert(expression); \
} while(0)
#else
#define ASSERT(expression) (void(0))
#endif
// A macro to indicate unimplemented functionality
#if !defined(NDEBUG)
#define UNIMPLEMENTED() do { \
FIXME("\t! Unimplemented: %s(%d)\n", __FUNCTION__, __LINE__); \
assert(false); \
} while(0)
#else
#define UNIMPLEMENTED() FIXME("\t! Unimplemented: %s(%d)\n", __FUNCTION__, __LINE__)
#endif
// A macro for code which is not expected to be reached under valid assumptions
#if !defined(NDEBUG)
#define UNREACHABLE() do { \
ERR("\t! Unreachable reached: %s(%d)\n", __FUNCTION__, __LINE__); \
assert(false); \
} while(0)
#else
#define UNREACHABLE() ERR("\t! Unreachable reached: %s(%d)\n", __FUNCTION__, __LINE__)
#endif
// A macro that determines whether an object has a given runtime type.
#if !defined(NDEBUG) && (!defined(_MSC_VER) || defined(_CPPRTTI))
#define HAS_DYNAMIC_TYPE(type, obj) (dynamic_cast<type >(obj) != NULL)
#else
#define HAS_DYNAMIC_TYPE(type, obj) true
#endif
// A macro functioning as a compile-time assert to validate constant conditions
#define META_ASSERT(condition) typedef int COMPILE_TIME_ASSERT_##__LINE__[static_cast<bool>(condition)?1:-1]
#endif // COMMON_DEBUG_H_
| 010smithzhang-ddd | src/common/debug.h | C++ | bsd | 3,767 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// BinaryStream.h: Provides binary serialization of simple types.
#ifndef LIBGLESV2_BINARYSTREAM_H_
#define LIBGLESV2_BINARYSTREAM_H_
#include "common/angleutils.h"
namespace gl
{
class BinaryInputStream
{
public:
BinaryInputStream(const void *data, size_t length)
{
mError = false;
mOffset = 0;
mData = static_cast<const char*>(data);
mLength = length;
}
template <typename T>
void read(T *v, size_t num)
{
union
{
T dummy; // Compilation error for non-trivial types
} dummy;
(void) dummy;
if (mError)
{
return;
}
size_t length = num * sizeof(T);
if (mOffset + length > mLength)
{
mError = true;
return;
}
memcpy(v, mData + mOffset, length);
mOffset += length;
}
template <typename T>
void read(T * v)
{
read(v, 1);
}
void read(std::string *v)
{
size_t length;
read(&length);
if (mError)
{
return;
}
if (mOffset + length > mLength)
{
mError = true;
return;
}
v->assign(mData + mOffset, length);
mOffset += length;
}
void skip(size_t length)
{
if (mOffset + length > mLength)
{
mError = true;
return;
}
mOffset += length;
}
size_t offset() const
{
return mOffset;
}
bool error() const
{
return mError;
}
bool endOfStream() const
{
return mOffset == mLength;
}
private:
DISALLOW_COPY_AND_ASSIGN(BinaryInputStream);
bool mError;
size_t mOffset;
const char *mData;
size_t mLength;
};
class BinaryOutputStream
{
public:
BinaryOutputStream()
{
}
template <typename T>
void write(const T *v, size_t num)
{
union
{
T dummy; // Compilation error for non-trivial types
} dummy;
(void) dummy;
const char *asBytes = reinterpret_cast<const char*>(v);
mData.insert(mData.end(), asBytes, asBytes + num * sizeof(T));
}
template <typename T>
void write(const T &v)
{
write(&v, 1);
}
void write(const std::string &v)
{
size_t length = v.length();
write(length);
write(v.c_str(), length);
}
size_t length() const
{
return mData.size();
}
const void* data() const
{
return mData.size() ? &mData[0] : NULL;
}
private:
DISALLOW_COPY_AND_ASSIGN(BinaryOutputStream);
std::vector<char> mData;
};
}
#endif // LIBGLESV2_BINARYSTREAM_H_
| 010smithzhang-ddd | src/libGLESv2/BinaryStream.h | C++ | bsd | 2,940 |
# Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# This script generates a function that converts 16-bit precision floating
# point numbers to 32-bit.
# It is based on ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf.
def convertMantissa(i):
if i == 0:
return 0
elif i < 1024:
m = i << 13
e = 0
while not (m & 0x00800000):
e -= 0x00800000
m = m << 1
m &= ~0x00800000
e += 0x38800000
return m | e
else:
return 0x38000000 + ((i - 1024) << 13)
def convertExponent(i):
if i == 0:
return 0
elif i in range(1, 31):
return i << 23
elif i == 31:
return 0x47800000
elif i == 32:
return 0x80000000
elif i in range(33, 63):
return 0x80000000 + ((i - 32) << 23)
else:
return 0xC7800000
def convertOffset(i):
if i == 0 or i == 32:
return 0
else:
return 1024
print """//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file is automatically generated.
namespace gl
{
"""
print "const static unsigned g_mantissa[2048] = {"
for i in range(0, 2048):
print " %#010x," % convertMantissa(i)
print "};\n"
print "const static unsigned g_exponent[64] = {"
for i in range(0, 64):
print " %#010x," % convertExponent(i)
print "};\n"
print "const static unsigned g_offset[64] = {"
for i in range(0, 64):
print " %#010x," % convertOffset(i)
print "};\n"
print """float float16ToFloat32(unsigned short h)
{
unsigned i32 = g_mantissa[g_offset[h >> 10] + (h & 0x3ff)] + g_exponent[h >> 10];
return *(float*) &i32;
}
}
"""
| 010smithzhang-ddd | src/libGLESv2/Float16ToFloat32.py | Python | bsd | 1,897 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// precompiled.cpp: Precompiled header source file for libGLESv2.
#include "precompiled.h"
| 010smithzhang-ddd | src/libGLESv2/precompiled.cpp | C++ | bsd | 273 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Renderbuffer.cpp: the gl::Renderbuffer class and its derived classes
// Colorbuffer, Depthbuffer and Stencilbuffer. Implements GL renderbuffer
// objects and related functionality. [OpenGL ES 2.0.24] section 4.4.3 page 108.
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/renderer/RenderTarget.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/utilities.h"
namespace gl
{
unsigned int RenderbufferStorage::mCurrentSerial = 1;
RenderbufferInterface::RenderbufferInterface()
{
}
// The default case for classes inherited from RenderbufferInterface is not to
// need to do anything upon the reference count to the parent Renderbuffer incrementing
// or decrementing.
void RenderbufferInterface::addProxyRef(const Renderbuffer *proxy)
{
}
void RenderbufferInterface::releaseProxy(const Renderbuffer *proxy)
{
}
GLuint RenderbufferInterface::getRedSize() const
{
return gl::GetRedSize(getActualFormat());
}
GLuint RenderbufferInterface::getGreenSize() const
{
return gl::GetGreenSize(getActualFormat());
}
GLuint RenderbufferInterface::getBlueSize() const
{
return gl::GetBlueSize(getActualFormat());
}
GLuint RenderbufferInterface::getAlphaSize() const
{
return gl::GetAlphaSize(getActualFormat());
}
GLuint RenderbufferInterface::getDepthSize() const
{
return gl::GetDepthSize(getActualFormat());
}
GLuint RenderbufferInterface::getStencilSize() const
{
return gl::GetStencilSize(getActualFormat());
}
///// RenderbufferTexture2D Implementation ////////
RenderbufferTexture2D::RenderbufferTexture2D(Texture2D *texture, GLenum target) : mTarget(target)
{
mTexture2D.set(texture);
}
RenderbufferTexture2D::~RenderbufferTexture2D()
{
mTexture2D.set(NULL);
}
// Textures need to maintain their own reference count for references via
// Renderbuffers acting as proxies. Here, we notify the texture of a reference.
void RenderbufferTexture2D::addProxyRef(const Renderbuffer *proxy)
{
mTexture2D->addProxyRef(proxy);
}
void RenderbufferTexture2D::releaseProxy(const Renderbuffer *proxy)
{
mTexture2D->releaseProxy(proxy);
}
rx::RenderTarget *RenderbufferTexture2D::getRenderTarget()
{
return mTexture2D->getRenderTarget(mTarget);
}
rx::RenderTarget *RenderbufferTexture2D::getDepthStencil()
{
return mTexture2D->getDepthStencil(mTarget);
}
GLsizei RenderbufferTexture2D::getWidth() const
{
return mTexture2D->getWidth(0);
}
GLsizei RenderbufferTexture2D::getHeight() const
{
return mTexture2D->getHeight(0);
}
GLenum RenderbufferTexture2D::getInternalFormat() const
{
return mTexture2D->getInternalFormat(0);
}
GLenum RenderbufferTexture2D::getActualFormat() const
{
return mTexture2D->getActualFormat(0);
}
GLsizei RenderbufferTexture2D::getSamples() const
{
return 0;
}
unsigned int RenderbufferTexture2D::getSerial() const
{
return mTexture2D->getRenderTargetSerial(mTarget);
}
///// RenderbufferTextureCubeMap Implementation ////////
RenderbufferTextureCubeMap::RenderbufferTextureCubeMap(TextureCubeMap *texture, GLenum target) : mTarget(target)
{
mTextureCubeMap.set(texture);
}
RenderbufferTextureCubeMap::~RenderbufferTextureCubeMap()
{
mTextureCubeMap.set(NULL);
}
// Textures need to maintain their own reference count for references via
// Renderbuffers acting as proxies. Here, we notify the texture of a reference.
void RenderbufferTextureCubeMap::addProxyRef(const Renderbuffer *proxy)
{
mTextureCubeMap->addProxyRef(proxy);
}
void RenderbufferTextureCubeMap::releaseProxy(const Renderbuffer *proxy)
{
mTextureCubeMap->releaseProxy(proxy);
}
rx::RenderTarget *RenderbufferTextureCubeMap::getRenderTarget()
{
return mTextureCubeMap->getRenderTarget(mTarget);
}
rx::RenderTarget *RenderbufferTextureCubeMap::getDepthStencil()
{
return NULL;
}
GLsizei RenderbufferTextureCubeMap::getWidth() const
{
return mTextureCubeMap->getWidth(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0);
}
GLsizei RenderbufferTextureCubeMap::getHeight() const
{
return mTextureCubeMap->getHeight(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0);
}
GLenum RenderbufferTextureCubeMap::getInternalFormat() const
{
return mTextureCubeMap->getInternalFormat(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0);
}
GLenum RenderbufferTextureCubeMap::getActualFormat() const
{
return mTextureCubeMap->getActualFormat(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0);
}
GLsizei RenderbufferTextureCubeMap::getSamples() const
{
return 0;
}
unsigned int RenderbufferTextureCubeMap::getSerial() const
{
return mTextureCubeMap->getRenderTargetSerial(mTarget);
}
////// Renderbuffer Implementation //////
Renderbuffer::Renderbuffer(rx::Renderer *renderer, GLuint id, RenderbufferInterface *instance) : RefCountObject(id)
{
ASSERT(instance != NULL);
mInstance = instance;
}
Renderbuffer::~Renderbuffer()
{
delete mInstance;
}
// The RenderbufferInterface contained in this Renderbuffer may need to maintain
// its own reference count, so we pass it on here.
void Renderbuffer::addRef() const
{
mInstance->addProxyRef(this);
RefCountObject::addRef();
}
void Renderbuffer::release() const
{
mInstance->releaseProxy(this);
RefCountObject::release();
}
rx::RenderTarget *Renderbuffer::getRenderTarget()
{
return mInstance->getRenderTarget();
}
rx::RenderTarget *Renderbuffer::getDepthStencil()
{
return mInstance->getDepthStencil();
}
GLsizei Renderbuffer::getWidth() const
{
return mInstance->getWidth();
}
GLsizei Renderbuffer::getHeight() const
{
return mInstance->getHeight();
}
GLenum Renderbuffer::getInternalFormat() const
{
return mInstance->getInternalFormat();
}
GLenum Renderbuffer::getActualFormat() const
{
return mInstance->getActualFormat();
}
GLuint Renderbuffer::getRedSize() const
{
return mInstance->getRedSize();
}
GLuint Renderbuffer::getGreenSize() const
{
return mInstance->getGreenSize();
}
GLuint Renderbuffer::getBlueSize() const
{
return mInstance->getBlueSize();
}
GLuint Renderbuffer::getAlphaSize() const
{
return mInstance->getAlphaSize();
}
GLuint Renderbuffer::getDepthSize() const
{
return mInstance->getDepthSize();
}
GLuint Renderbuffer::getStencilSize() const
{
return mInstance->getStencilSize();
}
GLsizei Renderbuffer::getSamples() const
{
return mInstance->getSamples();
}
unsigned int Renderbuffer::getSerial() const
{
return mInstance->getSerial();
}
void Renderbuffer::setStorage(RenderbufferStorage *newStorage)
{
ASSERT(newStorage != NULL);
delete mInstance;
mInstance = newStorage;
}
RenderbufferStorage::RenderbufferStorage() : mSerial(issueSerial())
{
mWidth = 0;
mHeight = 0;
mInternalFormat = GL_RGBA4;
mActualFormat = GL_RGBA8_OES;
mSamples = 0;
}
RenderbufferStorage::~RenderbufferStorage()
{
}
rx::RenderTarget *RenderbufferStorage::getRenderTarget()
{
return NULL;
}
rx::RenderTarget *RenderbufferStorage::getDepthStencil()
{
return NULL;
}
GLsizei RenderbufferStorage::getWidth() const
{
return mWidth;
}
GLsizei RenderbufferStorage::getHeight() const
{
return mHeight;
}
GLenum RenderbufferStorage::getInternalFormat() const
{
return mInternalFormat;
}
GLenum RenderbufferStorage::getActualFormat() const
{
return mActualFormat;
}
GLsizei RenderbufferStorage::getSamples() const
{
return mSamples;
}
unsigned int RenderbufferStorage::getSerial() const
{
return mSerial;
}
unsigned int RenderbufferStorage::issueSerial()
{
return mCurrentSerial++;
}
unsigned int RenderbufferStorage::issueCubeSerials()
{
unsigned int firstSerial = mCurrentSerial;
mCurrentSerial += 6;
return firstSerial;
}
Colorbuffer::Colorbuffer(rx::Renderer *renderer, rx::SwapChain *swapChain)
{
mRenderTarget = renderer->createRenderTarget(swapChain, false);
if (mRenderTarget)
{
mWidth = mRenderTarget->getWidth();
mHeight = mRenderTarget->getHeight();
mInternalFormat = mRenderTarget->getInternalFormat();
mActualFormat = mRenderTarget->getActualFormat();
mSamples = mRenderTarget->getSamples();
}
}
Colorbuffer::Colorbuffer(rx::Renderer *renderer, int width, int height, GLenum format, GLsizei samples) : mRenderTarget(NULL)
{
mRenderTarget = renderer->createRenderTarget(width, height, format, samples, false);
if (mRenderTarget)
{
mWidth = width;
mHeight = height;
mInternalFormat = format;
mActualFormat = mRenderTarget->getActualFormat();
mSamples = mRenderTarget->getSamples();
}
}
Colorbuffer::~Colorbuffer()
{
if (mRenderTarget)
{
delete mRenderTarget;
}
}
rx::RenderTarget *Colorbuffer::getRenderTarget()
{
if (mRenderTarget)
{
return mRenderTarget;
}
return NULL;
}
DepthStencilbuffer::DepthStencilbuffer(rx::Renderer *renderer, rx::SwapChain *swapChain)
{
mDepthStencil = renderer->createRenderTarget(swapChain, true);
if (mDepthStencil)
{
mWidth = mDepthStencil->getWidth();
mHeight = mDepthStencil->getHeight();
mInternalFormat = mDepthStencil->getInternalFormat();
mSamples = mDepthStencil->getSamples();
mActualFormat = mDepthStencil->getActualFormat();
}
}
DepthStencilbuffer::DepthStencilbuffer(rx::Renderer *renderer, int width, int height, GLsizei samples)
{
mDepthStencil = renderer->createRenderTarget(width, height, GL_DEPTH24_STENCIL8_OES, samples, true);
mWidth = mDepthStencil->getWidth();
mHeight = mDepthStencil->getHeight();
mInternalFormat = GL_DEPTH24_STENCIL8_OES;
mActualFormat = mDepthStencil->getActualFormat();
mSamples = mDepthStencil->getSamples();
}
DepthStencilbuffer::~DepthStencilbuffer()
{
if (mDepthStencil)
{
delete mDepthStencil;
}
}
rx::RenderTarget *DepthStencilbuffer::getDepthStencil()
{
if (mDepthStencil)
{
return mDepthStencil;
}
return NULL;
}
Depthbuffer::Depthbuffer(rx::Renderer *renderer, int width, int height, GLsizei samples) : DepthStencilbuffer(renderer, width, height, samples)
{
if (mDepthStencil)
{
mInternalFormat = GL_DEPTH_COMPONENT16; // If the renderbuffer parameters are queried, the calling function
// will expect one of the valid renderbuffer formats for use in
// glRenderbufferStorage
}
}
Depthbuffer::~Depthbuffer()
{
}
Stencilbuffer::Stencilbuffer(rx::Renderer *renderer, int width, int height, GLsizei samples) : DepthStencilbuffer(renderer, width, height, samples)
{
if (mDepthStencil)
{
mInternalFormat = GL_STENCIL_INDEX8; // If the renderbuffer parameters are queried, the calling function
// will expect one of the valid renderbuffer formats for use in
// glRenderbufferStorage
}
}
Stencilbuffer::~Stencilbuffer()
{
}
}
| 010smithzhang-ddd | src/libGLESv2/Renderbuffer.cpp | C++ | bsd | 11,201 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Query.cpp: Implements the gl::Query class
#include "libGLESv2/Query.h"
#include "libGLESv2/renderer/QueryImpl.h"
#include "libGLESv2/renderer/Renderer.h"
namespace gl
{
Query::Query(rx::Renderer *renderer, GLenum type, GLuint id) : RefCountObject(id)
{
mQuery = renderer->createQuery(type);
}
Query::~Query()
{
delete mQuery;
}
void Query::begin()
{
mQuery->begin();
}
void Query::end()
{
mQuery->end();
}
GLuint Query::getResult()
{
return mQuery->getResult();
}
GLboolean Query::isResultAvailable()
{
return mQuery->isResultAvailable();
}
GLenum Query::getType() const
{
return mQuery->getType();
}
}
| 010smithzhang-ddd | src/libGLESv2/Query.cpp | C++ | bsd | 851 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Framebuffer.h: Defines the gl::Framebuffer class. Implements GL framebuffer
// objects and related functionality. [OpenGL ES 2.0.24] section 4.4 page 105.
#ifndef LIBGLESV2_FRAMEBUFFER_H_
#define LIBGLESV2_FRAMEBUFFER_H_
#include "common/angleutils.h"
#include "common/RefCountObject.h"
#include "constants.h"
namespace rx
{
class Renderer;
}
namespace gl
{
class Renderbuffer;
class Colorbuffer;
class Depthbuffer;
class Stencilbuffer;
class DepthStencilbuffer;
class Framebuffer
{
public:
explicit Framebuffer(rx::Renderer *renderer);
virtual ~Framebuffer();
void setColorbuffer(unsigned int colorAttachment, GLenum type, GLuint colorbuffer);
void setDepthbuffer(GLenum type, GLuint depthbuffer);
void setStencilbuffer(GLenum type, GLuint stencilbuffer);
void detachTexture(GLuint texture);
void detachRenderbuffer(GLuint renderbuffer);
unsigned int getRenderTargetSerial(unsigned int colorAttachment) const;
unsigned int getDepthbufferSerial() const;
unsigned int getStencilbufferSerial() const;
Renderbuffer *getColorbuffer(unsigned int colorAttachment) const;
Renderbuffer *getDepthbuffer() const;
Renderbuffer *getStencilbuffer() const;
Renderbuffer *getDepthOrStencilbuffer() const;
Renderbuffer *getReadColorbuffer() const;
GLenum getReadColorbufferType() const;
Renderbuffer *getFirstColorbuffer() const;
GLenum getColorbufferType(unsigned int colorAttachment) const;
GLenum getDepthbufferType() const;
GLenum getStencilbufferType() const;
GLuint getColorbufferHandle(unsigned int colorAttachment) const;
GLuint getDepthbufferHandle() const;
GLuint getStencilbufferHandle() const;
GLenum getDrawBufferState(unsigned int colorAttachment) const;
void setDrawBufferState(unsigned int colorAttachment, GLenum drawBuffer);
bool isEnabledColorAttachment(unsigned int colorAttachment) const;
bool hasEnabledColorAttachment() const;
bool hasStencil() const;
int getSamples() const;
bool usingExtendedDrawBuffers() const;
virtual GLenum completeness() const;
protected:
GLenum mColorbufferTypes[IMPLEMENTATION_MAX_DRAW_BUFFERS];
BindingPointer<Renderbuffer> mColorbufferPointers[IMPLEMENTATION_MAX_DRAW_BUFFERS];
GLenum mDrawBufferStates[IMPLEMENTATION_MAX_DRAW_BUFFERS];
GLenum mReadBufferState;
GLenum mDepthbufferType;
BindingPointer<Renderbuffer> mDepthbufferPointer;
GLenum mStencilbufferType;
BindingPointer<Renderbuffer> mStencilbufferPointer;
rx::Renderer *mRenderer;
private:
DISALLOW_COPY_AND_ASSIGN(Framebuffer);
Renderbuffer *lookupRenderbuffer(GLenum type, GLuint handle) const;
};
class DefaultFramebuffer : public Framebuffer
{
public:
DefaultFramebuffer(rx::Renderer *Renderer, Colorbuffer *colorbuffer, DepthStencilbuffer *depthStencil);
virtual GLenum completeness() const;
private:
DISALLOW_COPY_AND_ASSIGN(DefaultFramebuffer);
};
}
#endif // LIBGLESV2_FRAMEBUFFER_H_
| 010smithzhang-ddd | src/libGLESv2/Framebuffer.h | C++ | bsd | 3,194 |
#include "precompiled.h"
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ResourceManager.cpp: Implements the gl::ResourceManager class, which tracks and
// retrieves objects which may be shared by multiple Contexts.
#include "libGLESv2/ResourceManager.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/Shader.h"
#include "libGLESv2/Texture.h"
namespace gl
{
ResourceManager::ResourceManager(rx::Renderer *renderer)
{
mRefCount = 1;
mRenderer = renderer;
}
ResourceManager::~ResourceManager()
{
while (!mBufferMap.empty())
{
deleteBuffer(mBufferMap.begin()->first);
}
while (!mProgramMap.empty())
{
deleteProgram(mProgramMap.begin()->first);
}
while (!mShaderMap.empty())
{
deleteShader(mShaderMap.begin()->first);
}
while (!mRenderbufferMap.empty())
{
deleteRenderbuffer(mRenderbufferMap.begin()->first);
}
while (!mTextureMap.empty())
{
deleteTexture(mTextureMap.begin()->first);
}
}
void ResourceManager::addRef()
{
mRefCount++;
}
void ResourceManager::release()
{
if (--mRefCount == 0)
{
delete this;
}
}
// Returns an unused buffer name
GLuint ResourceManager::createBuffer()
{
GLuint handle = mBufferHandleAllocator.allocate();
mBufferMap[handle] = NULL;
return handle;
}
// Returns an unused shader/program name
GLuint ResourceManager::createShader(GLenum type)
{
GLuint handle = mProgramShaderHandleAllocator.allocate();
if (type == GL_VERTEX_SHADER)
{
mShaderMap[handle] = new VertexShader(this, mRenderer, handle);
}
else if (type == GL_FRAGMENT_SHADER)
{
mShaderMap[handle] = new FragmentShader(this, mRenderer, handle);
}
else UNREACHABLE();
return handle;
}
// Returns an unused program/shader name
GLuint ResourceManager::createProgram()
{
GLuint handle = mProgramShaderHandleAllocator.allocate();
mProgramMap[handle] = new Program(mRenderer, this, handle);
return handle;
}
// Returns an unused texture name
GLuint ResourceManager::createTexture()
{
GLuint handle = mTextureHandleAllocator.allocate();
mTextureMap[handle] = NULL;
return handle;
}
// Returns an unused renderbuffer name
GLuint ResourceManager::createRenderbuffer()
{
GLuint handle = mRenderbufferHandleAllocator.allocate();
mRenderbufferMap[handle] = NULL;
return handle;
}
void ResourceManager::deleteBuffer(GLuint buffer)
{
BufferMap::iterator bufferObject = mBufferMap.find(buffer);
if (bufferObject != mBufferMap.end())
{
mBufferHandleAllocator.release(bufferObject->first);
if (bufferObject->second) bufferObject->second->release();
mBufferMap.erase(bufferObject);
}
}
void ResourceManager::deleteShader(GLuint shader)
{
ShaderMap::iterator shaderObject = mShaderMap.find(shader);
if (shaderObject != mShaderMap.end())
{
if (shaderObject->second->getRefCount() == 0)
{
mProgramShaderHandleAllocator.release(shaderObject->first);
delete shaderObject->second;
mShaderMap.erase(shaderObject);
}
else
{
shaderObject->second->flagForDeletion();
}
}
}
void ResourceManager::deleteProgram(GLuint program)
{
ProgramMap::iterator programObject = mProgramMap.find(program);
if (programObject != mProgramMap.end())
{
if (programObject->second->getRefCount() == 0)
{
mProgramShaderHandleAllocator.release(programObject->first);
delete programObject->second;
mProgramMap.erase(programObject);
}
else
{
programObject->second->flagForDeletion();
}
}
}
void ResourceManager::deleteTexture(GLuint texture)
{
TextureMap::iterator textureObject = mTextureMap.find(texture);
if (textureObject != mTextureMap.end())
{
mTextureHandleAllocator.release(textureObject->first);
if (textureObject->second) textureObject->second->release();
mTextureMap.erase(textureObject);
}
}
void ResourceManager::deleteRenderbuffer(GLuint renderbuffer)
{
RenderbufferMap::iterator renderbufferObject = mRenderbufferMap.find(renderbuffer);
if (renderbufferObject != mRenderbufferMap.end())
{
mRenderbufferHandleAllocator.release(renderbufferObject->first);
if (renderbufferObject->second) renderbufferObject->second->release();
mRenderbufferMap.erase(renderbufferObject);
}
}
Buffer *ResourceManager::getBuffer(unsigned int handle)
{
BufferMap::iterator buffer = mBufferMap.find(handle);
if (buffer == mBufferMap.end())
{
return NULL;
}
else
{
return buffer->second;
}
}
Shader *ResourceManager::getShader(unsigned int handle)
{
ShaderMap::iterator shader = mShaderMap.find(handle);
if (shader == mShaderMap.end())
{
return NULL;
}
else
{
return shader->second;
}
}
Texture *ResourceManager::getTexture(unsigned int handle)
{
if (handle == 0) return NULL;
TextureMap::iterator texture = mTextureMap.find(handle);
if (texture == mTextureMap.end())
{
return NULL;
}
else
{
return texture->second;
}
}
Program *ResourceManager::getProgram(unsigned int handle)
{
ProgramMap::iterator program = mProgramMap.find(handle);
if (program == mProgramMap.end())
{
return NULL;
}
else
{
return program->second;
}
}
Renderbuffer *ResourceManager::getRenderbuffer(unsigned int handle)
{
RenderbufferMap::iterator renderbuffer = mRenderbufferMap.find(handle);
if (renderbuffer == mRenderbufferMap.end())
{
return NULL;
}
else
{
return renderbuffer->second;
}
}
void ResourceManager::setRenderbuffer(GLuint handle, Renderbuffer *buffer)
{
mRenderbufferMap[handle] = buffer;
}
void ResourceManager::checkBufferAllocation(unsigned int buffer)
{
if (buffer != 0 && !getBuffer(buffer))
{
Buffer *bufferObject = new Buffer(mRenderer, buffer);
mBufferMap[buffer] = bufferObject;
bufferObject->addRef();
}
}
void ResourceManager::checkTextureAllocation(GLuint texture, TextureType type)
{
if (!getTexture(texture) && texture != 0)
{
Texture *textureObject;
if (type == TEXTURE_2D)
{
textureObject = new Texture2D(mRenderer, texture);
}
else if (type == TEXTURE_CUBE)
{
textureObject = new TextureCubeMap(mRenderer, texture);
}
else
{
UNREACHABLE();
return;
}
mTextureMap[texture] = textureObject;
textureObject->addRef();
}
}
void ResourceManager::checkRenderbufferAllocation(GLuint renderbuffer)
{
if (renderbuffer != 0 && !getRenderbuffer(renderbuffer))
{
Renderbuffer *renderbufferObject = new Renderbuffer(mRenderer, renderbuffer, new Colorbuffer(mRenderer, 0, 0, GL_RGBA4, 0));
mRenderbufferMap[renderbuffer] = renderbufferObject;
renderbufferObject->addRef();
}
}
}
| 010smithzhang-ddd | src/libGLESv2/ResourceManager.cpp | C++ | bsd | 7,390 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Shader.h: Defines the abstract gl::Shader class and its concrete derived
// classes VertexShader and FragmentShader. Implements GL shader objects and
// related functionality. [OpenGL ES 2.0.24] section 2.10 page 24 and section
// 3.8 page 84.
#ifndef LIBGLESV2_SHADER_H_
#define LIBGLESV2_SHADER_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#include <string>
#include <list>
#include <vector>
#include "compiler/Uniform.h"
#include "common/angleutils.h"
namespace rx
{
class Renderer;
}
namespace gl
{
class ResourceManager;
struct Varying
{
Varying(GLenum type, const std::string &name, int size, bool array)
: type(type), name(name), size(size), array(array), reg(-1), col(-1)
{
}
GLenum type;
std::string name;
int size; // Number of 'type' elements
bool array;
int reg; // First varying register, assigned during link
int col; // First register element, assigned during link
};
typedef std::list<Varying> VaryingList;
class Shader
{
friend class ProgramBinary;
public:
Shader(ResourceManager *manager, const rx::Renderer *renderer, GLuint handle);
virtual ~Shader();
virtual GLenum getType() = 0;
GLuint getHandle() const;
void deleteSource();
void setSource(GLsizei count, const char **string, const GLint *length);
int getInfoLogLength() const;
void getInfoLog(GLsizei bufSize, GLsizei *length, char *infoLog);
int getSourceLength() const;
void getSource(GLsizei bufSize, GLsizei *length, char *buffer);
int getTranslatedSourceLength() const;
void getTranslatedSource(GLsizei bufSize, GLsizei *length, char *buffer);
const sh::ActiveUniforms &getUniforms();
virtual void compile() = 0;
virtual void uncompile();
bool isCompiled();
const char *getHLSL();
void addRef();
void release();
unsigned int getRefCount() const;
bool isFlaggedForDeletion() const;
void flagForDeletion();
static void releaseCompiler();
protected:
void parseVaryings();
void resetVaryingsRegisterAssignment();
void compileToHLSL(void *compiler);
void getSourceImpl(char *source, GLsizei bufSize, GLsizei *length, char *buffer);
static GLenum parseType(const std::string &type);
static bool compareVarying(const Varying &x, const Varying &y);
const rx::Renderer *const mRenderer;
VaryingList mVaryings;
bool mUsesMultipleRenderTargets;
bool mUsesFragColor;
bool mUsesFragData;
bool mUsesFragCoord;
bool mUsesFrontFacing;
bool mUsesPointSize;
bool mUsesPointCoord;
bool mUsesDepthRange;
bool mUsesFragDepth;
static void *mFragmentCompiler;
static void *mVertexCompiler;
private:
DISALLOW_COPY_AND_ASSIGN(Shader);
void initializeCompiler();
const GLuint mHandle;
unsigned int mRefCount; // Number of program objects this shader is attached to
bool mDeleteStatus; // Flag to indicate that the shader can be deleted when no longer in use
char *mSource;
char *mHlsl;
char *mInfoLog;
sh::ActiveUniforms mActiveUniforms;
ResourceManager *mResourceManager;
};
struct Attribute
{
Attribute() : type(GL_NONE), name("")
{
}
Attribute(GLenum type, const std::string &name) : type(type), name(name)
{
}
GLenum type;
std::string name;
};
typedef std::vector<Attribute> AttributeArray;
class VertexShader : public Shader
{
friend class ProgramBinary;
public:
VertexShader(ResourceManager *manager, const rx::Renderer *renderer, GLuint handle);
~VertexShader();
virtual GLenum getType();
virtual void compile();
virtual void uncompile();
int getSemanticIndex(const std::string &attributeName);
private:
DISALLOW_COPY_AND_ASSIGN(VertexShader);
void parseAttributes();
AttributeArray mAttributes;
};
class FragmentShader : public Shader
{
public:
FragmentShader(ResourceManager *manager,const rx::Renderer *renderer, GLuint handle);
~FragmentShader();
virtual GLenum getType();
virtual void compile();
private:
DISALLOW_COPY_AND_ASSIGN(FragmentShader);
};
}
#endif // LIBGLESV2_SHADER_H_
| 010smithzhang-ddd | src/libGLESv2/Shader.h | C++ | bsd | 4,367 |
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Buffer.cpp: Implements the gl::Buffer class, representing storage of vertex and/or
// index data. Implements GL buffer objects and related functionality.
// [OpenGL ES 2.0.24] section 2.9 page 21.
#include "libGLESv2/Buffer.h"
#include "libGLESv2/renderer/VertexBuffer.h"
#include "libGLESv2/renderer/IndexBuffer.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "libGLESv2/renderer/Renderer.h"
namespace gl
{
Buffer::Buffer(rx::Renderer *renderer, GLuint id) : RefCountObject(id)
{
mRenderer = renderer;
mUsage = GL_DYNAMIC_DRAW;
mBufferStorage = renderer->createBufferStorage();
mStaticVertexBuffer = NULL;
mStaticIndexBuffer = NULL;
mUnmodifiedDataUse = 0;
}
Buffer::~Buffer()
{
delete mBufferStorage;
delete mStaticVertexBuffer;
delete mStaticIndexBuffer;
}
void Buffer::bufferData(const void *data, GLsizeiptr size, GLenum usage)
{
mBufferStorage->clear();
mBufferStorage->setData(data, size, 0);
mUsage = usage;
invalidateStaticData();
if (usage == GL_STATIC_DRAW)
{
mStaticVertexBuffer = new rx::StaticVertexBufferInterface(mRenderer);
mStaticIndexBuffer = new rx::StaticIndexBufferInterface(mRenderer);
}
}
void Buffer::bufferSubData(const void *data, GLsizeiptr size, GLintptr offset)
{
mBufferStorage->setData(data, size, offset);
if ((mStaticVertexBuffer && mStaticVertexBuffer->getBufferSize() != 0) || (mStaticIndexBuffer && mStaticIndexBuffer->getBufferSize() != 0))
{
invalidateStaticData();
}
mUnmodifiedDataUse = 0;
}
rx::BufferStorage *Buffer::getStorage() const
{
return mBufferStorage;
}
unsigned int Buffer::size()
{
return mBufferStorage->getSize();
}
GLenum Buffer::usage() const
{
return mUsage;
}
rx::StaticVertexBufferInterface *Buffer::getStaticVertexBuffer()
{
return mStaticVertexBuffer;
}
rx::StaticIndexBufferInterface *Buffer::getStaticIndexBuffer()
{
return mStaticIndexBuffer;
}
void Buffer::invalidateStaticData()
{
delete mStaticVertexBuffer;
mStaticVertexBuffer = NULL;
delete mStaticIndexBuffer;
mStaticIndexBuffer = NULL;
mUnmodifiedDataUse = 0;
}
// Creates static buffers if sufficient used data has been left unmodified
void Buffer::promoteStaticUsage(int dataSize)
{
if (!mStaticVertexBuffer && !mStaticIndexBuffer)
{
mUnmodifiedDataUse += dataSize;
if (mUnmodifiedDataUse > 3 * mBufferStorage->getSize())
{
mStaticVertexBuffer = new rx::StaticVertexBufferInterface(mRenderer);
mStaticIndexBuffer = new rx::StaticIndexBufferInterface(mRenderer);
}
}
}
}
| 010smithzhang-ddd | src/libGLESv2/Buffer.cpp | C++ | bsd | 2,859 |
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Framebuffer.cpp: Implements the gl::Framebuffer class. Implements GL framebuffer
// objects and related functionality. [OpenGL ES 2.0.24] section 4.4 page 105.
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/main.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/Renderbuffer.h"
namespace gl
{
Framebuffer::Framebuffer(rx::Renderer *renderer)
: mRenderer(renderer)
{
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
mColorbufferTypes[colorAttachment] = GL_NONE;
mDrawBufferStates[colorAttachment] = GL_NONE;
}
mDrawBufferStates[0] = GL_COLOR_ATTACHMENT0_EXT;
mReadBufferState = GL_COLOR_ATTACHMENT0_EXT;
mDepthbufferType = GL_NONE;
mStencilbufferType = GL_NONE;
}
Framebuffer::~Framebuffer()
{
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
mColorbufferPointers[colorAttachment].set(NULL);
}
mDepthbufferPointer.set(NULL);
mStencilbufferPointer.set(NULL);
}
Renderbuffer *Framebuffer::lookupRenderbuffer(GLenum type, GLuint handle) const
{
gl::Context *context = gl::getContext();
Renderbuffer *buffer = NULL;
if (type == GL_NONE)
{
buffer = NULL;
}
else if (type == GL_RENDERBUFFER)
{
buffer = context->getRenderbuffer(handle);
}
else if (IsInternalTextureTarget(type))
{
buffer = context->getTexture(handle)->getRenderbuffer(type);
}
else
{
UNREACHABLE();
}
return buffer;
}
void Framebuffer::setColorbuffer(unsigned int colorAttachment, GLenum type, GLuint colorbuffer)
{
ASSERT(colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS);
mColorbufferTypes[colorAttachment] = (colorbuffer != 0) ? type : GL_NONE;
mColorbufferPointers[colorAttachment].set(lookupRenderbuffer(type, colorbuffer));
}
void Framebuffer::setDepthbuffer(GLenum type, GLuint depthbuffer)
{
mDepthbufferType = (depthbuffer != 0) ? type : GL_NONE;
mDepthbufferPointer.set(lookupRenderbuffer(type, depthbuffer));
}
void Framebuffer::setStencilbuffer(GLenum type, GLuint stencilbuffer)
{
mStencilbufferType = (stencilbuffer != 0) ? type : GL_NONE;
mStencilbufferPointer.set(lookupRenderbuffer(type, stencilbuffer));
}
void Framebuffer::detachTexture(GLuint texture)
{
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (mColorbufferPointers[colorAttachment].id() == texture && IsInternalTextureTarget(mColorbufferTypes[colorAttachment]))
{
mColorbufferTypes[colorAttachment] = GL_NONE;
mColorbufferPointers[colorAttachment].set(NULL);
}
}
if (mDepthbufferPointer.id() == texture && IsInternalTextureTarget(mDepthbufferType))
{
mDepthbufferType = GL_NONE;
mDepthbufferPointer.set(NULL);
}
if (mStencilbufferPointer.id() == texture && IsInternalTextureTarget(mStencilbufferType))
{
mStencilbufferType = GL_NONE;
mStencilbufferPointer.set(NULL);
}
}
void Framebuffer::detachRenderbuffer(GLuint renderbuffer)
{
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (mColorbufferPointers[colorAttachment].id() == renderbuffer && mColorbufferTypes[colorAttachment] == GL_RENDERBUFFER)
{
mColorbufferTypes[colorAttachment] = GL_NONE;
mColorbufferPointers[colorAttachment].set(NULL);
}
}
if (mDepthbufferPointer.id() == renderbuffer && mDepthbufferType == GL_RENDERBUFFER)
{
mDepthbufferType = GL_NONE;
mDepthbufferPointer.set(NULL);
}
if (mStencilbufferPointer.id() == renderbuffer && mStencilbufferType == GL_RENDERBUFFER)
{
mStencilbufferType = GL_NONE;
mStencilbufferPointer.set(NULL);
}
}
unsigned int Framebuffer::getRenderTargetSerial(unsigned int colorAttachment) const
{
ASSERT(colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS);
Renderbuffer *colorbuffer = mColorbufferPointers[colorAttachment].get();
if (colorbuffer)
{
return colorbuffer->getSerial();
}
return 0;
}
unsigned int Framebuffer::getDepthbufferSerial() const
{
Renderbuffer *depthbuffer = mDepthbufferPointer.get();
if (depthbuffer)
{
return depthbuffer->getSerial();
}
return 0;
}
unsigned int Framebuffer::getStencilbufferSerial() const
{
Renderbuffer *stencilbuffer = mStencilbufferPointer.get();
if (stencilbuffer)
{
return stencilbuffer->getSerial();
}
return 0;
}
Renderbuffer *Framebuffer::getColorbuffer(unsigned int colorAttachment) const
{
ASSERT(colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS);
return mColorbufferPointers[colorAttachment].get();
}
Renderbuffer *Framebuffer::getDepthbuffer() const
{
return mDepthbufferPointer.get();
}
Renderbuffer *Framebuffer::getStencilbuffer() const
{
return mStencilbufferPointer.get();
}
Renderbuffer *Framebuffer::getDepthOrStencilbuffer() const
{
Renderbuffer *depthstencilbuffer = mDepthbufferPointer.get();
if (!depthstencilbuffer)
{
depthstencilbuffer = mStencilbufferPointer.get();
}
return depthstencilbuffer;
}
Renderbuffer *Framebuffer::getReadColorbuffer() const
{
// Will require more logic if glReadBuffers is supported
return mColorbufferPointers[0].get();
}
GLenum Framebuffer::getReadColorbufferType() const
{
// Will require more logic if glReadBuffers is supported
return mColorbufferTypes[0];
}
Renderbuffer *Framebuffer::getFirstColorbuffer() const
{
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (mColorbufferTypes[colorAttachment] != GL_NONE)
{
return mColorbufferPointers[colorAttachment].get();
}
}
return NULL;
}
GLenum Framebuffer::getColorbufferType(unsigned int colorAttachment) const
{
ASSERT(colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS);
return mColorbufferTypes[colorAttachment];
}
GLenum Framebuffer::getDepthbufferType() const
{
return mDepthbufferType;
}
GLenum Framebuffer::getStencilbufferType() const
{
return mStencilbufferType;
}
GLuint Framebuffer::getColorbufferHandle(unsigned int colorAttachment) const
{
ASSERT(colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS);
return mColorbufferPointers[colorAttachment].id();
}
GLuint Framebuffer::getDepthbufferHandle() const
{
return mDepthbufferPointer.id();
}
GLuint Framebuffer::getStencilbufferHandle() const
{
return mStencilbufferPointer.id();
}
GLenum Framebuffer::getDrawBufferState(unsigned int colorAttachment) const
{
return mDrawBufferStates[colorAttachment];
}
void Framebuffer::setDrawBufferState(unsigned int colorAttachment, GLenum drawBuffer)
{
mDrawBufferStates[colorAttachment] = drawBuffer;
}
bool Framebuffer::isEnabledColorAttachment(unsigned int colorAttachment) const
{
return (mColorbufferTypes[colorAttachment] != GL_NONE && mDrawBufferStates[colorAttachment] != GL_NONE);
}
bool Framebuffer::hasEnabledColorAttachment() const
{
for (unsigned int colorAttachment = 0; colorAttachment < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (isEnabledColorAttachment(colorAttachment))
{
return true;
}
}
return false;
}
bool Framebuffer::hasStencil() const
{
if (mStencilbufferType != GL_NONE)
{
const Renderbuffer *stencilbufferObject = getStencilbuffer();
if (stencilbufferObject)
{
return stencilbufferObject->getStencilSize() > 0;
}
}
return false;
}
bool Framebuffer::usingExtendedDrawBuffers() const
{
for (unsigned int colorAttachment = 1; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (isEnabledColorAttachment(colorAttachment))
{
return true;
}
}
return false;
}
GLenum Framebuffer::completeness() const
{
int width = 0;
int height = 0;
int colorbufferSize = 0;
int samples = -1;
bool missingAttachment = true;
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (mColorbufferTypes[colorAttachment] != GL_NONE)
{
const Renderbuffer *colorbuffer = getColorbuffer(colorAttachment);
if (!colorbuffer)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (colorbuffer->getWidth() == 0 || colorbuffer->getHeight() == 0)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (mColorbufferTypes[colorAttachment] == GL_RENDERBUFFER)
{
if (!gl::IsColorRenderable(colorbuffer->getInternalFormat()))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else if (IsInternalTextureTarget(mColorbufferTypes[colorAttachment]))
{
GLint internalformat = colorbuffer->getInternalFormat();
GLenum format = gl::ExtractFormat(internalformat);
if (IsCompressed(format) ||
format == GL_ALPHA ||
format == GL_LUMINANCE ||
format == GL_LUMINANCE_ALPHA)
{
return GL_FRAMEBUFFER_UNSUPPORTED;
}
bool filtering, renderable;
if ((gl::IsFloat32Format(internalformat) && !mRenderer->getFloat32TextureSupport(&filtering, &renderable)) ||
(gl::IsFloat16Format(internalformat) && !mRenderer->getFloat16TextureSupport(&filtering, &renderable)))
{
return GL_FRAMEBUFFER_UNSUPPORTED;
}
if (gl::IsDepthTexture(internalformat) || gl::IsStencilTexture(internalformat))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else
{
UNREACHABLE();
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (!missingAttachment)
{
// all color attachments must have the same width and height
if (colorbuffer->getWidth() != width || colorbuffer->getHeight() != height)
{
return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
}
// APPLE_framebuffer_multisample, which EXT_draw_buffers refers to, requires that
// all color attachments have the same number of samples for the FBO to be complete.
if (colorbuffer->getSamples() != samples)
{
return GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT;
}
// all color attachments attachments must have the same number of bitplanes
if (gl::ComputePixelSize(colorbuffer->getInternalFormat()) != colorbufferSize)
{
return GL_FRAMEBUFFER_UNSUPPORTED;
}
// D3D11 does not allow for overlapping RenderTargetViews, so ensure uniqueness
for (unsigned int previousColorAttachment = 0; previousColorAttachment < colorAttachment; previousColorAttachment++)
{
if (mColorbufferPointers[colorAttachment].get() == mColorbufferPointers[previousColorAttachment].get())
{
return GL_FRAMEBUFFER_UNSUPPORTED;
}
}
}
else
{
width = colorbuffer->getWidth();
height = colorbuffer->getHeight();
samples = colorbuffer->getSamples();
colorbufferSize = gl::ComputePixelSize(colorbuffer->getInternalFormat());
missingAttachment = false;
}
}
}
const Renderbuffer *depthbuffer = NULL;
const Renderbuffer *stencilbuffer = NULL;
if (mDepthbufferType != GL_NONE)
{
depthbuffer = getDepthbuffer();
if (!depthbuffer)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (depthbuffer->getWidth() == 0 || depthbuffer->getHeight() == 0)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (mDepthbufferType == GL_RENDERBUFFER)
{
if (!gl::IsDepthRenderable(depthbuffer->getInternalFormat()))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else if (IsInternalTextureTarget(mDepthbufferType))
{
GLint internalformat = depthbuffer->getInternalFormat();
// depth texture attachments require OES/ANGLE_depth_texture
if (!mRenderer->getDepthTextureSupport())
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (!gl::IsDepthTexture(internalformat))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else
{
UNREACHABLE();
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (missingAttachment)
{
width = depthbuffer->getWidth();
height = depthbuffer->getHeight();
samples = depthbuffer->getSamples();
missingAttachment = false;
}
else if (width != depthbuffer->getWidth() || height != depthbuffer->getHeight())
{
return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
}
else if (samples != depthbuffer->getSamples())
{
return GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE;
}
}
if (mStencilbufferType != GL_NONE)
{
stencilbuffer = getStencilbuffer();
if (!stencilbuffer)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (stencilbuffer->getWidth() == 0 || stencilbuffer->getHeight() == 0)
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (mStencilbufferType == GL_RENDERBUFFER)
{
if (!gl::IsStencilRenderable(stencilbuffer->getInternalFormat()))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else if (IsInternalTextureTarget(mStencilbufferType))
{
GLint internalformat = stencilbuffer->getInternalFormat();
// texture stencil attachments come along as part
// of OES_packed_depth_stencil + OES/ANGLE_depth_texture
if (!mRenderer->getDepthTextureSupport())
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (!gl::IsStencilTexture(internalformat))
{
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
}
else
{
UNREACHABLE();
return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
if (missingAttachment)
{
width = stencilbuffer->getWidth();
height = stencilbuffer->getHeight();
samples = stencilbuffer->getSamples();
missingAttachment = false;
}
else if (width != stencilbuffer->getWidth() || height != stencilbuffer->getHeight())
{
return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
}
else if (samples != stencilbuffer->getSamples())
{
return GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE;
}
}
// if we have both a depth and stencil buffer, they must refer to the same object
// since we only support packed_depth_stencil and not separate depth and stencil
if (depthbuffer && stencilbuffer && (depthbuffer != stencilbuffer))
{
return GL_FRAMEBUFFER_UNSUPPORTED;
}
// we need to have at least one attachment to be complete
if (missingAttachment)
{
return GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
}
return GL_FRAMEBUFFER_COMPLETE;
}
DefaultFramebuffer::DefaultFramebuffer(rx::Renderer *renderer, Colorbuffer *colorbuffer, DepthStencilbuffer *depthStencil)
: Framebuffer(renderer)
{
mColorbufferPointers[0].set(new Renderbuffer(mRenderer, 0, colorbuffer));
Renderbuffer *depthStencilRenderbuffer = new Renderbuffer(mRenderer, 0, depthStencil);
mDepthbufferPointer.set(depthStencilRenderbuffer);
mStencilbufferPointer.set(depthStencilRenderbuffer);
mColorbufferTypes[0] = GL_RENDERBUFFER;
mDepthbufferType = (depthStencilRenderbuffer->getDepthSize() != 0) ? GL_RENDERBUFFER : GL_NONE;
mStencilbufferType = (depthStencilRenderbuffer->getStencilSize() != 0) ? GL_RENDERBUFFER : GL_NONE;
mDrawBufferStates[0] = GL_BACK;
mReadBufferState = GL_BACK;
}
int Framebuffer::getSamples() const
{
if (completeness() == GL_FRAMEBUFFER_COMPLETE)
{
// for a complete framebuffer, all attachments must have the same sample count
// in this case return the first nonzero sample size
for (unsigned int colorAttachment = 0; colorAttachment < IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (mColorbufferTypes[colorAttachment] != GL_NONE)
{
return getColorbuffer(colorAttachment)->getSamples();
}
}
}
return 0;
}
GLenum DefaultFramebuffer::completeness() const
{
// The default framebuffer *must* always be complete, though it may not be
// subject to the same rules as application FBOs. ie, it could have 0x0 size.
return GL_FRAMEBUFFER_COMPLETE;
}
}
| 010smithzhang-ddd | src/libGLESv2/Framebuffer.cpp | C++ | bsd | 18,265 |
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ResourceManager.h : Defines the ResourceManager class, which tracks objects
// shared by multiple GL contexts.
#ifndef LIBGLESV2_RESOURCEMANAGER_H_
#define LIBGLESV2_RESOURCEMANAGER_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#ifdef _MSC_VER
#include <hash_map>
#else
#include <unordered_map>
#endif
#include "common/angleutils.h"
#include "libGLESv2/angletypes.h"
#include "libGLESv2/HandleAllocator.h"
namespace rx
{
class Renderer;
}
namespace gl
{
class Buffer;
class Shader;
class Program;
class Texture;
class Renderbuffer;
class ResourceManager
{
public:
explicit ResourceManager(rx::Renderer *renderer);
~ResourceManager();
void addRef();
void release();
GLuint createBuffer();
GLuint createShader(GLenum type);
GLuint createProgram();
GLuint createTexture();
GLuint createRenderbuffer();
void deleteBuffer(GLuint buffer);
void deleteShader(GLuint shader);
void deleteProgram(GLuint program);
void deleteTexture(GLuint texture);
void deleteRenderbuffer(GLuint renderbuffer);
Buffer *getBuffer(GLuint handle);
Shader *getShader(GLuint handle);
Program *getProgram(GLuint handle);
Texture *getTexture(GLuint handle);
Renderbuffer *getRenderbuffer(GLuint handle);
void setRenderbuffer(GLuint handle, Renderbuffer *renderbuffer);
void checkBufferAllocation(unsigned int buffer);
void checkTextureAllocation(GLuint texture, TextureType type);
void checkRenderbufferAllocation(GLuint renderbuffer);
private:
DISALLOW_COPY_AND_ASSIGN(ResourceManager);
std::size_t mRefCount;
rx::Renderer *mRenderer;
#ifndef HASH_MAP
# ifdef _MSC_VER
# define HASH_MAP stdext::hash_map
# else
# define HASH_MAP std::unordered_map
# endif
#endif
typedef HASH_MAP<GLuint, Buffer*> BufferMap;
BufferMap mBufferMap;
HandleAllocator mBufferHandleAllocator;
typedef HASH_MAP<GLuint, Shader*> ShaderMap;
ShaderMap mShaderMap;
typedef HASH_MAP<GLuint, Program*> ProgramMap;
ProgramMap mProgramMap;
HandleAllocator mProgramShaderHandleAllocator;
typedef HASH_MAP<GLuint, Texture*> TextureMap;
TextureMap mTextureMap;
HandleAllocator mTextureHandleAllocator;
typedef HASH_MAP<GLuint, Renderbuffer*> RenderbufferMap;
RenderbufferMap mRenderbufferMap;
HandleAllocator mRenderbufferHandleAllocator;
};
}
#endif // LIBGLESV2_RESOURCEMANAGER_H_
| 010smithzhang-ddd | src/libGLESv2/ResourceManager.h | C++ | bsd | 2,597 |
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// angletypes.h : Defines a variety of structures and enum types that are used throughout libGLESv2
#ifndef LIBGLESV2_ANGLETYPES_H_
#define LIBGLESV2_ANGLETYPES_H_
namespace gl
{
enum TextureType
{
TEXTURE_2D,
TEXTURE_CUBE,
TEXTURE_TYPE_COUNT,
TEXTURE_UNKNOWN
};
enum SamplerType
{
SAMPLER_PIXEL,
SAMPLER_VERTEX
};
struct Color
{
float red;
float green;
float blue;
float alpha;
};
struct Rectangle
{
int x;
int y;
int width;
int height;
};
struct RasterizerState
{
bool cullFace;
GLenum cullMode;
GLenum frontFace;
bool polygonOffsetFill;
GLfloat polygonOffsetFactor;
GLfloat polygonOffsetUnits;
bool pointDrawMode;
bool multiSample;
};
struct BlendState
{
bool blend;
GLenum sourceBlendRGB;
GLenum destBlendRGB;
GLenum sourceBlendAlpha;
GLenum destBlendAlpha;
GLenum blendEquationRGB;
GLenum blendEquationAlpha;
bool colorMaskRed;
bool colorMaskGreen;
bool colorMaskBlue;
bool colorMaskAlpha;
bool sampleAlphaToCoverage;
bool dither;
};
struct DepthStencilState
{
bool depthTest;
GLenum depthFunc;
bool depthMask;
bool stencilTest;
GLenum stencilFunc;
GLuint stencilMask;
GLenum stencilFail;
GLenum stencilPassDepthFail;
GLenum stencilPassDepthPass;
GLuint stencilWritemask;
GLenum stencilBackFunc;
GLuint stencilBackMask;
GLenum stencilBackFail;
GLenum stencilBackPassDepthFail;
GLenum stencilBackPassDepthPass;
GLuint stencilBackWritemask;
};
struct SamplerState
{
GLenum minFilter;
GLenum magFilter;
GLenum wrapS;
GLenum wrapT;
float maxAnisotropy;
int lodOffset;
};
struct ClearParameters
{
GLbitfield mask;
Color colorClearValue;
bool colorMaskRed;
bool colorMaskGreen;
bool colorMaskBlue;
bool colorMaskAlpha;
float depthClearValue;
GLint stencilClearValue;
GLuint stencilWriteMask;
};
}
#endif // LIBGLESV2_ANGLETYPES_H_
| 010smithzhang-ddd | src/libGLESv2/angletypes.h | C++ | bsd | 2,203 |
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Shader.cpp: Implements the gl::Shader class and its derived classes
// VertexShader and FragmentShader. Implements GL shader objects and related
// functionality. [OpenGL ES 2.0.24] section 2.10 page 24 and section 3.8 page 84.
#include "libGLESv2/Shader.h"
#include "GLSLANG/ShaderLang.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/Constants.h"
#include "libGLESv2/ResourceManager.h"
namespace gl
{
void *Shader::mFragmentCompiler = NULL;
void *Shader::mVertexCompiler = NULL;
Shader::Shader(ResourceManager *manager, const rx::Renderer *renderer, GLuint handle)
: mHandle(handle), mRenderer(renderer), mResourceManager(manager)
{
mSource = NULL;
mHlsl = NULL;
mInfoLog = NULL;
uncompile();
initializeCompiler();
mRefCount = 0;
mDeleteStatus = false;
}
Shader::~Shader()
{
delete[] mSource;
delete[] mHlsl;
delete[] mInfoLog;
}
GLuint Shader::getHandle() const
{
return mHandle;
}
void Shader::setSource(GLsizei count, const char **string, const GLint *length)
{
delete[] mSource;
int totalLength = 0;
for (int i = 0; i < count; i++)
{
if (length && length[i] >= 0)
{
totalLength += length[i];
}
else
{
totalLength += (int)strlen(string[i]);
}
}
mSource = new char[totalLength + 1];
char *code = mSource;
for (int i = 0; i < count; i++)
{
int stringLength;
if (length && length[i] >= 0)
{
stringLength = length[i];
}
else
{
stringLength = (int)strlen(string[i]);
}
strncpy(code, string[i], stringLength);
code += stringLength;
}
mSource[totalLength] = '\0';
}
int Shader::getInfoLogLength() const
{
if (!mInfoLog)
{
return 0;
}
else
{
return strlen(mInfoLog) + 1;
}
}
void Shader::getInfoLog(GLsizei bufSize, GLsizei *length, char *infoLog)
{
int index = 0;
if (bufSize > 0)
{
if (mInfoLog)
{
index = std::min(bufSize - 1, (int)strlen(mInfoLog));
memcpy(infoLog, mInfoLog, index);
}
infoLog[index] = '\0';
}
if (length)
{
*length = index;
}
}
int Shader::getSourceLength() const
{
if (!mSource)
{
return 0;
}
else
{
return strlen(mSource) + 1;
}
}
int Shader::getTranslatedSourceLength() const
{
if (!mHlsl)
{
return 0;
}
else
{
return strlen(mHlsl) + 1;
}
}
void Shader::getSourceImpl(char *source, GLsizei bufSize, GLsizei *length, char *buffer)
{
int index = 0;
if (bufSize > 0)
{
if (source)
{
index = std::min(bufSize - 1, (int)strlen(source));
memcpy(buffer, source, index);
}
buffer[index] = '\0';
}
if (length)
{
*length = index;
}
}
void Shader::getSource(GLsizei bufSize, GLsizei *length, char *buffer)
{
getSourceImpl(mSource, bufSize, length, buffer);
}
void Shader::getTranslatedSource(GLsizei bufSize, GLsizei *length, char *buffer)
{
getSourceImpl(mHlsl, bufSize, length, buffer);
}
const sh::ActiveUniforms &Shader::getUniforms()
{
return mActiveUniforms;
}
bool Shader::isCompiled()
{
return mHlsl != NULL;
}
const char *Shader::getHLSL()
{
return mHlsl;
}
void Shader::addRef()
{
mRefCount++;
}
void Shader::release()
{
mRefCount--;
if (mRefCount == 0 && mDeleteStatus)
{
mResourceManager->deleteShader(mHandle);
}
}
unsigned int Shader::getRefCount() const
{
return mRefCount;
}
bool Shader::isFlaggedForDeletion() const
{
return mDeleteStatus;
}
void Shader::flagForDeletion()
{
mDeleteStatus = true;
}
// Perform a one-time initialization of the shader compiler (or after being destructed by releaseCompiler)
void Shader::initializeCompiler()
{
if (!mFragmentCompiler)
{
int result = ShInitialize();
if (result)
{
ShShaderOutput hlslVersion = (mRenderer->getMajorShaderModel() >= 4) ? SH_HLSL11_OUTPUT : SH_HLSL9_OUTPUT;
ShBuiltInResources resources;
ShInitBuiltInResources(&resources);
resources.MaxVertexAttribs = MAX_VERTEX_ATTRIBS;
resources.MaxVertexUniformVectors = mRenderer->getMaxVertexUniformVectors();
resources.MaxVaryingVectors = mRenderer->getMaxVaryingVectors();
resources.MaxVertexTextureImageUnits = mRenderer->getMaxVertexTextureImageUnits();
resources.MaxCombinedTextureImageUnits = mRenderer->getMaxCombinedTextureImageUnits();
resources.MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
resources.MaxFragmentUniformVectors = mRenderer->getMaxFragmentUniformVectors();
resources.MaxDrawBuffers = mRenderer->getMaxRenderTargets();
resources.OES_standard_derivatives = mRenderer->getDerivativeInstructionSupport();
resources.EXT_draw_buffers = mRenderer->getMaxRenderTargets() > 1;
// resources.OES_EGL_image_external = mRenderer->getShareHandleSupport() ? 1 : 0; // TODO: commented out until the extension is actually supported.
resources.FragmentPrecisionHigh = 1; // Shader Model 2+ always supports FP24 (s16e7) which corresponds to highp
resources.EXT_frag_depth = 1; // Shader Model 2+ always supports explicit depth output
mFragmentCompiler = ShConstructCompiler(SH_FRAGMENT_SHADER, SH_GLES2_SPEC, hlslVersion, &resources);
mVertexCompiler = ShConstructCompiler(SH_VERTEX_SHADER, SH_GLES2_SPEC, hlslVersion, &resources);
}
}
}
void Shader::releaseCompiler()
{
ShDestruct(mFragmentCompiler);
ShDestruct(mVertexCompiler);
mFragmentCompiler = NULL;
mVertexCompiler = NULL;
ShFinalize();
}
void Shader::parseVaryings()
{
if (mHlsl)
{
const char *input = strstr(mHlsl, "// Varyings") + 12;
while(true)
{
char varyingType[256];
char varyingName[256];
int matches = sscanf(input, "static %255s %255s", varyingType, varyingName);
if (matches != 2)
{
break;
}
char *array = strstr(varyingName, "[");
int size = 1;
if (array)
{
size = atoi(array + 1);
*array = '\0';
}
mVaryings.push_back(Varying(parseType(varyingType), varyingName, size, array != NULL));
input = strstr(input, ";") + 2;
}
mUsesMultipleRenderTargets = strstr(mHlsl, "GL_USES_MRT") != NULL;
mUsesFragColor = strstr(mHlsl, "GL_USES_FRAG_COLOR") != NULL;
mUsesFragData = strstr(mHlsl, "GL_USES_FRAG_DATA") != NULL;
mUsesFragCoord = strstr(mHlsl, "GL_USES_FRAG_COORD") != NULL;
mUsesFrontFacing = strstr(mHlsl, "GL_USES_FRONT_FACING") != NULL;
mUsesPointSize = strstr(mHlsl, "GL_USES_POINT_SIZE") != NULL;
mUsesPointCoord = strstr(mHlsl, "GL_USES_POINT_COORD") != NULL;
mUsesDepthRange = strstr(mHlsl, "GL_USES_DEPTH_RANGE") != NULL;
mUsesFragDepth = strstr(mHlsl, "GL_USES_FRAG_DEPTH") != NULL;
}
}
void Shader::resetVaryingsRegisterAssignment()
{
for (VaryingList::iterator var = mVaryings.begin(); var != mVaryings.end(); var++)
{
var->reg = -1;
var->col = -1;
}
}
// initialize/clean up previous state
void Shader::uncompile()
{
// set by compileToHLSL
delete[] mHlsl;
mHlsl = NULL;
delete[] mInfoLog;
mInfoLog = NULL;
// set by parseVaryings
mVaryings.clear();
mUsesMultipleRenderTargets = false;
mUsesFragColor = false;
mUsesFragData = false;
mUsesFragCoord = false;
mUsesFrontFacing = false;
mUsesPointSize = false;
mUsesPointCoord = false;
mUsesDepthRange = false;
mUsesFragDepth = false;
mActiveUniforms.clear();
}
void Shader::compileToHLSL(void *compiler)
{
// ensure we don't pass a NULL source to the compiler
const char *source = "\0";
if (mSource)
{
source = mSource;
}
// ensure the compiler is loaded
initializeCompiler();
int compileOptions = SH_OBJECT_CODE;
std::string sourcePath;
if (perfActive())
{
sourcePath = getTempPath();
writeFile(sourcePath.c_str(), source, strlen(source));
compileOptions |= SH_LINE_DIRECTIVES;
}
int result;
if (sourcePath.empty())
{
result = ShCompile(compiler, &source, 1, compileOptions);
}
else
{
const char* sourceStrings[2] =
{
sourcePath.c_str(),
source
};
result = ShCompile(compiler, sourceStrings, 2, compileOptions | SH_SOURCE_PATH);
}
if (result)
{
size_t objCodeLen = 0;
ShGetInfo(compiler, SH_OBJECT_CODE_LENGTH, &objCodeLen);
mHlsl = new char[objCodeLen];
ShGetObjectCode(compiler, mHlsl);
void *activeUniforms;
ShGetInfoPointer(compiler, SH_ACTIVE_UNIFORMS_ARRAY, &activeUniforms);
mActiveUniforms = *(sh::ActiveUniforms*)activeUniforms;
}
else
{
size_t infoLogLen = 0;
ShGetInfo(compiler, SH_INFO_LOG_LENGTH, &infoLogLen);
mInfoLog = new char[infoLogLen];
ShGetInfoLog(compiler, mInfoLog);
TRACE("\n%s", mInfoLog);
}
}
GLenum Shader::parseType(const std::string &type)
{
if (type == "float")
{
return GL_FLOAT;
}
else if (type == "float2")
{
return GL_FLOAT_VEC2;
}
else if (type == "float3")
{
return GL_FLOAT_VEC3;
}
else if (type == "float4")
{
return GL_FLOAT_VEC4;
}
else if (type == "float2x2")
{
return GL_FLOAT_MAT2;
}
else if (type == "float3x3")
{
return GL_FLOAT_MAT3;
}
else if (type == "float4x4")
{
return GL_FLOAT_MAT4;
}
else UNREACHABLE();
return GL_NONE;
}
// true if varying x has a higher priority in packing than y
bool Shader::compareVarying(const Varying &x, const Varying &y)
{
if(x.type == y.type)
{
return x.size > y.size;
}
switch (x.type)
{
case GL_FLOAT_MAT4: return true;
case GL_FLOAT_MAT2:
switch(y.type)
{
case GL_FLOAT_MAT4: return false;
case GL_FLOAT_MAT2: return true;
case GL_FLOAT_VEC4: return true;
case GL_FLOAT_MAT3: return true;
case GL_FLOAT_VEC3: return true;
case GL_FLOAT_VEC2: return true;
case GL_FLOAT: return true;
default: UNREACHABLE();
}
break;
case GL_FLOAT_VEC4:
switch(y.type)
{
case GL_FLOAT_MAT4: return false;
case GL_FLOAT_MAT2: return false;
case GL_FLOAT_VEC4: return true;
case GL_FLOAT_MAT3: return true;
case GL_FLOAT_VEC3: return true;
case GL_FLOAT_VEC2: return true;
case GL_FLOAT: return true;
default: UNREACHABLE();
}
break;
case GL_FLOAT_MAT3:
switch(y.type)
{
case GL_FLOAT_MAT4: return false;
case GL_FLOAT_MAT2: return false;
case GL_FLOAT_VEC4: return false;
case GL_FLOAT_MAT3: return true;
case GL_FLOAT_VEC3: return true;
case GL_FLOAT_VEC2: return true;
case GL_FLOAT: return true;
default: UNREACHABLE();
}
break;
case GL_FLOAT_VEC3:
switch(y.type)
{
case GL_FLOAT_MAT4: return false;
case GL_FLOAT_MAT2: return false;
case GL_FLOAT_VEC4: return false;
case GL_FLOAT_MAT3: return false;
case GL_FLOAT_VEC3: return true;
case GL_FLOAT_VEC2: return true;
case GL_FLOAT: return true;
default: UNREACHABLE();
}
break;
case GL_FLOAT_VEC2:
switch(y.type)
{
case GL_FLOAT_MAT4: return false;
case GL_FLOAT_MAT2: return false;
case GL_FLOAT_VEC4: return false;
case GL_FLOAT_MAT3: return false;
case GL_FLOAT_VEC3: return false;
case GL_FLOAT_VEC2: return true;
case GL_FLOAT: return true;
default: UNREACHABLE();
}
break;
case GL_FLOAT: return false;
default: UNREACHABLE();
}
return false;
}
VertexShader::VertexShader(ResourceManager *manager, const rx::Renderer *renderer, GLuint handle)
: Shader(manager, renderer, handle)
{
}
VertexShader::~VertexShader()
{
}
GLenum VertexShader::getType()
{
return GL_VERTEX_SHADER;
}
void VertexShader::uncompile()
{
Shader::uncompile();
// set by ParseAttributes
mAttributes.clear();
}
void VertexShader::compile()
{
uncompile();
compileToHLSL(mVertexCompiler);
parseAttributes();
parseVaryings();
}
int VertexShader::getSemanticIndex(const std::string &attributeName)
{
if (!attributeName.empty())
{
int semanticIndex = 0;
for (AttributeArray::iterator attribute = mAttributes.begin(); attribute != mAttributes.end(); attribute++)
{
if (attribute->name == attributeName)
{
return semanticIndex;
}
semanticIndex += VariableRowCount(attribute->type);
}
}
return -1;
}
void VertexShader::parseAttributes()
{
const char *hlsl = getHLSL();
if (hlsl)
{
const char *input = strstr(hlsl, "// Attributes") + 14;
while(true)
{
char attributeType[256];
char attributeName[256];
int matches = sscanf(input, "static %255s _%255s", attributeType, attributeName);
if (matches != 2)
{
break;
}
mAttributes.push_back(Attribute(parseType(attributeType), attributeName));
input = strstr(input, ";") + 2;
}
}
}
FragmentShader::FragmentShader(ResourceManager *manager, const rx::Renderer *renderer, GLuint handle)
: Shader(manager, renderer, handle)
{
}
FragmentShader::~FragmentShader()
{
}
GLenum FragmentShader::getType()
{
return GL_FRAGMENT_SHADER;
}
void FragmentShader::compile()
{
uncompile();
compileToHLSL(mFragmentCompiler);
parseVaryings();
mVaryings.sort(compareVarying);
}
}
| 010smithzhang-ddd | src/libGLESv2/Shader.cpp | C++ | bsd | 14,768 |
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by libGLESv2.rc
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 010smithzhang-ddd | src/libGLESv2/resource.h | C | bsd | 389 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Query.h: Defines the gl::Query class
#ifndef LIBGLESV2_QUERY_H_
#define LIBGLESV2_QUERY_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#include "common/angleutils.h"
#include "common/RefCountObject.h"
namespace rx
{
class Renderer;
class QueryImpl;
}
namespace gl
{
class Query : public RefCountObject
{
public:
Query(rx::Renderer *renderer, GLenum type, GLuint id);
virtual ~Query();
void begin();
void end();
GLuint getResult();
GLboolean isResultAvailable();
GLenum getType() const;
private:
DISALLOW_COPY_AND_ASSIGN(Query);
rx::QueryImpl *mQuery;
};
}
#endif // LIBGLESV2_QUERY_H_
| 010smithzhang-ddd | src/libGLESv2/Query.h | C++ | bsd | 822 |
//
// Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// HandleAllocator.h: Defines the gl::HandleAllocator class, which is used to
// allocate GL handles.
#ifndef LIBGLESV2_HANDLEALLOCATOR_H_
#define LIBGLESV2_HANDLEALLOCATOR_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#include <vector>
#include "common/angleutils.h"
namespace gl
{
class HandleAllocator
{
public:
HandleAllocator();
virtual ~HandleAllocator();
void setBaseHandle(GLuint value);
GLuint allocate();
void release(GLuint handle);
private:
DISALLOW_COPY_AND_ASSIGN(HandleAllocator);
GLuint mBaseValue;
GLuint mNextValue;
typedef std::vector<GLuint> HandleList;
HandleList mFreeValues;
};
}
#endif // LIBGLESV2_HANDLEALLOCATOR_H_
| 010smithzhang-ddd | src/libGLESv2/HandleAllocator.h | C++ | bsd | 885 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Texture.h: Defines the abstract gl::Texture class and its concrete derived
// classes Texture2D and TextureCubeMap. Implements GL texture objects and
// related functionality. [OpenGL ES 2.0.24] section 3.7 page 63.
#ifndef LIBGLESV2_TEXTURE_H_
#define LIBGLESV2_TEXTURE_H_
#include <vector>
#define GL_APICALL
#include <GLES2/gl2.h>
#include "common/debug.h"
#include "common/RefCountObject.h"
#include "libGLESv2/angletypes.h"
namespace egl
{
class Surface;
}
namespace rx
{
class Renderer;
class TextureStorageInterface;
class TextureStorageInterface2D;
class TextureStorageInterfaceCube;
class RenderTarget;
class Image;
}
namespace gl
{
class Framebuffer;
class Renderbuffer;
enum
{
// These are the maximums the implementation can support
// The actual GL caps are limited by the device caps
// and should be queried from the Context
IMPLEMENTATION_MAX_TEXTURE_SIZE = 16384,
IMPLEMENTATION_MAX_CUBE_MAP_TEXTURE_SIZE = 16384,
IMPLEMENTATION_MAX_TEXTURE_LEVELS = 15 // 1+log2 of MAX_TEXTURE_SIZE
};
class Texture : public RefCountObject
{
public:
Texture(rx::Renderer *renderer, GLuint id);
virtual ~Texture();
virtual void addProxyRef(const Renderbuffer *proxy) = 0;
virtual void releaseProxy(const Renderbuffer *proxy) = 0;
virtual GLenum getTarget() const = 0;
bool setMinFilter(GLenum filter);
bool setMagFilter(GLenum filter);
bool setWrapS(GLenum wrap);
bool setWrapT(GLenum wrap);
bool setMaxAnisotropy(float textureMaxAnisotropy, float contextMaxAnisotropy);
bool setUsage(GLenum usage);
GLenum getMinFilter() const;
GLenum getMagFilter() const;
GLenum getWrapS() const;
GLenum getWrapT() const;
float getMaxAnisotropy() const;
int getLodOffset();
void getSamplerState(SamplerState *sampler);
GLenum getUsage() const;
bool isMipmapFiltered() const;
virtual bool isSamplerComplete() const = 0;
rx::TextureStorageInterface *getNativeTexture();
virtual Renderbuffer *getRenderbuffer(GLenum target) = 0;
virtual void generateMipmaps() = 0;
virtual void copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source) = 0;
bool hasDirtyParameters() const;
bool hasDirtyImages() const;
void resetDirty();
unsigned int getTextureSerial();
unsigned int getRenderTargetSerial(GLenum target);
bool isImmutable() const;
static const GLuint INCOMPLETE_TEXTURE_ID = static_cast<GLuint>(-1); // Every texture takes an id at creation time. The value is arbitrary because it is never registered with the resource manager.
protected:
void setImage(GLint unpackAlignment, const void *pixels, rx::Image *image);
bool subImage(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels, rx::Image *image);
void setCompressedImage(GLsizei imageSize, const void *pixels, rx::Image *image);
bool subImageCompressed(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels, rx::Image *image);
GLint creationLevels(GLsizei width, GLsizei height) const;
GLint creationLevels(GLsizei size) const;
virtual void createTexture() = 0;
virtual void updateTexture() = 0;
virtual void convertToRenderTarget() = 0;
virtual rx::RenderTarget *getRenderTarget(GLenum target) = 0;
virtual int levelCount() = 0;
rx::Renderer *mRenderer;
SamplerState mSamplerState;
GLenum mUsage;
bool mDirtyImages;
bool mImmutable;
private:
DISALLOW_COPY_AND_ASSIGN(Texture);
virtual rx::TextureStorageInterface *getStorage(bool renderTarget) = 0;
};
class Texture2D : public Texture
{
public:
Texture2D(rx::Renderer *renderer, GLuint id);
~Texture2D();
void addProxyRef(const Renderbuffer *proxy);
void releaseProxy(const Renderbuffer *proxy);
virtual GLenum getTarget() const;
GLsizei getWidth(GLint level) const;
GLsizei getHeight(GLint level) const;
GLenum getInternalFormat(GLint level) const;
GLenum getActualFormat(GLint level) const;
bool isCompressed(GLint level) const;
bool isDepth(GLint level) const;
void setImage(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setCompressedImage(GLint level, GLenum format, GLsizei width, GLsizei height, GLsizei imageSize, const void *pixels);
void subImage(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void subImageCompressed(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels);
void copyImage(GLint level, GLenum format, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
virtual void copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
void storage(GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
virtual bool isSamplerComplete() const;
virtual void bindTexImage(egl::Surface *surface);
virtual void releaseTexImage();
virtual void generateMipmaps();
virtual Renderbuffer *getRenderbuffer(GLenum target);
protected:
friend class RenderbufferTexture2D;
virtual rx::RenderTarget *getRenderTarget(GLenum target);
virtual rx::RenderTarget *getDepthStencil(GLenum target);
virtual int levelCount();
private:
DISALLOW_COPY_AND_ASSIGN(Texture2D);
virtual void createTexture();
virtual void updateTexture();
virtual void convertToRenderTarget();
virtual rx::TextureStorageInterface *getStorage(bool renderTarget);
bool isMipmapComplete() const;
void redefineImage(GLint level, GLint internalformat, GLsizei width, GLsizei height);
void commitRect(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
rx::Image *mImageArray[IMPLEMENTATION_MAX_TEXTURE_LEVELS];
rx::TextureStorageInterface2D *mTexStorage;
egl::Surface *mSurface;
// A specific internal reference count is kept for colorbuffer proxy references,
// because, as the renderbuffer acting as proxy will maintain a binding pointer
// back to this texture, there would be a circular reference if we used a binding
// pointer here. This reference count will cause the pointer to be set to NULL if
// the count drops to zero, but will not cause deletion of the Renderbuffer.
Renderbuffer *mColorbufferProxy;
unsigned int mProxyRefs;
};
class TextureCubeMap : public Texture
{
public:
TextureCubeMap(rx::Renderer *renderer, GLuint id);
~TextureCubeMap();
void addProxyRef(const Renderbuffer *proxy);
void releaseProxy(const Renderbuffer *proxy);
virtual GLenum getTarget() const;
GLsizei getWidth(GLenum target, GLint level) const;
GLsizei getHeight(GLenum target, GLint level) const;
GLenum getInternalFormat(GLenum target, GLint level) const;
GLenum getActualFormat(GLenum target, GLint level) const;
bool isCompressed(GLenum target, GLint level) const;
void setImagePosX(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setImageNegX(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setImagePosY(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setImageNegY(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setImagePosZ(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setImageNegZ(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void setCompressedImage(GLenum face, GLint level, GLenum format, GLsizei width, GLsizei height, GLsizei imageSize, const void *pixels);
void subImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void subImageCompressed(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels);
void copyImage(GLenum target, GLint level, GLenum format, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
virtual void copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
void storage(GLsizei levels, GLenum internalformat, GLsizei size);
virtual bool isSamplerComplete() const;
virtual void generateMipmaps();
virtual Renderbuffer *getRenderbuffer(GLenum target);
static unsigned int faceIndex(GLenum face);
protected:
friend class RenderbufferTextureCubeMap;
virtual rx::RenderTarget *getRenderTarget(GLenum target);
virtual int levelCount();
private:
DISALLOW_COPY_AND_ASSIGN(TextureCubeMap);
virtual void createTexture();
virtual void updateTexture();
virtual void convertToRenderTarget();
virtual rx::TextureStorageInterface *getStorage(bool renderTarget);
bool isCubeComplete() const;
bool isMipmapCubeComplete() const;
void setImage(int faceIndex, GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
void commitRect(int faceIndex, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
void redefineImage(int faceIndex, GLint level, GLint internalformat, GLsizei width, GLsizei height);
rx::Image *mImageArray[6][IMPLEMENTATION_MAX_TEXTURE_LEVELS];
rx::TextureStorageInterfaceCube *mTexStorage;
// A specific internal reference count is kept for colorbuffer proxy references,
// because, as the renderbuffer acting as proxy will maintain a binding pointer
// back to this texture, there would be a circular reference if we used a binding
// pointer here. This reference count will cause the pointer to be set to NULL if
// the count drops to zero, but will not cause deletion of the Renderbuffer.
Renderbuffer *mFaceProxies[6];
unsigned int *mFaceProxyRefs[6];
};
}
#endif // LIBGLESV2_TEXTURE_H_
| 010smithzhang-ddd | src/libGLESv2/Texture.h | C++ | bsd | 10,885 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Contants.h: Defines some implementation specific and gl constants
#ifndef LIBGLESV2_CONSTANTS_H_
#define LIBGLESV2_CONSTANTS_H_
namespace gl
{
enum
{
MAX_VERTEX_ATTRIBS = 16,
MAX_TEXTURE_IMAGE_UNITS = 16,
// Implementation upper limits, real maximums depend on the hardware
IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 16,
IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS = MAX_TEXTURE_IMAGE_UNITS + IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS,
IMPLEMENTATION_MAX_VARYING_VECTORS = 32,
IMPLEMENTATION_MAX_DRAW_BUFFERS = 8
};
const float ALIASED_LINE_WIDTH_RANGE_MIN = 1.0f;
const float ALIASED_LINE_WIDTH_RANGE_MAX = 1.0f;
const float ALIASED_POINT_SIZE_RANGE_MIN = 1.0f;
}
#endif // LIBGLESV2_CONSTANTS_H_
| 010smithzhang-ddd | src/libGLESv2/constants.h | C++ | bsd | 935 |
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// utilities.cpp: Conversion functions and other utility routines.
#include "libGLESv2/utilities.h"
#include "libGLESv2/mathutil.h"
namespace gl
{
int UniformComponentCount(GLenum type)
{
switch (type)
{
case GL_BOOL:
case GL_FLOAT:
case GL_INT:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
return 1;
case GL_BOOL_VEC2:
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
return 2;
case GL_INT_VEC3:
case GL_FLOAT_VEC3:
case GL_BOOL_VEC3:
return 3;
case GL_BOOL_VEC4:
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
case GL_FLOAT_MAT2:
return 4;
case GL_FLOAT_MAT3:
return 9;
case GL_FLOAT_MAT4:
return 16;
default:
UNREACHABLE();
}
return 0;
}
GLenum UniformComponentType(GLenum type)
{
switch(type)
{
case GL_BOOL:
case GL_BOOL_VEC2:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
return GL_BOOL;
case GL_FLOAT:
case GL_FLOAT_VEC2:
case GL_FLOAT_VEC3:
case GL_FLOAT_VEC4:
case GL_FLOAT_MAT2:
case GL_FLOAT_MAT3:
case GL_FLOAT_MAT4:
return GL_FLOAT;
case GL_INT:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_INT_VEC4:
return GL_INT;
default:
UNREACHABLE();
}
return GL_NONE;
}
size_t UniformComponentSize(GLenum type)
{
switch(type)
{
case GL_BOOL: return sizeof(GLint);
case GL_FLOAT: return sizeof(GLfloat);
case GL_INT: return sizeof(GLint);
default: UNREACHABLE();
}
return 0;
}
size_t UniformInternalSize(GLenum type)
{
// Expanded to 4-element vectors
return UniformComponentSize(UniformComponentType(type)) * VariableRowCount(type) * 4;
}
size_t UniformExternalSize(GLenum type)
{
return UniformComponentSize(UniformComponentType(type)) * UniformComponentCount(type);
}
int VariableRowCount(GLenum type)
{
switch (type)
{
case GL_NONE:
return 0;
case GL_BOOL:
case GL_FLOAT:
case GL_INT:
case GL_BOOL_VEC2:
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_FLOAT_VEC3:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
return 1;
case GL_FLOAT_MAT2:
return 2;
case GL_FLOAT_MAT3:
return 3;
case GL_FLOAT_MAT4:
return 4;
default:
UNREACHABLE();
}
return 0;
}
int VariableColumnCount(GLenum type)
{
switch (type)
{
case GL_NONE:
return 0;
case GL_BOOL:
case GL_FLOAT:
case GL_INT:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
return 1;
case GL_BOOL_VEC2:
case GL_FLOAT_VEC2:
case GL_INT_VEC2:
case GL_FLOAT_MAT2:
return 2;
case GL_INT_VEC3:
case GL_FLOAT_VEC3:
case GL_BOOL_VEC3:
case GL_FLOAT_MAT3:
return 3;
case GL_BOOL_VEC4:
case GL_FLOAT_VEC4:
case GL_INT_VEC4:
case GL_FLOAT_MAT4:
return 4;
default:
UNREACHABLE();
}
return 0;
}
int AllocateFirstFreeBits(unsigned int *bits, unsigned int allocationSize, unsigned int bitsSize)
{
ASSERT(allocationSize <= bitsSize);
unsigned int mask = std::numeric_limits<unsigned int>::max() >> (std::numeric_limits<unsigned int>::digits - allocationSize);
for (unsigned int i = 0; i < bitsSize - allocationSize + 1; i++)
{
if ((*bits & mask) == 0)
{
*bits |= mask;
return i;
}
mask <<= 1;
}
return -1;
}
GLsizei ComputePitch(GLsizei width, GLint internalformat, GLint alignment)
{
ASSERT(alignment > 0 && isPow2(alignment));
GLsizei rawPitch = ComputePixelSize(internalformat) * width;
return (rawPitch + alignment - 1) & ~(alignment - 1);
}
GLsizei ComputeCompressedPitch(GLsizei width, GLenum internalformat)
{
return ComputeCompressedSize(width, 1, internalformat);
}
GLsizei ComputeCompressedSize(GLsizei width, GLsizei height, GLenum internalformat)
{
switch (internalformat)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return 8 * ((width + 3) / 4) * ((height + 3) / 4);
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
return 16 * ((width + 3) / 4) * ((height + 3) / 4);
default:
return 0;
}
}
bool IsCompressed(GLenum format)
{
if(format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT ||
format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ||
format == GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE ||
format == GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE)
{
return true;
}
else
{
return false;
}
}
bool IsDepthTexture(GLenum format)
{
if (format == GL_DEPTH_COMPONENT ||
format == GL_DEPTH_STENCIL_OES ||
format == GL_DEPTH_COMPONENT16 ||
format == GL_DEPTH_COMPONENT32_OES ||
format == GL_DEPTH24_STENCIL8_OES)
{
return true;
}
return false;
}
bool IsStencilTexture(GLenum format)
{
if (format == GL_DEPTH_STENCIL_OES ||
format == GL_DEPTH24_STENCIL8_OES)
{
return true;
}
return false;
}
void MakeValidSize(bool isImage, bool isCompressed, GLsizei *requestWidth, GLsizei *requestHeight, int *levelOffset)
{
int upsampleCount = 0;
if (isCompressed)
{
// Don't expand the size of full textures that are at least 4x4
// already.
if (isImage || *requestWidth < 4 || *requestHeight < 4)
{
while (*requestWidth % 4 != 0 || *requestHeight % 4 != 0)
{
*requestWidth <<= 1;
*requestHeight <<= 1;
upsampleCount++;
}
}
}
*levelOffset = upsampleCount;
}
// Returns the size, in bytes, of a single texel in an Image
int ComputePixelSize(GLint internalformat)
{
switch (internalformat)
{
case GL_ALPHA8_EXT: return sizeof(unsigned char);
case GL_LUMINANCE8_EXT: return sizeof(unsigned char);
case GL_ALPHA32F_EXT: return sizeof(float);
case GL_LUMINANCE32F_EXT: return sizeof(float);
case GL_ALPHA16F_EXT: return sizeof(unsigned short);
case GL_LUMINANCE16F_EXT: return sizeof(unsigned short);
case GL_LUMINANCE8_ALPHA8_EXT: return sizeof(unsigned char) * 2;
case GL_LUMINANCE_ALPHA32F_EXT: return sizeof(float) * 2;
case GL_LUMINANCE_ALPHA16F_EXT: return sizeof(unsigned short) * 2;
case GL_RGB8_OES: return sizeof(unsigned char) * 3;
case GL_RGB565: return sizeof(unsigned short);
case GL_RGB32F_EXT: return sizeof(float) * 3;
case GL_RGB16F_EXT: return sizeof(unsigned short) * 3;
case GL_RGBA8_OES: return sizeof(unsigned char) * 4;
case GL_RGBA4: return sizeof(unsigned short);
case GL_RGB5_A1: return sizeof(unsigned short);
case GL_RGBA32F_EXT: return sizeof(float) * 4;
case GL_RGBA16F_EXT: return sizeof(unsigned short) * 4;
case GL_BGRA8_EXT: return sizeof(unsigned char) * 4;
case GL_BGRA4_ANGLEX: return sizeof(unsigned short);
case GL_BGR5_A1_ANGLEX: return sizeof(unsigned short);
default: UNREACHABLE();
}
return 0;
}
bool IsCubemapTextureTarget(GLenum target)
{
return (target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z);
}
bool IsInternalTextureTarget(GLenum target)
{
return target == GL_TEXTURE_2D || IsCubemapTextureTarget(target);
}
GLint ConvertSizedInternalFormat(GLenum format, GLenum type)
{
switch (format)
{
case GL_ALPHA:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_ALPHA8_EXT;
case GL_FLOAT: return GL_ALPHA32F_EXT;
case GL_HALF_FLOAT_OES: return GL_ALPHA16F_EXT;
default: UNIMPLEMENTED();
}
break;
case GL_LUMINANCE:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_LUMINANCE8_EXT;
case GL_FLOAT: return GL_LUMINANCE32F_EXT;
case GL_HALF_FLOAT_OES: return GL_LUMINANCE16F_EXT;
default: UNIMPLEMENTED();
}
break;
case GL_LUMINANCE_ALPHA:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_LUMINANCE8_ALPHA8_EXT;
case GL_FLOAT: return GL_LUMINANCE_ALPHA32F_EXT;
case GL_HALF_FLOAT_OES: return GL_LUMINANCE_ALPHA16F_EXT;
default: UNIMPLEMENTED();
}
break;
case GL_RGB:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_RGB8_OES;
case GL_UNSIGNED_SHORT_5_6_5: return GL_RGB565;
case GL_FLOAT: return GL_RGB32F_EXT;
case GL_HALF_FLOAT_OES: return GL_RGB16F_EXT;
default: UNIMPLEMENTED();
}
break;
case GL_RGBA:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_RGBA8_OES;
case GL_UNSIGNED_SHORT_4_4_4_4: return GL_RGBA4;
case GL_UNSIGNED_SHORT_5_5_5_1: return GL_RGB5_A1;
case GL_FLOAT: return GL_RGBA32F_EXT;
case GL_HALF_FLOAT_OES: return GL_RGBA16F_EXT;
break;
default: UNIMPLEMENTED();
}
break;
case GL_BGRA_EXT:
switch (type)
{
case GL_UNSIGNED_BYTE: return GL_BGRA8_EXT;
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT: return GL_BGRA4_ANGLEX;
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT: return GL_BGR5_A1_ANGLEX;
default: UNIMPLEMENTED();
}
break;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
return format;
case GL_DEPTH_COMPONENT:
switch (type)
{
case GL_UNSIGNED_SHORT: return GL_DEPTH_COMPONENT16;
case GL_UNSIGNED_INT: return GL_DEPTH_COMPONENT32_OES;
default: UNIMPLEMENTED();
}
break;
case GL_DEPTH_STENCIL_OES:
switch (type)
{
case GL_UNSIGNED_INT_24_8_OES: return GL_DEPTH24_STENCIL8_OES;
default: UNIMPLEMENTED();
}
break;
default:
UNIMPLEMENTED();
}
return GL_NONE;
}
GLenum ExtractFormat(GLenum internalformat)
{
switch (internalformat)
{
case GL_RGB565: return GL_RGB;
case GL_RGBA4: return GL_RGBA;
case GL_RGB5_A1: return GL_RGBA;
case GL_RGB8_OES: return GL_RGB;
case GL_RGBA8_OES: return GL_RGBA;
case GL_LUMINANCE8_ALPHA8_EXT: return GL_LUMINANCE_ALPHA;
case GL_LUMINANCE8_EXT: return GL_LUMINANCE;
case GL_ALPHA8_EXT: return GL_ALPHA;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE: return GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE: return GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE;
case GL_RGBA32F_EXT: return GL_RGBA;
case GL_RGB32F_EXT: return GL_RGB;
case GL_ALPHA32F_EXT: return GL_ALPHA;
case GL_LUMINANCE32F_EXT: return GL_LUMINANCE;
case GL_LUMINANCE_ALPHA32F_EXT: return GL_LUMINANCE_ALPHA;
case GL_RGBA16F_EXT: return GL_RGBA;
case GL_RGB16F_EXT: return GL_RGB;
case GL_ALPHA16F_EXT: return GL_ALPHA;
case GL_LUMINANCE16F_EXT: return GL_LUMINANCE;
case GL_LUMINANCE_ALPHA16F_EXT: return GL_LUMINANCE_ALPHA;
case GL_BGRA8_EXT: return GL_BGRA_EXT;
case GL_DEPTH_COMPONENT16: return GL_DEPTH_COMPONENT;
case GL_DEPTH_COMPONENT32_OES: return GL_DEPTH_COMPONENT;
case GL_DEPTH24_STENCIL8_OES: return GL_DEPTH_STENCIL_OES;
default: return GL_NONE; // Unsupported
}
}
GLenum ExtractType(GLenum internalformat)
{
switch (internalformat)
{
case GL_RGB565: return GL_UNSIGNED_SHORT_5_6_5;
case GL_RGBA4: return GL_UNSIGNED_SHORT_4_4_4_4;
case GL_RGB5_A1: return GL_UNSIGNED_SHORT_5_5_5_1;
case GL_RGB8_OES: return GL_UNSIGNED_BYTE;
case GL_RGBA8_OES: return GL_UNSIGNED_BYTE;
case GL_LUMINANCE8_ALPHA8_EXT: return GL_UNSIGNED_BYTE;
case GL_LUMINANCE8_EXT: return GL_UNSIGNED_BYTE;
case GL_ALPHA8_EXT: return GL_UNSIGNED_BYTE;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: return GL_UNSIGNED_BYTE;
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: return GL_UNSIGNED_BYTE;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE: return GL_UNSIGNED_BYTE;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE: return GL_UNSIGNED_BYTE;
case GL_RGBA32F_EXT: return GL_FLOAT;
case GL_RGB32F_EXT: return GL_FLOAT;
case GL_ALPHA32F_EXT: return GL_FLOAT;
case GL_LUMINANCE32F_EXT: return GL_FLOAT;
case GL_LUMINANCE_ALPHA32F_EXT: return GL_FLOAT;
case GL_RGBA16F_EXT: return GL_HALF_FLOAT_OES;
case GL_RGB16F_EXT: return GL_HALF_FLOAT_OES;
case GL_ALPHA16F_EXT: return GL_HALF_FLOAT_OES;
case GL_LUMINANCE16F_EXT: return GL_HALF_FLOAT_OES;
case GL_LUMINANCE_ALPHA16F_EXT: return GL_HALF_FLOAT_OES;
case GL_BGRA8_EXT: return GL_UNSIGNED_BYTE;
case GL_DEPTH_COMPONENT16: return GL_UNSIGNED_SHORT;
case GL_DEPTH_COMPONENT32_OES: return GL_UNSIGNED_INT;
case GL_DEPTH24_STENCIL8_OES: return GL_UNSIGNED_INT_24_8_OES;
default: return GL_NONE; // Unsupported
}
}
bool IsColorRenderable(GLenum internalformat)
{
switch (internalformat)
{
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
return true;
case GL_DEPTH_COMPONENT16:
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_OES:
return false;
case GL_BGRA8_EXT:
return true;
default:
UNIMPLEMENTED();
}
return false;
}
bool IsDepthRenderable(GLenum internalformat)
{
switch (internalformat)
{
case GL_DEPTH_COMPONENT16:
case GL_DEPTH24_STENCIL8_OES:
return true;
case GL_STENCIL_INDEX8:
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
return false;
default:
UNIMPLEMENTED();
}
return false;
}
bool IsStencilRenderable(GLenum internalformat)
{
switch (internalformat)
{
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_OES:
return true;
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
case GL_DEPTH_COMPONENT16:
return false;
default:
UNIMPLEMENTED();
}
return false;
}
bool IsFloat32Format(GLint internalformat)
{
switch (internalformat)
{
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
case GL_ALPHA32F_EXT:
case GL_LUMINANCE32F_EXT:
case GL_LUMINANCE_ALPHA32F_EXT:
return true;
default:
return false;
}
}
bool IsFloat16Format(GLint internalformat)
{
switch (internalformat)
{
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
case GL_ALPHA16F_EXT:
case GL_LUMINANCE16F_EXT:
case GL_LUMINANCE_ALPHA16F_EXT:
return true;
default:
return false;
}
}
unsigned int GetAlphaSize(GLenum colorFormat)
{
switch (colorFormat)
{
case GL_RGBA16F_EXT:
return 16;
case GL_RGBA32F_EXT:
return 32;
case GL_RGBA4:
return 4;
case GL_RGBA8_OES:
case GL_BGRA8_EXT:
return 8;
case GL_RGB5_A1:
return 1;
case GL_RGB8_OES:
case GL_RGB565:
case GL_RGB32F_EXT:
case GL_RGB16F_EXT:
return 0;
default:
return 0;
}
}
unsigned int GetRedSize(GLenum colorFormat)
{
switch (colorFormat)
{
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
return 16;
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
return 32;
case GL_RGBA4:
return 4;
case GL_RGBA8_OES:
case GL_BGRA8_EXT:
case GL_RGB8_OES:
return 8;
case GL_RGB5_A1:
case GL_RGB565:
return 5;
default:
return 0;
}
}
unsigned int GetGreenSize(GLenum colorFormat)
{
switch (colorFormat)
{
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
return 16;
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
return 32;
case GL_RGBA4:
return 4;
case GL_RGBA8_OES:
case GL_BGRA8_EXT:
case GL_RGB8_OES:
return 8;
case GL_RGB5_A1:
return 5;
case GL_RGB565:
return 6;
default:
return 0;
}
}
unsigned int GetBlueSize(GLenum colorFormat)
{
switch (colorFormat)
{
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
return 16;
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
return 32;
case GL_RGBA4:
return 4;
case GL_RGBA8_OES:
case GL_BGRA8_EXT:
case GL_RGB8_OES:
return 8;
case GL_RGB5_A1:
case GL_RGB565:
return 5;
default:
return 0;
}
}
unsigned int GetDepthSize(GLenum depthFormat)
{
switch (depthFormat)
{
case GL_DEPTH_COMPONENT16: return 16;
case GL_DEPTH_COMPONENT32_OES: return 32;
case GL_DEPTH24_STENCIL8_OES: return 24;
default: return 0;
}
}
unsigned int GetStencilSize(GLenum stencilFormat)
{
switch (stencilFormat)
{
case GL_DEPTH24_STENCIL8_OES: return 8;
default: return 0;
}
}
bool IsTriangleMode(GLenum drawMode)
{
switch (drawMode)
{
case GL_TRIANGLES:
case GL_TRIANGLE_FAN:
case GL_TRIANGLE_STRIP:
return true;
case GL_POINTS:
case GL_LINES:
case GL_LINE_LOOP:
case GL_LINE_STRIP:
return false;
default: UNREACHABLE();
}
return false;
}
}
std::string getTempPath()
{
char path[MAX_PATH];
DWORD pathLen = GetTempPathA(sizeof(path) / sizeof(path[0]), path);
if (pathLen == 0)
{
UNREACHABLE();
return std::string();
}
UINT unique = GetTempFileNameA(path, "sh", 0, path);
if (unique == 0)
{
UNREACHABLE();
return std::string();
}
return path;
}
void writeFile(const char* path, const void* content, size_t size)
{
FILE* file = fopen(path, "w");
if (!file)
{
UNREACHABLE();
return;
}
fwrite(content, sizeof(char), size, file);
fclose(file);
}
| 010smithzhang-ddd | src/libGLESv2/utilities.cpp | C++ | bsd | 20,735 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// main.cpp: DLL entry point and management of thread-local data.
#include "libGLESv2/main.h"
#include "libGLESv2/Context.h"
static DWORD currentTLS = TLS_OUT_OF_INDEXES;
extern "C" BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved)
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
{
currentTLS = TlsAlloc();
if (currentTLS == TLS_OUT_OF_INDEXES)
{
return FALSE;
}
}
// Fall throught to initialize index
case DLL_THREAD_ATTACH:
{
gl::Current *current = (gl::Current*)LocalAlloc(LPTR, sizeof(gl::Current));
if (current)
{
TlsSetValue(currentTLS, current);
current->context = NULL;
current->display = NULL;
}
}
break;
case DLL_THREAD_DETACH:
{
void *current = TlsGetValue(currentTLS);
if (current)
{
LocalFree((HLOCAL)current);
}
}
break;
case DLL_PROCESS_DETACH:
{
void *current = TlsGetValue(currentTLS);
if (current)
{
LocalFree((HLOCAL)current);
}
TlsFree(currentTLS);
}
break;
default:
break;
}
return TRUE;
}
namespace gl
{
void makeCurrent(Context *context, egl::Display *display, egl::Surface *surface)
{
Current *current = (Current*)TlsGetValue(currentTLS);
current->context = context;
current->display = display;
if (context && display && surface)
{
context->makeCurrent(surface);
}
}
Context *getContext()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->context;
}
Context *getNonLostContext()
{
Context *context = getContext();
if (context)
{
if (context->isContextLost())
{
gl::error(GL_OUT_OF_MEMORY);
return NULL;
}
else
{
return context;
}
}
return NULL;
}
egl::Display *getDisplay()
{
Current *current = (Current*)TlsGetValue(currentTLS);
return current->display;
}
// Records an error code
void error(GLenum errorCode)
{
gl::Context *context = glGetCurrentContext();
if (context)
{
switch (errorCode)
{
case GL_INVALID_ENUM:
context->recordInvalidEnum();
TRACE("\t! Error generated: invalid enum\n");
break;
case GL_INVALID_VALUE:
context->recordInvalidValue();
TRACE("\t! Error generated: invalid value\n");
break;
case GL_INVALID_OPERATION:
context->recordInvalidOperation();
TRACE("\t! Error generated: invalid operation\n");
break;
case GL_OUT_OF_MEMORY:
context->recordOutOfMemory();
TRACE("\t! Error generated: out of memory\n");
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
context->recordInvalidFramebufferOperation();
TRACE("\t! Error generated: invalid framebuffer operation\n");
break;
default: UNREACHABLE();
}
}
}
}
| 010smithzhang-ddd | src/libGLESv2/main.cpp | C++ | bsd | 3,507 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// utilities.h: Conversion functions and other utility routines.
#ifndef LIBGLESV2_UTILITIES_H
#define LIBGLESV2_UTILITIES_H
#define GL_APICALL
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <string>
namespace gl
{
struct Color;
int UniformComponentCount(GLenum type);
GLenum UniformComponentType(GLenum type);
size_t UniformInternalSize(GLenum type);
size_t UniformExternalSize(GLenum type);
int VariableRowCount(GLenum type);
int VariableColumnCount(GLenum type);
int AllocateFirstFreeBits(unsigned int *bits, unsigned int allocationSize, unsigned int bitsSize);
void MakeValidSize(bool isImage, bool isCompressed, GLsizei *requestWidth, GLsizei *requestHeight, int *levelOffset);
int ComputePixelSize(GLint internalformat);
GLsizei ComputePitch(GLsizei width, GLint internalformat, GLint alignment);
GLsizei ComputeCompressedPitch(GLsizei width, GLenum format);
GLsizei ComputeCompressedSize(GLsizei width, GLsizei height, GLenum format);
bool IsCompressed(GLenum format);
bool IsDepthTexture(GLenum format);
bool IsStencilTexture(GLenum format);
bool IsCubemapTextureTarget(GLenum target);
bool IsInternalTextureTarget(GLenum target);
GLint ConvertSizedInternalFormat(GLenum format, GLenum type);
GLenum ExtractFormat(GLenum internalformat);
GLenum ExtractType(GLenum internalformat);
bool IsColorRenderable(GLenum internalformat);
bool IsDepthRenderable(GLenum internalformat);
bool IsStencilRenderable(GLenum internalformat);
bool IsFloat32Format(GLint internalformat);
bool IsFloat16Format(GLint internalformat);
GLuint GetAlphaSize(GLenum colorFormat);
GLuint GetRedSize(GLenum colorFormat);
GLuint GetGreenSize(GLenum colorFormat);
GLuint GetBlueSize(GLenum colorFormat);
GLuint GetDepthSize(GLenum depthFormat);
GLuint GetStencilSize(GLenum stencilFormat);
bool IsTriangleMode(GLenum drawMode);
}
std::string getTempPath();
void writeFile(const char* path, const void* data, size_t size);
#endif // LIBGLESV2_UTILITIES_H
| 010smithzhang-ddd | src/libGLESv2/utilities.h | C++ | bsd | 2,143 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// main.h: Management of thread-local data.
#ifndef LIBGLESV2_MAIN_H_
#define LIBGLESV2_MAIN_H_
#include "common/debug.h"
#include "common/system.h"
namespace egl
{
class Display;
class Surface;
}
namespace gl
{
class Context;
struct Current
{
Context *context;
egl::Display *display;
};
void makeCurrent(Context *context, egl::Display *display, egl::Surface *surface);
Context *getContext();
Context *getNonLostContext();
egl::Display *getDisplay();
void error(GLenum errorCode);
template<class T>
const T &error(GLenum errorCode, const T &returnValue)
{
error(errorCode);
return returnValue;
}
}
namespace rx
{
class Renderer;
}
extern "C"
{
// Exported functions for use by EGL
gl::Context *glCreateContext(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess);
void glDestroyContext(gl::Context *context);
void glMakeCurrent(gl::Context *context, egl::Display *display, egl::Surface *surface);
gl::Context *glGetCurrentContext();
rx::Renderer *glCreateRenderer(egl::Display *display, HDC hDc, EGLNativeDisplayType displayId);
void glDestroyRenderer(rx::Renderer *renderer);
__eglMustCastToProperFunctionPointerType __stdcall glGetProcAddress(const char *procname);
bool __stdcall glBindTexImage(egl::Surface *surface);
}
#endif // LIBGLESV2_MAIN_H_
| 010smithzhang-ddd | src/libGLESv2/main.h | C++ | bsd | 1,517 |
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Program.cpp: Implements the gl::Program class. Implements GL program objects
// and related functionality. [OpenGL ES 2.0.24] section 2.10.3 page 28.
#include "libGLESv2/Program.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/ResourceManager.h"
namespace gl
{
const char * const g_fakepath = "C:\\fakepath";
AttributeBindings::AttributeBindings()
{
}
AttributeBindings::~AttributeBindings()
{
}
InfoLog::InfoLog() : mInfoLog(NULL)
{
}
InfoLog::~InfoLog()
{
delete[] mInfoLog;
}
int InfoLog::getLength() const
{
if (!mInfoLog)
{
return 0;
}
else
{
return strlen(mInfoLog) + 1;
}
}
void InfoLog::getLog(GLsizei bufSize, GLsizei *length, char *infoLog)
{
int index = 0;
if (bufSize > 0)
{
if (mInfoLog)
{
index = std::min(bufSize - 1, (int)strlen(mInfoLog));
memcpy(infoLog, mInfoLog, index);
}
infoLog[index] = '\0';
}
if (length)
{
*length = index;
}
}
// append a santized message to the program info log.
// The D3D compiler includes a fake file path in some of the warning or error
// messages, so lets remove all occurrences of this fake file path from the log.
void InfoLog::appendSanitized(const char *message)
{
std::string msg(message);
size_t found;
do
{
found = msg.find(g_fakepath);
if (found != std::string::npos)
{
msg.erase(found, strlen(g_fakepath));
}
}
while (found != std::string::npos);
append("%s", msg.c_str());
}
void InfoLog::append(const char *format, ...)
{
if (!format)
{
return;
}
char info[1024];
va_list vararg;
va_start(vararg, format);
vsnprintf(info, sizeof(info), format, vararg);
va_end(vararg);
size_t infoLength = strlen(info);
if (!mInfoLog)
{
mInfoLog = new char[infoLength + 2];
strcpy(mInfoLog, info);
strcpy(mInfoLog + infoLength, "\n");
}
else
{
size_t logLength = strlen(mInfoLog);
char *newLog = new char[logLength + infoLength + 2];
strcpy(newLog, mInfoLog);
strcpy(newLog + logLength, info);
strcpy(newLog + logLength + infoLength, "\n");
delete[] mInfoLog;
mInfoLog = newLog;
}
}
void InfoLog::reset()
{
if (mInfoLog)
{
delete [] mInfoLog;
mInfoLog = NULL;
}
}
Program::Program(rx::Renderer *renderer, ResourceManager *manager, GLuint handle) : mResourceManager(manager), mHandle(handle)
{
mFragmentShader = NULL;
mVertexShader = NULL;
mProgramBinary.set(NULL);
mDeleteStatus = false;
mLinked = false;
mRefCount = 0;
mRenderer = renderer;
}
Program::~Program()
{
unlink(true);
if (mVertexShader != NULL)
{
mVertexShader->release();
}
if (mFragmentShader != NULL)
{
mFragmentShader->release();
}
}
bool Program::attachShader(Shader *shader)
{
if (shader->getType() == GL_VERTEX_SHADER)
{
if (mVertexShader)
{
return false;
}
mVertexShader = (VertexShader*)shader;
mVertexShader->addRef();
}
else if (shader->getType() == GL_FRAGMENT_SHADER)
{
if (mFragmentShader)
{
return false;
}
mFragmentShader = (FragmentShader*)shader;
mFragmentShader->addRef();
}
else UNREACHABLE();
return true;
}
bool Program::detachShader(Shader *shader)
{
if (shader->getType() == GL_VERTEX_SHADER)
{
if (mVertexShader != shader)
{
return false;
}
mVertexShader->release();
mVertexShader = NULL;
}
else if (shader->getType() == GL_FRAGMENT_SHADER)
{
if (mFragmentShader != shader)
{
return false;
}
mFragmentShader->release();
mFragmentShader = NULL;
}
else UNREACHABLE();
return true;
}
int Program::getAttachedShadersCount() const
{
return (mVertexShader ? 1 : 0) + (mFragmentShader ? 1 : 0);
}
void AttributeBindings::bindAttributeLocation(GLuint index, const char *name)
{
if (index < MAX_VERTEX_ATTRIBS)
{
for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
{
mAttributeBinding[i].erase(name);
}
mAttributeBinding[index].insert(name);
}
}
void Program::bindAttributeLocation(GLuint index, const char *name)
{
mAttributeBindings.bindAttributeLocation(index, name);
}
// Links the HLSL code of the vertex and pixel shader by matching up their varyings,
// compiling them into binaries, determining the attribute mappings, and collecting
// a list of uniforms
bool Program::link()
{
unlink(false);
mInfoLog.reset();
mProgramBinary.set(new ProgramBinary(mRenderer));
mLinked = mProgramBinary->link(mInfoLog, mAttributeBindings, mFragmentShader, mVertexShader);
return mLinked;
}
int AttributeBindings::getAttributeBinding(const std::string &name) const
{
for (int location = 0; location < MAX_VERTEX_ATTRIBS; location++)
{
if (mAttributeBinding[location].find(name) != mAttributeBinding[location].end())
{
return location;
}
}
return -1;
}
// Returns the program object to an unlinked state, before re-linking, or at destruction
void Program::unlink(bool destroy)
{
if (destroy) // Object being destructed
{
if (mFragmentShader)
{
mFragmentShader->release();
mFragmentShader = NULL;
}
if (mVertexShader)
{
mVertexShader->release();
mVertexShader = NULL;
}
}
mProgramBinary.set(NULL);
mLinked = false;
}
bool Program::isLinked()
{
return mLinked;
}
ProgramBinary* Program::getProgramBinary()
{
return mProgramBinary.get();
}
bool Program::setProgramBinary(const void *binary, GLsizei length)
{
unlink(false);
mInfoLog.reset();
mProgramBinary.set(new ProgramBinary(mRenderer));
mLinked = mProgramBinary->load(mInfoLog, binary, length);
if (!mLinked)
{
mProgramBinary.set(NULL);
}
return mLinked;
}
void Program::release()
{
mRefCount--;
if (mRefCount == 0 && mDeleteStatus)
{
mResourceManager->deleteProgram(mHandle);
}
}
void Program::addRef()
{
mRefCount++;
}
unsigned int Program::getRefCount() const
{
return mRefCount;
}
GLint Program::getProgramBinaryLength() const
{
ProgramBinary *programBinary = mProgramBinary.get();
if (programBinary)
{
return programBinary->getLength();
}
else
{
return 0;
}
}
int Program::getInfoLogLength() const
{
return mInfoLog.getLength();
}
void Program::getInfoLog(GLsizei bufSize, GLsizei *length, char *infoLog)
{
return mInfoLog.getLog(bufSize, length, infoLog);
}
void Program::getAttachedShaders(GLsizei maxCount, GLsizei *count, GLuint *shaders)
{
int total = 0;
if (mVertexShader)
{
if (total < maxCount)
{
shaders[total] = mVertexShader->getHandle();
}
total++;
}
if (mFragmentShader)
{
if (total < maxCount)
{
shaders[total] = mFragmentShader->getHandle();
}
total++;
}
if (count)
{
*count = total;
}
}
void Program::getActiveAttribute(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name)
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
programBinary->getActiveAttribute(index, bufsize, length, size, type, name);
}
else
{
if (bufsize > 0)
{
name[0] = '\0';
}
if (length)
{
*length = 0;
}
*type = GL_NONE;
*size = 1;
}
}
GLint Program::getActiveAttributeCount()
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
return programBinary->getActiveAttributeCount();
}
else
{
return 0;
}
}
GLint Program::getActiveAttributeMaxLength()
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
return programBinary->getActiveAttributeMaxLength();
}
else
{
return 0;
}
}
void Program::getActiveUniform(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name)
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
return programBinary->getActiveUniform(index, bufsize, length, size, type, name);
}
else
{
if (bufsize > 0)
{
name[0] = '\0';
}
if (length)
{
*length = 0;
}
*size = 0;
*type = GL_NONE;
}
}
GLint Program::getActiveUniformCount()
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
return programBinary->getActiveUniformCount();
}
else
{
return 0;
}
}
GLint Program::getActiveUniformMaxLength()
{
ProgramBinary *programBinary = getProgramBinary();
if (programBinary)
{
return programBinary->getActiveUniformMaxLength();
}
else
{
return 0;
}
}
void Program::flagForDeletion()
{
mDeleteStatus = true;
}
bool Program::isFlaggedForDeletion() const
{
return mDeleteStatus;
}
void Program::validate()
{
mInfoLog.reset();
ProgramBinary *programBinary = getProgramBinary();
if (isLinked() && programBinary)
{
programBinary->validate(mInfoLog);
}
else
{
mInfoLog.append("Program has not been successfully linked.");
}
}
bool Program::isValidated() const
{
ProgramBinary *programBinary = mProgramBinary.get();
if (programBinary)
{
return programBinary->isValidated();
}
else
{
return false;
}
}
}
| 010smithzhang-ddd | src/libGLESv2/Program.cpp | C++ | bsd | 10,217 |
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Context.cpp: Implements the gl::Context class, managing all GL state and performing
// rendering operations. It is the GLES2 specific implementation of EGLContext.
#include "libGLESv2/Context.h"
#include "libGLESv2/main.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/Fence.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/Query.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/ResourceManager.h"
#include "libGLESv2/renderer/IndexDataManager.h"
#include "libGLESv2/renderer/RenderTarget.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libEGL/Surface.h"
#undef near
#undef far
namespace gl
{
static const char* makeStaticString(const std::string& str)
{
static std::set<std::string> strings;
std::set<std::string>::iterator it = strings.find(str);
if (it != strings.end())
return it->c_str();
return strings.insert(str).first->c_str();
}
Context::Context(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess) : mRenderer(renderer)
{
ASSERT(robustAccess == false); // Unimplemented
mFenceHandleAllocator.setBaseHandle(0);
setClearColor(0.0f, 0.0f, 0.0f, 0.0f);
mState.depthClearValue = 1.0f;
mState.stencilClearValue = 0;
mState.rasterizer.cullFace = false;
mState.rasterizer.cullMode = GL_BACK;
mState.rasterizer.frontFace = GL_CCW;
mState.rasterizer.polygonOffsetFill = false;
mState.rasterizer.polygonOffsetFactor = 0.0f;
mState.rasterizer.polygonOffsetUnits = 0.0f;
mState.rasterizer.pointDrawMode = false;
mState.rasterizer.multiSample = false;
mState.scissorTest = false;
mState.scissor.x = 0;
mState.scissor.y = 0;
mState.scissor.width = 0;
mState.scissor.height = 0;
mState.blend.blend = false;
mState.blend.sourceBlendRGB = GL_ONE;
mState.blend.sourceBlendAlpha = GL_ONE;
mState.blend.destBlendRGB = GL_ZERO;
mState.blend.destBlendAlpha = GL_ZERO;
mState.blend.blendEquationRGB = GL_FUNC_ADD;
mState.blend.blendEquationAlpha = GL_FUNC_ADD;
mState.blend.sampleAlphaToCoverage = false;
mState.blend.dither = true;
mState.blendColor.red = 0;
mState.blendColor.green = 0;
mState.blendColor.blue = 0;
mState.blendColor.alpha = 0;
mState.depthStencil.depthTest = false;
mState.depthStencil.depthFunc = GL_LESS;
mState.depthStencil.depthMask = true;
mState.depthStencil.stencilTest = false;
mState.depthStencil.stencilFunc = GL_ALWAYS;
mState.depthStencil.stencilMask = -1;
mState.depthStencil.stencilWritemask = -1;
mState.depthStencil.stencilBackFunc = GL_ALWAYS;
mState.depthStencil.stencilBackMask = - 1;
mState.depthStencil.stencilBackWritemask = -1;
mState.depthStencil.stencilFail = GL_KEEP;
mState.depthStencil.stencilPassDepthFail = GL_KEEP;
mState.depthStencil.stencilPassDepthPass = GL_KEEP;
mState.depthStencil.stencilBackFail = GL_KEEP;
mState.depthStencil.stencilBackPassDepthFail = GL_KEEP;
mState.depthStencil.stencilBackPassDepthPass = GL_KEEP;
mState.stencilRef = 0;
mState.stencilBackRef = 0;
mState.sampleCoverage = false;
mState.sampleCoverageValue = 1.0f;
mState.sampleCoverageInvert = false;
mState.generateMipmapHint = GL_DONT_CARE;
mState.fragmentShaderDerivativeHint = GL_DONT_CARE;
mState.lineWidth = 1.0f;
mState.viewport.x = 0;
mState.viewport.y = 0;
mState.viewport.width = 0;
mState.viewport.height = 0;
mState.zNear = 0.0f;
mState.zFar = 1.0f;
mState.blend.colorMaskRed = true;
mState.blend.colorMaskGreen = true;
mState.blend.colorMaskBlue = true;
mState.blend.colorMaskAlpha = true;
if (shareContext != NULL)
{
mResourceManager = shareContext->mResourceManager;
mResourceManager->addRef();
}
else
{
mResourceManager = new ResourceManager(mRenderer);
}
// [OpenGL ES 2.0.24] section 3.7 page 83:
// In the initial state, TEXTURE_2D and TEXTURE_CUBE_MAP have twodimensional
// and cube map texture state vectors respectively associated with them.
// In order that access to these initial textures not be lost, they are treated as texture
// objects all of whose names are 0.
mTexture2DZero.set(new Texture2D(mRenderer, 0));
mTextureCubeMapZero.set(new TextureCubeMap(mRenderer, 0));
mState.activeSampler = 0;
bindArrayBuffer(0);
bindElementArrayBuffer(0);
bindTextureCubeMap(0);
bindTexture2D(0);
bindReadFramebuffer(0);
bindDrawFramebuffer(0);
bindRenderbuffer(0);
mState.currentProgram = 0;
mCurrentProgramBinary.set(NULL);
mState.packAlignment = 4;
mState.unpackAlignment = 4;
mState.packReverseRowOrder = false;
mExtensionString = NULL;
mRendererString = NULL;
mInvalidEnum = false;
mInvalidValue = false;
mInvalidOperation = false;
mOutOfMemory = false;
mInvalidFramebufferOperation = false;
mHasBeenCurrent = false;
mContextLost = false;
mResetStatus = GL_NO_ERROR;
mResetStrategy = (notifyResets ? GL_LOSE_CONTEXT_ON_RESET_EXT : GL_NO_RESET_NOTIFICATION_EXT);
mRobustAccess = robustAccess;
mSupportsBGRATextures = false;
mSupportsDXT1Textures = false;
mSupportsDXT3Textures = false;
mSupportsDXT5Textures = false;
mSupportsEventQueries = false;
mSupportsOcclusionQueries = false;
mNumCompressedTextureFormats = 0;
}
Context::~Context()
{
if (mState.currentProgram != 0)
{
Program *programObject = mResourceManager->getProgram(mState.currentProgram);
if (programObject)
{
programObject->release();
}
mState.currentProgram = 0;
}
mCurrentProgramBinary.set(NULL);
while (!mFramebufferMap.empty())
{
deleteFramebuffer(mFramebufferMap.begin()->first);
}
while (!mFenceMap.empty())
{
deleteFence(mFenceMap.begin()->first);
}
while (!mQueryMap.empty())
{
deleteQuery(mQueryMap.begin()->first);
}
for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
{
for (int sampler = 0; sampler < IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
{
mState.samplerTexture[type][sampler].set(NULL);
}
}
for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
{
mIncompleteTextures[type].set(NULL);
}
for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
{
mState.vertexAttribute[i].mBoundBuffer.set(NULL);
}
for (int i = 0; i < QUERY_TYPE_COUNT; i++)
{
mState.activeQuery[i].set(NULL);
}
mState.arrayBuffer.set(NULL);
mState.elementArrayBuffer.set(NULL);
mState.renderbuffer.set(NULL);
mTexture2DZero.set(NULL);
mTextureCubeMapZero.set(NULL);
mResourceManager->release();
}
void Context::makeCurrent(egl::Surface *surface)
{
if (!mHasBeenCurrent)
{
mMajorShaderModel = mRenderer->getMajorShaderModel();
mMaximumPointSize = mRenderer->getMaxPointSize();
mSupportsVertexTexture = mRenderer->getVertexTextureSupport();
mSupportsNonPower2Texture = mRenderer->getNonPower2TextureSupport();
mSupportsInstancing = mRenderer->getInstancingSupport();
mMaxViewportDimension = mRenderer->getMaxViewportDimension();
mMaxTextureDimension = std::min(std::min(mRenderer->getMaxTextureWidth(), mRenderer->getMaxTextureHeight()),
(int)gl::IMPLEMENTATION_MAX_TEXTURE_SIZE);
mMaxCubeTextureDimension = std::min(mMaxTextureDimension, (int)gl::IMPLEMENTATION_MAX_CUBE_MAP_TEXTURE_SIZE);
mMaxRenderbufferDimension = mMaxTextureDimension;
mMaxTextureLevel = log2(mMaxTextureDimension) + 1;
mMaxTextureAnisotropy = mRenderer->getTextureMaxAnisotropy();
TRACE("MaxTextureDimension=%d, MaxCubeTextureDimension=%d, MaxRenderbufferDimension=%d, MaxTextureLevel=%d, MaxTextureAnisotropy=%f",
mMaxTextureDimension, mMaxCubeTextureDimension, mMaxRenderbufferDimension, mMaxTextureLevel, mMaxTextureAnisotropy);
mSupportsEventQueries = mRenderer->getEventQuerySupport();
mSupportsOcclusionQueries = mRenderer->getOcclusionQuerySupport();
mSupportsBGRATextures = mRenderer->getBGRATextureSupport();
mSupportsDXT1Textures = mRenderer->getDXT1TextureSupport();
mSupportsDXT3Textures = mRenderer->getDXT3TextureSupport();
mSupportsDXT5Textures = mRenderer->getDXT5TextureSupport();
mSupportsFloat32Textures = mRenderer->getFloat32TextureSupport(&mSupportsFloat32LinearFilter, &mSupportsFloat32RenderableTextures);
mSupportsFloat16Textures = mRenderer->getFloat16TextureSupport(&mSupportsFloat16LinearFilter, &mSupportsFloat16RenderableTextures);
mSupportsLuminanceTextures = mRenderer->getLuminanceTextureSupport();
mSupportsLuminanceAlphaTextures = mRenderer->getLuminanceAlphaTextureSupport();
mSupportsDepthTextures = mRenderer->getDepthTextureSupport();
mSupportsTextureFilterAnisotropy = mRenderer->getTextureFilterAnisotropySupport();
mSupports32bitIndices = mRenderer->get32BitIndexSupport();
mNumCompressedTextureFormats = 0;
if (supportsDXT1Textures())
{
mNumCompressedTextureFormats += 2;
}
if (supportsDXT3Textures())
{
mNumCompressedTextureFormats += 1;
}
if (supportsDXT5Textures())
{
mNumCompressedTextureFormats += 1;
}
initExtensionString();
initRendererString();
mState.viewport.x = 0;
mState.viewport.y = 0;
mState.viewport.width = surface->getWidth();
mState.viewport.height = surface->getHeight();
mState.scissor.x = 0;
mState.scissor.y = 0;
mState.scissor.width = surface->getWidth();
mState.scissor.height = surface->getHeight();
mHasBeenCurrent = true;
}
// Wrap the existing swapchain resources into GL objects and assign them to the '0' names
rx::SwapChain *swapchain = surface->getSwapChain();
Colorbuffer *colorbufferZero = new Colorbuffer(mRenderer, swapchain);
DepthStencilbuffer *depthStencilbufferZero = new DepthStencilbuffer(mRenderer, swapchain);
Framebuffer *framebufferZero = new DefaultFramebuffer(mRenderer, colorbufferZero, depthStencilbufferZero);
setFramebufferZero(framebufferZero);
}
// NOTE: this function should not assume that this context is current!
void Context::markContextLost()
{
if (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT)
mResetStatus = GL_UNKNOWN_CONTEXT_RESET_EXT;
mContextLost = true;
}
bool Context::isContextLost()
{
return mContextLost;
}
void Context::setClearColor(float red, float green, float blue, float alpha)
{
mState.colorClearValue.red = red;
mState.colorClearValue.green = green;
mState.colorClearValue.blue = blue;
mState.colorClearValue.alpha = alpha;
}
void Context::setClearDepth(float depth)
{
mState.depthClearValue = depth;
}
void Context::setClearStencil(int stencil)
{
mState.stencilClearValue = stencil;
}
void Context::setCullFace(bool enabled)
{
mState.rasterizer.cullFace = enabled;
}
bool Context::isCullFaceEnabled() const
{
return mState.rasterizer.cullFace;
}
void Context::setCullMode(GLenum mode)
{
mState.rasterizer.cullMode = mode;
}
void Context::setFrontFace(GLenum front)
{
mState.rasterizer.frontFace = front;
}
void Context::setDepthTest(bool enabled)
{
mState.depthStencil.depthTest = enabled;
}
bool Context::isDepthTestEnabled() const
{
return mState.depthStencil.depthTest;
}
void Context::setDepthFunc(GLenum depthFunc)
{
mState.depthStencil.depthFunc = depthFunc;
}
void Context::setDepthRange(float zNear, float zFar)
{
mState.zNear = zNear;
mState.zFar = zFar;
}
void Context::setBlend(bool enabled)
{
mState.blend.blend = enabled;
}
bool Context::isBlendEnabled() const
{
return mState.blend.blend;
}
void Context::setBlendFactors(GLenum sourceRGB, GLenum destRGB, GLenum sourceAlpha, GLenum destAlpha)
{
mState.blend.sourceBlendRGB = sourceRGB;
mState.blend.destBlendRGB = destRGB;
mState.blend.sourceBlendAlpha = sourceAlpha;
mState.blend.destBlendAlpha = destAlpha;
}
void Context::setBlendColor(float red, float green, float blue, float alpha)
{
mState.blendColor.red = red;
mState.blendColor.green = green;
mState.blendColor.blue = blue;
mState.blendColor.alpha = alpha;
}
void Context::setBlendEquation(GLenum rgbEquation, GLenum alphaEquation)
{
mState.blend.blendEquationRGB = rgbEquation;
mState.blend.blendEquationAlpha = alphaEquation;
}
void Context::setStencilTest(bool enabled)
{
mState.depthStencil.stencilTest = enabled;
}
bool Context::isStencilTestEnabled() const
{
return mState.depthStencil.stencilTest;
}
void Context::setStencilParams(GLenum stencilFunc, GLint stencilRef, GLuint stencilMask)
{
mState.depthStencil.stencilFunc = stencilFunc;
mState.stencilRef = (stencilRef > 0) ? stencilRef : 0;
mState.depthStencil.stencilMask = stencilMask;
}
void Context::setStencilBackParams(GLenum stencilBackFunc, GLint stencilBackRef, GLuint stencilBackMask)
{
mState.depthStencil.stencilBackFunc = stencilBackFunc;
mState.stencilBackRef = (stencilBackRef > 0) ? stencilBackRef : 0;
mState.depthStencil.stencilBackMask = stencilBackMask;
}
void Context::setStencilWritemask(GLuint stencilWritemask)
{
mState.depthStencil.stencilWritemask = stencilWritemask;
}
void Context::setStencilBackWritemask(GLuint stencilBackWritemask)
{
mState.depthStencil.stencilBackWritemask = stencilBackWritemask;
}
void Context::setStencilOperations(GLenum stencilFail, GLenum stencilPassDepthFail, GLenum stencilPassDepthPass)
{
mState.depthStencil.stencilFail = stencilFail;
mState.depthStencil.stencilPassDepthFail = stencilPassDepthFail;
mState.depthStencil.stencilPassDepthPass = stencilPassDepthPass;
}
void Context::setStencilBackOperations(GLenum stencilBackFail, GLenum stencilBackPassDepthFail, GLenum stencilBackPassDepthPass)
{
mState.depthStencil.stencilBackFail = stencilBackFail;
mState.depthStencil.stencilBackPassDepthFail = stencilBackPassDepthFail;
mState.depthStencil.stencilBackPassDepthPass = stencilBackPassDepthPass;
}
void Context::setPolygonOffsetFill(bool enabled)
{
mState.rasterizer.polygonOffsetFill = enabled;
}
bool Context::isPolygonOffsetFillEnabled() const
{
return mState.rasterizer.polygonOffsetFill;
}
void Context::setPolygonOffsetParams(GLfloat factor, GLfloat units)
{
// An application can pass NaN values here, so handle this gracefully
mState.rasterizer.polygonOffsetFactor = factor != factor ? 0.0f : factor;
mState.rasterizer.polygonOffsetUnits = units != units ? 0.0f : units;
}
void Context::setSampleAlphaToCoverage(bool enabled)
{
mState.blend.sampleAlphaToCoverage = enabled;
}
bool Context::isSampleAlphaToCoverageEnabled() const
{
return mState.blend.sampleAlphaToCoverage;
}
void Context::setSampleCoverage(bool enabled)
{
mState.sampleCoverage = enabled;
}
bool Context::isSampleCoverageEnabled() const
{
return mState.sampleCoverage;
}
void Context::setSampleCoverageParams(GLclampf value, bool invert)
{
mState.sampleCoverageValue = value;
mState.sampleCoverageInvert = invert;
}
void Context::setScissorTest(bool enabled)
{
mState.scissorTest = enabled;
}
bool Context::isScissorTestEnabled() const
{
return mState.scissorTest;
}
void Context::setDither(bool enabled)
{
mState.blend.dither = enabled;
}
bool Context::isDitherEnabled() const
{
return mState.blend.dither;
}
void Context::setLineWidth(GLfloat width)
{
mState.lineWidth = width;
}
void Context::setGenerateMipmapHint(GLenum hint)
{
mState.generateMipmapHint = hint;
}
void Context::setFragmentShaderDerivativeHint(GLenum hint)
{
mState.fragmentShaderDerivativeHint = hint;
// TODO: Propagate the hint to shader translator so we can write
// ddx, ddx_coarse, or ddx_fine depending on the hint.
// Ignore for now. It is valid for implementations to ignore hint.
}
void Context::setViewportParams(GLint x, GLint y, GLsizei width, GLsizei height)
{
mState.viewport.x = x;
mState.viewport.y = y;
mState.viewport.width = width;
mState.viewport.height = height;
}
void Context::setScissorParams(GLint x, GLint y, GLsizei width, GLsizei height)
{
mState.scissor.x = x;
mState.scissor.y = y;
mState.scissor.width = width;
mState.scissor.height = height;
}
void Context::setColorMask(bool red, bool green, bool blue, bool alpha)
{
mState.blend.colorMaskRed = red;
mState.blend.colorMaskGreen = green;
mState.blend.colorMaskBlue = blue;
mState.blend.colorMaskAlpha = alpha;
}
void Context::setDepthMask(bool mask)
{
mState.depthStencil.depthMask = mask;
}
void Context::setActiveSampler(unsigned int active)
{
mState.activeSampler = active;
}
GLuint Context::getReadFramebufferHandle() const
{
return mState.readFramebuffer;
}
GLuint Context::getDrawFramebufferHandle() const
{
return mState.drawFramebuffer;
}
GLuint Context::getRenderbufferHandle() const
{
return mState.renderbuffer.id();
}
GLuint Context::getArrayBufferHandle() const
{
return mState.arrayBuffer.id();
}
GLuint Context::getActiveQuery(GLenum target) const
{
Query *queryObject = NULL;
switch (target)
{
case GL_ANY_SAMPLES_PASSED_EXT:
queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED].get();
break;
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE].get();
break;
default:
ASSERT(false);
}
if (queryObject)
{
return queryObject->id();
}
else
{
return 0;
}
}
void Context::setEnableVertexAttribArray(unsigned int attribNum, bool enabled)
{
mState.vertexAttribute[attribNum].mArrayEnabled = enabled;
}
const VertexAttribute &Context::getVertexAttribState(unsigned int attribNum)
{
return mState.vertexAttribute[attribNum];
}
void Context::setVertexAttribState(unsigned int attribNum, Buffer *boundBuffer, GLint size, GLenum type, bool normalized,
GLsizei stride, const void *pointer)
{
mState.vertexAttribute[attribNum].mBoundBuffer.set(boundBuffer);
mState.vertexAttribute[attribNum].mSize = size;
mState.vertexAttribute[attribNum].mType = type;
mState.vertexAttribute[attribNum].mNormalized = normalized;
mState.vertexAttribute[attribNum].mStride = stride;
mState.vertexAttribute[attribNum].mPointer = pointer;
}
const void *Context::getVertexAttribPointer(unsigned int attribNum) const
{
return mState.vertexAttribute[attribNum].mPointer;
}
void Context::setPackAlignment(GLint alignment)
{
mState.packAlignment = alignment;
}
GLint Context::getPackAlignment() const
{
return mState.packAlignment;
}
void Context::setUnpackAlignment(GLint alignment)
{
mState.unpackAlignment = alignment;
}
GLint Context::getUnpackAlignment() const
{
return mState.unpackAlignment;
}
void Context::setPackReverseRowOrder(bool reverseRowOrder)
{
mState.packReverseRowOrder = reverseRowOrder;
}
bool Context::getPackReverseRowOrder() const
{
return mState.packReverseRowOrder;
}
GLuint Context::createBuffer()
{
return mResourceManager->createBuffer();
}
GLuint Context::createProgram()
{
return mResourceManager->createProgram();
}
GLuint Context::createShader(GLenum type)
{
return mResourceManager->createShader(type);
}
GLuint Context::createTexture()
{
return mResourceManager->createTexture();
}
GLuint Context::createRenderbuffer()
{
return mResourceManager->createRenderbuffer();
}
// Returns an unused framebuffer name
GLuint Context::createFramebuffer()
{
GLuint handle = mFramebufferHandleAllocator.allocate();
mFramebufferMap[handle] = NULL;
return handle;
}
GLuint Context::createFence()
{
GLuint handle = mFenceHandleAllocator.allocate();
mFenceMap[handle] = new Fence(mRenderer);
return handle;
}
// Returns an unused query name
GLuint Context::createQuery()
{
GLuint handle = mQueryHandleAllocator.allocate();
mQueryMap[handle] = NULL;
return handle;
}
void Context::deleteBuffer(GLuint buffer)
{
if (mResourceManager->getBuffer(buffer))
{
detachBuffer(buffer);
}
mResourceManager->deleteBuffer(buffer);
}
void Context::deleteShader(GLuint shader)
{
mResourceManager->deleteShader(shader);
}
void Context::deleteProgram(GLuint program)
{
mResourceManager->deleteProgram(program);
}
void Context::deleteTexture(GLuint texture)
{
if (mResourceManager->getTexture(texture))
{
detachTexture(texture);
}
mResourceManager->deleteTexture(texture);
}
void Context::deleteRenderbuffer(GLuint renderbuffer)
{
if (mResourceManager->getRenderbuffer(renderbuffer))
{
detachRenderbuffer(renderbuffer);
}
mResourceManager->deleteRenderbuffer(renderbuffer);
}
void Context::deleteFramebuffer(GLuint framebuffer)
{
FramebufferMap::iterator framebufferObject = mFramebufferMap.find(framebuffer);
if (framebufferObject != mFramebufferMap.end())
{
detachFramebuffer(framebuffer);
mFramebufferHandleAllocator.release(framebufferObject->first);
delete framebufferObject->second;
mFramebufferMap.erase(framebufferObject);
}
}
void Context::deleteFence(GLuint fence)
{
FenceMap::iterator fenceObject = mFenceMap.find(fence);
if (fenceObject != mFenceMap.end())
{
mFenceHandleAllocator.release(fenceObject->first);
delete fenceObject->second;
mFenceMap.erase(fenceObject);
}
}
void Context::deleteQuery(GLuint query)
{
QueryMap::iterator queryObject = mQueryMap.find(query);
if (queryObject != mQueryMap.end())
{
mQueryHandleAllocator.release(queryObject->first);
if (queryObject->second)
{
queryObject->second->release();
}
mQueryMap.erase(queryObject);
}
}
Buffer *Context::getBuffer(GLuint handle)
{
return mResourceManager->getBuffer(handle);
}
Shader *Context::getShader(GLuint handle)
{
return mResourceManager->getShader(handle);
}
Program *Context::getProgram(GLuint handle)
{
return mResourceManager->getProgram(handle);
}
Texture *Context::getTexture(GLuint handle)
{
return mResourceManager->getTexture(handle);
}
Renderbuffer *Context::getRenderbuffer(GLuint handle)
{
return mResourceManager->getRenderbuffer(handle);
}
Framebuffer *Context::getReadFramebuffer()
{
return getFramebuffer(mState.readFramebuffer);
}
Framebuffer *Context::getDrawFramebuffer()
{
return mBoundDrawFramebuffer;
}
void Context::bindArrayBuffer(unsigned int buffer)
{
mResourceManager->checkBufferAllocation(buffer);
mState.arrayBuffer.set(getBuffer(buffer));
}
void Context::bindElementArrayBuffer(unsigned int buffer)
{
mResourceManager->checkBufferAllocation(buffer);
mState.elementArrayBuffer.set(getBuffer(buffer));
}
void Context::bindTexture2D(GLuint texture)
{
mResourceManager->checkTextureAllocation(texture, TEXTURE_2D);
mState.samplerTexture[TEXTURE_2D][mState.activeSampler].set(getTexture(texture));
}
void Context::bindTextureCubeMap(GLuint texture)
{
mResourceManager->checkTextureAllocation(texture, TEXTURE_CUBE);
mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].set(getTexture(texture));
}
void Context::bindReadFramebuffer(GLuint framebuffer)
{
if (!getFramebuffer(framebuffer))
{
mFramebufferMap[framebuffer] = new Framebuffer(mRenderer);
}
mState.readFramebuffer = framebuffer;
}
void Context::bindDrawFramebuffer(GLuint framebuffer)
{
if (!getFramebuffer(framebuffer))
{
mFramebufferMap[framebuffer] = new Framebuffer(mRenderer);
}
mState.drawFramebuffer = framebuffer;
mBoundDrawFramebuffer = getFramebuffer(framebuffer);
}
void Context::bindRenderbuffer(GLuint renderbuffer)
{
mResourceManager->checkRenderbufferAllocation(renderbuffer);
mState.renderbuffer.set(getRenderbuffer(renderbuffer));
}
void Context::useProgram(GLuint program)
{
GLuint priorProgram = mState.currentProgram;
mState.currentProgram = program; // Must switch before trying to delete, otherwise it only gets flagged.
if (priorProgram != program)
{
Program *newProgram = mResourceManager->getProgram(program);
Program *oldProgram = mResourceManager->getProgram(priorProgram);
mCurrentProgramBinary.set(NULL);
if (newProgram)
{
newProgram->addRef();
mCurrentProgramBinary.set(newProgram->getProgramBinary());
}
if (oldProgram)
{
oldProgram->release();
}
}
}
void Context::linkProgram(GLuint program)
{
Program *programObject = mResourceManager->getProgram(program);
bool linked = programObject->link();
// if the current program was relinked successfully we
// need to install the new executables
if (linked && program == mState.currentProgram)
{
mCurrentProgramBinary.set(programObject->getProgramBinary());
}
}
void Context::setProgramBinary(GLuint program, const void *binary, GLint length)
{
Program *programObject = mResourceManager->getProgram(program);
bool loaded = programObject->setProgramBinary(binary, length);
// if the current program was reloaded successfully we
// need to install the new executables
if (loaded && program == mState.currentProgram)
{
mCurrentProgramBinary.set(programObject->getProgramBinary());
}
}
void Context::beginQuery(GLenum target, GLuint query)
{
// From EXT_occlusion_query_boolean: If BeginQueryEXT is called with an <id>
// of zero, if the active query object name for <target> is non-zero (for the
// targets ANY_SAMPLES_PASSED_EXT and ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, if
// the active query for either target is non-zero), if <id> is the name of an
// existing query object whose type does not match <target>, or if <id> is the
// active query object name for any query type, the error INVALID_OPERATION is
// generated.
// Ensure no other queries are active
// NOTE: If other queries than occlusion are supported, we will need to check
// separately that:
// a) The query ID passed is not the current active query for any target/type
// b) There are no active queries for the requested target (and in the case
// of GL_ANY_SAMPLES_PASSED_EXT and GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT,
// no query may be active for either if glBeginQuery targets either.
for (int i = 0; i < QUERY_TYPE_COUNT; i++)
{
if (mState.activeQuery[i].get() != NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
}
QueryType qType;
switch (target)
{
case GL_ANY_SAMPLES_PASSED_EXT:
qType = QUERY_ANY_SAMPLES_PASSED;
break;
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
break;
default:
ASSERT(false);
return;
}
Query *queryObject = getQuery(query, true, target);
// check that name was obtained with glGenQueries
if (!queryObject)
{
return gl::error(GL_INVALID_OPERATION);
}
// check for type mismatch
if (queryObject->getType() != target)
{
return gl::error(GL_INVALID_OPERATION);
}
// set query as active for specified target
mState.activeQuery[qType].set(queryObject);
// begin query
queryObject->begin();
}
void Context::endQuery(GLenum target)
{
QueryType qType;
switch (target)
{
case GL_ANY_SAMPLES_PASSED_EXT:
qType = QUERY_ANY_SAMPLES_PASSED;
break;
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
break;
default:
ASSERT(false);
return;
}
Query *queryObject = mState.activeQuery[qType].get();
if (queryObject == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
queryObject->end();
mState.activeQuery[qType].set(NULL);
}
void Context::setFramebufferZero(Framebuffer *buffer)
{
delete mFramebufferMap[0];
mFramebufferMap[0] = buffer;
if (mState.drawFramebuffer == 0)
{
mBoundDrawFramebuffer = buffer;
}
}
void Context::setRenderbufferStorage(GLsizei width, GLsizei height, GLenum internalformat, GLsizei samples)
{
RenderbufferStorage *renderbuffer = NULL;
switch (internalformat)
{
case GL_DEPTH_COMPONENT16:
renderbuffer = new gl::Depthbuffer(mRenderer, width, height, samples);
break;
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
renderbuffer = new gl::Colorbuffer(mRenderer,width, height, internalformat, samples);
break;
case GL_STENCIL_INDEX8:
renderbuffer = new gl::Stencilbuffer(mRenderer, width, height, samples);
break;
case GL_DEPTH24_STENCIL8_OES:
renderbuffer = new gl::DepthStencilbuffer(mRenderer, width, height, samples);
break;
default:
UNREACHABLE(); return;
}
Renderbuffer *renderbufferObject = mState.renderbuffer.get();
renderbufferObject->setStorage(renderbuffer);
}
Framebuffer *Context::getFramebuffer(unsigned int handle)
{
FramebufferMap::iterator framebuffer = mFramebufferMap.find(handle);
if (framebuffer == mFramebufferMap.end())
{
return NULL;
}
else
{
return framebuffer->second;
}
}
Fence *Context::getFence(unsigned int handle)
{
FenceMap::iterator fence = mFenceMap.find(handle);
if (fence == mFenceMap.end())
{
return NULL;
}
else
{
return fence->second;
}
}
Query *Context::getQuery(unsigned int handle, bool create, GLenum type)
{
QueryMap::iterator query = mQueryMap.find(handle);
if (query == mQueryMap.end())
{
return NULL;
}
else
{
if (!query->second && create)
{
query->second = new Query(mRenderer, type, handle);
query->second->addRef();
}
return query->second;
}
}
Buffer *Context::getArrayBuffer()
{
return mState.arrayBuffer.get();
}
Buffer *Context::getElementArrayBuffer()
{
return mState.elementArrayBuffer.get();
}
ProgramBinary *Context::getCurrentProgramBinary()
{
return mCurrentProgramBinary.get();
}
Texture2D *Context::getTexture2D()
{
return static_cast<Texture2D*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D));
}
TextureCubeMap *Context::getTextureCubeMap()
{
return static_cast<TextureCubeMap*>(getSamplerTexture(mState.activeSampler, TEXTURE_CUBE));
}
Texture *Context::getSamplerTexture(unsigned int sampler, TextureType type)
{
GLuint texid = mState.samplerTexture[type][sampler].id();
if (texid == 0) // Special case: 0 refers to different initial textures based on the target
{
switch (type)
{
default: UNREACHABLE();
case TEXTURE_2D: return mTexture2DZero.get();
case TEXTURE_CUBE: return mTextureCubeMapZero.get();
}
}
return mState.samplerTexture[type][sampler].get();
}
bool Context::getBooleanv(GLenum pname, GLboolean *params)
{
switch (pname)
{
case GL_SHADER_COMPILER: *params = GL_TRUE; break;
case GL_SAMPLE_COVERAGE_INVERT: *params = mState.sampleCoverageInvert; break;
case GL_DEPTH_WRITEMASK: *params = mState.depthStencil.depthMask; break;
case GL_COLOR_WRITEMASK:
params[0] = mState.blend.colorMaskRed;
params[1] = mState.blend.colorMaskGreen;
params[2] = mState.blend.colorMaskBlue;
params[3] = mState.blend.colorMaskAlpha;
break;
case GL_CULL_FACE: *params = mState.rasterizer.cullFace; break;
case GL_POLYGON_OFFSET_FILL: *params = mState.rasterizer.polygonOffsetFill; break;
case GL_SAMPLE_ALPHA_TO_COVERAGE: *params = mState.blend.sampleAlphaToCoverage; break;
case GL_SAMPLE_COVERAGE: *params = mState.sampleCoverage; break;
case GL_SCISSOR_TEST: *params = mState.scissorTest; break;
case GL_STENCIL_TEST: *params = mState.depthStencil.stencilTest; break;
case GL_DEPTH_TEST: *params = mState.depthStencil.depthTest; break;
case GL_BLEND: *params = mState.blend.blend; break;
case GL_DITHER: *params = mState.blend.dither; break;
case GL_CONTEXT_ROBUST_ACCESS_EXT: *params = mRobustAccess ? GL_TRUE : GL_FALSE; break;
default:
return false;
}
return true;
}
bool Context::getFloatv(GLenum pname, GLfloat *params)
{
// Please note: DEPTH_CLEAR_VALUE is included in our internal getFloatv implementation
// because it is stored as a float, despite the fact that the GL ES 2.0 spec names
// GetIntegerv as its native query function. As it would require conversion in any
// case, this should make no difference to the calling application.
switch (pname)
{
case GL_LINE_WIDTH: *params = mState.lineWidth; break;
case GL_SAMPLE_COVERAGE_VALUE: *params = mState.sampleCoverageValue; break;
case GL_DEPTH_CLEAR_VALUE: *params = mState.depthClearValue; break;
case GL_POLYGON_OFFSET_FACTOR: *params = mState.rasterizer.polygonOffsetFactor; break;
case GL_POLYGON_OFFSET_UNITS: *params = mState.rasterizer.polygonOffsetUnits; break;
case GL_ALIASED_LINE_WIDTH_RANGE:
params[0] = gl::ALIASED_LINE_WIDTH_RANGE_MIN;
params[1] = gl::ALIASED_LINE_WIDTH_RANGE_MAX;
break;
case GL_ALIASED_POINT_SIZE_RANGE:
params[0] = gl::ALIASED_POINT_SIZE_RANGE_MIN;
params[1] = getMaximumPointSize();
break;
case GL_DEPTH_RANGE:
params[0] = mState.zNear;
params[1] = mState.zFar;
break;
case GL_COLOR_CLEAR_VALUE:
params[0] = mState.colorClearValue.red;
params[1] = mState.colorClearValue.green;
params[2] = mState.colorClearValue.blue;
params[3] = mState.colorClearValue.alpha;
break;
case GL_BLEND_COLOR:
params[0] = mState.blendColor.red;
params[1] = mState.blendColor.green;
params[2] = mState.blendColor.blue;
params[3] = mState.blendColor.alpha;
break;
case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
if (!supportsTextureFilterAnisotropy())
{
return false;
}
*params = mMaxTextureAnisotropy;
break;
default:
return false;
}
return true;
}
bool Context::getIntegerv(GLenum pname, GLint *params)
{
if (pname >= GL_DRAW_BUFFER0_EXT && pname <= GL_DRAW_BUFFER15_EXT)
{
unsigned int colorAttachment = (pname - GL_DRAW_BUFFER0_EXT);
if (colorAttachment >= mRenderer->getMaxRenderTargets())
{
// return true to stop further operation in the parent call
return gl::error(GL_INVALID_OPERATION, true);
}
Framebuffer *framebuffer = getDrawFramebuffer();
*params = framebuffer->getDrawBufferState(colorAttachment);
return true;
}
// Please note: DEPTH_CLEAR_VALUE is not included in our internal getIntegerv implementation
// because it is stored as a float, despite the fact that the GL ES 2.0 spec names
// GetIntegerv as its native query function. As it would require conversion in any
// case, this should make no difference to the calling application. You may find it in
// Context::getFloatv.
switch (pname)
{
case GL_MAX_VERTEX_ATTRIBS: *params = gl::MAX_VERTEX_ATTRIBS; break;
case GL_MAX_VERTEX_UNIFORM_VECTORS: *params = mRenderer->getMaxVertexUniformVectors(); break;
case GL_MAX_VARYING_VECTORS: *params = mRenderer->getMaxVaryingVectors(); break;
case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: *params = mRenderer->getMaxCombinedTextureImageUnits(); break;
case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS: *params = mRenderer->getMaxVertexTextureImageUnits(); break;
case GL_MAX_TEXTURE_IMAGE_UNITS: *params = gl::MAX_TEXTURE_IMAGE_UNITS; break;
case GL_MAX_FRAGMENT_UNIFORM_VECTORS: *params = mRenderer->getMaxFragmentUniformVectors(); break;
case GL_MAX_RENDERBUFFER_SIZE: *params = getMaximumRenderbufferDimension(); break;
case GL_MAX_COLOR_ATTACHMENTS_EXT: *params = mRenderer->getMaxRenderTargets(); break;
case GL_MAX_DRAW_BUFFERS_EXT: *params = mRenderer->getMaxRenderTargets(); break;
case GL_NUM_SHADER_BINARY_FORMATS: *params = 0; break;
case GL_SHADER_BINARY_FORMATS: /* no shader binary formats are supported */ break;
case GL_ARRAY_BUFFER_BINDING: *params = mState.arrayBuffer.id(); break;
case GL_ELEMENT_ARRAY_BUFFER_BINDING: *params = mState.elementArrayBuffer.id(); break;
//case GL_FRAMEBUFFER_BINDING: // now equivalent to GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
case GL_DRAW_FRAMEBUFFER_BINDING_ANGLE: *params = mState.drawFramebuffer; break;
case GL_READ_FRAMEBUFFER_BINDING_ANGLE: *params = mState.readFramebuffer; break;
case GL_RENDERBUFFER_BINDING: *params = mState.renderbuffer.id(); break;
case GL_CURRENT_PROGRAM: *params = mState.currentProgram; break;
case GL_PACK_ALIGNMENT: *params = mState.packAlignment; break;
case GL_PACK_REVERSE_ROW_ORDER_ANGLE: *params = mState.packReverseRowOrder; break;
case GL_UNPACK_ALIGNMENT: *params = mState.unpackAlignment; break;
case GL_GENERATE_MIPMAP_HINT: *params = mState.generateMipmapHint; break;
case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: *params = mState.fragmentShaderDerivativeHint; break;
case GL_ACTIVE_TEXTURE: *params = (mState.activeSampler + GL_TEXTURE0); break;
case GL_STENCIL_FUNC: *params = mState.depthStencil.stencilFunc; break;
case GL_STENCIL_REF: *params = mState.stencilRef; break;
case GL_STENCIL_VALUE_MASK: *params = mState.depthStencil.stencilMask; break;
case GL_STENCIL_BACK_FUNC: *params = mState.depthStencil.stencilBackFunc; break;
case GL_STENCIL_BACK_REF: *params = mState.stencilBackRef; break;
case GL_STENCIL_BACK_VALUE_MASK: *params = mState.depthStencil.stencilBackMask; break;
case GL_STENCIL_FAIL: *params = mState.depthStencil.stencilFail; break;
case GL_STENCIL_PASS_DEPTH_FAIL: *params = mState.depthStencil.stencilPassDepthFail; break;
case GL_STENCIL_PASS_DEPTH_PASS: *params = mState.depthStencil.stencilPassDepthPass; break;
case GL_STENCIL_BACK_FAIL: *params = mState.depthStencil.stencilBackFail; break;
case GL_STENCIL_BACK_PASS_DEPTH_FAIL: *params = mState.depthStencil.stencilBackPassDepthFail; break;
case GL_STENCIL_BACK_PASS_DEPTH_PASS: *params = mState.depthStencil.stencilBackPassDepthPass; break;
case GL_DEPTH_FUNC: *params = mState.depthStencil.depthFunc; break;
case GL_BLEND_SRC_RGB: *params = mState.blend.sourceBlendRGB; break;
case GL_BLEND_SRC_ALPHA: *params = mState.blend.sourceBlendAlpha; break;
case GL_BLEND_DST_RGB: *params = mState.blend.destBlendRGB; break;
case GL_BLEND_DST_ALPHA: *params = mState.blend.destBlendAlpha; break;
case GL_BLEND_EQUATION_RGB: *params = mState.blend.blendEquationRGB; break;
case GL_BLEND_EQUATION_ALPHA: *params = mState.blend.blendEquationAlpha; break;
case GL_STENCIL_WRITEMASK: *params = mState.depthStencil.stencilWritemask; break;
case GL_STENCIL_BACK_WRITEMASK: *params = mState.depthStencil.stencilBackWritemask; break;
case GL_STENCIL_CLEAR_VALUE: *params = mState.stencilClearValue; break;
case GL_SUBPIXEL_BITS: *params = 4; break;
case GL_MAX_TEXTURE_SIZE: *params = getMaximumTextureDimension(); break;
case GL_MAX_CUBE_MAP_TEXTURE_SIZE: *params = getMaximumCubeTextureDimension(); break;
case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
params[0] = mNumCompressedTextureFormats;
break;
case GL_MAX_SAMPLES_ANGLE:
{
GLsizei maxSamples = getMaxSupportedSamples();
if (maxSamples != 0)
{
*params = maxSamples;
}
else
{
return false;
}
break;
}
case GL_SAMPLE_BUFFERS:
case GL_SAMPLES:
{
gl::Framebuffer *framebuffer = getDrawFramebuffer();
if (framebuffer->completeness() == GL_FRAMEBUFFER_COMPLETE)
{
switch (pname)
{
case GL_SAMPLE_BUFFERS:
if (framebuffer->getSamples() != 0)
{
*params = 1;
}
else
{
*params = 0;
}
break;
case GL_SAMPLES:
*params = framebuffer->getSamples();
break;
}
}
else
{
*params = 0;
}
}
break;
case GL_IMPLEMENTATION_COLOR_READ_TYPE:
case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
{
GLenum format, type;
if (getCurrentReadFormatType(&format, &type))
{
if (pname == GL_IMPLEMENTATION_COLOR_READ_FORMAT)
*params = format;
else
*params = type;
}
}
break;
case GL_MAX_VIEWPORT_DIMS:
{
params[0] = mMaxViewportDimension;
params[1] = mMaxViewportDimension;
}
break;
case GL_COMPRESSED_TEXTURE_FORMATS:
{
if (supportsDXT1Textures())
{
*params++ = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
*params++ = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
}
if (supportsDXT3Textures())
{
*params++ = GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE;
}
if (supportsDXT5Textures())
{
*params++ = GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE;
}
}
break;
case GL_VIEWPORT:
params[0] = mState.viewport.x;
params[1] = mState.viewport.y;
params[2] = mState.viewport.width;
params[3] = mState.viewport.height;
break;
case GL_SCISSOR_BOX:
params[0] = mState.scissor.x;
params[1] = mState.scissor.y;
params[2] = mState.scissor.width;
params[3] = mState.scissor.height;
break;
case GL_CULL_FACE_MODE: *params = mState.rasterizer.cullMode; break;
case GL_FRONT_FACE: *params = mState.rasterizer.frontFace; break;
case GL_RED_BITS:
case GL_GREEN_BITS:
case GL_BLUE_BITS:
case GL_ALPHA_BITS:
{
gl::Framebuffer *framebuffer = getDrawFramebuffer();
gl::Renderbuffer *colorbuffer = framebuffer->getFirstColorbuffer();
if (colorbuffer)
{
switch (pname)
{
case GL_RED_BITS: *params = colorbuffer->getRedSize(); break;
case GL_GREEN_BITS: *params = colorbuffer->getGreenSize(); break;
case GL_BLUE_BITS: *params = colorbuffer->getBlueSize(); break;
case GL_ALPHA_BITS: *params = colorbuffer->getAlphaSize(); break;
}
}
else
{
*params = 0;
}
}
break;
case GL_DEPTH_BITS:
{
gl::Framebuffer *framebuffer = getDrawFramebuffer();
gl::Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
if (depthbuffer)
{
*params = depthbuffer->getDepthSize();
}
else
{
*params = 0;
}
}
break;
case GL_STENCIL_BITS:
{
gl::Framebuffer *framebuffer = getDrawFramebuffer();
gl::Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
if (stencilbuffer)
{
*params = stencilbuffer->getStencilSize();
}
else
{
*params = 0;
}
}
break;
case GL_TEXTURE_BINDING_2D:
{
if (mState.activeSampler > mRenderer->getMaxCombinedTextureImageUnits() - 1)
{
gl::error(GL_INVALID_OPERATION);
return false;
}
*params = mState.samplerTexture[TEXTURE_2D][mState.activeSampler].id();
}
break;
case GL_TEXTURE_BINDING_CUBE_MAP:
{
if (mState.activeSampler > mRenderer->getMaxCombinedTextureImageUnits() - 1)
{
gl::error(GL_INVALID_OPERATION);
return false;
}
*params = mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].id();
}
break;
case GL_RESET_NOTIFICATION_STRATEGY_EXT:
*params = mResetStrategy;
break;
case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
*params = 1;
break;
case GL_PROGRAM_BINARY_FORMATS_OES:
*params = GL_PROGRAM_BINARY_ANGLE;
break;
default:
return false;
}
return true;
}
bool Context::getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams)
{
if (pname >= GL_DRAW_BUFFER0_EXT && pname <= GL_DRAW_BUFFER15_EXT)
{
*type = GL_INT;
*numParams = 1;
return true;
}
// Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
// is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
// to the fact that it is stored internally as a float, and so would require conversion
// if returned from Context::getIntegerv. Since this conversion is already implemented
// in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
// place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
// application.
switch (pname)
{
case GL_COMPRESSED_TEXTURE_FORMATS:
{
*type = GL_INT;
*numParams = mNumCompressedTextureFormats;
}
break;
case GL_SHADER_BINARY_FORMATS:
{
*type = GL_INT;
*numParams = 0;
}
break;
case GL_MAX_VERTEX_ATTRIBS:
case GL_MAX_VERTEX_UNIFORM_VECTORS:
case GL_MAX_VARYING_VECTORS:
case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
case GL_MAX_TEXTURE_IMAGE_UNITS:
case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
case GL_MAX_RENDERBUFFER_SIZE:
case GL_MAX_COLOR_ATTACHMENTS_EXT:
case GL_MAX_DRAW_BUFFERS_EXT:
case GL_NUM_SHADER_BINARY_FORMATS:
case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
case GL_ARRAY_BUFFER_BINDING:
case GL_FRAMEBUFFER_BINDING:
case GL_RENDERBUFFER_BINDING:
case GL_CURRENT_PROGRAM:
case GL_PACK_ALIGNMENT:
case GL_PACK_REVERSE_ROW_ORDER_ANGLE:
case GL_UNPACK_ALIGNMENT:
case GL_GENERATE_MIPMAP_HINT:
case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
case GL_RED_BITS:
case GL_GREEN_BITS:
case GL_BLUE_BITS:
case GL_ALPHA_BITS:
case GL_DEPTH_BITS:
case GL_STENCIL_BITS:
case GL_ELEMENT_ARRAY_BUFFER_BINDING:
case GL_CULL_FACE_MODE:
case GL_FRONT_FACE:
case GL_ACTIVE_TEXTURE:
case GL_STENCIL_FUNC:
case GL_STENCIL_VALUE_MASK:
case GL_STENCIL_REF:
case GL_STENCIL_FAIL:
case GL_STENCIL_PASS_DEPTH_FAIL:
case GL_STENCIL_PASS_DEPTH_PASS:
case GL_STENCIL_BACK_FUNC:
case GL_STENCIL_BACK_VALUE_MASK:
case GL_STENCIL_BACK_REF:
case GL_STENCIL_BACK_FAIL:
case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
case GL_STENCIL_BACK_PASS_DEPTH_PASS:
case GL_DEPTH_FUNC:
case GL_BLEND_SRC_RGB:
case GL_BLEND_SRC_ALPHA:
case GL_BLEND_DST_RGB:
case GL_BLEND_DST_ALPHA:
case GL_BLEND_EQUATION_RGB:
case GL_BLEND_EQUATION_ALPHA:
case GL_STENCIL_WRITEMASK:
case GL_STENCIL_BACK_WRITEMASK:
case GL_STENCIL_CLEAR_VALUE:
case GL_SUBPIXEL_BITS:
case GL_MAX_TEXTURE_SIZE:
case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
case GL_SAMPLE_BUFFERS:
case GL_SAMPLES:
case GL_IMPLEMENTATION_COLOR_READ_TYPE:
case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
case GL_TEXTURE_BINDING_2D:
case GL_TEXTURE_BINDING_CUBE_MAP:
case GL_RESET_NOTIFICATION_STRATEGY_EXT:
case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
case GL_PROGRAM_BINARY_FORMATS_OES:
{
*type = GL_INT;
*numParams = 1;
}
break;
case GL_MAX_SAMPLES_ANGLE:
{
if (getMaxSupportedSamples() != 0)
{
*type = GL_INT;
*numParams = 1;
}
else
{
return false;
}
}
break;
case GL_MAX_VIEWPORT_DIMS:
{
*type = GL_INT;
*numParams = 2;
}
break;
case GL_VIEWPORT:
case GL_SCISSOR_BOX:
{
*type = GL_INT;
*numParams = 4;
}
break;
case GL_SHADER_COMPILER:
case GL_SAMPLE_COVERAGE_INVERT:
case GL_DEPTH_WRITEMASK:
case GL_CULL_FACE: // CULL_FACE through DITHER are natural to IsEnabled,
case GL_POLYGON_OFFSET_FILL: // but can be retrieved through the Get{Type}v queries.
case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
case GL_SAMPLE_COVERAGE:
case GL_SCISSOR_TEST:
case GL_STENCIL_TEST:
case GL_DEPTH_TEST:
case GL_BLEND:
case GL_DITHER:
case GL_CONTEXT_ROBUST_ACCESS_EXT:
{
*type = GL_BOOL;
*numParams = 1;
}
break;
case GL_COLOR_WRITEMASK:
{
*type = GL_BOOL;
*numParams = 4;
}
break;
case GL_POLYGON_OFFSET_FACTOR:
case GL_POLYGON_OFFSET_UNITS:
case GL_SAMPLE_COVERAGE_VALUE:
case GL_DEPTH_CLEAR_VALUE:
case GL_LINE_WIDTH:
{
*type = GL_FLOAT;
*numParams = 1;
}
break;
case GL_ALIASED_LINE_WIDTH_RANGE:
case GL_ALIASED_POINT_SIZE_RANGE:
case GL_DEPTH_RANGE:
{
*type = GL_FLOAT;
*numParams = 2;
}
break;
case GL_COLOR_CLEAR_VALUE:
case GL_BLEND_COLOR:
{
*type = GL_FLOAT;
*numParams = 4;
}
break;
case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
if (!supportsTextureFilterAnisotropy())
{
return false;
}
*type = GL_FLOAT;
*numParams = 1;
break;
default:
return false;
}
return true;
}
// Applies the render target surface, depth stencil surface, viewport rectangle and
// scissor rectangle to the renderer
bool Context::applyRenderTarget(GLenum drawMode, bool ignoreViewport)
{
Framebuffer *framebufferObject = getDrawFramebuffer();
if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION, false);
}
mRenderer->applyRenderTarget(framebufferObject);
if (!mRenderer->setViewport(mState.viewport, mState.zNear, mState.zFar, drawMode, mState.rasterizer.frontFace,
ignoreViewport))
{
return false;
}
mRenderer->setScissorRectangle(mState.scissor, mState.scissorTest);
return true;
}
// Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc) to the Direct3D 9 device
void Context::applyState(GLenum drawMode)
{
Framebuffer *framebufferObject = getDrawFramebuffer();
int samples = framebufferObject->getSamples();
mState.rasterizer.pointDrawMode = (drawMode == GL_POINTS);
mState.rasterizer.multiSample = (samples != 0);
mRenderer->setRasterizerState(mState.rasterizer);
unsigned int mask = 0;
if (mState.sampleCoverage)
{
if (mState.sampleCoverageValue != 0)
{
float threshold = 0.5f;
for (int i = 0; i < samples; ++i)
{
mask <<= 1;
if ((i + 1) * mState.sampleCoverageValue >= threshold)
{
threshold += 1.0f;
mask |= 1;
}
}
}
if (mState.sampleCoverageInvert)
{
mask = ~mask;
}
}
else
{
mask = 0xFFFFFFFF;
}
mRenderer->setBlendState(mState.blend, mState.blendColor, mask);
mRenderer->setDepthStencilState(mState.depthStencil, mState.stencilRef, mState.stencilBackRef,
mState.rasterizer.frontFace == GL_CCW);
}
// Applies the shaders and shader constants to the Direct3D 9 device
void Context::applyShaders()
{
ProgramBinary *programBinary = getCurrentProgramBinary();
mRenderer->applyShaders(programBinary);
programBinary->applyUniforms();
}
// Applies the textures and sampler states to the Direct3D 9 device
void Context::applyTextures()
{
applyTextures(SAMPLER_PIXEL);
if (mSupportsVertexTexture)
{
applyTextures(SAMPLER_VERTEX);
}
}
// For each Direct3D 9 sampler of either the pixel or vertex stage,
// looks up the corresponding OpenGL texture image unit and texture type,
// and sets the texture and its addressing/filtering state (or NULL when inactive).
void Context::applyTextures(SamplerType type)
{
ProgramBinary *programBinary = getCurrentProgramBinary();
// Range of Direct3D samplers of given sampler type
int samplerCount = (type == SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : mRenderer->getMaxVertexTextureImageUnits();
int samplerRange = programBinary->getUsedSamplerRange(type);
for (int samplerIndex = 0; samplerIndex < samplerRange; samplerIndex++)
{
int textureUnit = programBinary->getSamplerMapping(type, samplerIndex); // OpenGL texture image unit index
if (textureUnit != -1)
{
TextureType textureType = programBinary->getSamplerTextureType(type, samplerIndex);
Texture *texture = getSamplerTexture(textureUnit, textureType);
if (texture->isSamplerComplete())
{
SamplerState samplerState;
texture->getSamplerState(&samplerState);
mRenderer->setSamplerState(type, samplerIndex, samplerState);
mRenderer->setTexture(type, samplerIndex, texture);
texture->resetDirty();
}
else
{
mRenderer->setTexture(type, samplerIndex, getIncompleteTexture(textureType));
}
}
else
{
mRenderer->setTexture(type, samplerIndex, NULL);
}
}
for (int samplerIndex = samplerRange; samplerIndex < samplerCount; samplerIndex++)
{
mRenderer->setTexture(type, samplerIndex, NULL);
}
}
void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
{
Framebuffer *framebuffer = getReadFramebuffer();
if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION);
}
if (getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
GLsizei outputPitch = ComputePitch(width, ConvertSizedInternalFormat(format, type), getPackAlignment());
// sized query sanity check
if (bufSize)
{
int requiredSize = outputPitch * height;
if (requiredSize > *bufSize)
{
return gl::error(GL_INVALID_OPERATION);
}
}
mRenderer->readPixels(framebuffer, x, y, width, height, format, type, outputPitch, getPackReverseRowOrder(), getPackAlignment(), pixels);
}
void Context::clear(GLbitfield mask)
{
Framebuffer *framebufferObject = getDrawFramebuffer();
if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION);
}
DWORD flags = 0;
GLbitfield finalMask = 0;
if (mask & GL_COLOR_BUFFER_BIT)
{
mask &= ~GL_COLOR_BUFFER_BIT;
if (framebufferObject->hasEnabledColorAttachment())
{
finalMask |= GL_COLOR_BUFFER_BIT;
}
}
if (mask & GL_DEPTH_BUFFER_BIT)
{
mask &= ~GL_DEPTH_BUFFER_BIT;
if (mState.depthStencil.depthMask && framebufferObject->getDepthbufferType() != GL_NONE)
{
finalMask |= GL_DEPTH_BUFFER_BIT;
}
}
if (mask & GL_STENCIL_BUFFER_BIT)
{
mask &= ~GL_STENCIL_BUFFER_BIT;
if (framebufferObject->getStencilbufferType() != GL_NONE)
{
rx::RenderTarget *depthStencil = framebufferObject->getStencilbuffer()->getDepthStencil();
if (!depthStencil)
{
ERR("Depth stencil pointer unexpectedly null.");
return;
}
if (GetStencilSize(depthStencil->getActualFormat()) > 0)
{
finalMask |= GL_STENCIL_BUFFER_BIT;
}
}
}
if (mask != 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (!applyRenderTarget(GL_TRIANGLES, true)) // Clips the clear to the scissor rectangle but not the viewport
{
return;
}
ClearParameters clearParams;
clearParams.mask = finalMask;
clearParams.colorClearValue = mState.colorClearValue;
clearParams.colorMaskRed = mState.blend.colorMaskRed;
clearParams.colorMaskGreen = mState.blend.colorMaskGreen;
clearParams.colorMaskBlue = mState.blend.colorMaskBlue;
clearParams.colorMaskAlpha = mState.blend.colorMaskAlpha;
clearParams.depthClearValue = mState.depthClearValue;
clearParams.stencilClearValue = mState.stencilClearValue;
clearParams.stencilWriteMask = mState.depthStencil.stencilWritemask;
mRenderer->clear(clearParams, framebufferObject);
}
void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instances)
{
if (!mState.currentProgram)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!mRenderer->applyPrimitiveType(mode, count))
{
return;
}
if (!applyRenderTarget(mode, false))
{
return;
}
applyState(mode);
ProgramBinary *programBinary = getCurrentProgramBinary();
GLenum err = mRenderer->applyVertexBuffer(programBinary, mState.vertexAttribute, first, count, instances);
if (err != GL_NO_ERROR)
{
return gl::error(err);
}
applyShaders();
applyTextures();
if (!programBinary->validateSamplers(NULL))
{
return gl::error(GL_INVALID_OPERATION);
}
if (!skipDraw(mode))
{
mRenderer->drawArrays(mode, count, instances);
}
}
void Context::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei instances)
{
if (!mState.currentProgram)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!indices && !mState.elementArrayBuffer)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!mRenderer->applyPrimitiveType(mode, count))
{
return;
}
if (!applyRenderTarget(mode, false))
{
return;
}
applyState(mode);
rx::TranslatedIndexData indexInfo;
GLenum err = mRenderer->applyIndexBuffer(indices, mState.elementArrayBuffer.get(), count, mode, type, &indexInfo);
if (err != GL_NO_ERROR)
{
return gl::error(err);
}
ProgramBinary *programBinary = getCurrentProgramBinary();
GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
err = mRenderer->applyVertexBuffer(programBinary, mState.vertexAttribute, indexInfo.minIndex, vertexCount, instances);
if (err != GL_NO_ERROR)
{
return gl::error(err);
}
applyShaders();
applyTextures();
if (!programBinary->validateSamplers(NULL))
{
return gl::error(GL_INVALID_OPERATION);
}
if (!skipDraw(mode))
{
mRenderer->drawElements(mode, count, type, indices, mState.elementArrayBuffer.get(), indexInfo, instances);
}
}
// Implements glFlush when block is false, glFinish when block is true
void Context::sync(bool block)
{
mRenderer->sync(block);
}
void Context::recordInvalidEnum()
{
mInvalidEnum = true;
}
void Context::recordInvalidValue()
{
mInvalidValue = true;
}
void Context::recordInvalidOperation()
{
mInvalidOperation = true;
}
void Context::recordOutOfMemory()
{
mOutOfMemory = true;
}
void Context::recordInvalidFramebufferOperation()
{
mInvalidFramebufferOperation = true;
}
// Get one of the recorded errors and clear its flag, if any.
// [OpenGL ES 2.0.24] section 2.5 page 13.
GLenum Context::getError()
{
if (mInvalidEnum)
{
mInvalidEnum = false;
return GL_INVALID_ENUM;
}
if (mInvalidValue)
{
mInvalidValue = false;
return GL_INVALID_VALUE;
}
if (mInvalidOperation)
{
mInvalidOperation = false;
return GL_INVALID_OPERATION;
}
if (mOutOfMemory)
{
mOutOfMemory = false;
return GL_OUT_OF_MEMORY;
}
if (mInvalidFramebufferOperation)
{
mInvalidFramebufferOperation = false;
return GL_INVALID_FRAMEBUFFER_OPERATION;
}
return GL_NO_ERROR;
}
GLenum Context::getResetStatus()
{
if (mResetStatus == GL_NO_ERROR && !mContextLost)
{
// mResetStatus will be set by the markContextLost callback
// in the case a notification is sent
mRenderer->testDeviceLost(true);
}
GLenum status = mResetStatus;
if (mResetStatus != GL_NO_ERROR)
{
ASSERT(mContextLost);
if (mRenderer->testDeviceResettable())
{
mResetStatus = GL_NO_ERROR;
}
}
return status;
}
bool Context::isResetNotificationEnabled()
{
return (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT);
}
int Context::getMajorShaderModel() const
{
return mMajorShaderModel;
}
float Context::getMaximumPointSize() const
{
return mMaximumPointSize;
}
unsigned int Context::getMaximumCombinedTextureImageUnits() const
{
return mRenderer->getMaxCombinedTextureImageUnits();
}
int Context::getMaxSupportedSamples() const
{
return mRenderer->getMaxSupportedSamples();
}
unsigned int Context::getMaximumRenderTargets() const
{
return mRenderer->getMaxRenderTargets();
}
bool Context::supportsEventQueries() const
{
return mSupportsEventQueries;
}
bool Context::supportsOcclusionQueries() const
{
return mSupportsOcclusionQueries;
}
bool Context::supportsBGRATextures() const
{
return mSupportsBGRATextures;
}
bool Context::supportsDXT1Textures() const
{
return mSupportsDXT1Textures;
}
bool Context::supportsDXT3Textures() const
{
return mSupportsDXT3Textures;
}
bool Context::supportsDXT5Textures() const
{
return mSupportsDXT5Textures;
}
bool Context::supportsFloat32Textures() const
{
return mSupportsFloat32Textures;
}
bool Context::supportsFloat32LinearFilter() const
{
return mSupportsFloat32LinearFilter;
}
bool Context::supportsFloat32RenderableTextures() const
{
return mSupportsFloat32RenderableTextures;
}
bool Context::supportsFloat16Textures() const
{
return mSupportsFloat16Textures;
}
bool Context::supportsFloat16LinearFilter() const
{
return mSupportsFloat16LinearFilter;
}
bool Context::supportsFloat16RenderableTextures() const
{
return mSupportsFloat16RenderableTextures;
}
int Context::getMaximumRenderbufferDimension() const
{
return mMaxRenderbufferDimension;
}
int Context::getMaximumTextureDimension() const
{
return mMaxTextureDimension;
}
int Context::getMaximumCubeTextureDimension() const
{
return mMaxCubeTextureDimension;
}
int Context::getMaximumTextureLevel() const
{
return mMaxTextureLevel;
}
bool Context::supportsLuminanceTextures() const
{
return mSupportsLuminanceTextures;
}
bool Context::supportsLuminanceAlphaTextures() const
{
return mSupportsLuminanceAlphaTextures;
}
bool Context::supportsDepthTextures() const
{
return mSupportsDepthTextures;
}
bool Context::supports32bitIndices() const
{
return mSupports32bitIndices;
}
bool Context::supportsNonPower2Texture() const
{
return mSupportsNonPower2Texture;
}
bool Context::supportsInstancing() const
{
return mSupportsInstancing;
}
bool Context::supportsTextureFilterAnisotropy() const
{
return mSupportsTextureFilterAnisotropy;
}
float Context::getTextureMaxAnisotropy() const
{
return mMaxTextureAnisotropy;
}
bool Context::getCurrentReadFormatType(GLenum *format, GLenum *type)
{
Framebuffer *framebuffer = getReadFramebuffer();
if (!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_OPERATION, false);
}
Renderbuffer *renderbuffer = framebuffer->getReadColorbuffer();
if (!renderbuffer)
{
return gl::error(GL_INVALID_OPERATION, false);
}
*format = gl::ExtractFormat(renderbuffer->getActualFormat());
*type = gl::ExtractType(renderbuffer->getActualFormat());
return true;
}
void Context::detachBuffer(GLuint buffer)
{
// [OpenGL ES 2.0.24] section 2.9 page 22:
// If a buffer object is deleted while it is bound, all bindings to that object in the current context
// (i.e. in the thread that called Delete-Buffers) are reset to zero.
if (mState.arrayBuffer.id() == buffer)
{
mState.arrayBuffer.set(NULL);
}
if (mState.elementArrayBuffer.id() == buffer)
{
mState.elementArrayBuffer.set(NULL);
}
for (int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
{
if (mState.vertexAttribute[attribute].mBoundBuffer.id() == buffer)
{
mState.vertexAttribute[attribute].mBoundBuffer.set(NULL);
}
}
}
void Context::detachTexture(GLuint texture)
{
// [OpenGL ES 2.0.24] section 3.8 page 84:
// If a texture object is deleted, it is as if all texture units which are bound to that texture object are
// rebound to texture object zero
for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
{
for (int sampler = 0; sampler < IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
{
if (mState.samplerTexture[type][sampler].id() == texture)
{
mState.samplerTexture[type][sampler].set(NULL);
}
}
}
// [OpenGL ES 2.0.24] section 4.4 page 112:
// If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
// as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
// image was attached in the currently bound framebuffer.
Framebuffer *readFramebuffer = getReadFramebuffer();
Framebuffer *drawFramebuffer = getDrawFramebuffer();
if (readFramebuffer)
{
readFramebuffer->detachTexture(texture);
}
if (drawFramebuffer && drawFramebuffer != readFramebuffer)
{
drawFramebuffer->detachTexture(texture);
}
}
void Context::detachFramebuffer(GLuint framebuffer)
{
// [OpenGL ES 2.0.24] section 4.4 page 107:
// If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
// BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
if (mState.readFramebuffer == framebuffer)
{
bindReadFramebuffer(0);
}
if (mState.drawFramebuffer == framebuffer)
{
bindDrawFramebuffer(0);
}
}
void Context::detachRenderbuffer(GLuint renderbuffer)
{
// [OpenGL ES 2.0.24] section 4.4 page 109:
// If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
// had been executed with the target RENDERBUFFER and name of zero.
if (mState.renderbuffer.id() == renderbuffer)
{
bindRenderbuffer(0);
}
// [OpenGL ES 2.0.24] section 4.4 page 111:
// If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
// then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
// point to which this image was attached in the currently bound framebuffer.
Framebuffer *readFramebuffer = getReadFramebuffer();
Framebuffer *drawFramebuffer = getDrawFramebuffer();
if (readFramebuffer)
{
readFramebuffer->detachRenderbuffer(renderbuffer);
}
if (drawFramebuffer && drawFramebuffer != readFramebuffer)
{
drawFramebuffer->detachRenderbuffer(renderbuffer);
}
}
Texture *Context::getIncompleteTexture(TextureType type)
{
Texture *t = mIncompleteTextures[type].get();
if (t == NULL)
{
static const GLubyte color[] = { 0, 0, 0, 255 };
switch (type)
{
default:
UNREACHABLE();
// default falls through to TEXTURE_2D
case TEXTURE_2D:
{
Texture2D *incomplete2d = new Texture2D(mRenderer, Texture::INCOMPLETE_TEXTURE_ID);
incomplete2d->setImage(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
t = incomplete2d;
}
break;
case TEXTURE_CUBE:
{
TextureCubeMap *incompleteCube = new TextureCubeMap(mRenderer, Texture::INCOMPLETE_TEXTURE_ID);
incompleteCube->setImagePosX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
incompleteCube->setImageNegX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
incompleteCube->setImagePosY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
incompleteCube->setImageNegY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
incompleteCube->setImagePosZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
incompleteCube->setImageNegZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
t = incompleteCube;
}
break;
}
mIncompleteTextures[type].set(t);
}
return t;
}
bool Context::skipDraw(GLenum drawMode)
{
if (drawMode == GL_POINTS)
{
// ProgramBinary assumes non-point rendering if gl_PointSize isn't written,
// which affects varying interpolation. Since the value of gl_PointSize is
// undefined when not written, just skip drawing to avoid unexpected results.
if (!getCurrentProgramBinary()->usesPointSize())
{
// This is stictly speaking not an error, but developers should be
// notified of risking undefined behavior.
ERR("Point rendering without writing to gl_PointSize.");
return true;
}
}
else if (IsTriangleMode(drawMode))
{
if (mState.rasterizer.cullFace && mState.rasterizer.cullMode == GL_FRONT_AND_BACK)
{
return true;
}
}
return false;
}
void Context::setVertexAttrib(GLuint index, const GLfloat *values)
{
ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
mState.vertexAttribute[index].mCurrentValue[0] = values[0];
mState.vertexAttribute[index].mCurrentValue[1] = values[1];
mState.vertexAttribute[index].mCurrentValue[2] = values[2];
mState.vertexAttribute[index].mCurrentValue[3] = values[3];
}
void Context::setVertexAttribDivisor(GLuint index, GLuint divisor)
{
ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
mState.vertexAttribute[index].mDivisor = divisor;
}
// keep list sorted in following order
// OES extensions
// EXT extensions
// Vendor extensions
void Context::initExtensionString()
{
std::string extensionString = "";
// OES extensions
if (supports32bitIndices())
{
extensionString += "GL_OES_element_index_uint ";
}
extensionString += "GL_OES_packed_depth_stencil ";
extensionString += "GL_OES_get_program_binary ";
extensionString += "GL_OES_rgb8_rgba8 ";
if (mRenderer->getDerivativeInstructionSupport())
{
extensionString += "GL_OES_standard_derivatives ";
}
if (supportsFloat16Textures())
{
extensionString += "GL_OES_texture_half_float ";
}
if (supportsFloat16LinearFilter())
{
extensionString += "GL_OES_texture_half_float_linear ";
}
if (supportsFloat32Textures())
{
extensionString += "GL_OES_texture_float ";
}
if (supportsFloat32LinearFilter())
{
extensionString += "GL_OES_texture_float_linear ";
}
if (supportsNonPower2Texture())
{
extensionString += "GL_OES_texture_npot ";
}
// Multi-vendor (EXT) extensions
if (supportsOcclusionQueries())
{
extensionString += "GL_EXT_occlusion_query_boolean ";
}
extensionString += "GL_EXT_read_format_bgra ";
extensionString += "GL_EXT_robustness ";
if (supportsDXT1Textures())
{
extensionString += "GL_EXT_texture_compression_dxt1 ";
}
if (supportsTextureFilterAnisotropy())
{
extensionString += "GL_EXT_texture_filter_anisotropic ";
}
if (supportsBGRATextures())
{
extensionString += "GL_EXT_texture_format_BGRA8888 ";
}
if (mRenderer->getMaxRenderTargets() > 1)
{
extensionString += "GL_EXT_draw_buffers ";
}
extensionString += "GL_EXT_texture_storage ";
extensionString += "GL_EXT_frag_depth ";
// ANGLE-specific extensions
if (supportsDepthTextures())
{
extensionString += "GL_ANGLE_depth_texture ";
}
extensionString += "GL_ANGLE_framebuffer_blit ";
if (getMaxSupportedSamples() != 0)
{
extensionString += "GL_ANGLE_framebuffer_multisample ";
}
if (supportsInstancing())
{
extensionString += "GL_ANGLE_instanced_arrays ";
}
extensionString += "GL_ANGLE_pack_reverse_row_order ";
if (supportsDXT3Textures())
{
extensionString += "GL_ANGLE_texture_compression_dxt3 ";
}
if (supportsDXT5Textures())
{
extensionString += "GL_ANGLE_texture_compression_dxt5 ";
}
extensionString += "GL_ANGLE_texture_usage ";
extensionString += "GL_ANGLE_translated_shader_source ";
// Other vendor-specific extensions
if (supportsEventQueries())
{
extensionString += "GL_NV_fence ";
}
std::string::size_type end = extensionString.find_last_not_of(' ');
if (end != std::string::npos)
{
extensionString.resize(end+1);
}
mExtensionString = makeStaticString(extensionString);
}
const char *Context::getExtensionString() const
{
return mExtensionString;
}
void Context::initRendererString()
{
std::ostringstream rendererString;
rendererString << "ANGLE (";
rendererString << mRenderer->getRendererDescription();
rendererString << ")";
mRendererString = makeStaticString(rendererString.str());
}
const char *Context::getRendererString() const
{
return mRendererString;
}
void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
GLbitfield mask)
{
Framebuffer *readFramebuffer = getReadFramebuffer();
Framebuffer *drawFramebuffer = getDrawFramebuffer();
if (!readFramebuffer || readFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE ||
!drawFramebuffer || drawFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION);
}
if (drawFramebuffer->getSamples() != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
Renderbuffer *readColorBuffer = readFramebuffer->getReadColorbuffer();
Renderbuffer *drawColorBuffer = drawFramebuffer->getFirstColorbuffer();
if (drawColorBuffer == NULL)
{
ERR("Draw buffers formats don't match, which is not supported in this implementation of BlitFramebufferANGLE");
return gl::error(GL_INVALID_OPERATION);
}
int readBufferWidth = readColorBuffer->getWidth();
int readBufferHeight = readColorBuffer->getHeight();
int drawBufferWidth = drawColorBuffer->getWidth();
int drawBufferHeight = drawColorBuffer->getHeight();
Rectangle sourceRect;
Rectangle destRect;
if (srcX0 < srcX1)
{
sourceRect.x = srcX0;
destRect.x = dstX0;
sourceRect.width = srcX1 - srcX0;
destRect.width = dstX1 - dstX0;
}
else
{
sourceRect.x = srcX1;
destRect.x = dstX1;
sourceRect.width = srcX0 - srcX1;
destRect.width = dstX0 - dstX1;
}
if (srcY0 < srcY1)
{
sourceRect.height = srcY1 - srcY0;
destRect.height = dstY1 - dstY0;
sourceRect.y = srcY0;
destRect.y = dstY0;
}
else
{
sourceRect.height = srcY0 - srcY1;
destRect.height = dstY0 - srcY1;
sourceRect.y = srcY1;
destRect.y = dstY1;
}
Rectangle sourceScissoredRect = sourceRect;
Rectangle destScissoredRect = destRect;
if (mState.scissorTest)
{
// Only write to parts of the destination framebuffer which pass the scissor test.
if (destRect.x < mState.scissor.x)
{
int xDiff = mState.scissor.x - destRect.x;
destScissoredRect.x = mState.scissor.x;
destScissoredRect.width -= xDiff;
sourceScissoredRect.x += xDiff;
sourceScissoredRect.width -= xDiff;
}
if (destRect.x + destRect.width > mState.scissor.x + mState.scissor.width)
{
int xDiff = (destRect.x + destRect.width) - (mState.scissor.x + mState.scissor.width);
destScissoredRect.width -= xDiff;
sourceScissoredRect.width -= xDiff;
}
if (destRect.y < mState.scissor.y)
{
int yDiff = mState.scissor.y - destRect.y;
destScissoredRect.y = mState.scissor.y;
destScissoredRect.height -= yDiff;
sourceScissoredRect.y += yDiff;
sourceScissoredRect.height -= yDiff;
}
if (destRect.y + destRect.height > mState.scissor.y + mState.scissor.height)
{
int yDiff = (destRect.y + destRect.height) - (mState.scissor.y + mState.scissor.height);
destScissoredRect.height -= yDiff;
sourceScissoredRect.height -= yDiff;
}
}
bool blitRenderTarget = false;
bool blitDepthStencil = false;
Rectangle sourceTrimmedRect = sourceScissoredRect;
Rectangle destTrimmedRect = destScissoredRect;
// The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
// the actual draw and read surfaces.
if (sourceTrimmedRect.x < 0)
{
int xDiff = 0 - sourceTrimmedRect.x;
sourceTrimmedRect.x = 0;
sourceTrimmedRect.width -= xDiff;
destTrimmedRect.x += xDiff;
destTrimmedRect.width -= xDiff;
}
if (sourceTrimmedRect.x + sourceTrimmedRect.width > readBufferWidth)
{
int xDiff = (sourceTrimmedRect.x + sourceTrimmedRect.width) - readBufferWidth;
sourceTrimmedRect.width -= xDiff;
destTrimmedRect.width -= xDiff;
}
if (sourceTrimmedRect.y < 0)
{
int yDiff = 0 - sourceTrimmedRect.y;
sourceTrimmedRect.y = 0;
sourceTrimmedRect.height -= yDiff;
destTrimmedRect.y += yDiff;
destTrimmedRect.height -= yDiff;
}
if (sourceTrimmedRect.y + sourceTrimmedRect.height > readBufferHeight)
{
int yDiff = (sourceTrimmedRect.y + sourceTrimmedRect.height) - readBufferHeight;
sourceTrimmedRect.height -= yDiff;
destTrimmedRect.height -= yDiff;
}
if (destTrimmedRect.x < 0)
{
int xDiff = 0 - destTrimmedRect.x;
destTrimmedRect.x = 0;
destTrimmedRect.width -= xDiff;
sourceTrimmedRect.x += xDiff;
sourceTrimmedRect.width -= xDiff;
}
if (destTrimmedRect.x + destTrimmedRect.width > drawBufferWidth)
{
int xDiff = (destTrimmedRect.x + destTrimmedRect.width) - drawBufferWidth;
destTrimmedRect.width -= xDiff;
sourceTrimmedRect.width -= xDiff;
}
if (destTrimmedRect.y < 0)
{
int yDiff = 0 - destTrimmedRect.y;
destTrimmedRect.y = 0;
destTrimmedRect.height -= yDiff;
sourceTrimmedRect.y += yDiff;
sourceTrimmedRect.height -= yDiff;
}
if (destTrimmedRect.y + destTrimmedRect.height > drawBufferHeight)
{
int yDiff = (destTrimmedRect.y + destTrimmedRect.height) - drawBufferHeight;
destTrimmedRect.height -= yDiff;
sourceTrimmedRect.height -= yDiff;
}
bool partialBufferCopy = false;
if (sourceTrimmedRect.height < readBufferHeight ||
sourceTrimmedRect.width < readBufferWidth ||
destTrimmedRect.height < drawBufferHeight ||
destTrimmedRect.width < drawBufferWidth ||
sourceTrimmedRect.y != 0 || destTrimmedRect.y != 0 || sourceTrimmedRect.x != 0 || destTrimmedRect.x != 0)
{
partialBufferCopy = true;
}
if (mask & GL_COLOR_BUFFER_BIT)
{
const GLenum readColorbufferType = readFramebuffer->getReadColorbufferType();
const bool validReadType = (readColorbufferType == GL_TEXTURE_2D) || (readColorbufferType == GL_RENDERBUFFER);
bool validDrawType = true;
bool validDrawFormat = true;
for (unsigned int colorAttachment = 0; colorAttachment < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (drawFramebuffer->isEnabledColorAttachment(colorAttachment))
{
if (drawFramebuffer->getColorbufferType(colorAttachment) != GL_TEXTURE_2D &&
drawFramebuffer->getColorbufferType(colorAttachment) != GL_RENDERBUFFER)
{
validDrawType = false;
}
if (drawFramebuffer->getColorbuffer(colorAttachment)->getActualFormat() != readColorBuffer->getActualFormat())
{
validDrawFormat = false;
}
}
}
if (!validReadType || !validDrawType || !validDrawFormat)
{
ERR("Color buffer format conversion in BlitFramebufferANGLE not supported by this implementation");
return gl::error(GL_INVALID_OPERATION);
}
if (partialBufferCopy && readFramebuffer->getSamples() != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
blitRenderTarget = true;
}
if (mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
{
Renderbuffer *readDSBuffer = NULL;
Renderbuffer *drawDSBuffer = NULL;
// We support OES_packed_depth_stencil, and do not support a separately attached depth and stencil buffer, so if we have
// both a depth and stencil buffer, it will be the same buffer.
if (mask & GL_DEPTH_BUFFER_BIT)
{
if (readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
{
if (readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType() ||
readFramebuffer->getDepthbuffer()->getActualFormat() != drawFramebuffer->getDepthbuffer()->getActualFormat())
{
return gl::error(GL_INVALID_OPERATION);
}
blitDepthStencil = true;
readDSBuffer = readFramebuffer->getDepthbuffer();
drawDSBuffer = drawFramebuffer->getDepthbuffer();
}
}
if (mask & GL_STENCIL_BUFFER_BIT)
{
if (readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
{
if (readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType() ||
readFramebuffer->getStencilbuffer()->getActualFormat() != drawFramebuffer->getStencilbuffer()->getActualFormat())
{
return gl::error(GL_INVALID_OPERATION);
}
blitDepthStencil = true;
readDSBuffer = readFramebuffer->getStencilbuffer();
drawDSBuffer = drawFramebuffer->getStencilbuffer();
}
}
if (partialBufferCopy)
{
ERR("Only whole-buffer depth and stencil blits are supported by this implementation.");
return gl::error(GL_INVALID_OPERATION); // only whole-buffer copies are permitted
}
if ((drawDSBuffer && drawDSBuffer->getSamples() != 0) ||
(readDSBuffer && readDSBuffer->getSamples() != 0))
{
return gl::error(GL_INVALID_OPERATION);
}
}
if (blitRenderTarget || blitDepthStencil)
{
mRenderer->blitRect(readFramebuffer, sourceTrimmedRect, drawFramebuffer, destTrimmedRect, blitRenderTarget, blitDepthStencil);
}
}
}
extern "C"
{
gl::Context *glCreateContext(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess)
{
return new gl::Context(shareContext, renderer, notifyResets, robustAccess);
}
void glDestroyContext(gl::Context *context)
{
delete context;
if (context == gl::getContext())
{
gl::makeCurrent(NULL, NULL, NULL);
}
}
void glMakeCurrent(gl::Context *context, egl::Display *display, egl::Surface *surface)
{
gl::makeCurrent(context, display, surface);
}
gl::Context *glGetCurrentContext()
{
return gl::getContext();
}
}
| 010smithzhang-ddd | src/libGLESv2/Context.cpp | C++ | bsd | 88,642 |
#include "precompiled.h"
//
// Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// HandleAllocator.cpp: Implements the gl::HandleAllocator class, which is used
// to allocate GL handles.
#include "libGLESv2/HandleAllocator.h"
#include "libGLESv2/main.h"
namespace gl
{
HandleAllocator::HandleAllocator() : mBaseValue(1), mNextValue(1)
{
}
HandleAllocator::~HandleAllocator()
{
}
void HandleAllocator::setBaseHandle(GLuint value)
{
ASSERT(mBaseValue == mNextValue);
mBaseValue = value;
mNextValue = value;
}
GLuint HandleAllocator::allocate()
{
if (mFreeValues.size())
{
GLuint handle = mFreeValues.back();
mFreeValues.pop_back();
return handle;
}
return mNextValue++;
}
void HandleAllocator::release(GLuint handle)
{
if (handle == mNextValue - 1)
{
// Don't drop below base value
if(mNextValue > mBaseValue)
{
mNextValue--;
}
}
else
{
// Only free handles that we own - don't drop below the base value
if (handle >= mBaseValue)
{
mFreeValues.push_back(handle);
}
}
}
}
| 010smithzhang-ddd | src/libGLESv2/HandleAllocator.cpp | C++ | bsd | 1,273 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Context.h: Defines the gl::Context class, managing all GL state and performing
// rendering operations. It is the GLES2 specific implementation of EGLContext.
#ifndef LIBGLESV2_CONTEXT_H_
#define LIBGLESV2_CONTEXT_H_
#define GL_APICALL
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#define EGLAPI
#include <EGL/egl.h>
#include <string>
#include <map>
#ifdef _MSC_VER
#include <hash_map>
#else
#include <unordered_map>
#endif
#include "common/angleutils.h"
#include "common/RefCountObject.h"
#include "libGLESv2/HandleAllocator.h"
#include "libGLESv2/angletypes.h"
#include "libGLESv2/Constants.h"
namespace rx
{
class Renderer;
}
namespace egl
{
class Display;
class Surface;
}
namespace gl
{
class Shader;
class Program;
class ProgramBinary;
class Texture;
class Texture2D;
class TextureCubeMap;
class Framebuffer;
class Renderbuffer;
class RenderbufferStorage;
class Colorbuffer;
class Depthbuffer;
class Stencilbuffer;
class DepthStencilbuffer;
class Fence;
class Query;
class ResourceManager;
class Buffer;
enum QueryType
{
QUERY_ANY_SAMPLES_PASSED,
QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE,
QUERY_TYPE_COUNT
};
// Helper structure describing a single vertex attribute
class VertexAttribute
{
public:
VertexAttribute() : mType(GL_FLOAT), mSize(0), mNormalized(false), mStride(0), mPointer(NULL), mArrayEnabled(false), mDivisor(0)
{
mCurrentValue[0] = 0.0f;
mCurrentValue[1] = 0.0f;
mCurrentValue[2] = 0.0f;
mCurrentValue[3] = 1.0f;
}
int typeSize() const
{
switch (mType)
{
case GL_BYTE: return mSize * sizeof(GLbyte);
case GL_UNSIGNED_BYTE: return mSize * sizeof(GLubyte);
case GL_SHORT: return mSize * sizeof(GLshort);
case GL_UNSIGNED_SHORT: return mSize * sizeof(GLushort);
case GL_FIXED: return mSize * sizeof(GLfixed);
case GL_FLOAT: return mSize * sizeof(GLfloat);
default: UNREACHABLE(); return mSize * sizeof(GLfloat);
}
}
GLsizei stride() const
{
return mStride ? mStride : typeSize();
}
// From glVertexAttribPointer
GLenum mType;
GLint mSize;
bool mNormalized;
GLsizei mStride; // 0 means natural stride
union
{
const void *mPointer;
intptr_t mOffset;
};
BindingPointer<Buffer> mBoundBuffer; // Captured when glVertexAttribPointer is called.
bool mArrayEnabled; // From glEnable/DisableVertexAttribArray
float mCurrentValue[4]; // From glVertexAttrib
unsigned int mDivisor;
};
// Helper structure to store all raw state
struct State
{
Color colorClearValue;
GLclampf depthClearValue;
int stencilClearValue;
RasterizerState rasterizer;
bool scissorTest;
Rectangle scissor;
BlendState blend;
Color blendColor;
bool sampleCoverage;
GLclampf sampleCoverageValue;
bool sampleCoverageInvert;
DepthStencilState depthStencil;
GLint stencilRef;
GLint stencilBackRef;
GLfloat lineWidth;
GLenum generateMipmapHint;
GLenum fragmentShaderDerivativeHint;
Rectangle viewport;
float zNear;
float zFar;
unsigned int activeSampler; // Active texture unit selector - GL_TEXTURE0
BindingPointer<Buffer> arrayBuffer;
BindingPointer<Buffer> elementArrayBuffer;
GLuint readFramebuffer;
GLuint drawFramebuffer;
BindingPointer<Renderbuffer> renderbuffer;
GLuint currentProgram;
VertexAttribute vertexAttribute[MAX_VERTEX_ATTRIBS];
BindingPointer<Texture> samplerTexture[TEXTURE_TYPE_COUNT][IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS];
BindingPointer<Query> activeQuery[QUERY_TYPE_COUNT];
GLint unpackAlignment;
GLint packAlignment;
bool packReverseRowOrder;
};
class Context
{
public:
Context(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess);
~Context();
void makeCurrent(egl::Surface *surface);
virtual void markContextLost();
bool isContextLost();
// State manipulation
void setClearColor(float red, float green, float blue, float alpha);
void setClearDepth(float depth);
void setClearStencil(int stencil);
void setCullFace(bool enabled);
bool isCullFaceEnabled() const;
void setCullMode(GLenum mode);
void setFrontFace(GLenum front);
void setDepthTest(bool enabled);
bool isDepthTestEnabled() const;
void setDepthFunc(GLenum depthFunc);
void setDepthRange(float zNear, float zFar);
void setBlend(bool enabled);
bool isBlendEnabled() const;
void setBlendFactors(GLenum sourceRGB, GLenum destRGB, GLenum sourceAlpha, GLenum destAlpha);
void setBlendColor(float red, float green, float blue, float alpha);
void setBlendEquation(GLenum rgbEquation, GLenum alphaEquation);
void setStencilTest(bool enabled);
bool isStencilTestEnabled() const;
void setStencilParams(GLenum stencilFunc, GLint stencilRef, GLuint stencilMask);
void setStencilBackParams(GLenum stencilBackFunc, GLint stencilBackRef, GLuint stencilBackMask);
void setStencilWritemask(GLuint stencilWritemask);
void setStencilBackWritemask(GLuint stencilBackWritemask);
void setStencilOperations(GLenum stencilFail, GLenum stencilPassDepthFail, GLenum stencilPassDepthPass);
void setStencilBackOperations(GLenum stencilBackFail, GLenum stencilBackPassDepthFail, GLenum stencilBackPassDepthPass);
void setPolygonOffsetFill(bool enabled);
bool isPolygonOffsetFillEnabled() const;
void setPolygonOffsetParams(GLfloat factor, GLfloat units);
void setSampleAlphaToCoverage(bool enabled);
bool isSampleAlphaToCoverageEnabled() const;
void setSampleCoverage(bool enabled);
bool isSampleCoverageEnabled() const;
void setSampleCoverageParams(GLclampf value, bool invert);
void setScissorTest(bool enabled);
bool isScissorTestEnabled() const;
void setDither(bool enabled);
bool isDitherEnabled() const;
void setLineWidth(GLfloat width);
void setGenerateMipmapHint(GLenum hint);
void setFragmentShaderDerivativeHint(GLenum hint);
void setViewportParams(GLint x, GLint y, GLsizei width, GLsizei height);
void setScissorParams(GLint x, GLint y, GLsizei width, GLsizei height);
void setColorMask(bool red, bool green, bool blue, bool alpha);
void setDepthMask(bool mask);
void setActiveSampler(unsigned int active);
GLuint getReadFramebufferHandle() const;
GLuint getDrawFramebufferHandle() const;
GLuint getRenderbufferHandle() const;
GLuint getArrayBufferHandle() const;
GLuint getActiveQuery(GLenum target) const;
void setEnableVertexAttribArray(unsigned int attribNum, bool enabled);
const VertexAttribute &getVertexAttribState(unsigned int attribNum);
void setVertexAttribState(unsigned int attribNum, Buffer *boundBuffer, GLint size, GLenum type,
bool normalized, GLsizei stride, const void *pointer);
const void *getVertexAttribPointer(unsigned int attribNum) const;
void setUnpackAlignment(GLint alignment);
GLint getUnpackAlignment() const;
void setPackAlignment(GLint alignment);
GLint getPackAlignment() const;
void setPackReverseRowOrder(bool reverseRowOrder);
bool getPackReverseRowOrder() const;
// These create and destroy methods are merely pass-throughs to
// ResourceManager, which owns these object types
GLuint createBuffer();
GLuint createShader(GLenum type);
GLuint createProgram();
GLuint createTexture();
GLuint createRenderbuffer();
void deleteBuffer(GLuint buffer);
void deleteShader(GLuint shader);
void deleteProgram(GLuint program);
void deleteTexture(GLuint texture);
void deleteRenderbuffer(GLuint renderbuffer);
// Framebuffers are owned by the Context, so these methods do not pass through
GLuint createFramebuffer();
void deleteFramebuffer(GLuint framebuffer);
// Fences are owned by the Context.
GLuint createFence();
void deleteFence(GLuint fence);
// Queries are owned by the Context;
GLuint createQuery();
void deleteQuery(GLuint query);
void bindArrayBuffer(GLuint buffer);
void bindElementArrayBuffer(GLuint buffer);
void bindTexture2D(GLuint texture);
void bindTextureCubeMap(GLuint texture);
void bindReadFramebuffer(GLuint framebuffer);
void bindDrawFramebuffer(GLuint framebuffer);
void bindRenderbuffer(GLuint renderbuffer);
void useProgram(GLuint program);
void linkProgram(GLuint program);
void setProgramBinary(GLuint program, const void *binary, GLint length);
void beginQuery(GLenum target, GLuint query);
void endQuery(GLenum target);
void setFramebufferZero(Framebuffer *framebuffer);
void setRenderbufferStorage(GLsizei width, GLsizei height, GLenum internalformat, GLsizei samples);
void setVertexAttrib(GLuint index, const GLfloat *values);
void setVertexAttribDivisor(GLuint index, GLuint divisor);
Buffer *getBuffer(GLuint handle);
Fence *getFence(GLuint handle);
Shader *getShader(GLuint handle);
Program *getProgram(GLuint handle);
Texture *getTexture(GLuint handle);
Framebuffer *getFramebuffer(GLuint handle);
Renderbuffer *getRenderbuffer(GLuint handle);
Query *getQuery(GLuint handle, bool create, GLenum type);
Buffer *getArrayBuffer();
Buffer *getElementArrayBuffer();
ProgramBinary *getCurrentProgramBinary();
Texture2D *getTexture2D();
TextureCubeMap *getTextureCubeMap();
Texture *getSamplerTexture(unsigned int sampler, TextureType type);
Framebuffer *getReadFramebuffer();
Framebuffer *getDrawFramebuffer();
bool getFloatv(GLenum pname, GLfloat *params);
bool getIntegerv(GLenum pname, GLint *params);
bool getBooleanv(GLenum pname, GLboolean *params);
bool getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams);
void readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei *bufSize, void* pixels);
void clear(GLbitfield mask);
void drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instances);
void drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei instances);
void sync(bool block); // flush/finish
void recordInvalidEnum();
void recordInvalidValue();
void recordInvalidOperation();
void recordOutOfMemory();
void recordInvalidFramebufferOperation();
GLenum getError();
GLenum getResetStatus();
virtual bool isResetNotificationEnabled();
int getMajorShaderModel() const;
float getMaximumPointSize() const;
unsigned int getMaximumCombinedTextureImageUnits() const;
int getMaximumRenderbufferDimension() const;
int getMaximumTextureDimension() const;
int getMaximumCubeTextureDimension() const;
int getMaximumTextureLevel() const;
unsigned int getMaximumRenderTargets() const;
GLsizei getMaxSupportedSamples() const;
const char *getExtensionString() const;
const char *getRendererString() const;
bool supportsEventQueries() const;
bool supportsOcclusionQueries() const;
bool supportsBGRATextures() const;
bool supportsDXT1Textures() const;
bool supportsDXT3Textures() const;
bool supportsDXT5Textures() const;
bool supportsFloat32Textures() const;
bool supportsFloat32LinearFilter() const;
bool supportsFloat32RenderableTextures() const;
bool supportsFloat16Textures() const;
bool supportsFloat16LinearFilter() const;
bool supportsFloat16RenderableTextures() const;
bool supportsLuminanceTextures() const;
bool supportsLuminanceAlphaTextures() const;
bool supportsDepthTextures() const;
bool supports32bitIndices() const;
bool supportsNonPower2Texture() const;
bool supportsInstancing() const;
bool supportsTextureFilterAnisotropy() const;
bool getCurrentReadFormatType(GLenum *format, GLenum *type);
float getTextureMaxAnisotropy() const;
void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
GLbitfield mask);
private:
DISALLOW_COPY_AND_ASSIGN(Context);
bool applyRenderTarget(GLenum drawMode, bool ignoreViewport);
void applyState(GLenum drawMode);
void applyShaders();
void applyTextures();
void applyTextures(SamplerType type);
void detachBuffer(GLuint buffer);
void detachTexture(GLuint texture);
void detachFramebuffer(GLuint framebuffer);
void detachRenderbuffer(GLuint renderbuffer);
Texture *getIncompleteTexture(TextureType type);
bool skipDraw(GLenum drawMode);
void initExtensionString();
void initRendererString();
rx::Renderer *const mRenderer;
State mState;
BindingPointer<Texture2D> mTexture2DZero;
BindingPointer<TextureCubeMap> mTextureCubeMapZero;
#ifndef HASH_MAP
# ifdef _MSC_VER
# define HASH_MAP stdext::hash_map
# else
# define HASH_MAP std::unordered_map
# endif
#endif
typedef HASH_MAP<GLuint, Framebuffer*> FramebufferMap;
FramebufferMap mFramebufferMap;
HandleAllocator mFramebufferHandleAllocator;
typedef HASH_MAP<GLuint, Fence*> FenceMap;
FenceMap mFenceMap;
HandleAllocator mFenceHandleAllocator;
typedef HASH_MAP<GLuint, Query*> QueryMap;
QueryMap mQueryMap;
HandleAllocator mQueryHandleAllocator;
const char *mExtensionString;
const char *mRendererString;
BindingPointer<Texture> mIncompleteTextures[TEXTURE_TYPE_COUNT];
// Recorded errors
bool mInvalidEnum;
bool mInvalidValue;
bool mInvalidOperation;
bool mOutOfMemory;
bool mInvalidFramebufferOperation;
// Current/lost context flags
bool mHasBeenCurrent;
bool mContextLost;
GLenum mResetStatus;
GLenum mResetStrategy;
bool mRobustAccess;
BindingPointer<ProgramBinary> mCurrentProgramBinary;
Framebuffer *mBoundDrawFramebuffer;
int mMajorShaderModel;
float mMaximumPointSize;
bool mSupportsVertexTexture;
bool mSupportsNonPower2Texture;
bool mSupportsInstancing;
int mMaxViewportDimension;
int mMaxRenderbufferDimension;
int mMaxTextureDimension;
int mMaxCubeTextureDimension;
int mMaxTextureLevel;
float mMaxTextureAnisotropy;
bool mSupportsEventQueries;
bool mSupportsOcclusionQueries;
bool mSupportsBGRATextures;
bool mSupportsDXT1Textures;
bool mSupportsDXT3Textures;
bool mSupportsDXT5Textures;
bool mSupportsFloat32Textures;
bool mSupportsFloat32LinearFilter;
bool mSupportsFloat32RenderableTextures;
bool mSupportsFloat16Textures;
bool mSupportsFloat16LinearFilter;
bool mSupportsFloat16RenderableTextures;
bool mSupportsLuminanceTextures;
bool mSupportsLuminanceAlphaTextures;
bool mSupportsDepthTextures;
bool mSupports32bitIndices;
bool mSupportsTextureFilterAnisotropy;
int mNumCompressedTextureFormats;
ResourceManager *mResourceManager;
};
}
#endif // INCLUDE_CONTEXT_H_
| 010smithzhang-ddd | src/libGLESv2/Context.h | C++ | bsd | 15,406 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// libGLESv2.cpp: Implements the exported OpenGL ES 2.0 functions.
#include "common/version.h"
#include "libGLESv2/main.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/Fence.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/Query.h"
#include "libGLESv2/Context.h"
bool validImageSize(GLint level, GLsizei width, GLsizei height)
{
if (level < 0 || width < 0 || height < 0)
{
return false;
}
if (gl::getContext() && gl::getContext()->supportsNonPower2Texture())
{
return true;
}
if (level == 0)
{
return true;
}
if (gl::isPow2(width) && gl::isPow2(height))
{
return true;
}
return false;
}
// Verify that format/type are one of the combinations from table 3.4.
bool checkTextureFormatType(GLenum format, GLenum type)
{
// validate <format> by itself (used as secondary key below)
switch (format)
{
case GL_RGBA:
case GL_BGRA_EXT:
case GL_RGB:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
case GL_DEPTH_COMPONENT:
case GL_DEPTH_STENCIL_OES:
break;
default:
return gl::error(GL_INVALID_ENUM, false);
}
// invalid <type> -> sets INVALID_ENUM
// invalid <format>+<type> combination -> sets INVALID_OPERATION
switch (type)
{
case GL_UNSIGNED_BYTE:
switch (format)
{
case GL_RGBA:
case GL_BGRA_EXT:
case GL_RGB:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
case GL_FLOAT:
case GL_HALF_FLOAT_OES:
switch (format)
{
case GL_RGBA:
case GL_RGB:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
switch (format)
{
case GL_RGBA:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
case GL_UNSIGNED_SHORT_5_6_5:
switch (format)
{
case GL_RGB:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
case GL_UNSIGNED_SHORT:
case GL_UNSIGNED_INT:
switch (format)
{
case GL_DEPTH_COMPONENT:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
case GL_UNSIGNED_INT_24_8_OES:
switch (format)
{
case GL_DEPTH_STENCIL_OES:
return true;
default:
return gl::error(GL_INVALID_OPERATION, false);
}
default:
return gl::error(GL_INVALID_ENUM, false);
}
}
bool validateSubImageParams2D(bool compressed, GLsizei width, GLsizei height,
GLint xoffset, GLint yoffset, GLint level, GLenum format, GLenum type,
gl::Texture2D *texture)
{
if (!texture)
{
return gl::error(GL_INVALID_OPERATION, false);
}
if (compressed != texture->isCompressed(level))
{
return gl::error(GL_INVALID_OPERATION, false);
}
if (format != GL_NONE)
{
GLenum internalformat = gl::ConvertSizedInternalFormat(format, type);
if (internalformat != texture->getInternalFormat(level))
{
return gl::error(GL_INVALID_OPERATION, false);
}
}
if (compressed)
{
if ((width % 4 != 0 && width != texture->getWidth(0)) ||
(height % 4 != 0 && height != texture->getHeight(0)))
{
return gl::error(GL_INVALID_OPERATION, false);
}
}
if (xoffset + width > texture->getWidth(level) ||
yoffset + height > texture->getHeight(level))
{
return gl::error(GL_INVALID_VALUE, false);
}
return true;
}
bool validateSubImageParamsCube(bool compressed, GLsizei width, GLsizei height,
GLint xoffset, GLint yoffset, GLenum target, GLint level, GLenum format, GLenum type,
gl::TextureCubeMap *texture)
{
if (!texture)
{
return gl::error(GL_INVALID_OPERATION, false);
}
if (compressed != texture->isCompressed(target, level))
{
return gl::error(GL_INVALID_OPERATION, false);
}
if (format != GL_NONE)
{
GLenum internalformat = gl::ConvertSizedInternalFormat(format, type);
if (internalformat != texture->getInternalFormat(target, level))
{
return gl::error(GL_INVALID_OPERATION, false);
}
}
if (compressed)
{
if ((width % 4 != 0 && width != texture->getWidth(target, 0)) ||
(height % 4 != 0 && height != texture->getHeight(target, 0)))
{
return gl::error(GL_INVALID_OPERATION, false);
}
}
if (xoffset + width > texture->getWidth(target, level) ||
yoffset + height > texture->getHeight(target, level))
{
return gl::error(GL_INVALID_VALUE, false);
}
return true;
}
// check for combinations of format and type that are valid for ReadPixels
bool validReadFormatType(GLenum format, GLenum type)
{
switch (format)
{
case GL_RGBA:
switch (type)
{
case GL_UNSIGNED_BYTE:
break;
default:
return false;
}
break;
case GL_BGRA_EXT:
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
break;
default:
return false;
}
break;
default:
return false;
}
return true;
}
extern "C"
{
void __stdcall glActiveTexture(GLenum texture)
{
EVENT("(GLenum texture = 0x%X)", texture);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (texture < GL_TEXTURE0 || texture > GL_TEXTURE0 + context->getMaximumCombinedTextureImageUnits() - 1)
{
return gl::error(GL_INVALID_ENUM);
}
context->setActiveSampler(texture - GL_TEXTURE0);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glAttachShader(GLuint program, GLuint shader)
{
EVENT("(GLuint program = %d, GLuint shader = %d)", program, shader);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
gl::Shader *shaderObject = context->getShader(shader);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (!shaderObject)
{
if (context->getProgram(shader))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (!programObject->attachShader(shaderObject))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBeginQueryEXT(GLenum target, GLuint id)
{
EVENT("(GLenum target = 0x%X, GLuint %d)", target, id);
try
{
switch (target)
{
case GL_ANY_SAMPLES_PASSED_EXT:
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (id == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->beginQuery(target, id);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBindAttribLocation(GLuint program, GLuint index, const GLchar* name)
{
EVENT("(GLuint program = %d, GLuint index = %d, const GLchar* name = 0x%0.8p)", program, index, name);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (strncmp(name, "gl_", 3) == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
programObject->bindAttributeLocation(index, name);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBindBuffer(GLenum target, GLuint buffer)
{
EVENT("(GLenum target = 0x%X, GLuint buffer = %d)", target, buffer);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (target)
{
case GL_ARRAY_BUFFER:
context->bindArrayBuffer(buffer);
return;
case GL_ELEMENT_ARRAY_BUFFER:
context->bindElementArrayBuffer(buffer);
return;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBindFramebuffer(GLenum target, GLuint framebuffer)
{
EVENT("(GLenum target = 0x%X, GLuint framebuffer = %d)", target, framebuffer);
try
{
if (target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER_ANGLE && target != GL_READ_FRAMEBUFFER_ANGLE)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (target == GL_READ_FRAMEBUFFER_ANGLE || target == GL_FRAMEBUFFER)
{
context->bindReadFramebuffer(framebuffer);
}
if (target == GL_DRAW_FRAMEBUFFER_ANGLE || target == GL_FRAMEBUFFER)
{
context->bindDrawFramebuffer(framebuffer);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBindRenderbuffer(GLenum target, GLuint renderbuffer)
{
EVENT("(GLenum target = 0x%X, GLuint renderbuffer = %d)", target, renderbuffer);
try
{
if (target != GL_RENDERBUFFER)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->bindRenderbuffer(renderbuffer);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBindTexture(GLenum target, GLuint texture)
{
EVENT("(GLenum target = 0x%X, GLuint texture = %d)", target, texture);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture *textureObject = context->getTexture(texture);
if (textureObject && textureObject->getTarget() != target && texture != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
switch (target)
{
case GL_TEXTURE_2D:
context->bindTexture2D(texture);
return;
case GL_TEXTURE_CUBE_MAP:
context->bindTextureCubeMap(texture);
return;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
{
EVENT("(GLclampf red = %f, GLclampf green = %f, GLclampf blue = %f, GLclampf alpha = %f)",
red, green, blue, alpha);
try
{
gl::Context* context = gl::getNonLostContext();
if (context)
{
context->setBlendColor(gl::clamp01(red), gl::clamp01(green), gl::clamp01(blue), gl::clamp01(alpha));
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBlendEquation(GLenum mode)
{
glBlendEquationSeparate(mode, mode);
}
void __stdcall glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha)
{
EVENT("(GLenum modeRGB = 0x%X, GLenum modeAlpha = 0x%X)", modeRGB, modeAlpha);
try
{
switch (modeRGB)
{
case GL_FUNC_ADD:
case GL_FUNC_SUBTRACT:
case GL_FUNC_REVERSE_SUBTRACT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (modeAlpha)
{
case GL_FUNC_ADD:
case GL_FUNC_SUBTRACT:
case GL_FUNC_REVERSE_SUBTRACT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setBlendEquation(modeRGB, modeAlpha);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBlendFunc(GLenum sfactor, GLenum dfactor)
{
glBlendFuncSeparate(sfactor, dfactor, sfactor, dfactor);
}
void __stdcall glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
{
EVENT("(GLenum srcRGB = 0x%X, GLenum dstRGB = 0x%X, GLenum srcAlpha = 0x%X, GLenum dstAlpha = 0x%X)",
srcRGB, dstRGB, srcAlpha, dstAlpha);
try
{
switch (srcRGB)
{
case GL_ZERO:
case GL_ONE:
case GL_SRC_COLOR:
case GL_ONE_MINUS_SRC_COLOR:
case GL_DST_COLOR:
case GL_ONE_MINUS_DST_COLOR:
case GL_SRC_ALPHA:
case GL_ONE_MINUS_SRC_ALPHA:
case GL_DST_ALPHA:
case GL_ONE_MINUS_DST_ALPHA:
case GL_CONSTANT_COLOR:
case GL_ONE_MINUS_CONSTANT_COLOR:
case GL_CONSTANT_ALPHA:
case GL_ONE_MINUS_CONSTANT_ALPHA:
case GL_SRC_ALPHA_SATURATE:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (dstRGB)
{
case GL_ZERO:
case GL_ONE:
case GL_SRC_COLOR:
case GL_ONE_MINUS_SRC_COLOR:
case GL_DST_COLOR:
case GL_ONE_MINUS_DST_COLOR:
case GL_SRC_ALPHA:
case GL_ONE_MINUS_SRC_ALPHA:
case GL_DST_ALPHA:
case GL_ONE_MINUS_DST_ALPHA:
case GL_CONSTANT_COLOR:
case GL_ONE_MINUS_CONSTANT_COLOR:
case GL_CONSTANT_ALPHA:
case GL_ONE_MINUS_CONSTANT_ALPHA:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (srcAlpha)
{
case GL_ZERO:
case GL_ONE:
case GL_SRC_COLOR:
case GL_ONE_MINUS_SRC_COLOR:
case GL_DST_COLOR:
case GL_ONE_MINUS_DST_COLOR:
case GL_SRC_ALPHA:
case GL_ONE_MINUS_SRC_ALPHA:
case GL_DST_ALPHA:
case GL_ONE_MINUS_DST_ALPHA:
case GL_CONSTANT_COLOR:
case GL_ONE_MINUS_CONSTANT_COLOR:
case GL_CONSTANT_ALPHA:
case GL_ONE_MINUS_CONSTANT_ALPHA:
case GL_SRC_ALPHA_SATURATE:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (dstAlpha)
{
case GL_ZERO:
case GL_ONE:
case GL_SRC_COLOR:
case GL_ONE_MINUS_SRC_COLOR:
case GL_DST_COLOR:
case GL_ONE_MINUS_DST_COLOR:
case GL_SRC_ALPHA:
case GL_ONE_MINUS_SRC_ALPHA:
case GL_DST_ALPHA:
case GL_ONE_MINUS_DST_ALPHA:
case GL_CONSTANT_COLOR:
case GL_ONE_MINUS_CONSTANT_COLOR:
case GL_CONSTANT_ALPHA:
case GL_ONE_MINUS_CONSTANT_ALPHA:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
bool constantColorUsed = (srcRGB == GL_CONSTANT_COLOR || srcRGB == GL_ONE_MINUS_CONSTANT_COLOR ||
dstRGB == GL_CONSTANT_COLOR || dstRGB == GL_ONE_MINUS_CONSTANT_COLOR);
bool constantAlphaUsed = (srcRGB == GL_CONSTANT_ALPHA || srcRGB == GL_ONE_MINUS_CONSTANT_ALPHA ||
dstRGB == GL_CONSTANT_ALPHA || dstRGB == GL_ONE_MINUS_CONSTANT_ALPHA);
if (constantColorUsed && constantAlphaUsed)
{
ERR("Simultaneous use of GL_CONSTANT_ALPHA/GL_ONE_MINUS_CONSTANT_ALPHA and GL_CONSTANT_COLOR/GL_ONE_MINUS_CONSTANT_COLOR invalid under WebGL");
return gl::error(GL_INVALID_OPERATION);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setBlendFactors(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBufferData(GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage)
{
EVENT("(GLenum target = 0x%X, GLsizeiptr size = %d, const GLvoid* data = 0x%0.8p, GLenum usage = %d)",
target, size, data, usage);
try
{
if (size < 0)
{
return gl::error(GL_INVALID_VALUE);
}
switch (usage)
{
case GL_STREAM_DRAW:
case GL_STATIC_DRAW:
case GL_DYNAMIC_DRAW:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Buffer *buffer;
switch (target)
{
case GL_ARRAY_BUFFER:
buffer = context->getArrayBuffer();
break;
case GL_ELEMENT_ARRAY_BUFFER:
buffer = context->getElementArrayBuffer();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (!buffer)
{
return gl::error(GL_INVALID_OPERATION);
}
buffer->bufferData(data, size, usage);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data)
{
EVENT("(GLenum target = 0x%X, GLintptr offset = %d, GLsizeiptr size = %d, const GLvoid* data = 0x%0.8p)",
target, offset, size, data);
try
{
if (size < 0 || offset < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (data == NULL)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Buffer *buffer;
switch (target)
{
case GL_ARRAY_BUFFER:
buffer = context->getArrayBuffer();
break;
case GL_ELEMENT_ARRAY_BUFFER:
buffer = context->getElementArrayBuffer();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (!buffer)
{
return gl::error(GL_INVALID_OPERATION);
}
if ((size_t)size + offset > buffer->size())
{
return gl::error(GL_INVALID_VALUE);
}
buffer->bufferSubData(data, size, offset);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLenum __stdcall glCheckFramebufferStatus(GLenum target)
{
EVENT("(GLenum target = 0x%X)", target);
try
{
if (target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER_ANGLE && target != GL_READ_FRAMEBUFFER_ANGLE)
{
return gl::error(GL_INVALID_ENUM, 0);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Framebuffer *framebuffer = NULL;
if (target == GL_READ_FRAMEBUFFER_ANGLE)
{
framebuffer = context->getReadFramebuffer();
}
else
{
framebuffer = context->getDrawFramebuffer();
}
return framebuffer->completeness();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, 0);
}
return 0;
}
void __stdcall glClear(GLbitfield mask)
{
EVENT("(GLbitfield mask = %X)", mask);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->clear(mask);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
{
EVENT("(GLclampf red = %f, GLclampf green = %f, GLclampf blue = %f, GLclampf alpha = %f)",
red, green, blue, alpha);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setClearColor(red, green, blue, alpha);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glClearDepthf(GLclampf depth)
{
EVENT("(GLclampf depth = %f)", depth);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setClearDepth(depth);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glClearStencil(GLint s)
{
EVENT("(GLint s = %d)", s);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setClearStencil(s);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
{
EVENT("(GLboolean red = %d, GLboolean green = %d, GLboolean blue = %d, GLboolean alpha = %d)",
red, green, blue, alpha);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setColorMask(red == GL_TRUE, green == GL_TRUE, blue == GL_TRUE, alpha == GL_TRUE);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glCompileShader(GLuint shader)
{
EVENT("(GLuint shader = %d)", shader);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
if (context->getProgram(shader))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
shaderObject->compile();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height,
GLint border, GLsizei imageSize, const GLvoid* data)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLenum internalformat = 0x%X, GLsizei width = %d, "
"GLsizei height = %d, GLint border = %d, GLsizei imageSize = %d, const GLvoid* data = 0x%0.8p)",
target, level, internalformat, width, height, border, imageSize, data);
try
{
if (!validImageSize(level, width, height) || border != 0 || imageSize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
switch (internalformat)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (border != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
if (width != 1 && width != 2 && width % 4 != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
if (height != 1 && height != 2 && height % 4 != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
switch (target)
{
case GL_TEXTURE_2D:
if (width > (context->getMaximumTextureDimension() >> level) ||
height > (context->getMaximumTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
if (width != height)
{
return gl::error(GL_INVALID_VALUE);
}
if (width > (context->getMaximumCubeTextureDimension() >> level) ||
height > (context->getMaximumCubeTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (internalformat) {
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (!context->supportsDXT1Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
if (!context->supportsDXT3Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
if (!context->supportsDXT5Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
default: UNREACHABLE();
}
if (imageSize != gl::ComputeCompressedSize(width, height, internalformat))
{
return gl::error(GL_INVALID_VALUE);
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->setCompressedImage(level, internalformat, width, height, imageSize, data);
}
else
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
switch (target)
{
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
texture->setCompressedImage(target, level, internalformat, width, height, imageSize, data);
break;
default: UNREACHABLE();
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLenum format, GLsizei imageSize, const GLvoid* data)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLint xoffset = %d, GLint yoffset = %d, "
"GLsizei width = %d, GLsizei height = %d, GLenum format = 0x%X, "
"GLsizei imageSize = %d, const GLvoid* data = 0x%0.8p)",
target, level, xoffset, yoffset, width, height, format, imageSize, data);
try
{
if (!gl::IsInternalTextureTarget(target))
{
return gl::error(GL_INVALID_ENUM);
}
if (xoffset < 0 || yoffset < 0 || !validImageSize(level, width, height) || imageSize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
switch (format)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (width == 0 || height == 0 || data == NULL)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
switch (format) {
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (!context->supportsDXT1Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
if (!context->supportsDXT3Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
if (!context->supportsDXT5Textures())
{
return gl::error(GL_INVALID_ENUM); // in this case, it's as though the internal format switch failed
}
break;
default: UNREACHABLE();
}
if (imageSize != gl::ComputeCompressedSize(width, height, format))
{
return gl::error(GL_INVALID_VALUE);
}
if (xoffset % 4 != 0 || yoffset % 4 != 0)
{
return gl::error(GL_INVALID_OPERATION); // we wait to check the offsets until this point, because the multiple-of-four restriction
// does not exist unless DXT textures are supported.
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (validateSubImageParams2D(true, width, height, xoffset, yoffset, level, format, GL_NONE, texture))
{
texture->subImageCompressed(level, xoffset, yoffset, width, height, format, imageSize, data);
}
}
else if (gl::IsCubemapTextureTarget(target))
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (validateSubImageParamsCube(true, width, height, xoffset, yoffset, target, level, format, GL_NONE, texture))
{
texture->subImageCompressed(target, level, xoffset, yoffset, width, height, format, imageSize, data);
}
}
else
{
UNREACHABLE();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLenum internalformat = 0x%X, "
"GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d, GLint border = %d)",
target, level, internalformat, x, y, width, height, border);
try
{
if (!validImageSize(level, width, height))
{
return gl::error(GL_INVALID_VALUE);
}
if (border != 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
switch (target)
{
case GL_TEXTURE_2D:
if (width > (context->getMaximumTextureDimension() >> level) ||
height > (context->getMaximumTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
if (width != height)
{
return gl::error(GL_INVALID_VALUE);
}
if (width > (context->getMaximumCubeTextureDimension() >> level) ||
height > (context->getMaximumCubeTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Framebuffer *framebuffer = context->getReadFramebuffer();
if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION);
}
if (context->getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Renderbuffer *source = framebuffer->getReadColorbuffer();
GLenum colorbufferFormat = source->getInternalFormat();
// [OpenGL ES 2.0.24] table 3.9
switch (internalformat)
{
case GL_ALPHA:
if (colorbufferFormat != GL_ALPHA8_EXT &&
colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_BGRA8_EXT &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_LUMINANCE:
case GL_RGB:
if (colorbufferFormat != GL_RGB565 &&
colorbufferFormat != GL_RGB8_OES &&
colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_BGRA8_EXT &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_LUMINANCE_ALPHA:
case GL_RGBA:
if (colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_BGRA8_EXT &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (context->supportsDXT1Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
if (context->supportsDXT3Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
if (context->supportsDXT5Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT32_OES:
case GL_DEPTH_STENCIL_OES:
case GL_DEPTH24_STENCIL8_OES:
if (context->supportsDepthTextures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
default:
return gl::error(GL_INVALID_ENUM);
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->copyImage(level, internalformat, x, y, width, height, framebuffer);
}
else if (gl::IsCubemapTextureTarget(target))
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->copyImage(target, level, internalformat, x, y, width, height, framebuffer);
}
else UNREACHABLE();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLint xoffset = %d, GLint yoffset = %d, "
"GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d)",
target, level, xoffset, yoffset, x, y, width, height);
try
{
if (!gl::IsInternalTextureTarget(target))
{
return gl::error(GL_INVALID_ENUM);
}
if (level < 0 || xoffset < 0 || yoffset < 0 || width < 0 || height < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (std::numeric_limits<GLsizei>::max() - xoffset < width || std::numeric_limits<GLsizei>::max() - yoffset < height)
{
return gl::error(GL_INVALID_VALUE);
}
if (width == 0 || height == 0)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
gl::Framebuffer *framebuffer = context->getReadFramebuffer();
if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
{
return gl::error(GL_INVALID_FRAMEBUFFER_OPERATION);
}
if (context->getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Renderbuffer *source = framebuffer->getReadColorbuffer();
GLenum colorbufferFormat = source->getInternalFormat();
gl::Texture *texture = NULL;
GLenum textureFormat = GL_RGBA;
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *tex2d = context->getTexture2D();
if (!validateSubImageParams2D(false, width, height, xoffset, yoffset, level, GL_NONE, GL_NONE, tex2d))
{
return; // error already registered by validateSubImageParams
}
textureFormat = gl::ExtractFormat(tex2d->getInternalFormat(level));
texture = tex2d;
}
else if (gl::IsCubemapTextureTarget(target))
{
gl::TextureCubeMap *texcube = context->getTextureCubeMap();
if (!validateSubImageParamsCube(false, width, height, xoffset, yoffset, target, level, GL_NONE, GL_NONE, texcube))
{
return; // error already registered by validateSubImageParams
}
textureFormat = gl::ExtractFormat(texcube->getInternalFormat(target, level));
texture = texcube;
}
else UNREACHABLE();
// [OpenGL ES 2.0.24] table 3.9
switch (textureFormat)
{
case GL_ALPHA:
if (colorbufferFormat != GL_ALPHA8_EXT &&
colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_LUMINANCE:
case GL_RGB:
if (colorbufferFormat != GL_RGB565 &&
colorbufferFormat != GL_RGB8_OES &&
colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_LUMINANCE_ALPHA:
case GL_RGBA:
if (colorbufferFormat != GL_RGBA4 &&
colorbufferFormat != GL_RGB5_A1 &&
colorbufferFormat != GL_RGBA8_OES)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
return gl::error(GL_INVALID_OPERATION);
case GL_DEPTH_COMPONENT:
case GL_DEPTH_STENCIL_OES:
return gl::error(GL_INVALID_OPERATION);
default:
return gl::error(GL_INVALID_OPERATION);
}
texture->copySubImage(target, level, xoffset, yoffset, x, y, width, height, framebuffer);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLuint __stdcall glCreateProgram(void)
{
EVENT("()");
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
return context->createProgram();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, 0);
}
return 0;
}
GLuint __stdcall glCreateShader(GLenum type)
{
EVENT("(GLenum type = 0x%X)", type);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (type)
{
case GL_FRAGMENT_SHADER:
case GL_VERTEX_SHADER:
return context->createShader(type);
default:
return gl::error(GL_INVALID_ENUM, 0);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, 0);
}
return 0;
}
void __stdcall glCullFace(GLenum mode)
{
EVENT("(GLenum mode = 0x%X)", mode);
try
{
switch (mode)
{
case GL_FRONT:
case GL_BACK:
case GL_FRONT_AND_BACK:
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setCullMode(mode);
}
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteBuffers(GLsizei n, const GLuint* buffers)
{
EVENT("(GLsizei n = %d, const GLuint* buffers = 0x%0.8p)", n, buffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
context->deleteBuffer(buffers[i]);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteFencesNV(GLsizei n, const GLuint* fences)
{
EVENT("(GLsizei n = %d, const GLuint* fences = 0x%0.8p)", n, fences);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
context->deleteFence(fences[i]);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers)
{
EVENT("(GLsizei n = %d, const GLuint* framebuffers = 0x%0.8p)", n, framebuffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
if (framebuffers[i] != 0)
{
context->deleteFramebuffer(framebuffers[i]);
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteProgram(GLuint program)
{
EVENT("(GLuint program = %d)", program);
try
{
if (program == 0)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (!context->getProgram(program))
{
if(context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
context->deleteProgram(program);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteQueriesEXT(GLsizei n, const GLuint *ids)
{
EVENT("(GLsizei n = %d, const GLuint *ids = 0x%0.8p)", n, ids);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
context->deleteQuery(ids[i]);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers)
{
EVENT("(GLsizei n = %d, const GLuint* renderbuffers = 0x%0.8p)", n, renderbuffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
context->deleteRenderbuffer(renderbuffers[i]);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteShader(GLuint shader)
{
EVENT("(GLuint shader = %d)", shader);
try
{
if (shader == 0)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (!context->getShader(shader))
{
if(context->getProgram(shader))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
context->deleteShader(shader);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDeleteTextures(GLsizei n, const GLuint* textures)
{
EVENT("(GLsizei n = %d, const GLuint* textures = 0x%0.8p)", n, textures);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
if (textures[i] != 0)
{
context->deleteTexture(textures[i]);
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDepthFunc(GLenum func)
{
EVENT("(GLenum func = 0x%X)", func);
try
{
switch (func)
{
case GL_NEVER:
case GL_ALWAYS:
case GL_LESS:
case GL_LEQUAL:
case GL_EQUAL:
case GL_GREATER:
case GL_GEQUAL:
case GL_NOTEQUAL:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setDepthFunc(func);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDepthMask(GLboolean flag)
{
EVENT("(GLboolean flag = %d)", flag);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setDepthMask(flag != GL_FALSE);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDepthRangef(GLclampf zNear, GLclampf zFar)
{
EVENT("(GLclampf zNear = %f, GLclampf zFar = %f)", zNear, zFar);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setDepthRange(zNear, zFar);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDetachShader(GLuint program, GLuint shader)
{
EVENT("(GLuint program = %d, GLuint shader = %d)", program, shader);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
gl::Shader *shaderObject = context->getShader(shader);
if (!programObject)
{
gl::Shader *shaderByProgramHandle;
shaderByProgramHandle = context->getShader(program);
if (!shaderByProgramHandle)
{
return gl::error(GL_INVALID_VALUE);
}
else
{
return gl::error(GL_INVALID_OPERATION);
}
}
if (!shaderObject)
{
gl::Program *programByShaderHandle = context->getProgram(shader);
if (!programByShaderHandle)
{
return gl::error(GL_INVALID_VALUE);
}
else
{
return gl::error(GL_INVALID_OPERATION);
}
}
if (!programObject->detachShader(shaderObject))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDisable(GLenum cap)
{
EVENT("(GLenum cap = 0x%X)", cap);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (cap)
{
case GL_CULL_FACE: context->setCullFace(false); break;
case GL_POLYGON_OFFSET_FILL: context->setPolygonOffsetFill(false); break;
case GL_SAMPLE_ALPHA_TO_COVERAGE: context->setSampleAlphaToCoverage(false); break;
case GL_SAMPLE_COVERAGE: context->setSampleCoverage(false); break;
case GL_SCISSOR_TEST: context->setScissorTest(false); break;
case GL_STENCIL_TEST: context->setStencilTest(false); break;
case GL_DEPTH_TEST: context->setDepthTest(false); break;
case GL_BLEND: context->setBlend(false); break;
case GL_DITHER: context->setDither(false); break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDisableVertexAttribArray(GLuint index)
{
EVENT("(GLuint index = %d)", index);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setEnableVertexAttribArray(index, false);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDrawArrays(GLenum mode, GLint first, GLsizei count)
{
EVENT("(GLenum mode = 0x%X, GLint first = %d, GLsizei count = %d)", mode, first, count);
try
{
if (count < 0 || first < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->drawArrays(mode, first, count, 0);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDrawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount)
{
EVENT("(GLenum mode = 0x%X, GLint first = %d, GLsizei count = %d, GLsizei primcount = %d)", mode, first, count, primcount);
try
{
if (count < 0 || first < 0 || primcount < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (primcount > 0)
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->drawArrays(mode, first, count, primcount);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices)
{
EVENT("(GLenum mode = 0x%X, GLsizei count = %d, GLenum type = 0x%X, const GLvoid* indices = 0x%0.8p)",
mode, count, type, indices);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT:
break;
case GL_UNSIGNED_INT:
if (!context->supports32bitIndices())
{
return gl::error(GL_INVALID_ENUM);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
context->drawElements(mode, count, type, indices, 0);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDrawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount)
{
EVENT("(GLenum mode = 0x%X, GLsizei count = %d, GLenum type = 0x%X, const GLvoid* indices = 0x%0.8p, GLsizei primcount = %d)",
mode, count, type, indices, primcount);
try
{
if (count < 0 || primcount < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (primcount > 0)
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT:
break;
case GL_UNSIGNED_INT:
if (!context->supports32bitIndices())
{
return gl::error(GL_INVALID_ENUM);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
context->drawElements(mode, count, type, indices, primcount);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glEnable(GLenum cap)
{
EVENT("(GLenum cap = 0x%X)", cap);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (cap)
{
case GL_CULL_FACE: context->setCullFace(true); break;
case GL_POLYGON_OFFSET_FILL: context->setPolygonOffsetFill(true); break;
case GL_SAMPLE_ALPHA_TO_COVERAGE: context->setSampleAlphaToCoverage(true); break;
case GL_SAMPLE_COVERAGE: context->setSampleCoverage(true); break;
case GL_SCISSOR_TEST: context->setScissorTest(true); break;
case GL_STENCIL_TEST: context->setStencilTest(true); break;
case GL_DEPTH_TEST: context->setDepthTest(true); break;
case GL_BLEND: context->setBlend(true); break;
case GL_DITHER: context->setDither(true); break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glEnableVertexAttribArray(GLuint index)
{
EVENT("(GLuint index = %d)", index);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setEnableVertexAttribArray(index, true);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glEndQueryEXT(GLenum target)
{
EVENT("GLenum target = 0x%X)", target);
try
{
switch (target)
{
case GL_ANY_SAMPLES_PASSED_EXT:
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->endQuery(target);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFinishFenceNV(GLuint fence)
{
EVENT("(GLuint fence = %d)", fence);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Fence* fenceObject = context->getFence(fence);
if (fenceObject == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
fenceObject->finishFence();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFinish(void)
{
EVENT("()");
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->sync(true);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFlush(void)
{
EVENT("()");
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->sync(false);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
{
EVENT("(GLenum target = 0x%X, GLenum attachment = 0x%X, GLenum renderbuffertarget = 0x%X, "
"GLuint renderbuffer = %d)", target, attachment, renderbuffertarget, renderbuffer);
try
{
if ((target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER_ANGLE && target != GL_READ_FRAMEBUFFER_ANGLE)
|| (renderbuffertarget != GL_RENDERBUFFER && renderbuffer != 0))
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Framebuffer *framebuffer = NULL;
GLuint framebufferHandle = 0;
if (target == GL_READ_FRAMEBUFFER_ANGLE)
{
framebuffer = context->getReadFramebuffer();
framebufferHandle = context->getReadFramebufferHandle();
}
else
{
framebuffer = context->getDrawFramebuffer();
framebufferHandle = context->getDrawFramebufferHandle();
}
if (!framebuffer || (framebufferHandle == 0 && renderbuffer != 0))
{
return gl::error(GL_INVALID_OPERATION);
}
if (attachment >= GL_COLOR_ATTACHMENT0_EXT && attachment <= GL_COLOR_ATTACHMENT15_EXT)
{
const unsigned int colorAttachment = (attachment - GL_COLOR_ATTACHMENT0_EXT);
if (colorAttachment >= context->getMaximumRenderTargets())
{
return gl::error(GL_INVALID_VALUE);
}
framebuffer->setColorbuffer(colorAttachment, GL_RENDERBUFFER, renderbuffer);
}
else
{
switch (attachment)
{
case GL_DEPTH_ATTACHMENT:
framebuffer->setDepthbuffer(GL_RENDERBUFFER, renderbuffer);
break;
case GL_STENCIL_ATTACHMENT:
framebuffer->setStencilbuffer(GL_RENDERBUFFER, renderbuffer);
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
{
EVENT("(GLenum target = 0x%X, GLenum attachment = 0x%X, GLenum textarget = 0x%X, "
"GLuint texture = %d, GLint level = %d)", target, attachment, textarget, texture, level);
try
{
if (target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER_ANGLE && target != GL_READ_FRAMEBUFFER_ANGLE)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (attachment >= GL_COLOR_ATTACHMENT0_EXT && attachment <= GL_COLOR_ATTACHMENT15_EXT)
{
const unsigned int colorAttachment = (attachment - GL_COLOR_ATTACHMENT0_EXT);
if (colorAttachment >= context->getMaximumRenderTargets())
{
return gl::error(GL_INVALID_VALUE);
}
}
else
{
switch (attachment)
{
case GL_DEPTH_ATTACHMENT:
case GL_STENCIL_ATTACHMENT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
if (texture == 0)
{
textarget = GL_NONE;
}
else
{
gl::Texture *tex = context->getTexture(texture);
if (tex == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
switch (textarget)
{
case GL_TEXTURE_2D:
{
if (tex->getTarget() != GL_TEXTURE_2D)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Texture2D *tex2d = static_cast<gl::Texture2D *>(tex);
if (tex2d->isCompressed(0))
{
return gl::error(GL_INVALID_OPERATION);
}
break;
}
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
{
if (tex->getTarget() != GL_TEXTURE_CUBE_MAP)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::TextureCubeMap *texcube = static_cast<gl::TextureCubeMap *>(tex);
if (texcube->isCompressed(textarget, level))
{
return gl::error(GL_INVALID_OPERATION);
}
break;
}
default:
return gl::error(GL_INVALID_ENUM);
}
if (level != 0)
{
return gl::error(GL_INVALID_VALUE);
}
}
gl::Framebuffer *framebuffer = NULL;
GLuint framebufferHandle = 0;
if (target == GL_READ_FRAMEBUFFER_ANGLE)
{
framebuffer = context->getReadFramebuffer();
framebufferHandle = context->getReadFramebufferHandle();
}
else
{
framebuffer = context->getDrawFramebuffer();
framebufferHandle = context->getDrawFramebufferHandle();
}
if (framebufferHandle == 0 || !framebuffer)
{
return gl::error(GL_INVALID_OPERATION);
}
if (attachment >= GL_COLOR_ATTACHMENT0_EXT && attachment <= GL_COLOR_ATTACHMENT15_EXT)
{
const unsigned int colorAttachment = (attachment - GL_COLOR_ATTACHMENT0_EXT);
if (colorAttachment >= context->getMaximumRenderTargets())
{
return gl::error(GL_INVALID_VALUE);
}
framebuffer->setColorbuffer(colorAttachment, textarget, texture);
}
else
{
switch (attachment)
{
case GL_DEPTH_ATTACHMENT: framebuffer->setDepthbuffer(textarget, texture); break;
case GL_STENCIL_ATTACHMENT: framebuffer->setStencilbuffer(textarget, texture); break;
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glFrontFace(GLenum mode)
{
EVENT("(GLenum mode = 0x%X)", mode);
try
{
switch (mode)
{
case GL_CW:
case GL_CCW:
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setFrontFace(mode);
}
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenBuffers(GLsizei n, GLuint* buffers)
{
EVENT("(GLsizei n = %d, GLuint* buffers = 0x%0.8p)", n, buffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
buffers[i] = context->createBuffer();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenerateMipmap(GLenum target)
{
EVENT("(GLenum target = 0x%X)", target);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (target)
{
case GL_TEXTURE_2D:
{
gl::Texture2D *tex2d = context->getTexture2D();
if (tex2d->isCompressed(0))
{
return gl::error(GL_INVALID_OPERATION);
}
if (tex2d->isDepth(0))
{
return gl::error(GL_INVALID_OPERATION);
}
tex2d->generateMipmaps();
break;
}
case GL_TEXTURE_CUBE_MAP:
{
gl::TextureCubeMap *texcube = context->getTextureCubeMap();
if (texcube->isCompressed(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0))
{
return gl::error(GL_INVALID_OPERATION);
}
texcube->generateMipmaps();
break;
}
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenFencesNV(GLsizei n, GLuint* fences)
{
EVENT("(GLsizei n = %d, GLuint* fences = 0x%0.8p)", n, fences);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
fences[i] = context->createFence();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenFramebuffers(GLsizei n, GLuint* framebuffers)
{
EVENT("(GLsizei n = %d, GLuint* framebuffers = 0x%0.8p)", n, framebuffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
framebuffers[i] = context->createFramebuffer();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenQueriesEXT(GLsizei n, GLuint* ids)
{
EVENT("(GLsizei n = %d, GLuint* ids = 0x%0.8p)", n, ids);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
ids[i] = context->createQuery();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenRenderbuffers(GLsizei n, GLuint* renderbuffers)
{
EVENT("(GLsizei n = %d, GLuint* renderbuffers = 0x%0.8p)", n, renderbuffers);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
renderbuffers[i] = context->createRenderbuffer();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGenTextures(GLsizei n, GLuint* textures)
{
EVENT("(GLsizei n = %d, GLuint* textures = 0x%0.8p)", n, textures);
try
{
if (n < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
for (int i = 0; i < n; i++)
{
textures[i] = context->createTexture();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetActiveAttrib(GLuint program, GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name)
{
EVENT("(GLuint program = %d, GLuint index = %d, GLsizei bufsize = %d, GLsizei *length = 0x%0.8p, "
"GLint *size = 0x%0.8p, GLenum *type = %0.8p, GLchar *name = %0.8p)",
program, index, bufsize, length, size, type, name);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (index >= (GLuint)programObject->getActiveAttributeCount())
{
return gl::error(GL_INVALID_VALUE);
}
programObject->getActiveAttribute(index, bufsize, length, size, type, name);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetActiveUniform(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, GLchar* name)
{
EVENT("(GLuint program = %d, GLuint index = %d, GLsizei bufsize = %d, "
"GLsizei* length = 0x%0.8p, GLint* size = 0x%0.8p, GLenum* type = 0x%0.8p, GLchar* name = 0x%0.8p)",
program, index, bufsize, length, size, type, name);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (index >= (GLuint)programObject->getActiveUniformCount())
{
return gl::error(GL_INVALID_VALUE);
}
programObject->getActiveUniform(index, bufsize, length, size, type, name);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders)
{
EVENT("(GLuint program = %d, GLsizei maxcount = %d, GLsizei* count = 0x%0.8p, GLuint* shaders = 0x%0.8p)",
program, maxcount, count, shaders);
try
{
if (maxcount < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
return programObject->getAttachedShaders(maxcount, count, shaders);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
int __stdcall glGetAttribLocation(GLuint program, const GLchar* name)
{
EVENT("(GLuint program = %d, const GLchar* name = %s)", program, name);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION, -1);
}
else
{
return gl::error(GL_INVALID_VALUE, -1);
}
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programObject->isLinked() || !programBinary)
{
return gl::error(GL_INVALID_OPERATION, -1);
}
return programBinary->getAttributeLocation(name);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, -1);
}
return -1;
}
void __stdcall glGetBooleanv(GLenum pname, GLboolean* params)
{
EVENT("(GLenum pname = 0x%X, GLboolean* params = 0x%0.8p)", pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (!(context->getBooleanv(pname, params)))
{
GLenum nativeType;
unsigned int numParams = 0;
if (!context->getQueryParameterInfo(pname, &nativeType, &numParams))
return gl::error(GL_INVALID_ENUM);
if (numParams == 0)
return; // it is known that the pname is valid, but there are no parameters to return
if (nativeType == GL_FLOAT)
{
GLfloat *floatParams = NULL;
floatParams = new GLfloat[numParams];
context->getFloatv(pname, floatParams);
for (unsigned int i = 0; i < numParams; ++i)
{
if (floatParams[i] == 0.0f)
params[i] = GL_FALSE;
else
params[i] = GL_TRUE;
}
delete [] floatParams;
}
else if (nativeType == GL_INT)
{
GLint *intParams = NULL;
intParams = new GLint[numParams];
context->getIntegerv(pname, intParams);
for (unsigned int i = 0; i < numParams; ++i)
{
if (intParams[i] == 0)
params[i] = GL_FALSE;
else
params[i] = GL_TRUE;
}
delete [] intParams;
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetBufferParameteriv(GLenum target, GLenum pname, GLint* params)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)", target, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Buffer *buffer;
switch (target)
{
case GL_ARRAY_BUFFER:
buffer = context->getArrayBuffer();
break;
case GL_ELEMENT_ARRAY_BUFFER:
buffer = context->getElementArrayBuffer();
break;
default: return gl::error(GL_INVALID_ENUM);
}
if (!buffer)
{
// A null buffer means that "0" is bound to the requested buffer target
return gl::error(GL_INVALID_OPERATION);
}
switch (pname)
{
case GL_BUFFER_USAGE:
*params = buffer->usage();
break;
case GL_BUFFER_SIZE:
*params = buffer->size();
break;
default: return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLenum __stdcall glGetError(void)
{
EVENT("()");
gl::Context *context = gl::getContext();
if (context)
{
return context->getError();
}
return GL_NO_ERROR;
}
void __stdcall glGetFenceivNV(GLuint fence, GLenum pname, GLint *params)
{
EVENT("(GLuint fence = %d, GLenum pname = 0x%X, GLint *params = 0x%0.8p)", fence, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Fence *fenceObject = context->getFence(fence);
if (fenceObject == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
fenceObject->getFenceiv(pname, params);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetFloatv(GLenum pname, GLfloat* params)
{
EVENT("(GLenum pname = 0x%X, GLfloat* params = 0x%0.8p)", pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (!(context->getFloatv(pname, params)))
{
GLenum nativeType;
unsigned int numParams = 0;
if (!context->getQueryParameterInfo(pname, &nativeType, &numParams))
return gl::error(GL_INVALID_ENUM);
if (numParams == 0)
return; // it is known that the pname is valid, but that there are no parameters to return.
if (nativeType == GL_BOOL)
{
GLboolean *boolParams = NULL;
boolParams = new GLboolean[numParams];
context->getBooleanv(pname, boolParams);
for (unsigned int i = 0; i < numParams; ++i)
{
if (boolParams[i] == GL_FALSE)
params[i] = 0.0f;
else
params[i] = 1.0f;
}
delete [] boolParams;
}
else if (nativeType == GL_INT)
{
GLint *intParams = NULL;
intParams = new GLint[numParams];
context->getIntegerv(pname, intParams);
for (unsigned int i = 0; i < numParams; ++i)
{
params[i] = (GLfloat)intParams[i];
}
delete [] intParams;
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params)
{
EVENT("(GLenum target = 0x%X, GLenum attachment = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)",
target, attachment, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (target != GL_FRAMEBUFFER && target != GL_DRAW_FRAMEBUFFER_ANGLE && target != GL_READ_FRAMEBUFFER_ANGLE)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Framebuffer *framebuffer = NULL;
if (target == GL_READ_FRAMEBUFFER_ANGLE)
{
if(context->getReadFramebufferHandle() == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
framebuffer = context->getReadFramebuffer();
}
else
{
if (context->getDrawFramebufferHandle() == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
framebuffer = context->getDrawFramebuffer();
}
GLenum attachmentType;
GLuint attachmentHandle;
if (attachment >= GL_COLOR_ATTACHMENT0_EXT && attachment <= GL_COLOR_ATTACHMENT15_EXT)
{
const unsigned int colorAttachment = (attachment - GL_COLOR_ATTACHMENT0_EXT);
if (colorAttachment >= context->getMaximumRenderTargets())
{
return gl::error(GL_INVALID_ENUM);
}
attachmentType = framebuffer->getColorbufferType(colorAttachment);
attachmentHandle = framebuffer->getColorbufferHandle(colorAttachment);
}
else
{
switch (attachment)
{
case GL_DEPTH_ATTACHMENT:
attachmentType = framebuffer->getDepthbufferType();
attachmentHandle = framebuffer->getDepthbufferHandle();
break;
case GL_STENCIL_ATTACHMENT:
attachmentType = framebuffer->getStencilbufferType();
attachmentHandle = framebuffer->getStencilbufferHandle();
break;
default: return gl::error(GL_INVALID_ENUM);
}
}
GLenum attachmentObjectType; // Type category
if (attachmentType == GL_NONE || attachmentType == GL_RENDERBUFFER)
{
attachmentObjectType = attachmentType;
}
else if (gl::IsInternalTextureTarget(attachmentType))
{
attachmentObjectType = GL_TEXTURE;
}
else
{
UNREACHABLE();
return;
}
switch (pname)
{
case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
*params = attachmentObjectType;
break;
case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
if (attachmentObjectType == GL_RENDERBUFFER || attachmentObjectType == GL_TEXTURE)
{
*params = attachmentHandle;
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:
if (attachmentObjectType == GL_TEXTURE)
{
*params = 0; // FramebufferTexture2D will not allow level to be set to anything else in GL ES 2.0
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:
if (attachmentObjectType == GL_TEXTURE)
{
if (gl::IsCubemapTextureTarget(attachmentType))
{
*params = attachmentType;
}
else
{
*params = 0;
}
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLenum __stdcall glGetGraphicsResetStatusEXT(void)
{
EVENT("()");
try
{
gl::Context *context = gl::getContext();
if (context)
{
return context->getResetStatus();
}
return GL_NO_ERROR;
}
catch(std::bad_alloc&)
{
return GL_OUT_OF_MEMORY;
}
}
void __stdcall glGetIntegerv(GLenum pname, GLint* params)
{
EVENT("(GLenum pname = 0x%X, GLint* params = 0x%0.8p)", pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (!(context->getIntegerv(pname, params)))
{
GLenum nativeType;
unsigned int numParams = 0;
if (!context->getQueryParameterInfo(pname, &nativeType, &numParams))
return gl::error(GL_INVALID_ENUM);
if (numParams == 0)
return; // it is known that pname is valid, but there are no parameters to return
if (nativeType == GL_BOOL)
{
GLboolean *boolParams = NULL;
boolParams = new GLboolean[numParams];
context->getBooleanv(pname, boolParams);
for (unsigned int i = 0; i < numParams; ++i)
{
if (boolParams[i] == GL_FALSE)
params[i] = 0;
else
params[i] = 1;
}
delete [] boolParams;
}
else if (nativeType == GL_FLOAT)
{
GLfloat *floatParams = NULL;
floatParams = new GLfloat[numParams];
context->getFloatv(pname, floatParams);
for (unsigned int i = 0; i < numParams; ++i)
{
if (pname == GL_DEPTH_RANGE || pname == GL_COLOR_CLEAR_VALUE || pname == GL_DEPTH_CLEAR_VALUE || pname == GL_BLEND_COLOR)
{
params[i] = (GLint)(((GLfloat)(0xFFFFFFFF) * floatParams[i] - 1.0f) / 2.0f);
}
else
params[i] = (GLint)(floatParams[i] > 0.0f ? floor(floatParams[i] + 0.5) : ceil(floatParams[i] - 0.5));
}
delete [] floatParams;
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetProgramiv(GLuint program, GLenum pname, GLint* params)
{
EVENT("(GLuint program = %d, GLenum pname = %d, GLint* params = 0x%0.8p)", program, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
return gl::error(GL_INVALID_VALUE);
}
switch (pname)
{
case GL_DELETE_STATUS:
*params = programObject->isFlaggedForDeletion();
return;
case GL_LINK_STATUS:
*params = programObject->isLinked();
return;
case GL_VALIDATE_STATUS:
*params = programObject->isValidated();
return;
case GL_INFO_LOG_LENGTH:
*params = programObject->getInfoLogLength();
return;
case GL_ATTACHED_SHADERS:
*params = programObject->getAttachedShadersCount();
return;
case GL_ACTIVE_ATTRIBUTES:
*params = programObject->getActiveAttributeCount();
return;
case GL_ACTIVE_ATTRIBUTE_MAX_LENGTH:
*params = programObject->getActiveAttributeMaxLength();
return;
case GL_ACTIVE_UNIFORMS:
*params = programObject->getActiveUniformCount();
return;
case GL_ACTIVE_UNIFORM_MAX_LENGTH:
*params = programObject->getActiveUniformMaxLength();
return;
case GL_PROGRAM_BINARY_LENGTH_OES:
*params = programObject->getProgramBinaryLength();
return;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetProgramInfoLog(GLuint program, GLsizei bufsize, GLsizei* length, GLchar* infolog)
{
EVENT("(GLuint program = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* infolog = 0x%0.8p)",
program, bufsize, length, infolog);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
return gl::error(GL_INVALID_VALUE);
}
programObject->getInfoLog(bufsize, length, infolog);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetQueryivEXT(GLenum target, GLenum pname, GLint *params)
{
EVENT("GLenum target = 0x%X, GLenum pname = 0x%X, GLint *params = 0x%0.8p)", target, pname, params);
try
{
switch (pname)
{
case GL_CURRENT_QUERY_EXT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
params[0] = context->getActiveQuery(target);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetQueryObjectuivEXT(GLuint id, GLenum pname, GLuint *params)
{
EVENT("(GLuint id = %d, GLenum pname = 0x%X, GLuint *params = 0x%0.8p)", id, pname, params);
try
{
switch (pname)
{
case GL_QUERY_RESULT_EXT:
case GL_QUERY_RESULT_AVAILABLE_EXT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Query *queryObject = context->getQuery(id, false, GL_NONE);
if (!queryObject)
{
return gl::error(GL_INVALID_OPERATION);
}
if (context->getActiveQuery(queryObject->getType()) == id)
{
return gl::error(GL_INVALID_OPERATION);
}
switch(pname)
{
case GL_QUERY_RESULT_EXT:
params[0] = queryObject->getResult();
break;
case GL_QUERY_RESULT_AVAILABLE_EXT:
params[0] = queryObject->isResultAvailable();
break;
default:
ASSERT(false);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)", target, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (target != GL_RENDERBUFFER)
{
return gl::error(GL_INVALID_ENUM);
}
if (context->getRenderbufferHandle() == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
gl::Renderbuffer *renderbuffer = context->getRenderbuffer(context->getRenderbufferHandle());
switch (pname)
{
case GL_RENDERBUFFER_WIDTH: *params = renderbuffer->getWidth(); break;
case GL_RENDERBUFFER_HEIGHT: *params = renderbuffer->getHeight(); break;
case GL_RENDERBUFFER_INTERNAL_FORMAT: *params = renderbuffer->getInternalFormat(); break;
case GL_RENDERBUFFER_RED_SIZE: *params = renderbuffer->getRedSize(); break;
case GL_RENDERBUFFER_GREEN_SIZE: *params = renderbuffer->getGreenSize(); break;
case GL_RENDERBUFFER_BLUE_SIZE: *params = renderbuffer->getBlueSize(); break;
case GL_RENDERBUFFER_ALPHA_SIZE: *params = renderbuffer->getAlphaSize(); break;
case GL_RENDERBUFFER_DEPTH_SIZE: *params = renderbuffer->getDepthSize(); break;
case GL_RENDERBUFFER_STENCIL_SIZE: *params = renderbuffer->getStencilSize(); break;
case GL_RENDERBUFFER_SAMPLES_ANGLE:
if (context->getMaxSupportedSamples() != 0)
{
*params = renderbuffer->getSamples();
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetShaderiv(GLuint shader, GLenum pname, GLint* params)
{
EVENT("(GLuint shader = %d, GLenum pname = %d, GLint* params = 0x%0.8p)", shader, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
return gl::error(GL_INVALID_VALUE);
}
switch (pname)
{
case GL_SHADER_TYPE:
*params = shaderObject->getType();
return;
case GL_DELETE_STATUS:
*params = shaderObject->isFlaggedForDeletion();
return;
case GL_COMPILE_STATUS:
*params = shaderObject->isCompiled() ? GL_TRUE : GL_FALSE;
return;
case GL_INFO_LOG_LENGTH:
*params = shaderObject->getInfoLogLength();
return;
case GL_SHADER_SOURCE_LENGTH:
*params = shaderObject->getSourceLength();
return;
case GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE:
*params = shaderObject->getTranslatedSourceLength();
return;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetShaderInfoLog(GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* infolog)
{
EVENT("(GLuint shader = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* infolog = 0x%0.8p)",
shader, bufsize, length, infolog);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
return gl::error(GL_INVALID_VALUE);
}
shaderObject->getInfoLog(bufsize, length, infolog);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision)
{
EVENT("(GLenum shadertype = 0x%X, GLenum precisiontype = 0x%X, GLint* range = 0x%0.8p, GLint* precision = 0x%0.8p)",
shadertype, precisiontype, range, precision);
try
{
switch (shadertype)
{
case GL_VERTEX_SHADER:
case GL_FRAGMENT_SHADER:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (precisiontype)
{
case GL_LOW_FLOAT:
case GL_MEDIUM_FLOAT:
case GL_HIGH_FLOAT:
// Assume IEEE 754 precision
range[0] = 127;
range[1] = 127;
*precision = 23;
break;
case GL_LOW_INT:
case GL_MEDIUM_INT:
case GL_HIGH_INT:
// Some (most) hardware only supports single-precision floating-point numbers,
// which can accurately represent integers up to +/-16777216
range[0] = 24;
range[1] = 24;
*precision = 0;
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetShaderSource(GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source)
{
EVENT("(GLuint shader = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* source = 0x%0.8p)",
shader, bufsize, length, source);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
return gl::error(GL_INVALID_OPERATION);
}
shaderObject->getSource(bufsize, length, source);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetTranslatedShaderSourceANGLE(GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source)
{
EVENT("(GLuint shader = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* source = 0x%0.8p)",
shader, bufsize, length, source);
try
{
if (bufsize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
return gl::error(GL_INVALID_OPERATION);
}
shaderObject->getTranslatedSource(bufsize, length, source);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
const GLubyte* __stdcall glGetString(GLenum name)
{
EVENT("(GLenum name = 0x%X)", name);
try
{
gl::Context *context = gl::getNonLostContext();
switch (name)
{
case GL_VENDOR:
return (GLubyte*)"Google Inc.";
case GL_RENDERER:
return (GLubyte*)((context != NULL) ? context->getRendererString() : "ANGLE");
case GL_VERSION:
return (GLubyte*)"OpenGL ES 2.0 (ANGLE " VERSION_STRING ")";
case GL_SHADING_LANGUAGE_VERSION:
return (GLubyte*)"OpenGL ES GLSL ES 1.00 (ANGLE " VERSION_STRING ")";
case GL_EXTENSIONS:
return (GLubyte*)((context != NULL) ? context->getExtensionString() : "");
default:
return gl::error(GL_INVALID_ENUM, (GLubyte*)NULL);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, (GLubyte*)NULL);
}
}
void __stdcall glGetTexParameterfv(GLenum target, GLenum pname, GLfloat* params)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLfloat* params = 0x%0.8p)", target, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture *texture;
switch (target)
{
case GL_TEXTURE_2D:
texture = context->getTexture2D();
break;
case GL_TEXTURE_CUBE_MAP:
texture = context->getTextureCubeMap();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (pname)
{
case GL_TEXTURE_MAG_FILTER:
*params = (GLfloat)texture->getMagFilter();
break;
case GL_TEXTURE_MIN_FILTER:
*params = (GLfloat)texture->getMinFilter();
break;
case GL_TEXTURE_WRAP_S:
*params = (GLfloat)texture->getWrapS();
break;
case GL_TEXTURE_WRAP_T:
*params = (GLfloat)texture->getWrapT();
break;
case GL_TEXTURE_IMMUTABLE_FORMAT_EXT:
*params = (GLfloat)(texture->isImmutable() ? GL_TRUE : GL_FALSE);
break;
case GL_TEXTURE_USAGE_ANGLE:
*params = (GLfloat)texture->getUsage();
break;
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
if (!context->supportsTextureFilterAnisotropy())
{
return gl::error(GL_INVALID_ENUM);
}
*params = (GLfloat)texture->getMaxAnisotropy();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetTexParameteriv(GLenum target, GLenum pname, GLint* params)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)", target, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture *texture;
switch (target)
{
case GL_TEXTURE_2D:
texture = context->getTexture2D();
break;
case GL_TEXTURE_CUBE_MAP:
texture = context->getTextureCubeMap();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (pname)
{
case GL_TEXTURE_MAG_FILTER:
*params = texture->getMagFilter();
break;
case GL_TEXTURE_MIN_FILTER:
*params = texture->getMinFilter();
break;
case GL_TEXTURE_WRAP_S:
*params = texture->getWrapS();
break;
case GL_TEXTURE_WRAP_T:
*params = texture->getWrapT();
break;
case GL_TEXTURE_IMMUTABLE_FORMAT_EXT:
*params = texture->isImmutable() ? GL_TRUE : GL_FALSE;
break;
case GL_TEXTURE_USAGE_ANGLE:
*params = texture->getUsage();
break;
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
if (!context->supportsTextureFilterAnisotropy())
{
return gl::error(GL_INVALID_ENUM);
}
*params = (GLint)texture->getMaxAnisotropy();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetnUniformfvEXT(GLuint program, GLint location, GLsizei bufSize, GLfloat* params)
{
EVENT("(GLuint program = %d, GLint location = %d, GLsizei bufSize = %d, GLfloat* params = 0x%0.8p)",
program, location, bufSize, params);
try
{
if (bufSize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (program == 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Program *programObject = context->getProgram(program);
if (!programObject || !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->getUniformfv(location, &bufSize, params))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetUniformfv(GLuint program, GLint location, GLfloat* params)
{
EVENT("(GLuint program = %d, GLint location = %d, GLfloat* params = 0x%0.8p)", program, location, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (program == 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Program *programObject = context->getProgram(program);
if (!programObject || !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->getUniformfv(location, NULL, params))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetnUniformivEXT(GLuint program, GLint location, GLsizei bufSize, GLint* params)
{
EVENT("(GLuint program = %d, GLint location = %d, GLsizei bufSize = %d, GLint* params = 0x%0.8p)",
program, location, bufSize, params);
try
{
if (bufSize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (program == 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Program *programObject = context->getProgram(program);
if (!programObject || !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->getUniformiv(location, &bufSize, params))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetUniformiv(GLuint program, GLint location, GLint* params)
{
EVENT("(GLuint program = %d, GLint location = %d, GLint* params = 0x%0.8p)", program, location, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (program == 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Program *programObject = context->getProgram(program);
if (!programObject || !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->getUniformiv(location, NULL, params))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
int __stdcall glGetUniformLocation(GLuint program, const GLchar* name)
{
EVENT("(GLuint program = %d, const GLchar* name = 0x%0.8p)", program, name);
try
{
gl::Context *context = gl::getNonLostContext();
if (strstr(name, "gl_") == name)
{
return -1;
}
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION, -1);
}
else
{
return gl::error(GL_INVALID_VALUE, -1);
}
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programObject->isLinked() || !programBinary)
{
return gl::error(GL_INVALID_OPERATION, -1);
}
return programBinary->getUniformLocation(name);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, -1);
}
return -1;
}
void __stdcall glGetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params)
{
EVENT("(GLuint index = %d, GLenum pname = 0x%X, GLfloat* params = 0x%0.8p)", index, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
const gl::VertexAttribute &attribState = context->getVertexAttribState(index);
switch (pname)
{
case GL_VERTEX_ATTRIB_ARRAY_ENABLED:
*params = (GLfloat)(attribState.mArrayEnabled ? GL_TRUE : GL_FALSE);
break;
case GL_VERTEX_ATTRIB_ARRAY_SIZE:
*params = (GLfloat)attribState.mSize;
break;
case GL_VERTEX_ATTRIB_ARRAY_STRIDE:
*params = (GLfloat)attribState.mStride;
break;
case GL_VERTEX_ATTRIB_ARRAY_TYPE:
*params = (GLfloat)attribState.mType;
break;
case GL_VERTEX_ATTRIB_ARRAY_NORMALIZED:
*params = (GLfloat)(attribState.mNormalized ? GL_TRUE : GL_FALSE);
break;
case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:
*params = (GLfloat)attribState.mBoundBuffer.id();
break;
case GL_CURRENT_VERTEX_ATTRIB:
for (int i = 0; i < 4; ++i)
{
params[i] = attribState.mCurrentValue[i];
}
break;
case GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE:
*params = (GLfloat)attribState.mDivisor;
break;
default: return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetVertexAttribiv(GLuint index, GLenum pname, GLint* params)
{
EVENT("(GLuint index = %d, GLenum pname = 0x%X, GLint* params = 0x%0.8p)", index, pname, params);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
const gl::VertexAttribute &attribState = context->getVertexAttribState(index);
switch (pname)
{
case GL_VERTEX_ATTRIB_ARRAY_ENABLED:
*params = (attribState.mArrayEnabled ? GL_TRUE : GL_FALSE);
break;
case GL_VERTEX_ATTRIB_ARRAY_SIZE:
*params = attribState.mSize;
break;
case GL_VERTEX_ATTRIB_ARRAY_STRIDE:
*params = attribState.mStride;
break;
case GL_VERTEX_ATTRIB_ARRAY_TYPE:
*params = attribState.mType;
break;
case GL_VERTEX_ATTRIB_ARRAY_NORMALIZED:
*params = (attribState.mNormalized ? GL_TRUE : GL_FALSE);
break;
case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:
*params = attribState.mBoundBuffer.id();
break;
case GL_CURRENT_VERTEX_ATTRIB:
for (int i = 0; i < 4; ++i)
{
float currentValue = attribState.mCurrentValue[i];
params[i] = (GLint)(currentValue > 0.0f ? floor(currentValue + 0.5f) : ceil(currentValue - 0.5f));
}
break;
case GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE:
*params = (GLint)attribState.mDivisor;
break;
default: return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetVertexAttribPointerv(GLuint index, GLenum pname, GLvoid** pointer)
{
EVENT("(GLuint index = %d, GLenum pname = 0x%X, GLvoid** pointer = 0x%0.8p)", index, pname, pointer);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
if (pname != GL_VERTEX_ATTRIB_ARRAY_POINTER)
{
return gl::error(GL_INVALID_ENUM);
}
*pointer = const_cast<GLvoid*>(context->getVertexAttribPointer(index));
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glHint(GLenum target, GLenum mode)
{
EVENT("(GLenum target = 0x%X, GLenum mode = 0x%X)", target, mode);
try
{
switch (mode)
{
case GL_FASTEST:
case GL_NICEST:
case GL_DONT_CARE:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
switch (target)
{
case GL_GENERATE_MIPMAP_HINT:
if (context) context->setGenerateMipmapHint(mode);
break;
case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
if (context) context->setFragmentShaderDerivativeHint(mode);
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLboolean __stdcall glIsBuffer(GLuint buffer)
{
EVENT("(GLuint buffer = %d)", buffer);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && buffer)
{
gl::Buffer *bufferObject = context->getBuffer(buffer);
if (bufferObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsEnabled(GLenum cap)
{
EVENT("(GLenum cap = 0x%X)", cap);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (cap)
{
case GL_CULL_FACE: return context->isCullFaceEnabled();
case GL_POLYGON_OFFSET_FILL: return context->isPolygonOffsetFillEnabled();
case GL_SAMPLE_ALPHA_TO_COVERAGE: return context->isSampleAlphaToCoverageEnabled();
case GL_SAMPLE_COVERAGE: return context->isSampleCoverageEnabled();
case GL_SCISSOR_TEST: return context->isScissorTestEnabled();
case GL_STENCIL_TEST: return context->isStencilTestEnabled();
case GL_DEPTH_TEST: return context->isDepthTestEnabled();
case GL_BLEND: return context->isBlendEnabled();
case GL_DITHER: return context->isDitherEnabled();
default:
return gl::error(GL_INVALID_ENUM, false);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, false);
}
return false;
}
GLboolean __stdcall glIsFenceNV(GLuint fence)
{
EVENT("(GLuint fence = %d)", fence);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Fence *fenceObject = context->getFence(fence);
if (fenceObject == NULL)
{
return GL_FALSE;
}
return fenceObject->isFence();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsFramebuffer(GLuint framebuffer)
{
EVENT("(GLuint framebuffer = %d)", framebuffer);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && framebuffer)
{
gl::Framebuffer *framebufferObject = context->getFramebuffer(framebuffer);
if (framebufferObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsProgram(GLuint program)
{
EVENT("(GLuint program = %d)", program);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && program)
{
gl::Program *programObject = context->getProgram(program);
if (programObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsQueryEXT(GLuint id)
{
EVENT("(GLuint id = %d)", id);
try
{
if (id == 0)
{
return GL_FALSE;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Query *queryObject = context->getQuery(id, false, GL_NONE);
if (queryObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsRenderbuffer(GLuint renderbuffer)
{
EVENT("(GLuint renderbuffer = %d)", renderbuffer);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && renderbuffer)
{
gl::Renderbuffer *renderbufferObject = context->getRenderbuffer(renderbuffer);
if (renderbufferObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsShader(GLuint shader)
{
EVENT("(GLuint shader = %d)", shader);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && shader)
{
gl::Shader *shaderObject = context->getShader(shader);
if (shaderObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
GLboolean __stdcall glIsTexture(GLuint texture)
{
EVENT("(GLuint texture = %d)", texture);
try
{
gl::Context *context = gl::getNonLostContext();
if (context && texture)
{
gl::Texture *textureObject = context->getTexture(texture);
if (textureObject)
{
return GL_TRUE;
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, GL_FALSE);
}
return GL_FALSE;
}
void __stdcall glLineWidth(GLfloat width)
{
EVENT("(GLfloat width = %f)", width);
try
{
if (width <= 0.0f)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setLineWidth(width);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glLinkProgram(GLuint program)
{
EVENT("(GLuint program = %d)", program);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
context->linkProgram(program);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glPixelStorei(GLenum pname, GLint param)
{
EVENT("(GLenum pname = 0x%X, GLint param = %d)", pname, param);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (pname)
{
case GL_UNPACK_ALIGNMENT:
if (param != 1 && param != 2 && param != 4 && param != 8)
{
return gl::error(GL_INVALID_VALUE);
}
context->setUnpackAlignment(param);
break;
case GL_PACK_ALIGNMENT:
if (param != 1 && param != 2 && param != 4 && param != 8)
{
return gl::error(GL_INVALID_VALUE);
}
context->setPackAlignment(param);
break;
case GL_PACK_REVERSE_ROW_ORDER_ANGLE:
context->setPackReverseRowOrder(param != 0);
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glPolygonOffset(GLfloat factor, GLfloat units)
{
EVENT("(GLfloat factor = %f, GLfloat units = %f)", factor, units);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setPolygonOffsetParams(factor, units);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glReadnPixelsEXT(GLint x, GLint y, GLsizei width, GLsizei height,
GLenum format, GLenum type, GLsizei bufSize,
GLvoid *data)
{
EVENT("(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d, "
"GLenum format = 0x%X, GLenum type = 0x%X, GLsizei bufSize = 0x%d, GLvoid *data = 0x%0.8p)",
x, y, width, height, format, type, bufSize, data);
try
{
if (width < 0 || height < 0 || bufSize < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLenum currentFormat, currentType;
// Failure in getCurrentReadFormatType indicates that no color attachment is currently bound,
// and attempting to read back if that's the case is an error. The error will be registered
// by getCurrentReadFormat.
if (!context->getCurrentReadFormatType(¤tFormat, ¤tType))
return;
if (!(currentFormat == format && currentType == type) && !validReadFormatType(format, type))
{
return gl::error(GL_INVALID_OPERATION);
}
context->readPixels(x, y, width, height, format, type, &bufSize, data);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height,
GLenum format, GLenum type, GLvoid* pixels)
{
EVENT("(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d, "
"GLenum format = 0x%X, GLenum type = 0x%X, GLvoid* pixels = 0x%0.8p)",
x, y, width, height, format, type, pixels);
try
{
if (width < 0 || height < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLenum currentFormat, currentType;
// Failure in getCurrentReadFormatType indicates that no color attachment is currently bound,
// and attempting to read back if that's the case is an error. The error will be registered
// by getCurrentReadFormat.
if (!context->getCurrentReadFormatType(¤tFormat, ¤tType))
return;
if (!(currentFormat == format && currentType == type) && !validReadFormatType(format, type))
{
return gl::error(GL_INVALID_OPERATION);
}
context->readPixels(x, y, width, height, format, type, NULL, pixels);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glReleaseShaderCompiler(void)
{
EVENT("()");
try
{
gl::Shader::releaseCompiler();
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glRenderbufferStorageMultisampleANGLE(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
{
EVENT("(GLenum target = 0x%X, GLsizei samples = %d, GLenum internalformat = 0x%X, GLsizei width = %d, GLsizei height = %d)",
target, samples, internalformat, width, height);
try
{
switch (target)
{
case GL_RENDERBUFFER:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (!gl::IsColorRenderable(internalformat) && !gl::IsDepthRenderable(internalformat) && !gl::IsStencilRenderable(internalformat))
{
return gl::error(GL_INVALID_ENUM);
}
if (width < 0 || height < 0 || samples < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (width > context->getMaximumRenderbufferDimension() ||
height > context->getMaximumRenderbufferDimension() ||
samples > context->getMaxSupportedSamples())
{
return gl::error(GL_INVALID_VALUE);
}
GLuint handle = context->getRenderbufferHandle();
if (handle == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
switch (internalformat)
{
case GL_DEPTH_COMPONENT16:
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB565:
case GL_RGB8_OES:
case GL_RGBA8_OES:
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_OES:
context->setRenderbufferStorage(width, height, internalformat, samples);
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
{
glRenderbufferStorageMultisampleANGLE(target, 0, internalformat, width, height);
}
void __stdcall glSampleCoverage(GLclampf value, GLboolean invert)
{
EVENT("(GLclampf value = %f, GLboolean invert = %d)", value, invert);
try
{
gl::Context* context = gl::getNonLostContext();
if (context)
{
context->setSampleCoverageParams(gl::clamp01(value), invert == GL_TRUE);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glSetFenceNV(GLuint fence, GLenum condition)
{
EVENT("(GLuint fence = %d, GLenum condition = 0x%X)", fence, condition);
try
{
if (condition != GL_ALL_COMPLETED_NV)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Fence *fenceObject = context->getFence(fence);
if (fenceObject == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
fenceObject->setFence(condition);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glScissor(GLint x, GLint y, GLsizei width, GLsizei height)
{
EVENT("(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d)", x, y, width, height);
try
{
if (width < 0 || height < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context* context = gl::getNonLostContext();
if (context)
{
context->setScissorParams(x, y, width, height);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glShaderBinary(GLsizei n, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length)
{
EVENT("(GLsizei n = %d, const GLuint* shaders = 0x%0.8p, GLenum binaryformat = 0x%X, "
"const GLvoid* binary = 0x%0.8p, GLsizei length = %d)",
n, shaders, binaryformat, binary, length);
try
{
// No binary shader formats are supported.
return gl::error(GL_INVALID_ENUM);
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glShaderSource(GLuint shader, GLsizei count, const GLchar** string, const GLint* length)
{
EVENT("(GLuint shader = %d, GLsizei count = %d, const GLchar** string = 0x%0.8p, const GLint* length = 0x%0.8p)",
shader, count, string, length);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Shader *shaderObject = context->getShader(shader);
if (!shaderObject)
{
if (context->getProgram(shader))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
shaderObject->setSource(count, string, length);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glStencilFunc(GLenum func, GLint ref, GLuint mask)
{
glStencilFuncSeparate(GL_FRONT_AND_BACK, func, ref, mask);
}
void __stdcall glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
{
EVENT("(GLenum face = 0x%X, GLenum func = 0x%X, GLint ref = %d, GLuint mask = %d)", face, func, ref, mask);
try
{
switch (face)
{
case GL_FRONT:
case GL_BACK:
case GL_FRONT_AND_BACK:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (func)
{
case GL_NEVER:
case GL_ALWAYS:
case GL_LESS:
case GL_LEQUAL:
case GL_EQUAL:
case GL_GEQUAL:
case GL_GREATER:
case GL_NOTEQUAL:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
{
context->setStencilParams(func, ref, mask);
}
if (face == GL_BACK || face == GL_FRONT_AND_BACK)
{
context->setStencilBackParams(func, ref, mask);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glStencilMask(GLuint mask)
{
glStencilMaskSeparate(GL_FRONT_AND_BACK, mask);
}
void __stdcall glStencilMaskSeparate(GLenum face, GLuint mask)
{
EVENT("(GLenum face = 0x%X, GLuint mask = %d)", face, mask);
try
{
switch (face)
{
case GL_FRONT:
case GL_BACK:
case GL_FRONT_AND_BACK:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
{
context->setStencilWritemask(mask);
}
if (face == GL_BACK || face == GL_FRONT_AND_BACK)
{
context->setStencilBackWritemask(mask);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glStencilOp(GLenum fail, GLenum zfail, GLenum zpass)
{
glStencilOpSeparate(GL_FRONT_AND_BACK, fail, zfail, zpass);
}
void __stdcall glStencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
{
EVENT("(GLenum face = 0x%X, GLenum fail = 0x%X, GLenum zfail = 0x%X, GLenum zpas = 0x%Xs)",
face, fail, zfail, zpass);
try
{
switch (face)
{
case GL_FRONT:
case GL_BACK:
case GL_FRONT_AND_BACK:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (fail)
{
case GL_ZERO:
case GL_KEEP:
case GL_REPLACE:
case GL_INCR:
case GL_DECR:
case GL_INVERT:
case GL_INCR_WRAP:
case GL_DECR_WRAP:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (zfail)
{
case GL_ZERO:
case GL_KEEP:
case GL_REPLACE:
case GL_INCR:
case GL_DECR:
case GL_INVERT:
case GL_INCR_WRAP:
case GL_DECR_WRAP:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (zpass)
{
case GL_ZERO:
case GL_KEEP:
case GL_REPLACE:
case GL_INCR:
case GL_DECR:
case GL_INVERT:
case GL_INCR_WRAP:
case GL_DECR_WRAP:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (face == GL_FRONT || face == GL_FRONT_AND_BACK)
{
context->setStencilOperations(fail, zfail, zpass);
}
if (face == GL_BACK || face == GL_FRONT_AND_BACK)
{
context->setStencilBackOperations(fail, zfail, zpass);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
GLboolean __stdcall glTestFenceNV(GLuint fence)
{
EVENT("(GLuint fence = %d)", fence);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Fence *fenceObject = context->getFence(fence);
if (fenceObject == NULL)
{
return gl::error(GL_INVALID_OPERATION, GL_TRUE);
}
return fenceObject->testFence();
}
}
catch(std::bad_alloc&)
{
gl::error(GL_OUT_OF_MEMORY);
}
return GL_TRUE;
}
void __stdcall glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height,
GLint border, GLenum format, GLenum type, const GLvoid* pixels)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLint internalformat = %d, GLsizei width = %d, GLsizei height = %d, "
"GLint border = %d, GLenum format = 0x%X, GLenum type = 0x%X, const GLvoid* pixels = 0x%0.8p)",
target, level, internalformat, width, height, border, format, type, pixels);
try
{
if (!validImageSize(level, width, height))
{
return gl::error(GL_INVALID_VALUE);
}
if (internalformat != GLint(format))
{
return gl::error(GL_INVALID_OPERATION);
}
// validate <type> by itself (used as secondary key below)
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT_5_6_5:
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
case GL_UNSIGNED_SHORT:
case GL_UNSIGNED_INT:
case GL_UNSIGNED_INT_24_8_OES:
case GL_HALF_FLOAT_OES:
case GL_FLOAT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
// validate <format> + <type> combinations
// - invalid <format> -> sets INVALID_ENUM
// - invalid <format>+<type> combination -> sets INVALID_OPERATION
switch (format)
{
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_FLOAT:
case GL_HALF_FLOAT_OES:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_RGB:
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT_5_6_5:
case GL_FLOAT:
case GL_HALF_FLOAT_OES:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_RGBA:
switch (type)
{
case GL_UNSIGNED_BYTE:
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
case GL_FLOAT:
case GL_HALF_FLOAT_OES:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_BGRA_EXT:
switch (type)
{
case GL_UNSIGNED_BYTE:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: // error cases for compressed textures are handled below
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
break;
case GL_DEPTH_COMPONENT:
switch (type)
{
case GL_UNSIGNED_SHORT:
case GL_UNSIGNED_INT:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
case GL_DEPTH_STENCIL_OES:
switch (type)
{
case GL_UNSIGNED_INT_24_8_OES:
break;
default:
return gl::error(GL_INVALID_OPERATION);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (border != 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
switch (target)
{
case GL_TEXTURE_2D:
if (width > (context->getMaximumTextureDimension() >> level) ||
height > (context->getMaximumTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
if (width != height)
{
return gl::error(GL_INVALID_VALUE);
}
if (width > (context->getMaximumCubeTextureDimension() >> level) ||
height > (context->getMaximumCubeTextureDimension() >> level))
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (format) {
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (context->supportsDXT1Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
if (context->supportsDXT3Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
if (context->supportsDXT5Textures())
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_STENCIL_OES:
if (!context->supportsDepthTextures())
{
return gl::error(GL_INVALID_VALUE);
}
if (target != GL_TEXTURE_2D)
{
return gl::error(GL_INVALID_OPERATION);
}
// OES_depth_texture supports loading depth data and multiple levels,
// but ANGLE_depth_texture does not
if (pixels != NULL || level != 0)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
default:
break;
}
if (type == GL_FLOAT)
{
if (!context->supportsFloat32Textures())
{
return gl::error(GL_INVALID_ENUM);
}
}
else if (type == GL_HALF_FLOAT_OES)
{
if (!context->supportsFloat16Textures())
{
return gl::error(GL_INVALID_ENUM);
}
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->setImage(level, width, height, format, type, context->getUnpackAlignment(), pixels);
}
else
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (!texture)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
switch (target)
{
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
texture->setImagePosX(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
texture->setImageNegX(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
texture->setImagePosY(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
texture->setImageNegY(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
texture->setImagePosZ(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
texture->setImageNegZ(level, width, height, format, type, context->getUnpackAlignment(), pixels);
break;
default: UNREACHABLE();
}
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glTexParameterf(GLenum target, GLenum pname, GLfloat param)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLint param = %f)", target, pname, param);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture *texture;
switch (target)
{
case GL_TEXTURE_2D:
texture = context->getTexture2D();
break;
case GL_TEXTURE_CUBE_MAP:
texture = context->getTextureCubeMap();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (pname)
{
case GL_TEXTURE_WRAP_S:
if (!texture->setWrapS((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_WRAP_T:
if (!texture->setWrapT((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MIN_FILTER:
if (!texture->setMinFilter((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MAG_FILTER:
if (!texture->setMagFilter((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_USAGE_ANGLE:
if (!texture->setUsage((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
if (!context->supportsTextureFilterAnisotropy())
{
return gl::error(GL_INVALID_ENUM);
}
if (!texture->setMaxAnisotropy((float)param, context->getTextureMaxAnisotropy()))
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glTexParameterfv(GLenum target, GLenum pname, const GLfloat* params)
{
glTexParameterf(target, pname, (GLfloat)*params);
}
void __stdcall glTexParameteri(GLenum target, GLenum pname, GLint param)
{
EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLint param = %d)", target, pname, param);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture *texture;
switch (target)
{
case GL_TEXTURE_2D:
texture = context->getTexture2D();
break;
case GL_TEXTURE_CUBE_MAP:
texture = context->getTextureCubeMap();
break;
default:
return gl::error(GL_INVALID_ENUM);
}
switch (pname)
{
case GL_TEXTURE_WRAP_S:
if (!texture->setWrapS((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_WRAP_T:
if (!texture->setWrapT((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MIN_FILTER:
if (!texture->setMinFilter((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MAG_FILTER:
if (!texture->setMagFilter((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_USAGE_ANGLE:
if (!texture->setUsage((GLenum)param))
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
if (!context->supportsTextureFilterAnisotropy())
{
return gl::error(GL_INVALID_ENUM);
}
if (!texture->setMaxAnisotropy((float)param, context->getTextureMaxAnisotropy()))
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glTexParameteriv(GLenum target, GLenum pname, const GLint* params)
{
glTexParameteri(target, pname, *params);
}
void __stdcall glTexStorage2DEXT(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
{
EVENT("(GLenum target = 0x%X, GLsizei levels = %d, GLenum internalformat = 0x%X, GLsizei width = %d, GLsizei height = %d)",
target, levels, internalformat, width, height);
try
{
if (target != GL_TEXTURE_2D && target != GL_TEXTURE_CUBE_MAP)
{
return gl::error(GL_INVALID_ENUM);
}
if (width < 1 || height < 1 || levels < 1)
{
return gl::error(GL_INVALID_VALUE);
}
if (target == GL_TEXTURE_CUBE_MAP && width != height)
{
return gl::error(GL_INVALID_VALUE);
}
if (levels != 1 && levels != gl::log2(std::max(width, height)) + 1)
{
return gl::error(GL_INVALID_OPERATION);
}
GLenum format = gl::ExtractFormat(internalformat);
GLenum type = gl::ExtractType(internalformat);
if (format == GL_NONE || type == GL_NONE)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
switch (target)
{
case GL_TEXTURE_2D:
if (width > context->getMaximumTextureDimension() ||
height > context->getMaximumTextureDimension())
{
return gl::error(GL_INVALID_VALUE);
}
break;
case GL_TEXTURE_CUBE_MAP:
if (width > context->getMaximumCubeTextureDimension() ||
height > context->getMaximumCubeTextureDimension())
{
return gl::error(GL_INVALID_VALUE);
}
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (levels != 1 && !context->supportsNonPower2Texture())
{
if (!gl::isPow2(width) || !gl::isPow2(height))
{
return gl::error(GL_INVALID_OPERATION);
}
}
switch (internalformat)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
if (!context->supportsDXT1Textures())
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
if (!context->supportsDXT3Textures())
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
if (!context->supportsDXT5Textures())
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_RGBA32F_EXT:
case GL_RGB32F_EXT:
case GL_ALPHA32F_EXT:
case GL_LUMINANCE32F_EXT:
case GL_LUMINANCE_ALPHA32F_EXT:
if (!context->supportsFloat32Textures())
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_RGBA16F_EXT:
case GL_RGB16F_EXT:
case GL_ALPHA16F_EXT:
case GL_LUMINANCE16F_EXT:
case GL_LUMINANCE_ALPHA16F_EXT:
if (!context->supportsFloat16Textures())
{
return gl::error(GL_INVALID_ENUM);
}
break;
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT32_OES:
case GL_DEPTH24_STENCIL8_OES:
if (!context->supportsDepthTextures())
{
return gl::error(GL_INVALID_ENUM);
}
if (target != GL_TEXTURE_2D)
{
return gl::error(GL_INVALID_OPERATION);
}
// ANGLE_depth_texture only supports 1-level textures
if (levels != 1)
{
return gl::error(GL_INVALID_OPERATION);
}
break;
default:
break;
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (!texture || texture->id() == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->storage(levels, internalformat, width, height);
}
else if (target == GL_TEXTURE_CUBE_MAP)
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (!texture || texture->id() == 0)
{
return gl::error(GL_INVALID_OPERATION);
}
if (texture->isImmutable())
{
return gl::error(GL_INVALID_OPERATION);
}
texture->storage(levels, internalformat, width);
}
else UNREACHABLE();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLenum format, GLenum type, const GLvoid* pixels)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLint xoffset = %d, GLint yoffset = %d, "
"GLsizei width = %d, GLsizei height = %d, GLenum format = 0x%X, GLenum type = 0x%X, "
"const GLvoid* pixels = 0x%0.8p)",
target, level, xoffset, yoffset, width, height, format, type, pixels);
try
{
if (!gl::IsInternalTextureTarget(target))
{
return gl::error(GL_INVALID_ENUM);
}
if (level < 0 || xoffset < 0 || yoffset < 0 || width < 0 || height < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (std::numeric_limits<GLsizei>::max() - xoffset < width || std::numeric_limits<GLsizei>::max() - yoffset < height)
{
return gl::error(GL_INVALID_VALUE);
}
if (!checkTextureFormatType(format, type))
{
return; // error is set by helper function
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (level > context->getMaximumTextureLevel())
{
return gl::error(GL_INVALID_VALUE);
}
if (format == GL_FLOAT)
{
if (!context->supportsFloat32Textures())
{
return gl::error(GL_INVALID_ENUM);
}
}
else if (format == GL_HALF_FLOAT_OES)
{
if (!context->supportsFloat16Textures())
{
return gl::error(GL_INVALID_ENUM);
}
}
else if (gl::IsDepthTexture(format))
{
if (!context->supportsDepthTextures())
{
return gl::error(GL_INVALID_ENUM);
}
if (target != GL_TEXTURE_2D)
{
return gl::error(GL_INVALID_OPERATION);
}
// OES_depth_texture supports loading depth data, but ANGLE_depth_texture does not
return gl::error(GL_INVALID_OPERATION);
}
if (width == 0 || height == 0 || pixels == NULL)
{
return;
}
if (target == GL_TEXTURE_2D)
{
gl::Texture2D *texture = context->getTexture2D();
if (validateSubImageParams2D(false, width, height, xoffset, yoffset, level, format, type, texture))
{
texture->subImage(level, xoffset, yoffset, width, height, format, type, context->getUnpackAlignment(), pixels);
}
}
else if (gl::IsCubemapTextureTarget(target))
{
gl::TextureCubeMap *texture = context->getTextureCubeMap();
if (validateSubImageParamsCube(false, width, height, xoffset, yoffset, target, level, format, type, texture))
{
texture->subImage(target, level, xoffset, yoffset, width, height, format, type, context->getUnpackAlignment(), pixels);
}
}
else
{
UNREACHABLE();
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform1f(GLint location, GLfloat x)
{
glUniform1fv(location, 1, &x);
}
void __stdcall glUniform1fv(GLint location, GLsizei count, const GLfloat* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform1fv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform1i(GLint location, GLint x)
{
glUniform1iv(location, 1, &x);
}
void __stdcall glUniform1iv(GLint location, GLsizei count, const GLint* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform1iv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform2f(GLint location, GLfloat x, GLfloat y)
{
GLfloat xy[2] = {x, y};
glUniform2fv(location, 1, (GLfloat*)&xy);
}
void __stdcall glUniform2fv(GLint location, GLsizei count, const GLfloat* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform2fv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform2i(GLint location, GLint x, GLint y)
{
GLint xy[4] = {x, y};
glUniform2iv(location, 1, (GLint*)&xy);
}
void __stdcall glUniform2iv(GLint location, GLsizei count, const GLint* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform2iv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform3f(GLint location, GLfloat x, GLfloat y, GLfloat z)
{
GLfloat xyz[3] = {x, y, z};
glUniform3fv(location, 1, (GLfloat*)&xyz);
}
void __stdcall glUniform3fv(GLint location, GLsizei count, const GLfloat* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform3fv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform3i(GLint location, GLint x, GLint y, GLint z)
{
GLint xyz[3] = {x, y, z};
glUniform3iv(location, 1, (GLint*)&xyz);
}
void __stdcall glUniform3iv(GLint location, GLsizei count, const GLint* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform3iv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform4f(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
{
GLfloat xyzw[4] = {x, y, z, w};
glUniform4fv(location, 1, (GLfloat*)&xyzw);
}
void __stdcall glUniform4fv(GLint location, GLsizei count, const GLfloat* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform4fv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniform4i(GLint location, GLint x, GLint y, GLint z, GLint w)
{
GLint xyzw[4] = {x, y, z, w};
glUniform4iv(location, 1, (GLint*)&xyzw);
}
void __stdcall glUniform4iv(GLint location, GLsizei count, const GLint* v)
{
EVENT("(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)", location, count, v);
try
{
if (count < 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniform4iv(location, count, v))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
{
EVENT("(GLint location = %d, GLsizei count = %d, GLboolean transpose = %d, const GLfloat* value = 0x%0.8p)",
location, count, transpose, value);
try
{
if (count < 0 || transpose != GL_FALSE)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniformMatrix2fv(location, count, value))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
{
EVENT("(GLint location = %d, GLsizei count = %d, GLboolean transpose = %d, const GLfloat* value = 0x%0.8p)",
location, count, transpose, value);
try
{
if (count < 0 || transpose != GL_FALSE)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniformMatrix3fv(location, count, value))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
{
EVENT("(GLint location = %d, GLsizei count = %d, GLboolean transpose = %d, const GLfloat* value = 0x%0.8p)",
location, count, transpose, value);
try
{
if (count < 0 || transpose != GL_FALSE)
{
return gl::error(GL_INVALID_VALUE);
}
if (location == -1)
{
return;
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::ProgramBinary *programBinary = context->getCurrentProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->setUniformMatrix4fv(location, count, value))
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glUseProgram(GLuint program)
{
EVENT("(GLuint program = %d)", program);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject && program != 0)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
if (program != 0 && !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
context->useProgram(program);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glValidateProgram(GLuint program)
{
EVENT("(GLuint program = %d)", program);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
if (context->getShader(program))
{
return gl::error(GL_INVALID_OPERATION);
}
else
{
return gl::error(GL_INVALID_VALUE);
}
}
programObject->validate();
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib1f(GLuint index, GLfloat x)
{
EVENT("(GLuint index = %d, GLfloat x = %f)", index, x);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { x, 0, 0, 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib1fv(GLuint index, const GLfloat* values)
{
EVENT("(GLuint index = %d, const GLfloat* values = 0x%0.8p)", index, values);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { values[0], 0, 0, 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib2f(GLuint index, GLfloat x, GLfloat y)
{
EVENT("(GLuint index = %d, GLfloat x = %f, GLfloat y = %f)", index, x, y);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { x, y, 0, 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib2fv(GLuint index, const GLfloat* values)
{
EVENT("(GLuint index = %d, const GLfloat* values = 0x%0.8p)", index, values);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { values[0], values[1], 0, 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z)
{
EVENT("(GLuint index = %d, GLfloat x = %f, GLfloat y = %f, GLfloat z = %f)", index, x, y, z);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { x, y, z, 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib3fv(GLuint index, const GLfloat* values)
{
EVENT("(GLuint index = %d, const GLfloat* values = 0x%0.8p)", index, values);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { values[0], values[1], values[2], 1 };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
{
EVENT("(GLuint index = %d, GLfloat x = %f, GLfloat y = %f, GLfloat z = %f, GLfloat w = %f)", index, x, y, z, w);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
GLfloat vals[4] = { x, y, z, w };
context->setVertexAttrib(index, vals);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttrib4fv(GLuint index, const GLfloat* values)
{
EVENT("(GLuint index = %d, const GLfloat* values = 0x%0.8p)", index, values);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setVertexAttrib(index, values);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttribDivisorANGLE(GLuint index, GLuint divisor)
{
EVENT("(GLuint index = %d, GLuint divisor = %d)", index, divisor);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setVertexAttribDivisor(index, divisor);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* ptr)
{
EVENT("(GLuint index = %d, GLint size = %d, GLenum type = 0x%X, "
"GLboolean normalized = %d, GLsizei stride = %d, const GLvoid* ptr = 0x%0.8p)",
index, size, type, normalized, stride, ptr);
try
{
if (index >= gl::MAX_VERTEX_ATTRIBS)
{
return gl::error(GL_INVALID_VALUE);
}
if (size < 1 || size > 4)
{
return gl::error(GL_INVALID_VALUE);
}
switch (type)
{
case GL_BYTE:
case GL_UNSIGNED_BYTE:
case GL_SHORT:
case GL_UNSIGNED_SHORT:
case GL_FIXED:
case GL_FLOAT:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if (stride < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setVertexAttribState(index, context->getArrayBuffer(), size, type, (normalized == GL_TRUE), stride, ptr);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glViewport(GLint x, GLint y, GLsizei width, GLsizei height)
{
EVENT("(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d)", x, y, width, height);
try
{
if (width < 0 || height < 0)
{
return gl::error(GL_INVALID_VALUE);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
context->setViewportParams(x, y, width, height);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glBlitFramebufferANGLE(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
GLbitfield mask, GLenum filter)
{
EVENT("(GLint srcX0 = %d, GLint srcY0 = %d, GLint srcX1 = %d, GLint srcY1 = %d, "
"GLint dstX0 = %d, GLint dstY0 = %d, GLint dstX1 = %d, GLint dstY1 = %d, "
"GLbitfield mask = 0x%X, GLenum filter = 0x%X)",
srcX0, srcY0, srcX1, srcX1, dstX0, dstY0, dstX1, dstY1, mask, filter);
try
{
switch (filter)
{
case GL_NEAREST:
break;
default:
return gl::error(GL_INVALID_ENUM);
}
if ((mask & ~(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)) != 0)
{
return gl::error(GL_INVALID_VALUE);
}
if (srcX1 - srcX0 != dstX1 - dstX0 || srcY1 - srcY0 != dstY1 - dstY0)
{
ERR("Scaling and flipping in BlitFramebufferANGLE not supported by this implementation");
return gl::error(GL_INVALID_OPERATION);
}
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (context->getReadFramebufferHandle() == context->getDrawFramebufferHandle())
{
ERR("Blits with the same source and destination framebuffer are not supported by this implementation.");
return gl::error(GL_INVALID_OPERATION);
}
context->blitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glTexImage3DOES(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth,
GLint border, GLenum format, GLenum type, const GLvoid* pixels)
{
EVENT("(GLenum target = 0x%X, GLint level = %d, GLenum internalformat = 0x%X, "
"GLsizei width = %d, GLsizei height = %d, GLsizei depth = %d, GLint border = %d, "
"GLenum format = 0x%X, GLenum type = 0x%x, const GLvoid* pixels = 0x%0.8p)",
target, level, internalformat, width, height, depth, border, format, type, pixels);
try
{
UNIMPLEMENTED(); // FIXME
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glGetProgramBinaryOES(GLuint program, GLsizei bufSize, GLsizei *length,
GLenum *binaryFormat, void *binary)
{
EVENT("(GLenum program = 0x%X, bufSize = %d, length = 0x%0.8p, binaryFormat = 0x%0.8p, binary = 0x%0.8p)",
program, bufSize, length, binaryFormat, binary);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Program *programObject = context->getProgram(program);
if (!programObject || !programObject->isLinked())
{
return gl::error(GL_INVALID_OPERATION);
}
gl::ProgramBinary *programBinary = programObject->getProgramBinary();
if (!programBinary)
{
return gl::error(GL_INVALID_OPERATION);
}
if (!programBinary->save(binary, bufSize, length))
{
return gl::error(GL_INVALID_OPERATION);
}
*binaryFormat = GL_PROGRAM_BINARY_ANGLE;
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glProgramBinaryOES(GLuint program, GLenum binaryFormat,
const void *binary, GLint length)
{
EVENT("(GLenum program = 0x%X, binaryFormat = 0x%x, binary = 0x%0.8p, length = %d)",
program, binaryFormat, binary, length);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (binaryFormat != GL_PROGRAM_BINARY_ANGLE)
{
return gl::error(GL_INVALID_ENUM);
}
gl::Program *programObject = context->getProgram(program);
if (!programObject)
{
return gl::error(GL_INVALID_OPERATION);
}
context->setProgramBinary(program, binary, length);
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
void __stdcall glDrawBuffersEXT(GLsizei n, const GLenum *bufs)
{
EVENT("(GLenum n = %d, bufs = 0x%0.8p)", n, bufs);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
if (n < 0 || (unsigned int)n > context->getMaximumRenderTargets())
{
return gl::error(GL_INVALID_VALUE);
}
if (context->getDrawFramebufferHandle() == 0)
{
if (n != 1)
{
return gl::error(GL_INVALID_OPERATION);
}
if (bufs[0] != GL_NONE && bufs[0] != GL_BACK)
{
return gl::error(GL_INVALID_OPERATION);
}
}
else
{
for (int colorAttachment = 0; colorAttachment < n; colorAttachment++)
{
const GLenum attachment = GL_COLOR_ATTACHMENT0_EXT + colorAttachment;
if (bufs[colorAttachment] != GL_NONE && bufs[colorAttachment] != attachment)
{
return gl::error(GL_INVALID_OPERATION);
}
}
}
gl::Framebuffer *framebuffer = context->getDrawFramebuffer();
for (int colorAttachment = 0; colorAttachment < n; colorAttachment++)
{
framebuffer->setDrawBufferState(colorAttachment, bufs[colorAttachment]);
}
for (int colorAttachment = n; colorAttachment < (int)context->getMaximumRenderTargets(); colorAttachment++)
{
framebuffer->setDrawBufferState(colorAttachment, GL_NONE);
}
}
}
catch (std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
__eglMustCastToProperFunctionPointerType __stdcall glGetProcAddress(const char *procname)
{
struct Extension
{
const char *name;
__eglMustCastToProperFunctionPointerType address;
};
static const Extension glExtensions[] =
{
{"glTexImage3DOES", (__eglMustCastToProperFunctionPointerType)glTexImage3DOES},
{"glBlitFramebufferANGLE", (__eglMustCastToProperFunctionPointerType)glBlitFramebufferANGLE},
{"glRenderbufferStorageMultisampleANGLE", (__eglMustCastToProperFunctionPointerType)glRenderbufferStorageMultisampleANGLE},
{"glDeleteFencesNV", (__eglMustCastToProperFunctionPointerType)glDeleteFencesNV},
{"glGenFencesNV", (__eglMustCastToProperFunctionPointerType)glGenFencesNV},
{"glIsFenceNV", (__eglMustCastToProperFunctionPointerType)glIsFenceNV},
{"glTestFenceNV", (__eglMustCastToProperFunctionPointerType)glTestFenceNV},
{"glGetFenceivNV", (__eglMustCastToProperFunctionPointerType)glGetFenceivNV},
{"glFinishFenceNV", (__eglMustCastToProperFunctionPointerType)glFinishFenceNV},
{"glSetFenceNV", (__eglMustCastToProperFunctionPointerType)glSetFenceNV},
{"glGetTranslatedShaderSourceANGLE", (__eglMustCastToProperFunctionPointerType)glGetTranslatedShaderSourceANGLE},
{"glTexStorage2DEXT", (__eglMustCastToProperFunctionPointerType)glTexStorage2DEXT},
{"glGetGraphicsResetStatusEXT", (__eglMustCastToProperFunctionPointerType)glGetGraphicsResetStatusEXT},
{"glReadnPixelsEXT", (__eglMustCastToProperFunctionPointerType)glReadnPixelsEXT},
{"glGetnUniformfvEXT", (__eglMustCastToProperFunctionPointerType)glGetnUniformfvEXT},
{"glGetnUniformivEXT", (__eglMustCastToProperFunctionPointerType)glGetnUniformivEXT},
{"glGenQueriesEXT", (__eglMustCastToProperFunctionPointerType)glGenQueriesEXT},
{"glDeleteQueriesEXT", (__eglMustCastToProperFunctionPointerType)glDeleteQueriesEXT},
{"glIsQueryEXT", (__eglMustCastToProperFunctionPointerType)glIsQueryEXT},
{"glBeginQueryEXT", (__eglMustCastToProperFunctionPointerType)glBeginQueryEXT},
{"glEndQueryEXT", (__eglMustCastToProperFunctionPointerType)glEndQueryEXT},
{"glGetQueryivEXT", (__eglMustCastToProperFunctionPointerType)glGetQueryivEXT},
{"glGetQueryObjectuivEXT", (__eglMustCastToProperFunctionPointerType)glGetQueryObjectuivEXT},
{"glDrawBuffersEXT", (__eglMustCastToProperFunctionPointerType)glDrawBuffersEXT},
{"glVertexAttribDivisorANGLE", (__eglMustCastToProperFunctionPointerType)glVertexAttribDivisorANGLE},
{"glDrawArraysInstancedANGLE", (__eglMustCastToProperFunctionPointerType)glDrawArraysInstancedANGLE},
{"glDrawElementsInstancedANGLE", (__eglMustCastToProperFunctionPointerType)glDrawElementsInstancedANGLE},
{"glGetProgramBinaryOES", (__eglMustCastToProperFunctionPointerType)glGetProgramBinaryOES},
{"glProgramBinaryOES", (__eglMustCastToProperFunctionPointerType)glProgramBinaryOES}, };
for (unsigned int ext = 0; ext < ArraySize(glExtensions); ext++)
{
if (strcmp(procname, glExtensions[ext].name) == 0)
{
return (__eglMustCastToProperFunctionPointerType)glExtensions[ext].address;
}
}
return NULL;
}
// Non-public functions used by EGL
bool __stdcall glBindTexImage(egl::Surface *surface)
{
EVENT("(egl::Surface* surface = 0x%0.8p)",
surface);
try
{
gl::Context *context = gl::getNonLostContext();
if (context)
{
gl::Texture2D *textureObject = context->getTexture2D();
if (textureObject->isImmutable())
{
return false;
}
if (textureObject)
{
textureObject->bindTexImage(surface);
}
}
}
catch(std::bad_alloc&)
{
return gl::error(GL_OUT_OF_MEMORY, false);
}
return true;
}
}
| 010smithzhang-ddd | src/libGLESv2/libGLESv2.cpp | C++ | bsd | 198,245 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file is automatically generated.
namespace gl
{
const static unsigned g_mantissa[2048] = {
0x00000000,
0x33800000,
0x34000000,
0x34400000,
0x34800000,
0x34a00000,
0x34c00000,
0x34e00000,
0x35000000,
0x35100000,
0x35200000,
0x35300000,
0x35400000,
0x35500000,
0x35600000,
0x35700000,
0x35800000,
0x35880000,
0x35900000,
0x35980000,
0x35a00000,
0x35a80000,
0x35b00000,
0x35b80000,
0x35c00000,
0x35c80000,
0x35d00000,
0x35d80000,
0x35e00000,
0x35e80000,
0x35f00000,
0x35f80000,
0x36000000,
0x36040000,
0x36080000,
0x360c0000,
0x36100000,
0x36140000,
0x36180000,
0x361c0000,
0x36200000,
0x36240000,
0x36280000,
0x362c0000,
0x36300000,
0x36340000,
0x36380000,
0x363c0000,
0x36400000,
0x36440000,
0x36480000,
0x364c0000,
0x36500000,
0x36540000,
0x36580000,
0x365c0000,
0x36600000,
0x36640000,
0x36680000,
0x366c0000,
0x36700000,
0x36740000,
0x36780000,
0x367c0000,
0x36800000,
0x36820000,
0x36840000,
0x36860000,
0x36880000,
0x368a0000,
0x368c0000,
0x368e0000,
0x36900000,
0x36920000,
0x36940000,
0x36960000,
0x36980000,
0x369a0000,
0x369c0000,
0x369e0000,
0x36a00000,
0x36a20000,
0x36a40000,
0x36a60000,
0x36a80000,
0x36aa0000,
0x36ac0000,
0x36ae0000,
0x36b00000,
0x36b20000,
0x36b40000,
0x36b60000,
0x36b80000,
0x36ba0000,
0x36bc0000,
0x36be0000,
0x36c00000,
0x36c20000,
0x36c40000,
0x36c60000,
0x36c80000,
0x36ca0000,
0x36cc0000,
0x36ce0000,
0x36d00000,
0x36d20000,
0x36d40000,
0x36d60000,
0x36d80000,
0x36da0000,
0x36dc0000,
0x36de0000,
0x36e00000,
0x36e20000,
0x36e40000,
0x36e60000,
0x36e80000,
0x36ea0000,
0x36ec0000,
0x36ee0000,
0x36f00000,
0x36f20000,
0x36f40000,
0x36f60000,
0x36f80000,
0x36fa0000,
0x36fc0000,
0x36fe0000,
0x37000000,
0x37010000,
0x37020000,
0x37030000,
0x37040000,
0x37050000,
0x37060000,
0x37070000,
0x37080000,
0x37090000,
0x370a0000,
0x370b0000,
0x370c0000,
0x370d0000,
0x370e0000,
0x370f0000,
0x37100000,
0x37110000,
0x37120000,
0x37130000,
0x37140000,
0x37150000,
0x37160000,
0x37170000,
0x37180000,
0x37190000,
0x371a0000,
0x371b0000,
0x371c0000,
0x371d0000,
0x371e0000,
0x371f0000,
0x37200000,
0x37210000,
0x37220000,
0x37230000,
0x37240000,
0x37250000,
0x37260000,
0x37270000,
0x37280000,
0x37290000,
0x372a0000,
0x372b0000,
0x372c0000,
0x372d0000,
0x372e0000,
0x372f0000,
0x37300000,
0x37310000,
0x37320000,
0x37330000,
0x37340000,
0x37350000,
0x37360000,
0x37370000,
0x37380000,
0x37390000,
0x373a0000,
0x373b0000,
0x373c0000,
0x373d0000,
0x373e0000,
0x373f0000,
0x37400000,
0x37410000,
0x37420000,
0x37430000,
0x37440000,
0x37450000,
0x37460000,
0x37470000,
0x37480000,
0x37490000,
0x374a0000,
0x374b0000,
0x374c0000,
0x374d0000,
0x374e0000,
0x374f0000,
0x37500000,
0x37510000,
0x37520000,
0x37530000,
0x37540000,
0x37550000,
0x37560000,
0x37570000,
0x37580000,
0x37590000,
0x375a0000,
0x375b0000,
0x375c0000,
0x375d0000,
0x375e0000,
0x375f0000,
0x37600000,
0x37610000,
0x37620000,
0x37630000,
0x37640000,
0x37650000,
0x37660000,
0x37670000,
0x37680000,
0x37690000,
0x376a0000,
0x376b0000,
0x376c0000,
0x376d0000,
0x376e0000,
0x376f0000,
0x37700000,
0x37710000,
0x37720000,
0x37730000,
0x37740000,
0x37750000,
0x37760000,
0x37770000,
0x37780000,
0x37790000,
0x377a0000,
0x377b0000,
0x377c0000,
0x377d0000,
0x377e0000,
0x377f0000,
0x37800000,
0x37808000,
0x37810000,
0x37818000,
0x37820000,
0x37828000,
0x37830000,
0x37838000,
0x37840000,
0x37848000,
0x37850000,
0x37858000,
0x37860000,
0x37868000,
0x37870000,
0x37878000,
0x37880000,
0x37888000,
0x37890000,
0x37898000,
0x378a0000,
0x378a8000,
0x378b0000,
0x378b8000,
0x378c0000,
0x378c8000,
0x378d0000,
0x378d8000,
0x378e0000,
0x378e8000,
0x378f0000,
0x378f8000,
0x37900000,
0x37908000,
0x37910000,
0x37918000,
0x37920000,
0x37928000,
0x37930000,
0x37938000,
0x37940000,
0x37948000,
0x37950000,
0x37958000,
0x37960000,
0x37968000,
0x37970000,
0x37978000,
0x37980000,
0x37988000,
0x37990000,
0x37998000,
0x379a0000,
0x379a8000,
0x379b0000,
0x379b8000,
0x379c0000,
0x379c8000,
0x379d0000,
0x379d8000,
0x379e0000,
0x379e8000,
0x379f0000,
0x379f8000,
0x37a00000,
0x37a08000,
0x37a10000,
0x37a18000,
0x37a20000,
0x37a28000,
0x37a30000,
0x37a38000,
0x37a40000,
0x37a48000,
0x37a50000,
0x37a58000,
0x37a60000,
0x37a68000,
0x37a70000,
0x37a78000,
0x37a80000,
0x37a88000,
0x37a90000,
0x37a98000,
0x37aa0000,
0x37aa8000,
0x37ab0000,
0x37ab8000,
0x37ac0000,
0x37ac8000,
0x37ad0000,
0x37ad8000,
0x37ae0000,
0x37ae8000,
0x37af0000,
0x37af8000,
0x37b00000,
0x37b08000,
0x37b10000,
0x37b18000,
0x37b20000,
0x37b28000,
0x37b30000,
0x37b38000,
0x37b40000,
0x37b48000,
0x37b50000,
0x37b58000,
0x37b60000,
0x37b68000,
0x37b70000,
0x37b78000,
0x37b80000,
0x37b88000,
0x37b90000,
0x37b98000,
0x37ba0000,
0x37ba8000,
0x37bb0000,
0x37bb8000,
0x37bc0000,
0x37bc8000,
0x37bd0000,
0x37bd8000,
0x37be0000,
0x37be8000,
0x37bf0000,
0x37bf8000,
0x37c00000,
0x37c08000,
0x37c10000,
0x37c18000,
0x37c20000,
0x37c28000,
0x37c30000,
0x37c38000,
0x37c40000,
0x37c48000,
0x37c50000,
0x37c58000,
0x37c60000,
0x37c68000,
0x37c70000,
0x37c78000,
0x37c80000,
0x37c88000,
0x37c90000,
0x37c98000,
0x37ca0000,
0x37ca8000,
0x37cb0000,
0x37cb8000,
0x37cc0000,
0x37cc8000,
0x37cd0000,
0x37cd8000,
0x37ce0000,
0x37ce8000,
0x37cf0000,
0x37cf8000,
0x37d00000,
0x37d08000,
0x37d10000,
0x37d18000,
0x37d20000,
0x37d28000,
0x37d30000,
0x37d38000,
0x37d40000,
0x37d48000,
0x37d50000,
0x37d58000,
0x37d60000,
0x37d68000,
0x37d70000,
0x37d78000,
0x37d80000,
0x37d88000,
0x37d90000,
0x37d98000,
0x37da0000,
0x37da8000,
0x37db0000,
0x37db8000,
0x37dc0000,
0x37dc8000,
0x37dd0000,
0x37dd8000,
0x37de0000,
0x37de8000,
0x37df0000,
0x37df8000,
0x37e00000,
0x37e08000,
0x37e10000,
0x37e18000,
0x37e20000,
0x37e28000,
0x37e30000,
0x37e38000,
0x37e40000,
0x37e48000,
0x37e50000,
0x37e58000,
0x37e60000,
0x37e68000,
0x37e70000,
0x37e78000,
0x37e80000,
0x37e88000,
0x37e90000,
0x37e98000,
0x37ea0000,
0x37ea8000,
0x37eb0000,
0x37eb8000,
0x37ec0000,
0x37ec8000,
0x37ed0000,
0x37ed8000,
0x37ee0000,
0x37ee8000,
0x37ef0000,
0x37ef8000,
0x37f00000,
0x37f08000,
0x37f10000,
0x37f18000,
0x37f20000,
0x37f28000,
0x37f30000,
0x37f38000,
0x37f40000,
0x37f48000,
0x37f50000,
0x37f58000,
0x37f60000,
0x37f68000,
0x37f70000,
0x37f78000,
0x37f80000,
0x37f88000,
0x37f90000,
0x37f98000,
0x37fa0000,
0x37fa8000,
0x37fb0000,
0x37fb8000,
0x37fc0000,
0x37fc8000,
0x37fd0000,
0x37fd8000,
0x37fe0000,
0x37fe8000,
0x37ff0000,
0x37ff8000,
0x38000000,
0x38004000,
0x38008000,
0x3800c000,
0x38010000,
0x38014000,
0x38018000,
0x3801c000,
0x38020000,
0x38024000,
0x38028000,
0x3802c000,
0x38030000,
0x38034000,
0x38038000,
0x3803c000,
0x38040000,
0x38044000,
0x38048000,
0x3804c000,
0x38050000,
0x38054000,
0x38058000,
0x3805c000,
0x38060000,
0x38064000,
0x38068000,
0x3806c000,
0x38070000,
0x38074000,
0x38078000,
0x3807c000,
0x38080000,
0x38084000,
0x38088000,
0x3808c000,
0x38090000,
0x38094000,
0x38098000,
0x3809c000,
0x380a0000,
0x380a4000,
0x380a8000,
0x380ac000,
0x380b0000,
0x380b4000,
0x380b8000,
0x380bc000,
0x380c0000,
0x380c4000,
0x380c8000,
0x380cc000,
0x380d0000,
0x380d4000,
0x380d8000,
0x380dc000,
0x380e0000,
0x380e4000,
0x380e8000,
0x380ec000,
0x380f0000,
0x380f4000,
0x380f8000,
0x380fc000,
0x38100000,
0x38104000,
0x38108000,
0x3810c000,
0x38110000,
0x38114000,
0x38118000,
0x3811c000,
0x38120000,
0x38124000,
0x38128000,
0x3812c000,
0x38130000,
0x38134000,
0x38138000,
0x3813c000,
0x38140000,
0x38144000,
0x38148000,
0x3814c000,
0x38150000,
0x38154000,
0x38158000,
0x3815c000,
0x38160000,
0x38164000,
0x38168000,
0x3816c000,
0x38170000,
0x38174000,
0x38178000,
0x3817c000,
0x38180000,
0x38184000,
0x38188000,
0x3818c000,
0x38190000,
0x38194000,
0x38198000,
0x3819c000,
0x381a0000,
0x381a4000,
0x381a8000,
0x381ac000,
0x381b0000,
0x381b4000,
0x381b8000,
0x381bc000,
0x381c0000,
0x381c4000,
0x381c8000,
0x381cc000,
0x381d0000,
0x381d4000,
0x381d8000,
0x381dc000,
0x381e0000,
0x381e4000,
0x381e8000,
0x381ec000,
0x381f0000,
0x381f4000,
0x381f8000,
0x381fc000,
0x38200000,
0x38204000,
0x38208000,
0x3820c000,
0x38210000,
0x38214000,
0x38218000,
0x3821c000,
0x38220000,
0x38224000,
0x38228000,
0x3822c000,
0x38230000,
0x38234000,
0x38238000,
0x3823c000,
0x38240000,
0x38244000,
0x38248000,
0x3824c000,
0x38250000,
0x38254000,
0x38258000,
0x3825c000,
0x38260000,
0x38264000,
0x38268000,
0x3826c000,
0x38270000,
0x38274000,
0x38278000,
0x3827c000,
0x38280000,
0x38284000,
0x38288000,
0x3828c000,
0x38290000,
0x38294000,
0x38298000,
0x3829c000,
0x382a0000,
0x382a4000,
0x382a8000,
0x382ac000,
0x382b0000,
0x382b4000,
0x382b8000,
0x382bc000,
0x382c0000,
0x382c4000,
0x382c8000,
0x382cc000,
0x382d0000,
0x382d4000,
0x382d8000,
0x382dc000,
0x382e0000,
0x382e4000,
0x382e8000,
0x382ec000,
0x382f0000,
0x382f4000,
0x382f8000,
0x382fc000,
0x38300000,
0x38304000,
0x38308000,
0x3830c000,
0x38310000,
0x38314000,
0x38318000,
0x3831c000,
0x38320000,
0x38324000,
0x38328000,
0x3832c000,
0x38330000,
0x38334000,
0x38338000,
0x3833c000,
0x38340000,
0x38344000,
0x38348000,
0x3834c000,
0x38350000,
0x38354000,
0x38358000,
0x3835c000,
0x38360000,
0x38364000,
0x38368000,
0x3836c000,
0x38370000,
0x38374000,
0x38378000,
0x3837c000,
0x38380000,
0x38384000,
0x38388000,
0x3838c000,
0x38390000,
0x38394000,
0x38398000,
0x3839c000,
0x383a0000,
0x383a4000,
0x383a8000,
0x383ac000,
0x383b0000,
0x383b4000,
0x383b8000,
0x383bc000,
0x383c0000,
0x383c4000,
0x383c8000,
0x383cc000,
0x383d0000,
0x383d4000,
0x383d8000,
0x383dc000,
0x383e0000,
0x383e4000,
0x383e8000,
0x383ec000,
0x383f0000,
0x383f4000,
0x383f8000,
0x383fc000,
0x38400000,
0x38404000,
0x38408000,
0x3840c000,
0x38410000,
0x38414000,
0x38418000,
0x3841c000,
0x38420000,
0x38424000,
0x38428000,
0x3842c000,
0x38430000,
0x38434000,
0x38438000,
0x3843c000,
0x38440000,
0x38444000,
0x38448000,
0x3844c000,
0x38450000,
0x38454000,
0x38458000,
0x3845c000,
0x38460000,
0x38464000,
0x38468000,
0x3846c000,
0x38470000,
0x38474000,
0x38478000,
0x3847c000,
0x38480000,
0x38484000,
0x38488000,
0x3848c000,
0x38490000,
0x38494000,
0x38498000,
0x3849c000,
0x384a0000,
0x384a4000,
0x384a8000,
0x384ac000,
0x384b0000,
0x384b4000,
0x384b8000,
0x384bc000,
0x384c0000,
0x384c4000,
0x384c8000,
0x384cc000,
0x384d0000,
0x384d4000,
0x384d8000,
0x384dc000,
0x384e0000,
0x384e4000,
0x384e8000,
0x384ec000,
0x384f0000,
0x384f4000,
0x384f8000,
0x384fc000,
0x38500000,
0x38504000,
0x38508000,
0x3850c000,
0x38510000,
0x38514000,
0x38518000,
0x3851c000,
0x38520000,
0x38524000,
0x38528000,
0x3852c000,
0x38530000,
0x38534000,
0x38538000,
0x3853c000,
0x38540000,
0x38544000,
0x38548000,
0x3854c000,
0x38550000,
0x38554000,
0x38558000,
0x3855c000,
0x38560000,
0x38564000,
0x38568000,
0x3856c000,
0x38570000,
0x38574000,
0x38578000,
0x3857c000,
0x38580000,
0x38584000,
0x38588000,
0x3858c000,
0x38590000,
0x38594000,
0x38598000,
0x3859c000,
0x385a0000,
0x385a4000,
0x385a8000,
0x385ac000,
0x385b0000,
0x385b4000,
0x385b8000,
0x385bc000,
0x385c0000,
0x385c4000,
0x385c8000,
0x385cc000,
0x385d0000,
0x385d4000,
0x385d8000,
0x385dc000,
0x385e0000,
0x385e4000,
0x385e8000,
0x385ec000,
0x385f0000,
0x385f4000,
0x385f8000,
0x385fc000,
0x38600000,
0x38604000,
0x38608000,
0x3860c000,
0x38610000,
0x38614000,
0x38618000,
0x3861c000,
0x38620000,
0x38624000,
0x38628000,
0x3862c000,
0x38630000,
0x38634000,
0x38638000,
0x3863c000,
0x38640000,
0x38644000,
0x38648000,
0x3864c000,
0x38650000,
0x38654000,
0x38658000,
0x3865c000,
0x38660000,
0x38664000,
0x38668000,
0x3866c000,
0x38670000,
0x38674000,
0x38678000,
0x3867c000,
0x38680000,
0x38684000,
0x38688000,
0x3868c000,
0x38690000,
0x38694000,
0x38698000,
0x3869c000,
0x386a0000,
0x386a4000,
0x386a8000,
0x386ac000,
0x386b0000,
0x386b4000,
0x386b8000,
0x386bc000,
0x386c0000,
0x386c4000,
0x386c8000,
0x386cc000,
0x386d0000,
0x386d4000,
0x386d8000,
0x386dc000,
0x386e0000,
0x386e4000,
0x386e8000,
0x386ec000,
0x386f0000,
0x386f4000,
0x386f8000,
0x386fc000,
0x38700000,
0x38704000,
0x38708000,
0x3870c000,
0x38710000,
0x38714000,
0x38718000,
0x3871c000,
0x38720000,
0x38724000,
0x38728000,
0x3872c000,
0x38730000,
0x38734000,
0x38738000,
0x3873c000,
0x38740000,
0x38744000,
0x38748000,
0x3874c000,
0x38750000,
0x38754000,
0x38758000,
0x3875c000,
0x38760000,
0x38764000,
0x38768000,
0x3876c000,
0x38770000,
0x38774000,
0x38778000,
0x3877c000,
0x38780000,
0x38784000,
0x38788000,
0x3878c000,
0x38790000,
0x38794000,
0x38798000,
0x3879c000,
0x387a0000,
0x387a4000,
0x387a8000,
0x387ac000,
0x387b0000,
0x387b4000,
0x387b8000,
0x387bc000,
0x387c0000,
0x387c4000,
0x387c8000,
0x387cc000,
0x387d0000,
0x387d4000,
0x387d8000,
0x387dc000,
0x387e0000,
0x387e4000,
0x387e8000,
0x387ec000,
0x387f0000,
0x387f4000,
0x387f8000,
0x387fc000,
0x38000000,
0x38002000,
0x38004000,
0x38006000,
0x38008000,
0x3800a000,
0x3800c000,
0x3800e000,
0x38010000,
0x38012000,
0x38014000,
0x38016000,
0x38018000,
0x3801a000,
0x3801c000,
0x3801e000,
0x38020000,
0x38022000,
0x38024000,
0x38026000,
0x38028000,
0x3802a000,
0x3802c000,
0x3802e000,
0x38030000,
0x38032000,
0x38034000,
0x38036000,
0x38038000,
0x3803a000,
0x3803c000,
0x3803e000,
0x38040000,
0x38042000,
0x38044000,
0x38046000,
0x38048000,
0x3804a000,
0x3804c000,
0x3804e000,
0x38050000,
0x38052000,
0x38054000,
0x38056000,
0x38058000,
0x3805a000,
0x3805c000,
0x3805e000,
0x38060000,
0x38062000,
0x38064000,
0x38066000,
0x38068000,
0x3806a000,
0x3806c000,
0x3806e000,
0x38070000,
0x38072000,
0x38074000,
0x38076000,
0x38078000,
0x3807a000,
0x3807c000,
0x3807e000,
0x38080000,
0x38082000,
0x38084000,
0x38086000,
0x38088000,
0x3808a000,
0x3808c000,
0x3808e000,
0x38090000,
0x38092000,
0x38094000,
0x38096000,
0x38098000,
0x3809a000,
0x3809c000,
0x3809e000,
0x380a0000,
0x380a2000,
0x380a4000,
0x380a6000,
0x380a8000,
0x380aa000,
0x380ac000,
0x380ae000,
0x380b0000,
0x380b2000,
0x380b4000,
0x380b6000,
0x380b8000,
0x380ba000,
0x380bc000,
0x380be000,
0x380c0000,
0x380c2000,
0x380c4000,
0x380c6000,
0x380c8000,
0x380ca000,
0x380cc000,
0x380ce000,
0x380d0000,
0x380d2000,
0x380d4000,
0x380d6000,
0x380d8000,
0x380da000,
0x380dc000,
0x380de000,
0x380e0000,
0x380e2000,
0x380e4000,
0x380e6000,
0x380e8000,
0x380ea000,
0x380ec000,
0x380ee000,
0x380f0000,
0x380f2000,
0x380f4000,
0x380f6000,
0x380f8000,
0x380fa000,
0x380fc000,
0x380fe000,
0x38100000,
0x38102000,
0x38104000,
0x38106000,
0x38108000,
0x3810a000,
0x3810c000,
0x3810e000,
0x38110000,
0x38112000,
0x38114000,
0x38116000,
0x38118000,
0x3811a000,
0x3811c000,
0x3811e000,
0x38120000,
0x38122000,
0x38124000,
0x38126000,
0x38128000,
0x3812a000,
0x3812c000,
0x3812e000,
0x38130000,
0x38132000,
0x38134000,
0x38136000,
0x38138000,
0x3813a000,
0x3813c000,
0x3813e000,
0x38140000,
0x38142000,
0x38144000,
0x38146000,
0x38148000,
0x3814a000,
0x3814c000,
0x3814e000,
0x38150000,
0x38152000,
0x38154000,
0x38156000,
0x38158000,
0x3815a000,
0x3815c000,
0x3815e000,
0x38160000,
0x38162000,
0x38164000,
0x38166000,
0x38168000,
0x3816a000,
0x3816c000,
0x3816e000,
0x38170000,
0x38172000,
0x38174000,
0x38176000,
0x38178000,
0x3817a000,
0x3817c000,
0x3817e000,
0x38180000,
0x38182000,
0x38184000,
0x38186000,
0x38188000,
0x3818a000,
0x3818c000,
0x3818e000,
0x38190000,
0x38192000,
0x38194000,
0x38196000,
0x38198000,
0x3819a000,
0x3819c000,
0x3819e000,
0x381a0000,
0x381a2000,
0x381a4000,
0x381a6000,
0x381a8000,
0x381aa000,
0x381ac000,
0x381ae000,
0x381b0000,
0x381b2000,
0x381b4000,
0x381b6000,
0x381b8000,
0x381ba000,
0x381bc000,
0x381be000,
0x381c0000,
0x381c2000,
0x381c4000,
0x381c6000,
0x381c8000,
0x381ca000,
0x381cc000,
0x381ce000,
0x381d0000,
0x381d2000,
0x381d4000,
0x381d6000,
0x381d8000,
0x381da000,
0x381dc000,
0x381de000,
0x381e0000,
0x381e2000,
0x381e4000,
0x381e6000,
0x381e8000,
0x381ea000,
0x381ec000,
0x381ee000,
0x381f0000,
0x381f2000,
0x381f4000,
0x381f6000,
0x381f8000,
0x381fa000,
0x381fc000,
0x381fe000,
0x38200000,
0x38202000,
0x38204000,
0x38206000,
0x38208000,
0x3820a000,
0x3820c000,
0x3820e000,
0x38210000,
0x38212000,
0x38214000,
0x38216000,
0x38218000,
0x3821a000,
0x3821c000,
0x3821e000,
0x38220000,
0x38222000,
0x38224000,
0x38226000,
0x38228000,
0x3822a000,
0x3822c000,
0x3822e000,
0x38230000,
0x38232000,
0x38234000,
0x38236000,
0x38238000,
0x3823a000,
0x3823c000,
0x3823e000,
0x38240000,
0x38242000,
0x38244000,
0x38246000,
0x38248000,
0x3824a000,
0x3824c000,
0x3824e000,
0x38250000,
0x38252000,
0x38254000,
0x38256000,
0x38258000,
0x3825a000,
0x3825c000,
0x3825e000,
0x38260000,
0x38262000,
0x38264000,
0x38266000,
0x38268000,
0x3826a000,
0x3826c000,
0x3826e000,
0x38270000,
0x38272000,
0x38274000,
0x38276000,
0x38278000,
0x3827a000,
0x3827c000,
0x3827e000,
0x38280000,
0x38282000,
0x38284000,
0x38286000,
0x38288000,
0x3828a000,
0x3828c000,
0x3828e000,
0x38290000,
0x38292000,
0x38294000,
0x38296000,
0x38298000,
0x3829a000,
0x3829c000,
0x3829e000,
0x382a0000,
0x382a2000,
0x382a4000,
0x382a6000,
0x382a8000,
0x382aa000,
0x382ac000,
0x382ae000,
0x382b0000,
0x382b2000,
0x382b4000,
0x382b6000,
0x382b8000,
0x382ba000,
0x382bc000,
0x382be000,
0x382c0000,
0x382c2000,
0x382c4000,
0x382c6000,
0x382c8000,
0x382ca000,
0x382cc000,
0x382ce000,
0x382d0000,
0x382d2000,
0x382d4000,
0x382d6000,
0x382d8000,
0x382da000,
0x382dc000,
0x382de000,
0x382e0000,
0x382e2000,
0x382e4000,
0x382e6000,
0x382e8000,
0x382ea000,
0x382ec000,
0x382ee000,
0x382f0000,
0x382f2000,
0x382f4000,
0x382f6000,
0x382f8000,
0x382fa000,
0x382fc000,
0x382fe000,
0x38300000,
0x38302000,
0x38304000,
0x38306000,
0x38308000,
0x3830a000,
0x3830c000,
0x3830e000,
0x38310000,
0x38312000,
0x38314000,
0x38316000,
0x38318000,
0x3831a000,
0x3831c000,
0x3831e000,
0x38320000,
0x38322000,
0x38324000,
0x38326000,
0x38328000,
0x3832a000,
0x3832c000,
0x3832e000,
0x38330000,
0x38332000,
0x38334000,
0x38336000,
0x38338000,
0x3833a000,
0x3833c000,
0x3833e000,
0x38340000,
0x38342000,
0x38344000,
0x38346000,
0x38348000,
0x3834a000,
0x3834c000,
0x3834e000,
0x38350000,
0x38352000,
0x38354000,
0x38356000,
0x38358000,
0x3835a000,
0x3835c000,
0x3835e000,
0x38360000,
0x38362000,
0x38364000,
0x38366000,
0x38368000,
0x3836a000,
0x3836c000,
0x3836e000,
0x38370000,
0x38372000,
0x38374000,
0x38376000,
0x38378000,
0x3837a000,
0x3837c000,
0x3837e000,
0x38380000,
0x38382000,
0x38384000,
0x38386000,
0x38388000,
0x3838a000,
0x3838c000,
0x3838e000,
0x38390000,
0x38392000,
0x38394000,
0x38396000,
0x38398000,
0x3839a000,
0x3839c000,
0x3839e000,
0x383a0000,
0x383a2000,
0x383a4000,
0x383a6000,
0x383a8000,
0x383aa000,
0x383ac000,
0x383ae000,
0x383b0000,
0x383b2000,
0x383b4000,
0x383b6000,
0x383b8000,
0x383ba000,
0x383bc000,
0x383be000,
0x383c0000,
0x383c2000,
0x383c4000,
0x383c6000,
0x383c8000,
0x383ca000,
0x383cc000,
0x383ce000,
0x383d0000,
0x383d2000,
0x383d4000,
0x383d6000,
0x383d8000,
0x383da000,
0x383dc000,
0x383de000,
0x383e0000,
0x383e2000,
0x383e4000,
0x383e6000,
0x383e8000,
0x383ea000,
0x383ec000,
0x383ee000,
0x383f0000,
0x383f2000,
0x383f4000,
0x383f6000,
0x383f8000,
0x383fa000,
0x383fc000,
0x383fe000,
0x38400000,
0x38402000,
0x38404000,
0x38406000,
0x38408000,
0x3840a000,
0x3840c000,
0x3840e000,
0x38410000,
0x38412000,
0x38414000,
0x38416000,
0x38418000,
0x3841a000,
0x3841c000,
0x3841e000,
0x38420000,
0x38422000,
0x38424000,
0x38426000,
0x38428000,
0x3842a000,
0x3842c000,
0x3842e000,
0x38430000,
0x38432000,
0x38434000,
0x38436000,
0x38438000,
0x3843a000,
0x3843c000,
0x3843e000,
0x38440000,
0x38442000,
0x38444000,
0x38446000,
0x38448000,
0x3844a000,
0x3844c000,
0x3844e000,
0x38450000,
0x38452000,
0x38454000,
0x38456000,
0x38458000,
0x3845a000,
0x3845c000,
0x3845e000,
0x38460000,
0x38462000,
0x38464000,
0x38466000,
0x38468000,
0x3846a000,
0x3846c000,
0x3846e000,
0x38470000,
0x38472000,
0x38474000,
0x38476000,
0x38478000,
0x3847a000,
0x3847c000,
0x3847e000,
0x38480000,
0x38482000,
0x38484000,
0x38486000,
0x38488000,
0x3848a000,
0x3848c000,
0x3848e000,
0x38490000,
0x38492000,
0x38494000,
0x38496000,
0x38498000,
0x3849a000,
0x3849c000,
0x3849e000,
0x384a0000,
0x384a2000,
0x384a4000,
0x384a6000,
0x384a8000,
0x384aa000,
0x384ac000,
0x384ae000,
0x384b0000,
0x384b2000,
0x384b4000,
0x384b6000,
0x384b8000,
0x384ba000,
0x384bc000,
0x384be000,
0x384c0000,
0x384c2000,
0x384c4000,
0x384c6000,
0x384c8000,
0x384ca000,
0x384cc000,
0x384ce000,
0x384d0000,
0x384d2000,
0x384d4000,
0x384d6000,
0x384d8000,
0x384da000,
0x384dc000,
0x384de000,
0x384e0000,
0x384e2000,
0x384e4000,
0x384e6000,
0x384e8000,
0x384ea000,
0x384ec000,
0x384ee000,
0x384f0000,
0x384f2000,
0x384f4000,
0x384f6000,
0x384f8000,
0x384fa000,
0x384fc000,
0x384fe000,
0x38500000,
0x38502000,
0x38504000,
0x38506000,
0x38508000,
0x3850a000,
0x3850c000,
0x3850e000,
0x38510000,
0x38512000,
0x38514000,
0x38516000,
0x38518000,
0x3851a000,
0x3851c000,
0x3851e000,
0x38520000,
0x38522000,
0x38524000,
0x38526000,
0x38528000,
0x3852a000,
0x3852c000,
0x3852e000,
0x38530000,
0x38532000,
0x38534000,
0x38536000,
0x38538000,
0x3853a000,
0x3853c000,
0x3853e000,
0x38540000,
0x38542000,
0x38544000,
0x38546000,
0x38548000,
0x3854a000,
0x3854c000,
0x3854e000,
0x38550000,
0x38552000,
0x38554000,
0x38556000,
0x38558000,
0x3855a000,
0x3855c000,
0x3855e000,
0x38560000,
0x38562000,
0x38564000,
0x38566000,
0x38568000,
0x3856a000,
0x3856c000,
0x3856e000,
0x38570000,
0x38572000,
0x38574000,
0x38576000,
0x38578000,
0x3857a000,
0x3857c000,
0x3857e000,
0x38580000,
0x38582000,
0x38584000,
0x38586000,
0x38588000,
0x3858a000,
0x3858c000,
0x3858e000,
0x38590000,
0x38592000,
0x38594000,
0x38596000,
0x38598000,
0x3859a000,
0x3859c000,
0x3859e000,
0x385a0000,
0x385a2000,
0x385a4000,
0x385a6000,
0x385a8000,
0x385aa000,
0x385ac000,
0x385ae000,
0x385b0000,
0x385b2000,
0x385b4000,
0x385b6000,
0x385b8000,
0x385ba000,
0x385bc000,
0x385be000,
0x385c0000,
0x385c2000,
0x385c4000,
0x385c6000,
0x385c8000,
0x385ca000,
0x385cc000,
0x385ce000,
0x385d0000,
0x385d2000,
0x385d4000,
0x385d6000,
0x385d8000,
0x385da000,
0x385dc000,
0x385de000,
0x385e0000,
0x385e2000,
0x385e4000,
0x385e6000,
0x385e8000,
0x385ea000,
0x385ec000,
0x385ee000,
0x385f0000,
0x385f2000,
0x385f4000,
0x385f6000,
0x385f8000,
0x385fa000,
0x385fc000,
0x385fe000,
0x38600000,
0x38602000,
0x38604000,
0x38606000,
0x38608000,
0x3860a000,
0x3860c000,
0x3860e000,
0x38610000,
0x38612000,
0x38614000,
0x38616000,
0x38618000,
0x3861a000,
0x3861c000,
0x3861e000,
0x38620000,
0x38622000,
0x38624000,
0x38626000,
0x38628000,
0x3862a000,
0x3862c000,
0x3862e000,
0x38630000,
0x38632000,
0x38634000,
0x38636000,
0x38638000,
0x3863a000,
0x3863c000,
0x3863e000,
0x38640000,
0x38642000,
0x38644000,
0x38646000,
0x38648000,
0x3864a000,
0x3864c000,
0x3864e000,
0x38650000,
0x38652000,
0x38654000,
0x38656000,
0x38658000,
0x3865a000,
0x3865c000,
0x3865e000,
0x38660000,
0x38662000,
0x38664000,
0x38666000,
0x38668000,
0x3866a000,
0x3866c000,
0x3866e000,
0x38670000,
0x38672000,
0x38674000,
0x38676000,
0x38678000,
0x3867a000,
0x3867c000,
0x3867e000,
0x38680000,
0x38682000,
0x38684000,
0x38686000,
0x38688000,
0x3868a000,
0x3868c000,
0x3868e000,
0x38690000,
0x38692000,
0x38694000,
0x38696000,
0x38698000,
0x3869a000,
0x3869c000,
0x3869e000,
0x386a0000,
0x386a2000,
0x386a4000,
0x386a6000,
0x386a8000,
0x386aa000,
0x386ac000,
0x386ae000,
0x386b0000,
0x386b2000,
0x386b4000,
0x386b6000,
0x386b8000,
0x386ba000,
0x386bc000,
0x386be000,
0x386c0000,
0x386c2000,
0x386c4000,
0x386c6000,
0x386c8000,
0x386ca000,
0x386cc000,
0x386ce000,
0x386d0000,
0x386d2000,
0x386d4000,
0x386d6000,
0x386d8000,
0x386da000,
0x386dc000,
0x386de000,
0x386e0000,
0x386e2000,
0x386e4000,
0x386e6000,
0x386e8000,
0x386ea000,
0x386ec000,
0x386ee000,
0x386f0000,
0x386f2000,
0x386f4000,
0x386f6000,
0x386f8000,
0x386fa000,
0x386fc000,
0x386fe000,
0x38700000,
0x38702000,
0x38704000,
0x38706000,
0x38708000,
0x3870a000,
0x3870c000,
0x3870e000,
0x38710000,
0x38712000,
0x38714000,
0x38716000,
0x38718000,
0x3871a000,
0x3871c000,
0x3871e000,
0x38720000,
0x38722000,
0x38724000,
0x38726000,
0x38728000,
0x3872a000,
0x3872c000,
0x3872e000,
0x38730000,
0x38732000,
0x38734000,
0x38736000,
0x38738000,
0x3873a000,
0x3873c000,
0x3873e000,
0x38740000,
0x38742000,
0x38744000,
0x38746000,
0x38748000,
0x3874a000,
0x3874c000,
0x3874e000,
0x38750000,
0x38752000,
0x38754000,
0x38756000,
0x38758000,
0x3875a000,
0x3875c000,
0x3875e000,
0x38760000,
0x38762000,
0x38764000,
0x38766000,
0x38768000,
0x3876a000,
0x3876c000,
0x3876e000,
0x38770000,
0x38772000,
0x38774000,
0x38776000,
0x38778000,
0x3877a000,
0x3877c000,
0x3877e000,
0x38780000,
0x38782000,
0x38784000,
0x38786000,
0x38788000,
0x3878a000,
0x3878c000,
0x3878e000,
0x38790000,
0x38792000,
0x38794000,
0x38796000,
0x38798000,
0x3879a000,
0x3879c000,
0x3879e000,
0x387a0000,
0x387a2000,
0x387a4000,
0x387a6000,
0x387a8000,
0x387aa000,
0x387ac000,
0x387ae000,
0x387b0000,
0x387b2000,
0x387b4000,
0x387b6000,
0x387b8000,
0x387ba000,
0x387bc000,
0x387be000,
0x387c0000,
0x387c2000,
0x387c4000,
0x387c6000,
0x387c8000,
0x387ca000,
0x387cc000,
0x387ce000,
0x387d0000,
0x387d2000,
0x387d4000,
0x387d6000,
0x387d8000,
0x387da000,
0x387dc000,
0x387de000,
0x387e0000,
0x387e2000,
0x387e4000,
0x387e6000,
0x387e8000,
0x387ea000,
0x387ec000,
0x387ee000,
0x387f0000,
0x387f2000,
0x387f4000,
0x387f6000,
0x387f8000,
0x387fa000,
0x387fc000,
0x387fe000,
};
const static unsigned g_exponent[64] = {
0x00000000,
0x00800000,
0x01000000,
0x01800000,
0x02000000,
0x02800000,
0x03000000,
0x03800000,
0x04000000,
0x04800000,
0x05000000,
0x05800000,
0x06000000,
0x06800000,
0x07000000,
0x07800000,
0x08000000,
0x08800000,
0x09000000,
0x09800000,
0x0a000000,
0x0a800000,
0x0b000000,
0x0b800000,
0x0c000000,
0x0c800000,
0x0d000000,
0x0d800000,
0x0e000000,
0x0e800000,
0x0f000000,
0x47800000,
0x80000000,
0x80800000,
0x81000000,
0x81800000,
0x82000000,
0x82800000,
0x83000000,
0x83800000,
0x84000000,
0x84800000,
0x85000000,
0x85800000,
0x86000000,
0x86800000,
0x87000000,
0x87800000,
0x88000000,
0x88800000,
0x89000000,
0x89800000,
0x8a000000,
0x8a800000,
0x8b000000,
0x8b800000,
0x8c000000,
0x8c800000,
0x8d000000,
0x8d800000,
0x8e000000,
0x8e800000,
0x8f000000,
0xc7800000,
};
const static unsigned g_offset[64] = {
0x00000000,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000000,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
0x00000400,
};
float float16ToFloat32(unsigned short h)
{
unsigned i32 = g_mantissa[g_offset[h >> 10] + (h & 0x3ff)] + g_exponent[h >> 10];
return *(float*) &i32;
}
}
| 010smithzhang-ddd | src/libGLESv2/Float16ToFloat32.cpp | C++ | bsd | 35,376 |
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Program.cpp: Implements the gl::Program class. Implements GL program objects
// and related functionality. [OpenGL ES 2.0.24] section 2.10.3 page 28.
#include "libGLESv2/BinaryStream.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/renderer/ShaderExecutable.h"
#include "common/debug.h"
#include "common/version.h"
#include "utilities.h"
#include "libGLESv2/main.h"
#include "libGLESv2/Shader.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/renderer/VertexDataManager.h"
#undef near
#undef far
namespace gl
{
std::string str(int i)
{
char buffer[20];
snprintf(buffer, sizeof(buffer), "%d", i);
return buffer;
}
UniformLocation::UniformLocation(const std::string &name, unsigned int element, unsigned int index)
: name(name), element(element), index(index)
{
}
unsigned int ProgramBinary::mCurrentSerial = 1;
ProgramBinary::ProgramBinary(rx::Renderer *renderer) : mRenderer(renderer), RefCountObject(0), mSerial(issueSerial())
{
mPixelExecutable = NULL;
mVertexExecutable = NULL;
mGeometryExecutable = NULL;
mValidated = false;
for (int index = 0; index < MAX_VERTEX_ATTRIBS; index++)
{
mSemanticIndex[index] = -1;
}
for (int index = 0; index < MAX_TEXTURE_IMAGE_UNITS; index++)
{
mSamplersPS[index].active = false;
}
for (int index = 0; index < IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS; index++)
{
mSamplersVS[index].active = false;
}
mUsedVertexSamplerRange = 0;
mUsedPixelSamplerRange = 0;
mUsesPointSize = false;
}
ProgramBinary::~ProgramBinary()
{
delete mPixelExecutable;
mPixelExecutable = NULL;
delete mVertexExecutable;
mVertexExecutable = NULL;
delete mGeometryExecutable;
mGeometryExecutable = NULL;
while (!mUniforms.empty())
{
delete mUniforms.back();
mUniforms.pop_back();
}
}
unsigned int ProgramBinary::getSerial() const
{
return mSerial;
}
unsigned int ProgramBinary::issueSerial()
{
return mCurrentSerial++;
}
rx::ShaderExecutable *ProgramBinary::getPixelExecutable()
{
return mPixelExecutable;
}
rx::ShaderExecutable *ProgramBinary::getVertexExecutable()
{
return mVertexExecutable;
}
rx::ShaderExecutable *ProgramBinary::getGeometryExecutable()
{
return mGeometryExecutable;
}
GLuint ProgramBinary::getAttributeLocation(const char *name)
{
if (name)
{
for (int index = 0; index < MAX_VERTEX_ATTRIBS; index++)
{
if (mLinkedAttribute[index].name == std::string(name))
{
return index;
}
}
}
return -1;
}
int ProgramBinary::getSemanticIndex(int attributeIndex)
{
ASSERT(attributeIndex >= 0 && attributeIndex < MAX_VERTEX_ATTRIBS);
return mSemanticIndex[attributeIndex];
}
// Returns one more than the highest sampler index used.
GLint ProgramBinary::getUsedSamplerRange(SamplerType type)
{
switch (type)
{
case SAMPLER_PIXEL:
return mUsedPixelSamplerRange;
case SAMPLER_VERTEX:
return mUsedVertexSamplerRange;
default:
UNREACHABLE();
return 0;
}
}
bool ProgramBinary::usesPointSize() const
{
return mUsesPointSize;
}
bool ProgramBinary::usesPointSpriteEmulation() const
{
return mUsesPointSize && mRenderer->getMajorShaderModel() >= 4;
}
bool ProgramBinary::usesGeometryShader() const
{
return usesPointSpriteEmulation();
}
// Returns the index of the texture image unit (0-19) corresponding to a Direct3D 9 sampler
// index (0-15 for the pixel shader and 0-3 for the vertex shader).
GLint ProgramBinary::getSamplerMapping(SamplerType type, unsigned int samplerIndex)
{
GLint logicalTextureUnit = -1;
switch (type)
{
case SAMPLER_PIXEL:
ASSERT(samplerIndex < sizeof(mSamplersPS)/sizeof(mSamplersPS[0]));
if (mSamplersPS[samplerIndex].active)
{
logicalTextureUnit = mSamplersPS[samplerIndex].logicalTextureUnit;
}
break;
case SAMPLER_VERTEX:
ASSERT(samplerIndex < sizeof(mSamplersVS)/sizeof(mSamplersVS[0]));
if (mSamplersVS[samplerIndex].active)
{
logicalTextureUnit = mSamplersVS[samplerIndex].logicalTextureUnit;
}
break;
default: UNREACHABLE();
}
if (logicalTextureUnit >= 0 && logicalTextureUnit < (GLint)mRenderer->getMaxCombinedTextureImageUnits())
{
return logicalTextureUnit;
}
return -1;
}
// Returns the texture type for a given Direct3D 9 sampler type and
// index (0-15 for the pixel shader and 0-3 for the vertex shader).
TextureType ProgramBinary::getSamplerTextureType(SamplerType type, unsigned int samplerIndex)
{
switch (type)
{
case SAMPLER_PIXEL:
ASSERT(samplerIndex < sizeof(mSamplersPS)/sizeof(mSamplersPS[0]));
ASSERT(mSamplersPS[samplerIndex].active);
return mSamplersPS[samplerIndex].textureType;
case SAMPLER_VERTEX:
ASSERT(samplerIndex < sizeof(mSamplersVS)/sizeof(mSamplersVS[0]));
ASSERT(mSamplersVS[samplerIndex].active);
return mSamplersVS[samplerIndex].textureType;
default: UNREACHABLE();
}
return TEXTURE_2D;
}
GLint ProgramBinary::getUniformLocation(std::string name)
{
unsigned int subscript = 0;
// Strip any trailing array operator and retrieve the subscript
size_t open = name.find_last_of('[');
size_t close = name.find_last_of(']');
if (open != std::string::npos && close == name.length() - 1)
{
subscript = atoi(name.substr(open + 1).c_str());
name.erase(open);
}
unsigned int numUniforms = mUniformIndex.size();
for (unsigned int location = 0; location < numUniforms; location++)
{
if (mUniformIndex[location].name == name &&
mUniformIndex[location].element == subscript)
{
return location;
}
}
return -1;
}
bool ProgramBinary::setUniform1fv(GLint location, GLsizei count, const GLfloat* v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_FLOAT)
{
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = 0;
target[2] = 0;
target[3] = 0;
target += 4;
v += 1;
}
}
else if (targetUniform->type == GL_BOOL)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[1] = GL_FALSE;
boolParams[2] = GL_FALSE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 1;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform2fv(GLint location, GLsizei count, const GLfloat *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_FLOAT_VEC2)
{
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = 0;
target[3] = 0;
target += 4;
v += 2;
}
}
else if (targetUniform->type == GL_BOOL_VEC2)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[2] = GL_FALSE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 2;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform3fv(GLint location, GLsizei count, const GLfloat *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_FLOAT_VEC3)
{
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = v[2];
target[3] = 0;
target += 4;
v += 3;
}
}
else if (targetUniform->type == GL_BOOL_VEC3)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[2] = (v[2] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 3;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform4fv(GLint location, GLsizei count, const GLfloat *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_FLOAT_VEC4)
{
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = v[2];
target[3] = v[3];
target += 4;
v += 4;
}
}
else if (targetUniform->type == GL_BOOL_VEC4)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[2] = (v[2] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams[3] = (v[3] == 0.0f) ? GL_FALSE : GL_TRUE;
boolParams += 4;
v += 4;
}
}
else
{
return false;
}
return true;
}
template<typename T, int targetWidth, int targetHeight, int srcWidth, int srcHeight>
void transposeMatrix(T *target, const GLfloat *value)
{
int copyWidth = std::min(targetWidth, srcWidth);
int copyHeight = std::min(targetHeight, srcHeight);
for (int x = 0; x < copyWidth; x++)
{
for (int y = 0; y < copyHeight; y++)
{
target[x * targetWidth + y] = (T)value[y * srcWidth + x];
}
}
// clear unfilled right side
for (int y = 0; y < copyHeight; y++)
{
for (int x = srcWidth; x < targetWidth; x++)
{
target[y * targetWidth + x] = (T)0;
}
}
// clear unfilled bottom.
for (int y = srcHeight; y < targetHeight; y++)
{
for (int x = 0; x < targetWidth; x++)
{
target[y * targetWidth + x] = (T)0;
}
}
}
bool ProgramBinary::setUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
if (targetUniform->type != GL_FLOAT_MAT2)
{
return false;
}
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 8;
for (int i = 0; i < count; i++)
{
transposeMatrix<GLfloat,4,2,2,2>(target, value);
target += 8;
value += 4;
}
return true;
}
bool ProgramBinary::setUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
if (targetUniform->type != GL_FLOAT_MAT3)
{
return false;
}
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
GLfloat *target = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 12;
for (int i = 0; i < count; i++)
{
transposeMatrix<GLfloat,4,3,3,3>(target, value);
target += 12;
value += 9;
}
return true;
}
bool ProgramBinary::setUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
if (targetUniform->type != GL_FLOAT_MAT4)
{
return false;
}
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
GLfloat *target = (GLfloat*)(targetUniform->data + mUniformIndex[location].element * sizeof(GLfloat) * 16);
for (int i = 0; i < count; i++)
{
transposeMatrix<GLfloat,4,4,4,4>(target, value);
target += 16;
value += 16;
}
return true;
}
bool ProgramBinary::setUniform1iv(GLint location, GLsizei count, const GLint *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_INT ||
targetUniform->type == GL_SAMPLER_2D ||
targetUniform->type == GL_SAMPLER_CUBE)
{
GLint *target = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = 0;
target[2] = 0;
target[3] = 0;
target += 4;
v += 1;
}
}
else if (targetUniform->type == GL_BOOL)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0) ? GL_FALSE : GL_TRUE;
boolParams[1] = GL_FALSE;
boolParams[2] = GL_FALSE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 1;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform2iv(GLint location, GLsizei count, const GLint *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_INT_VEC2)
{
GLint *target = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = 0;
target[3] = 0;
target += 4;
v += 2;
}
}
else if (targetUniform->type == GL_BOOL_VEC2)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0) ? GL_FALSE : GL_TRUE;
boolParams[2] = GL_FALSE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 2;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform3iv(GLint location, GLsizei count, const GLint *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_INT_VEC3)
{
GLint *target = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = v[2];
target[3] = 0;
target += 4;
v += 3;
}
}
else if (targetUniform->type == GL_BOOL_VEC3)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0) ? GL_FALSE : GL_TRUE;
boolParams[2] = (v[2] == 0) ? GL_FALSE : GL_TRUE;
boolParams[3] = GL_FALSE;
boolParams += 4;
v += 3;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::setUniform4iv(GLint location, GLsizei count, const GLint *v)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
targetUniform->dirty = true;
int elementCount = targetUniform->elementCount();
if (elementCount == 1 && count > 1)
return false; // attempting to write an array to a non-array uniform is an INVALID_OPERATION
count = std::min(elementCount - (int)mUniformIndex[location].element, count);
if (targetUniform->type == GL_INT_VEC4)
{
GLint *target = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
target[0] = v[0];
target[1] = v[1];
target[2] = v[2];
target[3] = v[3];
target += 4;
v += 4;
}
}
else if (targetUniform->type == GL_BOOL_VEC4)
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (int i = 0; i < count; i++)
{
boolParams[0] = (v[0] == 0) ? GL_FALSE : GL_TRUE;
boolParams[1] = (v[1] == 0) ? GL_FALSE : GL_TRUE;
boolParams[2] = (v[2] == 0) ? GL_FALSE : GL_TRUE;
boolParams[3] = (v[3] == 0) ? GL_FALSE : GL_TRUE;
boolParams += 4;
v += 4;
}
}
else
{
return false;
}
return true;
}
bool ProgramBinary::getUniformfv(GLint location, GLsizei *bufSize, GLfloat *params)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
// sized queries -- ensure the provided buffer is large enough
if (bufSize)
{
int requiredBytes = UniformExternalSize(targetUniform->type);
if (*bufSize < requiredBytes)
{
return false;
}
}
switch (targetUniform->type)
{
case GL_FLOAT_MAT2:
transposeMatrix<GLfloat,2,2,4,2>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 8);
break;
case GL_FLOAT_MAT3:
transposeMatrix<GLfloat,3,3,4,3>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 12);
break;
case GL_FLOAT_MAT4:
transposeMatrix<GLfloat,4,4,4,4>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 16);
break;
default:
{
unsigned int size = UniformComponentCount(targetUniform->type);
switch (UniformComponentType(targetUniform->type))
{
case GL_BOOL:
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (unsigned int i = 0; i < size; i++)
{
params[i] = (boolParams[i] == GL_FALSE) ? 0.0f : 1.0f;
}
}
break;
case GL_FLOAT:
memcpy(params, targetUniform->data + mUniformIndex[location].element * 4 * sizeof(GLfloat),
size * sizeof(GLfloat));
break;
case GL_INT:
{
GLint *intParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (unsigned int i = 0; i < size; i++)
{
params[i] = (float)intParams[i];
}
}
break;
default: UNREACHABLE();
}
}
}
return true;
}
bool ProgramBinary::getUniformiv(GLint location, GLsizei *bufSize, GLint *params)
{
if (location < 0 || location >= (int)mUniformIndex.size())
{
return false;
}
Uniform *targetUniform = mUniforms[mUniformIndex[location].index];
// sized queries -- ensure the provided buffer is large enough
if (bufSize)
{
int requiredBytes = UniformExternalSize(targetUniform->type);
if (*bufSize < requiredBytes)
{
return false;
}
}
switch (targetUniform->type)
{
case GL_FLOAT_MAT2:
transposeMatrix<GLint,2,2,4,2>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 8);
break;
case GL_FLOAT_MAT3:
transposeMatrix<GLint,3,3,4,3>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 12);
break;
case GL_FLOAT_MAT4:
transposeMatrix<GLint,4,4,4,4>(params, (GLfloat*)targetUniform->data + mUniformIndex[location].element * 16);
break;
default:
{
unsigned int size = VariableColumnCount(targetUniform->type);
switch (UniformComponentType(targetUniform->type))
{
case GL_BOOL:
{
GLint *boolParams = (GLint*)targetUniform->data + mUniformIndex[location].element * 4;
for (unsigned int i = 0; i < size; i++)
{
params[i] = boolParams[i];
}
}
break;
case GL_FLOAT:
{
GLfloat *floatParams = (GLfloat*)targetUniform->data + mUniformIndex[location].element * 4;
for (unsigned int i = 0; i < size; i++)
{
params[i] = (GLint)floatParams[i];
}
}
break;
case GL_INT:
memcpy(params, targetUniform->data + mUniformIndex[location].element * 4 * sizeof(GLint),
size * sizeof(GLint));
break;
default: UNREACHABLE();
}
}
}
return true;
}
void ProgramBinary::dirtyAllUniforms()
{
unsigned int numUniforms = mUniforms.size();
for (unsigned int index = 0; index < numUniforms; index++)
{
mUniforms[index]->dirty = true;
}
}
// Applies all the uniforms set for this program object to the renderer
void ProgramBinary::applyUniforms()
{
// Retrieve sampler uniform values
for (std::vector<Uniform*>::iterator ub = mUniforms.begin(), ue = mUniforms.end(); ub != ue; ++ub)
{
Uniform *targetUniform = *ub;
if (targetUniform->dirty)
{
if (targetUniform->type == GL_SAMPLER_2D ||
targetUniform->type == GL_SAMPLER_CUBE)
{
int count = targetUniform->elementCount();
GLint (*v)[4] = (GLint(*)[4])targetUniform->data;
if (targetUniform->psRegisterIndex >= 0)
{
unsigned int firstIndex = targetUniform->psRegisterIndex;
for (int i = 0; i < count; i++)
{
unsigned int samplerIndex = firstIndex + i;
if (samplerIndex < MAX_TEXTURE_IMAGE_UNITS)
{
ASSERT(mSamplersPS[samplerIndex].active);
mSamplersPS[samplerIndex].logicalTextureUnit = v[i][0];
}
}
}
if (targetUniform->vsRegisterIndex >= 0)
{
unsigned int firstIndex = targetUniform->vsRegisterIndex;
for (int i = 0; i < count; i++)
{
unsigned int samplerIndex = firstIndex + i;
if (samplerIndex < IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS)
{
ASSERT(mSamplersVS[samplerIndex].active);
mSamplersVS[samplerIndex].logicalTextureUnit = v[i][0];
}
}
}
}
}
}
mRenderer->applyUniforms(this, &mUniforms);
}
// Packs varyings into generic varying registers, using the algorithm from [OpenGL ES Shading Language 1.00 rev. 17] appendix A section 7 page 111
// Returns the number of used varying registers, or -1 if unsuccesful
int ProgramBinary::packVaryings(InfoLog &infoLog, const Varying *packing[][4], FragmentShader *fragmentShader)
{
const int maxVaryingVectors = mRenderer->getMaxVaryingVectors();
fragmentShader->resetVaryingsRegisterAssignment();
for (VaryingList::iterator varying = fragmentShader->mVaryings.begin(); varying != fragmentShader->mVaryings.end(); varying++)
{
int n = VariableRowCount(varying->type) * varying->size;
int m = VariableColumnCount(varying->type);
bool success = false;
if (m == 2 || m == 3 || m == 4)
{
for (int r = 0; r <= maxVaryingVectors - n && !success; r++)
{
bool available = true;
for (int y = 0; y < n && available; y++)
{
for (int x = 0; x < m && available; x++)
{
if (packing[r + y][x])
{
available = false;
}
}
}
if (available)
{
varying->reg = r;
varying->col = 0;
for (int y = 0; y < n; y++)
{
for (int x = 0; x < m; x++)
{
packing[r + y][x] = &*varying;
}
}
success = true;
}
}
if (!success && m == 2)
{
for (int r = maxVaryingVectors - n; r >= 0 && !success; r--)
{
bool available = true;
for (int y = 0; y < n && available; y++)
{
for (int x = 2; x < 4 && available; x++)
{
if (packing[r + y][x])
{
available = false;
}
}
}
if (available)
{
varying->reg = r;
varying->col = 2;
for (int y = 0; y < n; y++)
{
for (int x = 2; x < 4; x++)
{
packing[r + y][x] = &*varying;
}
}
success = true;
}
}
}
}
else if (m == 1)
{
int space[4] = {0};
for (int y = 0; y < maxVaryingVectors; y++)
{
for (int x = 0; x < 4; x++)
{
space[x] += packing[y][x] ? 0 : 1;
}
}
int column = 0;
for (int x = 0; x < 4; x++)
{
if (space[x] >= n && space[x] < space[column])
{
column = x;
}
}
if (space[column] >= n)
{
for (int r = 0; r < maxVaryingVectors; r++)
{
if (!packing[r][column])
{
varying->reg = r;
for (int y = r; y < r + n; y++)
{
packing[y][column] = &*varying;
}
break;
}
}
varying->col = column;
success = true;
}
}
else UNREACHABLE();
if (!success)
{
infoLog.append("Could not pack varying %s", varying->name.c_str());
return -1;
}
}
// Return the number of used registers
int registers = 0;
for (int r = 0; r < maxVaryingVectors; r++)
{
if (packing[r][0] || packing[r][1] || packing[r][2] || packing[r][3])
{
registers++;
}
}
return registers;
}
bool ProgramBinary::linkVaryings(InfoLog &infoLog, int registers, const Varying *packing[][4],
std::string& pixelHLSL, std::string& vertexHLSL,
FragmentShader *fragmentShader, VertexShader *vertexShader)
{
if (pixelHLSL.empty() || vertexHLSL.empty())
{
return false;
}
bool usesMRT = fragmentShader->mUsesMultipleRenderTargets;
bool usesFragColor = fragmentShader->mUsesFragColor;
bool usesFragData = fragmentShader->mUsesFragData;
if (usesFragColor && usesFragData)
{
infoLog.append("Cannot use both gl_FragColor and gl_FragData in the same fragment shader.");
return false;
}
// Write the HLSL input/output declarations
const int shaderModel = mRenderer->getMajorShaderModel();
const int maxVaryingVectors = mRenderer->getMaxVaryingVectors();
const int registersNeeded = registers + (fragmentShader->mUsesFragCoord ? 1 : 0) + (fragmentShader->mUsesPointCoord ? 1 : 0);
// The output color is broadcast to all enabled draw buffers when writing to gl_FragColor
const bool broadcast = fragmentShader->mUsesFragColor;
const unsigned int numRenderTargets = (broadcast || usesMRT ? mRenderer->getMaxRenderTargets() : 1);
if (registersNeeded > maxVaryingVectors)
{
infoLog.append("No varying registers left to support gl_FragCoord/gl_PointCoord");
return false;
}
vertexShader->resetVaryingsRegisterAssignment();
for (VaryingList::iterator input = fragmentShader->mVaryings.begin(); input != fragmentShader->mVaryings.end(); input++)
{
bool matched = false;
for (VaryingList::iterator output = vertexShader->mVaryings.begin(); output != vertexShader->mVaryings.end(); output++)
{
if (output->name == input->name)
{
if (output->type != input->type || output->size != input->size)
{
infoLog.append("Type of vertex varying %s does not match that of the fragment varying", output->name.c_str());
return false;
}
output->reg = input->reg;
output->col = input->col;
matched = true;
break;
}
}
if (!matched)
{
infoLog.append("Fragment varying %s does not match any vertex varying", input->name.c_str());
return false;
}
}
mUsesPointSize = vertexShader->mUsesPointSize;
std::string varyingSemantic = (mUsesPointSize && shaderModel == 3) ? "COLOR" : "TEXCOORD";
std::string targetSemantic = (shaderModel >= 4) ? "SV_Target" : "COLOR";
std::string positionSemantic = (shaderModel >= 4) ? "SV_Position" : "POSITION";
std::string depthSemantic = (shaderModel >= 4) ? "SV_Depth" : "DEPTH";
// special varyings that use reserved registers
int reservedRegisterIndex = registers;
std::string fragCoordSemantic;
std::string pointCoordSemantic;
if (fragmentShader->mUsesFragCoord)
{
fragCoordSemantic = varyingSemantic + str(reservedRegisterIndex++);
}
if (fragmentShader->mUsesPointCoord)
{
// Shader model 3 uses a special TEXCOORD semantic for point sprite texcoords.
// In DX11 we compute this in the GS.
if (shaderModel == 3)
{
pointCoordSemantic = "TEXCOORD0";
}
else if (shaderModel >= 4)
{
pointCoordSemantic = varyingSemantic + str(reservedRegisterIndex++);
}
}
vertexHLSL += "struct VS_INPUT\n"
"{\n";
int semanticIndex = 0;
for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++)
{
switch (attribute->type)
{
case GL_FLOAT: vertexHLSL += " float "; break;
case GL_FLOAT_VEC2: vertexHLSL += " float2 "; break;
case GL_FLOAT_VEC3: vertexHLSL += " float3 "; break;
case GL_FLOAT_VEC4: vertexHLSL += " float4 "; break;
case GL_FLOAT_MAT2: vertexHLSL += " float2x2 "; break;
case GL_FLOAT_MAT3: vertexHLSL += " float3x3 "; break;
case GL_FLOAT_MAT4: vertexHLSL += " float4x4 "; break;
default: UNREACHABLE();
}
vertexHLSL += decorateAttribute(attribute->name) + " : TEXCOORD" + str(semanticIndex) + ";\n";
semanticIndex += VariableRowCount(attribute->type);
}
vertexHLSL += "};\n"
"\n"
"struct VS_OUTPUT\n"
"{\n";
if (shaderModel < 4)
{
vertexHLSL += " float4 gl_Position : " + positionSemantic + ";\n";
}
for (int r = 0; r < registers; r++)
{
int registerSize = packing[r][3] ? 4 : (packing[r][2] ? 3 : (packing[r][1] ? 2 : 1));
vertexHLSL += " float" + str(registerSize) + " v" + str(r) + " : " + varyingSemantic + str(r) + ";\n";
}
if (fragmentShader->mUsesFragCoord)
{
vertexHLSL += " float4 gl_FragCoord : " + fragCoordSemantic + ";\n";
}
if (vertexShader->mUsesPointSize && shaderModel >= 3)
{
vertexHLSL += " float gl_PointSize : PSIZE;\n";
}
if (shaderModel >= 4)
{
vertexHLSL += " float4 gl_Position : " + positionSemantic + ";\n";
}
vertexHLSL += "};\n"
"\n"
"VS_OUTPUT main(VS_INPUT input)\n"
"{\n";
for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++)
{
vertexHLSL += " " + decorateAttribute(attribute->name) + " = ";
if (VariableRowCount(attribute->type) > 1) // Matrix
{
vertexHLSL += "transpose";
}
vertexHLSL += "(input." + decorateAttribute(attribute->name) + ");\n";
}
if (shaderModel >= 4)
{
vertexHLSL += "\n"
" gl_main();\n"
"\n"
" VS_OUTPUT output;\n"
" output.gl_Position.x = gl_Position.x;\n"
" output.gl_Position.y = -gl_Position.y;\n"
" output.gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n"
" output.gl_Position.w = gl_Position.w;\n";
}
else
{
vertexHLSL += "\n"
" gl_main();\n"
"\n"
" VS_OUTPUT output;\n"
" output.gl_Position.x = gl_Position.x * dx_ViewAdjust.z + dx_ViewAdjust.x * gl_Position.w;\n"
" output.gl_Position.y = -(gl_Position.y * dx_ViewAdjust.w + dx_ViewAdjust.y * gl_Position.w);\n"
" output.gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n"
" output.gl_Position.w = gl_Position.w;\n";
}
if (vertexShader->mUsesPointSize && shaderModel >= 3)
{
vertexHLSL += " output.gl_PointSize = gl_PointSize;\n";
}
if (fragmentShader->mUsesFragCoord)
{
vertexHLSL += " output.gl_FragCoord = gl_Position;\n";
}
for (VaryingList::iterator varying = vertexShader->mVaryings.begin(); varying != vertexShader->mVaryings.end(); varying++)
{
if (varying->reg >= 0)
{
for (int i = 0; i < varying->size; i++)
{
int rows = VariableRowCount(varying->type);
for (int j = 0; j < rows; j++)
{
int r = varying->reg + i * rows + j;
vertexHLSL += " output.v" + str(r);
bool sharedRegister = false; // Register used by multiple varyings
for (int x = 0; x < 4; x++)
{
if (packing[r][x] && packing[r][x] != packing[r][0])
{
sharedRegister = true;
break;
}
}
if(sharedRegister)
{
vertexHLSL += ".";
for (int x = 0; x < 4; x++)
{
if (packing[r][x] == &*varying)
{
switch(x)
{
case 0: vertexHLSL += "x"; break;
case 1: vertexHLSL += "y"; break;
case 2: vertexHLSL += "z"; break;
case 3: vertexHLSL += "w"; break;
}
}
}
}
vertexHLSL += " = " + varying->name;
if (varying->array)
{
vertexHLSL += "[" + str(i) + "]";
}
if (rows > 1)
{
vertexHLSL += "[" + str(j) + "]";
}
vertexHLSL += ";\n";
}
}
}
}
vertexHLSL += "\n"
" return output;\n"
"}\n";
pixelHLSL += "struct PS_INPUT\n"
"{\n";
for (VaryingList::iterator varying = fragmentShader->mVaryings.begin(); varying != fragmentShader->mVaryings.end(); varying++)
{
if (varying->reg >= 0)
{
for (int i = 0; i < varying->size; i++)
{
int rows = VariableRowCount(varying->type);
for (int j = 0; j < rows; j++)
{
std::string n = str(varying->reg + i * rows + j);
pixelHLSL += " float" + str(VariableColumnCount(varying->type)) + " v" + n + " : " + varyingSemantic + n + ";\n";
}
}
}
else UNREACHABLE();
}
if (fragmentShader->mUsesFragCoord)
{
pixelHLSL += " float4 gl_FragCoord : " + fragCoordSemantic + ";\n";
}
if (fragmentShader->mUsesPointCoord && shaderModel >= 3)
{
pixelHLSL += " float2 gl_PointCoord : " + pointCoordSemantic + ";\n";
}
// Must consume the PSIZE element if the geometry shader is not active
// We won't know if we use a GS until we draw
if (vertexShader->mUsesPointSize && shaderModel >= 4)
{
pixelHLSL += " float gl_PointSize : PSIZE;\n";
}
if (fragmentShader->mUsesFragCoord)
{
if (shaderModel >= 4)
{
pixelHLSL += " float4 dx_VPos : SV_Position;\n";
}
else if (shaderModel >= 3)
{
pixelHLSL += " float2 dx_VPos : VPOS;\n";
}
}
pixelHLSL += "};\n"
"\n"
"struct PS_OUTPUT\n"
"{\n";
for (unsigned int renderTargetIndex = 0; renderTargetIndex < numRenderTargets; renderTargetIndex++)
{
pixelHLSL += " float4 gl_Color" + str(renderTargetIndex) + " : " + targetSemantic + str(renderTargetIndex) + ";\n";
}
if (fragmentShader->mUsesFragDepth)
{
pixelHLSL += " float gl_Depth : " + depthSemantic + ";\n";
}
pixelHLSL += "};\n"
"\n";
if (fragmentShader->mUsesFrontFacing)
{
if (shaderModel >= 4)
{
pixelHLSL += "PS_OUTPUT main(PS_INPUT input, bool isFrontFace : SV_IsFrontFace)\n"
"{\n";
}
else
{
pixelHLSL += "PS_OUTPUT main(PS_INPUT input, float vFace : VFACE)\n"
"{\n";
}
}
else
{
pixelHLSL += "PS_OUTPUT main(PS_INPUT input)\n"
"{\n";
}
if (fragmentShader->mUsesFragCoord)
{
pixelHLSL += " float rhw = 1.0 / input.gl_FragCoord.w;\n";
if (shaderModel >= 4)
{
pixelHLSL += " gl_FragCoord.x = input.dx_VPos.x;\n"
" gl_FragCoord.y = input.dx_VPos.y;\n";
}
else if (shaderModel >= 3)
{
pixelHLSL += " gl_FragCoord.x = input.dx_VPos.x + 0.5;\n"
" gl_FragCoord.y = input.dx_VPos.y + 0.5;\n";
}
else
{
// dx_ViewCoords contains the viewport width/2, height/2, center.x and center.y. See Renderer::setViewport()
pixelHLSL += " gl_FragCoord.x = (input.gl_FragCoord.x * rhw) * dx_ViewCoords.x + dx_ViewCoords.z;\n"
" gl_FragCoord.y = (input.gl_FragCoord.y * rhw) * dx_ViewCoords.y + dx_ViewCoords.w;\n";
}
pixelHLSL += " gl_FragCoord.z = (input.gl_FragCoord.z * rhw) * dx_DepthFront.x + dx_DepthFront.y;\n"
" gl_FragCoord.w = rhw;\n";
}
if (fragmentShader->mUsesPointCoord && shaderModel >= 3)
{
pixelHLSL += " gl_PointCoord.x = input.gl_PointCoord.x;\n";
pixelHLSL += " gl_PointCoord.y = 1.0 - input.gl_PointCoord.y;\n";
}
if (fragmentShader->mUsesFrontFacing)
{
if (shaderModel <= 3)
{
pixelHLSL += " gl_FrontFacing = (vFace * dx_DepthFront.z >= 0.0);\n";
}
else
{
pixelHLSL += " gl_FrontFacing = isFrontFace;\n";
}
}
for (VaryingList::iterator varying = fragmentShader->mVaryings.begin(); varying != fragmentShader->mVaryings.end(); varying++)
{
if (varying->reg >= 0)
{
for (int i = 0; i < varying->size; i++)
{
int rows = VariableRowCount(varying->type);
for (int j = 0; j < rows; j++)
{
std::string n = str(varying->reg + i * rows + j);
pixelHLSL += " " + varying->name;
if (varying->array)
{
pixelHLSL += "[" + str(i) + "]";
}
if (rows > 1)
{
pixelHLSL += "[" + str(j) + "]";
}
switch (VariableColumnCount(varying->type))
{
case 1: pixelHLSL += " = input.v" + n + ".x;\n"; break;
case 2: pixelHLSL += " = input.v" + n + ".xy;\n"; break;
case 3: pixelHLSL += " = input.v" + n + ".xyz;\n"; break;
case 4: pixelHLSL += " = input.v" + n + ";\n"; break;
default: UNREACHABLE();
}
}
}
}
else UNREACHABLE();
}
pixelHLSL += "\n"
" gl_main();\n"
"\n"
" PS_OUTPUT output;\n";
for (unsigned int renderTargetIndex = 0; renderTargetIndex < numRenderTargets; renderTargetIndex++)
{
unsigned int sourceColorIndex = broadcast ? 0 : renderTargetIndex;
pixelHLSL += " output.gl_Color" + str(renderTargetIndex) + " = gl_Color[" + str(sourceColorIndex) + "];\n";
}
if (fragmentShader->mUsesFragDepth)
{
pixelHLSL += " output.gl_Depth = gl_Depth;\n";
}
pixelHLSL += "\n"
" return output;\n"
"}\n";
return true;
}
bool ProgramBinary::load(InfoLog &infoLog, const void *binary, GLsizei length)
{
BinaryInputStream stream(binary, length);
int format = 0;
stream.read(&format);
if (format != GL_PROGRAM_BINARY_ANGLE)
{
infoLog.append("Invalid program binary format.");
return false;
}
int version = 0;
stream.read(&version);
if (version != VERSION_DWORD)
{
infoLog.append("Invalid program binary version.");
return false;
}
int compileFlags = 0;
stream.read(&compileFlags);
if (compileFlags != ANGLE_COMPILE_OPTIMIZATION_LEVEL)
{
infoLog.append("Mismatched compilation flags.");
return false;
}
for (int i = 0; i < MAX_VERTEX_ATTRIBS; ++i)
{
stream.read(&mLinkedAttribute[i].type);
std::string name;
stream.read(&name);
mLinkedAttribute[i].name = name;
stream.read(&mSemanticIndex[i]);
}
for (unsigned int i = 0; i < MAX_TEXTURE_IMAGE_UNITS; ++i)
{
stream.read(&mSamplersPS[i].active);
stream.read(&mSamplersPS[i].logicalTextureUnit);
int textureType;
stream.read(&textureType);
mSamplersPS[i].textureType = (TextureType) textureType;
}
for (unsigned int i = 0; i < IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS; ++i)
{
stream.read(&mSamplersVS[i].active);
stream.read(&mSamplersVS[i].logicalTextureUnit);
int textureType;
stream.read(&textureType);
mSamplersVS[i].textureType = (TextureType) textureType;
}
stream.read(&mUsedVertexSamplerRange);
stream.read(&mUsedPixelSamplerRange);
stream.read(&mUsesPointSize);
size_t size;
stream.read(&size);
if (stream.error())
{
infoLog.append("Invalid program binary.");
return false;
}
mUniforms.resize(size);
for (unsigned int i = 0; i < size; ++i)
{
GLenum type;
GLenum precision;
std::string name;
unsigned int arraySize;
stream.read(&type);
stream.read(&precision);
stream.read(&name);
stream.read(&arraySize);
mUniforms[i] = new Uniform(type, precision, name, arraySize);
stream.read(&mUniforms[i]->psRegisterIndex);
stream.read(&mUniforms[i]->vsRegisterIndex);
stream.read(&mUniforms[i]->registerCount);
}
stream.read(&size);
if (stream.error())
{
infoLog.append("Invalid program binary.");
return false;
}
mUniformIndex.resize(size);
for (unsigned int i = 0; i < size; ++i)
{
stream.read(&mUniformIndex[i].name);
stream.read(&mUniformIndex[i].element);
stream.read(&mUniformIndex[i].index);
}
unsigned int pixelShaderSize;
stream.read(&pixelShaderSize);
unsigned int vertexShaderSize;
stream.read(&vertexShaderSize);
unsigned int geometryShaderSize;
stream.read(&geometryShaderSize);
const char *ptr = (const char*) binary + stream.offset();
const GUID *binaryIdentifier = (const GUID *) ptr;
ptr += sizeof(GUID);
GUID identifier = mRenderer->getAdapterIdentifier();
if (memcmp(&identifier, binaryIdentifier, sizeof(GUID)) != 0)
{
infoLog.append("Invalid program binary.");
return false;
}
const char *pixelShaderFunction = ptr;
ptr += pixelShaderSize;
const char *vertexShaderFunction = ptr;
ptr += vertexShaderSize;
const char *geometryShaderFunction = geometryShaderSize > 0 ? ptr : NULL;
ptr += geometryShaderSize;
mPixelExecutable = mRenderer->loadExecutable(reinterpret_cast<const DWORD*>(pixelShaderFunction),
pixelShaderSize, rx::SHADER_PIXEL);
if (!mPixelExecutable)
{
infoLog.append("Could not create pixel shader.");
return false;
}
mVertexExecutable = mRenderer->loadExecutable(reinterpret_cast<const DWORD*>(vertexShaderFunction),
vertexShaderSize, rx::SHADER_VERTEX);
if (!mVertexExecutable)
{
infoLog.append("Could not create vertex shader.");
delete mPixelExecutable;
mPixelExecutable = NULL;
return false;
}
if (geometryShaderFunction != NULL && geometryShaderSize > 0)
{
mGeometryExecutable = mRenderer->loadExecutable(reinterpret_cast<const DWORD*>(geometryShaderFunction),
geometryShaderSize, rx::SHADER_GEOMETRY);
if (!mGeometryExecutable)
{
infoLog.append("Could not create geometry shader.");
delete mPixelExecutable;
mPixelExecutable = NULL;
delete mVertexExecutable;
mVertexExecutable = NULL;
return false;
}
}
else
{
mGeometryExecutable = NULL;
}
return true;
}
bool ProgramBinary::save(void* binary, GLsizei bufSize, GLsizei *length)
{
BinaryOutputStream stream;
stream.write(GL_PROGRAM_BINARY_ANGLE);
stream.write(VERSION_DWORD);
stream.write(ANGLE_COMPILE_OPTIMIZATION_LEVEL);
for (unsigned int i = 0; i < MAX_VERTEX_ATTRIBS; ++i)
{
stream.write(mLinkedAttribute[i].type);
stream.write(mLinkedAttribute[i].name);
stream.write(mSemanticIndex[i]);
}
for (unsigned int i = 0; i < MAX_TEXTURE_IMAGE_UNITS; ++i)
{
stream.write(mSamplersPS[i].active);
stream.write(mSamplersPS[i].logicalTextureUnit);
stream.write((int) mSamplersPS[i].textureType);
}
for (unsigned int i = 0; i < IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS; ++i)
{
stream.write(mSamplersVS[i].active);
stream.write(mSamplersVS[i].logicalTextureUnit);
stream.write((int) mSamplersVS[i].textureType);
}
stream.write(mUsedVertexSamplerRange);
stream.write(mUsedPixelSamplerRange);
stream.write(mUsesPointSize);
stream.write(mUniforms.size());
for (unsigned int i = 0; i < mUniforms.size(); ++i)
{
stream.write(mUniforms[i]->type);
stream.write(mUniforms[i]->precision);
stream.write(mUniforms[i]->name);
stream.write(mUniforms[i]->arraySize);
stream.write(mUniforms[i]->psRegisterIndex);
stream.write(mUniforms[i]->vsRegisterIndex);
stream.write(mUniforms[i]->registerCount);
}
stream.write(mUniformIndex.size());
for (unsigned int i = 0; i < mUniformIndex.size(); ++i)
{
stream.write(mUniformIndex[i].name);
stream.write(mUniformIndex[i].element);
stream.write(mUniformIndex[i].index);
}
UINT pixelShaderSize = mPixelExecutable->getLength();
stream.write(pixelShaderSize);
UINT vertexShaderSize = mVertexExecutable->getLength();
stream.write(vertexShaderSize);
UINT geometryShaderSize = (mGeometryExecutable != NULL) ? mGeometryExecutable->getLength() : 0;
stream.write(geometryShaderSize);
GUID identifier = mRenderer->getAdapterIdentifier();
GLsizei streamLength = stream.length();
const void *streamData = stream.data();
GLsizei totalLength = streamLength + sizeof(GUID) + pixelShaderSize + vertexShaderSize + geometryShaderSize;
if (totalLength > bufSize)
{
if (length)
{
*length = 0;
}
return false;
}
if (binary)
{
char *ptr = (char*) binary;
memcpy(ptr, streamData, streamLength);
ptr += streamLength;
memcpy(ptr, &identifier, sizeof(GUID));
ptr += sizeof(GUID);
memcpy(ptr, mPixelExecutable->getFunction(), pixelShaderSize);
ptr += pixelShaderSize;
memcpy(ptr, mVertexExecutable->getFunction(), vertexShaderSize);
ptr += vertexShaderSize;
if (mGeometryExecutable != NULL && geometryShaderSize > 0)
{
memcpy(ptr, mGeometryExecutable->getFunction(), geometryShaderSize);
ptr += geometryShaderSize;
}
ASSERT(ptr - totalLength == binary);
}
if (length)
{
*length = totalLength;
}
return true;
}
GLint ProgramBinary::getLength()
{
GLint length;
if (save(NULL, INT_MAX, &length))
{
return length;
}
else
{
return 0;
}
}
bool ProgramBinary::link(InfoLog &infoLog, const AttributeBindings &attributeBindings, FragmentShader *fragmentShader, VertexShader *vertexShader)
{
if (!fragmentShader || !fragmentShader->isCompiled())
{
return false;
}
if (!vertexShader || !vertexShader->isCompiled())
{
return false;
}
std::string pixelHLSL = fragmentShader->getHLSL();
std::string vertexHLSL = vertexShader->getHLSL();
// Map the varyings to the register file
const Varying *packing[IMPLEMENTATION_MAX_VARYING_VECTORS][4] = {NULL};
int registers = packVaryings(infoLog, packing, fragmentShader);
if (registers < 0)
{
return false;
}
if (!linkVaryings(infoLog, registers, packing, pixelHLSL, vertexHLSL, fragmentShader, vertexShader))
{
return false;
}
bool success = true;
mVertexExecutable = mRenderer->compileToExecutable(infoLog, vertexHLSL.c_str(), rx::SHADER_VERTEX);
mPixelExecutable = mRenderer->compileToExecutable(infoLog, pixelHLSL.c_str(), rx::SHADER_PIXEL);
if (usesGeometryShader())
{
std::string geometryHLSL = generateGeometryShaderHLSL(registers, packing, fragmentShader, vertexShader);
mGeometryExecutable = mRenderer->compileToExecutable(infoLog, geometryHLSL.c_str(), rx::SHADER_GEOMETRY);
}
if (!mVertexExecutable || !mPixelExecutable || (usesGeometryShader() && !mGeometryExecutable))
{
infoLog.append("Failed to create D3D shaders.");
success = false;
delete mVertexExecutable;
mVertexExecutable = NULL;
delete mPixelExecutable;
mPixelExecutable = NULL;
delete mGeometryExecutable;
mGeometryExecutable = NULL;
}
if (!linkAttributes(infoLog, attributeBindings, fragmentShader, vertexShader))
{
success = false;
}
if (!linkUniforms(infoLog, vertexShader->getUniforms(), fragmentShader->getUniforms()))
{
success = false;
}
// special case for gl_DepthRange, the only built-in uniform (also a struct)
if (vertexShader->mUsesDepthRange || fragmentShader->mUsesDepthRange)
{
mUniforms.push_back(new Uniform(GL_FLOAT, GL_HIGH_FLOAT, "gl_DepthRange.near", 0));
mUniforms.push_back(new Uniform(GL_FLOAT, GL_HIGH_FLOAT, "gl_DepthRange.far", 0));
mUniforms.push_back(new Uniform(GL_FLOAT, GL_HIGH_FLOAT, "gl_DepthRange.diff", 0));
}
return success;
}
// Determines the mapping between GL attributes and Direct3D 9 vertex stream usage indices
bool ProgramBinary::linkAttributes(InfoLog &infoLog, const AttributeBindings &attributeBindings, FragmentShader *fragmentShader, VertexShader *vertexShader)
{
unsigned int usedLocations = 0;
// Link attributes that have a binding location
for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++)
{
int location = attributeBindings.getAttributeBinding(attribute->name);
if (location != -1) // Set by glBindAttribLocation
{
if (!mLinkedAttribute[location].name.empty())
{
// Multiple active attributes bound to the same location; not an error
}
mLinkedAttribute[location] = *attribute;
int rows = VariableRowCount(attribute->type);
if (rows + location > MAX_VERTEX_ATTRIBS)
{
infoLog.append("Active attribute (%s) at location %d is too big to fit", attribute->name.c_str(), location);
return false;
}
for (int i = 0; i < rows; i++)
{
usedLocations |= 1 << (location + i);
}
}
}
// Link attributes that don't have a binding location
for (AttributeArray::iterator attribute = vertexShader->mAttributes.begin(); attribute != vertexShader->mAttributes.end(); attribute++)
{
int location = attributeBindings.getAttributeBinding(attribute->name);
if (location == -1) // Not set by glBindAttribLocation
{
int rows = VariableRowCount(attribute->type);
int availableIndex = AllocateFirstFreeBits(&usedLocations, rows, MAX_VERTEX_ATTRIBS);
if (availableIndex == -1 || availableIndex + rows > MAX_VERTEX_ATTRIBS)
{
infoLog.append("Too many active attributes (%s)", attribute->name.c_str());
return false; // Fail to link
}
mLinkedAttribute[availableIndex] = *attribute;
}
}
for (int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; )
{
int index = vertexShader->getSemanticIndex(mLinkedAttribute[attributeIndex].name);
int rows = std::max(VariableRowCount(mLinkedAttribute[attributeIndex].type), 1);
for (int r = 0; r < rows; r++)
{
mSemanticIndex[attributeIndex++] = index++;
}
}
return true;
}
bool ProgramBinary::linkUniforms(InfoLog &infoLog, const sh::ActiveUniforms &vertexUniforms, const sh::ActiveUniforms &fragmentUniforms)
{
for (sh::ActiveUniforms::const_iterator uniform = vertexUniforms.begin(); uniform != vertexUniforms.end(); uniform++)
{
if (!defineUniform(GL_VERTEX_SHADER, *uniform, infoLog))
{
return false;
}
}
for (sh::ActiveUniforms::const_iterator uniform = fragmentUniforms.begin(); uniform != fragmentUniforms.end(); uniform++)
{
if (!defineUniform(GL_FRAGMENT_SHADER, *uniform, infoLog))
{
return false;
}
}
return true;
}
bool ProgramBinary::defineUniform(GLenum shader, const sh::Uniform &constant, InfoLog &infoLog)
{
if (constant.type == GL_SAMPLER_2D ||
constant.type == GL_SAMPLER_CUBE)
{
unsigned int samplerIndex = constant.registerIndex;
do
{
if (shader == GL_VERTEX_SHADER)
{
if (samplerIndex < mRenderer->getMaxVertexTextureImageUnits())
{
mSamplersVS[samplerIndex].active = true;
mSamplersVS[samplerIndex].textureType = (constant.type == GL_SAMPLER_CUBE) ? TEXTURE_CUBE : TEXTURE_2D;
mSamplersVS[samplerIndex].logicalTextureUnit = 0;
mUsedVertexSamplerRange = std::max(samplerIndex + 1, mUsedVertexSamplerRange);
}
else
{
infoLog.append("Vertex shader sampler count exceeds the maximum vertex texture units (%d).", mRenderer->getMaxVertexTextureImageUnits());
return false;
}
}
else if (shader == GL_FRAGMENT_SHADER)
{
if (samplerIndex < MAX_TEXTURE_IMAGE_UNITS)
{
mSamplersPS[samplerIndex].active = true;
mSamplersPS[samplerIndex].textureType = (constant.type == GL_SAMPLER_CUBE) ? TEXTURE_CUBE : TEXTURE_2D;
mSamplersPS[samplerIndex].logicalTextureUnit = 0;
mUsedPixelSamplerRange = std::max(samplerIndex + 1, mUsedPixelSamplerRange);
}
else
{
infoLog.append("Pixel shader sampler count exceeds MAX_TEXTURE_IMAGE_UNITS (%d).", MAX_TEXTURE_IMAGE_UNITS);
return false;
}
}
else UNREACHABLE();
samplerIndex++;
}
while (samplerIndex < constant.registerIndex + constant.arraySize);
}
Uniform *uniform = NULL;
GLint location = getUniformLocation(constant.name);
if (location >= 0) // Previously defined, type and precision must match
{
uniform = mUniforms[mUniformIndex[location].index];
if (uniform->type != constant.type)
{
infoLog.append("Types for uniform %s do not match between the vertex and fragment shader", uniform->name.c_str());
return false;
}
if (uniform->precision != constant.precision)
{
infoLog.append("Precisions for uniform %s do not match between the vertex and fragment shader", uniform->name.c_str());
return false;
}
}
else
{
uniform = new Uniform(constant.type, constant.precision, constant.name, constant.arraySize);
}
if (!uniform)
{
return false;
}
if (shader == GL_FRAGMENT_SHADER)
{
uniform->psRegisterIndex = constant.registerIndex;
}
else if (shader == GL_VERTEX_SHADER)
{
uniform->vsRegisterIndex = constant.registerIndex;
}
else UNREACHABLE();
if (location >= 0)
{
return uniform->type == constant.type;
}
mUniforms.push_back(uniform);
unsigned int uniformIndex = mUniforms.size() - 1;
for (unsigned int i = 0; i < uniform->elementCount(); i++)
{
mUniformIndex.push_back(UniformLocation(constant.name, i, uniformIndex));
}
if (shader == GL_VERTEX_SHADER)
{
if (constant.registerIndex + uniform->registerCount > mRenderer->getReservedVertexUniformVectors() + mRenderer->getMaxVertexUniformVectors())
{
infoLog.append("Vertex shader active uniforms exceed GL_MAX_VERTEX_UNIFORM_VECTORS (%u)", mRenderer->getMaxVertexUniformVectors());
return false;
}
}
else if (shader == GL_FRAGMENT_SHADER)
{
if (constant.registerIndex + uniform->registerCount > mRenderer->getReservedFragmentUniformVectors() + mRenderer->getMaxFragmentUniformVectors())
{
infoLog.append("Fragment shader active uniforms exceed GL_MAX_FRAGMENT_UNIFORM_VECTORS (%u)", mRenderer->getMaxFragmentUniformVectors());
return false;
}
}
else UNREACHABLE();
return true;
}
std::string ProgramBinary::generateGeometryShaderHLSL(int registers, const Varying *packing[][4], FragmentShader *fragmentShader, VertexShader *vertexShader) const
{
// for now we only handle point sprite emulation
ASSERT(usesPointSpriteEmulation());
return generatePointSpriteHLSL(registers, packing, fragmentShader, vertexShader);
}
std::string ProgramBinary::generatePointSpriteHLSL(int registers, const Varying *packing[][4], FragmentShader *fragmentShader, VertexShader *vertexShader) const
{
ASSERT(registers >= 0);
ASSERT(vertexShader->mUsesPointSize);
ASSERT(mRenderer->getMajorShaderModel() >= 4);
std::string geomHLSL;
std::string varyingSemantic = "TEXCOORD";
std::string fragCoordSemantic;
std::string pointCoordSemantic;
int reservedRegisterIndex = registers;
if (fragmentShader->mUsesFragCoord)
{
fragCoordSemantic = varyingSemantic + str(reservedRegisterIndex++);
}
if (fragmentShader->mUsesPointCoord)
{
pointCoordSemantic = varyingSemantic + str(reservedRegisterIndex++);
}
geomHLSL += "uniform float4 dx_ViewCoords : register(c1);\n"
"\n"
"struct GS_INPUT\n"
"{\n";
for (int r = 0; r < registers; r++)
{
int registerSize = packing[r][3] ? 4 : (packing[r][2] ? 3 : (packing[r][1] ? 2 : 1));
geomHLSL += " float" + str(registerSize) + " v" + str(r) + " : " + varyingSemantic + str(r) + ";\n";
}
if (fragmentShader->mUsesFragCoord)
{
geomHLSL += " float4 gl_FragCoord : " + fragCoordSemantic + ";\n";
}
geomHLSL += " float gl_PointSize : PSIZE;\n"
" float4 gl_Position : SV_Position;\n"
"};\n"
"\n"
"struct GS_OUTPUT\n"
"{\n";
for (int r = 0; r < registers; r++)
{
int registerSize = packing[r][3] ? 4 : (packing[r][2] ? 3 : (packing[r][1] ? 2 : 1));
geomHLSL += " float" + str(registerSize) + " v" + str(r) + " : " + varyingSemantic + str(r) + ";\n";
}
if (fragmentShader->mUsesFragCoord)
{
geomHLSL += " float4 gl_FragCoord : " + fragCoordSemantic + ";\n";
}
if (fragmentShader->mUsesPointCoord)
{
geomHLSL += " float2 gl_PointCoord : " + pointCoordSemantic + ";\n";
}
geomHLSL += " float gl_PointSize : PSIZE;\n"
" float4 gl_Position : SV_Position;\n"
"};\n"
"\n"
"static float2 pointSpriteCorners[] = \n"
"{\n"
" float2( 0.5f, -0.5f),\n"
" float2( 0.5f, 0.5f),\n"
" float2(-0.5f, -0.5f),\n"
" float2(-0.5f, 0.5f)\n"
"};\n"
"\n"
"static float2 pointSpriteTexcoords[] = \n"
"{\n"
" float2(1.0f, 1.0f),\n"
" float2(1.0f, 0.0f),\n"
" float2(0.0f, 1.0f),\n"
" float2(0.0f, 0.0f)\n"
"};\n"
"\n"
"static float minPointSize = " + str(ALIASED_POINT_SIZE_RANGE_MIN) + ".0f;\n"
"static float maxPointSize = " + str(mRenderer->getMaxPointSize()) + ".0f;\n"
"\n"
"[maxvertexcount(4)]\n"
"void main(point GS_INPUT input[1], inout TriangleStream<GS_OUTPUT> outStream)\n"
"{\n"
" GS_OUTPUT output = (GS_OUTPUT)0;\n"
" output.gl_PointSize = input[0].gl_PointSize;\n";
for (int r = 0; r < registers; r++)
{
geomHLSL += " output.v" + str(r) + " = input[0].v" + str(r) + ";\n";
}
if (fragmentShader->mUsesFragCoord)
{
geomHLSL += " output.gl_FragCoord = input[0].gl_FragCoord;\n";
}
geomHLSL += " \n"
" float gl_PointSize = clamp(input[0].gl_PointSize, minPointSize, maxPointSize);\n"
" float4 gl_Position = input[0].gl_Position;\n"
" float2 viewportScale = float2(1.0f / dx_ViewCoords.x, 1.0f / dx_ViewCoords.y) * gl_Position.w;\n";
for (int corner = 0; corner < 4; corner++)
{
geomHLSL += " \n"
" output.gl_Position = gl_Position + float4(pointSpriteCorners[" + str(corner) + "] * viewportScale * gl_PointSize, 0.0f, 0.0f);\n";
if (fragmentShader->mUsesPointCoord)
{
geomHLSL += " output.gl_PointCoord = pointSpriteTexcoords[" + str(corner) + "];\n";
}
geomHLSL += " outStream.Append(output);\n";
}
geomHLSL += " \n"
" outStream.RestartStrip();\n"
"}\n";
return geomHLSL;
}
// This method needs to match OutputHLSL::decorate
std::string ProgramBinary::decorateAttribute(const std::string &name)
{
if (name.compare(0, 3, "gl_") != 0 && name.compare(0, 3, "dx_") != 0)
{
return "_" + name;
}
return name;
}
bool ProgramBinary::isValidated() const
{
return mValidated;
}
void ProgramBinary::getActiveAttribute(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) const
{
// Skip over inactive attributes
unsigned int activeAttribute = 0;
unsigned int attribute;
for (attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
{
if (mLinkedAttribute[attribute].name.empty())
{
continue;
}
if (activeAttribute == index)
{
break;
}
activeAttribute++;
}
if (bufsize > 0)
{
const char *string = mLinkedAttribute[attribute].name.c_str();
strncpy(name, string, bufsize);
name[bufsize - 1] = '\0';
if (length)
{
*length = strlen(name);
}
}
*size = 1; // Always a single 'type' instance
*type = mLinkedAttribute[attribute].type;
}
GLint ProgramBinary::getActiveAttributeCount() const
{
int count = 0;
for (int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; attributeIndex++)
{
if (!mLinkedAttribute[attributeIndex].name.empty())
{
count++;
}
}
return count;
}
GLint ProgramBinary::getActiveAttributeMaxLength() const
{
int maxLength = 0;
for (int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; attributeIndex++)
{
if (!mLinkedAttribute[attributeIndex].name.empty())
{
maxLength = std::max((int)(mLinkedAttribute[attributeIndex].name.length() + 1), maxLength);
}
}
return maxLength;
}
void ProgramBinary::getActiveUniform(GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) const
{
ASSERT(index < mUniforms.size()); // index must be smaller than getActiveUniformCount()
if (bufsize > 0)
{
std::string string = mUniforms[index]->name;
if (mUniforms[index]->isArray())
{
string += "[0]";
}
strncpy(name, string.c_str(), bufsize);
name[bufsize - 1] = '\0';
if (length)
{
*length = strlen(name);
}
}
*size = mUniforms[index]->elementCount();
*type = mUniforms[index]->type;
}
GLint ProgramBinary::getActiveUniformCount() const
{
return mUniforms.size();
}
GLint ProgramBinary::getActiveUniformMaxLength() const
{
int maxLength = 0;
unsigned int numUniforms = mUniforms.size();
for (unsigned int uniformIndex = 0; uniformIndex < numUniforms; uniformIndex++)
{
if (!mUniforms[uniformIndex]->name.empty())
{
int length = (int)(mUniforms[uniformIndex]->name.length() + 1);
if (mUniforms[uniformIndex]->isArray())
{
length += 3; // Counting in "[0]".
}
maxLength = std::max(length, maxLength);
}
}
return maxLength;
}
void ProgramBinary::validate(InfoLog &infoLog)
{
applyUniforms();
if (!validateSamplers(&infoLog))
{
mValidated = false;
}
else
{
mValidated = true;
}
}
bool ProgramBinary::validateSamplers(InfoLog *infoLog)
{
// if any two active samplers in a program are of different types, but refer to the same
// texture image unit, and this is the current program, then ValidateProgram will fail, and
// DrawArrays and DrawElements will issue the INVALID_OPERATION error.
const unsigned int maxCombinedTextureImageUnits = mRenderer->getMaxCombinedTextureImageUnits();
TextureType textureUnitType[IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS];
for (unsigned int i = 0; i < IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS; ++i)
{
textureUnitType[i] = TEXTURE_UNKNOWN;
}
for (unsigned int i = 0; i < mUsedPixelSamplerRange; ++i)
{
if (mSamplersPS[i].active)
{
unsigned int unit = mSamplersPS[i].logicalTextureUnit;
if (unit >= maxCombinedTextureImageUnits)
{
if (infoLog)
{
infoLog->append("Sampler uniform (%d) exceeds IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS (%d)", unit, maxCombinedTextureImageUnits);
}
return false;
}
if (textureUnitType[unit] != TEXTURE_UNKNOWN)
{
if (mSamplersPS[i].textureType != textureUnitType[unit])
{
if (infoLog)
{
infoLog->append("Samplers of conflicting types refer to the same texture image unit (%d).", unit);
}
return false;
}
}
else
{
textureUnitType[unit] = mSamplersPS[i].textureType;
}
}
}
for (unsigned int i = 0; i < mUsedVertexSamplerRange; ++i)
{
if (mSamplersVS[i].active)
{
unsigned int unit = mSamplersVS[i].logicalTextureUnit;
if (unit >= maxCombinedTextureImageUnits)
{
if (infoLog)
{
infoLog->append("Sampler uniform (%d) exceeds IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS (%d)", unit, maxCombinedTextureImageUnits);
}
return false;
}
if (textureUnitType[unit] != TEXTURE_UNKNOWN)
{
if (mSamplersVS[i].textureType != textureUnitType[unit])
{
if (infoLog)
{
infoLog->append("Samplers of conflicting types refer to the same texture image unit (%d).", unit);
}
return false;
}
}
else
{
textureUnitType[unit] = mSamplersVS[i].textureType;
}
}
}
return true;
}
ProgramBinary::Sampler::Sampler() : active(false), logicalTextureUnit(0), textureType(TEXTURE_2D)
{
}
struct AttributeSorter
{
AttributeSorter(const int (&semanticIndices)[MAX_VERTEX_ATTRIBS])
: originalIndices(semanticIndices)
{
for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
{
indices[i] = i;
}
std::sort(&indices[0], &indices[MAX_VERTEX_ATTRIBS], *this);
}
bool operator()(int a, int b)
{
return originalIndices[a] == -1 ? false : originalIndices[a] < originalIndices[b];
}
int indices[MAX_VERTEX_ATTRIBS];
const int (&originalIndices)[MAX_VERTEX_ATTRIBS];
};
void ProgramBinary::sortAttributesByLayout(rx::TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS], int sortedSemanticIndices[MAX_VERTEX_ATTRIBS]) const
{
AttributeSorter sorter(mSemanticIndex);
int oldIndices[MAX_VERTEX_ATTRIBS];
rx::TranslatedAttribute oldTranslatedAttributes[MAX_VERTEX_ATTRIBS];
for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
{
oldIndices[i] = mSemanticIndex[i];
oldTranslatedAttributes[i] = attributes[i];
}
for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
{
int oldIndex = sorter.indices[i];
sortedSemanticIndices[i] = oldIndices[oldIndex];
attributes[i] = oldTranslatedAttributes[oldIndex];
}
}
}
| 010smithzhang-ddd | src/libGLESv2/ProgramBinary.cpp | C++ | bsd | 79,056 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Image.h: Implements the rx::Image class, an abstract base class for the
// renderer-specific classes which will define the interface to the underlying
// surfaces or resources.
#include "libGLESv2/renderer/Image.h"
namespace rx
{
Image::Image()
{
mWidth = 0;
mHeight = 0;
mInternalFormat = GL_NONE;
mActualFormat = GL_NONE;
}
void Image::loadAlphaDataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = 0;
dest[4 * x + 1] = 0;
dest[4 * x + 2] = 0;
dest[4 * x + 3] = source[x];
}
}
}
void Image::loadAlphaDataToNative(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
memcpy(dest, source, width);
}
}
void Image::loadAlphaFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = 0;
dest[4 * x + 1] = 0;
dest[4 * x + 2] = 0;
dest[4 * x + 3] = source[x];
}
}
}
void Image::loadAlphaHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned short *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned short*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = 0;
dest[4 * x + 1] = 0;
dest[4 * x + 2] = 0;
dest[4 * x + 3] = source[x];
}
}
}
void Image::loadLuminanceDataToNativeOrBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output, bool native)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
if (!native) // BGRA8 destination format
{
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x];
dest[4 * x + 1] = source[x];
dest[4 * x + 2] = source[x];
dest[4 * x + 3] = 0xFF;
}
}
else // L8 destination format
{
memcpy(dest, source, width);
}
}
}
void Image::loadLuminanceFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x];
dest[4 * x + 1] = source[x];
dest[4 * x + 2] = source[x];
dest[4 * x + 3] = 1.0f;
}
}
}
void Image::loadLuminanceFloatDataToRGB(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[3 * x + 0] = source[x];
dest[3 * x + 1] = source[x];
dest[3 * x + 2] = source[x];
}
}
}
void Image::loadLuminanceHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned short *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned short*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x];
dest[4 * x + 1] = source[x];
dest[4 * x + 2] = source[x];
dest[4 * x + 3] = 0x3C00; // SEEEEEMMMMMMMMMM, S = 0, E = 15, M = 0: 16bit flpt representation of 1
}
}
}
void Image::loadLuminanceAlphaDataToNativeOrBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output, bool native)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
if (!native) // BGRA8 destination format
{
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[2*x+0];
dest[4 * x + 1] = source[2*x+0];
dest[4 * x + 2] = source[2*x+0];
dest[4 * x + 3] = source[2*x+1];
}
}
else
{
memcpy(dest, source, width * 2);
}
}
}
void Image::loadLuminanceAlphaFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[2*x+0];
dest[4 * x + 1] = source[2*x+0];
dest[4 * x + 2] = source[2*x+0];
dest[4 * x + 3] = source[2*x+1];
}
}
}
void Image::loadLuminanceAlphaHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned short *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned short*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[2*x+0];
dest[4 * x + 1] = source[2*x+0];
dest[4 * x + 2] = source[2*x+0];
dest[4 * x + 3] = source[2*x+1];
}
}
}
void Image::loadRGBUByteDataToBGRX(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x * 3 + 2];
dest[4 * x + 1] = source[x * 3 + 1];
dest[4 * x + 2] = source[x * 3 + 0];
dest[4 * x + 3] = 0xFF;
}
}
}
void Image::loadRGBUByteDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x * 3 + 0];
dest[4 * x + 1] = source[x * 3 + 1];
dest[4 * x + 2] = source[x * 3 + 2];
dest[4 * x + 3] = 0xFF;
}
}
}
void Image::loadRGB565DataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0x001F) << 3) | ((rgba & 0x001F) >> 2);
dest[4 * x + 1] = ((rgba & 0x07E0) >> 3) | ((rgba & 0x07E0) >> 9);
dest[4 * x + 2] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
dest[4 * x + 3] = 0xFF;
}
}
}
void Image::loadRGB565DataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
dest[4 * x + 1] = ((rgba & 0x07E0) >> 3) | ((rgba & 0x07E0) >> 9);
dest[4 * x + 2] = ((rgba & 0x001F) << 3) | ((rgba & 0x001F) >> 2);
dest[4 * x + 3] = 0xFF;
}
}
}
void Image::loadRGBFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x * 3 + 0];
dest[4 * x + 1] = source[x * 3 + 1];
dest[4 * x + 2] = source[x * 3 + 2];
dest[4 * x + 3] = 1.0f;
}
}
}
void Image::loadRGBFloatDataToNative(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
memcpy(dest, source, width * 12);
}
}
void Image::loadRGBHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned short *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned short*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
dest[4 * x + 0] = source[x * 3 + 0];
dest[4 * x + 1] = source[x * 3 + 1];
dest[4 * x + 2] = source[x * 3 + 2];
dest[4 * x + 3] = 0x3C00; // SEEEEEMMMMMMMMMM, S = 0, E = 15, M = 0: 16bit flpt representation of 1
}
}
}
void Image::loadRGBAUByteDataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned int *source = NULL;
unsigned int *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned int*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned int*>(static_cast<unsigned char*>(output) + y * outputPitch);
for (int x = 0; x < width; x++)
{
unsigned int rgba = source[x];
dest[x] = (_rotl(rgba, 16) & 0x00ff00ff) | (rgba & 0xff00ff00);
}
}
}
void Image::loadRGBAUByteDataToNative(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned int *source = NULL;
unsigned int *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned int*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned int*>(static_cast<unsigned char*>(output) + y * outputPitch);
memcpy(dest, source, width * 4);
}
}
void Image::loadRGBA4444DataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0x00F0) << 0) | ((rgba & 0x00F0) >> 4);
dest[4 * x + 1] = ((rgba & 0x0F00) >> 4) | ((rgba & 0x0F00) >> 8);
dest[4 * x + 2] = ((rgba & 0xF000) >> 8) | ((rgba & 0xF000) >> 12);
dest[4 * x + 3] = ((rgba & 0x000F) << 4) | ((rgba & 0x000F) >> 0);
}
}
}
void Image::loadRGBA4444DataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0xF000) >> 8) | ((rgba & 0xF000) >> 12);
dest[4 * x + 1] = ((rgba & 0x0F00) >> 4) | ((rgba & 0x0F00) >> 8);
dest[4 * x + 2] = ((rgba & 0x00F0) << 0) | ((rgba & 0x00F0) >> 4);
dest[4 * x + 3] = ((rgba & 0x000F) << 4) | ((rgba & 0x000F) >> 0);
}
}
}
void Image::loadRGBA5551DataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0x003E) << 2) | ((rgba & 0x003E) >> 3);
dest[4 * x + 1] = ((rgba & 0x07C0) >> 3) | ((rgba & 0x07C0) >> 8);
dest[4 * x + 2] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
dest[4 * x + 3] = (rgba & 0x0001) ? 0xFF : 0;
}
}
}
void Image::loadRGBA5551DataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned short *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned short*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = static_cast<unsigned char*>(output) + y * outputPitch;
for (int x = 0; x < width; x++)
{
unsigned short rgba = source[x];
dest[4 * x + 0] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
dest[4 * x + 1] = ((rgba & 0x07C0) >> 3) | ((rgba & 0x07C0) >> 8);
dest[4 * x + 2] = ((rgba & 0x003E) << 2) | ((rgba & 0x003E) >> 3);
dest[4 * x + 3] = (rgba & 0x0001) ? 0xFF : 0;
}
}
}
void Image::loadRGBAFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const float *source = NULL;
float *dest = NULL;
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const float*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<float*>(static_cast<unsigned char*>(output) + y * outputPitch);
memcpy(dest, source, width * 16);
}
}
void Image::loadRGBAHalfFloatDataToRGBA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
memcpy(dest, source, width * 8);
}
}
void Image::loadBGRADataToBGRA(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned char *dest = NULL;
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = static_cast<unsigned char*>(output) + y * outputPitch;
memcpy(dest, source, width*4);
}
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/Image.cpp | C++ | bsd | 20,213 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexBuffer9.h: Defines the D3D9 VertexBuffer implementation.
#ifndef LIBGLESV2_RENDERER_VERTEXBUFFER9_H_
#define LIBGLESV2_RENDERER_VERTEXBUFFER9_H_
#include "libGLESv2/renderer/VertexBuffer.h"
namespace rx
{
class Renderer9;
class VertexBuffer9 : public VertexBuffer
{
public:
explicit VertexBuffer9(rx::Renderer9 *const renderer);
virtual ~VertexBuffer9();
virtual bool initialize(unsigned int size, bool dynamicUsage);
static VertexBuffer9 *makeVertexBuffer9(VertexBuffer *vertexBuffer);
virtual bool storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count, GLsizei instances,
unsigned int offset);
virtual bool storeRawData(const void* data, unsigned int size, unsigned int offset);
virtual unsigned int getSpaceRequired(const gl::VertexAttribute &attrib, GLsizei count, GLsizei instances) const;
virtual bool requiresConversion(const gl::VertexAttribute &attrib) const;
unsigned int getVertexSize(const gl::VertexAttribute &attrib) const;
D3DDECLTYPE getDeclType(const gl::VertexAttribute &attrib) const;
virtual unsigned int getBufferSize() const;
virtual bool setBufferSize(unsigned int size);
virtual bool discard();
IDirect3DVertexBuffer9 *getBuffer() const;
private:
DISALLOW_COPY_AND_ASSIGN(VertexBuffer9);
rx::Renderer9 *const mRenderer;
IDirect3DVertexBuffer9 *mVertexBuffer;
unsigned int mBufferSize;
bool mDynamicUsage;
// Attribute format conversion
enum { NUM_GL_VERTEX_ATTRIB_TYPES = 6 };
struct FormatConverter
{
bool identity;
std::size_t outputElementSize;
void (*convertArray)(const void *in, std::size_t stride, std::size_t n, void *out);
D3DDECLTYPE d3dDeclType;
};
static bool mTranslationsInitialized;
static void initializeTranslations(DWORD declTypes);
// [GL types as enumerated by typeIndex()][normalized][size - 1]
static FormatConverter mFormatConverters[NUM_GL_VERTEX_ATTRIB_TYPES][2][4];
struct TranslationDescription
{
DWORD capsFlag;
FormatConverter preferredConversion;
FormatConverter fallbackConversion;
};
// This table is used to generate mFormatConverters.
// [GL types as enumerated by typeIndex()][normalized][size - 1]
static const TranslationDescription mPossibleTranslations[NUM_GL_VERTEX_ATTRIB_TYPES][2][4];
static unsigned int typeIndex(GLenum type);
static const FormatConverter &formatConverter(const gl::VertexAttribute &attribute);
static unsigned int spaceRequired(const gl::VertexAttribute &attrib, std::size_t count, GLsizei instances);
};
}
#endif // LIBGLESV2_RENDERER_VERTEXBUFFER9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/VertexBuffer9.h | C++ | bsd | 2,936 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// InputLayoutCache.cpp: Defines InputLayoutCache, a class that builds and caches
// D3D11 input layouts.
#include "libGLESv2/renderer/InputLayoutCache.h"
#include "libGLESv2/renderer/VertexBuffer11.h"
#include "libGLESv2/renderer/BufferStorage11.h"
#include "libGLESv2/renderer/ShaderExecutable11.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/Context.h"
#include "libGLESv2/renderer/VertexDataManager.h"
#include "third_party/murmurhash/MurmurHash3.h"
namespace rx
{
const unsigned int InputLayoutCache::kMaxInputLayouts = 1024;
InputLayoutCache::InputLayoutCache() : mInputLayoutMap(kMaxInputLayouts, hashInputLayout, compareInputLayouts)
{
mCounter = 0;
mDevice = NULL;
mDeviceContext = NULL;
}
InputLayoutCache::~InputLayoutCache()
{
clear();
}
void InputLayoutCache::initialize(ID3D11Device *device, ID3D11DeviceContext *context)
{
clear();
mDevice = device;
mDeviceContext = context;
}
void InputLayoutCache::clear()
{
for (InputLayoutMap::iterator i = mInputLayoutMap.begin(); i != mInputLayoutMap.end(); i++)
{
i->second.inputLayout->Release();
}
mInputLayoutMap.clear();
}
GLenum InputLayoutCache::applyVertexBuffers(TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS],
gl::ProgramBinary *programBinary)
{
int sortedSemanticIndices[gl::MAX_VERTEX_ATTRIBS];
programBinary->sortAttributesByLayout(attributes, sortedSemanticIndices);
if (!mDevice || !mDeviceContext)
{
ERR("InputLayoutCache is not initialized.");
return GL_INVALID_OPERATION;
}
InputLayoutKey ilKey = { 0 };
ID3D11Buffer *vertexBuffers[gl::MAX_VERTEX_ATTRIBS] = { NULL };
UINT vertexStrides[gl::MAX_VERTEX_ATTRIBS] = { 0 };
UINT vertexOffsets[gl::MAX_VERTEX_ATTRIBS] = { 0 };
static const char* semanticName = "TEXCOORD";
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
VertexBuffer11 *vertexBuffer = VertexBuffer11::makeVertexBuffer11(attributes[i].vertexBuffer);
BufferStorage11 *bufferStorage = attributes[i].storage ? BufferStorage11::makeBufferStorage11(attributes[i].storage) : NULL;
D3D11_INPUT_CLASSIFICATION inputClass = attributes[i].divisor > 0 ? D3D11_INPUT_PER_INSTANCE_DATA : D3D11_INPUT_PER_VERTEX_DATA;
// Record the type of the associated vertex shader vector in our key
// This will prevent mismatched vertex shaders from using the same input layout
GLint attributeSize;
programBinary->getActiveAttribute(ilKey.elementCount, 0, NULL, &attributeSize, &ilKey.glslElementType[ilKey.elementCount], NULL);
ilKey.elements[ilKey.elementCount].SemanticName = semanticName;
ilKey.elements[ilKey.elementCount].SemanticIndex = sortedSemanticIndices[i];
ilKey.elements[ilKey.elementCount].Format = attributes[i].attribute->mArrayEnabled ? vertexBuffer->getDXGIFormat(*attributes[i].attribute) : DXGI_FORMAT_R32G32B32A32_FLOAT;
ilKey.elements[ilKey.elementCount].InputSlot = i;
ilKey.elements[ilKey.elementCount].AlignedByteOffset = 0;
ilKey.elements[ilKey.elementCount].InputSlotClass = inputClass;
ilKey.elements[ilKey.elementCount].InstanceDataStepRate = attributes[i].divisor;
ilKey.elementCount++;
vertexBuffers[i] = bufferStorage ? bufferStorage->getBuffer() : vertexBuffer->getBuffer();
vertexStrides[i] = attributes[i].stride;
vertexOffsets[i] = attributes[i].offset;
}
}
ID3D11InputLayout *inputLayout = NULL;
InputLayoutMap::iterator i = mInputLayoutMap.find(ilKey);
if (i != mInputLayoutMap.end())
{
inputLayout = i->second.inputLayout;
i->second.lastUsedTime = mCounter++;
}
else
{
ShaderExecutable11 *shader = ShaderExecutable11::makeShaderExecutable11(programBinary->getVertexExecutable());
HRESULT result = mDevice->CreateInputLayout(ilKey.elements, ilKey.elementCount, shader->getFunction(), shader->getLength(), &inputLayout);
if (FAILED(result))
{
ERR("Failed to crate input layout, result: 0x%08x", result);
return GL_INVALID_OPERATION;
}
if (mInputLayoutMap.size() >= kMaxInputLayouts)
{
TRACE("Overflowed the limit of %u input layouts, removing the least recently used "
"to make room.", kMaxInputLayouts);
InputLayoutMap::iterator leastRecentlyUsed = mInputLayoutMap.begin();
for (InputLayoutMap::iterator i = mInputLayoutMap.begin(); i != mInputLayoutMap.end(); i++)
{
if (i->second.lastUsedTime < leastRecentlyUsed->second.lastUsedTime)
{
leastRecentlyUsed = i;
}
}
leastRecentlyUsed->second.inputLayout->Release();
mInputLayoutMap.erase(leastRecentlyUsed);
}
InputLayoutCounterPair inputCounterPair;
inputCounterPair.inputLayout = inputLayout;
inputCounterPair.lastUsedTime = mCounter++;
mInputLayoutMap.insert(std::make_pair(ilKey, inputCounterPair));
}
mDeviceContext->IASetInputLayout(inputLayout);
mDeviceContext->IASetVertexBuffers(0, gl::MAX_VERTEX_ATTRIBS, vertexBuffers, vertexStrides, vertexOffsets);
return GL_NO_ERROR;
}
std::size_t InputLayoutCache::hashInputLayout(const InputLayoutKey &inputLayout)
{
static const unsigned int seed = 0xDEADBEEF;
std::size_t hash = 0;
MurmurHash3_x86_32(&inputLayout, sizeof(InputLayoutKey), seed, &hash);
return hash;
}
bool InputLayoutCache::compareInputLayouts(const InputLayoutKey &a, const InputLayoutKey &b)
{
return memcmp(&a, &b, sizeof(InputLayoutKey)) == 0;
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/InputLayoutCache.cpp | C++ | bsd | 6,090 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Indexffer9.h: Defines the D3D9 IndexBuffer implementation.
#ifndef LIBGLESV2_RENDERER_INDEXBUFFER9_H_
#define LIBGLESV2_RENDERER_INDEXBUFFER9_H_
#include "libGLESv2/renderer/IndexBuffer.h"
namespace rx
{
class Renderer9;
class IndexBuffer9 : public IndexBuffer
{
public:
explicit IndexBuffer9(Renderer9 *const renderer);
virtual ~IndexBuffer9();
virtual bool initialize(unsigned int bufferSize, GLenum indexType, bool dynamic);
static IndexBuffer9 *makeIndexBuffer9(IndexBuffer *indexBuffer);
virtual bool mapBuffer(unsigned int offset, unsigned int size, void** outMappedMemory);
virtual bool unmapBuffer();
virtual GLenum getIndexType() const;
virtual unsigned int getBufferSize() const;
virtual bool setSize(unsigned int bufferSize, GLenum indexType);
virtual bool discard();
D3DFORMAT getIndexFormat() const;
IDirect3DIndexBuffer9 *getBuffer() const;
private:
DISALLOW_COPY_AND_ASSIGN(IndexBuffer9);
rx::Renderer9 *const mRenderer;
IDirect3DIndexBuffer9 *mIndexBuffer;
unsigned int mBufferSize;
GLenum mIndexType;
bool mDynamic;
};
}
#endif // LIBGLESV2_RENDERER_INDEXBUFFER9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/IndexBuffer9.h | C++ | bsd | 1,363 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexBuffer.cpp: Defines the abstract VertexBuffer class and VertexBufferInterface
// class with derivations, classes that perform graphics API agnostic vertex buffer operations.
#include "libGLESv2/renderer/VertexBuffer.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/Context.h"
namespace rx
{
unsigned int VertexBuffer::mNextSerial = 1;
VertexBuffer::VertexBuffer()
{
updateSerial();
}
VertexBuffer::~VertexBuffer()
{
}
void VertexBuffer::updateSerial()
{
mSerial = mNextSerial++;
}
unsigned int VertexBuffer::getSerial() const
{
return mSerial;
}
VertexBufferInterface::VertexBufferInterface(rx::Renderer *renderer, bool dynamic) : mRenderer(renderer)
{
mDynamic = dynamic;
mWritePosition = 0;
mReservedSpace = 0;
mVertexBuffer = renderer->createVertexBuffer();
}
VertexBufferInterface::~VertexBufferInterface()
{
delete mVertexBuffer;
}
unsigned int VertexBufferInterface::getSerial() const
{
return mVertexBuffer->getSerial();
}
unsigned int VertexBufferInterface::getBufferSize() const
{
return mVertexBuffer->getBufferSize();
}
bool VertexBufferInterface::setBufferSize(unsigned int size)
{
if (mVertexBuffer->getBufferSize() == 0)
{
return mVertexBuffer->initialize(size, mDynamic);
}
else
{
return mVertexBuffer->setBufferSize(size);
}
}
unsigned int VertexBufferInterface::getWritePosition() const
{
return mWritePosition;
}
void VertexBufferInterface::setWritePosition(unsigned int writePosition)
{
mWritePosition = writePosition;
}
bool VertexBufferInterface::discard()
{
return mVertexBuffer->discard();
}
int VertexBufferInterface::storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count, GLsizei instances)
{
if (!reserveSpace(mReservedSpace))
{
return -1;
}
mReservedSpace = 0;
if (!mVertexBuffer->storeVertexAttributes(attrib, start, count, instances, mWritePosition))
{
return -1;
}
int oldWritePos = static_cast<int>(mWritePosition);
mWritePosition += mVertexBuffer->getSpaceRequired(attrib, count, instances);
return oldWritePos;
}
int VertexBufferInterface::storeRawData(const void* data, unsigned int size)
{
if (!reserveSpace(mReservedSpace))
{
return -1;
}
mReservedSpace = 0;
if (!mVertexBuffer->storeRawData(data, size, mWritePosition))
{
return -1;
}
int oldWritePos = static_cast<int>(mWritePosition);
mWritePosition += size;
return oldWritePos;
}
void VertexBufferInterface::reserveVertexSpace(const gl::VertexAttribute &attribute, GLsizei count, GLsizei instances)
{
mReservedSpace += mVertexBuffer->getSpaceRequired(attribute, count, instances);
}
void VertexBufferInterface::reserveRawDataSpace(unsigned int size)
{
mReservedSpace += size;
}
VertexBuffer* VertexBufferInterface::getVertexBuffer() const
{
return mVertexBuffer;
}
StreamingVertexBufferInterface::StreamingVertexBufferInterface(rx::Renderer *renderer, std::size_t initialSize) : VertexBufferInterface(renderer, true)
{
setBufferSize(initialSize);
}
StreamingVertexBufferInterface::~StreamingVertexBufferInterface()
{
}
bool StreamingVertexBufferInterface::reserveSpace(unsigned int size)
{
bool result = true;
unsigned int curBufferSize = getBufferSize();
if (size > curBufferSize)
{
result = setBufferSize(std::max(size, 3 * curBufferSize / 2));
setWritePosition(0);
}
else if (getWritePosition() + size > curBufferSize)
{
if (!discard())
{
return false;
}
setWritePosition(0);
}
return result;
}
StaticVertexBufferInterface::StaticVertexBufferInterface(rx::Renderer *renderer) : VertexBufferInterface(renderer, false)
{
}
StaticVertexBufferInterface::~StaticVertexBufferInterface()
{
}
int StaticVertexBufferInterface::lookupAttribute(const gl::VertexAttribute &attribute)
{
for (unsigned int element = 0; element < mCache.size(); element++)
{
if (mCache[element].type == attribute.mType &&
mCache[element].size == attribute.mSize &&
mCache[element].stride == attribute.stride() &&
mCache[element].normalized == attribute.mNormalized)
{
if (mCache[element].attributeOffset == attribute.mOffset % attribute.stride())
{
return mCache[element].streamOffset;
}
}
}
return -1;
}
bool StaticVertexBufferInterface::reserveSpace(unsigned int size)
{
unsigned int curSize = getBufferSize();
if (curSize == 0)
{
setBufferSize(size);
return true;
}
else if (curSize >= size)
{
return true;
}
else
{
UNREACHABLE(); // Static vertex buffers can't be resized
return false;
}
}
int StaticVertexBufferInterface::storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count, GLsizei instances)
{
int attributeOffset = attrib.mOffset % attrib.stride();
VertexElement element = { attrib.mType, attrib.mSize, attrib.stride(), attrib.mNormalized, attributeOffset, getWritePosition() };
mCache.push_back(element);
return VertexBufferInterface::storeVertexAttributes(attrib, start, count, instances);
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/VertexBuffer.cpp | C++ | bsd | 5,544 |
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Renderer.h: Defines a back-end specific class that hides the details of the
// implementation-specific renderer.
#ifndef LIBGLESV2_RENDERER_RENDERER_H_
#define LIBGLESV2_RENDERER_RENDERER_H_
#include "libGLESv2/Uniform.h"
#include "libGLESv2/angletypes.h"
#if !defined(ANGLE_COMPILE_OPTIMIZATION_LEVEL)
#define ANGLE_COMPILE_OPTIMIZATION_LEVEL D3DCOMPILE_OPTIMIZATION_LEVEL3
#endif
const int versionWindowsVista = MAKEWORD(0x00, 0x06);
const int versionWindows7 = MAKEWORD(0x01, 0x06);
// Return the version of the operating system in a format suitable for ordering
// comparison.
inline int getComparableOSVersion()
{
DWORD version = GetVersion();
int majorVersion = LOBYTE(LOWORD(version));
int minorVersion = HIBYTE(LOWORD(version));
return MAKEWORD(minorVersion, majorVersion);
}
namespace egl
{
class Display;
}
namespace gl
{
class InfoLog;
class ProgramBinary;
class VertexAttribute;
class Buffer;
class Texture;
class Framebuffer;
}
namespace rx
{
class TextureStorageInterface2D;
class TextureStorageInterfaceCube;
class VertexBuffer;
class IndexBuffer;
class QueryImpl;
class FenceImpl;
class BufferStorage;
class Blit;
struct TranslatedIndexData;
class ShaderExecutable;
class SwapChain;
class RenderTarget;
class Image;
class TextureStorage;
typedef void * ShaderBlob;
typedef void (*pCompileFunc)();
struct ConfigDesc
{
GLenum renderTargetFormat;
GLenum depthStencilFormat;
GLint multiSample;
bool fastConfig;
};
struct dx_VertexConstants
{
float depthRange[4];
float viewAdjust[4];
};
struct dx_PixelConstants
{
float depthRange[4];
float viewCoords[4];
float depthFront[4];
};
enum ShaderType
{
SHADER_VERTEX,
SHADER_PIXEL,
SHADER_GEOMETRY
};
class Renderer
{
public:
explicit Renderer(egl::Display *display);
virtual ~Renderer();
virtual EGLint initialize() = 0;
virtual bool resetDevice() = 0;
virtual int generateConfigs(ConfigDesc **configDescList) = 0;
virtual void deleteConfigs(ConfigDesc *configDescList) = 0;
virtual void sync(bool block) = 0;
virtual SwapChain *createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat) = 0;
virtual void setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &sampler) = 0;
virtual void setTexture(gl::SamplerType type, int index, gl::Texture *texture) = 0;
virtual void setRasterizerState(const gl::RasterizerState &rasterState) = 0;
virtual void setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor,
unsigned int sampleMask) = 0;
virtual void setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
int stencilBackRef, bool frontFaceCCW) = 0;
virtual void setScissorRectangle(const gl::Rectangle &scissor, bool enabled) = 0;
virtual bool setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
bool ignoreViewport) = 0;
virtual bool applyRenderTarget(gl::Framebuffer *frameBuffer) = 0;
virtual void applyShaders(gl::ProgramBinary *programBinary) = 0;
virtual void applyUniforms(gl::ProgramBinary *programBinary, gl::UniformArray *uniformArray) = 0;
virtual bool applyPrimitiveType(GLenum primitiveType, GLsizei elementCount) = 0;
virtual GLenum applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances) = 0;
virtual GLenum applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo) = 0;
virtual void drawArrays(GLenum mode, GLsizei count, GLsizei instances) = 0;
virtual void drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const TranslatedIndexData &indexInfo, GLsizei instances) = 0;
virtual void clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer) = 0;
virtual void markAllStateDirty() = 0;
// lost device
virtual void notifyDeviceLost() = 0;
virtual bool isDeviceLost() = 0;
virtual bool testDeviceLost(bool notify) = 0;
virtual bool testDeviceResettable() = 0;
// Renderer capabilities
virtual DWORD getAdapterVendor() const = 0;
virtual std::string getRendererDescription() const = 0;
virtual GUID getAdapterIdentifier() const = 0;
virtual bool getBGRATextureSupport() const = 0;
virtual bool getDXT1TextureSupport() = 0;
virtual bool getDXT3TextureSupport() = 0;
virtual bool getDXT5TextureSupport() = 0;
virtual bool getEventQuerySupport() = 0;
virtual bool getFloat32TextureSupport(bool *filtering, bool *renderable) = 0;
virtual bool getFloat16TextureSupport(bool *filtering, bool *renderable) = 0;
virtual bool getLuminanceTextureSupport() = 0;
virtual bool getLuminanceAlphaTextureSupport() = 0;
bool getVertexTextureSupport() const { return getMaxVertexTextureImageUnits() > 0; }
virtual unsigned int getMaxVertexTextureImageUnits() const = 0;
virtual unsigned int getMaxCombinedTextureImageUnits() const = 0;
virtual unsigned int getReservedVertexUniformVectors() const = 0;
virtual unsigned int getReservedFragmentUniformVectors() const = 0;
virtual unsigned int getMaxVertexUniformVectors() const = 0;
virtual unsigned int getMaxFragmentUniformVectors() const = 0;
virtual unsigned int getMaxVaryingVectors() const = 0;
virtual bool getNonPower2TextureSupport() const = 0;
virtual bool getDepthTextureSupport() const = 0;
virtual bool getOcclusionQuerySupport() const = 0;
virtual bool getInstancingSupport() const = 0;
virtual bool getTextureFilterAnisotropySupport() const = 0;
virtual float getTextureMaxAnisotropy() const = 0;
virtual bool getShareHandleSupport() const = 0;
virtual bool getDerivativeInstructionSupport() const = 0;
virtual bool getPostSubBufferSupport() const = 0;
virtual int getMajorShaderModel() const = 0;
virtual float getMaxPointSize() const = 0;
virtual int getMaxViewportDimension() const = 0;
virtual int getMaxTextureWidth() const = 0;
virtual int getMaxTextureHeight() const = 0;
virtual bool get32BitIndexSupport() const = 0;
virtual int getMinSwapInterval() const = 0;
virtual int getMaxSwapInterval() const = 0;
virtual GLsizei getMaxSupportedSamples() const = 0;
virtual unsigned int getMaxRenderTargets() const = 0;
// Pixel operations
virtual bool copyToRenderTarget(TextureStorageInterface2D *dest, TextureStorageInterface2D *source) = 0;
virtual bool copyToRenderTarget(TextureStorageInterfaceCube *dest, TextureStorageInterfaceCube *source) = 0;
virtual bool copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level) = 0;
virtual bool copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level) = 0;
virtual bool blitRect(gl::Framebuffer *readTarget, const gl::Rectangle &readRect, gl::Framebuffer *drawTarget, const gl::Rectangle &drawRect,
bool blitRenderTarget, bool blitDepthStencil) = 0;
virtual void readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels) = 0;
// RenderTarget creation
virtual RenderTarget *createRenderTarget(SwapChain *swapChain, bool depth) = 0;
virtual RenderTarget *createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth) = 0;
// Shader operations
virtual ShaderExecutable *loadExecutable(const void *function, size_t length, rx::ShaderType type) = 0;
virtual ShaderExecutable *compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, rx::ShaderType type) = 0;
// Image operations
virtual Image *createImage() = 0;
virtual void generateMipmap(Image *dest, Image *source) = 0;
virtual TextureStorage *createTextureStorage2D(SwapChain *swapChain) = 0;
virtual TextureStorage *createTextureStorage2D(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height) = 0;
virtual TextureStorage *createTextureStorageCube(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size) = 0;
// Buffer creation
virtual VertexBuffer *createVertexBuffer() = 0;
virtual IndexBuffer *createIndexBuffer() = 0;
virtual BufferStorage *createBufferStorage() = 0;
// Query and Fence creation
virtual QueryImpl *createQuery(GLenum type) = 0;
virtual FenceImpl *createFence() = 0;
virtual bool getLUID(LUID *adapterLuid) const = 0;
protected:
bool initializeCompiler();
ShaderBlob *compileToBinary(gl::InfoLog &infoLog, const char *hlsl, const char *profile, UINT optimizationFlags, bool alternateFlags);
egl::Display *mDisplay;
private:
DISALLOW_COPY_AND_ASSIGN(Renderer);
HMODULE mD3dCompilerModule;
pCompileFunc mD3DCompileFunc;
};
}
#endif // LIBGLESV2_RENDERER_RENDERER_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Renderer.h | C++ | bsd | 9,724 |
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Renderer9.h: Defines a back-end specific class for the D3D9 renderer.
#ifndef LIBGLESV2_RENDERER_RENDERER9_H_
#define LIBGLESV2_RENDERER_RENDERER9_H_
#include "common/angleutils.h"
#include "libGLESv2/mathutil.h"
#include "libGLESv2/renderer/ShaderCache.h"
#include "libGLESv2/renderer/VertexDeclarationCache.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/renderer/RenderTarget.h"
namespace gl
{
class Renderbuffer;
}
namespace rx
{
class VertexDataManager;
class IndexDataManager;
class StreamingIndexBufferInterface;
struct TranslatedAttribute;
class Renderer9 : public Renderer
{
public:
Renderer9(egl::Display *display, HDC hDc, bool softwareDevice);
virtual ~Renderer9();
static Renderer9 *makeRenderer9(Renderer *renderer);
virtual EGLint initialize();
virtual bool resetDevice();
virtual int generateConfigs(ConfigDesc **configDescList);
virtual void deleteConfigs(ConfigDesc *configDescList);
void startScene();
void endScene();
virtual void sync(bool block);
virtual SwapChain *createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat);
IDirect3DQuery9* allocateEventQuery();
void freeEventQuery(IDirect3DQuery9* query);
// resource creation
IDirect3DVertexShader9 *createVertexShader(const DWORD *function, size_t length);
IDirect3DPixelShader9 *createPixelShader(const DWORD *function, size_t length);
HRESULT createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer);
HRESULT createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer);
#if 0
void *createTexture2D();
void *createTextureCube();
void *createQuery();
void *createIndexBuffer();
void *createVertexbuffer();
// state setup
void applyShaders();
void applyConstants();
#endif
virtual void setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &sampler);
virtual void setTexture(gl::SamplerType type, int index, gl::Texture *texture);
virtual void setRasterizerState(const gl::RasterizerState &rasterState);
virtual void setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor,
unsigned int sampleMask);
virtual void setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
int stencilBackRef, bool frontFaceCCW);
virtual void setScissorRectangle(const gl::Rectangle &scissor, bool enabled);
virtual bool setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
bool ignoreViewport);
virtual bool applyRenderTarget(gl::Framebuffer *frameBuffer);
virtual void applyShaders(gl::ProgramBinary *programBinary);
virtual void applyUniforms(gl::ProgramBinary *programBinary, gl::UniformArray *uniformArray);
virtual bool applyPrimitiveType(GLenum primitiveType, GLsizei elementCount);
virtual GLenum applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances);
virtual GLenum applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo);
virtual void drawArrays(GLenum mode, GLsizei count, GLsizei instances);
virtual void drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const TranslatedIndexData &indexInfo, GLsizei instances);
virtual void clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer);
virtual void markAllStateDirty();
// lost device
void notifyDeviceLost();
virtual bool isDeviceLost();
virtual bool testDeviceLost(bool notify);
virtual bool testDeviceResettable();
// Renderer capabilities
IDirect3DDevice9 *getDevice() { return mDevice; }
virtual DWORD getAdapterVendor() const;
virtual std::string getRendererDescription() const;
virtual GUID getAdapterIdentifier() const;
virtual bool getBGRATextureSupport() const;
virtual bool getDXT1TextureSupport();
virtual bool getDXT3TextureSupport();
virtual bool getDXT5TextureSupport();
virtual bool getEventQuerySupport();
virtual bool getFloat32TextureSupport(bool *filtering, bool *renderable);
virtual bool getFloat16TextureSupport(bool *filtering, bool *renderable);
virtual bool getLuminanceTextureSupport();
virtual bool getLuminanceAlphaTextureSupport();
virtual unsigned int getMaxVertexTextureImageUnits() const;
virtual unsigned int getMaxCombinedTextureImageUnits() const;
virtual unsigned int getReservedVertexUniformVectors() const;
virtual unsigned int getReservedFragmentUniformVectors() const;
virtual unsigned int getMaxVertexUniformVectors() const;
virtual unsigned int getMaxFragmentUniformVectors() const;
virtual unsigned int getMaxVaryingVectors() const;
virtual bool getNonPower2TextureSupport() const;
virtual bool getDepthTextureSupport() const;
virtual bool getOcclusionQuerySupport() const;
virtual bool getInstancingSupport() const;
virtual bool getTextureFilterAnisotropySupport() const;
virtual float getTextureMaxAnisotropy() const;
virtual bool getShareHandleSupport() const;
virtual bool getDerivativeInstructionSupport() const;
virtual bool getPostSubBufferSupport() const;
virtual int getMajorShaderModel() const;
virtual float getMaxPointSize() const;
virtual int getMaxViewportDimension() const;
virtual int getMaxTextureWidth() const;
virtual int getMaxTextureHeight() const;
virtual bool get32BitIndexSupport() const;
DWORD getCapsDeclTypes() const;
virtual int getMinSwapInterval() const;
virtual int getMaxSwapInterval() const;
virtual GLsizei getMaxSupportedSamples() const;
int getNearestSupportedSamples(D3DFORMAT format, int requested) const;
virtual unsigned int getMaxRenderTargets() const;
D3DFORMAT ConvertTextureInternalFormat(GLint internalformat);
// Pixel operations
virtual bool copyToRenderTarget(TextureStorageInterface2D *dest, TextureStorageInterface2D *source);
virtual bool copyToRenderTarget(TextureStorageInterfaceCube *dest, TextureStorageInterfaceCube *source);
virtual bool copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level);
virtual bool copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level);
virtual bool blitRect(gl::Framebuffer *readTarget, const gl::Rectangle &readRect, gl::Framebuffer *drawTarget, const gl::Rectangle &drawRect,
bool blitRenderTarget, bool blitDepthStencil);
virtual void readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels);
// RenderTarget creation
virtual RenderTarget *createRenderTarget(SwapChain *swapChain, bool depth);
virtual RenderTarget *createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth);
// Shader operations
virtual ShaderExecutable *loadExecutable(const void *function, size_t length, rx::ShaderType type);
virtual ShaderExecutable *compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, rx::ShaderType type);
// Image operations
virtual Image *createImage();
virtual void generateMipmap(Image *dest, Image *source);
virtual TextureStorage *createTextureStorage2D(SwapChain *swapChain);
virtual TextureStorage *createTextureStorage2D(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height);
virtual TextureStorage *createTextureStorageCube(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size);
// Buffer creation
virtual VertexBuffer *createVertexBuffer();
virtual IndexBuffer *createIndexBuffer();
virtual BufferStorage *createBufferStorage();
// Query and Fence creation
virtual QueryImpl *createQuery(GLenum type);
virtual FenceImpl *createFence();
// D3D9-renderer specific methods
bool boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest);
D3DPOOL getTexturePool(DWORD usage) const;
virtual bool getLUID(LUID *adapterLuid) const;
private:
DISALLOW_COPY_AND_ASSIGN(Renderer9);
void applyUniformnfv(gl::Uniform *targetUniform, const GLfloat *v);
void applyUniformniv(gl::Uniform *targetUniform, const GLint *v);
void applyUniformnbv(gl::Uniform *targetUniform, const GLint *v);
void drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer);
void drawIndexedPoints(GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer);
void getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray);
bool copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged);
gl::Renderbuffer *getNullColorbuffer(gl::Renderbuffer *depthbuffer);
D3DPOOL getBufferPool(DWORD usage) const;
HMODULE mD3d9Module;
HDC mDc;
void initializeDevice();
D3DPRESENT_PARAMETERS getDefaultPresentParameters();
void releaseDeviceResources();
UINT mAdapter;
D3DDEVTYPE mDeviceType;
bool mSoftwareDevice; // FIXME: Deprecate
IDirect3D9 *mD3d9; // Always valid after successful initialization.
IDirect3D9Ex *mD3d9Ex; // Might be null if D3D9Ex is not supported.
IDirect3DDevice9 *mDevice;
IDirect3DDevice9Ex *mDeviceEx; // Might be null if D3D9Ex is not supported.
Blit *mBlit;
HWND mDeviceWindow;
bool mDeviceLost;
D3DCAPS9 mDeviceCaps;
D3DADAPTER_IDENTIFIER9 mAdapterIdentifier;
D3DPRIMITIVETYPE mPrimitiveType;
int mPrimitiveCount;
GLsizei mRepeatDraw;
bool mSceneStarted;
bool mSupportsNonPower2Textures;
bool mSupportsTextureFilterAnisotropy;
int mMinSwapInterval;
int mMaxSwapInterval;
bool mOcclusionQuerySupport;
bool mEventQuerySupport;
bool mVertexTextureSupport;
bool mDepthTextureSupport;
bool mFloat32TextureSupport;
bool mFloat32FilterSupport;
bool mFloat32RenderSupport;
bool mFloat16TextureSupport;
bool mFloat16FilterSupport;
bool mFloat16RenderSupport;
bool mDXT1TextureSupport;
bool mDXT3TextureSupport;
bool mDXT5TextureSupport;
bool mLuminanceTextureSupport;
bool mLuminanceAlphaTextureSupport;
std::map<D3DFORMAT, bool *> mMultiSampleSupport;
GLsizei mMaxSupportedSamples;
// current render target states
unsigned int mAppliedRenderTargetSerial;
unsigned int mAppliedDepthbufferSerial;
unsigned int mAppliedStencilbufferSerial;
bool mDepthStencilInitialized;
bool mRenderTargetDescInitialized;
rx::RenderTarget::Desc mRenderTargetDesc;
unsigned int mCurStencilSize;
unsigned int mCurDepthSize;
IDirect3DStateBlock9 *mMaskedClearSavedState;
// previously set render states
bool mForceSetDepthStencilState;
gl::DepthStencilState mCurDepthStencilState;
int mCurStencilRef;
int mCurStencilBackRef;
bool mCurFrontFaceCCW;
bool mForceSetRasterState;
gl::RasterizerState mCurRasterState;
bool mForceSetScissor;
gl::Rectangle mCurScissor;
bool mScissorEnabled;
bool mForceSetViewport;
gl::Rectangle mCurViewport;
float mCurNear;
float mCurFar;
bool mForceSetBlendState;
gl::BlendState mCurBlendState;
gl::Color mCurBlendColor;
GLuint mCurSampleMask;
// Currently applied sampler states
bool mForceSetVertexSamplerStates[gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS];
gl::SamplerState mCurVertexSamplerStates[gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS];
bool mForceSetPixelSamplerStates[gl::MAX_TEXTURE_IMAGE_UNITS];
gl::SamplerState mCurPixelSamplerStates[gl::MAX_TEXTURE_IMAGE_UNITS];
// Currently applied textures
unsigned int mCurVertexTextureSerials[gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS];
unsigned int mCurPixelTextureSerials[gl::MAX_TEXTURE_IMAGE_UNITS];
unsigned int mAppliedIBSerial;
unsigned int mAppliedProgramBinarySerial;
rx::dx_VertexConstants mVertexConstants;
rx::dx_PixelConstants mPixelConstants;
bool mDxUniformsDirty;
// A pool of event queries that are currently unused.
std::vector<IDirect3DQuery9*> mEventQueryPool;
VertexShaderCache mVertexShaderCache;
PixelShaderCache mPixelShaderCache;
VertexDataManager *mVertexDataManager;
VertexDeclarationCache mVertexDeclarationCache;
IndexDataManager *mIndexDataManager;
StreamingIndexBufferInterface *mLineLoopIB;
enum { NUM_NULL_COLORBUFFER_CACHE_ENTRIES = 12 };
struct NullColorbufferCacheEntry
{
UINT lruCount;
int width;
int height;
gl::Renderbuffer *buffer;
} mNullColorbufferCache[NUM_NULL_COLORBUFFER_CACHE_ENTRIES];
UINT mMaxNullColorbufferLRU;
};
}
#endif // LIBGLESV2_RENDERER_RENDERER9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Renderer9.h | C++ | bsd | 13,756 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Image9.h: Defines the rx::Image9 class, which acts as the interface to
// the actual underlying surfaces of a Texture.
#ifndef LIBGLESV2_RENDERER_IMAGE9_H_
#define LIBGLESV2_RENDERER_IMAGE9_H_
#include "libGLESv2/renderer/Image.h"
#include "common/debug.h"
namespace gl
{
class Framebuffer;
}
namespace rx
{
class Renderer;
class Renderer9;
class TextureStorageInterface2D;
class TextureStorageInterfaceCube;
class Image9 : public Image
{
public:
Image9();
~Image9();
static Image9 *makeImage9(Image *img);
static void generateMipmap(Image9 *dest, Image9 *source);
static void generateMip(IDirect3DSurface9 *destSurface, IDirect3DSurface9 *sourceSurface);
static void copyLockableSurfaces(IDirect3DSurface9 *dest, IDirect3DSurface9 *source);
virtual bool redefine(Renderer *renderer, GLint internalformat, GLsizei width, GLsizei height, bool forceRelease);
virtual bool isRenderableFormat() const;
D3DFORMAT getD3DFormat() const;
virtual bool isDirty() const {return mSurface && mDirty;}
IDirect3DSurface9 *getSurface();
virtual void setManagedSurface(TextureStorageInterface2D *storage, int level);
virtual void setManagedSurface(TextureStorageInterfaceCube *storage, int face, int level);
virtual bool updateSurface(TextureStorageInterface2D *storage, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
virtual bool updateSurface(TextureStorageInterfaceCube *storage, int face, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
virtual void loadData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLint unpackAlignment, const void *input);
virtual void loadCompressedData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
const void *input);
virtual void copy(GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, gl::Framebuffer *source);
private:
DISALLOW_COPY_AND_ASSIGN(Image9);
void createSurface();
void setManagedSurface(IDirect3DSurface9 *surface);
bool updateSurface(IDirect3DSurface9 *dest, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
HRESULT lock(D3DLOCKED_RECT *lockedRect, const RECT *rect);
void unlock();
Renderer9 *mRenderer;
D3DPOOL mD3DPool; // can only be D3DPOOL_SYSTEMMEM or D3DPOOL_MANAGED since it needs to be lockable.
D3DFORMAT mD3DFormat;
IDirect3DSurface9 *mSurface;
};
}
#endif // LIBGLESV2_RENDERER_IMAGE9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Image9.h | C++ | bsd | 2,740 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexDataManager.h: Defines the VertexDataManager, a class that
// runs the Buffer translation process.
#ifndef LIBGLESV2_RENDERER_VERTEXDATAMANAGER_H_
#define LIBGLESV2_RENDERER_VERTEXDATAMANAGER_H_
#include "libGLESv2/Constants.h"
#include "common/angleutils.h"
namespace gl
{
class VertexAttribute;
class ProgramBinary;
}
namespace rx
{
class BufferStorage;
class StreamingVertexBufferInterface;
class VertexBuffer;
class Renderer;
struct TranslatedAttribute
{
bool active;
const gl::VertexAttribute *attribute;
UINT offset;
UINT stride; // 0 means not to advance the read pointer at all
VertexBuffer *vertexBuffer;
BufferStorage *storage;
unsigned int serial;
unsigned int divisor;
};
class VertexDataManager
{
public:
VertexDataManager(rx::Renderer *renderer);
virtual ~VertexDataManager();
GLenum prepareVertexData(const gl::VertexAttribute attribs[], gl::ProgramBinary *programBinary, GLint start, GLsizei count, TranslatedAttribute *outAttribs, GLsizei instances);
private:
DISALLOW_COPY_AND_ASSIGN(VertexDataManager);
rx::Renderer *const mRenderer;
StreamingVertexBufferInterface *mStreamingBuffer;
float mCurrentValue[gl::MAX_VERTEX_ATTRIBS][4];
StreamingVertexBufferInterface *mCurrentValueBuffer[gl::MAX_VERTEX_ATTRIBS];
std::size_t mCurrentValueOffsets[gl::MAX_VERTEX_ATTRIBS];
};
}
#endif // LIBGLESV2_RENDERER_VERTEXDATAMANAGER_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/VertexDataManager.h | C++ | bsd | 1,627 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// TextureStorage.h: Defines the abstract rx::TextureStorageInterface class and its concrete derived
// classes TextureStorageInterface2D and TextureStorageInterfaceCube, which act as the interface to the
// GPU-side texture.
#ifndef LIBGLESV2_RENDERER_TEXTURESTORAGE_H_
#define LIBGLESV2_RENDERER_TEXTURESTORAGE_H_
#include "common/debug.h"
namespace rx
{
class Renderer;
class SwapChain;
class RenderTarget;
class Blit;
class TextureStorage
{
public:
TextureStorage() {};
virtual ~TextureStorage() {};
virtual int getLodOffset() const = 0;
virtual bool isRenderTarget() const = 0;
virtual bool isManaged() const = 0;
virtual int levelCount() = 0;
virtual RenderTarget *getRenderTarget() = 0;
virtual RenderTarget *getRenderTarget(GLenum faceTarget) = 0;
virtual void generateMipmap(int level) = 0;
virtual void generateMipmap(int face, int level) = 0;
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorage);
};
class TextureStorageInterface
{
public:
TextureStorageInterface();
virtual ~TextureStorageInterface();
TextureStorage *getStorageInstance() { return mInstance; }
unsigned int getTextureSerial() const;
virtual unsigned int getRenderTargetSerial(GLenum target) const = 0;
virtual int getLodOffset() const;
virtual bool isRenderTarget() const;
virtual bool isManaged() const;
virtual int levelCount();
protected:
TextureStorage *mInstance;
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorageInterface);
const unsigned int mTextureSerial;
static unsigned int issueTextureSerial();
static unsigned int mCurrentTextureSerial;
};
class TextureStorageInterface2D : public TextureStorageInterface
{
public:
TextureStorageInterface2D(Renderer *renderer, SwapChain *swapchain);
TextureStorageInterface2D(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height);
virtual ~TextureStorageInterface2D();
void generateMipmap(int level);
RenderTarget *getRenderTarget() const;
virtual unsigned int getRenderTargetSerial(GLenum target) const;
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorageInterface2D);
const unsigned int mRenderTargetSerial;
};
class TextureStorageInterfaceCube : public TextureStorageInterface
{
public:
TextureStorageInterfaceCube(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size);
virtual ~TextureStorageInterfaceCube();
void generateMipmap(int face, int level);
RenderTarget *getRenderTarget(GLenum faceTarget) const;
virtual unsigned int getRenderTargetSerial(GLenum target) const;
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorageInterfaceCube);
const unsigned int mFirstRenderTargetSerial;
};
}
#endif // LIBGLESV2_RENDERER_TEXTURESTORAGE_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/TextureStorage.h | C++ | bsd | 3,064 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Image11.h: Implements the rx::Image11 class, which acts as the interface to
// the actual underlying resources of a Texture
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/renderer/Image11.h"
#include "libGLESv2/renderer/TextureStorage11.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/main.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/renderer/renderer11_utils.h"
#include "libGLESv2/renderer/generatemip.h"
namespace rx
{
Image11::Image11()
{
mStagingTexture = NULL;
mRenderer = NULL;
mDXGIFormat = DXGI_FORMAT_UNKNOWN;
}
Image11::~Image11()
{
if (mStagingTexture)
{
mStagingTexture->Release();
}
}
Image11 *Image11::makeImage11(Image *img)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::Image11*, img));
return static_cast<rx::Image11*>(img);
}
void Image11::generateMipmap(Image11 *dest, Image11 *src)
{
ASSERT(src->getDXGIFormat() == dest->getDXGIFormat());
ASSERT(src->getWidth() == 1 || src->getWidth() / 2 == dest->getWidth());
ASSERT(src->getHeight() == 1 || src->getHeight() / 2 == dest->getHeight());
D3D11_MAPPED_SUBRESOURCE destMapped, srcMapped;
dest->map(&destMapped);
src->map(&srcMapped);
const unsigned char *sourceData = reinterpret_cast<const unsigned char*>(srcMapped.pData);
unsigned char *destData = reinterpret_cast<unsigned char*>(destMapped.pData);
if (sourceData && destData)
{
switch (src->getDXGIFormat())
{
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_B8G8R8A8_UNORM:
GenerateMip<R8G8B8A8>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_A8_UNORM:
GenerateMip<A8>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R8_UNORM:
GenerateMip<R8>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
GenerateMip<A32B32G32R32F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R32G32B32_FLOAT:
GenerateMip<R32G32B32F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R16G16B16A16_FLOAT:
GenerateMip<A16B16G16R16F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R8G8_UNORM:
GenerateMip<R8G8>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R16_FLOAT:
GenerateMip<R16F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R16G16_FLOAT:
GenerateMip<R16G16F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R32_FLOAT:
GenerateMip<R32F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
case DXGI_FORMAT_R32G32_FLOAT:
GenerateMip<R32G32F>(src->getWidth(), src->getHeight(), sourceData, srcMapped.RowPitch, destData, destMapped.RowPitch);
break;
default:
UNREACHABLE();
break;
}
dest->unmap();
src->unmap();
}
dest->markDirty();
}
bool Image11::isDirty() const
{
return (mStagingTexture && mDirty);
}
bool Image11::updateSurface(TextureStorageInterface2D *storage, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height)
{
TextureStorage11_2D *storage11 = TextureStorage11_2D::makeTextureStorage11_2D(storage->getStorageInstance());
return storage11->updateSubresourceLevel(getStagingTexture(), getStagingSubresource(), level, 0, xoffset, yoffset, width, height);
}
bool Image11::updateSurface(TextureStorageInterfaceCube *storage, int face, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height)
{
TextureStorage11_Cube *storage11 = TextureStorage11_Cube::makeTextureStorage11_Cube(storage->getStorageInstance());
return storage11->updateSubresourceLevel(getStagingTexture(), getStagingSubresource(), level, face, xoffset, yoffset, width, height);
}
bool Image11::redefine(Renderer *renderer, GLint internalformat, GLsizei width, GLsizei height, bool forceRelease)
{
if (mWidth != width ||
mHeight != height ||
mInternalFormat != internalformat ||
forceRelease)
{
mRenderer = Renderer11::makeRenderer11(renderer);
mWidth = width;
mHeight = height;
mInternalFormat = internalformat;
// compute the d3d format that will be used
mDXGIFormat = gl_d3d11::ConvertTextureFormat(internalformat);
mActualFormat = d3d11_gl::ConvertTextureInternalFormat(mDXGIFormat);
if (mStagingTexture)
{
mStagingTexture->Release();
mStagingTexture = NULL;
}
return true;
}
return false;
}
bool Image11::isRenderableFormat() const
{
return TextureStorage11::IsTextureFormatRenderable(mDXGIFormat);
}
DXGI_FORMAT Image11::getDXGIFormat() const
{
// this should only happen if the image hasn't been redefined first
// which would be a bug by the caller
ASSERT(mDXGIFormat != DXGI_FORMAT_UNKNOWN);
return mDXGIFormat;
}
// Store the pixel rectangle designated by xoffset,yoffset,width,height with pixels stored as format/type at input
// into the target pixel rectangle.
void Image11::loadData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLint unpackAlignment, const void *input)
{
D3D11_MAPPED_SUBRESOURCE mappedImage;
HRESULT result = map(&mappedImage);
if (FAILED(result))
{
ERR("Could not map image for loading.");
return;
}
GLsizei inputPitch = gl::ComputePitch(width, mInternalFormat, unpackAlignment);
size_t pixelSize = d3d11::ComputePixelSizeBits(mDXGIFormat) / 8;
void* offsetMappedData = (void*)((BYTE *)mappedImage.pData + (yoffset * mappedImage.RowPitch + xoffset * pixelSize));
switch (mInternalFormat)
{
case GL_ALPHA8_EXT:
loadAlphaDataToNative(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_LUMINANCE8_EXT:
loadLuminanceDataToNativeOrBGRA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData, false);
break;
case GL_ALPHA32F_EXT:
loadAlphaFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_LUMINANCE32F_EXT:
loadLuminanceFloatDataToRGB(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_ALPHA16F_EXT:
loadAlphaHalfFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_LUMINANCE16F_EXT:
loadLuminanceHalfFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_LUMINANCE8_ALPHA8_EXT:
loadLuminanceAlphaDataToNativeOrBGRA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData, false);
break;
case GL_LUMINANCE_ALPHA32F_EXT:
loadLuminanceAlphaFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_LUMINANCE_ALPHA16F_EXT:
loadLuminanceAlphaHalfFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGB8_OES:
loadRGBUByteDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGB565:
loadRGB565DataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGBA8_OES:
loadRGBAUByteDataToNative(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGBA4:
loadRGBA4444DataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGB5_A1:
loadRGBA5551DataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_BGRA8_EXT:
loadBGRADataToBGRA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGB32F_EXT:
loadRGBFloatDataToNative(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGB16F_EXT:
loadRGBHalfFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGBA32F_EXT:
loadRGBAFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
case GL_RGBA16F_EXT:
loadRGBAHalfFloatDataToRGBA(width, height, inputPitch, input, mappedImage.RowPitch, offsetMappedData);
break;
default: UNREACHABLE();
}
unmap();
}
void Image11::loadCompressedData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
const void *input)
{
ASSERT(xoffset % 4 == 0);
ASSERT(yoffset % 4 == 0);
D3D11_MAPPED_SUBRESOURCE mappedImage;
HRESULT result = map(&mappedImage);
if (FAILED(result))
{
ERR("Could not map image for loading.");
return;
}
// Size computation assumes a 4x4 block compressed texture format
size_t blockSize = d3d11::ComputeBlockSizeBits(mDXGIFormat) / 8;
void* offsetMappedData = (void*)((BYTE *)mappedImage.pData + ((yoffset / 4) * mappedImage.RowPitch + (xoffset / 4) * blockSize));
GLsizei inputSize = gl::ComputeCompressedSize(width, height, mInternalFormat);
GLsizei inputPitch = gl::ComputeCompressedPitch(width, mInternalFormat);
int rows = inputSize / inputPitch;
for (int i = 0; i < rows; ++i)
{
memcpy((void*)((BYTE*)offsetMappedData + i * mappedImage.RowPitch), (void*)((BYTE*)input + i * inputPitch), inputPitch);
}
unmap();
}
void Image11::copy(GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, gl::Framebuffer *source)
{
gl::Renderbuffer *colorbuffer = source->getReadColorbuffer();
if (colorbuffer && colorbuffer->getActualFormat() == (GLuint)mActualFormat)
{
// No conversion needed-- use copyback fastpath
ID3D11Texture2D *colorBufferTexture = NULL;
unsigned int subresourceIndex = 0;
if (mRenderer->getRenderTargetResource(colorbuffer, &subresourceIndex, &colorBufferTexture))
{
D3D11_TEXTURE2D_DESC textureDesc;
colorBufferTexture->GetDesc(&textureDesc);
ID3D11Device *device = mRenderer->getDevice();
ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
ID3D11Texture2D* srcTex = NULL;
if (textureDesc.SampleDesc.Count > 1)
{
D3D11_TEXTURE2D_DESC resolveDesc;
resolveDesc.Width = textureDesc.Width;
resolveDesc.Height = textureDesc.Height;
resolveDesc.MipLevels = 1;
resolveDesc.ArraySize = 1;
resolveDesc.Format = textureDesc.Format;
resolveDesc.SampleDesc.Count = 1;
resolveDesc.SampleDesc.Quality = 0;
resolveDesc.Usage = D3D11_USAGE_DEFAULT;
resolveDesc.BindFlags = 0;
resolveDesc.CPUAccessFlags = 0;
resolveDesc.MiscFlags = 0;
HRESULT result = device->CreateTexture2D(&resolveDesc, NULL, &srcTex);
if (FAILED(result))
{
ERR("Failed to create resolve texture for Image11::copy, HRESULT: 0x%X.", result);
return;
}
deviceContext->ResolveSubresource(srcTex, 0, colorBufferTexture, subresourceIndex, textureDesc.Format);
subresourceIndex = 0;
}
else
{
srcTex = colorBufferTexture;
srcTex->AddRef();
}
D3D11_BOX srcBox;
srcBox.left = x;
srcBox.right = x + width;
srcBox.top = y;
srcBox.bottom = y + height;
srcBox.front = 0;
srcBox.back = 1;
deviceContext->CopySubresourceRegion(mStagingTexture, 0, xoffset, yoffset, 0, srcTex, subresourceIndex, &srcBox);
srcTex->Release();
colorBufferTexture->Release();
}
}
else
{
// This format requires conversion, so we must copy the texture to staging and manually convert via readPixels
D3D11_MAPPED_SUBRESOURCE mappedImage;
HRESULT result = map(&mappedImage);
// determine the offset coordinate into the destination buffer
GLsizei rowOffset = gl::ComputePixelSize(mActualFormat) * xoffset;
void *dataOffset = static_cast<unsigned char*>(mappedImage.pData) + mappedImage.RowPitch * yoffset + rowOffset;
mRenderer->readPixels(source, x, y, width, height, gl::ExtractFormat(mInternalFormat),
gl::ExtractType(mInternalFormat), mappedImage.RowPitch, false, 4, dataOffset);
unmap();
}
}
ID3D11Texture2D *Image11::getStagingTexture()
{
createStagingTexture();
return mStagingTexture;
}
unsigned int Image11::getStagingSubresource()
{
createStagingTexture();
return mStagingSubresource;
}
void Image11::createStagingTexture()
{
if (mStagingTexture)
{
return;
}
ID3D11Texture2D *newTexture = NULL;
int lodOffset = 1;
const DXGI_FORMAT dxgiFormat = getDXGIFormat();
ASSERT(!d3d11::IsDepthStencilFormat(dxgiFormat)); // We should never get here for depth textures
if (mWidth != 0 && mHeight != 0)
{
GLsizei width = mWidth;
GLsizei height = mHeight;
// adjust size if needed for compressed textures
gl::MakeValidSize(false, d3d11::IsCompressed(dxgiFormat), &width, &height, &lodOffset);
ID3D11Device *device = mRenderer->getDevice();
D3D11_TEXTURE2D_DESC desc;
desc.Width = width;
desc.Height = height;
desc.MipLevels = lodOffset + 1;
desc.ArraySize = 1;
desc.Format = dxgiFormat;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
HRESULT result = device->CreateTexture2D(&desc, NULL, &newTexture);
if (FAILED(result))
{
ASSERT(result == E_OUTOFMEMORY);
ERR("Creating image failed.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
mStagingTexture = newTexture;
mStagingSubresource = D3D11CalcSubresource(lodOffset, 0, lodOffset + 1);
mDirty = false;
}
HRESULT Image11::map(D3D11_MAPPED_SUBRESOURCE *map)
{
createStagingTexture();
HRESULT result = E_FAIL;
if (mStagingTexture)
{
ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
result = deviceContext->Map(mStagingTexture, mStagingSubresource, D3D11_MAP_WRITE, 0, map);
// this can fail if the device is removed (from TDR)
if (d3d11::isDeviceLostError(result))
{
mRenderer->notifyDeviceLost();
}
else if (SUCCEEDED(result))
{
mDirty = true;
}
}
return result;
}
void Image11::unmap()
{
if (mStagingTexture)
{
ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
deviceContext->Unmap(mStagingTexture, mStagingSubresource);
}
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/Image11.cpp | C++ | bsd | 16,601 |
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ShaderExecutable11.h: Defines a D3D11-specific class to contain shader
// executable implementation details.
#ifndef LIBGLESV2_RENDERER_SHADEREXECUTABLE11_H_
#define LIBGLESV2_RENDERER_SHADEREXECUTABLE11_H_
#include "libGLESv2/renderer/ShaderExecutable.h"
namespace rx
{
class ShaderExecutable11 : public ShaderExecutable
{
public:
ShaderExecutable11(const void *function, size_t length, ID3D11PixelShader *executable);
ShaderExecutable11(const void *function, size_t length, ID3D11VertexShader *executable);
ShaderExecutable11(const void *function, size_t length, ID3D11GeometryShader *executable);
virtual ~ShaderExecutable11();
static ShaderExecutable11 *makeShaderExecutable11(ShaderExecutable *executable);
ID3D11PixelShader *getPixelShader() const;
ID3D11VertexShader *getVertexShader() const;
ID3D11GeometryShader *getGeometryShader() const;
ID3D11Buffer *getConstantBuffer(ID3D11Device *device, unsigned int registerCount);
private:
DISALLOW_COPY_AND_ASSIGN(ShaderExecutable11);
ID3D11PixelShader *mPixelExecutable;
ID3D11VertexShader *mVertexExecutable;
ID3D11GeometryShader *mGeometryExecutable;
ID3D11Buffer *mConstantBuffer;
};
}
#endif // LIBGLESV2_RENDERER_SHADEREXECUTABLE11_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/ShaderExecutable11.h | C++ | bsd | 1,455 |
#include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Query9.cpp: Defines the rx::Query9 class which implements rx::QueryImpl.
#include "libGLESv2/renderer/Query9.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/renderer9_utils.h"
#include "libGLESv2/renderer/Renderer9.h"
namespace rx
{
Query9::Query9(rx::Renderer9 *renderer, GLenum type) : QueryImpl(type)
{
mRenderer = renderer;
mQuery = NULL;
}
Query9::~Query9()
{
if (mQuery)
{
mQuery->Release();
mQuery = NULL;
}
}
void Query9::begin()
{
if (mQuery == NULL)
{
if (FAILED(mRenderer->getDevice()->CreateQuery(D3DQUERYTYPE_OCCLUSION, &mQuery)))
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
HRESULT result = mQuery->Issue(D3DISSUE_BEGIN);
ASSERT(SUCCEEDED(result));
}
void Query9::end()
{
if (mQuery == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
HRESULT result = mQuery->Issue(D3DISSUE_END);
ASSERT(SUCCEEDED(result));
mStatus = GL_FALSE;
mResult = GL_FALSE;
}
GLuint Query9::getResult()
{
if (mQuery != NULL)
{
while (!testQuery())
{
Sleep(0);
// explicitly check for device loss
// some drivers seem to return S_FALSE even if the device is lost
// instead of D3DERR_DEVICELOST like they should
if (mRenderer->testDeviceLost(true))
{
return gl::error(GL_OUT_OF_MEMORY, 0);
}
}
}
return mResult;
}
GLboolean Query9::isResultAvailable()
{
if (mQuery != NULL)
{
testQuery();
}
return mStatus;
}
GLboolean Query9::testQuery()
{
if (mQuery != NULL && mStatus != GL_TRUE)
{
DWORD numPixels = 0;
HRESULT hres = mQuery->GetData(&numPixels, sizeof(DWORD), D3DGETDATA_FLUSH);
if (hres == S_OK)
{
mStatus = GL_TRUE;
switch (getType())
{
case GL_ANY_SAMPLES_PASSED_EXT:
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
mResult = (numPixels > 0) ? GL_TRUE : GL_FALSE;
break;
default:
ASSERT(false);
}
}
else if (d3d9::isDeviceLostError(hres))
{
mRenderer->notifyDeviceLost();
return gl::error(GL_OUT_OF_MEMORY, GL_TRUE);
}
return mStatus;
}
return GL_TRUE; // prevent blocking when query is null
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/Query9.cpp | C++ | bsd | 2,670 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// BufferStorage11.h Defines the BufferStorage11 class.
#ifndef LIBGLESV2_RENDERER_BUFFERSTORAGE11_H_
#define LIBGLESV2_RENDERER_BUFFERSTORAGE11_H_
#include "libGLESv2/renderer/BufferStorage.h"
namespace rx
{
class Renderer11;
class BufferStorage11 : public BufferStorage
{
public:
explicit BufferStorage11(Renderer11 *renderer);
virtual ~BufferStorage11();
static BufferStorage11 *makeBufferStorage11(BufferStorage *bufferStorage);
virtual void *getData();
virtual void setData(const void* data, unsigned int size, unsigned int offset);
virtual void clear();
virtual unsigned int getSize() const;
virtual bool supportsDirectBinding() const;
virtual void markBufferUsage();
ID3D11Buffer *getBuffer() const;
private:
Renderer11 *mRenderer;
ID3D11Buffer *mStagingBuffer;
unsigned int mStagingBufferSize;
ID3D11Buffer *mBuffer;
unsigned int mBufferSize;
unsigned int mSize;
void *mResolvedData;
unsigned int mResolvedDataSize;
bool mResolvedDataValid;
unsigned int mReadUsageCount;
unsigned int mWriteUsageCount;
};
}
#endif // LIBGLESV2_RENDERER_BUFFERSTORAGE11_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/BufferStorage11.h | C++ | bsd | 1,347 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ShaderCache: Defines rx::ShaderCache, a cache of Direct3D shader objects
// keyed by their byte code.
#ifndef LIBGLESV2_RENDERER_SHADER_CACHE_H_
#define LIBGLESV2_RENDERER_SHADER_CACHE_H_
#include "common/debug.h"
namespace rx
{
template <typename ShaderObject>
class ShaderCache
{
public:
ShaderCache() : mDevice(NULL)
{
}
~ShaderCache()
{
// Call clear while the device is still valid.
ASSERT(mMap.empty());
}
void initialize(IDirect3DDevice9* device)
{
mDevice = device;
}
ShaderObject *create(const DWORD *function, size_t length)
{
std::string key(reinterpret_cast<const char*>(function), length);
typename Map::iterator it = mMap.find(key);
if (it != mMap.end())
{
it->second->AddRef();
return it->second;
}
ShaderObject *shader;
HRESULT result = createShader(function, &shader);
if (FAILED(result))
{
return NULL;
}
// Random eviction policy.
if (mMap.size() >= kMaxMapSize)
{
mMap.begin()->second->Release();
mMap.erase(mMap.begin());
}
shader->AddRef();
mMap[key] = shader;
return shader;
}
void clear()
{
for (typename Map::iterator it = mMap.begin(); it != mMap.end(); ++it)
{
it->second->Release();
}
mMap.clear();
}
private:
DISALLOW_COPY_AND_ASSIGN(ShaderCache);
const static size_t kMaxMapSize = 100;
HRESULT createShader(const DWORD *function, IDirect3DVertexShader9 **shader)
{
return mDevice->CreateVertexShader(function, shader);
}
HRESULT createShader(const DWORD *function, IDirect3DPixelShader9 **shader)
{
return mDevice->CreatePixelShader(function, shader);
}
#ifndef HASH_MAP
# ifdef _MSC_VER
# define HASH_MAP stdext::hash_map
# else
# define HASH_MAP std::unordered_map
# endif
#endif
typedef HASH_MAP<std::string, ShaderObject*> Map;
Map mMap;
IDirect3DDevice9 *mDevice;
};
typedef ShaderCache<IDirect3DVertexShader9> VertexShaderCache;
typedef ShaderCache<IDirect3DPixelShader9> PixelShaderCache;
}
#endif // LIBGLESV2_RENDERER_SHADER_CACHE_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/ShaderCache.h | C++ | bsd | 2,471 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// renderer9_utils.h: Conversion functions and other utility routines
// specific to the D3D9 renderer
#ifndef LIBGLESV2_RENDERER_RENDERER9_UTILS_H
#define LIBGLESV2_RENDERER_RENDERER9_UTILS_H
#include "libGLESv2/utilities.h"
const D3DFORMAT D3DFMT_INTZ = ((D3DFORMAT)(MAKEFOURCC('I','N','T','Z')));
const D3DFORMAT D3DFMT_NULL = ((D3DFORMAT)(MAKEFOURCC('N','U','L','L')));
namespace gl_d3d9
{
D3DCMPFUNC ConvertComparison(GLenum comparison);
D3DCOLOR ConvertColor(gl::Color color);
D3DBLEND ConvertBlendFunc(GLenum blend);
D3DBLENDOP ConvertBlendOp(GLenum blendOp);
D3DSTENCILOP ConvertStencilOp(GLenum stencilOp);
D3DTEXTUREADDRESS ConvertTextureWrap(GLenum wrap);
D3DCULL ConvertCullMode(GLenum cullFace, GLenum frontFace);
D3DCUBEMAP_FACES ConvertCubeFace(GLenum cubeFace);
DWORD ConvertColorMask(bool red, bool green, bool blue, bool alpha);
D3DTEXTUREFILTERTYPE ConvertMagFilter(GLenum magFilter, float maxAnisotropy);
void ConvertMinFilter(GLenum minFilter, D3DTEXTUREFILTERTYPE *d3dMinFilter, D3DTEXTUREFILTERTYPE *d3dMipFilter, float maxAnisotropy);
D3DFORMAT ConvertRenderbufferFormat(GLenum format);
D3DMULTISAMPLE_TYPE GetMultisampleTypeFromSamples(GLsizei samples);
}
namespace d3d9_gl
{
GLuint GetAlphaSize(D3DFORMAT colorFormat);
GLuint GetStencilSize(D3DFORMAT stencilFormat);
GLsizei GetSamplesFromMultisampleType(D3DMULTISAMPLE_TYPE type);
bool IsFormatChannelEquivalent(D3DFORMAT d3dformat, GLenum format);
GLenum ConvertBackBufferFormat(D3DFORMAT format);
GLenum ConvertDepthStencilFormat(D3DFORMAT format);
GLenum ConvertRenderTargetFormat(D3DFORMAT format);
GLenum GetEquivalentFormat(D3DFORMAT format);
}
namespace d3d9
{
bool IsCompressedFormat(D3DFORMAT format);
size_t ComputeRowSize(D3DFORMAT format, unsigned int width);
inline bool isDeviceLostError(HRESULT errorCode)
{
switch (errorCode)
{
case D3DERR_DRIVERINTERNALERROR:
case D3DERR_DEVICELOST:
case D3DERR_DEVICEHUNG:
case D3DERR_DEVICEREMOVED:
return true;
default:
return false;
}
}
}
#endif // LIBGLESV2_RENDERER_RENDERER9_UTILS_H
| 010smithzhang-ddd | src/libGLESv2/renderer/renderer9_utils.h | C++ | bsd | 2,278 |
#include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// VertexBuffer11.cpp: Defines the D3D11 VertexBuffer implementation.
#include "libGLESv2/renderer/VertexBuffer11.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/Context.h"
namespace rx
{
VertexBuffer11::VertexBuffer11(rx::Renderer11 *const renderer) : mRenderer(renderer)
{
mBuffer = NULL;
mBufferSize = 0;
mDynamicUsage = false;
}
VertexBuffer11::~VertexBuffer11()
{
if (mBuffer)
{
mBuffer->Release();
mBuffer = NULL;
}
}
bool VertexBuffer11::initialize(unsigned int size, bool dynamicUsage)
{
if (mBuffer)
{
mBuffer->Release();
mBuffer = NULL;
}
updateSerial();
if (size > 0)
{
ID3D11Device* dxDevice = mRenderer->getDevice();
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = size;
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
HRESULT result = dxDevice->CreateBuffer(&bufferDesc, NULL, &mBuffer);
if (FAILED(result))
{
return false;
}
}
mBufferSize = size;
mDynamicUsage = dynamicUsage;
return true;
}
VertexBuffer11 *VertexBuffer11::makeVertexBuffer11(VertexBuffer *vetexBuffer)
{
ASSERT(HAS_DYNAMIC_TYPE(VertexBuffer11*, vetexBuffer));
return static_cast<VertexBuffer11*>(vetexBuffer);
}
bool VertexBuffer11::storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count,
GLsizei instances, unsigned int offset)
{
if (mBuffer)
{
gl::Buffer *buffer = attrib.mBoundBuffer.get();
int inputStride = attrib.stride();
const VertexConverter &converter = getVertexConversion(attrib);
ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();
D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT result = dxContext->Map(mBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedResource);
if (FAILED(result))
{
ERR("Vertex buffer map failed with error 0x%08x", result);
return false;
}
char* output = reinterpret_cast<char*>(mappedResource.pData) + offset;
const char *input = NULL;
if (buffer)
{
BufferStorage *storage = buffer->getStorage();
input = static_cast<const char*>(storage->getData()) + static_cast<int>(attrib.mOffset);
}
else
{
input = static_cast<const char*>(attrib.mPointer);
}
if (instances == 0 || attrib.mDivisor == 0)
{
input += inputStride * start;
}
converter.conversionFunc(input, inputStride, count, output);
dxContext->Unmap(mBuffer, 0);
return true;
}
else
{
ERR("Vertex buffer not initialized.");
return false;
}
}
bool VertexBuffer11::storeRawData(const void* data, unsigned int size, unsigned int offset)
{
if (mBuffer)
{
ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();
D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT result = dxContext->Map(mBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedResource);
if (FAILED(result))
{
ERR("Vertex buffer map failed with error 0x%08x", result);
return false;
}
char* bufferData = static_cast<char*>(mappedResource.pData);
memcpy(bufferData + offset, data, size);
dxContext->Unmap(mBuffer, 0);
return true;
}
else
{
ERR("Vertex buffer not initialized.");
return false;
}
}
unsigned int VertexBuffer11::getSpaceRequired(const gl::VertexAttribute &attrib, GLsizei count,
GLsizei instances) const
{
unsigned int elementSize = getVertexConversion(attrib).outputElementSize;
if (instances == 0 || attrib.mDivisor == 0)
{
return elementSize * count;
}
else
{
return elementSize * ((instances + attrib.mDivisor - 1) / attrib.mDivisor);
}
}
bool VertexBuffer11::requiresConversion(const gl::VertexAttribute &attrib) const
{
return !getVertexConversion(attrib).identity;
}
unsigned int VertexBuffer11::getBufferSize() const
{
return mBufferSize;
}
bool VertexBuffer11::setBufferSize(unsigned int size)
{
if (size > mBufferSize)
{
return initialize(size, mDynamicUsage);
}
else
{
return true;
}
}
bool VertexBuffer11::discard()
{
if (mBuffer)
{
ID3D11DeviceContext *dxContext = mRenderer->getDeviceContext();
D3D11_MAPPED_SUBRESOURCE mappedResource;
HRESULT result = dxContext->Map(mBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
ERR("Vertex buffer map failed with error 0x%08x", result);
return false;
}
dxContext->Unmap(mBuffer, 0);
return true;
}
else
{
ERR("Vertex buffer not initialized.");
return false;
}
}
unsigned int VertexBuffer11::getVertexSize(const gl::VertexAttribute &attrib) const
{
return getVertexConversion(attrib).outputElementSize;
}
DXGI_FORMAT VertexBuffer11::getDXGIFormat(const gl::VertexAttribute &attrib) const
{
return getVertexConversion(attrib).dxgiFormat;
}
ID3D11Buffer *VertexBuffer11::getBuffer() const
{
return mBuffer;
}
template <typename T, unsigned int componentCount, bool widen, bool normalized>
static void copyVertexData(const void *input, unsigned int stride, unsigned int count, void *output)
{
unsigned int attribSize = sizeof(T) * componentCount;
if (attribSize == stride && !widen)
{
memcpy(output, input, count * attribSize);
}
else
{
unsigned int outputStride = widen ? 4 : componentCount;
T defaultVal = normalized ? std::numeric_limits<T>::max() : T(1);
for (unsigned int i = 0; i < count; i++)
{
const T *offsetInput = reinterpret_cast<const T*>(reinterpret_cast<const char*>(input) + i * stride);
T *offsetOutput = reinterpret_cast<T*>(output) + i * outputStride;
for (unsigned int j = 0; j < componentCount; j++)
{
offsetOutput[j] = offsetInput[j];
}
if (widen)
{
offsetOutput[3] = defaultVal;
}
}
}
}
template <unsigned int componentCount>
static void copyFixedVertexData(const void* input, unsigned int stride, unsigned int count, void* output)
{
static const float divisor = 1.0f / (1 << 16);
for (unsigned int i = 0; i < count; i++)
{
const GLfixed* offsetInput = reinterpret_cast<const GLfixed*>(reinterpret_cast<const char*>(input) + stride * i);
float* offsetOutput = reinterpret_cast<float*>(output) + i * componentCount;
for (unsigned int j = 0; j < componentCount; j++)
{
offsetOutput[j] = static_cast<float>(offsetInput[j]) * divisor;
}
}
}
template <typename T, unsigned int componentCount, bool normalized>
static void copyToFloatVertexData(const void* input, unsigned int stride, unsigned int count, void* output)
{
typedef std::numeric_limits<T> NL;
for (unsigned int i = 0; i < count; i++)
{
const T *offsetInput = reinterpret_cast<const T*>(reinterpret_cast<const char*>(input) + stride * i);
float *offsetOutput = reinterpret_cast<float*>(output) + i * componentCount;
for (unsigned int j = 0; j < componentCount; j++)
{
if (normalized)
{
if (NL::is_signed)
{
const float divisor = 1.0f / (2 * static_cast<float>(NL::max()) + 1);
offsetOutput[j] = (2 * static_cast<float>(offsetInput[j]) + 1) * divisor;
}
else
{
offsetOutput[j] = static_cast<float>(offsetInput[j]) / NL::max();
}
}
else
{
offsetOutput[j] = static_cast<float>(offsetInput[j]);
}
}
}
}
const VertexBuffer11::VertexConverter VertexBuffer11::mPossibleTranslations[NUM_GL_VERTEX_ATTRIB_TYPES][2][4] =
{
{ // GL_BYTE
{ // unnormalized
{ ©ToFloatVertexData<GLbyte, 1, false>, false, DXGI_FORMAT_R32_FLOAT, 4 },
{ ©ToFloatVertexData<GLbyte, 2, false>, false, DXGI_FORMAT_R32G32_FLOAT, 8 },
{ ©ToFloatVertexData<GLbyte, 3, false>, false, DXGI_FORMAT_R32G32B32_FLOAT, 12 },
{ ©ToFloatVertexData<GLbyte, 4, false>, false, DXGI_FORMAT_R32G32B32A32_FLOAT, 16 },
},
{ // normalized
{ ©VertexData<GLbyte, 1, false, true>, true, DXGI_FORMAT_R8_SNORM, 1 },
{ ©VertexData<GLbyte, 2, false, true>, true, DXGI_FORMAT_R8G8_SNORM, 2 },
{ ©VertexData<GLbyte, 3, true, true>, false, DXGI_FORMAT_R8G8B8A8_SNORM, 4 },
{ ©VertexData<GLbyte, 4, false, true>, true, DXGI_FORMAT_R8G8B8A8_SNORM, 4 },
},
},
{ // GL_UNSIGNED_BYTE
{ // unnormalized
{ ©ToFloatVertexData<GLubyte, 1, false>, false, DXGI_FORMAT_R32_FLOAT, 4 },
{ ©ToFloatVertexData<GLubyte, 2, false>, false, DXGI_FORMAT_R32G32_FLOAT, 8 },
{ ©ToFloatVertexData<GLubyte, 3, false>, false, DXGI_FORMAT_R32G32B32_FLOAT, 12 },
{ ©ToFloatVertexData<GLubyte, 4, false>, false, DXGI_FORMAT_R32G32B32A32_FLOAT, 16 },
},
{ // normalized
{ ©VertexData<GLubyte, 1, false, true>, true, DXGI_FORMAT_R8_UNORM, 1 },
{ ©VertexData<GLubyte, 2, false, true>, true, DXGI_FORMAT_R8G8_UNORM, 2 },
{ ©VertexData<GLubyte, 3, true, true>, false, DXGI_FORMAT_R8G8B8A8_UNORM, 4 },
{ ©VertexData<GLubyte, 4, false, true>, true, DXGI_FORMAT_R8G8B8A8_UNORM, 4 },
},
},
{ // GL_SHORT
{ // unnormalized
{ ©ToFloatVertexData<GLshort, 1, false>, false, DXGI_FORMAT_R32_FLOAT, 4 },
{ ©ToFloatVertexData<GLshort, 2, false>, false, DXGI_FORMAT_R32G32_FLOAT, 8 },
{ ©ToFloatVertexData<GLshort, 3, false>, false, DXGI_FORMAT_R32G32B32_FLOAT, 12 },
{ ©ToFloatVertexData<GLshort, 4, false>, false, DXGI_FORMAT_R32G32B32A32_FLOAT, 16 },
},
{ // normalized
{ ©VertexData<GLshort, 1, false, true>, true, DXGI_FORMAT_R16_SNORM, 2 },
{ ©VertexData<GLshort, 2, false, true>, true, DXGI_FORMAT_R16G16_SNORM, 4 },
{ ©VertexData<GLshort, 3, true, true>, false, DXGI_FORMAT_R16G16B16A16_SNORM, 8 },
{ ©VertexData<GLshort, 4, false, true>, true, DXGI_FORMAT_R16G16B16A16_SNORM, 8 },
},
},
{ // GL_UNSIGNED_SHORT
{ // unnormalized
{ ©ToFloatVertexData<GLushort, 1, false>, false, DXGI_FORMAT_R32_FLOAT, 4 },
{ ©ToFloatVertexData<GLushort, 2, false>, false, DXGI_FORMAT_R32G32_FLOAT, 8 },
{ ©ToFloatVertexData<GLushort, 3, false>, false, DXGI_FORMAT_R32G32B32_FLOAT, 12 },
{ ©ToFloatVertexData<GLushort, 4, false>, false, DXGI_FORMAT_R32G32B32A32_FLOAT, 16 },
},
{ // normalized
{ ©VertexData<GLushort, 1, false, true>, true, DXGI_FORMAT_R16_UNORM, 2 },
{ ©VertexData<GLushort, 2, false, true>, true, DXGI_FORMAT_R16G16_UNORM, 4 },
{ ©VertexData<GLushort, 3, true, true>, false, DXGI_FORMAT_R16G16B16A16_UNORM, 8 },
{ ©VertexData<GLushort, 4, false, true>, true, DXGI_FORMAT_R16G16B16A16_UNORM, 8 },
},
},
{ // GL_FIXED
{ // unnormalized
{ ©FixedVertexData<1>, false, DXGI_FORMAT_R32_FLOAT, 4 },
{ ©FixedVertexData<2>, false, DXGI_FORMAT_R32G32_FLOAT, 8 },
{ ©FixedVertexData<3>, false, DXGI_FORMAT_R32G32B32_FLOAT, 12 },
{ ©FixedVertexData<4>, false, DXGI_FORMAT_R32G32B32A32_FLOAT, 16 },
},
{ // normalized
{ ©FixedVertexData<1>, false, DXGI_FORMAT_R32_FLOAT, 4 },
{ ©FixedVertexData<2>, false, DXGI_FORMAT_R32G32_FLOAT, 8 },
{ ©FixedVertexData<3>, false, DXGI_FORMAT_R32G32B32_FLOAT, 12 },
{ ©FixedVertexData<4>, false, DXGI_FORMAT_R32G32B32A32_FLOAT, 16 },
},
},
{ // GL_FLOAT
{ // unnormalized
{ ©VertexData<GLfloat, 1, false, false>, true, DXGI_FORMAT_R32_FLOAT, 4 },
{ ©VertexData<GLfloat, 2, false, false>, true, DXGI_FORMAT_R32G32_FLOAT, 8 },
{ ©VertexData<GLfloat, 3, false, false>, true, DXGI_FORMAT_R32G32B32_FLOAT, 12 },
{ ©VertexData<GLfloat, 4, false, false>, true, DXGI_FORMAT_R32G32B32A32_FLOAT, 16 },
},
{ // normalized
{ ©VertexData<GLfloat, 1, false, false>, true, DXGI_FORMAT_R32_FLOAT, 4 },
{ ©VertexData<GLfloat, 2, false, false>, true, DXGI_FORMAT_R32G32_FLOAT, 8 },
{ ©VertexData<GLfloat, 3, false, false>, true, DXGI_FORMAT_R32G32B32_FLOAT, 12 },
{ ©VertexData<GLfloat, 4, false, false>, true, DXGI_FORMAT_R32G32B32A32_FLOAT, 16 },
},
},
};
const VertexBuffer11::VertexConverter &VertexBuffer11::getVertexConversion(const gl::VertexAttribute &attribute)
{
unsigned int typeIndex = 0;
switch (attribute.mType)
{
case GL_BYTE: typeIndex = 0; break;
case GL_UNSIGNED_BYTE: typeIndex = 1; break;
case GL_SHORT: typeIndex = 2; break;
case GL_UNSIGNED_SHORT: typeIndex = 3; break;
case GL_FIXED: typeIndex = 4; break;
case GL_FLOAT: typeIndex = 5; break;
default: UNREACHABLE(); break;
}
return mPossibleTranslations[typeIndex][attribute.mNormalized ? 1 : 0][attribute.mSize - 1];
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/VertexBuffer11.cpp | C++ | bsd | 14,448 |
#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Renderer11.cpp: Implements a back-end specific class for the D3D11 renderer.
#include "libGLESv2/main.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/RenderBuffer.h"
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/renderer/RenderTarget11.h"
#include "libGLESv2/renderer/renderer11_utils.h"
#include "libGLESv2/renderer/ShaderExecutable11.h"
#include "libGLESv2/renderer/SwapChain11.h"
#include "libGLESv2/renderer/Image11.h"
#include "libGLESv2/renderer/VertexBuffer11.h"
#include "libGLESv2/renderer/IndexBuffer11.h"
#include "libGLESv2/renderer/BufferStorage11.h"
#include "libGLESv2/renderer/VertexDataManager.h"
#include "libGLESv2/renderer/IndexDataManager.h"
#include "libGLESv2/renderer/TextureStorage11.h"
#include "libGLESv2/renderer/Query11.h"
#include "libGLESv2/renderer/Fence11.h"
#include "libGLESv2/renderer/shaders/compiled/passthrough11vs.h"
#include "libGLESv2/renderer/shaders/compiled/passthroughrgba11ps.h"
#include "libGLESv2/renderer/shaders/compiled/passthroughrgb11ps.h"
#include "libGLESv2/renderer/shaders/compiled/passthroughlum11ps.h"
#include "libGLESv2/renderer/shaders/compiled/passthroughlumalpha11ps.h"
#include "libGLESv2/renderer/shaders/compiled/clear11vs.h"
#include "libGLESv2/renderer/shaders/compiled/clearsingle11ps.h"
#include "libGLESv2/renderer/shaders/compiled/clearmultiple11ps.h"
#include "libEGL/Display.h"
#ifdef _DEBUG
// this flag enables suppressing some spurious warnings that pop up in certain WebGL samples
// and conformance tests. to enable all warnings, remove this define.
#define ANGLE_SUPPRESS_D3D11_HAZARD_WARNINGS 1
#endif
namespace rx
{
static const DXGI_FORMAT RenderTargetFormats[] =
{
DXGI_FORMAT_B8G8R8A8_UNORM,
DXGI_FORMAT_R8G8B8A8_UNORM
};
static const DXGI_FORMAT DepthStencilFormats[] =
{
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_D24_UNORM_S8_UINT,
DXGI_FORMAT_D16_UNORM
};
enum
{
MAX_TEXTURE_IMAGE_UNITS_VTF_SM4 = 16
};
Renderer11::Renderer11(egl::Display *display, HDC hDc) : Renderer(display), mDc(hDc)
{
mVertexDataManager = NULL;
mIndexDataManager = NULL;
mLineLoopIB = NULL;
mTriangleFanIB = NULL;
mCopyResourcesInitialized = false;
mCopyVB = NULL;
mCopySampler = NULL;
mCopyIL = NULL;
mCopyVS = NULL;
mCopyRGBAPS = NULL;
mCopyRGBPS = NULL;
mCopyLumPS = NULL;
mCopyLumAlphaPS = NULL;
mClearResourcesInitialized = false;
mClearVB = NULL;
mClearIL = NULL;
mClearVS = NULL;
mClearSinglePS = NULL;
mClearMultiplePS = NULL;
mClearScissorRS = NULL;
mClearNoScissorRS = NULL;
mSyncQuery = NULL;
mD3d11Module = NULL;
mDxgiModule = NULL;
mDeviceLost = false;
mMaxSupportedSamples = 0;
mDevice = NULL;
mDeviceContext = NULL;
mDxgiAdapter = NULL;
mDxgiFactory = NULL;
mDriverConstantBufferVS = NULL;
mDriverConstantBufferPS = NULL;
mBGRATextureSupport = false;
mIsGeometryShaderActive = false;
}
Renderer11::~Renderer11()
{
release();
}
Renderer11 *Renderer11::makeRenderer11(Renderer *renderer)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::Renderer11*, renderer));
return static_cast<rx::Renderer11*>(renderer);
}
#ifndef __d3d11_1_h__
#define D3D11_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET ((D3D11_MESSAGE_ID)3146081)
#endif
EGLint Renderer11::initialize()
{
if (!initializeCompiler())
{
return EGL_NOT_INITIALIZED;
}
mDxgiModule = LoadLibrary(TEXT("dxgi.dll"));
mD3d11Module = LoadLibrary(TEXT("d3d11.dll"));
if (mD3d11Module == NULL || mDxgiModule == NULL)
{
ERR("Could not load D3D11 or DXGI library - aborting!\n");
return EGL_NOT_INITIALIZED;
}
// create the D3D11 device
ASSERT(mDevice == NULL);
PFN_D3D11_CREATE_DEVICE D3D11CreateDevice = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(mD3d11Module, "D3D11CreateDevice");
if (D3D11CreateDevice == NULL)
{
ERR("Could not retrieve D3D11CreateDevice address - aborting!\n");
return EGL_NOT_INITIALIZED;
}
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
HRESULT result = S_OK;
#ifdef _DEBUG
result = D3D11CreateDevice(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
D3D11_CREATE_DEVICE_DEBUG,
featureLevels,
ArraySize(featureLevels),
D3D11_SDK_VERSION,
&mDevice,
&mFeatureLevel,
&mDeviceContext);
if (!mDevice || FAILED(result))
{
ERR("Failed creating Debug D3D11 device - falling back to release runtime.\n");
}
if (!mDevice || FAILED(result))
#endif
{
result = D3D11CreateDevice(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
0,
featureLevels,
ArraySize(featureLevels),
D3D11_SDK_VERSION,
&mDevice,
&mFeatureLevel,
&mDeviceContext);
if (!mDevice || FAILED(result))
{
ERR("Could not create D3D11 device - aborting!\n");
return EGL_NOT_INITIALIZED; // Cleanup done by destructor through glDestroyRenderer
}
}
IDXGIDevice *dxgiDevice = NULL;
result = mDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);
if (FAILED(result))
{
ERR("Could not query DXGI device - aborting!\n");
return EGL_NOT_INITIALIZED;
}
result = dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&mDxgiAdapter);
if (FAILED(result))
{
ERR("Could not retrieve DXGI adapter - aborting!\n");
return EGL_NOT_INITIALIZED;
}
dxgiDevice->Release();
mDxgiAdapter->GetDesc(&mAdapterDescription);
memset(mDescription, 0, sizeof(mDescription));
wcstombs(mDescription, mAdapterDescription.Description, sizeof(mDescription) - 1);
result = mDxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&mDxgiFactory);
if (!mDxgiFactory || FAILED(result))
{
ERR("Could not create DXGI factory - aborting!\n");
return EGL_NOT_INITIALIZED;
}
// Disable some spurious D3D11 debug warnings to prevent them from flooding the output log
#if defined(ANGLE_SUPPRESS_D3D11_HAZARD_WARNINGS) && defined(_DEBUG)
ID3D11InfoQueue *infoQueue;
result = mDevice->QueryInterface(__uuidof(ID3D11InfoQueue), (void **)&infoQueue);
if (SUCCEEDED(result))
{
D3D11_MESSAGE_ID hideMessages[] =
{
D3D11_MESSAGE_ID_DEVICE_OMSETRENDERTARGETS_HAZARD,
D3D11_MESSAGE_ID_DEVICE_PSSETSHADERRESOURCES_HAZARD,
D3D11_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET
};
D3D11_INFO_QUEUE_FILTER filter = {0};
filter.DenyList.NumIDs = ArraySize(hideMessages);
filter.DenyList.pIDList = hideMessages;
infoQueue->AddStorageFilterEntries(&filter);
infoQueue->Release();
}
#endif
unsigned int maxSupportedSamples = 0;
unsigned int rtFormatCount = ArraySize(RenderTargetFormats);
unsigned int dsFormatCount = ArraySize(DepthStencilFormats);
for (unsigned int i = 0; i < rtFormatCount + dsFormatCount; ++i)
{
DXGI_FORMAT format = (i < rtFormatCount) ? RenderTargetFormats[i] : DepthStencilFormats[i - rtFormatCount];
if (format != DXGI_FORMAT_UNKNOWN)
{
UINT formatSupport;
result = mDevice->CheckFormatSupport(format, &formatSupport);
if (SUCCEEDED(result) && (formatSupport & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET))
{
MultisampleSupportInfo supportInfo;
for (unsigned int j = 1; j <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; j++)
{
result = mDevice->CheckMultisampleQualityLevels(format, j, &supportInfo.qualityLevels[j - 1]);
if (SUCCEEDED(result) && supportInfo.qualityLevels[j - 1] > 0)
{
maxSupportedSamples = std::max(j, maxSupportedSamples);
}
else
{
supportInfo.qualityLevels[j - 1] = 0;
}
}
mMultisampleSupportMap.insert(std::make_pair(format, supportInfo));
}
}
}
mMaxSupportedSamples = maxSupportedSamples;
initializeDevice();
// BGRA texture support is optional in feature levels 10 and 10_1
UINT formatSupport;
result = mDevice->CheckFormatSupport(DXGI_FORMAT_B8G8R8A8_UNORM, &formatSupport);
if (FAILED(result))
{
ERR("Error checking BGRA format support: 0x%08X", result);
}
else
{
const int flags = (D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_RENDER_TARGET);
mBGRATextureSupport = (formatSupport & flags) == flags;
}
// Check floating point texture support
static const unsigned int requiredTextureFlags = D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_TEXTURECUBE;
static const unsigned int requiredRenderableFlags = D3D11_FORMAT_SUPPORT_RENDER_TARGET;
static const unsigned int requiredFilterFlags = D3D11_FORMAT_SUPPORT_SHADER_SAMPLE;
DXGI_FORMAT float16Formats[] =
{
DXGI_FORMAT_R16_FLOAT,
DXGI_FORMAT_R16G16_FLOAT,
DXGI_FORMAT_R16G16B16A16_FLOAT,
};
DXGI_FORMAT float32Formats[] =
{
DXGI_FORMAT_R32_FLOAT,
DXGI_FORMAT_R32G32_FLOAT,
DXGI_FORMAT_R32G32B32_FLOAT,
DXGI_FORMAT_R32G32B32A32_FLOAT,
};
mFloat16TextureSupport = true;
mFloat16FilterSupport = true;
mFloat16RenderSupport = true;
for (unsigned int i = 0; i < ArraySize(float16Formats); i++)
{
if (SUCCEEDED(mDevice->CheckFormatSupport(float16Formats[i], &formatSupport)))
{
mFloat16TextureSupport = mFloat16TextureSupport && (formatSupport & requiredTextureFlags) == requiredTextureFlags;
mFloat16FilterSupport = mFloat16FilterSupport && (formatSupport & requiredFilterFlags) == requiredFilterFlags;
mFloat16RenderSupport = mFloat16RenderSupport && (formatSupport & requiredRenderableFlags) == requiredRenderableFlags;
}
else
{
mFloat16TextureSupport = false;
mFloat16RenderSupport = false;
mFloat16FilterSupport = false;
}
}
mFloat32TextureSupport = true;
mFloat32FilterSupport = true;
mFloat32RenderSupport = true;
for (unsigned int i = 0; i < ArraySize(float32Formats); i++)
{
if (SUCCEEDED(mDevice->CheckFormatSupport(float32Formats[i], &formatSupport)))
{
mFloat32TextureSupport = mFloat32TextureSupport && (formatSupport & requiredTextureFlags) == requiredTextureFlags;
mFloat32FilterSupport = mFloat32FilterSupport && (formatSupport & requiredFilterFlags) == requiredFilterFlags;
mFloat32RenderSupport = mFloat32RenderSupport && (formatSupport & requiredRenderableFlags) == requiredRenderableFlags;
}
else
{
mFloat32TextureSupport = false;
mFloat32FilterSupport = false;
mFloat32RenderSupport = false;
}
}
// Check compressed texture support
const unsigned int requiredCompressedTextureFlags = D3D11_FORMAT_SUPPORT_TEXTURE2D;
if (SUCCEEDED(mDevice->CheckFormatSupport(DXGI_FORMAT_BC1_UNORM, &formatSupport)))
{
mDXT1TextureSupport = (formatSupport & requiredCompressedTextureFlags) == requiredCompressedTextureFlags;
}
else
{
mDXT1TextureSupport = false;
}
if (SUCCEEDED(mDevice->CheckFormatSupport(DXGI_FORMAT_BC3_UNORM, &formatSupport)))
{
mDXT3TextureSupport = (formatSupport & requiredCompressedTextureFlags) == requiredCompressedTextureFlags;
}
else
{
mDXT3TextureSupport = false;
}
if (SUCCEEDED(mDevice->CheckFormatSupport(DXGI_FORMAT_BC5_UNORM, &formatSupport)))
{
mDXT5TextureSupport = (formatSupport & requiredCompressedTextureFlags) == requiredCompressedTextureFlags;
}
else
{
mDXT5TextureSupport = false;
}
// Check depth texture support
DXGI_FORMAT depthTextureFormats[] =
{
DXGI_FORMAT_D16_UNORM,
DXGI_FORMAT_D24_UNORM_S8_UINT,
};
static const unsigned int requiredDepthTextureFlags = D3D11_FORMAT_SUPPORT_DEPTH_STENCIL |
D3D11_FORMAT_SUPPORT_TEXTURE2D;
mDepthTextureSupport = true;
for (unsigned int i = 0; i < ArraySize(depthTextureFormats); i++)
{
if (SUCCEEDED(mDevice->CheckFormatSupport(depthTextureFormats[i], &formatSupport)))
{
mDepthTextureSupport = mDepthTextureSupport && ((formatSupport & requiredDepthTextureFlags) == requiredDepthTextureFlags);
}
else
{
mDepthTextureSupport = false;
}
}
return EGL_SUCCESS;
}
// do any one-time device initialization
// NOTE: this is also needed after a device lost/reset
// to reset the scene status and ensure the default states are reset.
void Renderer11::initializeDevice()
{
mStateCache.initialize(mDevice);
mInputLayoutCache.initialize(mDevice, mDeviceContext);
ASSERT(!mVertexDataManager && !mIndexDataManager);
mVertexDataManager = new VertexDataManager(this);
mIndexDataManager = new IndexDataManager(this);
markAllStateDirty();
}
int Renderer11::generateConfigs(ConfigDesc **configDescList)
{
unsigned int numRenderFormats = ArraySize(RenderTargetFormats);
unsigned int numDepthFormats = ArraySize(DepthStencilFormats);
(*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
int numConfigs = 0;
for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
{
for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
{
DXGI_FORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
UINT formatSupport = 0;
HRESULT result = mDevice->CheckFormatSupport(renderTargetFormat, &formatSupport);
if (SUCCEEDED(result) && (formatSupport & D3D11_FORMAT_SUPPORT_RENDER_TARGET))
{
DXGI_FORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
bool depthStencilFormatOK = true;
if (depthStencilFormat != DXGI_FORMAT_UNKNOWN)
{
UINT formatSupport = 0;
result = mDevice->CheckFormatSupport(depthStencilFormat, &formatSupport);
depthStencilFormatOK = SUCCEEDED(result) && (formatSupport & D3D11_FORMAT_SUPPORT_DEPTH_STENCIL);
}
if (depthStencilFormatOK)
{
ConfigDesc newConfig;
newConfig.renderTargetFormat = d3d11_gl::ConvertBackBufferFormat(renderTargetFormat);
newConfig.depthStencilFormat = d3d11_gl::ConvertDepthStencilFormat(depthStencilFormat);
newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
newConfig.fastConfig = true; // Assume all DX11 format conversions to be fast
(*configDescList)[numConfigs++] = newConfig;
}
}
}
}
return numConfigs;
}
void Renderer11::deleteConfigs(ConfigDesc *configDescList)
{
delete [] (configDescList);
}
void Renderer11::sync(bool block)
{
if (block)
{
HRESULT result;
if (!mSyncQuery)
{
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_EVENT;
queryDesc.MiscFlags = 0;
result = mDevice->CreateQuery(&queryDesc, &mSyncQuery);
ASSERT(SUCCEEDED(result));
}
mDeviceContext->End(mSyncQuery);
mDeviceContext->Flush();
do
{
result = mDeviceContext->GetData(mSyncQuery, NULL, 0, D3D11_ASYNC_GETDATA_DONOTFLUSH);
// Keep polling, but allow other threads to do something useful first
Sleep(0);
if (testDeviceLost(true))
{
return;
}
}
while (result == S_FALSE);
}
else
{
mDeviceContext->Flush();
}
}
SwapChain *Renderer11::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
{
return new rx::SwapChain11(this, window, shareHandle, backBufferFormat, depthBufferFormat);
}
void Renderer11::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
{
if (type == gl::SAMPLER_PIXEL)
{
if (index < 0 || index >= gl::MAX_TEXTURE_IMAGE_UNITS)
{
ERR("Pixel shader sampler index %i is not valid.", index);
return;
}
if (mForceSetPixelSamplerStates[index] || memcmp(&samplerState, &mCurPixelSamplerStates[index], sizeof(gl::SamplerState)) != 0)
{
ID3D11SamplerState *dxSamplerState = mStateCache.getSamplerState(samplerState);
if (!dxSamplerState)
{
ERR("NULL sampler state returned by RenderStateCache::getSamplerState, setting the default"
"sampler state for pixel shaders at slot %i.", index);
}
mDeviceContext->PSSetSamplers(index, 1, &dxSamplerState);
mCurPixelSamplerStates[index] = samplerState;
}
mForceSetPixelSamplerStates[index] = false;
}
else if (type == gl::SAMPLER_VERTEX)
{
if (index < 0 || index >= (int)getMaxVertexTextureImageUnits())
{
ERR("Vertex shader sampler index %i is not valid.", index);
return;
}
if (mForceSetVertexSamplerStates[index] || memcmp(&samplerState, &mCurVertexSamplerStates[index], sizeof(gl::SamplerState)) != 0)
{
ID3D11SamplerState *dxSamplerState = mStateCache.getSamplerState(samplerState);
if (!dxSamplerState)
{
ERR("NULL sampler state returned by RenderStateCache::getSamplerState, setting the default"
"sampler state for vertex shaders at slot %i.", index);
}
mDeviceContext->VSSetSamplers(index, 1, &dxSamplerState);
mCurVertexSamplerStates[index] = samplerState;
}
mForceSetVertexSamplerStates[index] = false;
}
else UNREACHABLE();
}
void Renderer11::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
{
ID3D11ShaderResourceView *textureSRV = NULL;
unsigned int serial = 0;
bool forceSetTexture = false;
if (texture)
{
TextureStorageInterface *texStorage = texture->getNativeTexture();
if (texStorage)
{
TextureStorage11 *storage11 = TextureStorage11::makeTextureStorage11(texStorage->getStorageInstance());
textureSRV = storage11->getSRV();
}
// If we get NULL back from getSRV here, something went wrong in the texture class and we're unexpectedly
// missing the shader resource view
ASSERT(textureSRV != NULL);
serial = texture->getTextureSerial();
forceSetTexture = texture->hasDirtyImages();
}
if (type == gl::SAMPLER_PIXEL)
{
if (index < 0 || index >= gl::MAX_TEXTURE_IMAGE_UNITS)
{
ERR("Pixel shader sampler index %i is not valid.", index);
return;
}
if (forceSetTexture || mCurPixelTextureSerials[index] != serial)
{
mDeviceContext->PSSetShaderResources(index, 1, &textureSRV);
}
mCurPixelTextureSerials[index] = serial;
}
else if (type == gl::SAMPLER_VERTEX)
{
if (index < 0 || index >= (int)getMaxVertexTextureImageUnits())
{
ERR("Vertex shader sampler index %i is not valid.", index);
return;
}
if (forceSetTexture || mCurVertexTextureSerials[index] != serial)
{
mDeviceContext->VSSetShaderResources(index, 1, &textureSRV);
}
mCurVertexTextureSerials[index] = serial;
}
else UNREACHABLE();
}
void Renderer11::setRasterizerState(const gl::RasterizerState &rasterState)
{
if (mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0)
{
ID3D11RasterizerState *dxRasterState = mStateCache.getRasterizerState(rasterState, mScissorEnabled,
mCurDepthSize);
if (!dxRasterState)
{
ERR("NULL rasterizer state returned by RenderStateCache::getRasterizerState, setting the default"
"rasterizer state.");
}
mDeviceContext->RSSetState(dxRasterState);
mCurRasterState = rasterState;
}
mForceSetRasterState = false;
}
void Renderer11::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor,
unsigned int sampleMask)
{
if (mForceSetBlendState ||
memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0 ||
memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0 ||
sampleMask != mCurSampleMask)
{
ID3D11BlendState *dxBlendState = mStateCache.getBlendState(blendState);
if (!dxBlendState)
{
ERR("NULL blend state returned by RenderStateCache::getBlendState, setting the default "
"blend state.");
}
float blendColors[4] = {0.0f};
if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
{
blendColors[0] = blendColor.red;
blendColors[1] = blendColor.green;
blendColors[2] = blendColor.blue;
blendColors[3] = blendColor.alpha;
}
else
{
blendColors[0] = blendColor.alpha;
blendColors[1] = blendColor.alpha;
blendColors[2] = blendColor.alpha;
blendColors[3] = blendColor.alpha;
}
mDeviceContext->OMSetBlendState(dxBlendState, blendColors, sampleMask);
mCurBlendState = blendState;
mCurBlendColor = blendColor;
mCurSampleMask = sampleMask;
}
mForceSetBlendState = false;
}
void Renderer11::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
int stencilBackRef, bool frontFaceCCW)
{
if (mForceSetDepthStencilState ||
memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0 ||
stencilRef != mCurStencilRef || stencilBackRef != mCurStencilBackRef)
{
if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
stencilRef != stencilBackRef ||
depthStencilState.stencilMask != depthStencilState.stencilBackMask)
{
ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are "
"invalid under WebGL.");
return gl::error(GL_INVALID_OPERATION);
}
ID3D11DepthStencilState *dxDepthStencilState = mStateCache.getDepthStencilState(depthStencilState);
if (!dxDepthStencilState)
{
ERR("NULL depth stencil state returned by RenderStateCache::getDepthStencilState, "
"setting the default depth stencil state.");
}
mDeviceContext->OMSetDepthStencilState(dxDepthStencilState, static_cast<UINT>(stencilRef));
mCurDepthStencilState = depthStencilState;
mCurStencilRef = stencilRef;
mCurStencilBackRef = stencilBackRef;
}
mForceSetDepthStencilState = false;
}
void Renderer11::setScissorRectangle(const gl::Rectangle &scissor, bool enabled)
{
if (mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0 ||
enabled != mScissorEnabled)
{
if (enabled)
{
D3D11_RECT rect;
rect.left = std::max(0, scissor.x);
rect.top = std::max(0, scissor.y);
rect.right = scissor.x + std::max(0, scissor.width);
rect.bottom = scissor.y + std::max(0, scissor.height);
mDeviceContext->RSSetScissorRects(1, &rect);
}
if (enabled != mScissorEnabled)
{
mForceSetRasterState = true;
}
mCurScissor = scissor;
mScissorEnabled = enabled;
}
mForceSetScissor = false;
}
bool Renderer11::setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
bool ignoreViewport)
{
gl::Rectangle actualViewport = viewport;
float actualZNear = gl::clamp01(zNear);
float actualZFar = gl::clamp01(zFar);
if (ignoreViewport)
{
actualViewport.x = 0;
actualViewport.y = 0;
actualViewport.width = mRenderTargetDesc.width;
actualViewport.height = mRenderTargetDesc.height;
actualZNear = 0.0f;
actualZFar = 1.0f;
}
// Get D3D viewport bounds, which depends on the feature level
const Range& viewportBounds = getViewportBounds();
// Clamp width and height first to the gl maximum, then clamp further if we extend past the D3D maximum bounds
D3D11_VIEWPORT dxViewport;
dxViewport.TopLeftX = gl::clamp(actualViewport.x, viewportBounds.start, viewportBounds.end);
dxViewport.TopLeftY = gl::clamp(actualViewport.y, viewportBounds.start, viewportBounds.end);
dxViewport.Width = gl::clamp(actualViewport.width, 0, getMaxViewportDimension());
dxViewport.Height = gl::clamp(actualViewport.height, 0, getMaxViewportDimension());
dxViewport.Width = std::min((int)dxViewport.Width, viewportBounds.end - static_cast<int>(dxViewport.TopLeftX));
dxViewport.Height = std::min((int)dxViewport.Height, viewportBounds.end - static_cast<int>(dxViewport.TopLeftY));
dxViewport.MinDepth = actualZNear;
dxViewport.MaxDepth = actualZFar;
if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
{
return false; // Nothing to render
}
bool viewportChanged = mForceSetViewport || memcmp(&actualViewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
actualZNear != mCurNear || actualZFar != mCurFar;
if (viewportChanged)
{
mDeviceContext->RSSetViewports(1, &dxViewport);
mCurViewport = actualViewport;
mCurNear = actualZNear;
mCurFar = actualZFar;
mPixelConstants.viewCoords[0] = actualViewport.width * 0.5f;
mPixelConstants.viewCoords[1] = actualViewport.height * 0.5f;
mPixelConstants.viewCoords[2] = actualViewport.x + (actualViewport.width * 0.5f);
mPixelConstants.viewCoords[3] = actualViewport.y + (actualViewport.height * 0.5f);
mPixelConstants.depthFront[0] = (actualZFar - actualZNear) * 0.5f;
mPixelConstants.depthFront[1] = (actualZNear + actualZFar) * 0.5f;
mVertexConstants.depthRange[0] = actualZNear;
mVertexConstants.depthRange[1] = actualZFar;
mVertexConstants.depthRange[2] = actualZFar - actualZNear;
mPixelConstants.depthRange[0] = actualZNear;
mPixelConstants.depthRange[1] = actualZFar;
mPixelConstants.depthRange[2] = actualZFar - actualZNear;
}
mForceSetViewport = false;
return true;
}
bool Renderer11::applyPrimitiveType(GLenum mode, GLsizei count)
{
D3D11_PRIMITIVE_TOPOLOGY primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
switch (mode)
{
case GL_POINTS: primitiveTopology = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; break;
case GL_LINES: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_LINELIST; break;
case GL_LINE_LOOP: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; break;
case GL_LINE_STRIP: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; break;
case GL_TRIANGLES: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break;
case GL_TRIANGLE_STRIP: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; break;
// emulate fans via rewriting index buffer
case GL_TRIANGLE_FAN: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break;
default:
return gl::error(GL_INVALID_ENUM, false);
}
mDeviceContext->IASetPrimitiveTopology(primitiveTopology);
return count > 0;
}
bool Renderer11::applyRenderTarget(gl::Framebuffer *framebuffer)
{
// Get the color render buffer and serial
// Also extract the render target dimensions and view
unsigned int renderTargetWidth = 0;
unsigned int renderTargetHeight = 0;
GLenum renderTargetFormat = 0;
unsigned int renderTargetSerials[gl::IMPLEMENTATION_MAX_DRAW_BUFFERS] = {0};
ID3D11RenderTargetView* framebufferRTVs[gl::IMPLEMENTATION_MAX_DRAW_BUFFERS] = {NULL};
bool missingColorRenderTarget = true;
for (unsigned int colorAttachment = 0; colorAttachment < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
const GLenum drawBufferState = framebuffer->getDrawBufferState(colorAttachment);
if (framebuffer->getColorbufferType(colorAttachment) != GL_NONE && drawBufferState != GL_NONE)
{
// the draw buffer must be either "none", "back" for the default buffer or the same index as this color (in order)
ASSERT(drawBufferState == GL_BACK || drawBufferState == (GL_COLOR_ATTACHMENT0_EXT + colorAttachment));
gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer(colorAttachment);
if (!colorbuffer)
{
ERR("render target pointer unexpectedly null.");
return false;
}
// check for zero-sized default framebuffer, which is a special case.
// in this case we do not wish to modify any state and just silently return false.
// this will not report any gl error but will cause the calling method to return.
if (colorbuffer->getWidth() == 0 || colorbuffer->getHeight() == 0)
{
return false;
}
renderTargetSerials[colorAttachment] = colorbuffer->getSerial();
// Extract the render target dimensions and view
RenderTarget11 *renderTarget = RenderTarget11::makeRenderTarget11(colorbuffer->getRenderTarget());
if (!renderTarget)
{
ERR("render target pointer unexpectedly null.");
return false;
}
framebufferRTVs[colorAttachment] = renderTarget->getRenderTargetView();
if (!framebufferRTVs[colorAttachment])
{
ERR("render target view pointer unexpectedly null.");
return false;
}
if (missingColorRenderTarget)
{
renderTargetWidth = colorbuffer->getWidth();
renderTargetHeight = colorbuffer->getHeight();
renderTargetFormat = colorbuffer->getActualFormat();
missingColorRenderTarget = false;
}
}
}
// Get the depth stencil render buffer and serials
gl::Renderbuffer *depthStencil = NULL;
unsigned int depthbufferSerial = 0;
unsigned int stencilbufferSerial = 0;
if (framebuffer->getDepthbufferType() != GL_NONE)
{
depthStencil = framebuffer->getDepthbuffer();
if (!depthStencil)
{
ERR("Depth stencil pointer unexpectedly null.");
SafeRelease(framebufferRTVs);
return false;
}
depthbufferSerial = depthStencil->getSerial();
}
else if (framebuffer->getStencilbufferType() != GL_NONE)
{
depthStencil = framebuffer->getStencilbuffer();
if (!depthStencil)
{
ERR("Depth stencil pointer unexpectedly null.");
SafeRelease(framebufferRTVs);
return false;
}
stencilbufferSerial = depthStencil->getSerial();
}
// Extract the depth stencil sizes and view
unsigned int depthSize = 0;
unsigned int stencilSize = 0;
ID3D11DepthStencilView* framebufferDSV = NULL;
if (depthStencil)
{
RenderTarget11 *depthStencilRenderTarget = RenderTarget11::makeRenderTarget11(depthStencil->getDepthStencil());
if (!depthStencilRenderTarget)
{
ERR("render target pointer unexpectedly null.");
SafeRelease(framebufferRTVs);
return false;
}
framebufferDSV = depthStencilRenderTarget->getDepthStencilView();
if (!framebufferDSV)
{
ERR("depth stencil view pointer unexpectedly null.");
SafeRelease(framebufferRTVs);
return false;
}
// If there is no render buffer, the width, height and format values come from
// the depth stencil
if (missingColorRenderTarget)
{
renderTargetWidth = depthStencil->getWidth();
renderTargetHeight = depthStencil->getHeight();
renderTargetFormat = depthStencil->getActualFormat();
}
depthSize = depthStencil->getDepthSize();
stencilSize = depthStencil->getStencilSize();
}
// Apply the render target and depth stencil
if (!mRenderTargetDescInitialized || !mDepthStencilInitialized ||
memcmp(renderTargetSerials, mAppliedRenderTargetSerials, sizeof(renderTargetSerials)) != 0 ||
depthbufferSerial != mAppliedDepthbufferSerial ||
stencilbufferSerial != mAppliedStencilbufferSerial)
{
mDeviceContext->OMSetRenderTargets(getMaxRenderTargets(), framebufferRTVs, framebufferDSV);
mRenderTargetDesc.width = renderTargetWidth;
mRenderTargetDesc.height = renderTargetHeight;
mRenderTargetDesc.format = renderTargetFormat;
mForceSetViewport = true;
mForceSetScissor = true;
if (!mDepthStencilInitialized || depthSize != mCurDepthSize)
{
mCurDepthSize = depthSize;
mForceSetRasterState = true;
}
mCurStencilSize = stencilSize;
for (unsigned int rtIndex = 0; rtIndex < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; rtIndex++)
{
mAppliedRenderTargetSerials[rtIndex] = renderTargetSerials[rtIndex];
}
mAppliedDepthbufferSerial = depthbufferSerial;
mAppliedStencilbufferSerial = stencilbufferSerial;
mRenderTargetDescInitialized = true;
mDepthStencilInitialized = true;
}
SafeRelease(framebufferRTVs);
SafeRelease(framebufferDSV);
return true;
}
GLenum Renderer11::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
{
TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
if (err != GL_NO_ERROR)
{
return err;
}
return mInputLayoutCache.applyVertexBuffers(attributes, programBinary);
}
GLenum Renderer11::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
{
GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo);
if (err == GL_NO_ERROR)
{
if (indexInfo->storage)
{
if (indexInfo->serial != mAppliedStorageIBSerial || indexInfo->startOffset != mAppliedIBOffset)
{
BufferStorage11 *storage = BufferStorage11::makeBufferStorage11(indexInfo->storage);
IndexBuffer11* indexBuffer = IndexBuffer11::makeIndexBuffer11(indexInfo->indexBuffer);
mDeviceContext->IASetIndexBuffer(storage->getBuffer(), indexBuffer->getIndexFormat(), indexInfo->startOffset);
mAppliedIBSerial = 0;
mAppliedStorageIBSerial = storage->getSerial();
mAppliedIBOffset = indexInfo->startOffset;
}
}
else if (indexInfo->serial != mAppliedIBSerial || indexInfo->startOffset != mAppliedIBOffset)
{
IndexBuffer11* indexBuffer = IndexBuffer11::makeIndexBuffer11(indexInfo->indexBuffer);
mDeviceContext->IASetIndexBuffer(indexBuffer->getBuffer(), indexBuffer->getIndexFormat(), indexInfo->startOffset);
mAppliedIBSerial = indexInfo->serial;
mAppliedStorageIBSerial = 0;
mAppliedIBOffset = indexInfo->startOffset;
}
}
return err;
}
void Renderer11::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
{
if (mode == GL_LINE_LOOP)
{
drawLineLoop(count, GL_NONE, NULL, 0, NULL);
}
else if (mode == GL_TRIANGLE_FAN)
{
drawTriangleFan(count, GL_NONE, NULL, 0, NULL, instances);
}
else if (instances > 0)
{
mDeviceContext->DrawInstanced(count, instances, 0, 0);
}
else
{
mDeviceContext->Draw(count, 0);
}
}
void Renderer11::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const TranslatedIndexData &indexInfo, GLsizei instances)
{
if (mode == GL_LINE_LOOP)
{
drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
}
else if (mode == GL_TRIANGLE_FAN)
{
drawTriangleFan(count, type, indices, indexInfo.minIndex, elementArrayBuffer, instances);
}
else if (instances > 0)
{
mDeviceContext->DrawIndexedInstanced(count, instances, 0, -static_cast<int>(indexInfo.minIndex), 0);
}
else
{
mDeviceContext->DrawIndexed(count, 0, -static_cast<int>(indexInfo.minIndex));
}
}
void Renderer11::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
{
// Get the raw indices for an indexed draw
if (type != GL_NONE && elementArrayBuffer)
{
gl::Buffer *indexBuffer = elementArrayBuffer;
BufferStorage *storage = indexBuffer->getStorage();
intptr_t offset = reinterpret_cast<intptr_t>(indices);
indices = static_cast<const GLubyte*>(storage->getData()) + offset;
}
if (!mLineLoopIB)
{
mLineLoopIB = new StreamingIndexBufferInterface(this);
if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
{
delete mLineLoopIB;
mLineLoopIB = NULL;
ERR("Could not create a 32-bit looping index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
const int spaceNeeded = (count + 1) * sizeof(unsigned int);
if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT))
{
ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
void* mappedMemory = NULL;
int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
if (offset == -1 || mappedMemory == NULL)
{
ERR("Could not map index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
unsigned int indexBufferOffset = static_cast<unsigned int>(offset);
switch (type)
{
case GL_NONE: // Non-indexed draw
for (int i = 0; i < count; i++)
{
data[i] = i;
}
data[count] = 0;
break;
case GL_UNSIGNED_BYTE:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLubyte*>(indices)[i];
}
data[count] = static_cast<const GLubyte*>(indices)[0];
break;
case GL_UNSIGNED_SHORT:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLushort*>(indices)[i];
}
data[count] = static_cast<const GLushort*>(indices)[0];
break;
case GL_UNSIGNED_INT:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLuint*>(indices)[i];
}
data[count] = static_cast<const GLuint*>(indices)[0];
break;
default: UNREACHABLE();
}
if (!mLineLoopIB->unmapBuffer())
{
ERR("Could not unmap index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
if (mAppliedIBSerial != mLineLoopIB->getSerial() || mAppliedIBOffset != indexBufferOffset)
{
IndexBuffer11 *indexBuffer = IndexBuffer11::makeIndexBuffer11(mLineLoopIB->getIndexBuffer());
mDeviceContext->IASetIndexBuffer(indexBuffer->getBuffer(), indexBuffer->getIndexFormat(), indexBufferOffset);
mAppliedIBSerial = mLineLoopIB->getSerial();
mAppliedStorageIBSerial = 0;
mAppliedIBOffset = indexBufferOffset;
}
mDeviceContext->DrawIndexed(count + 1, 0, -minIndex);
}
void Renderer11::drawTriangleFan(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer, int instances)
{
// Get the raw indices for an indexed draw
if (type != GL_NONE && elementArrayBuffer)
{
gl::Buffer *indexBuffer = elementArrayBuffer;
BufferStorage *storage = indexBuffer->getStorage();
intptr_t offset = reinterpret_cast<intptr_t>(indices);
indices = static_cast<const GLubyte*>(storage->getData()) + offset;
}
if (!mTriangleFanIB)
{
mTriangleFanIB = new StreamingIndexBufferInterface(this);
if (!mTriangleFanIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
{
delete mTriangleFanIB;
mTriangleFanIB = NULL;
ERR("Could not create a scratch index buffer for GL_TRIANGLE_FAN.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
const int numTris = count - 2;
const int spaceNeeded = (numTris * 3) * sizeof(unsigned int);
if (!mTriangleFanIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT))
{
ERR("Could not reserve enough space in scratch index buffer for GL_TRIANGLE_FAN.");
return gl::error(GL_OUT_OF_MEMORY);
}
void* mappedMemory = NULL;
int offset = mTriangleFanIB->mapBuffer(spaceNeeded, &mappedMemory);
if (offset == -1 || mappedMemory == NULL)
{
ERR("Could not map scratch index buffer for GL_TRIANGLE_FAN.");
return gl::error(GL_OUT_OF_MEMORY);
}
unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
unsigned int indexBufferOffset = static_cast<unsigned int>(offset);
switch (type)
{
case GL_NONE: // Non-indexed draw
for (int i = 0; i < numTris; i++)
{
data[i*3 + 0] = 0;
data[i*3 + 1] = i + 1;
data[i*3 + 2] = i + 2;
}
break;
case GL_UNSIGNED_BYTE:
for (int i = 0; i < numTris; i++)
{
data[i*3 + 0] = static_cast<const GLubyte*>(indices)[0];
data[i*3 + 1] = static_cast<const GLubyte*>(indices)[i + 1];
data[i*3 + 2] = static_cast<const GLubyte*>(indices)[i + 2];
}
break;
case GL_UNSIGNED_SHORT:
for (int i = 0; i < numTris; i++)
{
data[i*3 + 0] = static_cast<const GLushort*>(indices)[0];
data[i*3 + 1] = static_cast<const GLushort*>(indices)[i + 1];
data[i*3 + 2] = static_cast<const GLushort*>(indices)[i + 2];
}
break;
case GL_UNSIGNED_INT:
for (int i = 0; i < numTris; i++)
{
data[i*3 + 0] = static_cast<const GLuint*>(indices)[0];
data[i*3 + 1] = static_cast<const GLuint*>(indices)[i + 1];
data[i*3 + 2] = static_cast<const GLuint*>(indices)[i + 2];
}
break;
default: UNREACHABLE();
}
if (!mTriangleFanIB->unmapBuffer())
{
ERR("Could not unmap scratch index buffer for GL_TRIANGLE_FAN.");
return gl::error(GL_OUT_OF_MEMORY);
}
if (mAppliedIBSerial != mTriangleFanIB->getSerial() || mAppliedIBOffset != indexBufferOffset)
{
IndexBuffer11 *indexBuffer = IndexBuffer11::makeIndexBuffer11(mTriangleFanIB->getIndexBuffer());
mDeviceContext->IASetIndexBuffer(indexBuffer->getBuffer(), indexBuffer->getIndexFormat(), indexBufferOffset);
mAppliedIBSerial = mTriangleFanIB->getSerial();
mAppliedStorageIBSerial = 0;
mAppliedIBOffset = indexBufferOffset;
}
if (instances > 0)
{
mDeviceContext->DrawIndexedInstanced(numTris * 3, instances, 0, -minIndex, 0);
}
else
{
mDeviceContext->DrawIndexed(numTris * 3, 0, -minIndex);
}
}
void Renderer11::applyShaders(gl::ProgramBinary *programBinary)
{
unsigned int programBinarySerial = programBinary->getSerial();
const bool updateProgramState = (programBinarySerial != mAppliedProgramBinarySerial);
if (updateProgramState)
{
ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
ID3D11VertexShader *vertexShader = NULL;
if (vertexExe) vertexShader = ShaderExecutable11::makeShaderExecutable11(vertexExe)->getVertexShader();
ID3D11PixelShader *pixelShader = NULL;
if (pixelExe) pixelShader = ShaderExecutable11::makeShaderExecutable11(pixelExe)->getPixelShader();
mDeviceContext->PSSetShader(pixelShader, NULL, 0);
mDeviceContext->VSSetShader(vertexShader, NULL, 0);
programBinary->dirtyAllUniforms();
mAppliedProgramBinarySerial = programBinarySerial;
}
// Only use the geometry shader currently for point sprite drawing
const bool usesGeometryShader = (programBinary->usesGeometryShader() && mCurRasterState.pointDrawMode);
if (updateProgramState || usesGeometryShader != mIsGeometryShaderActive)
{
if (usesGeometryShader)
{
ShaderExecutable *geometryExe = programBinary->getGeometryExecutable();
ID3D11GeometryShader *geometryShader = ShaderExecutable11::makeShaderExecutable11(geometryExe)->getGeometryShader();
mDeviceContext->GSSetShader(geometryShader, NULL, 0);
}
else
{
mDeviceContext->GSSetShader(NULL, NULL, 0);
}
mIsGeometryShaderActive = usesGeometryShader;
}
}
void Renderer11::applyUniforms(gl::ProgramBinary *programBinary, gl::UniformArray *uniformArray)
{
ShaderExecutable11 *vertexExecutable = ShaderExecutable11::makeShaderExecutable11(programBinary->getVertexExecutable());
ShaderExecutable11 *pixelExecutable = ShaderExecutable11::makeShaderExecutable11(programBinary->getPixelExecutable());
unsigned int totalRegisterCountVS = 0;
unsigned int totalRegisterCountPS = 0;
bool vertexUniformsDirty = false;
bool pixelUniformsDirty = false;
for (gl::UniformArray::const_iterator uniform_iterator = uniformArray->begin(); uniform_iterator != uniformArray->end(); uniform_iterator++)
{
const gl::Uniform *uniform = *uniform_iterator;
if (uniform->vsRegisterIndex >= 0)
{
totalRegisterCountVS += uniform->registerCount;
vertexUniformsDirty = vertexUniformsDirty || uniform->dirty;
}
if (uniform->psRegisterIndex >= 0)
{
totalRegisterCountPS += uniform->registerCount;
pixelUniformsDirty = pixelUniformsDirty || uniform->dirty;
}
}
ID3D11Buffer *vertexConstantBuffer = vertexExecutable->getConstantBuffer(mDevice, totalRegisterCountVS);
ID3D11Buffer *pixelConstantBuffer = pixelExecutable->getConstantBuffer(mDevice, totalRegisterCountPS);
float (*mapVS)[4] = NULL;
float (*mapPS)[4] = NULL;
if (totalRegisterCountVS > 0 && vertexUniformsDirty)
{
D3D11_MAPPED_SUBRESOURCE map = {0};
HRESULT result = mDeviceContext->Map(vertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
ASSERT(SUCCEEDED(result));
mapVS = (float(*)[4])map.pData;
}
if (totalRegisterCountPS > 0 && pixelUniformsDirty)
{
D3D11_MAPPED_SUBRESOURCE map = {0};
HRESULT result = mDeviceContext->Map(pixelConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
ASSERT(SUCCEEDED(result));
mapPS = (float(*)[4])map.pData;
}
for (gl::UniformArray::iterator uniform_iterator = uniformArray->begin(); uniform_iterator != uniformArray->end(); uniform_iterator++)
{
gl::Uniform *uniform = *uniform_iterator;
if (uniform->type != GL_SAMPLER_2D && uniform->type != GL_SAMPLER_CUBE)
{
if (uniform->vsRegisterIndex >= 0 && mapVS)
{
memcpy(mapVS + uniform->vsRegisterIndex, uniform->data, uniform->registerCount * sizeof(float[4]));
}
if (uniform->psRegisterIndex >= 0 && mapPS)
{
memcpy(mapPS + uniform->psRegisterIndex, uniform->data, uniform->registerCount * sizeof(float[4]));
}
}
uniform->dirty = false;
}
if (mapVS)
{
mDeviceContext->Unmap(vertexConstantBuffer, 0);
}
if (mapPS)
{
mDeviceContext->Unmap(pixelConstantBuffer, 0);
}
mDeviceContext->VSSetConstantBuffers(0, 1, &vertexConstantBuffer);
mDeviceContext->PSSetConstantBuffers(0, 1, &pixelConstantBuffer);
// Driver uniforms
if (!mDriverConstantBufferVS)
{
D3D11_BUFFER_DESC constantBufferDescription = {0};
constantBufferDescription.ByteWidth = sizeof(dx_VertexConstants);
constantBufferDescription.Usage = D3D11_USAGE_DEFAULT;
constantBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constantBufferDescription.CPUAccessFlags = 0;
constantBufferDescription.MiscFlags = 0;
constantBufferDescription.StructureByteStride = 0;
HRESULT result = mDevice->CreateBuffer(&constantBufferDescription, NULL, &mDriverConstantBufferVS);
ASSERT(SUCCEEDED(result));
mDeviceContext->VSSetConstantBuffers(1, 1, &mDriverConstantBufferVS);
}
if (!mDriverConstantBufferPS)
{
D3D11_BUFFER_DESC constantBufferDescription = {0};
constantBufferDescription.ByteWidth = sizeof(dx_PixelConstants);
constantBufferDescription.Usage = D3D11_USAGE_DEFAULT;
constantBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constantBufferDescription.CPUAccessFlags = 0;
constantBufferDescription.MiscFlags = 0;
constantBufferDescription.StructureByteStride = 0;
HRESULT result = mDevice->CreateBuffer(&constantBufferDescription, NULL, &mDriverConstantBufferPS);
ASSERT(SUCCEEDED(result));
mDeviceContext->PSSetConstantBuffers(1, 1, &mDriverConstantBufferPS);
}
if (memcmp(&mVertexConstants, &mAppliedVertexConstants, sizeof(dx_VertexConstants)) != 0)
{
mDeviceContext->UpdateSubresource(mDriverConstantBufferVS, 0, NULL, &mVertexConstants, 16, 0);
memcpy(&mAppliedVertexConstants, &mVertexConstants, sizeof(dx_VertexConstants));
}
if (memcmp(&mPixelConstants, &mAppliedPixelConstants, sizeof(dx_PixelConstants)) != 0)
{
mDeviceContext->UpdateSubresource(mDriverConstantBufferPS, 0, NULL, &mPixelConstants, 16, 0);
memcpy(&mAppliedPixelConstants, &mPixelConstants, sizeof(dx_PixelConstants));
}
// needed for the point sprite geometry shader
mDeviceContext->GSSetConstantBuffers(0, 1, &mDriverConstantBufferPS);
}
void Renderer11::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
{
bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
!(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
clearParams.colorMaskBlue && alphaUnmasked);
unsigned int stencilUnmasked = 0x0;
if (frameBuffer->hasStencil())
{
unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
stencilUnmasked = (0x1 << stencilSize) - 1;
}
bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
(clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
bool needScissoredClear = mScissorEnabled && (mCurScissor.x > 0 || mCurScissor.y > 0 ||
mCurScissor.x + mCurScissor.width < mRenderTargetDesc.width ||
mCurScissor.y + mCurScissor.height < mRenderTargetDesc.height);
if (needMaskedColorClear || needMaskedStencilClear || needScissoredClear)
{
maskedClear(clearParams, frameBuffer->usingExtendedDrawBuffers());
}
else
{
if (clearParams.mask & GL_COLOR_BUFFER_BIT)
{
for (unsigned int colorAttachment = 0; colorAttachment < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (frameBuffer->isEnabledColorAttachment(colorAttachment))
{
gl::Renderbuffer *renderbufferObject = frameBuffer->getColorbuffer(colorAttachment);
if (renderbufferObject)
{
RenderTarget11 *renderTarget = RenderTarget11::makeRenderTarget11(renderbufferObject->getRenderTarget());
if (!renderTarget)
{
ERR("render target pointer unexpectedly null.");
return;
}
ID3D11RenderTargetView *framebufferRTV = renderTarget->getRenderTargetView();
if (!framebufferRTV)
{
ERR("render target view pointer unexpectedly null.");
return;
}
const float clearValues[4] = { clearParams.colorClearValue.red,
clearParams.colorClearValue.green,
clearParams.colorClearValue.blue,
clearParams.colorClearValue.alpha };
mDeviceContext->ClearRenderTargetView(framebufferRTV, clearValues);
framebufferRTV->Release();
}
}
}
}
if (clearParams.mask & GL_DEPTH_BUFFER_BIT || clearParams.mask & GL_STENCIL_BUFFER_BIT)
{
gl::Renderbuffer *renderbufferObject = frameBuffer->getDepthOrStencilbuffer();
if (renderbufferObject)
{
RenderTarget11 *renderTarget = RenderTarget11::makeRenderTarget11(renderbufferObject->getDepthStencil());
if (!renderTarget)
{
ERR("render target pointer unexpectedly null.");
return;
}
ID3D11DepthStencilView *framebufferDSV = renderTarget->getDepthStencilView();
if (!framebufferDSV)
{
ERR("depth stencil view pointer unexpectedly null.");
return;
}
UINT clearFlags = 0;
if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
{
clearFlags |= D3D11_CLEAR_DEPTH;
}
if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
{
clearFlags |= D3D11_CLEAR_STENCIL;
}
float depthClear = gl::clamp01(clearParams.depthClearValue);
UINT8 stencilClear = clearParams.stencilClearValue & 0x000000FF;
mDeviceContext->ClearDepthStencilView(framebufferDSV, clearFlags, depthClear, stencilClear);
framebufferDSV->Release();
}
}
}
}
void Renderer11::maskedClear(const gl::ClearParameters &clearParams, bool usingExtendedDrawBuffers)
{
HRESULT result;
if (!mClearResourcesInitialized)
{
ASSERT(!mClearVB && !mClearVS && !mClearSinglePS && !mClearMultiplePS && !mClearScissorRS && !mClearNoScissorRS);
D3D11_BUFFER_DESC vbDesc;
vbDesc.ByteWidth = sizeof(d3d11::PositionDepthColorVertex) * 4;
vbDesc.Usage = D3D11_USAGE_DYNAMIC;
vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vbDesc.MiscFlags = 0;
vbDesc.StructureByteStride = 0;
result = mDevice->CreateBuffer(&vbDesc, NULL, &mClearVB);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearVB, "Renderer11 masked clear vertex buffer");
D3D11_INPUT_ELEMENT_DESC quadLayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
result = mDevice->CreateInputLayout(quadLayout, 2, g_VS_Clear, sizeof(g_VS_Clear), &mClearIL);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearIL, "Renderer11 masked clear input layout");
result = mDevice->CreateVertexShader(g_VS_Clear, sizeof(g_VS_Clear), NULL, &mClearVS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearVS, "Renderer11 masked clear vertex shader");
result = mDevice->CreatePixelShader(g_PS_ClearSingle, sizeof(g_PS_ClearSingle), NULL, &mClearSinglePS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearSinglePS, "Renderer11 masked clear pixel shader (1 RT)");
result = mDevice->CreatePixelShader(g_PS_ClearMultiple, sizeof(g_PS_ClearMultiple), NULL, &mClearMultiplePS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearMultiplePS, "Renderer11 masked clear pixel shader (MRT)");
D3D11_RASTERIZER_DESC rsScissorDesc;
rsScissorDesc.FillMode = D3D11_FILL_SOLID;
rsScissorDesc.CullMode = D3D11_CULL_NONE;
rsScissorDesc.FrontCounterClockwise = FALSE;
rsScissorDesc.DepthBias = 0;
rsScissorDesc.DepthBiasClamp = 0.0f;
rsScissorDesc.SlopeScaledDepthBias = 0.0f;
rsScissorDesc.DepthClipEnable = FALSE;
rsScissorDesc.ScissorEnable = TRUE;
rsScissorDesc.MultisampleEnable = FALSE;
rsScissorDesc.AntialiasedLineEnable = FALSE;
result = mDevice->CreateRasterizerState(&rsScissorDesc, &mClearScissorRS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearScissorRS, "Renderer11 masked clear scissor rasterizer state");
D3D11_RASTERIZER_DESC rsNoScissorDesc;
rsNoScissorDesc.FillMode = D3D11_FILL_SOLID;
rsNoScissorDesc.CullMode = D3D11_CULL_NONE;
rsNoScissorDesc.FrontCounterClockwise = FALSE;
rsNoScissorDesc.DepthBias = 0;
rsNoScissorDesc.DepthBiasClamp = 0.0f;
rsNoScissorDesc.SlopeScaledDepthBias = 0.0f;
rsNoScissorDesc.DepthClipEnable = FALSE;
rsNoScissorDesc.ScissorEnable = FALSE;
rsNoScissorDesc.MultisampleEnable = FALSE;
rsNoScissorDesc.AntialiasedLineEnable = FALSE;
result = mDevice->CreateRasterizerState(&rsNoScissorDesc, &mClearNoScissorRS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearNoScissorRS, "Renderer11 masked clear no scissor rasterizer state");
mClearResourcesInitialized = true;
}
// Prepare the depth stencil state to write depth values if the depth should be cleared
// and stencil values if the stencil should be cleared
gl::DepthStencilState glDSState;
glDSState.depthTest = (clearParams.mask & GL_DEPTH_BUFFER_BIT) != 0;
glDSState.depthFunc = GL_ALWAYS;
glDSState.depthMask = (clearParams.mask & GL_DEPTH_BUFFER_BIT) != 0;
glDSState.stencilTest = (clearParams.mask & GL_STENCIL_BUFFER_BIT) != 0;
glDSState.stencilFunc = GL_ALWAYS;
glDSState.stencilMask = 0;
glDSState.stencilFail = GL_REPLACE;
glDSState.stencilPassDepthFail = GL_REPLACE;
glDSState.stencilPassDepthPass = GL_REPLACE;
glDSState.stencilWritemask = clearParams.stencilWriteMask;
glDSState.stencilBackFunc = GL_ALWAYS;
glDSState.stencilBackMask = 0;
glDSState.stencilBackFail = GL_REPLACE;
glDSState.stencilBackPassDepthFail = GL_REPLACE;
glDSState.stencilBackPassDepthPass = GL_REPLACE;
glDSState.stencilBackWritemask = clearParams.stencilWriteMask;
int stencilClear = clearParams.stencilClearValue & 0x000000FF;
ID3D11DepthStencilState *dsState = mStateCache.getDepthStencilState(glDSState);
// Prepare the blend state to use a write mask if the color buffer should be cleared
gl::BlendState glBlendState;
glBlendState.blend = false;
glBlendState.sourceBlendRGB = GL_ONE;
glBlendState.destBlendRGB = GL_ZERO;
glBlendState.sourceBlendAlpha = GL_ONE;
glBlendState.destBlendAlpha = GL_ZERO;
glBlendState.blendEquationRGB = GL_FUNC_ADD;
glBlendState.blendEquationAlpha = GL_FUNC_ADD;
glBlendState.colorMaskRed = (clearParams.mask & GL_COLOR_BUFFER_BIT) ? clearParams.colorMaskRed : false;
glBlendState.colorMaskGreen = (clearParams.mask & GL_COLOR_BUFFER_BIT) ? clearParams.colorMaskGreen : false;
glBlendState.colorMaskBlue = (clearParams.mask & GL_COLOR_BUFFER_BIT) ? clearParams.colorMaskBlue : false;
glBlendState.colorMaskAlpha = (clearParams.mask & GL_COLOR_BUFFER_BIT) ? clearParams.colorMaskAlpha : false;
glBlendState.sampleAlphaToCoverage = false;
glBlendState.dither = false;
static const float blendFactors[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
static const UINT sampleMask = 0xFFFFFFFF;
ID3D11BlendState *blendState = mStateCache.getBlendState(glBlendState);
// Set the vertices
D3D11_MAPPED_SUBRESOURCE mappedResource;
result = mDeviceContext->Map(mClearVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
ERR("Failed to map masked clear vertex buffer, HRESULT: 0x%X.", result);
return;
}
d3d11::PositionDepthColorVertex *vertices = reinterpret_cast<d3d11::PositionDepthColorVertex*>(mappedResource.pData);
float depthClear = gl::clamp01(clearParams.depthClearValue);
d3d11::SetPositionDepthColorVertex(&vertices[0], -1.0f, 1.0f, depthClear, clearParams.colorClearValue);
d3d11::SetPositionDepthColorVertex(&vertices[1], -1.0f, -1.0f, depthClear, clearParams.colorClearValue);
d3d11::SetPositionDepthColorVertex(&vertices[2], 1.0f, 1.0f, depthClear, clearParams.colorClearValue);
d3d11::SetPositionDepthColorVertex(&vertices[3], 1.0f, -1.0f, depthClear, clearParams.colorClearValue);
mDeviceContext->Unmap(mClearVB, 0);
// Apply state
mDeviceContext->OMSetBlendState(blendState, blendFactors, sampleMask);
mDeviceContext->OMSetDepthStencilState(dsState, stencilClear);
mDeviceContext->RSSetState(mScissorEnabled ? mClearScissorRS : mClearNoScissorRS);
// Apply shaders
ID3D11PixelShader *pixelShader = usingExtendedDrawBuffers ? mClearMultiplePS : mClearSinglePS;
mDeviceContext->IASetInputLayout(mClearIL);
mDeviceContext->VSSetShader(mClearVS, NULL, 0);
mDeviceContext->PSSetShader(pixelShader, NULL, 0);
mDeviceContext->GSSetShader(NULL, NULL, 0);
// Apply vertex buffer
static UINT stride = sizeof(d3d11::PositionDepthColorVertex);
static UINT startIdx = 0;
mDeviceContext->IASetVertexBuffers(0, 1, &mClearVB, &stride, &startIdx);
mDeviceContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
// Draw the clear quad
mDeviceContext->Draw(4, 0);
// Clean up
markAllStateDirty();
}
void Renderer11::markAllStateDirty()
{
for (unsigned int rtIndex = 0; rtIndex < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; rtIndex++)
{
mAppliedRenderTargetSerials[rtIndex] = 0;
}
mAppliedDepthbufferSerial = 0;
mAppliedStencilbufferSerial = 0;
mDepthStencilInitialized = false;
mRenderTargetDescInitialized = false;
for (int i = 0; i < gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS; i++)
{
mForceSetVertexSamplerStates[i] = true;
mCurVertexTextureSerials[i] = 0;
}
for (int i = 0; i < gl::MAX_TEXTURE_IMAGE_UNITS; i++)
{
mForceSetPixelSamplerStates[i] = true;
mCurPixelTextureSerials[i] = 0;
}
mForceSetBlendState = true;
mForceSetRasterState = true;
mForceSetDepthStencilState = true;
mForceSetScissor = true;
mForceSetViewport = true;
mAppliedIBSerial = 0;
mAppliedStorageIBSerial = 0;
mAppliedIBOffset = 0;
mAppliedProgramBinarySerial = 0;
memset(&mAppliedVertexConstants, 0, sizeof(dx_VertexConstants));
memset(&mAppliedPixelConstants, 0, sizeof(dx_PixelConstants));
}
void Renderer11::releaseDeviceResources()
{
mStateCache.clear();
mInputLayoutCache.clear();
delete mVertexDataManager;
mVertexDataManager = NULL;
delete mIndexDataManager;
mIndexDataManager = NULL;
delete mLineLoopIB;
mLineLoopIB = NULL;
delete mTriangleFanIB;
mTriangleFanIB = NULL;
SafeRelease(mCopyVB);
SafeRelease(mCopySampler);
SafeRelease(mCopyIL);
SafeRelease(mCopyIL);
SafeRelease(mCopyVS);
SafeRelease(mCopyRGBAPS);
SafeRelease(mCopyRGBPS);
SafeRelease(mCopyLumPS);
SafeRelease(mCopyLumAlphaPS);
mCopyResourcesInitialized = false;
SafeRelease(mClearVB);
SafeRelease(mClearIL);
SafeRelease(mClearVS);
SafeRelease(mClearSinglePS);
SafeRelease(mClearMultiplePS);
SafeRelease(mClearScissorRS);
SafeRelease(mClearNoScissorRS);
mClearResourcesInitialized = false;
SafeRelease(mDriverConstantBufferVS);
SafeRelease(mDriverConstantBufferPS);
SafeRelease(mSyncQuery);
}
void Renderer11::notifyDeviceLost()
{
mDeviceLost = true;
mDisplay->notifyDeviceLost();
}
bool Renderer11::isDeviceLost()
{
return mDeviceLost;
}
// set notify to true to broadcast a message to all contexts of the device loss
bool Renderer11::testDeviceLost(bool notify)
{
bool isLost = false;
// GetRemovedReason is used to test if the device is removed
HRESULT result = mDevice->GetDeviceRemovedReason();
isLost = d3d11::isDeviceLostError(result);
if (isLost)
{
// Log error if this is a new device lost event
if (mDeviceLost == false)
{
ERR("The D3D11 device was removed: 0x%08X", result);
}
// ensure we note the device loss --
// we'll probably get this done again by notifyDeviceLost
// but best to remember it!
// Note that we don't want to clear the device loss status here
// -- this needs to be done by resetDevice
mDeviceLost = true;
if (notify)
{
notifyDeviceLost();
}
}
return isLost;
}
bool Renderer11::testDeviceResettable()
{
// determine if the device is resettable by creating a dummy device
PFN_D3D11_CREATE_DEVICE D3D11CreateDevice = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(mD3d11Module, "D3D11CreateDevice");
if (D3D11CreateDevice == NULL)
{
return false;
}
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
ID3D11Device* dummyDevice;
D3D_FEATURE_LEVEL dummyFeatureLevel;
ID3D11DeviceContext* dummyContext;
HRESULT result = D3D11CreateDevice(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
#if defined(_DEBUG)
D3D11_CREATE_DEVICE_DEBUG,
#else
0,
#endif
featureLevels,
ArraySize(featureLevels),
D3D11_SDK_VERSION,
&dummyDevice,
&dummyFeatureLevel,
&dummyContext);
if (!mDevice || FAILED(result))
{
return false;
}
dummyContext->Release();
dummyDevice->Release();
return true;
}
void Renderer11::release()
{
releaseDeviceResources();
if (mDxgiFactory)
{
mDxgiFactory->Release();
mDxgiFactory = NULL;
}
if (mDxgiAdapter)
{
mDxgiAdapter->Release();
mDxgiAdapter = NULL;
}
if (mDeviceContext)
{
mDeviceContext->ClearState();
mDeviceContext->Flush();
mDeviceContext->Release();
mDeviceContext = NULL;
}
if (mDevice)
{
mDevice->Release();
mDevice = NULL;
}
if (mD3d11Module)
{
FreeLibrary(mD3d11Module);
mD3d11Module = NULL;
}
if (mDxgiModule)
{
FreeLibrary(mDxgiModule);
mDxgiModule = NULL;
}
}
bool Renderer11::resetDevice()
{
// recreate everything
release();
EGLint result = initialize();
if (result != EGL_SUCCESS)
{
ERR("Could not reinitialize D3D11 device: %08X", result);
return false;
}
mDeviceLost = false;
return true;
}
DWORD Renderer11::getAdapterVendor() const
{
return mAdapterDescription.VendorId;
}
std::string Renderer11::getRendererDescription() const
{
std::ostringstream rendererString;
rendererString << mDescription;
rendererString << " Direct3D11";
rendererString << " vs_" << getMajorShaderModel() << "_" << getMinorShaderModel();
rendererString << " ps_" << getMajorShaderModel() << "_" << getMinorShaderModel();
return rendererString.str();
}
GUID Renderer11::getAdapterIdentifier() const
{
// Use the adapter LUID as our adapter ID
// This number is local to a machine is only guaranteed to be unique between restarts
META_ASSERT(sizeof(LUID) <= sizeof(GUID));
GUID adapterId = {0};
memcpy(&adapterId, &mAdapterDescription.AdapterLuid, sizeof(LUID));
return adapterId;
}
bool Renderer11::getBGRATextureSupport() const
{
return mBGRATextureSupport;
}
bool Renderer11::getDXT1TextureSupport()
{
return mDXT1TextureSupport;
}
bool Renderer11::getDXT3TextureSupport()
{
return mDXT3TextureSupport;
}
bool Renderer11::getDXT5TextureSupport()
{
return mDXT5TextureSupport;
}
bool Renderer11::getDepthTextureSupport() const
{
return mDepthTextureSupport;
}
bool Renderer11::getFloat32TextureSupport(bool *filtering, bool *renderable)
{
*renderable = mFloat32RenderSupport;
*filtering = mFloat32FilterSupport;
return mFloat32TextureSupport;
}
bool Renderer11::getFloat16TextureSupport(bool *filtering, bool *renderable)
{
*renderable = mFloat16RenderSupport;
*filtering = mFloat16FilterSupport;
return mFloat16TextureSupport;
}
bool Renderer11::getLuminanceTextureSupport()
{
return false;
}
bool Renderer11::getLuminanceAlphaTextureSupport()
{
return false;
}
bool Renderer11::getTextureFilterAnisotropySupport() const
{
return true;
}
float Renderer11::getTextureMaxAnisotropy() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
return D3D11_MAX_MAXANISOTROPY;
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return D3D10_MAX_MAXANISOTROPY;
default: UNREACHABLE();
return 0;
}
}
bool Renderer11::getEventQuerySupport()
{
return true;
}
Range Renderer11::getViewportBounds() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
return Range(D3D11_VIEWPORT_BOUNDS_MIN, D3D11_VIEWPORT_BOUNDS_MAX);
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return Range(D3D10_VIEWPORT_BOUNDS_MIN, D3D10_VIEWPORT_BOUNDS_MAX);
default: UNREACHABLE();
return Range(0, 0);
}
}
unsigned int Renderer11::getMaxVertexTextureImageUnits() const
{
META_ASSERT(MAX_TEXTURE_IMAGE_UNITS_VTF_SM4 <= gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS);
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return MAX_TEXTURE_IMAGE_UNITS_VTF_SM4;
default: UNREACHABLE();
return 0;
}
}
unsigned int Renderer11::getMaxCombinedTextureImageUnits() const
{
return gl::MAX_TEXTURE_IMAGE_UNITS + getMaxVertexTextureImageUnits();
}
unsigned int Renderer11::getReservedVertexUniformVectors() const
{
return 0; // Driver uniforms are stored in a separate constant buffer
}
unsigned int Renderer11::getReservedFragmentUniformVectors() const
{
return 0; // Driver uniforms are stored in a separate constant buffer
}
unsigned int Renderer11::getMaxVertexUniformVectors() const
{
META_ASSERT(MAX_VERTEX_UNIFORM_VECTORS_D3D11 <= D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT);
ASSERT(mFeatureLevel >= D3D_FEATURE_LEVEL_10_0);
return MAX_VERTEX_UNIFORM_VECTORS_D3D11;
}
unsigned int Renderer11::getMaxFragmentUniformVectors() const
{
META_ASSERT(MAX_FRAGMENT_UNIFORM_VECTORS_D3D11 <= D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT);
ASSERT(mFeatureLevel >= D3D_FEATURE_LEVEL_10_0);
return MAX_FRAGMENT_UNIFORM_VECTORS_D3D11;
}
unsigned int Renderer11::getMaxVaryingVectors() const
{
META_ASSERT(gl::IMPLEMENTATION_MAX_VARYING_VECTORS == D3D11_VS_OUTPUT_REGISTER_COUNT);
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
return D3D11_VS_OUTPUT_REGISTER_COUNT;
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return D3D10_VS_OUTPUT_REGISTER_COUNT;
default: UNREACHABLE();
return 0;
}
}
bool Renderer11::getNonPower2TextureSupport() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return true;
default: UNREACHABLE();
return false;
}
}
bool Renderer11::getOcclusionQuerySupport() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return true;
default: UNREACHABLE();
return false;
}
}
bool Renderer11::getInstancingSupport() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return true;
default: UNREACHABLE();
return false;
}
}
bool Renderer11::getShareHandleSupport() const
{
// We only currently support share handles with BGRA surfaces, because
// chrome needs BGRA. Once chrome fixes this, we should always support them.
// PIX doesn't seem to support using share handles, so disable them.
return getBGRATextureSupport() && !gl::perfActive();
}
bool Renderer11::getDerivativeInstructionSupport() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return true;
default: UNREACHABLE();
return false;
}
}
bool Renderer11::getPostSubBufferSupport() const
{
// D3D11 does not support present with dirty rectangles until D3D11.1 and DXGI 1.2.
return false;
}
int Renderer11::getMajorShaderModel() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0: return D3D11_SHADER_MAJOR_VERSION; // 5
case D3D_FEATURE_LEVEL_10_1: return D3D10_1_SHADER_MAJOR_VERSION; // 4
case D3D_FEATURE_LEVEL_10_0: return D3D10_SHADER_MAJOR_VERSION; // 4
default: UNREACHABLE(); return 0;
}
}
int Renderer11::getMinorShaderModel() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0: return D3D11_SHADER_MINOR_VERSION; // 0
case D3D_FEATURE_LEVEL_10_1: return D3D10_1_SHADER_MINOR_VERSION; // 1
case D3D_FEATURE_LEVEL_10_0: return D3D10_SHADER_MINOR_VERSION; // 0
default: UNREACHABLE(); return 0;
}
}
float Renderer11::getMaxPointSize() const
{
// choose a reasonable maximum. we enforce this in the shader.
// (nb: on a Radeon 2600xt, DX9 reports a 256 max point size)
return 1024.0f;
}
int Renderer11::getMaxViewportDimension() const
{
// Maximum viewport size must be at least as large as the largest render buffer (or larger).
// In our case return the maximum texture size, which is the maximum render buffer size.
META_ASSERT(D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION * 2 - 1 <= D3D11_VIEWPORT_BOUNDS_MAX);
META_ASSERT(D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION * 2 - 1 <= D3D10_VIEWPORT_BOUNDS_MAX);
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 16384
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 8192
default: UNREACHABLE();
return 0;
}
}
int Renderer11::getMaxTextureWidth() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0: return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 16384
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0: return D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 8192
default: UNREACHABLE(); return 0;
}
}
int Renderer11::getMaxTextureHeight() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0: return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 16384
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0: return D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 8192
default: UNREACHABLE(); return 0;
}
}
bool Renderer11::get32BitIndexSupport() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0: return D3D10_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP >= 32; // true
default: UNREACHABLE(); return false;
}
}
int Renderer11::getMinSwapInterval() const
{
return 0;
}
int Renderer11::getMaxSwapInterval() const
{
return 4;
}
int Renderer11::getMaxSupportedSamples() const
{
return mMaxSupportedSamples;
}
int Renderer11::getNearestSupportedSamples(DXGI_FORMAT format, unsigned int requested) const
{
if (requested == 0)
{
return 0;
}
MultisampleSupportMap::const_iterator iter = mMultisampleSupportMap.find(format);
if (iter != mMultisampleSupportMap.end())
{
const MultisampleSupportInfo& info = iter->second;
for (unsigned int i = requested - 1; i < D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; i++)
{
if (info.qualityLevels[i] > 0)
{
return i + 1;
}
}
}
return -1;
}
unsigned int Renderer11::getMaxRenderTargets() const
{
META_ASSERT(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT <= gl::IMPLEMENTATION_MAX_DRAW_BUFFERS);
META_ASSERT(D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT <= gl::IMPLEMENTATION_MAX_DRAW_BUFFERS);
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
return D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; // 8
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT; // 8
default:
UNREACHABLE();
return 1;
}
}
bool Renderer11::copyToRenderTarget(TextureStorageInterface2D *dest, TextureStorageInterface2D *source)
{
if (source && dest)
{
TextureStorage11_2D *source11 = TextureStorage11_2D::makeTextureStorage11_2D(source->getStorageInstance());
TextureStorage11_2D *dest11 = TextureStorage11_2D::makeTextureStorage11_2D(dest->getStorageInstance());
mDeviceContext->CopyResource(dest11->getBaseTexture(), source11->getBaseTexture());
return true;
}
return false;
}
bool Renderer11::copyToRenderTarget(TextureStorageInterfaceCube *dest, TextureStorageInterfaceCube *source)
{
if (source && dest)
{
TextureStorage11_Cube *source11 = TextureStorage11_Cube::makeTextureStorage11_Cube(source->getStorageInstance());
TextureStorage11_Cube *dest11 = TextureStorage11_Cube::makeTextureStorage11_Cube(dest->getStorageInstance());
mDeviceContext->CopyResource(dest11->getBaseTexture(), source11->getBaseTexture());
return true;
}
return false;
}
bool Renderer11::copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level)
{
gl::Renderbuffer *colorbuffer = framebuffer->getReadColorbuffer();
if (!colorbuffer)
{
ERR("Failed to retrieve the color buffer from the frame buffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget11 *sourceRenderTarget = RenderTarget11::makeRenderTarget11(colorbuffer->getRenderTarget());
if (!sourceRenderTarget)
{
ERR("Failed to retrieve the render target from the frame buffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11ShaderResourceView *source = sourceRenderTarget->getShaderResourceView();
if (!source)
{
ERR("Failed to retrieve the render target view from the render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
TextureStorage11_2D *storage11 = TextureStorage11_2D::makeTextureStorage11_2D(storage->getStorageInstance());
if (!storage11)
{
source->Release();
ERR("Failed to retrieve the texture storage from the destination.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget11 *destRenderTarget = RenderTarget11::makeRenderTarget11(storage11->getRenderTarget(level));
if (!destRenderTarget)
{
source->Release();
ERR("Failed to retrieve the render target from the destination storage.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11RenderTargetView *dest = destRenderTarget->getRenderTargetView();
if (!dest)
{
source->Release();
ERR("Failed to retrieve the render target view from the destination render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
gl::Rectangle destRect;
destRect.x = xoffset;
destRect.y = yoffset;
destRect.width = sourceRect.width;
destRect.height = sourceRect.height;
bool ret = copyTexture(source, sourceRect, sourceRenderTarget->getWidth(), sourceRenderTarget->getHeight(),
dest, destRect, destRenderTarget->getWidth(), destRenderTarget->getHeight(), destFormat);
source->Release();
dest->Release();
return ret;
}
bool Renderer11::copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level)
{
gl::Renderbuffer *colorbuffer = framebuffer->getReadColorbuffer();
if (!colorbuffer)
{
ERR("Failed to retrieve the color buffer from the frame buffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget11 *sourceRenderTarget = RenderTarget11::makeRenderTarget11(colorbuffer->getRenderTarget());
if (!sourceRenderTarget)
{
ERR("Failed to retrieve the render target from the frame buffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11ShaderResourceView *source = sourceRenderTarget->getShaderResourceView();
if (!source)
{
ERR("Failed to retrieve the render target view from the render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
TextureStorage11_Cube *storage11 = TextureStorage11_Cube::makeTextureStorage11_Cube(storage->getStorageInstance());
if (!storage11)
{
source->Release();
ERR("Failed to retrieve the texture storage from the destination.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget11 *destRenderTarget = RenderTarget11::makeRenderTarget11(storage11->getRenderTarget(target, level));
if (!destRenderTarget)
{
source->Release();
ERR("Failed to retrieve the render target from the destination storage.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11RenderTargetView *dest = destRenderTarget->getRenderTargetView();
if (!dest)
{
source->Release();
ERR("Failed to retrieve the render target view from the destination render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
gl::Rectangle destRect;
destRect.x = xoffset;
destRect.y = yoffset;
destRect.width = sourceRect.width;
destRect.height = sourceRect.height;
bool ret = copyTexture(source, sourceRect, sourceRenderTarget->getWidth(), sourceRenderTarget->getHeight(),
dest, destRect, destRenderTarget->getWidth(), destRenderTarget->getHeight(), destFormat);
source->Release();
dest->Release();
return ret;
}
bool Renderer11::copyTexture(ID3D11ShaderResourceView *source, const gl::Rectangle &sourceArea, unsigned int sourceWidth, unsigned int sourceHeight,
ID3D11RenderTargetView *dest, const gl::Rectangle &destArea, unsigned int destWidth, unsigned int destHeight, GLenum destFormat)
{
HRESULT result;
if (!mCopyResourcesInitialized)
{
ASSERT(!mCopyVB && !mCopySampler && !mCopyIL && !mCopyVS && !mCopyRGBAPS && !mCopyRGBPS && !mCopyLumPS && !mCopyLumAlphaPS);
D3D11_BUFFER_DESC vbDesc;
vbDesc.ByteWidth = sizeof(d3d11::PositionTexCoordVertex) * 4;
vbDesc.Usage = D3D11_USAGE_DYNAMIC;
vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vbDesc.MiscFlags = 0;
vbDesc.StructureByteStride = 0;
result = mDevice->CreateBuffer(&vbDesc, NULL, &mCopyVB);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyVB, "Renderer11 copy texture vertex buffer");
D3D11_SAMPLER_DESC samplerDesc;
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 0;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.BorderColor[0] = 0.0f;
samplerDesc.BorderColor[1] = 0.0f;
samplerDesc.BorderColor[2] = 0.0f;
samplerDesc.BorderColor[3] = 0.0f;
samplerDesc.MinLOD = 0.0f;
samplerDesc.MaxLOD = 0.0f;
result = mDevice->CreateSamplerState(&samplerDesc, &mCopySampler);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopySampler, "Renderer11 copy sampler");
D3D11_INPUT_ELEMENT_DESC quadLayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
result = mDevice->CreateInputLayout(quadLayout, 2, g_VS_Passthrough, sizeof(g_VS_Passthrough), &mCopyIL);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyIL, "Renderer11 copy texture input layout");
result = mDevice->CreateVertexShader(g_VS_Passthrough, sizeof(g_VS_Passthrough), NULL, &mCopyVS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyVS, "Renderer11 copy texture vertex shader");
result = mDevice->CreatePixelShader(g_PS_PassthroughRGBA, sizeof(g_PS_PassthroughRGBA), NULL, &mCopyRGBAPS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyRGBAPS, "Renderer11 copy texture RGBA pixel shader");
result = mDevice->CreatePixelShader(g_PS_PassthroughRGB, sizeof(g_PS_PassthroughRGB), NULL, &mCopyRGBPS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyRGBPS, "Renderer11 copy texture RGB pixel shader");
result = mDevice->CreatePixelShader(g_PS_PassthroughLum, sizeof(g_PS_PassthroughLum), NULL, &mCopyLumPS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyLumPS, "Renderer11 copy texture luminance pixel shader");
result = mDevice->CreatePixelShader(g_PS_PassthroughLumAlpha, sizeof(g_PS_PassthroughLumAlpha), NULL, &mCopyLumAlphaPS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyLumAlphaPS, "Renderer11 copy texture luminance alpha pixel shader");
mCopyResourcesInitialized = true;
}
// Verify the source and destination area sizes
if (sourceArea.x < 0 || sourceArea.x + sourceArea.width > static_cast<int>(sourceWidth) ||
sourceArea.y < 0 || sourceArea.y + sourceArea.height > static_cast<int>(sourceHeight) ||
destArea.x < 0 || destArea.x + destArea.width > static_cast<int>(destWidth) ||
destArea.y < 0 || destArea.y + destArea.height > static_cast<int>(destHeight))
{
return gl::error(GL_INVALID_VALUE, false);
}
// Set vertices
D3D11_MAPPED_SUBRESOURCE mappedResource;
result = mDeviceContext->Map(mCopyVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
ERR("Failed to map vertex buffer for texture copy, HRESULT: 0x%X.", result);
return gl::error(GL_OUT_OF_MEMORY, false);
}
d3d11::PositionTexCoordVertex *vertices = static_cast<d3d11::PositionTexCoordVertex*>(mappedResource.pData);
// Create a quad in homogeneous coordinates
float x1 = (destArea.x / float(destWidth)) * 2.0f - 1.0f;
float y1 = ((destHeight - destArea.y - destArea.height) / float(destHeight)) * 2.0f - 1.0f;
float x2 = ((destArea.x + destArea.width) / float(destWidth)) * 2.0f - 1.0f;
float y2 = ((destHeight - destArea.y) / float(destHeight)) * 2.0f - 1.0f;
float u1 = sourceArea.x / float(sourceWidth);
float v1 = sourceArea.y / float(sourceHeight);
float u2 = (sourceArea.x + sourceArea.width) / float(sourceWidth);
float v2 = (sourceArea.y + sourceArea.height) / float(sourceHeight);
d3d11::SetPositionTexCoordVertex(&vertices[0], x1, y1, u1, v2);
d3d11::SetPositionTexCoordVertex(&vertices[1], x1, y2, u1, v1);
d3d11::SetPositionTexCoordVertex(&vertices[2], x2, y1, u2, v2);
d3d11::SetPositionTexCoordVertex(&vertices[3], x2, y2, u2, v1);
mDeviceContext->Unmap(mCopyVB, 0);
static UINT stride = sizeof(d3d11::PositionTexCoordVertex);
static UINT startIdx = 0;
mDeviceContext->IASetVertexBuffers(0, 1, &mCopyVB, &stride, &startIdx);
// Apply state
mDeviceContext->OMSetBlendState(NULL, NULL, 0xFFFFFFF);
mDeviceContext->OMSetDepthStencilState(NULL, 0xFFFFFFFF);
mDeviceContext->RSSetState(NULL);
// Apply shaders
mDeviceContext->IASetInputLayout(mCopyIL);
mDeviceContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
mDeviceContext->VSSetShader(mCopyVS, NULL, 0);
ID3D11PixelShader *ps = NULL;
switch(destFormat)
{
case GL_RGBA: ps = mCopyRGBAPS; break;
case GL_RGB: ps = mCopyRGBPS; break;
case GL_ALPHA: ps = mCopyRGBAPS; break;
case GL_BGRA_EXT: ps = mCopyRGBAPS; break;
case GL_LUMINANCE: ps = mCopyLumPS; break;
case GL_LUMINANCE_ALPHA: ps = mCopyLumAlphaPS; break;
default: UNREACHABLE(); ps = NULL; break;
}
mDeviceContext->PSSetShader(ps, NULL, 0);
mDeviceContext->GSSetShader(NULL, NULL, 0);
// Unset the currently bound shader resource to avoid conflicts
static ID3D11ShaderResourceView *const nullSRV = NULL;
mDeviceContext->PSSetShaderResources(0, 1, &nullSRV);
// Apply render target
setOneTimeRenderTarget(dest);
// Set the viewport
D3D11_VIEWPORT viewport;
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = destWidth;
viewport.Height = destHeight;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
mDeviceContext->RSSetViewports(1, &viewport);
// Apply textures
mDeviceContext->PSSetShaderResources(0, 1, &source);
mDeviceContext->PSSetSamplers(0, 1, &mCopySampler);
// Draw the quad
mDeviceContext->Draw(4, 0);
// Unbind textures and render targets and vertex buffer
mDeviceContext->PSSetShaderResources(0, 1, &nullSRV);
unapplyRenderTargets();
UINT zero = 0;
ID3D11Buffer *const nullBuffer = NULL;
mDeviceContext->IASetVertexBuffers(0, 1, &nullBuffer, &zero, &zero);
markAllStateDirty();
return true;
}
void Renderer11::unapplyRenderTargets()
{
setOneTimeRenderTarget(NULL);
}
void Renderer11::setOneTimeRenderTarget(ID3D11RenderTargetView *renderTargetView)
{
ID3D11RenderTargetView *rtvArray[gl::IMPLEMENTATION_MAX_DRAW_BUFFERS] = {NULL};
rtvArray[0] = renderTargetView;
mDeviceContext->OMSetRenderTargets(getMaxRenderTargets(), rtvArray, NULL);
// Do not preserve the serial for this one-time-use render target
for (unsigned int rtIndex = 0; rtIndex < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; rtIndex++)
{
mAppliedRenderTargetSerials[rtIndex] = 0;
}
}
RenderTarget *Renderer11::createRenderTarget(SwapChain *swapChain, bool depth)
{
SwapChain11 *swapChain11 = SwapChain11::makeSwapChain11(swapChain);
RenderTarget11 *renderTarget = NULL;
if (depth)
{
// Note: depth stencil may be NULL for 0 sized surfaces
renderTarget = new RenderTarget11(this, swapChain11->getDepthStencil(),
swapChain11->getDepthStencilTexture(), NULL,
swapChain11->getWidth(), swapChain11->getHeight());
}
else
{
// Note: render target may be NULL for 0 sized surfaces
renderTarget = new RenderTarget11(this, swapChain11->getRenderTarget(),
swapChain11->getOffscreenTexture(),
swapChain11->getRenderTargetShaderResource(),
swapChain11->getWidth(), swapChain11->getHeight());
}
return renderTarget;
}
RenderTarget *Renderer11::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
{
RenderTarget11 *renderTarget = new RenderTarget11(this, width, height, format, samples, depth);
return renderTarget;
}
ShaderExecutable *Renderer11::loadExecutable(const void *function, size_t length, rx::ShaderType type)
{
ShaderExecutable11 *executable = NULL;
switch (type)
{
case rx::SHADER_VERTEX:
{
ID3D11VertexShader *vshader = NULL;
HRESULT result = mDevice->CreateVertexShader(function, length, NULL, &vshader);
ASSERT(SUCCEEDED(result));
if (vshader)
{
executable = new ShaderExecutable11(function, length, vshader);
}
}
break;
case rx::SHADER_PIXEL:
{
ID3D11PixelShader *pshader = NULL;
HRESULT result = mDevice->CreatePixelShader(function, length, NULL, &pshader);
ASSERT(SUCCEEDED(result));
if (pshader)
{
executable = new ShaderExecutable11(function, length, pshader);
}
}
break;
case rx::SHADER_GEOMETRY:
{
ID3D11GeometryShader *gshader = NULL;
HRESULT result = mDevice->CreateGeometryShader(function, length, NULL, &gshader);
ASSERT(SUCCEEDED(result));
if (gshader)
{
executable = new ShaderExecutable11(function, length, gshader);
}
}
break;
default:
UNREACHABLE();
break;
}
return executable;
}
ShaderExecutable *Renderer11::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, rx::ShaderType type)
{
const char *profile = NULL;
switch (type)
{
case rx::SHADER_VERTEX:
profile = "vs_4_0";
break;
case rx::SHADER_PIXEL:
profile = "ps_4_0";
break;
case rx::SHADER_GEOMETRY:
profile = "gs_4_0";
break;
default:
UNREACHABLE();
return NULL;
}
ID3DBlob *binary = (ID3DBlob*)compileToBinary(infoLog, shaderHLSL, profile, D3DCOMPILE_OPTIMIZATION_LEVEL0, false);
if (!binary)
return NULL;
ShaderExecutable *executable = loadExecutable((DWORD *)binary->GetBufferPointer(), binary->GetBufferSize(), type);
binary->Release();
return executable;
}
VertexBuffer *Renderer11::createVertexBuffer()
{
return new VertexBuffer11(this);
}
IndexBuffer *Renderer11::createIndexBuffer()
{
return new IndexBuffer11(this);
}
BufferStorage *Renderer11::createBufferStorage()
{
return new BufferStorage11(this);
}
QueryImpl *Renderer11::createQuery(GLenum type)
{
return new Query11(this, type);
}
FenceImpl *Renderer11::createFence()
{
return new Fence11(this);
}
bool Renderer11::getRenderTargetResource(gl::Renderbuffer *colorbuffer, unsigned int *subresourceIndex, ID3D11Texture2D **resource)
{
ASSERT(colorbuffer != NULL);
RenderTarget11 *renderTarget = RenderTarget11::makeRenderTarget11(colorbuffer->getRenderTarget());
if (renderTarget)
{
*subresourceIndex = renderTarget->getSubresourceIndex();
ID3D11RenderTargetView *colorBufferRTV = renderTarget->getRenderTargetView();
if (colorBufferRTV)
{
ID3D11Resource *textureResource = NULL;
colorBufferRTV->GetResource(&textureResource);
colorBufferRTV->Release();
if (textureResource)
{
HRESULT result = textureResource->QueryInterface(IID_ID3D11Texture2D, (void**)resource);
textureResource->Release();
if (SUCCEEDED(result))
{
return true;
}
else
{
ERR("Failed to extract the ID3D11Texture2D from the render target resource, "
"HRESULT: 0x%X.", result);
}
}
}
}
return false;
}
bool Renderer11::blitRect(gl::Framebuffer *readTarget, const gl::Rectangle &readRect, gl::Framebuffer *drawTarget, const gl::Rectangle &drawRect,
bool blitRenderTarget, bool blitDepthStencil)
{
if (blitRenderTarget)
{
gl::Renderbuffer *readBuffer = readTarget->getReadColorbuffer();
if (!readBuffer)
{
ERR("Failed to retrieve the read buffer from the read framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget *readRenderTarget = readBuffer->getRenderTarget();
for (unsigned int colorAttachment = 0; colorAttachment < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (drawTarget->isEnabledColorAttachment(colorAttachment))
{
gl::Renderbuffer *drawBuffer = drawTarget->getColorbuffer(colorAttachment);
if (!drawBuffer)
{
ERR("Failed to retrieve the draw buffer from the draw framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget *drawRenderTarget = drawBuffer->getRenderTarget();
if (!blitRenderbufferRect(readRect, drawRect, readRenderTarget, drawRenderTarget, false))
{
return false;
}
}
}
}
if (blitDepthStencil)
{
gl::Renderbuffer *readBuffer = readTarget->getDepthOrStencilbuffer();
gl::Renderbuffer *drawBuffer = drawTarget->getDepthOrStencilbuffer();
if (!readBuffer)
{
ERR("Failed to retrieve the read depth-stencil buffer from the read framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
if (!drawBuffer)
{
ERR("Failed to retrieve the draw depth-stencil buffer from the draw framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget *readRenderTarget = readBuffer->getDepthStencil();
RenderTarget *drawRenderTarget = drawBuffer->getDepthStencil();
if (!blitRenderbufferRect(readRect, drawRect, readRenderTarget, drawRenderTarget, true))
{
return false;
}
}
return true;
}
void Renderer11::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
{
ID3D11Texture2D *colorBufferTexture = NULL;
unsigned int subresourceIndex = 0;
gl::Renderbuffer *colorbuffer = framebuffer->getReadColorbuffer();
if (colorbuffer && getRenderTargetResource(colorbuffer, &subresourceIndex, &colorBufferTexture))
{
gl::Rectangle area;
area.x = x;
area.y = y;
area.width = width;
area.height = height;
readTextureData(colorBufferTexture, subresourceIndex, area, format, type, outputPitch,
packReverseRowOrder, packAlignment, pixels);
colorBufferTexture->Release();
colorBufferTexture = NULL;
}
}
Image *Renderer11::createImage()
{
return new Image11();
}
void Renderer11::generateMipmap(Image *dest, Image *src)
{
Image11 *dest11 = Image11::makeImage11(dest);
Image11 *src11 = Image11::makeImage11(src);
Image11::generateMipmap(dest11, src11);
}
TextureStorage *Renderer11::createTextureStorage2D(SwapChain *swapChain)
{
SwapChain11 *swapChain11 = SwapChain11::makeSwapChain11(swapChain);
return new TextureStorage11_2D(this, swapChain11);
}
TextureStorage *Renderer11::createTextureStorage2D(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height)
{
return new TextureStorage11_2D(this, levels, internalformat, usage, forceRenderable, width, height);
}
TextureStorage *Renderer11::createTextureStorageCube(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size)
{
return new TextureStorage11_Cube(this, levels, internalformat, usage, forceRenderable, size);
}
static inline unsigned int getFastPixelCopySize(DXGI_FORMAT sourceFormat, GLenum destFormat, GLenum destType)
{
if (sourceFormat == DXGI_FORMAT_A8_UNORM &&
destFormat == GL_ALPHA &&
destType == GL_UNSIGNED_BYTE)
{
return 1;
}
else if (sourceFormat == DXGI_FORMAT_R8G8B8A8_UNORM &&
destFormat == GL_RGBA &&
destType == GL_UNSIGNED_BYTE)
{
return 4;
}
else if (sourceFormat == DXGI_FORMAT_B8G8R8A8_UNORM &&
destFormat == GL_BGRA_EXT &&
destType == GL_UNSIGNED_BYTE)
{
return 4;
}
else if (sourceFormat == DXGI_FORMAT_R16G16B16A16_FLOAT &&
destFormat == GL_RGBA &&
destType == GL_HALF_FLOAT_OES)
{
return 8;
}
else if (sourceFormat == DXGI_FORMAT_R32G32B32_FLOAT &&
destFormat == GL_RGB &&
destType == GL_FLOAT)
{
return 12;
}
else if (sourceFormat == DXGI_FORMAT_R32G32B32A32_FLOAT &&
destFormat == GL_RGBA &&
destType == GL_FLOAT)
{
return 16;
}
else
{
return 0;
}
}
static inline void readPixelColor(const unsigned char *data, DXGI_FORMAT format, unsigned int x,
unsigned int y, int inputPitch, gl::Color *outColor)
{
switch (format)
{
case DXGI_FORMAT_R8G8B8A8_UNORM:
{
unsigned int rgba = *reinterpret_cast<const unsigned int*>(data + 4 * x + y * inputPitch);
outColor->red = (rgba & 0x000000FF) * (1.0f / 0x000000FF);
outColor->green = (rgba & 0x0000FF00) * (1.0f / 0x0000FF00);
outColor->blue = (rgba & 0x00FF0000) * (1.0f / 0x00FF0000);
outColor->alpha = (rgba & 0xFF000000) * (1.0f / 0xFF000000);
}
break;
case DXGI_FORMAT_A8_UNORM:
{
outColor->red = 0.0f;
outColor->green = 0.0f;
outColor->blue = 0.0f;
outColor->alpha = *(data + x + y * inputPitch) / 255.0f;
}
break;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
{
outColor->red = *(reinterpret_cast<const float*>(data + 16 * x + y * inputPitch) + 0);
outColor->green = *(reinterpret_cast<const float*>(data + 16 * x + y * inputPitch) + 1);
outColor->blue = *(reinterpret_cast<const float*>(data + 16 * x + y * inputPitch) + 2);
outColor->alpha = *(reinterpret_cast<const float*>(data + 16 * x + y * inputPitch) + 3);
}
break;
case DXGI_FORMAT_R32G32B32_FLOAT:
{
outColor->red = *(reinterpret_cast<const float*>(data + 12 * x + y * inputPitch) + 0);
outColor->green = *(reinterpret_cast<const float*>(data + 12 * x + y * inputPitch) + 1);
outColor->blue = *(reinterpret_cast<const float*>(data + 12 * x + y * inputPitch) + 2);
outColor->alpha = 1.0f;
}
break;
case DXGI_FORMAT_R16G16B16A16_FLOAT:
{
outColor->red = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 8 * x + y * inputPitch) + 0));
outColor->green = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 8 * x + y * inputPitch) + 1));
outColor->blue = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 8 * x + y * inputPitch) + 2));
outColor->alpha = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 8 * x + y * inputPitch) + 3));
}
break;
case DXGI_FORMAT_B8G8R8A8_UNORM:
{
unsigned int bgra = *reinterpret_cast<const unsigned int*>(data + 4 * x + y * inputPitch);
outColor->red = (bgra & 0x00FF0000) * (1.0f / 0x00FF0000);
outColor->blue = (bgra & 0x000000FF) * (1.0f / 0x000000FF);
outColor->green = (bgra & 0x0000FF00) * (1.0f / 0x0000FF00);
outColor->alpha = (bgra & 0xFF000000) * (1.0f / 0xFF000000);
}
break;
case DXGI_FORMAT_R8_UNORM:
{
outColor->red = *(data + x + y * inputPitch) / 255.0f;
outColor->green = 0.0f;
outColor->blue = 0.0f;
outColor->alpha = 1.0f;
}
break;
case DXGI_FORMAT_R8G8_UNORM:
{
unsigned short rg = *reinterpret_cast<const unsigned short*>(data + 2 * x + y * inputPitch);
outColor->red = (rg & 0xFF00) * (1.0f / 0xFF00);
outColor->green = (rg & 0x00FF) * (1.0f / 0x00FF);
outColor->blue = 0.0f;
outColor->alpha = 1.0f;
}
break;
case DXGI_FORMAT_R16_FLOAT:
{
outColor->red = gl::float16ToFloat32(*reinterpret_cast<const unsigned short*>(data + 2 * x + y * inputPitch));
outColor->green = 0.0f;
outColor->blue = 0.0f;
outColor->alpha = 1.0f;
}
break;
case DXGI_FORMAT_R16G16_FLOAT:
{
outColor->red = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 4 * x + y * inputPitch) + 0));
outColor->green = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 4 * x + y * inputPitch) + 1));
outColor->blue = 0.0f;
outColor->alpha = 1.0f;
}
break;
default:
ERR("ReadPixelColor not implemented for DXGI format %u.", format);
UNIMPLEMENTED();
break;
}
}
static inline void writePixelColor(const gl::Color &color, GLenum format, GLenum type, unsigned int x,
unsigned int y, int outputPitch, void *outData)
{
unsigned char* byteData = reinterpret_cast<unsigned char*>(outData);
unsigned short* shortData = reinterpret_cast<unsigned short*>(outData);
switch (format)
{
case GL_RGBA:
switch (type)
{
case GL_UNSIGNED_BYTE:
byteData[4 * x + y * outputPitch + 0] = static_cast<unsigned char>(255 * color.red + 0.5f);
byteData[4 * x + y * outputPitch + 1] = static_cast<unsigned char>(255 * color.green + 0.5f);
byteData[4 * x + y * outputPitch + 2] = static_cast<unsigned char>(255 * color.blue + 0.5f);
byteData[4 * x + y * outputPitch + 3] = static_cast<unsigned char>(255 * color.alpha + 0.5f);
break;
default:
ERR("WritePixelColor not implemented for format GL_RGBA and type 0x%X.", type);
UNIMPLEMENTED();
break;
}
break;
case GL_BGRA_EXT:
switch (type)
{
case GL_UNSIGNED_BYTE:
byteData[4 * x + y * outputPitch + 0] = static_cast<unsigned char>(255 * color.blue + 0.5f);
byteData[4 * x + y * outputPitch + 1] = static_cast<unsigned char>(255 * color.green + 0.5f);
byteData[4 * x + y * outputPitch + 2] = static_cast<unsigned char>(255 * color.red + 0.5f);
byteData[4 * x + y * outputPitch + 3] = static_cast<unsigned char>(255 * color.alpha + 0.5f);
break;
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
// According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
// this type is packed as follows:
// 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
// --------------------------------------------------------------------------------
// | 4th | 3rd | 2nd | 1st component |
// --------------------------------------------------------------------------------
// in the case of BGRA_EXT, B is the first component, G the second, and so forth.
shortData[x + y * outputPitch / sizeof(unsigned short)] =
(static_cast<unsigned short>(15 * color.alpha + 0.5f) << 12) |
(static_cast<unsigned short>(15 * color.red + 0.5f) << 8) |
(static_cast<unsigned short>(15 * color.green + 0.5f) << 4) |
(static_cast<unsigned short>(15 * color.blue + 0.5f) << 0);
break;
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
// According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
// this type is packed as follows:
// 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
// --------------------------------------------------------------------------------
// | 4th | 3rd | 2nd | 1st component |
// --------------------------------------------------------------------------------
// in the case of BGRA_EXT, B is the first component, G the second, and so forth.
shortData[x + y * outputPitch / sizeof(unsigned short)] =
(static_cast<unsigned short>( color.alpha + 0.5f) << 15) |
(static_cast<unsigned short>(31 * color.red + 0.5f) << 10) |
(static_cast<unsigned short>(31 * color.green + 0.5f) << 5) |
(static_cast<unsigned short>(31 * color.blue + 0.5f) << 0);
break;
default:
ERR("WritePixelColor not implemented for format GL_BGRA_EXT and type 0x%X.", type);
UNIMPLEMENTED();
break;
}
break;
case GL_RGB:
switch (type)
{
case GL_UNSIGNED_SHORT_5_6_5:
shortData[x + y * outputPitch / sizeof(unsigned short)] =
(static_cast<unsigned short>(31 * color.blue + 0.5f) << 0) |
(static_cast<unsigned short>(63 * color.green + 0.5f) << 5) |
(static_cast<unsigned short>(31 * color.red + 0.5f) << 11);
break;
case GL_UNSIGNED_BYTE:
byteData[3 * x + y * outputPitch + 0] = static_cast<unsigned char>(255 * color.red + 0.5f);
byteData[3 * x + y * outputPitch + 1] = static_cast<unsigned char>(255 * color.green + 0.5f);
byteData[3 * x + y * outputPitch + 2] = static_cast<unsigned char>(255 * color.blue + 0.5f);
break;
default:
ERR("WritePixelColor not implemented for format GL_RGB and type 0x%X.", type);
UNIMPLEMENTED();
break;
}
break;
default:
ERR("WritePixelColor not implemented for format 0x%X.", format);
UNIMPLEMENTED();
break;
}
}
void Renderer11::readTextureData(ID3D11Texture2D *texture, unsigned int subResource, const gl::Rectangle &area,
GLenum format, GLenum type, GLsizei outputPitch, bool packReverseRowOrder,
GLint packAlignment, void *pixels)
{
D3D11_TEXTURE2D_DESC textureDesc;
texture->GetDesc(&textureDesc);
D3D11_TEXTURE2D_DESC stagingDesc;
stagingDesc.Width = area.width;
stagingDesc.Height = area.height;
stagingDesc.MipLevels = 1;
stagingDesc.ArraySize = 1;
stagingDesc.Format = textureDesc.Format;
stagingDesc.SampleDesc.Count = 1;
stagingDesc.SampleDesc.Quality = 0;
stagingDesc.Usage = D3D11_USAGE_STAGING;
stagingDesc.BindFlags = 0;
stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
stagingDesc.MiscFlags = 0;
ID3D11Texture2D* stagingTex = NULL;
HRESULT result = mDevice->CreateTexture2D(&stagingDesc, NULL, &stagingTex);
if (FAILED(result))
{
ERR("Failed to create staging texture for readPixels, HRESULT: 0x%X.", result);
return;
}
ID3D11Texture2D* srcTex = NULL;
if (textureDesc.SampleDesc.Count > 1)
{
D3D11_TEXTURE2D_DESC resolveDesc;
resolveDesc.Width = textureDesc.Width;
resolveDesc.Height = textureDesc.Height;
resolveDesc.MipLevels = 1;
resolveDesc.ArraySize = 1;
resolveDesc.Format = textureDesc.Format;
resolveDesc.SampleDesc.Count = 1;
resolveDesc.SampleDesc.Quality = 0;
resolveDesc.Usage = D3D11_USAGE_DEFAULT;
resolveDesc.BindFlags = 0;
resolveDesc.CPUAccessFlags = 0;
resolveDesc.MiscFlags = 0;
result = mDevice->CreateTexture2D(&resolveDesc, NULL, &srcTex);
if (FAILED(result))
{
ERR("Failed to create resolve texture for readPixels, HRESULT: 0x%X.", result);
stagingTex->Release();
return;
}
mDeviceContext->ResolveSubresource(srcTex, 0, texture, subResource, textureDesc.Format);
subResource = 0;
}
else
{
srcTex = texture;
srcTex->AddRef();
}
D3D11_BOX srcBox;
srcBox.left = area.x;
srcBox.right = area.x + area.width;
srcBox.top = area.y;
srcBox.bottom = area.y + area.height;
srcBox.front = 0;
srcBox.back = 1;
mDeviceContext->CopySubresourceRegion(stagingTex, 0, 0, 0, 0, srcTex, subResource, &srcBox);
srcTex->Release();
srcTex = NULL;
D3D11_MAPPED_SUBRESOURCE mapping;
mDeviceContext->Map(stagingTex, 0, D3D11_MAP_READ, 0, &mapping);
unsigned char *source;
int inputPitch;
if (packReverseRowOrder)
{
source = static_cast<unsigned char*>(mapping.pData) + mapping.RowPitch * (area.height - 1);
inputPitch = -static_cast<int>(mapping.RowPitch);
}
else
{
source = static_cast<unsigned char*>(mapping.pData);
inputPitch = static_cast<int>(mapping.RowPitch);
}
unsigned int fastPixelSize = getFastPixelCopySize(textureDesc.Format, format, type);
if (fastPixelSize != 0)
{
unsigned char *dest = static_cast<unsigned char*>(pixels);
for (int j = 0; j < area.height; j++)
{
memcpy(dest + j * outputPitch, source + j * inputPitch, area.width * fastPixelSize);
}
}
else if (textureDesc.Format == DXGI_FORMAT_B8G8R8A8_UNORM &&
format == GL_RGBA &&
type == GL_UNSIGNED_BYTE)
{
// Fast path for swapping red with blue
unsigned char *dest = static_cast<unsigned char*>(pixels);
for (int j = 0; j < area.height; j++)
{
for (int i = 0; i < area.width; i++)
{
unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
*(unsigned int*)(dest + 4 * i + j * outputPitch) =
(argb & 0xFF00FF00) | // Keep alpha and green
(argb & 0x00FF0000) >> 16 | // Move red to blue
(argb & 0x000000FF) << 16; // Move blue to red
}
}
}
else
{
gl::Color pixelColor;
for (int j = 0; j < area.height; j++)
{
for (int i = 0; i < area.width; i++)
{
readPixelColor(source, textureDesc.Format, i, j, inputPitch, &pixelColor);
writePixelColor(pixelColor, format, type, i, j, outputPitch, pixels);
}
}
}
mDeviceContext->Unmap(stagingTex, 0);
stagingTex->Release();
stagingTex = NULL;
}
bool Renderer11::blitRenderbufferRect(const gl::Rectangle &readRect, const gl::Rectangle &drawRect, RenderTarget *readRenderTarget,
RenderTarget *drawRenderTarget, bool wholeBufferCopy)
{
ASSERT(readRect.width == drawRect.width && readRect.height == drawRect.height);
RenderTarget11 *readRenderTarget11 = RenderTarget11::makeRenderTarget11(readRenderTarget);
if (!readRenderTarget)
{
ERR("Failed to retrieve the read render target from the read framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11Texture2D *readTexture = NULL;
unsigned int readSubresource = 0;
if (readRenderTarget->getSamples() > 0)
{
ID3D11Texture2D *unresolvedTexture = readRenderTarget11->getTexture();
readTexture = resolveMultisampledTexture(unresolvedTexture, readRenderTarget11->getSubresourceIndex());
readSubresource = 0;
unresolvedTexture->Release();
}
else
{
readTexture = readRenderTarget11->getTexture();
readSubresource = readRenderTarget11->getSubresourceIndex();
}
if (!readTexture)
{
ERR("Failed to retrieve the read render target view from the read render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget11 *drawRenderTarget11 = RenderTarget11::makeRenderTarget11(drawRenderTarget);
if (!drawRenderTarget)
{
readTexture->Release();
ERR("Failed to retrieve the draw render target from the draw framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11Texture2D *drawTexture = drawRenderTarget11->getTexture();
unsigned int drawSubresource = drawRenderTarget11->getSubresourceIndex();
D3D11_BOX readBox;
readBox.left = readRect.x;
readBox.right = readRect.x + readRect.width;
readBox.top = readRect.y;
readBox.bottom = readRect.y + readRect.height;
readBox.front = 0;
readBox.back = 1;
// D3D11 needs depth-stencil CopySubresourceRegions to have a NULL pSrcBox
// We also require complete framebuffer copies for depth-stencil blit.
D3D11_BOX *pSrcBox = wholeBufferCopy ? NULL : &readBox;
mDeviceContext->CopySubresourceRegion(drawTexture, drawSubresource, drawRect.x, drawRect.y, 0,
readTexture, readSubresource, pSrcBox);
readTexture->Release();
drawTexture->Release();
return true;
}
ID3D11Texture2D *Renderer11::resolveMultisampledTexture(ID3D11Texture2D *source, unsigned int subresource)
{
D3D11_TEXTURE2D_DESC textureDesc;
source->GetDesc(&textureDesc);
if (textureDesc.SampleDesc.Count > 1)
{
D3D11_TEXTURE2D_DESC resolveDesc;
resolveDesc.Width = textureDesc.Width;
resolveDesc.Height = textureDesc.Height;
resolveDesc.MipLevels = 1;
resolveDesc.ArraySize = 1;
resolveDesc.Format = textureDesc.Format;
resolveDesc.SampleDesc.Count = 1;
resolveDesc.SampleDesc.Quality = 0;
resolveDesc.Usage = textureDesc.Usage;
resolveDesc.BindFlags = textureDesc.BindFlags;
resolveDesc.CPUAccessFlags = 0;
resolveDesc.MiscFlags = 0;
ID3D11Texture2D *resolveTexture = NULL;
HRESULT result = mDevice->CreateTexture2D(&resolveDesc, NULL, &resolveTexture);
if (FAILED(result))
{
ERR("Failed to create a multisample resolve texture, HRESULT: 0x%X.", result);
return NULL;
}
mDeviceContext->ResolveSubresource(resolveTexture, 0, source, subresource, textureDesc.Format);
return resolveTexture;
}
else
{
source->AddRef();
return source;
}
}
bool Renderer11::getLUID(LUID *adapterLuid) const
{
adapterLuid->HighPart = 0;
adapterLuid->LowPart = 0;
if (!mDxgiAdapter)
{
return false;
}
DXGI_ADAPTER_DESC adapterDesc;
if (FAILED(mDxgiAdapter->GetDesc(&adapterDesc)))
{
return false;
}
*adapterLuid = adapterDesc.AdapterLuid;
return true;
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/Renderer11.cpp | C++ | bsd | 123,275 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// RenderTarget11.cpp: Implements a DX11-specific wrapper for ID3D11View pointers
// retained by Renderbuffers.
#include "libGLESv2/renderer/RenderTarget11.h"
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/renderer/renderer11_utils.h"
#include "libGLESv2/main.h"
namespace rx
{
static unsigned int getRTVSubresourceIndex(ID3D11Texture2D *texture, ID3D11RenderTargetView *view)
{
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc;
view->GetDesc(&rtvDesc);
D3D11_TEXTURE2D_DESC texDesc;
texture->GetDesc(&texDesc);
unsigned int mipSlice = 0;
unsigned int arraySlice = 0;
unsigned int mipLevels = texDesc.MipLevels;
switch (rtvDesc.ViewDimension)
{
case D3D11_RTV_DIMENSION_TEXTURE1D:
mipSlice = rtvDesc.Texture1D.MipSlice;
arraySlice = 0;
break;
case D3D11_RTV_DIMENSION_TEXTURE1DARRAY:
mipSlice = rtvDesc.Texture1DArray.MipSlice;
arraySlice = rtvDesc.Texture1DArray.FirstArraySlice;
break;
case D3D11_RTV_DIMENSION_TEXTURE2D:
mipSlice = rtvDesc.Texture2D.MipSlice;
arraySlice = 0;
break;
case D3D11_RTV_DIMENSION_TEXTURE2DARRAY:
mipSlice = rtvDesc.Texture2DArray.MipSlice;
arraySlice = rtvDesc.Texture2DArray.FirstArraySlice;
break;
case D3D11_RTV_DIMENSION_TEXTURE2DMS:
mipSlice = 0;
arraySlice = 0;
break;
case D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY:
mipSlice = 0;
arraySlice = rtvDesc.Texture2DMSArray.FirstArraySlice;
break;
case D3D11_RTV_DIMENSION_TEXTURE3D:
mipSlice = rtvDesc.Texture3D.MipSlice;
arraySlice = 0;
break;
case D3D11_RTV_DIMENSION_UNKNOWN:
case D3D11_RTV_DIMENSION_BUFFER:
UNIMPLEMENTED();
break;
default:
UNREACHABLE();
break;
}
return D3D11CalcSubresource(mipSlice, arraySlice, mipLevels);
}
static unsigned int getDSVSubresourceIndex(ID3D11Texture2D *texture, ID3D11DepthStencilView *view)
{
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
view->GetDesc(&dsvDesc);
D3D11_TEXTURE2D_DESC texDesc;
texture->GetDesc(&texDesc);
unsigned int mipSlice = 0;
unsigned int arraySlice = 0;
unsigned int mipLevels = texDesc.MipLevels;
switch (dsvDesc.ViewDimension)
{
case D3D11_DSV_DIMENSION_TEXTURE1D:
mipSlice = dsvDesc.Texture1D.MipSlice;
arraySlice = 0;
break;
case D3D11_DSV_DIMENSION_TEXTURE1DARRAY:
mipSlice = dsvDesc.Texture1DArray.MipSlice;
arraySlice = dsvDesc.Texture1DArray.FirstArraySlice;
break;
case D3D11_DSV_DIMENSION_TEXTURE2D:
mipSlice = dsvDesc.Texture2D.MipSlice;
arraySlice = 0;
break;
case D3D11_DSV_DIMENSION_TEXTURE2DARRAY:
mipSlice = dsvDesc.Texture2DArray.MipSlice;
arraySlice = dsvDesc.Texture2DArray.FirstArraySlice;
break;
case D3D11_DSV_DIMENSION_TEXTURE2DMS:
mipSlice = 0;
arraySlice = 0;
break;
case D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY:
mipSlice = 0;
arraySlice = dsvDesc.Texture2DMSArray.FirstArraySlice;
break;
case D3D11_RTV_DIMENSION_UNKNOWN:
UNIMPLEMENTED();
break;
default:
UNREACHABLE();
break;
}
return D3D11CalcSubresource(mipSlice, arraySlice, mipLevels);
}
RenderTarget11::RenderTarget11(Renderer *renderer, ID3D11RenderTargetView *rtv, ID3D11Texture2D *tex, ID3D11ShaderResourceView *srv, GLsizei width, GLsizei height)
{
mRenderer = Renderer11::makeRenderer11(renderer);
mTexture = tex;
mRenderTarget = rtv;
mDepthStencil = NULL;
mShaderResource = srv;
mSubresourceIndex = 0;
if (mRenderTarget && mTexture)
{
D3D11_RENDER_TARGET_VIEW_DESC desc;
mRenderTarget->GetDesc(&desc);
D3D11_TEXTURE2D_DESC texDesc;
mTexture->GetDesc(&texDesc);
mSubresourceIndex = getRTVSubresourceIndex(mTexture, mRenderTarget);
mWidth = width;
mHeight = height;
mSamples = (texDesc.SampleDesc.Count > 1) ? texDesc.SampleDesc.Count : 0;
mInternalFormat = d3d11_gl::ConvertTextureInternalFormat(desc.Format);
mActualFormat = d3d11_gl::ConvertTextureInternalFormat(desc.Format);
}
}
RenderTarget11::RenderTarget11(Renderer *renderer, ID3D11DepthStencilView *dsv, ID3D11Texture2D *tex, ID3D11ShaderResourceView *srv, GLsizei width, GLsizei height)
{
mRenderer = Renderer11::makeRenderer11(renderer);
mTexture = tex;
mRenderTarget = NULL;
mDepthStencil = dsv;
mShaderResource = srv;
mSubresourceIndex = 0;
if (mDepthStencil && mTexture)
{
D3D11_DEPTH_STENCIL_VIEW_DESC desc;
mDepthStencil->GetDesc(&desc);
D3D11_TEXTURE2D_DESC texDesc;
mTexture->GetDesc(&texDesc);
mSubresourceIndex = getDSVSubresourceIndex(mTexture, mDepthStencil);
mWidth = width;
mHeight = height;
mSamples = (texDesc.SampleDesc.Count > 1) ? texDesc.SampleDesc.Count : 0;
mInternalFormat = d3d11_gl::ConvertTextureInternalFormat(desc.Format);
mActualFormat = d3d11_gl::ConvertTextureInternalFormat(desc.Format);
}
}
RenderTarget11::RenderTarget11(Renderer *renderer, GLsizei width, GLsizei height, GLenum format, GLsizei samples, bool depth)
{
mRenderer = Renderer11::makeRenderer11(renderer);
mTexture = NULL;
mRenderTarget = NULL;
mDepthStencil = NULL;
mShaderResource = NULL;
DXGI_FORMAT requestedFormat = gl_d3d11::ConvertRenderbufferFormat(format);
int supportedSamples = mRenderer->getNearestSupportedSamples(requestedFormat, samples);
if (supportedSamples < 0)
{
gl::error(GL_OUT_OF_MEMORY);
return;
}
if (width > 0 && height > 0)
{
// Create texture resource
D3D11_TEXTURE2D_DESC desc;
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = requestedFormat;
desc.SampleDesc.Count = (supportedSamples == 0) ? 1 : supportedSamples;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
desc.BindFlags = (depth ? D3D11_BIND_DEPTH_STENCIL : (D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE));
ID3D11Device *device = mRenderer->getDevice();
HRESULT result = device->CreateTexture2D(&desc, NULL, &mTexture);
if (result == E_OUTOFMEMORY)
{
gl::error(GL_OUT_OF_MEMORY);
return;
}
ASSERT(SUCCEEDED(result));
if (depth)
{
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
dsvDesc.Format = requestedFormat;
dsvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_DSV_DIMENSION_TEXTURE2D : D3D11_DSV_DIMENSION_TEXTURE2DMS;
dsvDesc.Texture2D.MipSlice = 0;
dsvDesc.Flags = 0;
result = device->CreateDepthStencilView(mTexture, &dsvDesc, &mDepthStencil);
if (result == E_OUTOFMEMORY)
{
mTexture->Release();
mTexture = NULL;
gl::error(GL_OUT_OF_MEMORY);
}
ASSERT(SUCCEEDED(result));
}
else
{
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc;
rtvDesc.Format = requestedFormat;
rtvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_RTV_DIMENSION_TEXTURE2D : D3D11_RTV_DIMENSION_TEXTURE2DMS;
rtvDesc.Texture2D.MipSlice = 0;
result = device->CreateRenderTargetView(mTexture, &rtvDesc, &mRenderTarget);
if (result == E_OUTOFMEMORY)
{
mTexture->Release();
mTexture = NULL;
gl::error(GL_OUT_OF_MEMORY);
return;
}
ASSERT(SUCCEEDED(result));
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = requestedFormat;
srvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_SRV_DIMENSION_TEXTURE2D : D3D11_SRV_DIMENSION_TEXTURE2DMS;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = 1;
result = device->CreateShaderResourceView(mTexture, &srvDesc, &mShaderResource);
if (result == E_OUTOFMEMORY)
{
mTexture->Release();
mTexture = NULL;
mRenderTarget->Release();
mRenderTarget = NULL;
gl::error(GL_OUT_OF_MEMORY);
return;
}
ASSERT(SUCCEEDED(result));
}
}
mWidth = width;
mHeight = height;
mInternalFormat = format;
mSamples = supportedSamples;
mActualFormat = d3d11_gl::ConvertTextureInternalFormat(requestedFormat);
mSubresourceIndex = D3D11CalcSubresource(0, 0, 1);
}
RenderTarget11::~RenderTarget11()
{
if (mTexture)
{
mTexture->Release();
mTexture = NULL;
}
if (mRenderTarget)
{
mRenderTarget->Release();
mRenderTarget = NULL;
}
if (mDepthStencil)
{
mDepthStencil->Release();
mDepthStencil = NULL;
}
if (mShaderResource)
{
mShaderResource->Release();
mShaderResource = NULL;
}
}
RenderTarget11 *RenderTarget11::makeRenderTarget11(RenderTarget *target)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::RenderTarget11*, target));
return static_cast<rx::RenderTarget11*>(target);
}
ID3D11Texture2D *RenderTarget11::getTexture() const
{
if (mTexture)
{
mTexture->AddRef();
}
return mTexture;
}
// Adds reference, caller must call Release
ID3D11RenderTargetView *RenderTarget11::getRenderTargetView() const
{
if (mRenderTarget)
{
mRenderTarget->AddRef();
}
return mRenderTarget;
}
// Adds reference, caller must call Release
ID3D11DepthStencilView *RenderTarget11::getDepthStencilView() const
{
if (mDepthStencil)
{
mDepthStencil->AddRef();
}
return mDepthStencil;
}
// Adds reference, caller must call Release
ID3D11ShaderResourceView *RenderTarget11::getShaderResourceView() const
{
if (mShaderResource)
{
mShaderResource->AddRef();
}
return mShaderResource;
}
unsigned int RenderTarget11::getSubresourceIndex() const
{
return mSubresourceIndex;
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/RenderTarget11.cpp | C++ | bsd | 10,673 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// generatemip.h: Defines the GenerateMip function, templated on the format
// type of the image for which mip levels are being generated.
#ifndef LIBGLESV2_RENDERER_GENERATEMIP_H_
#define LIBGLESV2_RENDERER_GENERATEMIP_H_
#include "libGLESv2/mathutil.h"
namespace rx
{
struct L8
{
unsigned char L;
static void average(L8 *dst, const L8 *src1, const L8 *src2)
{
dst->L = ((src1->L ^ src2->L) >> 1) + (src1->L & src2->L);
}
};
typedef L8 R8; // R8 type is functionally equivalent for mip purposes
typedef L8 A8; // A8 type is functionally equivalent for mip purposes
struct A8L8
{
unsigned char L;
unsigned char A;
static void average(A8L8 *dst, const A8L8 *src1, const A8L8 *src2)
{
*(unsigned short*)dst = (((*(unsigned short*)src1 ^ *(unsigned short*)src2) & 0xFEFE) >> 1) + (*(unsigned short*)src1 & *(unsigned short*)src2);
}
};
typedef A8L8 R8G8; // R8G8 type is functionally equivalent for mip purposes
struct A8R8G8B8
{
unsigned char B;
unsigned char G;
unsigned char R;
unsigned char A;
static void average(A8R8G8B8 *dst, const A8R8G8B8 *src1, const A8R8G8B8 *src2)
{
*(unsigned int*)dst = (((*(unsigned int*)src1 ^ *(unsigned int*)src2) & 0xFEFEFEFE) >> 1) + (*(unsigned int*)src1 & *(unsigned int*)src2);
}
};
typedef A8R8G8B8 R8G8B8A8; // R8G8B8A8 type is functionally equivalent for mip purposes
struct A16B16G16R16F
{
unsigned short R;
unsigned short G;
unsigned short B;
unsigned short A;
static void average(A16B16G16R16F *dst, const A16B16G16R16F *src1, const A16B16G16R16F *src2)
{
dst->R = gl::float32ToFloat16((gl::float16ToFloat32(src1->R) + gl::float16ToFloat32(src2->R)) * 0.5f);
dst->G = gl::float32ToFloat16((gl::float16ToFloat32(src1->G) + gl::float16ToFloat32(src2->G)) * 0.5f);
dst->B = gl::float32ToFloat16((gl::float16ToFloat32(src1->B) + gl::float16ToFloat32(src2->B)) * 0.5f);
dst->A = gl::float32ToFloat16((gl::float16ToFloat32(src1->A) + gl::float16ToFloat32(src2->A)) * 0.5f);
}
};
struct R16F
{
unsigned short R;
static void average(R16F *dst, const R16F *src1, const R16F *src2)
{
dst->R = gl::float32ToFloat16((gl::float16ToFloat32(src1->R) + gl::float16ToFloat32(src2->R)) * 0.5f);
}
};
struct R16G16F
{
unsigned short R;
unsigned short G;
static void average(R16G16F *dst, const R16G16F *src1, const R16G16F *src2)
{
dst->R = gl::float32ToFloat16((gl::float16ToFloat32(src1->R) + gl::float16ToFloat32(src2->R)) * 0.5f);
dst->G = gl::float32ToFloat16((gl::float16ToFloat32(src1->G) + gl::float16ToFloat32(src2->G)) * 0.5f);
}
};
struct A32B32G32R32F
{
float R;
float G;
float B;
float A;
static void average(A32B32G32R32F *dst, const A32B32G32R32F *src1, const A32B32G32R32F *src2)
{
dst->R = (src1->R + src2->R) * 0.5f;
dst->G = (src1->G + src2->G) * 0.5f;
dst->B = (src1->B + src2->B) * 0.5f;
dst->A = (src1->A + src2->A) * 0.5f;
}
};
struct R32F
{
float R;
static void average(R32F *dst, const R32F *src1, const R32F *src2)
{
dst->R = (src1->R + src2->R) * 0.5f;
}
};
struct R32G32F
{
float R;
float G;
static void average(R32G32F *dst, const R32G32F *src1, const R32G32F *src2)
{
dst->R = (src1->R + src2->R) * 0.5f;
dst->G = (src1->G + src2->G) * 0.5f;
}
};
struct R32G32B32F
{
float R;
float G;
float B;
static void average(R32G32B32F *dst, const R32G32B32F *src1, const R32G32B32F *src2)
{
dst->R = (src1->R + src2->R) * 0.5f;
dst->G = (src1->G + src2->G) * 0.5f;
dst->B = (src1->B + src2->B) * 0.5f;
}
};
template <typename T>
static void GenerateMip(unsigned int sourceWidth, unsigned int sourceHeight,
const unsigned char *sourceData, int sourcePitch,
unsigned char *destData, int destPitch)
{
unsigned int mipWidth = std::max(1U, sourceWidth >> 1);
unsigned int mipHeight = std::max(1U, sourceHeight >> 1);
if (sourceHeight == 1)
{
ASSERT(sourceWidth != 1);
const T *src = (const T*)sourceData;
T *dst = (T*)destData;
for (unsigned int x = 0; x < mipWidth; x++)
{
T::average(&dst[x], &src[x * 2], &src[x * 2 + 1]);
}
}
else if (sourceWidth == 1)
{
ASSERT(sourceHeight != 1);
for (unsigned int y = 0; y < mipHeight; y++)
{
const T *src0 = (const T*)(sourceData + y * 2 * sourcePitch);
const T *src1 = (const T*)(sourceData + y * 2 * sourcePitch + sourcePitch);
T *dst = (T*)(destData + y * destPitch);
T::average(dst, src0, src1);
}
}
else
{
for (unsigned int y = 0; y < mipHeight; y++)
{
const T *src0 = (const T*)(sourceData + y * 2 * sourcePitch);
const T *src1 = (const T*)(sourceData + y * 2 * sourcePitch + sourcePitch);
T *dst = (T*)(destData + y * destPitch);
for (unsigned int x = 0; x < mipWidth; x++)
{
T tmp0;
T tmp1;
T::average(&tmp0, &src0[x * 2], &src0[x * 2 + 1]);
T::average(&tmp1, &src1[x * 2], &src1[x * 2 + 1]);
T::average(&dst[x], &tmp0, &tmp1);
}
}
}
}
}
#endif // LIBGLESV2_RENDERER_GENERATEMIP_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/generatemip.h | C++ | bsd | 5,673 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Indexffer9.cpp: Defines the D3D9 IndexBuffer implementation.
#include "libGLESv2/renderer/IndexBuffer9.h"
#include "libGLESv2/renderer/Renderer9.h"
namespace rx
{
IndexBuffer9::IndexBuffer9(Renderer9 *const renderer) : mRenderer(renderer)
{
mIndexBuffer = NULL;
mBufferSize = 0;
mIndexType = 0;
mDynamic = false;
}
IndexBuffer9::~IndexBuffer9()
{
if (mIndexBuffer)
{
mIndexBuffer->Release();
mIndexBuffer = NULL;
}
}
bool IndexBuffer9::initialize(unsigned int bufferSize, GLenum indexType, bool dynamic)
{
if (mIndexBuffer)
{
mIndexBuffer->Release();
mIndexBuffer = NULL;
}
updateSerial();
if (bufferSize > 0)
{
D3DFORMAT format;
if (indexType == GL_UNSIGNED_SHORT || indexType == GL_UNSIGNED_BYTE)
{
format = D3DFMT_INDEX16;
}
else if (indexType == GL_UNSIGNED_INT)
{
if (mRenderer->get32BitIndexSupport())
{
format = D3DFMT_INDEX32;
}
else
{
ERR("Attempted to create a 32-bit index buffer but renderer does not support 32-bit indices.");
return false;
}
}
else
{
ERR("Invalid index type %u.", indexType);
return false;
}
DWORD usageFlags = D3DUSAGE_WRITEONLY;
if (dynamic)
{
usageFlags |= D3DUSAGE_DYNAMIC;
}
HRESULT result = mRenderer->createIndexBuffer(bufferSize, usageFlags, format, &mIndexBuffer);
if (FAILED(result))
{
ERR("Failed to create an index buffer of size %u, result: 0x%08x.", mBufferSize, result);
return false;
}
}
mBufferSize = bufferSize;
mIndexType = indexType;
mDynamic = dynamic;
return true;
}
IndexBuffer9 *IndexBuffer9::makeIndexBuffer9(IndexBuffer *indexBuffer)
{
ASSERT(HAS_DYNAMIC_TYPE(IndexBuffer9*, indexBuffer));
return static_cast<IndexBuffer9*>(indexBuffer);
}
bool IndexBuffer9::mapBuffer(unsigned int offset, unsigned int size, void** outMappedMemory)
{
if (mIndexBuffer)
{
DWORD lockFlags = mDynamic ? D3DLOCK_NOOVERWRITE : 0;
void *mapPtr = NULL;
HRESULT result = mIndexBuffer->Lock(offset, size, &mapPtr, lockFlags);
if (FAILED(result))
{
ERR("Index buffer lock failed with error 0x%08x", result);
return false;
}
*outMappedMemory = mapPtr;
return true;
}
else
{
ERR("Index buffer not initialized.");
return false;
}
}
bool IndexBuffer9::unmapBuffer()
{
if (mIndexBuffer)
{
HRESULT result = mIndexBuffer->Unlock();
if (FAILED(result))
{
ERR("Index buffer unlock failed with error 0x%08x", result);
return false;
}
return true;
}
else
{
ERR("Index buffer not initialized.");
return false;
}
}
GLenum IndexBuffer9::getIndexType() const
{
return mIndexType;
}
unsigned int IndexBuffer9::getBufferSize() const
{
return mBufferSize;
}
bool IndexBuffer9::setSize(unsigned int bufferSize, GLenum indexType)
{
if (bufferSize > mBufferSize || indexType != mIndexType)
{
return initialize(bufferSize, indexType, mDynamic);
}
else
{
return true;
}
}
bool IndexBuffer9::discard()
{
if (mIndexBuffer)
{
void *dummy;
HRESULT result;
result = mIndexBuffer->Lock(0, 1, &dummy, D3DLOCK_DISCARD);
if (FAILED(result))
{
ERR("Discard lock failed with error 0x%08x", result);
return false;
}
result = mIndexBuffer->Unlock();
if (FAILED(result))
{
ERR("Discard unlock failed with error 0x%08x", result);
return false;
}
return true;
}
else
{
ERR("Index buffer not initialized.");
return false;
}
}
D3DFORMAT IndexBuffer9::getIndexFormat() const
{
switch (mIndexType)
{
case GL_UNSIGNED_BYTE: return D3DFMT_INDEX16;
case GL_UNSIGNED_SHORT: return D3DFMT_INDEX16;
case GL_UNSIGNED_INT: return D3DFMT_INDEX32;
default: UNREACHABLE(); return D3DFMT_UNKNOWN;
}
}
IDirect3DIndexBuffer9 * IndexBuffer9::getBuffer() const
{
return mIndexBuffer;
}
} | 010smithzhang-ddd | src/libGLESv2/renderer/IndexBuffer9.cpp | C++ | bsd | 4,655 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Image11.h: Defines the rx::Image11 class, which acts as the interface to
// the actual underlying resources of a Texture
#ifndef LIBGLESV2_RENDERER_IMAGE11_H_
#define LIBGLESV2_RENDERER_IMAGE11_H_
#include "libGLESv2/renderer/Image.h"
#include "common/debug.h"
namespace gl
{
class Framebuffer;
}
namespace rx
{
class Renderer;
class Renderer11;
class TextureStorageInterface2D;
class TextureStorageInterfaceCube;
class Image11 : public Image
{
public:
Image11();
virtual ~Image11();
static Image11 *makeImage11(Image *img);
static void generateMipmap(Image11 *dest, Image11 *src);
virtual bool isDirty() const;
virtual bool updateSurface(TextureStorageInterface2D *storage, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
virtual bool updateSurface(TextureStorageInterfaceCube *storage, int face, int level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
virtual bool redefine(Renderer *renderer, GLint internalformat, GLsizei width, GLsizei height, bool forceRelease);
virtual bool isRenderableFormat() const;
DXGI_FORMAT getDXGIFormat() const;
virtual void loadData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLint unpackAlignment, const void *input);
virtual void loadCompressedData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
const void *input);
virtual void copy(GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, gl::Framebuffer *source);
protected:
HRESULT map(D3D11_MAPPED_SUBRESOURCE *map);
void unmap();
private:
DISALLOW_COPY_AND_ASSIGN(Image11);
ID3D11Texture2D *getStagingTexture();
unsigned int getStagingSubresource();
void createStagingTexture();
Renderer11 *mRenderer;
DXGI_FORMAT mDXGIFormat;
ID3D11Texture2D *mStagingTexture;
unsigned int mStagingSubresource;
};
}
#endif // LIBGLESV2_RENDERER_IMAGE11_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Image11.h | C++ | bsd | 2,189 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// TextureStorage9.h: Defines the abstract rx::TextureStorage9 class and its concrete derived
// classes TextureStorage9_2D and TextureStorage9_Cube, which act as the interface to the
// D3D9 texture.
#ifndef LIBGLESV2_RENDERER_TEXTURESTORAGE9_H_
#define LIBGLESV2_RENDERER_TEXTURESTORAGE9_H_
#include "libGLESv2/renderer/TextureStorage.h"
#include "common/debug.h"
namespace rx
{
class Renderer9;
class SwapChain9;
class RenderTarget;
class RenderTarget9;
class Blit;
class TextureStorage9 : public TextureStorage
{
public:
TextureStorage9(Renderer *renderer, DWORD usage);
virtual ~TextureStorage9();
static TextureStorage9 *makeTextureStorage9(TextureStorage *storage);
static DWORD GetTextureUsage(D3DFORMAT d3dfmt, GLenum glusage, bool forceRenderable);
static bool IsTextureFormatRenderable(D3DFORMAT format);
D3DPOOL getPool() const;
DWORD getUsage() const;
virtual IDirect3DBaseTexture9 *getBaseTexture() const = 0;
virtual RenderTarget *getRenderTarget() { return NULL; }
virtual RenderTarget *getRenderTarget(GLenum faceTarget) { return NULL; }
virtual void generateMipmap(int level) {};
virtual void generateMipmap(int face, int level) {};
virtual int getLodOffset() const;
virtual bool isRenderTarget() const;
virtual bool isManaged() const;
virtual int levelCount();
protected:
int mLodOffset;
Renderer9 *mRenderer;
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorage9);
const DWORD mD3DUsage;
const D3DPOOL mD3DPool;
};
class TextureStorage9_2D : public TextureStorage9
{
public:
TextureStorage9_2D(Renderer *renderer, SwapChain9 *swapchain);
TextureStorage9_2D(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height);
virtual ~TextureStorage9_2D();
static TextureStorage9_2D *makeTextureStorage9_2D(TextureStorage *storage);
IDirect3DSurface9 *getSurfaceLevel(int level, bool dirty);
virtual RenderTarget *getRenderTarget();
virtual IDirect3DBaseTexture9 *getBaseTexture() const;
virtual void generateMipmap(int level);
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorage9_2D);
void initializeRenderTarget();
IDirect3DTexture9 *mTexture;
RenderTarget9 *mRenderTarget;
};
class TextureStorage9_Cube : public TextureStorage9
{
public:
TextureStorage9_Cube(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size);
virtual ~TextureStorage9_Cube();
static TextureStorage9_Cube *makeTextureStorage9_Cube(TextureStorage *storage);
IDirect3DSurface9 *getCubeMapSurface(GLenum faceTarget, int level, bool dirty);
virtual RenderTarget *getRenderTarget(GLenum faceTarget);
virtual IDirect3DBaseTexture9 *getBaseTexture() const;
virtual void generateMipmap(int face, int level);
private:
DISALLOW_COPY_AND_ASSIGN(TextureStorage9_Cube);
void initializeRenderTarget();
IDirect3DCubeTexture9 *mTexture;
RenderTarget9 *mRenderTarget[6];
};
}
#endif // LIBGLESV2_RENDERER_TEXTURESTORAGE9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/TextureStorage9.h | C++ | bsd | 3,292 |
#include "precompiled.h"
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Blit.cpp: Surface copy utility class.
#include "libGLESv2/renderer/Blit.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/renderer9_utils.h"
#include "libGLESv2/renderer/TextureStorage9.h"
#include "libGLESv2/renderer/RenderTarget9.h"
#include "libGLESv2/renderer/Renderer9.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/Renderbuffer.h"
namespace
{
#include "libGLESv2/renderer/shaders/compiled/standardvs.h"
#include "libGLESv2/renderer/shaders/compiled/flipyvs.h"
#include "libGLESv2/renderer/shaders/compiled/passthroughps.h"
#include "libGLESv2/renderer/shaders/compiled/luminanceps.h"
#include "libGLESv2/renderer/shaders/compiled/componentmaskps.h"
const BYTE* const g_shaderCode[] =
{
g_vs20_standardvs,
g_vs20_flipyvs,
g_ps20_passthroughps,
g_ps20_luminanceps,
g_ps20_componentmaskps
};
const size_t g_shaderSize[] =
{
sizeof(g_vs20_standardvs),
sizeof(g_vs20_flipyvs),
sizeof(g_ps20_passthroughps),
sizeof(g_ps20_luminanceps),
sizeof(g_ps20_componentmaskps)
};
}
namespace rx
{
Blit::Blit(rx::Renderer9 *renderer)
: mRenderer(renderer), mQuadVertexBuffer(NULL), mQuadVertexDeclaration(NULL), mSavedStateBlock(NULL), mSavedRenderTarget(NULL), mSavedDepthStencil(NULL)
{
initGeometry();
memset(mCompiledShaders, 0, sizeof(mCompiledShaders));
}
Blit::~Blit()
{
if (mSavedStateBlock) mSavedStateBlock->Release();
if (mQuadVertexBuffer) mQuadVertexBuffer->Release();
if (mQuadVertexDeclaration) mQuadVertexDeclaration->Release();
for (int i = 0; i < SHADER_COUNT; i++)
{
if (mCompiledShaders[i])
{
mCompiledShaders[i]->Release();
}
}
}
void Blit::initGeometry()
{
static const float quad[] =
{
-1, -1,
-1, 1,
1, -1,
1, 1
};
IDirect3DDevice9 *device = mRenderer->getDevice();
HRESULT result = device->CreateVertexBuffer(sizeof(quad), D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, &mQuadVertexBuffer, NULL);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
return gl::error(GL_OUT_OF_MEMORY);
}
void *lockPtr = NULL;
result = mQuadVertexBuffer->Lock(0, 0, &lockPtr, 0);
if (FAILED(result) || lockPtr == NULL)
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
return gl::error(GL_OUT_OF_MEMORY);
}
memcpy(lockPtr, quad, sizeof(quad));
mQuadVertexBuffer->Unlock();
static const D3DVERTEXELEMENT9 elements[] =
{
{ 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
D3DDECL_END()
};
result = device->CreateVertexDeclaration(elements, &mQuadVertexDeclaration);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
return gl::error(GL_OUT_OF_MEMORY);
}
}
template <class D3DShaderType>
bool Blit::setShader(ShaderId source, const char *profile,
D3DShaderType *(rx::Renderer9::*createShader)(const DWORD *, size_t length),
HRESULT (WINAPI IDirect3DDevice9::*setShader)(D3DShaderType*))
{
IDirect3DDevice9 *device = mRenderer->getDevice();
D3DShaderType *shader;
if (mCompiledShaders[source] != NULL)
{
shader = static_cast<D3DShaderType*>(mCompiledShaders[source]);
}
else
{
const BYTE* shaderCode = g_shaderCode[source];
size_t shaderSize = g_shaderSize[source];
shader = (mRenderer->*createShader)(reinterpret_cast<const DWORD*>(shaderCode), shaderSize);
if (!shader)
{
ERR("Failed to create shader for blit operation");
return false;
}
mCompiledShaders[source] = shader;
}
HRESULT hr = (device->*setShader)(shader);
if (FAILED(hr))
{
ERR("Failed to set shader for blit operation");
return false;
}
return true;
}
bool Blit::setVertexShader(ShaderId shader)
{
return setShader<IDirect3DVertexShader9>(shader, "vs_2_0", &rx::Renderer9::createVertexShader, &IDirect3DDevice9::SetVertexShader);
}
bool Blit::setPixelShader(ShaderId shader)
{
return setShader<IDirect3DPixelShader9>(shader, "ps_2_0", &rx::Renderer9::createPixelShader, &IDirect3DDevice9::SetPixelShader);
}
RECT Blit::getSurfaceRect(IDirect3DSurface9 *surface) const
{
D3DSURFACE_DESC desc;
surface->GetDesc(&desc);
RECT rect;
rect.left = 0;
rect.top = 0;
rect.right = desc.Width;
rect.bottom = desc.Height;
return rect;
}
bool Blit::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
{
IDirect3DTexture9 *texture = copySurfaceToTexture(source, getSurfaceRect(source));
if (!texture)
{
return false;
}
IDirect3DDevice9 *device = mRenderer->getDevice();
saveState();
device->SetTexture(0, texture);
device->SetRenderTarget(0, dest);
setVertexShader(SHADER_VS_STANDARD);
setPixelShader(SHADER_PS_PASSTHROUGH);
setCommonBlitState();
device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
setViewport(getSurfaceRect(dest), 0, 0);
render();
texture->Release();
restoreState();
return true;
}
bool Blit::copy(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat, GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level)
{
RenderTarget9 *renderTarget = NULL;
IDirect3DSurface9 *source = NULL;
gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer(0);
if (colorbuffer)
{
renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
}
if (renderTarget)
{
source = renderTarget->getSurface();
}
if (!source)
{
ERR("Failed to retrieve the render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
TextureStorage9_2D *storage9 = TextureStorage9_2D::makeTextureStorage9_2D(storage->getStorageInstance());
IDirect3DSurface9 *destSurface = storage9->getSurfaceLevel(level, true);
bool result = false;
if (destSurface)
{
result = copy(source, sourceRect, destFormat, xoffset, yoffset, destSurface);
destSurface->Release();
}
source->Release();
return result;
}
bool Blit::copy(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat, GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level)
{
RenderTarget9 *renderTarget = NULL;
IDirect3DSurface9 *source = NULL;
gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer(0);
if (colorbuffer)
{
renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
}
if (renderTarget)
{
source = renderTarget->getSurface();
}
if (!source)
{
ERR("Failed to retrieve the render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
TextureStorage9_Cube *storage9 = TextureStorage9_Cube::makeTextureStorage9_Cube(storage->getStorageInstance());
IDirect3DSurface9 *destSurface = storage9->getCubeMapSurface(target, level, true);
bool result = false;
if (destSurface)
{
result = copy(source, sourceRect, destFormat, xoffset, yoffset, destSurface);
destSurface->Release();
}
source->Release();
return result;
}
bool Blit::copy(IDirect3DSurface9 *source, const RECT &sourceRect, GLenum destFormat, GLint xoffset, GLint yoffset, IDirect3DSurface9 *dest)
{
if (!dest)
{
return false;
}
IDirect3DDevice9 *device = mRenderer->getDevice();
D3DSURFACE_DESC sourceDesc;
D3DSURFACE_DESC destDesc;
source->GetDesc(&sourceDesc);
dest->GetDesc(&destDesc);
if (sourceDesc.Format == destDesc.Format && destDesc.Usage & D3DUSAGE_RENDERTARGET &&
d3d9_gl::IsFormatChannelEquivalent(destDesc.Format, destFormat)) // Can use StretchRect
{
RECT destRect = {xoffset, yoffset, xoffset + (sourceRect.right - sourceRect.left), yoffset + (sourceRect.bottom - sourceRect.top)};
HRESULT result = device->StretchRect(source, &sourceRect, dest, &destRect, D3DTEXF_POINT);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
return gl::error(GL_OUT_OF_MEMORY, false);
}
}
else
{
return formatConvert(source, sourceRect, destFormat, xoffset, yoffset, dest);
}
return true;
}
bool Blit::formatConvert(IDirect3DSurface9 *source, const RECT &sourceRect, GLenum destFormat, GLint xoffset, GLint yoffset, IDirect3DSurface9 *dest)
{
IDirect3DTexture9 *texture = copySurfaceToTexture(source, sourceRect);
if (!texture)
{
return false;
}
IDirect3DDevice9 *device = mRenderer->getDevice();
saveState();
device->SetTexture(0, texture);
device->SetRenderTarget(0, dest);
setViewport(sourceRect, xoffset, yoffset);
setCommonBlitState();
if (setFormatConvertShaders(destFormat))
{
render();
}
texture->Release();
restoreState();
return true;
}
bool Blit::setFormatConvertShaders(GLenum destFormat)
{
bool okay = setVertexShader(SHADER_VS_STANDARD);
switch (destFormat)
{
default: UNREACHABLE();
case GL_RGBA:
case GL_BGRA_EXT:
case GL_RGB:
case GL_ALPHA:
okay = okay && setPixelShader(SHADER_PS_COMPONENTMASK);
break;
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
okay = okay && setPixelShader(SHADER_PS_LUMINANCE);
break;
}
if (!okay)
{
return false;
}
enum { X = 0, Y = 1, Z = 2, W = 3 };
// The meaning of this constant depends on the shader that was selected.
// See the shader assembly code above for details.
float psConst0[4] = { 0, 0, 0, 0 };
switch (destFormat)
{
default: UNREACHABLE();
case GL_RGBA:
case GL_BGRA_EXT:
psConst0[X] = 1;
psConst0[Z] = 1;
break;
case GL_RGB:
psConst0[X] = 1;
psConst0[W] = 1;
break;
case GL_ALPHA:
psConst0[Z] = 1;
break;
case GL_LUMINANCE:
psConst0[Y] = 1;
break;
case GL_LUMINANCE_ALPHA:
psConst0[X] = 1;
break;
}
mRenderer->getDevice()->SetPixelShaderConstantF(0, psConst0, 1);
return true;
}
IDirect3DTexture9 *Blit::copySurfaceToTexture(IDirect3DSurface9 *surface, const RECT &sourceRect)
{
if (!surface)
{
return NULL;
}
IDirect3DDevice9 *device = mRenderer->getDevice();
D3DSURFACE_DESC sourceDesc;
surface->GetDesc(&sourceDesc);
// Copy the render target into a texture
IDirect3DTexture9 *texture;
HRESULT result = device->CreateTexture(sourceRect.right - sourceRect.left, sourceRect.bottom - sourceRect.top, 1, D3DUSAGE_RENDERTARGET, sourceDesc.Format, D3DPOOL_DEFAULT, &texture, NULL);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
return gl::error(GL_OUT_OF_MEMORY, (IDirect3DTexture9*)NULL);
}
IDirect3DSurface9 *textureSurface;
result = texture->GetSurfaceLevel(0, &textureSurface);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
texture->Release();
return gl::error(GL_OUT_OF_MEMORY, (IDirect3DTexture9*)NULL);
}
mRenderer->endScene();
result = device->StretchRect(surface, &sourceRect, textureSurface, NULL, D3DTEXF_NONE);
textureSurface->Release();
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
texture->Release();
return gl::error(GL_OUT_OF_MEMORY, (IDirect3DTexture9*)NULL);
}
return texture;
}
void Blit::setViewport(const RECT &sourceRect, GLint xoffset, GLint yoffset)
{
IDirect3DDevice9 *device = mRenderer->getDevice();
D3DVIEWPORT9 vp;
vp.X = xoffset;
vp.Y = yoffset;
vp.Width = sourceRect.right - sourceRect.left;
vp.Height = sourceRect.bottom - sourceRect.top;
vp.MinZ = 0.0f;
vp.MaxZ = 1.0f;
device->SetViewport(&vp);
float halfPixelAdjust[4] = { -1.0f/vp.Width, 1.0f/vp.Height, 0, 0 };
device->SetVertexShaderConstantF(0, halfPixelAdjust, 1);
}
void Blit::setCommonBlitState()
{
IDirect3DDevice9 *device = mRenderer->getDevice();
device->SetDepthStencilSurface(NULL);
device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
device->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, FALSE);
device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
RECT scissorRect = {0}; // Scissoring is disabled for flipping, but we need this to capture and restore the old rectangle
device->SetScissorRect(&scissorRect);
for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
device->SetStreamSourceFreq(i, 1);
}
}
void Blit::render()
{
IDirect3DDevice9 *device = mRenderer->getDevice();
HRESULT hr = device->SetStreamSource(0, mQuadVertexBuffer, 0, 2 * sizeof(float));
hr = device->SetVertexDeclaration(mQuadVertexDeclaration);
mRenderer->startScene();
hr = device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
}
void Blit::saveState()
{
IDirect3DDevice9 *device = mRenderer->getDevice();
HRESULT hr;
device->GetDepthStencilSurface(&mSavedDepthStencil);
device->GetRenderTarget(0, &mSavedRenderTarget);
if (mSavedStateBlock == NULL)
{
hr = device->BeginStateBlock();
ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
setCommonBlitState();
static const float dummyConst[4] = { 0, 0, 0, 0 };
device->SetVertexShader(NULL);
device->SetVertexShaderConstantF(0, dummyConst, 1);
device->SetPixelShader(NULL);
device->SetPixelShaderConstantF(0, dummyConst, 1);
D3DVIEWPORT9 dummyVp;
dummyVp.X = 0;
dummyVp.Y = 0;
dummyVp.Width = 1;
dummyVp.Height = 1;
dummyVp.MinZ = 0;
dummyVp.MaxZ = 1;
device->SetViewport(&dummyVp);
device->SetTexture(0, NULL);
device->SetStreamSource(0, mQuadVertexBuffer, 0, 0);
device->SetVertexDeclaration(mQuadVertexDeclaration);
hr = device->EndStateBlock(&mSavedStateBlock);
ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
}
ASSERT(mSavedStateBlock != NULL);
if (mSavedStateBlock != NULL)
{
hr = mSavedStateBlock->Capture();
ASSERT(SUCCEEDED(hr));
}
}
void Blit::restoreState()
{
IDirect3DDevice9 *device = mRenderer->getDevice();
device->SetDepthStencilSurface(mSavedDepthStencil);
if (mSavedDepthStencil != NULL)
{
mSavedDepthStencil->Release();
mSavedDepthStencil = NULL;
}
device->SetRenderTarget(0, mSavedRenderTarget);
if (mSavedRenderTarget != NULL)
{
mSavedRenderTarget->Release();
mSavedRenderTarget = NULL;
}
ASSERT(mSavedStateBlock != NULL);
if (mSavedStateBlock != NULL)
{
mSavedStateBlock->Apply();
}
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/Blit.cpp | C++ | bsd | 16,298 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Query9.h: Defines the rx::Query9 class which implements rx::QueryImpl.
#ifndef LIBGLESV2_RENDERER_QUERY9_H_
#define LIBGLESV2_RENDERER_QUERY9_H_
#include "libGLESv2/renderer/QueryImpl.h"
namespace rx
{
class Renderer9;
class Query9 : public QueryImpl
{
public:
Query9(rx::Renderer9 *renderer, GLenum type);
virtual ~Query9();
void begin();
void end();
GLuint getResult();
GLboolean isResultAvailable();
private:
DISALLOW_COPY_AND_ASSIGN(Query9);
GLboolean testQuery();
rx::Renderer9 *mRenderer;
IDirect3DQuery9 *mQuery;
};
}
#endif // LIBGLESV2_RENDERER_QUERY9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Query9.h | C++ | bsd | 802 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ImageSSE2.cpp: Implements SSE2-based functions of rx::Image class. It's
// in a separated file for GCC, which can enable SSE usage only per-file,
// not for code blocks that use SSE2 explicitly.
#include "libGLESv2/Texture.h"
#include "libGLESv2/renderer/Image.h"
namespace rx
{
void Image::loadRGBAUByteDataToBGRASSE2(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned int *source = NULL;
unsigned int *dest = NULL;
__m128i brMask = _mm_set1_epi32(0x00ff00ff);
for (int y = 0; y < height; y++)
{
source = reinterpret_cast<const unsigned int*>(static_cast<const unsigned char*>(input) + y * inputPitch);
dest = reinterpret_cast<unsigned int*>(static_cast<unsigned char*>(output) + y * outputPitch);
int x = 0;
// Make output writes aligned
for (x = 0; ((reinterpret_cast<intptr_t>(&dest[x]) & 15) != 0) && x < width; x++)
{
unsigned int rgba = source[x];
dest[x] = (_rotl(rgba, 16) & 0x00ff00ff) | (rgba & 0xff00ff00);
}
for (; x + 3 < width; x += 4)
{
__m128i sourceData = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&source[x]));
// Mask out g and a, which don't change
__m128i gaComponents = _mm_andnot_si128(brMask, sourceData);
// Mask out b and r
__m128i brComponents = _mm_and_si128(sourceData, brMask);
// Swap b and r
__m128i brSwapped = _mm_shufflehi_epi16(_mm_shufflelo_epi16(brComponents, _MM_SHUFFLE(2, 3, 0, 1)), _MM_SHUFFLE(2, 3, 0, 1));
__m128i result = _mm_or_si128(gaComponents, brSwapped);
_mm_store_si128(reinterpret_cast<__m128i*>(&dest[x]), result);
}
// Perform leftover writes
for (; x < width; x++)
{
unsigned int rgba = source[x];
dest[x] = (_rotl(rgba, 16) & 0x00ff00ff) | (rgba & 0xff00ff00);
}
}
}
void Image::loadAlphaDataToBGRASSE2(GLsizei width, GLsizei height,
int inputPitch, const void *input, size_t outputPitch, void *output)
{
const unsigned char *source = NULL;
unsigned int *dest = NULL;
__m128i zeroWide = _mm_setzero_si128();
for (int y = 0; y < height; y++)
{
source = static_cast<const unsigned char*>(input) + y * inputPitch;
dest = reinterpret_cast<unsigned int*>(static_cast<unsigned char*>(output) + y * outputPitch);
int x;
// Make output writes aligned
for (x = 0; ((reinterpret_cast<intptr_t>(&dest[x]) & 0xF) != 0 && x < width); x++)
{
dest[x] = static_cast<unsigned int>(source[x]) << 24;
}
for (; x + 7 < width; x += 8)
{
__m128i sourceData = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(&source[x]));
// Interleave each byte to 16bit, make the lower byte to zero
sourceData = _mm_unpacklo_epi8(zeroWide, sourceData);
// Interleave each 16bit to 32bit, make the lower 16bit to zero
__m128i lo = _mm_unpacklo_epi16(zeroWide, sourceData);
__m128i hi = _mm_unpackhi_epi16(zeroWide, sourceData);
_mm_store_si128(reinterpret_cast<__m128i*>(&dest[x]), lo);
_mm_store_si128(reinterpret_cast<__m128i*>(&dest[x + 4]), hi);
}
// Handle the remainder
for (; x < width; x++)
{
dest[x] = static_cast<unsigned int>(source[x]) << 24;
}
}
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/ImageSSE2.cpp | C++ | bsd | 3,808 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SwapChain.h: Defines a back-end specific class that hides the details of the
// implementation-specific swapchain.
#ifndef LIBGLESV2_RENDERER_SWAPCHAIN_H_
#define LIBGLESV2_RENDERER_SWAPCHAIN_H_
#include "common/angleutils.h"
namespace rx
{
class SwapChain
{
public:
SwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
: mWindow(window), mShareHandle(shareHandle), mBackBufferFormat(backBufferFormat), mDepthBufferFormat(depthBufferFormat)
{
}
virtual ~SwapChain() {};
virtual EGLint resize(EGLint backbufferWidth, EGLint backbufferSize) = 0;
virtual EGLint reset(EGLint backbufferWidth, EGLint backbufferHeight, EGLint swapInterval) = 0;
virtual EGLint swapRect(EGLint x, EGLint y, EGLint width, EGLint height) = 0;
virtual void recreate() = 0;
virtual HANDLE getShareHandle() {return mShareHandle;};
protected:
const HWND mWindow; // Window that the surface is created for.
const GLenum mBackBufferFormat;
const GLenum mDepthBufferFormat;
HANDLE mShareHandle;
};
}
#endif // LIBGLESV2_RENDERER_SWAPCHAIN_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/SwapChain.h | C++ | bsd | 1,320 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// RenderTarget9.cpp: Implements a D3D9-specific wrapper for IDirect3DSurface9
// pointers retained by renderbuffers.
#include "libGLESv2/renderer/RenderTarget9.h"
#include "libGLESv2/renderer/Renderer9.h"
#include "libGLESv2/renderer/renderer9_utils.h"
#include "libGLESv2/main.h"
namespace rx
{
RenderTarget9::RenderTarget9(Renderer *renderer, IDirect3DSurface9 *surface)
{
mRenderer = Renderer9::makeRenderer9(renderer);
mRenderTarget = surface;
if (mRenderTarget)
{
D3DSURFACE_DESC description;
mRenderTarget->GetDesc(&description);
mWidth = description.Width;
mHeight = description.Height;
mInternalFormat = d3d9_gl::GetEquivalentFormat(description.Format);
mActualFormat = d3d9_gl::GetEquivalentFormat(description.Format);
mSamples = d3d9_gl::GetSamplesFromMultisampleType(description.MultiSampleType);
}
}
RenderTarget9::RenderTarget9(Renderer *renderer, GLsizei width, GLsizei height, GLenum format, GLsizei samples)
{
mRenderer = Renderer9::makeRenderer9(renderer);
mRenderTarget = NULL;
D3DFORMAT requestedFormat = gl_d3d9::ConvertRenderbufferFormat(format);
int supportedSamples = mRenderer->getNearestSupportedSamples(requestedFormat, samples);
if (supportedSamples == -1)
{
gl::error(GL_OUT_OF_MEMORY);
return;
}
HRESULT result = D3DERR_INVALIDCALL;
if (width > 0 && height > 0)
{
if (requestedFormat == D3DFMT_D24S8)
{
result = mRenderer->getDevice()->CreateDepthStencilSurface(width, height, requestedFormat,
gl_d3d9::GetMultisampleTypeFromSamples(supportedSamples),
0, FALSE, &mRenderTarget, NULL);
}
else
{
result = mRenderer->getDevice()->CreateRenderTarget(width, height, requestedFormat,
gl_d3d9::GetMultisampleTypeFromSamples(supportedSamples),
0, FALSE, &mRenderTarget, NULL);
}
if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY)
{
gl::error(GL_OUT_OF_MEMORY);
return;
}
ASSERT(SUCCEEDED(result));
}
mWidth = width;
mHeight = height;
mInternalFormat = format;
mSamples = supportedSamples;
mActualFormat = d3d9_gl::GetEquivalentFormat(requestedFormat);
}
RenderTarget9::~RenderTarget9()
{
if (mRenderTarget)
{
mRenderTarget->Release();
}
}
RenderTarget9 *RenderTarget9::makeRenderTarget9(RenderTarget *target)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::RenderTarget9*, target));
return static_cast<rx::RenderTarget9*>(target);
}
IDirect3DSurface9 *RenderTarget9::getSurface()
{
// Caller is responsible for releasing the returned surface reference.
if (mRenderTarget)
{
mRenderTarget->AddRef();
}
return mRenderTarget;
}
} | 010smithzhang-ddd | src/libGLESv2/renderer/RenderTarget9.cpp | C++ | bsd | 3,296 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// TextureStorage11.cpp: Implements the abstract rx::TextureStorage11 class and its concrete derived
// classes TextureStorage11_2D and TextureStorage11_Cube, which act as the interface to the D3D11 texture.
#include "libGLESv2/renderer/TextureStorage11.h"
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/renderer/RenderTarget11.h"
#include "libGLESv2/renderer/SwapChain11.h"
#include "libGLESv2/renderer/renderer11_utils.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/main.h"
namespace rx
{
TextureStorage11::TextureStorage11(Renderer *renderer, UINT bindFlags)
: mBindFlags(bindFlags),
mLodOffset(0),
mMipLevels(0),
mTexture(NULL),
mTextureFormat(DXGI_FORMAT_UNKNOWN),
mShaderResourceFormat(DXGI_FORMAT_UNKNOWN),
mRenderTargetFormat(DXGI_FORMAT_UNKNOWN),
mDepthStencilFormat(DXGI_FORMAT_UNKNOWN),
mSRV(NULL),
mTextureWidth(0),
mTextureHeight(0)
{
mRenderer = Renderer11::makeRenderer11(renderer);
}
TextureStorage11::~TextureStorage11()
{
}
TextureStorage11 *TextureStorage11::makeTextureStorage11(TextureStorage *storage)
{
ASSERT(HAS_DYNAMIC_TYPE(TextureStorage11*, storage));
return static_cast<TextureStorage11*>(storage);
}
DWORD TextureStorage11::GetTextureBindFlags(DXGI_FORMAT format, GLenum glusage, bool forceRenderable)
{
UINT bindFlags = D3D11_BIND_SHADER_RESOURCE;
if (d3d11::IsDepthStencilFormat(format))
{
bindFlags |= D3D11_BIND_DEPTH_STENCIL;
}
else if(forceRenderable || (TextureStorage11::IsTextureFormatRenderable(format) && (glusage == GL_FRAMEBUFFER_ATTACHMENT_ANGLE)))
{
bindFlags |= D3D11_BIND_RENDER_TARGET;
}
return bindFlags;
}
bool TextureStorage11::IsTextureFormatRenderable(DXGI_FORMAT format)
{
switch(format)
{
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_A8_UNORM:
case DXGI_FORMAT_R32G32B32A32_FLOAT:
case DXGI_FORMAT_R32G32B32_FLOAT:
case DXGI_FORMAT_R16G16B16A16_FLOAT:
case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_R8_UNORM:
case DXGI_FORMAT_R8G8_UNORM:
case DXGI_FORMAT_R16_FLOAT:
case DXGI_FORMAT_R16G16_FLOAT:
return true;
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC3_UNORM:
return false;
default:
UNREACHABLE();
return false;
}
}
UINT TextureStorage11::getBindFlags() const
{
return mBindFlags;
}
ID3D11Texture2D *TextureStorage11::getBaseTexture() const
{
return mTexture;
}
int TextureStorage11::getLodOffset() const
{
return mLodOffset;
}
bool TextureStorage11::isRenderTarget() const
{
return (mBindFlags & (D3D11_BIND_RENDER_TARGET | D3D11_BIND_DEPTH_STENCIL)) != 0;
}
bool TextureStorage11::isManaged() const
{
return false;
}
int TextureStorage11::levelCount()
{
int levels = 0;
if (getBaseTexture())
{
levels = mMipLevels - getLodOffset();
}
return levels;
}
UINT TextureStorage11::getSubresourceIndex(int level, int faceIndex)
{
UINT index = 0;
if (getBaseTexture())
{
index = D3D11CalcSubresource(level, faceIndex, mMipLevels);
}
return index;
}
bool TextureStorage11::updateSubresourceLevel(ID3D11Texture2D *srcTexture, unsigned int sourceSubresource,
int level, int face, GLint xoffset, GLint yoffset,
GLsizei width, GLsizei height)
{
if (srcTexture)
{
// Round up the width and height to the nearest multiple of dimension alignment
unsigned int dimensionAlignment = d3d11::GetTextureFormatDimensionAlignment(mTextureFormat);
width = width + dimensionAlignment - 1 - (width - 1) % dimensionAlignment;
height = height + dimensionAlignment - 1 - (height - 1) % dimensionAlignment;
D3D11_BOX srcBox;
srcBox.left = xoffset;
srcBox.top = yoffset;
srcBox.right = xoffset + width;
srcBox.bottom = yoffset + height;
srcBox.front = 0;
srcBox.back = 1;
ID3D11DeviceContext *context = mRenderer->getDeviceContext();
ASSERT(getBaseTexture());
context->CopySubresourceRegion(getBaseTexture(), getSubresourceIndex(level + mLodOffset, face),
xoffset, yoffset, 0, srcTexture, sourceSubresource, &srcBox);
return true;
}
return false;
}
void TextureStorage11::generateMipmapLayer(RenderTarget11 *source, RenderTarget11 *dest)
{
if (source && dest)
{
ID3D11ShaderResourceView *sourceSRV = source->getShaderResourceView();
ID3D11RenderTargetView *destRTV = dest->getRenderTargetView();
if (sourceSRV && destRTV)
{
gl::Rectangle sourceArea;
sourceArea.x = 0;
sourceArea.y = 0;
sourceArea.width = source->getWidth();
sourceArea.height = source->getHeight();
gl::Rectangle destArea;
destArea.x = 0;
destArea.y = 0;
destArea.width = dest->getWidth();
destArea.height = dest->getHeight();
mRenderer->copyTexture(sourceSRV, sourceArea, source->getWidth(), source->getHeight(),
destRTV, destArea, dest->getWidth(), dest->getHeight(),
GL_RGBA);
}
if (sourceSRV)
{
sourceSRV->Release();
}
if (destRTV)
{
destRTV->Release();
}
}
}
TextureStorage11_2D::TextureStorage11_2D(Renderer *renderer, SwapChain11 *swapchain)
: TextureStorage11(renderer, D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE)
{
mTexture = swapchain->getOffscreenTexture();
mSRV = swapchain->getRenderTargetShaderResource();
for (unsigned int i = 0; i < gl::IMPLEMENTATION_MAX_TEXTURE_LEVELS; i++)
{
mRenderTarget[i] = NULL;
}
D3D11_TEXTURE2D_DESC texDesc;
mTexture->GetDesc(&texDesc);
mMipLevels = texDesc.MipLevels;
mTextureFormat = texDesc.Format;
mTextureWidth = texDesc.Width;
mTextureHeight = texDesc.Height;
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
mSRV->GetDesc(&srvDesc);
mShaderResourceFormat = srvDesc.Format;
ID3D11RenderTargetView* offscreenRTV = swapchain->getRenderTarget();
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc;
offscreenRTV->GetDesc(&rtvDesc);
mRenderTargetFormat = rtvDesc.Format;
offscreenRTV->Release();
mDepthStencilFormat = DXGI_FORMAT_UNKNOWN;
}
TextureStorage11_2D::TextureStorage11_2D(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height)
: TextureStorage11(renderer, GetTextureBindFlags(gl_d3d11::ConvertTextureFormat(internalformat), usage, forceRenderable))
{
for (unsigned int i = 0; i < gl::IMPLEMENTATION_MAX_TEXTURE_LEVELS; i++)
{
mRenderTarget[i] = NULL;
}
DXGI_FORMAT convertedFormat = gl_d3d11::ConvertTextureFormat(internalformat);
if (d3d11::IsDepthStencilFormat(convertedFormat))
{
mTextureFormat = d3d11::GetDepthTextureFormat(convertedFormat);
mShaderResourceFormat = d3d11::GetDepthShaderResourceFormat(convertedFormat);
mDepthStencilFormat = convertedFormat;
mRenderTargetFormat = DXGI_FORMAT_UNKNOWN;
}
else
{
mTextureFormat = convertedFormat;
mShaderResourceFormat = convertedFormat;
mDepthStencilFormat = DXGI_FORMAT_UNKNOWN;
mRenderTargetFormat = convertedFormat;
}
// if the width or height is not positive this should be treated as an incomplete texture
// we handle that here by skipping the d3d texture creation
if (width > 0 && height > 0)
{
// adjust size if needed for compressed textures
gl::MakeValidSize(false, gl::IsCompressed(internalformat), &width, &height, &mLodOffset);
ID3D11Device *device = mRenderer->getDevice();
D3D11_TEXTURE2D_DESC desc;
desc.Width = width; // Compressed texture size constraints?
desc.Height = height;
desc.MipLevels = (levels > 0) ? levels + mLodOffset : 0;
desc.ArraySize = 1;
desc.Format = mTextureFormat;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = getBindFlags();
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
HRESULT result = device->CreateTexture2D(&desc, NULL, &mTexture);
// this can happen from windows TDR
if (d3d11::isDeviceLostError(result))
{
mRenderer->notifyDeviceLost();
gl::error(GL_OUT_OF_MEMORY);
}
else if (FAILED(result))
{
ASSERT(result == E_OUTOFMEMORY);
ERR("Creating image failed.");
gl::error(GL_OUT_OF_MEMORY);
}
else
{
mTexture->GetDesc(&desc);
mMipLevels = desc.MipLevels;
mTextureWidth = desc.Width;
mTextureHeight = desc.Height;
}
}
}
TextureStorage11_2D::~TextureStorage11_2D()
{
if (mTexture)
{
mTexture->Release();
mTexture = NULL;
}
if (mSRV)
{
mSRV->Release();
mSRV = NULL;
}
for (unsigned int i = 0; i < gl::IMPLEMENTATION_MAX_TEXTURE_LEVELS; i++)
{
delete mRenderTarget[i];
mRenderTarget[i] = NULL;
}
}
TextureStorage11_2D *TextureStorage11_2D::makeTextureStorage11_2D(TextureStorage *storage)
{
ASSERT(HAS_DYNAMIC_TYPE(TextureStorage11_2D*, storage));
return static_cast<TextureStorage11_2D*>(storage);
}
RenderTarget *TextureStorage11_2D::getRenderTarget(int level)
{
if (level >= 0 && level < static_cast<int>(mMipLevels))
{
if (!mRenderTarget[level])
{
ID3D11Device *device = mRenderer->getDevice();
HRESULT result;
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = mShaderResourceFormat;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = level;
srvDesc.Texture2D.MipLevels = 1;
ID3D11ShaderResourceView *srv;
result = device->CreateShaderResourceView(mTexture, &srvDesc, &srv);
if (result == E_OUTOFMEMORY)
{
return gl::error(GL_OUT_OF_MEMORY, static_cast<RenderTarget*>(NULL));
}
ASSERT(SUCCEEDED(result));
if (mRenderTargetFormat != DXGI_FORMAT_UNKNOWN)
{
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc;
rtvDesc.Format = mRenderTargetFormat;
rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
rtvDesc.Texture2D.MipSlice = level;
ID3D11RenderTargetView *rtv;
result = device->CreateRenderTargetView(mTexture, &rtvDesc, &rtv);
if (result == E_OUTOFMEMORY)
{
srv->Release();
return gl::error(GL_OUT_OF_MEMORY, static_cast<RenderTarget*>(NULL));
}
ASSERT(SUCCEEDED(result));
// RenderTarget11 expects to be the owner of the resources it is given but TextureStorage11
// also needs to keep a reference to the texture.
mTexture->AddRef();
mRenderTarget[level] = new RenderTarget11(mRenderer, rtv, mTexture, srv,
std::max(mTextureWidth >> level, 1U),
std::max(mTextureHeight >> level, 1U));
}
else if (mDepthStencilFormat != DXGI_FORMAT_UNKNOWN)
{
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
dsvDesc.Format = mDepthStencilFormat;
dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
dsvDesc.Texture2D.MipSlice = level;
dsvDesc.Flags = 0;
ID3D11DepthStencilView *dsv;
result = device->CreateDepthStencilView(mTexture, &dsvDesc, &dsv);
if (result == E_OUTOFMEMORY)
{
srv->Release();
return gl::error(GL_OUT_OF_MEMORY, static_cast<RenderTarget*>(NULL));
}
ASSERT(SUCCEEDED(result));
// RenderTarget11 expects to be the owner of the resources it is given but TextureStorage11
// also needs to keep a reference to the texture.
mTexture->AddRef();
mRenderTarget[level] = new RenderTarget11(mRenderer, dsv, mTexture, srv,
std::max(mTextureWidth >> level, 1U),
std::max(mTextureHeight >> level, 1U));
}
else
{
UNREACHABLE();
}
}
return mRenderTarget[level];
}
else
{
return NULL;
}
}
ID3D11ShaderResourceView *TextureStorage11_2D::getSRV()
{
if (!mSRV)
{
ID3D11Device *device = mRenderer->getDevice();
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = mShaderResourceFormat;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = (mMipLevels == 0 ? -1 : mMipLevels);
srvDesc.Texture2D.MostDetailedMip = 0;
HRESULT result = device->CreateShaderResourceView(mTexture, &srvDesc, &mSRV);
if (result == E_OUTOFMEMORY)
{
return gl::error(GL_OUT_OF_MEMORY, static_cast<ID3D11ShaderResourceView*>(NULL));
}
ASSERT(SUCCEEDED(result));
}
return mSRV;
}
void TextureStorage11_2D::generateMipmap(int level)
{
RenderTarget11 *source = RenderTarget11::makeRenderTarget11(getRenderTarget(level - 1));
RenderTarget11 *dest = RenderTarget11::makeRenderTarget11(getRenderTarget(level));
generateMipmapLayer(source, dest);
}
TextureStorage11_Cube::TextureStorage11_Cube(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size)
: TextureStorage11(renderer, GetTextureBindFlags(gl_d3d11::ConvertTextureFormat(internalformat), usage, forceRenderable))
{
for (unsigned int i = 0; i < 6; i++)
{
for (unsigned int j = 0; j < gl::IMPLEMENTATION_MAX_TEXTURE_LEVELS; j++)
{
mRenderTarget[i][j] = NULL;
}
}
DXGI_FORMAT convertedFormat = gl_d3d11::ConvertTextureFormat(internalformat);
if (d3d11::IsDepthStencilFormat(convertedFormat))
{
mTextureFormat = d3d11::GetDepthTextureFormat(convertedFormat);
mShaderResourceFormat = d3d11::GetDepthShaderResourceFormat(convertedFormat);
mDepthStencilFormat = convertedFormat;
mRenderTargetFormat = DXGI_FORMAT_UNKNOWN;
}
else
{
mTextureFormat = convertedFormat;
mShaderResourceFormat = convertedFormat;
mDepthStencilFormat = DXGI_FORMAT_UNKNOWN;
mRenderTargetFormat = convertedFormat;
}
// if the size is not positive this should be treated as an incomplete texture
// we handle that here by skipping the d3d texture creation
if (size > 0)
{
// adjust size if needed for compressed textures
int height = size;
gl::MakeValidSize(false, gl::IsCompressed(internalformat), &size, &height, &mLodOffset);
ID3D11Device *device = mRenderer->getDevice();
D3D11_TEXTURE2D_DESC desc;
desc.Width = size;
desc.Height = size;
desc.MipLevels = (levels > 0) ? levels + mLodOffset : 0;
desc.ArraySize = 6;
desc.Format = mTextureFormat;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = getBindFlags();
desc.CPUAccessFlags = 0;
desc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
HRESULT result = device->CreateTexture2D(&desc, NULL, &mTexture);
if (FAILED(result))
{
ASSERT(result == E_OUTOFMEMORY);
ERR("Creating image failed.");
gl::error(GL_OUT_OF_MEMORY);
}
else
{
mTexture->GetDesc(&desc);
mMipLevels = desc.MipLevels;
mTextureWidth = desc.Width;
mTextureHeight = desc.Height;
}
}
}
TextureStorage11_Cube::~TextureStorage11_Cube()
{
if (mTexture)
{
mTexture->Release();
mTexture = NULL;
}
if (mSRV)
{
mSRV->Release();
mSRV = NULL;
}
for (unsigned int i = 0; i < 6; i++)
{
for (unsigned int j = 0; j < gl::IMPLEMENTATION_MAX_TEXTURE_LEVELS; j++)
{
delete mRenderTarget[i][j];
mRenderTarget[i][j] = NULL;
}
}
}
TextureStorage11_Cube *TextureStorage11_Cube::makeTextureStorage11_Cube(TextureStorage *storage)
{
ASSERT(HAS_DYNAMIC_TYPE(TextureStorage11_Cube*, storage));
return static_cast<TextureStorage11_Cube*>(storage);
}
RenderTarget *TextureStorage11_Cube::getRenderTarget(GLenum faceTarget, int level)
{
unsigned int faceIdx = gl::TextureCubeMap::faceIndex(faceTarget);
if (level >= 0 && level < static_cast<int>(mMipLevels))
{
if (!mRenderTarget[faceIdx][level])
{
ID3D11Device *device = mRenderer->getDevice();
HRESULT result;
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = mShaderResourceFormat;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
srvDesc.Texture2DArray.MostDetailedMip = level;
srvDesc.Texture2DArray.MipLevels = 1;
srvDesc.Texture2DArray.FirstArraySlice = faceIdx;
srvDesc.Texture2DArray.ArraySize = 1;
ID3D11ShaderResourceView *srv;
result = device->CreateShaderResourceView(mTexture, &srvDesc, &srv);
if (result == E_OUTOFMEMORY)
{
return gl::error(GL_OUT_OF_MEMORY, static_cast<RenderTarget*>(NULL));
}
ASSERT(SUCCEEDED(result));
if (mRenderTargetFormat != DXGI_FORMAT_UNKNOWN)
{
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc;
rtvDesc.Format = mRenderTargetFormat;
rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
rtvDesc.Texture2DArray.MipSlice = level;
rtvDesc.Texture2DArray.FirstArraySlice = faceIdx;
rtvDesc.Texture2DArray.ArraySize = 1;
ID3D11RenderTargetView *rtv;
result = device->CreateRenderTargetView(mTexture, &rtvDesc, &rtv);
if (result == E_OUTOFMEMORY)
{
srv->Release();
return gl::error(GL_OUT_OF_MEMORY, static_cast<RenderTarget*>(NULL));
}
ASSERT(SUCCEEDED(result));
// RenderTarget11 expects to be the owner of the resources it is given but TextureStorage11
// also needs to keep a reference to the texture.
mTexture->AddRef();
mRenderTarget[faceIdx][level] = new RenderTarget11(mRenderer, rtv, mTexture, srv,
std::max(mTextureWidth >> level, 1U),
std::max(mTextureHeight >> level, 1U));
}
else if (mDepthStencilFormat != DXGI_FORMAT_UNKNOWN)
{
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
dsvDesc.Format = mRenderTargetFormat;
dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
dsvDesc.Texture2DArray.MipSlice = level;
dsvDesc.Texture2DArray.FirstArraySlice = faceIdx;
dsvDesc.Texture2DArray.ArraySize = 1;
ID3D11DepthStencilView *dsv;
result = device->CreateDepthStencilView(mTexture, &dsvDesc, &dsv);
if (result == E_OUTOFMEMORY)
{
srv->Release();
return gl::error(GL_OUT_OF_MEMORY, static_cast<RenderTarget*>(NULL));
}
ASSERT(SUCCEEDED(result));
// RenderTarget11 expects to be the owner of the resources it is given but TextureStorage11
// also needs to keep a reference to the texture.
mTexture->AddRef();
mRenderTarget[faceIdx][level] = new RenderTarget11(mRenderer, dsv, mTexture, srv,
std::max(mTextureWidth >> level, 1U),
std::max(mTextureHeight >> level, 1U));
}
else
{
UNREACHABLE();
}
}
return mRenderTarget[faceIdx][level];
}
else
{
return NULL;
}
}
ID3D11ShaderResourceView *TextureStorage11_Cube::getSRV()
{
if (!mSRV)
{
ID3D11Device *device = mRenderer->getDevice();
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = mShaderResourceFormat;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
srvDesc.TextureCube.MipLevels = (mMipLevels == 0 ? -1 : mMipLevels);
srvDesc.TextureCube.MostDetailedMip = 0;
HRESULT result = device->CreateShaderResourceView(mTexture, &srvDesc, &mSRV);
if (result == E_OUTOFMEMORY)
{
return gl::error(GL_OUT_OF_MEMORY, static_cast<ID3D11ShaderResourceView*>(NULL));
}
ASSERT(SUCCEEDED(result));
}
return mSRV;
}
void TextureStorage11_Cube::generateMipmap(int face, int level)
{
RenderTarget11 *source = RenderTarget11::makeRenderTarget11(getRenderTarget(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level - 1));
RenderTarget11 *dest = RenderTarget11::makeRenderTarget11(getRenderTarget(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level));
generateMipmapLayer(source, dest);
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/TextureStorage11.cpp | C++ | bsd | 22,563 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SwapChain9.h: Defines a back-end specific class for the D3D9 swap chain.
#ifndef LIBGLESV2_RENDERER_SWAPCHAIN9_H_
#define LIBGLESV2_RENDERER_SWAPCHAIN9_H_
#include "common/angleutils.h"
#include "libGLESv2/renderer/SwapChain.h"
namespace rx
{
class Renderer9;
class SwapChain9 : public SwapChain
{
public:
SwapChain9(Renderer9 *renderer, HWND window, HANDLE shareHandle,
GLenum backBufferFormat, GLenum depthBufferFormat);
virtual ~SwapChain9();
EGLint resize(EGLint backbufferWidth, EGLint backbufferHeight);
virtual EGLint reset(EGLint backbufferWidth, EGLint backbufferHeight, EGLint swapInterval);
virtual EGLint swapRect(EGLint x, EGLint y, EGLint width, EGLint height);
virtual void recreate();
virtual IDirect3DSurface9 *getRenderTarget();
virtual IDirect3DSurface9 *getDepthStencil();
virtual IDirect3DTexture9 *getOffscreenTexture();
static SwapChain9 *makeSwapChain9(SwapChain *swapChain);
private:
DISALLOW_COPY_AND_ASSIGN(SwapChain9);
void release();
Renderer9 *mRenderer;
EGLint mHeight;
EGLint mWidth;
EGLint mSwapInterval;
IDirect3DSwapChain9 *mSwapChain;
IDirect3DSurface9 *mBackBuffer;
IDirect3DSurface9 *mRenderTarget;
IDirect3DSurface9 *mDepthStencil;
IDirect3DTexture9* mOffscreenTexture;
};
}
#endif // LIBGLESV2_RENDERER_SWAPCHAIN9_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/SwapChain9.h | C++ | bsd | 1,556 |
#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ShaderExecutable11.cpp: Implements a D3D11-specific class to contain shader
// executable implementation details.
#include "libGLESv2/renderer/ShaderExecutable11.h"
#include "common/debug.h"
namespace rx
{
ShaderExecutable11::ShaderExecutable11(const void *function, size_t length, ID3D11PixelShader *executable)
: ShaderExecutable(function, length)
{
mPixelExecutable = executable;
mVertexExecutable = NULL;
mGeometryExecutable = NULL;
mConstantBuffer = NULL;
}
ShaderExecutable11::ShaderExecutable11(const void *function, size_t length, ID3D11VertexShader *executable)
: ShaderExecutable(function, length)
{
mVertexExecutable = executable;
mPixelExecutable = NULL;
mGeometryExecutable = NULL;
mConstantBuffer = NULL;
}
ShaderExecutable11::ShaderExecutable11(const void *function, size_t length, ID3D11GeometryShader *executable)
: ShaderExecutable(function, length)
{
mGeometryExecutable = executable;
mVertexExecutable = NULL;
mPixelExecutable = NULL;
mConstantBuffer = NULL;
}
ShaderExecutable11::~ShaderExecutable11()
{
if (mVertexExecutable)
{
mVertexExecutable->Release();
}
if (mPixelExecutable)
{
mPixelExecutable->Release();
}
if (mGeometryExecutable)
{
mGeometryExecutable->Release();
}
if (mConstantBuffer)
{
mConstantBuffer->Release();
}
}
ShaderExecutable11 *ShaderExecutable11::makeShaderExecutable11(ShaderExecutable *executable)
{
ASSERT(HAS_DYNAMIC_TYPE(ShaderExecutable11*, executable));
return static_cast<ShaderExecutable11*>(executable);
}
ID3D11VertexShader *ShaderExecutable11::getVertexShader() const
{
return mVertexExecutable;
}
ID3D11PixelShader *ShaderExecutable11::getPixelShader() const
{
return mPixelExecutable;
}
ID3D11GeometryShader *ShaderExecutable11::getGeometryShader() const
{
return mGeometryExecutable;
}
ID3D11Buffer *ShaderExecutable11::getConstantBuffer(ID3D11Device *device, unsigned int registerCount)
{
if (!mConstantBuffer && registerCount > 0)
{
D3D11_BUFFER_DESC constantBufferDescription = {0};
constantBufferDescription.ByteWidth = registerCount * sizeof(float[4]);
constantBufferDescription.Usage = D3D11_USAGE_DYNAMIC;
constantBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constantBufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
constantBufferDescription.MiscFlags = 0;
constantBufferDescription.StructureByteStride = 0;
HRESULT result = device->CreateBuffer(&constantBufferDescription, NULL, &mConstantBuffer);
ASSERT(SUCCEEDED(result));
}
return mConstantBuffer;
}
} | 010smithzhang-ddd | src/libGLESv2/renderer/ShaderExecutable11.cpp | C++ | bsd | 2,931 |
#include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// BufferStorage.cpp Defines the abstract BufferStorage class.
#include "libGLESv2/renderer/BufferStorage.h"
namespace rx
{
unsigned int BufferStorage::mNextSerial = 1;
BufferStorage::BufferStorage()
{
updateSerial();
}
BufferStorage::~BufferStorage()
{
}
unsigned int BufferStorage::getSerial() const
{
return mSerial;
}
void BufferStorage::updateSerial()
{
mSerial = mNextSerial++;
}
void BufferStorage::markBufferUsage()
{
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/BufferStorage.cpp | C++ | bsd | 657 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Query11.h: Defines the rx::Query11 class which implements rx::QueryImpl.
#ifndef LIBGLESV2_RENDERER_QUERY11_H_
#define LIBGLESV2_RENDERER_QUERY11_H_
#include "libGLESv2/renderer/QueryImpl.h"
namespace rx
{
class Renderer11;
class Query11 : public QueryImpl
{
public:
Query11(rx::Renderer11 *renderer, GLenum type);
virtual ~Query11();
void begin();
void end();
GLuint getResult();
GLboolean isResultAvailable();
private:
DISALLOW_COPY_AND_ASSIGN(Query11);
GLboolean testQuery();
rx::Renderer11 *mRenderer;
ID3D11Query *mQuery;
};
}
#endif // LIBGLESV2_RENDERER_QUERY11_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/Query11.h | C++ | bsd | 810 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// TextureStorage9.cpp: Implements the abstract rx::TextureStorage9 class and its concrete derived
// classes TextureStorage9_2D and TextureStorage9_Cube, which act as the interface to the
// D3D9 texture.
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/Renderer9.h"
#include "libGLESv2/renderer/TextureStorage9.h"
#include "libGLESv2/renderer/SwapChain9.h"
#include "libGLESv2/renderer/RenderTarget9.h"
#include "libGLESv2/renderer/renderer9_utils.h"
#include "libGLESv2/Texture.h"
namespace rx
{
TextureStorage9::TextureStorage9(Renderer *renderer, DWORD usage)
: mLodOffset(0),
mRenderer(Renderer9::makeRenderer9(renderer)),
mD3DUsage(usage),
mD3DPool(mRenderer->getTexturePool(usage))
{
}
TextureStorage9::~TextureStorage9()
{
}
TextureStorage9 *TextureStorage9::makeTextureStorage9(TextureStorage *storage)
{
ASSERT(HAS_DYNAMIC_TYPE(TextureStorage9*, storage));
return static_cast<TextureStorage9*>(storage);
}
DWORD TextureStorage9::GetTextureUsage(D3DFORMAT d3dfmt, GLenum glusage, bool forceRenderable)
{
DWORD d3dusage = 0;
if (d3dfmt == D3DFMT_INTZ)
{
d3dusage |= D3DUSAGE_DEPTHSTENCIL;
}
else if(forceRenderable || (TextureStorage9::IsTextureFormatRenderable(d3dfmt) && (glusage == GL_FRAMEBUFFER_ATTACHMENT_ANGLE)))
{
d3dusage |= D3DUSAGE_RENDERTARGET;
}
return d3dusage;
}
bool TextureStorage9::IsTextureFormatRenderable(D3DFORMAT format)
{
if (format == D3DFMT_INTZ)
{
return true;
}
switch(format)
{
case D3DFMT_L8:
case D3DFMT_A8L8:
case D3DFMT_DXT1:
case D3DFMT_DXT3:
case D3DFMT_DXT5:
return false;
case D3DFMT_A8R8G8B8:
case D3DFMT_X8R8G8B8:
case D3DFMT_A16B16G16R16F:
case D3DFMT_A32B32G32R32F:
return true;
default:
UNREACHABLE();
}
return false;
}
bool TextureStorage9::isRenderTarget() const
{
return (mD3DUsage & (D3DUSAGE_RENDERTARGET | D3DUSAGE_DEPTHSTENCIL)) != 0;
}
bool TextureStorage9::isManaged() const
{
return (mD3DPool == D3DPOOL_MANAGED);
}
D3DPOOL TextureStorage9::getPool() const
{
return mD3DPool;
}
DWORD TextureStorage9::getUsage() const
{
return mD3DUsage;
}
int TextureStorage9::getLodOffset() const
{
return mLodOffset;
}
int TextureStorage9::levelCount()
{
return getBaseTexture() ? getBaseTexture()->GetLevelCount() - getLodOffset() : 0;
}
TextureStorage9_2D::TextureStorage9_2D(Renderer *renderer, SwapChain9 *swapchain) : TextureStorage9(renderer, D3DUSAGE_RENDERTARGET)
{
IDirect3DTexture9 *surfaceTexture = swapchain->getOffscreenTexture();
mTexture = surfaceTexture;
mRenderTarget = NULL;
initializeRenderTarget();
}
TextureStorage9_2D::TextureStorage9_2D(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height)
: TextureStorage9(renderer, GetTextureUsage(Renderer9::makeRenderer9(renderer)->ConvertTextureInternalFormat(internalformat), usage, forceRenderable))
{
mTexture = NULL;
mRenderTarget = NULL;
// if the width or height is not positive this should be treated as an incomplete texture
// we handle that here by skipping the d3d texture creation
if (width > 0 && height > 0)
{
IDirect3DDevice9 *device = mRenderer->getDevice();
gl::MakeValidSize(false, gl::IsCompressed(internalformat), &width, &height, &mLodOffset);
HRESULT result = device->CreateTexture(width, height, levels ? levels + mLodOffset : 0, getUsage(),
mRenderer->ConvertTextureInternalFormat(internalformat), getPool(), &mTexture, NULL);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
gl::error(GL_OUT_OF_MEMORY);
}
}
initializeRenderTarget();
}
TextureStorage9_2D::~TextureStorage9_2D()
{
if (mTexture)
{
mTexture->Release();
}
delete mRenderTarget;
}
TextureStorage9_2D *TextureStorage9_2D::makeTextureStorage9_2D(TextureStorage *storage)
{
ASSERT(HAS_DYNAMIC_TYPE(TextureStorage9_2D*, storage));
return static_cast<TextureStorage9_2D*>(storage);
}
// Increments refcount on surface.
// caller must Release() the returned surface
IDirect3DSurface9 *TextureStorage9_2D::getSurfaceLevel(int level, bool dirty)
{
IDirect3DSurface9 *surface = NULL;
if (mTexture)
{
HRESULT result = mTexture->GetSurfaceLevel(level + mLodOffset, &surface);
ASSERT(SUCCEEDED(result));
// With managed textures the driver needs to be informed of updates to the lower mipmap levels
if (level + mLodOffset != 0 && isManaged() && dirty)
{
mTexture->AddDirtyRect(NULL);
}
}
return surface;
}
RenderTarget *TextureStorage9_2D::getRenderTarget()
{
return mRenderTarget;
}
void TextureStorage9_2D::generateMipmap(int level)
{
IDirect3DSurface9 *upper = getSurfaceLevel(level - 1, false);
IDirect3DSurface9 *lower = getSurfaceLevel(level, true);
if (upper != NULL && lower != NULL)
{
mRenderer->boxFilter(upper, lower);
}
if (upper != NULL) upper->Release();
if (lower != NULL) lower->Release();
}
IDirect3DBaseTexture9 *TextureStorage9_2D::getBaseTexture() const
{
return mTexture;
}
void TextureStorage9_2D::initializeRenderTarget()
{
ASSERT(mRenderTarget == NULL);
if (mTexture != NULL && isRenderTarget())
{
IDirect3DSurface9 *surface = getSurfaceLevel(0, false);
mRenderTarget = new RenderTarget9(mRenderer, surface);
}
}
TextureStorage9_Cube::TextureStorage9_Cube(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size)
: TextureStorage9(renderer, GetTextureUsage(Renderer9::makeRenderer9(renderer)->ConvertTextureInternalFormat(internalformat), usage, forceRenderable))
{
mTexture = NULL;
for (int i = 0; i < 6; ++i)
{
mRenderTarget[i] = NULL;
}
// if the size is not positive this should be treated as an incomplete texture
// we handle that here by skipping the d3d texture creation
if (size > 0)
{
IDirect3DDevice9 *device = mRenderer->getDevice();
int height = size;
gl::MakeValidSize(false, gl::IsCompressed(internalformat), &size, &height, &mLodOffset);
HRESULT result = device->CreateCubeTexture(size, levels ? levels + mLodOffset : 0, getUsage(),
mRenderer->ConvertTextureInternalFormat(internalformat), getPool(), &mTexture, NULL);
if (FAILED(result))
{
ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
gl::error(GL_OUT_OF_MEMORY);
}
}
initializeRenderTarget();
}
TextureStorage9_Cube::~TextureStorage9_Cube()
{
if (mTexture)
{
mTexture->Release();
}
for (int i = 0; i < 6; ++i)
{
delete mRenderTarget[i];
}
}
TextureStorage9_Cube *TextureStorage9_Cube::makeTextureStorage9_Cube(TextureStorage *storage)
{
ASSERT(HAS_DYNAMIC_TYPE(TextureStorage9_Cube*, storage));
return static_cast<TextureStorage9_Cube*>(storage);
}
// Increments refcount on surface.
// caller must Release() the returned surface
IDirect3DSurface9 *TextureStorage9_Cube::getCubeMapSurface(GLenum faceTarget, int level, bool dirty)
{
IDirect3DSurface9 *surface = NULL;
if (mTexture)
{
D3DCUBEMAP_FACES face = gl_d3d9::ConvertCubeFace(faceTarget);
HRESULT result = mTexture->GetCubeMapSurface(face, level + mLodOffset, &surface);
ASSERT(SUCCEEDED(result));
// With managed textures the driver needs to be informed of updates to the lower mipmap levels
if (level != 0 && isManaged() && dirty)
{
mTexture->AddDirtyRect(face, NULL);
}
}
return surface;
}
RenderTarget *TextureStorage9_Cube::getRenderTarget(GLenum faceTarget)
{
return mRenderTarget[gl::TextureCubeMap::faceIndex(faceTarget)];
}
void TextureStorage9_Cube::generateMipmap(int face, int level)
{
IDirect3DSurface9 *upper = getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level - 1, false);
IDirect3DSurface9 *lower = getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, true);
if (upper != NULL && lower != NULL)
{
mRenderer->boxFilter(upper, lower);
}
if (upper != NULL) upper->Release();
if (lower != NULL) lower->Release();
}
IDirect3DBaseTexture9 *TextureStorage9_Cube::getBaseTexture() const
{
return mTexture;
}
void TextureStorage9_Cube::initializeRenderTarget()
{
if (mTexture != NULL && isRenderTarget())
{
IDirect3DSurface9 *surface = NULL;
for (int i = 0; i < 6; ++i)
{
ASSERT(mRenderTarget[i] == NULL);
surface = getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, false);
mRenderTarget[i] = new RenderTarget9(mRenderer, surface);
}
}
}
} | 010smithzhang-ddd | src/libGLESv2/renderer/TextureStorage9.cpp | C++ | bsd | 9,284 |
#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// renderer11_utils.cpp: Conversion functions and other utility routines
// specific to the D3D11 renderer.
#include "libGLESv2/renderer/renderer11_utils.h"
#include "common/debug.h"
namespace gl_d3d11
{
D3D11_BLEND ConvertBlendFunc(GLenum glBlend, bool isAlpha)
{
D3D11_BLEND d3dBlend = D3D11_BLEND_ZERO;
switch (glBlend)
{
case GL_ZERO: d3dBlend = D3D11_BLEND_ZERO; break;
case GL_ONE: d3dBlend = D3D11_BLEND_ONE; break;
case GL_SRC_COLOR: d3dBlend = (isAlpha ? D3D11_BLEND_SRC_ALPHA : D3D11_BLEND_SRC_COLOR); break;
case GL_ONE_MINUS_SRC_COLOR: d3dBlend = (isAlpha ? D3D11_BLEND_INV_SRC_ALPHA : D3D11_BLEND_INV_SRC_COLOR); break;
case GL_DST_COLOR: d3dBlend = (isAlpha ? D3D11_BLEND_DEST_ALPHA : D3D11_BLEND_DEST_COLOR); break;
case GL_ONE_MINUS_DST_COLOR: d3dBlend = (isAlpha ? D3D11_BLEND_INV_DEST_ALPHA : D3D11_BLEND_INV_DEST_COLOR); break;
case GL_SRC_ALPHA: d3dBlend = D3D11_BLEND_SRC_ALPHA; break;
case GL_ONE_MINUS_SRC_ALPHA: d3dBlend = D3D11_BLEND_INV_SRC_ALPHA; break;
case GL_DST_ALPHA: d3dBlend = D3D11_BLEND_DEST_ALPHA; break;
case GL_ONE_MINUS_DST_ALPHA: d3dBlend = D3D11_BLEND_INV_DEST_ALPHA; break;
case GL_CONSTANT_COLOR: d3dBlend = D3D11_BLEND_BLEND_FACTOR; break;
case GL_ONE_MINUS_CONSTANT_COLOR: d3dBlend = D3D11_BLEND_INV_BLEND_FACTOR; break;
case GL_CONSTANT_ALPHA: d3dBlend = D3D11_BLEND_BLEND_FACTOR; break;
case GL_ONE_MINUS_CONSTANT_ALPHA: d3dBlend = D3D11_BLEND_INV_BLEND_FACTOR; break;
case GL_SRC_ALPHA_SATURATE: d3dBlend = D3D11_BLEND_SRC_ALPHA_SAT; break;
default: UNREACHABLE();
}
return d3dBlend;
}
D3D11_BLEND_OP ConvertBlendOp(GLenum glBlendOp)
{
D3D11_BLEND_OP d3dBlendOp = D3D11_BLEND_OP_ADD;
switch (glBlendOp)
{
case GL_FUNC_ADD: d3dBlendOp = D3D11_BLEND_OP_ADD; break;
case GL_FUNC_SUBTRACT: d3dBlendOp = D3D11_BLEND_OP_SUBTRACT; break;
case GL_FUNC_REVERSE_SUBTRACT: d3dBlendOp = D3D11_BLEND_OP_REV_SUBTRACT; break;
default: UNREACHABLE();
}
return d3dBlendOp;
}
UINT8 ConvertColorMask(bool red, bool green, bool blue, bool alpha)
{
UINT8 mask = 0;
if (red)
{
mask |= D3D11_COLOR_WRITE_ENABLE_RED;
}
if (green)
{
mask |= D3D11_COLOR_WRITE_ENABLE_GREEN;
}
if (blue)
{
mask |= D3D11_COLOR_WRITE_ENABLE_BLUE;
}
if (alpha)
{
mask |= D3D11_COLOR_WRITE_ENABLE_ALPHA;
}
return mask;
}
D3D11_CULL_MODE ConvertCullMode(bool cullEnabled, GLenum cullMode)
{
D3D11_CULL_MODE cull = D3D11_CULL_NONE;
if (cullEnabled)
{
switch (cullMode)
{
case GL_FRONT: cull = D3D11_CULL_FRONT; break;
case GL_BACK: cull = D3D11_CULL_BACK; break;
case GL_FRONT_AND_BACK: cull = D3D11_CULL_NONE; break;
default: UNREACHABLE();
}
}
else
{
cull = D3D11_CULL_NONE;
}
return cull;
}
D3D11_COMPARISON_FUNC ConvertComparison(GLenum comparison)
{
D3D11_COMPARISON_FUNC d3dComp = D3D11_COMPARISON_NEVER;
switch (comparison)
{
case GL_NEVER: d3dComp = D3D11_COMPARISON_NEVER; break;
case GL_ALWAYS: d3dComp = D3D11_COMPARISON_ALWAYS; break;
case GL_LESS: d3dComp = D3D11_COMPARISON_LESS; break;
case GL_LEQUAL: d3dComp = D3D11_COMPARISON_LESS_EQUAL; break;
case GL_EQUAL: d3dComp = D3D11_COMPARISON_EQUAL; break;
case GL_GREATER: d3dComp = D3D11_COMPARISON_GREATER; break;
case GL_GEQUAL: d3dComp = D3D11_COMPARISON_GREATER_EQUAL; break;
case GL_NOTEQUAL: d3dComp = D3D11_COMPARISON_NOT_EQUAL; break;
default: UNREACHABLE();
}
return d3dComp;
}
D3D11_DEPTH_WRITE_MASK ConvertDepthMask(bool depthWriteEnabled)
{
return depthWriteEnabled ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
}
UINT8 ConvertStencilMask(GLuint stencilmask)
{
return static_cast<UINT8>(stencilmask);
}
D3D11_STENCIL_OP ConvertStencilOp(GLenum stencilOp)
{
D3D11_STENCIL_OP d3dStencilOp = D3D11_STENCIL_OP_KEEP;
switch (stencilOp)
{
case GL_ZERO: d3dStencilOp = D3D11_STENCIL_OP_ZERO; break;
case GL_KEEP: d3dStencilOp = D3D11_STENCIL_OP_KEEP; break;
case GL_REPLACE: d3dStencilOp = D3D11_STENCIL_OP_REPLACE; break;
case GL_INCR: d3dStencilOp = D3D11_STENCIL_OP_INCR_SAT; break;
case GL_DECR: d3dStencilOp = D3D11_STENCIL_OP_DECR_SAT; break;
case GL_INVERT: d3dStencilOp = D3D11_STENCIL_OP_INVERT; break;
case GL_INCR_WRAP: d3dStencilOp = D3D11_STENCIL_OP_INCR; break;
case GL_DECR_WRAP: d3dStencilOp = D3D11_STENCIL_OP_DECR; break;
default: UNREACHABLE();
}
return d3dStencilOp;
}
D3D11_FILTER ConvertFilter(GLenum minFilter, GLenum magFilter, float maxAnisotropy)
{
if (maxAnisotropy > 1.0f)
{
return D3D11_ENCODE_ANISOTROPIC_FILTER(false);
}
else
{
D3D11_FILTER_TYPE dxMin = D3D11_FILTER_TYPE_POINT;
D3D11_FILTER_TYPE dxMip = D3D11_FILTER_TYPE_POINT;
switch (minFilter)
{
case GL_NEAREST: dxMin = D3D11_FILTER_TYPE_POINT; dxMip = D3D11_FILTER_TYPE_POINT; break;
case GL_LINEAR: dxMin = D3D11_FILTER_TYPE_LINEAR; dxMip = D3D11_FILTER_TYPE_POINT; break;
case GL_NEAREST_MIPMAP_NEAREST: dxMin = D3D11_FILTER_TYPE_POINT; dxMip = D3D11_FILTER_TYPE_POINT; break;
case GL_LINEAR_MIPMAP_NEAREST: dxMin = D3D11_FILTER_TYPE_LINEAR; dxMip = D3D11_FILTER_TYPE_POINT; break;
case GL_NEAREST_MIPMAP_LINEAR: dxMin = D3D11_FILTER_TYPE_POINT; dxMip = D3D11_FILTER_TYPE_LINEAR; break;
case GL_LINEAR_MIPMAP_LINEAR: dxMin = D3D11_FILTER_TYPE_LINEAR; dxMip = D3D11_FILTER_TYPE_LINEAR; break;
default: UNREACHABLE();
}
D3D11_FILTER_TYPE dxMag = D3D11_FILTER_TYPE_POINT;
switch (magFilter)
{
case GL_NEAREST: dxMag = D3D11_FILTER_TYPE_POINT; break;
case GL_LINEAR: dxMag = D3D11_FILTER_TYPE_LINEAR; break;
default: UNREACHABLE();
}
return D3D11_ENCODE_BASIC_FILTER(dxMin, dxMag, dxMip, false);
}
}
D3D11_TEXTURE_ADDRESS_MODE ConvertTextureWrap(GLenum wrap)
{
switch (wrap)
{
case GL_REPEAT: return D3D11_TEXTURE_ADDRESS_WRAP;
case GL_CLAMP_TO_EDGE: return D3D11_TEXTURE_ADDRESS_CLAMP;
case GL_MIRRORED_REPEAT: return D3D11_TEXTURE_ADDRESS_MIRROR;
default: UNREACHABLE();
}
return D3D11_TEXTURE_ADDRESS_WRAP;
}
FLOAT ConvertMinLOD(GLenum minFilter, unsigned int lodOffset)
{
return (minFilter == GL_NEAREST || minFilter == GL_LINEAR) ? static_cast<float>(lodOffset) : -FLT_MAX;
}
FLOAT ConvertMaxLOD(GLenum minFilter, unsigned int lodOffset)
{
return (minFilter == GL_NEAREST || minFilter == GL_LINEAR) ? static_cast<float>(lodOffset) : FLT_MAX;
}
}
namespace d3d11_gl
{
GLenum ConvertBackBufferFormat(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_R8G8B8A8_UNORM: return GL_RGBA8_OES;
case DXGI_FORMAT_B8G8R8A8_UNORM: return GL_BGRA8_EXT;
default:
UNREACHABLE();
}
return GL_RGBA8_OES;
}
GLenum ConvertDepthStencilFormat(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_UNKNOWN: return GL_NONE;
case DXGI_FORMAT_D16_UNORM: return GL_DEPTH_COMPONENT16;
case DXGI_FORMAT_D24_UNORM_S8_UINT: return GL_DEPTH24_STENCIL8_OES;
default:
UNREACHABLE();
}
return GL_DEPTH24_STENCIL8_OES;
}
GLenum ConvertRenderbufferFormat(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_B8G8R8A8_UNORM:
return GL_BGRA8_EXT;
case DXGI_FORMAT_R8G8B8A8_UNORM:
return GL_RGBA8_OES;
case DXGI_FORMAT_D16_UNORM:
return GL_DEPTH_COMPONENT16;
case DXGI_FORMAT_D24_UNORM_S8_UINT:
return GL_DEPTH24_STENCIL8_OES;
default:
UNREACHABLE();
}
return GL_RGBA8_OES;
}
GLenum ConvertTextureInternalFormat(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_R8G8B8A8_UNORM:
return GL_RGBA8_OES;
case DXGI_FORMAT_A8_UNORM:
return GL_ALPHA8_EXT;
case DXGI_FORMAT_BC1_UNORM:
return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case DXGI_FORMAT_BC2_UNORM:
return GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE;
case DXGI_FORMAT_BC3_UNORM:
return GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
return GL_RGBA32F_EXT;
case DXGI_FORMAT_R32G32B32_FLOAT:
return GL_RGB32F_EXT;
case DXGI_FORMAT_R16G16B16A16_FLOAT:
return GL_RGBA16F_EXT;
case DXGI_FORMAT_B8G8R8A8_UNORM:
return GL_BGRA8_EXT;
case DXGI_FORMAT_R8_UNORM:
return GL_R8_EXT;
case DXGI_FORMAT_R8G8_UNORM:
return GL_RG8_EXT;
case DXGI_FORMAT_R16_FLOAT:
return GL_R16F_EXT;
case DXGI_FORMAT_R16G16_FLOAT:
return GL_RG16F_EXT;
case DXGI_FORMAT_D16_UNORM:
return GL_DEPTH_COMPONENT16;
case DXGI_FORMAT_D24_UNORM_S8_UINT:
return GL_DEPTH24_STENCIL8_OES;
case DXGI_FORMAT_UNKNOWN:
return GL_NONE;
default:
UNREACHABLE();
}
return GL_RGBA8_OES;
}
}
namespace gl_d3d11
{
DXGI_FORMAT ConvertRenderbufferFormat(GLenum format)
{
switch (format)
{
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGBA8_OES:
case GL_RGB565:
case GL_RGB8_OES:
return DXGI_FORMAT_R8G8B8A8_UNORM;
case GL_BGRA8_EXT:
return DXGI_FORMAT_B8G8R8A8_UNORM;
case GL_DEPTH_COMPONENT16:
return DXGI_FORMAT_D16_UNORM;
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_OES:
return DXGI_FORMAT_D24_UNORM_S8_UINT;
default:
UNREACHABLE();
}
return DXGI_FORMAT_R8G8B8A8_UNORM;
}
DXGI_FORMAT ConvertTextureFormat(GLenum internalformat)
{
switch (internalformat)
{
case GL_RGB565:
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGB8_OES:
case GL_RGBA8_OES:
case GL_LUMINANCE8_EXT:
case GL_LUMINANCE8_ALPHA8_EXT:
return DXGI_FORMAT_R8G8B8A8_UNORM;
case GL_ALPHA8_EXT:
return DXGI_FORMAT_A8_UNORM;
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return DXGI_FORMAT_BC1_UNORM;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
return DXGI_FORMAT_BC2_UNORM;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
return DXGI_FORMAT_BC3_UNORM;
case GL_RGBA32F_EXT:
case GL_ALPHA32F_EXT:
case GL_LUMINANCE_ALPHA32F_EXT:
return DXGI_FORMAT_R32G32B32A32_FLOAT;
case GL_RGB32F_EXT:
case GL_LUMINANCE32F_EXT:
return DXGI_FORMAT_R32G32B32_FLOAT;
case GL_RGBA16F_EXT:
case GL_ALPHA16F_EXT:
case GL_LUMINANCE_ALPHA16F_EXT:
case GL_RGB16F_EXT:
case GL_LUMINANCE16F_EXT:
return DXGI_FORMAT_R16G16B16A16_FLOAT;
case GL_BGRA8_EXT:
return DXGI_FORMAT_B8G8R8A8_UNORM;
case GL_R8_EXT:
return DXGI_FORMAT_R8_UNORM;
case GL_RG8_EXT:
return DXGI_FORMAT_R8G8_UNORM;
case GL_R16F_EXT:
return DXGI_FORMAT_R16_FLOAT;
case GL_RG16F_EXT:
return DXGI_FORMAT_R16G16_FLOAT;
case GL_DEPTH_COMPONENT16:
return DXGI_FORMAT_D16_UNORM;
case GL_DEPTH_COMPONENT32_OES:
case GL_DEPTH24_STENCIL8_OES:
return DXGI_FORMAT_D24_UNORM_S8_UINT;
case GL_NONE:
return DXGI_FORMAT_UNKNOWN;
default:
UNREACHABLE();
}
return DXGI_FORMAT_R8G8B8A8_UNORM;
}
}
namespace d3d11
{
void SetPositionTexCoordVertex(PositionTexCoordVertex* vertex, float x, float y, float u, float v)
{
vertex->x = x;
vertex->y = y;
vertex->u = u;
vertex->v = v;
}
void SetPositionDepthColorVertex(PositionDepthColorVertex* vertex, float x, float y, float z,
const gl::Color &color)
{
vertex->x = x;
vertex->y = y;
vertex->z = z;
vertex->r = color.red;
vertex->g = color.green;
vertex->b = color.blue;
vertex->a = color.alpha;
}
size_t ComputePixelSizeBits(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_R1_UNORM:
return 1;
case DXGI_FORMAT_A8_UNORM:
case DXGI_FORMAT_R8_SINT:
case DXGI_FORMAT_R8_SNORM:
case DXGI_FORMAT_R8_TYPELESS:
case DXGI_FORMAT_R8_UINT:
case DXGI_FORMAT_R8_UNORM:
return 8;
case DXGI_FORMAT_B5G5R5A1_UNORM:
case DXGI_FORMAT_B5G6R5_UNORM:
case DXGI_FORMAT_D16_UNORM:
case DXGI_FORMAT_R16_FLOAT:
case DXGI_FORMAT_R16_SINT:
case DXGI_FORMAT_R16_SNORM:
case DXGI_FORMAT_R16_TYPELESS:
case DXGI_FORMAT_R16_UINT:
case DXGI_FORMAT_R16_UNORM:
case DXGI_FORMAT_R8G8_SINT:
case DXGI_FORMAT_R8G8_SNORM:
case DXGI_FORMAT_R8G8_TYPELESS:
case DXGI_FORMAT_R8G8_UINT:
case DXGI_FORMAT_R8G8_UNORM:
return 16;
case DXGI_FORMAT_B8G8R8X8_TYPELESS:
case DXGI_FORMAT_B8G8R8X8_UNORM:
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
case DXGI_FORMAT_D24_UNORM_S8_UINT:
case DXGI_FORMAT_D32_FLOAT:
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
case DXGI_FORMAT_G8R8_G8B8_UNORM:
case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
case DXGI_FORMAT_R10G10B10A2_TYPELESS:
case DXGI_FORMAT_R10G10B10A2_UINT:
case DXGI_FORMAT_R10G10B10A2_UNORM:
case DXGI_FORMAT_R11G11B10_FLOAT:
case DXGI_FORMAT_R16G16_FLOAT:
case DXGI_FORMAT_R16G16_SINT:
case DXGI_FORMAT_R16G16_SNORM:
case DXGI_FORMAT_R16G16_TYPELESS:
case DXGI_FORMAT_R16G16_UINT:
case DXGI_FORMAT_R16G16_UNORM:
case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
case DXGI_FORMAT_R24G8_TYPELESS:
case DXGI_FORMAT_R32_FLOAT:
case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
case DXGI_FORMAT_R32_SINT:
case DXGI_FORMAT_R32_TYPELESS:
case DXGI_FORMAT_R32_UINT:
case DXGI_FORMAT_R8G8_B8G8_UNORM:
case DXGI_FORMAT_R8G8B8A8_SINT:
case DXGI_FORMAT_R8G8B8A8_SNORM:
case DXGI_FORMAT_R8G8B8A8_TYPELESS:
case DXGI_FORMAT_R8G8B8A8_UINT:
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
case DXGI_FORMAT_B8G8R8A8_TYPELESS:
case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
return 32;
case DXGI_FORMAT_R16G16B16A16_FLOAT:
case DXGI_FORMAT_R16G16B16A16_SINT:
case DXGI_FORMAT_R16G16B16A16_SNORM:
case DXGI_FORMAT_R16G16B16A16_TYPELESS:
case DXGI_FORMAT_R16G16B16A16_UINT:
case DXGI_FORMAT_R16G16B16A16_UNORM:
case DXGI_FORMAT_R32G32_FLOAT:
case DXGI_FORMAT_R32G32_SINT:
case DXGI_FORMAT_R32G32_TYPELESS:
case DXGI_FORMAT_R32G32_UINT:
case DXGI_FORMAT_R32G8X24_TYPELESS:
return 64;
case DXGI_FORMAT_R32G32B32_FLOAT:
case DXGI_FORMAT_R32G32B32_SINT:
case DXGI_FORMAT_R32G32B32_TYPELESS:
case DXGI_FORMAT_R32G32B32_UINT:
return 96;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
case DXGI_FORMAT_R32G32B32A32_SINT:
case DXGI_FORMAT_R32G32B32A32_TYPELESS:
case DXGI_FORMAT_R32G32B32A32_UINT:
return 128;
case DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC4_SNORM:
case DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT_BC4_UNORM:
return 4;
case DXGI_FORMAT_BC2_TYPELESS:
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT_BC3_TYPELESS:
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT_BC5_SNORM:
case DXGI_FORMAT_BC5_TYPELESS:
case DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT_BC6H_SF16:
case DXGI_FORMAT_BC6H_TYPELESS:
case DXGI_FORMAT_BC6H_UF16:
case DXGI_FORMAT_BC7_TYPELESS:
case DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT_BC7_UNORM_SRGB:
return 8;
default:
return 0;
}
}
size_t ComputeBlockSizeBits(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC4_SNORM:
case DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT_BC4_UNORM:
case DXGI_FORMAT_BC2_TYPELESS:
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT_BC3_TYPELESS:
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT_BC5_SNORM:
case DXGI_FORMAT_BC5_TYPELESS:
case DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT_BC6H_SF16:
case DXGI_FORMAT_BC6H_TYPELESS:
case DXGI_FORMAT_BC6H_UF16:
case DXGI_FORMAT_BC7_TYPELESS:
case DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT_BC7_UNORM_SRGB:
return ComputePixelSizeBits(format) * 16;
default:
UNREACHABLE();
return 0;
}
}
bool IsCompressed(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC4_SNORM:
case DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT_BC4_UNORM:
case DXGI_FORMAT_BC2_TYPELESS:
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT_BC3_TYPELESS:
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT_BC5_SNORM:
case DXGI_FORMAT_BC5_TYPELESS:
case DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT_BC6H_SF16:
case DXGI_FORMAT_BC6H_TYPELESS:
case DXGI_FORMAT_BC6H_UF16:
case DXGI_FORMAT_BC7_TYPELESS:
case DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT_BC7_UNORM_SRGB:
return true;
case DXGI_FORMAT_UNKNOWN:
UNREACHABLE();
return false;
default:
return false;
}
}
unsigned int GetTextureFormatDimensionAlignment(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC4_SNORM:
case DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT_BC4_UNORM:
case DXGI_FORMAT_BC2_TYPELESS:
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT_BC3_TYPELESS:
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT_BC5_SNORM:
case DXGI_FORMAT_BC5_TYPELESS:
case DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT_BC6H_SF16:
case DXGI_FORMAT_BC6H_TYPELESS:
case DXGI_FORMAT_BC6H_UF16:
case DXGI_FORMAT_BC7_TYPELESS:
case DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT_BC7_UNORM_SRGB:
return 4;
case DXGI_FORMAT_UNKNOWN:
UNREACHABLE();
return 1;
default:
return 1;
}
}
bool IsDepthStencilFormat(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
case DXGI_FORMAT_D32_FLOAT:
case DXGI_FORMAT_D24_UNORM_S8_UINT:
case DXGI_FORMAT_D16_UNORM:
return true;
default:
return false;
}
}
DXGI_FORMAT GetDepthTextureFormat(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return DXGI_FORMAT_R32G8X24_TYPELESS;
case DXGI_FORMAT_D32_FLOAT: return DXGI_FORMAT_R32_TYPELESS;
case DXGI_FORMAT_D24_UNORM_S8_UINT: return DXGI_FORMAT_R24G8_TYPELESS;
case DXGI_FORMAT_D16_UNORM: return DXGI_FORMAT_R16_TYPELESS;
default: UNREACHABLE(); return DXGI_FORMAT_UNKNOWN;
}
}
DXGI_FORMAT GetDepthShaderResourceFormat(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
case DXGI_FORMAT_D32_FLOAT: return DXGI_FORMAT_R32_UINT;
case DXGI_FORMAT_D24_UNORM_S8_UINT: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
case DXGI_FORMAT_D16_UNORM: return DXGI_FORMAT_R16_UNORM;
default: UNREACHABLE(); return DXGI_FORMAT_UNKNOWN;
}
}
HRESULT SetDebugName(ID3D11DeviceChild *resource, const char *name)
{
#if defined(_DEBUG)
return resource->SetPrivateData(WKPDID_D3DDebugObjectName, strlen(name), name);
#else
return S_OK;
#endif
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/renderer11_utils.cpp | C++ | bsd | 21,331 |
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// RenderStateCache.h: Defines rx::RenderStateCache, a cache of Direct3D render
// state objects.
#ifndef LIBGLESV2_RENDERER_RENDERSTATECACHE_H_
#define LIBGLESV2_RENDERER_RENDERSTATECACHE_H_
#include "libGLESv2/angletypes.h"
#include "common/angleutils.h"
namespace rx
{
class RenderStateCache
{
public:
RenderStateCache();
virtual ~RenderStateCache();
void initialize(ID3D11Device *device);
void clear();
// Increments refcount on the returned blend state, Release() must be called.
ID3D11BlendState *getBlendState(const gl::BlendState &blendState);
ID3D11RasterizerState *getRasterizerState(const gl::RasterizerState &rasterState,
bool scissorEnabled, unsigned int depthSize);
ID3D11DepthStencilState *getDepthStencilState(const gl::DepthStencilState &dsState);
ID3D11SamplerState *getSamplerState(const gl::SamplerState &samplerState);
private:
DISALLOW_COPY_AND_ASSIGN(RenderStateCache);
unsigned long long mCounter;
// Blend state cache
static std::size_t hashBlendState(const gl::BlendState &blendState);
static bool compareBlendStates(const gl::BlendState &a, const gl::BlendState &b);
static const unsigned int kMaxBlendStates;
typedef std::size_t (*BlendStateHashFunction)(const gl::BlendState &);
typedef bool (*BlendStateEqualityFunction)(const gl::BlendState &, const gl::BlendState &);
typedef std::pair<ID3D11BlendState*, unsigned long long> BlendStateCounterPair;
typedef std::unordered_map<gl::BlendState, BlendStateCounterPair, BlendStateHashFunction, BlendStateEqualityFunction> BlendStateMap;
BlendStateMap mBlendStateCache;
// Rasterizer state cache
struct RasterizerStateKey
{
gl::RasterizerState rasterizerState;
bool scissorEnabled;
unsigned int depthSize;
};
static std::size_t hashRasterizerState(const RasterizerStateKey &rasterState);
static bool compareRasterizerStates(const RasterizerStateKey &a, const RasterizerStateKey &b);
static const unsigned int kMaxRasterizerStates;
typedef std::size_t (*RasterizerStateHashFunction)(const RasterizerStateKey &);
typedef bool (*RasterizerStateEqualityFunction)(const RasterizerStateKey &, const RasterizerStateKey &);
typedef std::pair<ID3D11RasterizerState*, unsigned long long> RasterizerStateCounterPair;
typedef std::unordered_map<RasterizerStateKey, RasterizerStateCounterPair, RasterizerStateHashFunction, RasterizerStateEqualityFunction> RasterizerStateMap;
RasterizerStateMap mRasterizerStateCache;
// Depth stencil state cache
static std::size_t hashDepthStencilState(const gl::DepthStencilState &dsState);
static bool compareDepthStencilStates(const gl::DepthStencilState &a, const gl::DepthStencilState &b);
static const unsigned int kMaxDepthStencilStates;
typedef std::size_t (*DepthStencilStateHashFunction)(const gl::DepthStencilState &);
typedef bool (*DepthStencilStateEqualityFunction)(const gl::DepthStencilState &, const gl::DepthStencilState &);
typedef std::pair<ID3D11DepthStencilState*, unsigned long long> DepthStencilStateCounterPair;
typedef std::unordered_map<gl::DepthStencilState,
DepthStencilStateCounterPair,
DepthStencilStateHashFunction,
DepthStencilStateEqualityFunction> DepthStencilStateMap;
DepthStencilStateMap mDepthStencilStateCache;
// Sample state cache
static std::size_t hashSamplerState(const gl::SamplerState &samplerState);
static bool compareSamplerStates(const gl::SamplerState &a, const gl::SamplerState &b);
static const unsigned int kMaxSamplerStates;
typedef std::size_t (*SamplerStateHashFunction)(const gl::SamplerState &);
typedef bool (*SamplerStateEqualityFunction)(const gl::SamplerState &, const gl::SamplerState &);
typedef std::pair<ID3D11SamplerState*, unsigned long long> SamplerStateCounterPair;
typedef std::unordered_map<gl::SamplerState,
SamplerStateCounterPair,
SamplerStateHashFunction,
SamplerStateEqualityFunction> SamplerStateMap;
SamplerStateMap mSamplerStateCache;
ID3D11Device *mDevice;
};
}
#endif // LIBGLESV2_RENDERER_RENDERSTATECACHE_H_ | 010smithzhang-ddd | src/libGLESv2/renderer/RenderStateCache.h | C++ | bsd | 4,559 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// renderer11_utils.h: Conversion functions and other utility routines
// specific to the D3D11 renderer.
#ifndef LIBGLESV2_RENDERER_RENDERER11_UTILS_H
#define LIBGLESV2_RENDERER_RENDERER11_UTILS_H
#include "libGLESv2/angletypes.h"
namespace gl_d3d11
{
D3D11_BLEND ConvertBlendFunc(GLenum glBlend, bool isAlpha);
D3D11_BLEND_OP ConvertBlendOp(GLenum glBlendOp);
UINT8 ConvertColorMask(bool maskRed, bool maskGreen, bool maskBlue, bool maskAlpha);
D3D11_CULL_MODE ConvertCullMode(bool cullEnabled, GLenum cullMode);
D3D11_COMPARISON_FUNC ConvertComparison(GLenum comparison);
D3D11_DEPTH_WRITE_MASK ConvertDepthMask(bool depthWriteEnabled);
UINT8 ConvertStencilMask(GLuint stencilmask);
D3D11_STENCIL_OP ConvertStencilOp(GLenum stencilOp);
D3D11_FILTER ConvertFilter(GLenum minFilter, GLenum magFilter, float maxAnisotropy);
D3D11_TEXTURE_ADDRESS_MODE ConvertTextureWrap(GLenum wrap);
FLOAT ConvertMinLOD(GLenum minFilter, unsigned int lodOffset);
FLOAT ConvertMaxLOD(GLenum minFilter, unsigned int lodOffset);
DXGI_FORMAT ConvertRenderbufferFormat(GLenum format);
DXGI_FORMAT ConvertTextureFormat(GLenum format);
}
namespace d3d11_gl
{
GLenum ConvertBackBufferFormat(DXGI_FORMAT format);
GLenum ConvertDepthStencilFormat(DXGI_FORMAT format);
GLenum ConvertRenderbufferFormat(DXGI_FORMAT format);
GLenum ConvertTextureInternalFormat(DXGI_FORMAT format);
}
namespace d3d11
{
struct PositionTexCoordVertex
{
float x, y;
float u, v;
};
void SetPositionTexCoordVertex(PositionTexCoordVertex* vertex, float x, float y, float u, float v);
struct PositionDepthColorVertex
{
float x, y, z;
float r, g, b, a;
};
void SetPositionDepthColorVertex(PositionDepthColorVertex* vertex, float x, float y, float z,
const gl::Color &color);
size_t ComputePixelSizeBits(DXGI_FORMAT format);
size_t ComputeBlockSizeBits(DXGI_FORMAT format);
bool IsCompressed(DXGI_FORMAT format);
unsigned int GetTextureFormatDimensionAlignment(DXGI_FORMAT format);
bool IsDepthStencilFormat(DXGI_FORMAT format);
DXGI_FORMAT GetDepthTextureFormat(DXGI_FORMAT format);
DXGI_FORMAT GetDepthShaderResourceFormat(DXGI_FORMAT format);
HRESULT SetDebugName(ID3D11DeviceChild *resource, const char *name);
inline bool isDeviceLostError(HRESULT errorCode)
{
switch (errorCode)
{
case DXGI_ERROR_DEVICE_HUNG:
case DXGI_ERROR_DEVICE_REMOVED:
case DXGI_ERROR_DEVICE_RESET:
case DXGI_ERROR_DRIVER_INTERNAL_ERROR:
case DXGI_ERROR_NOT_CURRENTLY_AVAILABLE:
return true;
default:
return false;
}
}
}
#endif // LIBGLESV2_RENDERER_RENDERER11_UTILS_H
| 010smithzhang-ddd | src/libGLESv2/renderer/renderer11_utils.h | C++ | bsd | 2,808 |
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// QueryImpl.h: Defines the abstract rx::QueryImpl class.
#ifndef LIBGLESV2_RENDERER_QUERYIMPL_H_
#define LIBGLESV2_RENDERER_QUERYIMPL_H_
#include "common/angleutils.h"
namespace rx
{
class QueryImpl
{
public:
explicit QueryImpl(GLenum type) : mType(type), mStatus(GL_FALSE), mResult(0) { }
virtual ~QueryImpl() { }
virtual void begin() = 0;
virtual void end() = 0;
virtual GLuint getResult() = 0;
virtual GLboolean isResultAvailable() = 0;
GLenum getType() const { return mType; }
protected:
GLuint mResult;
GLboolean mStatus;
private:
DISALLOW_COPY_AND_ASSIGN(QueryImpl);
GLenum mType;
};
}
#endif // LIBGLESV2_RENDERER_QUERYIMPL_H_
| 010smithzhang-ddd | src/libGLESv2/renderer/QueryImpl.h | C++ | bsd | 877 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// TextureStorage.cpp: Implements the abstract rx::TextureStorageInterface class and its concrete derived
// classes TextureStorageInterface2D and TextureStorageInterfaceCube, which act as the interface to the
// GPU-side texture.
#include "libGLESv2/renderer/TextureStorage.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/Texture.h"
#include "common/debug.h"
namespace rx
{
unsigned int TextureStorageInterface::mCurrentTextureSerial = 1;
TextureStorageInterface::TextureStorageInterface()
: mTextureSerial(issueTextureSerial()),
mInstance(NULL)
{
}
TextureStorageInterface::~TextureStorageInterface()
{
delete mInstance;
}
bool TextureStorageInterface::isRenderTarget() const
{
return mInstance->isRenderTarget();
}
bool TextureStorageInterface::isManaged() const
{
return mInstance->isManaged();
}
unsigned int TextureStorageInterface::getTextureSerial() const
{
return mTextureSerial;
}
unsigned int TextureStorageInterface::issueTextureSerial()
{
return mCurrentTextureSerial++;
}
int TextureStorageInterface::getLodOffset() const
{
return mInstance->getLodOffset();
}
int TextureStorageInterface::levelCount()
{
return mInstance->levelCount();
}
TextureStorageInterface2D::TextureStorageInterface2D(Renderer *renderer, SwapChain *swapchain)
: mRenderTargetSerial(gl::RenderbufferStorage::issueSerial())
{
mInstance = renderer->createTextureStorage2D(swapchain);
}
TextureStorageInterface2D::TextureStorageInterface2D(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height)
: mRenderTargetSerial(gl::RenderbufferStorage::issueSerial())
{
mInstance = renderer->createTextureStorage2D(levels, internalformat, usage, forceRenderable, width, height);
}
TextureStorageInterface2D::~TextureStorageInterface2D()
{
}
RenderTarget *TextureStorageInterface2D::getRenderTarget() const
{
return mInstance->getRenderTarget();
}
void TextureStorageInterface2D::generateMipmap(int level)
{
mInstance->generateMipmap(level);
}
unsigned int TextureStorageInterface2D::getRenderTargetSerial(GLenum target) const
{
return mRenderTargetSerial;
}
TextureStorageInterfaceCube::TextureStorageInterfaceCube(Renderer *renderer, int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size)
: mFirstRenderTargetSerial(gl::RenderbufferStorage::issueCubeSerials())
{
mInstance = renderer->createTextureStorageCube(levels, internalformat, usage, forceRenderable, size);
}
TextureStorageInterfaceCube::~TextureStorageInterfaceCube()
{
}
RenderTarget *TextureStorageInterfaceCube::getRenderTarget(GLenum faceTarget) const
{
return mInstance->getRenderTarget(faceTarget);
}
void TextureStorageInterfaceCube::generateMipmap(int face, int level)
{
mInstance->generateMipmap(face, level);
}
unsigned int TextureStorageInterfaceCube::getRenderTargetSerial(GLenum target) const
{
return mFirstRenderTargetSerial + gl::TextureCubeMap::faceIndex(target);
}
} | 010smithzhang-ddd | src/libGLESv2/renderer/TextureStorage.cpp | C++ | bsd | 3,284 |
#include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Fence9.cpp: Defines the rx::Fence9 class.
#include "libGLESv2/renderer/Fence9.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/renderer9_utils.h"
#include "libGLESv2/renderer/Renderer9.h"
namespace rx
{
Fence9::Fence9(rx::Renderer9 *renderer)
{
mRenderer = renderer;
mQuery = NULL;
}
Fence9::~Fence9()
{
if (mQuery)
{
mRenderer->freeEventQuery(mQuery);
mQuery = NULL;
}
}
GLboolean Fence9::isFence()
{
// GL_NV_fence spec:
// A name returned by GenFencesNV, but not yet set via SetFenceNV, is not the name of an existing fence.
return mQuery != NULL;
}
void Fence9::setFence(GLenum condition)
{
if (!mQuery)
{
mQuery = mRenderer->allocateEventQuery();
if (!mQuery)
{
return gl::error(GL_OUT_OF_MEMORY);
}
}
HRESULT result = mQuery->Issue(D3DISSUE_END);
ASSERT(SUCCEEDED(result));
setCondition(condition);
setStatus(GL_FALSE);
}
GLboolean Fence9::testFence()
{
if (mQuery == NULL)
{
return gl::error(GL_INVALID_OPERATION, GL_TRUE);
}
HRESULT result = mQuery->GetData(NULL, 0, D3DGETDATA_FLUSH);
if (d3d9::isDeviceLostError(result))
{
mRenderer->notifyDeviceLost();
return gl::error(GL_OUT_OF_MEMORY, GL_TRUE);
}
ASSERT(result == S_OK || result == S_FALSE);
setStatus(result == S_OK);
return getStatus();
}
void Fence9::finishFence()
{
if (mQuery == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
while (!testFence())
{
Sleep(0);
}
}
void Fence9::getFenceiv(GLenum pname, GLint *params)
{
if (mQuery == NULL)
{
return gl::error(GL_INVALID_OPERATION);
}
switch (pname)
{
case GL_FENCE_STATUS_NV:
{
// GL_NV_fence spec:
// Once the status of a fence has been finished (via FinishFenceNV) or tested and the returned status is TRUE (via either TestFenceNV
// or GetFenceivNV querying the FENCE_STATUS_NV), the status remains TRUE until the next SetFenceNV of the fence.
if (getStatus())
{
params[0] = GL_TRUE;
return;
}
HRESULT result = mQuery->GetData(NULL, 0, 0);
if (d3d9::isDeviceLostError(result))
{
params[0] = GL_TRUE;
mRenderer->notifyDeviceLost();
return gl::error(GL_OUT_OF_MEMORY);
}
ASSERT(result == S_OK || result == S_FALSE);
setStatus(result == S_OK);
params[0] = getStatus();
break;
}
case GL_FENCE_CONDITION_NV:
params[0] = getCondition();
break;
default:
return gl::error(GL_INVALID_ENUM);
break;
}
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/Fence9.cpp | C++ | bsd | 3,063 |
#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// renderer9_utils.cpp: Conversion functions and other utility routines
// specific to the D3D9 renderer.
#include "libGLESv2/renderer/renderer9_utils.h"
#include "libGLESv2/mathutil.h"
#include "libGLESv2/Context.h"
#include "common/debug.h"
namespace gl_d3d9
{
D3DCMPFUNC ConvertComparison(GLenum comparison)
{
D3DCMPFUNC d3dComp = D3DCMP_ALWAYS;
switch (comparison)
{
case GL_NEVER: d3dComp = D3DCMP_NEVER; break;
case GL_ALWAYS: d3dComp = D3DCMP_ALWAYS; break;
case GL_LESS: d3dComp = D3DCMP_LESS; break;
case GL_LEQUAL: d3dComp = D3DCMP_LESSEQUAL; break;
case GL_EQUAL: d3dComp = D3DCMP_EQUAL; break;
case GL_GREATER: d3dComp = D3DCMP_GREATER; break;
case GL_GEQUAL: d3dComp = D3DCMP_GREATEREQUAL; break;
case GL_NOTEQUAL: d3dComp = D3DCMP_NOTEQUAL; break;
default: UNREACHABLE();
}
return d3dComp;
}
D3DCOLOR ConvertColor(gl::Color color)
{
return D3DCOLOR_RGBA(gl::unorm<8>(color.red),
gl::unorm<8>(color.green),
gl::unorm<8>(color.blue),
gl::unorm<8>(color.alpha));
}
D3DBLEND ConvertBlendFunc(GLenum blend)
{
D3DBLEND d3dBlend = D3DBLEND_ZERO;
switch (blend)
{
case GL_ZERO: d3dBlend = D3DBLEND_ZERO; break;
case GL_ONE: d3dBlend = D3DBLEND_ONE; break;
case GL_SRC_COLOR: d3dBlend = D3DBLEND_SRCCOLOR; break;
case GL_ONE_MINUS_SRC_COLOR: d3dBlend = D3DBLEND_INVSRCCOLOR; break;
case GL_DST_COLOR: d3dBlend = D3DBLEND_DESTCOLOR; break;
case GL_ONE_MINUS_DST_COLOR: d3dBlend = D3DBLEND_INVDESTCOLOR; break;
case GL_SRC_ALPHA: d3dBlend = D3DBLEND_SRCALPHA; break;
case GL_ONE_MINUS_SRC_ALPHA: d3dBlend = D3DBLEND_INVSRCALPHA; break;
case GL_DST_ALPHA: d3dBlend = D3DBLEND_DESTALPHA; break;
case GL_ONE_MINUS_DST_ALPHA: d3dBlend = D3DBLEND_INVDESTALPHA; break;
case GL_CONSTANT_COLOR: d3dBlend = D3DBLEND_BLENDFACTOR; break;
case GL_ONE_MINUS_CONSTANT_COLOR: d3dBlend = D3DBLEND_INVBLENDFACTOR; break;
case GL_CONSTANT_ALPHA: d3dBlend = D3DBLEND_BLENDFACTOR; break;
case GL_ONE_MINUS_CONSTANT_ALPHA: d3dBlend = D3DBLEND_INVBLENDFACTOR; break;
case GL_SRC_ALPHA_SATURATE: d3dBlend = D3DBLEND_SRCALPHASAT; break;
default: UNREACHABLE();
}
return d3dBlend;
}
D3DBLENDOP ConvertBlendOp(GLenum blendOp)
{
D3DBLENDOP d3dBlendOp = D3DBLENDOP_ADD;
switch (blendOp)
{
case GL_FUNC_ADD: d3dBlendOp = D3DBLENDOP_ADD; break;
case GL_FUNC_SUBTRACT: d3dBlendOp = D3DBLENDOP_SUBTRACT; break;
case GL_FUNC_REVERSE_SUBTRACT: d3dBlendOp = D3DBLENDOP_REVSUBTRACT; break;
default: UNREACHABLE();
}
return d3dBlendOp;
}
D3DSTENCILOP ConvertStencilOp(GLenum stencilOp)
{
D3DSTENCILOP d3dStencilOp = D3DSTENCILOP_KEEP;
switch (stencilOp)
{
case GL_ZERO: d3dStencilOp = D3DSTENCILOP_ZERO; break;
case GL_KEEP: d3dStencilOp = D3DSTENCILOP_KEEP; break;
case GL_REPLACE: d3dStencilOp = D3DSTENCILOP_REPLACE; break;
case GL_INCR: d3dStencilOp = D3DSTENCILOP_INCRSAT; break;
case GL_DECR: d3dStencilOp = D3DSTENCILOP_DECRSAT; break;
case GL_INVERT: d3dStencilOp = D3DSTENCILOP_INVERT; break;
case GL_INCR_WRAP: d3dStencilOp = D3DSTENCILOP_INCR; break;
case GL_DECR_WRAP: d3dStencilOp = D3DSTENCILOP_DECR; break;
default: UNREACHABLE();
}
return d3dStencilOp;
}
D3DTEXTUREADDRESS ConvertTextureWrap(GLenum wrap)
{
D3DTEXTUREADDRESS d3dWrap = D3DTADDRESS_WRAP;
switch (wrap)
{
case GL_REPEAT: d3dWrap = D3DTADDRESS_WRAP; break;
case GL_CLAMP_TO_EDGE: d3dWrap = D3DTADDRESS_CLAMP; break;
case GL_MIRRORED_REPEAT: d3dWrap = D3DTADDRESS_MIRROR; break;
default: UNREACHABLE();
}
return d3dWrap;
}
D3DCULL ConvertCullMode(GLenum cullFace, GLenum frontFace)
{
D3DCULL cull = D3DCULL_CCW;
switch (cullFace)
{
case GL_FRONT:
cull = (frontFace == GL_CCW ? D3DCULL_CW : D3DCULL_CCW);
break;
case GL_BACK:
cull = (frontFace == GL_CCW ? D3DCULL_CCW : D3DCULL_CW);
break;
case GL_FRONT_AND_BACK:
cull = D3DCULL_NONE; // culling will be handled during draw
break;
default: UNREACHABLE();
}
return cull;
}
D3DCUBEMAP_FACES ConvertCubeFace(GLenum cubeFace)
{
D3DCUBEMAP_FACES face = D3DCUBEMAP_FACE_POSITIVE_X;
switch (cubeFace)
{
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
face = D3DCUBEMAP_FACE_POSITIVE_X;
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
face = D3DCUBEMAP_FACE_NEGATIVE_X;
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
face = D3DCUBEMAP_FACE_POSITIVE_Y;
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
face = D3DCUBEMAP_FACE_NEGATIVE_Y;
break;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
face = D3DCUBEMAP_FACE_POSITIVE_Z;
break;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
face = D3DCUBEMAP_FACE_NEGATIVE_Z;
break;
default: UNREACHABLE();
}
return face;
}
DWORD ConvertColorMask(bool red, bool green, bool blue, bool alpha)
{
return (red ? D3DCOLORWRITEENABLE_RED : 0) |
(green ? D3DCOLORWRITEENABLE_GREEN : 0) |
(blue ? D3DCOLORWRITEENABLE_BLUE : 0) |
(alpha ? D3DCOLORWRITEENABLE_ALPHA : 0);
}
D3DTEXTUREFILTERTYPE ConvertMagFilter(GLenum magFilter, float maxAnisotropy)
{
if (maxAnisotropy > 1.0f)
{
return D3DTEXF_ANISOTROPIC;
}
D3DTEXTUREFILTERTYPE d3dMagFilter = D3DTEXF_POINT;
switch (magFilter)
{
case GL_NEAREST: d3dMagFilter = D3DTEXF_POINT; break;
case GL_LINEAR: d3dMagFilter = D3DTEXF_LINEAR; break;
default: UNREACHABLE();
}
return d3dMagFilter;
}
void ConvertMinFilter(GLenum minFilter, D3DTEXTUREFILTERTYPE *d3dMinFilter, D3DTEXTUREFILTERTYPE *d3dMipFilter, float maxAnisotropy)
{
switch (minFilter)
{
case GL_NEAREST:
*d3dMinFilter = D3DTEXF_POINT;
*d3dMipFilter = D3DTEXF_NONE;
break;
case GL_LINEAR:
*d3dMinFilter = D3DTEXF_LINEAR;
*d3dMipFilter = D3DTEXF_NONE;
break;
case GL_NEAREST_MIPMAP_NEAREST:
*d3dMinFilter = D3DTEXF_POINT;
*d3dMipFilter = D3DTEXF_POINT;
break;
case GL_LINEAR_MIPMAP_NEAREST:
*d3dMinFilter = D3DTEXF_LINEAR;
*d3dMipFilter = D3DTEXF_POINT;
break;
case GL_NEAREST_MIPMAP_LINEAR:
*d3dMinFilter = D3DTEXF_POINT;
*d3dMipFilter = D3DTEXF_LINEAR;
break;
case GL_LINEAR_MIPMAP_LINEAR:
*d3dMinFilter = D3DTEXF_LINEAR;
*d3dMipFilter = D3DTEXF_LINEAR;
break;
default:
*d3dMinFilter = D3DTEXF_POINT;
*d3dMipFilter = D3DTEXF_NONE;
UNREACHABLE();
}
if (maxAnisotropy > 1.0f)
{
*d3dMinFilter = D3DTEXF_ANISOTROPIC;
}
}
D3DFORMAT ConvertRenderbufferFormat(GLenum format)
{
switch (format)
{
case GL_NONE: return D3DFMT_NULL;
case GL_RGBA4:
case GL_RGB5_A1:
case GL_RGBA8_OES: return D3DFMT_A8R8G8B8;
case GL_RGB565: return D3DFMT_R5G6B5;
case GL_RGB8_OES: return D3DFMT_X8R8G8B8;
case GL_DEPTH_COMPONENT16:
case GL_STENCIL_INDEX8:
case GL_DEPTH24_STENCIL8_OES: return D3DFMT_D24S8;
default: UNREACHABLE(); return D3DFMT_A8R8G8B8;
}
}
D3DMULTISAMPLE_TYPE GetMultisampleTypeFromSamples(GLsizei samples)
{
if (samples <= 1)
return D3DMULTISAMPLE_NONE;
else
return (D3DMULTISAMPLE_TYPE)samples;
}
}
namespace d3d9_gl
{
unsigned int GetStencilSize(D3DFORMAT stencilFormat)
{
if (stencilFormat == D3DFMT_INTZ)
{
return 8;
}
switch(stencilFormat)
{
case D3DFMT_D24FS8:
case D3DFMT_D24S8:
return 8;
case D3DFMT_D24X4S4:
return 4;
case D3DFMT_D15S1:
return 1;
case D3DFMT_D16_LOCKABLE:
case D3DFMT_D32:
case D3DFMT_D24X8:
case D3DFMT_D32F_LOCKABLE:
case D3DFMT_D16:
return 0;
//case D3DFMT_D32_LOCKABLE: return 0; // DirectX 9Ex only
//case D3DFMT_S8_LOCKABLE: return 8; // DirectX 9Ex only
default:
return 0;
}
}
unsigned int GetAlphaSize(D3DFORMAT colorFormat)
{
switch (colorFormat)
{
case D3DFMT_A16B16G16R16F:
return 16;
case D3DFMT_A32B32G32R32F:
return 32;
case D3DFMT_A2R10G10B10:
return 2;
case D3DFMT_A8R8G8B8:
return 8;
case D3DFMT_A1R5G5B5:
return 1;
case D3DFMT_X8R8G8B8:
case D3DFMT_R5G6B5:
return 0;
default:
return 0;
}
}
GLsizei GetSamplesFromMultisampleType(D3DMULTISAMPLE_TYPE type)
{
if (type == D3DMULTISAMPLE_NONMASKABLE)
return 0;
else
return type;
}
bool IsFormatChannelEquivalent(D3DFORMAT d3dformat, GLenum format)
{
switch (d3dformat)
{
case D3DFMT_L8:
return (format == GL_LUMINANCE);
case D3DFMT_A8L8:
return (format == GL_LUMINANCE_ALPHA);
case D3DFMT_DXT1:
return (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT || format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
case D3DFMT_DXT3:
return (format == GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE);
case D3DFMT_DXT5:
return (format == GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE);
case D3DFMT_A8R8G8B8:
case D3DFMT_A16B16G16R16F:
case D3DFMT_A32B32G32R32F:
return (format == GL_RGBA || format == GL_BGRA_EXT);
case D3DFMT_X8R8G8B8:
return (format == GL_RGB);
default:
if (d3dformat == D3DFMT_INTZ && gl::IsDepthTexture(format))
return true;
return false;
}
}
GLenum ConvertBackBufferFormat(D3DFORMAT format)
{
switch (format)
{
case D3DFMT_A4R4G4B4: return GL_RGBA4;
case D3DFMT_A8R8G8B8: return GL_RGBA8_OES;
case D3DFMT_A1R5G5B5: return GL_RGB5_A1;
case D3DFMT_R5G6B5: return GL_RGB565;
case D3DFMT_X8R8G8B8: return GL_RGB8_OES;
default:
UNREACHABLE();
}
return GL_RGBA4;
}
GLenum ConvertDepthStencilFormat(D3DFORMAT format)
{
if (format == D3DFMT_INTZ)
{
return GL_DEPTH24_STENCIL8_OES;
}
switch (format)
{
case D3DFMT_D16:
case D3DFMT_D24X8:
return GL_DEPTH_COMPONENT16;
case D3DFMT_D24S8:
return GL_DEPTH24_STENCIL8_OES;
case D3DFMT_UNKNOWN:
return GL_NONE;
default:
UNREACHABLE();
}
return GL_DEPTH24_STENCIL8_OES;
}
GLenum ConvertRenderTargetFormat(D3DFORMAT format)
{
if (format == D3DFMT_INTZ)
{
return GL_DEPTH24_STENCIL8_OES;
}
switch (format)
{
case D3DFMT_A4R4G4B4: return GL_RGBA4;
case D3DFMT_A8R8G8B8: return GL_RGBA8_OES;
case D3DFMT_A1R5G5B5: return GL_RGB5_A1;
case D3DFMT_R5G6B5: return GL_RGB565;
case D3DFMT_X8R8G8B8: return GL_RGB8_OES;
case D3DFMT_D16:
case D3DFMT_D24X8:
return GL_DEPTH_COMPONENT16;
case D3DFMT_D24S8:
return GL_DEPTH24_STENCIL8_OES;
case D3DFMT_UNKNOWN:
return GL_NONE;
default:
UNREACHABLE();
}
return GL_RGBA4;
}
GLenum GetEquivalentFormat(D3DFORMAT format)
{
if (format == D3DFMT_INTZ)
return GL_DEPTH24_STENCIL8_OES;
if (format == D3DFMT_NULL)
return GL_NONE;
switch (format)
{
case D3DFMT_A4R4G4B4: return GL_RGBA4;
case D3DFMT_A8R8G8B8: return GL_RGBA8_OES;
case D3DFMT_A1R5G5B5: return GL_RGB5_A1;
case D3DFMT_R5G6B5: return GL_RGB565;
case D3DFMT_X8R8G8B8: return GL_RGB8_OES;
case D3DFMT_D16: return GL_DEPTH_COMPONENT16;
case D3DFMT_D24S8: return GL_DEPTH24_STENCIL8_OES;
case D3DFMT_UNKNOWN: return GL_NONE;
case D3DFMT_DXT1: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case D3DFMT_DXT3: return GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE;
case D3DFMT_DXT5: return GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE;
case D3DFMT_A32B32G32R32F: return GL_RGBA32F_EXT;
case D3DFMT_A16B16G16R16F: return GL_RGBA16F_EXT;
case D3DFMT_L8: return GL_LUMINANCE8_EXT;
case D3DFMT_A8L8: return GL_LUMINANCE8_ALPHA8_EXT;
default: UNREACHABLE();
return GL_NONE;
}
}
}
namespace d3d9
{
bool IsCompressedFormat(D3DFORMAT surfaceFormat)
{
switch(surfaceFormat)
{
case D3DFMT_DXT1:
case D3DFMT_DXT2:
case D3DFMT_DXT3:
case D3DFMT_DXT4:
case D3DFMT_DXT5:
return true;
default:
return false;
}
}
size_t ComputeRowSize(D3DFORMAT format, unsigned int width)
{
if (format == D3DFMT_INTZ)
{
return 4 * width;
}
switch (format)
{
case D3DFMT_L8:
return 1 * width;
case D3DFMT_A8L8:
return 2 * width;
case D3DFMT_X8R8G8B8:
case D3DFMT_A8R8G8B8:
return 4 * width;
case D3DFMT_A16B16G16R16F:
return 8 * width;
case D3DFMT_A32B32G32R32F:
return 16 * width;
case D3DFMT_DXT1:
return 8 * ((width + 3) / 4);
case D3DFMT_DXT3:
case D3DFMT_DXT5:
return 16 * ((width + 3) / 4);
default:
UNREACHABLE();
return 0;
}
}
}
| 010smithzhang-ddd | src/libGLESv2/renderer/renderer9_utils.cpp | C++ | bsd | 14,160 |